-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathparse-protocol-expr.js
72 lines (61 loc) · 2.09 KB
/
parse-protocol-expr.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
let finalLine = 'Alas the file is done, aborting';
let sizePrefixLength = 6;
// converts lines in the format of 0000<length>(:data ..)0000<length>(:more ..) to ['(:data ..', '(:more ..']
function readPrefixedLines(str) {
let lines = [];
while (str.indexOf(finalLine) !== 0) {
let size = parseInt(str.slice(0, sizePrefixLength), 16);
if (!size) break;
lines.push(str.slice(sizePrefixLength, size + sizePrefixLength - 1));
str = str.slice(size + sizePrefixLength);
}
return lines;
}
function parseProtocolExpr(str) {
let prevChar = '';
let insideQuotes = false;
let buffer = '';
let data = [];
let refHierarchy = [];
let ref = data;
for (let line of readPrefixedLines(str)) {
for (let char of line.split('')) {
if (insideQuotes) {
if (prevChar != '\\' && char == '"') {
insideQuotes = false;
} else {
buffer = buffer + char;
}
} else {
switch (char) {
case '"':
insideQuotes = true;
break;
case ' ':
if (buffer) ref.push(buffer);
buffer = '';
break;
case '(':
let add = [];
refHierarchy.push(ref);
ref.push(add);
ref = add;
break;
case ')':
if (buffer) ref.push(buffer);
buffer = '';
if (refHierarchy.length < 1) {
throw `Line "${line}" is missing closing parenthesis.`;
}
ref = refHierarchy.pop();
break;
default:
buffer = buffer + char;
}
}
prevChar = char;
}
}
return data;
}
module.exports = parseProtocolExpr;