-
Notifications
You must be signed in to change notification settings - Fork 0
/
next-json.pegjs
237 lines (176 loc) · 8.73 KB
/
next-json.pegjs
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
// NJSON Next-JSON Grammar
// Based on https://github.com/peggyjs/peggy/blob/main/examples/json.pegjs
NJSON = wss @(value / function)
ws "white space" = [ \t\n\r] / "//" (![\n] .)* / "/*" (!"*/" .)* "*/"
wss "white spaces" = ws*
colon = ":" wss
comma = "," wss
dot = "." wss
semicolon = ";" wss
open_round = "(" wss
closed_round = ")" wss
open_square = "[" wss
closed_square = "]" wss
open_brace = "{" wss
closed_brace = "}" wss
value = @(array / chain / constructor / false / null / number / object / object_assign / string / true / undefined) wss
false = "false" { return false; }
null = "null" { return null; }
true = "true" { return true; }
undefined = "undefined" { return undefined; }
object = open_brace entries:(head:entry tail:(comma @entry)* comma? { return Object.fromEntries([head, ...tail]); })? closed_brace { return entries || {}; }
entry = name:string colon value:value { return [name, value]; }
array = open_square values:(head:value tail:(comma @value)* comma? { return [head, ...tail]; })? closed_square { return values || []; }
number "number" = ("NaN" { return NaN; } / "-"? ("Infinity" / integer ("n" / frac? exp?))) wss
{
const txt = text();
if(txt === "-Infinity") return -Infinity;
if(txt === "-0") return -0;
if(txt === "Infinity") return Infinity;
return txt.slice(-1) === "n" ? BigInt(txt.slice(0, -1)) : parseFloat(txt);
}
exp = [eE] ("-" / "+")? decimal+
frac = "." decimal+
integer = "0" / ([1-9] decimal*)
decimal = [0-9]
string "string" = '"' chars:char* escaped_new_line '"' wss { return chars.join(""); }
char = escaped_new_line @([^\0-\x1F"\\] / "\\" @(
"b" { return "\b"; } /
"f" { return "\f"; } /
"n" { return "\n"; } /
"r" { return "\r"; } /
"t" { return "\t"; } /
"u" digits:$(hexadecimal hexadecimal hexadecimal hexadecimal) { return String.fromCharCode(parseInt(digits, 16)); } /
[^\0-\x1F]
))
escaped_new_line = ("\\\r\n" / "\\\r" / "\\\n")*
hexadecimal = digit:.
{
if(digit.match(/[0-9a-f]/i)) return digit;
throw peg$buildSimpleError("Invalid Unicode escape sequence.", location());
}
constructor = "new" ws wss @(date / error / int8array / map / regexp / set / uint8array / uint8clampedarray / url)
date = "Date" wss open_round time:(value:(number / string) { return { location: location(), value }; }) closed_round
{
const { value } = time as { value: number | string };
if(typeof value === "number" && isNaN(value)) return new Date(NaN);
const date = new Date(value);
if(isNaN(date.getTime())) throw peg$buildSimpleError("Invalid date.", time.location);
return date;
}
regexp =
"RegExp" wss open_round
exp:(value:string { return { location: location(), value }; })
flags:(comma @(value:string { return { location: location(), value }; }))?
closed_round
{
try {
return flags ? new RegExp(exp.value, flags.value) : new RegExp(exp.value);
} catch(e: any) {
const { message } = e;
throw peg$buildSimpleError(message + ".", message.match("Invalid flags") ? flags.location : exp.location);
}
}
url = "URL" wss open_round url:(value:string { return { location: location(), value }; }) closed_round
{
try {
return new URL(url.value);
} catch(e: any) {
const { message } = e;
throw peg$buildSimpleError(message + ".", url.location);
}
}
set = "Set" wss open_round elements:array? closed_round { return new Set(elements || []); }
map = "Map" wss open_round elements:array_map_entry? closed_round { return new Map(elements || []); }
map_entry = open_square key:value comma value:value closed_square { return [key, value]; }
array_map_entry = open_square values:(head:map_entry tail:(comma @map_entry)* { return [head, ...tail]; })? closed_square { return values || []; }
int8array = "Int8Array" wss open_round elements:array_small_number? closed_round { return elements ? new Int8Array(elements) : new Int8Array(); }
uint8array = "Uint8Array" wss open_round elements:array_small_number? closed_round { return elements ? new Uint8Array(elements) : new Uint8Array(); }
uint8clampedarray = "Uint8ClampedArray" wss open_round elements:array_small_number? closed_round { return elements ? new Uint8ClampedArray(elements) : new Uint8ClampedArray(); }
array_small_number = open_square values:(head:small_number tail:(comma @small_number)* { return [head, ...tail]; })? closed_square { return values || []; }
small_number = value:number
{
if(typeof value === "bigint") throw peg$buildSimpleError("BigInt is not allowed for TypedArray.", location());
return value;
}
object_assign = "Object" wss dot "assign" wss open_round dest:value comma source:value closed_round
{
if(Object.assign(dest, source) instanceof Error && (source.message || source.name) && ! source.stack) {
dest.stack = `${dest.name}: ${dest.message}\n from NJSON`;
}
return dest;
}
error =
err:("Error" / "EvalError" / "RangeError" / "ReferenceError" / "SyntaxError" / "TypeError" / "URIError") wss
open_round message:value closed_round
{
const constructor = errors[err as Errors];
const props = { configurable: true, value: undefined, writable: true };
const val = new constructor(message);
return Object.defineProperties(val, { "cause": props, "stack": {...props,value:`${err}: ${message}\n from NJSON`} });
}
function = open_round parameters "=>" wss body closed_round arguments
{
Object.assign(options!, { body: true, running: true, startRule: "statement" });
for(const statement of options!.statements) {
options!.offset = statement[1];
const ret = peg$parse(statement[0], options);
if(ret instanceof Array) return ret[0];
}
}
identifier = identifier:($[A-Z]+) ! [a-z] wss
{
const { offset, running, vars } = options!;
if(running && ! (identifier in vars)) throw peg$buildSimpleError(`Undeclared variable ${identifier}.`, addLocations(offset, location()));
return identifier;
}
parameters = open_round params:(head:identifier tail:(comma @identifier)* { return [head, ...tail]; }) closed_round
{
const vars: any = {};
Object.assign(options!, { body: true, params, types: {}, vars });
for(const param of params as string[]) vars[param] = undefined;
return null;
}
body = open_brace statements:(head:statement tail:(semicolon @statement)* { return [head, ...tail]; }) closed_brace { Object.assign(options!, { body: false, statements }); }
statement = chain / return
method =
dot
@(
( method:("add" { return { location: location(), name: "add" }; }) wss open_round value:value { return { ...method, value }; } ) /
( method:("push" { return { location: location(), name: "push" }; }) wss open_round args:(head:value tail:(comma @value)* comma? { return [head, ...tail]; }) { return { ...method, args }; } ) /
( method:("set" { return { location: location(), name: "set" }; }) wss open_round key:value comma value:value { return { ...method, key, value }; } )
)
closed_round
chain = identifier:identifier methods:(@method)*
{
const { body, offset, running, types, vars } = options!;
let first = true;
if(! body) throw peg$buildSimpleError("Unexpected identifier in this context.", location());
if(! running) return [text(), location()];
for(const method of methods) {
const { args, key, location, name, value } = method;
const type = types[identifier];
if(name === "add") {
if(type !== "Set") throw peg$buildSimpleError(`Can't call method "add" on ${first ? type : "Number"}.`, addLocations(offset, location));
vars[identifier].add(value);
} else if(name === "set") {
if(type !== "Map") throw peg$buildSimpleError(`Can't call method "set" on ${first ? type : "Number"}.`, addLocations(offset, location));
vars[identifier].set(key, value);
} else {
if(type !== "Array" || ! first) throw peg$buildSimpleError(`Can't call method "push" on ${first ? type : "Number"}.`, addLocations(offset, location));
first = false;
vars[identifier].push(...args);
}
}
return first ? vars[identifier] : vars[identifier].length;
}
return = "return" ws wss value:value { return options!.running ? [value] : [text(), location()]; }
arguments = open_round args:(head:value tail:(comma @value)* { return [head, ...tail]; }) closed_round
{
const { params, types, vars } = options!;
if(params.length !== args.length) throw peg$buildSimpleError(`Expected ${params.length} arguments but ${args.length} found.`, location());
for(let i = 0; i < args.length; ++i) {
types[params[i]] = args[i].constructor.name;
vars[params[i]] = args[i];
}
}