-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy path$RascalModule.java
More file actions
4311 lines (3724 loc) · 135 KB
/
$RascalModule.java
File metadata and controls
4311 lines (3724 loc) · 135 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
/*
* Copyright (c) 2018-2025, NWO-I CWI, Swat.engineering and Paul Klint
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.rascalmpl.runtime;
import static org.rascalmpl.values.RascalValueFactory.TYPE_STORE_SUPPLIER;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.rascalmpl.debug.IRascalMonitor;
import org.rascalmpl.exceptions.JavaMethodLink;
import org.rascalmpl.exceptions.RuntimeExceptionFactory;
import org.rascalmpl.ideservices.IDEServices;
import org.rascalmpl.interpreter.load.RascalSearchPath;
import org.rascalmpl.interpreter.utils.IResourceLocationProvider;
import org.rascalmpl.interpreter.utils.RascalManifest;
import org.rascalmpl.library.util.PathConfig;
import org.rascalmpl.library.util.ToplevelType;
import org.rascalmpl.parser.gtd.result.out.INodeFlattener;
import org.rascalmpl.runtime.traverse.Traverse;
import org.rascalmpl.shell.CommandlineParser;
import org.rascalmpl.types.DefaultRascalTypeVisitor;
import org.rascalmpl.types.NonTerminalType;
import org.rascalmpl.types.RascalTypeFactory;
import org.rascalmpl.uri.SourceLocationURICompare;
import org.rascalmpl.uri.URIResolverRegistry;
import org.rascalmpl.uri.URIUtil;
import org.rascalmpl.uri.project.ProjectURIResolver;
import org.rascalmpl.uri.project.TargetURIResolver;
import org.rascalmpl.values.IRascalValueFactory;
import org.rascalmpl.values.RascalValueFactory;
import org.rascalmpl.values.functions.IFunction;
import org.rascalmpl.values.parsetrees.ITree;
import org.rascalmpl.values.parsetrees.ProductionAdapter;
import org.rascalmpl.values.parsetrees.SymbolAdapter;
import org.rascalmpl.values.parsetrees.TreeAdapter;
import org.rascalmpl.values.parsetrees.TreeAdapter.FieldResult;
import io.usethesource.vallang.IBool;
import io.usethesource.vallang.IConstructor;
import io.usethesource.vallang.IDateTime;
import io.usethesource.vallang.IInteger;
import io.usethesource.vallang.IList;
import io.usethesource.vallang.IListWriter;
import io.usethesource.vallang.IMap;
import io.usethesource.vallang.IMapWriter;
import io.usethesource.vallang.INode;
import io.usethesource.vallang.INumber;
import io.usethesource.vallang.IRational;
import io.usethesource.vallang.IReal;
import io.usethesource.vallang.ISet;
import io.usethesource.vallang.ISetWriter;
import io.usethesource.vallang.ISourceLocation;
import io.usethesource.vallang.IString;
import io.usethesource.vallang.ITuple;
import io.usethesource.vallang.IValue;
import io.usethesource.vallang.IValueFactory;
import io.usethesource.vallang.exceptions.FactTypeUseException;
import io.usethesource.vallang.exceptions.InvalidDateTimeException;
import io.usethesource.vallang.io.binary.stream.IValueInputStream;
import io.usethesource.vallang.type.Type;
import io.usethesource.vallang.type.TypeFactory;
import io.usethesource.vallang.type.TypeStore;
public abstract class $RascalModule {
/*************************************************************************/
/* Utilities for generated code */
/*************************************************************************/
// ---- value factory for creating functions, reified types and parsers unique to the Rascal runtime
final protected IRascalValueFactory $RVF;
// ---- library helper methods and fields -------------------------------------------
/*package*/ final PrintWriter $OUTWRITER;
/*package*/ final PrintWriter $ERRWRITER;
/*package*/ final Reader $IN;
/*package*/ final IRascalMonitor $MONITOR;
protected final RascalExecutionContext $rex;
//protected final IValueFactory $RVF;
public final TypeFactory $TF;
protected final RascalTypeFactory $RTF;
public final TypeStore $TS;
protected final Traverse $TRAVERSE;
private final IBool Rascal_TRUE;
private final IBool Rascal_FALSE;
protected final FailReturnFromVoidException $failReturnFromVoidException;
public $RascalModule(RascalExecutionContext rex){
this.$rex = rex;
$IN = rex.getInReader();
$OUTWRITER = rex.getOutWriter();
$ERRWRITER = rex.getErrWriter();
$MONITOR = rex;
$RVF = rex.getRascalRuntimeValueFactory();
$TF = rex.getTypeFactory();
$TS = rex.getTypeStore();
$RTF = rex.getRascalTypeFactory();
rex.setModule(this);
$TRAVERSE = rex.getTraverse();
Rascal_TRUE = $RVF.bool(true);
Rascal_FALSE = $RVF.bool(false);
$failReturnFromVoidException = new FailReturnFromVoidException();
}
protected final IConstructor $reifiedAType(IConstructor t, IMap definitions) {
return $RVF.reifiedType(t, definitions);
}
/**
* $testSetup(getClass()) is called by the constructors of all generated test classes.
* The method provides the context for the test to succeed:
*
* 1. project:// scheme for the current project under test
* 2. target:// scheme for the current project under test
*
* Test functions can then use `|project://project-name/path/to/test.csv|`,
* for example, to retrieve data or source code as input values.
*
* @param classUnderTest is used to find the root of the project, starting
* typically from target/classes/ClassUnderTest.class and looking for
* the META-INF/RASCAL.MF file or the pom.xml file of the project.
*/
protected void $testSetup(Class<?> classUnderTest) {
try {
var reg = URIResolverRegistry.getInstance();
var root = PathConfig.inferProjectRoot(classUnderTest);
var dirName = URIUtil.getLocationName(root);
var projectName = new RascalManifest().getProjectName(root);
if (!projectName.isEmpty() && !dirName.equals(projectName)) {
var msg = "Project name in RASCAL.MF (" + projectName + ") must be equal to directory name (" + dirName;
$ERRWRITER.println(msg);
throw new IllegalArgumentException(msg);
}
var prj = URIUtil.correctLocation("project", projectName, "");
if (!reg.exists(prj)) {
reg.registerLogical(new ProjectURIResolver(root, projectName));
reg.registerLogical(new TargetURIResolver(root, projectName));
}
}
catch (IOException e) {
$ERRWRITER.println("Test setup failed: " + e.getMessage());
}
}
@SuppressWarnings("unchecked")
protected <T> T $initLibrary(String className) {
PrintWriter[] outputs = new PrintWriter[] { $OUTWRITER, $ERRWRITER };
int writers = 0;
try{
Class<?> clazz = getClass().getClassLoader().loadClass(className);
if (clazz.getConstructors().length > 1) {
throw new IllegalArgumentException("Rascal JavaBridge can only deal with one constructor. This class has multiple: " + clazz);
}
Constructor<?>[] constructors = clazz.getConstructors();
if (constructors.length < 1) {
throw new JavaMethodLink(className, "no public constructors found", new IllegalArgumentException(className));
}
else if (constructors.length != 1) {
throw new JavaMethodLink(className, "more than one public constructor found", new IllegalArgumentException(className));
}
Constructor<?> constructor = constructors[0];
Object[] args = new Object[constructor.getParameterCount()];
Class<?>[] formals = constructor.getParameterTypes();
for (int i = 0; i < constructor.getParameterCount(); i++) {
if (formals[i].isAssignableFrom(IRascalValueFactory.class)) {
args[i] = $RVF;
}
else if (formals[i].isAssignableFrom(IValueFactory.class)) {
args[i] = $RVF;
}
else if (formals[i].isAssignableFrom(RascalSearchPath.class)) {
// we set an empty dummy because in the compiled context,
// there is no Rascal search path.
args[i] = new RascalSearchPath();
}
else if (formals[i].isAssignableFrom(TypeStore.class)) {
args[i] = $TS;
}
else if (formals[i].isAssignableFrom(TypeFactory.class)) {
args[i] = TypeFactory.getInstance();
}
else if (formals[i].isAssignableFrom(PrintWriter.class)) {
args[i] = outputs[writers++ % 2];
}
else if (formals[i].isAssignableFrom(Reader.class)) {
args[i] = $IN;
}
else if (formals[i].isAssignableFrom(IRascalMonitor.class)) {
args[i] = $MONITOR;
}
else if (formals[i].isAssignableFrom(ClassLoader.class)) {
// TODO: the classloaders have to become configurable later
args[i] = getClass().getClassLoader();
}
else if (formals[i].isAssignableFrom(IRascalValueFactory.class)) {
args[i] = $RVF;
}
else if (formals[i].isAssignableFrom($RascalModule.class)) {
args[i] = this;
}
else if (formals[i].isAssignableFrom(IDEServices.class)) {
if ($MONITOR instanceof IDEServices) {
args[i] = (IDEServices) $MONITOR;
}
else {
throw new IllegalArgumentException("No IDE services are available in this environment");
}
}
else if (formals[i].isAssignableFrom(IResourceLocationProvider.class)) {
// We provide resources directly from the run-time classpath of the current module.
// This means that test-resources must be copied to the test target or the target folder
// before we run this code.
args[i] = new IResourceLocationProvider() {
@Override
public Set<ISourceLocation> findResources(String fileName) {
Set<ISourceLocation> result = new HashSet<>();
try {
for (URL found : Collections.list(getClass().getClassLoader().getResources(fileName))) {
try {
result.add($RVF.sourceLocation(found.toURI()));
} catch (URISyntaxException e) {
$MONITOR.warning("WARNING: skipping " + found + " due to URI syntax exception", URIUtil.rootLocation("module-init"));
}
}
}
catch (IOException e) {
// then we don't have anything. it could happens if the folder or jar of the currently running code has
// dissappeared while running the code in it.
}
return result;
}
};
}
else {
throw new IllegalArgumentException(constructor + " has unknown arguments. Only IValueFactory, TypeStore, ClassLoader, PrintWriter, OutputStream, InputStream, &T extends $RascalModule, IRascalValueFactory, TypeFactory and IResourceLocationProvider are supported");
}
}
return (T) constructor.newInstance(args);
}
catch (ClassNotFoundException | NoClassDefFoundError | IllegalArgumentException | InstantiationException | IllegalAccessException | InvocationTargetException | SecurityException e) {
throw new JavaMethodLink(className, e.getMessage(), e);
}
}
private static void $usage(String module, String error, Type kwargs) {
PrintWriter $ERR = new PrintWriter(System.err);
if (!error.isEmpty() && !error.equals("help")) {
$ERR.println(error);
}
$ERR.println("Usage: ");
$ERR.println("java -cp ... " + module + " <options>");
if (kwargs.getArity() > 0) {
$ERR.println(" [options]\n\nOptions:\n");
for (String param : kwargs.getFieldNames()) {
$ERR.print("\t-");
$ERR.print(param);
if (kwargs.getFieldType(param).isSubtypeOf(TypeFactory.getInstance().boolType())) {
$ERR.println("\t[arg]: one of nothing (true), \'1\', \'0\', \'true\' or \'false\';");
}
else {
$ERR.println("\t[arg]: " + kwargs.getFieldType(param) + " argument;");
}
}
}
else {
$ERR.println('\n');
}
$ERR.flush();
if (!error.equals("help")) {
throw new IllegalArgumentException();
}
}
protected static Map<String, IValue> $parseCommandlineParameters(String module, String[] commandline, Type kwTypes) {
// reusing the same commandline parameter parser that the interpreter uses, based on the keyword parameter types
// of the function type of the `main` function.
try (PrintWriter writer = new PrintWriter(System.out)) {
// TODO: rather get this writer from the RascalExecutionContext, but the surrounding method is static still. FIXME.
return new CommandlineParser(writer).parseKeywordCommandLineArgs(module, commandline, kwTypes);
}
}
// ---- utility methods ---------------------------------------------------
protected final IMap $buildMap(final IValue...values){
IMapWriter w = $RVF.mapWriter();
if(values.length % 2 != 0) throw new InternalCompilerError("$RascalModule: buildMap should have even number of arguments");
for(int i = 0; i < values.length; i += 2) {
w.put(values[i], values[i+1]);
}
return w.done();
}
protected final boolean $intersectsType(Type t1, Type t2) {
return t1.intersects(t2);
}
protected final boolean $isComparable(Type t1, Type t2) {
return $isSubtypeOf(t1, t2) || $isSubtypeOf(t2, t1);
}
// private final boolean checkRightValueOrParam(Type left, Type right) {
// if(right.isTop()) {
// return true;
// }
// if(right.isParameter()) {
// return $isSubtypeOf(left, right.getBound());
// }
// return false;
// }
//TODO: consider caching this method
protected final boolean $isSubtypeOf(Type left, Type right) {
// TODO the following should be handled in ordinary isSubTypeOf in NonTerminalType
if(left instanceof NonTerminalType && (right instanceof NonTerminalType)){
NonTerminalType leftNT = (NonTerminalType) left;
IConstructor leftSym = leftNT.getSymbol();
NonTerminalType rightNT = (NonTerminalType) right;
IConstructor rightSym = rightNT.getSymbol();
if(SymbolAdapter.isStartSort(leftSym)){
leftSym = SymbolAdapter.getStart(leftSym);
return leftSym.equals(rightSym);
}
if(SymbolAdapter.isStartSort(rightSym)){
rightSym = SymbolAdapter.getStart(rightSym);
return leftSym.equals(rightSym);
}
}
return left.isSubtypeOf(right);
}
public boolean $isTreeProductionEqual(IValue tree, IConstructor production) {
if(!(tree instanceof ITree)) return false;
ITree itree = (ITree) tree;
return itree.isAppl() ? production.equals(itree.getProduction()) : false;
}
public boolean $isNonTerminal(Type treeType, IConstructor expected) {
return treeType instanceof NonTerminalType && (((NonTerminalType) treeType).getSymbol().equals(expected));
}
public boolean $isNonTerminal(Type treeType, Type expected) {
// TODO: this is an inefficient test, but it does unify parameterized ADTs, sorts and lexes.
if(treeType == expected) return true;
if(treeType instanceof NonTerminalType) {
NonTerminalType givenNT = (NonTerminalType) treeType;
if(expected instanceof NonTerminalType){
NonTerminalType expectedNT = (NonTerminalType) expected;
return givenNT.getSymbol().equals(expectedNT.getSymbol());
} else {
String lname = ((IConstructor) givenNT.getSymbol().getChildren()).get(0).toString();
lname = lname.substring(1,lname.length()-1); // remove quotes
String rname = expected.getName();
return lname.equals(rname);
}
}
return false;
}
public io.usethesource.vallang.type.Type $adt(String adtName){
Type adtType = $TF.abstractDataType($TS, adtName);
return adtType;
}
public io.usethesource.vallang.type.Type $parameterizedAdt(String adtName, Type[] params){
return $TF.abstractDataType($TS, adtName, params);
}
public io.usethesource.vallang.type.Type $sort(String adtName){
return $RTF.nonTerminalType($RVF.constructor(RascalValueFactory.Symbol_Sort, $RVF.string(adtName)));
}
public io.usethesource.vallang.type.Type $parameterizedSort(String adtName, Type[] parameters, IList bindings) {
return $RTF.nonTerminalType($RVF.constructor(RascalValueFactory.Symbol_ParameterizedSort, $VF.string(adtName), bindings));
}
public io.usethesource.vallang.type.Type $parameterizedLex(String adtName, Type[] parameters, IList bindings) {
return $RTF.nonTerminalType($RVF.constructor(RascalValueFactory.Symbol_ParameterizedLex, $VF.string(adtName), bindings));
}
public io.usethesource.vallang.type.Type $lex(String adtName){
return $RTF.nonTerminalType($RVF.constructor(RascalValueFactory.Symbol_Lex, $RVF.string(adtName)));
}
public io.usethesource.vallang.type.Type $layouts(String adtName){
return $RTF.nonTerminalType($RVF.constructor(RascalValueFactory.Symbol_Layouts, $RVF.string(adtName)));
}
public io.usethesource.vallang.type.Type $keywords(String adtName){
return $RTF.nonTerminalType($RVF.constructor(RascalValueFactory.Symbol_Keywords, $RVF.string(adtName)));
}
public io.usethesource.vallang.type.Type $parameterizedAdt(String adtName, Type[] tparams){
return $TF.abstractDataType($TS, adtName, tparams);
}
public io.usethesource.vallang.type.Type $parameterizedSort(String adtName, Type[] tparams, IList vparams){
return $RTF.nonTerminalType($RVF.constructor(RascalValueFactory.Symbol_ParameterizedSort, $RVF.string(adtName), vparams));
}
public io.usethesource.vallang.type.Type $parameterizedLex(String adtName, Type[] tparams, IList vparams){
return $RTF.nonTerminalType($RVF.constructor(RascalValueFactory.Symbol_ParameterizedLex, $RVF.string(adtName), vparams));
}
public IList readBinaryConstantsFile(Class<?> c, String path, int expected_length, String expected_md5Hash) {
// The constants file has the structure: <int nconstants, str md5Hash, list[value] constants>
Type constantsFileType = $TF.tupleType($TF.integerType(), $TF.stringType(), $TF.listType($TF.valueType()));
ISourceLocation loc = null;
try {
URL url = c.getClassLoader().getResource(path);
if(url == null) {
throw RuntimeExceptionFactory.io($RVF.string("Cannot find resource " + path));
}
loc = $RVF.sourceLocation(url.toURI());
} catch (URISyntaxException e) {
System.err.println("readBinaryConstantsFile: " + path + " throws " + e.getMessage());
}
try (IValueInputStream in = constructValueReader(loc)) {
IValue constantsFile = in.read();;
if(constantsFile.getType().isSubtypeOf(constantsFileType)){
ITuple tup = (ITuple)constantsFile;
int found_length = ((IInteger)tup.get(0)).intValue();
if(found_length != expected_length) {
throw RuntimeExceptionFactory.io($RVF.string("Expected " + expected_length + " constants, but only " + found_length + " found in " + path));
}
String found_hash = ((IString)tup.get(1)).getValue();
if(!found_hash.equals(expected_md5Hash)) {
throw RuntimeExceptionFactory.io($RVF.string("Expected md5Hash " + expected_md5Hash + ", but got " + found_hash + " for " + path));
}
IList lst = (IList) tup.get(2);
for(int i = 0; i < found_length; i++){
IValue cnst = lst.get(i);
if(cnst.getType().isConstructor()){
IConstructor cons = (IConstructor) cnst;
System.err.println(i + ": " + cons + ", " + cons.getConstructorType());
}
}
return (IList) tup.get(2);
} else {
throw RuntimeExceptionFactory.io($RVF.string("Requested type " + constantsFileType + ", but found " + constantsFile.getType()));
}
}
catch (IOException e) {
System.err.println("readBinaryConstantsFile: " + loc + " throws " + e.getMessage());
throw RuntimeExceptionFactory.io(e);
}
catch (Exception e) {
System.err.println("readBinaryConstantsFile: " + loc + " throws " + e.getMessage());
throw RuntimeExceptionFactory.io($RVF.string(e.getMessage()));
}
}
private IValueInputStream constructValueReader(ISourceLocation loc) throws IOException {
URIResolverRegistry registry = URIResolverRegistry.getInstance();
if (registry.supportsReadableFileChannel(loc)) {
FileChannel channel = registry.getReadableFileChannel(loc);
if (channel != null) {
return new IValueInputStream(channel, $RVF, TYPE_STORE_SUPPLIER);
}
}
return new IValueInputStream(registry.getInputStream(loc), $RVF, TYPE_STORE_SUPPLIER);
}
/*************************************************************************/
/* Rascal primitives called by generated code */
/*************************************************************************/
protected final IInteger $aint_add_aint(final IInteger lhs, final IInteger rhs) {
return lhs.add(rhs);
}
protected final IReal $aint_add_areal(final IInteger lhs, final IReal rhs) {
return lhs.add(rhs);
}
protected final INumber $aint_add_arat(final IInteger lhs, final IRational rhs) {
return lhs.add(rhs);
}
protected final INumber $aint_add_anum(final IInteger lhs, final INumber rhs) {
return lhs.add(rhs);
}
protected final INumber $areal_add_aint(final IReal lhs, final IInteger rhs) {
return lhs.add(rhs);
}
protected final IReal $areal_add_areal(final IReal lhs, final IReal rhs) {
return lhs.add(rhs);
}
protected final INumber $areal_add_arat(final IReal lhs, final IRational rhs) {
return lhs.add(rhs);
}
protected final INumber $areal_add_anum(final IReal lhs, final INumber rhs) {
return lhs.add(rhs);
}
protected final INumber $arat_add_aint(final IRational lhs, final IInteger rhs) {
return lhs.add(rhs);
}
protected final INumber $arat_add_areal(final IRational lhs, final IReal rhs) {
return lhs.add(rhs);
}
protected final IRational $arat_add_arat(final IRational lhs, final IRational rhs) {
return lhs.add(rhs);
}
protected final INumber $arat_add_anum(final IRational lhs, final INumber rhs) {
return lhs.add(rhs);
}
protected final INumber $anum_add_aint(final INumber lhs, final IInteger rhs) {
return lhs.add(rhs);
}
protected final INumber $anum_add_areal(final INumber lhs, final IReal rhs) {
return lhs.add(rhs);
}
protected final INumber $anum_add_arat(final INumber lhs, final IRational rhs) {
return lhs.add(rhs);
}
protected final INumber $anum_add_anum(final INumber lhs, final INumber rhs) {
return lhs.add(rhs);
}
protected final IString $astr_add_astr(final IString lhs, final IString rhs) {
return lhs.concat(rhs);
}
protected final ISourceLocation $aloc_add_astr(final ISourceLocation sloc, final IString s) {
String path = sloc.hasPath() ? sloc.getPath() : "";
if(!path.endsWith(URIUtil.URI_PATH_SEPARATOR)){
path = path + URIUtil.URI_PATH_SEPARATOR;
}
path = path.concat(s.getValue());
return $aloc_field_update("path", $RVF.string(path), sloc);
}
protected final ITuple $atuple_add_atuple(final ITuple t1, final ITuple t2) {
int len1 = t1.arity();
int len2 = t2.arity();
IValue elems[] = new IValue[len1 + len2];
for(int i = 0; i < len1; i++)
elems[i] = t1.get(i);
for(int i = 0; i < len2; i++)
elems[len1 + i] = t2.get(i);
return $RVF.tuple(elems);
}
protected final IList $alist_add_alist(final IList lhs, final IList rhs) {
return lhs.concat(rhs);
}
protected final IList $alist_add_elm(final IList lhs, final IValue rhs) {
return lhs.append(rhs);
}
protected final IList $elm_add_alist(final IValue lhs, final IList rhs) {
return rhs.insert(lhs);
}
protected final ISet $aset_add_aset(final ISet lhs, final ISet rhs) {
return lhs.union(rhs);
}
protected final ISet $aset_add_elm(final ISet lhs, final IValue rhs) {
return lhs.insert(rhs);
}
protected final ISet $elm_add_aset(final IValue lhs, final ISet rhs) {
return rhs.insert(lhs);
}
protected final IMap $amap_add_amap(final IMap lhs, final IMap rhs) {
return lhs.join(rhs);
}
// ---- annotation_get ----------------------------------------------------
protected final IValue $annotation_get(final IConstructor cons, final String fieldName) {
if(cons.asWithKeywordParameters().hasParameter(fieldName)) {
return cons.asWithKeywordParameters().getParameter(fieldName);
}
throw RuntimeExceptionFactory.noSuchAnnotation(fieldName);
}
protected final IValue $annotation_get(final INode cons, final String fieldName) {
if(cons.asWithKeywordParameters().hasParameter(fieldName)) {
return cons.asWithKeywordParameters().getParameter(fieldName);
}
throw RuntimeExceptionFactory.noSuchAnnotation(fieldName);
}
protected final GuardedIValue $guarded_annotation_get(final IConstructor cons, final String fieldName) {
if(cons.asWithKeywordParameters().hasParameter(fieldName)) {
return new GuardedIValue(cons.asWithKeywordParameters().getParameter(fieldName));
}
// Type consType = cons.getType();
// Map<String, Type> kwps = $TS.getKeywordParameters(consType);
if(TreeAdapter.isTree(cons) && TreeAdapter.isAppl((ITree) cons)) {
// TODO: keyword parameter of Tree
IConstructor prod = ((ITree) cons).getProduction();
for(IValue elem : ProductionAdapter.getSymbols(prod)) {
IConstructor arg = (IConstructor) elem;
if (SymbolAdapter.isLabel(arg) && SymbolAdapter.getLabel(arg).equals(fieldName)) {
return new GuardedIValue(arg);
}
}
}
return UNDEFINED;
}
protected final GuardedIValue $guarded_annotation_get(final INode cons, final String fieldName) {
if(cons.asWithKeywordParameters().hasParameter(fieldName)) {
return new GuardedIValue(cons.asWithKeywordParameters().getParameter(fieldName));
}
return UNDEFINED;
}
// ---- assert_fails ------------------------------------------------------
protected final IBool $assert_fails(final IString message) {
throw RuntimeExceptionFactory.assertionFailed(message);
}
// ---- create ------------------------------------------------------------
protected final ISourceLocation $create_aloc(final IString uri) {
try {
return URIUtil.createFromURI(uri.getValue());
}
catch (URISyntaxException e) {
// this is actually an unexpected run-time exception since Rascal prevents you from
// creating non-encoded
throw RuntimeExceptionFactory.malformedURI(uri.getValue());
}
catch (UnsupportedOperationException e) {
throw RuntimeExceptionFactory.malformedURI(uri.getValue() + ":" + e.getMessage());
}
}
/**
* Create a loc with given offsets and length
*/
protected final ISourceLocation $create_aloc_with_offset(final ISourceLocation loc, final IInteger offset, final IInteger length) {
return $RVF.sourceLocation(loc, offset.intValue(), length.intValue());
}
protected final ISourceLocation $create_aloc_with_offset_and_begin_end(final ISourceLocation loc, final IInteger offset, final IInteger length, final ITuple begin, final ITuple end) {
int beginLine = ((IInteger) begin.get(0)).intValue();
int beginCol = ((IInteger) begin.get(1)).intValue();
int endLine = ((IInteger) end.get(0)).intValue();
int endCol = ((IInteger) end.get(1)).intValue();
return $RVF.sourceLocation(loc, offset.intValue(), length.intValue(), beginLine, endLine, beginCol, endCol);
}
protected final IInteger $aint_divide_aint(final IInteger a, final IInteger b) {
try {
return a.divide(b);
} catch(ArithmeticException e) {
throw RuntimeExceptionFactory.arithmeticException("divide by zero");
}
}
protected final INumber $aint_divide_areal(final IInteger a, final IReal b) {
try {
return a.multiply($RVF.real(1.0)).divide(b, $RVF.getPrecision());
} catch(ArithmeticException e) {
throw RuntimeExceptionFactory.arithmeticException("divide by zero");
}
}
protected final IRational $aint_divide_arat(final IInteger a, final IRational b) {
try {
return a.toRational().divide(b);
} catch(ArithmeticException e) {
throw RuntimeExceptionFactory.arithmeticException("divide by zero");
}
}
protected final INumber $aint_divide_anum(final IInteger a, final INumber b) {
try {
return a.multiply($RVF.real(1.0)).divide(b, $RVF.getPrecision());
} catch(ArithmeticException e) {
throw RuntimeExceptionFactory.arithmeticException("divide by zero");
}
}
protected final IReal $areal_divide_aint(final IReal a, final IInteger b) {
try {
return (IReal) a.divide(b, $RVF.getPrecision());
} catch(ArithmeticException e) {
throw RuntimeExceptionFactory.arithmeticException("divide by zero");
}
}
protected final IReal $areal_divide_areal(final IReal a, final IReal b) {
try {
return a.divide(b, $RVF.getPrecision());
} catch(ArithmeticException e) {
throw RuntimeExceptionFactory.arithmeticException("divide by zero");
}
}
protected final IReal $areal_divide_arat(IReal a, IRational b) {
try {
return (IReal) a.divide(b, $RVF.getPrecision());
} catch(ArithmeticException e) {
throw RuntimeExceptionFactory.arithmeticException("divide by zero");
}
}
protected final INumber $areal_divide_anum(final IReal a, final INumber b) {
try {
return a.divide(b, $RVF.getPrecision());
} catch(ArithmeticException e) {
throw RuntimeExceptionFactory.arithmeticException("divide by zero");
}
}
protected final IRational $arat_divide_aint(final IRational a, final IInteger b) {
try {
return a.divide(b);
} catch(ArithmeticException e) {
throw RuntimeExceptionFactory.arithmeticException("divide by zero");
}
}
protected final IReal $arat_divide_areal(final IRational a, final IReal b) {
try {
return a.multiply($RVF.real(1.0)).divide(b, $RVF.getPrecision());
} catch(ArithmeticException e) {
throw RuntimeExceptionFactory.arithmeticException("divide by zero");
}
}
protected final IRational $arat_divide_arat(final IRational a, final IRational b) {
try {
return a.toRational().divide(b);
} catch(ArithmeticException e) {
throw RuntimeExceptionFactory.arithmeticException("divide by zero");
}
}
protected final INumber $arat_divide_anum(final IRational a, final INumber b) {
try {
return a.multiply($RVF.real(1.0)).divide(b, $RVF.getPrecision());
} catch(ArithmeticException e) {
throw RuntimeExceptionFactory.arithmeticException("divide by zero");
}
}
protected final INumber $anum_divide_aint(final INumber a, final IInteger b) {
try {
return a.divide(b, $RVF.getPrecision());
} catch(ArithmeticException e) {
throw RuntimeExceptionFactory.arithmeticException("divide by zero");
}
}
protected final INumber $anum_divide_areal(final INumber a, final IReal b) {
try {
return a.divide(b, $RVF.getPrecision());
} catch(ArithmeticException e) {
throw RuntimeExceptionFactory.arithmeticException("divide by zero");
}
}
protected final INumber $anum_divide_arat(final INumber a, final IRational b) {
try {
return a.divide(b, $RVF.getPrecision());
} catch(ArithmeticException e) {
throw RuntimeExceptionFactory.arithmeticException("divide by zero");
}
}
protected final INumber $anum_divide_anum(final INumber a, final INumber b) {
try {
return a.divide(b, $RVF.getPrecision());
} catch(ArithmeticException e) {
throw RuntimeExceptionFactory.arithmeticException("divide by zero");
}
}
// ---- equal -------------------------------------------------------------
protected final IBool $equal(final IValue left, final IValue right) {
Type leftType = left.getType();
Type rightType = right.getType();
if (leftType.isSubtypeOf($TF.numberType()) && rightType.isSubtypeOf($TF.numberType())) {
return ((INumber)left).equal((INumber)right);
} else if(leftType.isNode() && rightType.isNode()){
return ((INode) left).equals((INode) right) ? Rascal_TRUE : Rascal_FALSE;
} else if(left instanceof ITree && right instanceof ITree) {
return $RVF.bool(left.equals(right)); // use match to ignore "src" keyword parameters in trees
} else {
return $RVF.bool(left.equals(right));
}
}
// ---- get name ----------------------------------------------------------
protected final IString $anode_get_name(final INode nd) {
return $RVF.string(nd.getName());
}
// ---- get_field ---------------------------------------------------------
protected final IValue $anode_get_field(final INode nd, final String fieldName) {
IValue res = nd.asWithKeywordParameters().getParameter(fieldName);
if(res != null) {
return res;
}
if(nd instanceof IConstructor) {
IConstructor c = (IConstructor) nd;
if(c.has(fieldName)) {
return c.get(fieldName);
}
IValue res1 = c.asWithKeywordParameters().getParameter(fieldName);
if(res1 != null) {
return res1;
}
}
throw RuntimeExceptionFactory.noSuchField(fieldName);
}
protected final GuardedIValue $guarded_anode_get_field(final INode nd, final String fieldName) {
try {
IValue result = $anode_get_field(nd, fieldName);
return new GuardedIValue(result);
} catch (RuntimeException e) {
return UNDEFINED;
}
}
protected final IValue $aadt_get_field(final IConstructor cons, final String fieldName) {
Type consType = cons.getConstructorType();
if(TreeAdapter.isTree(cons) && TreeAdapter.isAppl((ITree) cons)) {
FieldResult fldres = TreeAdapter.getLabeledField((ITree) cons, fieldName);
if(fldres != null) {
ITree res = TreeAdapter.getLabeledField((ITree) cons, fieldName).tree;
if(res != null) {
return res;
}
}
}
// Does fieldName exist as positional field?
if(consType.hasField(fieldName)){
IValue res = cons.get(fieldName);
return res;
}
IValue result = cons.asWithKeywordParameters().getParameter(fieldName);
if(result != null) {
return result;
}
throw RuntimeExceptionFactory.noSuchField(fieldName);
}
protected final GuardedIValue $guarded_aadt_get_field(final IConstructor cons, final String fieldName) {
try {
IValue result = $aadt_get_field(cons, fieldName);
return new GuardedIValue(result);
} catch (RuntimeException e) {
return UNDEFINED;
}
}
protected final IValue $aloc_get_field(final ISourceLocation sloc, final String field) {
IValue v;
switch (field) {
case "scheme":
String s = sloc.getScheme();
v = $RVF.string(s == null ? "" : s);
break;
case "authority":
v = $RVF.string(sloc.hasAuthority() ? sloc.getAuthority() : "");
break;
case "host":
if (!URIResolverRegistry.getInstance().supportsHost(sloc)) {
throw RuntimeExceptionFactory.noSuchField("The scheme " + sloc.getScheme() + " does not support the host field, use authority instead.");
}
s = sloc.getURI().getHost();
v = $RVF.string(s == null ? "" : s);
break;
case "path":
v = $RVF.string(sloc.hasPath() ? sloc.getPath() : URIUtil.URI_PATH_SEPARATOR);
break;
case "parent":
String path = sloc.getPath();
if (path.equals("") || path.equals(URIUtil.URI_PATH_SEPARATOR)) {
throw RuntimeExceptionFactory.noParent(sloc);
}
// remove one or more /'s at the end
while (path.endsWith(URIUtil.URI_PATH_SEPARATOR)) {
path = path.substring(0, path.length() - URIUtil.URI_PATH_SEPARATOR.length());
}
int i = path.lastIndexOf(URIUtil.URI_PATH_SEPARATOR);
if (i != -1) {
path = path.substring(0, i);
if (sloc.getScheme().equalsIgnoreCase("file")) {
// there is a special case for file references to windows paths.
// the root path should end with a / (c:/ not c:)
if (path.lastIndexOf(URIUtil.URI_PATH_SEPARATOR) == 0 && path.endsWith(":")) {