/
semantic3.d
1689 lines (1512 loc) · 68.8 KB
/
semantic3.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
/**
* Performs the semantic3 stage, which deals with function bodies.
*
* 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/semantic3.d, _semantic3.d)
* Documentation: https://dlang.org/phobos/dmd_semantic3.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/semantic3.d
*/
module dmd.semantic3;
import core.stdc.stdio;
import core.stdc.string;
import dmd.aggregate;
import dmd.aliasthis;
import dmd.arraytypes;
import dmd.astcodegen;
import dmd.astenums;
import dmd.attrib;
import dmd.blockexit;
import dmd.clone;
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.dstruct;
import dmd.dsymbol;
import dmd.dsymbolsem;
import dmd.dtemplate;
import dmd.dversion;
import dmd.errors;
import dmd.escape;
import dmd.expression;
import dmd.expressionsem;
import dmd.func;
import dmd.funcsem;
import dmd.globals;
import dmd.id;
import dmd.identifier;
import dmd.init;
import dmd.initsem;
import dmd.hdrgen;
import dmd.location;
import dmd.mtype;
import dmd.nogc;
import dmd.nspace;
import dmd.ob;
import dmd.objc;
import dmd.opover;
import dmd.optimize;
import dmd.parse;
import dmd.root.filename;
import dmd.common.outbuffer;
import dmd.root.rmem;
import dmd.rootobject;
import dmd.root.utf;
import dmd.sideeffect;
import dmd.statementsem;
import dmd.staticassert;
import dmd.tokens;
import dmd.semantic2;
import dmd.statement;
import dmd.target;
import dmd.templateparamsem;
import dmd.typesem;
import dmd.visitor;
enum LOG = false;
/*************************************
* Does semantic analysis on function bodies.
*/
void semantic3(Dsymbol dsym, Scope* sc)
{
scope v = new Semantic3Visitor(sc);
dsym.accept(v);
}
private extern(C++) final class Semantic3Visitor : Visitor
{
alias visit = Visitor.visit;
Scope* sc;
this(Scope* sc) scope @safe
{
this.sc = sc;
}
override void visit(Dsymbol) {}
override void visit(TemplateInstance tempinst)
{
static if (LOG)
{
printf("TemplateInstance.semantic3('%s'), semanticRun = %d\n", tempinst.toChars(), tempinst.semanticRun);
}
//if (toChars()[0] == 'D') *(char*)0=0;
if (tempinst.semanticRun >= PASS.semantic3)
return;
tempinst.semanticRun = PASS.semantic3;
if (tempinst.errors || !tempinst.members)
return;
TemplateDeclaration tempdecl = tempinst.tempdecl.isTemplateDeclaration();
assert(tempdecl);
sc = tempdecl._scope;
sc = sc.push(tempinst.argsym);
sc = sc.push(tempinst);
sc.tinst = tempinst;
sc.minst = tempinst.minst;
int needGagging = (tempinst.gagged && !global.gag);
uint olderrors = global.errors;
int oldGaggedErrors = -1; // dead-store to prevent spurious warning
/* If this is a gagged instantiation, gag errors.
* Future optimisation: If the results are actually needed, errors
* would already be gagged, so we don't really need to run semantic
* on the members.
*/
if (needGagging)
oldGaggedErrors = global.startGagging();
for (size_t i = 0; i < tempinst.members.length; i++)
{
Dsymbol s = (*tempinst.members)[i];
s.semantic3(sc);
if (tempinst.gagged && global.errors != olderrors)
break;
}
if (global.errors != olderrors)
{
if (!tempinst.errors)
{
if (!tempdecl.literal)
.error(tempinst.loc, "%s `%s` error instantiating", tempinst.kind, tempinst.toPrettyChars);
if (tempinst.tinst)
tempinst.tinst.printInstantiationTrace();
}
tempinst.errors = true;
}
if (needGagging)
global.endGagging(oldGaggedErrors);
sc = sc.pop();
sc.pop();
}
override void visit(TemplateMixin tmix)
{
if (tmix.semanticRun >= PASS.semantic3)
return;
tmix.semanticRun = PASS.semantic3;
static if (LOG)
{
printf("TemplateMixin.semantic3('%s')\n", tmix.toChars());
}
if (!tmix.members)
return;
sc = sc.push(tmix.argsym);
sc = sc.push(tmix);
uint olderrors = global.errors;
for (size_t i = 0; i < tmix.members.length; i++)
{
Dsymbol s = (*tmix.members)[i];
s.semantic3(sc);
}
if (global.errors != olderrors)
errorSupplemental(tmix.loc, "parent scope from here: `mixin %s`", tmix.toChars());
sc = sc.pop();
sc.pop();
}
override void visit(Module mod)
{
//printf("Module::semantic3('%s'): parent = %p\n", toChars(), parent);
if (mod.semanticRun != PASS.semantic2done)
return;
mod.semanticRun = PASS.semantic3;
// Note that modules get their own scope, from scratch.
// This is so regardless of where in the syntax a module
// gets imported, it is unaffected by context.
Scope* sc = Scope.createGlobal(mod, global.errorSink); // create root scope
//printf("Module = %p\n", sc.scopesym);
if (mod.members)
{
// Pass 3 semantic routines: do initializers and function bodies
for (size_t i = 0; i < mod.members.length; i++)
{
Dsymbol s = (*mod.members)[i];
//printf("Module %s: %s.semantic3()\n", toChars(), s.toChars());
s.semantic3(sc);
mod.runDeferredSemantic2();
}
}
if (mod.userAttribDecl)
{
mod.userAttribDecl.semantic3(sc);
}
sc = sc.pop();
sc.pop();
mod.semanticRun = PASS.semantic3done;
}
override void visit(FuncDeclaration funcdecl)
{
//printf("FuncDeclaration::semantic3(%s '%s', sc = %p)\n", funcdecl.kind(), funcdecl.toChars(), sc);
/* Determine if function should add `return 0;`
*/
bool addReturn0()
{
//printf("addReturn0()\n");
auto f = funcdecl.type.isTypeFunction();
// C11 5.1.2.2.3
if (sc.flags & SCOPE.Cfile && funcdecl.isCMain() && f.next.ty == Tint32)
return true;
return f.next.ty == Tvoid && (funcdecl.isMain() || funcdecl.isCMain());
}
VarDeclaration _arguments = null;
if (!funcdecl.parent)
{
if (global.errors)
return;
//printf("FuncDeclaration::semantic3(%s '%s', sc = %p)\n", kind(), toChars(), sc);
assert(0);
}
if (funcdecl.errors || isError(funcdecl.parent))
{
funcdecl.errors = true;
// Mark that the return type could not be inferred
if (funcdecl.inferRetType)
{
assert(funcdecl.type);
auto tf = funcdecl.type.isTypeFunction();
// Only change the return type s.t. other analysis is
// still possible e.g. missmatched parameter types
if (tf && !tf.next)
tf.next = Type.terror;
}
return;
}
//printf("FuncDeclaration::semantic3('%s.%s', %p, sc = %p, loc = %s)\n", funcdecl.parent.toChars(), funcdecl.toChars(), funcdecl, sc, funcdecl.loc.toChars());
//fflush(stdout);
//printf("storage class = x%x %x\n", sc.stc, storage_class);
//{ static int x; if (++x == 2) *(char*)0=0; }
//printf("\tlinkage = %d\n", sc.linkage);
if (funcdecl.ident == Id.assign && !funcdecl.inuse)
{
if (funcdecl.storage_class & STC.inference)
{
/* https://issues.dlang.org/show_bug.cgi?id=15044
* For generated opAssign function, any errors
* from its body need to be gagged.
*/
uint oldErrors = global.startGagging();
++funcdecl.inuse;
funcdecl.semantic3(sc);
--funcdecl.inuse;
if (global.endGagging(oldErrors)) // if errors happened
{
// Disable generated opAssign, because some members forbid identity assignment.
funcdecl.storage_class |= STC.disable;
funcdecl.fbody = null; // remove fbody which contains the error
funcdecl.hasSemantic3Errors = false;
}
return;
}
}
//printf(" sc.incontract = %d\n", (sc.flags & SCOPE.contract));
if (funcdecl.semanticRun >= PASS.semantic3)
return;
funcdecl.semanticRun = PASS.semantic3;
funcdecl.hasSemantic3Errors = false;
if (!funcdecl.type || funcdecl.type.ty != Tfunction)
return;
TypeFunction f = cast(TypeFunction)funcdecl.type;
if (!funcdecl.inferRetType && f.next.ty == Terror)
return;
if (!funcdecl.fbody && funcdecl.inferRetType && !f.next)
{
.error(funcdecl.loc, "%s `%s` has no function body with return type inference", funcdecl.kind, funcdecl.toPrettyChars);
return;
}
uint oldErrors = global.errors;
auto fds = FuncDeclSem3(funcdecl,sc);
fds.checkInContractOverrides();
// Remember whether we need to generate an 'out' contract.
immutable bool needEnsure = FuncDeclaration.needsFensure(funcdecl);
if (funcdecl.fbody || funcdecl.frequires || needEnsure)
{
/* Symbol table into which we place parameters and nested functions,
* solely to diagnose name collisions.
*/
funcdecl.localsymtab = new DsymbolTable();
// Establish function scope
auto ss = new ScopeDsymbol(funcdecl.loc, null);
// find enclosing scope symbol, might skip symbol-less CTFE and/or FuncExp scopes
ss.parent = sc.inner().scopesym;
ss.endlinnum = funcdecl.endloc.linnum;
Scope* sc2 = sc.push(ss);
sc2.func = funcdecl;
sc2.parent = funcdecl;
sc2.ctorflow.callSuper = CSX.none;
sc2.sbreak = null;
sc2.scontinue = null;
sc2.sw = null;
sc2.fes = funcdecl.fes;
sc2.linkage = funcdecl.isCsymbol() ? LINK.c : LINK.d;
sc2.stc &= STC.flowThruFunction;
sc2.visibility = Visibility(Visibility.Kind.public_);
sc2.explicitVisibility = 0;
sc2.aligndecl = null;
if (funcdecl.ident != Id.require && funcdecl.ident != Id.ensure)
sc2.flags = sc.flags & ~SCOPE.contract;
sc2.tf = null;
sc2.os = null;
sc2.inLoop = false;
sc2.inDefaultArg = false;
sc2.userAttribDecl = null;
if (sc2.intypeof == 1)
sc2.intypeof = 2;
sc2.ctorflow.fieldinit = null;
/* Note: When a lambda is defined immediately under aggregate member
* scope, it should be contextless due to prevent interior pointers.
* e.g.
* // dg points 'this' - its interior pointer
* class C { int x; void delegate() dg = (){ this.x = 1; }; }
*
* However, lambdas could be used inside typeof, in order to check
* some expressions validity at compile time. For such case the lambda
* body can access aggregate instance members.
* e.g.
* class C { int x; static assert(is(typeof({ this.x = 1; }))); }
*
* To properly accept it, mark these lambdas as member functions.
*/
if (auto fld = funcdecl.isFuncLiteralDeclaration())
{
if (auto ad = funcdecl.isMember2())
{
if (!sc.intypeof)
{
if (fld.tok == TOK.delegate_)
.error(funcdecl.loc, "%s `%s` cannot be %s members", funcdecl.kind, funcdecl.toPrettyChars, ad.kind());
else
fld.tok = TOK.function_;
}
else
{
if (fld.tok != TOK.function_)
fld.tok = TOK.delegate_;
}
}
}
declareThis(funcdecl, sc2);
// Reverts: https://issues.dlang.org/show_bug.cgi?id=5710
// No compiler supports this, and there was never any spec for it.
// @@@DEPRECATED_2.116@@@
// Deprecated in 2.096, can be made an error in 2.116.
// The deprecation period is longer than usual as dual-context
// functions may be widely used by dmd-compiled projects.
// It also gives more time for the implementation of dual-context
// functions to be reworked as a frontend-only feature.
if (funcdecl.hasDualContext())
{
.deprecation(funcdecl.loc, "%s `%s` function requires a dual-context, which is deprecated", funcdecl.kind, funcdecl.toPrettyChars);
if (auto ti = sc2.parent ? sc2.parent.isInstantiated() : null)
ti.printInstantiationTrace(Classification.deprecation);
}
//printf("[%s] ad = %p vthis = %p\n", loc.toChars(), ad, vthis);
//if (vthis) printf("\tvthis.type = %s\n", vthis.type.toChars());
// Declare hidden variable _arguments[] and _argptr
if (f.parameterList.varargs == VarArg.variadic)
{
if (f.linkage == LINK.d)
{
// Variadic arguments depend on Typeinfo being defined.
if (!global.params.useTypeInfo || !Type.dtypeinfo || !Type.typeinfotypelist)
{
if (!global.params.useTypeInfo)
{
version (IN_GCC)
.error(funcdecl.loc, "%s `%s` D-style variadic functions cannot be used with `-fno-rtti`", funcdecl.kind, funcdecl.toPrettyChars);
else
.error(funcdecl.loc, "%s `%s` D-style variadic functions cannot be used with -betterC", funcdecl.kind, funcdecl.toPrettyChars);
}
else if (!Type.typeinfotypelist)
.error(funcdecl.loc, "%s `%s` `object.TypeInfo_Tuple` could not be found, but is implicitly used in D-style variadic functions", funcdecl.kind, funcdecl.toPrettyChars);
else
.error(funcdecl.loc, "%s `%s` `object.TypeInfo` could not be found, but is implicitly used in D-style variadic functions", funcdecl.kind, funcdecl.toPrettyChars);
fatal();
}
// Declare _arguments[]
funcdecl.v_arguments = new VarDeclaration(funcdecl.loc, Type.typeinfotypelist.type, Id._arguments_typeinfo, null);
funcdecl.v_arguments.storage_class |= STC.temp | STC.parameter;
funcdecl.v_arguments.dsymbolSemantic(sc2);
sc2.insert(funcdecl.v_arguments);
funcdecl.v_arguments.parent = funcdecl;
//Type t = Type.dtypeinfo.type.constOf().arrayOf();
Type t = Type.dtypeinfo.type.arrayOf();
_arguments = new VarDeclaration(funcdecl.loc, t, Id._arguments, null);
_arguments.storage_class |= STC.temp;
_arguments.dsymbolSemantic(sc2);
sc2.insert(_arguments);
_arguments.parent = funcdecl;
}
if (f.linkage == LINK.d || f.parameterList.length)
{
// Declare _argptr
Type t = target.va_listType(funcdecl.loc, sc);
// Init is handled in FuncDeclaration_toObjFile
funcdecl.v_argptr = new VarDeclaration(funcdecl.loc, t, Id._argptr, new VoidInitializer(funcdecl.loc));
funcdecl.v_argptr.storage_class |= STC.temp;
funcdecl.v_argptr.dsymbolSemantic(sc2);
sc2.insert(funcdecl.v_argptr);
funcdecl.v_argptr.parent = funcdecl;
}
}
/* Declare all the function parameters as variables
* and install them in parameters[]
*/
if (const nparams = f.parameterList.length)
{
/* parameters[] has all the tuples removed, as the back end
* doesn't know about tuples
*/
funcdecl.parameters = new VarDeclarations();
funcdecl.parameters.reserve(nparams);
foreach (i, fparam; f.parameterList)
{
Identifier id = fparam.ident;
StorageClass stc = 0;
if (!id)
{
/* Generate identifier for un-named parameter,
* because we need it later on.
*/
fparam.ident = id = Identifier.generateId("__param_", i);
stc |= STC.temp;
}
Type vtype = fparam.type;
auto v = new VarDeclaration(fparam.loc, vtype, id, null);
//printf("declaring parameter %s of type %s\n", v.toChars(), v.type.toChars());
stc |= STC.parameter;
if (f.parameterList.varargs == VarArg.typesafe && i + 1 == nparams)
{
stc |= STC.variadic;
}
stc |= fparam.storageClass & (STC.IOR | STC.return_ | STC.scope_ | STC.lazy_ | STC.final_ | STC.TYPECTOR | STC.nodtor | STC.returnScope | STC.register);
v.storage_class = stc;
v.dsymbolSemantic(sc2);
if (!sc2.insert(v))
{
.error(funcdecl.loc, "%s `%s` parameter `%s.%s` is already defined", funcdecl.kind, funcdecl.toPrettyChars, funcdecl.toChars(), v.toChars());
funcdecl.errors = true;
}
else
funcdecl.parameters.push(v);
funcdecl.localsymtab.insert(v);
v.parent = funcdecl;
if (fparam.userAttribDecl)
v.userAttribDecl = fparam.userAttribDecl;
}
}
// Declare the tuple symbols and put them in the symbol table,
// but not in parameters[].
if (f.parameterList.parameters)
foreach (fparam; *f.parameterList.parameters)
{
if (!fparam.ident)
continue; // never used, so ignore
// expand any tuples
if (fparam.type.ty != Ttuple)
continue;
TypeTuple t = cast(TypeTuple)fparam.type;
size_t dim = Parameter.dim(t.arguments);
auto exps = new Objects(dim);
foreach (j; 0 .. dim)
{
Parameter narg = Parameter.getNth(t.arguments, j);
assert(narg.ident);
Dsymbol pscopesym;
VarDeclaration v = sc2.search(Loc.initial, narg.ident, pscopesym).isVarDeclaration();
assert(v);
(*exps)[j] = new VarExp(v.loc, v);
}
assert(fparam.ident);
auto v = new TupleDeclaration(funcdecl.loc, fparam.ident, exps);
//printf("declaring tuple %s\n", v.toChars());
v.isexp = true;
if (!sc2.insert(v))
.error(funcdecl.loc, "%s `%s` parameter `%s.%s` is already defined", funcdecl.kind, funcdecl.toPrettyChars, funcdecl.toChars(), v.toChars());
funcdecl.localsymtab.insert(v);
v.parent = funcdecl;
}
// Precondition invariant
Statement fpreinv = null;
if (funcdecl.addPreInvariant())
{
Expression e = addInvariant(funcdecl.isThis(), funcdecl.vthis);
if (e)
fpreinv = new ExpStatement(Loc.initial, e);
}
// Postcondition invariant
Statement fpostinv = null;
if (funcdecl.addPostInvariant())
{
Expression e = addInvariant(funcdecl.isThis(), funcdecl.vthis);
if (e)
fpostinv = new ExpStatement(Loc.initial, e);
}
// Pre/Postcondition contract
if (!funcdecl.fbody)
funcdecl.buildEnsureRequire();
Scope* scout = null;
if (needEnsure || funcdecl.addPostInvariant())
{
/* https://issues.dlang.org/show_bug.cgi?id=3657
* Set the correct end line number for fensure scope.
*/
uint fensure_endlin = funcdecl.endloc.linnum;
if (funcdecl.fensure)
if (auto s = funcdecl.fensure.isScopeStatement())
fensure_endlin = s.endloc.linnum;
if ((needEnsure && global.params.useOut == CHECKENABLE.on) || fpostinv)
{
funcdecl.returnLabel = funcdecl.searchLabel(Id.returnLabel, Loc.initial);
}
// scope of out contract (need for vresult.semantic)
auto sym = new ScopeDsymbol(funcdecl.loc, null);
sym.parent = sc2.scopesym;
sym.endlinnum = fensure_endlin;
scout = sc2.push(sym);
}
if (funcdecl.fbody)
{
auto sym = new ScopeDsymbol(funcdecl.loc, null);
sym.parent = sc2.scopesym;
sym.endlinnum = funcdecl.endloc.linnum;
sc2 = sc2.push(sym);
auto ad2 = funcdecl.isMemberLocal();
/* If this is a class constructor
*/
if (ad2 && funcdecl.isCtorDeclaration())
{
sc2.ctorflow.allocFieldinit(ad2.fields.length);
foreach (v; ad2.fields)
{
v.ctorinit = 0;
}
}
bool inferRef = (f.isref && (funcdecl.storage_class & STC.auto_));
funcdecl.fbody = funcdecl.fbody.statementSemantic(sc2);
if (!funcdecl.fbody)
funcdecl.fbody = new CompoundStatement(Loc.initial, new Statements());
if (funcdecl.isNaked())
{
fpreinv = null; // can't accommodate with no stack frame
fpostinv = null;
}
assert(funcdecl.type == f || (funcdecl.type.ty == Tfunction && f.purity == PURE.impure && (cast(TypeFunction)funcdecl.type).purity >= PURE.fwdref));
f = cast(TypeFunction)funcdecl.type;
if (funcdecl.inferRetType)
{
// If no return type inferred yet, then infer a void
if (!f.next)
f.next = Type.tvoid;
if (f.checkRetType(funcdecl.loc))
funcdecl.fbody = new ErrorStatement();
else
funcdecl.checkMain(); // Check main() parameters and return type
}
if (f.next !is null)
f.next.checkComplexTransition(funcdecl.loc, sc);
if (funcdecl.returns && !funcdecl.fbody.isErrorStatement())
{
for (size_t i = 0; i < funcdecl.returns.length;)
{
Expression exp = (*funcdecl.returns)[i].exp;
if (exp.op == EXP.variable && (cast(VarExp)exp).var == funcdecl.vresult)
{
if (addReturn0())
exp.type = Type.tint32;
else
exp.type = f.next;
// Remove `return vresult;` from returns
funcdecl.returns.remove(i);
continue;
}
if (inferRef && f.isref && !exp.type.constConv(f.next)) // https://issues.dlang.org/show_bug.cgi?id=13336
f.isref = false;
i++;
}
}
if (f.isref) // Function returns a reference
{
if (funcdecl.storage_class & STC.auto_)
funcdecl.storage_class &= ~STC.auto_;
}
// handle NRVO
if (!target.isReturnOnStack(f, funcdecl.needThis()) || !funcdecl.checkNRVO())
funcdecl.isNRVO = false;
if (funcdecl.fbody.isErrorStatement())
{
}
else if (funcdecl.isStaticCtorDeclaration())
{
/* It's a static constructor. Ensure that all
* ctor consts were initialized.
*/
ScopeDsymbol pd = funcdecl.toParent().isScopeDsymbol();
for (size_t i = 0; i < pd.members.length; i++)
{
Dsymbol s = (*pd.members)[i];
s.checkCtorConstInit();
}
}
else if (ad2 && funcdecl.isCtorDeclaration())
{
ClassDeclaration cd = ad2.isClassDeclaration();
// Verify that all the ctorinit fields got initialized
if (!(sc2.ctorflow.callSuper & CSX.this_ctor))
{
foreach (i, v; ad2.fields)
{
if (v.isThisDeclaration())
continue;
if (v.ctorinit == 0)
{
/* Current bugs in the flow analysis:
* 1. union members should not produce error messages even if
* not assigned to
* 2. structs should recognize delegating opAssign calls as well
* as delegating calls to other constructors
*/
if (v.isCtorinit() && !v.type.isMutable() && cd)
.error(funcdecl.loc, "%s `%s` missing initializer for %s field `%s`", funcdecl.kind, funcdecl.toPrettyChars, MODtoChars(v.type.mod), v.toChars());
else if (v.storage_class & STC.nodefaultctor)
error(funcdecl.loc, "field `%s` must be initialized in constructor", v.toChars());
else if (v.type.needsNested())
error(funcdecl.loc, "field `%s` must be initialized in constructor, because it is nested struct", v.toChars());
}
else
{
bool mustInit = (v.storage_class & STC.nodefaultctor || v.type.needsNested());
if (mustInit && !(sc2.ctorflow.fieldinit[i].csx & CSX.this_ctor))
{
.error(funcdecl.loc, "%s `%s` field `%s` must be initialized but skipped", funcdecl.kind, funcdecl.toPrettyChars, v.toChars());
}
}
}
}
sc2.ctorflow.freeFieldinit();
if (cd && !(sc2.ctorflow.callSuper & (CSX.any_ctor | CSX.halt)) && cd.baseClass && cd.baseClass.ctor)
{
sc2.ctorflow.callSuper = CSX.none;
// Insert implicit super() at start of fbody
Type tthis = ad2.type.addMod(funcdecl.vthis.type.mod);
FuncDeclaration fd = resolveFuncCall(Loc.initial, sc2, cd.baseClass.ctor, null, tthis, ArgumentList(), FuncResolveFlag.quiet);
if (!fd)
{
.error(funcdecl.loc, "%s `%s` no match for implicit `super()` call in constructor", funcdecl.kind, funcdecl.toPrettyChars);
}
else if (fd.storage_class & STC.disable)
{
.error(funcdecl.loc, "%s `%s` cannot call `super()` implicitly because it is annotated with `@disable`", funcdecl.kind, funcdecl.toPrettyChars);
}
else
{
Expression e1 = new SuperExp(Loc.initial);
Expression e = new CallExp(Loc.initial, e1);
e = e.expressionSemantic(sc2);
Statement s = new ExpStatement(Loc.initial, e);
funcdecl.fbody = new CompoundStatement(Loc.initial, s, funcdecl.fbody);
}
}
//printf("ctorflow.callSuper = x%x\n", sc2.ctorflow.callSuper);
}
/* https://issues.dlang.org/show_bug.cgi?id=17502
* Wait until after the return type has been inferred before
* generating the contracts for this function, and merging contracts
* from overrides.
*
* https://issues.dlang.org/show_bug.cgi?id=17893
* However should take care to generate this before inferered
* function attributes are applied, such as 'nothrow'.
*
* This was originally at the end of the first semantic pass, but
* required a fix-up to be done here for the '__result' variable
* type of __ensure() inside auto functions, but this didn't work
* if the out parameter was implicit.
*/
funcdecl.buildEnsureRequire();
// Check for errors related to 'nothrow'.
const blockexit = funcdecl.fbody.blockExit(funcdecl, f.isnothrow ? global.errorSink : null);
if (f.isnothrow && blockexit & BE.throw_)
error(funcdecl.loc, "%s `%s` may throw but is marked as `nothrow`", funcdecl.kind(), funcdecl.toPrettyChars());
if (!(blockexit & (BE.throw_ | BE.halt) || funcdecl.hasCatches))
{
/* Don't generate unwind tables for this function
* https://issues.dlang.org/show_bug.cgi?id=17997
*/
funcdecl.hasNoEH = true;
}
if (funcdecl.nothrowInprocess)
{
if (funcdecl.type == f)
f = cast(TypeFunction)f.copy();
f.isnothrow = !(blockexit & BE.throw_);
}
if (funcdecl.fbody.isErrorStatement())
{
}
else if (ad2 && funcdecl.isCtorDeclaration())
{
/* Append:
* return this;
* to function body
*/
if (blockexit & BE.fallthru)
{
Statement s = new ReturnStatement(funcdecl.loc, null);
s = s.statementSemantic(sc2);
funcdecl.fbody = new CompoundStatement(funcdecl.loc, funcdecl.fbody, s);
funcdecl.hasReturnExp |= (funcdecl.hasReturnExp & 1 ? 16 : 1);
}
}
else if (funcdecl.fes)
{
// For foreach(){} body, append a return 0;
if (blockexit & BE.fallthru)
{
Expression e = IntegerExp.literal!0;
Statement s = new ReturnStatement(Loc.initial, e);
funcdecl.fbody = new CompoundStatement(Loc.initial, funcdecl.fbody, s);
funcdecl.hasReturnExp |= (funcdecl.hasReturnExp & 1 ? 16 : 1);
}
assert(!funcdecl.returnLabel);
}
else if (f.next.toBasetype().ty == Tnoreturn)
{
// Fallthrough despite being declared as noreturn? return is already rejected when evaluating the ReturnStatement
if (blockexit & BE.fallthru)
{
.error(funcdecl.loc, "%s `%s` is typed as `%s` but does return", funcdecl.kind, funcdecl.toPrettyChars, f.next.toChars());
funcdecl.loc.errorSupplemental("`noreturn` functions must either throw, abort or loop indefinitely");
}
}
else
{
const(bool) inlineAsm = (funcdecl.hasReturnExp & 8) != 0;
if ((blockexit & BE.fallthru) && f.next.ty != Tvoid && !inlineAsm && !(sc.flags & SCOPE.Cfile))
{
if (!funcdecl.hasReturnExp)
.error(funcdecl.loc, "%s `%s` has no `return` statement, but is expected to return a value of type `%s`", funcdecl.kind, funcdecl.toPrettyChars, f.next.toChars());
else
.error(funcdecl.loc, "%s `%s` no `return exp;` or `assert(0);` at end of function", funcdecl.kind, funcdecl.toPrettyChars);
}
}
if (funcdecl.returns)
{
bool implicit0 = addReturn0();
Type tret = implicit0 ? Type.tint32 : f.next;
assert(tret.ty != Tvoid);
if (funcdecl.vresult || funcdecl.returnLabel)
funcdecl.buildResultVar(scout ? scout : sc2, tret);
/* Cannot move this loop into NrvoWalker, because
* returns[i] may be in the nested delegate for foreach-body.
*/
for (size_t i = 0; i < funcdecl.returns.length; i++)
{
ReturnStatement rs = (*funcdecl.returns)[i];
Expression exp = rs.exp;
if (exp.op == EXP.error)
continue;
if (tret.ty == Terror)
{
// https://issues.dlang.org/show_bug.cgi?id=13702
exp = checkGC(sc2, exp);
continue;
}
/* If the expression in the return statement (exp) cannot be implicitly
* converted to the return type (tret) of the function and if the
* type of the expression is type isolated, then it may be possible
* that a promotion to `immutable` or `inout` (through a cast) will
* match the return type.
*/
if (!exp.implicitConvTo(tret) && funcdecl.isTypeIsolated(exp.type))
{
/* https://issues.dlang.org/show_bug.cgi?id=20073
*
* The problem is that if the type of the returned expression (exp.type)
* is an aggregated declaration with an alias this, the alias this may be
* used for the conversion testing without it being an isolated type.
*
* To make sure this does not happen, we can test here the implicit conversion
* only for the aggregated declaration type by using `implicitConvToWithoutAliasThis`.
* The implicit conversion with alias this is taken care of later.
*/
AggregateDeclaration aggDecl = isAggregate(exp.type);
TypeStruct tstruct;
TypeClass tclass;
bool hasAliasThis;
if (aggDecl && aggDecl.aliasthis)
{
hasAliasThis = true;
tclass = exp.type.isTypeClass();
if (!tclass)
tstruct = exp.type.isTypeStruct();
assert(tclass || tstruct);
}
if (hasAliasThis)
{
if (tclass)
{
if ((cast(TypeClass)(exp.type.immutableOf())).implicitConvToWithoutAliasThis(tret))
exp = exp.castTo(sc2, exp.type.immutableOf());
else if ((cast(TypeClass)(exp.type.wildOf())).implicitConvToWithoutAliasThis(tret))
exp = exp.castTo(sc2, exp.type.wildOf());
}
else
{
if ((cast(TypeStruct)exp.type.immutableOf()).implicitConvToWithoutAliasThis(tret))
exp = exp.castTo(sc2, exp.type.immutableOf());
else if ((cast(TypeStruct)exp.type.immutableOf()).implicitConvToWithoutAliasThis(tret))
exp = exp.castTo(sc2, exp.type.wildOf());
}
}
else
{
if (exp.type.immutableOf().implicitConvTo(tret))
exp = exp.castTo(sc2, exp.type.immutableOf());
else if (exp.type.wildOf().implicitConvTo(tret))
exp = exp.castTo(sc2, exp.type.wildOf());
}
}
const hasCopyCtor = exp.type.ty == Tstruct && (cast(TypeStruct)exp.type).sym.hasCopyCtor;
// if a copy constructor is present, the return type conversion will be handled by it
if (!(hasCopyCtor && exp.isLvalue()))
{
if (f.isref && !MODimplicitConv(exp.type.mod, tret.mod) && !tret.isTypeSArray())
error(exp.loc, "expression `%s` of type `%s` is not implicitly convertible to return type `ref %s`",
exp.toChars(), exp.type.toChars(), tret.toChars());
else
exp = exp.implicitCastTo(sc2, tret);
}
if (f.isref)
{
// Function returns a reference
exp = exp.toLvalue(sc2, "`ref` return");
checkReturnEscapeRef(sc2, exp, false);
exp = exp.optimize(WANTvalue, /*keepLvalue*/ true);
}
else
{
exp = exp.optimize(WANTvalue);
/* https://issues.dlang.org/show_bug.cgi?id=10789
* If NRVO is not possible, all returned lvalues should call their postblits.
*/
if (!funcdecl.isNRVO())
exp = doCopyOrMove(sc2, exp, f.next);
if (tret.hasPointers())
checkReturnEscape(sc2, exp, false);
}
exp = checkGC(sc2, exp);
if (funcdecl.vresult)
{
// Create: return vresult = exp;
exp = new BlitExp(rs.loc, funcdecl.vresult, exp);
exp.type = funcdecl.vresult.type;
if (rs.caseDim)
exp = Expression.combine(exp, new IntegerExp(rs.caseDim));
}
else if (funcdecl.tintro && !tret.equals(funcdecl.tintro.nextOf()))
{
exp = exp.implicitCastTo(sc2, funcdecl.tintro.nextOf());
}
rs.exp = exp;
}
}
if (funcdecl.nrvo_var || funcdecl.returnLabel)
{
scope NrvoWalker nw = new NrvoWalker();
nw.fd = funcdecl;
nw.sc = sc2;
nw.visitStmt(funcdecl.fbody);
}
sc2 = sc2.pop();
}
if (global.params.inclusiveInContracts)
{
funcdecl.frequire = funcdecl.mergeFrequireInclusivePreview(
funcdecl.frequire, funcdecl.fdrequireParams);
}
else
{
funcdecl.frequire = funcdecl.mergeFrequire(funcdecl.frequire, funcdecl.fdrequireParams);
}
funcdecl.fensure = funcdecl.mergeFensure(funcdecl.fensure, Id.result, funcdecl.fdensureParams);
Statement freq = funcdecl.frequire;
Statement fens = funcdecl.fensure;
/* Do the semantic analysis on the [in] preconditions and
* [out] postconditions.
*/
immutable bool isnothrow = f.isnothrow && !funcdecl.nothrowInprocess;
if (freq)
{
/* frequire is composed of the [in] contracts
*/
auto sym = new ScopeDsymbol(funcdecl.loc, null);
sym.parent = sc2.scopesym;
sym.endlinnum = funcdecl.endloc.linnum;
sc2 = sc2.push(sym);
sc2.flags = (sc2.flags & ~SCOPE.contract) | SCOPE.require;
// BUG: need to error if accessing out parameters
// BUG: need to disallow returns
// BUG: verify that all in and ref parameters are read