Repository navigation
Expand file tree
/
Copy pathdeclaration.d
More file actions
785 lines (732 loc) · 24.3 KB
/
Copy pathdeclaration.d
File metadata and controls
785 lines (732 loc) · 24.3 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
// Written in the D programming language
// License: http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0
module ast.declaration;
import astopt;
import std.array, std.algorithm, std.range, std.conv, std.exception;
import ast.lexer, ast.type, ast.expression, ast.scope_, util;
abstract class Declaration: Expression{
Identifier name;
this(Identifier name){
this.name=name;
this.type=unit;
}
protected Identifier copyNameImpl(CopyArgs args){
return name?name.copy(args):null;
}
void copyAnalyzedFieldsFrom(Declaration d){
loc=d.loc;
if(d.isSemError()) sstate=SemState.error;
else if(d.isSemCompleted()) sstate=SemState.completed;
canonicalSource_=d.canonicalSource;
// scope, rename, split/merge links, type-const blockers are established per copy
}
override @property string kind(){ return "declaration"; }
final @property Id getId(){ auto r=rename?rename:name; return r?r.id:Id(); }
final @property string getName(){ auto r=rename?rename:name; return r?r.name:""; }
override string toString(){ return getName; }
bool isLinear(){ return true; }
bool isConst(){ return false; }
bool isPinned(){ return false; } // `const` parameters
override Expression evalImpl(){ return this; }
mixin VariableFree;
override int componentsImpl(scope int delegate(Expression) dg){ return 0; }
// semantic information
Scope scope_;
Identifier rename=null;
Declaration splitFrom=null;
Declaration[] splitInto=[];
Declaration[] mergedFrom=[];
Declaration mergedInto=null;
Declaration promotedFrom=null; // if this declaration quantum-promotes another one, the original declaration
EarlyForgottenDecl earlyForgotten=null; // if consumption was speculative early forget
ReturnExp forgottenBeforeEarlyReturn=null; // if forgotten before a conditional because of this early return in a branch
Declaration canonicalSource_=null;
Declaration canonicalSource(){ // TODO: compute eagerly instead?
if(canonicalSource_) return canonicalSource_;
if(splitFrom) return canonicalSource_=splitFrom.canonicalSource;
if(mergedFrom.length==1) return canonicalSource_=mergedFrom[0].canonicalSource;
return canonicalSource_=this;
}
bool isToplevelDeclaration(){
return scope_&&cast(TopScope)scope_;
}
@property splitSequence(){
return recurrence!"a[n-1].splitFrom"(this).until!(d=>d is null);
}
bool isSplitFrom(Declaration outer){
return splitSequence.any!(d=>d is outer);
}
@property Declaration[] derivedSequence(){
auto result=[this];
if(splitFrom) result~=splitFrom.derivedSequence;
foreach(d;mergedFrom)
result~=d.derivedSequence;
return result;
}
bool isDerivedFrom(Declaration origin){
if(this is origin) return true;
if(splitFrom&&splitFrom.isDerivedFrom(origin))
return true;
if(mergedFrom.length&&mergedFrom.all!(d=>d.isDerivedFrom(origin)))
return true;
return false;
}
// semantic information
Expression typeConstBlocker=null;
uint typeConstBlockDepth=0;
}
class CompoundDecl: Expression{
Expression[] s;
this(Expression[] ss){s=ss;}
override CompoundDecl copyImpl(CopyArgs args){
return new CompoundDecl(s.map!(s=>s.copy(args)).array);
}
override string toString(){return "{\n"~indent(join(map!(a=>a.toString()~(a.isCompound()?"":";"))(s),"\n"))~"\n}";}
override bool isCompound(){ return true; }
override int componentsImpl(scope int delegate(Expression) dg){ return 0; }
// semantic information
AggregateScope ascope_;
override Expression evalImpl(){ return this; }
mixin VariableFree; // TODO!
}
class VarDecl: Declaration{
Expression dtype;
this(Identifier name){ super(name); }
override VarDecl copyImpl(CopyArgs args){
//enforce(!args.preserveSemantic||util.among(sstate,SemState.initial,SemState.error),"TODO");
//return new VarDecl(dtype.copy(args));
auto r=new VarDecl(copyNameImpl(args));
if(dtype) r.dtype=dtype.copy(args);
r.isConst_=isConst_;
return r;
}
bool isConst_=false;
override bool isConst(){ return isConst_; }
override string toString(){ return (isConst?"const ":"")~getName~(dtype?": "~dtype.toString():vtype?": "~vtype.toString():""); }
@property override string kind(){ return "variable"; }
alias copyAnalyzedFieldsFrom=Declaration.copyAnalyzedFieldsFrom;
void copyAnalyzedFieldsFrom(VarDecl d){
copyAnalyzedFieldsFrom(cast(Declaration)d);
// dtype, vtype, initializer and definition are established per copy
}
override bool isLinear(){
return vtype&&!vtype.isClassical();
}
// semantic information
Expression vtype;
Expression initializer;
DefineExp definition;
Identifier outOfScopeCause;
bool replaceType;
Identifier outOfScopeDup;
}
class Parameter: VarDecl{
this(bool isConst, Identifier name, Expression type){
super(name); this.dtype=type;
this.isConst_=isConst;
}
override Parameter copyImpl(CopyArgs args){
enforce(!args.preserveSemantic||util.among(sstate,SemState.initial,SemState.error),"TODO");
auto r=new Parameter(isConst,copyNameImpl(args),dtype?dtype.copy(args):dtype);
return r;
}
override bool isLinear(){
return !isConst&&(!vtype||!vtype.isClassical());
}
override bool isPinned(){
return isConst_;
}
override string toString(){
static if(language==silq){
return (isConst?"const ":"moved ")~getName~(vtype?": "~vtype.toString():dtype?": "~dtype.toString():"");
}else return getName~(vtype?": "~vtype.toString():dtype?": "~dtype.toString():"");
}
@property override string kind(){ return "parameter"; }
}
abstract class FixedPointDeclaration: Declaration{
this(Identifier name){ super(name); }
bool typeFinal=false;
FixedPointDeclaration[] dependents=[];
size_t numUpdatesPending=0;
int numInferenceRepetitions=0;
bool unsealed=false;
bool tainted=false;
}
class ToplevelDefinition: FixedPointDeclaration{
DefineExp definition;
DefineExp original;
Expression result;
VarDecl[] vars;
this(DefineExp definition){
super(null);
this.definition=definition;
}
override ToplevelDefinition copyImpl(CopyArgs args){ assert(0); }
override string toString(){ return text("toplevel definition `",definition,"`"); }
}
class FunctionDef: FixedPointDeclaration{
alias ftypeFinal=typeFinal;
Parameter[] params;
bool isTuple;
bool isSquare=false;
auto annotation=Annotation.none;
bool inferAnnotation=false;
Expression rret;
CompoundExp body_;
this(Identifier name, Parameter[] params, bool isTuple, Expression rret, CompoundExp body_)in{
assert(isTuple||params.length==1);
}do{
super(name); this.params=params; this.isTuple=isTuple; this.rret=rret; this.body_=body_;
}
void copyIntrinsicFieldsFrom(FunctionDef fd){
// non-semantic fields shared by all copies (see also copyImpl)
isSquare=fd.isSquare;
annotation=fd.annotation;
inferAnnotation=fd.inferAnnotation;
attributes=fd.attributes.dup;
}
alias copyAnalyzedFieldsFrom=Declaration.copyAnalyzedFieldsFrom;
void copyAnalyzedFieldsFrom(FunctionDef fd){
copyAnalyzedFieldsFrom(cast(Declaration)fd);
copyIntrinsicFieldsFrom(fd);
ret=fd.ret;
hasReturn=fd.hasReturn;
retNames=fd.retNames;
context=fd.context;
thisVar=fd.thisVar;
isConstructor=fd.isConstructor;
sealed=fd.sealed;
captureAnnotationReady=fd.captureAnnotationReady;
ftypeFinal=fd.ftypeFinal;
}
override FunctionDef copyImpl(CopyArgs args){
enforce(!args.preserveSemantic||util.among(sstate,SemState.initial,SemState.error),"TODO");
auto r=new FunctionDef(copyNameImpl(args),params.map!(p=>p.copy(args)).array,isTuple,rret?rret.copy(args):null,body_?body_.copy(args):null);
r.copyIntrinsicFieldsFrom(this);
if(args.preserveMeanings){
r.ret=ret;
r.hasReturn=hasReturn;
r.retNames=retNames;
import ast.substitute: computeCapturesFromBody;
computeCapturesFromBody(r);
}
return r;
}
override string toString(){
string d=isSquare?"[]":"()";
return "def "~(name?getName:"")~d[0]~join(map!(to!string)(params),",")~(isTuple&¶ms.length==1?",":"")~d[1]~(annotation?text(annotation):"")~(body_?body_.toStringFunctionDef():";");
}
override bool isCompound(){ return true; }
override bool isLinear(){ return ftype ? !ftype.isClassical() : context && context.vtype != contextTy(true) || capturedDecls.any!(d=>d.isLinear()); } // TODO: ok?
override Annotation getAnnotation(){ return pure_; }
override int freeVarsImpl(scope int delegate(Identifier) dg){
import ast.substitute:functionDefFreeVarsImpl;
return functionDefFreeVarsImpl(this,dg);
}
override Expression substituteImpl(MapSX!(Id,Expression) subst,TypeTransition* tt){
import ast.substitute:substituteFunctionDefExp;
return substituteFunctionDefExp(this,subst,false,tt);
}
@property override string kind(){ return "function"; }
// semantic information
FunctionScope fscope_;
DatDecl dataTypeOf=null;
VarDecl context;
static if(language==psi) VarDecl contextVal;
VarDecl thisVar; // for constructors
MapX!(Declaration,Identifier[]) captures;
Declaration[] capturedDecls;
bool captureAnnotationReady=false;
bool sealed=false;
static if(language==silq){
SetX!Id consumingCaptures; // consumed classical captures
bool captureReanalysis=false;
}
void addCapture(Declaration meaning,Identifier id)in{
assert(!!meaning&&(!meaning.isLinear||context&&context.vtype==contextTy(false)));
}do{
if(meaning !in captures) capturedDecls~=meaning;
captures[meaning]~=id;
}
final bool isConsumedCapture(Declaration capture)in{
assert(capture in captures);
assert(!!fscope_);
}do{
static if(language==silq) if(capture.name&&capture.name.id in consumingCaptures) return true;
auto id=captures[capture][0];
if(!id.meaning||!id.meaning.scope_) return false;
return id.meaning.scope_.isNestedIn(fscope_);
}
@property string contextName()in{assert(!!context,text(this));}do{ return context.getName; }
final CaptureAnnotation getCaptureAnnotation(){
bool hasConsumed=false;
bool hasConst=false;
foreach(capture;capturedDecls){
import ast.semantic_:typeForDecl;
auto type=typeForDecl(capture);
if(!type||type.isClassical()) continue;
if(isConsumedCapture(capture)) hasConsumed=true;
else hasConst=true;
}
if(!hasConsumed&&!hasConst) return CaptureAnnotation.none;
if(!captureAnnotationReady){
if(hasConsumed) return CaptureAnnotation.moved;
return CaptureAnnotation.none;
}
if(!hasConsumed) return CaptureAnnotation.const_;
if(!hasConst) return CaptureAnnotation.moved;
return CaptureAnnotation.once;
}
Expression ret; // return type
FunTy ftype;
void delegate(Expression)[] ftypeCallbacks; // called as soon as ftype has been determined
bool hasReturn;
bool isConstructor;
string[] retNames;
MapSX!(Id,Expression) attributes;
void seal(){
sealed=true;
}
bool inferringReturnType;
Expression origRret=null;
CompoundExp origBody_=null;
// inference mode
bool finalPassDone=false;
static if(language==silq) SetX!Id loweredConstIds; // for nested loop lowering
static if(language==silq) bool keepLoops=false;
static if(language==silq) int erpStage=0; // early-return elimination: 1: analyzing with loops kept, 2: rewritten
bool deferredSpecificityCheck=false;
void unseal()in{
assert(sealed);
}do{
sealed=false;
unsealed=true;
}
@property Scope realScope(){
if(!scope_) return null;
if(isConstructor) return scope_.getDatDecl().scope_;
return scope_;
}
@property bool isNested(){ return !!cast(NestedScope)realScope; }
@property size_t numArgs(){
if(!ftype) return 0;
return ftype.dom.numComponents;
}
@property size_t numReturns(){
if(!ftype) return 0;
return ftype.cod.numComponents;
}
bool boolAttribute(Id attr, bool default_=false) {
auto p = attributes.getPtr(attr);
if(!p||!*p) return default_;
auto val = *p;
if(!val) return default_;
auto num = val.asIntegerConstant();
if(!num) return default_; // TODO
return num.get() != 0;
}
string stringAttribute(Id attr, string default_=null) {
auto p = attributes.getPtr(attr);
if(!p) return default_;
auto e = cast(LiteralExp)*p;
if(!e) return default_;
auto str = e.asStringConstant();
if(!str) return default_; // TODO
return str.get();
}
FunctionDef reversed=null;
bool isMain=false;
}
enum Variance{
invariant_,
covariant,
contravariant,
}
class DatParameter: Parameter{
Variance variance;
this(Variance variance, Identifier name, Expression type){
this.variance=variance;
super(true,name,type);
}
override DatParameter copyImpl(CopyArgs args){
return new DatParameter(variance,copyNameImpl(args),dtype.copy(args));
}
override string toString(){
final switch(variance)with(Variance){
case invariant_: return super.toString();
case covariant: return "+"~super.toString();
case contravariant: return "-"~super.toString();
}
}
}
class DatDecl: Declaration{
AggregateTy dtype;
bool hasParams;
DatParameter[] params;
bool isTuple;
bool isQuantum;
CompoundDecl body_;
this(Identifier name,bool hasParams,DatParameter[] params,bool isTuple,bool isQuantum,CompoundDecl body_)in{
if(hasParams) assert(isTuple||params.length==1);
else assert(isTuple&¶ms.length==0);
}do{
super(name);
this.hasParams=hasParams;
this.params=params;
this.isTuple=isTuple;
this.isQuantum=isQuantum;
this.body_=body_;
}
override DatDecl copyImpl(CopyArgs args){
return new DatDecl(copyNameImpl(args),hasParams,params.map!(p=>p.copy(args)).array,isTuple,isQuantum,body_.copy(args));
}
override string toString(){
return "dat "~getName~(hasParams?text("[",params.map!(to!string).joiner(","),"]"):"")~(body_?body_.toString():";");
}
override bool isCompound(){ return true; }
override bool isLinear(){ return false; }
final MapSX!(Id,Expression) getSubst(Expression arg){
MapSX!(Id,Expression) subst;
if(isTuple){
foreach(i,p;params)
subst[p.getId]=new IndexExp(arg,new LiteralExp(Token(Tok!"0",to!string(i)))).eval();
}else{
assert(params.length==1);
subst[params[0].getId]=arg;
}
return subst;
}
// semantic information
int semanticDepth=0; // TODO: get rid of this
FunctionDef constructor;
DataScope dscope_;
VarDecl context;
MapX!(Declaration,Identifier[]) captures;
Declaration[] capturedDecls;
void addCapture(Declaration meaning,Identifier id){
if(meaning !in captures) capturedDecls~=meaning;
captures[meaning]~=id;
}
@property string contextName()in{assert(!!context);}do{ return context.getName; }
@property bool isNested(){ return !!cast(NestedScope)scope_; }
FunctionDef fd;
FunctionDef toFunctionDef()in{ // TODO: parse DatDecl with params as function with a local DatDecl inside in the first place?
assert(hasParams&&isSemCompleted());
}do{
if(fd) return fd;
auto fparams=params.map!((dparam){
auto name=new Identifier(dparam.getId);
name.loc=dparam.name.loc;
auto param=new Parameter(dparam.isConst, name, dparam.dtype);
param.loc=dparam.loc;
param.vtype=dparam.vtype;
assert(dparam.isSemCompleted());
param.sstate=dparam.sstate;
return param;
}).array;
auto id=new Identifier(getId);
id.loc=this.loc;
id.meaning=this;
import ast.semantic_:typeForDecl;
id.type=typeForDecl(this);
id.setSemCompleted();
auto ids=fparams.map!((fparam){
auto id=new Identifier(fparam.getId);
id.loc=fparam.loc;
id.meaning=fparam;
id.type=fparam.vtype;
id.setSemCompleted();
return id;
}).array;
Expression arg=ids[0];
if(isTuple){
arg=new TupleExp(ids.map!((Expression id)=>id).array);
arg.loc=ids.length?ids[0].loc.to(ids[$-1].loc):this.loc;
arg.type=tupleTy(ids.map!(id=>id.type).array);
arg.setSemCompleted();
}
CallExp call=new CallExp(id,arg,true,false);
call.loc=id.loc.to(arg.loc);
import ast.semantic_: ConstResult, InType, expSemContext, callSemantic; // TODO: get rid of this?
auto ncall=callSemantic(call,expSemContext(null,ConstResult.no,InType.no));
ncall.setSemCompleted();
auto ret=new ReturnExp(ncall);
ret.type=unit;
ret.setSemCompleted();
auto bdy=new CompoundExp([ret]);
bdy.type=unit;
bdy.setSemCompleted();
fd=new FunctionDef(null, fparams, isTuple, null, bdy);
fd.loc=this.loc;
fd.dataTypeOf=this;
fd.isSquare=true;
fd.annotation=pure_;
fd.scope_=this.scope_;
fd.ftype=cast(ProductTy)id.type;
assert(fd.ftype);
assert(!captures.length,"nested dat decl not supported");
fd.fscope_=new FunctionScope(this.dscope_.parent,fd);
foreach(fparam; fparams) {
fparam.scope_ = fd.fscope_;
}
fd.context=this.context;
fd.ret=fd.ftype.cod;
assert(isType(fd.ret));
fd.hasReturn=true;
fd.retNames=["r"];
fd.setSemCompleted();
return fd;
}
}
class ImportExp: Declaration{
Expression[] e;
this(Expression[] e){
super(null);
this.e=e;
}
override ImportExp copyImpl(CopyArgs args){
return new ImportExp(e.map!(e=>e.copy(args)).array);
}
static string getPath(Expression e){
static string doIt(Expression e){
import util.path;
if(auto i=cast(Identifier)e) return i.name;
if(auto f=cast(BinaryExp!(Tok!"."))e) return buildPath(doIt(f.e1),doIt(f.e2));
assert(0);
}
return doIt(e);
}
override @property string kind(){ return "import declaration"; }
override string toString(){ return "import "~e.map!(to!string).join(","); }
override bool isLinear(){ return false; }
}
// special declarations used during semantic analysis
abstract class DeadDecl: Declaration{
bool sameExplanation(DeadDecl other){ return this is other; }
this(Identifier name){
super(name);
}
override DeadDecl copyImpl(CopyArgs cargs){
return this; // TODO: ok?
}
bool reportUndefinedIdentifier(Identifier id,Scope sc){ return false; }
abstract void explain(string kind,Scope sc);
}
class ConsumedDecl: DeadDecl{
override bool sameExplanation(DeadDecl other){
auto o=cast(ConsumedDecl)other;
return o&&typeid(o) is typeid(this)&&o.use is use;
}
Identifier use;
this(Declaration decl,Identifier use)in{
assert(!!use);
}do{
super(decl.name);
this.type=decl.type;
this.use=use;
}
override void explain(string kind,Scope sc){
import std.format:format;
sc.note(format("%s `%s` consumed here",kind,use.meaning),use.loc);
}
override string toString(){
return text("consumed(",super.toString(),",",use.loc,")");
}
}
class OutOfScopeDecl: ConsumedDecl{
Identifier cause;
Identifier dupUse;
override bool sameExplanation(DeadDecl other){
auto o=cast(OutOfScopeDecl)other;
return o&&o.use is use&&o.cause is cause&&o.dupUse is dupUse;
}
this(Declaration decl,Identifier use,Identifier cause,Identifier dupUse=null)in{
assert(!!cause);
}do{
super(decl,use);
this.cause=cause;
this.dupUse=dupUse;
}
override void explain(string kind,Scope sc){
import std.format:format;
if(!dupUse||dupUse is use){
super.explain(kind,sc);
}else sc.note(format("%s `%s` went out of scope here",kind,use.meaning),use.loc);
if(dupUse&&dupUse !is use)
sc.note(format("`%s` was used in a consuming position here",dupUse.name),dupUse.loc);
sc.note(format("`%s` not recomputable after dependency `%s` was consumed here",use.name,cause.name),cause.loc);
}
override string toString(){
return text("outOfScope(",super.toString(),",",cause.loc,")");
}
}
class EarlyForgottenDecl: DeadDecl{
Declaration decl;
Declaration consumed;
Identifier use;
EarlyForgottenDecl reportVia=null;
this(Declaration decl,Declaration consumed,Identifier use)in{
assert(!!decl&&!!consumed&&!!use);
}do{
super(decl.name);
this.type=decl.type;
this.decl=decl;
this.consumed=consumed;
this.use=use;
}
override bool reportUndefinedIdentifier(Identifier id,Scope sc){
import std.format:format;
import ast.semantic_:typeForDecl;
if(reportVia) return reportVia.reportUndefinedIdentifier(id,sc);
if(isSemError()) return true;
setSemForceError();
sc.error(format("cannot consume `const` %s `%s`",consumed.kind,use),use.loc);
sc.note(format("`%s` cannot be consumed because the type `%s` of live %s `%s` depends on it",consumed.name,typeForDecl(decl),decl.kind,decl.getName),decl.loc);
return true;
}
override void explain(string kind,Scope sc){
import std.format:format;
if(isSemError()) return; // report only once
setSemForceError();
sc.note(format("%s `%s` consumed here",kind,decl),use?use.loc:decl.loc);
}
override string toString(){
return text("earlyForgotten(",super.toString(),",",use?text(use.loc):"<?>",")");
}
}
class EarlyReturnForgottenDecl: ConsumedDecl{
Declaration decl;
ReturnExp ret;
this(Declaration decl,Identifier use,ReturnExp ret)in{
assert(!!ret);
}do{
super(decl,use);
this.decl=decl;
this.ret=ret;
}
override bool reportUndefinedIdentifier(Identifier id,Scope sc){
import std.format:format;
if(isSemError()) return true; // (report only once)
setSemForceError();
if(cast(Parameter)decl) sc.error(format("%s `%s` is not consumed (perhaps return it or annotate it `const`)",decl.kind,decl.getName),decl.loc);
else sc.error(format("%s `%s` is not consumed (perhaps return it)",decl.kind,decl.getName),decl.loc);
sc.note("at function return",ret.loc);
sc.note(format("`%s` cannot be forgotten before the conditional, as it is used again here",decl.getName),id.loc);
return true;
}
override void explain(string kind,Scope sc){
import std.format:format;
sc.note(format("%s `%s` forgotten here, before a conditional with an early return",kind,use.meaning),use.loc);
sc.note("early return is here",ret.loc);
}
override string toString(){
return text("earlyReturnForgotten(",super.toString(),",",ret.loc,")");
}
}
class IllegalConsumedDecl: ConsumedDecl{
EarlyForgottenDecl earlyForgotten;
this(Declaration decl,Identifier use,EarlyForgottenDecl earlyForgotten)in{
assert(!!earlyForgotten);
}do{
super(decl,use);
this.earlyForgotten=earlyForgotten;
}
override bool reportUndefinedIdentifier(Identifier id,Scope sc){
return earlyForgotten.reportUndefinedIdentifier(id,sc);
}
}
class DeadMerge: DeadDecl{
bool quantumControl;
size_t numBranches=2;
this(Identifier name){
super(name);
}
override bool reportUndefinedIdentifier(Identifier id,Scope sc){
if(mergedFrom.length<numBranches&&mergedFrom.any!(d=>d.isSemError())) return true;
bool handled=false;
foreach(d;mergedFrom)
if(auto dd=cast(DeadDecl)d)
handled=dd.reportUndefinedIdentifier(id,sc)||handled;
return handled;
}
override void explain(string kind,Scope sc){
import std.format:format;
import ast.semantic_:typeForDecl;
assert(mergedFrom.length!=0);
auto deadDecls=mergedFrom.map!(d=>cast(DeadDecl)d).filter!(d=>!!d).array;
if(deadDecls.length){
DeadDecl[] explained;
foreach(dd;deadDecls){
if(explained.any!(e=>e.sameExplanation(dd))) continue;
explained~=dd;
dd.explain(kind,sc); // TODO: good?
}
return;
}
if(mergedFrom.length==1){
sc.note("declared on only one path",mergedFrom[0].loc);
}else if(mergedFrom.length<numBranches){
foreach(d;mergedFrom){
auto type=typeForDecl(d);
sc.note("declared on this path",d.loc);
}
auto d=mergedFrom[$-1];
sc.note("however, not declared on all paths",d.loc);
}else if(mergedFrom.length==numBranches){
Expression common=bottom;
foreach(d;mergedFrom){
auto type=typeForDecl(d);
if(type) common=common?joinTypes(common,type):null;
}
if(quantumControl){
bool ok=false;
foreach(d;mergedFrom){
auto type=typeForDecl(d);
if(!type) continue;
if(!isType(type.getQuantum)){
sc.note(format("declaration under quantum `if` has type `%s` which cannot be promoted to quantum",type),d.loc);
if(type.isSubtype(ℤt(true))){
sc.note("did you mean to use `int[n]` or `uint[n]`, with explicit bit width `n`?",d.loc);
}else if(cast(ArrayTy)type){
sc.note("quantum-dependent tuple length not yet supported",d.loc);
}else if(cast(FunTy)type){
sc.note("quantum-dependent closures not yet supported",d.loc);
}
ok=true;
break; // TODO: good?
}
}
if(ok) return;
if(common&&!common.getQuantum){
foreach(d;mergedFrom){
auto type=typeForDecl(d);
sc.note(format("declared with type `%s` here",type),d.loc);
}
auto d=mergedFrom[$-1];
sc.note(format("declarations under quantum `if` have common type `%s` which cannot be promoted to quantum",common),d.loc);
if(cast(ArrayTy)common){
sc.note("quantum-dependent tuple length not yet supported",d.loc);
}else if(cast(FunTy)type){
sc.note("quantum-dependent closures not yet supported",d.loc);
}
return;
}
}
if(!common){
foreach(d;mergedFrom){
auto type=typeForDecl(d);
sc.note(format("declared with type `%s` here",type),d.loc);
}
auto d=mergedFrom[$-1];
sc.note("declarations on different paths have incompatible types",d.loc);
}
}
}
override string toString(){
return text("deadMerge(",super.toString(),")");
}
}
bool isConstLocal(Declaration decl){
auto vd=cast(VarDecl)decl;
return vd&&!cast(Parameter)vd&&vd.isConst_;
}