/
statementsem.d
5041 lines (4526 loc) · 171 KB
/
statementsem.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
/**
* Does semantic analysis for statements.
*
* Specification: $(LINK2 https://dlang.org/spec/statement.html, Statements)
*
* Copyright: Copyright (C) 1999-2024 by The D Language Foundation, All Rights Reserved
* Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
* License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/statementsem.d, _statementsem.d)
* Documentation: https://dlang.org/phobos/dmd_statementsem.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/statementsem.d
*/
module dmd.statementsem;
import core.stdc.stdio;
import dmd.aggregate;
import dmd.arrayop;
import dmd.arraytypes;
import dmd.astcodegen;
import dmd.astenums;
import dmd.blockexit;
import dmd.clone;
import dmd.cond;
import dmd.ctorflow;
import dmd.dcast;
import dmd.dclass;
import dmd.declaration;
import dmd.denum;
import dmd.dimport;
import dmd.dinterpret;
import dmd.dmodule;
import dmd.dscope;
import dmd.dsymbol;
import dmd.dsymbolsem;
import dmd.errors;
import dmd.escape;
import dmd.expression;
import dmd.expressionsem;
import dmd.func;
import dmd.funcsem;
import dmd.globals;
import dmd.hdrgen;
import dmd.iasm;
import dmd.id;
import dmd.identifier;
import dmd.importc;
import dmd.init;
import dmd.intrange;
import dmd.location;
import dmd.mtype;
import dmd.mustuse;
import dmd.nogc;
import dmd.optimize;
import dmd.opover;
import dmd.parse;
import dmd.common.outbuffer;
import dmd.root.string;
import dmd.semantic2;
import dmd.sideeffect;
import dmd.statement;
import dmd.target;
import dmd.tokens;
import dmd.typesem;
import dmd.visitor;
version (DMDLIB)
{
version = CallbackAPI;
}
/*****************************************
* CTFE requires FuncDeclaration::labtab for the interpretation.
* So fixing the label name inside in/out contracts is necessary
* for the uniqueness in labtab.
* Params:
* sc = context
* ident = statement label name to be adjusted
* Returns:
* adjusted label name
*/
private Identifier fixupLabelName(Scope* sc, Identifier ident)
{
uint flags = (sc.flags & SCOPE.contract);
const id = ident.toString();
if (flags && flags != SCOPE.invariant_ &&
!(id.length >= 2 && id[0] == '_' && id[1] == '_')) // does not start with "__"
{
OutBuffer buf;
buf.writestring(flags == SCOPE.require ? "__in_" : "__out_");
buf.writestring(ident.toString());
ident = Identifier.idPool(buf[]);
}
return ident;
}
/*******************************************
* Check to see if statement is the innermost labeled statement.
* Params:
* sc = context
* statement = Statement to check
* Returns:
* if `true`, then the `LabelStatement`, otherwise `null`
*/
private LabelStatement checkLabeledLoop(Scope* sc, Statement statement) @safe
{
if (sc.slabel && sc.slabel.statement == statement)
{
return sc.slabel;
}
return null;
}
/***********************************************************
* Check an assignment is used as a condition.
* Intended to be use before the `semantic` call on `e`.
* Params:
* e = condition expression which is not yet run semantic analysis.
* Returns:
* `e` or ErrorExp.
*/
private Expression checkAssignmentAsCondition(Expression e, Scope* sc)
{
if (sc.flags & SCOPE.Cfile)
return e;
auto ec = lastComma(e);
if (ec.op == EXP.assign)
{
error(ec.loc, "assignment cannot be used as a condition, perhaps `==` was meant?");
return ErrorExp.get();
}
return e;
}
// Performs semantic analysis in Statement AST nodes
Statement statementSemantic(Statement s, Scope* sc)
{
import dmd.compiler;
version (CallbackAPI)
Compiler.onStatementSemanticStart(s, sc);
Statement result = statementSemanticVisit(s, sc);
version (CallbackAPI)
Compiler.onStatementSemanticDone(s, sc);
return result;
}
package (dmd)
Statement statementSemanticVisit(Statement s, Scope* sc)
{
Statement result;
void setError()
{
result = new ErrorStatement();
}
void visitDefaultCase(Statement s)
{
result = s;
}
void visitError(ErrorStatement s)
{
result = s;
}
void visitPeel(PeelStatement s)
{
/* "peel" off this wrapper, and don't run semantic()
* on the result.
*/
result = s.s;
}
void visitExp(ExpStatement s)
{
/* https://dlang.org/spec/statement.html#expression-statement
*/
if (!s.exp)
{
result = s;
return;
}
//printf("ExpStatement::semantic() %s\n", exp.toChars());
// Allow CommaExp in ExpStatement because return isn't used
CommaExp.allow(s.exp);
s.exp = s.exp.expressionSemantic(sc);
s.exp = resolveProperties(sc, s.exp);
s.exp = s.exp.addDtorHook(sc);
if (checkNonAssignmentArrayOp(s.exp))
s.exp = ErrorExp.get();
if (auto f = isFuncAddress(s.exp))
{
if (f.checkForwardRef(s.exp.loc))
s.exp = ErrorExp.get();
}
if (checkMustUse(s.exp, sc))
s.exp = ErrorExp.get();
if (!(sc.flags & SCOPE.Cfile) && discardValue(s.exp))
s.exp = ErrorExp.get();
s.exp = s.exp.optimize(WANTvalue);
s.exp = checkGC(sc, s.exp);
if (s.exp.op == EXP.error)
return setError();
result = s;
}
void visitDtorExp(DtorExpStatement s)
{
visitExp(s);
}
void visitMixin(MixinStatement cs)
{
/* https://dlang.org/spec/statement.html#mixin-statement
*/
//printf("MixinStatement::semantic() %s\n", exp.toChars());
Statements* a = cs.flatten(sc);
if (!a)
return;
Statement s = new CompoundStatement(cs.loc, a);
result = s.statementSemantic(sc);
}
void visitCompound(CompoundStatement cs)
{
//printf("CompoundStatement::semantic(this = %p, sc = %p)\n", cs, sc);
version (none)
{
foreach (i, s; cs.statements)
{
if (s)
printf("[%d]: %s", i, s.toChars());
}
}
for (size_t i = 0; i < cs.statements.length;)
{
Statement s = (*cs.statements)[i];
if (!s)
{
++i;
continue;
}
if (auto flt = s.flatten(sc))
{
cs.statements.remove(i);
cs.statements.insert(i, flt);
continue;
}
s = s.statementSemantic(sc);
(*cs.statements)[i] = s;
if (!s)
{
/* Remove NULL statements from the list.
*/
cs.statements.remove(i);
continue;
}
if (s.isErrorStatement())
{
result = s; // propagate error up the AST
++i;
continue; // look for errors in rest of statements
}
// expand tuple variables in order to attach destruction/exception logic
if (auto es = s.isExpStatement())
{
if (es.exp && es.exp.isDeclarationExp())
{
auto de = es.exp.isDeclarationExp();
auto vd = de.declaration.isVarDeclaration();
if (vd && vd.aliasTuple && vd.aliasTuple.objects.length)
{
auto j = i;
cs.statements.insert(i, vd.aliasTuple.objects.length - 1, null);
vd.aliasTuple.foreachVar((v) { (*cs.statements)[j++] = toStatement(v); });
s = (*cs.statements)[i];
}
}
}
Statement sentry;
Statement sexception;
Statement sfinally;
(*cs.statements)[i] = s.scopeCode(sc, sentry, sexception, sfinally);
if (sentry)
{
sentry = sentry.statementSemantic(sc);
cs.statements.insert(i, sentry);
i++;
}
if (sexception)
sexception = sexception.statementSemantic(sc);
if (sexception)
{
/* Returns: true if statements[] are empty statements
*/
static bool isEmpty(const Statement[] statements)
{
foreach (s; statements)
{
if (const cs = s.isCompoundStatement())
{
if (!isEmpty((*cs.statements)[]))
return false;
}
else
return false;
}
return true;
}
if (!sfinally && isEmpty((*cs.statements)[i + 1 .. cs.statements.length]))
{
}
else
{
/* Rewrite:
* s; s1; s2;
* As:
* s;
* try { s1; s2; }
* catch (Throwable __o)
* { sexception; throw __o; }
*/
auto a = new Statements();
a.pushSlice((*cs.statements)[i + 1 .. cs.statements.length]);
cs.statements.setDim(i + 1);
Statement _body = new CompoundStatement(Loc.initial, a);
_body = new ScopeStatement(Loc.initial, _body, Loc.initial);
Identifier id = Identifier.generateId("__o");
Statement handler = new PeelStatement(sexception);
if (sexception.blockExit(sc.func, null) & BE.fallthru)
{
auto ts = new ThrowStatement(Loc.initial, new IdentifierExp(Loc.initial, id));
ts.internalThrow = true;
handler = new CompoundStatement(Loc.initial, handler, ts);
}
auto catches = new Catches();
auto ctch = new Catch(Loc.initial, getThrowable(), id, handler);
ctch.internalCatch = true;
catches.push(ctch);
Statement st = new TryCatchStatement(Loc.initial, _body, catches);
if (sfinally)
st = new TryFinallyStatement(Loc.initial, st, sfinally);
st = st.statementSemantic(sc);
cs.statements.push(st);
break;
}
}
else if (sfinally)
{
if (0 && i + 1 == cs.statements.length)
{
cs.statements.push(sfinally);
}
else
{
/* Rewrite:
* s; s1; s2;
* As:
* s; try { s1; s2; } finally { sfinally; }
*/
auto a = new Statements();
a.pushSlice((*cs.statements)[i + 1 .. cs.statements.length]);
cs.statements.setDim(i + 1);
auto _body = new CompoundStatement(Loc.initial, a);
Statement stf = new TryFinallyStatement(Loc.initial, _body, sfinally);
stf = stf.statementSemantic(sc);
cs.statements.push(stf);
break;
}
}
i++;
}
/* Flatten them in place
*/
void flattenStatements(ref Statements statements)
{
for (size_t i = 0; i < statements.length;)
{
if (auto s = statements[i])
{
if (auto flt = s.flatten(sc))
{
statements.remove(i);
statements.insert(i, flt);
continue;
}
}
++i;
}
}
/* https://issues.dlang.org/show_bug.cgi?id=11653
* 'semantic' may return another CompoundStatement
* (eg. CaseRangeStatement), so flatten it here.
*/
flattenStatements(*cs.statements);
foreach (s; *cs.statements)
{
if (!s)
continue;
if (auto se = s.isErrorStatement())
{
result = se;
return;
}
}
if (cs.statements.length == 1)
{
result = (*cs.statements)[0];
return;
}
result = cs;
}
void visitUnrolledLoop(UnrolledLoopStatement uls)
{
//printf("UnrolledLoopStatement::semantic(this = %p, sc = %p)\n", uls, sc);
Scope* scd = sc.push();
scd.sbreak = uls;
scd.scontinue = uls;
Statement serror = null;
foreach (i, ref s; *uls.statements)
{
if (s)
{
//printf("[%d]: %s\n", i, s.toChars());
s = s.statementSemantic(scd);
if (s && !serror)
serror = s.isErrorStatement();
}
}
scd.pop();
result = serror ? serror : uls;
}
void visitScope(ScopeStatement ss)
{
//printf("ScopeStatement::semantic(sc = %p)\n", sc);
if (!ss.statement)
{
result = ss;
return;
}
ScopeDsymbol sym = new ScopeDsymbol();
sym.parent = sc.scopesym;
sym.endlinnum = ss.endloc.linnum;
sc = sc.push(sym);
Statements* a = ss.statement.flatten(sc);
if (a)
{
ss.statement = new CompoundStatement(ss.loc, a);
}
ss.statement = ss.statement.statementSemantic(sc);
if (ss.statement)
{
if (ss.statement.isErrorStatement())
{
sc.pop();
result = ss.statement;
return;
}
Statement sentry;
Statement sexception;
Statement sfinally;
ss.statement = ss.statement.scopeCode(sc, sentry, sexception, sfinally);
assert(!sentry);
assert(!sexception);
if (sfinally)
{
//printf("adding sfinally\n");
sfinally = sfinally.statementSemantic(sc);
ss.statement = new CompoundStatement(ss.loc, ss.statement, sfinally);
}
}
sc.pop();
result = ss;
}
void visitForwarding(ForwardingStatement ss)
{
assert(ss.sym);
for (Scope* csc = sc; !ss.sym.parent; csc = csc.enclosing)
{
assert(csc);
ss.sym.parent = csc.scopesym;
}
sc = sc.push(ss.sym);
sc.sbreak = ss;
sc.scontinue = ss;
ss.statement = ss.statement.statementSemantic(sc);
sc = sc.pop();
result = ss.statement;
}
void visitWhile(WhileStatement ws)
{
/* Rewrite as a for(;condition;) loop
* https://dlang.org/spec/statement.html#while-statement
*/
Expression cond = ws.condition;
Statement _body = ws._body;
if (ws.param)
{
/**
* If the while loop is of form `while(auto a = exp) { loop_body }`,
* rewrite to:
*
* while(true)
* if (auto a = exp)
* { loop_body }
* else
* { break; }
*/
_body = new IfStatement(ws.loc, ws.param, ws.condition, ws._body, new BreakStatement(ws.loc, null), ws.endloc);
cond = IntegerExp.createBool(true);
}
Statement s = new ForStatement(ws.loc, null, cond, null, _body, ws.endloc);
s = s.statementSemantic(sc);
result = s;
}
void visitDo(DoStatement ds)
{
/* https://dlang.org/spec/statement.html#do-statement
*/
const inLoopSave = sc.inLoop;
sc.inLoop = true;
if (ds._body)
ds._body = ds._body.semanticScope(sc, ds, ds, null);
sc.inLoop = inLoopSave;
if (auto dotid = ds.condition.isDotIdExp())
dotid.noderef = true;
// check in syntax level
ds.condition = checkAssignmentAsCondition(ds.condition, sc);
ds.condition = ds.condition.expressionSemantic(sc);
ds.condition = resolveProperties(sc, ds.condition);
if (checkNonAssignmentArrayOp(ds.condition))
ds.condition = ErrorExp.get();
ds.condition = ds.condition.optimize(WANTvalue);
ds.condition = checkGC(sc, ds.condition);
ds.condition = ds.condition.toBoolean(sc);
if (ds.condition.op == EXP.error)
return setError();
if (ds._body && ds._body.isErrorStatement())
{
result = ds._body;
return;
}
result = ds;
}
void visitFor(ForStatement fs)
{
/* https://dlang.org/spec/statement.html#for-statement
*/
//printf("ForStatement::semantic %s\n", fs.toChars());
if (fs._init)
{
/* Rewrite:
* for (auto v1 = i1, v2 = i2; condition; increment) { ... }
* to:
* { auto v1 = i1, v2 = i2; for (; condition; increment) { ... } }
* then lowered to:
* auto v1 = i1;
* try {
* auto v2 = i2;
* try {
* for (; condition; increment) { ... }
* } finally { v2.~this(); }
* } finally { v1.~this(); }
*/
auto ainit = new Statements();
ainit.push(fs._init);
fs._init = null;
ainit.push(fs);
Statement s = new CompoundStatement(fs.loc, ainit);
s = new ScopeStatement(fs.loc, s, fs.endloc);
s = s.statementSemantic(sc);
if (!s.isErrorStatement())
{
if (LabelStatement ls = checkLabeledLoop(sc, fs))
ls.gotoTarget = fs;
fs.relatedLabeled = s;
}
result = s;
return;
}
assert(fs._init is null);
auto sym = new ScopeDsymbol();
sym.parent = sc.scopesym;
sym.endlinnum = fs.endloc.linnum;
sc = sc.push(sym);
sc.inLoop = true;
if (fs.condition)
{
if (auto dotid = fs.condition.isDotIdExp())
dotid.noderef = true;
// check in syntax level
fs.condition = checkAssignmentAsCondition(fs.condition, sc);
fs.condition = fs.condition.expressionSemantic(sc);
fs.condition = resolveProperties(sc, fs.condition);
if (checkNonAssignmentArrayOp(fs.condition))
fs.condition = ErrorExp.get();
fs.condition = fs.condition.optimize(WANTvalue);
fs.condition = checkGC(sc, fs.condition);
fs.condition = fs.condition.toBoolean(sc);
}
if (fs.increment)
{
CommaExp.allow(fs.increment);
fs.increment = fs.increment.expressionSemantic(sc);
fs.increment = resolveProperties(sc, fs.increment);
// @@@DEPRECATED_2.112@@@
// remove gagging and deprecation() to turn deprecation into an error when
// deprecation cycle is over
const olderrors = global.startGagging();
discardValue(fs.increment);
if (global.endGagging(olderrors))
deprecation(fs.increment.loc, "`%s` has no effect", fs.increment.toChars());
if (checkNonAssignmentArrayOp(fs.increment))
fs.increment = ErrorExp.get();
fs.increment = fs.increment.optimize(WANTvalue);
fs.increment = checkGC(sc, fs.increment);
}
sc.sbreak = fs;
sc.scontinue = fs;
if (fs._body)
fs._body = fs._body.semanticNoScope(sc);
sc.pop();
if (fs.condition && fs.condition.op == EXP.error ||
fs.increment && fs.increment.op == EXP.error ||
fs._body && fs._body.isErrorStatement())
return setError();
result = fs;
}
void visitForeach(ForeachStatement fs)
{
/* https://dlang.org/spec/statement.html#foreach-statement
*/
//printf("ForeachStatement::semantic() %p\n", fs);
/******
* Issue error if any of the ForeachTypes were not supplied and could not be inferred.
* Returns:
* true if error issued
*/
static bool checkForArgTypes(ForeachStatement fs)
{
bool result = false;
foreach (p; *fs.parameters)
{
if (!p.type)
{
error(fs.loc, "cannot infer type for `foreach` variable `%s`, perhaps set it explicitly", p.ident.toChars());
p.type = Type.terror;
result = true;
}
}
return result;
}
const loc = fs.loc;
const dim = fs.parameters.length;
fs.func = sc.func;
if (fs.func.fes)
fs.func = fs.func.fes.func;
VarDeclaration vinit = null;
fs.aggr = fs.aggr.expressionSemantic(sc);
fs.aggr = resolveProperties(sc, fs.aggr);
fs.aggr = fs.aggr.optimize(WANTvalue);
if (fs.aggr.op == EXP.error)
return setError();
Expression oaggr = fs.aggr; // remember original for error messages
if (fs.aggr.type && fs.aggr.type.toBasetype().isTypeStruct() &&
fs.aggr.type.toBasetype().isTypeStruct().sym.dtor &&
!fs.aggr.isTypeExp() && !fs.aggr.isLvalue())
{
// https://issues.dlang.org/show_bug.cgi?id=14653
// Extend the life of rvalue aggregate till the end of foreach.
vinit = copyToTemp(STC.rvalue, "__aggr", fs.aggr);
vinit.endlinnum = fs.endloc.linnum;
vinit.dsymbolSemantic(sc);
fs.aggr = new VarExp(fs.aggr.loc, vinit);
}
/* If aggregate is a vector type, add the .array to make it a static array
*/
if (fs.aggr.type)
if (auto tv = fs.aggr.type.toBasetype().isTypeVector())
{
auto vae = new VectorArrayExp(fs.aggr.loc, fs.aggr);
vae.type = tv.basetype;
fs.aggr = vae;
}
Dsymbol sapply = null; // the inferred opApply() or front() function
if (!inferForeachAggregate(sc, fs.op == TOK.foreach_, fs.aggr, sapply))
{
assert(oaggr.type);
error(fs.loc, "invalid `%s` aggregate `%s` of type `%s`",
Token.toChars(fs.op), oaggr.toChars(), oaggr.type.toPrettyChars());
if (auto ad = isAggregate(fs.aggr.type))
{
if (fs.op == TOK.foreach_reverse_)
{
fs.loc.errorSupplemental("`foreach_reverse` works with bidirectional ranges"~
" (implementing `back` and `popBack`), aggregates implementing" ~
" `opApplyReverse`, or the result of an aggregate's `.tupleof` property");
fs.loc.errorSupplemental("https://dlang.org/phobos/std_range_primitives.html#isBidirectionalRange");
}
else
{
fs.loc.errorSupplemental("`foreach` works with input ranges"~
" (implementing `front` and `popFront`), aggregates implementing" ~
" `opApply`, or the result of an aggregate's `.tupleof` property");
fs.loc.errorSupplemental("https://dlang.org/phobos/std_range_primitives.html#isInputRange");
}
}
return setError();
}
Dsymbol sapplyOld = sapply; // 'sapply' will be NULL if and after 'inferApplyArgTypes' errors
/* Check for inference errors
*/
if (!inferApplyArgTypes(fs, sc, sapply))
{
/**
Try and extract the parameter count of the opApply callback function, e.g.:
int opApply(int delegate(int, float)) => 2 args
*/
bool foundMismatch = false;
size_t foreachParamCount = 0;
if (sapplyOld)
{
if (FuncDeclaration fd = sapplyOld.isFuncDeclaration())
{
auto fparameters = fd.getParameterList();
if (fparameters.length == 1)
{
// first param should be the callback function
Parameter fparam = fparameters[0];
if ((fparam.type.ty == Tpointer ||
fparam.type.ty == Tdelegate) &&
fparam.type.nextOf().isTypeFunction())
{
auto tf = fparam.type.nextOf().isTypeFunction();
foreachParamCount = tf.parameterList.length;
foundMismatch = true;
}
}
}
}
//printf("dim = %d, parameters.length = %d\n", dim, parameters.length);
if (foundMismatch && dim != foreachParamCount)
{
const(char)* plural = foreachParamCount > 1 ? "s" : "";
error(fs.loc, "cannot infer argument types, expected %llu argument%s, not %llu",
cast(ulong) foreachParamCount, plural, cast(ulong) dim);
}
else
error(fs.loc, "cannot uniquely infer `foreach` argument types");
return setError();
}
Type tab = fs.aggr.type.toBasetype();
if (tab.ty == Ttuple) // don't generate new scope for tuple loops
{
Statement s = makeTupleForeach(sc, false, false, fs, null, false).statement;
if (vinit)
s = new CompoundStatement(loc, new ExpStatement(loc, vinit), s);
result = s.statementSemantic(sc);
return;
}
auto sym = new ScopeDsymbol();
sym.parent = sc.scopesym;
sym.endlinnum = fs.endloc.linnum;
auto sc2 = sc.push(sym);
sc2.inLoop = true;
foreach (Parameter p; *fs.parameters)
{
if (p.storageClass & STC.manifest)
{
error(fs.loc, "cannot declare `enum` loop variables for non-unrolled foreach");
}
if (p.storageClass & STC.alias_)
{
error(fs.loc, "cannot declare `alias` loop variables for non-unrolled foreach");
}
}
void retError()
{
sc2.pop();
result = new ErrorStatement();
}
void rangeError()
{
error(fs.loc, "cannot infer argument types");
return retError();
}
void retStmt(Statement s)
{
if (!s)
return retError();
s = s.statementSemantic(sc2);
sc2.pop();
result = s;
}
Type tn = null;
Type tnv = null;
Statement apply()
{
if (checkForArgTypes(fs))
return null;
TypeFunction tfld = null;
if (sapply)
{
if (auto fdapply = sapply.isFuncDeclaration())
{
assert(fdapply.type && fdapply.type.isTypeFunction());
tfld = fdapply.type.typeSemantic(loc, sc2).isTypeFunction();
goto Lget;
}
else if (tab.isTypeDelegate())
{
tfld = tab.nextOf().isTypeFunction();
Lget:
//printf("tfld = %s\n", tfld.toChars());
if (tfld.parameterList.parameters.length == 1)
{
Parameter p = tfld.parameterList[0];
if (p.type && p.type.isTypeDelegate())
{
auto t = p.type.typeSemantic(loc, sc2);
assert(t.ty == Tdelegate);
tfld = t.nextOf().isTypeFunction();
}
}
}
}
FuncExp flde = foreachBodyToFunction(sc2, fs, tfld);
if (!flde)
return null;
// Resolve any forward referenced goto's
foreach (ScopeStatement ss; *fs.gotos)
{
GotoStatement gs = ss.statement.isGotoStatement();
if (!gs.label.statement)
{
// 'Promote' it to this scope, and replace with a return
fs.cases.push(gs);
ss.statement = new ReturnStatement(Loc.initial, new IntegerExp(fs.cases.length + 1));
}
}
Expression e = null;
if (vinit)
{
e = new DeclarationExp(loc, vinit);
e = e.expressionSemantic(sc2);
if (e.op == EXP.error)
return null;
}
Expression ec;
switch (tab.ty)
{
case Tarray:
case Tsarray: ec = applyArray (fs, flde, tab, sc2, tn, tnv); break;
case Tdelegate: ec = applyDelegate (fs, flde, tab, sc2); break;
case Taarray: ec = applyAssocArray(fs, flde, tab); break;
default: ec = applyOpApply (fs, flde, tab, sc2, sapply); break;
}
if (!ec)
return null;
e = Expression.combine(e, ec);
return loopReturn(e, fs.cases, loc);
}
switch (tab.ty)
{
case Tarray:
case Tsarray:
{
if (checkForArgTypes(fs))
return retError();
if (dim < 1 || dim > 2)
{
error(fs.loc, "only one or two arguments for array `foreach`");
return retError();
}
// Finish semantic on all foreach parameter types.
foreach (i; 0 .. dim)
{
Parameter p = (*fs.parameters)[i];
p.type = p.type.typeSemantic(loc, sc2);
p.type = p.type.addStorageClass(p.storageClass);
}
tn = tab.nextOf().toBasetype();
if (dim == 2)
{
Type tindex = (*fs.parameters)[0].type;
if (!tindex.isintegral())
{
error(fs.loc, "foreach: key cannot be of non-integral type `%s`", tindex.toChars());
return retError();
}
/* What cases to deprecate implicit conversions for:
* 1. foreach aggregate is a dynamic array
* 2. foreach body is lowered to _aApply (see special case below).
*/
Type tv = (*fs.parameters)[1].type.toBasetype();
if ((tab.isTypeDArray() ||
(tn.ty != tv.ty && tn.ty.isSomeChar && tv.ty.isSomeChar)) &&
!Type.tsize_t.implicitConvTo(tindex))
{
deprecation(fs.loc, "foreach: loop index implicitly converted from `size_t` to `%s`",
tindex.toChars());
}
}
/* Look for special case of parsing char types out of char type
* array.
*/
if (tn.ty.isSomeChar)