1 
2 /* Compiler implementation of the D programming language
3  * Copyright (C) 1999-2019 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  * https://github.com/D-Programming-Language/dmd/blob/master/src/declaration.c
9  */
10 
11 #include "root/dsystem.h"
12 #include "root/checkedint.h"
13 
14 #include "errors.h"
15 #include "init.h"
16 #include "declaration.h"
17 #include "attrib.h"
18 #include "mtype.h"
19 #include "template.h"
20 #include "scope.h"
21 #include "aggregate.h"
22 #include "module.h"
23 #include "import.h"
24 #include "id.h"
25 #include "expression.h"
26 #include "statement.h"
27 #include "ctfe.h"
28 #include "target.h"
29 #include "hdrgen.h"
30 
31 bool checkNestedRef(Dsymbol *s, Dsymbol *p);
32 VarDeclaration *copyToTemp(StorageClass stc, const char *name, Expression *e);
33 Expression *semantic(Expression *e, Scope *sc);
34 Initializer *inferType(Initializer *init, Scope *sc);
35 Initializer *semantic(Initializer *init, Scope *sc, Type *t, NeedInterpret needInterpret);
36 
37 /************************************
38  * Check to see the aggregate type is nested and its context pointer is
39  * accessible from the current scope.
40  * Returns true if error occurs.
41  */
42 bool checkFrameAccess(Loc loc, Scope *sc, AggregateDeclaration *ad, size_t iStart = 0)
43 {
44     Dsymbol *sparent = ad->toParent2();
45     Dsymbol *s = sc->func;
46     if (ad->isNested() && s)
47     {
48         //printf("ad = %p %s [%s], parent:%p\n", ad, ad->toChars(), ad->loc.toChars(), ad->parent);
49         //printf("sparent = %p %s [%s], parent: %s\n", sparent, sparent->toChars(), sparent->loc.toChars(), sparent->parent->toChars());
50         if (checkNestedRef(s, sparent))
51         {
52             error(loc, "cannot access frame pointer of %s", ad->toPrettyChars());
53             return true;
54         }
55     }
56 
57     bool result = false;
58     for (size_t i = iStart; i < ad->fields.dim; i++)
59     {
60         VarDeclaration *vd = ad->fields[i];
61         Type *tb = vd->type->baseElemOf();
62         if (tb->ty == Tstruct)
63         {
64             result |= checkFrameAccess(loc, sc, ((TypeStruct *)tb)->sym);
65         }
66     }
67     return result;
68 }
69 
70 /********************************* Declaration ****************************/
71 
Declaration(Identifier * id)72 Declaration::Declaration(Identifier *id)
73     : Dsymbol(id)
74 {
75     type = NULL;
76     originalType = NULL;
77     storage_class = STCundefined;
78     protection = Prot(PROTundefined);
79     linkage = LINKdefault;
80     inuse = 0;
81     mangleOverride = NULL;
82 }
83 
semantic(Scope *)84 void Declaration::semantic(Scope *)
85 {
86 }
87 
kind()88 const char *Declaration::kind() const
89 {
90     return "declaration";
91 }
92 
size(Loc)93 d_uns64 Declaration::size(Loc)
94 {
95     assert(type);
96     return type->size();
97 }
98 
isDelete()99 bool Declaration::isDelete()
100 {
101     return false;
102 }
103 
isDataseg()104 bool Declaration::isDataseg()
105 {
106     return false;
107 }
108 
isThreadlocal()109 bool Declaration::isThreadlocal()
110 {
111     return false;
112 }
113 
isCodeseg()114 bool Declaration::isCodeseg() const
115 {
116     return false;
117 }
118 
prot()119 Prot Declaration::prot()
120 {
121     return protection;
122 }
123 
124 /*************************************
125  * Check to see if declaration can be modified in this context (sc).
126  * Issue error if not.
127  */
128 
checkModify(Loc loc,Scope * sc,Type *,Expression * e1,int flag)129 int Declaration::checkModify(Loc loc, Scope *sc, Type *, Expression *e1, int flag)
130 {
131     VarDeclaration *v = isVarDeclaration();
132     if (v && v->canassign)
133         return 2;
134 
135     if (isParameter() || isResult())
136     {
137         for (Scope *scx = sc; scx; scx = scx->enclosing)
138         {
139             if (scx->func == parent && (scx->flags & SCOPEcontract))
140             {
141                 const char *s = isParameter() && parent->ident != Id::ensure ? "parameter" : "result";
142                 if (!flag) error(loc, "cannot modify %s '%s' in contract", s, toChars());
143                 return 2;   // do not report type related errors
144             }
145         }
146     }
147 
148     if (v && (isCtorinit() || isField()))
149     {
150         // It's only modifiable if inside the right constructor
151         if ((storage_class & (STCforeach | STCref)) == (STCforeach | STCref))
152             return 2;
153         return modifyFieldVar(loc, sc, v, e1) ? 2 : 1;
154     }
155     return 1;
156 }
157 
search(const Loc & loc,Identifier * ident,int flags)158 Dsymbol *Declaration::search(const Loc &loc, Identifier *ident, int flags)
159 {
160     Dsymbol *s = Dsymbol::search(loc, ident, flags);
161     if (!s && type)
162     {
163         s = type->toDsymbol(_scope);
164         if (s)
165             s = s->search(loc, ident, flags);
166     }
167     return s;
168 }
169 
170 
171 /********************************* TupleDeclaration ****************************/
172 
TupleDeclaration(Loc loc,Identifier * id,Objects * objects)173 TupleDeclaration::TupleDeclaration(Loc loc, Identifier *id, Objects *objects)
174     : Declaration(id)
175 {
176     this->loc = loc;
177     this->type = NULL;
178     this->objects = objects;
179     this->isexp = false;
180     this->tupletype = NULL;
181 }
182 
syntaxCopy(Dsymbol *)183 Dsymbol *TupleDeclaration::syntaxCopy(Dsymbol *)
184 {
185     assert(0);
186     return NULL;
187 }
188 
kind()189 const char *TupleDeclaration::kind() const
190 {
191     return "tuple";
192 }
193 
getType()194 Type *TupleDeclaration::getType()
195 {
196     /* If this tuple represents a type, return that type
197      */
198 
199     //printf("TupleDeclaration::getType() %s\n", toChars());
200     if (isexp)
201         return NULL;
202     if (!tupletype)
203     {
204         /* It's only a type tuple if all the Object's are types
205          */
206         for (size_t i = 0; i < objects->dim; i++)
207         {
208             RootObject *o = (*objects)[i];
209             if (o->dyncast() != DYNCAST_TYPE)
210             {
211                 //printf("\tnot[%d], %p, %d\n", i, o, o->dyncast());
212                 return NULL;
213             }
214         }
215 
216         /* We know it's a type tuple, so build the TypeTuple
217          */
218         Types *types = (Types *)objects;
219         Parameters *args = new Parameters();
220         args->setDim(objects->dim);
221         OutBuffer buf;
222         int hasdeco = 1;
223         for (size_t i = 0; i < types->dim; i++)
224         {
225             Type *t = (*types)[i];
226             //printf("type = %s\n", t->toChars());
227             Parameter *arg = new Parameter(0, t, NULL, NULL);
228             (*args)[i] = arg;
229             if (!t->deco)
230                 hasdeco = 0;
231         }
232 
233         tupletype = new TypeTuple(args);
234         if (hasdeco)
235             return tupletype->semantic(Loc(), NULL);
236     }
237 
238     return tupletype;
239 }
240 
toAlias2()241 Dsymbol *TupleDeclaration::toAlias2()
242 {
243     //printf("TupleDeclaration::toAlias2() '%s' objects = %s\n", toChars(), objects->toChars());
244 
245     for (size_t i = 0; i < objects->dim; i++)
246     {
247         RootObject *o = (*objects)[i];
248         if (Dsymbol *s = isDsymbol(o))
249         {
250             s = s->toAlias2();
251             (*objects)[i] = s;
252         }
253     }
254     return this;
255 }
256 
needThis()257 bool TupleDeclaration::needThis()
258 {
259     //printf("TupleDeclaration::needThis(%s)\n", toChars());
260     for (size_t i = 0; i < objects->dim; i++)
261     {
262         RootObject *o = (*objects)[i];
263         if (o->dyncast() == DYNCAST_EXPRESSION)
264         {
265             Expression *e = (Expression *)o;
266             if (e->op == TOKdsymbol)
267             {
268                 DsymbolExp *ve = (DsymbolExp *)e;
269                 Declaration *d = ve->s->isDeclaration();
270                 if (d && d->needThis())
271                 {
272                     return true;
273                 }
274             }
275         }
276     }
277     return false;
278 }
279 
280 /********************************* AliasDeclaration ****************************/
281 
AliasDeclaration(Loc loc,Identifier * id,Type * type)282 AliasDeclaration::AliasDeclaration(Loc loc, Identifier *id, Type *type)
283     : Declaration(id)
284 {
285     //printf("AliasDeclaration(id = '%s', type = %p)\n", id->toChars(), type);
286     //printf("type = '%s'\n", type->toChars());
287     this->loc = loc;
288     this->type = type;
289     this->aliassym = NULL;
290     this->_import = NULL;
291     this->overnext = NULL;
292     assert(type);
293 }
294 
AliasDeclaration(Loc loc,Identifier * id,Dsymbol * s)295 AliasDeclaration::AliasDeclaration(Loc loc, Identifier *id, Dsymbol *s)
296     : Declaration(id)
297 {
298     //printf("AliasDeclaration(id = '%s', s = %p)\n", id->toChars(), s);
299     assert(s != this);
300     this->loc = loc;
301     this->type = NULL;
302     this->aliassym = s;
303     this->_import = NULL;
304     this->overnext = NULL;
305     assert(s);
306 }
307 
create(Loc loc,Identifier * id,Type * type)308 AliasDeclaration *AliasDeclaration::create(Loc loc, Identifier *id, Type *type)
309 {
310     return new AliasDeclaration(loc, id, type);
311 }
312 
syntaxCopy(Dsymbol * s)313 Dsymbol *AliasDeclaration::syntaxCopy(Dsymbol *s)
314 {
315     //printf("AliasDeclaration::syntaxCopy()\n");
316     assert(!s);
317     AliasDeclaration *sa =
318         type ? new AliasDeclaration(loc, ident, type->syntaxCopy())
319              : new AliasDeclaration(loc, ident, aliassym->syntaxCopy(NULL));
320     sa->storage_class = storage_class;
321     return sa;
322 }
323 
semantic(Scope * sc)324 void AliasDeclaration::semantic(Scope *sc)
325 {
326     if (semanticRun >= PASSsemanticdone)
327         return;
328     assert(semanticRun <= PASSsemantic);
329 
330     storage_class |= sc->stc & STCdeprecated;
331     protection = sc->protection;
332     userAttribDecl = sc->userAttribDecl;
333 
334     if (!sc->func && inNonRoot())
335         return;
336 
337     aliasSemantic(sc);
338 }
339 
aliasSemantic(Scope * sc)340 void AliasDeclaration::aliasSemantic(Scope *sc)
341 {
342     //printf("AliasDeclaration::semantic() %s\n", toChars());
343     // TypeTraits needs to know if it's located in an AliasDeclaration
344     sc->flags |= SCOPEalias;
345 
346     if (aliassym)
347     {
348         FuncDeclaration *fd = aliassym->isFuncLiteralDeclaration();
349         TemplateDeclaration *td = aliassym->isTemplateDeclaration();
350         if (fd || (td && td->literal))
351         {
352             if (fd && fd->semanticRun >= PASSsemanticdone)
353             {
354                 sc->flags &= ~SCOPEalias;
355                 return;
356             }
357 
358             Expression *e = new FuncExp(loc, aliassym);
359             e = ::semantic(e, sc);
360             if (e->op == TOKfunction)
361             {
362                 FuncExp *fe = (FuncExp *)e;
363                 aliassym = fe->td ? (Dsymbol *)fe->td : fe->fd;
364             }
365             else
366             {
367                 aliassym = NULL;
368                 type = Type::terror;
369             }
370             sc->flags &= ~SCOPEalias;
371             return;
372         }
373 
374         if (aliassym->isTemplateInstance())
375             aliassym->semantic(sc);
376         sc->flags &= ~SCOPEalias;
377         return;
378     }
379     inuse = 1;
380 
381     // Given:
382     //  alias foo.bar.abc def;
383     // it is not knowable from the syntax whether this is an alias
384     // for a type or an alias for a symbol. It is up to the semantic()
385     // pass to distinguish.
386     // If it is a type, then type is set and getType() will return that
387     // type. If it is a symbol, then aliassym is set and type is NULL -
388     // toAlias() will return aliasssym.
389 
390     unsigned int errors = global.errors;
391     Type *oldtype = type;
392 
393     // Ungag errors when not instantiated DeclDefs scope alias
394     Ungag ungag(global.gag);
395     //printf("%s parent = %s, gag = %d, instantiated = %d\n", toChars(), parent, global.gag, isInstantiated());
396     if (parent && global.gag && !isInstantiated() && !toParent2()->isFuncDeclaration())
397     {
398         //printf("%s type = %s\n", toPrettyChars(), type->toChars());
399         global.gag = 0;
400     }
401 
402     /* This section is needed because Type::resolve() will:
403      *   const x = 3;
404      *   alias y = x;
405      * try to convert identifier x to 3.
406      */
407     Dsymbol *s = type->toDsymbol(sc);
408     if (errors != global.errors)
409     {
410         s = NULL;
411         type = Type::terror;
412     }
413     if (s && s == this)
414     {
415         error("cannot resolve");
416         s = NULL;
417         type = Type::terror;
418     }
419     if (!s || !s->isEnumMember())
420     {
421         Type *t;
422         Expression *e;
423         Scope *sc2 = sc;
424         if (storage_class & (STCref | STCnothrow | STCnogc | STCpure | STCdisable))
425         {
426             // For 'ref' to be attached to function types, and picked
427             // up by Type::resolve(), it has to go into sc.
428             sc2 = sc->push();
429             sc2->stc |= storage_class & (STCref | STCnothrow | STCnogc | STCpure | STCshared | STCdisable);
430         }
431         type = type->addSTC(storage_class);
432         type->resolve(loc, sc2, &e, &t, &s);
433         if (sc2 != sc)
434             sc2->pop();
435 
436         if (e)  // Try to convert Expression to Dsymbol
437         {
438             s = getDsymbol(e);
439             if (!s)
440             {
441                 if (e->op != TOKerror)
442                     error("cannot alias an expression %s", e->toChars());
443                 t = Type::terror;
444             }
445         }
446         type = t;
447     }
448     if (s == this)
449     {
450         assert(global.errors);
451         type = Type::terror;
452         s = NULL;
453     }
454     if (!s) // it's a type alias
455     {
456         //printf("alias %s resolved to type %s\n", toChars(), type->toChars());
457         type = type->semantic(loc, sc);
458         aliassym = NULL;
459     }
460     else    // it's a symbolic alias
461     {
462         //printf("alias %s resolved to %s %s\n", toChars(), s->kind(), s->toChars());
463         type = NULL;
464         aliassym = s;
465     }
466     if (global.gag && errors != global.errors)
467     {
468         type = oldtype;
469         aliassym = NULL;
470     }
471     inuse = 0;
472     semanticRun = PASSsemanticdone;
473 
474     if (Dsymbol *sx = overnext)
475     {
476         overnext = NULL;
477 
478         if (!overloadInsert(sx))
479             ScopeDsymbol::multiplyDefined(Loc(), sx, this);
480     }
481     sc->flags &= ~SCOPEalias;
482 }
483 
overloadInsert(Dsymbol * s)484 bool AliasDeclaration::overloadInsert(Dsymbol *s)
485 {
486     //printf("[%s] AliasDeclaration::overloadInsert('%s') s = %s %s @ [%s]\n",
487     //    loc.toChars(), toChars(), s->kind(), s->toChars(), s->loc.toChars());
488 
489     /** Aliases aren't overloadable themselves, but if their Aliasee is
490      *  overloadable they are converted to an overloadable Alias (either
491      *  FuncAliasDeclaration or OverDeclaration).
492      *
493      *  This is done by moving the Aliasee into such an overloadable alias
494      *  which is then used to replace the existing Aliasee. The original
495      *  Alias (_this_) remains a useless shell.
496      *
497      *  This is a horrible mess. It was probably done to avoid replacing
498      *  existing AST nodes and references, but it needs a major
499      *  simplification b/c it's too complex to maintain.
500      *
501      *  A simpler approach might be to merge any colliding symbols into a
502      *  simple Overload class (an array) and then later have that resolve
503      *  all collisions.
504      */
505     if (semanticRun >= PASSsemanticdone)
506     {
507         /* Semantic analysis is already finished, and the aliased entity
508          * is not overloadable.
509          */
510         if (type)
511             return false;
512 
513         /* When s is added in member scope by static if, mixin("code") or others,
514          * aliassym is determined already. See the case in: test/compilable/test61.d
515          */
516         Dsymbol *sa = aliassym->toAlias();
517         if (FuncDeclaration *fd = sa->isFuncDeclaration())
518         {
519             FuncAliasDeclaration *fa = new FuncAliasDeclaration(ident, fd);
520             fa->protection = protection;
521             fa->parent = parent;
522             aliassym = fa;
523             return aliassym->overloadInsert(s);
524         }
525         if (TemplateDeclaration *td = sa->isTemplateDeclaration())
526         {
527             OverDeclaration *od = new OverDeclaration(ident, td);
528             od->protection = protection;
529             od->parent = parent;
530             aliassym = od;
531             return aliassym->overloadInsert(s);
532         }
533         if (OverDeclaration *od = sa->isOverDeclaration())
534         {
535             if (sa->ident != ident || sa->parent != parent)
536             {
537                 od = new OverDeclaration(ident, od);
538                 od->protection = protection;
539                 od->parent = parent;
540                 aliassym = od;
541             }
542             return od->overloadInsert(s);
543         }
544         if (OverloadSet *os = sa->isOverloadSet())
545         {
546             if (sa->ident != ident || sa->parent != parent)
547             {
548                 os = new OverloadSet(ident, os);
549                 // TODO: protection is lost here b/c OverloadSets have no protection attribute
550                 // Might no be a practical issue, b/c the code below fails to resolve the overload anyhow.
551                 // ----
552                 // module os1;
553                 // import a, b;
554                 // private alias merged = foo; // private alias to overload set of a.foo and b.foo
555                 // ----
556                 // module os2;
557                 // import a, b;
558                 // public alias merged = bar; // public alias to overload set of a.bar and b.bar
559                 // ----
560                 // module bug;
561                 // import os1, os2;
562                 // void test() { merged(123); } // should only look at os2.merged
563                 //
564                 // os.protection = protection;
565                 os->parent = parent;
566                 aliassym = os;
567             }
568             os->push(s);
569             return true;
570         }
571         return false;
572     }
573 
574     /* Don't know yet what the aliased symbol is, so assume it can
575      * be overloaded and check later for correctness.
576      */
577     if (overnext)
578         return overnext->overloadInsert(s);
579     if (s == this)
580         return true;
581     overnext = s;
582     return true;
583 }
584 
kind()585 const char *AliasDeclaration::kind() const
586 {
587     return "alias";
588 }
589 
getType()590 Type *AliasDeclaration::getType()
591 {
592     if (type)
593         return type;
594     return toAlias()->getType();
595 }
596 
toAlias()597 Dsymbol *AliasDeclaration::toAlias()
598 {
599     //printf("[%s] AliasDeclaration::toAlias('%s', this = %p, aliassym = %p, kind = '%s', inuse = %d)\n",
600     //    loc.toChars(), toChars(), this, aliassym, aliassym ? aliassym->kind() : "", inuse);
601     assert(this != aliassym);
602     //static int count; if (++count == 10) *(char*)0=0;
603     if (inuse == 1 && type && _scope)
604     {
605         inuse = 2;
606         unsigned olderrors = global.errors;
607         Dsymbol *s = type->toDsymbol(_scope);
608         //printf("[%s] type = %s, s = %p, this = %p\n", loc.toChars(), type->toChars(), s, this);
609         if (global.errors != olderrors)
610             goto Lerr;
611         if (s)
612         {
613             s = s->toAlias();
614             if (global.errors != olderrors)
615                 goto Lerr;
616             aliassym = s;
617             inuse = 0;
618         }
619         else
620         {
621             Type *t = type->semantic(loc, _scope);
622             if (t->ty == Terror)
623                 goto Lerr;
624             if (global.errors != olderrors)
625                 goto Lerr;
626             //printf("t = %s\n", t->toChars());
627             inuse = 0;
628         }
629     }
630     if (inuse)
631     {
632         error("recursive alias declaration");
633 
634     Lerr:
635         // Avoid breaking "recursive alias" state during errors gagged
636         if (global.gag)
637             return this;
638 
639         aliassym = new AliasDeclaration(loc, ident, Type::terror);
640         type = Type::terror;
641         return aliassym;
642     }
643 
644     if (semanticRun >= PASSsemanticdone)
645     {
646         // semantic is already done.
647 
648         // Do not see aliassym !is null, because of lambda aliases.
649 
650         // Do not see type.deco !is null, even so "alias T = const int;` needs
651         // semantic analysis to take the storage class `const` as type qualifier.
652     }
653     else
654     {
655         if (_import && _import->_scope)
656         {
657             /* If this is an internal alias for selective/renamed import,
658              * load the module first.
659              */
660             _import->semantic(NULL);
661         }
662         if (_scope)
663         {
664             aliasSemantic(_scope);
665         }
666     }
667 
668     inuse = 1;
669     Dsymbol *s = aliassym ? aliassym->toAlias() : this;
670     inuse = 0;
671     return s;
672 }
673 
toAlias2()674 Dsymbol *AliasDeclaration::toAlias2()
675 {
676     if (inuse)
677     {
678         error("recursive alias declaration");
679         return this;
680     }
681     inuse = 1;
682     Dsymbol *s  = aliassym ? aliassym->toAlias2() : this;
683     inuse = 0;
684     return s;
685 }
686 
isOverloadable()687 bool AliasDeclaration::isOverloadable()
688 {
689     // assume overloadable until alias is resolved
690     return semanticRun < PASSsemanticdone ||
691         (aliassym && aliassym->isOverloadable());
692 }
693 
694 /****************************** OverDeclaration **************************/
695 
OverDeclaration(Identifier * ident,Dsymbol * s,bool hasOverloads)696 OverDeclaration::OverDeclaration(Identifier *ident, Dsymbol *s, bool hasOverloads)
697     : Declaration(ident)
698 {
699     this->overnext = NULL;
700     this->aliassym = s;
701 
702     this->hasOverloads = hasOverloads;
703     if (hasOverloads)
704     {
705         if (OverDeclaration *od = aliassym->isOverDeclaration())
706             this->hasOverloads = od->hasOverloads;
707     }
708     else
709     {
710         // for internal use
711         assert(!aliassym->isOverDeclaration());
712     }
713 }
714 
kind()715 const char *OverDeclaration::kind() const
716 {
717     return "overload alias";    // todo
718 }
719 
semantic(Scope *)720 void OverDeclaration::semantic(Scope *)
721 {
722 }
723 
equals(RootObject * o)724 bool OverDeclaration::equals(RootObject *o)
725 {
726     if (this == o)
727         return true;
728 
729     Dsymbol *s = isDsymbol(o);
730     if (!s)
731         return false;
732 
733     OverDeclaration *od1 = this;
734     if (OverDeclaration *od2 = s->isOverDeclaration())
735     {
736         return od1->aliassym->equals(od2->aliassym) &&
737                od1->hasOverloads == od2->hasOverloads;
738     }
739     if (aliassym == s)
740     {
741         if (hasOverloads)
742             return true;
743         if (FuncDeclaration *fd = s->isFuncDeclaration())
744         {
745             return fd->isUnique() != NULL;
746         }
747         if (TemplateDeclaration *td = s->isTemplateDeclaration())
748         {
749             return td->overnext == NULL;
750         }
751     }
752     return false;
753 }
754 
overloadInsert(Dsymbol * s)755 bool OverDeclaration::overloadInsert(Dsymbol *s)
756 {
757     //printf("OverDeclaration::overloadInsert('%s') aliassym = %p, overnext = %p\n", s->toChars(), aliassym, overnext);
758     if (overnext)
759         return overnext->overloadInsert(s);
760     if (s == this)
761         return true;
762     overnext = s;
763     return true;
764 }
765 
toAlias()766 Dsymbol *OverDeclaration::toAlias()
767 {
768     return this;
769 }
770 
isOverloadable()771 bool OverDeclaration::isOverloadable()
772 {
773     return true;
774 }
775 
isUnique()776 Dsymbol *OverDeclaration::isUnique()
777 {
778     if (!hasOverloads)
779     {
780         if (aliassym->isFuncDeclaration() ||
781             aliassym->isTemplateDeclaration())
782         {
783             return aliassym;
784         }
785     }
786 
787   struct ParamUniqueSym
788   {
789     static int fp(void *param, Dsymbol *s)
790     {
791         Dsymbol **ps = (Dsymbol **)param;
792         if (*ps)
793         {
794             *ps = NULL;
795             return 1;   // ambiguous, done
796         }
797         else
798         {
799             *ps = s;
800             return 0;
801         }
802     }
803   };
804     Dsymbol *result = NULL;
805     overloadApply(aliassym, &result, &ParamUniqueSym::fp);
806     return result;
807 }
808 
809 /********************************* VarDeclaration ****************************/
810 
VarDeclaration(Loc loc,Type * type,Identifier * id,Initializer * init)811 VarDeclaration::VarDeclaration(Loc loc, Type *type, Identifier *id, Initializer *init)
812     : Declaration(id)
813 {
814     //printf("VarDeclaration('%s')\n", id->toChars());
815     assert(id);
816     assert(type || init);
817     this->type = type;
818     this->_init = init;
819     this->loc = loc;
820     offset = 0;
821     isargptr = false;
822     alignment = 0;
823     ctorinit = 0;
824     aliassym = NULL;
825     onstack = false;
826     mynew = false;
827     canassign = 0;
828     overlapped = false;
829     overlapUnsafe = false;
830     doNotInferScope = false;
831     isdataseg = 0;
832     lastVar = NULL;
833     endlinnum = 0;
834     ctfeAdrOnStack = -1;
835     edtor = NULL;
836     range = NULL;
837 
838     static unsigned nextSequenceNumber = 0;
839     this->sequenceNumber = ++nextSequenceNumber;
840 }
841 
create(Loc loc,Type * type,Identifier * id,Initializer * init)842 VarDeclaration *VarDeclaration::create(Loc loc, Type *type, Identifier *id, Initializer *init)
843 {
844     return new VarDeclaration(loc, type, id, init);
845 }
846 
syntaxCopy(Dsymbol * s)847 Dsymbol *VarDeclaration::syntaxCopy(Dsymbol *s)
848 {
849     //printf("VarDeclaration::syntaxCopy(%s)\n", toChars());
850     assert(!s);
851     VarDeclaration *v = new VarDeclaration(loc,
852             type ? type->syntaxCopy() : NULL,
853             ident,
854             _init ? _init->syntaxCopy() : NULL);
855     v->storage_class = storage_class;
856     return v;
857 }
858 
859 
semantic(Scope * sc)860 void VarDeclaration::semantic(Scope *sc)
861 {
862 //    if (semanticRun > PASSinit)
863 //      return;
864 //    semanticRun = PASSsemantic;
865 
866     if (semanticRun >= PASSsemanticdone)
867         return;
868 
869     Scope *scx = NULL;
870     if (_scope)
871     {
872         sc = _scope;
873         scx = sc;
874         _scope = NULL;
875     }
876 
877     if (!sc)
878         return;
879 
880     semanticRun = PASSsemantic;
881 
882     /* Pick up storage classes from context, but except synchronized,
883      * override, abstract, and final.
884      */
885     storage_class |= (sc->stc & ~(STCsynchronized | STCoverride | STCabstract | STCfinal));
886     if (storage_class & STCextern && _init)
887         error("extern symbols cannot have initializers");
888 
889     userAttribDecl = sc->userAttribDecl;
890 
891     AggregateDeclaration *ad = isThis();
892     if (ad)
893         storage_class |= ad->storage_class & STC_TYPECTOR;
894 
895     /* If auto type inference, do the inference
896      */
897     int inferred = 0;
898     if (!type)
899     {
900         inuse++;
901 
902         // Infering the type requires running semantic,
903         // so mark the scope as ctfe if required
904         bool needctfe = (storage_class & (STCmanifest | STCstatic)) != 0;
905         if (needctfe) sc = sc->startCTFE();
906 
907         //printf("inferring type for %s with init %s\n", toChars(), _init->toChars());
908         _init = inferType(_init, sc);
909         type = initializerToExpression(_init)->type;
910 
911         if (needctfe) sc = sc->endCTFE();
912 
913         inuse--;
914         inferred = 1;
915 
916         /* This is a kludge to support the existing syntax for RAII
917          * declarations.
918          */
919         storage_class &= ~STCauto;
920         originalType = type->syntaxCopy();
921     }
922     else
923     {
924         if (!originalType)
925             originalType = type->syntaxCopy();
926 
927         /* Prefix function attributes of variable declaration can affect
928          * its type:
929          *      pure nothrow void function() fp;
930          *      static assert(is(typeof(fp) == void function() pure nothrow));
931          */
932         Scope *sc2 = sc->push();
933         sc2->stc |= (storage_class & STC_FUNCATTR);
934         inuse++;
935         type = type->semantic(loc, sc2);
936         inuse--;
937         sc2->pop();
938     }
939     //printf(" semantic type = %s\n", type ? type->toChars() : "null");
940     if (type->ty == Terror)
941         errors = true;
942 
943     type->checkDeprecated(loc, sc);
944     linkage = sc->linkage;
945     this->parent = sc->parent;
946     //printf("this = %p, parent = %p, '%s'\n", this, parent, parent->toChars());
947     protection = sc->protection;
948 
949     /* If scope's alignment is the default, use the type's alignment,
950      * otherwise the scope overrrides.
951      */
952     alignment = sc->alignment();
953     if (alignment == STRUCTALIGN_DEFAULT)
954         alignment = type->alignment();          // use type's alignment
955 
956     //printf("sc->stc = %x\n", sc->stc);
957     //printf("storage_class = x%x\n", storage_class);
958 
959     if (global.params.vcomplex)
960         type->checkComplexTransition(loc);
961 
962     // Calculate type size + safety checks
963     if (sc->func && !sc->intypeof)
964     {
965         if ((storage_class & STCgshared) && !isMember())
966         {
967             if (sc->func->setUnsafe())
968                 error("__gshared not allowed in safe functions; use shared");
969         }
970     }
971 
972     Dsymbol *parent = toParent();
973 
974     Type *tb = type->toBasetype();
975     Type *tbn = tb->baseElemOf();
976     if (tb->ty == Tvoid && !(storage_class & STClazy))
977     {
978         if (inferred)
979         {
980             error("type %s is inferred from initializer %s, and variables cannot be of type void",
981                 type->toChars(), _init->toChars());
982         }
983         else
984             error("variables cannot be of type void");
985         type = Type::terror;
986         tb = type;
987     }
988     if (tb->ty == Tfunction)
989     {
990         error("cannot be declared to be a function");
991         type = Type::terror;
992         tb = type;
993     }
994     if (tb->ty == Tstruct)
995     {
996         TypeStruct *ts = (TypeStruct *)tb;
997         if (!ts->sym->members)
998         {
999             error("no definition of struct %s", ts->toChars());
1000         }
1001     }
1002     if ((storage_class & STCauto) && !inferred)
1003         error("storage class 'auto' has no effect if type is not inferred, did you mean 'scope'?");
1004 
1005     if (tb->ty == Ttuple)
1006     {
1007         /* Instead, declare variables for each of the tuple elements
1008          * and add those.
1009          */
1010         TypeTuple *tt = (TypeTuple *)tb;
1011         size_t nelems = Parameter::dim(tt->arguments);
1012         Expression *ie = (_init && !_init->isVoidInitializer()) ? initializerToExpression(_init) : NULL;
1013         if (ie)
1014             ie = ::semantic(ie, sc);
1015 
1016         if (nelems > 0 && ie)
1017         {
1018             Expressions *iexps = new Expressions();
1019             iexps->push(ie);
1020 
1021             Expressions *exps = new Expressions();
1022 
1023             for (size_t pos = 0; pos < iexps->dim; pos++)
1024             {
1025             Lexpand1:
1026                 Expression *e = (*iexps)[pos];
1027                 Parameter *arg = Parameter::getNth(tt->arguments, pos);
1028                 arg->type = arg->type->semantic(loc, sc);
1029                 //printf("[%d] iexps->dim = %d, ", pos, iexps->dim);
1030                 //printf("e = (%s %s, %s), ", Token::tochars[e->op], e->toChars(), e->type->toChars());
1031                 //printf("arg = (%s, %s)\n", arg->toChars(), arg->type->toChars());
1032 
1033                 if (e != ie)
1034                 {
1035                 if (iexps->dim > nelems)
1036                     goto Lnomatch;
1037                 if (e->type->implicitConvTo(arg->type))
1038                     continue;
1039                 }
1040 
1041                 if (e->op == TOKtuple)
1042                 {
1043                     TupleExp *te = (TupleExp *)e;
1044                     if (iexps->dim - 1 + te->exps->dim > nelems)
1045                         goto Lnomatch;
1046 
1047                     iexps->remove(pos);
1048                     iexps->insert(pos, te->exps);
1049                     (*iexps)[pos] = Expression::combine(te->e0, (*iexps)[pos]);
1050                     goto Lexpand1;
1051                 }
1052                 else if (isAliasThisTuple(e))
1053                 {
1054                     VarDeclaration *v = copyToTemp(0, "__tup", e);
1055                     v->semantic(sc);
1056                     VarExp *ve = new VarExp(loc, v);
1057                     ve->type = e->type;
1058 
1059                     exps->setDim(1);
1060                     (*exps)[0] = ve;
1061                     expandAliasThisTuples(exps, 0);
1062 
1063                     for (size_t u = 0; u < exps->dim ; u++)
1064                     {
1065                     Lexpand2:
1066                         Expression *ee = (*exps)[u];
1067                         arg = Parameter::getNth(tt->arguments, pos + u);
1068                         arg->type = arg->type->semantic(loc, sc);
1069                         //printf("[%d+%d] exps->dim = %d, ", pos, u, exps->dim);
1070                         //printf("ee = (%s %s, %s), ", Token::tochars[ee->op], ee->toChars(), ee->type->toChars());
1071                         //printf("arg = (%s, %s)\n", arg->toChars(), arg->type->toChars());
1072 
1073                         size_t iexps_dim = iexps->dim - 1 + exps->dim;
1074                         if (iexps_dim > nelems)
1075                             goto Lnomatch;
1076                         if (ee->type->implicitConvTo(arg->type))
1077                             continue;
1078 
1079                         if (expandAliasThisTuples(exps, u) != -1)
1080                             goto Lexpand2;
1081                     }
1082 
1083                     if ((*exps)[0] != ve)
1084                     {
1085                         Expression *e0 = (*exps)[0];
1086                         (*exps)[0] = new CommaExp(loc, new DeclarationExp(loc, v), e0);
1087                         (*exps)[0]->type = e0->type;
1088 
1089                         iexps->remove(pos);
1090                         iexps->insert(pos, exps);
1091                         goto Lexpand1;
1092                     }
1093                 }
1094             }
1095             if (iexps->dim < nelems)
1096                 goto Lnomatch;
1097 
1098             ie = new TupleExp(_init->loc, iexps);
1099         }
1100 Lnomatch:
1101 
1102         if (ie && ie->op == TOKtuple)
1103         {
1104             TupleExp *te = (TupleExp *)ie;
1105             size_t tedim = te->exps->dim;
1106             if (tedim != nelems)
1107             {
1108                 ::error(loc, "tuple of %d elements cannot be assigned to tuple of %d elements", (int)tedim, (int)nelems);
1109                 for (size_t u = tedim; u < nelems; u++) // fill dummy expression
1110                     te->exps->push(new ErrorExp());
1111             }
1112         }
1113 
1114         Objects *exps = new Objects();
1115         exps->setDim(nelems);
1116         for (size_t i = 0; i < nelems; i++)
1117         {
1118             Parameter *arg = Parameter::getNth(tt->arguments, i);
1119 
1120             OutBuffer buf;
1121             buf.printf("__%s_field_%llu", ident->toChars(), (ulonglong)i);
1122             const char *name = buf.extractString();
1123             Identifier *id = Identifier::idPool(name);
1124 
1125             Initializer *ti;
1126             if (ie)
1127             {
1128                 Expression *einit = ie;
1129                 if (ie->op == TOKtuple)
1130                 {
1131                     TupleExp *te = (TupleExp *)ie;
1132                     einit = (*te->exps)[i];
1133                     if (i == 0)
1134                         einit = Expression::combine(te->e0, einit);
1135                 }
1136                 ti = new ExpInitializer(einit->loc, einit);
1137             }
1138             else
1139                 ti = _init ? _init->syntaxCopy() : NULL;
1140 
1141             VarDeclaration *v = new VarDeclaration(loc, arg->type, id, ti);
1142             v->storage_class |= STCtemp | storage_class;
1143             if (arg->storageClass & STCparameter)
1144                 v->storage_class |= arg->storageClass;
1145             //printf("declaring field %s of type %s\n", v->toChars(), v->type->toChars());
1146             v->semantic(sc);
1147 
1148             if (sc->scopesym)
1149             {
1150                 //printf("adding %s to %s\n", v->toChars(), sc->scopesym->toChars());
1151                 if (sc->scopesym->members)
1152                     sc->scopesym->members->push(v);
1153             }
1154 
1155             Expression *e = new DsymbolExp(loc, v);
1156             (*exps)[i] = e;
1157         }
1158         TupleDeclaration *v2 = new TupleDeclaration(loc, ident, exps);
1159         v2->parent = this->parent;
1160         v2->isexp = true;
1161         aliassym = v2;
1162         semanticRun = PASSsemanticdone;
1163         return;
1164     }
1165 
1166     /* Storage class can modify the type
1167      */
1168     type = type->addStorageClass(storage_class);
1169 
1170     /* Adjust storage class to reflect type
1171      */
1172     if (type->isConst())
1173     {
1174         storage_class |= STCconst;
1175         if (type->isShared())
1176             storage_class |= STCshared;
1177     }
1178     else if (type->isImmutable())
1179         storage_class |= STCimmutable;
1180     else if (type->isShared())
1181         storage_class |= STCshared;
1182     else if (type->isWild())
1183         storage_class |= STCwild;
1184 
1185     if (StorageClass stc = storage_class & (STCsynchronized | STCoverride | STCabstract | STCfinal))
1186     {
1187         if (stc == STCfinal)
1188             error("cannot be final, perhaps you meant const?");
1189         else
1190         {
1191             OutBuffer buf;
1192             stcToBuffer(&buf, stc);
1193             error("cannot be %s", buf.peekString());
1194         }
1195         storage_class &= ~stc;  // strip off
1196     }
1197 
1198     if (storage_class & STCscope)
1199     {
1200         StorageClass stc = storage_class & (STCstatic | STCextern | STCmanifest | STCtls | STCgshared);
1201         if (stc)
1202         {
1203             OutBuffer buf;
1204             stcToBuffer(&buf, stc);
1205             error("cannot be 'scope' and '%s'", buf.peekString());
1206         }
1207         else if (isMember())
1208         {
1209             error("field cannot be 'scope'");
1210         }
1211         else if (!type->hasPointers())
1212         {
1213             storage_class &= ~STCscope;     // silently ignore; may occur in generic code
1214         }
1215     }
1216 
1217     if (storage_class & (STCstatic | STCextern | STCmanifest | STCtemplateparameter | STCtls | STCgshared | STCctfe))
1218     {
1219     }
1220     else
1221     {
1222         AggregateDeclaration *aad = parent->isAggregateDeclaration();
1223         if (aad)
1224         {
1225             if (global.params.vfield &&
1226                 storage_class & (STCconst | STCimmutable) && _init && !_init->isVoidInitializer())
1227             {
1228                 const char *s = (storage_class & STCimmutable) ? "immutable" : "const";
1229                 message(loc, "`%s.%s` is `%s` field", ad->toPrettyChars(), toChars(), s);
1230             }
1231             storage_class |= STCfield;
1232             if (tbn->ty == Tstruct && ((TypeStruct *)tbn)->sym->noDefaultCtor)
1233             {
1234                 if (!isThisDeclaration() && !_init)
1235                     aad->noDefaultCtor = true;
1236             }
1237         }
1238 
1239         InterfaceDeclaration *id = parent->isInterfaceDeclaration();
1240         if (id)
1241         {
1242             error("field not allowed in interface");
1243         }
1244         else if (aad && aad->sizeok == SIZEOKdone)
1245         {
1246             error("cannot be further field because it will change the determined %s size", aad->toChars());
1247         }
1248 
1249         /* Templates cannot add fields to aggregates
1250          */
1251         TemplateInstance *ti = parent->isTemplateInstance();
1252         if (ti)
1253         {
1254             // Take care of nested templates
1255             while (1)
1256             {
1257                 TemplateInstance *ti2 = ti->tempdecl->parent->isTemplateInstance();
1258                 if (!ti2)
1259                     break;
1260                 ti = ti2;
1261             }
1262 
1263             // If it's a member template
1264             AggregateDeclaration *ad2 = ti->tempdecl->isMember();
1265             if (ad2 && storage_class != STCundefined)
1266             {
1267                 error("cannot use template to add field to aggregate '%s'", ad2->toChars());
1268             }
1269         }
1270     }
1271 
1272     if ((storage_class & (STCref | STCparameter | STCforeach | STCtemp | STCresult)) == STCref && ident != Id::This)
1273     {
1274         error("only parameters or foreach declarations can be ref");
1275     }
1276 
1277     if (type->hasWild())
1278     {
1279         if (storage_class & (STCstatic | STCextern | STCtls | STCgshared | STCmanifest | STCfield) ||
1280             isDataseg()
1281             )
1282         {
1283             error("only parameters or stack based variables can be inout");
1284         }
1285         FuncDeclaration *func = sc->func;
1286         if (func)
1287         {
1288             if (func->fes)
1289                 func = func->fes->func;
1290             bool isWild = false;
1291             for (FuncDeclaration *fd = func; fd; fd = fd->toParent2()->isFuncDeclaration())
1292             {
1293                 if (((TypeFunction *)fd->type)->iswild)
1294                 {
1295                     isWild = true;
1296                     break;
1297                 }
1298             }
1299             if (!isWild)
1300             {
1301                 error("inout variables can only be declared inside inout functions");
1302             }
1303         }
1304     }
1305 
1306     if (!(storage_class & (STCctfe | STCref | STCresult)) && tbn->ty == Tstruct &&
1307         ((TypeStruct *)tbn)->sym->noDefaultCtor)
1308     {
1309         if (!_init)
1310         {
1311             if (isField())
1312             {
1313                 /* For fields, we'll check the constructor later to make sure it is initialized
1314                  */
1315                 storage_class |= STCnodefaultctor;
1316             }
1317             else if (storage_class & STCparameter)
1318                 ;
1319             else
1320                 error("default construction is disabled for type %s", type->toChars());
1321         }
1322     }
1323 
1324     FuncDeclaration *fd = parent->isFuncDeclaration();
1325     if (type->isscope() && !(storage_class & STCnodtor))
1326     {
1327         if (storage_class & (STCfield | STCout | STCref | STCstatic | STCmanifest | STCtls | STCgshared) || !fd)
1328         {
1329             error("globals, statics, fields, manifest constants, ref and out parameters cannot be scope");
1330         }
1331 
1332         if (!(storage_class & STCscope))
1333         {
1334             if (!(storage_class & STCparameter) && ident != Id::withSym)
1335                 error("reference to scope class must be scope");
1336         }
1337     }
1338 
1339     // Calculate type size + safety checks
1340     if (sc->func && !sc->intypeof)
1341     {
1342         if (_init && _init->isVoidInitializer() && type->hasPointers()) // get type size
1343         {
1344             if (sc->func->setUnsafe())
1345                 error("void initializers for pointers not allowed in safe functions");
1346         }
1347         else if (!_init &&
1348                  !(storage_class & (STCstatic | STCextern | STCtls | STCgshared | STCmanifest | STCfield | STCparameter)) &&
1349                  type->hasVoidInitPointers())
1350         {
1351             if (sc->func->setUnsafe())
1352                 error("void initializers for pointers not allowed in safe functions");
1353         }
1354     }
1355 
1356     if (!_init && !fd)
1357     {
1358         // If not mutable, initializable by constructor only
1359         storage_class |= STCctorinit;
1360     }
1361 
1362     if (_init)
1363         storage_class |= STCinit;     // remember we had an explicit initializer
1364     else if (storage_class & STCmanifest)
1365         error("manifest constants must have initializers");
1366 
1367     bool isBlit = false;
1368     d_uns64 sz = 0;
1369     if (!_init && !sc->inunion && !(storage_class & (STCstatic | STCgshared | STCextern)) && fd &&
1370         (!(storage_class & (STCfield | STCin | STCforeach | STCparameter | STCresult))
1371          || (storage_class & STCout)) &&
1372         (sz = type->size()) != 0)
1373     {
1374         // Provide a default initializer
1375         //printf("Providing default initializer for '%s'\n", toChars());
1376         if (sz == SIZE_INVALID && type->ty != Terror)
1377             error("size of type %s is invalid", type->toChars());
1378 
1379         Type *tv = type;
1380         while (tv->ty == Tsarray)    // Don't skip Tenum
1381             tv = tv->nextOf();
1382         if (tv->needsNested())
1383         {
1384             /* Nested struct requires valid enclosing frame pointer.
1385              * In StructLiteralExp::toElem(), it's calculated.
1386              */
1387             assert(tv->toBasetype()->ty == Tstruct);
1388             checkFrameAccess(loc, sc, ((TypeStruct *)tbn)->sym);
1389 
1390             Expression *e = tv->defaultInitLiteral(loc);
1391             e = new BlitExp(loc, new VarExp(loc, this), e);
1392             e = ::semantic(e, sc);
1393             _init = new ExpInitializer(loc, e);
1394             goto Ldtor;
1395         }
1396         if (tv->ty == Tstruct && ((TypeStruct *)tv)->sym->zeroInit == 1)
1397         {
1398             /* If a struct is all zeros, as a special case
1399              * set it's initializer to the integer 0.
1400              * In AssignExp::toElem(), we check for this and issue
1401              * a memset() to initialize the struct.
1402              * Must do same check in interpreter.
1403              */
1404             Expression *e = new IntegerExp(loc, 0, Type::tint32);
1405             e = new BlitExp(loc, new VarExp(loc, this), e);
1406             e->type = type;         // don't type check this, it would fail
1407             _init = new ExpInitializer(loc, e);
1408             goto Ldtor;
1409         }
1410         if (type->baseElemOf()->ty == Tvoid)
1411         {
1412             error("%s does not have a default initializer", type->toChars());
1413         }
1414         else if (Expression *e = type->defaultInit(loc))
1415         {
1416             _init = new ExpInitializer(loc, e);
1417         }
1418         // Default initializer is always a blit
1419         isBlit = true;
1420     }
1421 
1422     if (_init)
1423     {
1424         sc = sc->push();
1425         sc->stc &= ~(STC_TYPECTOR | STCpure | STCnothrow | STCnogc | STCref | STCdisable);
1426 
1427         ExpInitializer *ei = _init->isExpInitializer();
1428         if (ei)     // Bugzilla 13424: Preset the required type to fail in FuncLiteralDeclaration::semantic3
1429             ei->exp = inferType(ei->exp, type);
1430 
1431         // If inside function, there is no semantic3() call
1432         if (sc->func || sc->intypeof == 1)
1433         {
1434             // If local variable, use AssignExp to handle all the various
1435             // possibilities.
1436             if (fd &&
1437                 !(storage_class & (STCmanifest | STCstatic | STCtls | STCgshared | STCextern)) &&
1438                 !_init->isVoidInitializer())
1439             {
1440                 //printf("fd = '%s', var = '%s'\n", fd->toChars(), toChars());
1441                 if (!ei)
1442                 {
1443                     ArrayInitializer *ai = _init->isArrayInitializer();
1444                     Expression *e;
1445                     if (ai && tb->ty == Taarray)
1446                         e = ai->toAssocArrayLiteral();
1447                     else
1448                         e = initializerToExpression(_init);
1449                     if (!e)
1450                     {
1451                         // Run semantic, but don't need to interpret
1452                         _init = ::semantic(_init, sc, type, INITnointerpret);
1453                         e = initializerToExpression(_init);
1454                         if (!e)
1455                         {
1456                             error("is not a static and cannot have static initializer");
1457                             e = new ErrorExp();
1458                         }
1459                     }
1460                     ei = new ExpInitializer(_init->loc, e);
1461                     _init = ei;
1462                 }
1463 
1464                 Expression *exp = ei->exp;
1465                 Expression *e1 = new VarExp(loc, this);
1466                 if (isBlit)
1467                     exp = new BlitExp(loc, e1, exp);
1468                 else
1469                     exp = new ConstructExp(loc, e1, exp);
1470                 canassign++;
1471                 exp = ::semantic(exp, sc);
1472                 canassign--;
1473                 exp = exp->optimize(WANTvalue);
1474 
1475                 if (exp->op == TOKerror)
1476                 {
1477                     _init = new ErrorInitializer();
1478                     ei = NULL;
1479                 }
1480                 else
1481                     ei->exp = exp;
1482 
1483                 if (ei && isScope())
1484                 {
1485                     Expression *ex = ei->exp;
1486                     while (ex->op == TOKcomma)
1487                         ex = ((CommaExp *)ex)->e2;
1488                     if (ex->op == TOKblit || ex->op == TOKconstruct)
1489                         ex = ((AssignExp *)ex)->e2;
1490                     if (ex->op == TOKnew)
1491                     {
1492                         // See if initializer is a NewExp that can be allocated on the stack
1493                         NewExp *ne = (NewExp *)ex;
1494                         if (type->toBasetype()->ty == Tclass)
1495                         {
1496                             if (ne->newargs && ne->newargs->dim > 1)
1497                             {
1498                                 mynew = true;
1499                             }
1500                             else
1501                             {
1502                                 ne->onstack = true;
1503                                 onstack = true;
1504                             }
1505                         }
1506                     }
1507                     else if (ex->op == TOKfunction)
1508                     {
1509                         // or a delegate that doesn't escape a reference to the function
1510                         FuncDeclaration *f = ((FuncExp *)ex)->fd;
1511                         f->tookAddressOf--;
1512                     }
1513                 }
1514             }
1515             else
1516             {
1517                 // Bugzilla 14166: Don't run CTFE for the temporary variables inside typeof
1518                 _init = ::semantic(_init, sc, type, sc->intypeof == 1 ? INITnointerpret : INITinterpret);
1519             }
1520         }
1521         else if (parent->isAggregateDeclaration())
1522         {
1523             _scope = scx ? scx : sc->copy();
1524             _scope->setNoFree();
1525         }
1526         else if (storage_class & (STCconst | STCimmutable | STCmanifest) ||
1527                  type->isConst() || type->isImmutable())
1528         {
1529             /* Because we may need the results of a const declaration in a
1530              * subsequent type, such as an array dimension, before semantic2()
1531              * gets ordinarily run, try to run semantic2() now.
1532              * Ignore failure.
1533              */
1534 
1535             if (!inferred)
1536             {
1537                 unsigned errors = global.errors;
1538                 inuse++;
1539                 if (ei)
1540                 {
1541                     Expression *exp = ei->exp->syntaxCopy();
1542 
1543                     bool needctfe = isDataseg() || (storage_class & STCmanifest);
1544                     if (needctfe) sc = sc->startCTFE();
1545                     exp = ::semantic(exp, sc);
1546                     exp = resolveProperties(sc, exp);
1547                     if (needctfe) sc = sc->endCTFE();
1548 
1549                     Type *tb2 = type->toBasetype();
1550                     Type *ti = exp->type->toBasetype();
1551 
1552                     /* The problem is the following code:
1553                      *  struct CopyTest {
1554                      *     double x;
1555                      *     this(double a) { x = a * 10.0;}
1556                      *     this(this) { x += 2.0; }
1557                      *  }
1558                      *  const CopyTest z = CopyTest(5.3);  // ok
1559                      *  const CopyTest w = z;              // not ok, postblit not run
1560                      *  static assert(w.x == 55.0);
1561                      * because the postblit doesn't get run on the initialization of w.
1562                      */
1563                     if (ti->ty == Tstruct)
1564                     {
1565                         StructDeclaration *sd = ((TypeStruct *)ti)->sym;
1566                         /* Look to see if initializer involves a copy constructor
1567                          * (which implies a postblit)
1568                          */
1569                          // there is a copy constructor
1570                          // and exp is the same struct
1571                         if (sd->postblit &&
1572                             tb2->toDsymbol(NULL) == sd)
1573                         {
1574                             // The only allowable initializer is a (non-copy) constructor
1575                             if (exp->isLvalue())
1576                                 error("of type struct %s uses this(this), which is not allowed in static initialization", tb2->toChars());
1577                         }
1578                     }
1579                     ei->exp = exp;
1580                 }
1581                 _init = ::semantic(_init, sc, type, INITinterpret);
1582                 inuse--;
1583                 if (global.errors > errors)
1584                 {
1585                     _init = new ErrorInitializer();
1586                     type = Type::terror;
1587                 }
1588             }
1589             else
1590             {
1591                 _scope = scx ? scx : sc->copy();
1592                 _scope->setNoFree();
1593             }
1594         }
1595         sc = sc->pop();
1596     }
1597 
1598 Ldtor:
1599     /* Build code to execute destruction, if necessary
1600      */
1601     edtor = callScopeDtor(sc);
1602     if (edtor)
1603     {
1604         if (sc->func && storage_class & (STCstatic | STCgshared))
1605             edtor = ::semantic(edtor, sc->_module->_scope);
1606         else
1607             edtor = ::semantic(edtor, sc);
1608 
1609 #if 0 // currently disabled because of std.stdio.stdin, stdout and stderr
1610         if (isDataseg() && !(storage_class & STCextern))
1611             error("static storage variables cannot have destructors");
1612 #endif
1613     }
1614 
1615     semanticRun = PASSsemanticdone;
1616 
1617     if (type->toBasetype()->ty == Terror)
1618         errors = true;
1619 
1620     if (sc->scopesym && !sc->scopesym->isAggregateDeclaration())
1621     {
1622         for (ScopeDsymbol *sym = sc->scopesym; sym && endlinnum == 0;
1623              sym = sym->parent ? sym->parent->isScopeDsymbol() : NULL)
1624             endlinnum = sym->endlinnum;
1625     }
1626 }
1627 
semantic2(Scope * sc)1628 void VarDeclaration::semantic2(Scope *sc)
1629 {
1630     if (semanticRun < PASSsemanticdone && inuse)
1631         return;
1632 
1633     //printf("VarDeclaration::semantic2('%s')\n", toChars());
1634 
1635     if (_init && !toParent()->isFuncDeclaration())
1636     {
1637         inuse++;
1638         // Bugzilla 14166: Don't run CTFE for the temporary variables inside typeof
1639         _init = ::semantic(_init, sc, type, sc->intypeof == 1 ? INITnointerpret : INITinterpret);
1640         inuse--;
1641     }
1642     if (_init && storage_class & STCmanifest)
1643     {
1644         /* Cannot initializer enums with CTFE classreferences and addresses of struct literals.
1645          * Scan initializer looking for them. Issue error if found.
1646          */
1647         if (ExpInitializer *ei = _init->isExpInitializer())
1648         {
1649             struct EnumInitializer
1650             {
1651                 static bool arrayHasInvalidEnumInitializer(Expressions *elems)
1652                 {
1653                     for (size_t i = 0; i < elems->dim; i++)
1654                     {
1655                         Expression *e = (*elems)[i];
1656                         if (e && hasInvalidEnumInitializer(e))
1657                             return true;
1658                     }
1659                     return false;
1660                 }
1661 
1662                 static bool hasInvalidEnumInitializer(Expression *e)
1663                 {
1664                     if (e->op == TOKclassreference)
1665                         return true;
1666                     if (e->op == TOKaddress && ((AddrExp *)e)->e1->op == TOKstructliteral)
1667                         return true;
1668                     if (e->op == TOKarrayliteral)
1669                         return arrayHasInvalidEnumInitializer(((ArrayLiteralExp *)e)->elements);
1670                     if (e->op == TOKstructliteral)
1671                         return arrayHasInvalidEnumInitializer(((StructLiteralExp *)e)->elements);
1672                     if (e->op == TOKassocarrayliteral)
1673                     {
1674                         AssocArrayLiteralExp *ae = (AssocArrayLiteralExp *)e;
1675                         return arrayHasInvalidEnumInitializer(ae->values) ||
1676                             arrayHasInvalidEnumInitializer(ae->keys);
1677                     }
1678                     return false;
1679                 }
1680             };
1681             if (EnumInitializer::hasInvalidEnumInitializer(ei->exp))
1682                 error(": Unable to initialize enum with class or pointer to struct. Use static const variable instead.");
1683         }
1684     }
1685     else if (_init && isThreadlocal())
1686     {
1687         if ((type->ty == Tclass) && type->isMutable() && !type->isShared())
1688         {
1689             ExpInitializer *ei = _init->isExpInitializer();
1690             if (ei && ei->exp->op == TOKclassreference)
1691                 error("is mutable. Only const or immutable class thread local variable are allowed, not %s", type->toChars());
1692         }
1693         else if (type->ty == Tpointer && type->nextOf()->ty == Tstruct && type->nextOf()->isMutable() &&!type->nextOf()->isShared())
1694         {
1695             ExpInitializer *ei = _init->isExpInitializer();
1696             if (ei && ei->exp->op == TOKaddress && ((AddrExp *)ei->exp)->e1->op == TOKstructliteral)
1697             {
1698                 error("is a pointer to mutable struct. Only pointers to const, immutable or shared struct thread local variable are allowed, not %s", type->toChars());
1699             }
1700         }
1701     }
1702     semanticRun = PASSsemantic2done;
1703 }
1704 
setFieldOffset(AggregateDeclaration * ad,unsigned * poffset,bool isunion)1705 void VarDeclaration::setFieldOffset(AggregateDeclaration *ad, unsigned *poffset, bool isunion)
1706 {
1707     //printf("VarDeclaration::setFieldOffset(ad = %s) %s\n", ad->toChars(), toChars());
1708 
1709     if (aliassym)
1710     {
1711         // If this variable was really a tuple, set the offsets for the tuple fields
1712         TupleDeclaration *v2 = aliassym->isTupleDeclaration();
1713         assert(v2);
1714         for (size_t i = 0; i < v2->objects->dim; i++)
1715         {
1716             RootObject *o = (*v2->objects)[i];
1717             assert(o->dyncast() == DYNCAST_EXPRESSION);
1718             Expression *e = (Expression *)o;
1719             assert(e->op == TOKdsymbol);
1720             DsymbolExp *se = (DsymbolExp *)e;
1721             se->s->setFieldOffset(ad, poffset, isunion);
1722         }
1723         return;
1724     }
1725 
1726     if (!isField())
1727         return;
1728     assert(!(storage_class & (STCstatic | STCextern | STCparameter | STCtls)));
1729 
1730     //printf("+VarDeclaration::setFieldOffset(ad = %s) %s\n", ad->toChars(), toChars());
1731 
1732     /* Fields that are tuples appear both as part of TupleDeclarations and
1733      * as members. That means ignore them if they are already a field.
1734      */
1735     if (offset)
1736     {
1737         // already a field
1738         *poffset = ad->structsize;  // Bugzilla 13613
1739         return;
1740     }
1741     for (size_t i = 0; i < ad->fields.dim; i++)
1742     {
1743         if (ad->fields[i] == this)
1744         {
1745             // already a field
1746             *poffset = ad->structsize;  // Bugzilla 13613
1747             return;
1748         }
1749     }
1750 
1751     // Check for forward referenced types which will fail the size() call
1752     Type *t = type->toBasetype();
1753     if (storage_class & STCref)
1754     {
1755         // References are the size of a pointer
1756         t = Type::tvoidptr;
1757     }
1758     Type *tv = t->baseElemOf();
1759     if (tv->ty == Tstruct)
1760     {
1761         TypeStruct *ts = (TypeStruct *)tv;
1762         assert(ts->sym != ad);   // already checked in ad->determineFields()
1763         if (!ts->sym->determineSize(loc))
1764         {
1765             type = Type::terror;
1766             errors = true;
1767             return;
1768         }
1769     }
1770 
1771     // List in ad->fields. Even if the type is error, it's necessary to avoid
1772     // pointless error diagnostic "more initializers than fields" on struct literal.
1773     ad->fields.push(this);
1774 
1775     if (t->ty == Terror)
1776         return;
1777 
1778     const d_uns64 sz = t->size(loc);
1779     assert(sz != SIZE_INVALID && sz < UINT32_MAX);
1780     unsigned memsize = (unsigned)sz;                 // size of member
1781     unsigned memalignsize = Target::fieldalign(t);   // size of member for alignment purposes
1782 
1783     offset = AggregateDeclaration::placeField(poffset, memsize, memalignsize, alignment,
1784                 &ad->structsize, &ad->alignsize, isunion);
1785 
1786     //printf("\t%s: memalignsize = %d\n", toChars(), memalignsize);
1787 
1788     //printf(" addField '%s' to '%s' at offset %d, size = %d\n", toChars(), ad->toChars(), offset, memsize);
1789 }
1790 
kind()1791 const char *VarDeclaration::kind() const
1792 {
1793     return "variable";
1794 }
1795 
toAlias()1796 Dsymbol *VarDeclaration::toAlias()
1797 {
1798     //printf("VarDeclaration::toAlias('%s', this = %p, aliassym = %p)\n", toChars(), this, aliassym);
1799     if ((!type || !type->deco) && _scope)
1800         semantic(_scope);
1801 
1802     assert(this != aliassym);
1803     Dsymbol *s = aliassym ? aliassym->toAlias() : this;
1804     return s;
1805 }
1806 
isThis()1807 AggregateDeclaration *VarDeclaration::isThis()
1808 {
1809     AggregateDeclaration *ad = NULL;
1810 
1811     if (!(storage_class & (STCstatic | STCextern | STCmanifest | STCtemplateparameter |
1812                            STCtls | STCgshared | STCctfe)))
1813     {
1814         for (Dsymbol *s = this; s; s = s->parent)
1815         {
1816             ad = s->isMember();
1817             if (ad)
1818                 break;
1819             if (!s->parent || !s->parent->isTemplateMixin()) break;
1820         }
1821     }
1822     return ad;
1823 }
1824 
needThis()1825 bool VarDeclaration::needThis()
1826 {
1827     //printf("VarDeclaration::needThis(%s, x%x)\n", toChars(), storage_class);
1828     return isField();
1829 }
1830 
isExport()1831 bool VarDeclaration::isExport() const
1832 {
1833     return protection.kind == PROTexport;
1834 }
1835 
isImportedSymbol()1836 bool VarDeclaration::isImportedSymbol() const
1837 {
1838     if (protection.kind == PROTexport && !_init &&
1839         (storage_class & STCstatic || parent->isModule()))
1840         return true;
1841     return false;
1842 }
1843 
1844 /*******************************************
1845  * Helper function for the expansion of manifest constant.
1846  */
expandInitializer(Loc loc)1847 Expression *VarDeclaration::expandInitializer(Loc loc)
1848 {
1849     assert((storage_class & STCmanifest) && _init);
1850 
1851     Expression *e = getConstInitializer();
1852     if (!e)
1853     {
1854         ::error(loc, "cannot make expression out of initializer for %s", toChars());
1855         return new ErrorExp();
1856     }
1857 
1858     e = e->copy();
1859     e->loc = loc;    // for better error message
1860     return e;
1861 }
1862 
checkCtorConstInit()1863 void VarDeclaration::checkCtorConstInit()
1864 {
1865 #if 0 /* doesn't work if more than one static ctor */
1866     if (ctorinit == 0 && isCtorinit() && !isField())
1867         error("missing initializer in static constructor for const variable");
1868 #endif
1869 }
1870 
1871 bool lambdaCheckForNestedRef(Expression *e, Scope *sc);
1872 
1873 /************************************
1874  * Check to see if this variable is actually in an enclosing function
1875  * rather than the current one.
1876  * Returns true if error occurs.
1877  */
checkNestedReference(Scope * sc,Loc loc)1878 bool VarDeclaration::checkNestedReference(Scope *sc, Loc loc)
1879 {
1880     //printf("VarDeclaration::checkNestedReference() %s\n", toChars());
1881     if (sc->intypeof == 1 || (sc->flags & SCOPEctfe))
1882         return false;
1883     if (!parent || parent == sc->parent)
1884         return false;
1885     if (isDataseg() || (storage_class & STCmanifest))
1886         return false;
1887 
1888     // The current function
1889     FuncDeclaration *fdthis = sc->parent->isFuncDeclaration();
1890     if (!fdthis)
1891         return false;   // out of function scope
1892 
1893     Dsymbol *p = toParent2();
1894 
1895     // Function literals from fdthis to p must be delegates
1896     checkNestedRef(fdthis, p);
1897 
1898     // The function that this variable is in
1899     FuncDeclaration *fdv = p->isFuncDeclaration();
1900     if (!fdv || fdv == fdthis)
1901         return false;
1902 
1903     // Add fdthis to nestedrefs[] if not already there
1904     for (size_t i = 0; 1; i++)
1905     {
1906         if (i == nestedrefs.dim)
1907         {
1908             nestedrefs.push(fdthis);
1909             break;
1910         }
1911         if (nestedrefs[i] == fdthis)
1912             break;
1913     }
1914 
1915     /* __require and __ensure will always get called directly,
1916      * so they never make outer functions closure.
1917      */
1918     if (fdthis->ident == Id::require || fdthis->ident == Id::ensure)
1919         return false;
1920 
1921     //printf("\tfdv = %s\n", fdv->toChars());
1922     //printf("\tfdthis = %s\n", fdthis->toChars());
1923     if (loc.filename)
1924     {
1925         int lv = fdthis->getLevel(loc, sc, fdv);
1926         if (lv == -2)   // error
1927             return true;
1928     }
1929 
1930     // Add this to fdv->closureVars[] if not already there
1931     for (size_t i = 0; 1; i++)
1932     {
1933         if (i == fdv->closureVars.dim)
1934         {
1935             if (!sc->intypeof && !(sc->flags & SCOPEcompile))
1936                 fdv->closureVars.push(this);
1937             break;
1938         }
1939         if (fdv->closureVars[i] == this)
1940             break;
1941     }
1942 
1943     //printf("fdthis is %s\n", fdthis->toChars());
1944     //printf("var %s in function %s is nested ref\n", toChars(), fdv->toChars());
1945     // __dollar creates problems because it isn't a real variable Bugzilla 3326
1946     if (ident == Id::dollar)
1947     {
1948         ::error(loc, "cannnot use $ inside a function literal");
1949         return true;
1950     }
1951 
1952     if (ident == Id::withSym)       // Bugzilla 1759
1953     {
1954         ExpInitializer *ez = _init->isExpInitializer();
1955         assert(ez);
1956         Expression *e = ez->exp;
1957         if (e->op == TOKconstruct || e->op == TOKblit)
1958             e = ((AssignExp *)e)->e2;
1959         return lambdaCheckForNestedRef(e, sc);
1960     }
1961 
1962     return false;
1963 }
1964 
1965 /*******************************************
1966  * If variable has a constant expression initializer, get it.
1967  * Otherwise, return NULL.
1968  */
1969 
getConstInitializer(bool needFullType)1970 Expression *VarDeclaration::getConstInitializer(bool needFullType)
1971 {
1972     assert(type && _init);
1973 
1974     // Ungag errors when not speculative
1975     unsigned oldgag = global.gag;
1976     if (global.gag)
1977     {
1978         Dsymbol *sym = toParent()->isAggregateDeclaration();
1979         if (sym && !sym->isSpeculative())
1980             global.gag = 0;
1981     }
1982 
1983     if (_scope)
1984     {
1985         inuse++;
1986         _init = ::semantic(_init, _scope, type, INITinterpret);
1987         _scope = NULL;
1988         inuse--;
1989     }
1990     Expression *e = initializerToExpression(_init, needFullType ? type : NULL);
1991 
1992     global.gag = oldgag;
1993     return e;
1994 }
1995 
1996 /*************************************
1997  * Return true if we can take the address of this variable.
1998  */
1999 
canTakeAddressOf()2000 bool VarDeclaration::canTakeAddressOf()
2001 {
2002     return !(storage_class & STCmanifest);
2003 }
2004 
2005 
2006 /*******************************
2007  * Does symbol go into data segment?
2008  * Includes extern variables.
2009  */
2010 
isDataseg()2011 bool VarDeclaration::isDataseg()
2012 {
2013     if (isdataseg == 0) // the value is not cached
2014     {
2015         isdataseg = 2; // The Variables does not go into the datasegment
2016 
2017         if (!canTakeAddressOf())
2018         {
2019             return false;
2020         }
2021 
2022         Dsymbol *parent = toParent();
2023         if (!parent && !(storage_class & STCstatic))
2024         {
2025             error("forward referenced");
2026             type = Type::terror;
2027         }
2028         else if (storage_class & (STCstatic | STCextern | STCtls | STCgshared) ||
2029                  parent->isModule() || parent->isTemplateInstance() || parent->isNspace())
2030         {
2031             assert(!isParameter() && !isResult());
2032             isdataseg = 1; // It is in the DataSegment
2033         }
2034     }
2035 
2036     return (isdataseg == 1);
2037 }
2038 
2039 /************************************
2040  * Does symbol go into thread local storage?
2041  */
2042 
isThreadlocal()2043 bool VarDeclaration::isThreadlocal()
2044 {
2045     //printf("VarDeclaration::isThreadlocal(%p, '%s')\n", this, toChars());
2046     /* Data defaults to being thread-local. It is not thread-local
2047      * if it is immutable, const or shared.
2048      */
2049     bool i = isDataseg() &&
2050         !(storage_class & (STCimmutable | STCconst | STCshared | STCgshared));
2051     //printf("\treturn %d\n", i);
2052     return i;
2053 }
2054 
2055 /********************************************
2056  * Can variable be read and written by CTFE?
2057  */
2058 
isCTFE()2059 bool VarDeclaration::isCTFE()
2060 {
2061     return (storage_class & STCctfe) != 0; // || !isDataseg();
2062 }
2063 
isOverlappedWith(VarDeclaration * v)2064 bool VarDeclaration::isOverlappedWith(VarDeclaration *v)
2065 {
2066     const d_uns64 vsz = v->type->size();
2067     const d_uns64 tsz = type->size();
2068     assert(vsz != SIZE_INVALID && tsz != SIZE_INVALID);
2069     return offset < v->offset + vsz &&
2070         v->offset < offset + tsz;
2071 }
2072 
hasPointers()2073 bool VarDeclaration::hasPointers()
2074 {
2075     //printf("VarDeclaration::hasPointers() %s, ty = %d\n", toChars(), type->ty);
2076     return (!isDataseg() && type->hasPointers());
2077 }
2078 
2079 /******************************************
2080  * Return true if variable needs to call the destructor.
2081  */
2082 
needsScopeDtor()2083 bool VarDeclaration::needsScopeDtor()
2084 {
2085     //printf("VarDeclaration::needsScopeDtor() %s\n", toChars());
2086     return edtor && !(storage_class & STCnodtor);
2087 }
2088 
2089 
2090 /******************************************
2091  * If a variable has a scope destructor call, return call for it.
2092  * Otherwise, return NULL.
2093  */
2094 
callScopeDtor(Scope *)2095 Expression *VarDeclaration::callScopeDtor(Scope *)
2096 {
2097     //printf("VarDeclaration::callScopeDtor() %s\n", toChars());
2098 
2099     // Destruction of STCfield's is handled by buildDtor()
2100     if (storage_class & (STCnodtor | STCref | STCout | STCfield))
2101     {
2102         return NULL;
2103     }
2104 
2105     Expression *e = NULL;
2106 
2107     // Destructors for structs and arrays of structs
2108     Type *tv = type->baseElemOf();
2109     if (tv->ty == Tstruct)
2110     {
2111         StructDeclaration *sd = ((TypeStruct *)tv)->sym;
2112         if (!sd->dtor || sd->errors)
2113            return NULL;
2114 
2115         const d_uns64 sz = type->size();
2116         assert(sz != SIZE_INVALID);
2117         if (!sz)
2118             return NULL;
2119 
2120         if (type->toBasetype()->ty == Tstruct)
2121         {
2122             // v.__xdtor()
2123             e = new VarExp(loc, this);
2124 
2125             /* This is a hack so we can call destructors on const/immutable objects.
2126              * Need to add things like "const ~this()" and "immutable ~this()" to
2127              * fix properly.
2128              */
2129             e->type = e->type->mutableOf();
2130 
2131             // Enable calling destructors on shared objects.
2132             // The destructor is always a single, non-overloaded function,
2133             // and must serve both shared and non-shared objects.
2134             e->type = e->type->unSharedOf();
2135 
2136             e = new DotVarExp(loc, e, sd->dtor, false);
2137             e = new CallExp(loc, e);
2138         }
2139         else
2140         {
2141             // __ArrayDtor(v[0 .. n])
2142             e = new VarExp(loc, this);
2143 
2144             const d_uns64 sdsz = sd->type->size();
2145             assert(sdsz != SIZE_INVALID && sdsz != 0);
2146             const d_uns64 n = sz / sdsz;
2147             e = new SliceExp(loc, e, new IntegerExp(loc, 0, Type::tsize_t),
2148                                      new IntegerExp(loc, n, Type::tsize_t));
2149             // Prevent redundant bounds check
2150             ((SliceExp *)e)->upperIsInBounds = true;
2151             ((SliceExp *)e)->lowerIsLessThanUpper = true;
2152 
2153             // This is a hack so we can call destructors on const/immutable objects.
2154             e->type = sd->type->arrayOf();
2155 
2156             e = new CallExp(loc, new IdentifierExp(loc, Id::__ArrayDtor), e);
2157         }
2158         return e;
2159     }
2160 
2161     // Destructors for classes
2162     if (storage_class & (STCauto | STCscope) && !(storage_class & STCparameter))
2163     {
2164         for (ClassDeclaration *cd = type->isClassHandle();
2165              cd;
2166              cd = cd->baseClass)
2167         {
2168             /* We can do better if there's a way with onstack
2169              * classes to determine if there's no way the monitor
2170              * could be set.
2171              */
2172             //if (cd->isInterfaceDeclaration())
2173                 //error("interface %s cannot be scope", cd->toChars());
2174 
2175             // Destroying C++ scope classes crashes currently. Since C++ class dtors are not currently supported, simply do not run dtors for them.
2176             // See https://issues.dlang.org/show_bug.cgi?id=13182
2177             if (cd->isCPPclass())
2178             {
2179                 break;
2180             }
2181             if (mynew || onstack) // if any destructors
2182             {
2183                 // delete this;
2184                 Expression *ec;
2185 
2186                 ec = new VarExp(loc, this);
2187                 e = new DeleteExp(loc, ec, true);
2188                 e->type = Type::tvoid;
2189                 break;
2190             }
2191         }
2192     }
2193     return e;
2194 }
2195 
2196 /**********************************
2197  * Determine if `this` has a lifetime that lasts past
2198  * the destruction of `v`
2199  * Params:
2200  *  v = variable to test against
2201  * Returns:
2202  *  true if it does
2203  */
enclosesLifetimeOf(VarDeclaration * v)2204 bool VarDeclaration::enclosesLifetimeOf(VarDeclaration *v) const
2205 {
2206     return sequenceNumber < v->sequenceNumber;
2207 }
2208 
2209 /******************************************
2210  */
2211 
ObjectNotFound(Identifier * id)2212 void ObjectNotFound(Identifier *id)
2213 {
2214     Type::error(Loc(), "%s not found. object.d may be incorrectly installed or corrupt.", id->toChars());
2215     fatal();
2216 }
2217 
2218 /******************************** SymbolDeclaration ********************************/
2219 
SymbolDeclaration(Loc loc,StructDeclaration * dsym)2220 SymbolDeclaration::SymbolDeclaration(Loc loc, StructDeclaration *dsym)
2221         : Declaration(dsym->ident)
2222 {
2223     this->loc = loc;
2224     this->dsym = dsym;
2225     storage_class |= STCconst;
2226 }
2227 
2228 /********************************* TypeInfoDeclaration ****************************/
2229 
TypeInfoDeclaration(Type * tinfo)2230 TypeInfoDeclaration::TypeInfoDeclaration(Type *tinfo)
2231     : VarDeclaration(Loc(), Type::dtypeinfo->type, tinfo->getTypeInfoIdent(), NULL)
2232 {
2233     this->tinfo = tinfo;
2234     storage_class = STCstatic | STCgshared;
2235     protection = Prot(PROTpublic);
2236     linkage = LINKc;
2237     alignment = Target::ptrsize;
2238 }
2239 
create(Type * tinfo)2240 TypeInfoDeclaration *TypeInfoDeclaration::create(Type *tinfo)
2241 {
2242     return new TypeInfoDeclaration(tinfo);
2243 }
2244 
syntaxCopy(Dsymbol *)2245 Dsymbol *TypeInfoDeclaration::syntaxCopy(Dsymbol *)
2246 {
2247     assert(0);          // should never be produced by syntax
2248     return NULL;
2249 }
2250 
semantic(Scope *)2251 void TypeInfoDeclaration::semantic(Scope *)
2252 {
2253     assert(linkage == LINKc);
2254 }
2255 
toChars()2256 const char *TypeInfoDeclaration::toChars()
2257 {
2258     //printf("TypeInfoDeclaration::toChars() tinfo = %s\n", tinfo->toChars());
2259     OutBuffer buf;
2260     buf.writestring("typeid(");
2261     buf.writestring(tinfo->toChars());
2262     buf.writeByte(')');
2263     return buf.extractString();
2264 }
2265 
2266 /***************************** TypeInfoConstDeclaration **********************/
2267 
TypeInfoConstDeclaration(Type * tinfo)2268 TypeInfoConstDeclaration::TypeInfoConstDeclaration(Type *tinfo)
2269     : TypeInfoDeclaration(tinfo)
2270 {
2271     if (!Type::typeinfoconst)
2272     {
2273         ObjectNotFound(Id::TypeInfo_Const);
2274     }
2275     type = Type::typeinfoconst->type;
2276 }
2277 
create(Type * tinfo)2278 TypeInfoConstDeclaration *TypeInfoConstDeclaration::create(Type *tinfo)
2279 {
2280     return new TypeInfoConstDeclaration(tinfo);
2281 }
2282 
2283 /***************************** TypeInfoInvariantDeclaration **********************/
2284 
TypeInfoInvariantDeclaration(Type * tinfo)2285 TypeInfoInvariantDeclaration::TypeInfoInvariantDeclaration(Type *tinfo)
2286     : TypeInfoDeclaration(tinfo)
2287 {
2288     if (!Type::typeinfoinvariant)
2289     {
2290         ObjectNotFound(Id::TypeInfo_Invariant);
2291     }
2292     type = Type::typeinfoinvariant->type;
2293 }
2294 
create(Type * tinfo)2295 TypeInfoInvariantDeclaration *TypeInfoInvariantDeclaration::create(Type *tinfo)
2296 {
2297     return new TypeInfoInvariantDeclaration(tinfo);
2298 }
2299 
2300 /***************************** TypeInfoSharedDeclaration **********************/
2301 
TypeInfoSharedDeclaration(Type * tinfo)2302 TypeInfoSharedDeclaration::TypeInfoSharedDeclaration(Type *tinfo)
2303     : TypeInfoDeclaration(tinfo)
2304 {
2305     if (!Type::typeinfoshared)
2306     {
2307         ObjectNotFound(Id::TypeInfo_Shared);
2308     }
2309     type = Type::typeinfoshared->type;
2310 }
2311 
create(Type * tinfo)2312 TypeInfoSharedDeclaration *TypeInfoSharedDeclaration::create(Type *tinfo)
2313 {
2314     return new TypeInfoSharedDeclaration(tinfo);
2315 }
2316 
2317 /***************************** TypeInfoWildDeclaration **********************/
2318 
TypeInfoWildDeclaration(Type * tinfo)2319 TypeInfoWildDeclaration::TypeInfoWildDeclaration(Type *tinfo)
2320     : TypeInfoDeclaration(tinfo)
2321 {
2322     if (!Type::typeinfowild)
2323     {
2324         ObjectNotFound(Id::TypeInfo_Wild);
2325     }
2326     type = Type::typeinfowild->type;
2327 }
2328 
create(Type * tinfo)2329 TypeInfoWildDeclaration *TypeInfoWildDeclaration::create(Type *tinfo)
2330 {
2331     return new TypeInfoWildDeclaration(tinfo);
2332 }
2333 
2334 /***************************** TypeInfoStructDeclaration **********************/
2335 
TypeInfoStructDeclaration(Type * tinfo)2336 TypeInfoStructDeclaration::TypeInfoStructDeclaration(Type *tinfo)
2337     : TypeInfoDeclaration(tinfo)
2338 {
2339     if (!Type::typeinfostruct)
2340     {
2341         ObjectNotFound(Id::TypeInfo_Struct);
2342     }
2343     type = Type::typeinfostruct->type;
2344 }
2345 
create(Type * tinfo)2346 TypeInfoStructDeclaration *TypeInfoStructDeclaration::create(Type *tinfo)
2347 {
2348     return new TypeInfoStructDeclaration(tinfo);
2349 }
2350 
2351 /***************************** TypeInfoClassDeclaration ***********************/
2352 
TypeInfoClassDeclaration(Type * tinfo)2353 TypeInfoClassDeclaration::TypeInfoClassDeclaration(Type *tinfo)
2354     : TypeInfoDeclaration(tinfo)
2355 {
2356     if (!Type::typeinfoclass)
2357     {
2358         ObjectNotFound(Id::TypeInfo_Class);
2359     }
2360     type = Type::typeinfoclass->type;
2361 }
2362 
create(Type * tinfo)2363 TypeInfoClassDeclaration *TypeInfoClassDeclaration::create(Type *tinfo)
2364 {
2365     return new TypeInfoClassDeclaration(tinfo);
2366 }
2367 
2368 /***************************** TypeInfoInterfaceDeclaration *******************/
2369 
TypeInfoInterfaceDeclaration(Type * tinfo)2370 TypeInfoInterfaceDeclaration::TypeInfoInterfaceDeclaration(Type *tinfo)
2371     : TypeInfoDeclaration(tinfo)
2372 {
2373     if (!Type::typeinfointerface)
2374     {
2375         ObjectNotFound(Id::TypeInfo_Interface);
2376     }
2377     type = Type::typeinfointerface->type;
2378 }
2379 
create(Type * tinfo)2380 TypeInfoInterfaceDeclaration *TypeInfoInterfaceDeclaration::create(Type *tinfo)
2381 {
2382     return new TypeInfoInterfaceDeclaration(tinfo);
2383 }
2384 
2385 /***************************** TypeInfoPointerDeclaration *********************/
2386 
TypeInfoPointerDeclaration(Type * tinfo)2387 TypeInfoPointerDeclaration::TypeInfoPointerDeclaration(Type *tinfo)
2388     : TypeInfoDeclaration(tinfo)
2389 {
2390     if (!Type::typeinfopointer)
2391     {
2392         ObjectNotFound(Id::TypeInfo_Pointer);
2393     }
2394     type = Type::typeinfopointer->type;
2395 }
2396 
create(Type * tinfo)2397 TypeInfoPointerDeclaration *TypeInfoPointerDeclaration::create(Type *tinfo)
2398 {
2399     return new TypeInfoPointerDeclaration(tinfo);
2400 }
2401 
2402 /***************************** TypeInfoArrayDeclaration ***********************/
2403 
TypeInfoArrayDeclaration(Type * tinfo)2404 TypeInfoArrayDeclaration::TypeInfoArrayDeclaration(Type *tinfo)
2405     : TypeInfoDeclaration(tinfo)
2406 {
2407     if (!Type::typeinfoarray)
2408     {
2409         ObjectNotFound(Id::TypeInfo_Array);
2410     }
2411     type = Type::typeinfoarray->type;
2412 }
2413 
create(Type * tinfo)2414 TypeInfoArrayDeclaration *TypeInfoArrayDeclaration::create(Type *tinfo)
2415 {
2416     return new TypeInfoArrayDeclaration(tinfo);
2417 }
2418 
2419 /***************************** TypeInfoStaticArrayDeclaration *****************/
2420 
TypeInfoStaticArrayDeclaration(Type * tinfo)2421 TypeInfoStaticArrayDeclaration::TypeInfoStaticArrayDeclaration(Type *tinfo)
2422     : TypeInfoDeclaration(tinfo)
2423 {
2424     if (!Type::typeinfostaticarray)
2425     {
2426         ObjectNotFound(Id::TypeInfo_StaticArray);
2427     }
2428     type = Type::typeinfostaticarray->type;
2429 }
2430 
create(Type * tinfo)2431 TypeInfoStaticArrayDeclaration *TypeInfoStaticArrayDeclaration::create(Type *tinfo)
2432 {
2433     return new TypeInfoStaticArrayDeclaration(tinfo);
2434 }
2435 
2436 /***************************** TypeInfoAssociativeArrayDeclaration ************/
2437 
TypeInfoAssociativeArrayDeclaration(Type * tinfo)2438 TypeInfoAssociativeArrayDeclaration::TypeInfoAssociativeArrayDeclaration(Type *tinfo)
2439     : TypeInfoDeclaration(tinfo)
2440 {
2441     if (!Type::typeinfoassociativearray)
2442     {
2443         ObjectNotFound(Id::TypeInfo_AssociativeArray);
2444     }
2445     type = Type::typeinfoassociativearray->type;
2446 }
2447 
create(Type * tinfo)2448 TypeInfoAssociativeArrayDeclaration *TypeInfoAssociativeArrayDeclaration::create(Type *tinfo)
2449 {
2450     return new TypeInfoAssociativeArrayDeclaration(tinfo);
2451 }
2452 
2453 /***************************** TypeInfoVectorDeclaration ***********************/
2454 
TypeInfoVectorDeclaration(Type * tinfo)2455 TypeInfoVectorDeclaration::TypeInfoVectorDeclaration(Type *tinfo)
2456     : TypeInfoDeclaration(tinfo)
2457 {
2458     if (!Type::typeinfovector)
2459     {
2460         ObjectNotFound(Id::TypeInfo_Vector);
2461     }
2462     type = Type::typeinfovector->type;
2463 }
2464 
create(Type * tinfo)2465 TypeInfoVectorDeclaration *TypeInfoVectorDeclaration::create(Type *tinfo)
2466 {
2467     return new TypeInfoVectorDeclaration(tinfo);
2468 }
2469 
2470 /***************************** TypeInfoEnumDeclaration ***********************/
2471 
TypeInfoEnumDeclaration(Type * tinfo)2472 TypeInfoEnumDeclaration::TypeInfoEnumDeclaration(Type *tinfo)
2473     : TypeInfoDeclaration(tinfo)
2474 {
2475     if (!Type::typeinfoenum)
2476     {
2477         ObjectNotFound(Id::TypeInfo_Enum);
2478     }
2479     type = Type::typeinfoenum->type;
2480 }
2481 
create(Type * tinfo)2482 TypeInfoEnumDeclaration *TypeInfoEnumDeclaration::create(Type *tinfo)
2483 {
2484     return new TypeInfoEnumDeclaration(tinfo);
2485 }
2486 
2487 /***************************** TypeInfoFunctionDeclaration ********************/
2488 
TypeInfoFunctionDeclaration(Type * tinfo)2489 TypeInfoFunctionDeclaration::TypeInfoFunctionDeclaration(Type *tinfo)
2490     : TypeInfoDeclaration(tinfo)
2491 {
2492     if (!Type::typeinfofunction)
2493     {
2494         ObjectNotFound(Id::TypeInfo_Function);
2495     }
2496     type = Type::typeinfofunction->type;
2497 }
2498 
create(Type * tinfo)2499 TypeInfoFunctionDeclaration *TypeInfoFunctionDeclaration::create(Type *tinfo)
2500 {
2501     return new TypeInfoFunctionDeclaration(tinfo);
2502 }
2503 
2504 /***************************** TypeInfoDelegateDeclaration ********************/
2505 
TypeInfoDelegateDeclaration(Type * tinfo)2506 TypeInfoDelegateDeclaration::TypeInfoDelegateDeclaration(Type *tinfo)
2507     : TypeInfoDeclaration(tinfo)
2508 {
2509     if (!Type::typeinfodelegate)
2510     {
2511         ObjectNotFound(Id::TypeInfo_Delegate);
2512     }
2513     type = Type::typeinfodelegate->type;
2514 }
2515 
create(Type * tinfo)2516 TypeInfoDelegateDeclaration *TypeInfoDelegateDeclaration::create(Type *tinfo)
2517 {
2518     return new TypeInfoDelegateDeclaration(tinfo);
2519 }
2520 
2521 /***************************** TypeInfoTupleDeclaration **********************/
2522 
TypeInfoTupleDeclaration(Type * tinfo)2523 TypeInfoTupleDeclaration::TypeInfoTupleDeclaration(Type *tinfo)
2524     : TypeInfoDeclaration(tinfo)
2525 {
2526     if (!Type::typeinfotypelist)
2527     {
2528         ObjectNotFound(Id::TypeInfo_Tuple);
2529     }
2530     type = Type::typeinfotypelist->type;
2531 }
2532 
create(Type * tinfo)2533 TypeInfoTupleDeclaration *TypeInfoTupleDeclaration::create(Type *tinfo)
2534 {
2535     return new TypeInfoTupleDeclaration(tinfo);
2536 }
2537 
2538 /********************************* ThisDeclaration ****************************/
2539 
2540 // For the "this" parameter to member functions
2541 
ThisDeclaration(Loc loc,Type * t)2542 ThisDeclaration::ThisDeclaration(Loc loc, Type *t)
2543    : VarDeclaration(loc, t, Id::This, NULL)
2544 {
2545     storage_class |= STCnodtor;
2546 }
2547 
syntaxCopy(Dsymbol *)2548 Dsymbol *ThisDeclaration::syntaxCopy(Dsymbol *)
2549 {
2550     assert(0);          // should never be produced by syntax
2551     return NULL;
2552 }
2553 
2554