forked from dashjoin/jsonata-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParser.java
More file actions
1463 lines (1339 loc) · 55.3 KB
/
Parser.java
File metadata and controls
1463 lines (1339 loc) · 55.3 KB
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
/**
* jsonata-java is the JSONata Java reference port
*
* Copyright Dashjoin GmbH. https://dashjoin.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Derived from Javascript code under this license:
/**
* © Copyright IBM Corp. 2016, 2018 All Rights Reserved
* Project name: JSONata
* This project is licensed under the MIT License, see LICENSE
*/
package com.dashjoin.jsonata;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import com.dashjoin.jsonata.Jsonata.Frame;
import com.dashjoin.jsonata.Tokenizer.Token;
import com.dashjoin.jsonata.utils.Signature;
//var parseSignature = require('./signature');
@SuppressWarnings({"unchecked"})
public class Parser {
boolean dbg = false;
// 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
String source;
boolean recover;
//var parser = function (source, recover) {
Symbol node;
Tokenizer lexer;
HashMap<String, Symbol> symbolTable = new HashMap<>();
List<Exception> errors = new ArrayList<>();
List<Token> remainingTokens() {
List<Token> remaining = new ArrayList<>();
if (!node.id.equals("(end)")) {
Token t = new Token();
t.type = node.type; t.value = node.value; t.position = node.position;
remaining.add(t);
}
Token nxt = lexer.next(false);
while (nxt != null) {
remaining.add(nxt);
nxt = lexer.next(false);
}
return remaining;
};
public static<T> T clone(T object) {
try {
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bOut);
out.writeObject(object);
out.close();
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bOut.toByteArray()));
T copy = (T)in.readObject();
in.close();
return copy;
}
catch(Exception e) {
throw new RuntimeException(e);
}
}
public class Symbol implements Cloneable {
//Symbol s;
String id;
String type;
Object value;
int bp;
int lbp;
int position;
boolean keepArray; // [
boolean descending; // ^
Symbol expression; // ^
public List<Symbol> seekingParent;
public List<Exception> errors;
List<Symbol> steps;
Symbol slot;
Symbol nextFunction;
public boolean keepSingletonArray;
public boolean consarray;
public int level;
public Object focus;
public Object token;
public boolean thunk;
// Procedure:
Symbol procedure;
List<Symbol> arguments;
Symbol body;
List<Symbol> predicate;
public List<Symbol> stages;
public Object input;
public Frame environment;
public Object tuple;
public Object expr;
public Symbol group;
public Object name;
// Infix attributes
Symbol lhs, rhs;
// where rhs = list of Symbol pairs
public List<Symbol[]> lhsObject, rhsObject;
// where rhs = list of Symbols
List<Symbol> rhsTerms;
List<Symbol> terms;
// Ternary operator:
Symbol condition, then, _else;
List<Symbol> expressions;
// processAST error handling
public JException error;
public Object signature;
// Prefix attributes
Symbol pattern, update, delete;
// Ancestor attributes
public String label;
public Object index;
public boolean _jsonata_lambda;
public Symbol ancestor;
Symbol nud() {
// error - symbol has been invoked as a unary operator
final JException _err = new JException("S0211", position, value);
if (recover) {
/*
err.remaining = remainingTokens();
err.type = "error";
errors.add(err);
return err;
*/
return new Symbol("(error)") {
//JException err = _err;
};
} else {
throw _err;
}
}
Symbol led(Symbol left) {
throw new Error("led not implemented");
}
//class Symbol {
Symbol() {}
Symbol(String id) { this(id, 0); }
Symbol(String id, int bp) {
this.id = id; this.value = id;
this.bp = bp;
/* use register(Symbol) ! Otherwise inheritance doesn't work
Symbol s = symbolTable.get(id);
//bp = bp != 0 ? bp : 0;
if (s != null) {
if (bp >= s.lbp) {
s.lbp = bp;
}
} else {
s = new Symbol();
s.value = s.id = id;
s.lbp = bp;
symbolTable.put(id, s);
}
*/
//return s;
}
public Symbol create() {
// We want a shallow clone (do not duplicate outer class!)
try {
Symbol cl = (Symbol) this.clone();
//System.err.println("cloning "+this+" clone="+cl);
return cl;
} catch (CloneNotSupportedException e) {
// never reached
if (dbg) e.printStackTrace();
return null;
}
}
@Override public String toString() {
return this.getClass().getSimpleName()+" "+id+" value="+value;
}
}
void register(Symbol t) {
//if (t instanceof Infix || t instanceof InfixR) return;
Symbol s = symbolTable.get(t.id);
if (s != null) {
if (dbg) System.out.println("Symbol in table "+t.id+" "+s.getClass().getName()+" -> "+ t.getClass().getName());
//symbolTable.put(t.id, t);
if (t.bp >= s.lbp) {
if (dbg) System.out.println("Symbol in table "+t.id+" lbp="+s.lbp+" -> "+t.bp);
s.lbp = t.bp;
}
} else {
s = (Symbol) t.create();
s.value = s.id = t.id;
s.lbp = t.bp;
symbolTable.put(t.id, s);
}
}
public Symbol handleError(JException err) {
if (recover) {
err.remaining = remainingTokens();
errors.add(err);
//Symbol symbol = symbolTable.get("(error)");
Symbol node = new Symbol();
// FIXME node.error = err;
//node.type = "(error)";
return node;
} else {
throw err;
}
}
//}
Symbol advance() { return advance(null); }
Symbol advance(String id) { return advance(id, false); }
Symbol advance(String id, boolean infix) {
if (id!=null && !node.id.equals(id)) {
String code;
if (node.id.equals("(end)")) {
// unexpected end of buffer
code = "S0203";
} else {
code = "S0202";
}
JException err = new JException(
code,
node.position,
id,
node.value
);
return handleError(err);
}
Token next_token = lexer.next(infix);
if (dbg) System.out.println("nextToken "+(next_token!=null ? next_token.type : null));
if (next_token == null) {
node = symbolTable.get("(end)");
node.position = source.length();
return node;
}
Object value = next_token.value;
String type = next_token.type;
Symbol symbol;
switch (type) {
case "name":
case "variable":
symbol = symbolTable.get("(name)");
break;
case "operator":
symbol = symbolTable.get(""+value);
if (symbol==null) {
return handleError(new JException(
"S0204", next_token.position, value));
}
break;
case "string":
case "number":
case "value":
symbol = symbolTable.get("(literal)");
break;
case "regex":
type = "regex";
symbol = symbolTable.get("(regex)");
break;
/* istanbul ignore next */
default:
return handleError(new JException(
"S0205", next_token.position, value));
}
node = symbol.create();
//Token node = new Token(); //Object.create(symbol);
node.value = value;
node.type = type;
node.position = next_token.position;
if (dbg) System.out.println("advance "+node);
return node;
}
// Pratt's algorithm
Symbol expression(int rbp) {
Symbol left;
Symbol t = node;
advance(null, true);
left = t.nud();
while (rbp < node.lbp) {
t = node;
advance(null, false);
if (dbg) System.out.println("t="+t+", left="+left.type);
left = t.led(left);
}
return left;
};
class Terminal extends Symbol {
Terminal(String id) {
super(id, 0);
}
@Override Symbol nud() {
return this;
}
}
/*
var terminal = function (id) {
var s = symbol(id, 0);
s.nud = function () {
return this;
};
};
*/
// match infix operators
// <expression> <operator> <expression>
// left associative
class Infix extends Symbol {
Infix(String id) { this(id,0); }
Infix(String id, int bp) {
super(id, bp!=0 ? bp : (id!=null ? Tokenizer.operators.get(id) : 0));
}
@Override
Symbol led(Symbol left) {
lhs = left; rhs = expression(bp);
type = "binary";
return this;
}
}
class InfixAndPrefix extends Infix {
Prefix prefix;
InfixAndPrefix(String id) { this(id,0); }
InfixAndPrefix(String id, int bp) {
super(id, bp);
prefix = new Prefix(id);
}
@Override Symbol nud() {
return prefix.nud();
// expression(70);
// type="unary";
// return this;
}
@Override public Object clone() throws CloneNotSupportedException {
Object c = super.clone();
// IMPORTANT: make sure to allocate a new Prefix!!!
((InfixAndPrefix)c).prefix = new Prefix(((InfixAndPrefix)c).id);
return c;
}
}
// match infix operators
// <expression> <operator> <expression>
// right associative
class InfixR extends Symbol {
InfixR(String id, int bp) {
super(id, bp);
}
//abstract Object led();
}
// match prefix operators
// <operator> <expression>
class Prefix extends Symbol {
//public List<Symbol[]> lhs;
Prefix(String id) {
super(id);
//type = "unary";
}
//Symbol _expression;
@Override
Symbol nud() {
expression = expression(70);
type = "unary";
return this;
}
}
public Parser() {
register(new Terminal("(end)"));
register(new Terminal("(name)"));
register(new Terminal("(literal)"));
register(new Terminal("(regex)"));
register(new Symbol(":"));
register(new Symbol(";"));
register(new Symbol(","));
register(new Symbol(")"));
register(new Symbol("]"));
register(new Symbol("}"));
register(new Symbol("..")); // range operator
register(new Infix(".")); // map operator
register(new Infix("+")); // numeric addition
register(new InfixAndPrefix("-")); // numeric subtraction
// unary numeric negation
register(new Infix("*") {
// field wildcard (single level)
@Override Symbol nud() {
type = "wildcard";
return this;
}
}); // numeric multiplication
register(new Infix("/")); // numeric division
register(new Infix("%") {
// parent operator
@Override Symbol nud() {
type = "parent";
return this;
}
}); // numeric modulus
register(new Infix("=")); // equality
register(new Infix("<")); // less than
register(new Infix(">")); // greater than
register(new Infix("!=")); // not equal to
register(new Infix("<=")); // less than or equal
register(new Infix(">=")); // greater than or equal
register(new Infix("&")); // string concatenation
register(new Infix("and") {
// allow as terminal
@Override Symbol nud() { return this; }
}); // Boolean AND
register(new Infix("or") {
// allow as terminal
@Override Symbol nud() { return this; }
}); // Boolean OR
register(new Infix("in") {
// allow as terminal
@Override Symbol nud() { return this; }
}); // is member of array
// merged Infix: register(new Terminal("and")); // the 'keywords' can also be used as terminals (field names)
// merged Infix: register(new Terminal("or")); //
// merged Infix: register(new Terminal("in")); //
// merged Infix: register(new Prefix("-")); // unary numeric negation
register(new Infix("~>")); // function application
// coalescing operator
register(new Infix("??", Tokenizer.operators.get("??")) {
@Override Symbol led(Symbol left) {
this.type = "condition";
Symbol c = new Symbol();
this.condition = c;
{
c.type = "function";
c.value = "(";
Symbol p = new Symbol();
c.procedure = p; p.type = "variable"; p.value = "exists";
c.arguments = List.of(left);
}
this.then = left;
this._else = expression(0);
return this;
}
});
register(new InfixR("(error)", 10) {
@Override
Symbol led(Symbol left) {
throw new UnsupportedOperationException("TODO", null);
}
});
// field wildcard (single level)
// merged with Infix *
// register(new Prefix("*") {
// @Override Symbol nud() {
// type = "wildcard";
// return this;
// }
// });
// descendant wildcard (multi-level)
register(new Prefix("**") {
@Override Symbol nud() {
type = "descendant";
return this;
}
});
// parent operator
// merged with Infix %
// register(new Prefix("%") {
// @Override Symbol nud() {
// type = "parent";
// return this;
// }
// });
// function invocation
register(new Infix("(", Tokenizer.operators.get("(")) {
@Override Symbol led(Symbol left) {
// left is is what we are trying to invoke
this.procedure = left;
this.type = "function";
this.arguments = new ArrayList<>();
if (!node.id.equals(")")) {
for (; ;) {
if ("operator".equals(node.type) && node.id.equals("?")) {
// partial function application
this.type = "partial";
this.arguments.add(node);
advance("?");
} else {
this.arguments.add(expression(0));
}
if (!node.id.equals(",")) break;
advance(",");
}
}
advance(")", true);
// if the name of the function is 'function' or λ, then this is function definition (lambda function)
if (left.type.equals("name") && (left.value.equals("function") || left.value.equals("\u03BB"))) {
// all of the args must be VARIABLE tokens
//int index = 0;
for (Symbol arg : arguments) {
//this.arguments.forEach(function (arg, index) {
if (!arg.type.equals("variable")) {
return handleError(new JException("S0208",
arg.position,
arg.value//,
//index + 1
)
);
}
//index++;
}
this.type = "lambda";
// is the next token a '<' - if so, parse the function signature
if (node.id.equals("<")) {
int depth = 1;
String sig = "<";
while (depth > 0 && !node.id.equals("{") && !node.id.equals("(end)")) {
Symbol tok = advance();
if (tok.id.equals(">")) {
depth--;
} else if (tok.id.equals("<")) {
depth++;
}
sig += tok.value;
}
advance(">");
this.signature = new Signature(sig, "lambda");
}
// parse the function body
advance("{");
this.body = expression(0);
advance("}");
}
return this;
}
//});
// parenthesis - block expression
// Note: in Java both nud and led are in same class!
//register(new Prefix("(") {
@Override Symbol nud() {
if (dbg) System.out.println("Prefix (");
List<Symbol> expressions = new ArrayList<>();
while (!node.id.equals(")")) {
expressions.add(Parser.this.expression(0));
if (!node.id.equals(";")) {
break;
}
advance(";");
}
advance(")", true);
this.type = "block";
this.expressions = expressions;
return this;
}
});
// array constructor
// merged: register(new Prefix("[") {
register(new Infix("[", Tokenizer.operators.get("[")) {
@Override Symbol nud() {
List<Symbol> a = new ArrayList<>();
if (!node.id.equals("]")) {
for (; ;) {
var item = Parser.this.expression(0);
if (node.id.equals("..")) {
// range operator
var range = new Symbol();
range.type = "binary"; range.value = ".."; range.position = node.position; range.lhs = item;
advance("..");
range.rhs = expression(0);
item = range;
}
a.add(item);
if (!node.id.equals(",")) {
break;
}
advance(",");
}
}
advance("]", true);
this.expressions = a;
this.type = "unary";
return this;
}
//});
// filter - predicate or array index
//register(new Infix("[", Tokenizer.operators.get("[")) {
@Override Symbol led(Symbol left) {
if (node.id.equals("]")) {
// empty predicate means maintain singleton arrays in the output
var step = left;
while (step!=null && step.type.equals("binary") && step.value.equals("[")) {
step = ((Infix)step).lhs;
}
step.keepArray = true;
advance("]");
return left;
} else {
this.lhs = left;
this.rhs = expression(Tokenizer.operators.get("]"));
this.type = "binary";
advance("]", true);
return this;
}
}
});
// order-by
register(new Infix("^", Tokenizer.operators.get("^")) {
@Override Symbol led(Symbol left) {
advance("(");
List<Symbol> terms = new ArrayList<>();
for (; ;) {
final Symbol term = new Symbol();
term.descending = false;
if (node.id.equals("<")) {
// ascending sort
advance("<");
} else if (node.id.equals(">")) {
// descending sort
term.descending = true;
advance(">");
} else {
//unspecified - default to ascending
}
term.expression = Parser.this.expression(0);
terms.add(term);
if (!node.id.equals(",")) {
break;
}
advance(",");
}
advance(")");
this.lhs = left;
this.rhsTerms = terms;
this.type = "binary";
return this;
}
});
register(new Infix("{", Tokenizer.operators.get("{")) {
// merged register(new Prefix("{") {
@Override Symbol nud() {
return objectParser(null);
}
// });
// register(new Infix("{", Tokenizer.operators.get("{")) {
@Override Symbol led(Symbol left) {
return objectParser(left);
}
});
// bind variable
register(new InfixR(":=", Tokenizer.operators.get(":=")) {
@Override Symbol led(Symbol left) {
if (!left.type.equals("variable")) {
return handleError(new JException(
"S0212",
left.position,
left.value
));
}
this.lhs = left;
this.rhs = expression(Tokenizer.operators.get(":=") - 1); // subtract 1 from bindingPower for right associative operators
this.type = "binary";
return this;
}
});
// focus variable bind
register(new Infix("@", Tokenizer.operators.get("@")) {
@Override Symbol led(Symbol left) {
this.lhs = left;
this.rhs = expression(Tokenizer.operators.get("@"));
if(!this.rhs.type.equals("variable")) {
return handleError(new JException("S0214",
this.rhs.position,
"@"
));
}
this.type = "binary";
return this;
}
});
// index (position) variable bind
register(new Infix("#", Tokenizer.operators.get("#")) {
@Override Symbol led(Symbol left) {
this.lhs = left;
this.rhs = expression(Tokenizer.operators.get("#"));
if(!this.rhs.type.equals("variable")) {
return handleError(new JException("S0214",
this.rhs.position,
"#"
));
}
this.type = "binary";
return this;
}
});
// if/then/else ternary operator ?:
register(new Infix("?", Tokenizer.operators.get("?")) {
@Override Symbol led(Symbol left) {
this.type = "condition";
this.condition = left;
this.then = expression(0);
if (node.id.equals(":")) {
// else condition
advance(":");
this._else = expression(0);
}
return this;
}
});
// elvis/default operator
register(new Infix("?:", Tokenizer.operators.get("?:")) {
@Override Symbol led(Symbol left) {
this.type = "condition";
this.condition = left;
this.then = left;
this._else = expression(0);
return this;
}
});
// object transformer
register(new Prefix("|") {
@Override Symbol nud() {
this.type = "transform";
this.pattern = Parser.this.expression(0);
advance("|");
this.update = Parser.this.expression(0);
if (node.id.equals(",")) {
advance(",");
this.delete = Parser.this.expression(0);
}
advance("|");
return this;
}
});
}
// tail call optimization
// this is invoked by the post parser to analyse lambda functions to see
// if they make a tail call. If so, it is replaced by a thunk which will
// be invoked by the trampoline loop during function application.
// This enables tail-recursive functions to be written without growing the stack
Symbol tailCallOptimize(Symbol expr) {
Symbol result;
if (expr.type.equals("function") && expr.predicate==null) {
var thunk = new Symbol(); thunk.type = "lambda"; thunk.thunk = true; thunk.arguments = List.of(); thunk.position = expr.position;
thunk.body = expr;
result = thunk;
} else if (expr.type.equals("condition")) {
// analyse both branches
expr.then = tailCallOptimize(expr.then);
if (expr._else != null) {
expr._else = tailCallOptimize(expr._else);
}
result = expr;
} else if (expr.type.equals("block")) {
// only the last expression in the block
var length = expr.expressions.size();
if (length > 0) {
if (!(expr.expressions instanceof ArrayList))
expr.expressions = new ArrayList<>(expr.expressions);
expr.expressions.set(length - 1, tailCallOptimize(expr.expressions.get(length - 1)));
}
result = expr;
} else {
result = expr;
}
return result;
}
int ancestorLabel = 0;
int ancestorIndex = 0;
List<Symbol> ancestry = new ArrayList<>();
Symbol seekParent(Symbol node, Symbol slot) {
switch (node.type) {
case "name":
case "wildcard":
slot.level--;
if(slot.level == 0) {
if (node.ancestor == null) {
node.ancestor = slot;
} else {
// reuse the existing label
ancestry.get((int)slot.index).slot.label = node.ancestor.label;
node.ancestor = slot;
}
node.tuple = true;
}
break;
case "parent":
slot.level++;
break;
case "block":
// look in last expression in the block
if(node.expressions.size() > 0) {
node.tuple = true;
slot = seekParent(node.expressions.get(node.expressions.size() - 1), slot);
}
break;
case "path":
// last step in path
node.tuple = true;
var index = node.steps.size() - 1;
slot = seekParent(node.steps.get(index--), slot);
while (slot.level > 0 && index >= 0) {
// check previous steps
slot = seekParent(node.steps.get(index--), slot);
}
break;
default:
// error - can't derive ancestor
throw new JException("S0217",
node.position,
node.type
);
}
return slot;
};
void pushAncestry(Symbol result, Symbol value) {
if (value==null) return; // Added NPE check
if (value.seekingParent!=null || value.type.equals("parent")) {
List<Symbol> slots = (value.seekingParent != null) ? value.seekingParent : new ArrayList<>();
if (value.type.equals("parent")) {
slots.add(value.slot);
}
if (result.seekingParent==null) {
result.seekingParent = slots;
} else {
result.seekingParent.addAll(slots);
}
}
}
void resolveAncestry(Symbol path) {
var index = path.steps.size() - 1;
var laststep = path.steps.get(index);
var slots = (laststep.seekingParent != null) ? laststep.seekingParent : new ArrayList<Symbol>();
if (laststep.type.equals("parent")) {
slots.add(laststep.slot);
}
for(var is = 0; is < slots.size(); is++) {
var slot = slots.get(is);
index = path.steps.size() - 2;
while (slot.level > 0) {
if (index < 0) {
if(path.seekingParent == null) {
path.seekingParent = new ArrayList<>(Arrays.asList(slot));
} else {
path.seekingParent.add(slot);
}
break;
}
// try previous step
var step = path.steps.get(index--);
// multiple contiguous steps that bind the focus should be skipped
while(index >= 0 && step.focus!=null && path.steps.get(index).focus!=null) {
step = path.steps.get(index--);
}
slot = seekParent(step, slot);
}
}
}
// post-parse stage
// the purpose of this is to add as much semantic value to the parse tree as possible
// in order to simplify the work of the evaluator.
// This includes flattening the parts of the AST representing location paths,
// converting them to arrays of steps which in turn may contain arrays of predicates.
// following this, nodes containing '.' and '[' should be eliminated from the AST.
Symbol processAST(Symbol expr) {
Symbol result = expr;
if (expr==null) return null;
if (dbg) System.out.println(" > processAST type="+expr.type+" value='"+expr.value+"'");
switch (expr.type != null ? expr.type : "(null)") {
case "binary": {
switch (""+expr.value) {
case ".":
var lstep = processAST(((Infix)expr).lhs);
if (lstep.type.equals("path")) {
result = lstep;
} else {
result = new Infix(null);
result.type = "path";
result.steps = new ArrayList<>(Arrays.asList(lstep));
//result = {type: 'path', steps: [lstep]};
}
if(lstep.type.equals("parent")) {
result.seekingParent = new ArrayList<>(Arrays.asList(lstep.slot));
}
var rest = processAST(((Infix)expr).rhs);
if (rest.type.equals("function") &&
rest.procedure.type.equals("path") &&
rest.procedure.steps.size() == 1 &&
rest.procedure.steps.get(0).type.equals("name") &&