]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/d/dmd/dsymbolsem.c
d: Merge upstream dmd 7132b3537
[thirdparty/gcc.git] / gcc / d / dmd / dsymbolsem.c
1
2 /* Compiler implementation of the D programming language
3 * Copyright (C) 1999-2021 by The D Language Foundation, All Rights Reserved
4 * written by Walter Bright
5 * http://www.digitalmars.com
6 * Distributed under the Boost Software License, Version 1.0.
7 * http://www.boost.org/LICENSE_1_0.txt
8 */
9
10 #include "root/dsystem.h"
11 #include "root/aav.h"
12
13 #include "dsymbol.h"
14 #include "aggregate.h"
15 #include "aliasthis.h"
16 #include "attrib.h"
17 #include "cond.h"
18 #include "declaration.h"
19 #include "enum.h"
20 #include "errors.h"
21 #include "hdrgen.h"
22 #include "id.h"
23 #include "import.h"
24 #include "init.h"
25 #include "mars.h"
26 #include "module.h"
27 #include "nspace.h"
28 #include "objc.h"
29 #include "parse.h"
30 #include "scope.h"
31 #include "statement.h"
32 #include "staticassert.h"
33 #include "target.h"
34 #include "template.h"
35 #include "utf.h"
36 #include "version.h"
37 #include "visitor.h"
38
39 bool allowsContractWithoutBody(FuncDeclaration *funcdecl);
40 bool checkFrameAccess(Loc loc, Scope *sc, AggregateDeclaration *ad, size_t istart = 0);
41 VarDeclaration *copyToTemp(StorageClass stc, const char *name, Expression *e);
42 Initializer *inferType(Initializer *init, Scope *sc);
43 void MODtoBuffer(OutBuffer *buf, MOD mod);
44 bool reliesOnTident(Type *t, TemplateParameters *tparams = NULL, size_t iStart = 0);
45 Objc *objc();
46
47 static unsigned setMangleOverride(Dsymbol *s, char *sym)
48 {
49 AttribDeclaration *ad = s->isAttribDeclaration();
50
51 if (ad)
52 {
53 Dsymbols *decls = ad->include(NULL);
54 unsigned nestedCount = 0;
55
56 if (decls && decls->length)
57 for (size_t i = 0; i < decls->length; ++i)
58 nestedCount += setMangleOverride((*decls)[i], sym);
59
60 return nestedCount;
61 }
62 else if (s->isFuncDeclaration() || s->isVarDeclaration())
63 {
64 s->isDeclaration()->mangleOverride = sym;
65 return 1;
66 }
67 else
68 return 0;
69 }
70
71 /**********************************
72 * Decide if attributes for this function can be inferred from examining
73 * the function body.
74 * Returns:
75 * true if can
76 */
77 static bool canInferAttributes(FuncDeclaration *fd, Scope *sc)
78 {
79 if (!fd->fbody)
80 return false;
81
82 if (fd->isVirtualMethod())
83 return false; // since they may be overridden
84
85 if (sc->func &&
86 /********** this is for backwards compatibility for the moment ********/
87 (!fd->isMember() || (sc->func->isSafeBypassingInference() && !fd->isInstantiated())))
88 return true;
89
90 if (fd->isFuncLiteralDeclaration() || // externs are not possible with literals
91 (fd->storage_class & STCinference) || // do attribute inference
92 (fd->inferRetType && !fd->isCtorDeclaration()))
93 return true;
94
95 if (fd->isInstantiated())
96 {
97 TemplateInstance *ti = fd->parent->isTemplateInstance();
98 if (ti == NULL || ti->isTemplateMixin() || ti->tempdecl->ident == fd->ident)
99 return true;
100 }
101
102 return false;
103 }
104
105 /*****************************************
106 * Initialize for inferring the attributes of this function.
107 */
108 static void initInferAttributes(FuncDeclaration *fd)
109 {
110 //printf("initInferAttributes() for %s\n", toPrettyChars());
111 TypeFunction *tf = fd->type->toTypeFunction();
112 if (tf->purity == PUREimpure) // purity not specified
113 fd->flags |= FUNCFLAGpurityInprocess;
114
115 if (tf->trust == TRUSTdefault)
116 fd->flags |= FUNCFLAGsafetyInprocess;
117
118 if (!tf->isnothrow)
119 fd->flags |= FUNCFLAGnothrowInprocess;
120
121 if (!tf->isnogc)
122 fd->flags |= FUNCFLAGnogcInprocess;
123
124 if (!fd->isVirtual() || fd->introducing)
125 fd->flags |= FUNCFLAGreturnInprocess;
126
127 // Initialize for inferring STCscope
128 if (global.params.vsafe)
129 fd->flags |= FUNCFLAGinferScope;
130 }
131
132 static void badObjectDotD(ClassDeclaration *cd)
133 {
134 cd->error("missing or corrupt object.d");
135 fatal();
136 }
137
138 /* Bugzilla 12078, 12143 and 15733:
139 * While resolving base classes and interfaces, a base may refer
140 * the member of this derived class. In that time, if all bases of
141 * this class can be determined, we can go forward the semantc process
142 * beyond the Lancestorsdone. To do the recursive semantic analysis,
143 * temporarily set and unset `_scope` around exp().
144 */
145 static Type *resolveBase(ClassDeclaration *cd, Scope *sc, Scope *&scx, Type *type)
146 {
147 if (!scx)
148 {
149 scx = sc->copy();
150 scx->setNoFree();
151 }
152 cd->_scope = scx;
153 Type *t = typeSemantic(type, cd->loc, sc);
154 cd->_scope = NULL;
155 return t;
156 }
157
158 static void resolveBase(ClassDeclaration *cd, Scope *sc, Scope *&scx, ClassDeclaration *sym)
159 {
160 if (!scx)
161 {
162 scx = sc->copy();
163 scx->setNoFree();
164 }
165 cd->_scope = scx;
166 dsymbolSemantic(sym, NULL);
167 cd->_scope = NULL;
168 }
169
170 class DsymbolSemanticVisitor : public Visitor
171 {
172 public:
173 Scope *sc;
174
175 DsymbolSemanticVisitor(Scope *sc)
176 {
177 this->sc = sc;
178 }
179
180 void visit(Dsymbol *dsym)
181 {
182 dsym->error("%p has no semantic routine", dsym);
183 }
184
185 void visit(ScopeDsymbol *) { }
186 void visit(Declaration *) { }
187
188 void visit(AliasThis *dsym)
189 {
190 if (dsym->semanticRun != PASSinit)
191 return;
192
193 if (dsym->_scope)
194 {
195 sc = dsym->_scope;
196 dsym->_scope = NULL;
197 }
198
199 if (!sc)
200 return;
201
202 dsym->semanticRun = PASSsemantic;
203
204 Dsymbol *p = sc->parent->pastMixin();
205 AggregateDeclaration *ad = p->isAggregateDeclaration();
206 if (!ad)
207 {
208 error(dsym->loc, "alias this can only be a member of aggregate, not %s %s",
209 p->kind(), p->toChars());
210 return;
211 }
212
213 assert(ad->members);
214 Dsymbol *s = ad->search(dsym->loc, dsym->ident);
215 if (!s)
216 {
217 s = sc->search(dsym->loc, dsym->ident, NULL);
218 if (s)
219 error(dsym->loc, "%s is not a member of %s", s->toChars(), ad->toChars());
220 else
221 error(dsym->loc, "undefined identifier %s", dsym->ident->toChars());
222 return;
223 }
224 else if (ad->aliasthis && s != ad->aliasthis)
225 {
226 error(dsym->loc, "there can be only one alias this");
227 return;
228 }
229
230 if (ad->type->ty == Tstruct && ((TypeStruct *)ad->type)->sym != ad)
231 {
232 AggregateDeclaration *ad2 = ((TypeStruct *)ad->type)->sym;
233 assert(ad2->type == Type::terror);
234 ad->aliasthis = ad2->aliasthis;
235 return;
236 }
237
238 /* disable the alias this conversion so the implicit conversion check
239 * doesn't use it.
240 */
241 ad->aliasthis = NULL;
242
243 Dsymbol *sx = s;
244 if (sx->isAliasDeclaration())
245 sx = sx->toAlias();
246 Declaration *d = sx->isDeclaration();
247 if (d && !d->isTupleDeclaration())
248 {
249 Type *t = d->type;
250 assert(t);
251 if (ad->type->implicitConvTo(t) > MATCHnomatch)
252 {
253 error(dsym->loc, "alias this is not reachable as %s already converts to %s", ad->toChars(), t->toChars());
254 }
255 }
256
257 ad->aliasthis = s;
258 dsym->semanticRun = PASSsemanticdone;
259 }
260
261 void visit(AliasDeclaration *dsym)
262 {
263 if (dsym->semanticRun >= PASSsemanticdone)
264 return;
265 assert(dsym->semanticRun <= PASSsemantic);
266
267 dsym->storage_class |= sc->stc & STCdeprecated;
268 dsym->protection = sc->protection;
269 dsym->userAttribDecl = sc->userAttribDecl;
270
271 if (!sc->func && dsym->inNonRoot())
272 return;
273
274 aliasSemantic(dsym, sc);
275 }
276
277 void visit(VarDeclaration *dsym)
278 {
279 //if (dsym->semanticRun > PASSinit)
280 // return;
281 //dsym->semanticRun = PASSsemantic;
282
283 if (dsym->semanticRun >= PASSsemanticdone)
284 return;
285
286 Scope *scx = NULL;
287 if (dsym->_scope)
288 {
289 sc = dsym->_scope;
290 scx = sc;
291 dsym->_scope = NULL;
292 }
293
294 if (!sc)
295 return;
296
297 dsym->semanticRun = PASSsemantic;
298
299 /* Pick up storage classes from context, but except synchronized,
300 * override, abstract, and final.
301 */
302 dsym->storage_class |= (sc->stc & ~(STCsynchronized | STCoverride | STCabstract | STCfinal));
303 if (dsym->storage_class & STCextern && dsym->_init)
304 dsym->error("extern symbols cannot have initializers");
305
306 dsym->userAttribDecl = sc->userAttribDecl;
307
308 AggregateDeclaration *ad = dsym->isThis();
309 if (ad)
310 dsym->storage_class |= ad->storage_class & STC_TYPECTOR;
311
312 /* If auto type inference, do the inference
313 */
314 int inferred = 0;
315 if (!dsym->type)
316 {
317 dsym->inuse++;
318
319 // Infering the type requires running semantic,
320 // so mark the scope as ctfe if required
321 bool needctfe = (dsym->storage_class & (STCmanifest | STCstatic)) != 0;
322 if (needctfe) sc = sc->startCTFE();
323
324 //printf("inferring type for %s with init %s\n", dsym->toChars(), dsym->_init->toChars());
325 dsym->_init = inferType(dsym->_init, sc);
326 dsym->type = initializerToExpression(dsym->_init)->type;
327
328 if (needctfe) sc = sc->endCTFE();
329
330 dsym->inuse--;
331 inferred = 1;
332
333 /* This is a kludge to support the existing syntax for RAII
334 * declarations.
335 */
336 dsym->storage_class &= ~STCauto;
337 dsym->originalType = dsym->type->syntaxCopy();
338 }
339 else
340 {
341 if (!dsym->originalType)
342 dsym->originalType = dsym->type->syntaxCopy();
343
344 /* Prefix function attributes of variable declaration can affect
345 * its type:
346 * pure nothrow void function() fp;
347 * static assert(is(typeof(fp) == void function() pure nothrow));
348 */
349 Scope *sc2 = sc->push();
350 sc2->stc |= (dsym->storage_class & STC_FUNCATTR);
351 dsym->inuse++;
352 dsym->type = typeSemantic(dsym->type, dsym->loc, sc2);
353 dsym->inuse--;
354 sc2->pop();
355 }
356 //printf(" semantic type = %s\n", dsym->type ? dsym->type->toChars() : "null");
357 if (dsym->type->ty == Terror)
358 dsym->errors = true;
359
360 dsym->type->checkDeprecated(dsym->loc, sc);
361 dsym->linkage = sc->linkage;
362 dsym->parent = sc->parent;
363 //printf("this = %p, parent = %p, '%s'\n", dsym, dsym->parent, dsym->parent->toChars());
364 dsym->protection = sc->protection;
365
366 /* If scope's alignment is the default, use the type's alignment,
367 * otherwise the scope overrrides.
368 */
369 dsym->alignment = sc->alignment();
370 if (dsym->alignment == STRUCTALIGN_DEFAULT)
371 dsym->alignment = dsym->type->alignment(); // use type's alignment
372
373 //printf("sc->stc = %x\n", sc->stc);
374 //printf("storage_class = x%x\n", dsym->storage_class);
375
376 if (global.params.vcomplex)
377 dsym->type->checkComplexTransition(dsym->loc);
378
379 // Calculate type size + safety checks
380 if (sc->func && !sc->intypeof)
381 {
382 if ((dsym->storage_class & STCgshared) && !dsym->isMember())
383 {
384 if (sc->func->setUnsafe())
385 dsym->error("__gshared not allowed in safe functions; use shared");
386 }
387 }
388
389 Dsymbol *parent = dsym->toParent();
390
391 Type *tb = dsym->type->toBasetype();
392 Type *tbn = tb->baseElemOf();
393 if (tb->ty == Tvoid && !(dsym->storage_class & STClazy))
394 {
395 if (inferred)
396 {
397 dsym->error("type %s is inferred from initializer %s, and variables cannot be of type void",
398 dsym->type->toChars(), dsym->_init->toChars());
399 }
400 else
401 dsym->error("variables cannot be of type void");
402 dsym->type = Type::terror;
403 tb = dsym->type;
404 }
405 if (tb->ty == Tfunction)
406 {
407 dsym->error("cannot be declared to be a function");
408 dsym->type = Type::terror;
409 tb = dsym->type;
410 }
411 if (tb->ty == Tstruct)
412 {
413 TypeStruct *ts = (TypeStruct *)tb;
414 if (!ts->sym->members)
415 {
416 dsym->error("no definition of struct %s", ts->toChars());
417 }
418 }
419 if ((dsym->storage_class & STCauto) && !inferred)
420 dsym->error("storage class `auto` has no effect if type is not inferred, did you mean `scope`?");
421
422 if (tb->ty == Ttuple)
423 {
424 /* Instead, declare variables for each of the tuple elements
425 * and add those.
426 */
427 TypeTuple *tt = (TypeTuple *)tb;
428 size_t nelems = Parameter::dim(tt->arguments);
429 Expression *ie = (dsym->_init && !dsym->_init->isVoidInitializer()) ? initializerToExpression(dsym->_init) : NULL;
430 if (ie)
431 ie = expressionSemantic(ie, sc);
432
433 if (nelems > 0 && ie)
434 {
435 Expressions *iexps = new Expressions();
436 iexps->push(ie);
437
438 Expressions *exps = new Expressions();
439
440 for (size_t pos = 0; pos < iexps->length; pos++)
441 {
442 Lexpand1:
443 Expression *e = (*iexps)[pos];
444 Parameter *arg = Parameter::getNth(tt->arguments, pos);
445 arg->type = typeSemantic(arg->type, dsym->loc, sc);
446 //printf("[%d] iexps->length = %d, ", pos, iexps->length);
447 //printf("e = (%s %s, %s), ", Token::tochars[e->op], e->toChars(), e->type->toChars());
448 //printf("arg = (%s, %s)\n", arg->toChars(), arg->type->toChars());
449
450 if (e != ie)
451 {
452 if (iexps->length > nelems)
453 goto Lnomatch;
454 if (e->type->implicitConvTo(arg->type))
455 continue;
456 }
457
458 if (e->op == TOKtuple)
459 {
460 TupleExp *te = (TupleExp *)e;
461 if (iexps->length - 1 + te->exps->length > nelems)
462 goto Lnomatch;
463
464 iexps->remove(pos);
465 iexps->insert(pos, te->exps);
466 (*iexps)[pos] = Expression::combine(te->e0, (*iexps)[pos]);
467 goto Lexpand1;
468 }
469 else if (isAliasThisTuple(e))
470 {
471 VarDeclaration *v = copyToTemp(0, "__tup", e);
472 dsymbolSemantic(v, sc);
473 VarExp *ve = new VarExp(dsym->loc, v);
474 ve->type = e->type;
475
476 exps->setDim(1);
477 (*exps)[0] = ve;
478 expandAliasThisTuples(exps, 0);
479
480 for (size_t u = 0; u < exps->length ; u++)
481 {
482 Lexpand2:
483 Expression *ee = (*exps)[u];
484 arg = Parameter::getNth(tt->arguments, pos + u);
485 arg->type = typeSemantic(arg->type, dsym->loc, sc);
486 //printf("[%d+%d] exps->length = %d, ", pos, u, exps->length);
487 //printf("ee = (%s %s, %s), ", Token::tochars[ee->op], ee->toChars(), ee->type->toChars());
488 //printf("arg = (%s, %s)\n", arg->toChars(), arg->type->toChars());
489
490 size_t iexps_dim = iexps->length - 1 + exps->length;
491 if (iexps_dim > nelems)
492 goto Lnomatch;
493 if (ee->type->implicitConvTo(arg->type))
494 continue;
495
496 if (expandAliasThisTuples(exps, u) != -1)
497 goto Lexpand2;
498 }
499
500 if ((*exps)[0] != ve)
501 {
502 Expression *e0 = (*exps)[0];
503 (*exps)[0] = new CommaExp(dsym->loc, new DeclarationExp(dsym->loc, v), e0);
504 (*exps)[0]->type = e0->type;
505
506 iexps->remove(pos);
507 iexps->insert(pos, exps);
508 goto Lexpand1;
509 }
510 }
511 }
512 if (iexps->length < nelems)
513 goto Lnomatch;
514
515 ie = new TupleExp(dsym->_init->loc, iexps);
516 }
517 Lnomatch:
518
519 if (ie && ie->op == TOKtuple)
520 {
521 TupleExp *te = (TupleExp *)ie;
522 size_t tedim = te->exps->length;
523 if (tedim != nelems)
524 {
525 error(dsym->loc, "tuple of %d elements cannot be assigned to tuple of %d elements", (int)tedim, (int)nelems);
526 for (size_t u = tedim; u < nelems; u++) // fill dummy expression
527 te->exps->push(new ErrorExp());
528 }
529 }
530
531 Objects *exps = new Objects();
532 exps->setDim(nelems);
533 for (size_t i = 0; i < nelems; i++)
534 {
535 Parameter *arg = Parameter::getNth(tt->arguments, i);
536
537 OutBuffer buf;
538 buf.printf("__%s_field_%llu", dsym->ident->toChars(), (ulonglong)i);
539 const char *name = buf.extractChars();
540 Identifier *id = Identifier::idPool(name);
541
542 Initializer *ti;
543 if (ie)
544 {
545 Expression *einit = ie;
546 if (ie->op == TOKtuple)
547 {
548 TupleExp *te = (TupleExp *)ie;
549 einit = (*te->exps)[i];
550 if (i == 0)
551 einit = Expression::combine(te->e0, einit);
552 }
553 ti = new ExpInitializer(einit->loc, einit);
554 }
555 else
556 ti = dsym->_init ? dsym->_init->syntaxCopy() : NULL;
557
558 VarDeclaration *v = new VarDeclaration(dsym->loc, arg->type, id, ti);
559 v->storage_class |= STCtemp | dsym->storage_class;
560 if (arg->storageClass & STCparameter)
561 v->storage_class |= arg->storageClass;
562 //printf("declaring field %s of type %s\n", v->toChars(), v->type->toChars());
563 dsymbolSemantic(v, sc);
564
565 if (sc->scopesym)
566 {
567 //printf("adding %s to %s\n", v->toChars(), sc->scopesym->toChars());
568 if (sc->scopesym->members)
569 sc->scopesym->members->push(v);
570 }
571
572 Expression *e = new DsymbolExp(dsym->loc, v);
573 (*exps)[i] = e;
574 }
575 TupleDeclaration *v2 = new TupleDeclaration(dsym->loc, dsym->ident, exps);
576 v2->parent = dsym->parent;
577 v2->isexp = true;
578 dsym->aliassym = v2;
579 dsym->semanticRun = PASSsemanticdone;
580 return;
581 }
582
583 /* Storage class can modify the type
584 */
585 dsym->type = dsym->type->addStorageClass(dsym->storage_class);
586
587 /* Adjust storage class to reflect type
588 */
589 if (dsym->type->isConst())
590 {
591 dsym->storage_class |= STCconst;
592 if (dsym->type->isShared())
593 dsym->storage_class |= STCshared;
594 }
595 else if (dsym->type->isImmutable())
596 dsym->storage_class |= STCimmutable;
597 else if (dsym->type->isShared())
598 dsym->storage_class |= STCshared;
599 else if (dsym->type->isWild())
600 dsym->storage_class |= STCwild;
601
602 if (StorageClass stc = dsym->storage_class & (STCsynchronized | STCoverride | STCabstract | STCfinal))
603 {
604 if (stc == STCfinal)
605 dsym->error("cannot be final, perhaps you meant const?");
606 else
607 {
608 OutBuffer buf;
609 stcToBuffer(&buf, stc);
610 dsym->error("cannot be %s", buf.peekChars());
611 }
612 dsym->storage_class &= ~stc; // strip off
613 }
614
615 if (dsym->storage_class & STCscope)
616 {
617 StorageClass stc = dsym->storage_class & (STCstatic | STCextern | STCmanifest | STCtls | STCgshared);
618 if (stc)
619 {
620 OutBuffer buf;
621 stcToBuffer(&buf, stc);
622 dsym->error("cannot be `scope` and `%s`", buf.peekChars());
623 }
624 else if (dsym->isMember())
625 {
626 dsym->error("field cannot be `scope`");
627 }
628 else if (!dsym->type->hasPointers())
629 {
630 dsym->storage_class &= ~STCscope; // silently ignore; may occur in generic code
631 }
632 }
633
634 if (dsym->storage_class & (STCstatic | STCextern | STCmanifest | STCtemplateparameter | STCtls | STCgshared | STCctfe))
635 {
636 }
637 else
638 {
639 AggregateDeclaration *aad = parent->isAggregateDeclaration();
640 if (aad)
641 {
642 if (global.params.vfield &&
643 dsym->storage_class & (STCconst | STCimmutable) && dsym->_init && !dsym->_init->isVoidInitializer())
644 {
645 const char *s = (dsym->storage_class & STCimmutable) ? "immutable" : "const";
646 message(dsym->loc, "`%s.%s` is `%s` field", ad->toPrettyChars(), dsym->toChars(), s);
647 }
648 dsym->storage_class |= STCfield;
649 if (tbn->ty == Tstruct && ((TypeStruct *)tbn)->sym->noDefaultCtor)
650 {
651 if (!dsym->isThisDeclaration() && !dsym->_init)
652 aad->noDefaultCtor = true;
653 }
654 }
655
656 InterfaceDeclaration *id = parent->isInterfaceDeclaration();
657 if (id)
658 {
659 dsym->error("field not allowed in interface");
660 }
661 else if (aad && aad->sizeok == SIZEOKdone)
662 {
663 dsym->error("cannot be further field because it will change the determined %s size", aad->toChars());
664 }
665
666 /* Templates cannot add fields to aggregates
667 */
668 TemplateInstance *ti = parent->isTemplateInstance();
669 if (ti)
670 {
671 // Take care of nested templates
672 while (1)
673 {
674 TemplateInstance *ti2 = ti->tempdecl->parent->isTemplateInstance();
675 if (!ti2)
676 break;
677 ti = ti2;
678 }
679
680 // If it's a member template
681 AggregateDeclaration *ad2 = ti->tempdecl->isMember();
682 if (ad2 && dsym->storage_class != STCundefined)
683 {
684 dsym->error("cannot use template to add field to aggregate `%s`", ad2->toChars());
685 }
686 }
687 }
688
689 if ((dsym->storage_class & (STCref | STCparameter | STCforeach | STCtemp | STCresult)) == STCref && dsym->ident != Id::This)
690 {
691 dsym->error("only parameters or foreach declarations can be ref");
692 }
693
694 if (dsym->type->hasWild())
695 {
696 if (dsym->storage_class & (STCstatic | STCextern | STCtls | STCgshared | STCmanifest | STCfield) ||
697 dsym->isDataseg()
698 )
699 {
700 dsym->error("only parameters or stack based variables can be inout");
701 }
702 FuncDeclaration *func = sc->func;
703 if (func)
704 {
705 if (func->fes)
706 func = func->fes->func;
707 bool isWild = false;
708 for (FuncDeclaration *fd = func; fd; fd = fd->toParent2()->isFuncDeclaration())
709 {
710 if (((TypeFunction *)fd->type)->iswild)
711 {
712 isWild = true;
713 break;
714 }
715 }
716 if (!isWild)
717 {
718 dsym->error("inout variables can only be declared inside inout functions");
719 }
720 }
721 }
722
723 if (!(dsym->storage_class & (STCctfe | STCref | STCresult)) && tbn->ty == Tstruct &&
724 ((TypeStruct *)tbn)->sym->noDefaultCtor)
725 {
726 if (!dsym->_init)
727 {
728 if (dsym->isField())
729 {
730 /* For fields, we'll check the constructor later to make sure it is initialized
731 */
732 dsym->storage_class |= STCnodefaultctor;
733 }
734 else if (dsym->storage_class & STCparameter)
735 ;
736 else
737 dsym->error("default construction is disabled for type %s", dsym->type->toChars());
738 }
739 }
740
741 FuncDeclaration *fd = parent->isFuncDeclaration();
742 if (dsym->type->isscope() && !(dsym->storage_class & STCnodtor))
743 {
744 if (dsym->storage_class & (STCfield | STCout | STCref | STCstatic | STCmanifest | STCtls | STCgshared) || !fd)
745 {
746 dsym->error("globals, statics, fields, manifest constants, ref and out parameters cannot be scope");
747 }
748
749 if (!(dsym->storage_class & STCscope))
750 {
751 if (!(dsym->storage_class & STCparameter) && dsym->ident != Id::withSym)
752 dsym->error("reference to scope class must be scope");
753 }
754 }
755
756 // Calculate type size + safety checks
757 if (sc->func && !sc->intypeof)
758 {
759 if (dsym->_init && dsym->_init->isVoidInitializer() && dsym->type->hasPointers()) // get type size
760 {
761 if (sc->func->setUnsafe())
762 dsym->error("void initializers for pointers not allowed in safe functions");
763 }
764 else if (!dsym->_init &&
765 !(dsym->storage_class & (STCstatic | STCextern | STCtls | STCgshared | STCmanifest | STCfield | STCparameter)) &&
766 dsym->type->hasVoidInitPointers())
767 {
768 if (sc->func->setUnsafe())
769 dsym->error("void initializers for pointers not allowed in safe functions");
770 }
771 }
772
773 if (!dsym->_init && !fd)
774 {
775 // If not mutable, initializable by constructor only
776 dsym->storage_class |= STCctorinit;
777 }
778
779 if (dsym->_init)
780 dsym->storage_class |= STCinit; // remember we had an explicit initializer
781 else if (dsym->storage_class & STCmanifest)
782 dsym->error("manifest constants must have initializers");
783
784 bool isBlit = false;
785 d_uns64 sz = 0;
786 if (!dsym->_init && !sc->inunion && !(dsym->storage_class & (STCstatic | STCgshared | STCextern)) && fd &&
787 (!(dsym->storage_class & (STCfield | STCin | STCforeach | STCparameter | STCresult))
788 || (dsym->storage_class & STCout)) &&
789 (sz = dsym->type->size()) != 0)
790 {
791 // Provide a default initializer
792 //printf("Providing default initializer for '%s'\n", dsym->toChars());
793 if (sz == SIZE_INVALID && dsym->type->ty != Terror)
794 dsym->error("size of type %s is invalid", dsym->type->toChars());
795
796 Type *tv = dsym->type;
797 while (tv->ty == Tsarray) // Don't skip Tenum
798 tv = tv->nextOf();
799 if (tv->needsNested())
800 {
801 /* Nested struct requires valid enclosing frame pointer.
802 * In StructLiteralExp::toElem(), it's calculated.
803 */
804 assert(tv->toBasetype()->ty == Tstruct);
805 checkFrameAccess(dsym->loc, sc, ((TypeStruct *)tbn)->sym);
806
807 Expression *e = tv->defaultInitLiteral(dsym->loc);
808 e = new BlitExp(dsym->loc, new VarExp(dsym->loc, dsym), e);
809 e = expressionSemantic(e, sc);
810 dsym->_init = new ExpInitializer(dsym->loc, e);
811 goto Ldtor;
812 }
813 if (tv->ty == Tstruct && ((TypeStruct *)tv)->sym->zeroInit == 1)
814 {
815 /* If a struct is all zeros, as a special case
816 * set it's initializer to the integer 0.
817 * In AssignExp::toElem(), we check for this and issue
818 * a memset() to initialize the struct.
819 * Must do same check in interpreter.
820 */
821 Expression *e = new IntegerExp(dsym->loc, 0, Type::tint32);
822 e = new BlitExp(dsym->loc, new VarExp(dsym->loc, dsym), e);
823 e->type = dsym->type; // don't type check this, it would fail
824 dsym->_init = new ExpInitializer(dsym->loc, e);
825 goto Ldtor;
826 }
827 if (dsym->type->baseElemOf()->ty == Tvoid)
828 {
829 dsym->error("%s does not have a default initializer", dsym->type->toChars());
830 }
831 else if (Expression *e = dsym->type->defaultInit(dsym->loc))
832 {
833 dsym->_init = new ExpInitializer(dsym->loc, e);
834 }
835 // Default initializer is always a blit
836 isBlit = true;
837 }
838
839 if (dsym->_init)
840 {
841 sc = sc->push();
842 sc->stc &= ~(STC_TYPECTOR | STCpure | STCnothrow | STCnogc | STCref | STCdisable);
843
844 ExpInitializer *ei = dsym->_init->isExpInitializer();
845 if (ei) // Bugzilla 13424: Preset the required type to fail in FuncLiteralDeclaration::semantic3
846 ei->exp = inferType(ei->exp, dsym->type);
847
848 // If inside function, there is no semantic3() call
849 if (sc->func || sc->intypeof == 1)
850 {
851 // If local variable, use AssignExp to handle all the various
852 // possibilities.
853 if (fd &&
854 !(dsym->storage_class & (STCmanifest | STCstatic | STCtls | STCgshared | STCextern)) &&
855 !dsym->_init->isVoidInitializer())
856 {
857 //printf("fd = '%s', var = '%s'\n", fd->toChars(), dsym->toChars());
858 if (!ei)
859 {
860 ArrayInitializer *ai = dsym->_init->isArrayInitializer();
861 Expression *e;
862 if (ai && tb->ty == Taarray)
863 e = ai->toAssocArrayLiteral();
864 else
865 e = initializerToExpression(dsym->_init);
866 if (!e)
867 {
868 // Run semantic, but don't need to interpret
869 dsym->_init = initializerSemantic(dsym->_init, sc, dsym->type, INITnointerpret);
870 e = initializerToExpression(dsym->_init);
871 if (!e)
872 {
873 dsym->error("is not a static and cannot have static initializer");
874 e = new ErrorExp();
875 }
876 }
877 ei = new ExpInitializer(dsym->_init->loc, e);
878 dsym->_init = ei;
879 }
880
881 Expression *exp = ei->exp;
882 Expression *e1 = new VarExp(dsym->loc, dsym);
883 if (isBlit)
884 exp = new BlitExp(dsym->loc, e1, exp);
885 else
886 exp = new ConstructExp(dsym->loc, e1, exp);
887 dsym->canassign++;
888 exp = expressionSemantic(exp, sc);
889 dsym->canassign--;
890 exp = exp->optimize(WANTvalue);
891
892 if (exp->op == TOKerror)
893 {
894 dsym->_init = new ErrorInitializer();
895 ei = NULL;
896 }
897 else
898 ei->exp = exp;
899
900 if (ei && dsym->isScope())
901 {
902 Expression *ex = ei->exp;
903 while (ex->op == TOKcomma)
904 ex = ((CommaExp *)ex)->e2;
905 if (ex->op == TOKblit || ex->op == TOKconstruct)
906 ex = ((AssignExp *)ex)->e2;
907 if (ex->op == TOKnew)
908 {
909 // See if initializer is a NewExp that can be allocated on the stack
910 NewExp *ne = (NewExp *)ex;
911 if (dsym->type->toBasetype()->ty == Tclass)
912 {
913 if (ne->newargs && ne->newargs->length > 1)
914 {
915 dsym->mynew = true;
916 }
917 else
918 {
919 ne->onstack = true;
920 dsym->onstack = true;
921 }
922 }
923 }
924 else if (ex->op == TOKfunction)
925 {
926 // or a delegate that doesn't escape a reference to the function
927 FuncDeclaration *f = ((FuncExp *)ex)->fd;
928 f->tookAddressOf--;
929 }
930 }
931 }
932 else
933 {
934 // Bugzilla 14166: Don't run CTFE for the temporary variables inside typeof
935 dsym->_init = initializerSemantic(dsym->_init, sc, dsym->type, sc->intypeof == 1 ? INITnointerpret : INITinterpret);
936 }
937 }
938 else if (parent->isAggregateDeclaration())
939 {
940 dsym->_scope = scx ? scx : sc->copy();
941 dsym->_scope->setNoFree();
942 }
943 else if (dsym->storage_class & (STCconst | STCimmutable | STCmanifest) ||
944 dsym->type->isConst() || dsym->type->isImmutable())
945 {
946 /* Because we may need the results of a const declaration in a
947 * subsequent type, such as an array dimension, before semantic2()
948 * gets ordinarily run, try to run semantic2() now.
949 * Ignore failure.
950 */
951
952 if (!inferred)
953 {
954 unsigned errors = global.errors;
955 dsym->inuse++;
956 if (ei)
957 {
958 Expression *exp = ei->exp->syntaxCopy();
959
960 bool needctfe = dsym->isDataseg() || (dsym->storage_class & STCmanifest);
961 if (needctfe) sc = sc->startCTFE();
962 exp = expressionSemantic(exp, sc);
963 exp = resolveProperties(sc, exp);
964 if (needctfe) sc = sc->endCTFE();
965
966 Type *tb2 = dsym->type->toBasetype();
967 Type *ti = exp->type->toBasetype();
968
969 /* The problem is the following code:
970 * struct CopyTest {
971 * double x;
972 * this(double a) { x = a * 10.0;}
973 * this(this) { x += 2.0; }
974 * }
975 * const CopyTest z = CopyTest(5.3); // ok
976 * const CopyTest w = z; // not ok, postblit not run
977 * static assert(w.x == 55.0);
978 * because the postblit doesn't get run on the initialization of w.
979 */
980 if (ti->ty == Tstruct)
981 {
982 StructDeclaration *sd = ((TypeStruct *)ti)->sym;
983 /* Look to see if initializer involves a copy constructor
984 * (which implies a postblit)
985 */
986 // there is a copy constructor
987 // and exp is the same struct
988 if (sd->postblit &&
989 tb2->toDsymbol(NULL) == sd)
990 {
991 // The only allowable initializer is a (non-copy) constructor
992 if (exp->isLvalue())
993 dsym->error("of type struct %s uses this(this), which is not allowed in static initialization", tb2->toChars());
994 }
995 }
996 ei->exp = exp;
997 }
998 dsym->_init = initializerSemantic(dsym->_init, sc, dsym->type, INITinterpret);
999 dsym->inuse--;
1000 if (global.errors > errors)
1001 {
1002 dsym->_init = new ErrorInitializer();
1003 dsym->type = Type::terror;
1004 }
1005 }
1006 else
1007 {
1008 dsym->_scope = scx ? scx : sc->copy();
1009 dsym->_scope->setNoFree();
1010 }
1011 }
1012 sc = sc->pop();
1013 }
1014
1015 Ldtor:
1016 /* Build code to execute destruction, if necessary
1017 */
1018 dsym->edtor = dsym->callScopeDtor(sc);
1019 if (dsym->edtor)
1020 {
1021 if (sc->func && dsym->storage_class & (STCstatic | STCgshared))
1022 dsym->edtor = expressionSemantic(dsym->edtor, sc->_module->_scope);
1023 else
1024 dsym->edtor = expressionSemantic(dsym->edtor, sc);
1025
1026 #if 0 // currently disabled because of std.stdio.stdin, stdout and stderr
1027 if (dsym->isDataseg() && !(dsym->storage_class & STCextern))
1028 dsym->error("static storage variables cannot have destructors");
1029 #endif
1030 }
1031
1032 dsym->semanticRun = PASSsemanticdone;
1033
1034 if (dsym->type->toBasetype()->ty == Terror)
1035 dsym->errors = true;
1036
1037 if (sc->scopesym && !sc->scopesym->isAggregateDeclaration())
1038 {
1039 for (ScopeDsymbol *sym = sc->scopesym; sym && dsym->endlinnum == 0;
1040 sym = sym->parent ? sym->parent->isScopeDsymbol() : NULL)
1041 dsym->endlinnum = sym->endlinnum;
1042 }
1043 }
1044
1045 void visit(TypeInfoDeclaration *dsym)
1046 {
1047 assert(dsym->linkage == LINKc);
1048 }
1049
1050 void visit(Import *imp)
1051 {
1052 //printf("Import::semantic('%s') %s\n", toPrettyChars(), imp->id->toChars());
1053 if (imp->semanticRun > PASSinit)
1054 return;
1055
1056 if (imp->_scope)
1057 {
1058 sc = imp->_scope;
1059 imp->_scope = NULL;
1060 }
1061 if (!sc)
1062 return;
1063
1064 imp->semanticRun = PASSsemantic;
1065
1066 // Load if not already done so
1067 if (!imp->mod)
1068 {
1069 imp->load(sc);
1070 if (imp->mod)
1071 imp->mod->importAll(NULL);
1072 }
1073
1074 if (imp->mod)
1075 {
1076 // Modules need a list of each imported module
1077 //printf("%s imports %s\n", sc->_module->toChars(), imp->mod->toChars());
1078 sc->_module->aimports.push(imp->mod);
1079
1080 if (sc->explicitProtection)
1081 imp->protection = sc->protection;
1082
1083 if (!imp->aliasId && !imp->names.length) // neither a selective nor a renamed import
1084 {
1085 ScopeDsymbol *scopesym = NULL;
1086 if (sc->explicitProtection)
1087 imp->protection = sc->protection.kind;
1088 for (Scope *scd = sc; scd; scd = scd->enclosing)
1089 {
1090 if (!scd->scopesym)
1091 continue;
1092 scopesym = scd->scopesym;
1093 break;
1094 }
1095
1096 if (!imp->isstatic)
1097 {
1098 scopesym->importScope(imp->mod, imp->protection);
1099 }
1100
1101 // Mark the imported packages as accessible from the current
1102 // scope. This access check is necessary when using FQN b/c
1103 // we're using a single global package tree. See Bugzilla 313.
1104 if (imp->packages)
1105 {
1106 // import a.b.c.d;
1107 Package *p = imp->pkg; // a
1108 scopesym->addAccessiblePackage(p, imp->protection);
1109 for (size_t i = 1; i < imp->packages->length; i++) // [b, c]
1110 {
1111 Identifier *id = (*imp->packages)[i];
1112 p = (Package *) p->symtab->lookup(id);
1113 scopesym->addAccessiblePackage(p, imp->protection);
1114 }
1115 }
1116 scopesym->addAccessiblePackage(imp->mod, imp->protection); // d
1117 }
1118
1119 dsymbolSemantic(imp->mod, NULL);
1120
1121 if (imp->mod->needmoduleinfo)
1122 {
1123 //printf("module4 %s because of %s\n", sc->_module->toChars(), imp->mod->toChars());
1124 sc->_module->needmoduleinfo = 1;
1125 }
1126
1127 sc = sc->push(imp->mod);
1128 sc->protection = imp->protection;
1129 for (size_t i = 0; i < imp->aliasdecls.length; i++)
1130 {
1131 AliasDeclaration *ad = imp->aliasdecls[i];
1132 //printf("\tImport %s alias %s = %s, scope = %p\n", toPrettyChars(), imp->aliases[i]->toChars(), imp->names[i]->toChars(), ad->_scope);
1133 if (imp->mod->search(imp->loc, imp->names[i]))
1134 {
1135 dsymbolSemantic(ad, sc);
1136 // If the import declaration is in non-root module,
1137 // analysis of the aliased symbol is deferred.
1138 // Therefore, don't see the ad->aliassym or ad->type here.
1139 }
1140 else
1141 {
1142 Dsymbol *s = imp->mod->search_correct(imp->names[i]);
1143 if (s)
1144 imp->mod->error(imp->loc, "import `%s` not found, did you mean %s `%s`?", imp->names[i]->toChars(), s->kind(), s->toChars());
1145 else
1146 imp->mod->error(imp->loc, "import `%s` not found", imp->names[i]->toChars());
1147 ad->type = Type::terror;
1148 }
1149 }
1150 sc = sc->pop();
1151 }
1152
1153 imp->semanticRun = PASSsemanticdone;
1154
1155 // object self-imports itself, so skip that (Bugzilla 7547)
1156 // don't list pseudo modules __entrypoint.d, __main.d (Bugzilla 11117, 11164)
1157 if (global.params.moduleDeps != NULL &&
1158 !(imp->id == Id::object && sc->_module->ident == Id::object) &&
1159 sc->_module->ident != Id::entrypoint &&
1160 strcmp(sc->_module->ident->toChars(), "__main") != 0)
1161 {
1162 /* The grammar of the file is:
1163 * ImportDeclaration
1164 * ::= BasicImportDeclaration [ " : " ImportBindList ] [ " -> "
1165 * ModuleAliasIdentifier ] "\n"
1166 *
1167 * BasicImportDeclaration
1168 * ::= ModuleFullyQualifiedName " (" FilePath ") : " Protection|"string"
1169 * " [ " static" ] : " ModuleFullyQualifiedName " (" FilePath ")"
1170 *
1171 * FilePath
1172 * - any string with '(', ')' and '\' escaped with the '\' character
1173 */
1174
1175 OutBuffer *ob = global.params.moduleDeps;
1176 Module* imod = sc->instantiatingModule();
1177 if (!global.params.moduleDepsFile.length)
1178 ob->writestring("depsImport ");
1179 ob->writestring(imod->toPrettyChars());
1180 ob->writestring(" (");
1181 escapePath(ob, imod->srcfile->toChars());
1182 ob->writestring(") : ");
1183
1184 // use protection instead of sc->protection because it couldn't be
1185 // resolved yet, see the comment above
1186 protectionToBuffer(ob, imp->protection);
1187 ob->writeByte(' ');
1188 if (imp->isstatic)
1189 {
1190 stcToBuffer(ob, STCstatic);
1191 ob->writeByte(' ');
1192 }
1193 ob->writestring(": ");
1194
1195 if (imp->packages)
1196 {
1197 for (size_t i = 0; i < imp->packages->length; i++)
1198 {
1199 Identifier *pid = (*imp->packages)[i];
1200 ob->printf("%s.", pid->toChars());
1201 }
1202 }
1203
1204 ob->writestring(imp->id->toChars());
1205 ob->writestring(" (");
1206 if (imp->mod)
1207 escapePath(ob, imp->mod->srcfile->toChars());
1208 else
1209 ob->writestring("???");
1210 ob->writeByte(')');
1211
1212 for (size_t i = 0; i < imp->names.length; i++)
1213 {
1214 if (i == 0)
1215 ob->writeByte(':');
1216 else
1217 ob->writeByte(',');
1218
1219 Identifier *name = imp->names[i];
1220 Identifier *alias = imp->aliases[i];
1221
1222 if (!alias)
1223 {
1224 ob->printf("%s", name->toChars());
1225 alias = name;
1226 }
1227 else
1228 ob->printf("%s=%s", alias->toChars(), name->toChars());
1229 }
1230
1231 if (imp->aliasId)
1232 ob->printf(" -> %s", imp->aliasId->toChars());
1233
1234 ob->writenl();
1235 }
1236
1237 //printf("-Import::semantic('%s'), pkg = %p\n", imp->toChars(), imp->pkg);
1238 }
1239
1240 void attribSemantic(AttribDeclaration *ad)
1241 {
1242 if (ad->semanticRun != PASSinit)
1243 return;
1244 ad->semanticRun = PASSsemantic;
1245 Dsymbols *d = ad->include(sc);
1246 //printf("\tAttribDeclaration::semantic '%s', d = %p\n",toChars(), d);
1247 if (d)
1248 {
1249 Scope *sc2 = ad->newScope(sc);
1250 bool errors = false;
1251 for (size_t i = 0; i < d->length; i++)
1252 {
1253 Dsymbol *s = (*d)[i];
1254 dsymbolSemantic(s, sc2);
1255 errors |= s->errors;
1256 }
1257 ad->errors |= errors;
1258 if (sc2 != sc)
1259 sc2->pop();
1260 }
1261 ad->semanticRun = PASSsemanticdone;
1262 }
1263
1264 void visit(AttribDeclaration *atd)
1265 {
1266 attribSemantic(atd);
1267 }
1268
1269 void visit(AnonDeclaration *scd)
1270 {
1271 //printf("\tAnonDeclaration::semantic %s %p\n", isunion ? "union" : "struct", scd);
1272 assert(sc->parent);
1273 Dsymbol *p = sc->parent->pastMixin();
1274 AggregateDeclaration *ad = p->isAggregateDeclaration();
1275 if (!ad)
1276 {
1277 error(scd->loc, "%s can only be a part of an aggregate, not %s %s",
1278 scd->kind(), p->kind(), p->toChars());
1279 scd->errors = true;
1280 return;
1281 }
1282
1283 if (scd->decl)
1284 {
1285 sc = sc->push();
1286 sc->stc &= ~(STCauto | STCscope | STCstatic | STCtls | STCgshared);
1287 sc->inunion = scd->isunion;
1288 sc->flags = 0;
1289
1290 for (size_t i = 0; i < scd->decl->length; i++)
1291 {
1292 Dsymbol *s = (*scd->decl)[i];
1293 dsymbolSemantic(s, sc);
1294 }
1295 sc = sc->pop();
1296 }
1297 }
1298
1299 void visit(PragmaDeclaration *pd)
1300 {
1301 // Should be merged with PragmaStatement
1302 //printf("\tPragmaDeclaration::semantic '%s'\n",toChars());
1303 if (pd->ident == Id::msg)
1304 {
1305 if (pd->args)
1306 {
1307 for (size_t i = 0; i < pd->args->length; i++)
1308 {
1309 Expression *e = (*pd->args)[i];
1310
1311 sc = sc->startCTFE();
1312 e = expressionSemantic(e, sc);
1313 e = resolveProperties(sc, e);
1314 sc = sc->endCTFE();
1315
1316 // pragma(msg) is allowed to contain types as well as expressions
1317 e = ctfeInterpretForPragmaMsg(e);
1318 if (e->op == TOKerror)
1319 {
1320 errorSupplemental(pd->loc, "while evaluating pragma(msg, %s)", (*pd->args)[i]->toChars());
1321 return;
1322 }
1323 StringExp *se = e->toStringExp();
1324 if (se)
1325 {
1326 se = se->toUTF8(sc);
1327 fprintf(stderr, "%.*s", (int)se->len, (char *)se->string);
1328 }
1329 else
1330 fprintf(stderr, "%s", e->toChars());
1331 }
1332 fprintf(stderr, "\n");
1333 }
1334 goto Lnodecl;
1335 }
1336 else if (pd->ident == Id::lib)
1337 {
1338 if (!pd->args || pd->args->length != 1)
1339 pd->error("string expected for library name");
1340 else
1341 {
1342 StringExp *se = semanticString(sc, (*pd->args)[0], "library name");
1343 if (!se)
1344 goto Lnodecl;
1345 (*pd->args)[0] = se;
1346
1347 char *name = (char *)mem.xmalloc(se->len + 1);
1348 memcpy(name, se->string, se->len);
1349 name[se->len] = 0;
1350 if (global.params.verbose)
1351 message("library %s", name);
1352 if (global.params.moduleDeps && !global.params.moduleDepsFile.length)
1353 {
1354 OutBuffer *ob = global.params.moduleDeps;
1355 Module *imod = sc->instantiatingModule();
1356 ob->writestring("depsLib ");
1357 ob->writestring(imod->toPrettyChars());
1358 ob->writestring(" (");
1359 escapePath(ob, imod->srcfile->toChars());
1360 ob->writestring(") : ");
1361 ob->writestring((char *) name);
1362 ob->writenl();
1363 }
1364 mem.xfree(name);
1365 }
1366 goto Lnodecl;
1367 }
1368 else if (pd->ident == Id::startaddress)
1369 {
1370 if (!pd->args || pd->args->length != 1)
1371 pd->error("function name expected for start address");
1372 else
1373 {
1374 /* Bugzilla 11980:
1375 * resolveProperties and ctfeInterpret call are not necessary.
1376 */
1377 Expression *e = (*pd->args)[0];
1378
1379 sc = sc->startCTFE();
1380 e = expressionSemantic(e, sc);
1381 sc = sc->endCTFE();
1382
1383 (*pd->args)[0] = e;
1384 Dsymbol *sa = getDsymbol(e);
1385 if (!sa || !sa->isFuncDeclaration())
1386 pd->error("function name expected for start address, not `%s`", e->toChars());
1387 }
1388 goto Lnodecl;
1389 }
1390 else if (pd->ident == Id::Pinline)
1391 {
1392 goto Ldecl;
1393 }
1394 else if (pd->ident == Id::mangle)
1395 {
1396 if (!pd->args)
1397 pd->args = new Expressions();
1398 if (pd->args->length != 1)
1399 {
1400 pd->error("string expected for mangled name");
1401 pd->args->setDim(1);
1402 (*pd->args)[0] = new ErrorExp(); // error recovery
1403 goto Ldecl;
1404 }
1405
1406 StringExp *se = semanticString(sc, (*pd->args)[0], "mangled name");
1407 if (!se)
1408 goto Ldecl;
1409 (*pd->args)[0] = se; // Will be used for later
1410
1411 if (!se->len)
1412 {
1413 pd->error("zero-length string not allowed for mangled name");
1414 goto Ldecl;
1415 }
1416 if (se->sz != 1)
1417 {
1418 pd->error("mangled name characters can only be of type char");
1419 goto Ldecl;
1420 }
1421
1422 /* Note: D language specification should not have any assumption about backend
1423 * implementation. Ideally pragma(mangle) can accept a string of any content.
1424 *
1425 * Therefore, this validation is compiler implementation specific.
1426 */
1427 for (size_t i = 0; i < se->len; )
1428 {
1429 utf8_t *p = (utf8_t *)se->string;
1430 dchar_t c = p[i];
1431 if (c < 0x80)
1432 {
1433 if ((c >= 'A' && c <= 'Z') ||
1434 (c >= 'a' && c <= 'z') ||
1435 (c >= '0' && c <= '9') ||
1436 (c != 0 && strchr("$%().:?@[]_", c)))
1437 {
1438 ++i;
1439 continue;
1440 }
1441 else
1442 {
1443 pd->error("char 0x%02x not allowed in mangled name", c);
1444 break;
1445 }
1446 }
1447
1448 if (const char* msg = utf_decodeChar((utf8_t *)se->string, se->len, &i, &c))
1449 {
1450 pd->error("%s", msg);
1451 break;
1452 }
1453
1454 if (!isUniAlpha(c))
1455 {
1456 pd->error("char 0x%04x not allowed in mangled name", c);
1457 break;
1458 }
1459 }
1460 }
1461 else if (global.params.ignoreUnsupportedPragmas)
1462 {
1463 if (global.params.verbose)
1464 {
1465 /* Print unrecognized pragmas
1466 */
1467 OutBuffer buf;
1468 buf.writestring(pd->ident->toChars());
1469 if (pd->args)
1470 {
1471 for (size_t i = 0; i < pd->args->length; i++)
1472 {
1473 Expression *e = (*pd->args)[i];
1474
1475 sc = sc->startCTFE();
1476 e = expressionSemantic(e, sc);
1477 e = resolveProperties(sc, e);
1478 sc = sc->endCTFE();
1479
1480 e = e->ctfeInterpret();
1481 if (i == 0)
1482 buf.writestring(" (");
1483 else
1484 buf.writeByte(',');
1485 buf.writestring(e->toChars());
1486 }
1487 if (pd->args->length)
1488 buf.writeByte(')');
1489 }
1490 message("pragma %s", buf.peekChars());
1491 }
1492 goto Lnodecl;
1493 }
1494 else
1495 error(pd->loc, "unrecognized pragma(%s)", pd->ident->toChars());
1496
1497 Ldecl:
1498 if (pd->decl)
1499 {
1500 Scope *sc2 = pd->newScope(sc);
1501
1502 for (size_t i = 0; i < pd->decl->length; i++)
1503 {
1504 Dsymbol *s = (*pd->decl)[i];
1505
1506 dsymbolSemantic(s, sc2);
1507
1508 if (pd->ident == Id::mangle)
1509 {
1510 assert(pd->args && pd->args->length == 1);
1511 if (StringExp *se = (*pd->args)[0]->toStringExp())
1512 {
1513 char *name = (char *)mem.xmalloc(se->len + 1);
1514 memcpy(name, se->string, se->len);
1515 name[se->len] = 0;
1516
1517 unsigned cnt = setMangleOverride(s, name);
1518 if (cnt > 1)
1519 pd->error("can only apply to a single declaration");
1520 }
1521 }
1522 }
1523
1524 if (sc2 != sc)
1525 sc2->pop();
1526 }
1527 return;
1528
1529 Lnodecl:
1530 if (pd->decl)
1531 {
1532 pd->error("pragma is missing closing `;`");
1533 goto Ldecl; // do them anyway, to avoid segfaults.
1534 }
1535 }
1536
1537 void visit(StaticIfDeclaration *sid)
1538 {
1539 attribSemantic(sid);
1540 }
1541
1542 void visit(StaticForeachDeclaration *sfd)
1543 {
1544 attribSemantic(sfd);
1545 }
1546
1547 Dsymbols *compileIt(CompileDeclaration *cd)
1548 {
1549 //printf("CompileDeclaration::compileIt(loc = %d) %s\n", cd->loc.linnum, cd->exp->toChars());
1550 StringExp *se = semanticString(sc, cd->exp, "argument to mixin");
1551 if (!se)
1552 return NULL;
1553 se = se->toUTF8(sc);
1554
1555 unsigned errors = global.errors;
1556 Parser p(cd->loc, sc->_module, (utf8_t *)se->string, se->len, 0);
1557 p.nextToken();
1558
1559 Dsymbols *d = p.parseDeclDefs(0);
1560 if (global.errors != errors)
1561 return NULL;
1562
1563 if (p.token.value != TOKeof)
1564 {
1565 cd->exp->error("incomplete mixin declaration (%s)", se->toChars());
1566 return NULL;
1567 }
1568 return d;
1569 }
1570
1571 void visit(CompileDeclaration *cd)
1572 {
1573 //printf("CompileDeclaration::semantic()\n");
1574 if (!cd->compiled)
1575 {
1576 cd->decl = compileIt(cd);
1577 cd->AttribDeclaration::addMember(sc, cd->scopesym);
1578 cd->compiled = true;
1579
1580 if (cd->_scope && cd->decl)
1581 {
1582 for (size_t i = 0; i < cd->decl->length; i++)
1583 {
1584 Dsymbol *s = (*cd->decl)[i];
1585 s->setScope(cd->_scope);
1586 }
1587 }
1588 }
1589 attribSemantic(cd);
1590 }
1591
1592 void visit(UserAttributeDeclaration *uad)
1593 {
1594 //printf("UserAttributeDeclaration::semantic() %p\n", this);
1595 if (uad->decl && !uad->_scope)
1596 uad->Dsymbol::setScope(sc); // for function local symbols
1597
1598 attribSemantic(uad);
1599 }
1600
1601 void visit(StaticAssert *sa)
1602 {
1603 if (sa->semanticRun < PASSsemanticdone)
1604 sa->semanticRun = PASSsemanticdone;
1605 }
1606
1607 void visit(DebugSymbol *ds)
1608 {
1609 //printf("DebugSymbol::semantic() %s\n", ds->toChars());
1610 if (ds->semanticRun < PASSsemanticdone)
1611 ds->semanticRun = PASSsemanticdone;
1612 }
1613
1614 void visit(VersionSymbol *vs)
1615 {
1616 if (vs->semanticRun < PASSsemanticdone)
1617 vs->semanticRun = PASSsemanticdone;
1618 }
1619
1620 void visit(Package *pkg)
1621 {
1622 if (pkg->semanticRun < PASSsemanticdone)
1623 pkg->semanticRun = PASSsemanticdone;
1624 }
1625
1626 void visit(Module *m)
1627 {
1628 if (m->semanticRun != PASSinit)
1629 return;
1630
1631 //printf("+Module::semantic(this = %p, '%s'): parent = %p\n", this, m->toChars(), parent);
1632 m->semanticRun = PASSsemantic;
1633
1634 // Note that modules get their own scope, from scratch.
1635 // This is so regardless of where in the syntax a module
1636 // gets imported, it is unaffected by context.
1637 Scope *sc = m->_scope; // see if already got one from importAll()
1638 if (!sc)
1639 {
1640 Scope::createGlobal(m); // create root scope
1641 }
1642
1643 //printf("Module = %p, linkage = %d\n", sc->scopesym, sc->linkage);
1644
1645 // Pass 1 semantic routines: do public side of the definition
1646 for (size_t i = 0; i < m->members->length; i++)
1647 {
1648 Dsymbol *s = (*m->members)[i];
1649
1650 //printf("\tModule('%s'): '%s'.semantic()\n", m->toChars(), s->toChars());
1651 dsymbolSemantic(s, sc);
1652 m->runDeferredSemantic();
1653 }
1654
1655 if (m->userAttribDecl)
1656 {
1657 dsymbolSemantic(m->userAttribDecl, sc);
1658 }
1659
1660 if (!m->_scope)
1661 {
1662 sc = sc->pop();
1663 sc->pop(); // 2 pops because Scope::createGlobal() created 2
1664 }
1665 m->semanticRun = PASSsemanticdone;
1666 //printf("-Module::semantic(this = %p, '%s'): parent = %p\n", m, m->toChars(), parent);
1667 }
1668
1669 void visit(EnumDeclaration *ed)
1670 {
1671 //printf("EnumDeclaration::semantic(sd = %p, '%s') %s\n", sc->scopesym, sc->scopesym->toChars(), ed->toChars());
1672 //printf("EnumDeclaration::semantic() %p %s\n", ed, ed->toChars());
1673 if (ed->semanticRun >= PASSsemanticdone)
1674 return; // semantic() already completed
1675 if (ed->semanticRun == PASSsemantic)
1676 {
1677 assert(ed->memtype);
1678 error(ed->loc, "circular reference to enum base type %s", ed->memtype->toChars());
1679 ed->errors = true;
1680 ed->semanticRun = PASSsemanticdone;
1681 return;
1682 }
1683 unsigned dprogress_save = Module::dprogress;
1684
1685 Scope *scx = NULL;
1686 if (ed->_scope)
1687 {
1688 sc = ed->_scope;
1689 scx = ed->_scope; // save so we don't make redundant copies
1690 ed->_scope = NULL;
1691 }
1692
1693 if (!sc)
1694 return;
1695
1696 ed->parent = sc->parent;
1697 ed->type = typeSemantic(ed->type, ed->loc, sc);
1698
1699 ed->protection = sc->protection;
1700 if (sc->stc & STCdeprecated)
1701 ed->isdeprecated = true;
1702 ed->userAttribDecl = sc->userAttribDecl;
1703
1704 ed->semanticRun = PASSsemantic;
1705
1706 if (!ed->members && !ed->memtype) // enum ident;
1707 {
1708 ed->semanticRun = PASSsemanticdone;
1709 return;
1710 }
1711
1712 if (!ed->symtab)
1713 ed->symtab = new DsymbolTable();
1714
1715 /* The separate, and distinct, cases are:
1716 * 1. enum { ... }
1717 * 2. enum : memtype { ... }
1718 * 3. enum ident { ... }
1719 * 4. enum ident : memtype { ... }
1720 * 5. enum ident : memtype;
1721 * 6. enum ident;
1722 */
1723
1724 if (ed->memtype)
1725 {
1726 ed->memtype = typeSemantic(ed->memtype, ed->loc, sc);
1727
1728 /* Check to see if memtype is forward referenced
1729 */
1730 if (ed->memtype->ty == Tenum)
1731 {
1732 EnumDeclaration *sym = (EnumDeclaration *)ed->memtype->toDsymbol(sc);
1733 if (!sym->memtype || !sym->members || !sym->symtab || sym->_scope)
1734 {
1735 // memtype is forward referenced, so try again later
1736 ed->_scope = scx ? scx : sc->copy();
1737 ed->_scope->setNoFree();
1738 ed->_scope->_module->addDeferredSemantic(ed);
1739 Module::dprogress = dprogress_save;
1740 //printf("\tdeferring %s\n", ed->toChars());
1741 ed->semanticRun = PASSinit;
1742 return;
1743 }
1744 }
1745 if (ed->memtype->ty == Tvoid)
1746 {
1747 ed->error("base type must not be void");
1748 ed->memtype = Type::terror;
1749 }
1750 if (ed->memtype->ty == Terror)
1751 {
1752 ed->errors = true;
1753 if (ed->members)
1754 {
1755 for (size_t i = 0; i < ed->members->length; i++)
1756 {
1757 Dsymbol *s = (*ed->members)[i];
1758 s->errors = true; // poison all the members
1759 }
1760 }
1761 ed->semanticRun = PASSsemanticdone;
1762 return;
1763 }
1764 }
1765
1766 ed->semanticRun = PASSsemanticdone;
1767
1768 if (!ed->members) // enum ident : memtype;
1769 return;
1770
1771 if (ed->members->length == 0)
1772 {
1773 ed->error("enum %s must have at least one member", ed->toChars());
1774 ed->errors = true;
1775 return;
1776 }
1777
1778 Module::dprogress++;
1779
1780 Scope *sce;
1781 if (ed->isAnonymous())
1782 sce = sc;
1783 else
1784 {
1785 sce = sc->push(ed);
1786 sce->parent = ed;
1787 }
1788 sce = sce->startCTFE();
1789 sce->setNoFree(); // needed for getMaxMinValue()
1790
1791 /* Each enum member gets the sce scope
1792 */
1793 for (size_t i = 0; i < ed->members->length; i++)
1794 {
1795 EnumMember *em = (*ed->members)[i]->isEnumMember();
1796 if (em)
1797 em->_scope = sce;
1798 }
1799
1800 if (!ed->added)
1801 {
1802 /* addMember() is not called when the EnumDeclaration appears as a function statement,
1803 * so we have to do what addMember() does and install the enum members in the right symbol
1804 * table
1805 */
1806 ScopeDsymbol *scopesym = NULL;
1807 if (ed->isAnonymous())
1808 {
1809 /* Anonymous enum members get added to enclosing scope.
1810 */
1811 for (Scope *sct = sce; 1; sct = sct->enclosing)
1812 {
1813 assert(sct);
1814 if (sct->scopesym)
1815 {
1816 scopesym = sct->scopesym;
1817 if (!sct->scopesym->symtab)
1818 sct->scopesym->symtab = new DsymbolTable();
1819 break;
1820 }
1821 }
1822 }
1823 else
1824 {
1825 // Otherwise enum members are in the EnumDeclaration's symbol table
1826 scopesym = ed;
1827 }
1828
1829 for (size_t i = 0; i < ed->members->length; i++)
1830 {
1831 EnumMember *em = (*ed->members)[i]->isEnumMember();
1832 if (em)
1833 {
1834 em->ed = ed;
1835 em->addMember(sc, scopesym);
1836 }
1837 }
1838 }
1839
1840 for (size_t i = 0; i < ed->members->length; i++)
1841 {
1842 EnumMember *em = (*ed->members)[i]->isEnumMember();
1843 if (em)
1844 dsymbolSemantic(em, em->_scope);
1845 }
1846 //printf("defaultval = %lld\n", defaultval);
1847
1848 //if (defaultval) printf("defaultval: %s %s\n", defaultval->toChars(), defaultval->type->toChars());
1849 //printf("members = %s\n", ed->members->toChars());
1850 }
1851
1852 void visit(EnumMember *em)
1853 {
1854 //printf("EnumMember::semantic() %s\n", em->toChars());
1855 if (em->errors || em->semanticRun >= PASSsemanticdone)
1856 return;
1857 if (em->semanticRun == PASSsemantic)
1858 {
1859 em->error("circular reference to enum member");
1860 Lerrors:
1861 em->errors = true;
1862 em->semanticRun = PASSsemanticdone;
1863 return;
1864 }
1865 assert(em->ed);
1866
1867 dsymbolSemantic(em->ed, sc);
1868 if (em->ed->errors)
1869 goto Lerrors;
1870
1871 if (em->errors || em->semanticRun >= PASSsemanticdone)
1872 return;
1873
1874 if (em->_scope)
1875 sc = em->_scope;
1876 if (!sc)
1877 return;
1878
1879 em->semanticRun = PASSsemantic;
1880
1881 em->protection = em->ed->isAnonymous() ? em->ed->protection : Prot(Prot::public_);
1882 em->linkage = LINKd;
1883 em->storage_class |= STCmanifest;
1884
1885 // https://issues.dlang.org/show_bug.cgi?id=9701
1886 if (em->ed->isAnonymous())
1887 {
1888 if (em->userAttribDecl)
1889 em->userAttribDecl->userAttribDecl = em->ed->userAttribDecl;
1890 else
1891 em->userAttribDecl = em->ed->userAttribDecl;
1892 }
1893
1894 // The first enum member is special
1895 bool first = (em == (*em->ed->members)[0]);
1896
1897 if (em->origType)
1898 {
1899 em->origType = typeSemantic(em->origType, em->loc, sc);
1900 em->type = em->origType;
1901 assert(em->value()); // "type id;" is not a valid enum member declaration
1902 }
1903
1904 if (em->value())
1905 {
1906 Expression *e = em->value();
1907 assert(e->dyncast() == DYNCAST_EXPRESSION);
1908 e = expressionSemantic(e, sc);
1909 e = resolveProperties(sc, e);
1910 e = e->ctfeInterpret();
1911 if (e->op == TOKerror)
1912 goto Lerrors;
1913 if (first && !em->ed->memtype && !em->ed->isAnonymous())
1914 {
1915 em->ed->memtype = e->type;
1916 if (em->ed->memtype->ty == Terror)
1917 {
1918 em->ed->errors = true;
1919 goto Lerrors;
1920 }
1921 if (em->ed->memtype->ty != Terror)
1922 {
1923 /* Bugzilla 11746: All of named enum members should have same type
1924 * with the first member. If the following members were referenced
1925 * during the first member semantic, their types should be unified.
1926 */
1927 for (size_t i = 0; i < em->ed->members->length; i++)
1928 {
1929 EnumMember *enm = (*em->ed->members)[i]->isEnumMember();
1930 if (!enm || enm == em || enm->semanticRun < PASSsemanticdone || enm->origType)
1931 continue;
1932
1933 //printf("[%d] enm = %s, enm->semanticRun = %d\n", i, enm->toChars(), enm->semanticRun);
1934 Expression *ev = enm->value();
1935 ev = ev->implicitCastTo(sc, em->ed->memtype);
1936 ev = ev->ctfeInterpret();
1937 ev = ev->castTo(sc, em->ed->type);
1938 if (ev->op == TOKerror)
1939 em->ed->errors = true;
1940 enm->value() = ev;
1941 }
1942 if (em->ed->errors)
1943 {
1944 em->ed->memtype = Type::terror;
1945 goto Lerrors;
1946 }
1947 }
1948 }
1949
1950 if (em->ed->memtype && !em->origType)
1951 {
1952 e = e->implicitCastTo(sc, em->ed->memtype);
1953 e = e->ctfeInterpret();
1954
1955 // save origValue for better json output
1956 em->origValue = e;
1957
1958 if (!em->ed->isAnonymous())
1959 {
1960 e = e->castTo(sc, em->ed->type);
1961 e = e->ctfeInterpret();
1962 }
1963 }
1964 else if (em->origType)
1965 {
1966 e = e->implicitCastTo(sc, em->origType);
1967 e = e->ctfeInterpret();
1968 assert(em->ed->isAnonymous());
1969
1970 // save origValue for better json output
1971 em->origValue = e;
1972 }
1973 em->value() = e;
1974 }
1975 else if (first)
1976 {
1977 Type *t;
1978 if (em->ed->memtype)
1979 t = em->ed->memtype;
1980 else
1981 {
1982 t = Type::tint32;
1983 if (!em->ed->isAnonymous())
1984 em->ed->memtype = t;
1985 }
1986 Expression *e = new IntegerExp(em->loc, 0, Type::tint32);
1987 e = e->implicitCastTo(sc, t);
1988 e = e->ctfeInterpret();
1989
1990 // save origValue for better json output
1991 em->origValue = e;
1992
1993 if (!em->ed->isAnonymous())
1994 {
1995 e = e->castTo(sc, em->ed->type);
1996 e = e->ctfeInterpret();
1997 }
1998 em->value() = e;
1999 }
2000 else
2001 {
2002 /* Find the previous enum member,
2003 * and set this to be the previous value + 1
2004 */
2005 EnumMember *emprev = NULL;
2006 for (size_t i = 0; i < em->ed->members->length; i++)
2007 {
2008 EnumMember *enm = (*em->ed->members)[i]->isEnumMember();
2009 if (enm)
2010 {
2011 if (enm == em)
2012 break;
2013 emprev = enm;
2014 }
2015 }
2016 assert(emprev);
2017 if (emprev->semanticRun < PASSsemanticdone) // if forward reference
2018 dsymbolSemantic(emprev, emprev->_scope); // resolve it
2019 if (emprev->errors)
2020 goto Lerrors;
2021
2022 Expression *eprev = emprev->value();
2023 Type *tprev = eprev->type->equals(em->ed->type) ? em->ed->memtype : eprev->type;
2024
2025 Expression *emax = tprev->getProperty(em->ed->loc, Id::max, 0);
2026 emax = expressionSemantic(emax, sc);
2027 emax = emax->ctfeInterpret();
2028
2029 // Set value to (eprev + 1).
2030 // But first check that (eprev != emax)
2031 assert(eprev);
2032 Expression *e = new EqualExp(TOKequal, em->loc, eprev, emax);
2033 e = expressionSemantic(e, sc);
2034 e = e->ctfeInterpret();
2035 if (e->toInteger())
2036 {
2037 em->error("initialization with (%s.%s + 1) causes overflow for type `%s`", emprev->ed->toChars(), emprev->toChars(), em->ed->type->toBasetype()->toChars());
2038 goto Lerrors;
2039 }
2040
2041 // Now set e to (eprev + 1)
2042 e = new AddExp(em->loc, eprev, new IntegerExp(em->loc, 1, Type::tint32));
2043 e = expressionSemantic(e, sc);
2044 e = e->castTo(sc, eprev->type);
2045 e = e->ctfeInterpret();
2046
2047 // save origValue (without cast) for better json output
2048 if (e->op != TOKerror) // avoid duplicate diagnostics
2049 {
2050 assert(emprev->origValue);
2051 em->origValue = new AddExp(em->loc, emprev->origValue, new IntegerExp(em->loc, 1, Type::tint32));
2052 em->origValue = expressionSemantic(em->origValue, sc);
2053 em->origValue = em->origValue->ctfeInterpret();
2054 }
2055
2056 if (e->op == TOKerror)
2057 goto Lerrors;
2058 if (e->type->isfloating())
2059 {
2060 // Check that e != eprev (not always true for floats)
2061 Expression *etest = new EqualExp(TOKequal, em->loc, e, eprev);
2062 etest = expressionSemantic(etest, sc);
2063 etest = etest->ctfeInterpret();
2064 if (etest->toInteger())
2065 {
2066 em->error("has inexact value, due to loss of precision");
2067 goto Lerrors;
2068 }
2069 }
2070 em->value() = e;
2071 }
2072 if (!em->origType)
2073 em->type = em->value()->type;
2074
2075 assert(em->origValue);
2076 em->semanticRun = PASSsemanticdone;
2077 }
2078
2079 void visit(TemplateDeclaration *tempdecl)
2080 {
2081 if (tempdecl->semanticRun != PASSinit)
2082 return; // semantic() already run
2083
2084 // Remember templates defined in module object that we need to know about
2085 if (sc->_module && sc->_module->ident == Id::object)
2086 {
2087 if (tempdecl->ident == Id::RTInfo)
2088 Type::rtinfo = tempdecl;
2089 }
2090
2091 /* Remember Scope for later instantiations, but make
2092 * a copy since attributes can change.
2093 */
2094 if (!tempdecl->_scope)
2095 {
2096 tempdecl->_scope = sc->copy();
2097 tempdecl->_scope->setNoFree();
2098 }
2099
2100 tempdecl->semanticRun = PASSsemantic;
2101
2102 tempdecl->parent = sc->parent;
2103 tempdecl->protection = sc->protection;
2104 tempdecl->isstatic = tempdecl->toParent()->isModule() || (tempdecl->_scope->stc & STCstatic);
2105
2106 if (!tempdecl->isstatic)
2107 {
2108 if (AggregateDeclaration *ad = tempdecl->parent->pastMixin()->isAggregateDeclaration())
2109 ad->makeNested();
2110 }
2111
2112 // Set up scope for parameters
2113 ScopeDsymbol *paramsym = new ScopeDsymbol();
2114 paramsym->parent = tempdecl->parent;
2115 Scope *paramscope = sc->push(paramsym);
2116 paramscope->stc = 0;
2117
2118 if (global.params.doDocComments)
2119 {
2120 tempdecl->origParameters = new TemplateParameters();
2121 tempdecl->origParameters->setDim(tempdecl->parameters->length);
2122 for (size_t i = 0; i < tempdecl->parameters->length; i++)
2123 {
2124 TemplateParameter *tp = (*tempdecl->parameters)[i];
2125 (*tempdecl->origParameters)[i] = tp->syntaxCopy();
2126 }
2127 }
2128
2129 for (size_t i = 0; i < tempdecl->parameters->length; i++)
2130 {
2131 TemplateParameter *tp = (*tempdecl->parameters)[i];
2132
2133 if (!tp->declareParameter(paramscope))
2134 {
2135 error(tp->loc, "parameter `%s` multiply defined", tp->ident->toChars());
2136 tempdecl->errors = true;
2137 }
2138 if (!tpsemantic(tp, paramscope, tempdecl->parameters))
2139 {
2140 tempdecl->errors = true;
2141 }
2142 if (i + 1 != tempdecl->parameters->length && tp->isTemplateTupleParameter())
2143 {
2144 tempdecl->error("template tuple parameter must be last one");
2145 tempdecl->errors = true;
2146 }
2147 }
2148
2149 /* Calculate TemplateParameter::dependent
2150 */
2151 TemplateParameters tparams;
2152 tparams.setDim(1);
2153 for (size_t i = 0; i < tempdecl->parameters->length; i++)
2154 {
2155 TemplateParameter *tp = (*tempdecl->parameters)[i];
2156 tparams[0] = tp;
2157
2158 for (size_t j = 0; j < tempdecl->parameters->length; j++)
2159 {
2160 // Skip cases like: X(T : T)
2161 if (i == j)
2162 continue;
2163
2164 if (TemplateTypeParameter *ttp = (*tempdecl->parameters)[j]->isTemplateTypeParameter())
2165 {
2166 if (reliesOnTident(ttp->specType, &tparams))
2167 tp->dependent = true;
2168 }
2169 else if (TemplateAliasParameter *tap = (*tempdecl->parameters)[j]->isTemplateAliasParameter())
2170 {
2171 if (reliesOnTident(tap->specType, &tparams) ||
2172 reliesOnTident(isType(tap->specAlias), &tparams))
2173 {
2174 tp->dependent = true;
2175 }
2176 }
2177 }
2178 }
2179
2180 paramscope->pop();
2181
2182 // Compute again
2183 tempdecl->onemember = NULL;
2184 if (tempdecl->members)
2185 {
2186 Dsymbol *s;
2187 if (Dsymbol::oneMembers(tempdecl->members, &s, tempdecl->ident) && s)
2188 {
2189 tempdecl->onemember = s;
2190 s->parent = tempdecl;
2191 }
2192 }
2193
2194 /* BUG: should check:
2195 * o no virtual functions or non-static data members of classes
2196 */
2197 tempdecl->semanticRun = PASSsemanticdone;
2198 }
2199
2200 void visit(TemplateInstance *ti)
2201 {
2202 templateInstanceSemantic(ti, sc, NULL);
2203 }
2204
2205 void visit(TemplateMixin *tm)
2206 {
2207 if (tm->semanticRun != PASSinit)
2208 {
2209 // When a class/struct contains mixin members, and is done over
2210 // because of forward references, never reach here so semanticRun
2211 // has been reset to PASSinit.
2212 return;
2213 }
2214 tm->semanticRun = PASSsemantic;
2215
2216 Scope *scx = NULL;
2217 if (tm->_scope)
2218 {
2219 sc = tm->_scope;
2220 scx = tm->_scope; // save so we don't make redundant copies
2221 tm->_scope = NULL;
2222 }
2223
2224 /* Run semantic on each argument, place results in tiargs[],
2225 * then find best match template with tiargs
2226 */
2227 if (!tm->findTempDecl(sc) ||
2228 !tm->semanticTiargs(sc) ||
2229 !tm->findBestMatch(sc, NULL))
2230 {
2231 if (tm->semanticRun == PASSinit) // forward reference had occured
2232 {
2233 //printf("forward reference - deferring\n");
2234 tm->_scope = scx ? scx : sc->copy();
2235 tm->_scope->setNoFree();
2236 tm->_scope->_module->addDeferredSemantic(tm);
2237 return;
2238 }
2239
2240 tm->inst = tm;
2241 tm->errors = true;
2242 return; // error recovery
2243 }
2244 TemplateDeclaration *tempdecl = tm->tempdecl->isTemplateDeclaration();
2245 assert(tempdecl);
2246
2247 if (!tm->ident)
2248 {
2249 /* Assign scope local unique identifier, as same as lambdas.
2250 */
2251 const char *s = "__mixin";
2252
2253 if (FuncDeclaration *func = sc->parent->isFuncDeclaration())
2254 {
2255 tm->symtab = func->localsymtab;
2256 if (tm->symtab)
2257 {
2258 // Inside template constraint, symtab is not set yet.
2259 goto L1;
2260 }
2261 }
2262 else
2263 {
2264 tm->symtab = sc->parent->isScopeDsymbol()->symtab;
2265 L1:
2266 assert(tm->symtab);
2267 int num = (int)dmd_aaLen(tm->symtab->tab) + 1;
2268 tm->ident = Identifier::generateId(s, num);
2269 tm->symtab->insert(tm);
2270 }
2271 }
2272
2273 tm->inst = tm;
2274 tm->parent = sc->parent;
2275
2276 /* Detect recursive mixin instantiations.
2277 */
2278 for (Dsymbol *s = tm->parent; s; s = s->parent)
2279 {
2280 //printf("\ts = '%s'\n", s->toChars());
2281 TemplateMixin *tmix = s->isTemplateMixin();
2282 if (!tmix || tempdecl != tmix->tempdecl)
2283 continue;
2284
2285 /* Different argument list lengths happen with variadic args
2286 */
2287 if (tm->tiargs->length != tmix->tiargs->length)
2288 continue;
2289
2290 for (size_t i = 0; i < tm->tiargs->length; i++)
2291 {
2292 RootObject *o = (*tm->tiargs)[i];
2293 Type *ta = isType(o);
2294 Expression *ea = isExpression(o);
2295 Dsymbol *sa = isDsymbol(o);
2296 RootObject *tmo = (*tmix->tiargs)[i];
2297 if (ta)
2298 {
2299 Type *tmta = isType(tmo);
2300 if (!tmta)
2301 goto Lcontinue;
2302 if (!ta->equals(tmta))
2303 goto Lcontinue;
2304 }
2305 else if (ea)
2306 {
2307 Expression *tme = isExpression(tmo);
2308 if (!tme || !ea->equals(tme))
2309 goto Lcontinue;
2310 }
2311 else if (sa)
2312 {
2313 Dsymbol *tmsa = isDsymbol(tmo);
2314 if (sa != tmsa)
2315 goto Lcontinue;
2316 }
2317 else
2318 assert(0);
2319 }
2320 tm->error("recursive mixin instantiation");
2321 return;
2322
2323 Lcontinue:
2324 continue;
2325 }
2326
2327 // Copy the syntax trees from the TemplateDeclaration
2328 tm->members = Dsymbol::arraySyntaxCopy(tempdecl->members);
2329 if (!tm->members)
2330 return;
2331
2332 tm->symtab = new DsymbolTable();
2333
2334 for (Scope *sce = sc; 1; sce = sce->enclosing)
2335 {
2336 ScopeDsymbol *sds = (ScopeDsymbol *)sce->scopesym;
2337 if (sds)
2338 {
2339 sds->importScope(tm, Prot(Prot::public_));
2340 break;
2341 }
2342 }
2343
2344 Scope *scy = sc->push(tm);
2345 scy->parent = tm;
2346
2347 tm->argsym = new ScopeDsymbol();
2348 tm->argsym->parent = scy->parent;
2349 Scope *argscope = scy->push(tm->argsym);
2350
2351 unsigned errorsave = global.errors;
2352
2353 // Declare each template parameter as an alias for the argument type
2354 tm->declareParameters(argscope);
2355
2356 // Add members to enclosing scope, as well as this scope
2357 for (size_t i = 0; i < tm->members->length; i++)
2358 {
2359 Dsymbol *s = (*tm->members)[i];
2360 s->addMember(argscope, tm);
2361 //printf("sc->parent = %p, sc->scopesym = %p\n", sc->parent, sc->scopesym);
2362 //printf("s->parent = %s\n", s->parent->toChars());
2363 }
2364
2365 // Do semantic() analysis on template instance members
2366 Scope *sc2 = argscope->push(tm);
2367 //size_t deferred_dim = Module::deferred.length;
2368
2369 static int nest;
2370 //printf("%d\n", nest);
2371 if (++nest > global.recursionLimit)
2372 {
2373 global.gag = 0; // ensure error message gets printed
2374 tm->error("recursive expansion");
2375 fatal();
2376 }
2377
2378 for (size_t i = 0; i < tm->members->length; i++)
2379 {
2380 Dsymbol *s = (*tm->members)[i];
2381 s->setScope(sc2);
2382 }
2383
2384 for (size_t i = 0; i < tm->members->length; i++)
2385 {
2386 Dsymbol *s = (*tm->members)[i];
2387 s->importAll(sc2);
2388 }
2389
2390 for (size_t i = 0; i < tm->members->length; i++)
2391 {
2392 Dsymbol *s = (*tm->members)[i];
2393 dsymbolSemantic(s, sc2);
2394 }
2395
2396 nest--;
2397
2398 /* In DeclDefs scope, TemplateMixin does not have to handle deferred symbols.
2399 * Because the members would already call Module::addDeferredSemantic() for themselves.
2400 * See Struct, Class, Interface, and EnumDeclaration::semantic().
2401 */
2402 //if (!sc->func && Module::deferred.length > deferred_dim) {}
2403
2404 AggregateDeclaration *ad = tm->toParent()->isAggregateDeclaration();
2405 if (sc->func && !ad)
2406 {
2407 semantic2(tm, sc2);
2408 semantic3(tm, sc2);
2409 }
2410
2411 // Give additional context info if error occurred during instantiation
2412 if (global.errors != errorsave)
2413 {
2414 tm->error("error instantiating");
2415 tm->errors = true;
2416 }
2417
2418 sc2->pop();
2419 argscope->pop();
2420 scy->pop();
2421 }
2422
2423 void visit(Nspace *ns)
2424 {
2425 if (ns->semanticRun != PASSinit)
2426 return;
2427 if (ns->_scope)
2428 {
2429 sc = ns->_scope;
2430 ns->_scope = NULL;
2431 }
2432 if (!sc)
2433 return;
2434
2435 ns->semanticRun = PASSsemantic;
2436 ns->parent = sc->parent;
2437 if (ns->members)
2438 {
2439 assert(sc);
2440 sc = sc->push(ns);
2441 sc->linkage = LINKcpp; // note that namespaces imply C++ linkage
2442 sc->parent = ns;
2443
2444 for (size_t i = 0; i < ns->members->length; i++)
2445 {
2446 Dsymbol *s = (*ns->members)[i];
2447 s->importAll(sc);
2448 }
2449
2450 for (size_t i = 0; i < ns->members->length; i++)
2451 {
2452 Dsymbol *s = (*ns->members)[i];
2453 dsymbolSemantic(s, sc);
2454 }
2455 sc->pop();
2456 }
2457 ns->semanticRun = PASSsemanticdone;
2458 }
2459
2460 void funcDeclarationSemantic(FuncDeclaration *funcdecl)
2461 {
2462 TypeFunction *f;
2463 AggregateDeclaration *ad;
2464 InterfaceDeclaration *id;
2465
2466 if (funcdecl->semanticRun != PASSinit && funcdecl->isFuncLiteralDeclaration())
2467 {
2468 /* Member functions that have return types that are
2469 * forward references can have semantic() run more than
2470 * once on them.
2471 * See test\interface2.d, test20
2472 */
2473 return;
2474 }
2475
2476 if (funcdecl->semanticRun >= PASSsemanticdone)
2477 return;
2478 assert(funcdecl->semanticRun <= PASSsemantic);
2479 funcdecl->semanticRun = PASSsemantic;
2480
2481 if (funcdecl->_scope)
2482 {
2483 sc = funcdecl->_scope;
2484 funcdecl->_scope = NULL;
2485 }
2486
2487 if (!sc || funcdecl->errors)
2488 return;
2489
2490 funcdecl->parent = sc->parent;
2491 Dsymbol *parent = funcdecl->toParent();
2492
2493 funcdecl->foverrides.setDim(0); // reset in case semantic() is being retried for this function
2494
2495 funcdecl->storage_class |= sc->stc & ~STCref;
2496 ad = funcdecl->isThis();
2497 // Don't nest structs b/c of generated methods which should not access the outer scopes.
2498 // https://issues.dlang.org/show_bug.cgi?id=16627
2499 if (ad && !funcdecl->generated)
2500 {
2501 funcdecl->storage_class |= ad->storage_class & (STC_TYPECTOR | STCsynchronized);
2502 ad->makeNested();
2503 }
2504 if (sc->func)
2505 funcdecl->storage_class |= sc->func->storage_class & STCdisable;
2506 // Remove prefix storage classes silently.
2507 if ((funcdecl->storage_class & STC_TYPECTOR) && !(ad || funcdecl->isNested()))
2508 funcdecl->storage_class &= ~STC_TYPECTOR;
2509
2510 //printf("function storage_class = x%llx, sc->stc = x%llx, %x\n", funcdecl->storage_class, sc->stc, Declaration::isFinal());
2511
2512 FuncLiteralDeclaration *fld = funcdecl->isFuncLiteralDeclaration();
2513 if (fld && fld->treq)
2514 {
2515 Type *treq = fld->treq;
2516 assert(treq->nextOf()->ty == Tfunction);
2517 if (treq->ty == Tdelegate)
2518 fld->tok = TOKdelegate;
2519 else if (treq->ty == Tpointer && treq->nextOf()->ty == Tfunction)
2520 fld->tok = TOKfunction;
2521 else
2522 assert(0);
2523 funcdecl->linkage = treq->nextOf()->toTypeFunction()->linkage;
2524 }
2525 else
2526 funcdecl->linkage = sc->linkage;
2527 funcdecl->inlining = sc->inlining;
2528 funcdecl->protection = sc->protection;
2529 funcdecl->userAttribDecl = sc->userAttribDecl;
2530
2531 if (!funcdecl->originalType)
2532 funcdecl->originalType = funcdecl->type->syntaxCopy();
2533 if (funcdecl->type->ty != Tfunction)
2534 {
2535 if (funcdecl->type->ty != Terror)
2536 {
2537 funcdecl->error("%s must be a function instead of %s", funcdecl->toChars(), funcdecl->type->toChars());
2538 funcdecl->type = Type::terror;
2539 }
2540 funcdecl->errors = true;
2541 return;
2542 }
2543 if (!funcdecl->type->deco)
2544 {
2545 sc = sc->push();
2546 sc->stc |= funcdecl->storage_class & (STCdisable | STCdeprecated); // forward to function type
2547 TypeFunction *tf = funcdecl->type->toTypeFunction();
2548
2549 if (sc->func)
2550 {
2551 /* If the nesting parent is pure without inference,
2552 * then this function defaults to pure too.
2553 *
2554 * auto foo() pure {
2555 * auto bar() {} // become a weak purity funciton
2556 * class C { // nested class
2557 * auto baz() {} // become a weak purity funciton
2558 * }
2559 *
2560 * static auto boo() {} // typed as impure
2561 * // Even though, boo cannot call any impure functions.
2562 * // See also Expression::checkPurity().
2563 * }
2564 */
2565 if (tf->purity == PUREimpure && (funcdecl->isNested() || funcdecl->isThis()))
2566 {
2567 FuncDeclaration *fd = NULL;
2568 for (Dsymbol *p = funcdecl->toParent2(); p; p = p->toParent2())
2569 {
2570 if (AggregateDeclaration *adx = p->isAggregateDeclaration())
2571 {
2572 if (adx->isNested())
2573 continue;
2574 break;
2575 }
2576 if ((fd = p->isFuncDeclaration()) != NULL)
2577 break;
2578 }
2579
2580 /* If the parent's purity is inferred, then this function's purity needs
2581 * to be inferred first.
2582 */
2583 if (fd && fd->isPureBypassingInference() >= PUREweak &&
2584 !funcdecl->isInstantiated())
2585 {
2586 tf->purity = PUREfwdref; // default to pure
2587 }
2588 }
2589 }
2590
2591 if (tf->isref) sc->stc |= STCref;
2592 if (tf->isscope) sc->stc |= STCscope;
2593 if (tf->isnothrow) sc->stc |= STCnothrow;
2594 if (tf->isnogc) sc->stc |= STCnogc;
2595 if (tf->isproperty) sc->stc |= STCproperty;
2596 if (tf->purity == PUREfwdref) sc->stc |= STCpure;
2597 if (tf->trust != TRUSTdefault)
2598 sc->stc &= ~(STCsafe | STCsystem | STCtrusted);
2599 if (tf->trust == TRUSTsafe) sc->stc |= STCsafe;
2600 if (tf->trust == TRUSTsystem) sc->stc |= STCsystem;
2601 if (tf->trust == TRUSTtrusted) sc->stc |= STCtrusted;
2602
2603 if (funcdecl->isCtorDeclaration())
2604 {
2605 sc->flags |= SCOPEctor;
2606
2607 Type *tret = ad->handleType();
2608 assert(tret);
2609 tret = tret->addStorageClass(funcdecl->storage_class | sc->stc);
2610 tret = tret->addMod(funcdecl->type->mod);
2611 tf->next = tret;
2612
2613 if (ad->isStructDeclaration())
2614 sc->stc |= STCref;
2615 }
2616
2617 // 'return' on a non-static class member function implies 'scope' as well
2618 if (ad && ad->isClassDeclaration() && (tf->isreturn || sc->stc & STCreturn) && !(sc->stc & STCstatic))
2619 sc->stc |= STCscope;
2620
2621 // If 'this' has no pointers, remove 'scope' as it has no meaning
2622 if (sc->stc & STCscope && ad && ad->isStructDeclaration() && !ad->type->hasPointers())
2623 {
2624 sc->stc &= ~STCscope;
2625 tf->isscope = false;
2626 }
2627
2628 sc->linkage = funcdecl->linkage;
2629
2630 if (!tf->isNaked() && !(funcdecl->isThis() || funcdecl->isNested()))
2631 {
2632 OutBuffer buf;
2633 MODtoBuffer(&buf, tf->mod);
2634 funcdecl->error("without `this` cannot be %s", buf.peekChars());
2635 tf->mod = 0; // remove qualifiers
2636 }
2637
2638 /* Apply const, immutable, wild and shared storage class
2639 * to the function type. Do this before type semantic.
2640 */
2641 StorageClass stc = funcdecl->storage_class;
2642 if (funcdecl->type->isImmutable())
2643 stc |= STCimmutable;
2644 if (funcdecl->type->isConst())
2645 stc |= STCconst;
2646 if (funcdecl->type->isShared() || funcdecl->storage_class & STCsynchronized)
2647 stc |= STCshared;
2648 if (funcdecl->type->isWild())
2649 stc |= STCwild;
2650 switch (stc & STC_TYPECTOR)
2651 {
2652 case STCimmutable:
2653 case STCimmutable | STCconst:
2654 case STCimmutable | STCwild:
2655 case STCimmutable | STCwild | STCconst:
2656 case STCimmutable | STCshared:
2657 case STCimmutable | STCshared | STCconst:
2658 case STCimmutable | STCshared | STCwild:
2659 case STCimmutable | STCshared | STCwild | STCconst:
2660 // Don't use immutableOf(), as that will do a merge()
2661 funcdecl->type = funcdecl->type->makeImmutable();
2662 break;
2663
2664 case STCconst:
2665 funcdecl->type = funcdecl->type->makeConst();
2666 break;
2667
2668 case STCwild:
2669 funcdecl->type = funcdecl->type->makeWild();
2670 break;
2671
2672 case STCwild | STCconst:
2673 funcdecl->type = funcdecl->type->makeWildConst();
2674 break;
2675
2676 case STCshared:
2677 funcdecl->type = funcdecl->type->makeShared();
2678 break;
2679
2680 case STCshared | STCconst:
2681 funcdecl->type = funcdecl->type->makeSharedConst();
2682 break;
2683
2684 case STCshared | STCwild:
2685 funcdecl->type = funcdecl->type->makeSharedWild();
2686 break;
2687
2688 case STCshared | STCwild | STCconst:
2689 funcdecl->type = funcdecl->type->makeSharedWildConst();
2690 break;
2691
2692 case 0:
2693 break;
2694
2695 default:
2696 assert(0);
2697 }
2698
2699 funcdecl->type = typeSemantic(funcdecl->type, funcdecl->loc, sc);
2700 sc = sc->pop();
2701 }
2702 if (funcdecl->type->ty != Tfunction)
2703 {
2704 if (funcdecl->type->ty != Terror)
2705 {
2706 funcdecl->error("%s must be a function instead of %s", funcdecl->toChars(), funcdecl->type->toChars());
2707 funcdecl->type = Type::terror;
2708 }
2709 funcdecl->errors = true;
2710 return;
2711 }
2712 else
2713 {
2714 // Merge back function attributes into 'originalType'.
2715 // It's used for mangling, ddoc, and json output.
2716 TypeFunction *tfo = funcdecl->originalType->toTypeFunction();
2717 TypeFunction *tfx = funcdecl->type->toTypeFunction();
2718 tfo->mod = tfx->mod;
2719 tfo->isscope = tfx->isscope;
2720 tfo->isscopeinferred = tfx->isscopeinferred;
2721 tfo->isref = tfx->isref;
2722 tfo->isnothrow = tfx->isnothrow;
2723 tfo->isnogc = tfx->isnogc;
2724 tfo->isproperty = tfx->isproperty;
2725 tfo->purity = tfx->purity;
2726 tfo->trust = tfx->trust;
2727
2728 funcdecl->storage_class &= ~(STC_TYPECTOR | STC_FUNCATTR);
2729 }
2730
2731 f = (TypeFunction *)funcdecl->type;
2732
2733 if ((funcdecl->storage_class & STCauto) && !f->isref && !funcdecl->inferRetType)
2734 funcdecl->error("storage class `auto` has no effect if return type is not inferred");
2735 /* Functions can only be 'scope' if they have a 'this'
2736 */
2737 if (f->isscope && !funcdecl->isNested() && !ad)
2738 {
2739 funcdecl->error("functions cannot be scope");
2740 }
2741
2742 if (f->isreturn && !funcdecl->needThis() && !funcdecl->isNested())
2743 {
2744 /* Non-static nested functions have a hidden 'this' pointer to which
2745 * the 'return' applies
2746 */
2747 funcdecl->error("static member has no `this` to which `return` can apply");
2748 }
2749
2750 if (funcdecl->isAbstract() && !funcdecl->isVirtual())
2751 {
2752 const char *sfunc;
2753 if (funcdecl->isStatic())
2754 sfunc = "static";
2755 else if (funcdecl->protection.kind == Prot::private_ || funcdecl->protection.kind == Prot::package_)
2756 sfunc = protectionToChars(funcdecl->protection.kind);
2757 else
2758 sfunc = "non-virtual";
2759 funcdecl->error("%s functions cannot be abstract", sfunc);
2760 }
2761
2762 if (funcdecl->isOverride() && !funcdecl->isVirtual())
2763 {
2764 Prot::Kind kind = funcdecl->prot().kind;
2765 if ((kind == Prot::private_ || kind == Prot::package_) && funcdecl->isMember())
2766 funcdecl->error("%s method is not virtual and cannot override", protectionToChars(kind));
2767 else
2768 funcdecl->error("cannot override a non-virtual function");
2769 }
2770
2771 if (funcdecl->isAbstract() && funcdecl->isFinalFunc())
2772 funcdecl->error("cannot be both final and abstract");
2773
2774 id = parent->isInterfaceDeclaration();
2775 if (id)
2776 {
2777 funcdecl->storage_class |= STCabstract;
2778
2779 if (funcdecl->isCtorDeclaration() ||
2780 funcdecl->isPostBlitDeclaration() ||
2781 funcdecl->isDtorDeclaration() ||
2782 funcdecl->isInvariantDeclaration() ||
2783 funcdecl->isNewDeclaration() || funcdecl->isDelete())
2784 funcdecl->error("constructors, destructors, postblits, invariants, new and delete functions are not allowed in interface %s", id->toChars());
2785 if (funcdecl->fbody && funcdecl->isVirtual())
2786 funcdecl->error("function body only allowed in final functions in interface %s", id->toChars());
2787 }
2788
2789 if (UnionDeclaration *ud = parent->isUnionDeclaration())
2790 {
2791 if (funcdecl->isPostBlitDeclaration() ||
2792 funcdecl->isDtorDeclaration() ||
2793 funcdecl->isInvariantDeclaration())
2794 funcdecl->error("destructors, postblits and invariants are not allowed in union %s", ud->toChars());
2795 }
2796
2797 if (parent->isStructDeclaration())
2798 {
2799 if (funcdecl->isCtorDeclaration())
2800 {
2801 goto Ldone;
2802 }
2803 }
2804
2805 if (ClassDeclaration *cd = parent->isClassDeclaration())
2806 {
2807 if (funcdecl->isCtorDeclaration())
2808 {
2809 goto Ldone;
2810 }
2811
2812 if (funcdecl->storage_class & STCabstract)
2813 cd->isabstract = ABSyes;
2814
2815 // if static function, do not put in vtbl[]
2816 if (!funcdecl->isVirtual())
2817 {
2818 //printf("\tnot virtual\n");
2819 goto Ldone;
2820 }
2821 // Suppress further errors if the return type is an error
2822 if (funcdecl->type->nextOf() == Type::terror)
2823 goto Ldone;
2824
2825 bool may_override = false;
2826 for (size_t i = 0; i < cd->baseclasses->length; i++)
2827 {
2828 BaseClass *b = (*cd->baseclasses)[i];
2829 ClassDeclaration *cbd = b->type->toBasetype()->isClassHandle();
2830 if (!cbd)
2831 continue;
2832 for (size_t j = 0; j < cbd->vtbl.length; j++)
2833 {
2834 FuncDeclaration *f2 = cbd->vtbl[j]->isFuncDeclaration();
2835 if (!f2 || f2->ident != funcdecl->ident)
2836 continue;
2837 if (cbd->parent && cbd->parent->isTemplateInstance())
2838 {
2839 if (!f2->functionSemantic())
2840 goto Ldone;
2841 }
2842 may_override = true;
2843 }
2844 }
2845 if (may_override && funcdecl->type->nextOf() == NULL)
2846 {
2847 /* If same name function exists in base class but 'this' is auto return,
2848 * cannot find index of base class's vtbl[] to override.
2849 */
2850 funcdecl->error("return type inference is not supported if may override base class function");
2851 }
2852
2853 /* Find index of existing function in base class's vtbl[] to override
2854 * (the index will be the same as in cd's current vtbl[])
2855 */
2856 int vi = cd->baseClass ? funcdecl->findVtblIndex((Dsymbols*)&cd->baseClass->vtbl, (int)cd->baseClass->vtbl.length)
2857 : -1;
2858
2859 bool doesoverride = false;
2860 switch (vi)
2861 {
2862 case -1:
2863 Lintro:
2864 /* Didn't find one, so
2865 * This is an 'introducing' function which gets a new
2866 * slot in the vtbl[].
2867 */
2868
2869 // Verify this doesn't override previous final function
2870 if (cd->baseClass)
2871 {
2872 Dsymbol *s = cd->baseClass->search(funcdecl->loc, funcdecl->ident);
2873 if (s)
2874 {
2875 FuncDeclaration *f2 = s->isFuncDeclaration();
2876 if (f2)
2877 {
2878 f2 = f2->overloadExactMatch(funcdecl->type);
2879 if (f2 && f2->isFinalFunc() && f2->prot().kind != Prot::private_)
2880 funcdecl->error("cannot override final function %s", f2->toPrettyChars());
2881 }
2882 }
2883 }
2884
2885 /* These quirky conditions mimic what VC++ appears to do
2886 */
2887 if (global.params.mscoff && cd->isCPPclass() &&
2888 cd->baseClass && cd->baseClass->vtbl.length)
2889 {
2890 /* if overriding an interface function, then this is not
2891 * introducing and don't put it in the class vtbl[]
2892 */
2893 funcdecl->interfaceVirtual = funcdecl->overrideInterface();
2894 if (funcdecl->interfaceVirtual)
2895 {
2896 //printf("\tinterface function %s\n", funcdecl->toChars());
2897 cd->vtblFinal.push(funcdecl);
2898 goto Linterfaces;
2899 }
2900 }
2901
2902 if (funcdecl->isFinalFunc())
2903 {
2904 // Don't check here, as it may override an interface function
2905 //if (funcdecl->isOverride())
2906 //funcdecl->error("is marked as override, but does not override any function");
2907 cd->vtblFinal.push(funcdecl);
2908 }
2909 else
2910 {
2911 //printf("\tintroducing function %s\n", funcdecl->toChars());
2912 funcdecl->introducing = 1;
2913 if (cd->isCPPclass() && target.cpp.reverseOverloads)
2914 {
2915 // with dmc, overloaded functions are grouped and in reverse order
2916 funcdecl->vtblIndex = (int)cd->vtbl.length;
2917 for (int i = 0; i < (int)cd->vtbl.length; i++)
2918 {
2919 if (cd->vtbl[i]->ident == funcdecl->ident && cd->vtbl[i]->parent == parent)
2920 {
2921 funcdecl->vtblIndex = (int)i;
2922 break;
2923 }
2924 }
2925 // shift all existing functions back
2926 for (int i = (int)cd->vtbl.length; i > funcdecl->vtblIndex; i--)
2927 {
2928 FuncDeclaration *fd = cd->vtbl[i-1]->isFuncDeclaration();
2929 assert(fd);
2930 fd->vtblIndex++;
2931 }
2932 cd->vtbl.insert(funcdecl->vtblIndex, funcdecl);
2933 }
2934 else
2935 {
2936 // Append to end of vtbl[]
2937 vi = (int)cd->vtbl.length;
2938 cd->vtbl.push(funcdecl);
2939 funcdecl->vtblIndex = vi;
2940 }
2941 }
2942 break;
2943
2944 case -2:
2945 // can't determine because of forward references
2946 funcdecl->errors = true;
2947 return;
2948
2949 default:
2950 {
2951 FuncDeclaration *fdv = cd->baseClass->vtbl[vi]->isFuncDeclaration();
2952 FuncDeclaration *fdc = cd->vtbl[vi]->isFuncDeclaration();
2953 // This function is covariant with fdv
2954
2955 if (fdc == funcdecl)
2956 {
2957 doesoverride = true;
2958 break;
2959 }
2960
2961 if (fdc->toParent() == parent)
2962 {
2963 //printf("vi = %d,\tthis = %p %s %s @ [%s]\n\tfdc = %p %s %s @ [%s]\n\tfdv = %p %s %s @ [%s]\n",
2964 // vi, funcdecl, funcdecl->toChars(), funcdecl->type->toChars(), funcdecl->loc.toChars(),
2965 // fdc, fdc ->toChars(), fdc ->type->toChars(), fdc ->loc.toChars(),
2966 // fdv, fdv ->toChars(), fdv ->type->toChars(), fdv ->loc.toChars());
2967
2968 // fdc overrides fdv exactly, then this introduces new function.
2969 if (fdc->type->mod == fdv->type->mod && funcdecl->type->mod != fdv->type->mod)
2970 goto Lintro;
2971 }
2972
2973 // This function overrides fdv
2974 if (fdv->isFinalFunc())
2975 funcdecl->error("cannot override final function %s", fdv->toPrettyChars());
2976
2977 if (!funcdecl->isOverride())
2978 {
2979 if (fdv->isFuture())
2980 {
2981 ::deprecation(funcdecl->loc, "@__future base class method %s is being overridden by %s; rename the latter",
2982 fdv->toPrettyChars(), funcdecl->toPrettyChars());
2983 // Treat 'this' as an introducing function, giving it a separate hierarchy in the vtbl[]
2984 goto Lintro;
2985 }
2986 else
2987 {
2988 int vi2 = funcdecl->findVtblIndex(&cd->baseClass->vtbl, (int)cd->baseClass->vtbl.length, false);
2989 if (vi2 < 0)
2990 // https://issues.dlang.org/show_bug.cgi?id=17349
2991 ::deprecation(funcdecl->loc, "cannot implicitly override base class method `%s` with `%s`; add `override` attribute",
2992 fdv->toPrettyChars(), funcdecl->toPrettyChars());
2993 else
2994 error(funcdecl->loc, "implicitly overriding base class method %s with %s deprecated; add `override` attribute",
2995 fdv->toPrettyChars(), funcdecl->toPrettyChars());
2996 }
2997 }
2998
2999 doesoverride = true;
3000 if (fdc->toParent() == parent)
3001 {
3002 // If both are mixins, or both are not, then error.
3003 // If either is not, the one that is not overrides the other.
3004 bool thismixin = funcdecl->parent->isClassDeclaration() != NULL;
3005 bool fdcmixin = fdc->parent->isClassDeclaration() != NULL;
3006 if (thismixin == fdcmixin)
3007 {
3008 funcdecl->error("multiple overrides of same function");
3009 }
3010 else if (!thismixin) // fdc overrides fdv
3011 {
3012 // this doesn't override any function
3013 break;
3014 }
3015 }
3016 cd->vtbl[vi] = funcdecl;
3017 funcdecl->vtblIndex = vi;
3018
3019 /* Remember which functions this overrides
3020 */
3021 funcdecl->foverrides.push(fdv);
3022
3023 /* This works by whenever this function is called,
3024 * it actually returns tintro, which gets dynamically
3025 * cast to type. But we know that tintro is a base
3026 * of type, so we could optimize it by not doing a
3027 * dynamic cast, but just subtracting the isBaseOf()
3028 * offset if the value is != null.
3029 */
3030
3031 if (fdv->tintro)
3032 funcdecl->tintro = fdv->tintro;
3033 else if (!funcdecl->type->equals(fdv->type))
3034 {
3035 /* Only need to have a tintro if the vptr
3036 * offsets differ
3037 */
3038 int offset;
3039 if (fdv->type->nextOf()->isBaseOf(funcdecl->type->nextOf(), &offset))
3040 {
3041 funcdecl->tintro = fdv->type;
3042 }
3043 }
3044 break;
3045 }
3046 }
3047
3048 /* Go through all the interface bases.
3049 * If this function is covariant with any members of those interface
3050 * functions, set the tintro.
3051 */
3052 Linterfaces:
3053 for (size_t i = 0; i < cd->interfaces.length; i++)
3054 {
3055 BaseClass *b = cd->interfaces.ptr[i];
3056 vi = funcdecl->findVtblIndex((Dsymbols *)&b->sym->vtbl, (int)b->sym->vtbl.length);
3057 switch (vi)
3058 {
3059 case -1:
3060 break;
3061
3062 case -2:
3063 // can't determine because of forward references
3064 funcdecl->errors = true;
3065 return;
3066
3067 default:
3068 {
3069 FuncDeclaration *fdv = (FuncDeclaration *)b->sym->vtbl[vi];
3070 Type *ti = NULL;
3071
3072 /* Remember which functions this overrides
3073 */
3074 funcdecl->foverrides.push(fdv);
3075
3076 /* Should we really require 'override' when implementing
3077 * an interface function?
3078 */
3079 //if (!funcdecl->isOverride())
3080 //warning(funcdecl->loc, "overrides base class function %s, but is not marked with `override`", fdv->toPrettyChars());
3081
3082 if (fdv->tintro)
3083 ti = fdv->tintro;
3084 else if (!funcdecl->type->equals(fdv->type))
3085 {
3086 /* Only need to have a tintro if the vptr
3087 * offsets differ
3088 */
3089 int offset;
3090 if (fdv->type->nextOf()->isBaseOf(funcdecl->type->nextOf(), &offset))
3091 {
3092 ti = fdv->type;
3093 }
3094 }
3095 if (ti)
3096 {
3097 if (funcdecl->tintro)
3098 {
3099 if (!funcdecl->tintro->nextOf()->equals(ti->nextOf()) &&
3100 !funcdecl->tintro->nextOf()->isBaseOf(ti->nextOf(), NULL) &&
3101 !ti->nextOf()->isBaseOf(funcdecl->tintro->nextOf(), NULL))
3102 {
3103 funcdecl->error("incompatible covariant types %s and %s", funcdecl->tintro->toChars(), ti->toChars());
3104 }
3105 }
3106 funcdecl->tintro = ti;
3107 }
3108 goto L2;
3109 }
3110 }
3111 }
3112
3113 if (!doesoverride && funcdecl->isOverride() && (funcdecl->type->nextOf() || !may_override))
3114 {
3115 BaseClass *bc = NULL;
3116 Dsymbol *s = NULL;
3117 for (size_t i = 0; i < cd->baseclasses->length; i++)
3118 {
3119 bc = (*cd->baseclasses)[i];
3120 s = bc->sym->search_correct(funcdecl->ident);
3121 if (s) break;
3122 }
3123
3124 if (s)
3125 funcdecl->error("does not override any function, did you mean to override `%s%s`?",
3126 bc->sym->isCPPclass() ? "extern (C++) " : "", s->toPrettyChars());
3127 else
3128 funcdecl->error("does not override any function");
3129 }
3130
3131 L2: ;
3132
3133 /* Go through all the interface bases.
3134 * Disallow overriding any final functions in the interface(s).
3135 */
3136 for (size_t i = 0; i < cd->interfaces.length; i++)
3137 {
3138 BaseClass *b = cd->interfaces.ptr[i];
3139 if (b->sym)
3140 {
3141 Dsymbol *s = search_function(b->sym, funcdecl->ident);
3142 if (s)
3143 {
3144 FuncDeclaration *f2 = s->isFuncDeclaration();
3145 if (f2)
3146 {
3147 f2 = f2->overloadExactMatch(funcdecl->type);
3148 if (f2 && f2->isFinalFunc() && f2->prot().kind != Prot::private_)
3149 funcdecl->error("cannot override final function %s.%s", b->sym->toChars(), f2->toPrettyChars());
3150 }
3151 }
3152 }
3153 }
3154
3155 if (funcdecl->isOverride())
3156 {
3157 if (funcdecl->storage_class & STCdisable)
3158 funcdecl->deprecation("overridden functions cannot be annotated @disable");
3159 if (funcdecl->isDeprecated())
3160 funcdecl->deprecation("deprecated functions cannot be annotated @disable");
3161 }
3162 }
3163 else if (funcdecl->isOverride() && !parent->isTemplateInstance())
3164 funcdecl->error("override only applies to class member functions");
3165
3166 // Reflect this->type to f because it could be changed by findVtblIndex
3167 f = funcdecl->type->toTypeFunction();
3168
3169 Ldone:
3170 /* Contracts can only appear without a body when they are virtual interface functions
3171 */
3172 if (!funcdecl->fbody && !allowsContractWithoutBody(funcdecl))
3173 funcdecl->error("in and out contracts can only appear without a body when they are virtual interface functions or abstract");
3174
3175 /* Do not allow template instances to add virtual functions
3176 * to a class.
3177 */
3178 if (funcdecl->isVirtual())
3179 {
3180 TemplateInstance *ti = parent->isTemplateInstance();
3181 if (ti)
3182 {
3183 // Take care of nested templates
3184 while (1)
3185 {
3186 TemplateInstance *ti2 = ti->tempdecl->parent->isTemplateInstance();
3187 if (!ti2)
3188 break;
3189 ti = ti2;
3190 }
3191
3192 // If it's a member template
3193 ClassDeclaration *cd = ti->tempdecl->isClassMember();
3194 if (cd)
3195 {
3196 funcdecl->error("cannot use template to add virtual function to class `%s`", cd->toChars());
3197 }
3198 }
3199 }
3200
3201 if (funcdecl->isMain())
3202 funcdecl->checkDmain(); // Check main() parameters and return type
3203
3204 /* Purity and safety can be inferred for some functions by examining
3205 * the function body.
3206 */
3207 if (canInferAttributes(funcdecl, sc))
3208 initInferAttributes(funcdecl);
3209
3210 Module::dprogress++;
3211 funcdecl->semanticRun = PASSsemanticdone;
3212
3213 /* Save scope for possible later use (if we need the
3214 * function internals)
3215 */
3216 funcdecl->_scope = sc->copy();
3217 funcdecl->_scope->setNoFree();
3218
3219 static bool printedMain = false; // semantic might run more than once
3220 if (global.params.verbose && !printedMain)
3221 {
3222 const char *type = funcdecl->isMain() ? "main" : funcdecl->isWinMain() ? "winmain" : funcdecl->isDllMain() ? "dllmain" : (const char *)NULL;
3223 Module *mod = sc->_module;
3224
3225 if (type && mod)
3226 {
3227 printedMain = true;
3228 const char *name = mod->srcfile->toChars();
3229 const char *path = FileName::searchPath(global.path, name, true);
3230 message("entry %-10s\t%s", type, path ? path : name);
3231 }
3232 }
3233
3234 if (funcdecl->fbody && funcdecl->isMain() && sc->_module->isRoot())
3235 Compiler::genCmain(sc);
3236
3237 assert(funcdecl->type->ty != Terror || funcdecl->errors);
3238
3239 // semantic for parameters' UDAs
3240 const size_t nparams = f->parameterList.length();
3241 for (size_t i = 0; i < nparams; i++)
3242 {
3243 Parameter *param = f->parameterList[i];
3244 if (param && param->userAttribDecl)
3245 dsymbolSemantic(param->userAttribDecl, sc);
3246 }
3247 }
3248
3249 // Do the semantic analysis on the external interface to the function.
3250 void visit(FuncDeclaration *funcdecl)
3251 {
3252 funcDeclarationSemantic(funcdecl);
3253 }
3254
3255 void visit(CtorDeclaration *ctd)
3256 {
3257 //printf("CtorDeclaration::semantic() %s\n", ctd->toChars());
3258 if (ctd->semanticRun >= PASSsemanticdone)
3259 return;
3260 if (ctd->_scope)
3261 {
3262 sc = ctd->_scope;
3263 ctd->_scope = NULL;
3264 }
3265
3266 ctd->parent = sc->parent;
3267 Dsymbol *p = ctd->toParent2();
3268 AggregateDeclaration *ad = p->isAggregateDeclaration();
3269 if (!ad)
3270 {
3271 error(ctd->loc, "constructor can only be a member of aggregate, not %s %s",
3272 p->kind(), p->toChars());
3273 ctd->type = Type::terror;
3274 ctd->errors = true;
3275 return;
3276 }
3277
3278 sc = sc->push();
3279 sc->stc &= ~STCstatic; // not a static constructor
3280 sc->flags |= SCOPEctor;
3281
3282 funcDeclarationSemantic(ctd);
3283
3284 sc->pop();
3285
3286 if (ctd->errors)
3287 return;
3288
3289 TypeFunction *tf = ctd->type->toTypeFunction();
3290
3291 /* See if it's the default constructor
3292 * But, template constructor should not become a default constructor.
3293 */
3294 if (ad && (!ctd->parent->isTemplateInstance() || ctd->parent->isTemplateMixin()))
3295 {
3296 const size_t dim = tf->parameterList.length();
3297
3298 if (StructDeclaration *sd = ad->isStructDeclaration())
3299 {
3300 if (dim == 0 && tf->parameterList.varargs == VARARGnone) // empty default ctor w/o any varargs
3301 {
3302 if (ctd->fbody || !(ctd->storage_class & STCdisable) || dim)
3303 {
3304 ctd->error("default constructor for structs only allowed "
3305 "with @disable, no body, and no parameters");
3306 ctd->storage_class |= STCdisable;
3307 ctd->fbody = NULL;
3308 }
3309 sd->noDefaultCtor = true;
3310 }
3311 else if (dim == 0 && tf->parameterList.varargs) // allow varargs only ctor
3312 {
3313 }
3314 else if (dim && tf->parameterList[0]->defaultArg)
3315 {
3316 // if the first parameter has a default argument, then the rest does as well
3317 if (ctd->storage_class & STCdisable)
3318 {
3319 ctd->deprecation("@disable'd constructor cannot have default "
3320 "arguments for all parameters.");
3321 deprecationSupplemental(ctd->loc, "Use @disable this(); if you want to disable default initialization.");
3322 }
3323 else
3324 ctd->deprecation("all parameters have default arguments, "
3325 "but structs cannot have default constructors.");
3326 }
3327
3328 }
3329 else if (dim == 0 && tf->parameterList.varargs == VARARGnone)
3330 {
3331 ad->defaultCtor = ctd;
3332 }
3333 }
3334 }
3335
3336 void visit(PostBlitDeclaration *pbd)
3337 {
3338 //printf("PostBlitDeclaration::semantic() %s\n", pbd->toChars());
3339 //printf("ident: %s, %s, %p, %p\n", pbd->ident->toChars(), Id::dtor->toChars(), pbd->ident, Id::dtor);
3340 //printf("stc = x%llx\n", sc->stc);
3341 if (pbd->semanticRun >= PASSsemanticdone)
3342 return;
3343 if (pbd->_scope)
3344 {
3345 sc = pbd->_scope;
3346 pbd->_scope = NULL;
3347 }
3348
3349 pbd->parent = sc->parent;
3350 Dsymbol *p = pbd->toParent2();
3351 StructDeclaration *ad = p->isStructDeclaration();
3352 if (!ad)
3353 {
3354 error(pbd->loc, "postblit can only be a member of struct/union, not %s %s",
3355 p->kind(), p->toChars());
3356 pbd->type = Type::terror;
3357 pbd->errors = true;
3358 return;
3359 }
3360 if (pbd->ident == Id::postblit && pbd->semanticRun < PASSsemantic)
3361 ad->postblits.push(pbd);
3362 if (!pbd->type)
3363 pbd->type = new TypeFunction(ParameterList(), Type::tvoid, LINKd, pbd->storage_class);
3364
3365 sc = sc->push();
3366 sc->stc &= ~STCstatic; // not static
3367 sc->linkage = LINKd;
3368
3369 funcDeclarationSemantic(pbd);
3370
3371 sc->pop();
3372 }
3373
3374 void visit(DtorDeclaration *dd)
3375 {
3376 //printf("DtorDeclaration::semantic() %s\n", dd->toChars());
3377 //printf("ident: %s, %s, %p, %p\n", dd->ident->toChars(), Id::dtor->toChars(), dd->ident, Id::dtor);
3378 if (dd->semanticRun >= PASSsemanticdone)
3379 return;
3380 if (dd->_scope)
3381 {
3382 sc = dd->_scope;
3383 dd->_scope = NULL;
3384 }
3385
3386 dd->parent = sc->parent;
3387 Dsymbol *p = dd->toParent2();
3388 AggregateDeclaration *ad = p->isAggregateDeclaration();
3389 if (!ad)
3390 {
3391 error(dd->loc, "destructor can only be a member of aggregate, not %s %s",
3392 p->kind(), p->toChars());
3393 dd->type = Type::terror;
3394 dd->errors = true;
3395 return;
3396 }
3397 if (dd->ident == Id::dtor && dd->semanticRun < PASSsemantic)
3398 ad->dtors.push(dd);
3399 if (!dd->type)
3400 dd->type = new TypeFunction(ParameterList(), Type::tvoid, LINKd, dd->storage_class);
3401
3402 sc = sc->push();
3403 sc->stc &= ~STCstatic; // not a static destructor
3404 if (sc->linkage != LINKcpp)
3405 sc->linkage = LINKd;
3406
3407 funcDeclarationSemantic(dd);
3408
3409 sc->pop();
3410 }
3411
3412 void visit(StaticCtorDeclaration *scd)
3413 {
3414 //printf("StaticCtorDeclaration::semantic()\n");
3415 if (scd->semanticRun >= PASSsemanticdone)
3416 return;
3417 if (scd->_scope)
3418 {
3419 sc = scd->_scope;
3420 scd->_scope = NULL;
3421 }
3422
3423 scd->parent = sc->parent;
3424 Dsymbol *p = scd->parent->pastMixin();
3425 if (!p->isScopeDsymbol())
3426 {
3427 const char *s = (scd->isSharedStaticCtorDeclaration() ? "shared " : "");
3428 error(scd->loc, "%sstatic constructor can only be member of module/aggregate/template, not %s %s",
3429 s, p->kind(), p->toChars());
3430 scd->type = Type::terror;
3431 scd->errors = true;
3432 return;
3433 }
3434 if (!scd->type)
3435 scd->type = new TypeFunction(ParameterList(), Type::tvoid, LINKd, scd->storage_class);
3436
3437 /* If the static ctor appears within a template instantiation,
3438 * it could get called multiple times by the module constructors
3439 * for different modules. Thus, protect it with a gate.
3440 */
3441 if (scd->isInstantiated() && scd->semanticRun < PASSsemantic)
3442 {
3443 /* Add this prefix to the function:
3444 * static int gate;
3445 * if (++gate != 1) return;
3446 * Note that this is not thread safe; should not have threads
3447 * during static construction.
3448 */
3449 VarDeclaration *v = new VarDeclaration(Loc(), Type::tint32, Id::gate, NULL);
3450 v->storage_class = STCtemp | (scd->isSharedStaticCtorDeclaration() ? STCstatic : STCtls);
3451 Statements *sa = new Statements();
3452 Statement *s = new ExpStatement(Loc(), v);
3453 sa->push(s);
3454 Expression *e = new IdentifierExp(Loc(), v->ident);
3455 e = new AddAssignExp(Loc(), e, new IntegerExp(1));
3456 e = new EqualExp(TOKnotequal, Loc(), e, new IntegerExp(1));
3457 s = new IfStatement(Loc(), NULL, e, new ReturnStatement(Loc(), NULL), NULL, Loc());
3458 sa->push(s);
3459 if (scd->fbody)
3460 sa->push(scd->fbody);
3461 scd->fbody = new CompoundStatement(Loc(), sa);
3462 }
3463
3464 funcDeclarationSemantic(scd);
3465
3466 // We're going to need ModuleInfo
3467 Module *m = scd->getModule();
3468 if (!m)
3469 m = sc->_module;
3470 if (m)
3471 {
3472 m->needmoduleinfo = 1;
3473 //printf("module1 %s needs moduleinfo\n", m->toChars());
3474 }
3475 }
3476
3477 void visit(StaticDtorDeclaration *sdd)
3478 {
3479 if (sdd->semanticRun >= PASSsemanticdone)
3480 return;
3481 if (sdd->_scope)
3482 {
3483 sc = sdd->_scope;
3484 sdd->_scope = NULL;
3485 }
3486
3487 sdd->parent = sc->parent;
3488 Dsymbol *p = sdd->parent->pastMixin();
3489 if (!p->isScopeDsymbol())
3490 {
3491 const char *s = (sdd->isSharedStaticDtorDeclaration() ? "shared " : "");
3492 error(sdd->loc, "%sstatic destructor can only be member of module/aggregate/template, not %s %s",
3493 s, p->kind(), p->toChars());
3494 sdd->type = Type::terror;
3495 sdd->errors = true;
3496 return;
3497 }
3498 if (!sdd->type)
3499 sdd->type = new TypeFunction(ParameterList(), Type::tvoid, LINKd, sdd->storage_class);
3500
3501 /* If the static ctor appears within a template instantiation,
3502 * it could get called multiple times by the module constructors
3503 * for different modules. Thus, protect it with a gate.
3504 */
3505 if (sdd->isInstantiated() && sdd->semanticRun < PASSsemantic)
3506 {
3507 /* Add this prefix to the function:
3508 * static int gate;
3509 * if (--gate != 0) return;
3510 * Increment gate during constructor execution.
3511 * Note that this is not thread safe; should not have threads
3512 * during static destruction.
3513 */
3514 VarDeclaration *v = new VarDeclaration(Loc(), Type::tint32, Id::gate, NULL);
3515 v->storage_class = STCtemp | (sdd->isSharedStaticDtorDeclaration() ? STCstatic : STCtls);
3516 Statements *sa = new Statements();
3517 Statement *s = new ExpStatement(Loc(), v);
3518 sa->push(s);
3519 Expression *e = new IdentifierExp(Loc(), v->ident);
3520 e = new AddAssignExp(Loc(), e, new IntegerExp(-1));
3521 e = new EqualExp(TOKnotequal, Loc(), e, new IntegerExp(0));
3522 s = new IfStatement(Loc(), NULL, e, new ReturnStatement(Loc(), NULL), NULL, Loc());
3523 sa->push(s);
3524 if (sdd->fbody)
3525 sa->push(sdd->fbody);
3526 sdd->fbody = new CompoundStatement(Loc(), sa);
3527 sdd->vgate = v;
3528 }
3529
3530 funcDeclarationSemantic(sdd);
3531
3532 // We're going to need ModuleInfo
3533 Module *m = sdd->getModule();
3534 if (!m)
3535 m = sc->_module;
3536 if (m)
3537 {
3538 m->needmoduleinfo = 1;
3539 //printf("module2 %s needs moduleinfo\n", m->toChars());
3540 }
3541 }
3542
3543 void visit(InvariantDeclaration *invd)
3544 {
3545 if (invd->semanticRun >= PASSsemanticdone)
3546 return;
3547 if (invd->_scope)
3548 {
3549 sc = invd->_scope;
3550 invd->_scope = NULL;
3551 }
3552
3553 invd->parent = sc->parent;
3554 Dsymbol *p = invd->parent->pastMixin();
3555 AggregateDeclaration *ad = p->isAggregateDeclaration();
3556 if (!ad)
3557 {
3558 error(invd->loc, "invariant can only be a member of aggregate, not %s %s",
3559 p->kind(), p->toChars());
3560 invd->type = Type::terror;
3561 invd->errors = true;
3562 return;
3563 }
3564 if (invd->ident != Id::classInvariant &&
3565 invd->semanticRun < PASSsemantic &&
3566 !ad->isUnionDeclaration() // users are on their own with union fields
3567 )
3568 ad->invs.push(invd);
3569 if (!invd->type)
3570 invd->type = new TypeFunction(ParameterList(), Type::tvoid, LINKd, invd->storage_class);
3571
3572 sc = sc->push();
3573 sc->stc &= ~STCstatic; // not a static invariant
3574 sc->stc |= STCconst; // invariant() is always const
3575 sc->flags = (sc->flags & ~SCOPEcontract) | SCOPEinvariant;
3576 sc->linkage = LINKd;
3577
3578 funcDeclarationSemantic(invd);
3579
3580 sc->pop();
3581 }
3582
3583 void visit(UnitTestDeclaration *utd)
3584 {
3585 if (utd->semanticRun >= PASSsemanticdone)
3586 return;
3587 if (utd->_scope)
3588 {
3589 sc = utd->_scope;
3590 utd->_scope = NULL;
3591 }
3592
3593 utd->protection = sc->protection;
3594
3595 utd->parent = sc->parent;
3596 Dsymbol *p = utd->parent->pastMixin();
3597 if (!p->isScopeDsymbol())
3598 {
3599 error(utd->loc, "unittest can only be a member of module/aggregate/template, not %s %s",
3600 p->kind(), p->toChars());
3601 utd->type = Type::terror;
3602 utd->errors = true;
3603 return;
3604 }
3605
3606 if (global.params.useUnitTests)
3607 {
3608 if (!utd->type)
3609 utd->type = new TypeFunction(ParameterList(), Type::tvoid, LINKd, utd->storage_class);
3610 Scope *sc2 = sc->push();
3611 sc2->linkage = LINKd;
3612 funcDeclarationSemantic(utd);
3613 sc2->pop();
3614 }
3615 }
3616
3617 void visit(NewDeclaration *nd)
3618 {
3619 //printf("NewDeclaration::semantic()\n");
3620 if (nd->semanticRun >= PASSsemanticdone)
3621 return;
3622 if (nd->_scope)
3623 {
3624 sc = nd->_scope;
3625 nd->_scope = NULL;
3626 }
3627
3628 nd->parent = sc->parent;
3629 Dsymbol *p = nd->parent->pastMixin();
3630 if (!p->isAggregateDeclaration())
3631 {
3632 error(nd->loc, "allocator can only be a member of aggregate, not %s %s",
3633 p->kind(), p->toChars());
3634 nd->type = Type::terror;
3635 nd->errors = true;
3636 return;
3637 }
3638 Type *tret = Type::tvoid->pointerTo();
3639 if (!nd->type)
3640 nd->type = new TypeFunction(ParameterList(nd->parameters, nd->varargs), tret, LINKd, nd->storage_class);
3641
3642 nd->type = typeSemantic(nd->type, nd->loc, sc);
3643
3644 // Check that there is at least one argument of type size_t
3645 TypeFunction *tf = nd->type->toTypeFunction();
3646 if (tf->parameterList.length() < 1)
3647 {
3648 nd->error("at least one argument of type size_t expected");
3649 }
3650 else
3651 {
3652 Parameter *fparam = tf->parameterList[0];
3653 if (!fparam->type->equals(Type::tsize_t))
3654 nd->error("first argument must be type size_t, not %s", fparam->type->toChars());
3655 }
3656
3657 funcDeclarationSemantic(nd);
3658 }
3659
3660 void visit(DeleteDeclaration *deld)
3661 {
3662 //printf("DeleteDeclaration::semantic()\n");
3663 if (deld->semanticRun >= PASSsemanticdone)
3664 return;
3665 if (deld->_scope)
3666 {
3667 sc = deld->_scope;
3668 deld->_scope = NULL;
3669 }
3670
3671 deld->parent = sc->parent;
3672 Dsymbol *p = deld->parent->pastMixin();
3673 if (!p->isAggregateDeclaration())
3674 {
3675 error(deld->loc, "deallocator can only be a member of aggregate, not %s %s",
3676 p->kind(), p->toChars());
3677 deld->type = Type::terror;
3678 deld->errors = true;
3679 return;
3680 }
3681 if (!deld->type)
3682 deld->type = new TypeFunction(ParameterList(deld->parameters), Type::tvoid, LINKd, deld->storage_class);
3683
3684 deld->type = typeSemantic(deld->type, deld->loc, sc);
3685
3686 // Check that there is only one argument of type void*
3687 TypeFunction *tf = deld->type->toTypeFunction();
3688 if (tf->parameterList.length() != 1)
3689 {
3690 deld->error("one argument of type void* expected");
3691 }
3692 else
3693 {
3694 Parameter *fparam = tf->parameterList[0];
3695 if (!fparam->type->equals(Type::tvoid->pointerTo()))
3696 deld->error("one argument of type void* expected, not %s", fparam->type->toChars());
3697 }
3698
3699 funcDeclarationSemantic(deld);
3700 }
3701
3702 void visit(StructDeclaration *sd)
3703 {
3704 //printf("StructDeclaration::semantic(this=%p, %s '%s', sizeok = %d)\n", sd, sd->parent->toChars(), sd->toChars(), sizeok);
3705
3706 //static int count; if (++count == 20) halt();
3707
3708 if (sd->semanticRun >= PASSsemanticdone)
3709 return;
3710 unsigned errors = global.errors;
3711
3712 //printf("+StructDeclaration::semantic(this=%p, %s '%s', sizeok = %d)\n", sd, sd->parent->toChars(), sd->toChars(), sizeok);
3713 Scope *scx = NULL;
3714 if (sd->_scope)
3715 {
3716 sc = sd->_scope;
3717 scx = sd->_scope; // save so we don't make redundant copies
3718 sd->_scope = NULL;
3719 }
3720
3721 if (!sd->parent)
3722 {
3723 assert(sc->parent && sc->func);
3724 sd->parent = sc->parent;
3725 }
3726 assert(sd->parent && !sd->isAnonymous());
3727
3728 if (sd->errors)
3729 sd->type = Type::terror;
3730 if (sd->semanticRun == PASSinit)
3731 sd->type = sd->type->addSTC(sc->stc | sd->storage_class);
3732 sd->type = typeSemantic(sd->type, sd->loc, sc);
3733
3734 if (sd->type->ty == Tstruct && ((TypeStruct *)sd->type)->sym != sd)
3735 {
3736 TemplateInstance *ti = ((TypeStruct *)sd->type)->sym->isInstantiated();
3737 if (ti && isError(ti))
3738 ((TypeStruct *)sd->type)->sym = sd;
3739 }
3740
3741 // Ungag errors when not speculative
3742 Ungag ungag = sd->ungagSpeculative();
3743
3744 if (sd->semanticRun == PASSinit)
3745 {
3746 sd->protection = sc->protection;
3747
3748 sd->alignment = sc->alignment();
3749
3750 sd->storage_class |= sc->stc;
3751 if (sd->storage_class & STCdeprecated)
3752 sd->isdeprecated = true;
3753 if (sd->storage_class & STCabstract)
3754 sd->error("structs, unions cannot be abstract");
3755 sd->userAttribDecl = sc->userAttribDecl;
3756
3757 if (sc->linkage == LINKcpp)
3758 sd->classKind = ClassKind::cpp;
3759 }
3760 else if (sd->symtab && !scx)
3761 {
3762 return;
3763 }
3764 sd->semanticRun = PASSsemantic;
3765
3766 if (!sd->members) // if opaque declaration
3767 {
3768 sd->semanticRun = PASSsemanticdone;
3769 return;
3770 }
3771 if (!sd->symtab)
3772 {
3773 sd->symtab = new DsymbolTable();
3774
3775 for (size_t i = 0; i < sd->members->length; i++)
3776 {
3777 Dsymbol *s = (*sd->members)[i];
3778 //printf("adding member '%s' to '%s'\n", s->toChars(), sd->toChars());
3779 s->addMember(sc, sd);
3780 }
3781 }
3782
3783 Scope *sc2 = sd->newScope(sc);
3784
3785 /* Set scope so if there are forward references, we still might be able to
3786 * resolve individual members like enums.
3787 */
3788 for (size_t i = 0; i < sd->members->length; i++)
3789 {
3790 Dsymbol *s = (*sd->members)[i];
3791 //printf("struct: setScope %s %s\n", s->kind(), s->toChars());
3792 s->setScope(sc2);
3793 }
3794
3795 for (size_t i = 0; i < sd->members->length; i++)
3796 {
3797 Dsymbol *s = (*sd->members)[i];
3798 s->importAll(sc2);
3799 }
3800
3801 for (size_t i = 0; i < sd->members->length; i++)
3802 {
3803 Dsymbol *s = (*sd->members)[i];
3804 dsymbolSemantic(s, sc2);
3805 }
3806
3807 if (!sd->determineFields())
3808 {
3809 assert(sd->type->ty == Terror);
3810 sc2->pop();
3811 sd->semanticRun = PASSsemanticdone;
3812 return;
3813 }
3814
3815 /* Following special member functions creation needs semantic analysis
3816 * completion of sub-structs in each field types. For example, buildDtor
3817 * needs to check existence of elaborate dtor in type of each fields.
3818 * See the case in compilable/test14838.d
3819 */
3820 for (size_t i = 0; i < sd->fields.length; i++)
3821 {
3822 VarDeclaration *v = sd->fields[i];
3823 Type *tb = v->type->baseElemOf();
3824 if (tb->ty != Tstruct)
3825 continue;
3826 StructDeclaration *sdec = ((TypeStruct *)tb)->sym;
3827 if (sdec->semanticRun >= PASSsemanticdone)
3828 continue;
3829
3830 sc2->pop();
3831
3832 sd->_scope = scx ? scx : sc->copy();
3833 sd->_scope->setNoFree();
3834 sd->_scope->_module->addDeferredSemantic(sd);
3835
3836 //printf("\tdeferring %s\n", sd->toChars());
3837 return;
3838 }
3839
3840 /* Look for special member functions.
3841 */
3842 sd->aggNew = (NewDeclaration *)sd->search(Loc(), Id::classNew);
3843 sd->aggDelete = (DeleteDeclaration *)sd->search(Loc(), Id::classDelete);
3844
3845 // Look for the constructor
3846 sd->ctor = sd->searchCtor();
3847
3848 sd->dtor = buildDtor(sd, sc2);
3849 sd->postblit = buildPostBlit(sd, sc2);
3850
3851 buildOpAssign(sd, sc2);
3852 buildOpEquals(sd, sc2);
3853
3854 if (global.params.useTypeInfo && Type::dtypeinfo) // these functions are used for TypeInfo
3855 {
3856 sd->xeq = buildXopEquals(sd, sc2);
3857 sd->xcmp = buildXopCmp(sd, sc2);
3858 sd->xhash = buildXtoHash(sd, sc2);
3859 }
3860
3861 sd->inv = buildInv(sd, sc2);
3862
3863 Module::dprogress++;
3864 sd->semanticRun = PASSsemanticdone;
3865 //printf("-StructDeclaration::semantic(this=%p, '%s')\n", sd, sd->toChars());
3866
3867 sc2->pop();
3868
3869 if (sd->ctor)
3870 {
3871 Dsymbol *scall = sd->search(Loc(), Id::call);
3872 if (scall)
3873 {
3874 unsigned xerrors = global.startGagging();
3875 sc = sc->push();
3876 sc->tinst = NULL;
3877 sc->minst = NULL;
3878 FuncDeclaration *fcall = resolveFuncCall(sd->loc, sc, scall, NULL, NULL, NULL, 1);
3879 sc = sc->pop();
3880 global.endGagging(xerrors);
3881
3882 if (fcall && fcall->isStatic())
3883 {
3884 sd->error(fcall->loc, "`static opCall` is hidden by constructors and can never be called");
3885 errorSupplemental(fcall->loc, "Please use a factory method instead, or replace all constructors with `static opCall`.");
3886 }
3887 }
3888 }
3889
3890 if (sd->type->ty == Tstruct && ((TypeStruct *)sd->type)->sym != sd)
3891 {
3892 // https://issues.dlang.org/show_bug.cgi?id=19024
3893 StructDeclaration *sym = ((TypeStruct *)sd->type)->sym;
3894 sd->error("already exists at %s. Perhaps in another function with the same name?", sym->loc.toChars());
3895 }
3896
3897 if (global.errors != errors)
3898 {
3899 // The type is no good.
3900 sd->type = Type::terror;
3901 sd->errors = true;
3902 if (sd->deferred)
3903 sd->deferred->errors = true;
3904 }
3905
3906 if (sd->deferred && !global.gag)
3907 {
3908 semantic2(sd->deferred, sc);
3909 semantic3(sd->deferred, sc);
3910 }
3911 }
3912
3913 void interfaceSemantic(ClassDeclaration *cd)
3914 {
3915 cd->vtblInterfaces = new BaseClasses();
3916 cd->vtblInterfaces->reserve(cd->interfaces.length);
3917
3918 for (size_t i = 0; i < cd->interfaces.length; i++)
3919 {
3920 BaseClass *b = cd->interfaces.ptr[i];
3921 cd->vtblInterfaces->push(b);
3922 b->copyBaseInterfaces(cd->vtblInterfaces);
3923 }
3924 }
3925
3926 void visit(ClassDeclaration *cldec)
3927 {
3928 //printf("ClassDeclaration::semantic(%s), type = %p, sizeok = %d, this = %p\n", cldec->toChars(), cldec->type, sizeok, cldec);
3929 //printf("\tparent = %p, '%s'\n", sc->parent, sc->parent ? sc->parent->toChars() : "");
3930 //printf("sc->stc = %x\n", sc->stc);
3931
3932 //{ static int n; if (++n == 20) *(char*)0=0; }
3933
3934 if (cldec->semanticRun >= PASSsemanticdone)
3935 return;
3936 unsigned errors = global.errors;
3937
3938 //printf("+ClassDeclaration::semantic(%s), type = %p, sizeok = %d, this = %p\n", cldec->toChars(), cldec->type, sizeok, cldec);
3939
3940 Scope *scx = NULL;
3941 if (cldec->_scope)
3942 {
3943 sc = cldec->_scope;
3944 scx = cldec->_scope; // save so we don't make redundant copies
3945 cldec->_scope = NULL;
3946 }
3947
3948 if (!cldec->parent)
3949 {
3950 assert(sc->parent);
3951 cldec->parent = sc->parent;
3952 }
3953
3954 if (cldec->errors)
3955 cldec->type = Type::terror;
3956 cldec->type = typeSemantic(cldec->type, cldec->loc, sc);
3957
3958 if (cldec->type->ty == Tclass && ((TypeClass *)cldec->type)->sym != cldec)
3959 {
3960 TemplateInstance *ti = ((TypeClass *)cldec->type)->sym->isInstantiated();
3961 if (ti && isError(ti))
3962 ((TypeClass *)cldec->type)->sym = cldec;
3963 }
3964
3965 // Ungag errors when not speculative
3966 Ungag ungag = cldec->ungagSpeculative();
3967
3968 if (cldec->semanticRun == PASSinit)
3969 {
3970 cldec->protection = sc->protection;
3971
3972 cldec->storage_class |= sc->stc;
3973 if (cldec->storage_class & STCdeprecated)
3974 cldec->isdeprecated = true;
3975 if (cldec->storage_class & STCauto)
3976 cldec->error("storage class `auto` is invalid when declaring a class, did you mean to use `scope`?");
3977 if (cldec->storage_class & STCscope)
3978 cldec->isscope = true;
3979 if (cldec->storage_class & STCabstract)
3980 cldec->isabstract = ABSyes;
3981
3982 cldec->userAttribDecl = sc->userAttribDecl;
3983
3984 if (sc->linkage == LINKcpp)
3985 cldec->classKind = ClassKind::cpp;
3986 if (sc->linkage == LINKobjc)
3987 objc()->setObjc(cldec);
3988 }
3989 else if (cldec->symtab && !scx)
3990 {
3991 return;
3992 }
3993 cldec->semanticRun = PASSsemantic;
3994
3995 if (cldec->baseok < BASEOKdone)
3996 {
3997 cldec->baseok = BASEOKin;
3998
3999 // Expand any tuples in baseclasses[]
4000 for (size_t i = 0; i < cldec->baseclasses->length; )
4001 {
4002 BaseClass *b = (*cldec->baseclasses)[i];
4003 b->type = resolveBase(cldec, sc, scx, b->type);
4004
4005 Type *tb = b->type->toBasetype();
4006 if (tb->ty == Ttuple)
4007 {
4008 TypeTuple *tup = (TypeTuple *)tb;
4009 cldec->baseclasses->remove(i);
4010 size_t dim = Parameter::dim(tup->arguments);
4011 for (size_t j = 0; j < dim; j++)
4012 {
4013 Parameter *arg = Parameter::getNth(tup->arguments, j);
4014 b = new BaseClass(arg->type);
4015 cldec->baseclasses->insert(i + j, b);
4016 }
4017 }
4018 else
4019 i++;
4020 }
4021
4022 if (cldec->baseok >= BASEOKdone)
4023 {
4024 //printf("%s already semantic analyzed, semanticRun = %d\n", cldec->toChars(), cldec->semanticRun);
4025 if (cldec->semanticRun >= PASSsemanticdone)
4026 return;
4027 goto Lancestorsdone;
4028 }
4029
4030 // See if there's a base class as first in baseclasses[]
4031 if (cldec->baseclasses->length)
4032 {
4033 BaseClass *b = (*cldec->baseclasses)[0];
4034 Type *tb = b->type->toBasetype();
4035 TypeClass *tc = (tb->ty == Tclass) ? (TypeClass *)tb : NULL;
4036 if (!tc)
4037 {
4038 if (b->type != Type::terror)
4039 cldec->error("base type must be class or interface, not %s", b->type->toChars());
4040 cldec->baseclasses->remove(0);
4041 goto L7;
4042 }
4043
4044 if (tc->sym->isDeprecated())
4045 {
4046 if (!cldec->isDeprecated())
4047 {
4048 // Deriving from deprecated class makes this one deprecated too
4049 cldec->isdeprecated = true;
4050
4051 tc->checkDeprecated(cldec->loc, sc);
4052 }
4053 }
4054
4055 if (tc->sym->isInterfaceDeclaration())
4056 goto L7;
4057
4058 for (ClassDeclaration *cdb = tc->sym; cdb; cdb = cdb->baseClass)
4059 {
4060 if (cdb == cldec)
4061 {
4062 cldec->error("circular inheritance");
4063 cldec->baseclasses->remove(0);
4064 goto L7;
4065 }
4066 }
4067
4068 /* Bugzilla 11034: Essentially, class inheritance hierarchy
4069 * and instance size of each classes are orthogonal information.
4070 * Therefore, even if tc->sym->sizeof == SIZEOKnone,
4071 * we need to set baseClass field for class covariance check.
4072 */
4073 cldec->baseClass = tc->sym;
4074 b->sym = cldec->baseClass;
4075
4076 if (tc->sym->baseok < BASEOKdone)
4077 resolveBase(cldec, sc, scx, tc->sym); // Try to resolve forward reference
4078 if (tc->sym->baseok < BASEOKdone)
4079 {
4080 //printf("\ttry later, forward reference of base class %s\n", tc->sym->toChars());
4081 if (tc->sym->_scope)
4082 tc->sym->_scope->_module->addDeferredSemantic(tc->sym);
4083 cldec->baseok = BASEOKnone;
4084 }
4085 L7: ;
4086 }
4087
4088 // Treat the remaining entries in baseclasses as interfaces
4089 // Check for errors, handle forward references
4090 for (size_t i = (cldec->baseClass ? 1 : 0); i < cldec->baseclasses->length; )
4091 {
4092 BaseClass *b = (*cldec->baseclasses)[i];
4093 Type *tb = b->type->toBasetype();
4094 TypeClass *tc = (tb->ty == Tclass) ? (TypeClass *)tb : NULL;
4095 if (!tc || !tc->sym->isInterfaceDeclaration())
4096 {
4097 if (b->type != Type::terror)
4098 cldec->error("base type must be interface, not %s", b->type->toChars());
4099 cldec->baseclasses->remove(i);
4100 continue;
4101 }
4102
4103 // Check for duplicate interfaces
4104 for (size_t j = (cldec->baseClass ? 1 : 0); j < i; j++)
4105 {
4106 BaseClass *b2 = (*cldec->baseclasses)[j];
4107 if (b2->sym == tc->sym)
4108 {
4109 cldec->error("inherits from duplicate interface %s", b2->sym->toChars());
4110 cldec->baseclasses->remove(i);
4111 continue;
4112 }
4113 }
4114
4115 if (tc->sym->isDeprecated())
4116 {
4117 if (!cldec->isDeprecated())
4118 {
4119 // Deriving from deprecated class makes this one deprecated too
4120 cldec->isdeprecated = true;
4121
4122 tc->checkDeprecated(cldec->loc, sc);
4123 }
4124 }
4125
4126 b->sym = tc->sym;
4127
4128 if (tc->sym->baseok < BASEOKdone)
4129 resolveBase(cldec, sc, scx, tc->sym); // Try to resolve forward reference
4130 if (tc->sym->baseok < BASEOKdone)
4131 {
4132 //printf("\ttry later, forward reference of base %s\n", tc->sym->toChars());
4133 if (tc->sym->_scope)
4134 tc->sym->_scope->_module->addDeferredSemantic(tc->sym);
4135 cldec->baseok = BASEOKnone;
4136 }
4137 i++;
4138 }
4139 if (cldec->baseok == BASEOKnone)
4140 {
4141 // Forward referencee of one or more bases, try again later
4142 cldec->_scope = scx ? scx : sc->copy();
4143 cldec->_scope->setNoFree();
4144 cldec->_scope->_module->addDeferredSemantic(cldec);
4145 //printf("\tL%d semantic('%s') failed due to forward references\n", __LINE__, cldec->toChars());
4146 return;
4147 }
4148 cldec->baseok = BASEOKdone;
4149
4150 // If no base class, and this is not an Object, use Object as base class
4151 if (!cldec->baseClass && cldec->ident != Id::Object && !cldec->isCPPclass())
4152 {
4153 if (!ClassDeclaration::object || ClassDeclaration::object->errors)
4154 badObjectDotD(cldec);
4155
4156 Type *t = ClassDeclaration::object->type;
4157 t = typeSemantic(t, cldec->loc, sc)->toBasetype();
4158 if (t->ty == Terror)
4159 badObjectDotD(cldec);
4160 assert(t->ty == Tclass);
4161 TypeClass *tc = (TypeClass *)t;
4162
4163 BaseClass *b = new BaseClass(tc);
4164 cldec->baseclasses->shift(b);
4165
4166 cldec->baseClass = tc->sym;
4167 assert(!cldec->baseClass->isInterfaceDeclaration());
4168 b->sym = cldec->baseClass;
4169 }
4170 if (cldec->baseClass)
4171 {
4172 if (cldec->baseClass->storage_class & STCfinal)
4173 cldec->error("cannot inherit from final class %s", cldec->baseClass->toChars());
4174
4175 // Inherit properties from base class
4176 if (cldec->baseClass->isCOMclass())
4177 cldec->com = true;
4178 if (cldec->baseClass->isCPPclass())
4179 cldec->classKind = ClassKind::cpp;
4180 if (cldec->baseClass->isscope)
4181 cldec->isscope = true;
4182 cldec->enclosing = cldec->baseClass->enclosing;
4183 cldec->storage_class |= cldec->baseClass->storage_class & STC_TYPECTOR;
4184 }
4185
4186 cldec->interfaces.length = cldec->baseclasses->length - (cldec->baseClass ? 1 : 0);
4187 cldec->interfaces.ptr = cldec->baseclasses->tdata() + (cldec->baseClass ? 1 : 0);
4188
4189 for (size_t i = 0; i < cldec->interfaces.length; i++)
4190 {
4191 BaseClass *b = cldec->interfaces.ptr[i];
4192 // If this is an interface, and it derives from a COM interface,
4193 // then this is a COM interface too.
4194 if (b->sym->isCOMinterface())
4195 cldec->com = true;
4196 if (cldec->isCPPclass() && !b->sym->isCPPinterface())
4197 {
4198 error(cldec->loc, "C++ class `%s` cannot implement D interface `%s`",
4199 cldec->toPrettyChars(), b->sym->toPrettyChars());
4200 }
4201 }
4202
4203 interfaceSemantic(cldec);
4204 }
4205 Lancestorsdone:
4206 //printf("\tClassDeclaration::semantic(%s) baseok = %d\n", cldec->toChars(), cldec->baseok);
4207
4208 if (!cldec->members) // if opaque declaration
4209 {
4210 cldec->semanticRun = PASSsemanticdone;
4211 return;
4212 }
4213 if (!cldec->symtab)
4214 {
4215 cldec->symtab = new DsymbolTable();
4216
4217 /* Bugzilla 12152: The semantic analysis of base classes should be finished
4218 * before the members semantic analysis of this class, in order to determine
4219 * vtbl in this class. However if a base class refers the member of this class,
4220 * it can be resolved as a normal forward reference.
4221 * Call addMember() and setScope() to make this class members visible from the base classes.
4222 */
4223 for (size_t i = 0; i < cldec->members->length; i++)
4224 {
4225 Dsymbol *s = (*cldec->members)[i];
4226 s->addMember(sc, cldec);
4227 }
4228
4229 Scope *sc2 = cldec->newScope(sc);
4230
4231 /* Set scope so if there are forward references, we still might be able to
4232 * resolve individual members like enums.
4233 */
4234 for (size_t i = 0; i < cldec->members->length; i++)
4235 {
4236 Dsymbol *s = (*cldec->members)[i];
4237 //printf("[%d] setScope %s %s, sc2 = %p\n", i, s->kind(), s->toChars(), sc2);
4238 s->setScope(sc2);
4239 }
4240
4241 sc2->pop();
4242 }
4243
4244 for (size_t i = 0; i < cldec->baseclasses->length; i++)
4245 {
4246 BaseClass *b = (*cldec->baseclasses)[i];
4247 Type *tb = b->type->toBasetype();
4248 assert(tb->ty == Tclass);
4249 TypeClass *tc = (TypeClass *)tb;
4250
4251 if (tc->sym->semanticRun < PASSsemanticdone)
4252 {
4253 // Forward referencee of one or more bases, try again later
4254 cldec->_scope = scx ? scx : sc->copy();
4255 cldec->_scope->setNoFree();
4256 if (tc->sym->_scope)
4257 tc->sym->_scope->_module->addDeferredSemantic(tc->sym);
4258 cldec->_scope->_module->addDeferredSemantic(cldec);
4259 //printf("\tL%d semantic('%s') failed due to forward references\n", __LINE__, cldec->toChars());
4260 return;
4261 }
4262 }
4263
4264 if (cldec->baseok == BASEOKdone)
4265 {
4266 cldec->baseok = BASEOKsemanticdone;
4267
4268 // initialize vtbl
4269 if (cldec->baseClass)
4270 {
4271 if (cldec->isCPPclass() && cldec->baseClass->vtbl.length == 0)
4272 {
4273 cldec->error("C++ base class %s needs at least one virtual function", cldec->baseClass->toChars());
4274 }
4275
4276 // Copy vtbl[] from base class
4277 cldec->vtbl.setDim(cldec->baseClass->vtbl.length);
4278 memcpy(cldec->vtbl.tdata(), cldec->baseClass->vtbl.tdata(), sizeof(void *) * cldec->vtbl.length);
4279
4280 cldec->vthis = cldec->baseClass->vthis;
4281 }
4282 else
4283 {
4284 // No base class, so this is the root of the class hierarchy
4285 cldec->vtbl.setDim(0);
4286 if (cldec->vtblOffset())
4287 cldec->vtbl.push(cldec); // leave room for classinfo as first member
4288 }
4289
4290 /* If this is a nested class, add the hidden 'this'
4291 * member which is a pointer to the enclosing scope.
4292 */
4293 if (cldec->vthis) // if inheriting from nested class
4294 {
4295 // Use the base class's 'this' member
4296 if (cldec->storage_class & STCstatic)
4297 cldec->error("static class cannot inherit from nested class %s", cldec->baseClass->toChars());
4298 if (cldec->toParent2() != cldec->baseClass->toParent2() &&
4299 (!cldec->toParent2() ||
4300 !cldec->baseClass->toParent2()->getType() ||
4301 !cldec->baseClass->toParent2()->getType()->isBaseOf(cldec->toParent2()->getType(), NULL)))
4302 {
4303 if (cldec->toParent2())
4304 {
4305 cldec->error("is nested within %s, but super class %s is nested within %s",
4306 cldec->toParent2()->toChars(),
4307 cldec->baseClass->toChars(),
4308 cldec->baseClass->toParent2()->toChars());
4309 }
4310 else
4311 {
4312 cldec->error("is not nested, but super class %s is nested within %s",
4313 cldec->baseClass->toChars(),
4314 cldec->baseClass->toParent2()->toChars());
4315 }
4316 cldec->enclosing = NULL;
4317 }
4318 }
4319 else
4320 cldec->makeNested();
4321 }
4322
4323 Scope *sc2 = cldec->newScope(sc);
4324
4325 for (size_t i = 0; i < cldec->members->length; i++)
4326 {
4327 Dsymbol *s = (*cldec->members)[i];
4328 s->importAll(sc2);
4329 }
4330
4331 // Note that members.length can grow due to tuple expansion during semantic()
4332 for (size_t i = 0; i < cldec->members->length; i++)
4333 {
4334 Dsymbol *s = (*cldec->members)[i];
4335 dsymbolSemantic(s, sc2);
4336 }
4337
4338 if (!cldec->determineFields())
4339 {
4340 assert(cldec->type == Type::terror);
4341 sc2->pop();
4342 return;
4343 }
4344
4345 /* Following special member functions creation needs semantic analysis
4346 * completion of sub-structs in each field types.
4347 */
4348 for (size_t i = 0; i < cldec->fields.length; i++)
4349 {
4350 VarDeclaration *v = cldec->fields[i];
4351 Type *tb = v->type->baseElemOf();
4352 if (tb->ty != Tstruct)
4353 continue;
4354 StructDeclaration *sd = ((TypeStruct *)tb)->sym;
4355 if (sd->semanticRun >= PASSsemanticdone)
4356 continue;
4357
4358 sc2->pop();
4359
4360 cldec->_scope = scx ? scx : sc->copy();
4361 cldec->_scope->setNoFree();
4362 cldec->_scope->_module->addDeferredSemantic(cldec);
4363 //printf("\tdeferring %s\n", cldec->toChars());
4364 return;
4365 }
4366
4367 /* Look for special member functions.
4368 * They must be in this class, not in a base class.
4369 */
4370
4371 // Can be in base class
4372 cldec->aggNew = (NewDeclaration *)cldec->search(Loc(), Id::classNew);
4373 cldec->aggDelete = (DeleteDeclaration *)cldec->search(Loc(), Id::classDelete);
4374
4375 // Look for the constructor
4376 cldec->ctor = cldec->searchCtor();
4377
4378 if (!cldec->ctor && cldec->noDefaultCtor)
4379 {
4380 // A class object is always created by constructor, so this check is legitimate.
4381 for (size_t i = 0; i < cldec->fields.length; i++)
4382 {
4383 VarDeclaration *v = cldec->fields[i];
4384 if (v->storage_class & STCnodefaultctor)
4385 error(v->loc, "field %s must be initialized in constructor", v->toChars());
4386 }
4387 }
4388
4389 // If this class has no constructor, but base class has a default
4390 // ctor, create a constructor:
4391 // this() { }
4392 if (!cldec->ctor && cldec->baseClass && cldec->baseClass->ctor)
4393 {
4394 FuncDeclaration *fd = resolveFuncCall(cldec->loc, sc2, cldec->baseClass->ctor, NULL, cldec->type, NULL, 1);
4395 if (!fd) // try shared base ctor instead
4396 fd = resolveFuncCall(cldec->loc, sc2, cldec->baseClass->ctor, NULL, cldec->type->sharedOf(), NULL, 1);
4397 if (fd && !fd->errors)
4398 {
4399 //printf("Creating default this(){} for class %s\n", cldec->toChars());
4400 TypeFunction *btf = fd->type->toTypeFunction();
4401 TypeFunction *tf = new TypeFunction(ParameterList(), NULL, LINKd, fd->storage_class);
4402 tf->mod = btf->mod;
4403 tf->purity = btf->purity;
4404 tf->isnothrow = btf->isnothrow;
4405 tf->isnogc = btf->isnogc;
4406 tf->trust = btf->trust;
4407
4408 CtorDeclaration *ctor = new CtorDeclaration(cldec->loc, Loc(), 0, tf);
4409 ctor->fbody = new CompoundStatement(Loc(), new Statements());
4410
4411 cldec->members->push(ctor);
4412 ctor->addMember(sc, cldec);
4413 dsymbolSemantic(ctor, sc2);
4414
4415 cldec->ctor = ctor;
4416 cldec->defaultCtor = ctor;
4417 }
4418 else
4419 {
4420 cldec->error("cannot implicitly generate a default ctor when base class %s is missing a default ctor",
4421 cldec->baseClass->toPrettyChars());
4422 }
4423 }
4424
4425 cldec->dtor = buildDtor(cldec, sc2);
4426
4427 if (FuncDeclaration *f = hasIdentityOpAssign(cldec, sc2))
4428 {
4429 if (!(f->storage_class & STCdisable))
4430 cldec->error(f->loc, "identity assignment operator overload is illegal");
4431 }
4432
4433 cldec->inv = buildInv(cldec, sc2);
4434
4435 Module::dprogress++;
4436 cldec->semanticRun = PASSsemanticdone;
4437 //printf("-ClassDeclaration.semantic(%s), type = %p\n", cldec->toChars(), cldec->type);
4438 //members.print();
4439
4440 sc2->pop();
4441
4442 if (cldec->type->ty == Tclass && ((TypeClass *)cldec->type)->sym != cldec)
4443 {
4444 // https://issues.dlang.org/show_bug.cgi?id=17492
4445 ClassDeclaration *cd = ((TypeClass *)cldec->type)->sym;
4446 cldec->error("already exists at %s. Perhaps in another function with the same name?", cd->loc.toChars());
4447 }
4448
4449 if (global.errors != errors)
4450 {
4451 // The type is no good.
4452 cldec->type = Type::terror;
4453 cldec->errors = true;
4454 if (cldec->deferred)
4455 cldec->deferred->errors = true;
4456 }
4457
4458 // Verify fields of a synchronized class are not public
4459 if (cldec->storage_class & STCsynchronized)
4460 {
4461 for (size_t i = 0; i < cldec->fields.length; i++)
4462 {
4463 VarDeclaration *vd = cldec->fields[i];
4464 if (!vd->isThisDeclaration() &&
4465 !vd->prot().isMoreRestrictiveThan(Prot(Prot::public_)))
4466 {
4467 vd->error("Field members of a synchronized class cannot be %s",
4468 protectionToChars(vd->prot().kind));
4469 }
4470 }
4471 }
4472
4473 if (cldec->deferred && !global.gag)
4474 {
4475 semantic2(cldec->deferred, sc);
4476 semantic3(cldec->deferred, sc);
4477 }
4478 //printf("-ClassDeclaration::semantic(%s), type = %p, sizeok = %d, this = %p\n", cldec->toChars(), cldec->type, sizeok, cldec);
4479 }
4480
4481 void visit(InterfaceDeclaration *idec)
4482 {
4483 //printf("InterfaceDeclaration::semantic(%s), type = %p\n", idec->toChars(), idec->type);
4484 if (idec->semanticRun >= PASSsemanticdone)
4485 return;
4486 unsigned errors = global.errors;
4487
4488 //printf("+InterfaceDeclaration.semantic(%s), type = %p\n", idec->toChars(), idec->type);
4489
4490 Scope *scx = NULL;
4491 if (idec->_scope)
4492 {
4493 sc = idec->_scope;
4494 scx = idec->_scope; // save so we don't make redundant copies
4495 idec->_scope = NULL;
4496 }
4497
4498 if (!idec->parent)
4499 {
4500 assert(sc->parent && sc->func);
4501 idec->parent = sc->parent;
4502 }
4503 assert(idec->parent && !idec->isAnonymous());
4504
4505 if (idec->errors)
4506 idec->type = Type::terror;
4507 idec->type = typeSemantic(idec->type, idec->loc, sc);
4508
4509 if (idec->type->ty == Tclass && ((TypeClass *)idec->type)->sym != idec)
4510 {
4511 TemplateInstance *ti = ((TypeClass *)idec->type)->sym->isInstantiated();
4512 if (ti && isError(ti))
4513 ((TypeClass *)idec->type)->sym = idec;
4514 }
4515
4516 // Ungag errors when not speculative
4517 Ungag ungag = idec->ungagSpeculative();
4518
4519 if (idec->semanticRun == PASSinit)
4520 {
4521 idec->protection = sc->protection;
4522
4523 idec->storage_class |= sc->stc;
4524 if (idec->storage_class & STCdeprecated)
4525 idec->isdeprecated = true;
4526
4527 idec->userAttribDecl = sc->userAttribDecl;
4528 }
4529 else if (idec->symtab)
4530 {
4531 if (idec->sizeok == SIZEOKdone || !scx)
4532 {
4533 idec->semanticRun = PASSsemanticdone;
4534 return;
4535 }
4536 }
4537 idec->semanticRun = PASSsemantic;
4538
4539 if (idec->baseok < BASEOKdone)
4540 {
4541 idec->baseok = BASEOKin;
4542
4543 // Expand any tuples in baseclasses[]
4544 for (size_t i = 0; i < idec->baseclasses->length; )
4545 {
4546 BaseClass *b = (*idec->baseclasses)[i];
4547 b->type = resolveBase(idec, sc, scx, b->type);
4548
4549 Type *tb = b->type->toBasetype();
4550 if (tb->ty == Ttuple)
4551 {
4552 TypeTuple *tup = (TypeTuple *)tb;
4553 idec->baseclasses->remove(i);
4554 size_t dim = Parameter::dim(tup->arguments);
4555 for (size_t j = 0; j < dim; j++)
4556 {
4557 Parameter *arg = Parameter::getNth(tup->arguments, j);
4558 b = new BaseClass(arg->type);
4559 idec->baseclasses->insert(i + j, b);
4560 }
4561 }
4562 else
4563 i++;
4564 }
4565
4566 if (idec->baseok >= BASEOKdone)
4567 {
4568 //printf("%s already semantic analyzed, semanticRun = %d\n", idec->toChars(), idec->semanticRun);
4569 if (idec->semanticRun >= PASSsemanticdone)
4570 return;
4571 goto Lancestorsdone;
4572 }
4573
4574 if (!idec->baseclasses->length && sc->linkage == LINKcpp)
4575 idec->classKind = ClassKind::cpp;
4576 if (sc->linkage == LINKobjc)
4577 objc()->setObjc(idec);
4578
4579 // Check for errors, handle forward references
4580 for (size_t i = 0; i < idec->baseclasses->length; )
4581 {
4582 BaseClass *b = (*idec->baseclasses)[i];
4583 Type *tb = b->type->toBasetype();
4584 TypeClass *tc = (tb->ty == Tclass) ? (TypeClass *)tb : NULL;
4585 if (!tc || !tc->sym->isInterfaceDeclaration())
4586 {
4587 if (b->type != Type::terror)
4588 idec->error("base type must be interface, not %s", b->type->toChars());
4589 idec->baseclasses->remove(i);
4590 continue;
4591 }
4592
4593 // Check for duplicate interfaces
4594 for (size_t j = 0; j < i; j++)
4595 {
4596 BaseClass *b2 = (*idec->baseclasses)[j];
4597 if (b2->sym == tc->sym)
4598 {
4599 idec->error("inherits from duplicate interface %s", b2->sym->toChars());
4600 idec->baseclasses->remove(i);
4601 continue;
4602 }
4603 }
4604
4605 if (tc->sym == idec || idec->isBaseOf2(tc->sym))
4606 {
4607 idec->error("circular inheritance of interface");
4608 idec->baseclasses->remove(i);
4609 continue;
4610 }
4611
4612 if (tc->sym->isDeprecated())
4613 {
4614 if (!idec->isDeprecated())
4615 {
4616 // Deriving from deprecated class makes this one deprecated too
4617 idec->isdeprecated = true;
4618
4619 tc->checkDeprecated(idec->loc, sc);
4620 }
4621 }
4622
4623 b->sym = tc->sym;
4624
4625 if (tc->sym->baseok < BASEOKdone)
4626 resolveBase(idec, sc, scx, tc->sym); // Try to resolve forward reference
4627 if (tc->sym->baseok < BASEOKdone)
4628 {
4629 //printf("\ttry later, forward reference of base %s\n", tc->sym->toChars());
4630 if (tc->sym->_scope)
4631 tc->sym->_scope->_module->addDeferredSemantic(tc->sym);
4632 idec->baseok = BASEOKnone;
4633 }
4634 i++;
4635 }
4636 if (idec->baseok == BASEOKnone)
4637 {
4638 // Forward referencee of one or more bases, try again later
4639 idec->_scope = scx ? scx : sc->copy();
4640 idec->_scope->setNoFree();
4641 idec->_scope->_module->addDeferredSemantic(idec);
4642 return;
4643 }
4644 idec->baseok = BASEOKdone;
4645
4646 idec->interfaces.length = idec->baseclasses->length;
4647 idec->interfaces.ptr = idec->baseclasses->tdata();
4648
4649 for (size_t i = 0; i < idec->interfaces.length; i++)
4650 {
4651 BaseClass *b = idec->interfaces.ptr[i];
4652 // If this is an interface, and it derives from a COM interface,
4653 // then this is a COM interface too.
4654 if (b->sym->isCOMinterface())
4655 idec->com = true;
4656 if (b->sym->isCPPinterface())
4657 idec->classKind = ClassKind::cpp;
4658 }
4659
4660 interfaceSemantic(idec);
4661 }
4662 Lancestorsdone:
4663
4664 if (!idec->members) // if opaque declaration
4665 {
4666 idec->semanticRun = PASSsemanticdone;
4667 return;
4668 }
4669 if (!idec->symtab)
4670 idec->symtab = new DsymbolTable();
4671
4672 for (size_t i = 0; i < idec->baseclasses->length; i++)
4673 {
4674 BaseClass *b = (*idec->baseclasses)[i];
4675 Type *tb = b->type->toBasetype();
4676 assert(tb->ty == Tclass);
4677 TypeClass *tc = (TypeClass *)tb;
4678
4679 if (tc->sym->semanticRun < PASSsemanticdone)
4680 {
4681 // Forward referencee of one or more bases, try again later
4682 idec->_scope = scx ? scx : sc->copy();
4683 idec->_scope->setNoFree();
4684 if (tc->sym->_scope)
4685 tc->sym->_scope->_module->addDeferredSemantic(tc->sym);
4686 idec->_scope->_module->addDeferredSemantic(idec);
4687 return;
4688 }
4689 }
4690
4691 if (idec->baseok == BASEOKdone)
4692 {
4693 idec->baseok = BASEOKsemanticdone;
4694
4695 // initialize vtbl
4696 if (idec->vtblOffset())
4697 idec->vtbl.push(idec); // leave room at vtbl[0] for classinfo
4698
4699 // Cat together the vtbl[]'s from base cldec->interfaces
4700 for (size_t i = 0; i < idec->interfaces.length; i++)
4701 {
4702 BaseClass *b = idec->interfaces.ptr[i];
4703
4704 // Skip if b has already appeared
4705 for (size_t k = 0; k < i; k++)
4706 {
4707 if (b == idec->interfaces.ptr[k])
4708 goto Lcontinue;
4709 }
4710
4711 // Copy vtbl[] from base class
4712 if (b->sym->vtblOffset())
4713 {
4714 size_t d = b->sym->vtbl.length;
4715 if (d > 1)
4716 {
4717 idec->vtbl.reserve(d - 1);
4718 for (size_t j = 1; j < d; j++)
4719 idec->vtbl.push(b->sym->vtbl[j]);
4720 }
4721 }
4722 else
4723 {
4724 idec->vtbl.append(&b->sym->vtbl);
4725 }
4726
4727 Lcontinue:
4728 ;
4729 }
4730 }
4731
4732 for (size_t i = 0; i < idec->members->length; i++)
4733 {
4734 Dsymbol *s = (*idec->members)[i];
4735 s->addMember(sc, idec);
4736 }
4737
4738 Scope *sc2 = idec->newScope(sc);
4739
4740 /* Set scope so if there are forward references, we still might be able to
4741 * resolve individual members like enums.
4742 */
4743 for (size_t i = 0; i < idec->members->length; i++)
4744 {
4745 Dsymbol *s = (*idec->members)[i];
4746 //printf("setScope %s %s\n", s->kind(), s->toChars());
4747 s->setScope(sc2);
4748 }
4749
4750 for (size_t i = 0; i < idec->members->length; i++)
4751 {
4752 Dsymbol *s = (*idec->members)[i];
4753 s->importAll(sc2);
4754 }
4755
4756 for (size_t i = 0; i < idec->members->length; i++)
4757 {
4758 Dsymbol *s = (*idec->members)[i];
4759 dsymbolSemantic(s, sc2);
4760 }
4761
4762 Module::dprogress++;
4763 idec->semanticRun = PASSsemanticdone;
4764 //printf("-InterfaceDeclaration.semantic(%s), type = %p\n", idec->toChars(), idec->type);
4765 //members->print();
4766
4767 sc2->pop();
4768
4769 if (global.errors != errors)
4770 {
4771 // The type is no good.
4772 idec->type = Type::terror;
4773 }
4774
4775 assert(idec->type->ty != Tclass || ((TypeClass *)idec->type)->sym == idec);
4776 }
4777 };
4778
4779 void templateInstanceSemantic(TemplateInstance *tempinst, Scope *sc, Expressions *fargs)
4780 {
4781 //printf("[%s] TemplateInstance::semantic('%s', this=%p, gag = %d, sc = %p)\n", tempinst->loc.toChars(), tempinst->toChars(), tempinst, global.gag, sc);
4782 if (tempinst->inst) // if semantic() was already run
4783 {
4784 return;
4785 }
4786 if (tempinst->semanticRun != PASSinit)
4787 {
4788 Ungag ungag(global.gag);
4789 if (!tempinst->gagged)
4790 global.gag = 0;
4791 tempinst->error(tempinst->loc, "recursive template expansion");
4792 if (tempinst->gagged)
4793 tempinst->semanticRun = PASSinit;
4794 else
4795 tempinst->inst = tempinst;
4796 tempinst->errors = true;
4797 return;
4798 }
4799
4800 // Get the enclosing template instance from the scope tinst
4801 tempinst->tinst = sc->tinst;
4802
4803 // Get the instantiating module from the scope minst
4804 tempinst->minst = sc->minst;
4805 // Bugzilla 10920: If the enclosing function is non-root symbol,
4806 // this instance should be speculative.
4807 if (!tempinst->tinst && sc->func && sc->func->inNonRoot())
4808 {
4809 tempinst->minst = NULL;
4810 }
4811
4812 tempinst->gagged = (global.gag > 0);
4813
4814 tempinst->semanticRun = PASSsemantic;
4815
4816 /* Find template declaration first,
4817 * then run semantic on each argument (place results in tiargs[]),
4818 * last find most specialized template from overload list/set.
4819 */
4820 if (!tempinst->findTempDecl(sc, NULL) ||
4821 !tempinst->semanticTiargs(sc) ||
4822 !tempinst->findBestMatch(sc, fargs))
4823 {
4824 Lerror:
4825 if (tempinst->gagged)
4826 {
4827 // Bugzilla 13220: Rollback status for later semantic re-running.
4828 tempinst->semanticRun = PASSinit;
4829 }
4830 else
4831 tempinst->inst = tempinst;
4832 tempinst->errors = true;
4833 return;
4834 }
4835 TemplateDeclaration *tempdecl = tempinst->tempdecl->isTemplateDeclaration();
4836 assert(tempdecl);
4837
4838 // If tempdecl is a mixin, disallow it
4839 if (tempdecl->ismixin)
4840 {
4841 tempinst->error("mixin templates are not regular templates");
4842 goto Lerror;
4843 }
4844
4845 tempinst->hasNestedArgs(tempinst->tiargs, tempdecl->isstatic);
4846 if (tempinst->errors)
4847 goto Lerror;
4848
4849 /* See if there is an existing TemplateInstantiation that already
4850 * implements the typeargs. If so, just refer to that one instead.
4851 */
4852 tempinst->inst = tempdecl->findExistingInstance(tempinst, fargs);
4853 TemplateInstance *errinst = NULL;
4854 if (!tempinst->inst)
4855 {
4856 // So, we need to implement 'this' instance.
4857 }
4858 else if (tempinst->inst->gagged && !tempinst->gagged && tempinst->inst->errors)
4859 {
4860 // If the first instantiation had failed, re-run semantic,
4861 // so that error messages are shown.
4862 errinst = tempinst->inst;
4863 }
4864 else
4865 {
4866 // It's a match
4867 tempinst->parent = tempinst->inst->parent;
4868 tempinst->errors = tempinst->inst->errors;
4869
4870 // If both this and the previous instantiation were gagged,
4871 // use the number of errors that happened last time.
4872 global.errors += tempinst->errors;
4873 global.gaggedErrors += tempinst->errors;
4874
4875 // If the first instantiation was gagged, but this is not:
4876 if (tempinst->inst->gagged)
4877 {
4878 // It had succeeded, mark it is a non-gagged instantiation,
4879 // and reuse it.
4880 tempinst->inst->gagged = tempinst->gagged;
4881 }
4882
4883 tempinst->tnext = tempinst->inst->tnext;
4884 tempinst->inst->tnext = tempinst;
4885
4886 /* A module can have explicit template instance and its alias
4887 * in module scope (e,g, `alias Base64 = Base64Impl!('+', '/');`).
4888 * If the first instantiation 'inst' had happened in non-root module,
4889 * compiler can assume that its instantiated code would be included
4890 * in the separately compiled obj/lib file (e.g. phobos.lib).
4891 *
4892 * However, if 'this' second instantiation happened in root module,
4893 * compiler might need to invoke its codegen (Bugzilla 2500 & 2644).
4894 * But whole import graph is not determined until all semantic pass finished,
4895 * so 'inst' should conservatively finish the semantic3 pass for the codegen.
4896 */
4897 if (tempinst->minst && tempinst->minst->isRoot() && !(tempinst->inst->minst && tempinst->inst->minst->isRoot()))
4898 {
4899 /* Swap the position of 'inst' and 'this' in the instantiation graph.
4900 * Then, the primary instance `inst` will be changed to a root instance,
4901 * along with all members of `inst` having their scopes updated.
4902 *
4903 * Before:
4904 * non-root -> A!() -> B!()[inst] -> C!() { members[non-root] }
4905 * |
4906 * root -> D!() -> B!()[this]
4907 *
4908 * After:
4909 * non-root -> A!() -> B!()[this]
4910 * |
4911 * root -> D!() -> B!()[inst] -> C!() { members[root] }
4912 */
4913 Module *mi = tempinst->minst;
4914 TemplateInstance *ti = tempinst->tinst;
4915 tempinst->minst = tempinst->inst->minst;
4916 tempinst->tinst = tempinst->inst->tinst;
4917 tempinst->inst->minst = mi;
4918 tempinst->inst->tinst = ti;
4919
4920 /* https://issues.dlang.org/show_bug.cgi?id=21299
4921 `minst` has been updated on the primary instance `inst` so it is
4922 now coming from a root module, however all Dsymbol `inst.members`
4923 of the instance still have their `_scope.minst` pointing at the
4924 original non-root module. We must now propagate `minst` to all
4925 members so that forward referenced dependencies that get
4926 instantiated will also be appended to the root module, otherwise
4927 there will be undefined references at link-time. */
4928 class InstMemberWalker : public Visitor
4929 {
4930 public:
4931 TemplateInstance *inst;
4932
4933 InstMemberWalker(TemplateInstance *inst)
4934 : inst(inst) { }
4935
4936 void visit(Dsymbol *d)
4937 {
4938 if (d->_scope)
4939 d->_scope->minst = inst->minst;
4940 }
4941
4942 void visit(ScopeDsymbol *sds)
4943 {
4944 if (!sds->members)
4945 return;
4946 for (size_t i = 0; i < sds->members->length; i++)
4947 {
4948 Dsymbol *s = (*sds->members)[i];
4949 s->accept(this);
4950 }
4951 visit((Dsymbol *)sds);
4952 }
4953
4954 void visit(AttribDeclaration *ad)
4955 {
4956 Dsymbols *d = ad->include(NULL);
4957 if (!d)
4958 return;
4959 for (size_t i = 0; i < d->length; i++)
4960 {
4961 Dsymbol *s = (*d)[i];
4962 s->accept(this);
4963 }
4964 visit((Dsymbol *)ad);
4965 }
4966
4967 void visit(ConditionalDeclaration *cd)
4968 {
4969 if (cd->condition->inc)
4970 visit((AttribDeclaration *)cd);
4971 else
4972 visit((Dsymbol *)cd);
4973 }
4974 };
4975 InstMemberWalker v(tempinst->inst);
4976 tempinst->inst->accept(&v);
4977
4978 if (tempinst->minst) // if inst was not speculative
4979 {
4980 /* Add 'inst' once again to the root module members[], then the
4981 * instance members will get codegen chances.
4982 */
4983 tempinst->inst->appendToModuleMember();
4984 }
4985 }
4986
4987 return;
4988 }
4989 unsigned errorsave = global.errors;
4990
4991 tempinst->inst = tempinst;
4992 tempinst->parent = tempinst->enclosing ? tempinst->enclosing : tempdecl->parent;
4993 //printf("parent = '%s'\n", tempinst->parent->kind());
4994
4995 TemplateInstance *tempdecl_instance_idx = tempdecl->addInstance(tempinst);
4996
4997 //getIdent();
4998
4999 // Store the place we added it to in target_symbol_list(_idx) so we can
5000 // remove it later if we encounter an error.
5001 Dsymbols *target_symbol_list = tempinst->appendToModuleMember();
5002 size_t target_symbol_list_idx = target_symbol_list ? target_symbol_list->length - 1 : 0;
5003
5004 // Copy the syntax trees from the TemplateDeclaration
5005 tempinst->members = Dsymbol::arraySyntaxCopy(tempdecl->members);
5006
5007 // resolve TemplateThisParameter
5008 for (size_t i = 0; i < tempdecl->parameters->length; i++)
5009 {
5010 if ((*tempdecl->parameters)[i]->isTemplateThisParameter() == NULL)
5011 continue;
5012 Type *t = isType((*tempinst->tiargs)[i]);
5013 assert(t);
5014 if (StorageClass stc = ModToStc(t->mod))
5015 {
5016 //printf("t = %s, stc = x%llx\n", t->toChars(), stc);
5017 Dsymbols *s = new Dsymbols();
5018 s->push(new StorageClassDeclaration(stc, tempinst->members));
5019 tempinst->members = s;
5020 }
5021 break;
5022 }
5023
5024 // Create our own scope for the template parameters
5025 Scope *scope = tempdecl->_scope;
5026 if (tempdecl->semanticRun == PASSinit)
5027 {
5028 tempinst->error("template instantiation %s forward references template declaration %s", tempinst->toChars(), tempdecl->toChars());
5029 return;
5030 }
5031
5032 tempinst->argsym = new ScopeDsymbol();
5033 tempinst->argsym->parent = scope->parent;
5034 scope = scope->push(tempinst->argsym);
5035 scope->tinst = tempinst;
5036 scope->minst = tempinst->minst;
5037 //scope->stc = 0;
5038
5039 // Declare each template parameter as an alias for the argument type
5040 Scope *paramscope = scope->push();
5041 paramscope->stc = 0;
5042 paramscope->protection = Prot(Prot::public_); // Bugzilla 14169: template parameters should be public
5043 tempinst->declareParameters(paramscope);
5044 paramscope->pop();
5045
5046 // Add members of template instance to template instance symbol table
5047 // tempinst->parent = scope->scopesym;
5048 tempinst->symtab = new DsymbolTable();
5049 for (size_t i = 0; i < tempinst->members->length; i++)
5050 {
5051 Dsymbol *s = (*tempinst->members)[i];
5052 s->addMember(scope, tempinst);
5053 }
5054
5055 /* See if there is only one member of template instance, and that
5056 * member has the same name as the template instance.
5057 * If so, this template instance becomes an alias for that member.
5058 */
5059 //printf("members->length = %d\n", tempinst->members->length);
5060 if (tempinst->members->length)
5061 {
5062 Dsymbol *s;
5063 if (Dsymbol::oneMembers(tempinst->members, &s, tempdecl->ident) && s)
5064 {
5065 //printf("tempdecl->ident = %s, s = '%s'\n", tempdecl->ident->toChars(), s->kind(), s->toPrettyChars());
5066 //printf("setting aliasdecl\n");
5067 tempinst->aliasdecl = s;
5068 }
5069 }
5070
5071 /* If function template declaration
5072 */
5073 if (fargs && tempinst->aliasdecl)
5074 {
5075 FuncDeclaration *fd = tempinst->aliasdecl->isFuncDeclaration();
5076 if (fd)
5077 {
5078 /* Transmit fargs to type so that TypeFunction::semantic() can
5079 * resolve any "auto ref" storage classes.
5080 */
5081 TypeFunction *tf = (TypeFunction *)fd->type;
5082 if (tf && tf->ty == Tfunction)
5083 tf->fargs = fargs;
5084 }
5085 }
5086
5087 // Do semantic() analysis on template instance members
5088 Scope *sc2;
5089 sc2 = scope->push(tempinst);
5090 //printf("enclosing = %d, sc->parent = %s\n", tempinst->enclosing, sc->parent->toChars());
5091 sc2->parent = tempinst;
5092 sc2->tinst = tempinst;
5093 sc2->minst = tempinst->minst;
5094
5095 tempinst->tryExpandMembers(sc2);
5096
5097 tempinst->semanticRun = PASSsemanticdone;
5098
5099 /* ConditionalDeclaration may introduce eponymous declaration,
5100 * so we should find it once again after semantic.
5101 */
5102 if (tempinst->members->length)
5103 {
5104 Dsymbol *s;
5105 if (Dsymbol::oneMembers(tempinst->members, &s, tempdecl->ident) && s)
5106 {
5107 if (!tempinst->aliasdecl || tempinst->aliasdecl != s)
5108 {
5109 //printf("tempdecl->ident = %s, s = '%s'\n", tempdecl->ident->toChars(), s->kind(), s->toPrettyChars());
5110 //printf("setting aliasdecl 2\n");
5111 tempinst->aliasdecl = s;
5112 }
5113 }
5114 }
5115
5116 if (global.errors != errorsave)
5117 goto Laftersemantic;
5118
5119 /* If any of the instantiation members didn't get semantic() run
5120 * on them due to forward references, we cannot run semantic2()
5121 * or semantic3() yet.
5122 */
5123 {
5124 bool found_deferred_ad = false;
5125 for (size_t i = 0; i < Module::deferred.length; i++)
5126 {
5127 Dsymbol *sd = Module::deferred[i];
5128 AggregateDeclaration *ad = sd->isAggregateDeclaration();
5129 if (ad && ad->parent && ad->parent->isTemplateInstance())
5130 {
5131 //printf("deferred template aggregate: %s %s\n",
5132 // sd->parent->toChars(), sd->toChars());
5133 found_deferred_ad = true;
5134 if (ad->parent == tempinst)
5135 {
5136 ad->deferred = tempinst;
5137 break;
5138 }
5139 }
5140 }
5141 if (found_deferred_ad || Module::deferred.length)
5142 goto Laftersemantic;
5143 }
5144
5145 /* The problem is when to parse the initializer for a variable.
5146 * Perhaps VarDeclaration::semantic() should do it like it does
5147 * for initializers inside a function.
5148 */
5149 //if (sc->parent->isFuncDeclaration())
5150 {
5151 /* BUG 782: this has problems if the classes this depends on
5152 * are forward referenced. Find a way to defer semantic()
5153 * on this template.
5154 */
5155 semantic2(tempinst, sc2);
5156 }
5157 if (global.errors != errorsave)
5158 goto Laftersemantic;
5159
5160 if ((sc->func || (sc->flags & SCOPEfullinst)) && !tempinst->tinst)
5161 {
5162 /* If a template is instantiated inside function, the whole instantiation
5163 * should be done at that position. But, immediate running semantic3 of
5164 * dependent templates may cause unresolved forward reference (Bugzilla 9050).
5165 * To avoid the issue, don't run semantic3 until semantic and semantic2 done.
5166 */
5167 TemplateInstances deferred;
5168 tempinst->deferred = &deferred;
5169
5170 //printf("Run semantic3 on %s\n", tempinst->toChars());
5171 tempinst->trySemantic3(sc2);
5172
5173 for (size_t i = 0; i < deferred.length; i++)
5174 {
5175 //printf("+ run deferred semantic3 on %s\n", deferred[i]->toChars());
5176 semantic3(deferred[i], NULL);
5177 }
5178
5179 tempinst->deferred = NULL;
5180 }
5181 else if (tempinst->tinst)
5182 {
5183 bool doSemantic3 = false;
5184 if (sc->func && tempinst->aliasdecl && tempinst->aliasdecl->toAlias()->isFuncDeclaration())
5185 {
5186 /* Template function instantiation should run semantic3 immediately
5187 * for attribute inference.
5188 */
5189 tempinst->trySemantic3(sc2);
5190 }
5191 else if (sc->func)
5192 {
5193 /* A lambda function in template arguments might capture the
5194 * instantiated scope context. For the correct context inference,
5195 * all instantiated functions should run the semantic3 immediately.
5196 * See also compilable/test14973.d
5197 */
5198 for (size_t i = 0; i < tempinst->tdtypes.length; i++)
5199 {
5200 RootObject *oarg = tempinst->tdtypes[i];
5201 Dsymbol *s = getDsymbol(oarg);
5202 if (!s)
5203 continue;
5204
5205 if (TemplateDeclaration *td = s->isTemplateDeclaration())
5206 {
5207 if (!td->literal)
5208 continue;
5209 assert(td->members && td->members->length == 1);
5210 s = (*td->members)[0];
5211 }
5212 if (FuncLiteralDeclaration *fld = s->isFuncLiteralDeclaration())
5213 {
5214 if (fld->tok == TOKreserved)
5215 {
5216 doSemantic3 = true;
5217 break;
5218 }
5219 }
5220 }
5221 //printf("[%s] %s doSemantic3 = %d\n", tempinst->loc.toChars(), tempinst->toChars(), doSemantic3);
5222 }
5223 if (doSemantic3)
5224 tempinst->trySemantic3(sc2);
5225
5226 TemplateInstance *ti = tempinst->tinst;
5227 int nest = 0;
5228 while (ti && !ti->deferred && ti->tinst)
5229 {
5230 ti = ti->tinst;
5231 if (++nest > global.recursionLimit)
5232 {
5233 global.gag = 0; // ensure error message gets printed
5234 tempinst->error("recursive expansion");
5235 fatal();
5236 }
5237 }
5238 if (ti && ti->deferred)
5239 {
5240 //printf("deferred semantic3 of %p %s, ti = %s, ti->deferred = %p\n", tempinst, tempinst->toChars(), ti->toChars());
5241 for (size_t i = 0; ; i++)
5242 {
5243 if (i == ti->deferred->length)
5244 {
5245 ti->deferred->push(tempinst);
5246 break;
5247 }
5248 if ((*ti->deferred)[i] == tempinst)
5249 break;
5250 }
5251 }
5252 }
5253
5254 if (tempinst->aliasdecl)
5255 {
5256 /* Bugzilla 13816: AliasDeclaration tries to resolve forward reference
5257 * twice (See inuse check in AliasDeclaration::toAlias()). It's
5258 * necessary to resolve mutual references of instantiated symbols, but
5259 * it will left a true recursive alias in tuple declaration - an
5260 * AliasDeclaration A refers TupleDeclaration B, and B contains A
5261 * in its elements. To correctly make it an error, we strictly need to
5262 * resolve the alias of eponymous member.
5263 */
5264 tempinst->aliasdecl = tempinst->aliasdecl->toAlias2();
5265 }
5266
5267 Laftersemantic:
5268 sc2->pop();
5269
5270 scope->pop();
5271
5272 // Give additional context info if error occurred during instantiation
5273 if (global.errors != errorsave)
5274 {
5275 if (!tempinst->errors)
5276 {
5277 if (!tempdecl->literal)
5278 tempinst->error(tempinst->loc, "error instantiating");
5279 if (tempinst->tinst)
5280 tempinst->tinst->printInstantiationTrace();
5281 }
5282 tempinst->errors = true;
5283 if (tempinst->gagged)
5284 {
5285 // Errors are gagged, so remove the template instance from the
5286 // instance/symbol lists we added it to and reset our state to
5287 // finish clean and so we can try to instantiate it again later
5288 // (see bugzilla 4302 and 6602).
5289 tempdecl->removeInstance(tempdecl_instance_idx);
5290 if (target_symbol_list)
5291 {
5292 // Because we added 'this' in the last position above, we
5293 // should be able to remove it without messing other indices up.
5294 assert((*target_symbol_list)[target_symbol_list_idx] == tempinst);
5295 target_symbol_list->remove(target_symbol_list_idx);
5296 tempinst->memberOf = NULL; // no longer a member
5297 }
5298 tempinst->semanticRun = PASSinit;
5299 tempinst->inst = NULL;
5300 tempinst->symtab = NULL;
5301 }
5302 }
5303 else if (errinst)
5304 {
5305 /* Bugzilla 14541: If the previous gagged instance had failed by
5306 * circular references, currrent "error reproduction instantiation"
5307 * might succeed, because of the difference of instantiated context.
5308 * On such case, the cached error instance needs to be overridden by the
5309 * succeeded instance.
5310 */
5311 //printf("replaceInstance()\n");
5312 TemplateInstances *tinstances = (TemplateInstances *)dmd_aaGetRvalue((AA *)tempdecl->instances, (void *)tempinst->hash);
5313 assert(tinstances);
5314 for (size_t i = 0; i < tinstances->length; i++)
5315 {
5316 TemplateInstance *ti = (*tinstances)[i];
5317 if (ti == errinst)
5318 {
5319 (*tinstances)[i] = tempinst; // override
5320 break;
5321 }
5322 }
5323 }
5324 }
5325
5326 // function used to perform semantic on AliasDeclaration
5327 void aliasSemantic(AliasDeclaration *ds, Scope *sc)
5328 {
5329 //printf("AliasDeclaration::semantic() %s\n", ds->toChars());
5330
5331 // as AliasDeclaration::semantic, in case we're called first.
5332 // see https://issues.dlang.org/show_bug.cgi?id=21001
5333 ds->storage_class |= sc->stc & STCdeprecated;
5334 ds->protection = sc->protection;
5335 ds->userAttribDecl = sc->userAttribDecl;
5336
5337 // TypeTraits needs to know if it's located in an AliasDeclaration
5338 sc->flags |= SCOPEalias;
5339
5340 if (ds->aliassym)
5341 {
5342 FuncDeclaration *fd = ds->aliassym->isFuncLiteralDeclaration();
5343 TemplateDeclaration *td = ds->aliassym->isTemplateDeclaration();
5344 if (fd || (td && td->literal))
5345 {
5346 if (fd && fd->semanticRun >= PASSsemanticdone)
5347 {
5348 sc->flags &= ~SCOPEalias;
5349 return;
5350 }
5351
5352 Expression *e = new FuncExp(ds->loc, ds->aliassym);
5353 e = expressionSemantic(e, sc);
5354 if (e->op == TOKfunction)
5355 {
5356 FuncExp *fe = (FuncExp *)e;
5357 ds->aliassym = fe->td ? (Dsymbol *)fe->td : fe->fd;
5358 }
5359 else
5360 {
5361 ds->aliassym = NULL;
5362 ds->type = Type::terror;
5363 }
5364 sc->flags &= ~SCOPEalias;
5365 return;
5366 }
5367
5368 if (ds->aliassym->isTemplateInstance())
5369 dsymbolSemantic(ds->aliassym, sc);
5370 sc->flags &= ~SCOPEalias;
5371 return;
5372 }
5373 ds->inuse = 1;
5374
5375 // Given:
5376 // alias foo.bar.abc def;
5377 // it is not knowable from the syntax whether this is an alias
5378 // for a type or an alias for a symbol. It is up to the semantic()
5379 // pass to distinguish.
5380 // If it is a type, then type is set and getType() will return that
5381 // type. If it is a symbol, then aliassym is set and type is NULL -
5382 // toAlias() will return aliasssym.
5383
5384 unsigned int errors = global.errors;
5385 Type *oldtype = ds->type;
5386
5387 // Ungag errors when not instantiated DeclDefs scope alias
5388 Ungag ungag(global.gag);
5389 //printf("%s parent = %s, gag = %d, instantiated = %d\n", ds->toChars(), ds->parent, global.gag, ds->isInstantiated());
5390 if (ds->parent && global.gag && !ds->isInstantiated() && !ds->toParent2()->isFuncDeclaration())
5391 {
5392 //printf("%s type = %s\n", ds->toPrettyChars(), ds->type->toChars());
5393 global.gag = 0;
5394 }
5395
5396 /* This section is needed because Type::resolve() will:
5397 * const x = 3;
5398 * alias y = x;
5399 * try to convert identifier x to 3.
5400 */
5401 Dsymbol *s = ds->type->toDsymbol(sc);
5402 if (errors != global.errors)
5403 {
5404 s = NULL;
5405 ds->type = Type::terror;
5406 }
5407 if (s && s == ds)
5408 {
5409 ds->error("cannot resolve");
5410 s = NULL;
5411 ds->type = Type::terror;
5412 }
5413 if (!s || !s->isEnumMember())
5414 {
5415 Type *t;
5416 Expression *e;
5417 Scope *sc2 = sc;
5418 if (ds->storage_class & (STCref | STCnothrow | STCnogc | STCpure | STCdisable))
5419 {
5420 // For 'ref' to be attached to function types, and picked
5421 // up by Type::resolve(), it has to go into sc.
5422 sc2 = sc->push();
5423 sc2->stc |= ds->storage_class & (STCref | STCnothrow | STCnogc | STCpure | STCshared | STCdisable);
5424 }
5425 ds->type = ds->type->addSTC(ds->storage_class);
5426 ds->type->resolve(ds->loc, sc2, &e, &t, &s);
5427 if (sc2 != sc)
5428 sc2->pop();
5429
5430 if (e) // Try to convert Expression to Dsymbol
5431 {
5432 s = getDsymbol(e);
5433 if (!s)
5434 {
5435 if (e->op != TOKerror)
5436 ds->error("cannot alias an expression %s", e->toChars());
5437 t = Type::terror;
5438 }
5439 }
5440 ds->type = t;
5441 }
5442 if (s == ds)
5443 {
5444 assert(global.errors);
5445 ds->type = Type::terror;
5446 s = NULL;
5447 }
5448 if (!s) // it's a type alias
5449 {
5450 //printf("alias %s resolved to type %s\n", ds->toChars(), ds->type->toChars());
5451 ds->type = typeSemantic(ds->type, ds->loc, sc);
5452 ds->aliassym = NULL;
5453 }
5454 else // it's a symbolic alias
5455 {
5456 //printf("alias %s resolved to %s %s\n", ds->toChars(), s->kind(), s->toChars());
5457 ds->type = NULL;
5458 ds->aliassym = s;
5459 }
5460 if (global.gag && errors != global.errors)
5461 {
5462 ds->type = oldtype;
5463 ds->aliassym = NULL;
5464 }
5465 ds->inuse = 0;
5466 ds->semanticRun = PASSsemanticdone;
5467
5468 if (Dsymbol *sx = ds->overnext)
5469 {
5470 ds->overnext = NULL;
5471
5472 if (!ds->overloadInsert(sx))
5473 ScopeDsymbol::multiplyDefined(Loc(), sx, ds);
5474 }
5475 sc->flags &= ~SCOPEalias;
5476 }
5477
5478
5479 /*************************************
5480 * Does semantic analysis on the public face of declarations.
5481 */
5482 void dsymbolSemantic(Dsymbol *dsym, Scope *sc)
5483 {
5484 DsymbolSemanticVisitor v(sc);
5485 dsym->accept(&v);
5486 }