/
CheckTypes.rsc
8740 lines (7632 loc) · 418 KB
/
CheckTypes.rsc
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
@license{
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
}
@contributor{Mark Hills - Mark.Hills@cwi.nl (CWI)}
@contributor{Anastasia Izmaylova - Anastasia.Izmaylova@cwi.nl (CWI)}
@bootstrapParser
module lang::rascal::types::CheckTypes
import analysis::graphs::Graph;
import IO;
import Set;
import Map;
import Message;
import Node;
import Relation;
import util::Reflective;
import DateTime;
import String;
import ValueIO;
import lang::rascal::checker::ListUtils;
import lang::rascal::checker::TreeUtils;
import lang::rascal::types::AbstractKind;
import lang::rascal::types::AbstractName;
import lang::rascal::types::AbstractType;
import lang::rascal::types::ConvertType;
import lang::rascal::types::TypeSignature;
import lang::rascal::types::TypeInstantiation;
import lang::rascal::checker::ParserHelper;
import lang::rascal::grammar::definition::Symbols;
import lang::rascal::meta::ModuleInfo;
import lang::rascal::types::Util;
extend lang::rascal::types::CheckerConfig;
import lang::rascal::\syntax::Rascal;
//
// TODOs
// * Make sure that names propagate correctly with boolean operators. For instance,
// in a boolean or, a name needs to occur along both branches for it to be
// visible outside the or, but for and the name can occur along only one
// branch (since both need to be true, meaning both have been processed). [NOTE: this
// should be done, but we should double check]
//
// * Filter out bad assignables? For instance, we cannot have <x,y>.f, but it does
// parse, so we may be handed an example such as this.
//
// * Check tags to make sure they are declared
//
// * Make sure we always instantiate type parameters when we use a constructor. NOTE: This
// is partially done -- it has been done for call or tree expressions, but not yet for
// call or tree patterns.
//
// * Check values created by append NOTE: This is partially done, in that we are gathering
// the types. Additional checking may still be needed.
//
// * Make sure type var bounds are consistent.
//
// * Ensure that inferred types are handled appropriately in situations
// where we have control flow iteration: nested calls (other cases complete)
//
// * Typing for loops -- should this always be void? We never know if the loop actually evaluates.
//
// * Remember to keep track of throws declarations, right now these are just discarded.
// PARTIALLY DONE: We are now keeping track of these, but still need to check
// them to enforce they are constructors for runtime exception.
//
// * Need to account for default functions and constructors which have the same signature,
// this is allowed, and we give precedence to the function DONE
//
// * We should mark a function with the same signature and name as a constructor but with
// a different return type as an error. This is currently being done at the point of use,
// but should be done at the point of definition.
//
// * Need to pre-populate the type and name environments with the constructors for
// reified types, since we get these back if someone uses #type.
//
// * In statement blocks, segregate out function defs, these see the scope of the
// entire block, not just what came before; however, closures are still just
// expressions, so we still need the ability to capture an environment for them
// and smartly check for changes to inferred types
//
// * Make sure that, in a function, all paths return.
//
// * Make sure we don't allow changes to the types of variables bound in pattern matches.
// These do not follow the same rules as other inferred vars.
//
// * addition on functions
//
// * resolve deferred names in field accesses and updates, maybe in throws clauses as well
//
// * make sure statement types are computed correctly (e.g., assign results of an if)
//
// * Add support for keyword param type parameter instantiation in Call or Tree expressions
//
// * Add support for checking keyword parameter definitions that are defined in terms of other parameters
//
// * Split out descend on datatypes from declaration of constructors
public CheckResult checkStatementSequence(list[Statement] ss, Configuration c) {
// Introduce any functions in the statement list into the current scope, but
// don't process the bodies, just the signatures. This way we can use functions
// in the bodies of other functions inside the block before the declaring statement
// is reached.
fundecls = [ fd | Statement fds:(Statement)`<FunctionDeclaration fd>` <- ss ];
for (fundecl <- fundecls) {
c = checkFunctionDeclaration(fundecl, false, c);
}
t1 = Symbol::\void();
for (s <- ss) < c, t1 > = checkStmt(s, c);
return < c, t1 >;
}
@doc{Check the types of Rascal expressions: NonEmptyBlock (DONE)}
public CheckResult checkExp(Expression exp:(Expression)`{ <Statement+ ss> }`, Configuration c) {
cBlock = enterBlock(c,exp@\loc);
< cBlock, t1 > = checkStatementSequence([ssi | ssi <- ss], cBlock);
c = exitBlock(cBlock,c);
if (isFailType(t1)) return markLocationFailed(c,exp@\loc,t1);
return markLocationType(c,exp@\loc,t1);
}
@doc{Check the types of Rascal expressions: Bracket (DONE)}
public CheckResult checkExp(Expression exp:(Expression)`( <Expression e> )`, Configuration c) {
< c, t1 > = checkExp(e,c);
if (isFailType(t1)) return markLocationFailed(c,exp@\loc,t1);
return markLocationType(c,exp@\loc,t1);
}
@doc{Check the types of Rascal expressions: Closure (DONE)}
public CheckResult checkExp(Expression exp:(Expression)`<Type t> <Parameters ps> { <Statement+ ss> }`, Configuration c) {
// Add an empty closure -- this ensures that the parameters, processed
// when building the function type, are created in the closure environment
// instead of in the surrounding environment.
< cFun, rt > = convertAndExpandType(t,c);
Symbol funType = Symbol::\func(rt,[]);
cFun = addClosure(cFun, funType, ( ), exp@\loc);
// Calculate the parameter types. This returns the parameters as a tuple. As
// a side effect, names defined in the parameters are added to the environment.
< cFun, ptTuple > = checkParameters(ps, cFun);
list[Symbol] parameterTypes = getTupleFields(ptTuple);
< cFun, keywordParams > = checkKeywordFormals(getKeywordFormals(ps), cFun, typesOnly=false);
// Check each of the parameters for failures. If we have any failures, we do
// not build a function type.
paramFailures = { pt | pt <- (parameterTypes+toList(keywordParams<1>)), isFailType(pt) };
if (size(paramFailures) > 0) {
funType = collapseFailTypes(paramFailures + makeFailType("Could not calculate function type because of errors calculating the parameter types", exp@\loc));
} else {
funType = makeFunctionTypeFromTuple(rt, false, \tuple(parameterTypes));
}
// Update the closure with the computed function type.
cFun.store[head(cFun.stack)].rtype = funType;
cFun.store[head(cFun.stack)].keywordParams = keywordParams;
// In the environment with the parameters, check the body of the closure.
< cFun, st > = checkStatementSequence([ssi | ssi <- ss], cFun);
// Now, recover the environment active before the call, removing any names
// added by the closure (e.g., for parameters) from the environment. This
// also cleans up any parts of the configuration altered to invoke a
// function or closure.
c = recoverEnvironmentsAfterCall(cFun,c);
if (isFailType(funType))
return markLocationFailed(c, exp@\loc, funType);
else
return markLocationType(c,exp@\loc, funType);
}
@doc{Check the types of Rascal expressions: StepRange (DONE)}
public CheckResult checkExp(Expression exp:(Expression)`[ <Expression ef> , <Expression es> .. <Expression el> ]`, Configuration c) {
< c, t1 > = checkExp(ef, c);
< c, t2 > = checkExp(es, c);
< c, t3 > = checkExp(el, c);
if (!isFailType(t1) && !isFailType(t2) && !isFailType(t3) && subtype(t1,Symbol::\num()) && subtype(t2,Symbol::\num()) && subtype(t3,Symbol::\num())) {
return markLocationType(c,exp@\loc,\list(lubList([t1,t2,t3])));
} else {
if (!isFailType(t1) && !subtype(t1,Symbol::\num())) t1 = makeFailType("Invalid type: expected numeric type, found <prettyPrintType(t1)>", ef@\loc);
if (!isFailType(t2) && !subtype(t2,Symbol::\num())) t2 = makeFailType("Invalid type: expected numeric type, found <prettyPrintType(t2)>", es@\loc);
if (!isFailType(t3) && !subtype(t3,Symbol::\num())) t3 = makeFailType("Invalid type: expected numeric type, found <prettyPrintType(t3)>", el@\loc);
return markLocationFailed(c,exp@\loc,{t1,t2,t3});
}
}
@doc{Check the types of Rascal expressions: VoidClosure (DONE)}
public CheckResult checkExp(Expression exp:(Expression)`<Parameters ps> { <Statement* ss> }`, Configuration c) {
// Add an empty closure -- this ensures that the parameters, processed
// when building the function type, are created in the closure environment
// instead of in the surrounding environment.
rt = Symbol::\void();
Symbol funType = Symbol::\func(rt,[]);
cFun = addClosure(c, funType, ( ), exp@\loc);
// Calculate the parameter types. This returns the parameters as a tuple. As
// a side effect, names defined in the parameters are added to the environment.
< cFun, ptTuple > = checkParameters(ps, cFun);
< cFun, keywordParams > = checkKeywordFormals(getKeywordFormals(ps), cFun, typesOnly=false);
list[Symbol] parameterTypes = getTupleFields(ptTuple);
// Check each of the parameters for failures. If we have any failures, we do
// not build a function type.
paramFailures = { pt | pt <- (parameterTypes+toList(keywordParams<1>)), isFailType(pt) };
if (size(paramFailures) > 0) {
funType = collapseFailTypes(paramFailures + makeFailType("Could not calculate function type because of errors calculating the parameter types", exp@\loc));
} else {
funType = makeFunctionTypeFromTuple(rt, false, \tuple(parameterTypes));
}
// Update the closure with the computed function type.
cFun.store[head(cFun.stack)].rtype = funType;
cFun.store[head(cFun.stack)].keywordParams = keywordParams;
// In the environment with the parameters, check the body of the closure.
< cFun, t1 > = checkStatementSequence([ssi | ssi <- ss], cFun);
// Now, recover the environment active before the call, removing any names
// added by the closure (e.g., for parameters) from the environment. This
// also cleans up any parts of the configuration altered to invoke a
// function or closure.
c = recoverEnvironmentsAfterCall(cFun,c);
if (isFailType(funType))
return markLocationFailed(c, exp@\loc, funType);
else
return markLocationType(c,exp@\loc, funType);
}
@doc{Check the types of Rascal expressions: Visit (DONE)}
public CheckResult checkExp(Expression exp:(Expression)`<Label l> <Visit v>`, Configuration c) {
// Treat the visit as a block, since the label has a defined scope from the start to
// the end of the visit, but not outside of it.
cVisit = enterBlock(c,exp@\loc);
// Add the appropriate label into the label stack and label environment. If we have a blank
// label we still add it to the stack, but not to the environment, since we cannot access it
// using a name.
if ((Label)`<Name n> :` := l) {
labelName = convertName(n);
if (labelExists(cVisit,labelName)) cVisit = addMessage(cVisit,error("Cannot reuse label names: <n>", l@\loc));
cVisit = addLabel(cVisit,labelName,l@\loc,visitLabel());
cVisit.labelStack = labelStackItem(labelName, visitLabel(), Symbol::\void()) + cVisit.labelStack;
} else {
cVisit.labelStack = labelStackItem(RSimpleName(""), visitLabel(), Symbol::\void()) + cVisit.labelStack;
}
< cVisit, vt > = checkVisit(v,cVisit);
// Remove the added item from the label stack and then exit the block we created above,
// which will clear up the added label name, removing it from scope.
cVisit.labelStack = tail(cVisit.labelStack);
c = exitBlock(cVisit,c);
if (isFailType(vt)) return markLocationFailed(c,exp@\loc,vt);
return markLocationType(c,exp@\loc,vt);
}
@doc{Check the types of Rascal expressions: Reducer (DONE)}
public CheckResult checkExp(Expression exp:(Expression)`( <Expression ei> | <Expression er> | <{Expression ","}+ egs> )`, Configuration c) {
// Check the initializer first, which runs outside of a scope with "it" defined.
< c, t1 > = checkExp(ei, c);
// Enter a boolean expression scope, since we could bind new variables in
// the generators (egs) that should not be visible outside the reducer.
// NOTE: "it" is also not in scope here.
// TODO: The scope actually starts at er and goes to the end of the
// reducer. Modify the loc to account for this.
cRed = enterBooleanScope(c,exp@\loc);
list[Symbol] ts = [];
for (eg <- egs) { < cRed, t2 > = checkExp(eg,cRed); ts += t2; }
// If the initializer isn't fail, introduce the variable "it" into scope; it is
// available in er (the result), but not in the rest, and we need it to check er.
// Note that this means we cannot check er if we cannot assign an initial type to
// "it", since we have no information on which to base a reasonable assumption.
Symbol erType = t1;
if (!isFailType(t1)) {
cRed = addLocalVariable(cRed, RSimpleName("it"), true, exp@\loc, erType);
< cRed, t3 > = checkExp(er, cRed);
if (!isFailType(t3)) {
if (!equivalent(erType,t3) && lub(erType,t3) == t3) {
// If this is true, this means that "it" now has a different type, and
// that the type is growing towards value. We run the body again to
// see if the type changes again. This covers many standard cases
// such as assigning it the value [] and then adding items to the
// list, while failing in cases where the type is dependent on
// the number of iterations.
erType = t3;
cRed.store[cRed.fcvEnv[RSimpleName("it")]].rtype = erType;
< cRed, t3 > = checkExp(er, cRed);
if (!isFailType(t3)) {
if (!equivalent(erType,t3)) {
erType = makeFailType("Type of it does not stabilize", exp@\loc);
}
} else {
erType = t3;
}
} else if (!equivalent(erType,t3)) {
erType = makeFailType("Type changes in non-monotonic fashion", exp@\loc);
}
} else {
erType = t3;
}
cRed.store[cRed.fcvEnv[RSimpleName("it")]].rtype = erType;
}
// Leave the boolean scope, which will remove all names added in the generators and
// also will remove "it".
c = exitBooleanScope(cRed, c);
// Calculate the final type. If we had failures, it is a failure, else it
// is the type of the reducer step.
failTypes = { t | t <- (ts + t1 + erType), isFailType(t) };
if (size(failTypes) > 0) {
return markLocationFailed(c,exp@\loc,failTypes);
} else {
return markLocationType(c,exp@\loc,erType);
}
}
@doc{Check the types of Rascal expressions: ReifiedType (DONE)}
public CheckResult checkExp(Expression exp:(Expression)`type ( <Expression es> , <Expression ed> )`, Configuration c) {
// TODO: Is there anything we can do statically to make the result type more accurate?
< c, t1 > = checkExp(es, c);
< c, t2 > = checkExp(ed, c);
if (!isFailType(t1) && !subtype(t1,\adt("Symbol",[])))
t1 = makeFailType("Expected subtype of Symbol, instead found <prettyPrintType(t1)>",es@\loc);
if (!isFailType(t1) && !subtype(t2,\map(\adt("Symbol",[]),\adt("Production",[]))))
t2 = makeFailType("Expected subtype of map[Symbol,Production], instead found <prettyPrintType(t2)>",ed@\loc);
if (isFailType(t1) || isFailType(t2))
return markLocationFailed(c,exp@\loc,collapseFailTypes({t1,t2}));
else
return markLocationType(c,exp@\loc,\reified(Symbol::\value()));
}
@doc{Check the types of Rascal expressions: Concete Syntax Fragments (TODO)}
public CheckResult checkExp(Expression exp: (Expression) `<Concrete concrete>`, Configuration c) {
set[Symbol] failures = { };
for (hole(\one(Sym s, Name n)) <- concrete.parts) {
<c, rt> = convertAndExpandSymbol(s, c);
if(isFailType(rt)) {
failures += rt;
}
varName = convertName(n)[@at = n@\loc];
if (fcvExists(c, varName)) {
c.uses = c.uses + < c.fcvEnv[varName], n@\loc >;
c.usedIn[n@\loc] = head(c.stack);
<c, rt> = markLocationType(c, n@\loc, c.store[c.fcvEnv[varName]].rtype);
} else {
<c, rt> = markLocationFailed(c, n@\loc, makeFailType("Name <prettyPrintName(varName)> is not in scope", n@\loc));
failures += rt;
}
}
if(size(failures) > 0) {
return markLocationFailed(c, exp@\loc, failures);
}
<c, rt> = convertAndExpandSymbol(concrete.symbol, c);
return markLocationType(c, exp@\loc, rt);
}
@doc{Check the types of Rascal expressions: CallOrTree}
public CheckResult checkExp(Expression exp:(Expression)`<Expression e> ( <{Expression ","}* eps> <KeywordArguments[Expression] keywordArguments> )`, Configuration c) {
// check for failures
set[Symbol] failures = { };
list[Expression] epsList = [ epsi | epsi <- eps ];
< c, t1 > = checkExp(e, c);
usedItems = invert(c.uses)[e@\loc];
usedItems = { ui | ui <- usedItems, !(c.store[ui] is overload)} + { uii | ui <- usedItems, c.store[ui] is overload, uii <- c.store[ui].items };
rel[Symbol,KeywordParamMap] functionKP = { < c.store[ui].rtype, c.store[ui].keywordParams > | ui <- usedItems, c.store[ui] is function };
rel[Symbol,KeywordParamMap] constructorKP = { < c.store[ui].rtype, c.store[ui].keywordParams > | ui <- usedItems, c.store[ui] is constructor };
if (isFailType(t1)) failures += t1;
list[Symbol] tl = [];
for (ep <- eps) {
< c, t2 > = checkExp(ep, c);
tl += t2;
if (isFailType(t2)) failures += t2;
}
KeywordParamMap kl = ( );
if ((KeywordArguments[Expression])`<OptionalComma oc> <{KeywordArgument[Expression] ","}+ kargs>` := keywordArguments) {
for (ka:(KeywordArgument[Expression])`<Name kn> = <Expression ke>` <- kargs) {
< c, t3 > = checkExp(ke, c);
if (isFailType(t3)) failures += t3;
knr = convertName(kn);
if (knr notin kl) {
kl[knr] = t3;
} else {
c = addScopeError(c,"Cannot use keyword parameter <prettyPrintName(knr)> more than once",ka@\loc);
}
}
}
// If we have any failures, either in the head or in the arguments,
// we aren't going to be able to match, so filter these cases out
// here
if (size(failures) > 0)
return markLocationFailed(c, exp@\loc, failures);
tuple[Symbol, KeywordParamMap, bool, Configuration] instantiateFunctionTypeArgs(Configuration c, Symbol targetType, KeywordParamMap kpm) {
// If the function is parametric, we need to calculate the actual types of the
// parameters and make sure they fall within the proper bounds.
formalArgs = getFunctionArgumentTypes(targetType);
bool varArgs = ( ((targetType@isVarArgs)?) ? targetType@isVarArgs : false );
set[Symbol] typeVars = { *collectTypeVars(fa) | fa <- formalArgs };
map[str,Symbol] bindings = ( getTypeVarName(tv) : Symbol::\void() | tv <- typeVars );
bool canInstantiate = true;
if (!varArgs) {
// First try to get the bindings between the type vars and the actual types for each of the
// function parameters. Here this is not a varargs function, so there are the same number of
// formals as actuals.
for (idx <- index(tl)) {
try {
if (isOverloadedType(tl[idx])) {
// Note: this means the bindings must be consistant across all overload options, since we will only
// get this when we have a higher-order function being passed in and then we want to make sure this
// is true. The alternative would be to use this as a filter as well, discarding options that don't
// work with these bindings.
for (topt <- (getDefaultOverloadOptions(tl[idx]) + getNonDefaultOverloadOptions(tl[idx]))) {
bindings = match(formalArgs[idx],topt,bindings,bindIdenticalVars=true);
}
} else {
bindings = match(formalArgs[idx],tl[idx],bindings,bindIdenticalVars=true);
}
} catch : {
// c = addScopeError(c,"Cannot instantiate parameter <idx+1>, parameter type <prettyPrintType(tl[idx])> violates bound of type parameter in formal argument with type <prettyPrintType(formalArgs[idx])>", epsList[idx]@\loc);
canInstantiate = false;
}
}
} else {
// Get the bindings between the type vars and the actual types for each function parameter. Since
// this is a var-args function, we need to take that into account. The first for loop takes care
// of the fixes parameters, while the second takes care of those that are mapped to the var-args
// parameter.
for (idx <- index(tl), idx < size(formalArgs)) {
try {
bindings = match(formalArgs[idx],tl[idx],bindings,bindIdenticalVars=true);
} catch : {
// c = addScopeError(c,"Cannot instantiate parameter <idx+1>, parameter type <prettyPrintType(tl[idx])> violates bound of type parameter in formal argument with type <prettyPrintType(formalArgs[idx])>", epsList[idx]@\loc);
canInstantiate = false;
}
}
for (idx <- index(tl), idx >= size(formalArgs)) {
try {
bindings = match(getListElementType(formalArgs[size(formalArgs)-1]),tl[idx],bindings,bindIdenticalVars=true);
} catch : {
// c = addScopeError(c,"Cannot instantiate parameter <idx+1>, parameter type <prettyPrintType(tl[idx])> violates bound of type parameter in formal argument with type <prettyPrintType(getListElementType(formalArgs[size(formalArgs)-1]))>", epsList[idx]@\loc);
canInstantiate = false;
}
}
}
for (kn <- kpm) {
try {
bindings = match(kpm[kn], ((kn in kl) ? kl[kn] : kpm[kn]), bindings,bindIdenticalVars=true);
} catch : {
canInstantiate = false;
}
}
// Based on the above, either give an error message (if we could not match the function's parameter types) or
// try to instantiate the entire function type. The instantiation should only fail if we cannot instantiate
// the return type correctly, for instance if the instantiation would violate the bounds.
// NOTE: We may instantiate and still have type parameters, since we may be calling this from inside
// a function, using a value with a type parameter as its type.
if (canInstantiate) {
try {
targetType = instantiate(targetType, bindings);
} catch : {
canInstantiate = false;
}
}
return < targetType, kpm, canInstantiate, c >;
}
// Special handling for overloads -- if we have an overload, at least one of the overload options
// should be a subtype of the other type, but some of them may not be.
bool subtypeOrOverload(Symbol t1, Symbol t2) {
if (!isOverloadedType(t1)) {
return subtype(t1,t2);
} else {
overloads = getNonDefaultOverloadOptions(t1) + getDefaultOverloadOptions(t1);
return (true in { subtype(oitem,t2) | oitem <- overloads });
}
}
tuple[Configuration c, rel[Symbol,KeywordParamMap] matches, set[str] failures] matchFunctionAlts(Configuration c, set[Symbol] alts) {
rel[Symbol,KeywordParamMap] matches = { };
set[str] failureReasons = { };
for (a <- alts, isFunctionType(a), KeywordParamMap kpm <- ( (!isEmpty(functionKP[a])) ? functionKP[a] : { ( ) })) {
list[Symbol] args = getFunctionArgumentTypes(a);
// NOTE: We cannot assume the annotation is set, since we only set it when we add a
// function (and have the info available); we don't have the information when we only
// have a function type, such as with a function parameter.
bool varArgs = ( ((a@isVarArgs)?) ? a@isVarArgs : false );
if (!varArgs) {
//if (size(epsList) == size(args) && size(epsList) == 0) {
// matches += a;
//} else
if (size(epsList) == size(args)) {
if (typeContainsTypeVars(a)) {
< instantiated, instantiatedKP, b, c > = instantiateFunctionTypeArgs(c, a, kpm);
if (!b) {
failureReasons += "Could not instantiate type variables in type <prettyPrintType(a)> with argument types (<intercalate(",",[prettyPrintType(tli)|tli<-tl])>)";
continue;
}
args = getFunctionArgumentTypes(instantiated);
kpm = instantiatedKP;
}
if (false notin { subtypeOrOverload(tl[idx],args[idx]) | (idx <- index(epsList)) }) {
if (size(kl<0> - kpm<0>) > 0) {
failureReasons += "Unknown keyword parameters passed: <intercalate(",",[prettyPrintName(kpname)|kpname<-(kl<0>-kpm<0>)])>";
} else {
kpFailures = { kpname | kpname <- kl<0>, !subtypeOrOverload(kl[kpname],kpm[kpname]) };
if (size(kpFailures) > 0) {
for (kpname <- kpFailures) {
failureReasons += "Keyword parameter of type <prettyPrintType(kpm[kpname])> cannot be assigned argument of type <prettyPrintType(kl[kpname])>";
}
} else {
matches += < a, kpm > ;
}
}
} else {
failureReasons += "Function of type <prettyPrintType(a)> cannot be called with argument types (<intercalate(",",[prettyPrintType(tli)|tli<-tl])>)";
}
} else {
failureReasons += "Function of type <prettyPrintType(a)> cannot be called with argument types (<intercalate(",",[prettyPrintType(tli)|tli<-tl])>)";
}
} else {
if (size(epsList) >= size(args)-1) {
if (size(epsList) == 0) {
matches += < a, kpm >;
} else {
if (typeContainsTypeVars(a) && size(args)-1 <= size(tl)) {
< instantiated, instantiatedKP, b, c > = instantiateFunctionTypeArgs(c, a, kpm);
if (!b) {
failureReasons += "Could not instantiate type variables in type <prettyPrintType(a)> with argument types (<intercalate(",",[prettyPrintType(tli)|tli<-tl])>)";
continue;
}
args = getFunctionArgumentTypes(instantiated);
}
// TODO: It may be good to put another check here to make sure we don't
// continue if the size is wrong; we will still get the proper error, but
// we could potentially give a better message here
list[Symbol] fixedPart = head(tl,size(args)-1);
list[Symbol] varPart = tail(tl,size(tl)-size(args)+1);
list[Symbol] fixedArgs = head(args,size(args)-1);
Symbol varArgsType = getListElementType(last(args));
if (size(fixedPart) == 0 || all(idx <- index(fixedPart), subtypeOrOverload(fixedPart[idx],fixedArgs[idx]))) {
if ( (size(varPart) == 0 ) || (size(varPart) == 1 && subtypeOrOverload(varPart[0],last(args))) || (all(idx2 <- index(varPart),subtypeOrOverload(varPart[idx2],varArgsType))) ) {
if (size(kl<0> - kpm<0>) > 0) {
failureReasons += "Unknown keyword parameters passed: <intercalate(",",[prettyPrintName(kpname)|kpname<-(kl<0>-kpm<0>)])>";
} else {
kpFailures = { kpname | kpname <- kl<0>, !subtypeOrOverload(kl[kpname],kpm[kpname]) };
if (size(kpFailures) > 0) {
for (kpname <- kpFailures) {
failureReasons += "Keyword parameter of type <prettyPrintType(kpm[kpname])> cannot be assigned argument of type <prettyPrintType(kl[kpname])>";
}
} else {
matches += < a, kpm > ;
}
}
} else {
failureReasons += "Function of type <prettyPrintType(a)> cannot be called with argument types (<intercalate(",",[prettyPrintType(tli)|tli<-tl])>)";
}
} else {
failureReasons += "Function of type <prettyPrintType(a)> cannot be called with argument types (<intercalate(",",[prettyPrintType(tli)|tli<-tl])>)";
}
}
}
}
}
// TODO: Here would be a good place to filter out constructors that are "masked" by functions with the
// same name and signature. We already naturally mask function declarations by using a set, but we do
// need to keep track there of possible matching IDs so we can link things up correctly.
return < c, matches, failureReasons >;
}
tuple[Configuration c, rel[Symbol,KeywordParamMap] matches, set[str] failures] matchConstructorAlts(Configuration c, set[Symbol] alts) {
rel[Symbol,KeywordParamMap] matches = { };
set[str] failureReasons = { };
for (a <- alts, isConstructorType(a), kpm <- ( (!isEmpty(constructorKP[a])) ? constructorKP[a] : { ( ) })) {
list[Symbol] args = getConstructorArgumentTypes(a);
if ( (size(epsList) == size(args) && size(epsList) == 0) || (size(epsList) == size(args) && false notin { subtype(tl[idx],args[idx]) | idx <- index(epsList) }) ) {
if (size(kl<0> - kpm<0>) > 0) {
failureReasons += "Unknown keyword parameters passed: <intercalate(",",[prettyPrintName(kpname)|kpname<-(kl<0>-kpm<0>)])>";
} else {
kpFailures = { kpname | kpname <- kl<0>, !subtypeOrOverload(kl[kpname],kpm[kpname]) };
if (size(kpFailures) > 0) {
for (kpname <- kpFailures) {
failureReasons += "Keyword parameter of type <prettyPrintType(kpm[kpname])> cannot be assigned argument of type <prettyPrintType(kl[kpname])>";
}
} else {
matches += < a, kpm > ;
}
}
} else {
failureReasons += "Constructor of type <prettyPrintType(a)> cannot be built with argument types (<intercalate(",",[prettyPrintType(tli)|tli<-tl])>)";
}
}
// TODO: Here would be a good place to filter out constructors that are "masked" by functions with the
// same name and signature. We already naturally mask function declarations by using a set, but we do
// need to keep track there of possible matching IDs so we can link things up correctly.
return < c, matches, failureReasons >;
}
tuple[Configuration c, set[Symbol] matches, set[str] failures] matchProductionAlts(Configuration c, set[Symbol] alts) {
set[Symbol] matches = { };
set[str] failureReasons = { };
for (a <- alts, isProductionType(a)) {
list[Symbol] args = getProductionArgumentTypes(a);
if (size(epsList) == size(args) && size(epsList) == 0) {
matches += a;
} else if (size(epsList) == size(args) && false notin { subtype(tl[idx],args[idx]) | idx <- index(epsList) }) {
matches += a;
} else {
failureReasons += "Production of type <prettyPrintType(a)> cannot be built with argument types (<intercalate(",",[prettyPrintType(tli)|tli<-tl])>)";
}
}
// TODO: Here would be a good place to filter out productions that are "masked" by functions with the
// same name and signature. We already naturally mask function declarations by using a set, but we do
// need to keep track there of possible matching IDs so we can link things up correctly.
return < c, matches, failureReasons >;
}
// e was either a name or an expression that evaluated to a function, a constructor, a production,
// a source location, or a string
if (isFunctionType(t1) || isConstructorType(t1) || isOverloadedType(t1) || isProductionType(t1)) {
set[Symbol] alts = isFunctionType(t1) ? {t1} : ( (isConstructorType(t1) || isProductionType(t1)) ? { } : getNonDefaultOverloadOptions(t1) );
set[Symbol] defaults = isFunctionType(t1) ? { } : ( (isConstructorType(t1) || isProductionType(t1)) ? {t1} : getDefaultOverloadOptions(t1) );
< c, nonDefaultFunctionMatchesWithKP, nonDefaultFunctionFailureReasons > = matchFunctionAlts(c, alts);
< c, defaultFunctionMatchesWithKP, defaultFunctionFailureReasons > = matchFunctionAlts(c, defaults);
< c, constructorMatchesWithKP, constructorFailureReasons > = matchConstructorAlts(c, defaults);
< c, productionMatches, productionFailureReasons > = matchProductionAlts(c, defaults);
// TODO: To make this work for type hints with type vars we need to instantiate the vars; until we do that,
// just skip using the hint in those cases, since it then breaks cases where the hints are not needed.
if ( (exp@typeHint)? && (!typeContainsTypeVars(exp@typeHint))) {
nonDefaultFunctionMatchesWithKP = { < a, kpm > | < a, kpm > <- nonDefaultFunctionMatchesWithKP, typeContainsTypeVars(a) || subtype(getFunctionReturnType(a),exp@typeHint) };
defaultFunctionMatchesWithKP = { < a, kpm > | < a, kpm > <- defaultFunctionMatchesWithKP, typeContainsTypeVars(a) || subtype(getFunctionReturnType(a),exp@typeHint) };
constructorMatchesWithKP = { < a, kpm > | < a, kpm > <- constructorMatchesWithKP, typeContainsTypeVars(a) || subtype(getConstructorResultType(a),exp@typeHint) };
productionMatches = { a | a <- productionMatches, typeContainsTypeVars(a) || subtype(getProductionSortType(a),exp@typeHint) };
}
set[Symbol] nonDefaultFunctionMatches = nonDefaultFunctionMatchesWithKP<0>;
set[Symbol] defaultFunctionMatches = defaultFunctionMatchesWithKP<0>;
set[Symbol] constructorMatches = constructorMatchesWithKP<0>;
if (size(nonDefaultFunctionMatches + defaultFunctionMatches + constructorMatches + productionMatches) == 0) {
return markLocationFailed(c,exp@\loc,{makeFailType(reason,exp@\loc) | reason <- (nonDefaultFunctionFailureReasons + defaultFunctionFailureReasons + constructorFailureReasons + productionFailureReasons)});
} else if ( (size(nonDefaultFunctionMatches) > 1 || size(defaultFunctionMatches) > 1) && size(constructorMatches) > 1 && size(productionMatches) > 1) {
return markLocationFailed(c,exp@\loc,makeFailType("Multiple functions, constructors, and productions found which could be applied",exp@\loc));
} else if ( (size(nonDefaultFunctionMatches) > 1 || size(defaultFunctionMatches) > 1) && size(constructorMatches) > 1) {
return markLocationFailed(c,exp@\loc,makeFailType("Multiple functions and constructors found which could be applied",exp@\loc));
} else if ( (size(nonDefaultFunctionMatches) > 1 || size(defaultFunctionMatches) > 1) && size(productionMatches) > 1) {
return markLocationFailed(c,exp@\loc,makeFailType("Multiple functions and productions found which could be applied",exp@\loc));
} else if (size(nonDefaultFunctionMatches) > 1 || (size(nonDefaultFunctionMatches) == 0 && size(defaultFunctionMatches) > 1)) {
return markLocationFailed(c,exp@\loc,makeFailType("Multiple functions found which could be applied",exp@\loc));
} else if (size(constructorMatches) > 1) {
return markLocationFailed(c,exp@\loc,makeFailType("Multiple constructors found which could be applied",exp@\loc));
} else if (size(productionMatches) > 1) {
return markLocationFailed(c,exp@\loc,makeFailType("Multiple productions found which could be applied",exp@\loc));
} else if (size(productionMatches) >= 1 && size(constructorMatches) >= 1)
return markLocationFailed(c,exp@\loc,makeFailType("Both a constructor and a concrete syntax production could be applied",exp@\loc));
set[Symbol] finalNonDefaultMatches = {};
set[Symbol] finalDefaultMatches = {};
bool cannotInstantiateFunction = false;
bool cannotInstantiateConstructor = false;
bool cannotInstantiateProduction = false;
// TODO: The above code checks keyword parameters; they need to be properly instantiated below
// in case they are parametric.
if (size(nonDefaultFunctionMatches + defaultFunctionMatches) > 0) {
rts = nonDefaultFunctionMatches + defaultFunctionMatches;
for(rt <- rts) {
isInDefaults = rt in defaultFunctionMatches;
isInNonDefaults = rt in nonDefaultFunctionMatches;
if (typeContainsTypeVars(rt)) {
// TODO: Need to get back valid params here...
< rt, instantiatedKP, canInstantiate, c > = instantiateFunctionTypeArgs(c, rt, ());
cannotInstantiateFunction = !canInstantiate;
if(isInDefaults) {
finalDefaultMatches += rt;
}
if(isInNonDefaults) {
finalNonDefaultMatches += rt;
}
} else {
if(isInDefaults) {
finalDefaultMatches += rt;
}
if(isInNonDefaults) {
finalNonDefaultMatches += rt;
}
}
}
}
if (size(constructorMatches) == 1) {
rt = getOneFrom(constructorMatches);
if (typeContainsTypeVars(rt)) {
// If the constructor is parametric, we need to calculate the actual types of the
// parameters and make sure they fall within the proper bounds.
formalArgs = getConstructorArgumentTypes(rt);
set[Symbol] typeVars = { *collectTypeVars(fa) | fa <- (formalArgs+rt) };
map[str,Symbol] bindings = ( getTypeVarName(tv) : Symbol::\void() | tv <- typeVars );
for (idx <- index(tl)) {
try {
bindings = match(formalArgs[idx],tl[idx],bindings);
} catch : {
c = addScopeError(c,"Cannot instantiate parameter <idx+1>, parameter type <prettyPrintType(tl[idx])> violates bound of type parameter in formal argument with type <prettyPrintType(formalArgs[idx])>", epsList[idx]@\loc);
cannotInstantiateConstructor = true;
}
}
if (!cannotInstantiateConstructor) {
try {
rt = instantiate(rt, bindings);
finalDefaultMatches += rt;
} catch : {
cannotInstantiateConstructor = true;
}
}
} else {
finalDefaultMatches += rt;
}
}
if (size(productionMatches) == 1) {
rt = getOneFrom(productionMatches);
if (typeContainsTypeVars(rt)) {
// If the production is parametric, we need to calculate the actual types of the
// parameters and getProductionArgumentTypes sure they fall within the proper bounds.
formalArgs = getConstructorArgumentTypes(rt);
set[Symbol] typeVars = { *collectTypeVars(fa) | fa <- (formalArgs+rt) };
map[str,Symbol] bindings = ( getTypeVarName(tv) : Symbol::\void() | tv <- typeVars );
for (idx <- index(tl)) {
try {
bindings = match(formalArgs[idx],tl[idx],bindings);
} catch : {
c = addScopeError(c,"Cannot instantiate parameter <idx+1>, parameter type <prettyPrintType(tl[idx])> violates bound of type parameter in formal argument with type <prettyPrintType(formalArgs[idx])>", epsList[idx]@\loc);
cannotInstantiateProduction = true;
}
}
if (!cannotInstantiateProduction) {
try {
rt = instantiate(rt, bindings);
finalDefaultMatches += rt;
} catch : {
cannotInstantiateProduction = true;
}
}
} else {
finalDefaultMatches += rt;
}
}
if (cannotInstantiateFunction && cannotInstantiateConstructor && cannotInstantiateProduction) {
return markLocationFailed(c,exp@\loc,makeFailType("Cannot instantiate type parameters in function invocation and constructor and production", exp@\loc));
} else if (cannotInstantiateFunction && cannotInstantiateConstructor) {
return markLocationFailed(c,exp@\loc,makeFailType("Cannot instantiate type parameters in function invocation and constructor", exp@\loc));
} else if (cannotInstantiateFunction && cannotInstantiateProduction) {
return markLocationFailed(c,exp@\loc,makeFailType("Cannot instantiate type parameters in function invocation and production", exp@\loc));
} else if (cannotInstantiateConstructor && cannotInstantiateProduction) {
return markLocationFailed(c,exp@\loc,makeFailType("Cannot instantiate type parameters in constructor and production", exp@\loc));
} else if (cannotInstantiateFunction) {
return markLocationFailed(c,exp@\loc,makeFailType("Cannot instantiate type parameters in function invocation", exp@\loc));
} else if (cannotInstantiateConstructor) {
return markLocationFailed(c,exp@\loc,makeFailType("Cannot instantiate type parameters in constructor", exp@\loc));
} else if (cannotInstantiateProduction) {
return markLocationFailed(c,exp@\loc,makeFailType("Cannot instantiate type parameters in production", exp@\loc));
} else {
if (size(finalNonDefaultMatches) == 1) {
finalMatch = getOneFrom(finalNonDefaultMatches);
< c, rtp > = markLocationType(c,e@\loc,finalMatch);
if (isFunctionType(finalMatch)) {
actuallyUsed = { ui | ui <- usedItems, c.store[ui] is function, comparable(c.store[ui].rtype,finalMatch) };
if (size(actuallyUsed) > 0) {
c.narrowedUses = c.narrowedUses + (actuallyUsed*{e@\loc});
}
return markLocationType(c,exp@\loc,getFunctionReturnType(finalMatch));
} else {
return markLocationFailed(c,exp@\loc,makeFailType("Unexpected match, should have had a function type, instead found <prettyPrintType(finalMatch)>", exp@\loc));
}
} else if (size(finalDefaultMatches) == 1) {
finalMatch = getOneFrom(finalDefaultMatches);
< c, rtp > = markLocationType(c,e@\loc,finalMatch);
if (isFunctionType(finalMatch)) {
actuallyUsed = { ui | ui <- usedItems, c.store[ui] is function, comparable(c.store[ui].rtype,finalMatch) };
if (size(actuallyUsed) > 0) {
c.narrowedUses = c.narrowedUses + (actuallyUsed*{e@\loc});
}
return markLocationType(c,exp@\loc,getFunctionReturnType(finalMatch));
} else if (isConstructorType(finalMatch)) {
actuallyUsed = { ui | ui <- usedItems, c.store[ui] is constructor, comparable(c.store[ui].rtype,finalMatch) };
if (size(actuallyUsed) > 0) {
c.narrowedUses = c.narrowedUses + (actuallyUsed*{e@\loc});
}
return markLocationType(c,exp@\loc,getConstructorResultType(finalMatch));
} else if (isProductionType(finalMatch)) {
actuallyUsed = { ui | ui <- usedItems, c.store[ui] is production, comparable(c.store[ui].rtype,finalMatch) };
if (size(actuallyUsed) > 0) {
c.narrowedUses = c.narrowedUses + (actuallyUsed*{e@\loc});
}
return markLocationType(c,exp@\loc,getProductionSortType(finalMatch));
}
} else if (size(finalDefaultMatches) > 1) {
// Make sure the defaults function, constructor, and production variants have the same return type, else we
// have a conflict.
functionMatches = filterSet(finalDefaultMatches, isFunctionType);
functionVariant = getOneFrom(functionMatches);
constructorMatches = filterSet(finalDefaultMatches, isConstructorType);
productionMatches = filterSet(finalDefaultMatches, isProductionType);
nonFunctionResult = (size(constructorMatches) > 0) ? getConstructorResultType(getOneFrom(constructorMatches)) : getProductionSortType(getOneFrom(productionMatches));
if (!equivalent(getFunctionReturnType(functionVariant),nonFunctionResult)) {
// TODO: This should also result in an error on the function
// declaration, since we should not have a function with the same name
// and parameters but a different return type
c = addScopeWarning(c, "Call at <e@\loc> uses a function with a bad return type", e@\loc);
}
actuallyUsed = { ui | ui <- usedItems, c.store[ui] is function, comparable(c.store[ui].rtype,functionVariant) };
if (size(actuallyUsed) > 0) {
c.narrowedUses = c.narrowedUses + (actuallyUsed*{e@\loc});
}
< c, rtp > = markLocationType(c,e@\loc,functionVariant);
return markLocationType(c,exp@\loc,getFunctionReturnType(functionVariant));
}
}
} else if (isLocType(t1)) {
if (size(tl) == 4) {
// We are expecting a signature of int, int, tuple[int,int], tuple[int,int], make sure we got it
if (!isIntType(tl[0]))
failures += makeFailType("Expected int, found <prettyPrintType(tl[0])>", epsList[0]@\loc);
if (!isIntType(tl[1]))
failures += makeFailType("Expected int, found <prettyPrintType(tl[1])>", epsList[1]@\loc);
if (!isTupleType(tl[2])) {
failures += makeFailType("Expected tuple[int,int], found <prettyPrintType(tl[2])>", epsList[2]@\loc);
} else {
tf1 = getTupleFields(tl[2]);
if (!(size(tf1) == 2 && isIntType(tf1[0]) && isIntType(tf1[1])))
failures += makeFailType("Expected tuple[int,int], found <prettyPrintType(tl[2])>", epsList[2]@\loc);
}
if (!isTupleType(tl[3])) {
failures += makeFailType("Expected tuple[int,int], found <prettyPrintType(tl[3])>", epsList[3]@\loc);
} else {
tf2 = getTupleFields(tl[3]);
if (!(size(tf2) == 2 && isIntType(tf2[0]) && isIntType(tf2[1])))
failures += makeFailType("Expected tuple[int,int], found <prettyPrintType(tl[2])>", epsList[2]@\loc);
}
} else {
failures += makeFailType("Expected 4 arguments: int, int, tuple[int,int], and tuple[int,int]", exp@\loc);
}
if (size(kl) > 0) {
failures += makeFailType("Cannot pass keyword parameters as part of creating a location", exp@\loc);
}
if (size(failures) > 0)
return markLocationFailed(c,exp@\loc,failures);
else
return markLocationType(c,exp@\loc,Symbol::\loc());
} else if (isStrType(t1)) {
return markLocationType(c,exp@\loc,Symbol::\node());
}
return markLocationFailed(c,exp@\loc,makeFailType("Cannot use type <prettyPrintType(t1)> in calls", exp@\loc));
}
@doc{Check the types of Rascal expressions: Literal (DONE)}
public CheckResult checkExp(Expression exp:(Expression)`<Literal l>`, Configuration c) {
return checkLiteral(l, c);
}
public bool inBooleanScope(Configuration c) = ((size(c.stack) > 0) && (booleanScope(_,_) := c.store[c.stack[0]]));
@doc{Check the types of Rascal expressions: Any (DONE)}
public CheckResult checkExp(Expression exp:(Expression)`any ( <{Expression ","}+ egs> )`, Configuration c) {
// Start a new boolean scope. Names should not leak out of an any, even if
// this is embedded inside a boolean scope already. If nothing else, we may
// never have a valid match in the any, in which case the vars would not
// be bound anyway.
cAny = enterBooleanScope(c, exp@\loc);
// Now, check the type of each of the generators. They should all evaluate to
// a value of type bool.
set[Symbol] failures = { };
for (eg <- egs) {
< cAny, t1 > = checkExp(eg,cAny);
if (isFailType(t1)) {
failures += t1;
} else if (!isBoolType(t1)) {
failures += makeFailType("Expected type bool, found <prettyPrintType(t1)>", eg@\loc);
}
}
// Then, exit the boolean scope, which discards any of the names bound inside.
c = exitBooleanScope(cAny, c);
if (size(failures) > 0) return markLocationFailed(c, exp@\loc, collapseFailTypes(failures));
return markLocationType(c, exp@\loc, Symbol::\bool());
}
@doc{Check the types of Rascal expressions: All (DONE)}
public CheckResult checkExp(Expression exp:(Expression)`all ( <{Expression ","}+ egs> )`, Configuration c) {
// Start a new boolean scope. Names should not leak out of an all, even if
// this is embedded inside a boolean scope already. If nothing else, we may
// never have a valid match in the all, in which case the vars would not
// be bound anyway.
cAll = enterBooleanScope(c, exp@\loc);
// Now, check the type of each of the generators. They should all evaluate to
// a value of type bool.
set[Symbol] failures = { };
for (eg <- egs) {
< cAll, t1 > = checkExp(eg,cAll);
if (isFailType(t1)) {
failures += t1;
} else if (!isBoolType(t1)) {
failures += makeFailType("Expected type bool, found <prettyPrintType(t1)>", eg@\loc);
}
}
// Then, exit the boolean scope, which discards any of the names
// bound inside.
c = exitBooleanScope(cAll, c);
if (size(failures) > 0) return markLocationFailed(c, exp@\loc, collapseFailTypes(failures));
return markLocationType(c, exp@\loc, Symbol::\bool());
}
@doc{Check the types of Rascal expressions: Comprehension (DONE)}
public CheckResult checkExp(Expression exp:(Expression)`<Comprehension cp>`, Configuration c) {
return checkComprehension(cp, c);
}
@doc{Check the types of Rascal expressions: Set (DONE)}
public CheckResult checkExp(Expression exp:(Expression)`{ <{Expression ","}* es> }`, Configuration c) {
list[Symbol] tl = [ Symbol::\void() ];
for (e <- es) { < c, t1 > = checkExp(e,c); tl += t1; }
if (all(t <- tl, !isFailType(t))) {
return markLocationType(c, exp@\loc, \set(lubList(tl)));
} else {
return markLocationFailed(c, exp@\loc, {t|t<-tl});
}
}
@doc{Check the types of Rascal expressions: List (DONE)}
public CheckResult checkExp(Expression exp:(Expression)`[ <{Expression ","}* es> ]`, Configuration c) {
list[Symbol] tl = [ Symbol::\void() ];
for (e <- es) { < c, t1 > = checkExp(e,c); tl += t1; }
if (all(t <- tl, !isFailType(t))) {
return markLocationType(c, exp@\loc, \list(lubList(tl)));
} else {
return markLocationFailed(c, exp@\loc, {t|t<-tl});
}
}
@doc{Check the types of Rascal expressions: ReifyType (DONE)}
public CheckResult checkExp(Expression exp:(Expression)`# <Type t>`, Configuration c) {
< c, rt > = convertAndExpandType(t,c);
return markLocationType(c, exp@\loc, \reified(rt));
}
@doc{Check the types of Rascal expressions: Range (DONE)}
public CheckResult checkExp(Expression exp:(Expression)`[ <Expression ef> .. <Expression el> ]`, Configuration c) {
< c, t1 > = checkExp(ef, c);
< c, t2 > = checkExp(el, c);
if (!isFailType(t1) && !isFailType(t2) && subtype(t1,Symbol::\num()) && subtype(t2,Symbol::\num())) {
return markLocationType(c,exp@\loc,\list(lubList([t1,t2])));
} else {
if (!subtype(t1,Symbol::\num())) t1 = makeFailType("Invalid type: expected numeric type, found <prettyPrintType(t1)>", ef@\loc);
if (!subtype(t2,Symbol::\num())) t2 = makeFailType("Invalid type: expected numeric type, found <prettyPrintType(t2)>", el@\loc);
return markLocationFailed(c,exp@\loc,{t1,t2});
}