activity/tools/exp/typedef.go

69 行
1.7 KiB
Go
Raw 通常表示 履歴

2018-10-09 05:19:10 +09:00
package exp
import (
"github.com/dave/jennifer/jen"
)
2018-10-10 07:32:37 +09:00
// Typedef defines a non-struct-based type, its functions, and its methods for
// Go code generation.
2018-10-09 05:19:10 +09:00
type Typedef struct {
comment jen.Code
name string
concreteType jen.Code
methods map[string]*Method
constructors map[string]*Function
}
2018-10-10 07:32:37 +09:00
// NewTypedef creates a new commented Typedef.
2018-10-09 05:19:10 +09:00
func NewTypedef(comment jen.Code,
name string,
concreteType jen.Code,
methods []*Method,
constructors []*Function) *Typedef {
t := &Typedef{
comment: comment,
name: name,
concreteType: concreteType,
methods: make(map[string]*Method, len(methods)),
constructors: make(map[string]*Function, len(constructors)),
}
for _, m := range methods {
t.methods[m.Name()] = m
}
for _, c := range constructors {
t.constructors[c.Name()] = c
}
return t
}
2018-10-10 07:32:37 +09:00
// Definition generates the Go code required to define and implement this type,
// its methods, and its functions.
2018-10-09 05:19:10 +09:00
func (t *Typedef) Definition() jen.Code {
def := jen.Empty().Add(
t.comment,
).Line().Type().Id(
t.name,
).Add(
t.concreteType,
)
for _, c := range t.constructors {
def = def.Line().Line().Add(c.Definition())
}
for _, m := range t.methods {
def = def.Line().Line().Add(m.Definition())
}
return def
}
2018-10-10 07:32:37 +09:00
// Method obtains the Go code to be generated for the method with a specific
// name. Panics if no such method exists.
2018-10-09 05:19:10 +09:00
func (t *Typedef) Method(name string) *Method {
return t.methods[name]
}
2018-10-10 07:32:37 +09:00
// Constructors obtains the Go code to be generated for the function with a
// specific name. Panics if no such function exists.
2018-10-09 05:19:10 +09:00
func (t *Typedef) Constructors(name string) *Function {
return t.constructors[name]
}