/
dsymbolsem.d
7140 lines (6424 loc) · 256 KB
/
dsymbolsem.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
/**
* Compiler implementation of the
* $(LINK2 http://www.dlang.org, D programming language).
*
* Copyright: Copyright (c) 1999-2017 by Digital Mars, All Rights Reserved
* Authors: $(LINK2 http://www.digitalmars.com, Walter Bright)
* License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/ddmd/dsymbolsem.d, _dsymbolsem.d)
*/
module ddmd.dsymbolsem;
/**
* Documentation:
* https://dlang.org/phobos/ddmd_dsymbolsem.html
* Coverage:
* https://codecov.io/gh/dlang/dmd/src/master/src/ddmd/dsymbolsem.d
*/
import core.stdc.stdio;
import core.stdc.string;
import ddmd.aggregate;
import ddmd.aliasthis;
import ddmd.arraytypes;
import ddmd.astcodegen;
import ddmd.attrib;
import ddmd.blockexit;
import ddmd.clone;
import ddmd.dcast;
import ddmd.dclass;
import ddmd.declaration;
import ddmd.denum;
import ddmd.dimport;
import ddmd.dinterpret;
import ddmd.dmodule;
import ddmd.dscope;
import ddmd.dstruct;
import ddmd.dsymbol;
import ddmd.dtemplate;
import ddmd.dversion;
import ddmd.errors;
import ddmd.escape;
import ddmd.expression;
import ddmd.expressionsem;
import ddmd.func;
import ddmd.globals;
import ddmd.gluelayer;
import ddmd.id;
import ddmd.identifier;
import ddmd.init;
import ddmd.initsem;
import ddmd.hdrgen;
import ddmd.mars;
import ddmd.mtype;
import ddmd.nogc;
import ddmd.nspace;
import ddmd.objc;
import ddmd.opover;
import ddmd.parse;
import ddmd.root.filename;
import ddmd.root.outbuffer;
import ddmd.root.rmem;
import ddmd.root.rootobject;
import ddmd.sideeffect;
import ddmd.statementsem;
import ddmd.staticassert;
import ddmd.tokens;
import ddmd.utf;
import ddmd.utils;
import ddmd.semantic;
import ddmd.statement;
import ddmd.target;
import ddmd.templateparamsem;
import ddmd.typesem;
import ddmd.visitor;
enum LOG = false;
private uint setMangleOverride(Dsymbol s, char* sym)
{
AttribDeclaration ad = s.isAttribDeclaration();
if (ad)
{
Dsymbols* decls = ad.include(null, null);
uint nestedCount = 0;
if (decls && decls.dim)
for (size_t i = 0; i < decls.dim; ++i)
nestedCount += setMangleOverride((*decls)[i], sym);
return nestedCount;
}
else if (s.isFuncDeclaration() || s.isVarDeclaration())
{
s.isDeclaration().mangleOverride = sym;
return 1;
}
else
return 0;
}
/*************************************
* Does semantic analysis on the public face of declarations.
*/
extern(C++) void dsymbolSemantic(Dsymbol dsym, Scope* sc)
{
scope v = new DsymbolSemanticVisitor(sc);
dsym.accept(v);
}
extern(C++) final class Semantic2Visitor : Visitor
{
alias visit = super.visit;
Scope* sc;
this(Scope* sc)
{
this.sc = sc;
}
override void visit(Dsymbol) {}
override void visit(StaticAssert sa)
{
//printf("StaticAssert::semantic2() %s\n", sa.toChars());
auto sds = new ScopeDsymbol();
sc = sc.push(sds);
sc.tinst = null;
sc.minst = null;
import ddmd.staticcond;
bool errors;
bool result = evalStaticCondition(sc, sa.exp, sa.exp, errors);
sc = sc.pop();
if (errors)
{
errorSupplemental(sa.loc, "while evaluating: `static assert(%s)`", sa.exp.toChars());
}
else if (!result)
{
if (sa.msg)
{
sc = sc.startCTFE();
sa.msg = sa.msg.expressionSemantic(sc);
sa.msg = resolveProperties(sc, sa.msg);
sc = sc.endCTFE();
sa.msg = sa.msg.ctfeInterpret();
if (StringExp se = sa.msg.toStringExp())
{
// same with pragma(msg)
se = se.toUTF8(sc);
sa.error("\"%.*s\"", cast(int)se.len, se.string);
}
else
sa.error("%s", sa.msg.toChars());
}
else
sa.error("`%s` is false", sa.exp.toChars());
if (sc.tinst)
sc.tinst.printInstantiationTrace();
if (!global.gag)
fatal();
}
}
override void visit(TemplateInstance tempinst)
{
if (tempinst.semanticRun >= PASSsemantic2)
return;
tempinst.semanticRun = PASSsemantic2;
static if (LOG)
{
printf("+TemplateInstance.semantic2('%s')\n", tempinst.toChars());
}
if (!tempinst.errors && tempinst.members)
{
TemplateDeclaration tempdecl = tempinst.tempdecl.isTemplateDeclaration();
assert(tempdecl);
sc = tempdecl._scope;
assert(sc);
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 (needGagging)
oldGaggedErrors = global.startGagging();
for (size_t i = 0; i < tempinst.members.dim; i++)
{
Dsymbol s = (*tempinst.members)[i];
static if (LOG)
{
printf("\tmember '%s', kind = '%s'\n", s.toChars(), s.kind());
}
s.semantic2(sc);
if (tempinst.gagged && global.errors != olderrors)
break;
}
if (global.errors != olderrors)
{
if (!tempinst.errors)
{
if (!tempdecl.literal)
tempinst.error(tempinst.loc, "error instantiating");
if (tempinst.tinst)
tempinst.tinst.printInstantiationTrace();
}
tempinst.errors = true;
}
if (needGagging)
global.endGagging(oldGaggedErrors);
sc = sc.pop();
sc.pop();
}
static if (LOG)
{
printf("-TemplateInstance.semantic2('%s')\n", tempinst.toChars());
}
}
override void visit(TemplateMixin tmix)
{
if (tmix.semanticRun >= PASSsemantic2)
return;
tmix.semanticRun = PASSsemantic2;
static if (LOG)
{
printf("+TemplateMixin.semantic2('%s')\n", tmix.toChars());
}
if (tmix.members)
{
assert(sc);
sc = sc.push(tmix.argsym);
sc = sc.push(tmix);
for (size_t i = 0; i < tmix.members.dim; i++)
{
Dsymbol s = (*tmix.members)[i];
static if (LOG)
{
printf("\tmember '%s', kind = '%s'\n", s.toChars(), s.kind());
}
s.semantic2(sc);
}
sc = sc.pop();
sc.pop();
}
static if (LOG)
{
printf("-TemplateMixin.semantic2('%s')\n", tmix.toChars());
}
}
override void visit(VarDeclaration vd)
{
if (vd.semanticRun < PASSsemanticdone && vd.inuse)
return;
//printf("VarDeclaration::semantic2('%s')\n", toChars());
if (vd._init && !vd.toParent().isFuncDeclaration())
{
vd.inuse++;
version (none)
{
ExpInitializer ei = vd._init.isExpInitializer();
if (ei)
{
ei.exp.print();
printf("type = %p\n", ei.exp.type);
}
}
// https://issues.dlang.org/show_bug.cgi?id=14166
// Don't run CTFE for the temporary variables inside typeof
vd._init = vd._init.initializerSemantic(sc, vd.type, sc.intypeof == 1 ? INITnointerpret : INITinterpret);
vd.inuse--;
}
if (vd._init && vd.storage_class & STCmanifest)
{
/* Cannot initializer enums with CTFE classreferences and addresses of struct literals.
* Scan initializer looking for them. Issue error if found.
*/
if (ExpInitializer ei = vd._init.isExpInitializer())
{
static bool hasInvalidEnumInitializer(Expression e)
{
static bool arrayHasInvalidEnumInitializer(Expressions* elems)
{
foreach (e; *elems)
{
if (e && hasInvalidEnumInitializer(e))
return true;
}
return false;
}
if (e.op == TOKclassreference)
return true;
if (e.op == TOKaddress && (cast(AddrExp)e).e1.op == TOKstructliteral)
return true;
if (e.op == TOKarrayliteral)
return arrayHasInvalidEnumInitializer((cast(ArrayLiteralExp)e).elements);
if (e.op == TOKstructliteral)
return arrayHasInvalidEnumInitializer((cast(StructLiteralExp)e).elements);
if (e.op == TOKassocarrayliteral)
{
AssocArrayLiteralExp ae = cast(AssocArrayLiteralExp)e;
return arrayHasInvalidEnumInitializer(ae.values) ||
arrayHasInvalidEnumInitializer(ae.keys);
}
return false;
}
if (hasInvalidEnumInitializer(ei.exp))
vd.error(": Unable to initialize enum with class or pointer to struct. Use static const variable instead.");
}
}
else if (vd._init && vd.isThreadlocal())
{
if ((vd.type.ty == Tclass) && vd.type.isMutable() && !vd.type.isShared())
{
ExpInitializer ei = vd._init.isExpInitializer();
if (ei && ei.exp.op == TOKclassreference)
vd.error("is mutable. Only const or immutable class thread local variable are allowed, not %s", vd.type.toChars());
}
else if (vd.type.ty == Tpointer && vd.type.nextOf().ty == Tstruct && vd.type.nextOf().isMutable() && !vd.type.nextOf().isShared())
{
ExpInitializer ei = vd._init.isExpInitializer();
if (ei && ei.exp.op == TOKaddress && (cast(AddrExp)ei.exp).e1.op == TOKstructliteral)
{
vd.error("is a pointer to mutable struct. Only pointers to const, immutable or shared struct thread local variable are allowed, not %s", vd.type.toChars());
}
}
}
vd.semanticRun = PASSsemantic2done;
}
override void visit(Module mod)
{
//printf("Module::semantic2('%s'): parent = %p\n", toChars(), parent);
if (mod.semanticRun != PASSsemanticdone) // semantic() not completed yet - could be recursive call
return;
mod.semanticRun = PASSsemantic2;
// 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); // create root scope
//printf("Module = %p\n", sc.scopesym);
// Pass 2 semantic routines: do initializers and function bodies
for (size_t i = 0; i < mod.members.dim; i++)
{
Dsymbol s = (*mod.members)[i];
s.semantic2(sc);
}
if (mod.userAttribDecl)
{
mod.userAttribDecl.semantic2(sc);
}
sc = sc.pop();
sc.pop();
mod.semanticRun = PASSsemantic2done;
//printf("-Module::semantic2('%s'): parent = %p\n", toChars(), parent);
}
override void visit(FuncDeclaration fd)
{
if (fd.semanticRun >= PASSsemantic2done)
return;
assert(fd.semanticRun <= PASSsemantic2);
fd.semanticRun = PASSsemantic2;
objc.setSelector(fd, sc);
objc.validateSelector(fd);
if (ClassDeclaration cd = fd.parent.isClassDeclaration())
{
objc.checkLinkage(fd);
}
}
override void visit(Import i)
{
//printf("Import::semantic2('%s')\n", toChars());
if (i.mod)
{
i.mod.semantic2(null);
if (i.mod.needmoduleinfo)
{
//printf("module5 %s because of %s\n", sc.module.toChars(), mod.toChars());
if (sc)
sc._module.needmoduleinfo = 1;
}
}
}
override void visit(Nspace ns)
{
if (ns.semanticRun >= PASSsemantic2)
return;
ns.semanticRun = PASSsemantic2;
static if (LOG)
{
printf("+Nspace::semantic2('%s')\n", ns.toChars());
}
if (ns.members)
{
assert(sc);
sc = sc.push(ns);
sc.linkage = LINKcpp;
foreach (s; *ns.members)
{
static if (LOG)
{
printf("\tmember '%s', kind = '%s'\n", s.toChars(), s.kind());
}
s.semantic2(sc);
}
sc.pop();
}
static if (LOG)
{
printf("-Nspace::semantic2('%s')\n", ns.toChars());
}
}
override void visit(AttribDeclaration ad)
{
Dsymbols* d = ad.include(sc, null);
if (d)
{
Scope* sc2 = ad.newScope(sc);
for (size_t i = 0; i < d.dim; i++)
{
Dsymbol s = (*d)[i];
s.semantic2(sc2);
}
if (sc2 != sc)
sc2.pop();
}
}
/**
* Run the DeprecatedDeclaration's semantic2 phase then its members.
*
* The message set via a `DeprecatedDeclaration` can be either of:
* - a string literal
* - an enum
* - a static immutable
* So we need to call ctfe to resolve it.
* Afterward forwards to the members' semantic2.
*/
override void visit(DeprecatedDeclaration dd)
{
getMessage(dd);
visit(cast(AttribDeclaration)dd);
}
override void visit(AlignDeclaration ad)
{
ad.getAlignment(sc);
visit(cast(AttribDeclaration)ad);
}
override void visit(UserAttributeDeclaration uad)
{
if (uad.decl && uad.atts && uad.atts.dim && uad._scope)
{
static void eval(Scope* sc, Expressions* exps)
{
foreach (ref Expression e; *exps)
{
if (e)
{
e = e.expressionSemantic(sc);
if (definitelyValueParameter(e))
e = e.ctfeInterpret();
if (e.op == TOKtuple)
{
TupleExp te = cast(TupleExp)e;
eval(sc, te.exps);
}
}
}
}
uad._scope = null;
eval(sc, uad.atts);
}
visit(cast(AttribDeclaration)uad);
}
override void visit(AggregateDeclaration ad)
{
//printf("AggregateDeclaration::semantic2(%s) type = %s, errors = %d\n", toChars(), type.toChars(), errors);
if (!ad.members)
return;
if (ad._scope)
{
ad.error("has forward references");
return;
}
auto sc2 = ad.newScope(sc);
ad.determineSize(ad.loc);
for (size_t i = 0; i < ad.members.dim; i++)
{
Dsymbol s = (*ad.members)[i];
//printf("\t[%d] %s\n", i, s.toChars());
s.semantic2(sc2);
}
sc2.pop();
}
}
structalign_t getAlignment(AlignDeclaration ad, Scope* sc)
{
if (ad.salign != ad.UNKNOWN)
return ad.salign;
if (!ad.ealign)
return ad.salign = STRUCTALIGN_DEFAULT;
sc = sc.startCTFE();
ad.ealign = ad.ealign.expressionSemantic(sc);
ad.ealign = resolveProperties(sc, ad.ealign);
sc = sc.endCTFE();
ad.ealign = ad.ealign.ctfeInterpret();
if (ad.ealign.op == TOKerror)
return ad.salign = STRUCTALIGN_DEFAULT;
Type tb = ad.ealign.type.toBasetype();
auto n = ad.ealign.toInteger();
if (n < 1 || n & (n - 1) || structalign_t.max < n || !tb.isintegral())
{
error(ad.loc, "alignment must be an integer positive power of 2, not %s", ad.ealign.toChars());
return ad.salign = STRUCTALIGN_DEFAULT;
}
return ad.salign = cast(structalign_t)n;
}
const(char)* getMessage(DeprecatedDeclaration dd)
{
if (auto sc = dd._scope)
{
dd._scope = null;
sc = sc.startCTFE();
dd.msg = dd.msg.expressionSemantic(sc);
dd.msg = resolveProperties(sc, dd.msg);
sc = sc.endCTFE();
dd.msg = dd.msg.ctfeInterpret();
if (auto se = dd.msg.toStringExp())
dd.msgstr = se.toStringz().ptr;
else
dd.msg.error("compile time constant expected, not `%s`", dd.msg.toChars());
}
return dd.msgstr;
}
extern(C++) final class Semantic3Visitor : Visitor
{
alias visit = super.visit;
Scope* sc;
this(Scope* sc)
{
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 >= PASSsemantic3)
return;
tempinst.semanticRun = PASSsemantic3;
if (!tempinst.errors && tempinst.members)
{
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.dim; 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)
tempinst.error(tempinst.loc, "error instantiating");
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 >= PASSsemantic3)
return;
tmix.semanticRun = PASSsemantic3;
static if (LOG)
{
printf("TemplateMixin.semantic3('%s')\n", tmix.toChars());
}
if (tmix.members)
{
sc = sc.push(tmix.argsym);
sc = sc.push(tmix);
for (size_t i = 0; i < tmix.members.dim; i++)
{
Dsymbol s = (*tmix.members)[i];
s.semantic3(sc);
}
sc = sc.pop();
sc.pop();
}
}
override void visit(Module mod)
{
//printf("Module::semantic3('%s'): parent = %p\n", toChars(), parent);
if (mod.semanticRun != PASSsemantic2done)
return;
mod.semanticRun = PASSsemantic3;
// 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); // create root scope
//printf("Module = %p\n", sc.scopesym);
// Pass 3 semantic routines: do initializers and function bodies
for (size_t i = 0; i < mod.members.dim; 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 = PASSsemantic3done;
}
override void visit(FuncDeclaration funcdecl)
{
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;
return;
}
//printf("FuncDeclaration::semantic3('%s.%s', %p, sc = %p, loc = %s)\n", parent.toChars(), toChars(), this, sc, 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 & STCinference)
{
/* 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 |= STCdisable;
funcdecl.fbody = null; // remove fbody which contains the error
funcdecl.semantic3Errors = false;
}
return;
}
}
//printf(" sc.incontract = %d\n", (sc.flags & SCOPEcontract));
if (funcdecl.semanticRun >= PASSsemantic3)
return;
funcdecl.semanticRun = PASSsemantic3;
funcdecl.semantic3Errors = 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)
{
funcdecl.error("has no function body with return type inference");
return;
}
uint oldErrors = global.errors;
if (funcdecl.frequire)
{
for (size_t i = 0; i < funcdecl.foverrides.dim; i++)
{
FuncDeclaration fdv = funcdecl.foverrides[i];
if (fdv.fbody && !fdv.frequire)
{
funcdecl.error("cannot have an in contract when overridden function %s does not have an in contract", fdv.toPrettyChars());
break;
}
}
}
// Remember whether we need to generate an 'out' contract.
immutable bool needEnsure = FuncDeclaration.needsFensure(funcdecl);
if (funcdecl.fbody || funcdecl.frequire || 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();
// find enclosing scope symbol, might skip symbol-less CTFE and/or FuncExp scopes
for (auto scx = sc; ; scx = scx.enclosing)
{
if (scx.scopesym)
{
ss.parent = scx.scopesym;
break;
}
}
ss.loc = funcdecl.loc;
ss.endlinnum = funcdecl.endloc.linnum;
Scope* sc2 = sc.push(ss);
sc2.func = funcdecl;
sc2.parent = funcdecl;
sc2.callSuper = 0;
sc2.sbreak = null;
sc2.scontinue = null;
sc2.sw = null;
sc2.fes = funcdecl.fes;
sc2.linkage = LINKd;
sc2.stc &= ~(STCauto | STCscope | STCstatic | STCabstract | STCdeprecated | STCoverride | STC_TYPECTOR | STCfinal | STCtls | STCgshared | STCref | STCreturn | STCproperty | STCnothrow | STCpure | STCsafe | STCtrusted | STCsystem);
sc2.protection = Prot(PROTpublic);
sc2.explicitProtection = 0;
sc2.aligndecl = null;
if (funcdecl.ident != Id.require && funcdecl.ident != Id.ensure)
sc2.flags = sc.flags & ~SCOPEcontract;
sc2.flags &= ~SCOPEcompile;
sc2.tf = null;
sc2.os = null;
sc2.noctor = 0;
sc2.userAttribDecl = null;
if (sc2.intypeof == 1)
sc2.intypeof = 2;
sc2.fieldinit = null;
sc2.fieldinit_dim = 0;
/* 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' - it's 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 == TOKdelegate)
funcdecl.error("cannot be %s members", ad.kind());
else
fld.tok = TOKfunction;
}
else
{
if (fld.tok != TOKfunction)
fld.tok = TOKdelegate;
}
}
}
// Declare 'this'
auto ad = funcdecl.isThis();
funcdecl.vthis = funcdecl.declareThis(sc2, ad);
//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.varargs == 1)
{
if (f.linkage == LINKd)
{
// Declare _arguments[]
funcdecl.v_arguments = new VarDeclaration(Loc(), Type.typeinfotypelist.type, Id._arguments_typeinfo, null);
funcdecl.v_arguments.storage_class |= STCtemp | STCparameter;
funcdecl.v_arguments.dsymbolSemantic(sc2);
sc2.insert(funcdecl.v_arguments);
funcdecl.v_arguments.parent = funcdecl;
//Type *t = Type::typeinfo.type.constOf().arrayOf();
Type t = Type.dtypeinfo.type.arrayOf();
_arguments = new VarDeclaration(Loc(), t, Id._arguments, null);
_arguments.storage_class |= STCtemp;
_arguments.dsymbolSemantic(sc2);
sc2.insert(_arguments);
_arguments.parent = funcdecl;
}
if (f.linkage == LINKd || (f.parameters && Parameter.dim(f.parameters)))
{
// Declare _argptr
Type t = Type.tvalist;
// Init is handled in FuncDeclaration_toObjFile
funcdecl.v_argptr = new VarDeclaration(Loc(), t, Id._argptr, new VoidInitializer(funcdecl.loc));
funcdecl.v_argptr.storage_class |= STCtemp;
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[]
*/
size_t nparams = Parameter.dim(f.parameters);
if (nparams)
{
/* parameters[] has all the tuples removed, as the back end
* doesn't know about tuples
*/
funcdecl.parameters = new VarDeclarations();
funcdecl.parameters.reserve(nparams);
for (size_t i = 0; i < nparams; i++)
{
Parameter fparam = Parameter.getNth(f.parameters, i);
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 |= STCtemp;
}
Type vtype = fparam.type;
auto v = new VarDeclaration(funcdecl.loc, vtype, id, null);
//printf("declaring parameter %s of type %s\n", v.toChars(), v.type.toChars());
stc |= STCparameter;
if (f.varargs == 2 && i + 1 == nparams)
stc |= STCvariadic;
if (funcdecl.flags & FUNCFLAG.inferScope && !(fparam.storageClass & STCscope))
stc |= STCmaybescope;
stc |= fparam.storageClass & (STCin | STCout | STCref | STCreturn | STCscope | STClazy | STCfinal | STC_TYPECTOR | STCnodtor);
v.storage_class = stc;
v.dsymbolSemantic(sc2);
if (!sc2.insert(v))
{
funcdecl.error("parameter %s.%s is already defined", funcdecl.toChars(), v.toChars());
funcdecl.errors = true;
}
else
funcdecl.parameters.push(v);
funcdecl.localsymtab.insert(v);
v.parent = funcdecl;
}
}
// Declare the tuple symbols and put them in the symbol table,
// but not in parameters[].
if (f.parameters)
{
for (size_t i = 0; i < f.parameters.dim; i++)
{
Parameter fparam = (*f.parameters)[i];
if (!fparam.ident)
continue; // never used, so ignore
if (fparam.type.ty == Ttuple)
{
TypeTuple t = cast(TypeTuple)fparam.type;
size_t dim = Parameter.dim(t.arguments);
auto exps = new Objects();
exps.setDim(dim);
for (size_t j = 0; j < dim; j++)
{
Parameter narg = Parameter.getNth(t.arguments, j);
assert(narg.ident);
VarDeclaration v = sc2.search(Loc(), narg.ident, null).isVarDeclaration();
assert(v);
Expression e = new VarExp(v.loc, v);
(*exps)[j] = e;
}
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))
funcdecl.error("parameter %s.%s is already defined", funcdecl.toChars(), v.toChars());
funcdecl.localsymtab.insert(v);
v.parent = funcdecl;
}
}
}
// Precondition invariant
Statement fpreinv = null;
if (funcdecl.addPreInvariant())
{
Expression e = addInvariant(funcdecl.loc, sc, ad, funcdecl.vthis);
if (e)
fpreinv = new ExpStatement(Loc(), e);
}
// Postcondition invariant
Statement fpostinv = null;
if (funcdecl.addPostInvariant())
{
Expression e = addInvariant(funcdecl.loc, sc, ad, funcdecl.vthis);
if (e)
fpostinv = new ExpStatement(Loc(), e);
}
// Pre/Postcondition contract
if (!funcdecl.fbody)
funcdecl.buildEnsureRequire();
Scope* scout = null;
if (needEnsure || funcdecl.addPostInvariant())
{