Debian Codegraph @

gcc/d/dmd/dsymbolsem.d

raw
1 /**
2 * Does the semantic 1 pass on the AST, which looks at symbol declarations but not initializers
3 * or function bodies.
4 *
5 * Copyright: Copyright (C) 1999-2025 by The D Language Foundation, All Rights Reserved
6 * Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
7 * License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
8 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/compiler/src/dmd/dsymbolsem.d, _dsymbolsem.d)
9 * Documentation: https://dlang.org/phobos/dmd_dsymbolsem.html
10 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/dsymbolsem.d
11 */
12
13 module dmd.dsymbolsem;
14
15 import core.stdc.stdio;
16 import core.stdc.string;
17
18 import dmd.aggregate;
19 import dmd.aliasthis;
20 import dmd.arraytypes;
21 import dmd.astcodegen;
22 import dmd.astenums;
23 import dmd.attrib;
24 import dmd.attribsem;
25 import dmd.clone;
26 import dmd.cond;
27 import dmd.timetrace;
28 import dmd.dcast;
29 import dmd.dclass;
30 import dmd.declaration;
31 import dmd.denum;
32 import dmd.deps;
33 import dmd.dimport;
34 import dmd.dinterpret;
35 import dmd.dmodule;
36 import dmd.dscope;
37 import dmd.dstruct;
38 import dmd.dsymbol;
39 import dmd.dtemplate;
40 import dmd.dversion;
41 import dmd.enumsem;
42 import dmd.errors;
43 import dmd.escape;
44 import dmd.expression;
45 import dmd.expressionsem;
46 import dmd.func;
47 import dmd.funcsem;
48 import dmd.globals;
49 import dmd.id;
50 import dmd.identifier;
51 import dmd.importc;
52 import dmd.init;
53 import dmd.initsem;
54 import dmd.intrange;
55 import dmd.hdrgen;
56 import dmd.lexer;
57 import dmd.location;
58 import dmd.mtype;
59 import dmd.mustuse;
60 import dmd.nspace;
61 import dmd.objc;
62 import dmd.opover;
63 import dmd.optimize;
64 import dmd.parse;
65 debug import dmd.printast;
66 import dmd.root.array;
67 import dmd.root.filename;
68 import dmd.root.string;
69 import dmd.common.outbuffer;
70 import dmd.root.rmem;
71 import dmd.rootobject;
72 import dmd.safe;
73 import dmd.semantic2;
74 import dmd.semantic3;
75 import dmd.sideeffect;
76 import dmd.staticassert;
77 import dmd.tokens;
78 import dmd.utils;
79 import dmd.statement;
80 import dmd.target;
81 import dmd.templateparamsem;
82 import dmd.templatesem;
83 import dmd.typesem;
84 import dmd.visitor;
85
86 version (IN_GCC) {}
87 else version (IN_LLVM) {}
88 else version = MARS;
89
90 enum LOG = false;
91
92 /*************************************
93 * Does semantic analysis on the public face of declarations.
94 */
95 void dsymbolSemantic(Dsymbol dsym, Scope* sc)
96 {
97 scope v = new DsymbolSemanticVisitor(sc);
98 dsym.accept(v);
99 }
100
101 /***************************************************
102 * Determine the numerical value of the AlignmentDeclaration
103 * Params:
104 * ad = AlignmentDeclaration
105 * sc = context
106 * Returns:
107 * ad with alignment value determined
108 */
109 AlignDeclaration getAlignment(AlignDeclaration ad, Scope* sc)
110 {
111 if (!ad.salign.isUnknown()) // UNKNOWN is 0
112 return ad;
113
114 if (!ad.exps)
115 {
116 ad.salign.setDefault();
117 return ad;
118 }
119
120 dinteger_t strictest = 0; // strictest alignment
121 bool errors;
122 foreach (ref exp; (*ad.exps)[])
123 {
124 sc = sc.startCTFE();
125 auto e = exp.expressionSemantic(sc);
126 e = resolveProperties(sc, e);
127 sc = sc.endCTFE();
128 e = e.ctfeInterpret();
129 exp = e; // could be re-evaluated if exps are assigned to more than one AlignDeclaration by CParser.applySpecifier(),
130 // e.g. `_Alignas(8) int a, b;`
131 if (e.op == EXP.error)
132 errors = true;
133 else
134 {
135 auto n = e.toInteger();
136 if (sc.inCfile && n == 0) // C11 6.7.5-6 allows 0 for alignment
137 continue;
138
139 if (n < 1 || n & (n - 1) || ushort.max < n || !e.type.isIntegral())
140 {
141 error(ad.loc, "alignment must be an integer positive power of 2, not 0x%llx", cast(ulong)n);
142 errors = true;
143 }
144 if (n > strictest) // C11 6.7.5-6
145 strictest = n;
146 }
147 }
148
149 if (errors || strictest == 0) // C11 6.7.5-6 says alignment of 0 means no effect
150 ad.salign.setDefault();
151 else
152 ad.salign.set(cast(uint) strictest);
153
154 return ad;
155 }
156
157 const(char)* getMessage(DeprecatedDeclaration dd)
158 {
159 if (auto sc = dd._scope)
160 {
161 dd._scope = null;
162
163 sc = sc.startCTFE();
164 dd.msg = dd.msg.expressionSemantic(sc);
165 dd.msg = resolveProperties(sc, dd.msg);
166 sc = sc.endCTFE();
167 dd.msg = dd.msg.ctfeInterpret();
168
169 if (auto se = dd.msg.toStringExp())
170 dd.msgstr = se.toStringz().ptr;
171 else
172 error(dd.msg.loc, "compile time constant expected, not `%s`", dd.msg.toChars());
173 }
174 return dd.msgstr;
175 }
176
177 bool checkDeprecated(Dsymbol d, Loc loc, Scope* sc)
178 {
179 if (global.params.useDeprecated == DiagnosticReporting.off)
180 return false;
181 if (!d.isDeprecated())
182 return false;
183 // Don't complain if we're inside a deprecated symbol's scope
184 if (sc.isDeprecated())
185 return false;
186 // Don't complain if we're inside a template constraint
187 // https://issues.dlang.org/show_bug.cgi?id=21831
188 if (sc.inTemplateConstraint)
189 return false;
190
191 const(char)* message = null;
192 for (Dsymbol p = d; p; p = p.parent)
193 {
194 message = p.depdecl ? p.depdecl.getMessage() : null;
195 if (message)
196 break;
197 }
198 if (message)
199 deprecation(loc, "%s `%s` is deprecated - %s", d.kind, d.toPrettyChars, message);
200 else
201 deprecation(loc, "%s `%s` is deprecated", d.kind, d.toPrettyChars);
202
203 if (auto ti = sc.parent ? sc.parent.isInstantiated() : null)
204 ti.printInstantiationTrace(Classification.deprecation);
205 else if (auto ti = sc.parent ? sc.parent.isTemplateInstance() : null)
206 ti.printInstantiationTrace(Classification.deprecation);
207
208 return true;
209 }
210
211 /*********************************
212 * Check type to see if it is based on a deprecated symbol.
213 */
214 private void checkDeprecated(Type type, Loc loc, Scope* sc)
215 {
216 if (Dsymbol s = type.toDsymbol(sc))
217 {
218 s.checkDeprecated(loc, sc);
219 }
220
221 if (auto tn = type.nextOf())
222 tn.checkDeprecated(loc, sc);
223 }
224
225 // Returns true if a contract can appear without a function body.
226 package bool allowsContractWithoutBody(FuncDeclaration funcdecl)
227 {
228 assert(!funcdecl.fbody);
229
230 /* Contracts can only appear without a body when they are virtual
231 * interface functions or abstract.
232 */
233 Dsymbol parent = funcdecl.toParent();
234 InterfaceDeclaration id = parent.isInterfaceDeclaration();
235
236 if (!funcdecl.isAbstract() &&
237 (funcdecl.fensures || funcdecl.frequires) &&
238 !(id && funcdecl.isVirtual()))
239 {
240 auto cd = parent.isClassDeclaration();
241 if (!(cd && cd.isAbstract()))
242 return false;
243 }
244 return true;
245 }
246
247 /*
248 If sd has a copy constructor and ctor is an rvalue constructor,
249 issue an error.
250
251 Params:
252 sd = struct declaration that may contain both an rvalue and copy constructor
253 ctor = constructor that will be checked if it is an rvalue constructor
254 ti = template instance the ctor is part of
255
256 Return:
257 `true` if sd has a copy constructor and ctor is an rvalue constructor
258 */
259 bool checkHasBothRvalueAndCpCtor(StructDeclaration sd, CtorDeclaration ctor, TemplateInstance ti)
260 {
261 //printf("checkHasBothRvalueAndCpCtor() sd: %s ctor: %s ti: %s\n", sd.toChars(), ctor.toChars(), ti.toChars());
262 /* cannot use ctor.isMoveCtor because semantic pass may not have been run yet,
263 * so use isRvalueConstructor()
264 */
265 if (sd && sd.hasCopyCtor && isRvalueConstructor(sd, ctor))
266 {
267 .error(ctor.loc, "cannot define both an rvalue constructor and a copy constructor for `struct %s`", sd.toChars());
268 .errorSupplemental(ti.loc, "Template instance `%s` creates an rvalue constructor for `struct %s`",
269 ti.toPrettyChars(), sd.toChars());
270
271 return true;
272 }
273
274 return false;
275 }
276
277 /************************************************
278 * Check if ctor is an rvalue constructor.
279 * A constructor that receives a single parameter of the same type as
280 * `Unqual!typeof(this)` is an rvalue constructor.
281 * Params:
282 * sd = struct that ctor is a member of
283 * ctor = constructor to test
284 * Returns:
285 * true if it is an rvalue constructor
286 */
287 bool isRvalueConstructor(StructDeclaration sd, CtorDeclaration ctor)
288 {
289 // note commonality with setting isMoveCtor in the semantic code for CtorDeclaration
290 auto tf = ctor.type.isTypeFunction();
291 const dim = tf.parameterList.length;
292 if (dim == 1 || (dim > 1 && tf.parameterList[1].defaultArg))
293 {
294 auto param = tf.parameterList[0];
295 if (!(param.storageClass & STC.ref_) && param.type.mutableOf().unSharedOf() == sd.type.mutableOf().unSharedOf())
296 {
297 return true;
298 }
299 }
300 return false;
301 }
302
303 /*************************************
304 * Find the `alias this` symbol of e's type.
305 * Params:
306 * sc = context
307 * e = expression forming the `this`
308 * gag = do not print errors, return `null` instead
309 * findOnly = don't do further processing like resolving properties,
310 * i.e. just return plain dotExp() result.
311 * Returns:
312 * Expression that is `e.aliasthis`
313 */
314 Expression resolveAliasThis(Scope* sc, Expression e, bool gag = false, bool findOnly = false)
315 {
316 //printf("resolveAliasThis() %s\n", toChars(e));
317 import dmd.typesem : dotExp;
318 for (AggregateDeclaration ad = isAggregate(e.type); ad;)
319 {
320 if (ad.aliasthis)
321 {
322 Loc loc = e.loc;
323 Type tthis = (e.op == EXP.type ? e.type : null);
324 const flags = cast(DotExpFlag) (DotExpFlag.noAliasThis | (gag * DotExpFlag.gag));
325 const olderrors = gag ? global.startGagging() : 0;
326 e = dotExp(ad.type, sc, e, ad.aliasthis.ident, flags);
327 if (!e || findOnly)
328 return gag && global.endGagging(olderrors) ? null : e;
329
330 if (tthis && ad.aliasthis.sym.needThis())
331 {
332 if (auto ve = e.isVarExp())
333 {
334 if (auto fd = ve.var.isFuncDeclaration())
335 {
336 // https://issues.dlang.org/show_bug.cgi?id=13009
337 // Support better match for the overloaded alias this.
338 bool hasOverloads;
339 if (auto f = fd.overloadModMatch(loc, tthis, hasOverloads))
340 {
341 if (!hasOverloads)
342 fd = f; // use exact match
343 e = new VarExp(loc, fd, hasOverloads);
344 e.type = f.type;
345 e = new CallExp(loc, e);
346 goto L1;
347 }
348 }
349 }
350 /* non-@property function is not called inside typeof(),
351 * so resolve it ahead.
352 */
353 {
354 int save = sc.intypeof;
355 sc.intypeof = 1; // bypass "need this" error check
356 e = resolveProperties(sc, e);
357 sc.intypeof = save;
358 }
359 L1:
360 e = new TypeExp(loc, new TypeTypeof(loc, e));
361 e = e.expressionSemantic(sc);
362 }
363 e = resolveProperties(sc, e);
364 if (!gag)
365 ad.aliasthis.checkDeprecatedAliasThis(loc, sc);
366 else if (global.endGagging(olderrors))
367 e = null;
368 }
369
370 import dmd.dclass : ClassDeclaration;
371 auto cd = ad.isClassDeclaration();
372 if ((!e || !ad.aliasthis) && cd && cd.baseClass && cd.baseClass != ClassDeclaration.object)
373 {
374 ad = cd.baseClass;
375 continue;
376 }
377 break;
378 }
379 return e;
380 }
381
382 /**
383 * Check if an `alias this` is deprecated
384 *
385 * Usually one would use `expression.checkDeprecated(scope, aliasthis)` to
386 * check if `expression` uses a deprecated `aliasthis`, but this calls
387 * `toPrettyChars` which lead to the following message:
388 * "Deprecation: alias this `fullyqualified.aggregate.__anonymous` is deprecated"
389 *
390 * Params:
391 * at = The `AliasThis` object to check
392 * loc = `Loc` of the expression triggering the access to `at`
393 * sc = `Scope` of the expression
394 * (deprecations do not trigger in deprecated scopes)
395 *
396 * Returns:
397 * Whether the alias this was reported as deprecated.
398 */
399 private bool checkDeprecatedAliasThis(AliasThis at, Loc loc, Scope* sc)
400 {
401 if (global.params.useDeprecated != DiagnosticReporting.off
402 && at.isDeprecated() && !sc.isDeprecated())
403 {
404 const(char)* message = null;
405 for (Dsymbol p = at; p; p = p.parent)
406 {
407 message = p.depdecl ? p.depdecl.getMessage() : null;
408 if (message)
409 break;
410 }
411 if (message)
412 deprecation(loc, "`alias %s this` is deprecated - %s",
413 at.sym.toChars(), message);
414 else
415 deprecation(loc, "`alias %s this` is deprecated",
416 at.sym.toChars());
417
418 if (auto ti = sc.parent ? sc.parent.isInstantiated() : null)
419 ti.printInstantiationTrace(Classification.deprecation);
420
421 return true;
422 }
423 return false;
424 }
425
426 // Save the scope and defer semantic analysis on the Dsymbol.
427 void deferDsymbolSemantic(Scope* sc, Dsymbol s, Scope* scx)
428 {
429 s._scope = scx ? scx : sc.copy();
430 s._scope.setNoFree();
431 Module.addDeferredSemantic(s);
432 }
433
434
435 private extern(C++) final class DsymbolSemanticVisitor : Visitor
436 {
437 alias visit = Visitor.visit;
438
439 Scope* sc;
440 this(Scope* sc) scope @safe
441 {
442 this.sc = sc;
443 }
444
445 override void visit(Dsymbol dsym)
446 {
447 .error(dsym.loc, "%s `%s` %p has no semantic routine", dsym.kind, dsym.toPrettyChars, dsym);
448 }
449
450 override void visit(ScopeDsymbol) { }
451 override void visit(Declaration) { }
452
453 override void visit(AliasThis dsym)
454 {
455 if (dsym.semanticRun != PASS.initial)
456 return;
457
458 if (dsym._scope)
459 {
460 sc = dsym._scope;
461 dsym._scope = null;
462 }
463
464 if (!sc)
465 return;
466
467 dsym.semanticRun = PASS.semantic;
468 dsym.isDeprecated_ = !!(sc.stc & STC.deprecated_);
469
470 Dsymbol p = sc.parent.pastMixin();
471 AggregateDeclaration ad = p.isAggregateDeclaration();
472 if (!ad)
473 {
474 error(dsym.loc, "alias this can only be a member of aggregate, not %s `%s`", p.kind(), p.toChars());
475 return;
476 }
477
478 assert(ad.members);
479 Dsymbol s = ad.search(dsym.loc, dsym.ident);
480 if (!s)
481 {
482 Dsymbol pscopesym;
483 s = sc.search(dsym.loc, dsym.ident, pscopesym);
484 if (s)
485 error(dsym.loc, "`%s` is not a member of `%s`", s.toChars(), ad.toChars());
486 else
487 error(dsym.loc, "undefined identifier `%s`", dsym.ident.toChars());
488 return;
489 }
490 if (ad.aliasthis && s != ad.aliasthis)
491 {
492 error(dsym.loc, "there can be only one alias this");
493 return;
494 }
495
496 /* disable the alias this conversion so the implicit conversion check
497 * doesn't use it.
498 */
499 ad.aliasthis = null;
500
501 Dsymbol sx = s;
502 if (sx.isAliasDeclaration())
503 sx = sx.toAlias();
504 Declaration d = sx.isDeclaration();
505 if (d && !d.isTupleDeclaration())
506 {
507 /* https://issues.dlang.org/show_bug.cgi?id=18429
508 *
509 * If the identifier in the AliasThis declaration
510 * is defined later and is a voldemort type, we must
511 * perform semantic on the declaration to deduce the type.
512 */
513 if (!d.type)
514 d.dsymbolSemantic(sc);
515
516 Type t = d.type;
517 assert(t);
518 if (ad.type.implicitConvTo(t) > MATCH.nomatch)
519 {
520 error(dsym.loc, "alias this is not reachable as `%s` already converts to `%s`", ad.toChars(), t.toChars());
521 }
522 }
523
524 dsym.sym = s;
525 // Restore alias this
526 ad.aliasthis = dsym;
527 dsym.semanticRun = PASS.semanticdone;
528 }
529
530 override void visit(AliasDeclaration dsym)
531 {
532 if (dsym.semanticRun >= PASS.semanticdone)
533 return;
534 assert(dsym.semanticRun <= PASS.semantic);
535
536 if (!sc)
537 return;
538
539 dsym.semanticRun = PASS.semantic;
540
541 dsym.storage_class |= sc.stc & STC.deprecated_;
542 dsym.visibility = sc.visibility;
543 dsym.userAttribDecl = sc.userAttribDecl;
544
545 if (!sc.func && dsym.inNonRoot())
546 return;
547
548 aliasSemantic(dsym, sc);
549 }
550
551 override void visit(AliasAssign dsym)
552 {
553 //printf("visit(AliasAssign)\n");
554 if (dsym.semanticRun >= PASS.semanticdone)
555 return;
556 assert(dsym.semanticRun <= PASS.semantic);
557
558 if (!sc.func && dsym.inNonRoot())
559 return;
560
561 aliasAssignSemantic(dsym, sc);
562 }
563
564 override void visit(VarDeclaration dsym)
565 {
566 version (none)
567 {
568 printf("VarDeclaration::semantic('%s', parent = '%s') sem = %d\n",
569 dsym.toChars(), sc.parent ? sc.parent.toChars() : null, dsym.semanticRun);
570 printf(" type = %s\n", dsym.type ? dsym.type.toChars() : "null");
571 printf(" stc = x%llx\n", dsym.storage_class);
572 printf(" storage_class = x%llx\n", dsym.storage_class);
573 printf("linkage = %d\n", dsym._linkage);
574 //if (strcmp(toChars(), "mul") == 0) assert(0);
575 }
576 //if (semanticRun > PASS.initial)
577 // return;
578 //semanticRun = PSSsemantic;
579
580 if (dsym.semanticRun >= PASS.semanticdone)
581 return;
582
583 if (sc && sc.inunion && sc.inunion.isAnonDeclaration())
584 dsym.overlapped = true;
585
586 dsym.sequenceNumber = global.varSequenceNumber++;
587 if (!dsym.isScope())
588 dsym.maybeScope = true;
589
590 Scope* scx = null;
591 if (dsym._scope)
592 {
593 sc = dsym._scope;
594 scx = sc;
595 dsym._scope = null;
596 }
597
598 if (!sc)
599 return;
600
601 dsym.semanticRun = PASS.semantic;
602
603 // 'static foreach' variables should not inherit scope properties
604 // https://issues.dlang.org/show_bug.cgi?id=19482
605 if ((dsym.storage_class & (STC.foreach_ | STC.local)) == (STC.foreach_ | STC.local))
606 {
607 dsym._linkage = LINK.d;
608 dsym.visibility = Visibility(Visibility.Kind.public_);
609 dsym.overlapped = false; // unset because it is modified early on this function
610 dsym.userAttribDecl = null; // unset because it is set by Dsymbol.setScope()
611 }
612 else
613 {
614 /* Pick up storage classes from context, but except synchronized,
615 * override, abstract, and final.
616 */
617 dsym.storage_class |= (sc.stc & ~(STC.synchronized_ | STC.override_ | STC.abstract_ | STC.final_));
618 dsym.userAttribDecl = sc.userAttribDecl;
619 dsym.cppnamespace = sc.namespace;
620 dsym._linkage = sc.linkage;
621 dsym.visibility = sc.visibility;
622 dsym.alignment = sc.alignment();
623 }
624
625 if (dsym.storage_class & STC.extern_ && dsym._init)
626 {
627 if (sc.inCfile)
628 {
629 // https://issues.dlang.org/show_bug.cgi?id=24447
630 // extern int x = 3; is allowed in C
631 dsym.storage_class &= ~STC.extern_;
632 }
633 else
634 .error(dsym.loc, "%s `%s` extern symbols cannot have initializers", dsym.kind, dsym.toPrettyChars);
635
636 }
637
638 AggregateDeclaration ad = dsym.isThis();
639 if (ad)
640 dsym.storage_class |= ad.storage_class & STC.TYPECTOR;
641
642 if ((dsym.storage_class & STC.auto_) && (dsym.storage_class & STC.ref_))
643 {
644 if (!(dsym.storage_class & STC.autoref))
645 {
646 .error(dsym.loc, "%s `%s` - `auto ref` variable must have `auto` and `ref` adjacent", dsym.kind, dsym.toChars());
647 dsym.storage_class |= STC.autoref;
648 }
649 }
650
651 /* If auto type inference, do the inference
652 */
653 int inferred = 0;
654 if (!dsym.type)
655 {
656 dsym.inuse++;
657
658 // Infering the type requires running semantic,
659 // so mark the scope as ctfe if required
660 bool needctfe = (dsym.storage_class & (STC.manifest | STC.static_)) != 0 || !sc.func;
661 if (needctfe)
662 {
663 sc.condition = true;
664 sc = sc.startCTFE();
665 }
666 //printf("inferring type for %s with init %s\n", dsym.toChars(), dsym._init.toChars());
667 dsym._init = dsym._init.inferType(sc);
668 dsym.type = dsym._init.initializerToExpression(null, sc.inCfile).type;
669 if (needctfe)
670 sc = sc.endCTFE();
671
672 dsym.inuse--;
673 inferred = 1;
674
675 /* This is a kludge to support the existing syntax for RAII
676 * declarations.
677 */
678 dsym.storage_class &= ~STC.auto_;
679 dsym.originalType = dsym.type.syntaxCopy();
680 }
681 else
682 {
683 if (!dsym.originalType)
684 dsym.originalType = dsym.type.syntaxCopy();
685
686 /* Prefix function attributes of variable declaration can affect
687 * its type:
688 * pure nothrow void function() fp;
689 * static assert(is(typeof(fp) == void function() pure nothrow));
690 */
691 Scope* sc2 = sc.push();
692 sc2.stc |= (dsym.storage_class & STC.FUNCATTR);
693 dsym.inuse++;
694 dsym.type = dsym.type.typeSemantic(dsym.loc, sc2);
695 dsym.inuse--;
696 sc2.pop();
697 }
698 //printf(" semantic type = %s\n", dsym.type ? dsym.type.toChars() : "null");
699 if (dsym.type.ty == Terror)
700 dsym.errors = true;
701
702 dsym.type.checkDeprecated(dsym.loc, sc);
703 dsym.parent = sc.parent;
704 //printf("this = %p, parent = %p, '%s'\n", dsym, dsym.parent, dsym.parent.toChars());
705
706 /* If scope's alignment is the default, use the type's alignment,
707 * otherwise the scope overrrides.
708 */
709 if (dsym.alignment.isDefault())
710 dsym.alignment = dsym.type.alignment(); // use type's alignment
711
712 //printf("sc.stc = %x\n", sc.stc);
713 //printf("storage_class = x%x\n", storage_class);
714
715 dsym.type.checkComplexTransition(dsym.loc, sc);
716
717 // Calculate type size + safety checks
718 if (dsym.storage_class & STC.gshared && !dsym.isMember())
719 {
720 sc.setUnsafe(false, dsym.loc, "using `__gshared` instead of `shared`");
721 }
722
723 Dsymbol parent = dsym.toParent();
724
725 Type tb = dsym.type.toBasetype();
726 Type tbn = tb.baseElemOf();
727 if (tb.ty == Tvoid && !(dsym.storage_class & STC.lazy_))
728 {
729 if (inferred)
730 {
731 .error(dsym.loc, "%s `%s` - type `%s` is inferred from initializer `%s`, and variables cannot be of type `void`",
732 dsym.kind, dsym.toPrettyChars, dsym.type.toChars(), toChars(dsym._init));
733 }
734 else
735 .error(dsym.loc, "%s `%s` - variables cannot be of type `void`", dsym.kind, dsym.toPrettyChars);
736 dsym.type = Type.terror;
737 tb = dsym.type;
738 }
739 if (tb.ty == Tfunction)
740 {
741 .error(dsym.loc, "%s `%s` cannot be declared to be a function", dsym.kind, dsym.toPrettyChars);
742 dsym.type = Type.terror;
743 tb = dsym.type;
744 }
745 if (auto ts = tb.isTypeStruct())
746 {
747 // Require declarations, except when it's just a reference (as done for pointers)
748 // or when the variable is defined externally
749 if (!ts.sym.members && !(dsym.storage_class & (STC.ref_ | STC.extern_)))
750 {
751 .error(dsym.loc, "%s `%s` - no definition of struct `%s`", dsym.kind, dsym.toPrettyChars, ts.toChars());
752
753 // Explain why the definition is required when it's part of another type
754 if (!dsym.type.isTypeStruct())
755 {
756 // Prefer Loc of the dependant type
757 const s = dsym.type.toDsymbol(sc);
758 const loc = (s ? s : dsym).loc;
759 loc.errorSupplemental("required by type `%s`", dsym.type.toChars());
760 }
761 errorSupplemental(dsym.loc, "see https://dlang.org/spec/struct.html#opaque_struct_unions");
762 errorSupplemental(dsym.loc, "perhaps declare a variable with pointer type `%s*` instead", dsym.type.toChars());
763
764 // Flag variable as error to avoid invalid error messages due to unknown size
765 dsym.type = Type.terror;
766 }
767 }
768 if ((dsym.storage_class & STC.auto_) && !inferred && !(dsym.storage_class & STC.autoref))
769 .error(dsym.loc, "%s `%s` - storage class `auto` has no effect if type is not inferred, did you mean `scope`?", dsym.kind, dsym.toPrettyChars);
770
771 if (auto tt = tb.isTypeTuple())
772 {
773 /* Instead, declare variables for each of the tuple elements
774 * and add those.
775 */
776 size_t nelems = Parameter.dim(tt.arguments);
777 Expression ie = (dsym._init && !dsym._init.isVoidInitializer()) ? dsym._init.initializerToExpression(null, sc.inCfile) : null;
778 if (ie)
779 ie = ie.expressionSemantic(sc);
780 if (nelems > 0 && ie)
781 {
782 auto iexps = new Expressions();
783 iexps.push(ie);
784 auto exps = new Expressions();
785 for (size_t pos = 0; pos < iexps.length; pos++)
786 {
787 Lexpand1:
788 Expression e = (*iexps)[pos];
789 Parameter arg = Parameter.getNth(tt.arguments, pos);
790 arg.type = arg.type.typeSemantic(dsym.loc, sc);
791 //printf("[%d] iexps.length = %d, ", pos, iexps.length);
792 //printf("e = (%s %s, %s), ", Token.tochars[e.op], e.toChars(), e.type.toChars());
793 //printf("arg = (%s, %s)\n", arg.toChars(), arg.type.toChars());
794
795 if (e != ie)
796 {
797 if (iexps.length > nelems)
798 goto Lnomatch;
799 if (e.type.implicitConvTo(arg.type))
800 continue;
801 }
802
803 if (auto te = e.isTupleExp())
804 {
805 if (iexps.length - 1 + te.exps.length > nelems)
806 goto Lnomatch;
807
808 iexps.remove(pos);
809 iexps.insert(pos, te.exps);
810 (*iexps)[pos] = Expression.combine(te.e0, (*iexps)[pos]);
811 goto Lexpand1;
812 }
813 else if (isAliasThisTuple(e))
814 {
815 auto v = copyToTemp(STC.none, "__tup", e);
816 v.dsymbolSemantic(sc);
817 auto ve = new VarExp(dsym.loc, v);
818 ve.type = e.type;
819
820 exps.setDim(1);
821 (*exps)[0] = ve;
822 expandAliasThisTuples(exps, 0);
823
824 for (size_t u = 0; u < exps.length; u++)
825 {
826 Lexpand2:
827 Expression ee = (*exps)[u];
828 arg = Parameter.getNth(tt.arguments, pos + u);
829 arg.type = arg.type.typeSemantic(dsym.loc, sc);
830 //printf("[%d+%d] exps.length = %d, ", pos, u, exps.length);
831 //printf("ee = (%s %s, %s), ", Token.tochars[ee.op], ee.toChars(), ee.type.toChars());
832 //printf("arg = (%s, %s)\n", arg.toChars(), arg.type.toChars());
833
834 size_t iexps_dim = iexps.length - 1 + exps.length;
835 if (iexps_dim > nelems)
836 goto Lnomatch;
837 if (ee.type.implicitConvTo(arg.type))
838 continue;
839
840 if (expandAliasThisTuples(exps, u) != -1)
841 goto Lexpand2;
842 }
843
844 if ((*exps)[0] != ve)
845 {
846 Expression e0 = (*exps)[0];
847 (*exps)[0] = new CommaExp(dsym.loc, new DeclarationExp(dsym.loc, v), e0);
848 (*exps)[0].type = e0.type;
849
850 iexps.remove(pos);
851 iexps.insert(pos, exps);
852 goto Lexpand1;
853 }
854 }
855 }
856 if (iexps.length < nelems)
857 goto Lnomatch;
858
859 ie = new TupleExp(dsym._init.loc, iexps);
860 }
861 Lnomatch:
862
863 if (ie && ie.op == EXP.tuple)
864 {
865 auto te = ie.isTupleExp();
866 size_t tedim = te.exps.length;
867 if (tedim != nelems)
868 {
869 error(dsym.loc, "sequence of %d elements cannot be assigned to sequence of %d elements", cast(int)tedim, cast(int)nelems);
870 for (size_t u = tedim; u < nelems; u++) // fill dummy expression
871 te.exps.push(ErrorExp.get());
872 }
873 }
874
875 auto exps = new Objects(nelems);
876 for (size_t i = 0; i < nelems; i++)
877 {
878 Parameter arg = Parameter.getNth(tt.arguments, i);
879
880 OutBuffer buf;
881 buf.printf("__%s_field_%llu", dsym.ident.toChars(), cast(ulong)i);
882 auto id = Identifier.idPool(buf[]);
883
884 Initializer ti;
885 if (ie)
886 {
887 Expression einit = ie;
888 if (auto te = ie.isTupleExp())
889 {
890 einit = (*te.exps)[i];
891 if (i == 0)
892 einit = Expression.combine(te.e0, einit);
893 }
894 ti = new ExpInitializer(einit.loc, einit);
895 }
896 else
897 ti = dsym._init ? dsym._init.syntaxCopy() : null;
898
899 STC storage_class = STC.temp | dsym.storage_class;
900 if ((dsym.storage_class & STC.parameter) && (arg.storageClass & STC.parameter))
901 storage_class |= arg.storageClass;
902 auto v = new VarDeclaration(dsym.loc, arg.type, id, ti, storage_class);
903 //printf("declaring field %s of type %s\n", v.toChars(), v.type.toChars());
904 v.overlapped = dsym.overlapped;
905
906 v.dsymbolSemantic(sc);
907
908 Expression e = new VarExp(dsym.loc, v);
909 (*exps)[i] = e;
910 }
911 auto v2 = new TupleDeclaration(dsym.loc, dsym.ident, exps);
912 v2.parent = dsym.parent;
913 v2.isexp = true;
914 dsym.aliasTuple = v2;
915 dsym.semanticRun = PASS.semanticdone;
916 return;
917 }
918
919 /* Storage class can modify the type
920 */
921 dsym.type = dsym.type.addStorageClass(dsym.storage_class);
922
923 /* Adjust storage class to reflect type
924 */
925 if (dsym.type.isConst())
926 {
927 dsym.storage_class |= STC.const_;
928 if (dsym.type.isShared())
929 dsym.storage_class |= STC.shared_;
930 }
931 else if (dsym.type.isImmutable())
932 dsym.storage_class |= STC.immutable_;
933 else if (dsym.type.isShared())
934 dsym.storage_class |= STC.shared_;
935 else if (dsym.type.isWild())
936 dsym.storage_class |= STC.wild;
937
938 if (STC stc = dsym.storage_class & (STC.synchronized_ | STC.override_ | STC.abstract_ | STC.final_))
939 {
940 if (stc == STC.final_)
941 .error(dsym.loc, "%s `%s` cannot be `final`, perhaps you meant `const`?", dsym.kind, dsym.toPrettyChars);
942 else
943 {
944 OutBuffer buf;
945 stcToBuffer(buf, stc);
946 .error(dsym.loc, "%s `%s` cannot be `%s`", dsym.kind, dsym.toPrettyChars, buf.peekChars());
947 }
948 dsym.storage_class &= ~stc; // strip off
949 }
950
951 // At this point we can add `scope` to the STC instead of `in`,
952 // because we are never going to use this variable's STC for user messages
953 if (dsym.storage_class & STC.constscoperef)
954 dsym.storage_class |= STC.scope_;
955
956 if (dsym.storage_class & STC.scope_)
957 {
958 STC stc = dsym.storage_class & (STC.static_ | STC.extern_ | STC.manifest | STC.gshared);
959 if (stc)
960 {
961 OutBuffer buf;
962 stcToBuffer(buf, stc);
963 .error(dsym.loc, "%s `%s` cannot be `scope` and `%s`", dsym.kind, dsym.toPrettyChars, buf.peekChars());
964 }
965 else if (dsym.isMember())
966 {
967 error(dsym.loc, "field `%s` cannot be `scope`", dsym.toChars());
968 }
969 else if (!dsym.type.hasPointers())
970 {
971 dsym.storage_class &= ~STC.scope_; // silently ignore; may occur in generic code
972 // https://issues.dlang.org/show_bug.cgi?id=23168
973 if (dsym.storage_class & STC.returnScope)
974 {
975 dsym.storage_class &= ~(STC.return_ | STC.returnScope);
976 }
977 }
978 }
979
980 if (dsym.storage_class & (STC.static_ | STC.extern_ | STC.manifest | STC.templateparameter | STC.gshared | STC.ctfe))
981 {
982 }
983 else
984 {
985 AggregateDeclaration aad = parent.isAggregateDeclaration();
986 if (aad)
987 {
988 if (global.params.v.field && dsym.storage_class & (STC.const_ | STC.immutable_) && dsym._init && !dsym._init.isVoidInitializer())
989 {
990 const(char)* s = (dsym.storage_class & STC.immutable_) ? "immutable" : "const";
991 message(dsym.loc, "`%s.%s` is `%s` field", ad.toPrettyChars(), dsym.toChars(), s);
992 }
993 dsym.storage_class |= STC.field;
994 if (auto ts = tbn.isTypeStruct())
995 if (ts.sym.noDefaultCtor)
996 {
997 if (!dsym.isThisDeclaration() && !dsym._init)
998 aad.noDefaultCtor = true;
999 }
1000 }
1001
1002 InterfaceDeclaration id = parent.isInterfaceDeclaration();
1003 if (id)
1004 {
1005 error(dsym.loc, "field `%s` not allowed in interface", dsym.toChars());
1006 }
1007 else if (aad && aad.sizeok == Sizeok.done)
1008 {
1009 error(dsym.loc, "cannot declare field `%s` because it will change the determined size of `%s`", dsym.toChars(), aad.toChars());
1010 }
1011
1012 /* Templates cannot add fields to aggregates
1013 */
1014 TemplateInstance ti = parent.isTemplateInstance();
1015 if (ti)
1016 {
1017 // Take care of nested templates
1018 while (1)
1019 {
1020 TemplateInstance ti2 = ti.tempdecl.parent.isTemplateInstance();
1021 if (!ti2)
1022 break;
1023 ti = ti2;
1024 }
1025 // If it's a member template
1026 AggregateDeclaration ad2 = ti.tempdecl.isMember();
1027 if (ad2 && dsym.storage_class != STC.none)
1028 {
1029 .error(dsym.loc, "%s `%s` - cannot use template to add field to aggregate `%s`", dsym.kind, dsym.toPrettyChars, ad2.toChars());
1030 }
1031 }
1032 }
1033
1034 /* If the alignment of a stack local is greater than the stack alignment,
1035 * note it in the enclosing function's alignSectionVars
1036 */
1037 version (MARS)
1038 {
1039 if (!dsym.alignment.isDefault() && sc.func &&
1040 dsym.alignment.get() > target.stackAlign() &&
1041 sc.func && !dsym.isDataseg() && !dsym.isParameter() && !dsym.isField())
1042 {
1043 auto fd = sc.func;
1044 if (!fd.alignSectionVars)
1045 fd.alignSectionVars = new VarDeclarations();
1046 fd.alignSectionVars.push(dsym);
1047 }
1048 }
1049
1050 if ((dsym.storage_class & (STC.ref_ | STC.field)) == (STC.ref_ | STC.field) && dsym.ident != Id.This)
1051 {
1052 .error(dsym.loc, "%s `%s` - field declarations cannot be `ref`", dsym.kind, dsym.toPrettyChars);
1053 }
1054
1055 if (dsym.type.hasWild())
1056 {
1057 if (dsym.storage_class & (STC.static_ | STC.extern_ | STC.gshared | STC.manifest | STC.field) || dsym.isDataseg())
1058 {
1059 .error(dsym.loc, "%s `%s` - only parameters or stack-based variables can be `inout`", dsym.kind, dsym.toPrettyChars);
1060 }
1061 FuncDeclaration func = sc.func;
1062 if (func)
1063 {
1064 if (func.fes)
1065 func = func.fes.func;
1066 bool isWild = false;
1067 for (FuncDeclaration fd = func; fd; fd = fd.toParentDecl().isFuncDeclaration())
1068 {
1069 if (fd.type.isTypeFunction().iswild)
1070 {
1071 isWild = true;
1072 break;
1073 }
1074 }
1075 if (!isWild)
1076 {
1077 .error(dsym.loc, "%s `%s` - `inout` variables can only be declared inside `inout` functions", dsym.kind, dsym.toPrettyChars);
1078 }
1079 }
1080 }
1081
1082 if (!(dsym.storage_class & (STC.ctfe | STC.extern_ | STC.ref_ | STC.result)) &&
1083 tbn.ty == Tstruct && tbn.isTypeStruct().sym.noDefaultCtor)
1084 {
1085 if (!dsym._init)
1086 {
1087 if (dsym.isField())
1088 {
1089 /* For fields, we'll check the constructor later to make sure it is initialized
1090 */
1091 dsym.storage_class |= STC.nodefaultctor;
1092 }
1093 else if (dsym.storage_class & STC.parameter)
1094 {
1095 }
1096 else
1097 .error(dsym.loc, "%s `%s` - default construction is disabled for type `%s`", dsym.kind, dsym.toPrettyChars, dsym.type.toChars());
1098 }
1099 }
1100
1101 bool dsymIsRef = (dsym.storage_class & (STC.ref_ | STC.field | STC.parameter | STC.temp | STC.foreach_)) == STC.ref_;
1102 if (dsymIsRef)
1103 {
1104 if (!dsym._init && dsym.ident != Id.This)
1105 {
1106 if (dsym.storage_class & STC.autoref)
1107 {
1108 dsymIsRef = false;
1109 dsym.storage_class &= ~STC.ref_;
1110 }
1111 else
1112 .error(dsym.loc, "%s `%s` - initializer is required for `ref` variable", dsym.kind, dsym.toPrettyChars);
1113 }
1114 else if (dsym._init.isVoidInitializer())
1115 {
1116 .error(dsym.loc, "%s `%s` - void initializer not allowed for `ref` variable", dsym.kind, dsym.toPrettyChars);
1117 }
1118 }
1119
1120 FuncDeclaration fd = parent.isFuncDeclaration();
1121 if (dsym.type.isScopeClass() && !(dsym.storage_class & STC.nodtor))
1122 {
1123 if (dsym.storage_class & (STC.field | STC.out_ | STC.ref_ | STC.static_ | STC.manifest | STC.gshared) || !fd)
1124 {
1125 .error(dsym.loc, "%s `%s` globals, statics, fields, manifest constants, ref and out parameters cannot be `scope`", dsym.kind, dsym.toPrettyChars);
1126 }
1127
1128 // @@@DEPRECATED_2.097@@@ https://dlang.org/deprecate.html#scope%20as%20a%20type%20constraint
1129 // Deprecated in 2.087
1130 // Remove this when the feature is removed from the language
1131 if (!(dsym.storage_class & STC.scope_))
1132 {
1133 if (!(dsym.storage_class & STC.parameter) && dsym.ident != Id.withSym)
1134 .error(dsym.loc, "%s `%s` reference to `scope class` must be `scope`", dsym.kind, dsym.toPrettyChars);
1135 }
1136 }
1137
1138 // Calculate type size + safety checks
1139 if (sc && sc.func)
1140 {
1141 if (dsym._init && dsym._init.isVoidInitializer() && !(dsym.storage_class & STC.temp))
1142 {
1143 // Don't do these checks for STC.temp vars because the generated `opAssign`
1144 // for a struct with postblit and destructor void initializes a temporary
1145 // __swap variable, which can be trusted
1146
1147 if (dsym.type.hasPointers()) // also computes type size
1148 sc.setUnsafe(false, dsym.loc,
1149 "`void` initializing a pointer");
1150 else if (dsym.type.hasInvariant())
1151 sc.setUnsafe(false, dsym.loc,
1152 "`void` initializing a struct with an invariant");
1153 else if (dsym.type.toBasetype().ty == Tbool)
1154 sc.setUnsafePreview(global.params.systemVariables, false, dsym.loc,
1155 "void intializing a bool (which must always be 0 or 1)");
1156 else if (dsym.type.hasUnsafeBitpatterns())
1157 sc.setUnsafePreview(global.params.systemVariables, false, dsym.loc,
1158 "`void` initializing a type with unsafe bit patterns");
1159 }
1160 else if (!dsym._init &&
1161 !(dsym.storage_class & (STC.static_ | STC.extern_ | STC.gshared | STC.manifest | STC.field | STC.parameter)) &&
1162 dsym.type.hasVoidInitPointers())
1163 {
1164 sc.setUnsafe(false, dsym.loc, "`void` initializers for pointers");
1165 }
1166 }
1167
1168 if ((!dsym._init || dsym._init.isVoidInitializer) && !fd)
1169 {
1170 // If not mutable, initializable by constructor only
1171 dsym.setInCtorOnly = true;
1172 }
1173
1174 if (dsym._init)
1175 { } // remember we had an explicit initializer
1176 else if (dsym.storage_class & STC.manifest)
1177 .error(dsym.loc, "%s `%s` - manifest constants must have initializers", dsym.kind, dsym.toPrettyChars);
1178
1179 // Don't allow non-extern, non-__gshared variables to be interfaced with C++
1180 if (dsym._linkage == LINK.cpp && !(dsym.storage_class & (STC.ctfe | STC.extern_ | STC.gshared)) && dsym.isDataseg())
1181 {
1182 const char* p = (dsym.storage_class & STC.shared_) ? "shared" : "static";
1183 .error(dsym.loc, "%s `%s` cannot have `extern(C++)` linkage because it is `%s`", dsym.kind, dsym.toPrettyChars, p);
1184 errorSupplemental(dsym.loc, "perhaps declare it as `__gshared` instead");
1185 dsym.errors = true;
1186 }
1187
1188 bool isBlit = false;
1189 uinteger_t sz;
1190 if (sc.inCfile && !dsym._init)
1191 {
1192 addDefaultCInitializer(dsym);
1193 }
1194 if (!dsym._init &&
1195 !(dsym.storage_class & (STC.static_ | STC.gshared | STC.extern_)) &&
1196 fd &&
1197 (!(dsym.storage_class & (STC.field | STC.in_ | STC.foreach_ | STC.parameter | STC.result)) ||
1198 (dsym.storage_class & STC.out_)) &&
1199 (sz = dsym.type.size()) != 0)
1200 {
1201 // Provide a default initializer
1202
1203 //printf("Providing default initializer for '%s'\n", dsym.toChars());
1204 if (sz == SIZE_INVALID && dsym.type.ty != Terror)
1205 .error(dsym.loc, "%s `%s` - size of type `%s` is invalid", dsym.kind, dsym.toPrettyChars, dsym.type.toChars());
1206
1207 Type tv = dsym.type;
1208 while (tv.ty == Tsarray) // Don't skip Tenum
1209 tv = tv.nextOf();
1210 if (tv.needsNested())
1211 {
1212 /* Nested struct requires valid enclosing frame pointer.
1213 * In StructLiteralExp::toElem(), it's calculated.
1214 */
1215 assert(tbn.ty == Tstruct);
1216 checkFrameAccess(dsym.loc, sc, tbn.isTypeStruct().sym);
1217
1218 Expression e = tv.defaultInitLiteral(dsym.loc);
1219 e = new BlitExp(dsym.loc, new VarExp(dsym.loc, dsym), e);
1220 e = e.expressionSemantic(sc);
1221 dsym._init = new ExpInitializer(dsym.loc, e);
1222 goto Ldtor;
1223 }
1224 if (tv.ty == Tstruct && tv.isTypeStruct().sym.zeroInit)
1225 {
1226 /* If a struct is all zeros, as a special case
1227 * set its initializer to the integer 0.
1228 * In AssignExp::toElem(), we check for this and issue
1229 * a memset() to initialize the struct.
1230 * Must do same check in interpreter.
1231 */
1232 Expression e = IntegerExp.literal!0;
1233 e = new BlitExp(dsym.loc, new VarExp(dsym.loc, dsym), e);
1234 e.type = dsym.type; // don't type check this, it would fail
1235 dsym._init = new ExpInitializer(dsym.loc, e);
1236 goto Ldtor;
1237 }
1238 if (dsym.type.baseElemOf().ty == Tvoid)
1239 {
1240 .error(dsym.loc, "%s `%s` of type `%s` does not have a default initializer", dsym.kind, dsym.toPrettyChars, dsym.type.toChars());
1241 }
1242 else if (auto e = dsym.type.defaultInit(dsym.loc))
1243 {
1244 dsym._init = new ExpInitializer(dsym.loc, e);
1245 }
1246
1247 // Default initializer is always a blit
1248 isBlit = true;
1249 }
1250 if (dsym._init)
1251 {
1252 sc = sc.push();
1253 sc.stc &= ~(STC.TYPECTOR | STC.pure_ | STC.nothrow_ | STC.nogc | STC.ref_ | STC.disable);
1254
1255 if (sc.inCfile &&
1256 dsym.type.isTypeSArray() &&
1257 dsym.type.isTypeSArray().isIncomplete() &&
1258 dsym._init.isVoidInitializer() &&
1259 !(dsym.storage_class & STC.field))
1260 {
1261 .error(dsym.loc, "%s `%s` - incomplete array type must have initializer", dsym.kind, dsym.toPrettyChars);
1262 }
1263
1264 ExpInitializer ei = dsym._init.isExpInitializer();
1265
1266 if (ei) // https://issues.dlang.org/show_bug.cgi?id=13424
1267 // Preset the required type to fail in FuncLiteralDeclaration::semantic3
1268 ei.exp = inferType(ei.exp, dsym.type);
1269
1270 // If inside function, there is no semantic3() call
1271 if (sc.func || sc.intypeof == 1)
1272 {
1273 // If local variable, use AssignExp to handle all the various
1274 // possibilities.
1275 if (fd && !(dsym.storage_class & (STC.manifest | STC.static_ | STC.gshared | STC.extern_)) && !dsym._init.isVoidInitializer())
1276 {
1277 //printf("fd = '%s', var = '%s'\n", fd.toChars(), dsym.toChars());
1278 if (!ei)
1279 {
1280 ArrayInitializer ai = dsym._init.isArrayInitializer();
1281 Expression e;
1282 if (ai && tb.ty == Taarray)
1283 e = ai.toAssocArrayLiteral();
1284 else
1285 e = dsym._init.initializerToExpression(null, sc.inCfile);
1286 if (!e)
1287 {
1288 // Run semantic, but don't need to interpret
1289 dsym._init = dsym._init.initializerSemantic(sc, dsym.type, INITnointerpret);
1290 e = dsym._init.initializerToExpression(null, sc.inCfile);
1291 if (!e)
1292 {
1293 .error(dsym.loc, "%s `%s` is not a static and cannot have static initializer", dsym.kind, dsym.toPrettyChars);
1294 e = ErrorExp.get();
1295 }
1296 }
1297 ei = new ExpInitializer(dsym._init.loc, e);
1298 dsym._init = ei;
1299 }
1300 else if (sc.inCfile && dsym.type.isTypeSArray() &&
1301 dsym.type.isTypeSArray().isIncomplete())
1302 {
1303 // C11 6.7.9-22 determine the size of the incomplete array,
1304 // or issue an error that the initializer is invalid.
1305 dsym._init = dsym._init.initializerSemantic(sc, dsym.type, INITinterpret);
1306 }
1307
1308 if (ei && dsym.isScope())
1309 {
1310 Expression ex = ei.exp.lastComma();
1311 if (ex.op == EXP.blit || ex.op == EXP.construct)
1312 ex = (cast(AssignExp)ex).e2;
1313 if (auto ne = ex.isNewExp())
1314 {
1315 if (ne.placement)
1316 {
1317 }
1318 /* See if initializer is a NewExp that can be allocated on the stack.
1319 */
1320 else if (dsym.type.toBasetype().ty == Tclass)
1321 {
1322 /* Unsafe to allocate on stack if constructor is not `scope` because the `this` can leak.
1323 * https://issues.dlang.org/show_bug.cgi?id=23145
1324 */
1325 if (ne.member && !(ne.member.storage_class & STC.scope_))
1326 {
1327 import dmd.escape : setUnsafeDIP1000;
1328 const inSafeFunc = sc.func && sc.func.isSafeBypassingInference(); // isSafeBypassingInference may call setUnsafe().
1329 if (setUnsafeDIP1000(*sc, false, dsym.loc, "`scope` allocation of `%s` with a non-`scope` constructor", dsym))
1330 errorSupplemental(ne.member.loc, "is the location of the constructor");
1331 }
1332 ne.onstack = 1;
1333 dsym.onstack = true;
1334 }
1335 }
1336 else if (auto fe = ex.isFuncExp())
1337 {
1338 // or a delegate that doesn't escape a reference to the function
1339 FuncDeclaration f = fe.fd;
1340 if (f.tookAddressOf)
1341 f.tookAddressOf--;
1342 }
1343 else if (auto ale = ex.isArrayLiteralExp())
1344 {
1345 // or an array literal assigned to a `scope` variable
1346 if (sc.useDIP1000 == FeatureState.enabled
1347 && !dsym.type.nextOf().needsDestruction())
1348 ale.onstack = true;
1349 }
1350 }
1351
1352 Expression exp = ei.exp;
1353 Expression e1 = new VarExp(dsym.loc, dsym);
1354
1355 void constructInit(bool isBlit)
1356 {
1357 if (isBlit)
1358 exp = new BlitExp(dsym.loc, e1, exp);
1359 else
1360 exp = new ConstructExp(dsym.loc, e1, exp);
1361 dsym.canassign++;
1362 exp = exp.expressionSemantic(sc);
1363 dsym.canassign--;
1364 }
1365
1366 if (dsymIsRef) // follow logic similar to typesem.argumentMatchParameter() and statementsem.visitForeach()
1367 {
1368 dsym.storage_class |= STC.nodtor;
1369 exp = exp.expressionSemantic(sc);
1370 Type tp = dsym.type;
1371 Type ta = exp.type;
1372 if (!exp.isLvalue())
1373 {
1374 if (dsym.storage_class & STC.autoref)
1375 {
1376 dsym.storage_class &= ~STC.ref_;
1377 constructInit(isBlit);
1378 }
1379 else
1380 {
1381 .error(dsym.loc, "rvalue `%s` cannot be assigned to `ref %s`", exp.toChars(), dsym.toChars());
1382 exp = ErrorExp.get();
1383 }
1384 }
1385 else if (!ta.constConv(tp))
1386 {
1387 if (dsym.storage_class & STC.autoref)
1388 {
1389 dsym.storage_class &= ~STC.ref_;
1390 constructInit(false);
1391 }
1392 else
1393 {
1394 .error(dsym.loc, "type `%s` cannot be assigned to `ref %s %s`", ta.toChars(), tp.toChars(), dsym.toChars());
1395 exp = ErrorExp.get();
1396 }
1397 }
1398 else
1399 {
1400 constructInit(false);
1401 }
1402 }
1403 else
1404 {
1405 constructInit(isBlit);
1406 }
1407
1408 if (exp.op == EXP.error)
1409 {
1410 dsym._init = new ErrorInitializer();
1411 ei = null;
1412 }
1413 else
1414 ei.exp = exp.optimize(WANTvalue);
1415 }
1416 else
1417 {
1418 // https://issues.dlang.org/show_bug.cgi?id=14166
1419 // Don't run CTFE for the temporary variables inside typeof
1420 dsym._init = dsym._init.initializerSemantic(sc, dsym.type, sc.intypeof == 1 ? INITnointerpret : INITinterpret);
1421 import dmd.semantic2 : lowerStaticAAs;
1422 lowerStaticAAs(dsym, sc);
1423 auto init_err = dsym._init.isExpInitializer();
1424 if (init_err && init_err.exp.op == EXP.showCtfeContext)
1425 {
1426 init_err.exp = ErrorExp.get();
1427 errorSupplemental(dsym.loc, "compile time context created here");
1428 }
1429 }
1430 }
1431 else if (parent.isAggregateDeclaration())
1432 {
1433 dsym._scope = scx ? scx : sc.copy();
1434 dsym._scope.setNoFree();
1435 }
1436 else if (dsym.storage_class & (STC.const_ | STC.immutable_ | STC.manifest) ||
1437 dsym.type.isConst() || dsym.type.isImmutable() ||
1438 sc.inCfile)
1439 {
1440 /* Because we may need the results of a const declaration in a
1441 * subsequent type, such as an array dimension, before semantic2()
1442 * gets ordinarily run, try to run semantic2() now.
1443 * If a C array is of unknown size, the initializer can provide the size. Do this
1444 * eagerly because C does it eagerly.
1445 * Ignore failure.
1446 */
1447 if (!inferred)
1448 {
1449 const errors = global.errors;
1450 dsym.inuse++;
1451 // Bug 20549. Don't try this on modules or packages, syntaxCopy
1452 // could crash (inf. recursion) on a mod/pkg referencing itself
1453 if (ei && (ei.exp.op != EXP.scope_ ? true : !ei.exp.isScopeExp().sds.isPackage()))
1454 {
1455 if (ei.exp.type)
1456 {
1457 // If exp is already resolved we are done, our original init exp
1458 // could have a type painting that we need to respect
1459 // e.g. ['a'] typed as string, or [['z'], ""] as string[]
1460 // See https://issues.dlang.org/show_bug.cgi?id=15711
1461 }
1462 else
1463 {
1464 Expression exp = ei.exp.syntaxCopy();
1465
1466 bool needctfe = dsym.isDataseg() || (dsym.storage_class & STC.manifest);
1467 if (needctfe)
1468 sc = sc.startCTFE();
1469 sc = sc.push();
1470 sc.varDecl = dsym; // https://issues.dlang.org/show_bug.cgi?id=24051
1471 exp = exp.expressionSemantic(sc);
1472 exp = resolveProperties(sc, exp);
1473 sc = sc.pop();
1474 if (needctfe)
1475 sc = sc.endCTFE();
1476 ei.exp = exp;
1477 }
1478
1479 Type tb2 = dsym.type.toBasetype();
1480 Type ti = ei.exp.type.toBasetype();
1481
1482 /* The problem is the following code:
1483 * struct CopyTest {
1484 * double x;
1485 * this(double a) { x = a * 10.0;}
1486 * this(this) { x += 2.0; }
1487 * }
1488 * const CopyTest z = CopyTest(5.3); // ok
1489 * const CopyTest w = z; // not ok, postblit not run
1490 * static assert(w.x == 55.0);
1491 * because the postblit doesn't get run on the initialization of w.
1492 */
1493 if (auto ts = ti.isTypeStruct())
1494 {
1495 StructDeclaration sd = ts.sym;
1496 /* Look to see if initializer involves a copy constructor
1497 * (which implies a postblit)
1498 */
1499 // there is a copy constructor
1500 // and exp is the same struct
1501 if (sd.postblit && tb2.toDsymbol(null) == sd)
1502 {
1503 // The only allowable initializer is a (non-copy) constructor
1504 if (ei.exp.isLvalue())
1505 .error(dsym.loc, "%s `%s` of type struct `%s` uses `this(this)`, which is not allowed in static initialization", dsym.kind, dsym.toPrettyChars, tb2.toChars());
1506 }
1507 }
1508 }
1509
1510 dsym._init = dsym._init.initializerSemantic(sc, dsym.type, INITinterpret);
1511 dsym.inuse--;
1512 if (global.errors > errors)
1513 {
1514 dsym._init = new ErrorInitializer();
1515 dsym.type = Type.terror;
1516 }
1517 }
1518 else
1519 {
1520 dsym._scope = scx ? scx : sc.copy();
1521 dsym._scope.setNoFree();
1522 }
1523 }
1524 sc = sc.pop();
1525 }
1526
1527 Ldtor:
1528 /* Build code to execute destruction, if necessary
1529 */
1530 dsym.edtor = dsym.callScopeDtor(sc);
1531 if (dsym.edtor)
1532 {
1533 if (sc.func && dsym.storage_class & (STC.static_ | STC.gshared))
1534 dsym.edtor = dsym.edtor.expressionSemantic(sc._module._scope);
1535 else
1536 dsym.edtor = dsym.edtor.expressionSemantic(sc);
1537
1538 version (none)
1539 {
1540 // currently disabled because of std.stdio.stdin, stdout and stderr
1541 if (dsym.isDataseg() && !(dsym.storage_class & STC.extern_))
1542 .error(dsym.loc, "%s `%s` static storage variables cannot have destructors", dsym.kind, dsym.toPrettyChars);
1543 }
1544 }
1545
1546 dsym.semanticRun = PASS.semanticdone;
1547
1548 if (dsym.type.toBasetype().ty == Terror)
1549 dsym.errors = true;
1550
1551 if(sc.scopesym && !sc.scopesym.isAggregateDeclaration())
1552 {
1553 for (ScopeDsymbol sym = sc.scopesym; sym && dsym.endlinnum == 0;
1554 sym = sym.parent ? sym.parent.isScopeDsymbol() : null)
1555 dsym.endlinnum = sym.endlinnum;
1556 }
1557 }
1558
1559 override void visit(TypeInfoDeclaration dsym)
1560 {
1561 assert(dsym._linkage == LINK.c);
1562 }
1563
1564 override void visit(CAsmDeclaration dsym)
1565 {
1566 if (dsym.semanticRun >= PASS.semanticdone)
1567 return;
1568 import dmd.iasm : asmSemantic;
1569 asmSemantic(dsym, sc);
1570 dsym.semanticRun = PASS.semanticdone;
1571 }
1572
1573 override void visit(BitFieldDeclaration dsym)
1574 {
1575 //printf("BitField::semantic('%s')\n", dsym.toChars());
1576 if (dsym.semanticRun >= PASS.semanticdone)
1577 return;
1578
1579 visit(cast(VarDeclaration)dsym);
1580 if (dsym.errors)
1581 return;
1582
1583 if (!(sc.previews.bitfields || sc.inCfile))
1584 {
1585 version (IN_GCC)
1586 .error(dsym.loc, "%s `%s` use `-fpreview=bitfields` for bitfield support", dsym.kind, dsym.toPrettyChars);
1587 else
1588 .error(dsym.loc, "%s `%s` use -preview=bitfields for bitfield support", dsym.kind, dsym.toPrettyChars);
1589 }
1590
1591 if (!dsym.parent.isStructDeclaration() && !dsym.parent.isClassDeclaration())
1592 {
1593 .error(dsym.loc, "%s `%s` - bit-field must be member of struct, union, or class", dsym.kind, dsym.toPrettyChars);
1594 }
1595
1596 sc = sc.startCTFE();
1597 auto width = dsym.width.expressionSemantic(sc);
1598 sc = sc.endCTFE();
1599 width = width.ctfeInterpret();
1600 if (!dsym.type.isIntegral())
1601 {
1602 // C11 6.7.2.1-5
1603 error(width.loc, "bit-field type `%s` is not an integer type", dsym.type.toChars());
1604 dsym.errors = true;
1605 }
1606 if (!width.isIntegerExp())
1607 {
1608 error(width.loc, "bit-field width `%s` is not an integer constant", dsym.width.toChars());
1609 dsym.errors = true;
1610 }
1611 const uwidth = width.toInteger(); // uwidth is unsigned
1612 if (uwidth == 0 && !dsym.isAnonymous())
1613 {
1614 error(width.loc, "bit-field `%s` has zero width", dsym.toChars());
1615 dsym.errors = true;
1616 }
1617 const sz = dsym.type.size();
1618 if (sz == SIZE_INVALID)
1619 dsym.errors = true;
1620 const max_width = sz * 8;
1621 if (uwidth > max_width)
1622 {
1623 error(width.loc, "width `%lld` of bit-field `%s` does not fit in type `%s`", cast(long)uwidth, dsym.toChars(), dsym.type.toChars());
1624 dsym.errors = true;
1625 }
1626 dsym.fieldWidth = cast(uint)uwidth;
1627 }
1628
1629 override void visit(Import imp)
1630 {
1631 timeTraceBeginEvent(TimeTraceEventType.sema1Import);
1632 scope (exit) timeTraceEndEvent(TimeTraceEventType.sema1Import, imp);
1633 static if (LOG)
1634 {
1635 printf("Import::semantic('%s') %s\n", imp.toPrettyChars(), imp.id.toChars());
1636 scope(exit)
1637 printf("-Import::semantic('%s'), pkg = %p\n", imp.toChars(), imp.pkg);
1638 }
1639 if (imp.semanticRun > PASS.initial)
1640 return;
1641
1642 if (imp._scope)
1643 {
1644 sc = imp._scope;
1645 imp._scope = null;
1646 }
1647 if (!sc)
1648 return;
1649
1650 imp.parent = sc.parent;
1651
1652 imp.semanticRun = PASS.semantic;
1653
1654 // Load if not already done so
1655 if (!imp.mod)
1656 {
1657 // https://issues.dlang.org/show_bug.cgi?id=22857
1658 // if parser errors occur when loading a module
1659 // we should just stop compilation
1660 if (imp.load(sc))
1661 {
1662 for (size_t i = 0; i < imp.aliasdecls.length; i++)
1663 imp.aliasdecls[i].type = Type.terror;
1664 return;
1665 }
1666
1667 if (imp.mod)
1668 {
1669 imp.mod.importAll(null);
1670 imp.mod.checkImportDeprecation(imp.loc, sc);
1671 }
1672 }
1673 if (!imp.mod)
1674 {
1675 imp.semanticRun = PASS.semanticdone;
1676 addImportDep(global.params.moduleDeps, imp, sc._module);
1677 }
1678
1679 // Modules need a list of each imported module
1680
1681 // if inside a template instantiation, the instantianting
1682 // module gets the import.
1683 // https://issues.dlang.org/show_bug.cgi?id=17181
1684 Module importer = sc._module;
1685 if (sc.minst && sc.tinst)
1686 {
1687 importer = sc.minst;
1688 if (!sc.tinst.importedModules.contains(imp.mod))
1689 sc.tinst.importedModules.push(imp.mod);
1690 }
1691 //printf("%s imports %s\n", importer.toChars(), imp.mod.toChars());
1692 if (!importer.aimports.contains(imp.mod))
1693 importer.aimports.push(imp.mod);
1694
1695 if (sc.explicitVisibility)
1696 imp.visibility = sc.visibility;
1697
1698 if (!imp.aliasId && !imp.names.length) // neither a selective nor a renamed import
1699 {
1700 ScopeDsymbol scopesym = sc.getScopesym();
1701
1702 if (!imp.isstatic)
1703 {
1704 scopesym.importScope(imp.mod, imp.visibility);
1705 }
1706
1707
1708 imp.addPackageAccess(scopesym);
1709 }
1710
1711 // if a module has errors it means that parsing has failed.
1712 if (!imp.mod.errors)
1713 imp.mod.dsymbolSemantic(null);
1714
1715 if (imp.mod.needmoduleinfo)
1716 {
1717 //printf("module4 %s because of %s\n", importer.toChars(), imp.mod.toChars());
1718 importer.needmoduleinfo = 1;
1719 }
1720
1721 sc = sc.push(imp.mod);
1722 sc.visibility = imp.visibility;
1723 for (size_t i = 0; i < imp.aliasdecls.length; i++)
1724 {
1725 AliasDeclaration ad = imp.aliasdecls[i];
1726 //printf("\tImport %s alias %s = %s, scope = %p\n", toPrettyChars(), aliases[i].toChars(), names[i].toChars(), ad._scope);
1727 Dsymbol sym = imp.mod.search(imp.loc, imp.names[i], SearchOpt.ignorePrivateImports);
1728 if (sym)
1729 {
1730 import dmd.access : symbolIsVisible;
1731 if (!symbolIsVisible(sc, sym) && !sym.errors)
1732 {
1733 .error(imp.loc, "%s `%s` member `%s` is not visible from module `%s`", imp.mod.kind, imp.mod.toPrettyChars,
1734 imp.names[i].toChars(), sc._module.toChars());
1735 sym.errors = true;
1736 }
1737 ad.dsymbolSemantic(sc);
1738 // If the import declaration is in non-root module,
1739 // analysis of the aliased symbol is deferred.
1740 // Therefore, don't see the ad.aliassym or ad.type here.
1741 }
1742 else
1743 {
1744 Dsymbol s = imp.mod.search_correct(imp.names[i]);
1745 // https://issues.dlang.org/show_bug.cgi?id=23908
1746 // Don't suggest symbols from the importer's module
1747 if (s && s.parent != importer)
1748 .error(imp.loc, "%s `%s` import `%s` not found, did you mean %s `%s`?", imp.mod.kind, imp.mod.toPrettyChars, imp.names[i].toChars(), s.kind(), s.toPrettyChars());
1749 else
1750 .error(imp.loc, "%s `%s` import `%s` not found", imp.mod.kind, imp.mod.toPrettyChars, imp.names[i].toChars());
1751 ad.type = Type.terror;
1752 }
1753 }
1754 sc = sc.pop();
1755
1756 imp.semanticRun = PASS.semanticdone;
1757 addImportDep(global.params.moduleDeps, imp, sc._module);
1758 }
1759
1760 void attribSemantic(AttribDeclaration ad)
1761 {
1762 if (ad.semanticRun != PASS.initial)
1763 return;
1764 ad.semanticRun = PASS.semantic;
1765 Dsymbols* d = ad.include(sc);
1766 //printf("\tAttribDeclaration::semantic '%s', d = %p\n",toChars(), d);
1767 if (!d)
1768 {
1769 ad.semanticRun = PASS.semanticdone;
1770 return;
1771 }
1772
1773 Scope* sc2 = ad.newScope(sc);
1774 bool errors;
1775 for (size_t i = 0; i < d.length; i++)
1776 {
1777 Dsymbol s = (*d)[i];
1778 s.dsymbolSemantic(sc2);
1779 errors |= s.errors;
1780 }
1781 if (errors)
1782 ad.errors = true;
1783 if (sc2 != sc)
1784 sc2.pop();
1785
1786 ad.semanticRun = PASS.semanticdone;
1787 }
1788
1789 override void visit(AttribDeclaration atd)
1790 {
1791 attribSemantic(atd);
1792 }
1793
1794 override void visit(AnonDeclaration scd)
1795 {
1796 //printf("\tAnonDeclaration::semantic isunion:%d ptr:%p\n", scd.isunion, scd);
1797 assert(sc.parent);
1798 auto p = sc.parent.pastMixin();
1799 auto ad = p.isAggregateDeclaration();
1800 if (!ad)
1801 {
1802 error(scd.loc, "%s can only be a part of an aggregate, not %s `%s`", scd.kind(), p.kind(), p.toChars());
1803 scd.errors = true;
1804 return;
1805 }
1806
1807 if (!scd.decl)
1808 return;
1809
1810 sc = sc.push();
1811 sc.stc &= ~(STC.auto_ | STC.scope_ | STC.static_ | STC.gshared);
1812 sc.inunion = scd.isunion ? scd : null;
1813 sc.resetAllFlags();
1814 for (size_t i = 0; i < scd.decl.length; i++)
1815 {
1816 Dsymbol s = (*scd.decl)[i];
1817 if (auto var = s.isVarDeclaration)
1818 {
1819 if (scd.isunion)
1820 var.overlapped = true;
1821 }
1822 s.dsymbolSemantic(sc);
1823 }
1824 sc = sc.pop();
1825 }
1826
1827 override void visit(PragmaDeclaration pd)
1828 {
1829 import dmd.pragmasem : pragmaDeclSemantic;
1830 pragmaDeclSemantic(pd, sc);
1831 }
1832
1833 override void visit(StaticIfDeclaration sid)
1834 {
1835 attribSemantic(sid);
1836 }
1837
1838 override void visit(StaticForeachDeclaration sfd)
1839 {
1840 attribSemantic(sfd);
1841 }
1842
1843 private Dsymbols* compileIt(MixinDeclaration cd)
1844 {
1845 //printf("MixinDeclaration::compileIt(loc = %d) %s\n", cd.loc.linnum, cd.exp.toChars());
1846 OutBuffer buf;
1847 if (expressionsToString(buf, sc, cd.exps, cd.loc, null, true))
1848 return null;
1849
1850 const errors = global.errors;
1851 const len = buf.length;
1852 buf.writeByte(0);
1853 const str = buf.extractSlice()[0 .. len];
1854 const bool doUnittests = global.params.parsingUnittestsRequired();
1855 scope p = new Parser!ASTCodegen(sc._module, str, false, global.errorSink, &global.compileEnv, doUnittests);
1856 adjustLocForMixin(str, cd.loc, *p.baseLoc, global.params.mixinOut);
1857 p.linnum = p.baseLoc.startLine;
1858 p.nextToken();
1859
1860 auto d = p.parseDeclDefs(0);
1861 if (global.errors != errors)
1862 return null;
1863
1864 if (p.token.value != TOK.endOfFile)
1865 {
1866 .error(cd.loc, "%s `%s` incomplete mixin declaration `%s`", cd.kind, cd.toPrettyChars, str.ptr);
1867 return null;
1868 }
1869 return d;
1870 }
1871
1872 /***********************************************************
1873 * https://dlang.org/spec/module.html#mixin-declaration
1874 */
1875 override void visit(MixinDeclaration cd)
1876 {
1877 //printf("MixinDeclaration::semantic()\n");
1878 if (!cd.compiled)
1879 {
1880 cd.decl = compileIt(cd);
1881 attribAddMember(cd, sc, cd.scopesym);
1882 cd.compiled = true;
1883
1884 if (cd._scope && cd.decl)
1885 {
1886 for (size_t i = 0; i < cd.decl.length; i++)
1887 {
1888 Dsymbol s = (*cd.decl)[i];
1889 s.setScope(cd._scope);
1890 }
1891 }
1892 }
1893 attribSemantic(cd);
1894 }
1895
1896 override void visit(CPPNamespaceDeclaration ns)
1897 {
1898 Identifier identFromSE (StringExp se)
1899 {
1900 const sident = se.toStringz();
1901 if (!sident.length || !Identifier.isValidIdentifier(sident))
1902 {
1903 error(ns.exp.loc, "expected valid identifier for C++ namespace but got `%s`", se.toErrMsg());
1904 return null;
1905 }
1906 else
1907 return Identifier.idPool(sident);
1908 }
1909
1910 if (ns.ident !is null)
1911 return attribSemantic(ns);
1912
1913 ns.cppnamespace = sc.namespace;
1914 sc = sc.startCTFE();
1915 ns.exp = ns.exp.expressionSemantic(sc);
1916 ns.exp = resolveProperties(sc, ns.exp);
1917 sc = sc.endCTFE();
1918 ns.exp = ns.exp.ctfeInterpret();
1919 // Can be either a tuple of strings or a string itself
1920 if (auto te = ns.exp.isTupleExp())
1921 {
1922 expandTuples(te.exps);
1923 CPPNamespaceDeclaration current = ns.cppnamespace;
1924 for (size_t d = 0; d < te.exps.length; ++d)
1925 {
1926 auto exp = (*te.exps)[d];
1927 auto prev = d ? current : ns.cppnamespace;
1928 current = (d + 1) != te.exps.length
1929 ? new CPPNamespaceDeclaration(ns.loc, exp, null)
1930 : ns;
1931 current.exp = exp;
1932 current.cppnamespace = prev;
1933 if (auto se = exp.toStringExp())
1934 {
1935 current.ident = identFromSE(se);
1936 if (current.ident is null)
1937 return; // An error happened in `identFromSE`
1938 }
1939 else
1940 error(ns.exp.loc, "`%s`: index %llu is not a string constant, it is a `%s`",
1941 ns.exp.toChars(), cast(ulong) d, ns.exp.type.toChars());
1942 }
1943 }
1944 else if (auto se = ns.exp.toStringExp())
1945 ns.ident = identFromSE(se);
1946 // Empty Tuple
1947 else if (ns.exp.isTypeExp() && ns.exp.isTypeExp().type.toBasetype().isTypeTuple())
1948 {
1949 }
1950 else if (!ns.exp.type.isTypeError())
1951 error(ns.exp.loc, "compile time string constant (or sequence) expected, not `%s`",
1952 ns.exp.toChars());
1953 attribSemantic(ns);
1954 }
1955
1956 override void visit(UserAttributeDeclaration uad)
1957 {
1958 //printf("UserAttributeDeclaration::semantic() %p\n", this);
1959 if (uad.decl && !uad._scope)
1960 uad.Dsymbol.setScope(sc); // for function local symbols
1961 arrayExpressionSemantic(uad.atts.peekSlice(), sc, true);
1962 return attribSemantic(uad);
1963 }
1964
1965 override void visit(StaticAssert sa)
1966 {
1967 if (sa.semanticRun < PASS.semanticdone)
1968 sa.semanticRun = PASS.semanticdone;
1969 else
1970 return;
1971
1972 // https://issues.dlang.org/show_bug.cgi?id=24645
1973 // This is a short-circuit. Usually, static assert conditions are evaluated
1974 // in semantic2, but it's not uncommon to use this pattern:
1975 // ---
1976 // version(X)
1977 // {}
1978 // else
1979 // static assert(false, "unsupported platform");
1980 // ---
1981 // However, without this short-circuit, the static assert error may get drowned
1982 // out by subsequent semantic1 (import) errors. Only short-circuit at module scope though,
1983 // inside mixin templates you want an instantiation trace (which you don't get here).
1984 if (sc.parent && sc.parent.isModule())
1985 if (auto i = sa.exp.isIntegerExp())
1986 if (i.toInteger() == 0)
1987 staticAssertFail(sa, sc);
1988 }
1989
1990 override void visit(DebugSymbol ds)
1991 {
1992 //printf("DebugSymbol::semantic() %s\n", toChars());
1993 if (ds.semanticRun < PASS.semanticdone)
1994 ds.semanticRun = PASS.semanticdone;
1995 }
1996
1997 override void visit(VersionSymbol vs)
1998 {
1999 if (vs.semanticRun < PASS.semanticdone)
2000 vs.semanticRun = PASS.semanticdone;
2001 }
2002
2003 override void visit(Package pkg)
2004 {
2005 if (pkg.semanticRun < PASS.semanticdone)
2006 pkg.semanticRun = PASS.semanticdone;
2007 }
2008
2009 override void visit(Module m)
2010 {
2011 if (m.semanticRun != PASS.initial)
2012 return;
2013
2014 timeTraceBeginEvent(TimeTraceEventType.sema1Module);
2015 scope (exit) timeTraceEndEvent(TimeTraceEventType.sema1Module, m);
2016
2017 //printf("+Module::semantic(this = %p, '%s'): parent = %p\n", this, toChars(), parent);
2018 m.semanticRun = PASS.semantic;
2019 // Note that modules get their own scope, from scratch.
2020 // This is so regardless of where in the syntax a module
2021 // gets imported, it is unaffected by context.
2022 Scope* sc = m._scope; // see if already got one from importAll()
2023 if (!sc)
2024 {
2025 sc = Scope.createGlobal(m, global.errorSink); // create root scope
2026 }
2027
2028 //printf("Module = %p, linkage = %d\n", sc.scopesym, sc.linkage);
2029 // Pass 1 semantic routines: do public side of the definition
2030 m.members.foreachDsymbol( (s)
2031 {
2032 //printf("\tModule('%s'): '%s'.dsymbolSemantic()\n", toChars(), s.toChars());
2033 s.dsymbolSemantic(sc);
2034 m.runDeferredSemantic();
2035 });
2036
2037 if (m.userAttribDecl)
2038 {
2039 m.userAttribDecl.dsymbolSemantic(sc);
2040 }
2041 if (!m._scope)
2042 {
2043 sc = sc.pop();
2044 sc.pop(); // 2 pops because Scope.createGlobal() created 2
2045 }
2046 m.semanticRun = PASS.semanticdone;
2047 //printf("-Module::semantic(this = %p, '%s'): parent = %p\n", this, toChars(), parent);
2048 }
2049
2050 override void visit(EnumDeclaration ed)
2051 {
2052 enumSemantic(sc, ed);
2053 }
2054
2055 override void visit(EnumMember em)
2056 {
2057 enumMemberSemantic(sc, em);
2058 }
2059
2060 override void visit(TemplateDeclaration tempdecl)
2061 {
2062 templateDeclarationSemantic(sc, tempdecl);
2063 }
2064
2065 override void visit(TemplateInstance ti)
2066 {
2067 templateInstanceSemantic(ti, sc, ArgumentList());
2068 }
2069
2070 override void visit(TemplateMixin tm)
2071 {
2072 static if (LOG)
2073 {
2074 printf("+TemplateMixin.dsymbolSemantic('%s', this=%p)\n", tm.toChars(), tm);
2075 fflush(stdout);
2076 }
2077 if (tm.semanticRun != PASS.initial)
2078 {
2079 // When a class/struct contains mixin members, and is done over
2080 // because of forward references, never reach here so semanticRun
2081 // has been reset to PASS.initial.
2082 static if (LOG)
2083 {
2084 printf("\tsemantic done\n");
2085 }
2086 return;
2087 }
2088 tm.semanticRun = PASS.semantic;
2089 static if (LOG)
2090 {
2091 printf("\tdo semantic\n");
2092 }
2093
2094 Scope* scx = null;
2095 if (tm._scope)
2096 {
2097 sc = tm._scope;
2098 scx = tm._scope; // save so we don't make redundant copies
2099 tm._scope = null;
2100 }
2101
2102 /* Run semantic on each argument, place results in tiargs[],
2103 * then find best match template with tiargs
2104 */
2105 if (!tm.findTempDecl(sc) || !tm.semanticTiargs(sc) || !tm.findBestMatch(sc, ArgumentList()))
2106 {
2107 if (tm.semanticRun == PASS.initial) // forward reference had occurred
2108 {
2109 //printf("forward reference - deferring\n");
2110 return deferDsymbolSemantic(sc, tm, scx);
2111 }
2112
2113 tm.inst = tm;
2114 tm.errors = true;
2115 return; // error recovery
2116 }
2117
2118 auto tempdecl = tm.tempdecl.isTemplateDeclaration();
2119 assert(tempdecl);
2120
2121 if (!tm.ident)
2122 {
2123 /* Assign scope local unique identifier, as same as lambdas.
2124 */
2125 const(char)[] s = "__mixin";
2126
2127 if (FuncDeclaration func = sc.parent.isFuncDeclaration())
2128 {
2129 tm.symtab = func.localsymtab;
2130 if (tm.symtab)
2131 {
2132 // Inside template constraint, symtab is not set yet.
2133 goto L1;
2134 }
2135 }
2136 else
2137 {
2138 tm.symtab = sc.parent.isScopeDsymbol().symtab;
2139 L1:
2140 assert(tm.symtab);
2141 tm.ident = Identifier.generateId(s, tm.symtab.length + 1);
2142 tm.symtab.insert(tm);
2143 }
2144 }
2145
2146 tm.inst = tm;
2147 tm.parent = sc.parent;
2148
2149 /* Detect recursive mixin instantiations.
2150 */
2151 for (Dsymbol s = tm.parent; s; s = s.parent)
2152 {
2153 //printf("\ts = '%s'\n", s.toChars());
2154 TemplateMixin tmix = s.isTemplateMixin();
2155 if (!tmix || tempdecl != tmix.tempdecl)
2156 continue;
2157
2158 /* Different argument list lengths happen with variadic args
2159 */
2160 if (tm.tiargs.length != tmix.tiargs.length)
2161 continue;
2162
2163 for (size_t i = 0; i < tm.tiargs.length; i++)
2164 {
2165 RootObject o = (*tm.tiargs)[i];
2166 Type ta = isType(o);
2167 Expression ea = isExpression(o);
2168 Dsymbol sa = isDsymbol(o);
2169 RootObject tmo = (*tmix.tiargs)[i];
2170 if (ta)
2171 {
2172 Type tmta = isType(tmo);
2173 if (!tmta)
2174 goto Lcontinue;
2175 if (!ta.equals(tmta))
2176 goto Lcontinue;
2177 }
2178 else if (ea)
2179 {
2180 Expression tme = isExpression(tmo);
2181 if (!tme || !ea.equals(tme))
2182 goto Lcontinue;
2183 }
2184 else if (sa)
2185 {
2186 Dsymbol tmsa = isDsymbol(tmo);
2187 if (sa != tmsa)
2188 goto Lcontinue;
2189 }
2190 else
2191 assert(0);
2192 }
2193 .error(tm.loc, "%s `%s` recursive mixin instantiation", tm.kind, tm.toPrettyChars);
2194 return;
2195
2196 Lcontinue:
2197 continue;
2198 }
2199
2200 // Copy the syntax trees from the TemplateDeclaration
2201 tm.members = Dsymbol.arraySyntaxCopy(tempdecl.members);
2202 if (!tm.members)
2203 return;
2204
2205 tm.symtab = new DsymbolTable();
2206
2207 sc.getScopesym().importScope(tm, Visibility(Visibility.Kind.public_));
2208
2209 static if (LOG)
2210 {
2211 printf("\tcreate scope for template parameters '%s'\n", tm.toChars());
2212 }
2213 Scope* scy = sc.push(tm);
2214 scy.parent = tm;
2215
2216 /* https://issues.dlang.org/show_bug.cgi?id=930
2217 *
2218 * If the template that is to be mixed in is in the scope of a template
2219 * instance, we have to also declare the type aliases in the new mixin scope.
2220 */
2221 auto parentInstance = tempdecl.parent ? tempdecl.parent.isTemplateInstance() : null;
2222 if (parentInstance)
2223 parentInstance.declareParameters(scy);
2224
2225 tm.argsym = new ScopeDsymbol();
2226 tm.argsym.parent = scy.parent;
2227 Scope* argscope = scy.push(tm.argsym);
2228
2229 const errorsave = global.errors;
2230
2231 // Declare each template parameter as an alias for the argument type
2232 tm.declareParameters(argscope);
2233
2234 // Add members to enclosing scope, as well as this scope
2235 tm.members.foreachDsymbol(s => s.addMember(argscope, tm));
2236
2237 // Do semantic() analysis on template instance members
2238 static if (LOG)
2239 {
2240 printf("\tdo semantic() on template instance members '%s'\n", tm.toChars());
2241 }
2242 Scope* sc2 = argscope.push(tm);
2243 //size_t deferred_dim = Module.deferred.length;
2244
2245 __gshared int nest;
2246 //printf("%d\n", nest);
2247 if (++nest > global.recursionLimit)
2248 {
2249 global.gag = 0; // ensure error message gets printed
2250 .error(tm.loc, "%s `%s` recursive expansion", tm.kind, tm.toPrettyChars);
2251 fatal();
2252 }
2253
2254 tm.members.foreachDsymbol( s => s.setScope(sc2) );
2255
2256 tm.members.foreachDsymbol( s => s.importAll(sc2) );
2257
2258 tm.members.foreachDsymbol( s => s.dsymbolSemantic(sc2) );
2259
2260 nest--;
2261
2262 /* In DeclDefs scope, TemplateMixin does not have to handle deferred symbols.
2263 * Because the members would already call Module.addDeferredSemantic() for themselves.
2264 * See Struct, Class, Interface, and EnumDeclaration.dsymbolSemantic().
2265 */
2266 //if (!sc.func && Module.deferred.length > deferred_dim) {}
2267
2268 AggregateDeclaration ad = tm.isMember();
2269 if (sc.func && !ad)
2270 {
2271 tm.semantic2(sc2);
2272 tm.semantic3(sc2);
2273 }
2274
2275 // Give additional context info if error occurred during instantiation
2276 if (global.errors != errorsave)
2277 {
2278 .error(tm.loc, "%s `%s` error instantiating", tm.kind, tm.toPrettyChars);
2279 tm.errors = true;
2280 }
2281
2282 sc2.pop();
2283 argscope.pop();
2284 scy.pop();
2285
2286 static if (LOG)
2287 {
2288 printf("-TemplateMixin.dsymbolSemantic('%s', this=%p)\n", tm.toChars(), tm);
2289 }
2290 }
2291
2292 override void visit(Nspace ns)
2293 {
2294 if (ns.semanticRun != PASS.initial)
2295 return;
2296 static if (LOG)
2297 {
2298 printf("+Nspace::semantic('%s')\n", ns.toChars());
2299 scope(exit) printf("-Nspace::semantic('%s')\n", ns.toChars());
2300 }
2301 if (ns._scope)
2302 {
2303 sc = ns._scope;
2304 ns._scope = null;
2305 }
2306 if (!sc)
2307 return;
2308
2309 bool repopulateMembers = false;
2310 if (ns.identExp)
2311 {
2312 // resolve the namespace identifier
2313 sc = sc.startCTFE();
2314 Expression resolved = ns.identExp.expressionSemantic(sc);
2315 resolved = resolveProperties(sc, resolved);
2316 sc = sc.endCTFE();
2317 resolved = resolved.ctfeInterpret();
2318 StringExp name = resolved.toStringExp();
2319 TupleExp tup = name ? null : resolved.isTupleExp();
2320 if (!tup && !name)
2321 {
2322 error(ns.loc, "expected string expression for namespace name, got `%s`", ns.identExp.toChars());
2323 return;
2324 }
2325 ns.identExp = resolved; // we don't need to keep the old AST around
2326 if (name)
2327 {
2328 const(char)[] ident = name.toStringz();
2329 if (ident.length == 0 || !Identifier.isValidIdentifier(ident))
2330 {
2331 error(ns.loc, "expected valid identifier for C++ namespace but got `%.*s`", cast(int)ident.length, ident.ptr);
2332 return;
2333 }
2334 ns.ident = Identifier.idPool(ident);
2335 }
2336 else
2337 {
2338 // create namespace stack from the tuple
2339 Nspace parentns = ns;
2340 foreach (i, exp; *tup.exps)
2341 {
2342 name = exp.toStringExp();
2343 if (!name)
2344 {
2345 error(ns.loc, "expected string expression for namespace name, got `%s`", exp.toChars());
2346 return;
2347 }
2348 const(char)[] ident = name.toStringz();
2349 if (ident.length == 0 || !Identifier.isValidIdentifier(ident))
2350 {
2351 error(ns.loc, "expected valid identifier for C++ namespace but got `%.*s`", cast(int)ident.length, ident.ptr);
2352 return;
2353 }
2354 if (i == 0)
2355 {
2356 ns.ident = Identifier.idPool(ident);
2357 }
2358 else
2359 {
2360 // insert the new namespace
2361 Nspace childns = new Nspace(ns.loc, Identifier.idPool(ident), null, parentns.members);
2362 parentns.members = new Dsymbols;
2363 parentns.members.push(childns);
2364 parentns = childns;
2365 repopulateMembers = true;
2366 }
2367 }
2368 }
2369 }
2370
2371 ns.semanticRun = PASS.semantic;
2372 ns.parent = sc.parent;
2373 // Link does not matter here, if the UDA is present it will error
2374 checkGNUABITag(ns, LINK.cpp);
2375
2376 if (!ns.members)
2377 {
2378 ns.semanticRun = PASS.semanticdone;
2379 return;
2380 }
2381 assert(sc);
2382 sc = sc.push(ns);
2383 sc.linkage = LINK.cpp; // note that namespaces imply C++ linkage
2384 sc.parent = ns;
2385 foreach (s; *ns.members)
2386 {
2387 if (repopulateMembers)
2388 {
2389 s.addMember(sc, sc.scopesym);
2390 s.setScope(sc);
2391 }
2392 s.importAll(sc);
2393 }
2394 foreach (s; *ns.members)
2395 {
2396 static if (LOG)
2397 {
2398 printf("\tmember '%s', kind = '%s'\n", s.toChars(), s.kind());
2399 }
2400 s.dsymbolSemantic(sc);
2401 }
2402 sc.pop();
2403 ns.semanticRun = PASS.semanticdone;
2404 }
2405
2406 /// Do the semantic analysis on the external interface to the function.
2407 override void visit(FuncDeclaration funcdecl)
2408 {
2409 funcDeclarationSemantic(sc, funcdecl);
2410 }
2411
2412 override void visit(CtorDeclaration ctd)
2413 {
2414 //printf("CtorDeclaration::semantic() %p %s\n", ctd, ctd.toChars());
2415 if (ctd.semanticRun >= PASS.semanticdone)
2416 return;
2417 if (ctd._scope)
2418 {
2419 sc = ctd._scope;
2420 ctd._scope = null;
2421 }
2422
2423 ctd.parent = sc.parent;
2424 Dsymbol p = ctd.toParentDecl();
2425 AggregateDeclaration ad = p.isAggregateDeclaration();
2426 if (!ad)
2427 {
2428 error(ctd.loc, "constructor can only be a member of aggregate, not %s `%s`", p.kind(), p.toChars());
2429 ctd.type = Type.terror;
2430 ctd.errors = true;
2431 return;
2432 }
2433
2434 sc = sc.push();
2435
2436 if (sc.stc & STC.static_)
2437 {
2438 if (sc.stc & STC.shared_)
2439 error(ctd.loc, "`shared static` has no effect on a constructor inside a `shared static` block. Use `shared static this()`");
2440 else
2441 error(ctd.loc, "`static` has no effect on a constructor inside a `static` block. Use `static this()`");
2442 }
2443
2444 sc.stc &= ~STC.static_; // not a static constructor
2445
2446 funcDeclarationSemantic(sc, ctd);
2447 // Check short constructor: this() => expr;
2448 if (ctd.fbody)
2449 {
2450 if (auto s = ctd.fbody.isExpStatement())
2451 {
2452 if (s.exp)
2453 {
2454 auto ce = s.exp.isCallExp();
2455 // check this/super before semantic
2456 if (!ce || (!ce.e1.isThisExp() && !ce.e1.isSuperExp()))
2457 {
2458 s.exp = s.exp.expressionSemantic(sc);
2459 if (s.exp.type.ty != Tvoid)
2460 error(s.loc, "can only return void expression, `this` call or `super` call from constructor");
2461 }
2462 }
2463 }
2464 }
2465
2466 sc.pop();
2467
2468 if (ctd.errors)
2469 return;
2470
2471 TypeFunction tf = ctd.type.toTypeFunction();
2472 immutable dim = tf.parameterList.length;
2473 auto sd = ad.isStructDeclaration();
2474
2475 /* See if it's the default constructor
2476 * But, template constructor should not become a default constructor.
2477 */
2478 if (ad && (!ctd.parent.isTemplateInstance() || ctd.parent.isTemplateMixin()))
2479 {
2480 if (!sd)
2481 {
2482 if (dim == 0 && tf.parameterList.varargs == VarArg.none)
2483 ad.defaultCtor = ctd;
2484 return;
2485 }
2486
2487 if (dim == 0 && tf.parameterList.varargs == VarArg.none) // empty default ctor w/o any varargs
2488 {
2489 if (ctd.fbody || !(ctd.storage_class & STC.disable))
2490 {
2491 .error(ctd.loc, "%s `%s` default constructor for structs only allowed " ~
2492 "with `@disable`, no body, and no parameters", ctd.kind, ctd.toPrettyChars);
2493 ctd.storage_class |= STC.disable;
2494 ctd.fbody = null;
2495 }
2496 sd.noDefaultCtor = true;
2497 }
2498 else if (dim == 0 && tf.parameterList.varargs != VarArg.none) // allow varargs only ctor
2499 {
2500 }
2501 else if (dim && !tf.parameterList.hasArgsWithoutDefault)
2502 {
2503 if (ctd.storage_class & STC.disable)
2504 {
2505 .error(ctd.loc, "%s `%s` is marked `@disable`, so it cannot have default "~
2506 "arguments for all parameters.", ctd.kind, ctd.toPrettyChars);
2507 errorSupplemental(ctd.loc, "Use `@disable this();` if you want to disable default initialization.");
2508 }
2509 else
2510 .error(ctd.loc, "%s `%s` all parameters have default arguments, "~
2511 "but structs cannot have default constructors.", ctd.kind, ctd.toPrettyChars);
2512 }
2513 else if ((dim == 1 || (dim > 1 && tf.parameterList[1].defaultArg)))
2514 {
2515 //printf("tf: %s\n", toChars(tf));
2516 auto param = tf.parameterList[0];
2517 if (param.type.mutableOf().unSharedOf() == sd.type.mutableOf().unSharedOf())
2518 {
2519 //printf("copy constructor %p\n", ctd);
2520 assert(!ctd.isCpCtor && !ctd.isMoveCtor);
2521 if (param.storageClass & STC.ref_)
2522 ctd.isCpCtor = true; // copy constructor
2523 else
2524 ctd.isMoveCtor = true; // move constructor
2525 assert(!(ctd.isCpCtor && ctd.isMoveCtor));
2526 }
2527 }
2528 }
2529 // https://issues.dlang.org/show_bug.cgi?id=22593
2530 else if (auto ti = ctd.parent.isTemplateInstance())
2531 {
2532 checkHasBothRvalueAndCpCtor(sd, ctd, ti);
2533 }
2534 }
2535
2536 override void visit(PostBlitDeclaration pbd)
2537 {
2538 //printf("PostBlitDeclaration::semantic() %s\n", toChars());
2539 //printf("ident: %s, %s, %p, %p\n", ident.toChars(), Id.dtor.toChars(), ident, Id.dtor);
2540 //printf("stc = x%llx\n", sc.stc);
2541 if (pbd.semanticRun >= PASS.semanticdone)
2542 return;
2543 if (pbd._scope)
2544 {
2545 sc = pbd._scope;
2546 pbd._scope = null;
2547 }
2548
2549 pbd.parent = sc.parent;
2550 Dsymbol p = pbd.toParent2();
2551 StructDeclaration ad = p.isStructDeclaration();
2552 if (!ad)
2553 {
2554 error(pbd.loc, "postblit can only be a member of struct, not %s `%s`", p.kind(), p.toChars());
2555 pbd.type = Type.terror;
2556 pbd.errors = true;
2557 return;
2558 }
2559 if (pbd.ident == Id.postblit && pbd.semanticRun < PASS.semantic)
2560 ad.postblits.push(pbd);
2561 if (!pbd.type)
2562 pbd.type = new TypeFunction(ParameterList(), Type.tvoid, LINK.d, pbd.storage_class);
2563
2564 sc = sc.push();
2565 sc.stc &= ~STC.static_; // not static
2566 sc.linkage = LINK.d;
2567
2568 funcDeclarationSemantic(sc, pbd);
2569
2570 sc.pop();
2571 }
2572
2573 override void visit(DtorDeclaration dd)
2574 {
2575 //printf("DtorDeclaration::semantic() %s\n", dd.toChars());
2576 //printf("ident: %s, %s, %p, %p\n", dd.ident.toChars(), Id.dtor.toChars(), dd.ident, Id.dtor);
2577 if (dd.semanticRun >= PASS.semanticdone)
2578 return;
2579 if (dd._scope)
2580 {
2581 sc = dd._scope;
2582 dd._scope = null;
2583 }
2584
2585 dd.parent = sc.parent;
2586 Dsymbol p = dd.toParent2();
2587 AggregateDeclaration ad = p.isAggregateDeclaration();
2588 if (!ad)
2589 {
2590 error(dd.loc, "destructor can only be a member of aggregate, not %s `%s`", p.kind(), p.toChars());
2591 dd.type = Type.terror;
2592 dd.errors = true;
2593 return;
2594 }
2595
2596 if (ad.isClassDeclaration() && ad.classKind == ClassKind.d)
2597 {
2598 // Class destructors are implicitly `scope`
2599 dd.storage_class |= STC.scope_;
2600 }
2601
2602 if (dd.ident == Id.dtor && dd.semanticRun < PASS.semantic)
2603 ad.userDtors.push(dd);
2604 if (!dd.type)
2605 {
2606 dd.type = new TypeFunction(ParameterList(), Type.tvoid, LINK.d, dd.storage_class);
2607 if (ad.classKind == ClassKind.cpp && dd.ident == Id.dtor)
2608 {
2609 if (auto cldec = ad.isClassDeclaration())
2610 {
2611 assert (cldec.cppDtorVtblIndex == -1); // double-call check already by dd.type
2612 if (cldec.baseClass && cldec.baseClass.cppDtorVtblIndex != -1)
2613 {
2614 // override the base virtual
2615 cldec.cppDtorVtblIndex = cldec.baseClass.cppDtorVtblIndex;
2616 }
2617 else if (!dd.isFinal())
2618 {
2619 // reserve the dtor slot for the destructor (which we'll create later)
2620 cldec.cppDtorVtblIndex = cast(int)cldec.vtbl.length;
2621 cldec.vtbl.push(dd);
2622 if (target.cpp.twoDtorInVtable)
2623 cldec.vtbl.push(dd); // deleting destructor uses a second slot
2624 }
2625 }
2626 }
2627 }
2628
2629 sc = sc.push();
2630 sc.stc &= ~STC.static_; // not a static destructor
2631 if (sc.linkage != LINK.cpp)
2632 sc.linkage = LINK.d;
2633
2634 funcDeclarationSemantic(sc, dd);
2635
2636 sc.pop();
2637 }
2638
2639 void visitStaticCDtorDeclaration(FuncDeclaration sd, bool isDestructor)
2640 {
2641 if (sd.semanticRun >= PASS.semanticdone)
2642 return;
2643 if (sd._scope)
2644 {
2645 sc = sd._scope;
2646 sd._scope = null;
2647 }
2648 sd.parent = sc.parent;
2649 Dsymbol p = sd.parent.pastMixin();
2650 const bool isShared = !!(sd.isSharedStaticDtorDeclaration() || sd.isSharedStaticCtorDeclaration());
2651 const(char)* what = isDestructor ? "destructor" : "constructor";
2652 if (!p.isScopeDsymbol())
2653 {
2654 const(char)* s = isShared ? "shared " : "";
2655 error(sd.loc, "`%sstatic` %s can only be member of module/aggregate/template, not %s `%s`", s, what, p.kind(), p.toChars());
2656 sd.type = Type.terror;
2657 sd.errors = true;
2658 return;
2659 }
2660
2661 if (!sd.type)
2662 sd.type = new TypeFunction(ParameterList(), Type.tvoid, LINK.d, sd.storage_class);
2663
2664 /* If the static [dc]tor appears within a template instantiation,
2665 * it could get called multiple times by the module constructors
2666 * for different modules. Thus, protect it with a gate.
2667 */
2668 if (sd.isInstantiated() && sd.semanticRun < PASS.semantic)
2669 {
2670 /* Add this prefix to the constructor:
2671 * ```
2672 * static int gate;
2673 * if ([--|++]gate != [0|1]) return; // dependant on ctor/dtor
2674 * ```
2675 * or, for shared constructor:
2676 * ```
2677 * shared int gate;
2678 * enum op = isDestructor ? "-=" : "+=";
2679 * enum cmp = isDestructor ? 0 : 1;
2680 * if (core.atomic.atomicOp!op(gate, 1) != cmp) return;
2681 * ```
2682 */
2683
2684 auto v = new VarDeclaration(Loc.initial, Type.tint32, Id.gate, null);
2685 v.storage_class = STC.temp | STC.static_ | (isShared ? STC.shared_ : STC.none);
2686
2687 auto sa = new Statements();
2688 Statement s = new ExpStatement(Loc.initial, v);
2689 sa.push(s);
2690
2691 Expression e;
2692 if (isShared)
2693 {
2694 e = doAtomicOp(isDestructor ? "-=" : "+=", v.ident, IntegerExp.literal!(1));
2695 if (e is null)
2696 {
2697 .error(sd.loc, "%s `%s` shared static %s within a template require `core.atomic : atomicOp` to be present", sd.kind, sd.toPrettyChars, what);
2698 return;
2699 }
2700 }
2701 else
2702 {
2703 IntegerExp one = isDestructor ? IntegerExp.literal!(-1) : IntegerExp.literal!(1);
2704 e = new AddAssignExp(
2705 Loc.initial, new IdentifierExp(Loc.initial, v.ident), one);
2706 }
2707 IntegerExp cmp = isDestructor ? IntegerExp.literal!0 : IntegerExp.literal!1;
2708 e = new EqualExp(EXP.notEqual, Loc.initial, e, cmp);
2709 s = new IfStatement(Loc.initial, null, e, new ReturnStatement(Loc.initial, null), null, Loc.initial);
2710
2711 sa.push(s);
2712 if (sd.fbody)
2713 sa.push(sd.fbody);
2714
2715 sd.fbody = new CompoundStatement(Loc.initial, sa);
2716 if (isDestructor)
2717 (cast(StaticDtorDeclaration)sd).vgate = v;
2718 }
2719 const LINK save = sc.linkage;
2720 if (save != LINK.d)
2721 {
2722 const(char)* s = isShared ? "shared " : "";
2723 deprecation(sd.loc, "`%sstatic` %s can only be of D linkage", s, what);
2724 // Just correct it
2725 sc.linkage = LINK.d;
2726 }
2727 funcDeclarationSemantic(sc, sd);
2728 sc.linkage = save;
2729
2730 // We're going to need ModuleInfo
2731 Module m = sd.getModule();
2732 if (!m)
2733 m = sc._module;
2734 if (m)
2735 {
2736 m.needmoduleinfo = 1;
2737 //printf("module2 %s needs moduleinfo\n", m.toChars());
2738 }
2739 }
2740 override void visit(StaticCtorDeclaration scd)
2741 {
2742 //printf("StaticCtorDeclaration::semantic()\n");
2743 visitStaticCDtorDeclaration(scd, false);
2744
2745 foreachUda(scd, sc, (Expression e) {
2746 import dmd.attrib : isEnumAttribute;
2747 if (!isEnumAttribute(e, Id.udaStandalone))
2748 return 0;
2749
2750 if (auto sharedCtor = scd.isSharedStaticCtorDeclaration())
2751 {
2752 auto trust = sharedCtor.type.isTypeFunction().trust;
2753 if (trust != TRUST.system && trust != TRUST.trusted)
2754 error(e.loc, "a module constructor using `@%s` must be `@system` or `@trusted`", Id.udaStandalone.toChars());
2755 sharedCtor.standalone = true;
2756 }
2757 else
2758 .error(e.loc, "`@%s` can only be used on shared static constructors", Id.udaStandalone.toChars());
2759
2760 return 1;
2761 });
2762 }
2763
2764 override void visit(StaticDtorDeclaration sdd)
2765 {
2766 visitStaticCDtorDeclaration(sdd, true);
2767 }
2768
2769 override void visit(InvariantDeclaration invd)
2770 {
2771 if (invd.semanticRun >= PASS.semanticdone)
2772 return;
2773 if (invd._scope)
2774 {
2775 sc = invd._scope;
2776 invd._scope = null;
2777 }
2778
2779 invd.parent = sc.parent;
2780 Dsymbol p = invd.parent.pastMixin();
2781 AggregateDeclaration ad = p.isAggregateDeclaration();
2782 if (!ad)
2783 {
2784 error(invd.loc, "`invariant` can only be a member of aggregate, not %s `%s`", p.kind(), p.toChars());
2785 invd.type = Type.terror;
2786 invd.errors = true;
2787 return;
2788 }
2789 if (invd.ident != Id.classInvariant &&
2790 invd.semanticRun < PASS.semantic &&
2791 !ad.isUnionDeclaration() // users are on their own with union fields
2792 )
2793 {
2794 invd.fixupInvariantIdent(ad.invs.length);
2795 ad.invs.push(invd);
2796 }
2797 if (!invd.type)
2798 invd.type = new TypeFunction(ParameterList(), Type.tvoid, LINK.d, invd.storage_class);
2799
2800 sc = sc.push();
2801 sc.stc &= ~STC.static_; // not a static invariant
2802 sc.stc |= STC.const_; // invariant() is always const
2803 sc.contract = Contract.invariant_;
2804 sc.linkage = LINK.d;
2805
2806 funcDeclarationSemantic(sc, invd);
2807
2808 sc.pop();
2809 }
2810
2811 override void visit(UnitTestDeclaration utd)
2812 {
2813 if (utd.semanticRun >= PASS.semanticdone)
2814 return;
2815 if (utd._scope)
2816 {
2817 sc = utd._scope;
2818 utd._scope = null;
2819 }
2820
2821 utd.visibility = sc.visibility;
2822
2823 utd.parent = sc.parent;
2824 Dsymbol p = utd.parent.pastMixin();
2825 if (!p.isScopeDsymbol())
2826 {
2827 error(utd.loc, "`unittest` can only be a member of module/aggregate/template, not %s `%s`", p.kind(), p.toChars());
2828 utd.type = Type.terror;
2829 utd.errors = true;
2830 return;
2831 }
2832
2833 if (global.params.useUnitTests)
2834 {
2835 if (!utd.type)
2836 utd.type = new TypeFunction(ParameterList(), Type.tvoid, LINK.d, utd.storage_class);
2837 Scope* sc2 = sc.push();
2838 sc2.linkage = LINK.d;
2839 funcDeclarationSemantic(sc, utd);
2840 sc2.pop();
2841 }
2842
2843 version (none)
2844 {
2845 // We're going to need ModuleInfo even if the unit tests are not
2846 // compiled in, because other modules may import this module and refer
2847 // to this ModuleInfo.
2848 // (This doesn't make sense to me?)
2849 Module m = utd.getModule();
2850 if (!m)
2851 m = sc._module;
2852 if (m)
2853 {
2854 //printf("module3 %s needs moduleinfo\n", m.toChars());
2855 m.needmoduleinfo = 1;
2856 }
2857 }
2858 }
2859
2860 override void visit(NewDeclaration nd)
2861 {
2862 //printf("NewDeclaration::semantic()\n");
2863 if (nd.semanticRun >= PASS.semanticdone)
2864 return;
2865 if (!nd.type)
2866 nd.type = new TypeFunction(ParameterList(), Type.tvoid.pointerTo(), LINK.d, nd.storage_class);
2867
2868 funcDeclarationSemantic(sc, nd);
2869 }
2870
2871 override void visit(StructDeclaration sd)
2872 {
2873 enum log = false;
2874 if (log) printf("+StructDeclaration::semantic(this=%p, '%s', sizeok = %d)\n", sd, sd.toPrettyChars(), sd.sizeok);
2875
2876 //static int count; if (++count == 20) assert(0);
2877
2878 if (sd.semanticRun >= PASS.semanticdone)
2879 return;
2880 const errors = global.errors;
2881
2882 //printf("+StructDeclaration::semantic(this=%p, '%s', sizeok = %d)\n", sd, sd.toPrettyChars(), sd.sizeok);
2883 Scope* scx = null;
2884 if (sd._scope)
2885 {
2886 sc = sd._scope;
2887 scx = sd._scope; // save so we don't make redundant copies
2888 sd._scope = null;
2889 }
2890
2891 if (!sd.parent)
2892 {
2893 assert(sc.parent && sc.func);
2894 sd.parent = sc.parent;
2895 }
2896 assert(sd.parent && !sd.isAnonymous());
2897
2898 if (sd.errors)
2899 sd.type = Type.terror;
2900 if (sd.semanticRun == PASS.initial)
2901 sd.type = sd.type.addSTC(sc.stc | sd.storage_class);
2902 sd.type = sd.type.typeSemantic(sd.loc, sc);
2903 auto ts = sd.type.isTypeStruct();
2904 if (ts)
2905 {
2906 if (ts.sym != sd)
2907 {
2908 TemplateInstance ti = ts.sym.isInstantiated();
2909 if (ti && isError(ti))
2910 ts.sym = sd;
2911 /* For C modules, if module A contains `struct S;` and
2912 * module B contains `struct S { members...}` then replace
2913 * the former with the latter
2914 */
2915 else if (!ts.sym.members && sd.members)
2916 ts.sym = sd;
2917 }
2918 }
2919
2920 // Ungag errors when not speculative
2921 Ungag ungag = sd.ungagSpeculative();
2922
2923 if (sd.semanticRun == PASS.initial)
2924 {
2925 sd.visibility = sc.visibility;
2926
2927 if (sd.alignment.isUnknown()) // can be set already by `struct __declspec(align(N)) Tag { ... }`
2928 sd.alignment = sc.alignment();
2929
2930 sd.storage_class |= sc.stc;
2931 if (sd.storage_class & STC.abstract_)
2932 .error(sd.loc, "%s `%s` structs, unions cannot be `abstract`", sd.kind, sd.toPrettyChars);
2933
2934 sd.userAttribDecl = sc.userAttribDecl;
2935
2936 if (sc.linkage == LINK.cpp)
2937 sd.classKind = ClassKind.cpp;
2938 else if (sc.linkage == LINK.c)
2939 sd.classKind = ClassKind.c;
2940 sd.cppnamespace = sc.namespace;
2941 sd.cppmangle = sc.cppmangle;
2942 }
2943 else if (sd.symtab && !scx)
2944 return;
2945
2946 sd.semanticRun = PASS.semantic;
2947 checkGNUABITag(sd, sc.linkage);
2948
2949 if (!sd.members) // if opaque declaration
2950 {
2951 if (log) printf("\topaque declaration %s\n", sd.toChars());
2952 sd.semanticRun = PASS.semanticdone;
2953 return;
2954 }
2955 if (!sd.symtab)
2956 {
2957 sd.symtab = new DsymbolTable();
2958
2959 sd.members.foreachDsymbol( s => s.addMember(sc, sd) );
2960 }
2961
2962 auto sc2 = sd.newScope(sc);
2963
2964 /* Set scope so if there are forward references, we still might be able to
2965 * resolve individual members like enums.
2966 */
2967 sd.members.foreachDsymbol( s => s.setScope(sc2) );
2968 sd.members.foreachDsymbol( s => s.importAll(sc2) );
2969 sd.members.foreachDsymbol( (s) { s.dsymbolSemantic(sc2); if (sd.errors) s.errors = true; } );
2970
2971 if (sd.errors)
2972 sd.type = Type.terror;
2973
2974 if (!sd.determineFields())
2975 {
2976 if (sd.type.ty != Terror)
2977 {
2978 .error(sd.loc, "%s `%s` circular or forward reference", sd.kind, sd.toPrettyChars);
2979 sd.errors = true;
2980 sd.type = Type.terror;
2981 }
2982
2983 sc2.pop();
2984 sd.semanticRun = PASS.semanticdone;
2985 return;
2986 }
2987 /* Following special member functions creation needs semantic analysis
2988 * completion of sub-structs in each field types. For example, buildDtor
2989 * needs to check existence of elaborate dtor in type of each fields.
2990 * See the case in compilable/test14838.d
2991 */
2992 foreach (v; sd.fields)
2993 {
2994 Type tb = v.type.baseElemOf();
2995 if (tb.ty != Tstruct)
2996 continue;
2997 auto sdec = (cast(TypeStruct)tb).sym;
2998 if (sdec.semanticRun >= PASS.semanticdone)
2999 continue;
3000
3001 sc2.pop();
3002
3003 if (log) printf("\tdeferring %s\n", sd.toChars());
3004 return deferDsymbolSemantic(sc, sd, scx);
3005 }
3006
3007 /* Look for special member functions.
3008 */
3009 sd.disableNew = sd.search(Loc.initial, Id.classNew) !is null;
3010
3011 // Look for the constructor
3012 sd.ctor = sd.searchCtor();
3013
3014 buildDtors(sd, sc2);
3015
3016 bool hasCopyCtor;
3017 bool hasMoveCtor;
3018 bool needCopyCtor;
3019 bool needMoveCtor;
3020 needCopyOrMoveCtor(sd, hasCopyCtor, hasMoveCtor, needCopyCtor, needMoveCtor);
3021 //printf("%s hasCopy %d hasMove %d needCopy %d needMove %d\n", sd.toChars(), hasCopyCtor, hasMoveCtor, needCopyCtor, needMoveCtor);
3022
3023 /* When generating a move ctor, generate a copy ctor too, otherwise
3024 * https://github.com/s-ludwig/taggedalgebraic/issues/75
3025 */
3026 if (0 && needMoveCtor && !hasCopyCtor)
3027 {
3028 needCopyCtor = true;
3029 }
3030
3031 if (needCopyCtor)
3032 {
3033 assert(hasCopyCtor == false);
3034 buildCopyOrMoveCtor(sd, sc2, false); // build copy constructor
3035 hasCopyCtor = true;
3036 }
3037 if (needMoveCtor)
3038 {
3039 assert(hasMoveCtor == false);
3040 buildCopyOrMoveCtor(sd, sc2, true); // build move constructor
3041 hasMoveCtor = true;
3042 }
3043 sd.hasCopyCtor = hasCopyCtor;
3044 sd.hasMoveCtor = hasMoveCtor;
3045
3046 sd.postblit = buildPostBlit(sd, sc2);
3047
3048 buildOpAssign(sd, sc2);
3049 buildOpEquals(sd, sc2);
3050
3051 if (!sc2.inCfile &&
3052 global.params.useTypeInfo && Type.dtypeinfo) // these functions are used for TypeInfo
3053 {
3054 sd.xeq = buildXopEquals(sd, sc2);
3055 sd.xcmp = buildXopCmp(sd, sc2);
3056 sd.xhash = buildXtoHash(sd, sc2);
3057 }
3058
3059 sd.inv = buildInv(sd, sc2);
3060
3061 sd.semanticRun = PASS.semanticdone;
3062 if (log) printf("-StructDeclaration::semantic(this=%p, '%s', sizeok = %d)\n", sd, sd.toPrettyChars(), sd.sizeok);
3063
3064 sc2.pop();
3065
3066 if (sd.ctor)
3067 {
3068 Dsymbol scall = sd.search(Loc.initial, Id.opCall);
3069 if (scall)
3070 {
3071 const xerrors = global.startGagging();
3072 sc = sc.push();
3073 sc.tinst = null;
3074 sc.minst = null;
3075 auto fcall = resolveFuncCall(sd.loc, sc, scall, null, null, ArgumentList(), FuncResolveFlag.quiet);
3076 sc = sc.pop();
3077 global.endGagging(xerrors);
3078
3079 if (fcall && fcall.isStatic())
3080 {
3081 .error(fcall.loc, "%s `%s` `static opCall` is hidden by constructors and can never be called", sd.kind, sd.toPrettyChars);
3082 errorSupplemental(fcall.loc, "Please use a factory method instead, or replace all constructors with `static opCall`.");
3083 }
3084 }
3085 }
3086
3087 if (ts && ts.sym != sd)
3088 {
3089 StructDeclaration sym = ts.sym;
3090 if (sd.isCsymbol() && sym.isCsymbol())
3091 {
3092 /* This is two structs imported from different C files.
3093 * Just ignore sd, the second one. The first one will always
3094 * be found when going through the type.
3095 */
3096 }
3097 else
3098 {
3099 version (none)
3100 {
3101 printf("this = %p %s\n", sd, sd.toChars());
3102 printf("type = %d sym = %p, %s\n", sd.type.ty, sym, sym.toPrettyChars());
3103 }
3104 // https://issues.dlang.org/show_bug.cgi?id=19024
3105 .error(sd.loc, "%s `%s` already exists at %s. Perhaps in another function with the same name?", sd.kind, sd.toPrettyChars, sym.loc.toChars());
3106 }
3107 }
3108
3109 if (global.errors != errors)
3110 {
3111 // The type is no good.
3112 sd.type = Type.terror;
3113 sd.errors = true;
3114 if (sd.deferred)
3115 sd.deferred.errors = true;
3116 }
3117
3118 if (sd.deferred && !global.gag)
3119 {
3120 sd.deferred.semantic2(sc);
3121 sd.deferred.semantic3(sc);
3122 }
3123
3124 version (none)
3125 {
3126 // @@@DEPRECATED_2.110@@@ https://dlang.org/deprecate.html#scope%20as%20a%20type%20constraint
3127 // Deprecated in 2.100
3128 // Make an error in 2.110
3129 if (sd.storage_class & STC.scope_)
3130 deprecation(sd.loc, "`scope` as a type constraint is deprecated. Use `scope` at the usage site.");
3131 }
3132 //printf("-StructDeclaration::semantic(this=%p, '%s', sizeok = %d)\n", sd, sd.toPrettyChars(), sd.sizeok);
3133 }
3134
3135 void interfaceSemantic(ClassDeclaration cd)
3136 {
3137 cd.vtblInterfaces = new BaseClasses();
3138 cd.vtblInterfaces.reserve(cd.interfaces.length);
3139 foreach (b; cd.interfaces)
3140 {
3141 cd.vtblInterfaces.push(b);
3142 b.copyBaseInterfaces(cd.vtblInterfaces);
3143 }
3144 }
3145
3146 override void visit(ClassDeclaration cldec)
3147 {
3148 //printf("ClassDeclaration.dsymbolSemantic(%s), type = %p, sizeok = %d, this = %p\n", cldec.toChars(), cldec.type, cldec.sizeok, this);
3149 //printf("\tparent = %p, '%s'\n", sc.parent, sc.parent ? sc.parent.toChars() : "");
3150 //printf("sc.stc = %x\n", sc.stc);
3151
3152 //{ static int n; if (++n == 20) *(char*)0=0; }
3153
3154 if (cldec.semanticRun >= PASS.semanticdone)
3155 return;
3156 const errors = global.errors;
3157
3158 //printf("+ClassDeclaration.dsymbolSemantic(%s), type = %p, sizeok = %d, this = %p\n", toChars(), type, sizeok, this);
3159
3160 Scope* scx = null;
3161 if (cldec._scope)
3162 {
3163 sc = cldec._scope;
3164 scx = cldec._scope; // save so we don't make redundant copies
3165 cldec._scope = null;
3166 }
3167
3168 if (!cldec.parent)
3169 {
3170 assert(sc.parent);
3171 cldec.parent = sc.parent;
3172 }
3173
3174 if (cldec.errors)
3175 cldec.type = Type.terror;
3176 if (cldec.semanticRun == PASS.initial)
3177 cldec.type = cldec.type.addSTC(sc.stc | cldec.storage_class);
3178 cldec.type = cldec.type.typeSemantic(cldec.loc, sc);
3179 if (auto tc = cldec.type.isTypeClass())
3180 if (tc.sym != cldec)
3181 {
3182 auto ti = tc.sym.isInstantiated();
3183 if (ti && isError(ti))
3184 tc.sym = cldec;
3185 }
3186
3187 // Ungag errors when not speculative
3188 Ungag ungag = cldec.ungagSpeculative();
3189
3190 if (cldec.semanticRun == PASS.initial)
3191 {
3192 cldec.visibility = sc.visibility;
3193
3194 cldec.storage_class |= sc.stc;
3195 if (cldec.storage_class & STC.auto_)
3196 .error(cldec.loc, "%s `%s` storage class `auto` is invalid when declaring a class, did you mean to use `scope`?", cldec.kind, cldec.toPrettyChars);
3197 if (cldec.storage_class & STC.scope_)
3198 cldec.stack = true;
3199 if (cldec.storage_class & STC.abstract_)
3200 cldec.isabstract = ThreeState.yes;
3201
3202 cldec.userAttribDecl = sc.userAttribDecl;
3203
3204 if (sc.linkage == LINK.cpp)
3205 cldec.classKind = ClassKind.cpp;
3206 cldec.cppnamespace = sc.namespace;
3207 cldec.cppmangle = sc.cppmangle;
3208 if (sc.linkage == LINK.objc)
3209 objc.setObjc(cldec);
3210 }
3211 else if (cldec.symtab && !scx)
3212 {
3213 return;
3214 }
3215 cldec.semanticRun = PASS.semantic;
3216 checkGNUABITag(cldec, sc.linkage);
3217 checkMustUseReserved(cldec);
3218
3219 if (cldec.baseok < Baseok.done)
3220 {
3221 /* https://issues.dlang.org/show_bug.cgi?id=12078
3222 * https://issues.dlang.org/show_bug.cgi?id=12143
3223 * https://issues.dlang.org/show_bug.cgi?id=15733
3224 * While resolving base classes and interfaces, a base may refer
3225 * the member of this derived class. In that time, if all bases of
3226 * this class can be determined, we can go forward the semantc process
3227 * beyond the Lancestorsdone. To do the recursive semantic analysis,
3228 * temporarily set and unset `_scope` around exp().
3229 */
3230 T resolveBase(T)(lazy T exp)
3231 {
3232 if (!scx)
3233 {
3234 scx = sc.copy();
3235 scx.setNoFree();
3236 }
3237 static if (!is(T == void))
3238 {
3239 cldec._scope = scx;
3240 auto r = exp();
3241 cldec._scope = null;
3242 return r;
3243 }
3244 else
3245 {
3246 cldec._scope = scx;
3247 exp();
3248 cldec._scope = null;
3249 }
3250 }
3251
3252 cldec.baseok = Baseok.start;
3253
3254 // Expand any tuples in baseclasses[]
3255 for (size_t i = 0; i < cldec.baseclasses.length;)
3256 {
3257 auto b = (*cldec.baseclasses)[i];
3258 b.type = resolveBase(b.type.typeSemantic(cldec.loc, sc));
3259
3260 Type tb = b.type.toBasetype();
3261 if (auto tup = tb.isTypeTuple())
3262 {
3263 cldec.baseclasses.remove(i);
3264 size_t dim = Parameter.dim(tup.arguments);
3265 for (size_t j = 0; j < dim; j++)
3266 {
3267 Parameter arg = Parameter.getNth(tup.arguments, j);
3268 b = new BaseClass(arg.type);
3269 cldec.baseclasses.insert(i + j, b);
3270 }
3271 }
3272 else
3273 i++;
3274 }
3275
3276 if (cldec.baseok >= Baseok.done)
3277 {
3278 //printf("%s already semantic analyzed, semanticRun = %d\n", toChars(), semanticRun);
3279 if (cldec.semanticRun >= PASS.semanticdone)
3280 return;
3281 goto Lancestorsdone;
3282 }
3283
3284 // See if there's a base class as first in baseclasses[]
3285 if (cldec.baseclasses.length)
3286 {
3287 BaseClass* b = (*cldec.baseclasses)[0];
3288 Type tb = b.type.toBasetype();
3289 TypeClass tc = tb.isTypeClass();
3290 if (!tc)
3291 {
3292 if (b.type != Type.terror)
3293 .error(cldec.loc, "%s `%s` base type must be `class` or `interface`, not `%s`", cldec.kind, cldec.toPrettyChars, b.type.toChars());
3294 cldec.baseclasses.remove(0);
3295 goto L7;
3296 }
3297 if (tc.sym.isDeprecated())
3298 {
3299 if (!cldec.isDeprecated())
3300 {
3301 // Deriving from deprecated class makes this one deprecated too
3302 cldec.setDeprecated();
3303 tc.checkDeprecated(cldec.loc, sc);
3304 }
3305 }
3306 if (tc.sym.isInterfaceDeclaration())
3307 goto L7;
3308
3309 for (ClassDeclaration cdb = tc.sym; cdb; cdb = cdb.baseClass)
3310 {
3311 if (cdb == cldec)
3312 {
3313 .error(cldec.loc, "%s `%s` circular inheritance", cldec.kind, cldec.toPrettyChars);
3314 cldec.baseclasses.remove(0);
3315 goto L7;
3316 }
3317 }
3318
3319 /* https://issues.dlang.org/show_bug.cgi?id=11034
3320 * Class inheritance hierarchy
3321 * and instance size of each classes are orthogonal information.
3322 * Therefore, even if tc.sym.sizeof == Sizeok.none,
3323 * we need to set baseClass field for class covariance check.
3324 */
3325 cldec.baseClass = tc.sym;
3326 b.sym = cldec.baseClass;
3327
3328 if (tc.sym.baseok < Baseok.done)
3329 resolveBase(tc.sym.dsymbolSemantic(null)); // Try to resolve forward reference
3330 if (tc.sym.baseok < Baseok.done)
3331 {
3332 //printf("\ttry later, forward reference of base class %s\n", tc.sym.toChars());
3333 if (tc.sym._scope)
3334 Module.addDeferredSemantic(tc.sym);
3335 cldec.baseok = Baseok.none;
3336 }
3337 L7:
3338 }
3339
3340 // Treat the remaining entries in baseclasses as interfaces
3341 // Check for errors, handle forward references
3342 int multiClassError = cldec.baseClass is null ? 0 : 1;
3343
3344 BCLoop:
3345 for (size_t i = (cldec.baseClass ? 1 : 0); i < cldec.baseclasses.length;)
3346 {
3347 BaseClass* b = (*cldec.baseclasses)[i];
3348 Type tb = b.type.toBasetype();
3349 TypeClass tc = tb.isTypeClass();
3350 if (!tc || !tc.sym.isInterfaceDeclaration())
3351 {
3352 // It's a class
3353 if (tc)
3354 {
3355 if (multiClassError == 0)
3356 {
3357 .error(cldec.loc,"`%s`: base class must be specified first, " ~
3358 "before any interfaces.", cldec.toPrettyChars());
3359 multiClassError += 1;
3360 }
3361 else if (multiClassError >= 1)
3362 {
3363 if(multiClassError == 1)
3364 .error(cldec.loc, "`%s`: multiple class inheritance is not supported." ~
3365 " Use multiple interface inheritance and/or composition.", cldec.toPrettyChars());
3366 multiClassError += 1;
3367
3368 if (tc.sym.fields.length)
3369 errorSupplemental(cldec.loc,"`%s` has fields, consider making it a member of `%s`",
3370 b.type.toChars(), cldec.type.toChars());
3371 else
3372 errorSupplemental(cldec.loc,"`%s` has no fields, consider making it an `interface`",
3373 b.type.toChars());
3374 }
3375 }
3376 // It's something else: e.g. `int` in `class Foo : Bar, int { ... }`
3377 else if (b.type != Type.terror)
3378 {
3379 error(cldec.loc,"`%s`: base type must be `interface`, not `%s`",
3380 cldec.toPrettyChars(), b.type.toChars());
3381 }
3382 cldec.baseclasses.remove(i);
3383 continue;
3384 }
3385
3386 // Check for duplicate interfaces
3387 for (size_t j = (cldec.baseClass ? 1 : 0); j < i; j++)
3388 {
3389 BaseClass* b2 = (*cldec.baseclasses)[j];
3390 if (b2.sym == tc.sym)
3391 {
3392 .error(cldec.loc, "%s `%s` inherits from duplicate interface `%s`", cldec.kind, cldec.toPrettyChars, b2.sym.toChars());
3393 cldec.baseclasses.remove(i);
3394 continue BCLoop;
3395 }
3396 }
3397 if (tc.sym.isDeprecated())
3398 {
3399 if (!cldec.isDeprecated())
3400 {
3401 // Deriving from deprecated class makes this one deprecated too
3402 cldec.setDeprecated();
3403 tc.checkDeprecated(cldec.loc, sc);
3404 }
3405 }
3406
3407 b.sym = tc.sym;
3408
3409 if (tc.sym.baseok < Baseok.done)
3410 resolveBase(tc.sym.dsymbolSemantic(null)); // Try to resolve forward reference
3411 if (tc.sym.baseok < Baseok.done)
3412 {
3413 //printf("\ttry later, forward reference of base %s\n", tc.sym.toChars());
3414 if (tc.sym._scope)
3415 Module.addDeferredSemantic(tc.sym);
3416 cldec.baseok = Baseok.none;
3417 }
3418 i++;
3419 }
3420 if (cldec.baseok == Baseok.none)
3421 {
3422 // Forward referencee of one or more bases, try again later
3423 //printf("\tL%d semantic('%s') failed due to forward references\n", __LINE__, toChars());
3424 return deferDsymbolSemantic(sc, cldec, scx);
3425 }
3426 cldec.baseok = Baseok.done;
3427
3428 if (cldec.classKind == ClassKind.objc || (cldec.baseClass && cldec.baseClass.classKind == ClassKind.objc))
3429 cldec.classKind = ClassKind.objc; // Objective-C classes do not inherit from Object
3430
3431 // If no base class, and this is not an Object, use Object as base class
3432 if (!cldec.baseClass && cldec.ident != Id.Object && cldec.object && cldec.classKind == ClassKind.d)
3433 {
3434 void badObjectDotD()
3435 {
3436 ObjectNotFound(cldec.loc, cldec.ident);
3437 }
3438
3439 if (!cldec.object || cldec.object.errors)
3440 badObjectDotD();
3441
3442 Type t = cldec.object.type;
3443 t = t.typeSemantic(cldec.loc, sc).toBasetype();
3444 if (t.ty == Terror)
3445 badObjectDotD();
3446 TypeClass tc = t.isTypeClass();
3447 assert(tc);
3448
3449 auto b = new BaseClass(tc);
3450 cldec.baseclasses.shift(b);
3451
3452 cldec.baseClass = tc.sym;
3453 assert(!cldec.baseClass.isInterfaceDeclaration());
3454 b.sym = cldec.baseClass;
3455 }
3456 if (cldec.baseClass)
3457 {
3458 if (cldec.baseClass.storage_class & STC.final_)
3459 .error(cldec.loc, "%s `%s` cannot inherit from class `%s` because it is `final`", cldec.kind, cldec.toPrettyChars, cldec.baseClass.toChars());
3460
3461 // Inherit properties from base class
3462 if (cldec.baseClass.isCOMclass())
3463 cldec.com = true;
3464 if (cldec.baseClass.isCPPclass())
3465 cldec.classKind = ClassKind.cpp;
3466 if (cldec.classKind != cldec.baseClass.classKind)
3467 .error(cldec.loc, "%s `%s` with %s linkage cannot inherit from class `%s` with %s linkage", cldec.kind, cldec.toPrettyChars,
3468 ClassKindToChars(cldec.classKind), cldec.baseClass.toChars(), ClassKindToChars(cldec.baseClass.classKind));
3469
3470 if (cldec.baseClass.stack)
3471 cldec.stack = true;
3472 cldec.enclosing = cldec.baseClass.enclosing;
3473 cldec.storage_class |= cldec.baseClass.storage_class & STC.TYPECTOR;
3474 }
3475
3476 cldec.interfaces = cldec.baseclasses.tdata()[(cldec.baseClass ? 1 : 0) .. cldec.baseclasses.length];
3477 foreach (b; cldec.interfaces)
3478 {
3479 // If this is an interface, and it derives from a COM interface,
3480 // then this is a COM interface too.
3481 if (b.sym.isCOMinterface())
3482 cldec.com = true;
3483 if (cldec.classKind == ClassKind.cpp && !b.sym.isCPPinterface())
3484 {
3485 .error(cldec.loc, "C++ class `%s` cannot implement D interface `%s`",
3486 cldec.toPrettyChars(), b.sym.toPrettyChars());
3487 }
3488 }
3489 interfaceSemantic(cldec);
3490 }
3491 Lancestorsdone:
3492 //printf("\tClassDeclaration.dsymbolSemantic(%s) baseok = %d\n", toChars(), baseok);
3493
3494 if (!cldec.members) // if opaque declaration
3495 {
3496 cldec.semanticRun = PASS.semanticdone;
3497 return;
3498 }
3499 if (!cldec.symtab)
3500 {
3501 cldec.symtab = new DsymbolTable();
3502
3503 /* https://issues.dlang.org/show_bug.cgi?id=12152
3504 * The semantic analysis of base classes should be finished
3505 * before the members semantic analysis of this class, in order to determine
3506 * vtbl in this class. However if a base class refers the member of this class,
3507 * it can be resolved as a normal forward reference.
3508 * Call addMember() and setScope() to make this class members visible from the base classes.
3509 */
3510 cldec.members.foreachDsymbol( s => s.addMember(sc, cldec) );
3511
3512 auto sc2 = cldec.newScope(sc);
3513
3514 /* Set scope so if there are forward references, we still might be able to
3515 * resolve individual members like enums.
3516 */
3517 cldec.members.foreachDsymbol( s => s.setScope(sc2) );
3518
3519 sc2.pop();
3520 }
3521
3522 for (size_t i = 0; i < cldec.baseclasses.length; i++)
3523 {
3524 BaseClass* b = (*cldec.baseclasses)[i];
3525 Type tb = b.type.toBasetype();
3526 TypeClass tc = tb.isTypeClass();
3527 if (tc.sym.semanticRun < PASS.semanticdone)
3528 {
3529 // Forward referencee of one or more bases, try again later
3530 if (tc.sym._scope)
3531 Module.addDeferredSemantic(tc.sym);
3532 //printf("\tL%d semantic('%s') failed due to forward references\n", __LINE__, toChars());
3533 return deferDsymbolSemantic(sc, cldec, scx);
3534 }
3535 }
3536
3537 if (cldec.baseok == Baseok.done)
3538 {
3539 cldec.baseok = Baseok.semanticdone;
3540 objc.setMetaclass(cldec, sc);
3541
3542 // initialize vtbl
3543 if (cldec.baseClass)
3544 {
3545 if (cldec.classKind == ClassKind.cpp && cldec.baseClass.vtbl.length == 0)
3546 {
3547 .error(cldec.loc, "%s `%s` C++ base class `%s` needs at least one virtual function", cldec.kind, cldec.toPrettyChars, cldec.baseClass.toChars());
3548 }
3549
3550 // Copy vtbl[] from base class
3551 assert(cldec.vtbl.length == 0);
3552 cldec.vtbl.setDim(cldec.baseClass.vtbl.length);
3553 memcpy(cldec.vtbl.tdata(), cldec.baseClass.vtbl.tdata(), (void*).sizeof * cldec.vtbl.length);
3554
3555 cldec.vthis = cldec.baseClass.vthis;
3556 cldec.vthis2 = cldec.baseClass.vthis2;
3557 }
3558 else
3559 {
3560 // No base class, so this is the root of the class hierarchy
3561 cldec.vtbl.setDim(0);
3562 if (cldec.vtblOffset())
3563 cldec.vtbl.push(cldec); // leave room for classinfo as first member
3564 }
3565
3566 /* If this is a nested class, add the hidden 'this'
3567 * member which is a pointer to the enclosing scope.
3568 */
3569 if (cldec.vthis) // if inheriting from nested class
3570 {
3571 // Use the base class's 'this' member
3572 if (cldec.storage_class & STC.static_)
3573 .error(cldec.loc, "%s `%s` static class cannot inherit from nested class `%s`", cldec.kind, cldec.toPrettyChars, cldec.baseClass.toChars());
3574 if (cldec.toParentLocal() != cldec.baseClass.toParentLocal() &&
3575 (!cldec.toParentLocal() ||
3576 !cldec.baseClass.toParentLocal().getType() ||
3577 !cldec.baseClass.toParentLocal().getType().isBaseOf(cldec.toParentLocal().getType(), null)))
3578 {
3579 if (cldec.toParentLocal())
3580 {
3581 .error(cldec.loc, "%s `%s` is nested within `%s`, but super class `%s` is nested within `%s`", cldec.kind, cldec.toPrettyChars,
3582 cldec.toParentLocal().toChars(),
3583 cldec.baseClass.toChars(),
3584 cldec.baseClass.toParentLocal().toChars());
3585 }
3586 else
3587 {
3588 .error(cldec.loc, "%s `%s` is not nested, but super class `%s` is nested within `%s`", cldec.kind, cldec.toPrettyChars,
3589 cldec.baseClass.toChars(),
3590 cldec.baseClass.toParentLocal().toChars());
3591 }
3592 }
3593 if (cldec.vthis2)
3594 {
3595 if (cldec.toParent2() != cldec.baseClass.toParent2() &&
3596 (!cldec.toParent2() ||
3597 !cldec.baseClass.toParent2().getType() ||
3598 !cldec.baseClass.toParent2().getType().isBaseOf(cldec.toParent2().getType(), null)))
3599 {
3600 if (cldec.toParent2() && cldec.toParent2() != cldec.toParentLocal())
3601 {
3602 .error(cldec.loc, "%s `%s` needs the frame pointer of `%s`, but super class `%s` needs the frame pointer of `%s`", cldec.kind, cldec.toPrettyChars,
3603 cldec.toParent2().toChars(),
3604 cldec.baseClass.toChars(),
3605 cldec.baseClass.toParent2().toChars());
3606 }
3607 else
3608 {
3609 .error(cldec.loc, "%s `%s` doesn't need a frame pointer, but super class `%s` needs the frame pointer of `%s`", cldec.kind, cldec.toPrettyChars,
3610 cldec.baseClass.toChars(),
3611 cldec.baseClass.toParent2().toChars());
3612 }
3613 }
3614 }
3615 else
3616 cldec.makeNested2();
3617 }
3618 else
3619 cldec.makeNested();
3620 }
3621
3622 auto sc2 = cldec.newScope(sc);
3623
3624 cldec.members.foreachDsymbol( s => s.importAll(sc2) );
3625
3626 // Note that members.length can grow due to tuple expansion during semantic()
3627 cldec.members.foreachDsymbol( s => s.dsymbolSemantic(sc2) );
3628
3629 if (!cldec.determineFields())
3630 {
3631 assert(cldec.type == Type.terror);
3632 sc2.pop();
3633 return;
3634 }
3635 /* Following special member functions creation needs semantic analysis
3636 * completion of sub-structs in each field types.
3637 */
3638 foreach (v; cldec.fields)
3639 {
3640 Type tb = v.type.baseElemOf();
3641 if (tb.ty != Tstruct)
3642 continue;
3643 auto sd = (cast(TypeStruct)tb).sym;
3644 if (sd.semanticRun >= PASS.semanticdone)
3645 continue;
3646
3647 sc2.pop();
3648
3649 //printf("\tdeferring %s\n", toChars());
3650 return deferDsymbolSemantic(sc, cldec, scx);
3651 }
3652
3653 /* Look for special member functions.
3654 * They must be in this class, not in a base class.
3655 */
3656 // Can be in base class
3657 cldec.disableNew = cldec.search(Loc.initial, Id.classNew) !is null;
3658
3659 // Look for the constructor
3660 cldec.ctor = cldec.searchCtor();
3661
3662 if (!cldec.ctor && cldec.noDefaultCtor)
3663 {
3664 // A class object is always created by constructor, so this check is legitimate.
3665 foreach (v; cldec.fields)
3666 {
3667 if (v.storage_class & STC.nodefaultctor)
3668 error(v.loc, "field `%s` must be initialized in constructor", v.toChars());
3669 }
3670 }
3671
3672 // If this class has no constructor, but base class has a default
3673 // ctor, create a constructor:
3674 // this() { }
3675 if (!cldec.ctor && cldec.baseClass && cldec.baseClass.ctor)
3676 {
3677 auto fd = resolveFuncCall(cldec.loc, sc2, cldec.baseClass.ctor, null, cldec.type, ArgumentList(), FuncResolveFlag.quiet);
3678 if (!fd) // try shared base ctor instead
3679 fd = resolveFuncCall(cldec.loc, sc2, cldec.baseClass.ctor, null, cldec.type.sharedOf, ArgumentList(), FuncResolveFlag.quiet);
3680 if (fd && !fd.errors)
3681 {
3682 //printf("Creating default this(){} for class %s\n", toChars());
3683 auto btf = fd.type.toTypeFunction();
3684 auto tf = new TypeFunction(ParameterList(), null, LINK.d, fd.storage_class);
3685 tf.mod = btf.mod;
3686 // Don't copy @safe, ... from the base class constructor and let it be inferred instead
3687 // This is required if other lowerings add code to the generated constructor which
3688 // is less strict (e.g. `preview=dtorfields` might introduce a call to a less qualified dtor)
3689
3690 auto ctor = new CtorDeclaration(cldec.loc, Loc.initial, STC.none, tf);
3691 ctor.storage_class |= STC.inference | (fd.storage_class & STC.scope_);
3692 ctor.isGenerated = true;
3693 ctor.fbody = new CompoundStatement(Loc.initial, new Statements());
3694
3695 cldec.members.push(ctor);
3696 ctor.addMember(sc, cldec);
3697 ctor.dsymbolSemantic(sc2);
3698
3699 cldec.ctor = ctor;
3700 cldec.defaultCtor = ctor;
3701 }
3702 else
3703 {
3704 .error(cldec.loc, "%s `%s` cannot implicitly generate a default constructor when base class `%s` is missing a default constructor", cldec.kind, cldec.toPrettyChars,
3705 cldec.baseClass.toPrettyChars());
3706 }
3707 }
3708
3709 buildDtors(cldec, sc2);
3710
3711 if (cldec.classKind == ClassKind.cpp && cldec.cppDtorVtblIndex != -1)
3712 {
3713 // now we've built the aggregate destructor, we'll make it virtual and assign it to the reserved vtable slot
3714 cldec.dtor.vtblIndex = cldec.cppDtorVtblIndex;
3715 cldec.vtbl[cldec.cppDtorVtblIndex] = cldec.dtor;
3716
3717 if (target.cpp.twoDtorInVtable)
3718 {
3719 // TODO: create a C++ compatible deleting destructor (call out to `operator delete`)
3720 // for the moment, we'll call the non-deleting destructor and leak
3721 cldec.vtbl[cldec.cppDtorVtblIndex + 1] = cldec.dtor;
3722 }
3723 }
3724
3725 if (auto f = hasIdentityOpAssign(cldec, sc2))
3726 {
3727 if (!(f.storage_class & STC.disable))
3728 .error(f.loc, "%s `%s` identity assignment operator overload is illegal", cldec.kind, cldec.toPrettyChars);
3729 }
3730
3731 cldec.inv = buildInv(cldec, sc2);
3732
3733 cldec.semanticRun = PASS.semanticdone;
3734 //printf("-ClassDeclaration.dsymbolSemantic(%s), type = %p\n", toChars(), type);
3735
3736 sc2.pop();
3737
3738 /* isAbstract() is undecidable in some cases because of circular dependencies.
3739 * Now that semantic is finished, get a definitive result, and error if it is not the same.
3740 */
3741 if (cldec.isabstract != ThreeState.none) // if evaluated it before completion
3742 {
3743 const isabstractsave = cldec.isabstract;
3744 cldec.isabstract = ThreeState.none;
3745 cldec.isAbstract(); // recalculate
3746 if (cldec.isabstract != isabstractsave)
3747 {
3748 .error(cldec.loc, "%s `%s` cannot infer `abstract` attribute due to circular dependencies", cldec.kind, cldec.toPrettyChars);
3749 }
3750 }
3751
3752 if (cldec.type.ty == Tclass && (cast(TypeClass)cldec.type).sym != cldec)
3753 {
3754 // https://issues.dlang.org/show_bug.cgi?id=17492
3755 ClassDeclaration cd = (cast(TypeClass)cldec.type).sym;
3756 version (none)
3757 {
3758 printf("this = %p %s\n", cldec, cldec.toPrettyChars());
3759 printf("type = %d sym = %p, %s\n", cldec.type.ty, cd, cd.toPrettyChars());
3760 }
3761 .error(cldec.loc, "%s `%s` already exists at %s. Perhaps in another function with the same name?", cldec.kind, cldec.toPrettyChars, cd.loc.toChars());
3762 }
3763
3764 if (global.errors != errors || (cldec.baseClass && cldec.baseClass.errors))
3765 {
3766 // The type is no good, but we should keep the
3767 // the type so that we have more accurate error messages
3768 // See: https://issues.dlang.org/show_bug.cgi?id=23552
3769 cldec.errors = true;
3770 if (cldec.deferred)
3771 cldec.deferred.errors = true;
3772 }
3773
3774 // Verify fields of a synchronized class are not public
3775 if (cldec.storage_class & STC.synchronized_)
3776 {
3777 foreach (vd; cldec.fields)
3778 {
3779 if (!vd.isThisDeclaration() &&
3780 vd.visible() >= Visibility(Visibility.Kind.public_))
3781 {
3782 .error(vd.loc, "%s `%s` Field members of a `synchronized` class cannot be `%s`", vd.kind, vd.toPrettyChars,
3783 visibilityToChars(vd.visible().kind));
3784 }
3785 }
3786 }
3787
3788 if (cldec.deferred && !global.gag)
3789 {
3790 cldec.deferred.semantic2(sc);
3791 cldec.deferred.semantic3(sc);
3792 }
3793 //printf("-ClassDeclaration.dsymbolSemantic(%s), type = %p, sizeok = %d, this = %p\n", toChars(), type, sizeok, this);
3794
3795 version (none)
3796 {
3797 // @@@DEPRECATED_2.110@@@ https://dlang.org/deprecate.html#scope%20as%20a%20type%20constraint
3798 // Deprecated in 2.100
3799 // Make an error in 2.110
3800 // Don't forget to remove code at https://github.com/dlang/dmd/blob/b2f8274ba76358607fc3297a1e9f361480f9bcf9/src/dmd/dsymbolsem.d#L1032-L1036
3801 if (cldec.storage_class & STC.scope_)
3802 deprecation(cldec.loc, "`scope` as a type constraint is deprecated. Use `scope` at the usage site.");
3803 }
3804 }
3805
3806 override void visit(InterfaceDeclaration idec)
3807 {
3808 /// Returns: `true` is this is an anonymous Objective-C metaclass
3809 static bool isAnonymousMetaclass(InterfaceDeclaration idec)
3810 {
3811 return idec.classKind == ClassKind.objc &&
3812 idec.objc.isMeta &&
3813 idec.isAnonymous;
3814 }
3815
3816 //printf("InterfaceDeclaration.dsymbolSemantic(%s), type = %p\n", toChars(), type);
3817 if (idec.semanticRun >= PASS.semanticdone)
3818 return;
3819 const errors = global.errors;
3820
3821 //printf("+InterfaceDeclaration.dsymbolSemantic(%s), type = %p\n", toChars(), type);
3822
3823 Scope* scx = null;
3824 if (idec._scope)
3825 {
3826 sc = idec._scope;
3827 scx = idec._scope; // save so we don't make redundant copies
3828 idec._scope = null;
3829 }
3830
3831 if (!idec.parent)
3832 {
3833 assert(sc.parent && sc.func);
3834 idec.parent = sc.parent;
3835 }
3836 // Objective-C metaclasses are anonymous
3837 assert(idec.parent && !idec.isAnonymous || isAnonymousMetaclass(idec));
3838
3839 if (idec.errors)
3840 idec.type = Type.terror;
3841 idec.type = idec.type.typeSemantic(idec.loc, sc);
3842 if (idec.type.ty == Tclass && (cast(TypeClass)idec.type).sym != idec)
3843 {
3844 auto ti = (cast(TypeClass)idec.type).sym.isInstantiated();
3845 if (ti && isError(ti))
3846 (cast(TypeClass)idec.type).sym = idec;
3847 }
3848
3849 // Ungag errors when not speculative
3850 Ungag ungag = idec.ungagSpeculative();
3851
3852 if (idec.semanticRun == PASS.initial)
3853 {
3854 idec.visibility = sc.visibility;
3855
3856 idec.storage_class |= sc.stc;
3857 idec.userAttribDecl = sc.userAttribDecl;
3858 }
3859 else if (idec.symtab)
3860 {
3861 if (idec.sizeok == Sizeok.done || !scx)
3862 {
3863 idec.semanticRun = PASS.semanticdone;
3864 return;
3865 }
3866 }
3867 idec.semanticRun = PASS.semantic;
3868
3869 if (idec.baseok < Baseok.done)
3870 {
3871 T resolveBase(T)(lazy T exp)
3872 {
3873 if (!scx)
3874 {
3875 scx = sc.copy();
3876 scx.setNoFree();
3877 }
3878 static if (!is(T == void))
3879 {
3880 idec._scope = scx;
3881 auto r = exp();
3882 idec._scope = null;
3883 return r;
3884 }
3885 else
3886 {
3887 idec._scope = scx;
3888 exp();
3889 idec._scope = null;
3890 }
3891 }
3892
3893 idec.baseok = Baseok.start;
3894
3895 // Expand any tuples in baseclasses[]
3896 for (size_t i = 0; i < idec.baseclasses.length;)
3897 {
3898 auto b = (*idec.baseclasses)[i];
3899 b.type = resolveBase(b.type.typeSemantic(idec.loc, sc));
3900
3901 Type tb = b.type.toBasetype();
3902 if (auto tup = tb.isTypeTuple())
3903 {
3904 idec.baseclasses.remove(i);
3905 size_t dim = Parameter.dim(tup.arguments);
3906 for (size_t j = 0; j < dim; j++)
3907 {
3908 Parameter arg = Parameter.getNth(tup.arguments, j);
3909 b = new BaseClass(arg.type);
3910 idec.baseclasses.insert(i + j, b);
3911 }
3912 }
3913 else
3914 i++;
3915 }
3916
3917 if (idec.baseok >= Baseok.done)
3918 {
3919 //printf("%s already semantic analyzed, semanticRun = %d\n", toChars(), semanticRun);
3920 if (idec.semanticRun >= PASS.semanticdone)
3921 return;
3922 goto Lancestorsdone;
3923 }
3924
3925 if (!idec.baseclasses.length && sc.linkage == LINK.cpp)
3926 idec.classKind = ClassKind.cpp;
3927 idec.cppnamespace = sc.namespace;
3928 checkGNUABITag(idec, sc.linkage);
3929 checkMustUseReserved(idec);
3930
3931 if (sc.linkage == LINK.objc)
3932 objc.setObjc(idec);
3933
3934 // Check for errors, handle forward references
3935 BCLoop:
3936 for (size_t i = 0; i < idec.baseclasses.length;)
3937 {
3938 BaseClass* b = (*idec.baseclasses)[i];
3939 Type tb = b.type.toBasetype();
3940 TypeClass tc = (tb.ty == Tclass) ? cast(TypeClass)tb : null;
3941 if (!tc || !tc.sym.isInterfaceDeclaration())
3942 {
3943 if (b.type != Type.terror)
3944 .error(idec.loc, "%s `%s` base type must be `interface`, not `%s`", idec.kind, idec.toPrettyChars, b.type.toChars());
3945 idec.baseclasses.remove(i);
3946 continue;
3947 }
3948
3949 // Check for duplicate interfaces
3950 for (size_t j = 0; j < i; j++)
3951 {
3952 BaseClass* b2 = (*idec.baseclasses)[j];
3953 if (b2.sym == tc.sym)
3954 {
3955 .error(idec.loc, "%s `%s` inherits from duplicate interface `%s`", idec.kind, idec.toPrettyChars, b2.sym.toChars());
3956 idec.baseclasses.remove(i);
3957 continue BCLoop;
3958 }
3959 }
3960 if (tc.sym == idec || idec.isBaseOf2(tc.sym))
3961 {
3962 .error(idec.loc, "%s `%s` circular inheritance of interface", idec.kind, idec.toPrettyChars);
3963 idec.baseclasses.remove(i);
3964 continue;
3965 }
3966 if (tc.sym.isDeprecated())
3967 {
3968 if (!idec.isDeprecated())
3969 {
3970 // Deriving from deprecated interface makes this one deprecated too
3971 idec.setDeprecated();
3972 tc.checkDeprecated(idec.loc, sc);
3973 }
3974 }
3975
3976 b.sym = tc.sym;
3977
3978 if (tc.sym.baseok < Baseok.done)
3979 resolveBase(tc.sym.dsymbolSemantic(null)); // Try to resolve forward reference
3980 if (tc.sym.baseok < Baseok.done)
3981 {
3982 //printf("\ttry later, forward reference of base %s\n", tc.sym.toChars());
3983 if (tc.sym._scope)
3984 Module.addDeferredSemantic(tc.sym);
3985 idec.baseok = Baseok.none;
3986 }
3987 i++;
3988 }
3989 if (idec.baseok == Baseok.none)
3990 {
3991 // Forward referencee of one or more bases, try again later
3992 return deferDsymbolSemantic(sc, idec, scx);
3993 }
3994 idec.baseok = Baseok.done;
3995
3996 idec.interfaces = idec.baseclasses.tdata()[0 .. idec.baseclasses.length];
3997 foreach (b; idec.interfaces)
3998 {
3999 // If this is an interface, and it derives from a COM interface,
4000 // then this is a COM interface too.
4001 if (b.sym.isCOMinterface())
4002 idec.com = true;
4003 if (b.sym.isCPPinterface())
4004 idec.classKind = ClassKind.cpp;
4005 }
4006
4007 interfaceSemantic(idec);
4008 }
4009 Lancestorsdone:
4010
4011 if (!idec.members) // if opaque declaration
4012 {
4013 idec.semanticRun = PASS.semanticdone;
4014 return;
4015 }
4016 if (!idec.symtab)
4017 idec.symtab = new DsymbolTable();
4018
4019 for (size_t i = 0; i < idec.baseclasses.length; i++)
4020 {
4021 BaseClass* b = (*idec.baseclasses)[i];
4022 Type tb = b.type.toBasetype();
4023 TypeClass tc = tb.isTypeClass();
4024 if (tc.sym.semanticRun < PASS.semanticdone)
4025 {
4026 // Forward referencee of one or more bases, try again later
4027 if (tc.sym._scope)
4028 Module.addDeferredSemantic(tc.sym);
4029 return deferDsymbolSemantic(sc, idec, scx);
4030 }
4031 }
4032
4033 if (idec.baseok == Baseok.done)
4034 {
4035 idec.baseok = Baseok.semanticdone;
4036 objc.setMetaclass(idec, sc);
4037
4038 // initialize vtbl
4039 if (idec.vtblOffset())
4040 idec.vtbl.push(idec); // leave room at vtbl[0] for classinfo
4041
4042 // Cat together the vtbl[]'s from base interfaces
4043 foreach (i, b; idec.interfaces)
4044 {
4045 // Skip if b has already appeared
4046 for (size_t k = 0; k < i; k++)
4047 {
4048 if (b == idec.interfaces[k])
4049 goto Lcontinue;
4050 }
4051
4052 // Copy vtbl[] from base class
4053 if (b.sym.vtblOffset())
4054 {
4055 size_t d = b.sym.vtbl.length;
4056 if (d > 1)
4057 {
4058 idec.vtbl.pushSlice(b.sym.vtbl[1 .. d]);
4059 }
4060 }
4061 else
4062 {
4063 idec.vtbl.append(&b.sym.vtbl);
4064 }
4065
4066 Lcontinue:
4067 }
4068 }
4069
4070 idec.members.foreachDsymbol( s => s.addMember(sc, idec) );
4071
4072 auto sc2 = idec.newScope(sc);
4073
4074 /* Set scope so if there are forward references, we still might be able to
4075 * resolve individual members like enums.
4076 */
4077 idec.members.foreachDsymbol( s => s.setScope(sc2) );
4078
4079 idec.members.foreachDsymbol( s => s.importAll(sc2) );
4080
4081 idec.members.foreachDsymbol( s => s.dsymbolSemantic(sc2) );
4082
4083 idec.semanticRun = PASS.semanticdone;
4084 //printf("-InterfaceDeclaration.dsymbolSemantic(%s), type = %p\n", toChars(), type);
4085
4086 sc2.pop();
4087
4088 if (global.errors != errors)
4089 {
4090 // The type is no good.
4091 idec.type = Type.terror;
4092 }
4093
4094 version (none)
4095 {
4096 if (type.ty == Tclass && (cast(TypeClass)idec.type).sym != idec)
4097 {
4098 printf("this = %p %s\n", idec, idec.toChars());
4099 printf("type = %d sym = %p\n", idec.type.ty, (cast(TypeClass)idec.type).sym);
4100 }
4101 }
4102 assert(idec.type.ty != Tclass || (cast(TypeClass)idec.type).sym == idec);
4103
4104 version (none)
4105 {
4106 // @@@DEPRECATED_2.120@@@ https://dlang.org/deprecate.html#scope%20as%20a%20type%20constraint
4107 // Deprecated in 2.087
4108 // Made an error in 2.100, but removal depends on `scope class` being removed too
4109 // Don't forget to remove code at https://github.com/dlang/dmd/blob/b2f8274ba76358607fc3297a1e9f361480f9bcf9/src/dmd/dsymbolsem.d#L1032-L1036
4110 if (idec.storage_class & STC.scope_)
4111 error(idec.loc, "`scope` as a type constraint is obsolete. Use `scope` at the usage site.");
4112 }
4113 }
4114 }
4115
4116 /*
4117 Adds dsym as a member of scope sds.
4118
4119 Params:
4120 dsym = dsymbol to inserted
4121 sc = scope where the dsymbol is declared
4122 sds = ScopeDsymbol where dsym is inserted
4123 */
4124 void addMember(Dsymbol dsym, Scope* sc, ScopeDsymbol sds)
4125 {
4126 auto addMemberVisitor = new AddMemberVisitor(sc, sds);
4127 dsym.accept(addMemberVisitor);
4128 }
4129
4130 private void attribAddMember(AttribDeclaration atb, Scope* sc, ScopeDsymbol sds)
4131 {
4132 Dsymbols* d = atb.include(sc);
4133 if (d)
4134 {
4135 Scope* sc2 = atb.newScope(sc);
4136 d.foreachDsymbol( s => s.addMember(sc2, sds) );
4137 if (sc2 != sc)
4138 sc2.pop();
4139 }
4140 }
4141
4142 private extern(C++) class AddMemberVisitor : Visitor
4143 {
4144 alias visit = Visitor.visit;
4145
4146 Scope* sc;
4147 ScopeDsymbol sds;
4148
4149 this(Scope* sc, ScopeDsymbol sds) @safe
4150 {
4151 this.sc = sc;
4152 this.sds = sds;
4153 }
4154
4155 override void visit(Dsymbol dsym)
4156 {
4157 //printf("Dsymbol::addMember('%s')\n", toChars());
4158 //printf("Dsymbol::addMember(this = %p, '%s' scopesym = '%s')\n", this, toChars(), sds.toChars());
4159 //printf("Dsymbol::addMember(this = %p, '%s' sds = %p, sds.symtab = %p)\n", this, toChars(), sds, sds.symtab);
4160 dsym.parent = sds;
4161 if (dsym.isAnonymous()) // no name, so can't add it to symbol table
4162 return;
4163
4164 if (!sds.symtabInsert(dsym)) // if name is already defined
4165 {
4166 if (dsym.isAliasDeclaration() && !dsym._scope)
4167 dsym.setScope(sc);
4168 Dsymbol s2 = sds.symtabLookup(dsym, dsym.ident);
4169 /* https://issues.dlang.org/show_bug.cgi?id=17434
4170 *
4171 * If we are trying to add an import to the symbol table
4172 * that has already been introduced, then keep the one with
4173 * larger visibility. This is fine for imports because if
4174 * we have multiple imports of the same file, if a single one
4175 * is public then the symbol is reachable.
4176 */
4177 if (auto i1 = dsym.isImport())
4178 {
4179 if (auto i2 = s2.isImport())
4180 {
4181 if (sc.explicitVisibility && sc.visibility > i2.visibility)
4182 sds.symtab.update(dsym);
4183 }
4184 }
4185
4186 // If using C tag/prototype/forward declaration rules
4187 if (sc && sc.inCfile && !dsym.isImport())
4188 // When merging master, replace with: if (sc && sc.inCfile && !dsym.isImport())
4189 {
4190 if (handleTagSymbols(*sc, dsym, s2, sds))
4191 return;
4192 if (handleSymbolRedeclarations(*sc, dsym, s2, sds))
4193 return;
4194
4195 sds.multiplyDefined(Loc.initial, dsym, s2); // ImportC doesn't allow overloading
4196 dsym.errors = true;
4197 return;
4198 }
4199
4200 if (!s2.overloadInsert(dsym))
4201 {
4202 sds.multiplyDefined(Loc.initial, dsym, s2);
4203 dsym.errors = true;
4204 }
4205 }
4206 if (sds.isAggregateDeclaration() || sds.isEnumDeclaration())
4207 {
4208 if (dsym.ident == Id.__sizeof ||
4209 !(sc && sc.inCfile) && (dsym.ident == Id.__xalignof || dsym.ident == Id._mangleof))
4210 {
4211 .error(dsym.loc, "%s `%s` `.%s` property cannot be redefined", dsym.kind, dsym.toPrettyChars, dsym.ident.toChars());
4212 dsym.errors = true;
4213 }
4214 }
4215 }
4216
4217
4218 override void visit(StaticAssert _)
4219 {
4220 // we didn't add anything
4221 }
4222
4223 /*****************************
4224 * Add import to sd's symbol table.
4225 */
4226 override void visit(Import imp)
4227 {
4228 //printf("Import.addMember(this=%s, sds=%s, sc=%p)\n", imp.toChars(), sds.toChars(), sc);
4229 if (imp.names.length == 0)
4230 return visit(cast(Dsymbol)imp);
4231 if (imp.aliasId)
4232 visit(cast(Dsymbol)imp);
4233
4234 /* Instead of adding the import to sds's symbol table,
4235 * add each of the alias=name pairs
4236 */
4237 for (size_t i = 0; i < imp.names.length; i++)
4238 {
4239 Identifier name = imp.names[i];
4240 Identifier _alias = imp.aliases[i];
4241 if (!_alias)
4242 _alias = name;
4243 auto tname = new TypeIdentifier(imp.loc, name);
4244 auto ad = new AliasDeclaration(imp.loc, _alias, tname);
4245 ad._import = imp;
4246 addMember(ad, sc, sds);
4247 imp.aliasdecls.push(ad);
4248 }
4249 }
4250
4251 override void visit(AttribDeclaration atb)
4252 {
4253 attribAddMember(atb, sc, sds);
4254 }
4255
4256 override void visit(StorageClassDeclaration stcd)
4257 {
4258 Dsymbols* d = stcd.include(sc);
4259 if (d)
4260 {
4261 Scope* sc2 = stcd.newScope(sc);
4262
4263 d.foreachDsymbol( (s)
4264 {
4265 //printf("\taddMember %s to %s\n", s.toChars(), sds.toChars());
4266 // STC.local needs to be attached before the member is added to the scope (because it influences the parent symbol)
4267 if (auto decl = s.isDeclaration())
4268 {
4269 decl.storage_class |= stcd.stc & STC.local;
4270 if (auto sdecl = s.isStorageClassDeclaration()) // TODO: why is this not enough to deal with the nested case?
4271 {
4272 sdecl.stc |= stcd.stc & STC.local;
4273 }
4274 }
4275 s.addMember(sc2, sds);
4276 });
4277
4278 if (sc2 != sc)
4279 sc2.pop();
4280 }
4281 }
4282
4283 override void visit(VisibilityDeclaration visd)
4284 {
4285 if (visd.pkg_identifiers)
4286 {
4287 Dsymbol tmp;
4288 Package.resolve(visd.pkg_identifiers, &tmp, null);
4289 visd.visibility.pkg = tmp ? tmp.isPackage() : null;
4290 visd.pkg_identifiers = null;
4291 }
4292 if (visd.visibility.kind == Visibility.Kind.package_ && visd.visibility.pkg && sc._module)
4293 {
4294 Module m = sc._module;
4295
4296 // https://issues.dlang.org/show_bug.cgi?id=17441
4297 // While isAncestorPackageOf does an equality check, the fix for the issue adds a check to see if
4298 // each package's .isModule() properites are equal.
4299 //
4300 // Properties generated from `package(foo)` i.e. visibility.pkg have .isModule() == null.
4301 // This breaks package declarations of the package in question if they are declared in
4302 // the same package.d file, which _do_ have a module associated with them, and hence a non-null
4303 // isModule()
4304 if (!m.isPackage() || !visd.visibility.pkg.ident.equals(m.isPackage().ident))
4305 {
4306 Package pkg = m.parent ? m.parent.isPackage() : null;
4307 if (!pkg || !visd.visibility.pkg.isAncestorPackageOf(pkg))
4308 .error(visd.loc, "%s `%s` does not bind to one of ancestor packages of module `%s`", visd.kind(), visd.toPrettyChars(false), m.toPrettyChars(true));
4309 }
4310 }
4311 attribAddMember(visd, sc, sds);
4312 }
4313
4314 override void visit(StaticIfDeclaration sid)
4315 {
4316 //printf("StaticIfDeclaration::addMember() '%s'\n", sid.toChars());
4317 /* This is deferred until the condition evaluated later (by the include() call),
4318 * so that expressions in the condition can refer to declarations
4319 * in the same scope, such as:
4320 *
4321 * template Foo(int i)
4322 * {
4323 * const int j = i + 1;
4324 * static if (j == 3)
4325 * const int k;
4326 * }
4327 */
4328 sid.scopesym = sds;
4329 }
4330
4331
4332 override void visit(StaticForeachDeclaration sfd)
4333 {
4334 // used only for caching the enclosing symbol
4335 sfd.scopesym = sds;
4336 }
4337
4338 /***************************************
4339 * Lazily initializes the scope to forward to.
4340 */
4341 override void visit(ForwardingAttribDeclaration fad)
4342 {
4343 fad.sym.parent = sds;
4344 sds = fad.sym;
4345 attribAddMember(fad, sc, fad.sym);
4346 }
4347
4348 override void visit(MixinDeclaration md)
4349 {
4350 //printf("MixinDeclaration::addMember(sc = %p, sds = %p, memnum = %d)\n", sc, sds, md.memnum);
4351 md.scopesym = sds;
4352 }
4353
4354 override void visit(DebugSymbol ds)
4355 {
4356 //printf("DebugSymbol::addMember('%s') %s\n", sds.toChars(), ds.toChars());
4357 Module m = sds.isModule();
4358 // Do not add the member to the symbol table,
4359 // just make sure subsequent debug declarations work.
4360 if (!m)
4361 {
4362 .error(ds.loc, "%s `%s` declaration must be at module level", ds.kind, ds.toPrettyChars);
4363 ds.errors = true;
4364 }
4365 else
4366 {
4367 if (m.debugidsNot && findCondition(*m.debugidsNot, ds.ident))
4368 {
4369 .error(ds.loc, "%s `%s` defined after use", ds.kind, ds.toPrettyChars);
4370 ds.errors = true;
4371 }
4372 if (!m.debugids)
4373 m.debugids = new Identifiers();
4374 m.debugids.push(ds.ident);
4375 }
4376 }
4377
4378 override void visit(VersionSymbol vs)
4379 {
4380 //printf("VersionSymbol::addMember('%s') %s\n", sds.toChars(), vs.toChars());
4381 Module m = sds.isModule();
4382 // Do not add the member to the symbol table,
4383 // just make sure subsequent debug declarations work.
4384 VersionCondition.checkReserved(vs.loc, vs.ident.toString());
4385 if (!m)
4386 {
4387 .error(vs.loc, "%s `%s` declaration must be at module level", vs.kind, vs.toPrettyChars);
4388 vs.errors = true;
4389 }
4390 else
4391 {
4392 if (m.versionidsNot && findCondition(*m.versionidsNot, vs.ident))
4393 {
4394 .error(vs.loc, "%s `%s` defined after use", vs.kind, vs.toPrettyChars);
4395 vs.errors = true;
4396 }
4397 if (!m.versionids)
4398 m.versionids = new Identifiers();
4399 m.versionids.push(vs.ident);
4400 }
4401
4402 }
4403
4404 override void visit(Nspace ns)
4405 {
4406 visit(cast(Dsymbol)ns);
4407
4408 if (ns.members)
4409 {
4410 if (!ns.symtab)
4411 ns.symtab = new DsymbolTable();
4412 // The namespace becomes 'imported' into the enclosing scope
4413 for (Scope* sce = sc; 1; sce = sce.enclosing)
4414 {
4415 ScopeDsymbol sds2 = sce.scopesym;
4416 if (sds2)
4417 {
4418 sds2.importScope(ns, Visibility(Visibility.Kind.public_));
4419 break;
4420 }
4421 }
4422 assert(sc);
4423 sc = sc.push(ns);
4424 sc.linkage = LINK.cpp; // namespaces default to C++ linkage
4425 sc.parent = ns;
4426 ns.members.foreachDsymbol(s => s.addMember(sc, ns));
4427 sc.pop();
4428 }
4429 }
4430
4431 override void visit(EnumDeclaration ed)
4432 {
4433 version (none)
4434 {
4435 printf("EnumDeclaration::addMember() %s\n", ed.toChars());
4436 for (size_t i = 0; i < ed.members.length; i++)
4437 {
4438 EnumMember em = (*ed.members)[i].isEnumMember();
4439 printf(" member %s\n", em.toChars());
4440 }
4441 }
4442 if (!ed.isAnonymous())
4443 {
4444 visit(cast(Dsymbol)ed);
4445 }
4446
4447 addEnumMembersToSymtab(ed, sc, sds);
4448 }
4449 }
4450
4451 /*******************************************
4452 * Add members of EnumDeclaration to the symbol table(s).
4453 * Params:
4454 * ed = EnumDeclaration
4455 * sc = context of `ed`
4456 * sds = symbol table that `ed` resides in
4457 */
4458 void addEnumMembersToSymtab(EnumDeclaration ed, Scope* sc, ScopeDsymbol sds)
4459 {
4460 const bool isCEnum = sc.inCfile; // it's an ImportC enum
4461 //printf("addEnumMembersToSymtab(ed: %s added: %d Cfile: %d)\n", ed.toChars(), ed.added, isCEnum);
4462 if (ed.added)
4463 return;
4464 ed.added = true;
4465
4466 if (!ed.members)
4467 return;
4468
4469 const bool isAnon = ed.isAnonymous();
4470
4471 if ((isCEnum || isAnon) && !sds.symtab)
4472 sds.symtab = new DsymbolTable();
4473
4474 if ((isCEnum || !isAnon) && !ed.symtab)
4475 ed.symtab = new DsymbolTable();
4476
4477 ed.members.foreachDsymbol( (s)
4478 {
4479 if (EnumMember em = s.isEnumMember())
4480 {
4481 //printf("adding EnumMember %s to %s %d\n", em.toChars(), ed.toChars(), isCEnum);
4482 em.ed = ed;
4483 if (isCEnum)
4484 {
4485 /* C doesn't add the enum member to the symbol table of the enum tag, it adds
4486 * it to the symbol table that the tag is in. This is in contrast to D, where enum
4487 * members become members of the enum tag. To accommodate this, we add
4488 * the enum members to both symbol tables.
4489 */
4490 em.addMember(sc, ed); // add em to ed's symbol table
4491 if (em.errors)
4492 return;
4493 em.addMember(sc, sds); // add em to symbol table that ed is in
4494 em.parent = ed; // restore it after previous addMember() changed it
4495 }
4496 else
4497 {
4498 em.addMember(sc, isAnon ? sds : ed);
4499 }
4500 }
4501 });
4502 }
4503
4504 /******************************************************
4505 * Verifies if the given Identifier is a DRuntime hook. It uses the hooks
4506 * defined in `id.d`.
4507 *
4508 * Params:
4509 * id = Identifier to verify
4510 * Returns:
4511 * true if `id` is a DRuntime hook
4512 * false otherwise
4513 */
4514 private bool isDRuntimeHook(Identifier id)
4515 {
4516 return id == Id._d_HookTraceImpl ||
4517 id == Id._d_newclassT || id == Id._d_newclassTTrace ||
4518 id == Id._d_arraycatnTX || id == Id._d_arraycatnTXTrace ||
4519 id == Id._d_newThrowable || id == Id._d_delThrowable ||
4520 id == Id._d_arrayassign_l || id == Id._d_arrayassign_r ||
4521 id == Id._d_arraysetassign || id == Id._d_arraysetctor ||
4522 id == Id._d_arrayctor ||
4523 id == Id._d_arraysetlengthTImpl || id == Id._d_arraysetlengthT ||
4524 id == Id._d_arraysetlengthTTrace ||
4525 id == Id._d_arrayappendT || id == Id._d_arrayappendTTrace ||
4526 id == Id._d_arrayappendcTX;
4527 }
4528
4529 void templateInstanceSemantic(TemplateInstance tempinst, Scope* sc, ArgumentList argumentList)
4530 {
4531 //printf("[%s] TemplateInstance.dsymbolSemantic('%s', this=%p, gag = %d, sc = %p)\n", tempinst.loc.toChars(), tempinst.toChars(), tempinst, global.gag, sc);
4532 version (none)
4533 {
4534 for (Dsymbol s = tempinst; s; s = s.parent)
4535 {
4536 printf("\t%s\n", s.toChars());
4537 }
4538 printf("Scope\n");
4539 for (Scope* scx = sc; scx; scx = scx.enclosing)
4540 {
4541 printf("\t%s parent %s\n", scx._module ? scx._module.toChars() : "null", scx.parent ? scx.parent.toChars() : "null");
4542 }
4543 }
4544
4545 static if (LOG)
4546 {
4547 printf("\n+TemplateInstance.dsymbolSemantic('%s', this=%p)\n", tempinst.toChars(), tempinst);
4548 }
4549 if (tempinst.inst) // if semantic() was already run
4550 {
4551 static if (LOG)
4552 {
4553 printf("-TemplateInstance.dsymbolSemantic('%s', this=%p) already run\n",
4554 tempinst.inst.toChars(), tempinst.inst);
4555 }
4556 return;
4557 }
4558 if (tempinst.semanticRun != PASS.initial)
4559 {
4560 static if (LOG)
4561 {
4562 printf("Recursive template expansion\n");
4563 }
4564 auto ungag = Ungag(global.gag);
4565 if (!tempinst.gagged)
4566 global.gag = 0;
4567 .error(tempinst.loc, "%s `%s` recursive template expansion", tempinst.kind, tempinst.toPrettyChars);
4568 if (tempinst.gagged)
4569 tempinst.semanticRun = PASS.initial;
4570 else
4571 tempinst.inst = tempinst;
4572 tempinst.errors = true;
4573 return;
4574 }
4575
4576 // Get the enclosing template instance from the scope tinst
4577 tempinst.tinst = sc.tinst;
4578
4579 // Get the instantiating module from the scope minst
4580 tempinst.minst = sc.minst;
4581 // https://issues.dlang.org/show_bug.cgi?id=10920
4582 // If the enclosing function is non-root symbol,
4583 // this instance should be speculative.
4584 if (!tempinst.tinst && sc.func && sc.func.inNonRoot())
4585 {
4586 tempinst.minst = null;
4587 }
4588
4589 tempinst.gagged = (global.gag > 0);
4590
4591 tempinst.semanticRun = PASS.semantic;
4592
4593 static if (LOG)
4594 {
4595 printf("\tdo semantic\n");
4596 }
4597 /* Find template declaration first,
4598 * then run semantic on each argument (place results in tiargs[]),
4599 * last find most specialized template from overload list/set.
4600 */
4601 if (!tempinst.findTempDecl(sc, null) || !tempinst.semanticTiargs(sc) || !tempinst.findBestMatch(sc, argumentList))
4602 {
4603 Lerror:
4604 if (tempinst.gagged)
4605 {
4606 // https://issues.dlang.org/show_bug.cgi?id=13220
4607 // Roll back status for later semantic re-running
4608 tempinst.semanticRun = PASS.initial;
4609 }
4610 else
4611 tempinst.inst = tempinst;
4612 tempinst.errors = true;
4613 return;
4614 }
4615 TemplateDeclaration tempdecl = tempinst.tempdecl.isTemplateDeclaration();
4616 assert(tempdecl);
4617
4618 if (global.params.v.templates)
4619 TemplateStats.incInstance(tempdecl, tempinst, global.params.v.templatesListInstances);
4620
4621 tempdecl.checkDeprecated(tempinst.loc, sc);
4622
4623 // If tempdecl is a mixin, disallow it
4624 if (tempdecl.ismixin)
4625 {
4626 .error(tempinst.loc, "%s `%s` mixin templates are not regular templates", tempinst.kind, tempinst.toPrettyChars);
4627 goto Lerror;
4628 }
4629
4630 tempinst.hasNestedArgs(tempinst.tiargs, tempdecl.isstatic);
4631 if (tempinst.errors)
4632 goto Lerror;
4633
4634 // Copy the tempdecl namespace (not the scope one)
4635 tempinst.cppnamespace = tempdecl.cppnamespace;
4636 if (tempinst.cppnamespace)
4637 tempinst.cppnamespace.dsymbolSemantic(sc);
4638
4639 /* Greatly simplified semantic processing for AliasSeq templates
4640 */
4641 if (tempdecl.isTrivialAliasSeq)
4642 {
4643 tempinst.inst = tempinst;
4644 return aliasSeqInstanceSemantic(tempinst, sc, tempdecl);
4645 }
4646
4647 /* Greatly simplified semantic processing for Alias templates
4648 */
4649 else if (tempdecl.isTrivialAlias)
4650 {
4651 tempinst.inst = tempinst;
4652 return aliasInstanceSemantic(tempinst, sc, tempdecl);
4653 }
4654
4655
4656 /* See if there is an existing TemplateInstantiation that already
4657 * implements the typeargs. If so, just refer to that one instead.
4658 */
4659 tempinst.inst = tempdecl.findExistingInstance(tempinst, argumentList);
4660 TemplateInstance errinst = null;
4661 if (!tempinst.inst)
4662 {
4663 // So, we need to implement 'this' instance.
4664 }
4665 else if (tempinst.inst.gagged && !tempinst.gagged && tempinst.inst.errors)
4666 {
4667 // If the first instantiation had failed, re-run semantic,
4668 // so that error messages are shown.
4669 errinst = tempinst.inst;
4670 }
4671 else
4672 {
4673 // It's a match
4674 tempinst.parent = tempinst.inst.parent;
4675 tempinst.errors = tempinst.inst.errors;
4676
4677 // If both this and the previous instantiation were gagged,
4678 // use the number of errors that happened last time.
4679 global.errors += tempinst.errors;
4680 global.gaggedErrors += tempinst.errors;
4681
4682 // If the first instantiation was gagged, but this is not:
4683 if (tempinst.inst.gagged)
4684 {
4685 // It had succeeded, mark it is a non-gagged instantiation,
4686 // and reuse it.
4687 tempinst.inst.gagged = tempinst.gagged;
4688 }
4689
4690 tempinst.tnext = tempinst.inst.tnext;
4691 tempinst.inst.tnext = tempinst;
4692
4693 /* A module can have explicit template instance and its alias
4694 * in module scope (e,g, `alias Base64 = Base64Impl!('+', '/');`).
4695 * If the first instantiation 'inst' had happened in non-root module,
4696 * compiler can assume that its instantiated code would be included
4697 * in the separately compiled obj/lib file (e.g. phobos.lib).
4698 *
4699 * However, if 'this' second instantiation happened in root module,
4700 * compiler might need to invoke its codegen
4701 * (https://issues.dlang.org/show_bug.cgi?id=2500 & https://issues.dlang.org/show_bug.cgi?id=2644).
4702 * But whole import graph is not determined until all semantic pass finished,
4703 * so 'inst' should conservatively finish the semantic3 pass for the codegen.
4704 */
4705 if (tempinst.minst && tempinst.minst.isRoot() && !(tempinst.inst.minst && tempinst.inst.minst.isRoot()))
4706 {
4707 /* Swap the position of 'inst' and 'this' in the instantiation graph.
4708 * Then, the primary instance `inst` will be changed to a root instance,
4709 * along with all members of `inst` having their scopes updated.
4710 *
4711 * Before:
4712 * non-root -> A!() -> B!()[inst] -> C!() { members[non-root] }
4713 * |
4714 * root -> D!() -> B!()[this]
4715 *
4716 * After:
4717 * non-root -> A!() -> B!()[this]
4718 * |
4719 * root -> D!() -> B!()[inst] -> C!() { members[root] }
4720 */
4721 Module mi = tempinst.minst;
4722 TemplateInstance ti = tempinst.tinst;
4723 tempinst.minst = tempinst.inst.minst;
4724 tempinst.tinst = tempinst.inst.tinst;
4725 tempinst.inst.minst = mi;
4726 tempinst.inst.tinst = ti;
4727
4728 /* https://issues.dlang.org/show_bug.cgi?id=21299
4729 `minst` has been updated on the primary instance `inst` so it is
4730 now coming from a root module, however all Dsymbol `inst.members`
4731 of the instance still have their `_scope.minst` pointing at the
4732 original non-root module. We must now propagate `minst` to all
4733 members so that forward referenced dependencies that get
4734 instantiated will also be appended to the root module, otherwise
4735 there will be undefined references at link-time. */
4736 extern (C++) final class InstMemberWalker : Visitor
4737 {
4738 alias visit = Visitor.visit;
4739 TemplateInstance inst;
4740
4741 extern (D) this(TemplateInstance inst) scope @safe
4742 {
4743 this.inst = inst;
4744 }
4745
4746 override void visit(Dsymbol d)
4747 {
4748 if (d._scope)
4749 d._scope.minst = inst.minst;
4750 }
4751
4752 override void visit(ScopeDsymbol sds)
4753 {
4754 sds.members.foreachDsymbol( s => s.accept(this) );
4755 visit(cast(Dsymbol)sds);
4756 }
4757
4758 override void visit(StructDeclaration sd)
4759 {
4760 // need to visit auto-generated methods as well
4761 if (sd.xeq) visit(sd.xeq);
4762 if (sd.xcmp) visit(sd.xcmp);
4763 if (sd.xhash) visit(sd.xhash);
4764 visit(cast(ScopeDsymbol)sd);
4765 }
4766
4767 override void visit(AttribDeclaration ad)
4768 {
4769 ad.include(null).foreachDsymbol( s => s.accept(this) );
4770 visit(cast(Dsymbol)ad);
4771 }
4772
4773 override void visit(ConditionalDeclaration cd)
4774 {
4775 if (cd.condition.inc)
4776 visit(cast(AttribDeclaration)cd);
4777 else
4778 visit(cast(Dsymbol)cd);
4779 }
4780 }
4781 scope v = new InstMemberWalker(tempinst.inst);
4782 tempinst.inst.accept(v);
4783
4784 if (!global.params.allInst &&
4785 tempinst.minst) // if inst was not speculative...
4786 {
4787 assert(!tempinst.minst.isRoot()); // ... it was previously appended to a non-root module
4788 // Append again to the root module members[], so that the instance will
4789 // get codegen chances (depending on `tempinst.inst.needsCodegen()`).
4790 tempinst.inst.appendToModuleMember();
4791 }
4792
4793 assert(tempinst.inst.memberOf && tempinst.inst.memberOf.isRoot(), "no codegen chances");
4794 }
4795
4796 // modules imported by an existing instance should be added to the module
4797 // that instantiates the instance.
4798 if (tempinst.minst)
4799 foreach(imp; tempinst.inst.importedModules)
4800 if (!tempinst.minst.aimports.contains(imp))
4801 tempinst.minst.aimports.push(imp);
4802
4803 static if (LOG)
4804 {
4805 printf("\tit's a match with instance %p, %d\n", tempinst.inst, tempinst.inst.semanticRun);
4806 }
4807 return;
4808 }
4809 static if (LOG)
4810 {
4811 printf("\timplement template instance %s '%s'\n", tempdecl.parent.toChars(), tempinst.toChars());
4812 printf("\ttempdecl %s\n", tempdecl.toChars());
4813 }
4814 const errorsave = global.errors;
4815
4816 tempinst.inst = tempinst;
4817 tempinst.parent = tempinst.enclosing ? tempinst.enclosing : tempdecl.parent;
4818 //printf("parent = '%s'\n", parent.kind());
4819
4820 if (global.params.v.templates)
4821 TemplateStats.incUnique(tempdecl, tempinst);
4822
4823 TemplateInstance tempdecl_instance_idx = tempdecl.addInstance(tempinst);
4824
4825 //getIdent();
4826
4827 // Store the place we added it to in target_symbol_list(_idx) so we can
4828 // remove it later if we encounter an error.
4829 Dsymbols* target_symbol_list = tempinst.appendToModuleMember();
4830 size_t target_symbol_list_idx = target_symbol_list ? target_symbol_list.length - 1 : 0;
4831
4832 // Copy the syntax trees from the TemplateDeclaration
4833 tempinst.members = Dsymbol.arraySyntaxCopy(tempdecl.members);
4834
4835 // resolve TemplateThisParameter
4836 for (size_t i = 0; i < tempdecl.parameters.length; i++)
4837 {
4838 if ((*tempdecl.parameters)[i].isTemplateThisParameter() is null)
4839 continue;
4840 Type t = isType((*tempinst.tiargs)[i]);
4841 assert(t);
4842 if (STC stc = ModToStc(t.mod))
4843 {
4844 //printf("t = %s, stc = x%llx\n", t.toChars(), stc);
4845 auto s = new Dsymbols();
4846 s.push(new StorageClassDeclaration(stc, tempinst.members));
4847 tempinst.members = s;
4848 }
4849 break;
4850 }
4851
4852 // Create our own scope for the template parameters
4853 Scope* _scope = tempdecl._scope;
4854 if (tempdecl.semanticRun == PASS.initial)
4855 {
4856 .error(tempinst.loc, "%s `%s` template instantiation `%s` forward references template declaration `%s`",
4857 tempinst.kind, tempinst.toPrettyChars, tempinst.toChars(), tempdecl.toChars());
4858 return;
4859 }
4860
4861 static if (LOG)
4862 {
4863 printf("\tcreate scope for template parameters '%s'\n", tempinst.toChars());
4864 }
4865 tempinst.argsym = new ScopeDsymbol();
4866 tempinst.argsym.parent = _scope.parent;
4867 _scope = _scope.push(tempinst.argsym);
4868 _scope.tinst = tempinst;
4869 _scope.minst = tempinst.minst;
4870 //scope.stc = STC.none;
4871
4872 // Declare each template parameter as an alias for the argument type
4873 Scope* paramscope = _scope.push();
4874 paramscope.stc = STC.none;
4875 paramscope.visibility = Visibility(Visibility.Kind.public_); // https://issues.dlang.org/show_bug.cgi?id=14169
4876 // template parameters should be public
4877 tempinst.declareParameters(paramscope);
4878 paramscope.pop();
4879
4880 // Add members of template instance to template instance symbol table
4881 //parent = scope.scopesym;
4882 tempinst.symtab = new DsymbolTable();
4883
4884 tempinst.members.foreachDsymbol( (s)
4885 {
4886 static if (LOG)
4887 {
4888 printf("\t adding member '%s' %p kind %s to '%s'\n", s.toChars(), s, s.kind(), tempinst.toChars());
4889 }
4890 s.addMember(_scope, tempinst);
4891 });
4892
4893 static if (LOG)
4894 {
4895 printf("adding members done\n");
4896 }
4897
4898 /* See if there is only one member of template instance, and that
4899 * member has the same name as the template instance.
4900 * If so, this template instance becomes an alias for that member.
4901 */
4902 //printf("members.length = %d\n", tempinst.members.length);
4903 if (tempinst.members.length)
4904 {
4905 Dsymbol s;
4906 if (Dsymbol.oneMembers(tempinst.members, s, tempdecl.ident) && s)
4907 {
4908 //printf("tempdecl.ident = %s, s = `%s %s`\n", tempdecl.ident.toChars(), s.kind(), s.toPrettyChars());
4909 //printf("setting aliasdecl\n");
4910 tempinst.aliasdecl = s;
4911 }
4912 }
4913
4914 /* If function template declaration
4915 */
4916 if (argumentList.length > 0 && tempinst.aliasdecl)
4917 {
4918 if (auto fd = tempinst.aliasdecl.isFuncDeclaration())
4919 {
4920 /* Transmit fargs to type so that TypeFunction.dsymbolSemantic() can
4921 * resolve any "auto ref" storage classes.
4922 */
4923 if (fd.type)
4924 if (auto tf = fd.type.isTypeFunction())
4925 tf.inferenceArguments = argumentList;
4926 }
4927 }
4928
4929 // Do semantic() analysis on template instance members
4930 static if (LOG)
4931 {
4932 printf("\tdo semantic() on template instance members '%s'\n", tempinst.toChars());
4933 }
4934 Scope* sc2;
4935 sc2 = _scope.push(tempinst);
4936 //printf("enclosing = %d, sc.parent = %s\n", tempinst.enclosing, sc.parent.toChars());
4937 sc2.parent = tempinst;
4938 sc2.tinst = tempinst;
4939 sc2.minst = tempinst.minst;
4940 sc2.stc &= ~STC.deprecated_;
4941 tempinst.tryExpandMembers(sc2);
4942
4943 tempinst.semanticRun = PASS.semanticdone;
4944
4945 /* ConditionalDeclaration may introduce eponymous declaration,
4946 * so we should find it once again after semantic.
4947 */
4948 if (tempinst.members.length)
4949 {
4950 Dsymbol s;
4951 if (Dsymbol.oneMembers(tempinst.members, s, tempdecl.ident) && s)
4952 {
4953 if (!tempinst.aliasdecl || tempinst.aliasdecl != s)
4954 {
4955 //printf("tempdecl.ident = %s, s = `%s %s`\n", tempdecl.ident.toChars(), s.kind(), s.toPrettyChars());
4956 //printf("setting aliasdecl 2\n");
4957 tempinst.aliasdecl = s;
4958 }
4959 }
4960 }
4961
4962 if (global.errors != errorsave)
4963 goto Laftersemantic;
4964
4965 /* If any of the instantiation members didn't get semantic() run
4966 * on them due to forward references, we cannot run semantic2()
4967 * or semantic3() yet.
4968 */
4969 {
4970 bool found_deferred_ad = false;
4971 for (size_t i = 0; i < Module.deferred.length; i++)
4972 {
4973 Dsymbol sd = Module.deferred[i];
4974 AggregateDeclaration ad = sd.isAggregateDeclaration();
4975 if (ad && ad.parent && ad.parent.isTemplateInstance())
4976 {
4977 //printf("deferred template aggregate: %s %s\n",
4978 // sd.parent.toChars(), sd.toChars());
4979 found_deferred_ad = true;
4980 if (ad.parent == tempinst)
4981 {
4982 ad.deferred = tempinst;
4983 break;
4984 }
4985 }
4986 }
4987 if (found_deferred_ad || Module.deferred.length)
4988 goto Laftersemantic;
4989 }
4990
4991 /* The problem is when to parse the initializer for a variable.
4992 * Perhaps VarDeclaration.dsymbolSemantic() should do it like it does
4993 * for initializers inside a function.
4994 */
4995 //if (sc.parent.isFuncDeclaration())
4996 {
4997 /* https://issues.dlang.org/show_bug.cgi?id=782
4998 * this has problems if the classes this depends on
4999 * are forward referenced. Find a way to defer semantic()
5000 * on this template.
5001 */
5002 tempinst.semantic2(sc2);
5003 }
5004 if (global.errors != errorsave)
5005 goto Laftersemantic;
5006
5007 if ((sc.func || sc.fullinst) && !tempinst.tinst)
5008 {
5009 /* If a template is instantiated inside function, the whole instantiation
5010 * should be done at that position. But, immediate running semantic3 of
5011 * dependent templates may cause unresolved forward reference.
5012 * https://issues.dlang.org/show_bug.cgi?id=9050
5013 * To avoid the issue, don't run semantic3 until semantic and semantic2 done.
5014 */
5015 TemplateInstances deferred;
5016 tempinst.deferred = &deferred;
5017
5018 //printf("Run semantic3 on %s\n", toChars());
5019
5020 /* https://issues.dlang.org/show_bug.cgi?id=23965
5021 * DRuntime hooks are not deprecated, but may be used for deprecated
5022 * types. Deprecations are disabled while analysing hooks to avoid
5023 * spurious error messages.
5024 */
5025 auto saveUseDeprecated = global.params.useDeprecated;
5026 if (sc.isDeprecated() && isDRuntimeHook(tempinst.name))
5027 global.params.useDeprecated = DiagnosticReporting.off;
5028
5029 tempinst.trySemantic3(sc2);
5030
5031 global.params.useDeprecated = saveUseDeprecated;
5032
5033 for (size_t i = 0; i < deferred.length; i++)
5034 {
5035 //printf("+ run deferred semantic3 on %s\n", deferred[i].toChars());
5036 deferred[i].semantic3(null);
5037 }
5038
5039 tempinst.deferred = null;
5040 }
5041 else if (tempinst.tinst)
5042 {
5043 bool doSemantic3 = false;
5044 FuncDeclaration fd;
5045 if (tempinst.aliasdecl)
5046 fd = tempinst.aliasdecl.toAlias2().isFuncDeclaration();
5047
5048 if (fd)
5049 {
5050 /* Template function instantiation should run semantic3 immediately
5051 * for attribute inference.
5052 */
5053 scope fld = fd.isFuncLiteralDeclaration();
5054 if (fld && fld.tok == TOK.reserved)
5055 doSemantic3 = true;
5056 else if (sc.func)
5057 doSemantic3 = true;
5058 }
5059 else if (sc.func)
5060 {
5061 /* A lambda function in template arguments might capture the
5062 * instantiated scope context. For the correct context inference,
5063 * all instantiated functions should run the semantic3 immediately.
5064 * See also compilable/test14973.d
5065 */
5066 foreach (oarg; tempinst.tdtypes)
5067 {
5068 auto s = getDsymbol(oarg);
5069 if (!s)
5070 continue;
5071
5072 if (auto td = s.isTemplateDeclaration())
5073 {
5074 if (!td.literal)
5075 continue;
5076 assert(td.members && td.members.length == 1);
5077 s = (*td.members)[0];
5078 }
5079 if (auto fld = s.isFuncLiteralDeclaration())
5080 {
5081 if (fld.tok == TOK.reserved)
5082 {
5083 doSemantic3 = true;
5084 break;
5085 }
5086 }
5087 }
5088 //printf("[%s] %s doSemantic3 = %d\n", tempinst.tinst.loc.toChars(), tempinst.tinst.toChars(), doSemantic3);
5089 }
5090 if (doSemantic3)
5091 tempinst.trySemantic3(sc2);
5092
5093 TemplateInstance ti = tempinst.tinst;
5094 int nest = 0;
5095 while (ti && !ti.deferred && ti.tinst)
5096 {
5097 ti = ti.tinst;
5098 if (++nest > global.recursionLimit)
5099 {
5100 global.gag = 0; // ensure error message gets printed
5101 .error(tempinst.loc, "%s `%s` recursive expansion", tempinst.kind, tempinst.toPrettyChars);
5102 fatal();
5103 }
5104 }
5105 if (ti && ti.deferred)
5106 {
5107 //printf("deferred semantic3 of %p %s, ti = %s, ti.deferred = %p\n", this, toChars(), ti.toChars());
5108 for (size_t i = 0;; i++)
5109 {
5110 if (i == ti.deferred.length)
5111 {
5112 ti.deferred.push(tempinst);
5113 break;
5114 }
5115 if ((*ti.deferred)[i] == tempinst)
5116 break;
5117 }
5118 }
5119 }
5120
5121 if (tempinst.aliasdecl)
5122 {
5123 /* https://issues.dlang.org/show_bug.cgi?id=13816
5124 * AliasDeclaration tries to resolve forward reference
5125 * twice (See inuse check in AliasDeclaration.toAlias()). It's
5126 * necessary to resolve mutual references of instantiated symbols, but
5127 * it will left a true recursive alias in tuple declaration - an
5128 * AliasDeclaration A refers TupleDeclaration B, and B contains A
5129 * in its elements. To correctly make it an error, we strictly need to
5130 * resolve the alias of eponymous member.
5131 */
5132 tempinst.aliasdecl = tempinst.aliasdecl.toAlias2();
5133
5134 // stop AliasAssign tuple building
5135 if (auto td = tempinst.aliasdecl.isTupleDeclaration())
5136 td.building = false;
5137 }
5138
5139 Laftersemantic:
5140 sc2.pop();
5141 _scope.pop();
5142
5143 // Give additional context info if error occurred during instantiation
5144 if (global.errors != errorsave)
5145 {
5146 if (!tempinst.errors)
5147 {
5148 if (!tempdecl.literal)
5149 .error(tempinst.loc, "%s `%s` error instantiating", tempinst.kind, tempinst.toPrettyChars);
5150 if (tempinst.tinst)
5151 tempinst.tinst.printInstantiationTrace();
5152 }
5153 tempinst.errors = true;
5154 if (tempinst.gagged)
5155 {
5156 // Errors are gagged, so remove the template instance from the
5157 // instance/symbol lists we added it to and reset our state to
5158 // finish clean and so we can try to instantiate it again later
5159 // (see https://issues.dlang.org/show_bug.cgi?id=4302 and https://issues.dlang.org/show_bug.cgi?id=6602).
5160 tempdecl.removeInstance(tempdecl_instance_idx);
5161 if (target_symbol_list)
5162 {
5163 // Because we added 'this' in the last position above, we
5164 // should be able to remove it without messing other indices up.
5165 assert((*target_symbol_list)[target_symbol_list_idx] == tempinst);
5166 target_symbol_list.remove(target_symbol_list_idx);
5167 tempinst.memberOf = null; // no longer a member
5168 }
5169 tempinst.semanticRun = PASS.initial;
5170 tempinst.inst = null;
5171 tempinst.symtab = null;
5172 }
5173 }
5174 else if (errinst)
5175 {
5176 /* https://issues.dlang.org/show_bug.cgi?id=14541
5177 * If the previous gagged instance had failed by
5178 * circular references, currrent "error reproduction instantiation"
5179 * might succeed, because of the difference of instantiated context.
5180 * On such case, the cached error instance needs to be overridden by the
5181 * succeeded instance.
5182 */
5183 //printf("replaceInstance()\n");
5184 assert(errinst.errors);
5185 auto ti1 = TemplateInstanceBox(errinst);
5186 tempdecl.instances.remove(ti1);
5187
5188 auto ti2 = TemplateInstanceBox(tempinst);
5189 tempdecl.instances[ti2] = tempinst;
5190 }
5191
5192 static if (LOG)
5193 {
5194 printf("-TemplateInstance.dsymbolSemantic('%s', this=%p)\n", tempinst.toChars(), tempinst);
5195 }
5196 }
5197
5198 /******************************************************
5199 * Do template instance semantic for isAliasSeq templates.
5200 * This is a greatly simplified version of templateInstanceSemantic().
5201 */
5202 private
5203 void aliasSeqInstanceSemantic(TemplateInstance tempinst, Scope* sc, TemplateDeclaration tempdecl)
5204 {
5205 //printf("[%s] aliasSeqInstance.dsymbolSemantic('%s')\n", tempinst.loc.toChars(), tempinst.toChars());
5206 Scope* paramscope = sc.push();
5207 paramscope.stc = STC.none;
5208 paramscope.visibility = Visibility(Visibility.Kind.public_);
5209
5210 TemplateTupleParameter ttp = (*tempdecl.parameters)[0].isTemplateTupleParameter();
5211 Tuple va = tempinst.tdtypes[0].isTuple();
5212 Declaration d = new TupleDeclaration(tempinst.loc, ttp.ident, &va.objects);
5213 d.storage_class |= STC.templateparameter;
5214 d.dsymbolSemantic(sc);
5215
5216 paramscope.pop();
5217
5218 tempinst.aliasdecl = d;
5219
5220 tempinst.semanticRun = PASS.semanticdone;
5221 }
5222
5223 /******************************************************
5224 * Do template instance semantic for isAlias templates.
5225 * This is a greatly simplified version of templateInstanceSemantic().
5226 */
5227 private
5228 void aliasInstanceSemantic(TemplateInstance tempinst, Scope* sc, TemplateDeclaration tempdecl)
5229 {
5230 //printf("[%s] aliasInstance.dsymbolSemantic('%s')\n", tempinst.loc.toChars(), tempinst.toChars());
5231 Scope* paramscope = sc.push();
5232 paramscope.stc = STC.none;
5233 paramscope.visibility = Visibility(Visibility.Kind.public_);
5234
5235 TemplateTypeParameter ttp = (*tempdecl.parameters)[0].isTemplateTypeParameter();
5236 Type ta = tempinst.tdtypes[0].isType();
5237 auto ad = tempdecl.onemember.isAliasDeclaration();
5238
5239 // Note: qualifiers can be in both 'ad.type.mod' and 'ad.storage_class'
5240 Declaration d = new AliasDeclaration(tempinst.loc, ttp.ident, ta.addMod(ad.type.mod));
5241 d.storage_class |= STC.templateparameter | ad.storage_class;
5242 d.dsymbolSemantic(sc);
5243
5244 paramscope.pop();
5245
5246 tempinst.aliasdecl = d;
5247
5248 tempinst.semanticRun = PASS.semanticdone;
5249 }
5250
5251 // function used to perform semantic on AliasDeclaration
5252 void aliasSemantic(AliasDeclaration ds, Scope* sc)
5253 {
5254 //printf("AliasDeclaration::semantic() %s %p\n", ds.toChars(), ds.aliassym);
5255
5256 // as DsymbolSemanticVisitor::visit(AliasDeclaration), in case we're called first.
5257 // see https://issues.dlang.org/show_bug.cgi?id=21001
5258 ds.storage_class |= sc.stc & STC.deprecated_;
5259 ds.visibility = sc.visibility;
5260 ds.userAttribDecl = sc.userAttribDecl;
5261
5262 void normalRet()
5263 {
5264 ds.inuse = 0;
5265 ds.semanticRun = PASS.semanticdone;
5266
5267 if (auto sx = ds.overnext)
5268 {
5269 ds.overnext = null;
5270 if (!ds.overloadInsert(sx))
5271 ScopeDsymbol.multiplyDefined(Loc.initial, sx, ds);
5272 }
5273 }
5274
5275 void errorRet()
5276 {
5277 ds.aliassym = null;
5278 ds.type = Type.terror;
5279 ds.inuse = 0;
5280 normalRet();
5281 }
5282
5283 // preserve the original type
5284 if (!ds.originalType && ds.type)
5285 ds.originalType = ds.type.syntaxCopy();
5286
5287 if (ds.aliassym)
5288 {
5289 auto fd = ds.aliassym.isFuncLiteralDeclaration();
5290 auto td = ds.aliassym.isTemplateDeclaration();
5291 if (fd || td && td.literal)
5292 {
5293 if (fd && fd.semanticRun >= PASS.semanticdone)
5294 return normalRet();
5295
5296 Expression e = new FuncExp(ds.loc, ds.aliassym);
5297 e = e.expressionSemantic(sc);
5298 if (auto fe = e.isFuncExp())
5299 {
5300 ds.aliassym = fe.td ? cast(Dsymbol)fe.td : fe.fd;
5301 return normalRet();
5302 }
5303 else
5304 return errorRet();
5305 }
5306
5307 if (ds.aliassym.isTemplateInstance())
5308 ds.aliassym.dsymbolSemantic(sc);
5309 return normalRet();
5310 }
5311 ds.inuse = 1;
5312
5313 // Given:
5314 // alias foo.bar.abc def;
5315 // it is not knowable from the syntax whether `def` is an alias
5316 // for type `foo.bar.abc` or an alias for symbol `foo.bar.abc`. It is up to the semantic()
5317 // pass to distinguish.
5318 // If it is a type, then `.type` is set and getType() will return that
5319 // type. If it is a symbol, then `.aliassym` is set and type is `null` -
5320 // toAlias() will return `.aliassym`
5321
5322 const errors = global.errors;
5323 Type oldtype = ds.type;
5324
5325 // Ungag errors when not instantiated DeclDefs scope alias
5326 auto ungag = Ungag(global.gag);
5327 //printf("%s parent = %s, gag = %d, instantiated = %d\n", ds.toChars(), ds.parent.toChars(), global.gag, ds.isInstantiated() !is null);
5328 if (ds.parent && global.gag && !ds.isInstantiated() && !ds.toParent2().isFuncDeclaration() && (sc.minst || sc.tinst))
5329 {
5330 //printf("%s type = %s\n", ds.toPrettyChars(), ds.type.toChars());
5331 global.gag = 0;
5332 }
5333
5334 // https://issues.dlang.org/show_bug.cgi?id=18480
5335 // Detect `alias sym = sym;` to prevent creating loops in overload overnext lists.
5336 if (auto tident = ds.type.isTypeIdentifier())
5337 {
5338 if (sc.hasEdition(Edition.v2024) && tident.idents.length)
5339 {
5340 alias mt = tident;
5341 Dsymbol pscopesym;
5342 Dsymbol s = sc.search(ds.loc, mt.ident, pscopesym);
5343 // detect `alias a = var1.member_var;` which confusingly resolves to
5344 // `typeof(var1).member_var`, which can be valid inside the aggregate type
5345 if (s && s.isVarDeclaration() &&
5346 mt.ident != Id.This && mt.ident != Id._super)
5347 {
5348 s = tident.toDsymbol(sc);
5349 // don't error for `var1.static_symbol`
5350 if (s && s.needThis())
5351 {
5352 error(ds.loc, "cannot alias %s member `%s` of variable `%s`",
5353 s.kind(), s.toChars(), mt.ident.toChars());
5354 errorSupplemental(ds.loc, "Use `typeof(%s)` instead to preserve behaviour",
5355 mt.ident.toChars());
5356 }
5357 }
5358 }
5359 // Selective imports are allowed to alias to the same name `import mod : sym=sym`.
5360 if (!ds._import)
5361 {
5362 if (tident.ident is ds.ident && !tident.idents.length)
5363 {
5364 error(ds.loc, "`alias %s = %s;` cannot alias itself, use a qualified name to create an overload set",
5365 ds.ident.toChars(), tident.ident.toChars());
5366 ds.type = Type.terror;
5367 }
5368 }
5369 }
5370 /* This section is needed because Type.resolve() will:
5371 * const x = 3;
5372 * alias y = x;
5373 * try to convert identifier x to 3.
5374 */
5375 auto s = ds.type.toDsymbol(sc);
5376 if (errors != global.errors)
5377 return errorRet();
5378 if (s == ds)
5379 {
5380 .error(ds.loc, "%s `%s` cannot resolve", ds.kind, ds.toPrettyChars);
5381 return errorRet();
5382 }
5383 if (!s || !s.isEnumMember())
5384 {
5385 Type t;
5386 Expression e;
5387 Scope* sc2 = sc;
5388 if (ds.storage_class & (STC.ref_ | STC.nothrow_ | STC.nogc | STC.pure_ | STC.disable))
5389 {
5390 // For 'ref' to be attached to function types, and picked
5391 // up by Type.resolve(), it has to go into sc.
5392 sc2 = sc.push();
5393 sc2.stc |= ds.storage_class & (STC.ref_ | STC.nothrow_ | STC.nogc | STC.pure_ | STC.shared_ | STC.disable);
5394 }
5395 ds.type = ds.type.addSTC(ds.storage_class);
5396 ds.type.resolve(ds.loc, sc2, e, t, s);
5397 if (sc2 != sc)
5398 sc2.pop();
5399
5400 if (e) // Try to convert Expression to Dsymbol
5401 {
5402 // TupleExp is naturally converted to a TupleDeclaration
5403 if (auto te = e.isTupleExp())
5404 s = new TupleDeclaration(te.loc, ds.ident, cast(Objects*)te.exps);
5405 else
5406 {
5407 s = getDsymbol(e);
5408 if (!s)
5409 {
5410 if (e.op != EXP.error)
5411 .error(ds.loc, "%s `%s` cannot alias an expression `%s`", ds.kind, ds.toPrettyChars, e.toChars());
5412 return errorRet();
5413 }
5414 }
5415 }
5416 ds.type = t;
5417 }
5418 if (s == ds)
5419 {
5420 assert(global.errors);
5421 return errorRet();
5422 }
5423 if (s) // it's a symbolic alias
5424 {
5425 //printf("alias %s resolved to %s %s\n", ds.toChars(), s.kind(), s.toChars());
5426 ds.type = null;
5427 ds.aliassym = s;
5428 }
5429 else // it's a type alias
5430 {
5431 //printf("alias %s resolved to type %s\n", ds.toChars(), ds.type.toChars());
5432 ds.type = ds.type.typeSemantic(ds.loc, sc);
5433 ds.aliassym = null;
5434 }
5435
5436 if (global.gag && errors != global.errors)
5437 return errorRet();
5438
5439 normalRet();
5440 }
5441
5442 /********************
5443 * Perform semantic on AliasAssignment.
5444 * Has a lot of similarities to aliasSemantic(). Perhaps they should share code.
5445 */
5446 private void aliasAssignSemantic(AliasAssign ds, Scope* sc)
5447 {
5448 //printf("AliasAssign::semantic() %p, %s\n", ds, ds.ident.toChars());
5449
5450 void errorRet()
5451 {
5452 ds.errors = true;
5453 ds.type = Type.terror;
5454 ds.semanticRun = PASS.semanticdone;
5455 return;
5456 }
5457
5458 /* Find the AliasDeclaration corresponding to ds.
5459 * Returns: AliasDeclaration if found, null if error
5460 */
5461 AliasDeclaration findAliasDeclaration(AliasAssign ds, Scope* sc)
5462 {
5463 Dsymbol scopesym;
5464 Dsymbol as = sc.search(ds.loc, ds.ident, scopesym);
5465 if (!as)
5466 {
5467 .error(ds.loc, "%s `%s` undefined identifier `%s`", ds.kind, ds.toPrettyChars, ds.ident.toChars());
5468 return null;
5469 }
5470 if (as.errors)
5471 return null;
5472
5473 auto ad = as.isAliasDeclaration();
5474 if (!ad)
5475 {
5476 .error(ds.loc, "%s `%s` identifier `%s` must be an alias declaration", ds.kind, ds.toPrettyChars, as.toChars());
5477 return null;
5478 }
5479
5480 if (ad.overnext)
5481 {
5482 error(ds.loc, "%s `%s` cannot reassign overloaded alias", ds.kind, ds.toPrettyChars);
5483 return null;
5484 }
5485
5486 // Check constraints on the parent
5487 auto adParent = ad.toParent();
5488 if (adParent != ds.toParent())
5489 {
5490 if (!adParent)
5491 adParent = ds.toParent();
5492 .error(ds.loc, "`%s` must have same parent `%s` as alias `%s`", ds.ident.toChars(), adParent.toChars(), ad.toChars());
5493 return null;
5494 }
5495 if (!adParent.isTemplateInstance())
5496 {
5497 .error(ds.loc, "%s `%s` must be a member of a template", ds.kind, ds.toPrettyChars);
5498 return null;
5499 }
5500
5501 return ad;
5502 }
5503
5504 auto aliassym = findAliasDeclaration(ds, sc);
5505 if (!aliassym)
5506 return errorRet();
5507
5508 if (aliassym.wasRead)
5509 {
5510 if (!aliassym.errors)
5511 error(ds.loc, "%s was read, so cannot reassign", aliassym.toChars());
5512 aliassym.errors = true;
5513 return errorRet();
5514 }
5515
5516 aliassym.ignoreRead = true; // temporarilly allow reads of aliassym
5517
5518 const storage_class = sc.stc & (STC.deprecated_ | STC.ref_ | STC.nothrow_ | STC.nogc | STC.pure_ | STC.shared_ | STC.disable);
5519
5520 if (ds.aliassym)
5521 {
5522 auto fd = ds.aliassym.isFuncLiteralDeclaration();
5523 auto td = ds.aliassym.isTemplateDeclaration();
5524 if (fd && fd.semanticRun >= PASS.semanticdone)
5525 {
5526 }
5527 else if (fd || td && td.literal)
5528 {
5529
5530 Expression e = new FuncExp(ds.loc, ds.aliassym);
5531 e = e.expressionSemantic(sc);
5532 auto fe = e.isFuncExp();
5533 if (!fe)
5534 return errorRet();
5535 ds.aliassym = fe.td ? cast(Dsymbol)fe.td : fe.fd;
5536 }
5537 else if (ds.aliassym.isTemplateInstance())
5538 ds.aliassym.dsymbolSemantic(sc);
5539
5540 aliassym.type = null;
5541 aliassym.aliassym = ds.aliassym;
5542 return;
5543 }
5544
5545 /* Given:
5546 * abc = def;
5547 * it is not knownable from the syntax whether `def` is a type or a symbol.
5548 * It appears here as `ds.type`. Do semantic analysis on `def` to disambiguate.
5549 */
5550
5551 const errors = global.errors;
5552 Dsymbol s;
5553
5554 // Try AliasSeq optimization
5555 if (auto ti = ds.type.isTypeInstance())
5556 {
5557 if (!ti.tempinst.findTempDecl(sc, null))
5558 return errorRet();
5559 if (auto tempinst = isAliasSeq(sc, ti))
5560 {
5561 s = aliasAssignInPlace(sc, tempinst, aliassym);
5562 if (!s)
5563 return errorRet();
5564 goto Lsymdone;
5565 }
5566 }
5567
5568 /* This section is needed because Type.resolve() will:
5569 * const x = 3;
5570 * alias y = x;
5571 * try to convert identifier x to 3.
5572 */
5573 s = ds.type.toDsymbol(sc);
5574 if (errors != global.errors)
5575 return errorRet();
5576 if (s == aliassym)
5577 {
5578 .error(ds.loc, "%s `%s` cannot resolve", ds.kind, ds.toPrettyChars);
5579 return errorRet();
5580 }
5581
5582 if (!s || !s.isEnumMember())
5583 {
5584 Type t;
5585 Expression e;
5586 Scope* sc2 = sc;
5587 if (storage_class & (STC.ref_ | STC.nothrow_ | STC.nogc | STC.pure_ | STC.shared_ | STC.disable))
5588 {
5589 // For 'ref' to be attached to function types, and picked
5590 // up by Type.resolve(), it has to go into sc.
5591 sc2 = sc.push();
5592 sc2.stc |= storage_class & (STC.ref_ | STC.nothrow_ | STC.nogc | STC.pure_ | STC.shared_ | STC.disable);
5593 }
5594 ds.type = ds.type.addSTC(storage_class);
5595 ds.type.resolve(ds.loc, sc2, e, t, s);
5596 if (sc2 != sc)
5597 sc2.pop();
5598
5599 if (e) // Try to convert Expression to Dsymbol
5600 {
5601 // TupleExp is naturally converted to a TupleDeclaration
5602 if (auto te = e.isTupleExp())
5603 s = new TupleDeclaration(te.loc, ds.ident, cast(Objects*)te.exps);
5604 else
5605 {
5606 s = getDsymbol(e);
5607 if (!s)
5608 {
5609 if (e.op != EXP.error)
5610 .error(ds.loc, "%s `%s` cannot alias an expression `%s`", ds.kind, ds.toPrettyChars, e.toChars());
5611 return errorRet();
5612 }
5613 }
5614 }
5615 ds.type = t;
5616 }
5617 if (s == aliassym)
5618 {
5619 assert(global.errors);
5620 return errorRet();
5621 }
5622
5623 if (s) // it's a symbolic alias
5624 {
5625 Lsymdone:
5626 //printf("alias %s resolved to %s %s\n", toChars(), s.kind(), s.toChars());
5627 aliassym.type = null;
5628 aliassym.aliassym = s;
5629 aliassym.storage_class |= sc.stc & STC.deprecated_;
5630 aliassym.visibility = sc.visibility;
5631 aliassym.userAttribDecl = sc.userAttribDecl;
5632 }
5633 else // it's a type alias
5634 {
5635 //printf("alias %s resolved to type %s\n", toChars(), type.toChars());
5636 aliassym.type = ds.type.typeSemantic(ds.loc, sc);
5637 aliassym.aliassym = null;
5638 }
5639
5640 aliassym.ignoreRead = false;
5641
5642 if (aliassym.type && aliassym.type.ty == Terror ||
5643 global.gag && errors != global.errors)
5644 {
5645 aliassym.type = Type.terror;
5646 aliassym.aliassym = null;
5647 return errorRet();
5648 }
5649
5650 ds.semanticRun = PASS.semanticdone;
5651 }
5652
5653 /***************************************
5654 * Expands template instance arguments inside 'alias assign' target declaration (aliassym),
5655 * instead of inside 'tempinst.tiargs' every time.
5656 * Params:
5657 * tempinst = AliasSeq instance
5658 * aliassym = the AliasDeclaration corresponding to AliasAssign
5659 * Returns:
5660 * null.
5661 */
5662 private TupleDeclaration aliasAssignInPlace(Scope* sc, TemplateInstance tempinst,
5663 AliasDeclaration aliassym)
5664 {
5665 // Mark instance with semantic done, not needed but just in case.
5666 tempinst.inst = tempinst;
5667 tempinst.semanticRun = PASS.semanticdone;
5668 TupleDeclaration td;
5669 if (aliassym.type)
5670 {
5671 // Convert TypeTuple to TupleDeclaration to avoid back and forth allocations
5672 // in the assignment process
5673 if (auto tt = aliassym.type.isTypeTuple())
5674 {
5675 auto objs = new Objects(tt.arguments.length);
5676 foreach (i, p; *tt.arguments)
5677 (*objs)[i] = p.type;
5678 td = new TupleDeclaration(tempinst.loc, aliassym.ident, objs);
5679 td.storage_class |= STC.templateparameter;
5680 td.building = true;
5681 aliassym.type = null;
5682 }
5683 else if (aliassym.type.isTypeError())
5684 return null;
5685
5686 }
5687 else if (auto otd = aliassym.aliassym.isTupleDeclaration())
5688 {
5689 if (otd.building)
5690 td = otd;
5691 else
5692 {
5693 td = new TupleDeclaration(tempinst.loc, aliassym.ident, otd.objects.copy());
5694 td.storage_class |= STC.templateparameter;
5695 td.building = true;
5696 }
5697 }
5698 // If starting from single element in aliassym (td == null) we need to build the tuple
5699 // after semanticTiargs to keep same semantics (for example a FuncLiteraldeclaration
5700 // template argument is converted to FuncExp)
5701 if (td)
5702 aliassym.aliassym = td;
5703 aliassym.semanticRun = PASS.semanticdone;
5704 if (!TemplateInstance.semanticTiargs(tempinst.loc, sc, tempinst.tiargs, 0, td))
5705 {
5706 tempinst.errors = true;
5707 return null;
5708 }
5709 // The alias will stop tuple 'building' mode when used (in AliasDeclaration.toAlias(),
5710 // then TupleDeclaration.getType() will work again)
5711 aliassym.semanticRun = PASS.initial;
5712 if (!td)
5713 {
5714 td = new TupleDeclaration(tempinst.loc, aliassym.ident, tempinst.tiargs);
5715 td.storage_class |= STC.templateparameter;
5716 td.building = true;
5717 return td;
5718 }
5719
5720 auto tiargs = tempinst.tiargs;
5721 size_t oldlen = td.objects.length;
5722 size_t origstart;
5723 size_t insertidx;
5724 size_t insertlen;
5725 foreach (i, o; *tiargs)
5726 {
5727 if (o !is td)
5728 {
5729 ++insertlen;
5730 continue;
5731 }
5732 // tuple contains itself (tuple = AliasSeq!(..., tuple, ...))
5733 if (insertlen) // insert any left element before
5734 {
5735 td.objects.insert(insertidx, (*tiargs)[i - insertlen .. i]);
5736 if (insertidx == 0) // reset original tuple start point
5737 origstart = insertlen;
5738 insertlen = 0;
5739 }
5740 if (insertidx) // insert tuple if found more than one time
5741 {
5742 td.objects.reserve(oldlen); // reserve first to assert a valid slice
5743 td.objects.pushSlice((*td.objects)[origstart .. origstart + oldlen]);
5744 }
5745 insertidx = td.objects.length;
5746 }
5747 if (insertlen)
5748 {
5749 if (insertlen != tiargs.length) // insert any left element
5750 td.objects.pushSlice((*tiargs)[$ - insertlen .. $]);
5751 else
5752 // just assign tiargs if tuple = AliasSeq!(nottuple, nottuple...)
5753 td.objects = tempinst.tiargs;
5754 }
5755 return td;
5756 }
5757
5758 /***************************************
5759 * Check if a template instance is a trivial AliasSeq but without other overloads.
5760 * We can only be 100% sure of being AliasSeq after running semanticTiargs()
5761 * and findBestMatch() but this optimization must happen before that.
5762 */
5763 private TemplateInstance isAliasSeq(Scope* sc, TypeInstance ti)
5764 {
5765 auto tovers = ti.tempinst.tempdecl.isOverloadSet();
5766 foreach (size_t oi; 0 .. tovers ? tovers.a.length : 1)
5767 {
5768 Dsymbol dstart = tovers ? tovers.a[oi] : ti.tempinst.tempdecl;
5769 int r = overloadApply(dstart, (Dsymbol s)
5770 {
5771 auto td = s.isTemplateDeclaration();
5772 if (!td || !td.isTrivialAliasSeq)
5773 return 1;
5774 return 0;
5775 });
5776 if (r)
5777 return null;
5778 }
5779 return ti.tempinst;
5780 }
5781
5782 /***************************************
5783 * Find all instance fields in `ad`, then push them into `fields`.
5784 *
5785 * Runs semantic() for all instance field variables, but also
5786 * the field types can remain yet not resolved forward references,
5787 * except direct recursive definitions.
5788 * After the process sizeok is set to Sizeok.fwd.
5789 *
5790 * Params:
5791 * ad = the AggregateDeclaration to examine
5792 * Returns:
5793 * false if any errors occur.
5794 */
5795 bool determineFields(AggregateDeclaration ad)
5796 {
5797 if (ad._scope)
5798 dsymbolSemantic(ad, null);
5799 if (ad.sizeok != Sizeok.none)
5800 return true;
5801
5802 //printf("determineFields() %s, fields.length = %d\n", toChars(), fields.length);
5803 // determineFields can be called recursively from one of the fields's v.semantic
5804 ad.fields.setDim(0);
5805
5806 static int func(Dsymbol s, void* ctx)
5807 {
5808 auto ad = cast(AggregateDeclaration)ctx;
5809 auto v = s.isVarDeclaration();
5810 if (!v)
5811 return 0;
5812 if (v.storage_class & STC.manifest)
5813 return 0;
5814
5815 if (v.semanticRun < PASS.semanticdone)
5816 v.dsymbolSemantic(null);
5817 // Return in case a recursive determineFields triggered by v.semantic already finished
5818 if (ad.sizeok != Sizeok.none)
5819 return 1;
5820
5821 if (v.aliasTuple)
5822 {
5823 // If this variable was really a tuple, process each element.
5824 return v.aliasTuple.foreachVar(tv => tv.apply(&func, cast(void*) ad));
5825 }
5826
5827 if (v.storage_class & (STC.static_ | STC.extern_ | STC.tls | STC.gshared | STC.manifest | STC.ctfe | STC.templateparameter))
5828 return 0;
5829 if (!v.isField() || v.semanticRun < PASS.semanticdone)
5830 return 1; // unresolvable forward reference
5831
5832 ad.fields.push(v);
5833
5834 if (v.storage_class & STC.ref_)
5835 return 0;
5836 auto tv = v.type.baseElemOf();
5837 if (auto tvs = tv.isTypeStruct())
5838 {
5839 if (ad == tvs.sym)
5840 {
5841 const(char)* psz = (v.type.toBasetype().ty == Tsarray) ? "static array of " : "";
5842 .error(ad.loc, "%s `%s` cannot have field `%s` with %ssame struct type", ad.kind, ad.toPrettyChars, v.toChars(), psz);
5843 ad.type = Type.terror;
5844 ad.errors = true;
5845 return 1;
5846 }
5847 }
5848 return 0;
5849 }
5850
5851 if (ad.members)
5852 {
5853 for (size_t i = 0; i < ad.members.length; i++)
5854 {
5855 auto s = (*ad.members)[i];
5856 if (s.apply(&func, cast(void *)ad))
5857 {
5858 if (ad.sizeok != Sizeok.none)
5859 {
5860 // recursive determineFields already finished
5861 return true;
5862 }
5863 return false;
5864 }
5865 }
5866 }
5867
5868 if (ad.sizeok != Sizeok.done)
5869 ad.sizeok = Sizeok.fwd;
5870
5871 return true;
5872 }
5873
5874 /// Do an atomic operation (currently tailored to [shared] static ctors|dtors) needs
5875 private CallExp doAtomicOp (string op, Identifier var, Expression arg)
5876 {
5877 assert(op == "-=" || op == "+=");
5878
5879 Module mod = Module.loadCoreAtomic();
5880 if (!mod)
5881 return null; // core.atomic couldn't be loaded
5882
5883 const loc = Loc.initial;
5884
5885 Objects* tiargs = new Objects(1);
5886 (*tiargs)[0] = new StringExp(loc, op);
5887
5888 Expressions* args = new Expressions(2);
5889 (*args)[0] = new IdentifierExp(loc, var);
5890 (*args)[1] = arg;
5891
5892 auto sc = new ScopeExp(loc, mod);
5893 auto dti = new DotTemplateInstanceExp(
5894 loc, sc, Id.atomicOp, tiargs);
5895
5896 return CallExp.create(loc, dti, args);
5897 }
5898
5899 /***************************************************
5900 * Set up loc for a parse of a mixin. Append the input text to the mixin.
5901 * Params:
5902 * input = mixin text
5903 * loc = location of expansion
5904 * baseLoc = location to adjust
5905 * mixinOut = sink for mixin text data
5906 * Returns:
5907 * adjusted loc suitable for Parser
5908 */
5909
5910 void adjustLocForMixin(const(char)[] input, Loc loc, ref BaseLoc baseLoc, ref Output mixinOut)
5911 {
5912 if (mixinOut.doOutput)
5913 {
5914 const lines = mixinOut.bufferLines;
5915 writeMixin(input, loc, mixinOut.bufferLines, *mixinOut.buffer);
5916 baseLoc.startLine = lines + 2;
5917 baseLoc.filename = mixinOut.name;
5918 return;
5919 }
5920
5921 SourceLoc sl = SourceLoc(loc);
5922 if (sl.filename.length == 0)
5923 {
5924 // Rare case of compiler-generated mixin exp, e.g. __xtoHash
5925 baseLoc.filename = "";
5926 return;
5927 }
5928
5929 /* Create a pseudo-filename for the mixin string, as it may not even exist
5930 * in the source file.
5931 */
5932 auto len = sl.filename.length + 7 + (sl.linnum).sizeof * 3 + 1;
5933 char* filename = cast(char*) mem.xmalloc(len);
5934 snprintf(filename, len, "%.*s-mixin-%d", cast(int) sl.filename.length, sl.filename.ptr, cast(int) sl.linnum);
5935 baseLoc.startLine = sl.line;
5936 baseLoc.filename = filename.toDString;
5937 }
5938
5939 /**************************************
5940 * Append source code text to output for better debugging.
5941 * Canonicalize line endings.
5942 * Params:
5943 * s = source code text
5944 * loc = location of source code text
5945 * lines = line count to update
5946 * output = sink for output
5947 */
5948 private void writeMixin(const(char)[] s, Loc loc, ref int lines, ref OutBuffer buf)
5949 {
5950 buf.writestring("// expansion at ");
5951 buf.writestring(loc.toChars());
5952 buf.writenl();
5953
5954 ++lines;
5955
5956 // write by line to create consistent line endings
5957 size_t lastpos = 0;
5958 for (size_t i = 0; i < s.length; ++i)
5959 {
5960 // detect LF and CRLF
5961 const c = s[i];
5962 if (c == '\n' || (c == '\r' && i+1 < s.length && s[i+1] == '\n'))
5963 {
5964 buf.writestring(s[lastpos .. i]);
5965 buf.writenl();
5966 ++lines;
5967 if (c == '\r')
5968 ++i;
5969 lastpos = i + 1;
5970 }
5971 }
5972
5973 if(lastpos < s.length)
5974 buf.writestring(s[lastpos .. $]);
5975
5976 if (s.length == 0 || s[$-1] != '\n')
5977 {
5978 buf.writenl(); // ensure empty line after expansion
5979 ++lines;
5980 }
5981 buf.writenl();
5982 ++lines;
5983 }
5984
5985 /*********************************************
5986 * Search for ident as member of d.
5987 * Params:
5988 * d = dsymbol where ident is searched for
5989 * loc = location to print for error messages
5990 * ident = identifier to search for
5991 * flags = search options
5992 * Returns:
5993 * null if not found
5994 */
5995 Dsymbol search(Dsymbol d, Loc loc, Identifier ident, SearchOptFlags flags = SearchOpt.all)
5996 {
5997 scope v = new SearchVisitor(loc, ident, flags);
5998 d.accept(v);
5999 return v.result;
6000 }
6001
6002 Dsymbol search_correct(Dsymbol d, Identifier ident)
6003 {
6004 /***************************************************
6005 * Search for symbol with correct spelling.
6006 */
6007 Dsymbol symbol_search_fp(const(char)[] seed, out int cost)
6008 {
6009 /* If not in the lexer's string table, it certainly isn't in the symbol table.
6010 * Doing this first is a lot faster.
6011 */
6012 if (!seed.length)
6013 return null;
6014 Identifier id = Identifier.lookup(seed);
6015 if (!id)
6016 return null;
6017 cost = 0; // all the same cost
6018 Dsymbol s = d;
6019 Module.clearCache();
6020 return s.search(Loc.initial, id, SearchOpt.ignoreErrors);
6021 }
6022
6023 if (global.gag)
6024 return null; // don't do it for speculative compiles; too time consuming
6025 // search for exact name first
6026 if (auto s = d.search(Loc.initial, ident, SearchOpt.ignoreErrors))
6027 return s;
6028
6029 import dmd.root.speller : speller;
6030 return speller!symbol_search_fp(ident.toString());
6031 }
6032
6033 private extern(C++) class SearchVisitor : Visitor
6034 {
6035 alias visit = Visitor.visit;
6036
6037 const Loc loc;
6038 Identifier ident;
6039 SearchOptFlags flags;
6040 Dsymbol result;
6041
6042 this(Loc loc, Identifier ident, SearchOptFlags flags) @safe
6043 {
6044 this.loc = loc;
6045 this.ident = ident;
6046 this.flags = flags;
6047 }
6048
6049 void setResult(Dsymbol d)
6050 {
6051 result = d;
6052 }
6053
6054 override void visit(Dsymbol d)
6055 {
6056 //printf("Dsymbol::search(this=%p,%s, ident='%s')\n", d, d.toChars(), ident.toChars());
6057 return setResult(null);
6058 }
6059
6060 override void visit(ScopeDsymbol sds)
6061 {
6062 //printf("%s.ScopeDsymbol::search(ident='%s', flags=x%x)\n", sds.toChars(), ident.toChars(), flags);
6063 //if (strcmp(ident.toChars(),"c") == 0) *(char*)0=0;
6064
6065 // Look in symbols declared in this module
6066 if (sds.symtab && !(flags & SearchOpt.importsOnly))
6067 {
6068 //printf(" look in locals\n");
6069 auto s1 = sds.symtab.lookup(ident);
6070 if (s1)
6071 {
6072 //printf("\tfound in locals = '%s.%s'\n",toChars(),s1.toChars());
6073 return setResult(s1);
6074 }
6075 }
6076 //printf(" not found in locals\n");
6077
6078 // Look in imported scopes
6079 if (!sds.importedScopes)
6080 return setResult(null);
6081
6082 //printf(" look in imports\n");
6083 Dsymbol s = null;
6084 OverloadSet a = null;
6085 // Look in imported modules
6086 for (size_t i = 0; i < sds.importedScopes.length; i++)
6087 {
6088 // If private import, don't search it
6089 if ((flags & SearchOpt.ignorePrivateImports) && sds.visibilities[i] == Visibility.Kind.private_)
6090 continue;
6091 SearchOptFlags sflags = flags & (SearchOpt.ignoreErrors | SearchOpt.ignoreAmbiguous); // remember these in recursive searches
6092 Dsymbol ss = (*sds.importedScopes)[i];
6093 //printf("\tscanning import '%s', visibilities = %d, isModule = %p, isImport = %p\n", ss.toChars(), visibilities[i], ss.isModule(), ss.isImport());
6094
6095 if (ss.isModule())
6096 {
6097 if (flags & SearchOpt.localsOnly)
6098 continue;
6099 }
6100 else // mixin template
6101 {
6102 if (flags & SearchOpt.importsOnly)
6103 continue;
6104
6105 sflags |= SearchOpt.localsOnly;
6106 }
6107
6108 /* Don't find private members if ss is a module
6109 */
6110 Dsymbol s2 = ss.search(loc, ident, sflags | (ss.isModule() ? SearchOpt.ignorePrivateImports : SearchOpt.all));
6111 import dmd.access : symbolIsVisible;
6112 if (!s2 || !(flags & SearchOpt.ignoreVisibility) && !symbolIsVisible(sds, s2))
6113 continue;
6114 if (!s)
6115 {
6116 s = s2;
6117 if (s && s.isOverloadSet())
6118 a = sds.mergeOverloadSet(ident, a, s);
6119 }
6120 else if (s2 && s != s2)
6121 {
6122 if (s.toAlias() == s2.toAlias() || s.getType() == s2.getType() && s.getType())
6123 {
6124 /* After following aliases, we found the same
6125 * symbol, so it's not an ambiguity. But if one
6126 * alias is deprecated or less accessible, prefer
6127 * the other.
6128 */
6129 if (s.isDeprecated() || s.visible() < s2.visible() && s2.visible().kind != Visibility.Kind.none)
6130 s = s2;
6131 }
6132 else
6133 {
6134 /* Two imports of the same module should be regarded as
6135 * the same.
6136 */
6137 Import i1 = s.isImport();
6138 Import i2 = s2.isImport();
6139 if (!(i1 && i2 && (i1.mod == i2.mod || (!i1.parent.isImport() && !i2.parent.isImport() && i1.ident.equals(i2.ident)))))
6140 {
6141 /* https://issues.dlang.org/show_bug.cgi?id=8668
6142 * Public selective import adds AliasDeclaration in module.
6143 * To make an overload set, resolve aliases in here and
6144 * get actual overload roots which accessible via s and s2.
6145 */
6146 s = s.toAlias();
6147 s2 = s2.toAlias();
6148 /* If both s2 and s are overloadable (though we only
6149 * need to check s once)
6150 */
6151
6152 auto so2 = s2.isOverloadSet();
6153 if ((so2 || s2.isOverloadable()) && (a || s.isOverloadable()))
6154 {
6155 if (symbolIsVisible(sds, s2))
6156 {
6157 a = sds.mergeOverloadSet(ident, a, s2);
6158 }
6159 if (!symbolIsVisible(sds, s))
6160 s = s2;
6161 continue;
6162 }
6163
6164 /* Two different overflow sets can have the same members
6165 * https://issues.dlang.org/show_bug.cgi?id=16709
6166 */
6167 auto so = s.isOverloadSet();
6168 if (so && so2)
6169 {
6170 if (so.a.length == so2.a.length)
6171 {
6172 foreach (j; 0 .. so.a.length)
6173 {
6174 if (so.a[j] !is so2.a[j])
6175 goto L1;
6176 }
6177 continue; // the same
6178 L1:
6179 { } // different
6180 }
6181 }
6182
6183 if (flags & SearchOpt.ignoreAmbiguous) // if return NULL on ambiguity
6184 return setResult(null);
6185
6186 /* If two imports from C import files, pick first one, as C has global name space
6187 */
6188 if (s.isCsymbol() && s2.isCsymbol())
6189 continue;
6190
6191 if (!(flags & SearchOpt.ignoreErrors))
6192 ScopeDsymbol.multiplyDefined(loc, s, s2);
6193 break;
6194 }
6195 }
6196 }
6197 }
6198 if (s)
6199 {
6200 /* Build special symbol if we had multiple finds
6201 */
6202 if (a)
6203 {
6204 if (!s.isOverloadSet())
6205 a = sds.mergeOverloadSet(ident, a, s);
6206 s = a;
6207 }
6208 //printf("\tfound in imports %s.%s\n", toChars(), s.toChars());
6209 return setResult(s);
6210 }
6211 //printf(" not found in imports\n");
6212 return setResult(null);
6213 }
6214
6215 override void visit(WithScopeSymbol ws)
6216 {
6217 //printf("WithScopeSymbol.search(%s)\n", ident.toChars());
6218 if (flags & SearchOpt.importsOnly)
6219 return setResult(null);
6220 // Acts as proxy to the with class declaration
6221 Dsymbol s = null;
6222 Expression eold = null;
6223 for (Expression e = ws.withstate.exp; e && e != eold; e = resolveAliasThis(ws._scope, e, true))
6224 {
6225 if (auto se = e.isScopeExp())
6226 {
6227 s = se.sds;
6228 }
6229 else if (e.isTypeExp())
6230 {
6231 s = e.type.toDsymbol(null);
6232 }
6233 else
6234 {
6235 Type t = e.type.toBasetype();
6236 s = t.toDsymbol(null);
6237 }
6238 if (s)
6239 {
6240 s = s.search(loc, ident, flags);
6241 if (s)
6242 return setResult(s);
6243 }
6244 eold = e;
6245 }
6246 return setResult(null);
6247 }
6248
6249 override void visit(ArrayScopeSymbol ass)
6250 {
6251 //printf("ArrayScopeSymbol::search('%s', flags = %d)\n", ident.toChars(), flags);
6252 if (ident != Id.dollar)
6253 return setResult(null);
6254
6255 VarDeclaration* pvar;
6256 Expression ce;
6257
6258 static Dsymbol dollarFromTypeTuple(Loc loc, TypeTuple tt, Scope* sc)
6259 {
6260
6261 /* $ gives the number of type entries in the type tuple
6262 */
6263 auto v = new VarDeclaration(loc, Type.tsize_t, Id.dollar, null);
6264 Expression e = new IntegerExp(Loc.initial, tt.arguments.length, Type.tsize_t);
6265 v._init = new ExpInitializer(Loc.initial, e);
6266 v.storage_class |= STC.temp | STC.static_ | STC.const_;
6267 v.dsymbolSemantic(sc);
6268 return v;
6269 }
6270
6271 const DYNCAST kind = ass.arrayContent.dyncast();
6272 switch (kind) with (DYNCAST)
6273 {
6274 case dsymbol:
6275 TupleDeclaration td = cast(TupleDeclaration) ass.arrayContent;
6276 /* $ gives the number of elements in the tuple
6277 */
6278 auto v = new VarDeclaration(loc, Type.tsize_t, Id.dollar, null);
6279 Expression e = new IntegerExp(Loc.initial, td.objects.length, Type.tsize_t);
6280 v._init = new ExpInitializer(Loc.initial, e);
6281 v.storage_class |= STC.temp | STC.static_ | STC.const_;
6282 v.dsymbolSemantic(ass._scope);
6283 return setResult(v);
6284 case type:
6285 return setResult(dollarFromTypeTuple(loc, cast(TypeTuple) ass.arrayContent, ass._scope));
6286 default:
6287 break;
6288 }
6289 Expression exp = cast(Expression) ass.arrayContent;
6290 if (auto ie = exp.isIndexExp())
6291 {
6292 /* array[index] where index is some function of $
6293 */
6294 pvar = &ie.lengthVar;
6295 ce = ie.e1;
6296 }
6297 else if (auto se = exp.isSliceExp())
6298 {
6299 /* array[lwr .. upr] where lwr or upr is some function of $
6300 */
6301 pvar = &se.lengthVar;
6302 ce = se.e1;
6303 }
6304 else if (auto ae = exp.isArrayExp())
6305 {
6306 /* array[e0, e1, e2, e3] where e0, e1, e2 are some function of $
6307 * $ is a opDollar!(dim)() where dim is the dimension(0,1,2,...)
6308 */
6309 pvar = &ae.lengthVar;
6310 ce = ae.e1;
6311 }
6312 else
6313 {
6314 /* Didn't find $, look in enclosing scope(s).
6315 */
6316 return setResult(null);
6317 }
6318 ce = ce.lastComma();
6319 /* If we are indexing into an array that is really a type
6320 * tuple, rewrite this as an index into a type tuple and
6321 * try again.
6322 */
6323 if (auto te = ce.isTypeExp())
6324 {
6325 if (auto ttp = te.type.isTypeTuple())
6326 return setResult(dollarFromTypeTuple(loc, ttp, ass._scope));
6327 }
6328 /* *pvar is lazily initialized, so if we refer to $
6329 * multiple times, it gets set only once.
6330 */
6331 if (!*pvar) // if not already initialized
6332 {
6333 /* Create variable v and set it to the value of $
6334 */
6335 VarDeclaration v;
6336 Type t;
6337 if (auto tupexp = ce.isTupleExp())
6338 {
6339 /* It is for an expression tuple, so the
6340 * length will be a const.
6341 */
6342 Expression e = new IntegerExp(Loc.initial, tupexp.exps.length, Type.tsize_t);
6343 v = new VarDeclaration(loc, Type.tsize_t, Id.dollar, new ExpInitializer(Loc.initial, e));
6344 v.storage_class |= STC.temp | STC.static_ | STC.const_;
6345 }
6346 else if (ce.type && (t = ce.type.toBasetype()) !is null && (t.ty == Tstruct || t.ty == Tclass))
6347 {
6348 // Look for opDollar
6349 assert(exp.op == EXP.array || exp.op == EXP.slice);
6350 AggregateDeclaration ad = isAggregate(t);
6351 assert(ad);
6352 Dsymbol s = ad.search(loc, Id.opDollar);
6353 if (!s) // no dollar exists -- search in higher scope
6354 return setResult(null);
6355 s = s.toAlias();
6356 Expression e = null;
6357 // Check for multi-dimensional opDollar(dim) template.
6358 if (TemplateDeclaration td = s.isTemplateDeclaration())
6359 {
6360 dinteger_t dim = 0;
6361 if (auto ae = exp.isArrayExp())
6362 {
6363 dim = ae.currentDimension;
6364 }
6365 else if (exp.isSliceExp())
6366 {
6367 dim = 0; // slices are currently always one-dimensional
6368 }
6369 else
6370 {
6371 assert(0);
6372 }
6373 auto tiargs = new Objects();
6374 Expression edim = new IntegerExp(Loc.initial, dim, Type.tsize_t);
6375 edim = edim.expressionSemantic(ass._scope);
6376 tiargs.push(edim);
6377 e = new DotTemplateInstanceExp(loc, ce, td.ident, tiargs);
6378 }
6379 else
6380 {
6381 /* opDollar exists, but it's not a template.
6382 * This is acceptable ONLY for single-dimension indexing.
6383 * Note that it's impossible to have both template & function opDollar,
6384 * because both take no arguments.
6385 */
6386 auto ae = exp.isArrayExp();
6387 if (ae && ae.arguments.length != 1)
6388 {
6389 error(exp.loc, "`%s` only defines opDollar for one dimension", ad.toChars());
6390 return setResult(null);
6391 }
6392 Declaration d = s.isDeclaration();
6393 assert(d);
6394 e = new DotVarExp(loc, ce, d);
6395 }
6396 e = e.expressionSemantic(ass._scope);
6397 if (!e.type)
6398 error(exp.loc, "`%s` has no value", e.toChars());
6399 t = e.type.toBasetype();
6400 if (t && t.ty == Tfunction)
6401 e = new CallExp(e.loc, e);
6402 v = new VarDeclaration(loc, null, Id.dollar, new ExpInitializer(Loc.initial, e));
6403 v.storage_class |= STC.temp | STC.ctfe | STC.rvalue;
6404 }
6405 else
6406 {
6407 /* For arrays, $ will either be a compile-time constant
6408 * (in which case its value in set during constant-folding),
6409 * or a variable (in which case an expression is created in
6410 * toir.c).
6411 */
6412
6413 // https://issues.dlang.org/show_bug.cgi?id=16213
6414 // For static arrays $ is known at compile time,
6415 // so declare it as a manifest constant.
6416 auto tsa = ce.type ? ce.type.isTypeSArray() : null;
6417 if (tsa)
6418 {
6419 auto e = new ExpInitializer(loc, tsa.dim);
6420 v = new VarDeclaration(loc, tsa.dim.type, Id.dollar, e, STC.manifest);
6421 }
6422 else
6423 {
6424 auto e = new VoidInitializer(Loc.initial);
6425 e.type = Type.tsize_t;
6426 v = new VarDeclaration(loc, Type.tsize_t, Id.dollar, e);
6427 v.storage_class |= STC.temp | STC.ctfe; // it's never a true static variable
6428 }
6429 }
6430 *pvar = v;
6431 }
6432 (*pvar).dsymbolSemantic(ass._scope);
6433 return setResult((*pvar));
6434
6435 }
6436
6437 override void visit(Import imp)
6438 {
6439 //printf("%s.Import.search(ident = '%s', flags = x%x)\n", imp.toChars(), ident.toChars(), flags);
6440 if (!imp.pkg)
6441 {
6442 imp.load(null);
6443 imp.mod.importAll(null);
6444 imp.mod.dsymbolSemantic(null);
6445 }
6446 // Forward it to the package/module
6447 return setResult(imp.pkg.search(loc, ident, flags));
6448
6449 }
6450
6451 override void visit(Nspace ns)
6452 {
6453 //printf("%s.Nspace.search('%s')\n", toChars(), ident.toChars());
6454 if (ns._scope && !ns.symtab)
6455 dsymbolSemantic(ns, ns._scope);
6456
6457 if (!ns.members || !ns.symtab) // opaque or semantic() is not yet called
6458 {
6459 if (!(flags & SearchOpt.ignoreErrors))
6460 .error(loc, "%s `%s` is forward referenced when looking for `%s`", ns.kind, ns.toPrettyChars, ident.toChars());
6461 return setResult(null);
6462 }
6463
6464 visit(cast(ScopeDsymbol)ns);
6465 }
6466
6467 override void visit(EnumDeclaration em)
6468 {
6469 //printf("%s.EnumDeclaration::search('%s')\n", em.toChars(), ident.toChars());
6470 if (em._scope)
6471 {
6472 // Try one last time to resolve this enum
6473 dsymbolSemantic(em, em._scope);
6474 }
6475
6476 visit(cast(ScopeDsymbol)em);
6477 }
6478
6479 override void visit(Package pkg)
6480 {
6481 //printf("%s Package.search('%s', flags = x%x)\n", pkg.toChars(), ident.toChars(), flags);
6482 flags &= ~cast(int)SearchOpt.localsOnly; // searching an import is always transitive
6483 if (!pkg.isModule() && pkg.mod)
6484 {
6485 // Prefer full package name.
6486 Dsymbol s = pkg.symtab ? pkg.symtab.lookup(ident) : null;
6487 if (s)
6488 return setResult(s);
6489 //printf("[%s] through pkdmod: %s\n", loc.toChars(), toChars());
6490 return setResult(pkg.mod.search(loc, ident, flags));
6491 }
6492
6493 visit(cast(ScopeDsymbol)pkg);
6494 }
6495
6496 override void visit(Module m)
6497 {
6498 /* Since modules can be circularly referenced,
6499 * need to stop infinite recursive searches.
6500 * This is done with the cache.
6501 */
6502 //printf("%s Module.search('%s', flags = x%x) insearch = %d\n", m.toChars(), ident.toChars(), flags, m.insearch);
6503 if (m.insearch)
6504 return setResult(null);
6505
6506 /* Qualified module searches always search their imports,
6507 * even if SearchLocalsOnly
6508 */
6509 if (!(flags & SearchOpt.unqualifiedModule))
6510 flags &= ~(SearchOpt.unqualifiedModule | SearchOpt.localsOnly);
6511
6512 if (m.searchCacheIdent == ident && m.searchCacheFlags == flags)
6513 {
6514 //printf("%s Module::search('%s', flags = %d) insearch = %d searchCacheSymbol = %s\n",
6515 // toChars(), ident.toChars(), flags, insearch, searchCacheSymbol ? searchCacheSymbol.toChars() : "null");
6516 return setResult(m.searchCacheSymbol);
6517 }
6518
6519 const errors = global.errors;
6520
6521 m.insearch = true;
6522 visit(cast(ScopeDsymbol)m);
6523 Dsymbol s = result;
6524 m.insearch = false;
6525
6526 if (errors == global.errors)
6527 {
6528 // https://issues.dlang.org/show_bug.cgi?id=10752
6529 // Can cache the result only when it does not cause
6530 // access error so the side-effect should be reproduced in later search.
6531 m.searchCacheIdent = ident;
6532 m.searchCacheSymbol = s;
6533 m.searchCacheFlags = flags;
6534 }
6535 return setResult(s);
6536 }
6537
6538 override void visit(Declaration decl)
6539 {
6540 Dsymbol s = null;
6541 if (decl.type)
6542 {
6543 s = decl.type.toDsymbol(decl._scope);
6544 if (s)
6545 s = s.search(loc, ident, flags);
6546 }
6547 return setResult(s);
6548 }
6549
6550 override void visit(StructDeclaration sd)
6551 {
6552 //printf("%s.StructDeclaration::search('%s', flags = x%x)\n", sd.toChars(), ident.toChars(), flags);
6553 if (sd._scope && !sd.symtab)
6554 dsymbolSemantic(sd, sd._scope);
6555
6556 if (!sd.members || !sd.symtab) // opaque or semantic() is not yet called
6557 {
6558 // .stringof is always defined (but may be hidden by some other symbol)
6559 if(ident != Id.stringof && !(flags & SearchOpt.ignoreErrors) && sd.semanticRun < PASS.semanticdone)
6560 .error(loc, "%s `%s` is forward referenced when looking for `%s`", sd.kind, sd.toPrettyChars, ident.toChars());
6561 return setResult(null);
6562 }
6563
6564 visit(cast(ScopeDsymbol)sd);
6565 }
6566
6567 override void visit(ClassDeclaration cd)
6568 {
6569 //printf("%s.ClassDeclaration.search('%s', flags=x%x)\n", cd.toChars(), ident.toChars(), flags);
6570 //if (_scope) printf("%s baseok = %d\n", toChars(), baseok);
6571 if (cd._scope && cd.baseok < Baseok.semanticdone)
6572 {
6573 if (!cd.inuse)
6574 {
6575 // must semantic on base class/interfaces
6576 cd.inuse = true;
6577 dsymbolSemantic(cd, null);
6578 cd.inuse = false;
6579 }
6580 }
6581
6582 if (!cd.members || !cd.symtab) // opaque or addMember is not yet done
6583 {
6584 // .stringof is always defined (but may be hidden by some other symbol)
6585 if (ident != Id.stringof && !(flags & SearchOpt.ignoreErrors) && cd.semanticRun < PASS.semanticdone)
6586 cd.classError("%s `%s` is forward referenced when looking for `%s`", ident.toChars());
6587 //*(char*)0=0;
6588 return setResult(null);
6589 }
6590
6591 visit(cast(ScopeDsymbol)cd);
6592 auto s = result;
6593
6594 // don't search imports of base classes
6595 if (flags & SearchOpt.importsOnly)
6596 return setResult(s);
6597
6598 if (s)
6599 return setResult(s);
6600
6601 // Search bases classes in depth-first, left to right order
6602 foreach (b; (*cd.baseclasses)[])
6603 {
6604 if (!b.sym)
6605 continue;
6606
6607 if (!b.sym.symtab)
6608 {
6609 cd.classError("%s `%s` base `%s` is forward referenced", b.sym.ident.toChars());
6610 continue;
6611 }
6612
6613 import dmd.access : symbolIsVisible;
6614
6615 s = b.sym.search(loc, ident, flags);
6616 if (!s)
6617 continue;
6618 if (s == cd) // happens if s is nested in this and derives from this
6619 s = null;
6620 else if (!(flags & SearchOpt.ignoreVisibility) && !(s.visible().kind == Visibility.Kind.protected_) && !symbolIsVisible(cd, s))
6621 s = null;
6622 else
6623 break;
6624 }
6625
6626 return setResult(s);
6627 }
6628 }
6629 /*************************************
6630 * Set scope for future semantic analysis so we can
6631 * deal better with forward references.
6632 *
6633 * Params:
6634 * d = dsymbol for which the scope is set
6635 * sc = scope that is used to set the value
6636 */
6637 void setScope(Dsymbol d, Scope* sc)
6638 {
6639 scope setScopeVisitor = new SetScopeVisitor(sc);
6640 d.accept(setScopeVisitor);
6641 }
6642
6643 private extern(C++) class SetScopeVisitor : Visitor
6644 {
6645 alias visit = typeof(super).visit;
6646 Scope* sc;
6647
6648 this(Scope* sc) @safe
6649 {
6650 this.sc = sc;
6651 }
6652
6653 override void visit(Dsymbol d)
6654 {
6655 //printf("Dsymbol::setScope() %p %s, %p stc = %llx\n", d, d.toChars(), sc, sc.stc);
6656 if (!sc.nofree)
6657 sc.setNoFree(); // may need it even after semantic() finishes
6658 d._scope = sc;
6659 if (sc.depdecl)
6660 d.depdecl = sc.depdecl;
6661 if (!d.userAttribDecl)
6662 d.userAttribDecl = sc.userAttribDecl;
6663 }
6664
6665 override void visit(Import i)
6666 {
6667 visit(cast(Dsymbol)i);
6668 if (i.aliasdecls.length)
6669 {
6670 if (!i.mod)
6671 i.importAll(sc);
6672
6673 sc = sc.push(i.mod);
6674 sc.visibility = i.visibility;
6675 foreach (ad; i.aliasdecls)
6676 ad.setScope(sc);
6677 sc = sc.pop();
6678 }
6679 }
6680
6681 override void visit(Nspace ns)
6682 {
6683 visit(cast(Dsymbol)ns);
6684 if (ns.members)
6685 {
6686 assert(sc);
6687 sc = sc.push(ns);
6688 sc.linkage = LINK.cpp; // namespaces default to C++ linkage
6689 sc.parent = ns;
6690 ns.members.foreachDsymbol(s => s.setScope(sc));
6691 sc.pop();
6692 }
6693 }
6694
6695 override void visit(EnumDeclaration ed)
6696 {
6697 if (ed.semanticRun > PASS.initial)
6698 return;
6699 visit(cast(Dsymbol)ed);
6700 }
6701
6702 override void visit(AggregateDeclaration ad)
6703 {
6704 // Might need a scope to resolve forward references. The check for
6705 // semanticRun prevents unnecessary setting of _scope during deferred
6706 // setScope phases for aggregates which already finished semantic().
6707 // See https://issues.dlang.org/show_bug.cgi?id=16607
6708 if (ad.semanticRun < PASS.semanticdone)
6709 visit(cast(Dsymbol)ad);
6710 }
6711
6712 override void visit(AttribDeclaration atr)
6713 {
6714 Dsymbols* d = atr.include(sc);
6715 //printf("\tAttribDeclaration::setScope '%s', d = %p\n",toChars(), d);
6716 if (d)
6717 {
6718 Scope* sc2 = atr.newScope(sc);
6719 d.foreachDsymbol( s => s.setScope(sc2) );
6720 if (sc2 != sc)
6721 sc2.pop();
6722 }
6723 }
6724
6725 override void visit(DeprecatedDeclaration dd)
6726 {
6727 //printf("DeprecatedDeclaration::setScope() %p\n", this);
6728 if (dd.decl)
6729 visit(cast(Dsymbol)dd); // for forward reference
6730 visit(cast(AttribDeclaration)dd);
6731 }
6732
6733 override void visit(CPPMangleDeclaration cppmd)
6734 {
6735 if (cppmd.decl)
6736 visit(cast(Dsymbol)cppmd); // for forward reference
6737 visit(cast(AttribDeclaration)cppmd);
6738 }
6739
6740 override void visit(AnonDeclaration anond)
6741 {
6742 if (anond.decl)
6743 visit(cast(Dsymbol)anond); // for forward reference
6744 visit(cast(AttribDeclaration)anond);
6745 }
6746
6747 override void visit(ConditionalDeclaration condd)
6748 {
6749 condd.include(sc).foreachDsymbol( s => s.setScope(sc) );
6750 }
6751
6752 override void visit(StaticIfDeclaration sid)
6753 {
6754 // do not evaluate condition before semantic pass
6755 // But do set the scope, in case we need it for forward referencing
6756 visit(cast(Dsymbol)sid); // for forward reference
6757 }
6758
6759 override void visit(StaticForeachDeclaration sfd)
6760 {
6761 // do not evaluate condition before semantic pass
6762 // But do set the scope, in case we need it for forward referencing
6763 visit(cast(Dsymbol)sfd); // for forward reference
6764 }
6765
6766 override void visit(MixinDeclaration md)
6767 {
6768 visit(cast(Dsymbol)md);
6769 }
6770
6771 override void visit(UserAttributeDeclaration uad)
6772 {
6773 //printf("UserAttributeDeclaration::setScope() %p\n", this);
6774 if (uad.decl)
6775 visit(cast(Dsymbol)uad);
6776 visit(cast(AttribDeclaration)uad);
6777 }
6778 }
6779
6780 void importAll(Dsymbol d, Scope* sc)
6781 {
6782 scope iav = new ImportAllVisitor(sc);
6783 d.accept(iav);
6784 }
6785
6786 extern(C++) class ImportAllVisitor : Visitor
6787 {
6788 alias visit = typeof(super).visit;
6789 Scope* sc;
6790
6791 this(Scope* sc) @safe
6792 {
6793 this.sc = sc;
6794 }
6795
6796 override void visit(Dsymbol d) {}
6797
6798 override void visit(Import imp)
6799 {
6800 if (imp.mod) return; // Already done
6801
6802 /*
6803 * https://issues.dlang.org/show_bug.cgi?id=15525
6804 *
6805 * Loading the import has failed,
6806 * most likely because of parsing errors.
6807 * Therefore we cannot trust the resulting AST.
6808 */
6809 if (imp.load(sc))
6810 {
6811 // https://issues.dlang.org/show_bug.cgi?id=23873
6812 // For imports that are not at module or function level,
6813 // e.g. aggregate level, the import symbol is added to the
6814 // symbol table and later semantic is performed on it.
6815 // This leads to semantic analysis on an malformed AST
6816 // which causes all kinds of segfaults.
6817 // The fix is to note that the module has errors and avoid
6818 // semantic analysis on it.
6819 if(imp.mod)
6820 imp.mod.errors = true;
6821 return;
6822 }
6823
6824 if (!imp.mod) return; // Failed
6825
6826 if (sc.stc & STC.static_)
6827 imp.isstatic = true;
6828 imp.mod.importAll(null);
6829 imp.mod.checkImportDeprecation(imp.loc, sc);
6830 if (sc.explicitVisibility)
6831 imp.visibility = sc.visibility;
6832 if (!imp.isstatic && !imp.aliasId && !imp.names.length)
6833 sc.scopesym.importScope(imp.mod, imp.visibility);
6834 // Enable access to pkgs/mod as soon as posible, because compiler
6835 // can traverse them before the import gets semantic (Issue: 21501)
6836 if (!imp.aliasId && !imp.names.length)
6837 imp.addPackageAccess(sc.scopesym);
6838 }
6839
6840 override void visit(Module m)
6841 {
6842 //printf("+Module::importAll(this = %p, '%s'): parent = %p\n", m, m.toChars(), m.parent);
6843 if (m._scope)
6844 return; // already done
6845 if (m.filetype == FileType.ddoc)
6846 {
6847 error(m.loc, "%s `%s` is a Ddoc file, cannot import it", m.kind, m.toPrettyChars);
6848 return;
6849 }
6850
6851 /* Note that modules get their own scope, from scratch.
6852 * This is so regardless of where in the syntax a module
6853 * gets imported, it is unaffected by context.
6854 * Ignore prevsc.
6855 */
6856 Scope* sc = Scope.createGlobal(m, global.errorSink); // create root scope
6857
6858 if (m.md && m.md.msg)
6859 m.md.msg = semanticString(sc, m.md.msg, "deprecation message");
6860
6861 // Add import of "object", even for the "object" module.
6862 // If it isn't there, some compiler rewrites, like
6863 // classinst == classinst -> .object.opEquals(classinst, classinst)
6864 // would fail inside object.d.
6865 if (m.filetype != FileType.c &&
6866 (m.members.length == 0 ||
6867 (*m.members)[0].ident != Id.object ||
6868 (*m.members)[0].isImport() is null))
6869 {
6870 auto im = new Import(m.loc, null, Id.object, null, 0);
6871 m.members.shift(im);
6872 }
6873 if (!m.symtab)
6874 {
6875 // Add all symbols into module's symbol table
6876 m.symtab = new DsymbolTable();
6877 for (size_t i = 0; i < m.members.length; i++)
6878 {
6879 Dsymbol s = (*m.members)[i];
6880 s.addMember(sc, sc.scopesym);
6881 }
6882 }
6883 // anything else should be run after addMember, so version/debug symbols are defined
6884 /* Set scope for the symbols so that if we forward reference
6885 * a symbol, it can possibly be resolved on the spot.
6886 * If this works out well, it can be extended to all modules
6887 * before any semantic() on any of them.
6888 */
6889 m.setScope(sc); // remember module scope for semantic
6890 for (size_t i = 0; i < m.members.length; i++)
6891 {
6892 Dsymbol s = (*m.members)[i];
6893 s.setScope(sc);
6894 }
6895 for (size_t i = 0; i < m.members.length; i++)
6896 {
6897 Dsymbol s = (*m.members)[i];
6898 s.importAll(sc);
6899 }
6900 sc = sc.pop();
6901 sc.pop(); // 2 pops because Scope.createGlobal() created 2
6902 }
6903
6904 override void visit(AttribDeclaration atb)
6905 {
6906 Dsymbols* d = atb.include(sc);
6907 //printf("\tAttribDeclaration::importAll '%s', d = %p\n", toChars(), d);
6908 if (d)
6909 {
6910 Scope* sc2 = atb.newScope(sc);
6911 d.foreachDsymbol( s => s.importAll(sc2) );
6912 if (sc2 != sc)
6913 sc2.pop();
6914 }
6915 }
6916
6917 // do not evaluate condition before semantic pass
6918 override void visit(StaticIfDeclaration _) {}
6919 // do not evaluate aggregate before semantic pass
6920 override void visit(StaticForeachDeclaration _) {}
6921 }
6922
6923 /*******************************
6924 * Load module.
6925 * Returns:
6926 * true for errors, false for success
6927 */
6928 extern (D) bool load(Import imp, Scope* sc)
6929 {
6930 // See if existing module
6931 const errors = global.errors;
6932 DsymbolTable dst = Package.resolve(imp.packages, null, &imp.pkg);
6933 version (none)
6934 {
6935 if (pkg && pkg.isModule())
6936 {
6937 .error(loc, "can only import from a module, not from a member of module `%s`. Did you mean `import %s : %s`?", pkg.toChars(), pkg.toPrettyChars(), id.toChars());
6938 mod = pkg.isModule(); // Error recovery - treat as import of that module
6939 return true;
6940 }
6941 }
6942 Dsymbol s = dst.lookup(imp.id);
6943 if (s)
6944 {
6945 if (s.isModule())
6946 imp.mod = cast(Module)s;
6947 else
6948 {
6949 if (s.isAliasDeclaration())
6950 {
6951 .error(imp.loc, "%s `%s` conflicts with `%s`", s.kind(), s.toPrettyChars(), imp.id.toChars());
6952 }
6953 else if (Package p = s.isPackage())
6954 {
6955 if (p.isPkgMod == PKG.unknown)
6956 {
6957 const preverrors = global.errors;
6958 imp.mod = Module.load(imp.loc, imp.packages, imp.id);
6959 if (!imp.mod)
6960 p.isPkgMod = PKG.package_;
6961 else
6962 {
6963 // imp.mod is a package.d, or a normal module which conflicts with the package name.
6964 if (imp.mod.isPackageFile)
6965 imp.mod.tag = p.tag; // reuse the same package tag
6966 else
6967 {
6968 // show error if Module.load does not
6969 if (preverrors == global.errors)
6970 .error(imp.loc, "%s `%s` from file %s conflicts with %s `%s`", imp.mod.kind(), imp.mod.toPrettyChars(), imp.mod.srcfile.toChars, p.kind(), p.toPrettyChars());
6971 return true;
6972 }
6973 }
6974 }
6975 else
6976 {
6977 imp.mod = p.isPackageMod();
6978 }
6979 if (!imp.mod)
6980 {
6981 .error(imp.loc, "can only import from a module, not from package `%s.%s`", p.toPrettyChars(), imp.id.toChars());
6982 }
6983 }
6984 else if (imp.pkg)
6985 {
6986 .error(imp.loc, "can only import from a module, not from package `%s.%s`", imp.pkg.toPrettyChars(), imp.id.toChars());
6987 }
6988 else
6989 {
6990 .error(imp.loc, "can only import from a module, not from package `%s`", imp.id.toChars());
6991 }
6992 }
6993 }
6994 if (!imp.mod)
6995 {
6996 // Load module
6997 imp.mod = Module.load(imp.loc, imp.packages, imp.id);
6998 if (imp.mod)
6999 {
7000 // imp.id may be different from mod.ident, if so then insert alias
7001 dst.insert(imp.id, imp.mod);
7002 }
7003 }
7004 if (imp.mod && !imp.mod.importedFrom)
7005 imp.mod.importedFrom = sc ? sc._module.importedFrom : Module.rootModule;
7006 if (!imp.pkg)
7007 {
7008 if (imp.mod && imp.mod.isPackageFile)
7009 {
7010 // one level depth package.d file (import pkg; ./pkg/package.d)
7011 // it's necessary to use the wrapping Package already created
7012 imp.pkg = imp.mod.pkg;
7013 }
7014 else
7015 imp.pkg = imp.mod;
7016 }
7017 return global.errors != errors;
7018 }
7019
7020 void setFieldOffset(Dsymbol d, AggregateDeclaration ad, FieldState* fieldState, bool isunion)
7021 {
7022 scope v = new SetFieldOffsetVisitor(ad, fieldState, isunion);
7023 d.accept(v);
7024 }
7025
7026 private extern(C++) class SetFieldOffsetVisitor : Visitor
7027 {
7028 alias visit = Visitor.visit;
7029
7030 AggregateDeclaration ad;
7031 FieldState* fieldState;
7032 bool isunion;
7033
7034 this(AggregateDeclaration ad, FieldState* fieldState, bool isunion) @safe
7035 {
7036 this.ad = ad;
7037 this.fieldState = fieldState;
7038 this.isunion = isunion;
7039 }
7040
7041 override void visit(Dsymbol d) {}
7042
7043 override void visit(Nspace ns)
7044 {
7045 //printf("Nspace::setFieldOffset() %s\n", toChars());
7046 if (ns._scope) // if fwd reference
7047 dsymbolSemantic(ns, null); // try to resolve it
7048 ns.members.foreachDsymbol( s => s.setFieldOffset(ad, fieldState, isunion) );
7049 }
7050
7051 override void visit(VarDeclaration vd)
7052 {
7053 //printf("VarDeclaration::setFieldOffset(ad = %s) %s\n", ad.toChars(), vd.toChars());
7054
7055 if (vd.aliasTuple)
7056 {
7057 // If this variable was really a tuple, set the offsets for the tuple fields
7058 vd.aliasTuple.foreachVar((s) { s.setFieldOffset(ad, fieldState, isunion); });
7059 return;
7060 }
7061
7062 if (!vd.isField())
7063 return;
7064 assert(!(vd.storage_class & (STC.static_ | STC.extern_ | STC.parameter)));
7065
7066 //printf("+VarDeclaration::setFieldOffset(ad = %s) %s\n", ad.toChars(), toChars());
7067
7068 /* Fields that are tuples appear both as part of TupleDeclarations and
7069 * as members. That means ignore them if they are already a field.
7070 */
7071 if (vd.offset)
7072 {
7073 // already a field
7074 fieldState.offset = ad.structsize; // https://issues.dlang.org/show_bug.cgi?id=13613
7075 return;
7076 }
7077 for (size_t i = 0; i < ad.fields.length; i++)
7078 {
7079 if (ad.fields[i] == vd)
7080 {
7081 // already a field
7082 fieldState.offset = ad.structsize; // https://issues.dlang.org/show_bug.cgi?id=13613
7083 return;
7084 }
7085 }
7086
7087 // Check for forward referenced types which will fail the size() call
7088 Type t = vd.type.toBasetype();
7089 if (vd.storage_class & STC.ref_)
7090 {
7091 // References are the size of a pointer
7092 t = Type.tvoidptr;
7093 }
7094 Type tv = t.baseElemOf();
7095 if (tv.ty == Tstruct)
7096 {
7097 auto ts = cast(TypeStruct)tv;
7098 assert(ts.sym != ad); // already checked in ad.determineFields()
7099 if (!ts.sym.determineSize(vd.loc))
7100 {
7101 vd.type = Type.terror;
7102 vd.errors = true;
7103 return;
7104 }
7105 }
7106
7107 // List in ad.fields. Even if the type is error, it's necessary to avoid
7108 // pointless error diagnostic "more initializers than fields" on struct literal.
7109 ad.fields.push(vd);
7110
7111 if (t.ty == Terror)
7112 return;
7113
7114 /* If coming after a bit field in progress,
7115 * advance past the field
7116 */
7117 fieldState.inFlight = false;
7118
7119 const sz = t.size(vd.loc);
7120 assert(sz != SIZE_INVALID && sz < uint.max);
7121 uint memsize = cast(uint)sz; // size of member
7122 uint memalignsize = target.fieldalign(t); // size of member for alignment purposes
7123 vd.offset = placeField(vd.loc,
7124 fieldState.offset,
7125 memsize, memalignsize, vd.alignment,
7126 ad.structsize, ad.alignsize,
7127 isunion);
7128
7129 //printf("\t%s: memalignsize = %d\n", toChars(), memalignsize);
7130 //printf(" addField '%s' to '%s' at offset %d, size = %d\n", toChars(), ad.toChars(), offset, memsize);
7131 }
7132
7133 override void visit(BitFieldDeclaration bfd)
7134 {
7135 enum log = false;
7136 static if (log)
7137 {
7138 printf("BitFieldDeclaration::setFieldOffset(ad: %s, field: %s)\n", ad.toChars(), bfd.toChars());
7139 void print(const FieldState* fieldState)
7140 {
7141 fieldState.print();
7142 printf(" fieldWidth = %d bits\n", bfd.fieldWidth);
7143 }
7144 print(fieldState);
7145 }
7146
7147 Type t = bfd.type.toBasetype();
7148 const bool anon = bfd.isAnonymous();
7149
7150 // List in ad.fields. Even if the type is error, it's necessary to avoid
7151 // pointless error diagnostic "more initializers than fields" on struct literal.
7152 if (!anon)
7153 ad.fields.push(bfd);
7154
7155 if (t.ty == Terror)
7156 return;
7157
7158 const sz = t.size(bfd.loc);
7159 assert(sz != SIZE_INVALID && sz < uint.max);
7160 uint memsize = cast(uint)sz; // size of member
7161 uint memalignsize = target.fieldalign(t); // size of member for alignment purposes
7162 if (log) printf(" memsize: %u memalignsize: %u\n", memsize, memalignsize);
7163
7164 if (bfd.fieldWidth == 0 && !anon)
7165 error(bfd.loc, "named bit fields cannot have 0 width");
7166 if (bfd.fieldWidth > memsize * 8)
7167 error(bfd.loc, "bit field width %d is larger than type", bfd.fieldWidth);
7168
7169 const style = target.c.bitFieldStyle;
7170 if (style != TargetC.BitFieldStyle.MS && style != TargetC.BitFieldStyle.Gcc_Clang)
7171 assert(0, "unsupported bit-field style");
7172
7173 const isMicrosoftStyle = style == TargetC.BitFieldStyle.MS;
7174 const contributesToAggregateAlignment = target.c.contributesToAggregateAlignment(bfd);
7175
7176 void startNewField()
7177 {
7178 if (log) printf("startNewField()\n");
7179 uint alignsize;
7180 if (isMicrosoftStyle)
7181 alignsize = memsize; // not memalignsize
7182 else
7183 {
7184 if (bfd.fieldWidth > 32)
7185 alignsize = memalignsize;
7186 else if (bfd.fieldWidth > 16)
7187 alignsize = 4;
7188 else if (bfd.fieldWidth > 8)
7189 alignsize = 2;
7190 else
7191 alignsize = 1;
7192 }
7193
7194 uint dummy;
7195 bfd.offset = placeField(bfd.loc,
7196 fieldState.offset,
7197 memsize, alignsize, bfd.alignment,
7198 ad.structsize,
7199 contributesToAggregateAlignment ? ad.alignsize : dummy,
7200 isunion);
7201
7202 fieldState.inFlight = true;
7203 fieldState.fieldOffset = bfd.offset;
7204 fieldState.bitOffset = 0;
7205 fieldState.fieldSize = memsize;
7206 }
7207
7208 if (ad.alignsize == 0)
7209 ad.alignsize = 1;
7210 if (!isMicrosoftStyle && contributesToAggregateAlignment && ad.alignsize < memalignsize)
7211 ad.alignsize = memalignsize;
7212
7213 if (bfd.fieldWidth == 0)
7214 {
7215 if (!isMicrosoftStyle && !isunion)
7216 {
7217 // Use type of zero width field to align to next field
7218 fieldState.offset = (fieldState.offset + memalignsize - 1) & ~(memalignsize - 1);
7219 ad.structsize = fieldState.offset;
7220 }
7221 else if (isMicrosoftStyle && fieldState.inFlight && !isunion)
7222 {
7223 // documentation says align to next int
7224 //const alsz = cast(uint)Type.tint32.size();
7225 const alsz = memsize; // but it really does this
7226 fieldState.offset = (fieldState.offset + alsz - 1) & ~(alsz - 1);
7227 ad.structsize = fieldState.offset;
7228 }
7229
7230 fieldState.inFlight = false;
7231 return;
7232 }
7233
7234 if (!fieldState.inFlight)
7235 {
7236 //printf("not in flight\n");
7237 startNewField();
7238 }
7239 else if (!isMicrosoftStyle)
7240 {
7241 // If the bit-field spans more units of alignment than its type
7242 // and is at the alignment boundary, start a new field at the
7243 // next alignment boundary. This affects when offsetof reports
7244 // a higher number and bitoffsetof starts at zero again.
7245 if (fieldState.bitOffset % (memalignsize * 8) == 0 &&
7246 fieldState.bitOffset + bfd.fieldWidth > memsize * 8)
7247 {
7248 if (log) printf("more units of alignment than its type\n");
7249 startNewField(); // the bit field is full
7250 }
7251 else
7252 {
7253 // if alignment boundary is crossed
7254 uint start = (fieldState.fieldOffset * 8 + fieldState.bitOffset) % (memalignsize * 8);
7255 uint end = start + bfd.fieldWidth;
7256 //printf("%s start: %d end: %d memalignsize: %d\n", ad.toChars(), start, end, memalignsize);
7257 if (start / (memsize * 8) != (end - 1) / (memsize * 8))
7258 {
7259 if (log) printf("alignment is crossed\n");
7260 startNewField();
7261 }
7262 }
7263 }
7264 else
7265 {
7266 if (memsize != fieldState.fieldSize ||
7267 fieldState.bitOffset + bfd.fieldWidth > fieldState.fieldSize * 8)
7268 {
7269 //printf("new field\n");
7270 startNewField();
7271 }
7272 }
7273
7274 bfd.offset = fieldState.fieldOffset;
7275 bfd.bitOffset = fieldState.bitOffset;
7276
7277 const pastField = bfd.bitOffset + bfd.fieldWidth;
7278 if (isMicrosoftStyle)
7279 fieldState.fieldSize = memsize;
7280 else
7281 {
7282 const size = (pastField + 7) / 8;
7283 fieldState.fieldSize = size;
7284 //printf(" offset: %d, size: %d\n", offset, size);
7285 if (isunion)
7286 {
7287 const newstructsize = bfd.offset + size;
7288 if (newstructsize > ad.structsize)
7289 ad.structsize = newstructsize;
7290 }
7291 else
7292 ad.structsize = bfd.offset + size;
7293 }
7294 //printf("at end: ad.structsize = %d\n", cast(int)ad.structsize);
7295 //print(fieldState);
7296
7297 if (!isunion)
7298 {
7299 fieldState.offset = bfd.offset + fieldState.fieldSize;
7300 fieldState.bitOffset = pastField;
7301 }
7302
7303 //printf("\t%s: offset = %d bitOffset = %d fieldWidth = %d memsize = %d\n", toChars(), offset, bitOffset, fieldWidth, memsize);
7304 //printf("\t%s: memalignsize = %d\n", toChars(), memalignsize);
7305 //printf(" addField '%s' to '%s' at offset %d, size = %d\n", toChars(), ad.toChars(), offset, memsize);
7306 }
7307
7308 override void visit(TemplateMixin tm)
7309 {
7310 //printf("TemplateMixin.setFieldOffset() %s\n", tm.toChars());
7311 if (tm._scope) // if fwd reference
7312 dsymbolSemantic(tm, null); // try to resolve it
7313
7314 tm.members.foreachDsymbol( (s) { s.setFieldOffset(ad, fieldState, isunion); } );
7315 }
7316
7317 override void visit(AttribDeclaration atd)
7318 {
7319 atd.include(null).foreachDsymbol( s => s.setFieldOffset(ad, fieldState, isunion) );
7320 }
7321
7322 override void visit(AnonDeclaration anond)
7323 {
7324 //printf("\tAnonDeclaration::setFieldOffset %s %p\n", isunion ? "union" : "struct", anond);
7325 if (anond.decl)
7326 {
7327 /* This works by treating an AnonDeclaration as an aggregate 'member',
7328 * so in order to place that member we need to compute the member's
7329 * size and alignment.
7330 */
7331 size_t fieldstart = ad.fields.length;
7332
7333 /* Hackishly hijack ad's structsize and alignsize fields
7334 * for use in our fake anon aggregate member.
7335 */
7336 uint savestructsize = ad.structsize;
7337 uint savealignsize = ad.alignsize;
7338 ad.structsize = 0;
7339 ad.alignsize = 0;
7340
7341 FieldState fs;
7342 anond.decl.foreachDsymbol( (s)
7343 {
7344 s.setFieldOffset(ad, &fs, anond.isunion);
7345 if (anond.isunion)
7346 fs.offset = 0;
7347 });
7348
7349 /* https://issues.dlang.org/show_bug.cgi?id=13613
7350 * If the fields in this.members had been already
7351 * added in ad.fields, just update *poffset for the subsequent
7352 * field offset calculation.
7353 */
7354 if (fieldstart == ad.fields.length)
7355 {
7356 ad.structsize = savestructsize;
7357 ad.alignsize = savealignsize;
7358 fieldState.offset = ad.structsize;
7359 return;
7360 }
7361
7362 anond.anonstructsize = ad.structsize;
7363 anond.anonalignsize = ad.alignsize;
7364 ad.structsize = savestructsize;
7365 ad.alignsize = savealignsize;
7366
7367 // 0 sized structs are set to 1 byte
7368 if (anond.anonstructsize == 0)
7369 {
7370 anond.anonstructsize = 1;
7371 anond.anonalignsize = 1;
7372 }
7373
7374 assert(anond._scope);
7375 auto alignment = anond._scope.alignment();
7376
7377 /* Given the anon 'member's size and alignment,
7378 * go ahead and place it.
7379 */
7380 anond.anonoffset = placeField(anond.loc,
7381 fieldState.offset,
7382 anond.anonstructsize, anond.anonalignsize, alignment,
7383 ad.structsize, ad.alignsize,
7384 isunion);
7385
7386 // Add to the anon fields the base offset of this anonymous aggregate
7387 //printf("anon fields, anonoffset = %d\n", anonoffset);
7388 foreach (const i; fieldstart .. ad.fields.length)
7389 {
7390 VarDeclaration v = ad.fields[i];
7391 //printf("\t[%d] %s %d\n", i, v.toChars(), v.offset);
7392 v.offset += anond.anonoffset;
7393 }
7394 }
7395 }
7396 }
7397
7398 extern(D) Scope* newScope(Dsymbol d, Scope* sc)
7399 {
7400 scope nsv = new NewScopeVisitor(sc);
7401 d.accept(nsv);
7402 return nsv.sc;
7403 }
7404
7405 private extern(C++) class NewScopeVisitor : Visitor
7406 {
7407 alias visit = typeof(super).visit;
7408 Scope* sc;
7409 this(Scope* sc)
7410 {
7411 this.sc = sc;
7412 }
7413
7414 /****************************************
7415 * A hook point to supply scope for members.
7416 * addMember, setScope, importAll, semantic, semantic2 and semantic3 will use this.
7417 */
7418 override void visit(AttribDeclaration dc){}
7419
7420 override void visit(StorageClassDeclaration swt)
7421 {
7422 STC scstc = sc.stc;
7423 /* These sets of storage classes are mutually exclusive,
7424 * so choose the innermost or most recent one.
7425 */
7426 if (swt.stc & (STC.auto_ | STC.scope_ | STC.static_ | STC.extern_ | STC.manifest))
7427 scstc &= ~(STC.auto_ | STC.scope_ | STC.static_ | STC.extern_ | STC.manifest);
7428 if (swt.stc & (STC.auto_ | STC.scope_ | STC.static_ | STC.manifest | STC.gshared))
7429 scstc &= ~(STC.auto_ | STC.scope_ | STC.static_ | STC.manifest | STC.gshared);
7430 if (swt.stc & (STC.const_ | STC.immutable_ | STC.manifest))
7431 scstc &= ~(STC.const_ | STC.immutable_ | STC.manifest);
7432 if (swt.stc & (STC.gshared | STC.shared_))
7433 scstc &= ~(STC.gshared | STC.shared_);
7434 if (swt.stc & (STC.safe | STC.trusted | STC.system))
7435 scstc &= ~(STC.safe | STC.trusted | STC.system);
7436 scstc |= swt.stc;
7437 //printf("scstc = x%llx\n", scstc);
7438 sc = swt.createNewScope(sc, scstc, sc.linkage, sc.cppmangle,
7439 sc.visibility, sc.explicitVisibility, sc.aligndecl, sc.inlining);
7440 }
7441
7442 /**
7443 * Provides a new scope with `STC.deprecated_` and `Scope.depdecl` set
7444 *
7445 * Calls `StorageClassDeclaration.newScope` (as it must be called or copied
7446 * in any function overriding `newScope`), then set the `Scope`'s depdecl.
7447 *
7448 * Returns:
7449 * Always a new scope, to use for this `DeprecatedDeclaration`'s members.
7450 */
7451 override void visit(DeprecatedDeclaration dpd)
7452 {
7453 auto oldsc = sc;
7454 visit((cast(StorageClassDeclaration)dpd));
7455 auto scx = sc;
7456 sc = oldsc;
7457 // The enclosing scope is deprecated as well
7458 if (scx == sc)
7459 scx = sc.push();
7460 scx.depdecl = dpd;
7461 sc = scx;
7462 }
7463
7464 override void visit(LinkDeclaration lid)
7465 {
7466 sc= lid.createNewScope(sc, sc.stc, lid.linkage, sc.cppmangle, sc.visibility, sc.explicitVisibility,
7467 sc.aligndecl, sc.inlining);
7468 }
7469
7470 override void visit(CPPMangleDeclaration cpmd)
7471 {
7472 sc = cpmd.createNewScope(sc, sc.stc, LINK.cpp, cpmd.cppmangle, sc.visibility, sc.explicitVisibility,
7473 sc.aligndecl, sc.inlining);
7474 }
7475
7476 /**
7477 * Returns:
7478 * A copy of the parent scope, with `this` as `namespace` and C++ linkage
7479 *///override Scope* visit(Scope* sc)
7480 override void visit(CPPNamespaceDeclaration scd)
7481 {
7482 auto scx = sc.copy();
7483 scx.linkage = LINK.cpp;
7484 scx.namespace = scd;
7485 sc = scx;
7486 }
7487
7488 override void visit(VisibilityDeclaration atbd)
7489 {
7490 if (atbd.pkg_identifiers)
7491 dsymbolSemantic(atbd, sc);
7492
7493 sc = atbd.createNewScope(sc, sc.stc, sc.linkage, sc.cppmangle, atbd.visibility, 1, sc.aligndecl, sc.inlining);
7494 }
7495
7496 override void visit(AlignDeclaration visd)
7497 {
7498 sc = visd.createNewScope(sc, sc.stc, sc.linkage, sc.cppmangle, sc.visibility,
7499 sc.explicitVisibility, visd, sc.inlining);
7500 }
7501
7502 override void visit(PragmaDeclaration prd)
7503 {
7504 if (prd.ident == Id.Pinline)
7505 {
7506 // We keep track of this pragma inside scopes,
7507 // then it's evaluated on demand in function semantic
7508 sc = prd.createNewScope(sc, sc.stc, sc.linkage, sc.cppmangle, sc.visibility, sc.explicitVisibility, sc.aligndecl, prd); // @suppress(dscanner.style.long_line)
7509 }
7510 }
7511
7512 /**************************************
7513 * Use the ForwardingScopeDsymbol as the parent symbol for members.
7514 */
7515 override void visit(ForwardingAttribDeclaration fad)
7516 {
7517 sc = sc.push(fad.sym);
7518 }
7519
7520 override void visit(UserAttributeDeclaration uac)
7521 {
7522 Scope* sc2 = sc;
7523 if (uac.atts && uac.atts.length)
7524 {
7525 // create new one for changes
7526 sc2 = sc.copy();
7527 sc2.userAttribDecl = uac;
7528 }
7529 sc = sc2;
7530 }
7531 }
7532
7533
7534 extern(C++) Dsymbols* include(Dsymbol d, Scope* sc)
7535 {
7536 scope icv = new IncludeVisitor(sc);
7537 d.accept(icv);
7538 return icv.symbols;
7539 }
7540
7541 extern(C++) class IncludeVisitor : Visitor
7542 {
7543 alias visit = typeof(super).visit;
7544 Scope* sc;
7545 Dsymbols* symbols;
7546 this(Scope* sc)
7547 {
7548 this.sc = sc;
7549 }
7550
7551 override void visit(AttribDeclaration ad)
7552 {
7553 if (ad.errors)
7554 {
7555 symbols = null;
7556 return;
7557 }
7558 symbols = ad.decl;
7559 return;
7560 }
7561
7562 // Decide if 'then' or 'else' code should be included
7563 override void visit(ConditionalDeclaration cdc)
7564 {
7565 //printf("ConditionalDeclaration::include(sc = %p) scope = %p\n", sc, _scope);
7566
7567 if (cdc.errors)
7568 {
7569 symbols = null;
7570 return;
7571 }
7572 assert(cdc.condition);
7573 symbols = cdc.condition.include(cdc._scope ? cdc._scope : sc) ? cdc.decl : cdc.elsedecl;
7574 }
7575
7576 override void visit(StaticIfDeclaration sif)
7577 {
7578 /****************************************
7579 * Different from other AttribDeclaration subclasses, include() call requires
7580 * the completion of addMember and setScope phases.
7581 */
7582 //printf("StaticIfDeclaration::include(sc = %p) scope = %p\n", sc, _scope);
7583 if (sif.errors || sif.onStack)
7584 {
7585 symbols = null;
7586 return;
7587 }
7588 sif.onStack = true;
7589 scope(exit) sif.onStack = false;
7590
7591 if (sc && sif.condition.inc == Include.notComputed)
7592 {
7593 assert(sif.scopesym); // addMember is already done
7594 assert(sif._scope); // setScope is already done
7595
7596 Scope* saved_scope = sc;
7597 sc = sif._scope;
7598 visit(cast(ConditionalDeclaration) sif);
7599 Dsymbols* d = symbols;
7600 sc = saved_scope;
7601
7602 if (d && !sif.addisdone)
7603 {
7604 // Add members lazily.
7605 d.foreachDsymbol( s => s.addMember(sif._scope, sif.scopesym) );
7606
7607 // Set the member scopes lazily.
7608 d.foreachDsymbol( s => s.setScope(sif._scope) );
7609
7610 sif.addisdone = true;
7611 }
7612 symbols = d;
7613 return;
7614 }
7615 else
7616 {
7617 visit(cast(ConditionalDeclaration)sif);
7618 }
7619 }
7620
7621 override void visit(StaticForeachDeclaration sfd)
7622 {
7623 if (sfd.errors || sfd.onStack)
7624 {
7625 symbols = null;
7626 return;
7627 }
7628 if (sfd.cached)
7629 {
7630 assert(!sfd.onStack);
7631 symbols = sfd.cache;
7632 return;
7633 }
7634 sfd.onStack = true;
7635 scope(exit) sfd.onStack = false;
7636
7637 if (sfd._scope)
7638 {
7639 sfd.sfe.prepare(sfd._scope); // lower static foreach aggregate
7640 }
7641 if (!sfd.sfe.ready())
7642 {
7643 symbols = null;// TODO: ok?
7644 return;
7645 }
7646
7647 // expand static foreach
7648 import dmd.statementsem: makeTupleForeach;
7649 Dsymbols* d = makeTupleForeach(sfd._scope, true, true, sfd.sfe.aggrfe, sfd.decl, sfd.sfe.needExpansion).decl;
7650 if (d) // process generated declarations
7651 {
7652 // Add members lazily.
7653 d.foreachDsymbol( s => s.addMember(sfd._scope, sfd.scopesym) );
7654
7655 // Set the member scopes lazily.
7656 d.foreachDsymbol( s => s.setScope(sfd._scope) );
7657 }
7658 sfd.cached = true;
7659 sfd.cache = d;
7660 symbols = d;
7661 }
7662 }
7663
7664 /**
7665 * Called from a symbol's semantic to check if `gnuAbiTag` UDA
7666 * can be applied to them
7667 *
7668 * Directly emits an error if the UDA doesn't work with this symbol
7669 *
7670 * Params:
7671 * sym = symbol to check for `gnuAbiTag`
7672 * linkage = Linkage of the symbol (Declaration.link or sc.link)
7673 */
7674 void checkGNUABITag(Dsymbol sym, LINK linkage)
7675 {
7676 if (global.params.cplusplus < CppStdRevision.cpp11)
7677 return;
7678
7679 foreachUdaNoSemantic(sym, (exp) {
7680 if (!isGNUABITag(exp))
7681 return 0; // continue
7682 if (sym.isCPPNamespaceDeclaration() || sym.isNspace())
7683 {
7684 .error(exp.loc, "`@%s` cannot be applied to namespaces", Id.udaGNUAbiTag.toChars());
7685 sym.errors = true;
7686 }
7687 else if (linkage != LINK.cpp)
7688 {
7689 .error(exp.loc, "`@%s` can only apply to C++ symbols", Id.udaGNUAbiTag.toChars());
7690 sym.errors = true;
7691 }
7692 // Only one `@gnuAbiTag` is allowed by semantic2
7693 return 1; // break
7694 });
7695 }
7696
7697 /**
7698 * Check if the provided expression references `core.attribute.gnuAbiTag`
7699 *
7700 * This should be called after semantic has been run on the expression.
7701 * Semantic on UDA happens in semantic2 (see `dmd.semantic2`).
7702 *
7703 * Params:
7704 * e = Expression to check (usually from `UserAttributeDeclaration.atts`)
7705 *
7706 * Returns:
7707 * `true` if the expression references the compiler-recognized `gnuAbiTag`
7708 */
7709 bool isGNUABITag(Expression e)
7710 {
7711 if (global.params.cplusplus < CppStdRevision.cpp11)
7712 return false;
7713
7714 auto ts = e.type ? e.type.isTypeStruct() : null;
7715 if (!ts)
7716 return false;
7717 if (ts.sym.ident != Id.udaGNUAbiTag || !ts.sym.parent)
7718 return false;
7719 // Can only be defined in druntime
7720 Module m = ts.sym.parent.isModule();
7721 if (!m || !m.isCoreModule(Id.attribute))
7722 return false;
7723 return true;
7724 }
7725
7726 /******************************************
7727 * If a variable has a scope destructor call, return call for it.
7728 * Otherwise, return NULL.
7729 */
7730 private Expression callScopeDtor(VarDeclaration vd, Scope* sc)
7731 {
7732 //printf("VarDeclaration::callScopeDtor() %s\n", toChars());
7733
7734 // Destruction of STC.field's is handled by buildDtor()
7735 if (vd.storage_class & (STC.nodtor | STC.ref_ | STC.out_ | STC.field))
7736 {
7737 return null;
7738 }
7739
7740 if (vd.iscatchvar)
7741 return null; // destructor is built by `void semantic(Catch c, Scope* sc)`, not here
7742
7743 Expression e = null;
7744 // Destructors for structs and arrays of structs
7745 Type tv = vd.type.baseElemOf();
7746 if (tv.ty == Tstruct)
7747 {
7748 StructDeclaration sd = (cast(TypeStruct)tv).sym;
7749 if (!sd.dtor || sd.errors)
7750 return null;
7751
7752 const sz = vd.type.size();
7753 assert(sz != SIZE_INVALID);
7754 if (!sz)
7755 return null;
7756
7757 if (vd.type.toBasetype().ty == Tstruct)
7758 {
7759 // v.__xdtor()
7760 e = new VarExp(vd.loc, vd);
7761
7762 /* This is a hack so we can call destructors on const/immutable objects.
7763 * Need to add things like "const ~this()" and "immutable ~this()" to
7764 * fix properly.
7765 */
7766 e.type = e.type.mutableOf();
7767
7768 // Enable calling destructors on shared objects.
7769 // The destructor is always a single, non-overloaded function,
7770 // and must serve both shared and non-shared objects.
7771 e.type = e.type.unSharedOf;
7772
7773 e = new DotVarExp(vd.loc, e, sd.dtor, false);
7774 e = new CallExp(vd.loc, e);
7775 }
7776 else
7777 {
7778 // __ArrayDtor(v[0 .. n])
7779 e = new VarExp(vd.loc, vd);
7780
7781 const sdsz = sd.type.size();
7782 assert(sdsz != SIZE_INVALID && sdsz != 0);
7783 const n = sz / sdsz;
7784 SliceExp se = new SliceExp(vd.loc, e, new IntegerExp(vd.loc, 0, Type.tsize_t),
7785 new IntegerExp(vd.loc, n, Type.tsize_t));
7786
7787 // Prevent redundant bounds check
7788 se.upperIsInBounds = true;
7789 se.lowerIsLessThanUpper = true;
7790
7791 // This is a hack so we can call destructors on const/immutable objects.
7792 se.type = sd.type.arrayOf();
7793
7794 e = new CallExp(vd.loc, new IdentifierExp(vd.loc, Id.__ArrayDtor), se);
7795 }
7796 return e;
7797 }
7798 // Destructors for classes
7799 if (!(vd.storage_class & (STC.auto_ | STC.scope_) && !(vd.storage_class & STC.parameter)))
7800 return null;
7801
7802 for (ClassDeclaration cd = vd.type.isClassHandle(); cd; cd = cd.baseClass)
7803 {
7804 /* We can do better if there's a way with onstack
7805 * classes to determine if there's no way the monitor
7806 * could be set.
7807 */
7808 //if (cd.isInterfaceDeclaration())
7809 // error("interface `%s` cannot be scope", cd.toChars());
7810
7811 if (!vd.onstack) // if any destructors
7812 continue;
7813 // delete'ing C++ classes crashes (and delete is deprecated anyway)
7814 if (cd.classKind == ClassKind.cpp)
7815 {
7816 // Don't call non-existant dtor
7817 if (!cd.dtor)
7818 break;
7819
7820 e = new VarExp(vd.loc, vd);
7821 e.type = e.type.mutableOf().unSharedOf(); // Hack for mutable ctor on immutable instances
7822 e = new DotVarExp(vd.loc, e, cd.dtor, false);
7823 e = new CallExp(vd.loc, e);
7824 break;
7825 }
7826
7827 // delete this;
7828 Expression ec;
7829 ec = new VarExp(vd.loc, vd);
7830 e = new DeleteExp(vd.loc, ec, true);
7831 break;
7832 }
7833 return e;
7834 }
7835
7836 /***************************************
7837 * Collect all instance fields, then determine instance size.
7838 * Returns:
7839 * false if failed to determine the size.
7840 */
7841 bool determineSize(AggregateDeclaration ad, Loc loc)
7842 {
7843 //printf("AggregateDeclaration::determineSize() %s, sizeok = %d\n", toChars(), sizeok);
7844
7845 // The previous instance size finalizing had:
7846 if (ad.type.ty == Terror || ad.errors)
7847 return false; // failed already
7848 if (ad.sizeok == Sizeok.done)
7849 return true; // succeeded
7850
7851 if (!ad.members)
7852 {
7853 .error(loc, "%s `%s` unknown size", ad.kind, ad.toPrettyChars);
7854 return false;
7855 }
7856
7857 if (ad._scope)
7858 dsymbolSemantic(ad, null);
7859
7860 // Determine the instance size of base class first.
7861 if (auto cd = ad.isClassDeclaration())
7862 {
7863 cd = cd.baseClass;
7864 if (cd && !cd.determineSize(loc))
7865 goto Lfail;
7866 }
7867
7868 // Determine instance fields when sizeok == Sizeok.none
7869 if (!ad.determineFields())
7870 goto Lfail;
7871 if (ad.sizeok != Sizeok.done)
7872 ad.finalizeSize();
7873
7874 // this aggregate type has:
7875 if (ad.type.ty == Terror)
7876 return false; // marked as invalid during the finalizing.
7877 if (ad.sizeok == Sizeok.done)
7878 return true; // succeeded to calculate instance size.
7879
7880 Lfail:
7881 // There's unresolvable forward reference.
7882 if (ad.type != Type.terror)
7883 error(loc, "%s `%s` no size because of forward reference", ad.kind, ad.toPrettyChars);
7884 // Don't cache errors from speculative semantic, might be resolvable later.
7885 // https://issues.dlang.org/show_bug.cgi?id=16574
7886 if (!global.gag)
7887 {
7888 ad.type = Type.terror;
7889 ad.errors = true;
7890 }
7891 return false;
7892 }
7893
7894 extern (C++) void addComment(Dsymbol d, const(char)* comment)
7895 {
7896 scope v = new AddCommentVisitor(comment);
7897 d.accept(v);
7898 }
7899
7900 extern (C++) class AddCommentVisitor: Visitor
7901 {
7902 alias visit = Visitor.visit;
7903
7904 const(char)* comment;
7905
7906 this(const(char)* comment)
7907 {
7908 this.comment = comment;
7909 }
7910
7911 override void visit(Dsymbol d)
7912 {
7913 if (!comment || !*comment)
7914 return;
7915
7916 //printf("addComment '%s' to Dsymbol %p '%s'\n", comment, this, toChars());
7917 void* h = cast(void*)d; // just the pointer is the key
7918 auto p = h in d.commentHashTable;
7919 if (!p)
7920 {
7921 d.commentHashTable[h] = comment;
7922 return;
7923 }
7924 if (strcmp(*p, comment) != 0)
7925 {
7926 // Concatenate the two
7927 *p = Lexer.combineComments((*p).toDString(), comment.toDString(), true);
7928 }
7929 }
7930 override void visit(AttribDeclaration atd)
7931 {
7932 if (comment)
7933 {
7934 atd.include(null).foreachDsymbol( s => s.addComment(comment) );
7935 }
7936 }
7937 override void visit(ConditionalDeclaration cd)
7938 {
7939 if (comment)
7940 {
7941 cd.decl .foreachDsymbol( s => s.addComment(comment) );
7942 cd.elsedecl.foreachDsymbol( s => s.addComment(comment) );
7943 }
7944 }
7945 override void visit(StaticForeachDeclaration sfd) {}
7946 }
7947
7948 void checkCtorConstInit(Dsymbol d)
7949 {
7950 scope v = new CheckCtorConstInitVisitor();
7951 d.accept(v);
7952 }
7953
7954 private extern(C++) class CheckCtorConstInitVisitor : Visitor
7955 {
7956 alias visit = Visitor.visit;
7957
7958 override void visit(AttribDeclaration ad)
7959 {
7960 ad.include(null).foreachDsymbol( s => s.checkCtorConstInit() );
7961 }
7962
7963 override void visit(VarDeclaration vd)
7964 {
7965 version (none)
7966 {
7967 /* doesn't work if more than one static ctor */
7968 if (vd.ctorinit == 0 && vd.isCtorinit() && !vd.isField())
7969 error("missing initializer in static constructor for const variable");
7970 }
7971 }
7972
7973 override void visit(Dsymbol d){}
7974 }
7975
7976 /**************************************
7977 * Determine if this symbol is only one.
7978 * Returns:
7979 * false, ps = null: There are 2 or more symbols
7980 * true, ps = null: There are zero symbols
7981 * true, ps = symbol: The one and only one symbol
7982 */
7983 bool oneMember(Dsymbol d, out Dsymbol ps, Identifier ident)
7984 {
7985 scope v = new OneMemberVisitor(ps, ident);
7986 d.accept(v);
7987 return v.result;
7988 }
7989
7990 private extern(C++) class OneMemberVisitor : Visitor
7991 {
7992 alias visit = Visitor.visit;
7993
7994 Dsymbol* ps;
7995 Identifier ident;
7996 bool result;
7997
7998 this(out Dsymbol ps, Identifier ident)
7999 {
8000 this.ps = &ps;
8001 this.ident = ident;
8002 }
8003
8004 override void visit(AttribDeclaration atb)
8005 {
8006 Dsymbols* d = atb.include(null);
8007 result = Dsymbol.oneMembers(d, *ps, ident);
8008 }
8009
8010 override void visit(StaticForeachDeclaration sfd)
8011 {
8012 // Required to support IFTI on a template that contains a
8013 // `static foreach` declaration. `super.oneMember` calls
8014 // include with a `null` scope. As `static foreach` requires
8015 // the scope for expansion, `oneMember` can only return a
8016 // precise result once `static foreach` has been expanded.
8017 if (sfd.cached)
8018 {
8019 this.visit(cast(AttribDeclaration) sfd);
8020 }
8021 else
8022 {
8023 *ps = null; // a `static foreach` declaration may in general expand to multiple symbols
8024 result = false;
8025 }
8026 }
8027
8028 override void visit(StorageClassDeclaration scd)
8029 {
8030 bool t = Dsymbol.oneMembers(scd.decl, *ps, ident);
8031 if (t && *ps)
8032 {
8033 /* This is to deal with the following case:
8034 * struct Tick {
8035 * template to(T) { const T to() { ... } }
8036 * }
8037 * For eponymous function templates, the 'const' needs to get attached to 'to'
8038 * before the semantic analysis of 'to', so that template overloading based on the
8039 * 'this' pointer can be successful.
8040 */
8041 if (FuncDeclaration fd = (*ps).isFuncDeclaration())
8042 {
8043 /* Use storage_class2 instead of storage_class otherwise when we do .di generation
8044 * we'll wind up with 'const const' rather than 'const'.
8045 */
8046 /* Don't think we need to worry about mutually exclusive storage classes here
8047 */
8048 fd.storage_class2 |= scd.stc;
8049 }
8050 }
8051 result = t;
8052 }
8053
8054 override void visit(ConditionalDeclaration cd)
8055 {
8056 //printf("ConditionalDeclaration::oneMember(), inc = %d\n", condition.inc);
8057 if (cd.condition.inc != Include.notComputed)
8058 {
8059 Dsymbols* d = cd.condition.include(null) ? cd.decl : cd.elsedecl;
8060 result = Dsymbol.oneMembers(d, *ps, ident);
8061 }
8062 else
8063 {
8064 bool res = (Dsymbol.oneMembers(cd.decl, *ps, ident) && *ps is null && Dsymbol.oneMembers(cd.elsedecl, *ps, ident) && *ps is null);
8065 *ps = null;
8066 result = res;
8067 }
8068 }
8069
8070 override void visit(ScopeDsymbol sd)
8071 {
8072 if (sd.isAnonymous())
8073 result = Dsymbol.oneMembers(sd.members, *ps, ident);
8074 else {
8075 // visit(Dsymbol dsym)
8076 *ps = sd;
8077 result = true;
8078 }
8079 }
8080
8081 override void visit(StaticAssert sa)
8082 {
8083 //printf("StaticAssert::oneMember())\n");
8084 *ps = null;
8085 result = true;
8086 }
8087
8088 override void visit(TemplateInstance ti)
8089 {
8090 *ps = null;
8091 result = true;
8092 }
8093
8094 override void visit(TemplateMixin tm)
8095 {
8096 *ps = tm;
8097 result = true;
8098 }
8099
8100 override void visit(Dsymbol dsym)
8101 {
8102 *ps = dsym;
8103 result = true;
8104 }
8105 }
8106
8107 /****************************************
8108 * Return true if any of the members are static ctors or static dtors, or if
8109 * any members have members that are.
8110 */
8111 extern(C++) bool hasStaticCtorOrDtor(Dsymbol d)
8112 {
8113 scope v = new HasStaticCtorOrDtor();
8114 d.accept(v);
8115 return v.result;
8116 }
8117
8118 private extern(C++) class HasStaticCtorOrDtor : Visitor
8119 {
8120 import dmd.mtype : Type;
8121
8122 alias visit = Visitor.visit;
8123 bool result;
8124
8125 // attrib.d
8126 override void visit(AttribDeclaration ad){
8127 result = ad.include(null).foreachDsymbol( (s) { return s.hasStaticCtorOrDtor(); } ) != 0;
8128 }
8129
8130 // dsymbol.d
8131 override void visit(Dsymbol d){
8132 //printf("Dsymbol::hasStaticCtorOrDtor() %s\n", toChars());
8133 result = false;
8134 }
8135
8136 override void visit(ScopeDsymbol sd) {
8137 if (sd.members)
8138 {
8139 for (size_t i = 0; i < sd.members.length; i++)
8140 {
8141 Dsymbol member = (*(sd.members))[i];
8142 if (member.hasStaticCtorOrDtor())
8143 result = true;
8144 return;
8145 }
8146 }
8147 result = false;
8148 }
8149
8150 // dtemplate.d
8151 override void visit(TemplateDeclaration td) {
8152 result = false; // don't scan uninstantiated templates
8153 }
8154
8155 // func.d
8156 override void visit(StaticCtorDeclaration scd) {
8157 result = true;
8158 }
8159
8160 override void visit(StaticDtorDeclaration sdd) @nogc nothrow pure @safe {
8161 result = true;
8162 }
8163 }
8164
8165 extern(C++) bool isFuncHidden(ClassDeclaration cd, FuncDeclaration fd)
8166 {
8167 import dmd.funcsem : overloadApply;
8168 //printf("ClassDeclaration.isFuncHidden(class = %s, fd = %s)\n", toChars(), fd.toPrettyChars());
8169 Dsymbol s = cd.search(Loc.initial, fd.ident, SearchOpt.ignoreAmbiguous | SearchOpt.ignoreErrors);
8170 if (!s)
8171 {
8172 //printf("not found\n");
8173 /* Because, due to a hack, if there are multiple definitions
8174 * of fd.ident, NULL is returned.
8175 */
8176 return false;
8177 }
8178 s = s.toAlias();
8179 if (auto os = s.isOverloadSet())
8180 {
8181 foreach (sm; os.a)
8182 {
8183 auto fm = sm.isFuncDeclaration();
8184 if (overloadApply(fm, s => fd == s.isFuncDeclaration()))
8185 return false;
8186 }
8187 return true;
8188 }
8189 else
8190 {
8191 auto f = s.isFuncDeclaration();
8192 //printf("%s fdstart = %p\n", s.kind(), fdstart);
8193 if (overloadApply(f, s => fd == s.isFuncDeclaration()))
8194 return false;
8195 return !fd.parent.isTemplateMixin();
8196 }
8197 }
8198
8199 Dsymbol vtblSymbol(ClassDeclaration cd)
8200 {
8201 if (!cd.vtblsym)
8202 {
8203 auto vtype = Type.tvoidptr.immutableOf().sarrayOf(cd.vtbl.length);
8204 auto var = new VarDeclaration(cd.loc, vtype, Identifier.idPool("__vtbl"), null, STC.immutable_ | STC.static_);
8205 var.addMember(null, cd);
8206 var.isdataseg = 1;
8207 var._linkage = LINK.d;
8208 var.semanticRun = PASS.semanticdone; // no more semantic wanted
8209 cd.vtblsym = var;
8210 }
8211 return cd.vtblsym;
8212 }