forked from jsonata-js/jsonata
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonata.js
4319 lines (4007 loc) · 154 KB
/
jsonata.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
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* © Copyright IBM Corp. 2016, 2017 All Rights Reserved
* Project name: JSONata
* This project is licensed under the MIT License, see LICENSE
*/
/**
* @module JSONata
* @description JSON query and transformation language
*/
/**
* jsonata
* @function
* @param {Object} expr - JSONata expression
* @returns {{evaluate: evaluate, assign: assign}} Evaluated expression
*/
var jsonata = (function() {
'use strict';
var operators = {
'.': 75,
'[': 80,
']': 0,
'{': 70,
'}': 0,
'(': 80,
')': 0,
',': 0,
'@': 75,
'#': 70,
';': 80,
':': 80,
'?': 20,
'+': 50,
'-': 50,
'*': 60,
'/': 60,
'%': 60,
'|': 20,
'=': 40,
'<': 40,
'>': 40,
'^': 40,
'**': 60,
'..': 20,
':=': 10,
'!=': 40,
'<=': 40,
'>=': 40,
'~>': 40,
'and': 30,
'or': 25,
'in': 40,
'&': 50,
'!': 0, // not an operator, but needed as a stop character for name tokens
'~': 0 // not an operator, but needed as a stop character for name tokens
};
var escapes = { // JSON string escape sequences - see json.org
'"': '"',
'\\': '\\',
'/': '/',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t'
};
// Tokenizer (lexer) - invoked by the parser to return one token at a time
var tokenizer = function (path) {
var position = 0;
var length = path.length;
var create = function (type, value) {
var obj = {type: type, value: value, position: position};
return obj;
};
var scanRegex = function() {
// the prefix '/' will have been previously scanned. Find the end of the regex.
// search for closing '/' ignoring any that are escaped, or within brackets
var start = position;
var depth = 0;
var pattern;
var flags;
while(position < length) {
var currentChar = path.charAt(position);
if(currentChar === '/' && path.charAt(position - 1) !== '\\' && depth === 0) {
// end of regex found
pattern = path.substring(start, position);
if(pattern === '') {
throw {
code: "S0301",
stack: (new Error()).stack,
position: position
};
}
position++;
currentChar = path.charAt(position);
// flags
start = position;
while(currentChar === 'i' || currentChar === 'm') {
position++;
currentChar = path.charAt(position);
}
flags = path.substring(start, position) + 'g';
return new RegExp(pattern, flags);
}
if((currentChar === '(' || currentChar === '[' || currentChar === '{') && path.charAt(position - 1) !== '\\' ) {
depth++;
}
if((currentChar === ')' || currentChar === ']' || currentChar === '}') && path.charAt(position - 1) !== '\\' ) {
depth--;
}
position++;
}
throw {
code: "S0302",
stack: (new Error()).stack,
position: position
};
};
var next = function (prefix) {
if (position >= length) return null;
var currentChar = path.charAt(position);
// skip whitespace
while (position < length && ' \t\n\r\v'.indexOf(currentChar) > -1) {
position++;
currentChar = path.charAt(position);
}
// test for regex
if (prefix !== true && currentChar === '/') {
position++;
return create('regex', scanRegex());
}
// handle double-char operators
if (currentChar === '.' && path.charAt(position + 1) === '.') {
// double-dot .. range operator
position += 2;
return create('operator', '..');
}
if (currentChar === ':' && path.charAt(position + 1) === '=') {
// := assignment
position += 2;
return create('operator', ':=');
}
if (currentChar === '!' && path.charAt(position + 1) === '=') {
// !=
position += 2;
return create('operator', '!=');
}
if (currentChar === '>' && path.charAt(position + 1) === '=') {
// >=
position += 2;
return create('operator', '>=');
}
if (currentChar === '<' && path.charAt(position + 1) === '=') {
// <=
position += 2;
return create('operator', '<=');
}
if (currentChar === '*' && path.charAt(position + 1) === '*') {
// ** descendant wildcard
position += 2;
return create('operator', '**');
}
if (currentChar === '~' && path.charAt(position + 1) === '>') {
// ~> chain function
position += 2;
return create('operator', '~>');
}
// test for single char operators
if (operators.hasOwnProperty(currentChar)) {
position++;
return create('operator', currentChar);
}
// test for string literals
if (currentChar === '"' || currentChar === "'") {
var quoteType = currentChar;
// double quoted string literal - find end of string
position++;
var qstr = "";
while (position < length) {
currentChar = path.charAt(position);
if (currentChar === '\\') { // escape sequence
position++;
currentChar = path.charAt(position);
if (escapes.hasOwnProperty(currentChar)) {
qstr += escapes[currentChar];
} else if (currentChar === 'u') {
// \u should be followed by 4 hex digits
var octets = path.substr(position + 1, 4);
if (/^[0-9a-fA-F]+$/.test(octets)) {
var codepoint = parseInt(octets, 16);
qstr += String.fromCharCode(codepoint);
position += 4;
} else {
throw {
code: "S0104",
stack: (new Error()).stack,
position: position
};
}
} else {
// illegal escape sequence
throw {
code: "S0103",
stack: (new Error()).stack,
position: position,
token: currentChar
};
}
} else if (currentChar === quoteType) {
position++;
return create('string', qstr);
} else {
qstr += currentChar;
}
position++;
}
throw {
code: "S0101",
stack: (new Error()).stack,
position: position
};
}
// test for numbers
var numregex = /^-?(0|([1-9][0-9]*))(\.[0-9]+)?([Ee][-+]?[0-9]+)?/;
var match = numregex.exec(path.substring(position));
if (match !== null) {
var num = parseFloat(match[0]);
if (!isNaN(num) && isFinite(num)) {
position += match[0].length;
return create('number', num);
} else {
throw {
code: "S0102",
stack: (new Error()).stack,
position: position,
token: match[0]
};
}
}
// test for quoted names (backticks)
var name;
if(currentChar === '`') {
// scan for closing quote
position++;
var end = path.indexOf('`', position);
if(end !== -1) {
name = path.substring(position, end);
position = end + 1;
return create('name', name);
}
position = length;
throw {
code: "S0105",
stack: (new Error()).stack,
position: position
};
}
// test for names
var i = position;
var ch;
for (;;) {
ch = path.charAt(i);
if (i === length || ' \t\n\r\v'.indexOf(ch) > -1 || operators.hasOwnProperty(ch)) {
if (path.charAt(position) === '$') {
// variable reference
name = path.substring(position + 1, i);
position = i;
return create('variable', name);
} else {
name = path.substring(position, i);
position = i;
switch (name) {
case 'or':
case 'in':
case 'and':
return create('operator', name);
case 'true':
return create('value', true);
case 'false':
return create('value', false);
case 'null':
return create('value', null);
default:
if (position === length && name === '') {
// whitespace at end of input
return null;
}
return create('name', name);
}
}
} else {
i++;
}
}
};
return next;
};
/**
* Parses a function signature definition and returns a validation function
* @param {string} signature - the signature between the <angle brackets>
* @returns {Function} validation function
*/
function parseSignature(signature) {
// create a Regex that represents this signature and return a function that when invoked,
// returns the validated (possibly fixed-up) arguments, or throws a validation error
// step through the signature, one symbol at a time
var position = 1;
var params = [];
var param = {};
var prevParam = param;
while (position < signature.length) {
var symbol = signature.charAt(position);
if(symbol === ':') {
// TODO figure out what to do with the return type
// ignore it for now
break;
}
var next = function() {
params.push(param);
prevParam = param;
param = {};
};
var findClosingBracket = function(str, start, openSymbol, closeSymbol) {
// returns the position of the closing symbol (e.g. bracket) in a string
// that balances the opening symbol at position start
var depth = 1;
var position = start;
while(position < str.length) {
position++;
symbol = str.charAt(position);
if(symbol === closeSymbol) {
depth--;
if(depth === 0) {
// we're done
break; // out of while loop
}
} else if(symbol === openSymbol) {
depth++;
}
}
return position;
};
switch (symbol) {
case 's': // string
case 'n': // number
case 'b': // boolean
case 'l': // not so sure about expecting null?
case 'o': // object
param.regex = '[' + symbol + 'm]';
param.type = symbol;
next();
break;
case 'a': // array
// normally treat any value as singleton array
param.regex = '[asnblfom]';
param.type = symbol;
param.array = true;
next();
break;
case 'f': // function
param.regex = 'f';
param.type = symbol;
next();
break;
case 'j': // any JSON type
param.regex = '[asnblom]';
param.type = symbol;
next();
break;
case 'x': // any type
param.regex = '[asnblfom]';
param.type = symbol;
next();
break;
case '-': // use context if param not supplied
prevParam.context = true;
prevParam.contextRegex = new RegExp(prevParam.regex); // pre-compiled to test the context type at runtime
prevParam.regex += '?';
break;
case '?': // optional param
case '+': // one or more
prevParam.regex += symbol;
break;
case '(': // choice of types
// search forward for matching ')'
var endParen = findClosingBracket(signature, position, '(', ')');
var choice = signature.substring(position + 1, endParen);
if(choice.indexOf('<') === -1) {
// no parameterized types, simple regex
param.regex = '[' + choice + 'm]';
} else {
// TODO harder
throw {
code: "S0402",
stack: (new Error()).stack,
value: choice,
offset: position
};
}
param.type = '(' + choice + ')';
position = endParen;
next();
break;
case '<': // type parameter - can only be applied to 'a' and 'f'
if(prevParam.type === 'a' || prevParam.type === 'f') {
// search forward for matching '>'
var endPos = findClosingBracket(signature, position, '<', '>');
prevParam.subtype = signature.substring(position + 1, endPos);
position = endPos;
} else {
throw {
code: "S0401",
stack: (new Error()).stack,
value: prevParam.type,
offset: position
};
}
break;
}
position++;
}
var regexStr = '^' +
params.map(function(param) {
return '(' + param.regex + ')';
}).join('') +
'$';
var regex = new RegExp(regexStr);
var getSymbol = function(value) {
var symbol;
if(isFunction(value)) {
symbol = 'f';
} else {
var type = typeof value;
switch (type) {
case 'string':
symbol = 's';
break;
case 'number':
symbol = 'n';
break;
case 'boolean':
symbol = 'b';
break;
case 'object':
if (value === null) {
symbol = 'l';
} else if (Array.isArray(value)) {
symbol = 'a';
} else {
symbol = 'o';
}
break;
case 'undefined':
// any value can be undefined, but should be allowed to match
symbol = 'm'; // m for missing
}
}
return symbol;
};
var throwValidationError = function(badArgs, badSig) {
// to figure out where this went wrong we need apply each component of the
// regex to each argument until we get to the one that fails to match
var partialPattern = '^';
var goodTo = 0;
for(var index = 0; index < params.length; index++) {
partialPattern += params[index].regex;
var match = badSig.match(partialPattern);
if(match === null) {
// failed here
throw {
code: "T0410",
stack: (new Error()).stack,
value: badArgs[goodTo],
index: goodTo + 1
};
}
goodTo = match[0].length;
}
// if it got this far, it's probably because of extraneous arguments (we
// haven't added the trailing '$' in the regex yet.
throw {
code: "T0410",
stack: (new Error()).stack,
value: badArgs[goodTo],
index: goodTo + 1
};
};
return {
definition: signature,
validate: function(args, context) {
var suppliedSig = '';
args.forEach(function(arg) {
suppliedSig += getSymbol(arg);
});
var isValid = regex.exec(suppliedSig);
if(isValid) {
var validatedArgs = [];
var argIndex = 0;
params.forEach(function(param, index) {
var arg = args[argIndex];
var match = isValid[index + 1];
if(match === '') {
if (param.context) {
// substitute context value for missing arg
// first check that the context value is the right type
var contextType = getSymbol(context);
// test contextType against the regex for this arg (without the trailing ?)
if(param.contextRegex.test(contextType)) {
validatedArgs.push(context);
} else {
// context value not compatible with this argument
throw {
code: "T0411",
stack: (new Error()).stack,
value: context,
index: argIndex + 1
};
}
} else {
validatedArgs.push(arg);
argIndex++;
}
} else {
// may have matched multiple args (if the regex ends with a '+'
// split into single tokens
match.split('').forEach(function(single) {
if (param.type === 'a') {
if (single === 'm') {
// missing (undefined)
arg = undefined;
} else {
arg = args[argIndex];
var arrayOK = true;
// is there type information on the contents of the array?
if (typeof param.subtype !== 'undefined') {
if (single !== 'a' && match !== param.subtype) {
arrayOK = false;
} else if (single === 'a') {
if (arg.length > 0) {
var itemType = getSymbol(arg[0]);
if (itemType !== param.subtype.charAt(0)) { // TODO recurse further
arrayOK = false;
} else {
// make sure every item in the array is this type
var differentItems = arg.filter(function (val) {
return (getSymbol(val) !== itemType);
});
arrayOK = (differentItems.length === 0);
}
}
}
}
if (!arrayOK) {
throw {
code: "T0412",
stack: (new Error()).stack,
value: arg,
index: argIndex + 1,
type: param.subtype // TODO translate symbol to type name
};
}
// the function expects an array. If it's not one, make it so
if (single !== 'a') {
arg = [arg];
}
}
validatedArgs.push(arg);
argIndex++;
} else {
validatedArgs.push(arg);
argIndex++;
}
});
}
});
return validatedArgs;
}
throwValidationError(args, suppliedSig);
}
};
}
// This parser implements the 'Top down operator precedence' algorithm developed by Vaughan R Pratt; http://dl.acm.org/citation.cfm?id=512931.
// and builds on the Javascript framework described by Douglas Crockford at http://javascript.crockford.com/tdop/tdop.html
// and in 'Beautiful Code', edited by Andy Oram and Greg Wilson, Copyright 2007 O'Reilly Media, Inc. 798-0-596-51004-6
var parser = function (source, recover) {
var node;
var lexer;
var symbol_table = {};
var errors = [];
var remainingTokens = function() {
var remaining = [];
if(node.id !== '(end)') {
remaining.push({type: node.type, value: node.value, position: node.position});
}
var nxt = lexer();
while(nxt !== null) {
remaining.push(nxt);
nxt = lexer();
}
return remaining;
};
var base_symbol = {
nud: function () {
// error - symbol has been invoked as a unary operator
var err = {
code: 'S0211',
token: this.value,
position: this.position
};
if(recover) {
err.remaining = remainingTokens();
err.type = 'error';
errors.push(err);
return err;
} else {
err.stack = (new Error()).stack;
throw err;
}
}
};
var symbol = function (id, bp) {
var s = symbol_table[id];
bp = bp || 0;
if (s) {
if (bp >= s.lbp) {
s.lbp = bp;
}
} else {
s = Object.create(base_symbol);
s.id = s.value = id;
s.lbp = bp;
symbol_table[id] = s;
}
return s;
};
var handleError = function(err) {
if(recover) {
// tokenize the rest of the buffer and add it to an error token
err.remaining = remainingTokens();
errors.push(err);
var symbol = symbol_table["(error)"];
node = Object.create(symbol);
node.error = err;
node.type = "(error)";
return node;
} else {
err.stack = (new Error()).stack;
throw err;
}
};
var advance = function (id, infix) {
if (id && node.id !== id) {
var code;
if(node.id === '(end)') {
// unexpected end of buffer
code = "S0203";
} else {
code = "S0202";
}
var err = {
code: code,
position: node.position,
token: node.value,
value: id
};
return handleError(err);
}
var next_token = lexer(infix);
if (next_token === null) {
node = symbol_table["(end)"];
node.position = source.length;
return node;
}
var value = next_token.value;
var type = next_token.type;
var symbol;
switch (type) {
case 'name':
case 'variable':
symbol = symbol_table["(name)"];
break;
case 'operator':
symbol = symbol_table[value];
if (!symbol) {
return handleError( {
code: "S0204",
stack: (new Error()).stack,
position: next_token.position,
token: value
});
}
break;
case 'string':
case 'number':
case 'value':
type = "literal";
symbol = symbol_table["(literal)"];
break;
case 'regex':
type = "regex";
symbol = symbol_table["(regex)"];
break;
/* istanbul ignore next */
default:
return handleError( {
code: "S0205",
stack: (new Error()).stack,
position: next_token.position,
token: value
});
}
node = Object.create(symbol);
node.value = value;
node.type = type;
node.position = next_token.position;
return node;
};
// Pratt's algorithm
var expression = function (rbp) {
var left;
var t = node;
advance(null, true);
left = t.nud();
while (rbp < node.lbp) {
t = node;
advance();
left = t.led(left);
}
return left;
};
var terminal = function(id) {
var s = symbol(id, 0);
s.nud = function() {
return this;
};
};
// match infix operators
// <expression> <operator> <expression>
// left associative
var infix = function (id, bp, led) {
var bindingPower = bp || operators[id];
var s = symbol(id, bindingPower);
s.led = led || function (left) {
this.lhs = left;
this.rhs = expression(bindingPower);
this.type = "binary";
return this;
};
return s;
};
// match infix operators
// <expression> <operator> <expression>
// right associative
var infixr = function (id, bp, led) {
var bindingPower = bp || operators[id];
var s = symbol(id, bindingPower);
s.led = led || function (left) {
this.lhs = left;
this.rhs = expression(bindingPower - 1); // subtract 1 from bindingPower for right associative operators
this.type = "binary";
return this;
};
return s;
};
// match prefix operators
// <operator> <expression>
var prefix = function (id, nud) {
var s = symbol(id);
s.nud = nud || function () {
this.expression = expression(70);
this.type = "unary";
return this;
};
return s;
};
terminal("(end)");
terminal("(name)");
terminal("(literal)");
terminal("(regex)");
symbol(":");
symbol(";");
symbol(",");
symbol(")");
symbol("]");
symbol("}");
symbol(".."); // range operator
infix("."); // field reference
infix("+"); // numeric addition
infix("-"); // numeric subtraction
infix("*"); // numeric multiplication
infix("/"); // numeric division
infix("%"); // numeric modulus
infix("="); // equality
infix("<"); // less than
infix(">"); // greater than
infix("!="); // not equal to
infix("<="); // less than or equal
infix(">="); // greater than or equal
infix("&"); // string concatenation
infix("and"); // Boolean AND
infix("or"); // Boolean OR
infix("in"); // is member of array
terminal("and"); // the 'keywords' can also be used as terminals (field names)
terminal("or"); //
terminal("in"); //
infixr(":="); // bind variable
prefix("-"); // unary numeric negation
infix("~>"); // function application
infixr("(error)", 10, function(left) {
this.lhs = left;
this.error = node.error;
this.remaining = remainingTokens();
this.type = 'error';
return this;
});
// field wildcard (single level)
prefix('*', function () {
this.type = "wildcard";
return this;
});
// descendant wildcard (multi-level)
prefix('**', function () {
this.type = "descendant";
return this;
});
// function invocation
infix("(", operators['('], function (left) {
// left is is what we are trying to invoke
this.procedure = left;
this.type = 'function';
this.arguments = [];
if (node.id !== ')') {
for (;;) {
if (node.type === 'operator' && node.id === '?') {
// partial function application
this.type = 'partial';
this.arguments.push(node);
advance('?');
} else {
this.arguments.push(expression(0));
}
if (node.id !== ',') break;
advance(',');
}
}
advance(")", true);
// if the name of the function is 'function' or λ, then this is function definition (lambda function)
if (left.type === 'name' && (left.value === 'function' || left.value === '\u03BB')) {
// all of the args must be VARIABLE tokens
this.arguments.forEach(function (arg, index) {
if (arg.type !== 'variable') {
return handleError( {
code: "S0208",
stack: (new Error()).stack,
position: arg.position,
token: arg.value,
value: index + 1
});
}
});
this.type = 'lambda';
// is the next token a '<' - if so, parse the function signature
if(node.id === '<') {
var sigPos = node.position;
var depth = 1;
var sig = '<';
while(depth > 0 && node.id !== '{' && node.id !== '(end)') {
var tok = advance();
if(tok.id === '>') {
depth--;
} else if(tok.id === '<') {
depth++;
}
sig += tok.value;
}
advance('>');
try {
this.signature = parseSignature(sig);
} catch(err) {
// insert the position into this error
err.position = sigPos + err.offset;
return handleError( err );
}
}
// parse the function body
advance('{');
this.body = expression(0);
advance('}');
}
return this;
});
// parenthesis - block expression
prefix("(", function () {
var expressions = [];
while (node.id !== ")") {
expressions.push(expression(0));
if (node.id !== ";") {
break;
}
advance(";");
}
advance(")", true);
this.type = 'block';
this.expressions = expressions;
return this;
});
// array constructor
prefix("[", function () {
var a = [];
if (node.id !== "]") {
for (;;) {
var item = expression(0);
if (node.id === "..") {
// range operator
var range = {type: "binary", value: "..", position: node.position, lhs: item};
advance("..");
range.rhs = expression(0);
item = range;
}
a.push(item);
if (node.id !== ",") {
break;
}
advance(",");
}
}
advance("]", true);
this.expressions = a;
this.type = "unary";
return this;
});
// filter - predicate or array index
infix("[", operators['['], function (left) {
if(node.id === "]") {
// empty predicate means maintain singleton arrays in the output
var step = left;
while(step && step.type === 'binary' && step.value === '[') {
step = step.lhs;
}
step.keepArray = true;
advance("]");
return left;
} else {
this.lhs = left;
this.rhs = expression(operators[']']);
this.type = 'binary';
advance("]", true);
return this;
}
});
// order-by
infix("^", operators['^'], function (left) {
advance("(");
var terms = [];
for(;;) {
var term = {
descending: false
};
if (node.id === "<") {