generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
module.go
266 lines (236 loc) · 6.59 KB
/
module.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package schema
import (
"database/sql"
"database/sql/driver"
"fmt"
"os"
"reflect"
"slices"
"sort"
"strings"
"github.com/alecthomas/types/optional"
"golang.org/x/exp/maps"
"google.golang.org/protobuf/proto"
schemapb "github.com/TBD54566975/ftl/backend/protos/xyz/block/ftl/v1/schema"
)
type Module struct {
Pos Position `parser:"" protobuf:"1,optional"`
Comments []string `parser:"@Comment*" protobuf:"2"`
Builtin bool `parser:"@'builtin'?" protobuf:"3"`
Name string `parser:"'module' @Ident '{'" protobuf:"4"`
Decls []Decl `parser:"@@* '}'" protobuf:"5"`
}
var _ Node = (*Module)(nil)
var _ Symbol = (*Module)(nil)
var _ sql.Scanner = (*Module)(nil)
var _ driver.Valuer = (*Module)(nil)
func (m *Module) Value() (driver.Value, error) { return proto.Marshal(m.ToProto()) }
func (m *Module) Scan(src any) error {
switch src := src.(type) {
case []byte:
module, err := ModuleFromBytes(src)
if err != nil {
return err
}
*m = *module
return nil
default:
return fmt.Errorf("cannot scan %T", src)
}
}
// Resolve returns the declaration in this module with the given name, or nil
func (m *Module) Resolve(ref Ref) *ModuleDecl {
if ref.Module != "" && ref.Module != m.Name {
return nil
}
for _, d := range m.Decls {
if d.GetName() == ref.Name {
return &ModuleDecl{optional.Some(m), d}
}
}
return nil
}
func (m *Module) schemaSymbol() {}
func (m *Module) Position() Position { return m.Pos }
func (m *Module) schemaChildren() []Node {
children := make([]Node, 0, len(m.Decls))
for _, d := range m.Decls {
children = append(children, d)
}
return children
}
type spacingRule struct {
gapWithinType bool
skipGapAfterTypes []reflect.Type
}
func (m *Module) String() string {
w := &strings.Builder{}
fmt.Fprint(w, EncodeComments(m.Comments))
if m.Builtin {
fmt.Fprint(w, "builtin ")
}
fmt.Fprintf(w, "module %s {\n", m.Name)
// print decls with spacing rules
typeSpacingRules := map[reflect.Type]spacingRule{
reflect.TypeOf(&Config{}): {gapWithinType: false},
reflect.TypeOf(&Secret{}): {gapWithinType: false, skipGapAfterTypes: []reflect.Type{reflect.TypeOf(&Config{})}},
reflect.TypeOf(&Database{}): {gapWithinType: false},
reflect.TypeOf(&Topic{}): {gapWithinType: false},
reflect.TypeOf(&Subscription{}): {gapWithinType: false, skipGapAfterTypes: []reflect.Type{reflect.TypeOf(&Topic{})}},
reflect.TypeOf(&Enum{}): {gapWithinType: true},
reflect.TypeOf(&Data{}): {gapWithinType: true},
reflect.TypeOf(&Verb{}): {gapWithinType: true},
}
lastTypePrinted := optional.None[reflect.Type]()
for _, decl := range m.Decls {
t := reflect.TypeOf(decl)
rules, ok := typeSpacingRules[t]
if !ok {
rules = spacingRule{gapWithinType: true}
}
if lastType, ok := lastTypePrinted.Get(); ok {
if lastType == t {
if rules.gapWithinType {
fmt.Fprintln(w)
}
} else if !slices.Contains(rules.skipGapAfterTypes, lastType) {
fmt.Fprintln(w)
}
}
fmt.Fprintln(w, indent(decl.String()))
lastTypePrinted = optional.Some[reflect.Type](t)
}
fmt.Fprintln(w, "}")
return w.String()
}
// AddDecls appends decls to the module.
//
// Decls are only added if they are not already present in the module or if they change the visibility of an existing
// Decl.
func (m *Module) AddDecls(decls []Decl) {
// decls are namespaced by their type.
typeQualifiedName := func(d Decl) string {
return reflect.TypeOf(d).Name() + "." + d.GetName()
}
existingDecls := map[string]Decl{}
for _, d := range m.Decls {
existingDecls[typeQualifiedName(d)] = d
}
for _, newDecl := range decls {
tqName := typeQualifiedName(newDecl)
if existingDecl, ok := existingDecls[tqName]; ok {
if newDecl.IsExported() && !existingDecl.IsExported() {
existingDecls[tqName] = newDecl
}
continue
}
existingDecls[tqName] = newDecl
}
m.Decls = maps.Values(existingDecls)
}
// AddDecl adds a single decl to the module.
//
// It is only added if not already present or if it changes the visibility of the existing Decl.
func (m *Module) AddDecl(decl Decl) {
m.AddDecls([]Decl{decl})
}
// AddData and return its index.
//
// If data is already in the module, the existing index is returned.
// If the new data is exported but the existing data is not, it sets it to being exported.
func (m *Module) AddData(data *Data) int {
for i, d := range m.Decls {
if d, ok := d.(*Data); ok && d.Name == data.Name {
d.Export = d.Export || data.Export
return i
}
}
m.Decls = append(m.Decls, data)
return len(m.Decls) - 1
}
func (m *Module) Verbs() []*Verb {
var verbs []*Verb
for _, d := range m.Decls {
if v, ok := d.(*Verb); ok {
verbs = append(verbs, v)
}
}
return verbs
}
func (m *Module) Data() []*Data {
var data []*Data
for _, d := range m.Decls {
if v, ok := d.(*Data); ok {
data = append(data, v)
}
}
return data
}
// Imports returns the modules imported by this module.
func (m *Module) Imports() []string {
imports := map[string]bool{}
_ = Visit(m, func(n Node, next func() error) error { //nolint:errcheck
switch n := n.(type) {
case *Ref:
if n.Module != "" && n.Module != m.Name {
imports[n.Module] = true
}
default:
}
return next()
})
importStrs := maps.Keys(imports)
sort.Strings(importStrs)
return importStrs
}
func (m *Module) ToProto() proto.Message {
return &schemapb.Module{
Pos: posToProto(m.Pos),
Builtin: m.Builtin,
Name: m.Name,
Comments: m.Comments,
Decls: declListToProto(m.Decls),
}
}
func (m *Module) GetName() string { return m.Name }
func (m *Module) IsExported() bool { return false }
// ModuleFromProtoFile loads a module from the given proto-encoded file.
func ModuleFromProtoFile(filename string) (*Module, error) {
data, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
return ModuleFromBytes(data)
}
// ModuleFromProto converts a protobuf Module to a Module and validates it.
func ModuleFromProto(s *schemapb.Module) (*Module, error) {
module := &Module{
Pos: posFromProto(s.Pos),
Builtin: s.Builtin,
Name: s.Name,
Comments: s.Comments,
Decls: declListToSchema(s.Decls),
}
return module, ValidateModule(module)
}
func ModuleFromBytes(b []byte) (*Module, error) {
s := &schemapb.Module{}
if err := proto.Unmarshal(b, s); err != nil {
return nil, err
}
return ModuleFromProto(s)
}
func ModuleToBytes(m *Module) ([]byte, error) {
return proto.Marshal(m.ToProto())
}
func moduleListToSchema(s []*schemapb.Module) ([]*Module, error) {
var out []*Module
for _, n := range s {
module, err := ModuleFromProto(n)
if err != nil {
return nil, err
}
out = append(out, module)
}
return out, nil
}