-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsemantic.d
13422 lines (12166 loc) · 400 KB
/
semantic.d
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
// Written in the D programming language
// Author: Timon Gehr
// License: http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0
import std.array, std.conv, std.algorithm, std.range, std.string;
import lexer, parser, expression, statement, declaration, scope_, util;
import analyze;
import variant;
public import operators;
public import interpret;
public import scheduler;
// TODO: this is just a stub
string uniqueIdent(string base){
shared static id=0;
return base~to!string(id++);
}
// helper macros
string[2] splitScope(string s){
if(!s.startsWith("sc=")) return ["sc",s];
string[2] r;
alias std.string.indexOf indexOf;
auto i = indexOf(s,";");
return [s[3..i], s[i+1..$]];
}
enum SemRet = q{
static if(is(typeof(this):typeof(return))) return this;
else static if(is(typeof(return)==class)) return null;
else static if(is(typeof(return)==bool)) return true;
else return;
};
template MultiArgument(alias a,string s) if(s.canFind(",")){
enum sp = splitScope(s);
enum ss=sp[1].split(",");
enum MultiArgument={
string r;
foreach(t;ToTuple!ss) r~=a!(mixin(X!q{sc=@(sp[0]);@(t)}));
return r;
}();
}
template Rewrite(string s) if(!s.canFind(",")){
enum Rewrite=mixin(X!q{
while(@(s).rewrite){
debug{
auto rw=@(s).rewrite;
assert(!!cast(typeof(@(s)))@(s).rewrite, text("rewrite from ",typeid(typeof(@(s)))," to ",typeid(rw)));
}
assert(@(s)!is @(s).rewrite, "non-terminating rewrite! "~.to!string(@(s)));
//assert(!!cast(typeof(@(s)))@(s).rewrite,"cannot store "~.to!string(typeid(@(s).rewrite))~" into reference of type "~.to!string(typeid(typeof(@(s)))));
@(s)=cast(typeof(@(s)))cast(void*)@(s).rewrite;
}
});
}
template ConstFold(string s) if(!s.canFind(",")){
enum sp = splitScope(s);
enum ConstFold=mixin(X!q{
@(sp[1]).constFold(@(sp[0]));
mixin(Rewrite!q{@(sp[1])});
});
}
template FinishDeductionProp(string s) if(!s.canFind(",")){
enum FinishDeductionProp=mixin(X!q{
if(!@(s).finishDeduction(sc)) mixin(ErrEplg);
});
}
template FinishDeduction(string s) if(!s.canFind(",")){
enum FinishDeduction=mixin(X!q{
if(!@(s).finishDeduction(sc)) mixin(SetErr!q{@(s)});
});
}
template PropErr(string s) if(!s.canFind(",")){
enum sp = splitScope(s);
enum PropErr=s.length?mixin(X!q{
static if(is(typeof(@(sp[1])): Node)){
if(@(sp[1]).sstate==SemState.error){
// auto xxx = @(sp[1]);dw("propagated error from ", typeid(xxx)," ",@(sp[1])," to ",this);
@(ErrEplg)
}
}else foreach(x;@(sp[1])) mixin(PropErr!q{x});
}):mixin(X!q{if(sstate==SemState.error){@(NoRetry)mixin(SemRet);}});
}
template PropErr(string s) if(s.canFind(",")){ alias MultiArgument!(.PropErr,s) PropErr; }
template PropRetryNoRew(string s) if(!s.canFind(",")){
enum sp = splitScope(s);
enum PropRetryNoRew=mixin(X!q{
static assert(!is(typeof(_nR)));
if(auto _nR=@(sp[1]).needRetry){
assert(_nR!=2 || sstate != SemState.error,text("error in cdep from ",@(sp[1])," to ",toString()));
if(sstate != SemState.error){
needRetry = _nR;
if(_nR==2){mixin(SetErr!q{@(sp[1])});}
// dw("propagated retry ",_nR," from ",@(sp[1])," to ",toString()," ",__LINE__);
Scheduler().await(this, @(sp[1]), @(sp[0]));
}
mixin(SemRet);
}
});
}
template PropRetry(string s) if(!s.canFind(",")){
enum sp = splitScope(s);
enum PropRetry=Rewrite!(sp[1])~PropRetryNoRew!s;
}
template PropRetry(string s) if(s.canFind(",")){ alias MultiArgument!(.PropRetry,s) PropRetry; }
template SemProp(string s){
enum sp = splitScope(s);
enum SemProp = PropRetry!s~PropErr!(sp[1]);
}
enum CheckRewrite=mixin(X!q{ if(rewrite) mixin(SemRet); });
enum SemCheck=mixin(X!q{ if(needRetry||rewrite||sstate==SemState.error){mixin(SemRet);} });
private template _SemChldImpl(string s, string op, string sc){ // TODO: get rid of duplication
template Doit(string v){
enum Doit=mixin(X!((op[0..3]!="exp"?q{
if(@(v).sstate != SemState.completed)
}:"")~q{@(v).@(op)(@(sc));@(Rewrite!v);}));
}
enum ss=s.split(",");
enum _SemChldImpl={
string r;
foreach(t;ToTuple!ss){
r~=mixin(X!q{
static if(is(typeof(@(t)): Node)){
@(Doit!t)
if(@(t).sstate != SemState.completed) mixin(PropRetryNoRew!q{sc=@(sc);@(t)});
else{
static if(is(typeof(@(t)): Expression) && !is(typeof(@(t)):Type)
&&(!is(typeof(this):Expression)||is(typeof(this):Type))){
if(@(t).sstate==SemState.completed) mixin(ConstFold!q{sc=@(sc);@(t)});
}
}
}else{
foreach(ref x;@(t)) mixin(_SemChldImpl!("x","@(op)","@(sc)"));
static if(is(typeof(@(t)): Expression[]) && (!is(typeof(this)==TemplateInstanceExp)||"@(t)"!="args")){
pragma(msg, typeof(this)," @(t)");
@(t)=mixin(`Tuple.expand(@(sc),AccessCheck.all,@(t),@(t~"Leftover"))`);
if(mixin(`@(t~"Leftover")`)){
mixin(_SemChldImpl!("@(t)Leftover","@(op)","@(sc)"));
}
mixin(PropErr!q{@(t)});
}
}
});
}
return r;
}();
}
template SemChld(string s){ // perform semantic analysis on child node, propagate all errors
enum sp = splitScope(s);
enum SemChld=_SemChldImpl!(sp[1],q{semantic},sp[0])~PropErr!s;
}
template SemChldPar(string s){
enum sp = splitScope(s);
enum SemChldPar=_SemChldImpl!(sp[1],q{semantic},sp[0]);
}
template SemChldExp(string s){ // perform semantic analysis on child node, require that it is an expression
enum sp = splitScope(s);
enum SemChldExp=_SemChldImpl!(sp[1],q{expSemantic},sp[0])~PropErr!s;
}
template SemChldExpPar(string s){
enum sp = splitScope(s);
enum SemChldExpPar=_SemChldImpl!(sp[1],q{expSemantic},sp[0]);
}
template ConvertTo(string s) if(s.split(",").length==2){
enum ss = s.split(",");
enum ConvertTo=mixin(X!q{
assert(!@(ss[0]).rewrite && @(ss[0]).sstate == SemState.completed,"ConvertTo!q{@(s)}");
@(ss[0])=@(ss[0]).convertTo(@(ss[1]));
mixin(SemChldExp!q{@(ss[0])});
assert(!@(ss[0]).rewrite,"ConvertTo!q{@(s)}");
});
}
template ImplConvertTo(string s) if(s.split(",").length==2){
enum ss = s.split(",");
enum ImplConvertTo=mixin(X!q{
assert(!@(ss[0]).rewrite && @(ss[0]).sstate == SemState.completed,@(ss[0]).toString()~" "~to!string(@(ss[0]).rewrite)~" "~to!string(@(ss[0]).sstate));
@(ss[0])=@(ss[0]).implicitlyConvertTo(@(ss[1]));
mixin(SemChldExp!q{@(ss[0])});
assert(!@(ss[0]).rewrite,"ImplConvertTo!q{@(s)}");
});
}
template ImplConvertToPar(string s) if(s.split(",").length==2){
enum ss = s.split(",");
enum ImplConvertToPar=mixin(X!q{
assert(!@(ss[0]).rewrite && @(ss[0]).sstate == SemState.completed);
@(ss[0])=@(ss[0]).implicitlyConvertTo(@(ss[1]));
mixin(SemChldExpPar!q{@(ss[0])});
assert(!@(ss[0]).rewrite,"ImplConvertToPar!q{@(s)}");
});
}
template CreateBinderForDependent(string name, string fun=lowerf(name)){
mixin(mixin(X!q{
template @(name)(string s, bool propErr = true) if(s.split(",")[0].split(";").length==2){
enum ss = s.split(";");
enum var = ss[0];
enum spl = var.split(" ");
enum varn = strip(spl.length==1?var:spl[$-1]);
enum sss = ss[1].split(",");
enum e1 = sss[0];
enum er = sss[1..$].join(" , ");
enum @(name)=`
auto _@(name)_`~varn~`=`~e1~`.@(fun)(`~er~`);
if(auto d=_@(name)_`~varn~`.dependee){
static if(is(typeof(return) A: Dependent!T,T)) return d.dependent!T;
else mixin(`~(propErr?q{SemProp}:q{PropRetry})~`!q{sc=d.scope_;d.node});
}
`~(propErr?`assert(!_@(name)_`~varn~`.dependee,text("illegal dependee ",_@(name)_`~varn~`.dependee.node," ",_@(name)_`~varn~`.dependee.node.sstate));`:``)~`
static if(!is(typeof(_@(name)_`~varn~`)==Dependent!void))`~var~`=_@(name)_`~varn~`.value;
`;
}
}));
}
mixin CreateBinderForDependent!("ImplConvertsTo","implicitlyConvertsTo");
mixin CreateBinderForDependent!("RefConvertsTo");
mixin CreateBinderForDependent!("ConstConvertsTo");
mixin CreateBinderForDependent!("ConvertsTo");
mixin CreateBinderForDependent!("TypeMostGeneral");
mixin CreateBinderForDependent!("TypeCombine");
mixin CreateBinderForDependent!("Combine");
mixin CreateBinderForDependent!("Unify");
mixin CreateBinderForDependent!("TypeMatch");
mixin CreateBinderForDependent!("RefCombine");
mixin CreateBinderForDependent!("MatchCall");
mixin CreateBinderForDependent!("MatchCallHelper");
mixin CreateBinderForDependent!("AtLeastAsSpecialized");
mixin CreateBinderForDependent!("DetermineMostSpecialized");
mixin CreateBinderForDependent!("Lookup");
mixin CreateBinderForDependent!("LookupHere");
mixin CreateBinderForDependent!("GetUnresolved");
mixin CreateBinderForDependent!("GetUnresolvedHere");
mixin CreateBinderForDependent!("IsDeclAccessible");
mixin CreateBinderForDependent!("DetermineOverride");
mixin CreateBinderForDependent!("FindOverrider");
mixin CreateBinderForDependent!("LookupSealedOverloadSet");
mixin CreateBinderForDependent!("LookupSealedOverloadSetWithRetry");
mixin CreateBinderForDependent!("EliminateLessSpecializedTemplateMatches");
template IntChld(string s) if(!s.canFind(",")){
enum IntChld=mixin(X!q{
@(s).interpret(sc);
mixin(SemProp!q{@(s)});
});
}
template Configure(string s){
enum Configure={
string r;
auto ss=s.split(".");
auto ss2=ss[1].split("=");
if(ss2[1][$-1]==';') ss2[1]=ss2[1][0..$-1];
r~="auto _old_"~ss[0]~"_"~ss2[0]~"="~ss[0]~"."~ss2[0]~";\n";
r~="scope(exit) "~ss[0]~"."~ss2[0]~"="~"_old_"~ss[0]~"_"~ss2[0]~";\n";
r~=s~";";
return r;
}();
}
template RevEpoLkup(string e){
enum RevEpoLkup=mixin(X!q{
if(auto ident=@(e).isIdentifier()){
if(ident.recursiveLookup && !ident.isLookupIdentifier()){
if(!ident.meaning && ident.sstate != SemState.error){
//ident.lookup(sc);
mixin(Lookup!q{_; ident, sc, sc});
if(auto nr=ident.needRetry) { needRetry = nr; return; }
}
if(ident.sstate == SemState.failed){
// show lookup error
ident.sstate = SemState.begin;
mixin(SemChldPar!q{@(e)});
}
if(ident.sstate != SemState.error && ident.meaning){
// constructor calls are not subject to reverse eponymous lookup
// reverse eponymous lookup is also not performed for reference
// aggregate declarations. This behaviour is copied from DMD.
static if(is(typeof(this)==CallExp))
if(ident.meaning.isAggregateDecl())
goto Lnorevepolkup;
@(e) = ident.reverseEponymousLookup(sc);
Lnorevepolkup:;
}
}
}
});
}
template RevEpoNoHope(string e){
enum RevEpoNoHope=mixin(X!q{
if(auto ident = e.isIdentifier()){
if(ident.recursiveLookup && !ident.isLookupIdentifier()){
if(!ident.meaning && ident.sstate != SemState.error){
ident.noHope(sc);
}
}
}
});
}
/+
// alternative implementation using an additional flag (firstlookup):
template RevEpoLkup(string e){
enum RevEpoLkup=mixin(X!q{
if(firstlookup){
auto ident = e.isIdentifier();
if(!ident) firstlookup=false;
else{
if(!ident.meaning){
ident.lookup(sc);
mixin(PropRetry!q{e});
}
if(e.sstate == SemState.failed){
mixin(SemChld!q{e});
assert(0);
}else{
assert(!!cast(Identifier)ident);
writeln(typeid(ident)); sc.note(ident.toString()~" here",ident.loc);
e = ident.reverseEponymousLookup(sc);
writeln(typeid(this.e));sc.note(e.toString()~" here",e.loc);
firstlookup = false;
}
}
}
});
}
+/
enum SemState:ubyte{
error,
failed, // identifier lookup failed
pre,
begin,
started,
completed,
}
enum SemPrlgDontSchedule=q{
if(sstate == SemState.error||sstate == SemState.completed||rewrite){mixin(SemRet);}
//dw(cccc++); if(!champ||cccc>champ.cccc) champ=this;
//dw(champ);
/+debug scope(failure){
if(loc.line) write("here! ",loc," ",typeid(this));
else write("here! ",toString()," ",typeid(this));
static if(is(typeof(meaning))) write(" meaning: ",meaning," ",typeid(this.meaning)," ",meaning.sstate);
writeln();
}+/
};
enum SemPrlg=SemPrlgDontSchedule~q{
Scheduler().add(this,sc);
};
//static if(is(typeof(dw(this)))) dw(this);
// removed because they crash the program when compiled with DMD sometimes
/+ debug scope(failure){
static if(is(typeof(sc))) if(sc) sc.note("here!",loc);
static if(is(typeof(this):Declaration)) writeln(scope_);
}+/
/+ debug scope(exit){
if(sstate != SemState.completed && returns_this){
assert(needRetry||sstate == SemState.error,toString()~" is not done but returns");
}
}+/
//static if(is(typeof(sc))) if(sc){
// sc.note("prolog "~this.to!string~"@"~__LINE__.to!string,loc);
// writeln(sc);
//}
//if(sstate>SemState.begin){sc.error("cyclic dependency",loc);sstate=SemState.error;return this;}
enum NoRetry=q{
needRetry = false;
Scheduler().remove(this);
};
enum SemEplg=q{
mixin(NoRetry);
sstate = SemState.completed;
mixin(SemRet);
};
template RewEplg(string s) if(!s.canFind(",")){
enum RewEplg=mixin(X!q{
assert(!rewrite," rewrite mustn't be set already "~toString()~" "~rewrite.toString());
rewrite = @(s);
// dw("rewriting ",this," to ",rewrite," ",__LINE__);
static assert(is(typeof(return)==void)||is(typeof(return)==bool));
Scheduler().remove(this);
mixin(SemRet);
});
}
enum ErrEplg=q{
// dw(this," ",__LINE__);
mixin(NoRetry);
sstate=SemState.error;
mixin(SemRet);
};
template SetErr(string s) if(!s.canFind(",")){
enum t=s.length?s~".":"";
enum SetErr=mixin(X!q{
@(t)needRetry=false; // TODO: macrolize?
Scheduler().remove(@(s.length?s:"this"));
@(t)sstate=SemState.error;
});
}
enum RetryEplg=q{
/+if(!needRetry)+/
assert(sstate != SemState.error,"1");
Identifier.tryAgain = true;
needRetry = true;
mixin(SemRet);
};
enum RetryBreakEplg=q{
assert(sstate != SemState.error,"2");
needRetry = true;
mixin(SemRet);
};
template Semantic(T) if(is(T==Node)){
// TODO: needRetry and sstate could be final properties to save one byte of space
// profile to see if it is worth it.
Node rewrite;
/+Node _rewrite;
@property Node rewrite(){ return _rewrite; }
@property Node rewrite(Node n){
if(!_rewrite) assert(!!n);
dw("old: ",_rewrite);
dw("new: ",n);
return _rewrite=n;
}+/
SemState sstate = SemState.begin;
ubyte needRetry = false; // needRetry == 2: unwind stack for circular dep handling
/+ubyte _needRetry = false;
@property ubyte needRetry(){ return _needRetry; }
@property void needRetry(ubyte val){
assert(val!=1||sstate!=SemState.error);
assert(!val || sstate != SemState.completed || isExpression()&&isExpression().isConstant(),val.to!string);
_needRetry=val;
}+/
invariant(){
//assert(sstate!=SemState.error||needRetry!=1, "needRetry and error "~to!string(loc)~" "~to!string(typeid(this))~(cast(Identifier)this?" "~(cast(Identifier)this).name:"")~" Identifier.tryAgain: "~to!string(Identifier.tryAgain)~" needRetry: "~to!string(needRetry)); // !!!!?
}
void semantic(Scope sc)in{assert(sstate>=SemState.begin);}body{
mixin(SemPrlg);
sc.error("feature not implemented",loc);
mixin(ErrEplg);
}
// analysis is trapped because of circular await-relationship involving this node
void noHope(Scope sc){}
}
// error nodes (TODO: file bug against covariance error)
mixin template Semantic(T) if(is(T==ErrorDecl)||is(T==ErrorExp)||is(T==ErrorStm)||is(T==ErrorTy)){
override void semantic(Scope sc){ }
static if(is(T:Declaration))
override void presemantic(Scope sc){assert(0);}
}
enum InContext:ubyte{
none,
addressTaken,
called,
instantiated,
passedToTemplateAndOrAliased,
fieldExp,
}
// expressions
mixin template Semantic(T) if(is(T==Expression)){
Type type;
invariant(){
assert(sstate != SemState.completed || type && type.sstate == SemState.completed,text(typeid(this)," ",loc));
}
// run before semantic if the expression occurs in a specified context
void isInContext(InContext inContext){ }
// TODO: those are not strictly necessary:
final void willTakeAddress(){ isInContext(InContext.addressTaken); }
final void willCall(){ isInContext(InContext.called); }
final void willInstantiate(){ isInContext(InContext.instantiated); }
final void willPassToTemplateAndOrAlias(){ isInContext(InContext.passedToTemplateAndOrAliased); }
final void willAlias(){ willPassToTemplateAndOrAlias(); }
final void willPassToTemplate(){ willPassToTemplateAndOrAlias(); }
protected mixin template ContextSensitive(){
enum isContextSensitive = true;
static assert(!is(typeof(super.inContext)), "already context-sensitive");
auto inContext = InContext.none;
override void isInContext(InContext inContext){
assert(this.inContext.among(InContext.none, inContext), text(this," ",this.inContext," ",inContext));
this.inContext=inContext;
}
final void transferContext(Expression r){
final switch(inContext) with(InContext){
case none: break;
case addressTaken: r.willTakeAddress(); break;
case called: r.willCall(); break;
case instantiated: r.willInstantiate(); break;
case passedToTemplateAndOrAliased: r.willPassToTemplateAndOrAlias(); break;
case fieldExp: if(auto sym=isSymbol()) sym.inContext=InContext.fieldExp; break;
}
}
}
void initOfVar(VarDecl decl){}
override void semantic(Scope sc){
mixin(SemPrlg);
sc.error("feature "~to!string(typeid(this))~" not implemented",loc);
mixin(ErrEplg);
}
Type typeSemantic(Scope sc){
// dw(this," ",sstate," ",typeid(this));
Expression me=this;
if(sstate != SemState.completed){ // TODO: is this ok?
me.semantic(sc);
mixin(Rewrite!q{me});
if(auto ty=me.isType()) return ty;
if(me is this) mixin(SemCheck);
else mixin(SemProp!q{me});
}
// the empty tuple is an expression except if a type is requested
if(auto et=me.isExpTuple()) if(!et.length) return et.type;
if(auto sym=me.isSymbol()) if(auto ov=sym.meaning.isCrossScopeOverloadSet()){
ov.reportConflict(sc,loc);
goto Lerr;
}
sc.error(format("%s '%s' is used as a type",me.kind,me.toString()),loc);
me.sstate = SemState.error;
Lerr:mixin(ErrEplg);
}
final void expSemantic(Scope sc){
semantic(sc);
auto f = this;
mixin(Rewrite!q{f});
void errorOut(){
sc.error(format("%s '%s' is not an expression", f.kind, f.toString()), loc);
rewrite = null;
mixin(ErrEplg);
}
if(f.sstate == SemState.completed){
if(f.isType()) return errorOut();
else if(auto et=f.isTuple()){
foreach(x; et) if(x.isType()) return errorOut();
}
}
}
final void weakenAccessCheck(AccessCheck check){
static struct WeakenCheck{
immutable AccessCheck check;
void perform(Symbol self){
self.accessCheck = min(self.accessCheck, check);
}
void perform(CurrentExp self){
self.accessCheck = min(self.accessCheck, check);
}
void perform(MixinExp self){
self.accessCheck = min(self.accessCheck, check);
}
}
runAnalysis!WeakenCheck(this,check);
}
final void restoreAccessCheck(Scope sc, AccessCheck check){
// TODO: _perform_ access check
static struct RestoreCheck{
immutable AccessCheck check;
bool r=false;
enum b=q{
if(self.accessCheck<check) r=true;
self.accessCheck = check;
};
void perform(Symbol self){ mixin(b); }
void perform(CurrentExp self){ mixin(b); }
void perform(MixinExp self){ mixin(b); }
}
if(runAnalysis!RestoreCheck(this,check).r){
static struct Reset{
void perform(Expression e){ if(!e.isType()) e.sstate = SemState.begin; }
}
runAnalysis!Reset(this);
semantic(sc);
}
}
final void checkAccess(Scope sc,AccessCheck accessCheck){
if(accessCheck==AccessCheck.none) return;
if(auto s=AliasDecl.getAliasBase(this)){
if(s.accessCheck<accessCheck){
s.accessCheck = accessCheck;
static struct ResetSstate{
void perform(Expression e){
if(e.sstate==SemState.error) return;
e.sstate = SemState.begin;
assert(!e.rewrite);
}
}
runAnalysis!ResetSstate(this);
semantic(sc);
}
}
}
bool isConstant(){ return false; }
bool isConstFoldable(){ return false; }
bool isUnique(){ return false; }
Expression clone(Scope sc, InContext inContext, AccessCheck accessCheck, const ref Location loc)in{
assert(sstate == SemState.completed);
}body{
Expression r;
if(isConstFoldable()) r=cloneConstant();
else r=ddup();
r.loc = loc;
r.isInContext(inContext);
return r;
}
private bool fdontConstFold = false; // mere optimization
final void dontConstFold(){fdontConstFold = true;}
final bool isAConstant(){return fdontConstFold;}
final void constFold(Scope sc)in{
assert(sstate == SemState.completed);
assert(!rewrite);
}body{
if(!isConstFoldable() || fdontConstFold) return;
// import std.stdio; writeln("folding constant ", this);
interpret(sc);
}
bool isLvalue(){return false;}
final bool checkLvalue(Scope sc, ref Location l){
if(isLvalue()) return true;
sc.error(format("%s '%s' is not an lvalue",kind,toString()),l);
return false;
}
final bool canMutate(){
return isLvalue() && type.isMutable();
}
bool checkMutate(Scope sc, ref Location l){
if(checkLvalue(sc,l)){
if(type.isMutable()) return true;
else sc.error(format("%s '%s' of type '%s' is read-only",kind,loc.rep,type),l);
}
return false;
}
Dependent!bool implicitlyConvertsTo(Type rhs)in{
assert(sstate == SemState.completed,toString()~" in state "~to!string(sstate));
}body{
if(auto t=type.implicitlyConvertsTo(rhs).prop) return t;
auto l = type.getHeadUnqual().isIntegral(), r = rhs.getHeadUnqual().isIntegral();
if(l && r && l.bitSize()<128 && r.bitSize()<128){ // TODO: VRP for cent and ucent
// note: r.getLongRange is always valid for other basic types
if(l.op == Tok!"long" || l.op == Tok!"ulong"){
return r.getLongRange().contains(getLongRange()).independent;
}else{
return r.getIntRange().contains(getIntRange()).independent;
}
}
return false.independent;
}
Expression implicitlyConvertTo(Type to)in{
assert(to && to.sstate == SemState.completed);
}body{
if(type.equals(to)) return this;
auto r = New!ImplicitCastExp(to,this);
r.loc = loc;
return r;
}
bool typeEquals(Type rhs)in{
assert(sstate == SemState.completed, text(typeid(this)," ",this," ",sstate," ",loc));
}body{
return type.equals(rhs);
}
final bool finishDeduction(Scope sc)in{assert(!!sc,text(this));}body{
static struct PropagateErrors{
void perform(CallExp exp){
// improve overload error messages
// (don't show redundant deduction failure messages)
// not required for correctness
foreach(a;exp.args)
if(auto ae = a.isAddressExp())
if(ae.isUndeducedFunctionLiteral()){
auto r=ae.e.isSymbol().meaning;
mixin(SetErr!q{r});
}
///
}
}
runAnalysis!PropagateErrors(this);
static struct FinishDeduction{
Scope sc;
bool result = true;
void perform(Symbol sym){
if(sym.isFunctionLiteral)
result &= runAnalysis!FinishDeduction(sym.meaning,sc).result;
if(sym.meaning)
if(auto cso=sym.meaning.isCrossScopeOverloadSet()){
cso.reportConflict(sc,sym.loc);
mixin(SetErr!q{sym});
}
}
void perform(FunctionDef fd){
if(fd.sstate == SemState.error) return;
size_t unres=0;
foreach(x; fd.type.params)
if(x.sstate!=SemState.error
&& x.mustBeTypeDeduced())
unres++;
if(!unres) return;
result = false;
if(unres==1){
foreach(x; fd.type.params){
if(!x.mustBeTypeDeduced()) continue;
sc.error(format("cannot deduce type for function literal parameter%s",
x.name?" '"~x.name.name~"'":""),x.loc);
break;
}
}else sc.error("cannot deduce parameter types for function literal",
fd.type.params[0].loc.to(fd.type.params[$-1].loc));
mixin(SetErr!q{fd.type});
mixin(SetErr!q{fd});
return;
}
}
return runAnalysis!FinishDeduction(this,sc).result;
}
// careful: this has to be kept in sync with Type.mostGeneral
final Dependent!Type typeMostGeneral(Expression rhs)in{
assert(sstate == SemState.completed && sstate == rhs.sstate);
}body{
Type r = null;
mixin(ImplConvertsTo!q{bool l2r; this, rhs.type});
mixin(ImplConvertsTo!q{bool r2l; rhs, this.type});
if(l2r ^ r2l){
r = r2l ? type : rhs.type;
STC stc = this.type.getHeadSTC() & rhs.type.getHeadSTC();
r.getHeadUnqual().applySTC(stc);
}
return r.independent;
}
final Dependent!Type typeCombine(Expression rhs)in{
assert(sstate == SemState.completed && sstate == rhs.sstate);
}body{
if(auto r = typeMostGeneral(rhs).prop) return r;
return type.combine(rhs.type);
}
Dependent!bool convertsTo(Type rhs)in{assert(sstate == SemState.completed);}body{
if(auto t=implicitlyConvertsTo(rhs).prop) return t;
if(auto t=type.convertsTo(rhs.getUnqual().getConst()).prop) return t;
return false.independent;
}
final Expression convertTo(Type to)in{assert(type&&to);}body{
if(type is to) return this;
/+/ TODO: do we need this? Why? If needed, also consider the dependee !is null case
auto iconvd = implicitlyConvertsTo(to);
if(!iconvd.dependee&&iconvd.value) return implicitlyConvertTo(to);
/// +/
auto r = New!CastExp(STC.init,to,this);
r.loc = loc;
return r;
}
Dependent!Expression matchCallHelper(Scope sc, const ref Location loc, Type this_, Expression[] args, ref MatchContext context)in{
assert(sstate == SemState.completed);
}body{
auto rd=type.getHeadUnqual().matchCallHelper(sc, loc, this_, args, context);
if(rd.value) rd.value = this; // valid for dependee is null and dependee !is null
return rd;
}
final Dependent!Expression matchCall(Scope sc, const ref Location loc, Expression[] args)in{
assert(sstate == SemState.completed);
}body{
MatchContext context;
mixin(MatchCallHelper!q{auto r; this, sc, loc, null, args, context});
if(!r){
if(sc && finishDeduction(sc)) matchError(sc, loc, null, args);
return null.independent!Expression;
}
if(r.sstate == SemState.completed) r=r.resolveInout(context.inoutRes);
else assert(r.needRetry||r.sstate==SemState.error||cast(TemplateInstanceExp)r, text(r," ",r.sstate," ",r.needRetry));//||r.isSymbol()&&(r.isSymbol().isSymbolMatcher||r.isSymbol().isFunctionLiteral)||cast(TemplateInstanceExp)r,text(r," ",typeid(r),r.isSymbol()?" "~r.isSymbol().meaning.toString():""," ",args," ",r.sstate," ",r.needRetry));
return r.independent;
}
Expression resolveInout(InoutRes res)in{
assert(sstate == SemState.completed);
}body{
type = type.resolveInout(res);
return this;
}
void matchError(Scope sc, Location loc, Type this_, Expression[] args){
sc.error(format("%s '%s' of type '%s' is not callable",kind,toString(),type.toString()),loc);
}
/* members
*/
Scope getMemberScope()in{
assert(sstate == SemState.completed);
}body{
return type.getMemberScope();
}
/* get an expression that can be used as 'this' reference.
this is useful for eg. e.bar!().foo, where e.bar!() is
the lhs expression for the member access, but only 'e'
will be used as 'this' reference.
*/
Expression extractThis(){ return this; }
AccessCheck deferredAccessCheck(){ return AccessCheck.none; }
IntRange getIntRange(){return type.getIntRange();}
LongRange getLongRange(){return type.getLongRange();}
// needed for template instantiation
bool tmplArgEquals(Expression rhs)in{
assert(sstate == SemState.completed,"not completed sstate "~toString());
assert(rhs.sstate == SemState.completed,"rhs not completed sstate "~rhs.toString());
}body{
assert(0, "unsupported operation");
}
size_t tmplArgToHash(){
// default implementation provided
// in order to support arbitrary expressions
// as tuple variable initializers
// TODO: this is hacky
return 0;
}
}
//pragma(msg, __traits(classInstanceSize,Expression)); // 0u. TODO: reduce and report
mixin template Semantic(T) if(is(T==LiteralExp)){
static Expression factory(Variant value)in{
assert(!!value.getType());
}body{
auto vtype=value.getType();
if(auto tt=vtype.isTypeTuple()){
auto vals=value.getTuple();
auto exprs=new Expression[](vals.length);
foreach(i,v;vals){
exprs[i]=factory(v);
assert(exprs[i].sstate==SemState.completed &&
exprs[i].type==tt.allIndices()[i]);
}
return New!ExpTuple(exprs.captureTemplArgs, vtype);
}
auto r = New!LiteralExp(value);
r.semantic(null);
mixin(Rewrite!q{r});
assert(r.type is vtype);
r.dontConstFold();
return r;
}
static Expression polyStringFactory(string value){
Expression r = factory(Variant(value, Type.get!string()));
assert(cast(LiteralExp)r);
(cast(LiteralExp)cast(void*)r).lit.type = Tok!"``";
return r;
}
override void semantic(Scope sc){
mixin(SemPrlg);
type = value.getType();
mixin(SemEplg);
}
override bool isConstant(){ return true; }
override bool isConstFoldable(){ return true; }
final bool isPolyString(){return lit.type == Tok!"``";}
override bool typeEquals(Type rhs){
if(super.typeEquals(rhs)) return true;
if(!isPolyString()) return false;
return rhs is Type.get!wstring()||rhs is Type.get!dstring();
}
override Dependent!bool implicitlyConvertsTo(Type rhs){
if(auto t=super.implicitlyConvertsTo(rhs).prop) return t;
if(type.getHeadUnqual().isSomeString())
if(auto ptr = rhs.getHeadUnqual().isPointerTy()){
return implicitlyConvertsTo(ptr.ty.getDynArr());
}
if(isPolyString()){
assert(Type.get!wstring().implicitlyConvertsTo(rhs).isIndependent &&
Type.get!dstring().implicitlyConvertsTo(rhs).isIndependent );
return Type.get!wstring().implicitlyConvertsTo(rhs).or(
Type.get!dstring().implicitlyConvertsTo(rhs));
}
return false.independent;
}
override IntRange getIntRange(){
if(auto bt = type.getHeadUnqual().isIntegral()){
auto v = value.get!ulong();
bool s = bt.isSigned() || bt.bitSize()<32;
return IntRange(cast(int)v,cast(int)v,s);
}
return super.getIntRange();
}
override LongRange getLongRange(){
if(auto bt = type.getHeadUnqual().isIntegral()){
auto v = value.get!ulong();
bool s = bt.isSigned() || bt.bitSize()<64;
return LongRange(v,v,s);
}
return super.getLongRange();
}
override bool tmplArgEquals(Expression rhs){
if(!type.equals(rhs.type)) return false;
if(!rhs.isConstant()) return false;
return interpretV()==rhs.interpretV();
}
override size_t tmplArgToHash(){
assert(!!type,text("no type! ",this));
import hashtable;
return FNV(type.toHash(), value.toHash());
}
}
mixin template Semantic(T) if(is(T==ArrayLiteralExp)){
Expression litLeftover=null;
override void semantic(Scope sc){
mixin(SemPrlg);
mixin(SemChld!q{lit});
if(!lit.length){if(!type) type=Type.get!EmptyArray(); mixin(SemEplg);}
auto ty=lit[0].type;
if(!type) foreach(i,x;lit[1..$]){
mixin(ImplConvertsTo!q{bool xtoty; x, ty}); // TODO: ditto?