This repository has been archived by the owner on Oct 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstructure.go
91 lines (76 loc) · 2.29 KB
/
structure.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package gogen
import (
"go/ast"
"fmt"
)
// Structure represents the struct type of a
// given build
type Structure struct {
BaseType
parent *ast.StructType
spec *ast.TypeSpec
// slice of fields
fields map[string]*StructField
// map of methods
methods map[string]*Function
}
// NewStructure returns new Instance of the structure type
// with the provided parent and type spec.
func NewStructure(parent *ast.StructType, spec *ast.TypeSpec, fMap map[string]*StructField, annotationMap *AnnotationMap) *Structure {
s := &Structure{
BaseType: BaseType{
name: spec.Name.Name,
annotations: annotationMap,
},
parent: parent,
spec: spec,
fields: fMap,
methods: make(map[string]*Function),
}
return s
}
// FilteredStructFields is a map of struct fields
// that can be filtered by their annotations
type FilteredStructFields map[string]*StructField
// Filter will filter struct fields map and return
// all those that have annotation with name given by parameter
func (f FilteredStructFields) Filter(name string) map[string]*StructField {
newMap := make(map[string]*StructField)
for it := range f {
if f[it].Annotations().Has(name) {
newMap[it] = f[it]
}
}
return newMap
}
// Fields returns fields that are associated with the
// given Structure.
func (s *Structure) Fields() FilteredStructFields {
return s.fields
}
// AddMethod binds a method into the current structure
func (s *Structure) AddMethod(fun *Function) {
s.methods[fun.Name()] = fun
}
// Method returns a Function bound to the current structure
func (s *Structure) Method(name string) *Function {
return s.methods[name]
}
// Methods returns all Function-s found to the current structure
func (s *Structure) Methods() map[string]*Function {
return s.methods
}
// ParseStruct will create a structure
// with parameters given and return it
func ParseStruct(spec *ast.TypeSpec, parent *ast.StructType, comments ast.CommentMap) *Structure {
fMap := make(map[string]*StructField)
for _, field := range parent.Fields.List {
if len(field.Names) == 0 {
fMap[fmt.Sprintf("_%s", field.Type)] = ParseStructField(field, comments.Filter(field))
continue
}
fMap[field.Names[0].Name] = ParseStructField(field, comments.Filter(field))
}
s := NewStructure(parent, spec, fMap, ParseAnnotations(comments))
return s
}