-
-
Notifications
You must be signed in to change notification settings - Fork 594
/
dsymbolsem.d
6664 lines (5964 loc) · 239 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
/**
* Does the semantic 1 pass on the AST, which looks at symbol declarations but not initializers
* or function bodies.
*
* Copyright: Copyright (C) 1999-2020 by The D Language Foundation, 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/dmd/dsymbolsem.d, _dsymbolsem.d)
* Documentation: https://dlang.org/phobos/dmd_dsymbolsem.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/dsymbolsem.d
*/
module dmd.dsymbolsem;
import core.stdc.stdio;
import core.stdc.string;
import dmd.aggregate;
import dmd.aliasthis;
import dmd.arraytypes;
import dmd.astcodegen;
import dmd.attrib;
import dmd.blockexit;
import dmd.clone;
import dmd.compiler;
import dmd.dcast;
import dmd.dclass;
import dmd.declaration;
import dmd.denum;
import dmd.dimport;
import dmd.dinterpret;
import dmd.dmangle;
import dmd.dmodule;
import dmd.dscope;
import dmd.dstruct;
import dmd.dsymbol;
import dmd.dtemplate;
import dmd.dversion;
import dmd.errors;
import dmd.escape;
import dmd.expression;
import dmd.expressionsem;
import dmd.func;
import dmd.globals;
import dmd.id;
import dmd.identifier;
import dmd.init;
import dmd.initsem;
import dmd.hdrgen;
import dmd.mtype;
import dmd.nogc;
import dmd.nspace;
import dmd.objc;
import dmd.opover;
import dmd.parse;
import dmd.root.filename;
import dmd.root.outbuffer;
import dmd.root.rmem;
import dmd.root.rootobject;
import dmd.semantic2;
import dmd.semantic3;
import dmd.sideeffect;
import dmd.statementsem;
import dmd.staticassert;
import dmd.tokens;
import dmd.utf;
import dmd.utils;
import dmd.statement;
import dmd.target;
import dmd.templateparamsem;
import dmd.typesem;
import dmd.visitor;
enum LOG = false;
/*****************************************
* Create inclusive postblit for struct by aggregating
* all the postblits in postblits[] with the postblits for
* all the members.
* Note the close similarity with AggregateDeclaration::buildDtor(),
* and the ordering changes (runs forward instead of backwards).
*/
private FuncDeclaration buildPostBlit(StructDeclaration sd, Scope* sc)
{
//printf("StructDeclaration::buildPostBlit() %s\n", sd.toChars());
if (sd.isUnionDeclaration())
return null;
// by default, the storage class of the created postblit
StorageClass stc = STC.safe | STC.nothrow_ | STC.pure_ | STC.nogc;
Loc declLoc = sd.postblits.dim ? sd.postblits[0].loc : sd.loc;
Loc loc; // internal code should have no loc to prevent coverage
// if any of the postblits are disabled, then the generated postblit
// will be disabled
for (size_t i = 0; i < sd.postblits.dim; i++)
{
stc |= sd.postblits[i].storage_class & STC.disable;
}
VarDeclaration[] fieldsToDestroy;
auto postblitCalls = new Statements();
// iterate through all the struct fields that are not disabled
for (size_t i = 0; i < sd.fields.dim && !(stc & STC.disable); i++)
{
auto structField = sd.fields[i];
if (structField.storage_class & STC.ref_)
continue;
if (structField.overlapped)
continue;
// if it's a struct declaration or an array of structs
Type tv = structField.type.baseElemOf();
if (tv.ty != Tstruct)
continue;
auto sdv = (cast(TypeStruct)tv).sym;
// which has a postblit declaration
if (!sdv.postblit)
continue;
assert(!sdv.isUnionDeclaration());
// if this field's postblit is not `nothrow`, add a `scope(failure)`
// block to destroy any prior successfully postblitted fields should
// this field's postblit fail
if (fieldsToDestroy.length > 0 && !(cast(TypeFunction)sdv.postblit.type).isnothrow)
{
// create a list of destructors that need to be called
Expression[] dtorCalls;
foreach(sf; fieldsToDestroy)
{
Expression ex;
tv = sf.type.toBasetype();
if (tv.ty == Tstruct)
{
// this.v.__xdtor()
ex = new ThisExp(loc);
ex = new DotVarExp(loc, ex, sf);
// This is a hack so we can call destructors on const/immutable objects.
ex = new AddrExp(loc, ex);
ex = new CastExp(loc, ex, sf.type.mutableOf().pointerTo());
ex = new PtrExp(loc, ex);
if (stc & STC.safe)
stc = (stc & ~STC.safe) | STC.trusted;
auto sfv = (cast(TypeStruct)sf.type.baseElemOf()).sym;
ex = new DotVarExp(loc, ex, sfv.dtor, false);
ex = new CallExp(loc, ex);
dtorCalls ~= ex;
}
else
{
// _ArrayDtor((cast(S*)this.v.ptr)[0 .. n])
const length = tv.numberOfElems(loc);
ex = new ThisExp(loc);
ex = new DotVarExp(loc, ex, sf);
// This is a hack so we can call destructors on const/immutable objects.
ex = new DotIdExp(loc, ex, Id.ptr);
ex = new CastExp(loc, ex, sdv.type.pointerTo());
if (stc & STC.safe)
stc = (stc & ~STC.safe) | STC.trusted;
auto se = new SliceExp(loc, ex, new IntegerExp(loc, 0, Type.tsize_t),
new IntegerExp(loc, length, Type.tsize_t));
// Prevent redundant bounds check
se.upperIsInBounds = true;
se.lowerIsLessThanUpper = true;
ex = new CallExp(loc, new IdentifierExp(loc, Id.__ArrayDtor), se);
dtorCalls ~= ex;
}
}
fieldsToDestroy = [];
// aggregate the destructor calls
auto dtors = new Statements();
foreach_reverse(dc; dtorCalls)
{
dtors.push(new ExpStatement(loc, dc));
}
// put destructor calls in a `scope(failure)` block
postblitCalls.push(new ScopeGuardStatement(loc, TOK.onScopeFailure, new CompoundStatement(loc, dtors)));
}
// perform semantic on the member postblit in order to
// be able to aggregate it later on with the rest of the
// postblits
sdv.postblit.functionSemantic();
stc = mergeFuncAttrs(stc, sdv.postblit);
stc = mergeFuncAttrs(stc, sdv.dtor);
// if any of the struct member fields has disabled
// its postblit, then `sd` is not copyable, so no
// postblit is generated
if (stc & STC.disable)
{
postblitCalls.setDim(0);
break;
}
Expression ex;
tv = structField.type.toBasetype();
if (tv.ty == Tstruct)
{
// this.v.__xpostblit()
ex = new ThisExp(loc);
ex = new DotVarExp(loc, ex, structField);
// This is a hack so we can call postblits on const/immutable objects.
ex = new AddrExp(loc, ex);
ex = new CastExp(loc, ex, structField.type.mutableOf().pointerTo());
ex = new PtrExp(loc, ex);
if (stc & STC.safe)
stc = (stc & ~STC.safe) | STC.trusted;
ex = new DotVarExp(loc, ex, sdv.postblit, false);
ex = new CallExp(loc, ex);
}
else
{
// _ArrayPostblit((cast(S*)this.v.ptr)[0 .. n])
const length = tv.numberOfElems(loc);
if (length == 0)
continue;
ex = new ThisExp(loc);
ex = new DotVarExp(loc, ex, structField);
// This is a hack so we can call postblits on const/immutable objects.
ex = new DotIdExp(loc, ex, Id.ptr);
ex = new CastExp(loc, ex, sdv.type.pointerTo());
if (stc & STC.safe)
stc = (stc & ~STC.safe) | STC.trusted;
auto se = new SliceExp(loc, ex, new IntegerExp(loc, 0, Type.tsize_t),
new IntegerExp(loc, length, Type.tsize_t));
// Prevent redundant bounds check
se.upperIsInBounds = true;
se.lowerIsLessThanUpper = true;
ex = new CallExp(loc, new IdentifierExp(loc, Id.__ArrayPostblit), se);
}
postblitCalls.push(new ExpStatement(loc, ex)); // combine in forward order
/* https://issues.dlang.org/show_bug.cgi?id=10972
* When subsequent field postblit calls fail,
* this field should be destructed for Exception Safety.
*/
if (sdv.dtor)
{
sdv.dtor.functionSemantic();
// keep a list of fields that need to be destroyed in case
// of a future postblit failure
fieldsToDestroy ~= structField;
}
}
void checkShared()
{
if (sd.type.isShared())
stc |= STC.shared_;
}
// Build our own "postblit" which executes a, but only if needed.
if (postblitCalls.dim || (stc & STC.disable))
{
//printf("Building __fieldPostBlit()\n");
checkShared();
auto dd = new PostBlitDeclaration(declLoc, Loc.initial, stc, Id.__fieldPostblit);
dd.generated = true;
dd.storage_class |= STC.inference;
dd.fbody = (stc & STC.disable) ? null : new CompoundStatement(loc, postblitCalls);
sd.postblits.shift(dd);
sd.members.push(dd);
dd.dsymbolSemantic(sc);
}
// create __xpostblit, which is the generated postblit
FuncDeclaration xpostblit = null;
switch (sd.postblits.dim)
{
case 0:
break;
case 1:
xpostblit = sd.postblits[0];
break;
default:
Expression e = null;
stc = STC.safe | STC.nothrow_ | STC.pure_ | STC.nogc;
for (size_t i = 0; i < sd.postblits.dim; i++)
{
auto fd = sd.postblits[i];
stc = mergeFuncAttrs(stc, fd);
if (stc & STC.disable)
{
e = null;
break;
}
Expression ex = new ThisExp(loc);
ex = new DotVarExp(loc, ex, fd, false);
ex = new CallExp(loc, ex);
e = Expression.combine(e, ex);
}
checkShared();
auto dd = new PostBlitDeclaration(declLoc, Loc.initial, stc, Id.__aggrPostblit);
dd.generated = true;
dd.storage_class |= STC.inference;
dd.fbody = new ExpStatement(loc, e);
sd.members.push(dd);
dd.dsymbolSemantic(sc);
xpostblit = dd;
break;
}
// Add an __xpostblit alias to make the inclusive postblit accessible
if (xpostblit)
{
auto _alias = new AliasDeclaration(Loc.initial, Id.__xpostblit, xpostblit);
_alias.dsymbolSemantic(sc);
sd.members.push(_alias);
_alias.addMember(sc, sd); // add to symbol table
}
return xpostblit;
}
/**
* Generates a copy constructor declaration with the specified storage
* class for the parameter and the function.
*
* Params:
* sd = the `struct` that contains the copy constructor
* paramStc = the storage class of the copy constructor parameter
* funcStc = the storage class for the copy constructor declaration
*
* Returns:
* The copy constructor declaration for struct `sd`.
*/
private CtorDeclaration generateCopyCtorDeclaration(StructDeclaration sd, const StorageClass paramStc, const StorageClass funcStc)
{
auto fparams = new Parameters();
auto structType = sd.type;
fparams.push(new Parameter(paramStc | STC.ref_ | STC.return_ | STC.scope_, structType, Id.p, null, null));
ParameterList pList = ParameterList(fparams);
auto tf = new TypeFunction(pList, structType, LINK.d, STC.ref_);
auto ccd = new CtorDeclaration(sd.loc, Loc.initial, STC.ref_, tf, true);
ccd.storage_class |= funcStc;
ccd.storage_class |= STC.inference;
ccd.generated = true;
return ccd;
}
/**
* Generates a trivial copy constructor body that simply does memberwise
* initialization:
*
* this.field1 = rhs.field1;
* this.field2 = rhs.field2;
* ...
*
* Params:
* sd = the `struct` declaration that contains the copy constructor
*
* Returns:
* A `CompoundStatement` containing the body of the copy constructor.
*/
private Statement generateCopyCtorBody(StructDeclaration sd)
{
Loc loc;
Expression e;
foreach (v; sd.fields)
{
auto ec = new AssignExp(loc,
new DotVarExp(loc, new ThisExp(loc), v),
new DotVarExp(loc, new IdentifierExp(loc, Id.p), v));
e = Expression.combine(e, ec);
//printf("e.toChars = %s\n", e.toChars());
}
Statement s1 = new ExpStatement(loc, e);
return new CompoundStatement(loc, s1);
}
/**
* Generates a copy constructor for a specified `struct` sd if
* the following conditions are met:
*
* 1. sd does not define a copy constructor
* 2. at least one field of sd defines a copy constructor
*
* If the above conditions are met, the following copy constructor
* is generated:
*
* this(ref return scope inout(S) rhs) inout
* {
* this.field1 = rhs.field1;
* this.field2 = rhs.field2;
* ...
* }
*
* Params:
* sd = the `struct` for which the copy constructor is generated
* sc = the scope where the copy constructor is generated
*
* Returns:
* `true` if `struct` sd defines a copy constructor (explicitly or generated),
* `false` otherwise.
*/
private bool buildCopyCtor(StructDeclaration sd, Scope* sc)
{
if (global.errors)
return false;
bool hasPostblit;
if (sd.postblit && !sd.postblit.isDisabled())
hasPostblit = true;
auto ctor = sd.search(sd.loc, Id.ctor);
CtorDeclaration cpCtor;
CtorDeclaration rvalueCtor;
if (ctor)
{
if (ctor.isOverloadSet())
return false;
if (auto td = ctor.isTemplateDeclaration())
ctor = td.funcroot;
}
if (!ctor)
goto LcheckFields;
overloadApply(ctor, (Dsymbol s)
{
if (s.isTemplateDeclaration())
return 0;
auto ctorDecl = s.isCtorDeclaration();
assert(ctorDecl);
if (ctorDecl.isCpCtor)
{
if (!cpCtor)
cpCtor = ctorDecl;
return 0;
}
auto tf = ctorDecl.type.toTypeFunction();
const dim = tf.parameterList.length;
if (dim == 1)
{
auto param = tf.parameterList[0];
if (param.type.mutableOf().unSharedOf() == sd.type.mutableOf().unSharedOf())
{
rvalueCtor = ctorDecl;
}
}
return 0;
});
if (cpCtor && rvalueCtor)
{
.error(sd.loc, "`struct %s` may not define both a rvalue constructor and a copy constructor", sd.toChars());
errorSupplemental(rvalueCtor.loc,"rvalue constructor defined here");
errorSupplemental(cpCtor.loc, "copy constructor defined here");
return true;
}
else if (cpCtor)
{
return !hasPostblit;
}
LcheckFields:
VarDeclaration fieldWithCpCtor;
// see if any struct members define a copy constructor
foreach (v; sd.fields)
{
if (v.storage_class & STC.ref_)
continue;
if (v.overlapped)
continue;
auto ts = v.type.baseElemOf().isTypeStruct();
if (!ts)
continue;
if (ts.sym.hasCopyCtor)
{
fieldWithCpCtor = v;
break;
}
}
if (fieldWithCpCtor && rvalueCtor)
{
.error(sd.loc, "`struct %s` may not define a rvalue constructor and have fields with copy constructors", sd.toChars());
errorSupplemental(rvalueCtor.loc,"rvalue constructor defined here");
errorSupplemental(fieldWithCpCtor.loc, "field with copy constructor defined here");
return false;
}
else if (!fieldWithCpCtor)
return false;
if (hasPostblit)
return false;
//printf("generating copy constructor for %s\n", sd.toChars());
const MOD paramMod = MODFlags.wild;
const MOD funcMod = MODFlags.wild;
auto ccd = generateCopyCtorDeclaration(sd, ModToStc(paramMod), ModToStc(funcMod));
auto copyCtorBody = generateCopyCtorBody(sd);
ccd.fbody = copyCtorBody;
sd.members.push(ccd);
ccd.addMember(sc, sd);
const errors = global.startGagging();
Scope* sc2 = sc.push();
sc2.stc = 0;
sc2.linkage = LINK.d;
ccd.dsymbolSemantic(sc2);
ccd.semantic2(sc2);
ccd.semantic3(sc2);
//printf("ccd semantic: %s\n", ccd.type.toChars());
sc2.pop();
if (global.endGagging(errors))
{
ccd.storage_class |= STC.disable;
ccd.fbody = null;
}
return true;
}
private uint setMangleOverride(Dsymbol s, const(char)[] sym)
{
if (s.isFuncDeclaration() || s.isVarDeclaration())
{
s.isDeclaration().mangleOverride = sym;
return 1;
}
if (auto ad = s.isAttribDeclaration())
{
uint nestedCount = 0;
ad.include(null).foreachDsymbol( (s) { nestedCount += setMangleOverride(s, sym); } );
return nestedCount;
}
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);
}
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 == TOK.error)
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;
}
// Returns true if a contract can appear without a function body.
package bool allowsContractWithoutBody(FuncDeclaration funcdecl)
{
assert(!funcdecl.fbody);
/* Contracts can only appear without a body when they are virtual
* interface functions or abstract.
*/
Dsymbol parent = funcdecl.toParent();
InterfaceDeclaration id = parent.isInterfaceDeclaration();
if (!funcdecl.isAbstract() &&
(funcdecl.fensures || funcdecl.frequires) &&
!(id && funcdecl.isVirtual()))
{
auto cd = parent.isClassDeclaration();
if (!(cd && cd.isAbstract()))
return false;
}
return true;
}
private extern(C++) final class DsymbolSemanticVisitor : Visitor
{
alias visit = Visitor.visit;
Scope* sc;
this(Scope* sc)
{
this.sc = sc;
}
// Save the scope and defer semantic analysis on the Dsymbol.
private void deferDsymbolSemantic(Dsymbol s, Scope *scx)
{
s._scope = scx ? scx : sc.copy();
s._scope.setNoFree();
Module.addDeferredSemantic(s);
}
override void visit(Dsymbol dsym)
{
dsym.error("%p has no semantic routine", dsym);
}
override void visit(ScopeDsymbol) { }
override void visit(Declaration) { }
override void visit(AliasThis dsym)
{
if (dsym.semanticRun != PASS.init)
return;
if (dsym._scope)
{
sc = dsym._scope;
dsym._scope = null;
}
if (!sc)
return;
dsym.semanticRun = PASS.semantic;
dsym.isDeprecated_ = !!(sc.stc & STC.deprecated_);
Dsymbol p = sc.parent.pastMixin();
AggregateDeclaration ad = p.isAggregateDeclaration();
if (!ad)
{
error(dsym.loc, "alias this can only be a member of aggregate, not %s `%s`", p.kind(), p.toChars());
return;
}
assert(ad.members);
Dsymbol s = ad.search(dsym.loc, dsym.ident);
if (!s)
{
s = sc.search(dsym.loc, dsym.ident, null);
if (s)
error(dsym.loc, "`%s` is not a member of `%s`", s.toChars(), ad.toChars());
else
error(dsym.loc, "undefined identifier `%s`", dsym.ident.toChars());
return;
}
if (ad.aliasthis && s != ad.aliasthis)
{
error(dsym.loc, "there can be only one alias this");
return;
}
/* disable the alias this conversion so the implicit conversion check
* doesn't use it.
*/
ad.aliasthis = null;
Dsymbol sx = s;
if (sx.isAliasDeclaration())
sx = sx.toAlias();
Declaration d = sx.isDeclaration();
if (d && !d.isTupleDeclaration())
{
/* https://issues.dlang.org/show_bug.cgi?id=18429
*
* If the identifier in the AliasThis declaration
* is defined later and is a voldemort type, we must
* perform semantic on the declaration to deduce the type.
*/
if (!d.type)
d.dsymbolSemantic(sc);
Type t = d.type;
assert(t);
if (ad.type.implicitConvTo(t) > MATCH.nomatch)
{
error(dsym.loc, "alias this is not reachable as `%s` already converts to `%s`", ad.toChars(), t.toChars());
}
}
dsym.sym = s;
// Restore alias this
ad.aliasthis = dsym;
dsym.semanticRun = PASS.semanticdone;
}
override void visit(AliasDeclaration dsym)
{
if (dsym.semanticRun >= PASS.semanticdone)
return;
assert(dsym.semanticRun <= PASS.semantic);
dsym.storage_class |= sc.stc & STC.deprecated_;
dsym.protection = sc.protection;
dsym.userAttribDecl = sc.userAttribDecl;
if (!sc.func && dsym.inNonRoot())
return;
aliasSemantic(dsym, sc);
}
override void visit(VarDeclaration dsym)
{
version (none)
{
printf("VarDeclaration::semantic('%s', parent = '%s') sem = %d\n",
dsym.toChars(), sc.parent ? sc.parent.toChars() : null, dsym.semanticRun);
printf(" type = %s\n", dsym.type ? dsym.type.toChars() : "null");
printf(" stc = x%x\n", dsym.storage_class.stc);
printf(" storage_class = x%llx\n", dsym.storage_class);
printf("linkage = %d\n", dsym.linkage);
//if (strcmp(toChars(), "mul") == 0) assert(0);
}
//if (semanticRun > PASS.init)
// return;
//semanticRun = PSSsemantic;
if (dsym.semanticRun >= PASS.semanticdone)
return;
if (sc && sc.inunion && sc.inunion.isAnonDeclaration())
dsym.overlapped = true;
Scope* scx = null;
if (dsym._scope)
{
sc = dsym._scope;
scx = sc;
dsym._scope = null;
}
if (!sc)
return;
dsym.semanticRun = PASS.semantic;
/* Pick up storage classes from context, but except synchronized,
* override, abstract, and final.
*/
dsym.storage_class |= (sc.stc & ~(STC.synchronized_ | STC.override_ | STC.abstract_ | STC.final_));
if (dsym.storage_class & STC.extern_ && dsym._init)
dsym.error("extern symbols cannot have initializers");
dsym.userAttribDecl = sc.userAttribDecl;
dsym.cppnamespace = sc.namespace;
AggregateDeclaration ad = dsym.isThis();
if (ad)
dsym.storage_class |= ad.storage_class & STC.TYPECTOR;
/* If auto type inference, do the inference
*/
int inferred = 0;
if (!dsym.type)
{
dsym.inuse++;
// Infering the type requires running semantic,
// so mark the scope as ctfe if required
bool needctfe = (dsym.storage_class & (STC.manifest | STC.static_)) != 0;
if (needctfe)
{
sc.flags |= SCOPE.condition;
sc = sc.startCTFE();
}
//printf("inferring type for %s with init %s\n", dsym.toChars(), dsym._init.toChars());
dsym._init = dsym._init.inferType(sc);
dsym.type = dsym._init.initializerToExpression().type;
if (needctfe)
sc = sc.endCTFE();
dsym.inuse--;
inferred = 1;
/* This is a kludge to support the existing syntax for RAII
* declarations.
*/
dsym.storage_class &= ~STC.auto_;
dsym.originalType = dsym.type.syntaxCopy();
}
else
{
if (!dsym.originalType)
dsym.originalType = dsym.type.syntaxCopy();
/* Prefix function attributes of variable declaration can affect
* its type:
* pure nothrow void function() fp;
* static assert(is(typeof(fp) == void function() pure nothrow));
*/
Scope* sc2 = sc.push();
sc2.stc |= (dsym.storage_class & STC.FUNCATTR);
dsym.inuse++;
dsym.type = dsym.type.typeSemantic(dsym.loc, sc2);
dsym.inuse--;
sc2.pop();
}
//printf(" semantic type = %s\n", dsym.type ? dsym.type.toChars() : "null");
if (dsym.type.ty == Terror)
dsym.errors = true;
dsym.type.checkDeprecated(dsym.loc, sc);
dsym.linkage = sc.linkage;
dsym.parent = sc.parent;
//printf("this = %p, parent = %p, '%s'\n", dsym, dsym.parent, dsym.parent.toChars());
dsym.protection = sc.protection;
/* If scope's alignment is the default, use the type's alignment,
* otherwise the scope overrrides.
*/
dsym.alignment = sc.alignment();
if (dsym.alignment == STRUCTALIGN_DEFAULT)
dsym.alignment = dsym.type.alignment(); // use type's alignment
//printf("sc.stc = %x\n", sc.stc);
//printf("storage_class = x%x\n", storage_class);
if (global.params.vcomplex)
dsym.type.checkComplexTransition(dsym.loc, sc);
// Calculate type size + safety checks
if (sc.func && !sc.intypeof)
{
if (dsym.storage_class & STC.gshared && !dsym.isMember())
{
if (sc.func.setUnsafe())
dsym.error("__gshared not allowed in safe functions; use shared");
}
}
Dsymbol parent = dsym.toParent();
Type tb = dsym.type.toBasetype();
Type tbn = tb.baseElemOf();
if (tb.ty == Tvoid && !(dsym.storage_class & STC.lazy_))
{
if (inferred)
{
dsym.error("type `%s` is inferred from initializer `%s`, and variables cannot be of type `void`", dsym.type.toChars(), dsym._init.toChars());
}
else
dsym.error("variables cannot be of type `void`");
dsym.type = Type.terror;
tb = dsym.type;
}
if (tb.ty == Tfunction)
{
dsym.error("cannot be declared to be a function");
dsym.type = Type.terror;
tb = dsym.type;
}
if (auto ts = tb.isTypeStruct())
{
if (!ts.sym.members)
{
dsym.error("no definition of struct `%s`", ts.toChars());
}
}
if ((dsym.storage_class & STC.auto_) && !inferred)
dsym.error("storage class `auto` has no effect if type is not inferred, did you mean `scope`?");
if (auto tt = tb.isTypeTuple())
{
/* Instead, declare variables for each of the tuple elements
* and add those.
*/
size_t nelems = Parameter.dim(tt.arguments);
Expression ie = (dsym._init && !dsym._init.isVoidInitializer()) ? dsym._init.initializerToExpression() : null;
if (ie)
ie = ie.expressionSemantic(sc);
if (nelems > 0 && ie)
{
auto iexps = new Expressions();
iexps.push(ie);
auto exps = new Expressions();
for (size_t pos = 0; pos < iexps.dim; pos++)
{
Lexpand1:
Expression e = (*iexps)[pos];
Parameter arg = Parameter.getNth(tt.arguments, pos);
arg.type = arg.type.typeSemantic(dsym.loc, sc);
//printf("[%d] iexps.dim = %d, ", pos, iexps.dim);
//printf("e = (%s %s, %s), ", Token::tochars[e.op], e.toChars(), e.type.toChars());
//printf("arg = (%s, %s)\n", arg.toChars(), arg.type.toChars());
if (e != ie)
{
if (iexps.dim > nelems)
goto Lnomatch;
if (e.type.implicitConvTo(arg.type))
continue;
}
if (e.op == TOK.tuple)
{
TupleExp te = cast(TupleExp)e;
if (iexps.dim - 1 + te.exps.dim > nelems)
goto Lnomatch;
iexps.remove(pos);
iexps.insert(pos, te.exps);
(*iexps)[pos] = Expression.combine(te.e0, (*iexps)[pos]);
goto Lexpand1;
}
else if (isAliasThisTuple(e))
{
auto v = copyToTemp(0, "__tup", e);
v.dsymbolSemantic(sc);
auto ve = new VarExp(dsym.loc, v);
ve.type = e.type;
exps.setDim(1);
(*exps)[0] = ve;
expandAliasThisTuples(exps, 0);
for (size_t u = 0; u < exps.dim; u++)
{
Lexpand2:
Expression ee = (*exps)[u];
arg = Parameter.getNth(tt.arguments, pos + u);
arg.type = arg.type.typeSemantic(dsym.loc, sc);
//printf("[%d+%d] exps.dim = %d, ", pos, u, exps.dim);
//printf("ee = (%s %s, %s), ", Token::tochars[ee.op], ee.toChars(), ee.type.toChars());
//printf("arg = (%s, %s)\n", arg.toChars(), arg.type.toChars());
size_t iexps_dim = iexps.dim - 1 + exps.dim;
if (iexps_dim > nelems)
goto Lnomatch;
if (ee.type.implicitConvTo(arg.type))
continue;
if (expandAliasThisTuples(exps, u) != -1)
goto Lexpand2;
}
if ((*exps)[0] != ve)
{
Expression e0 = (*exps)[0];
(*exps)[0] = new CommaExp(dsym.loc, new DeclarationExp(dsym.loc, v), e0);
(*exps)[0].type = e0.type;
iexps.remove(pos);
iexps.insert(pos, exps);
goto Lexpand1;
}