-
Notifications
You must be signed in to change notification settings - Fork 42
/
grammar.go
266 lines (245 loc) · 5.84 KB
/
grammar.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 importer
/* FIXME
type grammarParam struct {
grammarInput string
grammarName string
}
type Grammar struct {
grammarParam
grammar *parser.Grammar
logger *logrus.Logger
types TypeList
}
func LoadGrammar(args OutputData, grammarInput string, logger *logrus.Logger) (out string, err error) {
gParam := grammarParam{
grammarInput: grammarInput,
grammarName: args.AppName,
}
return newGrammar(gParam, logger).writeSysl()
}
func newGrammar(param grammarParam, logger *logrus.Logger) *Grammar {
return &Grammar{
grammarParam: param,
logger: logger,
types: TypeList{},
}
}
func (g *Grammar) writeSysl() (string, error) {
g.grammar = parser.ParseEBNF(g.grammarParam.grammarInput, "", "")
var syslBytes bytes.Buffer
syslWriter := newWriter(&syslBytes, g.logger)
syslWriter.DisableJSONTags = true
info := SyslInfo{
OutputData: OutputData{
AppName: g.grammarName,
},
Title: g.grammarName + "File",
Description: g.grammarName + " Grammar",
}
allTypes := syslutil.MakeStrSet()
for _, rule := range g.grammar.GetRules() {
rp := makeRule(rule)
allTypes = allTypes.Union(rp.deps)
for _, t := range rp.types.Items() {
g.types.Add(t)
allTypes.Remove(t.Name())
}
}
for k := range allTypes {
if _, found := g.types.Find(k); !found {
g.types.Add(&Alias{name: k, Target: StringAlias})
}
}
g.linkTypes()
sort.SliceStable(g.types.Items(), func(i, j int) bool {
// We want to sort so __prefix types end up under the rule they are linked with
a := g.types.Items()[i].Name()
b := g.types.Items()[j].Name()
switch {
case strings.HasPrefix(a, "__") && strings.HasPrefix(b, "__"):
return strings.Compare(a, b) < 0
case strings.HasPrefix(a, "__"):
return strings.Compare(a[2:], b) < 0
case strings.HasPrefix(b, "__"):
return strings.Compare(a, b[2:]) < 0
}
return strings.Compare(a, b) < 0
})
if err := syslWriter.Write(info, g.types); err != nil {
g.logger.Errorf("writing into buffer failed %s", err)
return "", err
}
return syslBytes.String(), nil
}
func makeRule(rule *parser.Rule) ruleProcessor {
rp := ruleProcessor{
rule: rule,
deps: syslutil.MakeStrSet(),
}
root := rp.createChoice(rule.Choices)
if val, ok := rp.types.Find(root); ok {
switch x := val.(type) {
case *Union:
x.name = rule.Name.Name
rp.deps.Remove(root)
return rp
case *StandardType:
x.name = rule.Name.Name
rp.deps.Remove(root)
return rp
}
}
rp.deps.Insert(root)
t := &Alias{name: rule.Name.Name, Target: &SyslBuiltIn{root}}
rp.types.Add(t)
return rp
}
type ruleProcessor struct {
rule *parser.Rule
deps syslutil.StrSet // Names of external rules which this rule depends on
types TypeList
counter int
}
func (rp *ruleProcessor) newName() string {
out := fmt.Sprintf("__%s_%02d", rp.rule.Name.Name, rp.counter)
rp.counter++
return out
}
func (rp *ruleProcessor) createChoice(c *parser.Choice) string {
if len(c.Sequence) == 1 {
return rp.buildSequence(c.Sequence[0])
}
t := &Union{
name: rp.newName(),
Options: FieldList{},
}
for _, f := range c.Sequence {
t.Options = append(t.Options, Field{Name: rp.buildSequence(f)})
}
rp.deps.Insert(t.name)
rp.types.Add(t)
return t.name
}
func makeSizedField(name string, q *parser.Quantifier) *Field {
field := Field{
Name: name,
}
nested := &Array{
name: name,
}
if q == nil {
return nil
}
switch q.Union.(type) {
case *parser.Quantifier_Optional:
field.Optional = true
case *parser.Quantifier_ZeroPlus:
field.Type = nested
field.SizeSpec = &sizeSpec{
Min: 0,
Max: 0,
MaxType: OpenEnded,
}
case *parser.Quantifier_OnePlus:
field.Type = nested
field.SizeSpec = &sizeSpec{
Min: 1,
Max: 0,
MaxType: OpenEnded,
}
}
return &field
}
func (rp *ruleProcessor) buildSequence(s *parser.Sequence) string {
var fields []term
for _, t := range s.Term {
fields = append(fields, rp.buildTerm(t))
}
if len(fields) == 1 && fields[0].field == nil {
rp.deps.Insert(fields[0].name)
return fields[0].name
}
t := &StandardType{
name: rp.newName(),
Properties: FieldList{},
}
for _, f := range fields {
if len(fields) > 1 && f.name == StringTypeName {
continue
}
if f.field == nil {
f.field = &Field{Name: f.name}
}
t.Properties = append(t.Properties, *f.field)
rp.deps.Insert(f.name)
}
rp.types.Add(t)
rp.deps.Insert(t.name)
return t.name
}
type term struct {
name string // name of the type being pointed to
field *Field
}
func (rp *ruleProcessor) buildTerm(t *parser.Term) term {
res := term{}
switch a := t.Atom.Union.(type) {
case *parser.Atom_String_:
res.name = StringTypeName
case *parser.Atom_Rulename:
res.name = a.Rulename.Name
case *parser.Atom_Choices:
res.name = rp.createChoice(a.Choices)
default:
logrus.Fatal("Unhandled Term type")
}
if t.Quantifier != nil {
res.field = makeSizedField(res.name, t.Quantifier)
}
return res
}
func linkType(t *Type, types TypeList, cache *map[string]Type) {
find := func(name string) Type {
if val, ok := (*cache)[name]; ok {
return val
} else if val, ok := types.Find(name); ok {
(*cache)[name] = val
return val
}
return StringAlias
}
switch x := (*t).(type) {
case *Union:
for i := range x.Options {
if x.Options[i].Type == nil {
x.Options[i].Type = find(x.Options[i].Name)
} else {
linkType(&x.Options[i].Type, types, cache)
}
}
case *Alias:
if x.Target == nil {
x.Target = find(x.name)
}
case *StandardType:
for i := range x.Properties {
if x.Properties[i].Type == nil {
x.Properties[i].Type = find(x.Properties[i].Name)
} else {
linkType(&x.Properties[i].Type, types, cache)
}
}
case *Array:
x.Items = find(x.name)
}
}
func (g *Grammar) linkTypes() {
cache := map[string]Type{}
for i := range g.types.Items() {
t := g.types.types[i]
name := g.types.types[i].Name()
cache[name] = t
linkType(&t, g.types, &cache)
}
}
*/