-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
106 lines (98 loc) · 2.53 KB
/
index.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
function UINode(id, args, srow) {
this.id = id;
this.args = args;
this.children = undefined;
this.up = undefined;
this.srow = srow;
Object.defineProperty(this, 'up', { enumerable: false });
}
UINode.tab = ' ';
UINode.prototype = {
getPath: function () {
if (!this.up)
return [];
var upp = this.up.getPath();
upp.push(this.id);
return upp;
},
toString: function (indent, is_ui) {
if (!indent)
indent = '';
if (!this.up)
return this.childrenToString(indent, is_ui);
if (is_ui) {
var s = this.args ? [indent, this.id, ' ', this.args].join('') : indent + this.id;
if (this.children && this.children.length)
s += '\n' + this.childrenToString(indent + UINode.tab, is_ui);
else
s += '\n';
} else {
var s = [indent, this.id, '(', this.args || '', ')'].join('');
if (this.children)
s += ' {\n' + this.childrenToString(indent + UINode.tab, is_ui) + indent + '}';
s += '\n';
}
return s;
},
childrenToString: function (indent, is_ui) {
var s = '';
if (this.children) {
this.children.forEach(function (d) {
s += d.toString(indent, is_ui);
});
}
return s;
},
add: function (d) {
if (this.children === undefined)
this.children = [];
this.children.push(d);
d.up = this;
},
enumChildren: function (cb) {
if (!this.children)
return;
for (var i = 0, ch = this.children, n = ch.length; i < n; ++i) {
var sub = ch[i];
cb(sub, sub.id, sub.args)
}
}
};
function parse_tree(text) {
if (typeof text !== 'string')
throw TypeError('source is not a string type');
var rows = text.split(/\r\n?|\n\r?/),
root = new UINode('root',''),
data = root,
last = undefined,
indents = [ 0 ];
indent = 0;
rows.forEach(function (row, index) {
var ind = /^([\t\s]*)(.*)$/.exec(row);
var row = ind[2];
if (!row || row[0] === '#' || (row[0] === row[1] && (row[0] === '/' || row[0] === '-'))) // '#', '//', '--' comment
return ;
var els = /^([a-z0-9-_$]+)(?:\s*(.*))?$/i.exec(row);
if (!els)
throw(Error(opts.file+'(' + (index+1) + '): Syntax error'));
var dir = new UINode(els[1], els[2], index + 1),
level = ind[1].length;
if (level > indent) {
data = last;
indents.push(indent);
indent = level;
} else
if (level < indent) {
do {
data = data.up;
indent = indents.pop();
} while (indent > level);
if (indent !== level)
throw(Error(opts.file+'(' + index-1 + '): Indentation error (not a regular indent)'));
}
data.add(last = dir);
});
return root;
}
module.exports = parse_tree;
parse_tree.Node = UINode;