-
Notifications
You must be signed in to change notification settings - Fork 1
/
codegen.go
314 lines (284 loc) · 9.23 KB
/
codegen.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package main
import (
"io"
"io/ioutil"
"os"
"sort"
sysl "github.com/anz-bank/sysl/src/proto"
parser "github.com/anz-bank/sysl/sysl2/naive"
ebnfGrammar "github.com/anz-bank/sysl/sysl2/proto"
"github.com/anz-bank/sysl/sysl2/sysl/eval"
"github.com/anz-bank/sysl/sysl2/sysl/msg"
"github.com/anz-bank/sysl/sysl2/sysl/parse"
"github.com/anz-bank/sysl/sysl2/sysl/syslutil"
"github.com/anz-bank/sysl/sysl2/sysl/validate"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"gopkg.in/alecthomas/kingpin.v2"
)
// Node can be string or node
type Node []interface{}
type CodeGenOutput struct {
filename string
output Node
}
func getKeyFromValueMap(v *sysl.Value, key string) *sysl.Value {
if m := v.GetMap(); m != nil {
return m.Items[key]
}
return nil
}
func processChoice(g *ebnfGrammar.Grammar, obj *sysl.Value, choice *ebnfGrammar.Choice) Node {
var result Node
for i, seq := range choice.Sequence {
seqResult := Node{}
fullScan := true
for _, term := range seq.Term {
switch x := term.Atom.Union.(type) {
// String tokens dont have quantifiers
case *ebnfGrammar.Atom_String_:
seqResult = append(seqResult, x.String_)
case *ebnfGrammar.Atom_Rulename:
var ruleResult interface{}
minc, maxc := parser.GetTermMinMaxCount(term)
v := getKeyFromValueMap(obj, x.Rulename.Name)
// raise error if required
// i.e. no quantifier or +
// and missing from obj map
if minc > 0 && v == nil {
fullScan = false
break
}
// skip if rule has
// quantifier == * or ?
// and does not exist in obj map
if minc == 0 && v == nil {
continue
}
if maxc > 1 {
var valueList []*sysl.Value
switch vv := v.Value.(type) {
case *sysl.Value_List_:
valueList = vv.List.Value
case *sysl.Value_Set:
valueList = vv.Set.Value
default:
logrus.Warnf("Expecting a collection type, got %T for rule %s", vv, x.Rulename.Name)
fullScan = false
}
ruleInstances := Node{}
for _, valueItem := range valueList {
// Drill down the rule
node := processRule(g, valueItem, x.Rulename.Name)
// Check post-conditions
if len(node) == 0 {
fullScan = false
break
}
ruleInstances = append(ruleInstances, node)
}
ruleResult = ruleInstances
} else { // maxc == 1
// Drill down the rule
if v.GetList() != nil || v.GetSet() != nil {
logrus.Warnf("Got List or Set instead of map")
}
node := processRule(g, v, x.Rulename.Name)
// Check post-conditions
if len(node) == 0 {
logrus.Warnf("could not process rule: ( %s )", x.Rulename.Name)
fullScan = false
break
}
if s, ok := node[0].(string); ok && len(node) == 1 {
ruleResult = s
} else {
ruleResult = node
}
}
seqResult = append(seqResult, ruleResult)
case *ebnfGrammar.Atom_Choices:
// minc, maxc := parser.GetMinMaxCount(term)
node := processChoice(g, obj, x.Choices)
if len(node) == 0 {
logrus.Warnf("could not process Choice\n")
fullScan = false
break
}
seqResult = append(seqResult, node)
default:
logrus.Warningf("processChoice: choice %d : %T", i, x)
panic("Unexpected atom type")
}
if !fullScan {
break
}
}
if fullScan {
result = append(result, seqResult)
}
}
return result
}
func processRule(g *ebnfGrammar.Grammar, obj *sysl.Value, ruleName string) Node {
var str string
if x := obj.GetMap(); x != nil {
for key := range x.Items {
str += key + ", "
}
}
// logrus.Debugf("processRule: %s, obj keys (%s)", ruleName, str)
rule := g.Rules[ruleName]
if rule == nil {
root := Node{}
if eval.IsCollectionType(obj) {
return nil
}
// Should we convert int and bools to string and return?
return append(root, obj.GetS())
}
root := processChoice(g, obj, rule.Choices)
return root
}
func readGrammar(filename, grammarName, startRule string) *ebnfGrammar.Grammar {
dat, err := ioutil.ReadFile(filename)
if err != nil {
logrus.Errorf("Unable to open grammar file: %s\nGot Error: %s", filename, err.Error())
return nil
}
return parser.ParseEBNF(string(dat), grammarName, startRule)
}
// applyTranformToModel loads applies the transform to input model
func applyTranformToModel(modelName, transformAppName, viewName string, model, transform *sysl.Module) *sysl.Value {
modelApp := model.Apps[modelName]
view := transform.Apps[transformAppName].Views[viewName]
if view == nil {
panic(errors.Errorf("Cannot execute missing view: %s, in app %s", viewName, transformAppName))
}
s := eval.Scope{}
s.AddApp("app", modelApp)
var result *sysl.Value
// assume args are
// app <: sysl.App and
// type <: sysl.Type
if len(view.Param) >= 2 {
result = eval.MakeValueList()
var tNames []string
for tName := range modelApp.Types {
tNames = append(tNames, tName)
}
sort.Strings(tNames)
for _, tName := range tNames {
t := modelApp.Types[tName]
s["typeName"] = eval.MakeValueString(tName)
s["type"] = eval.TypeToValue(t)
eval.AppendItemToValueList(result.GetList(), eval.EvaluateView(transform, transformAppName, viewName, s))
}
} else {
result = eval.EvaluateView(transform, transformAppName, viewName, s)
}
return result
}
// Serialize serializes node to string
func Serialize(w io.Writer, delim string, node Node) error {
for _, n := range node {
switch x := n.(type) {
case string:
if _, err := io.WriteString(w, x+delim); err != nil {
return err
}
case Node:
if err := Serialize(w, delim, x); err != nil {
return err
}
}
}
return nil
}
// GenerateCode transform input sysl model to code in the target language described by
// grammar and a sysl transform
func GenerateCode(codegenParams *CmdContextParamCodegen) []*CodeGenOutput {
var codeOutput []*CodeGenOutput
logrus.Debugf("root-model: %s\n", *codegenParams.rootModel)
logrus.Debugf("root-transform: %s\n", *codegenParams.rootTransform)
logrus.Debugf("model: %s\n", *codegenParams.model)
logrus.Debugf("transform: %s\n", *codegenParams.transform)
logrus.Debugf("grammar: %s\n", *codegenParams.grammar)
logrus.Debugf("start: %s\n", *codegenParams.start)
logrus.Debugf("loglevel: %s\n", *codegenParams.loglevel)
if *codegenParams.isVerbose {
*codegenParams.loglevel = debug
}
// Default info
if level, has := syslutil.LogLevels[*codegenParams.loglevel]; has {
logrus.SetLevel(level)
}
modelParser := parse.NewParser()
mod, modelAppName := parse.LoadAndGetDefaultApp(*codegenParams.rootModel, *codegenParams.model, modelParser)
tfmParser := parse.NewParser()
tx, transformAppName := parse.LoadAndGetDefaultApp(*codegenParams.rootTransform, *codegenParams.transform, tfmParser)
g := readGrammar(*codegenParams.grammar, "gen", *codegenParams.start)
if g == nil {
logrus.Errorf("Unable to load grammar: %s", *codegenParams.grammar)
return nil
}
grammarSysl, err := validate.LoadGrammar(*codegenParams.grammar)
if err == nil {
validator := validate.NewValidator(grammarSysl, tx.GetApps()[transformAppName], tfmParser)
validator.Validate(*codegenParams.start)
validator.LogMessages()
} else {
msg.NewMsg(msg.WarnValidationSkipped, []string{err.Error()}).LogMsg()
}
fileNames := applyTranformToModel(modelAppName, transformAppName, "filename", mod, tx)
if fileNames == nil {
return nil
}
result := applyTranformToModel(modelAppName, transformAppName, g.Start, mod, tx)
if result.GetMap() != nil {
filename := fileNames.GetMap().Items["filename"].GetS()
logrus.Println(filename)
r := processRule(g, result, g.Start)
codeOutput = append(codeOutput, &CodeGenOutput{filename, r})
} else {
fileValues := fileNames.GetList().Value
for i, v := range result.GetList().Value {
filename := fileValues[i].GetMap().Items["filename"].GetS()
r := processRule(g, v, g.Start)
codeOutput = append(codeOutput, &CodeGenOutput{filename, r})
}
}
return codeOutput
}
func outputToFiles(outDir string, output []*CodeGenOutput) error {
for _, o := range output {
f, err := os.Create(outDir + "/" + o.filename)
if err != nil {
return err
}
logrus.Warningln("Writing file: " + f.Name())
if err := Serialize(f, " ", o.output); err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
}
return nil
}
func configureCmdlineForCodegen(sysl *kingpin.Application) *CmdContextParamCodegen {
gen := sysl.Command("gen", "Generate code")
returnValues := &CmdContextParamCodegen{}
returnValues.rootModel = gen.Flag("root-model",
"sysl root directory for input model file (default: .)").Default(".").String()
returnValues.rootTransform = gen.Flag("root-transform",
"sysl root directory for input transform file (default: .)").Default(".").String()
returnValues.model = gen.Flag("model", "model.sysl").Default(".").String()
returnValues.transform = gen.Flag("transform", "grammar.g").Default(".").String()
returnValues.grammar = gen.Flag("grammar", "grammar.g").Default(".").String()
returnValues.start = gen.Flag("start", "start rule for the grammar").Default(".").String()
returnValues.outDir = gen.Flag("outdir", "output directory").Default(".").String()
returnValues.loglevel = gen.Flag("log", "log level[debug,info,warn,off]").Default("info").String()
returnValues.isVerbose = gen.Flag("verbose", "show output").Short('v').Default("false").Bool()
return returnValues
}