-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy pathEvaluator.java
More file actions
executable file
·1959 lines (1665 loc) · 67.6 KB
/
Evaluator.java
File metadata and controls
executable file
·1959 lines (1665 loc) · 67.6 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) 2009-2015 CWI
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* *
* * Jurgen J. Vinju - Jurgen.Vinju@cwi.nl - CWI
* * Tijs van der Storm - Tijs.van.der.Storm@cwi.nl
* * Emilie Balland - (CWI)
* * Anya Helene Bagge - anya@ii.uib.no (Univ. Bergen)
* * Paul Klint - Paul.Klint@cwi.nl - CWI
* * Mark Hills - Mark.Hills@cwi.nl (CWI)
* * Arnold Lankamp - Arnold.Lankamp@cwi.nl
* * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI
*******************************************************************************/
package org.rascalmpl.interpreter;
import static org.rascalmpl.semantics.dynamic.Import.parseFragments;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.SortedMap;
import java.util.Stack;
import java.util.TreeMap;
import java.util.concurrent.CopyOnWriteArrayList;
import org.rascalmpl.ast.AbstractAST;
import org.rascalmpl.ast.Command;
import org.rascalmpl.ast.Commands;
import org.rascalmpl.ast.Declaration;
import org.rascalmpl.ast.EvalCommand;
import org.rascalmpl.ast.Name;
import org.rascalmpl.ast.QualifiedName;
import org.rascalmpl.ast.Statement;
import org.rascalmpl.debug.AbstractInterpreterEventTrigger;
import org.rascalmpl.debug.IRascalFrame;
import org.rascalmpl.debug.IRascalMonitor;
import org.rascalmpl.debug.IRascalRuntimeInspection;
import org.rascalmpl.debug.IRascalSuspendTrigger;
import org.rascalmpl.debug.IRascalSuspendTriggerListener;
import org.rascalmpl.debug.NullRascalMonitor;
import org.rascalmpl.exceptions.ImplementationError;
import org.rascalmpl.exceptions.StackTrace;
import org.rascalmpl.ideservices.IDEServices;
import org.rascalmpl.interpreter.asserts.NotYetImplemented;
import org.rascalmpl.interpreter.callbacks.IConstructorDeclared;
import org.rascalmpl.interpreter.control_exceptions.Failure;
import org.rascalmpl.interpreter.control_exceptions.Insert;
import org.rascalmpl.interpreter.control_exceptions.MatchFailed;
import org.rascalmpl.interpreter.control_exceptions.Return;
import org.rascalmpl.interpreter.env.Environment;
import org.rascalmpl.interpreter.env.GlobalEnvironment;
import org.rascalmpl.interpreter.env.ModuleEnvironment;
import org.rascalmpl.interpreter.env.Pair;
import org.rascalmpl.interpreter.load.IRascalSearchPathContributor;
import org.rascalmpl.interpreter.load.RascalSearchPath;
import org.rascalmpl.interpreter.load.URIContributor;
import org.rascalmpl.interpreter.result.AbstractFunction;
import org.rascalmpl.interpreter.result.ICallableValue;
import org.rascalmpl.interpreter.result.OverloadedFunction;
import org.rascalmpl.interpreter.result.Result;
import org.rascalmpl.interpreter.result.ResultFactory;
import org.rascalmpl.interpreter.staticErrors.CommandlineError;
import org.rascalmpl.interpreter.staticErrors.UndeclaredFunction;
import org.rascalmpl.interpreter.staticErrors.UndeclaredVariable;
import org.rascalmpl.interpreter.staticErrors.UnguardedFail;
import org.rascalmpl.interpreter.staticErrors.UnguardedInsert;
import org.rascalmpl.interpreter.staticErrors.UnguardedReturn;
import org.rascalmpl.interpreter.utils.JavaBridge;
import org.rascalmpl.interpreter.utils.Names;
import org.rascalmpl.interpreter.utils.Profiler;
import org.rascalmpl.library.lang.rascal.syntax.RascalParser;
import org.rascalmpl.parser.ASTBuilder;
import org.rascalmpl.parser.Parser;
import org.rascalmpl.parser.ParserGenerator;
import org.rascalmpl.parser.gtd.io.InputConverter;
import org.rascalmpl.parser.gtd.result.action.IActionExecutor;
import org.rascalmpl.parser.gtd.result.out.DefaultNodeFlattener;
import org.rascalmpl.parser.gtd.result.out.INodeFlattener;
import org.rascalmpl.parser.uptr.UPTRNodeFactory;
import org.rascalmpl.parser.uptr.action.NoActionExecutor;
import org.rascalmpl.shell.CommandlineParser;
import org.rascalmpl.uri.URIResolverRegistry;
import org.rascalmpl.uri.URIUtil;
import org.rascalmpl.values.RascalFunctionValueFactory;
import org.rascalmpl.values.functions.IFunction;
import org.rascalmpl.values.parsetrees.ITree;
import io.usethesource.vallang.IConstructor;
import io.usethesource.vallang.IInteger;
import io.usethesource.vallang.IList;
import io.usethesource.vallang.IMap;
import io.usethesource.vallang.ISet;
import io.usethesource.vallang.ISourceLocation;
import io.usethesource.vallang.IString;
import io.usethesource.vallang.IValue;
import io.usethesource.vallang.IValueFactory;
import io.usethesource.vallang.type.Type;
import io.usethesource.vallang.type.TypeFactory;
public class Evaluator implements IEvaluator<Result<IValue>>, IRascalSuspendTrigger, IRascalRuntimeInspection {
private final RascalFunctionValueFactory vf; // sharable
private static final TypeFactory tf = TypeFactory.getInstance(); // always shared
protected volatile Environment currentEnvt; // not sharable
private final GlobalEnvironment heap; // shareable if frozen
private final Configuration config = new Configuration();
/**
* True if an interrupt has been signalled and we should abort execution
*/
private volatile boolean interrupt = false;
/**
* State to manage call tracing
*/
private int callNesting = 0;
private boolean callTracing = false;
@Override
public int getCallNesting() {
return callNesting;
}
@Override
public boolean getCallTracing() {
return callTracing;
}
@Override
public void setCallTracing(boolean callTracing) {
this.callTracing = callTracing;
}
@Override
public void incCallNesting() {
callNesting++;
}
@Override
public void decCallNesting() {
callNesting--;
}
private JavaBridge javaBridge; // sharable if synchronized
/**
* Used in runtime error messages
*/
private AbstractAST currentAST;
/**
* Used in debugger exception handling
*/
private Exception currentException;
/**
* True if we're doing profiling
*/
private boolean doProfiling = false;
/**
* Track if we already started a profiler, to avoid starting duplicates after a callback to an eval function.
*/
private boolean profilerRunning = false;
/**
* This flag helps preventing non-terminating bootstrapping cycles. If
* it is set we do not allow loading of another nested Parser Generator.
*/
private boolean isBootstrapper = false;
private final TypeDeclarationEvaluator typeDeclarator; // not sharable
private final List<ClassLoader> classLoaders; // sharable if frozen
private final ModuleEnvironment rootScope; // sharable if frozen
private final PrintWriter defOutWriter;
private final PrintWriter defErrWriter;
private final Reader defInput;
private PrintWriter curOutWriter = null;
private PrintWriter curErrWriter = null;
private Reader curInput = null;
/**
* Probably not sharable
*/
private ITestResultListener testReporter;
/**
* To avoid null pointer exceptions, avoid passing this directly to other classes, use
* the result of getMonitor() instead.
*/
private IRascalMonitor monitor;
private AbstractInterpreterEventTrigger eventTrigger; // can this be shared?
private final List<IRascalSuspendTriggerListener> suspendTriggerListeners; // can this be shared?
private Stack<Accumulator> accumulators = new Stack<>(); // not sharable
private final Stack<IString> indentStack = new Stack<>(); // not sharable
private final RascalSearchPath rascalPathResolver; // sharable if frozen
private final URIResolverRegistry resolverRegistry; // sharable
private final Map<IConstructorDeclared,Object> constructorDeclaredListeners; // can this be shared?
private static final Object dummy = new Object();
/**
* Promotes the monitor to the PrintWriter automatically if so required.
*/
public Evaluator(IValueFactory f, Reader input, PrintWriter stderr, PrintWriter stdout, IRascalMonitor monitor, ModuleEnvironment scope, GlobalEnvironment heap) {
this(f, input, stderr, monitor instanceof PrintWriter ? (PrintWriter) monitor : stdout, scope, heap, new ArrayList<ClassLoader>(Collections.singleton(Evaluator.class.getClassLoader())), new RascalSearchPath());
}
/**
* If your monitor should wrap stdout (like TerminalProgressBarMonitor) then you can use this constructor.
*/
public <M extends PrintWriter & IRascalMonitor> Evaluator(IValueFactory f, Reader input, PrintWriter stderr, M monitor, ModuleEnvironment scope, GlobalEnvironment heap) {
this(f, input, stderr, monitor, scope, heap, new ArrayList<ClassLoader>(Collections.singleton(Evaluator.class.getClassLoader())), new RascalSearchPath());
setMonitor(monitor);
}
public Evaluator(IValueFactory f, Reader input, PrintWriter stderr, PrintWriter stdout, ModuleEnvironment scope, GlobalEnvironment heap, IRascalMonitor monitor) {
this(f, input, stderr, monitor instanceof PrintWriter ? (PrintWriter) monitor : stdout, scope, heap, new ArrayList<ClassLoader>(Collections.singleton(Evaluator.class.getClassLoader())), new RascalSearchPath());
setMonitor(monitor);
}
public Evaluator(IValueFactory vf, Reader input, PrintWriter stderr, PrintWriter stdout, ModuleEnvironment scope, GlobalEnvironment heap, List<ClassLoader> classLoaders, RascalSearchPath rascalPathResolver) {
super();
this.vf = new RascalFunctionValueFactory(this);
this.heap = heap;
this.typeDeclarator = new TypeDeclarationEvaluator(this);
this.currentEnvt = scope;
this.rootScope = scope;
heap.addModule(scope);
this.classLoaders = classLoaders;
this.javaBridge = new JavaBridge(classLoaders, vf, config);
this.rascalPathResolver = rascalPathResolver;
this.resolverRegistry = rascalPathResolver.getRegistry();
this.defInput = input;
this.defErrWriter = stderr;
this.defOutWriter = stdout;
this.constructorDeclaredListeners = new HashMap<IConstructorDeclared,Object>();
this.suspendTriggerListeners = new CopyOnWriteArrayList<IRascalSuspendTriggerListener>();
updateProperties();
if (stderr == null) {
throw new NullPointerException("stderr is null");
}
if (stdout == null) {
throw new NullPointerException("stdout is null");
}
// default event trigger to swallow events
setEventTrigger(AbstractInterpreterEventTrigger.newNullEventTrigger());
}
private Evaluator(Evaluator source, ModuleEnvironment scope) {
super();
// this.accumulators = source.accumulators;
// this.testReporter = source.testReporter;
this.vf = source.vf;
this.heap = source.heap;
this.typeDeclarator = new TypeDeclarationEvaluator(this);
// this is probably not OK
this.currentEnvt = scope;
this.rootScope = scope;
// this is probably not OK
heap.addModule(scope);
this.classLoaders = source.classLoaders;
// the Java bridge is probably sharable if its methods are synchronized
this.javaBridge = new JavaBridge(classLoaders, vf, config);
this.rascalPathResolver = source.rascalPathResolver;
this.resolverRegistry = source.resolverRegistry;
this.defInput = source.defInput;
this.defErrWriter = source.defErrWriter;
this.defOutWriter = source.defOutWriter;
this.constructorDeclaredListeners = new HashMap<IConstructorDeclared,Object>(source.constructorDeclaredListeners);
this.suspendTriggerListeners = new CopyOnWriteArrayList<IRascalSuspendTriggerListener>(source.suspendTriggerListeners);
updateProperties();
// default event trigger to swallow events
setEventTrigger(AbstractInterpreterEventTrigger.newNullEventTrigger());
}
public void resetJavaBridge() {
this.javaBridge = new JavaBridge(classLoaders, vf, config);
}
@Override
public IRascalMonitor setMonitor(IRascalMonitor monitor) {
if (monitor == this) {
return monitor;
}
interrupt = false;
IRascalMonitor old = this.monitor;
this.monitor = monitor;
return old;
}
@Override
public int jobEnd(String name, boolean succeeded) {
if (monitor != null)
return monitor.jobEnd(name, succeeded);
return 0;
}
@Override
public void endAllJobs() {
if (monitor != null) {
monitor.endAllJobs();
}
}
@Override
public void jobStep(String name, String msg, int inc) {
if (monitor != null)
monitor.jobStep(name, msg, inc);
}
@Override
public void jobStart(String name, int workShare, int totalWork) {
if (monitor != null)
monitor.jobStart(name, workShare, totalWork);
}
@Override
public void jobTodo(String name, int work) {
if (monitor != null)
monitor.jobTodo(name, work);
}
@Override
public boolean jobIsCanceled(String name) {
if(monitor == null)
return false;
else
return monitor.jobIsCanceled(name);
}
@Override
public void registerConstructorDeclaredListener(IConstructorDeclared iml) {
constructorDeclaredListeners.put(iml,dummy);
}
@Override
public void notifyConstructorDeclaredListeners() {
for (IConstructorDeclared iml : constructorDeclaredListeners.keySet()) {
if (iml != null) {
iml.handleConstructorDeclaredEvent();
}
}
constructorDeclaredListeners.clear();
getHeap().clearLookupChaches();
}
@Override
public List<ClassLoader> getClassLoaders() {
return Collections.unmodifiableList(classLoaders);
}
@Override
public ModuleEnvironment __getRootScope() {
return rootScope;
}
@Override
public PrintWriter getOutPrinter() {
return curOutWriter == null ? defOutWriter : curOutWriter;
}
@Override
public Reader getInput() {
return curInput == null ? defInput : curInput;
}
@Override
public TypeDeclarationEvaluator __getTypeDeclarator() {
return typeDeclarator;
}
@Override
public GlobalEnvironment __getHeap() {
return heap;
}
@Override
public void __setInterrupt(boolean interrupt) {
this.interrupt = interrupt;
}
@Override
public Stack<Accumulator> __getAccumulators() {
return accumulators;
}
@Override
public IValueFactory __getVf() {
return vf;
}
public static TypeFactory __getTf() {
return tf;
}
@Override
public JavaBridge __getJavaBridge() {
return javaBridge;
}
@Override
public void interrupt() {
__setInterrupt(true);
}
@Override
public boolean isInterrupted() {
return interrupt;
}
@Override
public PrintWriter getErrorPrinter() {
return curErrWriter == null ? defErrWriter : curErrWriter;
}
public void setTestResultListener(ITestResultListener l) {
testReporter = l;
}
public JavaBridge getJavaBridge() {
return javaBridge;
}
@Override
public RascalSearchPath getRascalResolver() {
return rascalPathResolver;
}
@Override
public void indent(IString n) {
indentStack.push(n);
}
@Override
public void unindent() {
indentStack.pop();
}
@Override
public IString getCurrentIndent() {
return indentStack.peek();
}
/**
* Call a Rascal function with a number of arguments
*
* @return either null if its a void function, or the return value of the
* function.
*/
@Override
public IValue call(IRascalMonitor monitor, String name, IValue... args) {
IRascalMonitor old = setMonitor(monitor);
try {
return call(name, args);
}
finally {
setMonitor(old);
}
}
@Override
public IValue call(String adt, String name, IValue... args) {
List<AbstractFunction> candidates = new LinkedList<>();
Type[] types = new Type[args.length];
int i = 0;
for (IValue v : args) {
types[i++] = v.getType();
}
getCurrentEnvt().getAllFunctions(name, candidates);
if (candidates.isEmpty()) {
throw new UndeclaredFunction(name, types, this, getCurrentAST());
}
List<AbstractFunction> filtered = new LinkedList<>();
for (AbstractFunction candidate : candidates) {
if (candidate.getReturnType().isAbstractData() && candidate.getReturnType().getName().equals(adt)) {
filtered.add(candidate);
}
}
if (filtered.isEmpty()) {
throw new UndeclaredFunction(adt + "::" + name, types, this, getCurrentAST());
}
ICallableValue func = new OverloadedFunction(name, filtered);
return func.call(getMonitor(), types, args, Collections.emptyMap()).getValue();
};
@Override
public IValue call(String name, IValue... args) {
return call(name, (Map<String,IValue>) null, args);
}
/**
* Call a Rascal function with a number of arguments
*
* @return either null if its a void function, or the return value of the
* function.
*/
@Override
public IValue call(IRascalMonitor monitor, String module, String name, IValue... args) {
IRascalMonitor old = setMonitor(monitor);
Environment oldEnv = getCurrentEnvt();
try {
ModuleEnvironment modEnv = getHeap().getModule(module);
setCurrentEnvt(modEnv);
return call(name, (Map<String,IValue>) null, args);
}
finally {
setMonitor(old);
setCurrentEnvt(oldEnv);
}
}
/**
* This function processes commandline parameters as they are typically passed
* to a Rascal/Java program running on the commandline (a list of strings).
*
* The strings are interpreted as follows. If the first character is a '-' or the first two are '--'
* then the string is the name of a keyword parameter of the main function. The type of the
* declared parameter is used to determine how to parse the next string or strings. Note that
* several strings in a row that do not start with '-' or '--' will be composed into a list or
* a set depending on the type of the respective keyword parameter.
*/
public IValue main(IRascalMonitor monitor, String module, String function, String[] commandline) {
IRascalMonitor old = setMonitor(monitor);
Environment oldEnv = getCurrentEnvt();
CommandlineParser parser = new CommandlineParser(getOutPrinter());
try {
ModuleEnvironment modEnv = getHeap().getModule(module);
setCurrentEnvt(modEnv);
Name name = Names.toName(function, modEnv.getCreatorLocation());
Result<IValue> func = getCurrentEnvt().getVariable(name);
if (func instanceof OverloadedFunction) {
OverloadedFunction overloaded = (OverloadedFunction) getCurrentEnvt().getVariable(name);
func = overloaded.getFunctions().get(0);
}
if (func == null) {
throw new UndeclaredVariable(function, name);
}
if (!(func instanceof AbstractFunction)) {
throw new UnsupportedOperationException("main should be function");
}
AbstractFunction main = (AbstractFunction) func;
if (main.getArity() == 1 && main.getFormals().getFieldType(0).isSubtypeOf(tf.listType(tf.stringType()))) {
return main.call(getMonitor(), new Type[] { tf.listType(tf.stringType()) },new IValue[] { parser.parsePlainCommandLineArgs(commandline)}, null).getValue();
}
else if (main.hasKeywordArguments() && main.getArity() == 0) {
if (main.getType().getFieldTypes().getArity() > 0) {
throw new CommandlineError("main function should only have keyword parameters.", main.getType().getKeywordParameterTypes(), module);
}
Map<String, IValue> args = parser.parseKeywordCommandLineArgs(module, commandline, func.getStaticType().getKeywordParameterTypes());
return main.call(getMonitor(), new Type[] { },new IValue[] {}, args).getValue();
}
else {
throw new CommandlineError("main function should either have one argument of type list[str], or keyword parameters", main.getType(), module);
}
}
catch (MatchFailed e) {
getOutPrinter().println("Main function should either have a list[str] as a single parameter like so: \'void main(list[str] args)\', or a set of keyword parameters with defaults like so: \'void main(bool myOption=false, str input=\"\")\'");
return null;
}
finally {
setMonitor(old);
setCurrentEnvt(oldEnv);
}
}
/**
* This function processes commandline parameters as if already parsed to a Map<String,IValue>.
*/
public IValue main(IRascalMonitor monitor, String module, String function, Map<String,IValue> args) {
IRascalMonitor old = setMonitor(monitor);
Environment oldEnv = getCurrentEnvt();
try {
ModuleEnvironment modEnv = getHeap().getModule(module);
setCurrentEnvt(modEnv);
Name name = Names.toName(function, modEnv.getCreatorLocation());
Result<IValue> func = getCurrentEnvt().getVariable(name);
if (func instanceof OverloadedFunction) {
OverloadedFunction overloaded = (OverloadedFunction) getCurrentEnvt().getVariable(name);
func = overloaded.getFunctions().get(0);
}
if (func == null) {
throw new UndeclaredVariable(function, name);
}
if (!(func instanceof AbstractFunction)) {
throw new UnsupportedOperationException("main should be function");
}
AbstractFunction main = (AbstractFunction) func;
if (main.hasKeywordArguments() && main.getArity() == 0) {
if (main.getType().getFieldTypes().getArity() > 0) {
throw new CommandlineError("main function should only have keyword parameters.", main.getType().getKeywordParameterTypes(), module);
}
return main.call(getMonitor(), new Type[] { },new IValue[] {}, args).getValue();
}
else {
throw new CommandlineError("main function should either have one argument of type list[str], or keyword parameters", main.getType(), module);
}
}
catch (MatchFailed e) {
getOutPrinter().println("Main function should either have a list[str] as a single parameter like so: \'void main(list[str] args)\', or a set of keyword parameters with defaults like so: \'void main(bool myOption=false, str input=\"\")\'");
return null;
}
finally {
setMonitor(old);
setCurrentEnvt(oldEnv);
}
}
@Override
public IValue call(String name, String module, Map<String, IValue> kwArgs, IValue... args) {
IRascalMonitor old = setMonitor(monitor);
Environment oldEnv = getCurrentEnvt();
try {
ModuleEnvironment modEnv = getHeap().getModule(module);
setCurrentEnvt(modEnv);
return call(name, kwArgs, args);
}
finally {
setMonitor(old);
setCurrentEnvt(oldEnv);
}
}
private IValue call(String name, Map<String,IValue> kwArgs, IValue... args) {
QualifiedName qualifiedName = Names.toQualifiedName(name, getCurrentEnvt().getCreatorLocation());
setCurrentAST(qualifiedName);
return call(qualifiedName, kwArgs, args);
}
@Override
public IValue call(QualifiedName qualifiedName, Map<String,IValue> kwArgs, IValue... args) {
ICallableValue func = (ICallableValue) getCurrentEnvt().getVariable(qualifiedName);
Type[] types = new Type[args.length];
int i = 0;
for (IValue v : args) {
types[i++] = v.getType();
}
if (func == null) {
throw new UndeclaredFunction(Names.fullName(qualifiedName), types, this, getCurrentAST());
}
return func.call(getMonitor(), types, args, kwArgs).getValue();
}
@Override
public IConstructor getGrammar(Environment env) {
ModuleEnvironment root = (ModuleEnvironment) env.getRoot();
return getParserGenerator().getGrammarFromModules(monitor, root.getName(), root.getSyntaxDefinition());
}
public IConstructor getExpandedGrammar(IRascalMonitor monitor, ISourceLocation uri) {
IRascalMonitor old = setMonitor(monitor);
try {
ParserGenerator pgen = getParserGenerator();
String main = uri.getAuthority();
ModuleEnvironment env = getHeap().getModule(main);
return pgen.getExpandedGrammar(monitor, main, env.getSyntaxDefinition());
}
finally {
setMonitor(old);
}
}
public ISet getNestingRestrictions(IRascalMonitor monitor, IConstructor g) {
IRascalMonitor old = setMonitor(monitor);
try {
ParserGenerator pgen = getParserGenerator();
return pgen.getNestingRestrictions(monitor, g);
}
finally {
setMonitor(old);
}
}
private volatile ParserGenerator parserGenerator;
public ParserGenerator getParserGenerator() {
if (parserGenerator == null ){
if (isBootstrapper()) {
throw new ImplementationError("Cyclic bootstrapping is occurring, probably because a module in the bootstrap dependencies is using the concrete syntax feature.");
}
Evaluator self = this;
synchronized (self) {
if (parserGenerator == null) {
parserGenerator = new ParserGenerator(getMonitor(), (monitor instanceof PrintWriter) ? (PrintWriter)monitor : getErrorPrinter(), getValueFactory(), config);
}
}
}
return parserGenerator;
}
@Override
public void setCurrentAST(AbstractAST currentAST) {
this.currentAST = currentAST;
}
@Override
public AbstractAST getCurrentAST() {
return currentAST;
}
public Exception getCurrentException() {
return currentException;
}
public void addRascalSearchPathContributor(IRascalSearchPathContributor contrib) {
rascalPathResolver.addPathContributor(contrib);
}
public void addRascalSearchPath(final ISourceLocation uri) {
rascalPathResolver.addPathContributor(new URIContributor(uri));
}
public void addClassLoader(ClassLoader loader) {
// later loaders have precedence
classLoaders.add(0, loader);
}
@Override
public StackTrace getStackTrace() {
StackTrace trace = new StackTrace();
Environment env = currentEnvt;
while (env != null) {
trace.add(env.getCreatorLocation(), env.getName());
env = env.getCallerScope();
}
return trace.freeze();
}
/**
* Evaluate a statement
*
* Note, this method is not supposed to be called within another overriden
* eval(...) method, because it triggers and idle event after evaluation is
* done.
*
* @param stat
* @return
*/
@Override
public Result<IValue> eval(Statement stat) {
__setInterrupt(false);
try {
Profiler profiler = null;
if (doProfiling && !profilerRunning) {
profiler = new Profiler(this);
profiler.start();
profilerRunning = true;
}
currentAST = stat;
try {
return stat.interpret(this);
} finally {
if (profiler != null) {
profiler.pleaseStop();
profiler.report();
profilerRunning = false;
}
getEventTrigger().fireIdleEvent();
endAllJobs();
}
}
catch (Return e) {
throw new UnguardedReturn(stat);
}
catch (Failure e) {
throw new UnguardedFail(stat, e);
}
catch (Insert e) {
throw new UnguardedInsert(stat);
}
}
/**
* Parse and evaluate a command in the current execution environment
*
* Note, this method is not supposed to be called within another overriden
* eval(...) method, because it triggers and idle event after evaluation is
* done.
*
* @param command
* @return
*/
@Override
public Result<IValue> eval(IRascalMonitor monitor, String command, ISourceLocation location) {
IRascalMonitor old = setMonitor(monitor);
try {
return eval(command, location);
}
finally {
endAllJobs();
setMonitor(old);
getEventTrigger().fireIdleEvent();
}
}
/**
* Parse and evaluate a command in the current execution environment
*
* Note, this method is not supposed to be called within another overriden
* eval(...) method, because it triggers and idle event after evaluation is
* done.
*
* @param command
* @return
*/
@Override
public Result<IValue> evalMore(IRascalMonitor monitor, String commands, ISourceLocation location) {
IRascalMonitor old = setMonitor(monitor);
try {
return evalMore(commands, location);
}
finally {
endAllJobs();
setMonitor(old);
getEventTrigger().fireIdleEvent();
}
}
private Result<IValue> eval(String command, ISourceLocation location) throws ImplementationError {
__setInterrupt(false);
IActionExecutor<ITree> actionExecutor = new NoActionExecutor();
ITree tree = new RascalParser().parse(Parser.START_COMMAND, location.getURI(), command.toCharArray(), INodeFlattener.UNLIMITED_AMB_DEPTH, actionExecutor, new DefaultNodeFlattener<IConstructor, ITree, ISourceLocation>(), new UPTRNodeFactory(false));
if (!noBacktickOutsideStringConstant(command)) {
ModuleEnvironment curMod = getCurrentModuleEnvironment();
IFunction parsers = parserForCurrentModule(vf, curMod);
tree = org.rascalmpl.semantics.dynamic.Import.parseFragments(vf, getMonitor(), parsers, tree, location, getCurrentModuleEnvironment());
}
Command stat = new ASTBuilder().buildCommand(tree);
if (stat == null) {
throw new ImplementationError("Disambiguation failed: it removed all alternatives");
}
return eval(stat);
}
private IFunction parserForCurrentModule(RascalFunctionValueFactory vf, ModuleEnvironment curMod) {
IConstructor dummy = vf.constructor(RascalFunctionValueFactory.Symbol_Empty); // I just need _any_ ok non-terminal
IMap syntaxDefinition = curMod.getSyntaxDefinition();
IMap grammar = (IMap) getParserGenerator().getGrammarFromModules(getMonitor(), curMod.getName(), syntaxDefinition).get("rules");
IConstructor reifiedType = vf.reifiedType(dummy, grammar);
return vf.parsers(reifiedType, vf.bool(false), vf.integer(INodeFlattener.UNLIMITED_AMB_DEPTH), vf.bool(false), vf.integer(0), vf.integer(0), vf.bool(false), vf.bool(false), vf.set());
}
private Result<IValue> evalMore(String command, ISourceLocation location)
throws ImplementationError {
__setInterrupt(false);
ITree tree;
IActionExecutor<ITree> actionExecutor = new NoActionExecutor();
tree = new RascalParser().parse(Parser.START_COMMANDS, location.getURI(), command.toCharArray(), INodeFlattener.UNLIMITED_AMB_DEPTH, actionExecutor, new DefaultNodeFlattener<IConstructor, ITree, ISourceLocation>(), new UPTRNodeFactory(false));
if (!noBacktickOutsideStringConstant(command)) {
IFunction parsers = parserForCurrentModule(vf, getCurrentModuleEnvironment());
tree = org.rascalmpl.semantics.dynamic.Import.parseFragments(vf, getMonitor(), parsers, tree, location, getCurrentModuleEnvironment());
}
Commands stat = new ASTBuilder().buildCommands(tree);
if (stat == null) {
throw new ImplementationError("Disambiguation failed: it removed all alternatives");
}
return eval(stat);
}
/*
* This is dangereous, since inside embedded concrete fragments there may be unbalanced
* double quotes as well as unbalanced backticks. For now it is a workaround that prevents
* generation of parsers when some backtick is inside a string constant.
*/
private boolean noBacktickOutsideStringConstant(String command) {
boolean instring = false;
byte[] b = command.getBytes();
for (int i = 0; i < b.length; i++) {
if (b[i] == '\"') {
instring = !instring;
}
else if (!instring && b[i] == '`') {
return false;
}
}
return true;
}
@Override
public ITree parseCommand(IRascalMonitor monitor, String command, ISourceLocation location) {
IRascalMonitor old = setMonitor(monitor);
try {
return parseCommand(command, location);
}
finally {
setMonitor(old);
}
}
private ITree parseCommand(String command, ISourceLocation location) {
__setInterrupt(false);
IActionExecutor<ITree> actionExecutor = new NoActionExecutor();
ITree tree = new RascalParser().parse(Parser.START_COMMAND, location.getURI(), command.toCharArray(), INodeFlattener.UNLIMITED_AMB_DEPTH, actionExecutor, new DefaultNodeFlattener<IConstructor, ITree, ISourceLocation>(), new UPTRNodeFactory(false));
if (!noBacktickOutsideStringConstant(command)) {
tree = org.rascalmpl.semantics.dynamic.Import.parseFragments(vf, getMonitor(), parserForCurrentModule(vf, getCurrentModuleEnvironment()), tree, location, getCurrentModuleEnvironment());
}
return tree;
}
@Override
public ITree parseCommands(IRascalMonitor monitor, String commands, ISourceLocation location) {
IRascalMonitor old = setMonitor(monitor);
try {
__setInterrupt(false);
IActionExecutor<ITree> actionExecutor = new NoActionExecutor();
ITree tree = new RascalParser().parse(Parser.START_COMMANDS, location.getURI(), commands.toCharArray(), INodeFlattener.UNLIMITED_AMB_DEPTH, actionExecutor, new DefaultNodeFlattener<IConstructor, ITree, ISourceLocation>(), new UPTRNodeFactory(false));
if (!noBacktickOutsideStringConstant(commands)) {
tree = parseFragments(vf, getMonitor(), parserForCurrentModule(vf, getCurrentModuleEnvironment()), tree, location, getCurrentModuleEnvironment());
}