2022-10-18 12:37:50 +00:00
|
|
|
package codegen
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
|
|
|
"text/template"
|
|
|
|
|
2023-05-24 11:04:29 +00:00
|
|
|
"git.kmsign.ru/royalcat/repogen/internal/code"
|
2022-10-18 12:37:50 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const methodTemplate = `
|
|
|
|
func ({{.GenReceiver}}) {{.Name}}({{.GenParams}}){{.GenReturns}} {
|
2023-04-18 13:21:46 +00:00
|
|
|
{{.Body.Code}}
|
2022-10-18 12:37:50 +00:00
|
|
|
}
|
|
|
|
`
|
|
|
|
|
|
|
|
// MethodBuilder is an implementer of a method.
|
|
|
|
type MethodBuilder struct {
|
|
|
|
Receiver MethodReceiver
|
|
|
|
Name string
|
|
|
|
Params []code.Param
|
|
|
|
Returns []code.Type
|
2023-04-18 13:21:46 +00:00
|
|
|
Body FunctionBody
|
2022-10-18 12:37:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// MethodReceiver describes a specification of a method receiver.
|
|
|
|
type MethodReceiver struct {
|
|
|
|
Name string
|
|
|
|
Type code.SimpleType
|
|
|
|
Pointer bool
|
|
|
|
}
|
|
|
|
|
|
|
|
// Impl writes method declatation code to the buffer.
|
|
|
|
func (mb MethodBuilder) Impl(buffer *bytes.Buffer) error {
|
|
|
|
tmpl, err := template.New("function").Parse(methodTemplate)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// writing to a buffer should not cause errors.
|
|
|
|
_ = tmpl.Execute(buffer, mb)
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (mb MethodBuilder) GenReceiver() string {
|
|
|
|
if mb.Receiver.Name == "" {
|
|
|
|
return mb.generateReceiverType()
|
|
|
|
}
|
|
|
|
return fmt.Sprintf("%s %s", mb.Receiver.Name, mb.generateReceiverType())
|
|
|
|
}
|
|
|
|
|
|
|
|
func (mb MethodBuilder) generateReceiverType() string {
|
|
|
|
if !mb.Receiver.Pointer {
|
|
|
|
return mb.Receiver.Type.Code()
|
|
|
|
}
|
|
|
|
return code.PointerType{ContainedType: mb.Receiver.Type}.Code()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (mb MethodBuilder) GenParams() string {
|
|
|
|
return generateParams(mb.Params)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (mb MethodBuilder) GenReturns() string {
|
|
|
|
return generateReturns(mb.Returns)
|
|
|
|
}
|