-
Notifications
You must be signed in to change notification settings - Fork 1
/
parser.js
518 lines (489 loc) · 15.9 KB
/
parser.js
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
const Parser = require('jison').Parser
const fs = require('fs')
const path = require('path')
const crypto = require("crypto")
const newID = () => { return crypto.randomBytes(10).toString('hex') }
String.prototype.replaceAll = function (search, replacement) {
return this.split(search).join(replacement)
}
String.prototype.matchRule = function (rule) {
return new RegExp('^' + rule.split('*').join('.*') + '$').test(this)
}
const grammar = {
'lex': {
'rules': [
['^//.*\\n', '/**/'],
['group', "return 'GROUP'"],
['include', "return 'INCLUDE'"],
['^[A-Za-z\\*][A-Za-z0-9-\\.\\*]*', "return 'NAME'"],
[',', "return 'COMMA'"],
['\\{', "return 'OP'"],
['\\}', "return 'CP'"],
['\\[', "return 'OB'"],
['\\]', "return 'CB'"],
['-', "return 'STROKE'"],
['>', "return 'LARROW'"],
[':', "return 'COLON'"],
['^\\"([/:A-Za-z0-9-\\*].*)\\"', "return 'ITEM'"],
['^([/:A-Za-z0-9-].*)', "return 'STRING'"],
['[\\n\\s\\t\\r]+', '/**/']
]
},
'bnf': {
'craftdot': ['nodes'],
'nodes': [
['nodes node', '{$$=yy.appendOrNewArray($$, $2)}'],
['node', '{$$=yy.appendOrNewArray($$, $1)}']
],
'node': [
['GROUP NAME OP nodes CP', '{$$=yy.newGroup($2, $4); yy.addGroup($$)}'],
['names', '{$$=yy.newCrafts($1); yy.addCrafts($$)}'],
['names OP attrs CP', '{$$=yy.newCrafts($1, $3); yy.addCrafts($$) }'],
['names OB styleAttrs CB OP attrs CP', '{$$=yy.newCrafts($1, $6, $3); yy.addCrafts($$)}'],
['names OB styleAttrs CB', '{$$=yy.newCrafts($1, "", $3); yy.addCrafts($$)}'],
['INCLUDE OP ITEM CP', '{{$$=yy.newInclude($3); yy.addInclude($$)}}'],
'flows'
],
'names': [
['names COMMA name', '{$$=yy.appendOrNewArray($$, $3)}'],
['name', '{$$=yy.appendOrNewArray($$, $1)}']
],
'name': ['NAME'],
'attrs': [
['attrs attr', '{$$=yy.appendOrNewArray($$, $2)}'],
['attr', '{$$=yy.appendOrNewArray($$, $1)}']
],
'attr': [
['NAME COLON items', '{$$=yy.newAttr($1, $3)}'],
['NAME COLON item', '{$$=yy.newAttr($$, $3)}']
],
'items': [
['items STROKE item', '{$$=yy.appendOrNewArray($$, $3)}'],
['STROKE item', '{$$=yy.appendOrNewArray($$, $2)}']
],
'item': [
['ITEM', '{$$=yy.newItem($1)}'],
'NAME',
'STRING'
],
'flows': [
['flows STROKE LARROW names', '{$$=yy.appendToFlows($1, $4); yy.addFlows($$)}'],
['flow', '{yy.addFlows($$)}']
],
'flow': [
['names STROKE LARROW names', '{$$=yy.newFlows($1, $4)}'],
['names STROKE LARROW names OB styleAttrs CB', '{$$=yy.newFlows($1, $4, $6)}']
],
'styleAttrs': [
['styleAttrs styleAttr', '{$$=yy.appendOrNewArray($$, $2)}'],
['styleAttrs COMMA styleAttr', '{$$=yy.appendOrNewArray($$, $3)}'],
['styleAttr', '{$$=yy.appendOrNewArray($$, $1)}']
],
'styleAttr': [
['NAME COLON item', '{$$=yy.newSAttr($1, $3)}']
],
}
}
const parser = new Parser(grammar)
const yy = {
fileGroup: 'root',
nodes: {},
includes: {},
parsedFlows: [],
parsedNodes: [],
nodePath2ID: {},
flows: [],
cwd: '',
reset: () => {
yy.fileGroup = 'root'
yy.nodes = {}
yy.includes = {}
yy.parsedFlows = []
yy.parsedNodes = []
yy.nodePath2ID = {}
yy.flows = []
yy.cwd = ''
},
appendOrNewArray: (nodes, node) => {
if (!Array.isArray(nodes)) {
nodes = []
}
if (Array.isArray(node)) {
nodes = nodes.concat(node)
} else {
nodes.push(node)
}
return nodes
},
appendToFlows: (flows, names) => {
let newFlows = []
let tailFlows = flows.filter(x => x['tail'] == true)
if (tailFlows.length == 0) {
tailFlows = flows
}
tailFlows.forEach(flow => {flow['tail'] = false})
let fromList = Array.from(new Set(tailFlows.map(flow => flow.to)))
for (from of fromList){
for (name of names) {
let newFlow = yy.newFlow(from, name)
newFlow['tail'] = true
newFlows.push(newFlow)
}
}
return newFlows
},
newGroup: (name, childs) => {
const g = {
id: newID(),
path: '',
name: name,
type: 'group',
crafts: [],
includes: [],
subgroups: [],
parent: ''
}
if (yy.fileGroup !== 'root') {
g.parent = yy.fileGroup
yy.nodes[yy.fileGroup].subgroups.push(g.id)
}
for (child of childs) {
switch (child.type) {
case 'group':
g.subgroups.push(child.id)
break
case 'craft':
g.crafts.push(child.id)
yy.nodes[child.id]['group'] = g.id
break
case 'include':
g.includes.push(child.path)
yy.includes[child.path]['group'] = g.id
break
}
}
return g
},
newCrafts: (names, attrs, styleAttrs) => {
let crafts = []
for (let name of names) {
crafts.push(yy.newCraft(name, attrs, styleAttrs))
}
return crafts
},
newCraft: (name, attrs, styleAttrs) => {
const c = {
type: 'craft',
id: newID(),
name: name,
path: name,
}
if (yy.fileGroup !== 'root') {
c['group'] = yy.fileGroup
yy.nodes[yy.fileGroup].crafts.push(c.id)
}
if (name.includes('*')) {
c['wildcard'] = true
}
if (attrs) {
c['attrs'] = attrs
}
if (styleAttrs) {
c['styleAttrs'] = styleAttrs
}
return c
},
newInclude: (includePath) => {
includePath = includePath.replace(/(^")|("$)/g, "")
includePath = path.join(yy.cwd, includePath)
if (fs.existsSync(includePath)) {
return {
type: 'include',
id: newID(),
path: includePath,
}
}
return {
type: 'include',
id: newID(),
path: "",
}
},
newAttr: (name, value) => {
if (Array.isArray(value)) {
return {
name: name,
id: newID(),
items: value
}
}
return {
name: name,
id: newID(),
value: value
}
},
newItem: (item) => {
return item.replace(/(^")|("$)/g, "")
},
newFlow: (from, to, styleAttrs) => {
const flow = {
id: newID(),
from: from,
fromPath: '',
to: to,
toPath: ''
}
if (from.includes('*') || to.includes('*')) {
flow['wildcard'] = true
}
if (styleAttrs) {
flow['styleAttrs'] = styleAttrs
}
return flow
},
newFlows: (fromList, toList, styleAttrs) => {
const flows = []
for ( from of fromList ) {
for ( to of toList ) {
flows.push(yy.newFlow(from, to, styleAttrs))
}
}
return flows
},
newSAttr: (key, vaule) => {
return `${key}="${vaule}";`
},
parseGroupPath: (gid, parentGroupID, groups) => {
if (parentGroupID) {
yy.nodes[gid].path = `${yy.nodes[parentGroupID].path}-${yy.nodes[gid].name}`
} else {
yy.nodes[gid].path = yy.nodes[gid].name
}
if (yy.nodes[gid].path in groups){
console.log(`'${yy.nodes[gid].name}' already exist as '${yy.nodes[gid].path}'`)
process.exit()
}
groups[yy.nodes[gid].path] = yy.nodes[gid]
yy.nodes[gid].subgroups.forEach(g => {
yy.parseGroupPath(g, gid, groups)
})
},
addGroup: (group) => {
for (subg of group.subgroups) {
yy.nodes[subg]['parent'] = group.id
}
yy.nodes[group.id] = group
},
addCrafts: (crafts) => {
for (let craft of crafts) {
yy.addCraft(craft)
}
},
addCraft: (craft) => {
if (craft.id in yy.nodes) {
yy.nodes[craft.id] = mergeCraft(yy.nodes[craft.id], craft)
} else {
yy.nodes[craft.id] = craft
}
},
addInclude: (include) => {
if (!(include.path in yy.includes)) {
yy.includes[include.path] = include
}
},
addFlows: (flows) => {
for (flow of flows) {
yy.flows.push(flow)
}
},
parseWildcard: () => {
const wildcardCrafts = Object.keys(yy.nodes).filter(n => yy.nodes[n].type == 'craft').map(c => yy.nodes[c]).filter(c => 'wildcard' in c && c.wildcard == true)
const wildcardFlows = yy.flows.filter(f => 'wildcard' in f && f.wildcard == true)
const rootGroups = Object.keys(yy.nodes).filter(n => yy.nodes[n].type == 'group').map(g => yy.nodes[g]).filter(g => !g.parent)
let groups = {}
rootGroups.forEach(g => {
yy.parseGroupPath(g.id, '', groups)
})
let crafts = Object.keys(yy.nodes).filter(n => yy.nodes[n].type =='craft').map(c => yy.nodes[c]).filter(c => !('wildcard' in c))
let flows = yy.flows.filter(f => !('wildcard' in f))
crafts.forEach(c => {
if ('group' in c) {
c.path = `${yy.nodes[c.group].path}-${c.name}`
}
})
for (let wc of wildcardCrafts.reverse()) {
crafts = crafts.map(c => {
if (c.name.matchRule(wc.name)) {
c = mergeCraft(c, wc)
let {
name,
wildcard,
...wccopy
} = wc
return {
...c,
...{
...wccopy,
...c
}
}
}
return c
})
}
for (wf of wildcardFlows) {
flows = flows.map(f => {
if (f.from.matchRule(wf.from) && f.to.matchRule(wf.to)) {
let {
from,
to,
wildcard,
...wfcopy
} = wf
return {
...f,
...{
...wfcopy,
...f
}
}
}
return f
})
}
let paths = {}
let names = {}
crafts.forEach(c => {
if (c.path in paths) {
console.log(`'${c.name}' already exist as '${c.path}'`)
process.exit()
}
paths[c.path] = c.path
yy.nodePath2ID[c.path] = c.id
if (c.name in names) {
names[c.name].push(c.path)
} else {
names[c.name] = []
names[c.name].push(c.path)
}
})
Object.keys(groups).map(g => groups[g]).forEach(g => {
if (g.path in paths) {
console.log(`'${g.name}' already exist as '${g.path}'`)
process.exit()
}
paths[g.path] = g.path
yy.nodePath2ID[g.path] = g.id
if (g.name in names) {
names[g.name].push(g.path)
} else {
names[g.name] = []
names[g.name].push(g.path)
}
})
flows.forEach(f => {
const from = f.from.replaceAll('.', '-')
if (from in paths) {
f.fromPath = paths[from]
return
}
if (from in names) {
if (names[from].length == 1) {
f.fromPath = names[from][0]
return
}
if (names[from].length == 0) {
console.log(`${f.from} didn't found`)
process.exit()
}
if (names[from].length > 1) {
console.log(`conflict crafts '${f.from}', use full path like 'group1.${f.from}' and 'group2.${f.from}'`)
process.exit()
}
}
})
flows.forEach(f => {
const to = f.to.replaceAll('.', '-')
if (to in paths) {
f.toPath = paths[to]
return
}
if (to in names) {
if (names[to].length == 1) {
f.toPath = names[to][0]
return
}
if (names[to].length == 0) {
console.log(`${to} didn't found`)
process.exit()
}
if (names[to].length > 1) {
console.log(`conflict crafts '${f.to}', use full path like 'group1.${f.to}' and 'group2.${f.to}'`)
process.exit()
}
}
})
yy.parsedNodes.push(...crafts)
yy.parsedFlows = flows
yy.parsedNodes.push(...Object.keys(groups).map(g => groups[g]))
}
}
parser.yy = yy
function mergeCrafts(craftsA, craftsB) {
const craftsANames = Object.keys(craftA)
const craftsBNames = Object.keys(craftB)
const intersection = craftsANames.filter(v => craftsBNames.includes(v))
const missing = craftsANames
.concat(craftsBNames)
.filter(v => !craftsANames.includes(v) || !craftsBNames.includes(v))
.filter(v => craftsBNames.includes(v))
for (let m of missing) {
craftsA[m] = craftsB
}
for (let i of intersection) {
craftsA[i] = mergeCraft(craftsA[i], craftsB[i])
}
return craftsA
}
function mergeCraft(craftA, craftB) {
if ('attrs' in craftB) {
craftA['attrs'] = craftA.attrs || []
let attrs = craftA.attrs.map(x => x.name)
let missingAttrs = craftB.attrs.filter(x => !attrs.includes(x.name))
craftA.attrs.push(...missingAttrs)
}
return craftA
}
const parse = (craftdot, craftFilter, cwd, group) => {
craftFilter = craftFilter || '*'
parser.yy.cwd = cwd
if (group) {
parser.yy.fileGroup = group
}
parser.parse(craftdot)
parser.yy.parseWildcard()
if (Object.entries(parser.yy.includes).length !== 0 && parser.yy.includes.constructor === Object) {
for (let index in parser.yy.includes) {
const include = parser.yy.includes[index]
const includeCraftdot = fs.readFileSync(include.path, 'utf8')
delete parser.yy.includes[index]
const includeCwd = path.dirname(include.path)
parse(includeCraftdot, craftFilter, includeCwd, include.group)
}
}
const filteredCrafts = []
for (let flow of parser.yy.parsedFlows) {
if (flow.from.matchRule(craftFilter) || flow.to.matchRule(craftFilter)) {
filteredCrafts.push(flow.from)
filteredCrafts.push(flow.to)
}
}
parser.yy.parsedNodes = parser.yy.parsedNodes.filter(n => (n.type =='craft' && (n.name.matchRule(craftFilter) || filteredCrafts.includes(n.name))) || n.type != 'craft')
parser.yy.parsedFlows = parser.yy.parsedFlows.filter(flow => flow.from.matchRule(craftFilter) || flow.to.matchRule(craftFilter))
return parser.yy
}
module.exports = {
parse,
reset: yy.reset
}