-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathXQueryTranslationVisitor.java
More file actions
1771 lines (1630 loc) · 73.8 KB
/
XQueryTranslationVisitor.java
File metadata and controls
1771 lines (1630 loc) · 73.8 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
package org.rumbledb.compiler;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.rumbledb.config.RumbleRuntimeConfiguration;
import org.rumbledb.context.FunctionIdentifier;
import org.rumbledb.context.Name;
import org.rumbledb.context.StaticContext;
import org.rumbledb.errorcodes.ErrorCode;
import org.rumbledb.exceptions.*;
import org.rumbledb.expressions.CommaExpression;
import org.rumbledb.expressions.Expression;
import org.rumbledb.expressions.Node;
import org.rumbledb.expressions.arithmetic.AdditiveExpression;
import org.rumbledb.expressions.arithmetic.MultiplicativeExpression;
import org.rumbledb.expressions.arithmetic.UnaryExpression;
import org.rumbledb.expressions.comparison.ComparisonExpression;
import org.rumbledb.expressions.control.*;
import org.rumbledb.expressions.flowr.*;
import org.rumbledb.expressions.logic.AndExpression;
import org.rumbledb.expressions.logic.NotExpression;
import org.rumbledb.expressions.logic.OrExpression;
import org.rumbledb.expressions.miscellaneous.RangeExpression;
import org.rumbledb.expressions.miscellaneous.StringConcatExpression;
import org.rumbledb.expressions.module.*;
import org.rumbledb.expressions.postfix.*;
import org.rumbledb.expressions.primary.*;
import org.rumbledb.expressions.typing.CastExpression;
import org.rumbledb.expressions.typing.CastableExpression;
import org.rumbledb.expressions.typing.InstanceOfExpression;
import org.rumbledb.expressions.typing.TreatExpression;
import org.rumbledb.parser.XQueryParser;
import org.rumbledb.runtime.functions.input.FileSystemUtil;
import org.rumbledb.types.BuiltinTypesCatalogue;
import org.rumbledb.types.ItemType;
import org.rumbledb.types.SequenceType;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URI;
import java.util.*;
import static org.rumbledb.types.SequenceType.MOST_GENERAL_SEQUENCE_TYPE;
public class XQueryTranslationVisitor extends org.rumbledb.parser.XQueryParserBaseVisitor<Node> {
private StaticContext moduleContext;
private RumbleRuntimeConfiguration configuration;
private boolean isMainModule;
public XQueryTranslationVisitor(
StaticContext moduleContext,
boolean isMainModule,
RumbleRuntimeConfiguration configuration
) {
this.moduleContext = moduleContext;
this.moduleContext.bindNamespace("local", Name.LOCAL_NS);
this.configuration = configuration;
this.isMainModule = isMainModule;
}
// endregion expr
// region module
@Override
public Node visitModule(XQueryParser.ModuleContext ctx) {
XQueryParser.VersionDeclContext ver = ctx.versionDecl();
if (!(ver == null) && !ver.version.isEmpty()) {
String version = ver.version.getText().trim();
if (!(version.equals("3.1") || version.equals("3.0") || version.equals("1.0"))) {
throw new JsoniqVersionException(createMetadataFromContext(ctx));
}
}
if (this.isMainModule) {
if (ctx.mainModule() != null) {
return this.visitMainModule(ctx.mainModule());
}
throw new ParsingException(
"Main module expected, but library module found.",
createMetadataFromContext(ctx)
);
} else {
if (ctx.libraryModule() != null) {
return this.visitLibraryModule(ctx.libraryModule());
}
throw new ParsingException(
"Library module expected, but main module found.",
createMetadataFromContext(ctx)
);
}
}
private ExceptionMetadata createMetadataFromContext(ParserRuleContext ctx) {
return generateMetadata(ctx.getStart());
}
public ExceptionMetadata generateMetadata(Token token) {
return new ExceptionMetadata(
this.moduleContext.getStaticBaseURI().toString(),
token.getLine(),
token.getCharPositionInLine()
);
}
@Override
public Node visitMainModule(XQueryParser.MainModuleContext ctx) {
Prolog prolog = (Prolog) this.visitProlog(ctx.prolog());
Expression commaExpression = (Expression) this.visitExpr(ctx.queryBody().expr()); // Had to access query body
MainModule module = new MainModule(prolog, commaExpression, createMetadataFromContext(ctx));
module.setStaticContext(this.moduleContext);
return module;
}
// region Library
@Override
public Node visitLibraryModule(XQueryParser.LibraryModuleContext ctx) {
String prefix = ctx.moduleDecl().ncName().getText();
String namespace = processURILiteral(ctx.moduleDecl().uriLiteral());
if (namespace.equals("")) {
throw new EmptyModuleURIException("Module URI is empty.", createMetadataFromContext(ctx));
}
URI resolvedURI = FileSystemUtil.resolveURI(
this.moduleContext.getStaticBaseURI(),
namespace,
generateMetadata(ctx.getStop())
);
bindNamespace(
prefix,
resolvedURI.toString(),
generateMetadata(ctx.getStop())
);
Prolog prolog = (Prolog) this.visitProlog(ctx.prolog());
LibraryModule module = new LibraryModule(prolog, resolvedURI.toString(), createMetadataFromContext(ctx));
module.setStaticContext(this.moduleContext);
return module;
}
public void bindNamespace(String prefix, String namespace, ExceptionMetadata metadata) {
boolean success = this.moduleContext.bindNamespace(
prefix,
namespace
);
if (!success) {
throw new NamespacePrefixBoundTwiceException(
"Prefix " + prefix + " is bound twice.",
metadata
);
}
}
@Override
public Node visitProlog(XQueryParser.PrologContext ctx) {
// bind namespaces
for (XQueryParser.NamespaceDeclContext namespace : ctx.namespaceDecl()) {
this.processNamespaceDecl(namespace);
}
if (!ctx.defaultNamespaceDecl().isEmpty()) {
throw new XMLUnsupportedException(
"defaultNamespaceDeclContext not supported YET",
createMetadataFromContext(ctx)
);
}
if (!ctx.schemaImport().isEmpty()) {
throw new XMLUnsupportedException("schemaImport not supported", createMetadataFromContext(ctx));
}
List<XQueryParser.SetterContext> setters = ctx.setter();
boolean emptyOrderSet = false;
boolean defaultCollationSet = false;
for (XQueryParser.SetterContext setterContext : setters) {
if (setterContext.emptyOrderDecl() != null) {
if (emptyOrderSet) {
throw new MoreThanOneEmptyOrderDeclarationException(
"The empty order was already set.",
createMetadataFromContext(setterContext.emptyOrderDecl())
);
}
processEmptySequenceOrder(setterContext.emptyOrderDecl());
emptyOrderSet = true;
continue;
}
if (setterContext.defaultCollationDecl() != null) {
if (defaultCollationSet) {
throw new DefaultCollationException(
"The default collation was already set.",
createMetadataFromContext(setterContext.defaultCollationDecl())
);
}
processDefaultCollation(setterContext.defaultCollationDecl());
defaultCollationSet = true;
continue;
}
if (setterContext.copyNamespacesDecl() != null) {
throw new XMLUnsupportedException("copyNamespacesDecl not supported", createMetadataFromContext(ctx));
}
if (setterContext.constructionDecl() != null) {
throw new XMLUnsupportedException("constructionDecl not supported", createMetadataFromContext(ctx));
}
if (setterContext.boundarySpaceDecl() != null) {
throw new XMLUnsupportedException("boundarySpaceDecl not supported", createMetadataFromContext(ctx));
}
if (setterContext.decimalFormatDecl() != null) {
// TODO outside of the scope for thesis
throw new XMLUnsupportedException(
"decimalFormatDecl not supported YET",
createMetadataFromContext(ctx)
);
}
if (setterContext.baseURIDecl() != null) {
// TODO outside of the scope for thesis
throw new XMLUnsupportedException("baseURIDecl not supported YET", createMetadataFromContext(ctx));
}
throw new UnsupportedFeatureException(
"Setters are not supported yet, except for empty sequence ordering and default collations.",
createMetadataFromContext(setterContext)
);
}
List<LibraryModule> libraryModules = new ArrayList<>();
Set<String> namespaces = new HashSet<>();
for (XQueryParser.ModuleImportContext namespace : ctx.moduleImport()) {
LibraryModule libraryModule = this.processModuleImport(namespace);
libraryModules.add(libraryModule);
if (namespaces.contains(libraryModule.getNamespace())) {
throw new DuplicateModuleTargetNamespaceException(
"Duplicate module target namespace: " + libraryModule.getNamespace(),
createMetadataFromContext(namespace)
);
}
namespaces.add(libraryModule.getNamespace());
}
// parse variables and function
List<VariableDeclaration> globalVariables = new ArrayList<>();
List<FunctionDeclaration> functionDeclarations = new ArrayList<>();
for (XQueryParser.AnnotatedDeclContext annotatedDeclaration : ctx.annotatedDecl()) {
if (annotatedDeclaration.varDecl() != null) {
VariableDeclaration variableDeclaration = (VariableDeclaration) this.visitVarDecl(
annotatedDeclaration.varDecl()
);
if (!this.isMainModule) {
String moduleNamespace = this.moduleContext.getStaticBaseURI().toString();
String variableNamespace = variableDeclaration.getVariableName().getNamespace();
if (variableNamespace == null || !variableNamespace.equals(moduleNamespace)) {
throw new NamespaceDoesNotMatchModuleException(
"Variable "
+ variableDeclaration.getVariableName().getLocalName()
+ ": namespace "
+ variableNamespace
+ " must match module namespace "
+ moduleNamespace,
generateMetadata(annotatedDeclaration.getStop())
);
}
}
globalVariables.add(variableDeclaration);
} else if (annotatedDeclaration.functionDecl() != null) {
InlineFunctionExpression inlineFunctionExpression = (InlineFunctionExpression) this.visitFunctionDecl(
annotatedDeclaration.functionDecl()
);
if (!this.isMainModule) {
String moduleNamespace = this.moduleContext.getStaticBaseURI().toString();
String functionNamespace = inlineFunctionExpression.getName().getNamespace();
if (functionNamespace == null || !functionNamespace.equals(moduleNamespace)) {
throw new NamespaceDoesNotMatchModuleException(
"Function "
+ inlineFunctionExpression.getName().getLocalName()
+ ": namespace "
+ functionNamespace
+ " must match module namespace "
+ moduleNamespace,
generateMetadata(annotatedDeclaration.getStop())
);
}
}
functionDeclarations.add(
new FunctionDeclaration(inlineFunctionExpression, createMetadataFromContext(ctx))
);
} else if (annotatedDeclaration.contextItemDecl() != null) {
// TODO outside of the scope for thesis
throw new XMLUnsupportedException("contextItemDecl not supported YET", createMetadataFromContext(ctx));
} else if (annotatedDeclaration.optionDecl() != null) {
throw new XMLUnsupportedException("optionDecl not supported", createMetadataFromContext(ctx));
}
}
for (XQueryParser.ModuleImportContext module : ctx.moduleImport()) {
this.visitModuleImport(module);
}
Prolog prolog = new Prolog(
globalVariables,
functionDeclarations,
Collections.emptyList(),
createMetadataFromContext(ctx)
);
for (LibraryModule libraryModule : libraryModules) {
prolog.addImportedModule(libraryModule);
}
return prolog;
}
@Override
public Node visitVarDecl(XQueryParser.VarDeclContext ctx) {
SequenceType seq;
boolean external = false;
if (ctx.annotations() != null) {
processAnnotations(ctx.annotations());
}
Name var = ((VariableReferenceExpression) this.visitVarName(ctx.varName())).getVariableName();
if (ctx.typeDeclaration() != null) {
seq = this.processSequenceType(ctx.typeDeclaration().sequenceType());
} else {
seq = SequenceType.MOST_GENERAL_SEQUENCE_TYPE;
}
XQueryParser.ExprSingleContext exprSingle = null;
if (ctx.varDefaultValue() != null) {
external = true;
exprSingle = ctx.varDefaultValue().exprSingle();
}
Expression expr = null;
if (ctx.varValue() != null) {
exprSingle = ctx.varValue().exprSingle();
}
if (exprSingle != null) {
expr = (Expression) this.visitExprSingle(exprSingle);
if (!seq.equals(SequenceType.MOST_GENERAL_SEQUENCE_TYPE)) {
expr = new TreatExpression(expr, seq, ErrorCode.UnexpectedTypeErrorCode, expr.getMetadata());
}
}
return new VariableDeclaration(var, external, seq, expr, createMetadataFromContext(ctx));
}
private void processAnnotations(XQueryParser.AnnotationsContext annotations) {
if (annotations.annotation().size() > 1) {
// TODO outside of the scope for thesis
throw new XMLUnsupportedException(
"multipleAnnotations not supported YET",
createMetadataFromContext(annotations)
);
}
XQueryParser.AnnotationContext annotationContext = annotations.annotation().get(0);
XQueryParser.QNameContext newCtx = annotationContext.qName();
String localName;
if (newCtx.ncName() != null) {
if (newCtx.ncName().local_name != null) {
localName = newCtx.ncName().local_name.getText();
} else {
localName = newCtx.ncName().local_namekw.getText();
}
if (!localName.equals("public")) {
// TODO outside of the scope for thesis
throw new XMLUnsupportedException("private not supported YET", createMetadataFromContext(annotations));
}
} else {
// TODO outside of the scope for thesis
throw new XMLUnsupportedException("prefix not supported YET", createMetadataFromContext(annotations));
}
}
@Override
public Node visitFunctionDecl(XQueryParser.FunctionDeclContext ctx) {
Name name = parseName(ctx.eqName(), true, false);
LinkedHashMap<Name, SequenceType> fnParams = new LinkedHashMap<>();
SequenceType fnReturnType = MOST_GENERAL_SEQUENCE_TYPE;
Name paramName;
SequenceType paramType;
if (ctx.annotations() != null) {
processAnnotations(ctx.annotations());
}
if (ctx.functionParams() != null) {
for (XQueryParser.FunctionParamContext param : ctx.functionParams().functionParam()) {
paramName = parseName(param.qName(), false, false);
paramType = MOST_GENERAL_SEQUENCE_TYPE;
if (fnParams.containsKey(paramName)) {
throw new DuplicateParamNameException(
name,
paramName,
createMetadataFromContext(param)
);
}
if (param.typeDeclaration() != null) {
paramType = this.processSequenceType(param.typeDeclaration().sequenceType());
} else {
paramType = SequenceType.MOST_GENERAL_SEQUENCE_TYPE;
}
fnParams.put(paramName, paramType);
}
}
if (ctx.functionReturn() != null) {
fnReturnType = this.processSequenceType(ctx.functionReturn().sequenceType());
} else {
fnReturnType = SequenceType.MOST_GENERAL_SEQUENCE_TYPE;
}
Expression bodyExpression = null;
if (ctx.functionBody() != null) {
bodyExpression = (Expression) this.visitExpr(ctx.functionBody().enclosedExpression().expr());
} else {
bodyExpression = new CommaExpression(createMetadataFromContext(ctx));
}
return new InlineFunctionExpression(
name,
fnParams,
fnReturnType,
bodyExpression,
createMetadataFromContext(ctx)
);
}
public void processNamespaceDecl(XQueryParser.NamespaceDeclContext ctx) {
bindNamespace(
ctx.ncName().getText(),
processURILiteral(ctx.uriLiteral()),
generateMetadata(ctx.getStop())
);
}
private void processEmptySequenceOrder(XQueryParser.EmptyOrderDeclContext ctx) {
if (ctx.type.getText().equals("least")) {
this.moduleContext.setEmptySequenceOrderLeast(true);
}
if (ctx.type.getText().equals("greatest")) {
this.moduleContext.setEmptySequenceOrderLeast(false);
}
}
private void processDefaultCollation(XQueryParser.DefaultCollationDeclContext ctx) {
String uri = processURILiteral(ctx.uriLiteral());
if (!uri.equals(Name.DEFAULT_COLLATION_NS)) {
throw new DefaultCollationException(
"Unknown collation: " + uri,
createMetadataFromContext(ctx.uriLiteral())
);
}
}
public LibraryModule processModuleImport(XQueryParser.ModuleImportContext ctx) {
String namespace = processURILiteral(ctx.nsURI);
URI resolvedURI = FileSystemUtil.resolveURI(
this.moduleContext.getStaticBaseURI(),
namespace,
generateMetadata(ctx.getStop())
);
LibraryModule libraryModule = null;
try {
libraryModule = VisitorHelpers.parseLibraryModuleFromLocation(
resolvedURI,
this.configuration,
this.moduleContext,
generateMetadata(ctx.getStop())
);
if (!resolvedURI.toString().equals(libraryModule.getNamespace())) {
throw new ModuleNotFoundException(
"A module with namespace "
+ resolvedURI.toString()
+ " was not found. The namespace of the module at this location was: "
+ libraryModule.getNamespace(),
generateMetadata(ctx.getStop())
);
}
} catch (IOException e) {
RumbleException exception = new ModuleNotFoundException(
"I/O error while attempting to import a module: " + namespace + " Cause: " + e.getMessage(),
generateMetadata(ctx.getStop())
);
exception.initCause(e);
throw exception;
} catch (CannotRetrieveResourceException e) {
RumbleException exception = new ModuleNotFoundException(
"Module not found: " + namespace + " Cause: " + e.getMessage(),
generateMetadata(ctx.getStop())
);
exception.initCause(e);
throw exception;
}
if (ctx.ncName() != null) {
bindNamespace(
ctx.ncName().getText(),
resolvedURI.toString(),
generateMetadata(ctx.getStop())
);
}
return libraryModule;
}
// endregion
// region expr
@Override
public Node visitExpr(XQueryParser.ExprContext ctx) {
List<Expression> expressions = new ArrayList<>();
for (XQueryParser.ExprSingleContext expr : ctx.exprSingle()) {
expressions.add((Expression) this.visitExprSingle(expr));
}
if (expressions.size() == 1) {
return expressions.get(0);
}
return new CommaExpression(expressions, createMetadataFromContext(ctx));
}
@Override
public Node visitExprSingle(XQueryParser.ExprSingleContext ctx) {
ParseTree content = ctx.children.get(0);
if (content instanceof XQueryParser.OrExprContext) {
return this.visitOrExpr((XQueryParser.OrExprContext) content);
}
if (content instanceof XQueryParser.FlworExprContext) {
return this.visitFlworExpr((XQueryParser.FlworExprContext) content);
}
if (content instanceof XQueryParser.IfExprContext) {
return this.visitIfExpr((XQueryParser.IfExprContext) content);
}
if (content instanceof XQueryParser.QuantifiedExprContext) {
return this.visitQuantifiedExpr((XQueryParser.QuantifiedExprContext) content);
}
if (content instanceof XQueryParser.SwitchExprContext) {
return this.visitSwitchExpr((XQueryParser.SwitchExprContext) content);
}
if (content instanceof XQueryParser.TypeswitchExprContext) {
return this.visitTypeswitchExpr((XQueryParser.TypeswitchExprContext) content);
}
if (content instanceof XQueryParser.TryCatchExprContext) {
return this.visitTryCatchExpr((XQueryParser.TryCatchExprContext) content);
}
if (content instanceof XQueryParser.ExistUpdateExprContext) {
// TODO outside of the scope for thesis
throw new XMLUnsupportedException(
"ExistUpdateExprContext not supported YET",
createMetadataFromContext(ctx)
);
}
throw new OurBadException("Unrecognized ExprSingle.");
}
// endregion
// region Or
@Override
public Node visitOrExpr(XQueryParser.OrExprContext ctx) {
Expression result = (Expression) this.visitAndExpr(ctx.main_expr);
if (ctx.rhs == null || ctx.rhs.isEmpty()) {
return result;
}
for (XQueryParser.AndExprContext child : ctx.rhs) {
Expression rightExpression = (Expression) this.visitAndExpr(child);
result = new OrExpression(result, rightExpression, createMetadataFromContext(ctx));
}
return result;
}
@Override
public Node visitAndExpr(XQueryParser.AndExprContext ctx) {
Expression result = (Expression) this.visitComparisonExpr(ctx.main_expr);
if (ctx.rhs == null || ctx.rhs.isEmpty()) {
return result;
}
for (XQueryParser.ComparisonExprContext child : ctx.rhs) {
Expression rightExpression = (Expression) this.visitComparisonExpr(child);
result = new AndExpression(result, rightExpression, createMetadataFromContext(ctx));
}
return result;
}
@Override
public Node visitComparisonExpr(XQueryParser.ComparisonExprContext ctx) {
Expression mainExpression = (Expression) this.visitStringConcatExpr(ctx.main_expr);
if (ctx.rhs == null || ctx.rhs.isEmpty()) {
return mainExpression;
}
XQueryParser.StringConcatExprContext child = ctx.rhs.get(0);
Expression childExpression = (Expression) this.visitStringConcatExpr(child);
String op = "";
// is, <<, >>
if (ctx.nodeComp() != null)
throw new XMLUnsupportedException("nodeComp not supported", createMetadataFromContext(ctx));
// eq, ne, ge, gt, le, lt
if (ctx.valueComp() != null)
op = ctx.valueComp().getText();
// ==, !=, >=, >, <=, <
if (ctx.generalComp() != null)
op = ctx.generalComp().getText();
return new ComparisonExpression(
mainExpression,
childExpression,
ComparisonExpression.ComparisonOperator.fromSymbol(op),
createMetadataFromContext(ctx)
);
}
@Override
public Node visitStringConcatExpr(XQueryParser.StringConcatExprContext ctx) {
Expression result = (Expression) this.visitRangeExpr(ctx.main_expr);
if (ctx.rhs == null || ctx.rhs.isEmpty()) {
return result;
}
for (XQueryParser.RangeExprContext child : ctx.rhs) {
Expression rightExpression = (Expression) this.visitRangeExpr(child);
result = new StringConcatExpression(result, rightExpression, createMetadataFromContext(ctx));
}
return result;
}
@Override
public Node visitRangeExpr(XQueryParser.RangeExprContext ctx) {
Expression mainExpression = (Expression) this.visitAdditiveExpr(ctx.main_expr);
if (ctx.rhs == null || ctx.rhs.isEmpty()) {
return mainExpression;
}
XQueryParser.AdditiveExprContext child = ctx.rhs.get(0);
Expression childExpression = (Expression) this.visitAdditiveExpr(child);
return new RangeExpression(
mainExpression,
childExpression,
createMetadataFromContext(ctx)
);
}
@Override
public Node visitAdditiveExpr(XQueryParser.AdditiveExprContext ctx) {
Expression result = (Expression) this.visitMultiplicativeExpr(ctx.main_expr);
if (ctx.rhs == null || ctx.rhs.isEmpty()) {
return result;
}
for (int i = 0; i < ctx.rhs.size(); ++i) {
XQueryParser.MultiplicativeExprContext child = ctx.rhs.get(i);
Expression rightExpression = (Expression) this.visitMultiplicativeExpr(child);
result = new AdditiveExpression(
result,
rightExpression,
ctx.op.get(i).getText().equals("-"),
createMetadataFromContext(ctx)
);
}
return result;
}
@Override
public Node visitMultiplicativeExpr(XQueryParser.MultiplicativeExprContext ctx) {
Expression result = (Expression) this.visitUnionExpr(ctx.main_expr);
if (ctx.rhs == null || ctx.rhs.isEmpty()) {
return result;
}
for (int i = 0; i < ctx.rhs.size(); ++i) {
XQueryParser.UnionExprContext child = ctx.rhs.get(i);
Expression rightExpression = (Expression) this.visitUnionExpr(child);
result = new MultiplicativeExpression(
result,
rightExpression,
MultiplicativeExpression.MultiplicativeOperator.fromSymbol(ctx.op.get(i).getText()),
createMetadataFromContext(ctx)
);
}
return result;
}
@Override
public Node visitUnionExpr(XQueryParser.UnionExprContext ctx) {
Expression result = (Expression) this.visitIntersectExceptExpr(ctx.main_expr);
if (ctx.rhs == null || ctx.rhs.isEmpty()) {
return result;
}
throw new XMLUnsupportedException("UnionExprContext not supported", createMetadataFromContext(ctx));
}
@Override
public Node visitIntersectExceptExpr(XQueryParser.IntersectExceptExprContext ctx) {
Expression result = (Expression) this.visitInstanceOfExpr(ctx.main_expr);
if (ctx.rhs == null || ctx.rhs.isEmpty()) {
return result;
}
throw new XMLUnsupportedException("IntersectExceptExprContext not supported", createMetadataFromContext(ctx));
}
@Override
public Node visitInstanceOfExpr(XQueryParser.InstanceOfExprContext ctx) {
Expression mainExpression = (Expression) this.visitTreatExpr(ctx.main_expr);
if (ctx.seq == null || ctx.seq.isEmpty()) {
return mainExpression;
}
XQueryParser.SequenceTypeContext child = ctx.seq;
SequenceType sequenceType = this.processSequenceType(child);
return new InstanceOfExpression(
mainExpression,
sequenceType,
createMetadataFromContext(ctx)
);
}
public SequenceType processSequenceType(XQueryParser.SequenceTypeContext ctx) {
if (ctx.item == null) {
return SequenceType.EMPTY_SEQUENCE;
}
ItemType itemType = processItemType(ctx.item);
if (ctx.question.size() > 0) {
return new SequenceType(
itemType,
SequenceType.Arity.OneOrZero
);
}
if (ctx.star.size() > 0) {
return new SequenceType(
itemType,
SequenceType.Arity.ZeroOrMore
);
}
if (ctx.plus.size() > 0) {
return new SequenceType(
itemType,
SequenceType.Arity.OneOrMore
);
}
return new SequenceType(itemType);
}
private ItemType processItemType(XQueryParser.ItemTypeContext ctx) {
ParseTree child = ctx.children.get(0);
if (child instanceof XQueryParser.KindTestContext) {
throw new XMLUnsupportedException("KindTestContext not supported", createMetadataFromContext(ctx));
} else if (child instanceof XQueryParser.FunctionTestContext) {
// TODO outside of the scope for thesis
throw new XMLUnsupportedException("FunctionTestContext not supported YET", createMetadataFromContext(ctx));
} else if (child instanceof XQueryParser.MapTestContext) {
XQueryParser.MapTestContext mapTestContext = (XQueryParser.MapTestContext) child;
if (mapTestContext.typedMapTest() != null)
throw new XMLUnsupportedException("typedMapTest not supported", createMetadataFromContext(ctx));
else
return BuiltinTypesCatalogue.objectItem;
} else if (child instanceof XQueryParser.ArrayTestContext) {
XQueryParser.ArrayTestContext arrayTestContext = (XQueryParser.ArrayTestContext) child;
if (arrayTestContext.typedArrayTest() != null)
throw new XMLUnsupportedException("typedArrayTest not supported", createMetadataFromContext(ctx));
else
return BuiltinTypesCatalogue.arrayItem;
} else if (child instanceof XQueryParser.AtomicOrUnionTypeContext) {
return BuiltinTypesCatalogue.getItemTypeByName(
parseName(ctx.atomicOrUnionType().eqName().qName(), false, true)
);
} else if (child instanceof XQueryParser.ParenthesizedItemTestContext) {
return processItemType(((XQueryParser.ParenthesizedItemTestContext) child).itemType());
} else {
// It has to be (KW_ITEM LPAREN RPAREN)
return BuiltinTypesCatalogue.item;
}
}
@Override
public Node visitTreatExpr(XQueryParser.TreatExprContext ctx) {
Expression mainExpression = (Expression) this.visitCastableExpr(ctx.main_expr);
if (ctx.seq == null || ctx.seq.isEmpty()) {
return mainExpression;
}
XQueryParser.SequenceTypeContext child = ctx.seq;
SequenceType sequenceType = this.processSequenceType(child);
return new TreatExpression(
mainExpression,
sequenceType,
ErrorCode.DynamicTypeTreatErrorCode,
createMetadataFromContext(ctx)
);
}
@Override
public Node visitCastableExpr(XQueryParser.CastableExprContext ctx) {
Expression mainExpression = (Expression) this.visitCastExpr(ctx.main_expr);
if (ctx.single == null || ctx.single.isEmpty()) {
return mainExpression;
}
XQueryParser.SingleTypeContext child = ctx.single;
SequenceType sequenceType = this.processSingleType(child);
return new CastableExpression(mainExpression, sequenceType, createMetadataFromContext(ctx));
}
public SequenceType processSingleType(XQueryParser.SingleTypeContext ctx) {
if (ctx.item == null) {
return SequenceType.EMPTY_SEQUENCE;
}
ItemType itemType = BuiltinTypesCatalogue.getItemTypeByName(
parseName(ctx.item.typeName().eqName().qName(), false, true)
);
if (ctx.question.size() > 0) {
return new SequenceType(
itemType,
SequenceType.Arity.OneOrZero
);
}
return new SequenceType(itemType);
}
@Override
public Node visitCastExpr(XQueryParser.CastExprContext ctx) {
Expression mainExpression = (Expression) this.visitArrowExpr(ctx.main_expr);
if (ctx.single == null || ctx.single.isEmpty()) {
return mainExpression;
}
XQueryParser.SingleTypeContext child = ctx.single;
SequenceType sequenceType = this.processSingleType(child);
return new CastExpression(mainExpression, sequenceType, createMetadataFromContext(ctx));
}
@Override
public Node visitArrowExpr(XQueryParser.ArrowExprContext ctx) {
Expression mainExpression = (Expression) this.visitUnaryExpr(ctx.main_expr);
for (int i = 0; i < ctx.function_call_expr.size(); ++i) {
XQueryParser.ComplexArrowContext functionCallContext = ctx.function_call_expr.get(i);
if (functionCallContext.arrowFunctionSpecifier().parenthesizedExpr() != null) {
throw new XMLUnsupportedException("parenthesizedExpr not supported", createMetadataFromContext(ctx));
}
List<Expression> children = new ArrayList<Expression>();
children.add(mainExpression);
children.addAll(getArgumentsFromArgumentListContext(functionCallContext.argumentList()));
Name name;
if (functionCallContext.arrowFunctionSpecifier().eqName() != null)
name = parseName(functionCallContext.arrowFunctionSpecifier().eqName(), true, false);
else
name = parseName(functionCallContext.arrowFunctionSpecifier().varRef().eqName(), true, false);
mainExpression = processFunctionCall(name, functionCallContext, children);
}
return mainExpression;
}
private List<Expression> getArgumentsFromArgumentListContext(XQueryParser.ArgumentListContext ctx) {
List<Expression> arguments = new ArrayList<>();
if (ctx.args != null) {
for (XQueryParser.ArgumentContext arg : ctx.args) {
Expression currentArg = (Expression) this.visitArgument(arg);
arguments.add(currentArg);
}
}
return arguments;
}
private Expression processFunctionCall(Name name, ParserRuleContext ctx, List<Expression> children) {
if (
BuiltinTypesCatalogue.typeExists(name)
&& children.size() == 1
) {
return new CastExpression(
children.get(0),
SequenceType.createSequenceType(name.getLocalName() + "?"),
createMetadataFromContext(ctx)
);
}
if (
BuiltinTypesCatalogue.typeExists(Name.createVariableInDefaultTypeNamespace(name.getLocalName()))
&& children.size() == 1
&& name.getNamespace() != null
&& name.getNamespace().equals(Name.JSONIQ_DEFAULT_FUNCTION_NS)
&& !name.getLocalName().equals("boolean")
) {
return new CastExpression(
children.get(0),
SequenceType.createSequenceType(name.getLocalName() + "?"),
createMetadataFromContext(ctx)
);
}
return new FunctionCallExpression(
name,
children,
createMetadataFromContext(ctx)
);
}
private Name parseName(XQueryParser.EqNameContext ctx, boolean isFunction, boolean isType) {
if (ctx.qName() == null)
throw new XMLUnsupportedException("URIQualifiedName not supported", createMetadataFromContext(ctx));
XQueryParser.QNameContext newCtx = ctx.qName();
return parseName(newCtx, isFunction, isType);
}
private Name parseName(XQueryParser.QNameContext newCtx, boolean isFunction, boolean isType) {
String localName = null;
String prefix = null;
Name name = null;
if (newCtx.ncName() != null) {
if (newCtx.ncName().local_name != null) {
localName = newCtx.ncName().local_name.getText();
} else {
localName = newCtx.ncName().local_namekw.getText();
}
} else {
// We know that it will have single : as parser would throw an error earlier
String fullText = newCtx.FullQName().getText();
prefix = fullText.split(":")[0];
localName = fullText.split(":")[1];
}
if (prefix == null) {
if (isFunction) {
name = Name.createVariableInDefaultXQueryFunctionNamespace(localName);
} else if (isType) {
name = Name.createVariableInDefaultXQueryTypeNamespace(localName);
} else {
name = Name.createVariableInNoNamespace(localName);
}
} else {
name = Name.createVariableResolvingPrefix(prefix, localName, this.moduleContext);
}
if (name != null) {
return name;
}
throw new PrefixCannotBeExpandedException(
"Cannot expand prefix " + prefix,
generateMetadata(newCtx.getStop())
);
}
@Override
public Node visitUnaryExpr(XQueryParser.UnaryExprContext ctx) {
if (ctx.main_expr.simpleMapExpr() == null)
throw new XMLUnsupportedException(
"validateExpr and extensionExpr not supported",
createMetadataFromContext(ctx)
);
Expression mainExpression = (Expression) this.visitSimpleMapExpr(ctx.main_expr.simpleMapExpr());
if (ctx.op == null || ctx.op.isEmpty()) {
return mainExpression;
}
boolean negated = false;
for (Token t : ctx.op) {
if (t.getText().contentEquals("-")) {
negated = !negated;
}
}
return new UnaryExpression(
mainExpression,
negated,
createMetadataFromContext(ctx)
);
}
@Override
public Node visitSimpleMapExpr(XQueryParser.SimpleMapExprContext ctx) {
Expression result = (Expression) this.visitPathExpr(ctx.main_expr);
if (ctx.map_expr == null || ctx.map_expr.isEmpty()) {
return result;
}
for (int i = 0; i < ctx.map_expr.size(); ++i) {
XQueryParser.PathExprContext child = ctx.map_expr.get(i);
Expression rightExpression = (Expression) this.visitPathExpr(child);
result = new SimpleMapExpression(
result,
rightExpression,
createMetadataFromContext(ctx)
);
}
return result;
}
@Override
public Node visitPathExpr(XQueryParser.PathExprContext ctx) {
if (ctx.singleslash != null || ctx.doubleslash != null)
throw new XMLUnsupportedException("Path expressions are not supported", createMetadataFromContext(ctx));
return this.visitRelativePathExpr(ctx.relative);
}
@Override
public Node visitRelativePathExpr(XQueryParser.RelativePathExprContext ctx) {
if (ctx.stepExpr().size() != 1) {
throw new XMLUnsupportedException("Path expressions are not supported", createMetadataFromContext(ctx));
}
return this.visitStepExpr(ctx.stepExpr().get(0));
}
@Override
public Node visitStepExpr(XQueryParser.StepExprContext ctx) {
if (ctx.axisStep() != null) {
throw new XMLUnsupportedException("Path expressions are not supported", createMetadataFromContext(ctx));
}
return this.visitPostfixExpr(ctx.postfixExpr());
}
@Override
public Node visitPostfixExpr(XQueryParser.PostfixExprContext ctx) {
Expression mainExpression = (Expression) this.visitPrimaryExpr(ctx.main_expr);
for (ParseTree child : ctx.children.subList(1, ctx.children.size())) {
if (child instanceof XQueryParser.PredicateContext) {
Expression expr = (Expression) this.visitPredicate((XQueryParser.PredicateContext) child);
mainExpression = new FilterExpression(
mainExpression,
expr,
createMetadataFromContext(ctx)