This repository has been archived by the owner on Apr 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
108 lines (105 loc) · 2.92 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
107
108
var Parser = require('jison').Parser;
var grammar = {
lex: {
// https://stackoverflow.com/questions/25889540/jison-start-conditions-with-json-format
startConditions: {
DOUBLE_QUOTE_STRING_START_CONDITION: '// string starts with double quote',
SINGLE_QUOTE_STRING_START_CONDITION: '// string starts with single quote'
},
rules: [
['\\s+', '/* skip whitespace */'],
/** DOUBLE QUOTE STRING
* Note: visual "\n" we see in console when call JSON.stringify("a\nb") actually is "a" + "\" + "n" + "b"
*/
[`"`, `this.begin("DOUBLE_QUOTE_STRING_START_CONDITION"); return '"';`],
[
['DOUBLE_QUOTE_STRING_START_CONDITION'],
`[^"\\r\\n]+`,
'return "DOUBLE_QUOTE_STRING";'
],
[
['DOUBLE_QUOTE_STRING_START_CONDITION'],
`"`,
`this.popState(); return '"';`
],
/** SINGLE QUOTE STRING
*/
[`'`, `this.begin("SINGLE_QUOTE_STRING_START_CONDITION"); return "'";`],
[
['SINGLE_QUOTE_STRING_START_CONDITION'],
`[^'\\r\\n]+`,
'return "SINGLE_QUOTE_STRING";'
],
[
['SINGLE_QUOTE_STRING_START_CONDITION'],
`'`,
`this.popState(); return "'";`
],
/** IDENTIFIER
* - Start with alphabet or underscore or $
* - Followed by alphanumerics or underscores or $
*/
['[\\$a-zA-Z_][\\w\\$]*', 'return "IDENTIFIER"'],
/** NUMBER
* Support "1" , "-1" , "1.0" , "-1.0" , "1." , ".1"
*/
['[-]?((\\d+(\\.\\d*)?)|(\\d*\\.\\d+))', 'return "NUMBER";'],
[',', 'return ",";'],
['\\[', 'return "[";'],
[']', 'return "]";'],
['{', 'return "{";'],
['}', 'return "}";'],
[':', 'return ":";'],
['$', 'return "EOF";']
]
},
bnf: {
entry: [['expr EOF', 'return $1']],
expr: [
['number', '$$ = $1'],
['string', '$$ = $1'],
['array', '$$ = $1'],
['object', '$$ = $1'],
],
number: [['NUMBER', '$$ = Number($1)']],
string: [
['double_quote_string', '$$ = $1'],
['single_quote_string', '$$ = $1']
],
double_quote_string: [
[`" "`, '$$ = ""'],
[`" DOUBLE_QUOTE_STRING "`, '$$ = $2']
],
single_quote_string: [
[`' '`, '$$ = ""'],
[`' SINGLE_QUOTE_STRING '`, '$$ = $2']
],
array: [['[ argList ]', '$$ = $2']],
argList: [
['expr , argList', '$$ = [$1].concat($3)'],
['expr', '$$ = [$1]'],
['', '$$ = []']
],
object: [['{ objProperties }', '$$ = $2']],
objProperties: [
[
'key : value , objProperties',
'$$ = Object.assign({[$1]: $3}, $5)'
],
['key : value', '$$ = {[$1] : $3}'],
['', '$$ = {}']
],
key: [
['string', '$$ = $1'],
['IDENTIFIER', '$$ = $1']
],
value: [
['expr', '$$ = $1']
],
}
};
var parser = new Parser(grammar);
function parse(txt) {
return parser.parse(txt);
}
module.exports = parse;