forked from skanaar/nomnoml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nomnoml.parser.js
73 lines (65 loc) · 2.13 KB
/
nomnoml.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
var nomnoml = nomnoml || {}
nomnoml.parse = function (source){
function onlyCompilables(line){
var ok = line[0] != '#' && line.substring(0,2) != '//'
return ok ? line : ''
}
var isDirective = function (line){ return line[0] === '#' }
var lines = source.split('\n').map(function (s){ return s.trim() })
var pureDirectives = _.filter(lines, isDirective)
var directives = _.object(pureDirectives.map(function (line){
var tokens = line.substring(1).split(':')
return [tokens[0].trim(), tokens[1].trim()]
}))
var pureDiagramCode = _.map(lines, onlyCompilables).join('\n').trim()
var ast = nomnoml.transformParseIntoSyntaxTree(nomnoml.intermediateParse(pureDiagramCode))
ast.directives = directives
return ast
}
nomnoml.intermediateParse = function (x){
return parser.parse(x)
}
nomnoml.transformParseIntoSyntaxTree = function (entity){
var relationId = 0
function transformCompartment(parts){
var lines = []
var rawClassifiers = []
var relations = []
_.each(parts, function (p){
if (typeof p === 'string')
lines.push(p)
if (p.assoc){ // is a relation
rawClassifiers.push(p.start)
rawClassifiers.push(p.end)
relations.push({
id: relationId++,
assoc: p.assoc,
start: p.start.parts[0][0],
end: p.end.parts[0][0],
startLabel: p.startLabel,
endLabel: p.endLabel
})
}
if (p.parts){ // is a classifier
rawClassifiers.push(p)
}
})
var allClassifiers = _.map(rawClassifiers, transformItem)
var noDuplicates = _.map(_.groupBy(allClassifiers, 'name'), function (cList){
return _.max(cList, function (c){ return c.compartments.length })
})
return nomnoml.Compartment(lines, noDuplicates, relations)
}
function transformItem(entity){
if (typeof entity === 'string')
return entity
if (_.isArray(entity))
return transformCompartment(entity)
if (entity.parts){
var compartments = _.map(entity.parts, transformCompartment)
return nomnoml.Classifier(entity.type, entity.id, compartments)
}
return undefined
}
return transformItem(entity)
}