/
grammar.pegjs
435 lines (332 loc) · 14.3 KB
/
grammar.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
/////////////////
// Abstraction //
/////////////////
{
// Static functions
options.functions = Object.assign(options.functions || {}, Object.getOwnPropertyNames(Math).filter(n => typeof Math[n] === "function").reduce((a, op) => { a[`Math_${op}`] = Math[op]; return a; }, {}));
options.functions = Object.assign(options.functions || {}, Object.getOwnPropertyNames(Number).filter(n => typeof Number[n] === "function").reduce((a, op) => { a[`Number_${op}`] = Number[op]; return a; }, {}));
options.functions = Object.assign(options.functions || {}, Object.getOwnPropertyNames(String).filter(n => typeof String[n] === "function").reduce((a, op) => { a[`String_${op}`] = String[op]; return a; }, {}));
options.functions = Object.assign(options.functions || {}, Object.getOwnPropertyNames(Boolean).filter(n => typeof Boolean[n] === "function").reduce((a, op) => { a[`Boolean_${op}`] = Boolean[op]; return a; }, {}));
// Prototype functions
options.functions = Object.assign(options.functions || {}, Object.getOwnPropertyNames(Number.prototype).filter(n => n !== "constructor" && typeof Number.prototype[n] === "function").reduce((a, op) => { a[`number_${op}`] = (nb, ...args) => { return Number.prototype[op].call(nb, ...args); }; return a; }, {}));
options.functions = Object.assign(options.functions || {}, Object.getOwnPropertyNames(String.prototype).filter(n => n !== "constructor" && typeof String.prototype[n] === "function").reduce((a, op) => { a[`string_${op}`] = (str, ...args) => { return String.prototype[op].call(str, ...args); }; return a; }, {}));
options.functions = Object.assign(options.functions || {}, Object.getOwnPropertyNames(Boolean.prototype).filter(n => n !== "constructor" && typeof Boolean.prototype[n] === "function").reduce((a, op) => { a[`boolean_${op}`] = (bool, ...args) => { return Boolean.prototype[op].call(bool, ...args); }; return a; }, {}));
// Javascript identifiers
options.identifiers = Object.assign(options.identifiers || {}, Object.getOwnPropertyNames(Math).filter(n => typeof Math[n] !== "function").reduce((a, op) => { a["Math_" + op] = Math[op]; return a; }, {}));
options.identifiers = Object.assign(options.identifiers || {}, Object.getOwnPropertyNames(Number).filter(n => typeof Number[n] !== "function").reduce((a, op) => { a["Number_" + op] = Number[op]; return a; }, {}));
options.identifiers = Object.assign(options.identifiers || {}, Object.getOwnPropertyNames(String).filter(n => typeof String[n] !== "function").reduce((a, op) => { a["String_" + op] = String[op]; return a; }, {}));
options.identifiers = Object.assign(options.identifiers || {}, Object.getOwnPropertyNames(Boolean).filter(n => typeof Boolean[n] !== "function").reduce((a, op) => { a["Boolean_" + op] = Boolean[op]; return a; }, {}));
// User generated identifiers order
options.identifiers_order = [];
const unary_operation = (head, tail) => {
return {type: 'unary', head: head.map(operator => ({operator})), tail};
};
const binary_operation = (head, tail) => {
return {type: 'binary', head, tail: tail.map(t => ({operand: t[3], operator: t[1]}))};
};
const comparison_operators = {
"=": "eq", "<": "lt", ">": "gt",
"!=": "neq", "<=": "lte", ">=": "gte",
};
}
///////////////
// PostgREST //
///////////////
Postgrest
= p:PostgrestLogical { return `${p.name}=(${p.args})`; }
/ p:PostgrestFunction { return `${p.column}=${p.name}.${p.value}`; }
/ p:PostgrestComparison { return `${p.column}=${p.name}.${p.value}`; }
PostgrestNot
= "NOT"i "(" p:(PostgrestLogical) ")" { return `not.${p.name}(${p.args})`; }
/ "NOT"i "(" p:(PostgrestFunction / PostgrestComparison) ")" { return `${p.column}.not.${p.name}.${p.value}`; }
PostgrestLogical
= name:("OR"i / "AND"i) "(" __ args:PostgrestLogicalItem __ ")" { return {name: name.toLowerCase(), args}; }
PostgrestLogicalArg
= PostgrestNot
/ p:PostgrestLogical { return `${p.name}(${p.args})`; }
/ p:PostgrestFunction { return `${p.column}.${p.name}.${p.value}`; }
/ p:PostgrestComparison { return `${p.column}.${p.name}.${p.value}`; }
PostgrestLogicalItem
= head:PostgrestLogicalArg __ "," __ tail:PostgrestLogicalItem { return [head, ...tail]; }
/ p:PostgrestLogicalArg { return [p]; }
PostgrestFunction
= name:("LIKE"i / "ILIKE"i / "FTS"i / "WFTS"i / "PLFTS"i) "(" __ column:PostgrestColumnName __ "," __ value:StringLiteral __ ")" { return {name: name.toLowerCase(), value: encodeURI(value), column}; }
PostgrestComparison
= column:PostgrestColumnName __ name:("!=" / "<=" / ">=" / "<" / ">" / "=") __ value:Literal { return {column, name: comparison_operators[name], value: value.value}; }
PostgrestColumnName "column"
= name:PostgrestColumnIdentifierName { return encodeURI(name); }
PostgrestColumnIdentifierName
= [_a-zA-Z]+ [_a-zA-Z0-9]* { return text(); }
/////////////////
// Type system //
/////////////////
UnionType "union type"
= types:(__ SingleType __ "|" __)* __ type:SingleType { return {type: 'union_type', types: [...types.map(t => t[1]), type]}; }
SingleType "single type"
= name:IdentifierName template:SingleTypeTemplate? config:ObjectLiteral? { return ({type: 'single_type', name, config, fullname: text(), template}); }
SingleTypeTemplate "single type template"
= "<" __ types:(__ UnionType __ "," __)* __ type:UnionType __ ">" { return {type: 'single_type_template', types: [...types.map(t => t[1]), type]}; }
////////////////
// Expression //
////////////////
Expression
= expression:ConditionalExpression
EndExpression
= "(" __ expression:ConditionalExpression __ ")" { return expression; }
/ Literal
/ Function
/ Identifier
TrimmedExpression
= __ expression:EndExpression __ { return expression; }
PropertyAccessorKey
= "." __ key:IdentifierName { return key; }
/ "[" __ key:TrimmedExpression __ "]" { return key; }
PropertyAccessorExpression
= property:TrimmedExpression keys:PropertyAccessorKey+ { return {type: 'accessor', keys, property}; }
/ TrimmedExpression
UnaryExpression
= PropertyAccessorExpression
/ head:(__ UnaryOperator)* __ tail:PropertyAccessorExpression { return unary_operation(head.map(h => h[1]), tail); }
UnaryOperator
= $("+" !"+")
/ $("-" !"-")
/ $"~"
/ $"!"
/ $"NOT"
ExponentiationExpression
= head:UnaryExpression tail:(__ ExponentiationOperator __ UnaryExpression)* { return binary_operation(head, tail); }
ExponentiationOperator
= "**"
MultiplicativeExpression
= head:ExponentiationExpression tail:(__ MultiplicativeOperator __ ExponentiationExpression)* { return binary_operation(head, tail); }
MultiplicativeOperator
= $("*" !"*")
/ $("/")
/ $("%")
AdditiveExpression
= head:MultiplicativeExpression tail:(__ AdditiveOperator __ MultiplicativeExpression)* { return binary_operation(head, tail); }
AdditiveOperator
= $("+" ![+=])
/ $("-" ![-=])
EqualityExpression
= head:RelationalExpression tail:(__ EqualityOperator __ RelationalExpression)* { return binary_operation(head, tail); }
EqualityOperator
= "==="
/ "!=="
/ "=="
/ "!="
BitwiseShiftExpression
= head:AdditiveExpression tail:(__ BitwiseShiftOperator __ AdditiveExpression)* { return binary_operation(head, tail); }
BitwiseShiftOperator
= $("<<" )
/ $(">>>")
/ $(">>" )
RelationalExpression
= head:BitwiseShiftExpression tail:(__ RelationalOperator __ BitwiseShiftExpression)* { return binary_operation(head, tail); }
RelationalOperator
= "<="
/ ">="
/ $("<" !"<")
/ $(">" !">")
BitwiseAndExpression
= head:EqualityExpression tail:(__ BitwiseAndOperator __ EqualityExpression)* { return binary_operation(head, tail); }
BitwiseAndOperator
= "&"
BitwiseXorExpression
= head:BitwiseAndExpression tail:(__ BitwiseXorOperator __ BitwiseAndExpression)* { return binary_operation(head, tail); }
BitwiseXorOperator
= "^"
BitwiseOrExpression
= head:BitwiseXorExpression tail:(__ BitwiseOrOperator __ BitwiseXorExpression)* { return binary_operation(head, tail); }
BitwiseOrOperator
= "|"
LogicalAndExpression
= head:BitwiseOrExpression tail:(__ LogicalAndOperator __ BitwiseOrExpression)* { return binary_operation(head, tail); }
LogicalAndOperator
= "&&" / "AND"
LogicalOrExpression
= head:LogicalAndExpression tail:(__ LogicalOrOperator __ LogicalAndExpression)* { return binary_operation(head, tail); }
LogicalOrOperator
= "||" / "OR"
ConditionalExpression
= value:LogicalOrExpression __ "?" __ true_path:ConditionalExpression __ ":" __ false_path:ConditionalExpression { return {type: 'conditional', value, true_path, false_path}; }
/ value:LogicalOrExpression __ "?:" __ false_path:ConditionalExpression { return {type: 'conditional', value, true_path: value, false_path}; }
/ LogicalOrExpression
//////////////////////////
// Expression Functions //
//////////////////////////
Function
= name:IdentifierName __ "(" __ args:FunctionArguments? __ ")" { return {type: 'function_call', name, args: args || []}; }
FunctionArguments
= expression:Expression expressions:(__ "," __ Expression __ )* { return [expression, ...expressions.map(e => e[3])]; }
////////////////////////////
// Expression Identifiers //
////////////////////////////
Identifier
= name:IdentifierName {
if (!(name in options.identifiers) && !options.identifiers_order.includes(name)) {
options.identifiers_order.push(name);
}
return {type: 'identifier', name};
}
IdentifierName
= !IdentifierReserved IdentifierStart+ IdentifierPart* { return text(); }
IdentifierStart
= UnicodeLatinLetter
/ "_"
/ "$"
IdentifierPart
= IdentifierStart
/ [0-9]
IdentifierReserved
= NullLiteral
/ BooleanLiteral
/ "AND"
/ "OR"
/ "NOT"
/////////////////////////
// Expression Literals //
/////////////////////////
Literal
= ArrayLiteral
/ ObjectLiteral
/ value:NullLiteral { return {type: 'literal', value}; }
/ value:NumberLiteral { return {type: 'literal', value}; }
/ value:StringLiteral { return {type: 'literal', value}; }
/ value:BooleanLiteral { return {type: 'literal', value}; }
ArrayLiteral "array"
= '[' __ items:ArrayLiteralItem? __ ']' { return {type: 'array_literal', value: items || [] }; }
ArrayLiteralItem
= head:Expression __ ',' __ tail:ArrayLiteralItem { return [head, ...tail]; }
/ value:Expression { return [value]; }
ObjectLiteral "object"
= "{" __ entries:(ObjectKeyValue ","? __)* "}" { return {type: 'object_literal', value: entries.reduce((a, op) => Object.assign(a, op[0]), {})}; }
ObjectKey
= IdentifierName / NullLiteral / StringLiteral / BooleanLiteral
ObjectKeyValue
= __ key:ObjectKey __ ":" __ value:Expression __ { return {[key]: value} }
NullLiteral "null"
= NullLiteralToken { return null; }
NullLiteralToken
= "null"i !IdentifierPart
NumberLiteral "number"
= HexaLiteral
/ BinaryLiteral
/ DecimalLiteral
HexaLiteral
= "0x"i digits:$HexaDigit+ { return parseInt(digits, 16); }
HexaDigit
= [0-9a-f]i
BinaryLiteral
= "0b"i digits:$BinaryDigit+ { return parseInt(digits, 2); }
BinaryDigit
= [01]
DecimalLiteral
= DecimalSeparator DecimalDigit+ DecimalLiteralExponentialPart? { return parseFloat(text(), 10); }
/ DecimalDigit+ DecimalSeparator DecimalDigit* DecimalLiteralExponentialPart? { return parseFloat(text(), 10); }
/ DecimalDigit+ DecimalLiteralExponentialPart? { return parseFloat(text(), 10); }
DecimalDigit
= [0-9]
DecimalSeparator
= [.]
DecimalLiteralExponentialPart
= ExponentialLiteralToken DecimalDigit+
ExponentialLiteralToken
= "e"i
StringLiteral "string"
= '"' chars:DoubleStringCharacter* '"' { return chars.join(""); }
/ "'" chars:SingleStringCharacter* "'" { return chars.join(""); }
/ "`" chars:BackStringCharacter* "`" { return chars.join(""); }
DoubleStringCharacter
= !('"' / "\\") Character { return text(); }
/ "\\" sequence:EscapeSequence { return sequence; }
/ LineContinuation
SingleStringCharacter
= !("'" / "\\") Character { return text(); }
/ "\\" sequence:EscapeSequence { return sequence; }
/ LineContinuation
BackStringCharacter
= !("`" / "\\") Character { return text(); }
/ "\\" sequence:EscapeSequence { return sequence; }
/ LineContinuation
LineContinuation
= "\\" UnicodeLineTerminatorSequence { return ""; }
EscapeSequence
= CharacterEscapeSequence
/ "0" !DecimalDigit { return "\0"; }
/ HexEscapeSequence
/ UnicodeEscapeSequence
CharacterEscapeSequence
= SingleEscapeCharacter
/ NonEscapeCharacter
SingleEscapeCharacter
= "'"
/ '"'
/ "`"
/ "\\"
/ "b" { return "\b"; }
/ "f" { return "\f"; }
/ "n" { return "\n"; }
/ "r" { return "\r"; }
/ "t" { return "\t"; }
/ "v" { return "\v"; }
NonEscapeCharacter
= !(EscapeCharacter / UnicodeLineTerminator) Character { return text(); }
EscapeCharacter
= SingleEscapeCharacter
/ DecimalDigit
/ "x"
/ "u"
HexEscapeSequence
= "x" digits:$(HexaDigit HexaDigit) { return String.fromCharCode(parseInt(digits, 16)); }
UnicodeEscapeSequence
= "u" digits:$(HexaDigit HexaDigit HexaDigit HexaDigit) { return String.fromCharCode(parseInt(digits, 16)); }
Character
= .
BooleanLiteral "boolean"
= TrueLiteralToken { return true; }
/ FalseLiteralToken { return false; }
TrueLiteralToken
= "true"i !IdentifierPart
FalseLiteralToken
= "false"i !IdentifierPart
//////////////////////////////////////////////
// Unicode whitespaces and line terminators //
//////////////////////////////////////////////
__
= UnicodeWhitespace*
UnicodeWhitespace
= "\t"
/ "\v"
/ "\f"
/ " "
/ "\u00A0"
/ "\uFEFF"
/ [\u0020\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]
UnicodeLineTerminator
= [\n\r\u2028\u2029]
UnicodeLineTerminatorSequence
= "\n"
/ "\r\n"
/ "\r"
/ "\u2028"
/ "\u2029"
/////////////////////
// Unicode letters //
/////////////////////
UnicodeLatinLetter
= UnicodeLatinBasicLetter
/ UnicodeLatinSupplementLetter
/ UnicodeLatinExtendedALetter
/ UnicodeLatinExtendedBLetter
/ UnicodeLatinExtendedAdditionalLetter
UnicodeLatinBasicLetter
= [\u0041-\u005a\u0061-\u007a]
UnicodeLatinSupplementLetter
= [\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u00ff]
UnicodeLatinExtendedALetter
= [\u0100-\u017f]
UnicodeLatinExtendedBLetter
= [\u0180-\u024f]
UnicodeLatinExtendedAdditionalLetter
= [\u1e00-\u1eff]