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/dsymbol.c
9  */
10 
11 #include "root/dsystem.h"
12 #include "root/rmem.h"
13 #include "root/speller.h"
14 #include "root/aav.h"
15 
16 #include "mars.h"
17 #include "dsymbol.h"
18 #include "aggregate.h"
19 #include "identifier.h"
20 #include "module.h"
21 #include "mtype.h"
22 #include "expression.h"
23 #include "statement.h"
24 #include "declaration.h"
25 #include "id.h"
26 #include "scope.h"
27 #include "init.h"
28 #include "import.h"
29 #include "template.h"
30 #include "attrib.h"
31 #include "enum.h"
32 #include "lexer.h"
33 #include "nspace.h"
34 
35 bool symbolIsVisible(Dsymbol *origin, Dsymbol *s);
36 typedef int (*ForeachDg)(void *ctx, size_t idx, Dsymbol *s);
37 int ScopeDsymbol_foreach(Scope *sc, Dsymbols *members, ForeachDg dg, void *ctx, size_t *pn = NULL);
38 Expression *semantic(Expression *e, Scope *sc);
39 
40 
41 /****************************** Dsymbol ******************************/
42 
Dsymbol()43 Dsymbol::Dsymbol()
44 {
45     //printf("Dsymbol::Dsymbol(%p)\n", this);
46     this->ident = NULL;
47     this->parent = NULL;
48     this->csym = NULL;
49     this->isym = NULL;
50     this->loc = Loc();
51     this->comment = NULL;
52     this->_scope = NULL;
53     this->prettystring = NULL;
54     this->semanticRun = PASSinit;
55     this->errors = false;
56     this->depdecl = NULL;
57     this->userAttribDecl = NULL;
58     this->ddocUnittest = NULL;
59 }
60 
Dsymbol(Identifier * ident)61 Dsymbol::Dsymbol(Identifier *ident)
62 {
63     //printf("Dsymbol::Dsymbol(%p, ident)\n", this);
64     this->ident = ident;
65     this->parent = NULL;
66     this->csym = NULL;
67     this->isym = NULL;
68     this->loc = Loc();
69     this->comment = NULL;
70     this->_scope = NULL;
71     this->prettystring = NULL;
72     this->semanticRun = PASSinit;
73     this->errors = false;
74     this->depdecl = NULL;
75     this->userAttribDecl = NULL;
76     this->ddocUnittest = NULL;
77 }
78 
create(Identifier * ident)79 Dsymbol *Dsymbol::create(Identifier *ident)
80 {
81     return new Dsymbol(ident);
82 }
83 
equals(RootObject * o)84 bool Dsymbol::equals(RootObject *o)
85 {
86     if (this == o)
87         return true;
88     Dsymbol *s = (Dsymbol *)(o);
89     // Overload sets don't have an ident
90     if (s && ident && s->ident && ident->equals(s->ident))
91         return true;
92     return false;
93 }
94 
95 /**************************************
96  * Copy the syntax.
97  * Used for template instantiations.
98  * If s is NULL, allocate the new object, otherwise fill it in.
99  */
100 
syntaxCopy(Dsymbol *)101 Dsymbol *Dsymbol::syntaxCopy(Dsymbol *)
102 {
103     print();
104     printf("%s %s\n", kind(), toChars());
105     assert(0);
106     return NULL;
107 }
108 
109 /**************************************
110  * Determine if this symbol is only one.
111  * Returns:
112  *      false, *ps = NULL: There are 2 or more symbols
113  *      true,  *ps = NULL: There are zero symbols
114  *      true,  *ps = symbol: The one and only one symbol
115  */
116 
oneMember(Dsymbol ** ps,Identifier *)117 bool Dsymbol::oneMember(Dsymbol **ps, Identifier *)
118 {
119     //printf("Dsymbol::oneMember()\n");
120     *ps = this;
121     return true;
122 }
123 
124 /*****************************************
125  * Same as Dsymbol::oneMember(), but look at an array of Dsymbols.
126  */
127 
oneMembers(Dsymbols * members,Dsymbol ** ps,Identifier * ident)128 bool Dsymbol::oneMembers(Dsymbols *members, Dsymbol **ps, Identifier *ident)
129 {
130     //printf("Dsymbol::oneMembers() %d\n", members ? members->dim : 0);
131     Dsymbol *s = NULL;
132 
133     if (members)
134     {
135         for (size_t i = 0; i < members->dim; i++)
136         {
137             Dsymbol *sx = (*members)[i];
138             bool x = sx->oneMember(ps, ident);
139             //printf("\t[%d] kind %s = %d, s = %p\n", i, sx->kind(), x, *ps);
140             if (!x)
141             {
142                 //printf("\tfalse 1\n");
143                 assert(*ps == NULL);
144                 return false;
145             }
146             if (*ps)
147             {
148                 assert(ident);
149                 if (!(*ps)->ident || !(*ps)->ident->equals(ident))
150                     continue;
151                 if (!s)
152                     s = *ps;
153                 else if (s->isOverloadable() && (*ps)->isOverloadable())
154                 {
155                     // keep head of overload set
156                     FuncDeclaration *f1 = s->isFuncDeclaration();
157                     FuncDeclaration *f2 = (*ps)->isFuncDeclaration();
158                     if (f1 && f2)
159                     {
160                         assert(!f1->isFuncAliasDeclaration());
161                         assert(!f2->isFuncAliasDeclaration());
162                         for (; f1 != f2; f1 = f1->overnext0)
163                         {
164                             if (f1->overnext0 == NULL)
165                             {
166                                 f1->overnext0 = f2;
167                                 break;
168                             }
169                         }
170                     }
171                 }
172                 else                    // more than one symbol
173                 {
174                     *ps = NULL;
175                     //printf("\tfalse 2\n");
176                     return false;
177                 }
178             }
179         }
180     }
181     *ps = s;            // s is the one symbol, NULL if none
182     //printf("\ttrue\n");
183     return true;
184 }
185 
186 /*****************************************
187  * Is Dsymbol a variable that contains pointers?
188  */
189 
hasPointers()190 bool Dsymbol::hasPointers()
191 {
192     //printf("Dsymbol::hasPointers() %s\n", toChars());
193     return false;
194 }
195 
hasStaticCtorOrDtor()196 bool Dsymbol::hasStaticCtorOrDtor()
197 {
198     //printf("Dsymbol::hasStaticCtorOrDtor() %s\n", toChars());
199     return false;
200 }
201 
setFieldOffset(AggregateDeclaration *,unsigned *,bool)202 void Dsymbol::setFieldOffset(AggregateDeclaration *, unsigned *, bool)
203 {
204 }
205 
getIdent()206 Identifier *Dsymbol::getIdent()
207 {
208     return ident;
209 }
210 
toChars()211 const char *Dsymbol::toChars()
212 {
213     return ident ? ident->toChars() : "__anonymous";
214 }
215 
toPrettyCharsHelper()216 const char *Dsymbol::toPrettyCharsHelper()
217 {
218     return toChars();
219 }
220 
toPrettyChars(bool QualifyTypes)221 const char *Dsymbol::toPrettyChars(bool QualifyTypes)
222 {
223     if (prettystring && !QualifyTypes)
224         return (const char *)prettystring;
225 
226     //printf("Dsymbol::toPrettyChars() '%s'\n", toChars());
227     if (!parent)
228     {
229         const char *s = toChars();
230         if (!QualifyTypes)
231             prettystring = (const utf8_t *)s;
232         return s;
233     }
234 
235     // Computer number of components
236     size_t complength = 0;
237     for (Dsymbol *p = this; p; p = p->parent)
238         ++complength;
239 
240     // Allocate temporary array comp[]
241     const char **comp = (const char **)mem.xmalloc(complength * sizeof(char**));
242 
243     // Fill in comp[] and compute length of final result
244     size_t length = 0;
245     int i = 0;
246     for (Dsymbol *p = this; p; p = p->parent)
247     {
248         const char *s = QualifyTypes ? p->toPrettyCharsHelper() : p->toChars();
249         const size_t len = strlen(s);
250         comp[i] = s;
251         ++i;
252         length += len + 1;
253     }
254 
255     char *s = (char *)mem.xmalloc(length);
256     char *q = s + length - 1;
257     *q = 0;
258     for (size_t j = 0; j < complength; j++)
259     {
260         const char *t = comp[j];
261         const size_t len = strlen(t);
262         q -= len;
263         memcpy(q, t, len);
264         if (q == s)
265             break;
266         *--q = '.';
267     }
268     free(comp);
269     if (!QualifyTypes)
270         prettystring = (utf8_t *)s;
271     return s;
272 }
273 
getLoc()274 Loc& Dsymbol::getLoc()
275 {
276     if (!loc.filename)  // avoid bug 5861.
277     {
278         Module *m = getModule();
279 
280         if (m && m->srcfile)
281             loc.filename = m->srcfile->toChars();
282     }
283     return loc;
284 }
285 
locToChars()286 const char *Dsymbol::locToChars()
287 {
288     return getLoc().toChars();
289 }
290 
kind()291 const char *Dsymbol::kind() const
292 {
293     return "symbol";
294 }
295 
296 /*********************************
297  * If this symbol is really an alias for another,
298  * return that other.
299  * If needed, semantic() is invoked due to resolve forward reference.
300  */
toAlias()301 Dsymbol *Dsymbol::toAlias()
302 {
303     return this;
304 }
305 
306 /*********************************
307  * Resolve recursive tuple expansion in eponymous template.
308  */
toAlias2()309 Dsymbol *Dsymbol::toAlias2()
310 {
311     return toAlias();
312 }
313 
314 /**
315  * `pastMixin` returns the enclosing symbol if this is a template mixin.
316  *
317  * `pastMixinAndNspace` does likewise, additionally skipping over Nspaces that
318  * are mangleOnly.
319  *
320  * See also `parent`, `toParent`, `toParent2` and `toParent3`.
321  */
pastMixin()322 Dsymbol *Dsymbol::pastMixin()
323 {
324     Dsymbol *s = this;
325 
326     //printf("Dsymbol::pastMixin() %s\n", toChars());
327     while (s && s->isTemplateMixin())
328         s = s->parent;
329     return s;
330 }
331 
332 /// ditto
pastMixinAndNspace()333 Dsymbol *Dsymbol::pastMixinAndNspace()
334 {
335     //printf("Dsymbol::pastMixinAndNspace() %s\n", toChars());
336     Nspace *ns = isNspace();
337     if (!(ns && ns->mangleOnly) && !isTemplateMixin() && !isForwardingAttribDeclaration())
338         return this;
339     if (!parent)
340         return NULL;
341     return parent->pastMixinAndNspace();
342 }
343 
344 /**********************************
345  * `parent` field returns a lexically enclosing scope symbol this is a member of.
346  *
347  * `toParent()` returns a logically enclosing scope symbol this is a member of.
348  * It skips over TemplateMixin's and Nspaces that are mangleOnly.
349  *
350  * `toParent2()` returns an enclosing scope symbol this is living at runtime.
351  * It skips over both TemplateInstance's and TemplateMixin's.
352  * It's used when looking for the 'this' pointer of the enclosing function/class.
353  *
354  * `toParent3()` returns a logically enclosing scope symbol this is a member of.
355  * It skips over TemplateMixin's.
356  *
357  * Examples:
358  *  module mod;
359  *  template Foo(alias a) { mixin Bar!(); }
360  *  mixin template Bar() {
361  *    public {  // ProtDeclaration
362  *      void baz() { a = 2; }
363  *    }
364  *  }
365  *  void test() {
366  *    int v = 1;
367  *    alias foo = Foo!(v);
368  *    foo.baz();
369  *    assert(v == 2);
370  *  }
371  *
372  *  // s == FuncDeclaration('mod.test.Foo!().Bar!().baz()')
373  *  // s.parent == TemplateMixin('mod.test.Foo!().Bar!()')
374  *  // s.toParent() == TemplateInstance('mod.test.Foo!()')
375  *  // s.toParent2() == FuncDeclaration('mod.test')
376  */
toParent()377 Dsymbol *Dsymbol::toParent()
378 {
379     return parent ? parent->pastMixinAndNspace() : NULL;
380 }
381 
382 /// ditto
toParent2()383 Dsymbol *Dsymbol::toParent2()
384 {
385     Dsymbol *s = parent;
386     while (s && s->isTemplateInstance())
387         s = s->parent;
388     return s;
389 }
390 
391 /// ditto
toParent3()392 Dsymbol *Dsymbol::toParent3()
393 {
394     return parent ? parent->pastMixin() : NULL;
395 }
396 
isInstantiated()397 TemplateInstance *Dsymbol::isInstantiated()
398 {
399     for (Dsymbol *s = parent; s; s = s->parent)
400     {
401         TemplateInstance *ti = s->isTemplateInstance();
402         if (ti && !ti->isTemplateMixin())
403             return ti;
404     }
405     return NULL;
406 }
407 
408 // Check if this function is a member of a template which has only been
409 // instantiated speculatively, eg from inside is(typeof()).
410 // Return the speculative template instance it is part of,
411 // or NULL if not speculative.
isSpeculative()412 TemplateInstance *Dsymbol::isSpeculative()
413 {
414     Dsymbol *par = parent;
415     while (par)
416     {
417         TemplateInstance *ti = par->isTemplateInstance();
418         if (ti && ti->gagged)
419             return ti;
420         par = par->toParent();
421     }
422     return NULL;
423 }
424 
ungagSpeculative()425 Ungag Dsymbol::ungagSpeculative()
426 {
427     unsigned oldgag = global.gag;
428 
429     if (global.gag && !isSpeculative() && !toParent2()->isFuncDeclaration())
430         global.gag = 0;
431 
432     return Ungag(oldgag);
433 }
434 
isAnonymous()435 bool Dsymbol::isAnonymous()
436 {
437     return ident == NULL;
438 }
439 
440 /*************************************
441  * Set scope for future semantic analysis so we can
442  * deal better with forward references.
443  */
444 
setScope(Scope * sc)445 void Dsymbol::setScope(Scope *sc)
446 {
447     //printf("Dsymbol::setScope() %p %s, %p stc = %llx\n", this, toChars(), sc, sc->stc);
448     if (!sc->nofree)
449         sc->setNoFree();                // may need it even after semantic() finishes
450     _scope = sc;
451     if (sc->depdecl)
452         depdecl = sc->depdecl;
453 
454     if (!userAttribDecl)
455         userAttribDecl = sc->userAttribDecl;
456 }
457 
importAll(Scope *)458 void Dsymbol::importAll(Scope *)
459 {
460 }
461 
462 /*************************************
463  * Does semantic analysis on the public face of declarations.
464  */
465 
semantic(Scope *)466 void Dsymbol::semantic(Scope *)
467 {
468     error("%p has no semantic routine", this);
469 }
470 
471 /*************************************
472  * Does semantic analysis on initializers and members of aggregates.
473  */
474 
semantic2(Scope *)475 void Dsymbol::semantic2(Scope *)
476 {
477     // Most Dsymbols have no further semantic analysis needed
478 }
479 
480 /*************************************
481  * Does semantic analysis on function bodies.
482  */
483 
semantic3(Scope *)484 void Dsymbol::semantic3(Scope *)
485 {
486     // Most Dsymbols have no further semantic analysis needed
487 }
488 
489 /*********************************************
490  * Search for ident as member of s.
491  * Params:
492  *  loc = location to print for error messages
493  *  ident = identifier to search for
494  *  flags = IgnoreXXXX
495  * Returns:
496  *  NULL if not found
497  */
498 
search(const Loc &,Identifier *,int)499 Dsymbol *Dsymbol::search(const Loc &, Identifier *, int)
500 {
501     //printf("Dsymbol::search(this=%p,%s, ident='%s')\n", this, toChars(), ident->toChars());
502     return NULL;
503 }
504 
505 /***************************************************
506  * Search for symbol with correct spelling.
507  */
508 
symbol_search_fp(void * arg,const char * seed,int * cost)509 void *symbol_search_fp(void *arg, const char *seed, int *cost)
510 {
511     /* If not in the lexer's string table, it certainly isn't in the symbol table.
512      * Doing this first is a lot faster.
513      */
514     size_t len = strlen(seed);
515     if (!len)
516         return NULL;
517     Identifier *id = Identifier::lookup(seed, len);
518     if (!id)
519         return NULL;
520 
521     *cost = 0;
522     Dsymbol *s = (Dsymbol *)arg;
523     Module::clearCache();
524     return (void *)s->search(Loc(), id, IgnoreErrors);
525 }
526 
search_correct(Identifier * ident)527 Dsymbol *Dsymbol::search_correct(Identifier *ident)
528 {
529     if (global.gag)
530         return NULL;            // don't do it for speculative compiles; too time consuming
531 
532     return (Dsymbol *)speller(ident->toChars(), &symbol_search_fp, (void *)this, idchars);
533 }
534 
535 /***************************************
536  * Search for identifier id as a member of 'this'.
537  * id may be a template instance.
538  * Returns:
539  *      symbol found, NULL if not
540  */
searchX(Loc loc,Scope * sc,RootObject * id)541 Dsymbol *Dsymbol::searchX(Loc loc, Scope *sc, RootObject *id)
542 {
543     //printf("Dsymbol::searchX(this=%p,%s, ident='%s')\n", this, toChars(), ident->toChars());
544     Dsymbol *s = toAlias();
545     Dsymbol *sm;
546 
547     if (Declaration *d = s->isDeclaration())
548     {
549         if (d->inuse)
550         {
551             ::error(loc, "circular reference to '%s'", d->toPrettyChars());
552             return NULL;
553         }
554     }
555 
556     switch (id->dyncast())
557     {
558         case DYNCAST_IDENTIFIER:
559             sm = s->search(loc, (Identifier *)id);
560             break;
561 
562         case DYNCAST_DSYMBOL:
563         {
564             // It's a template instance
565             //printf("\ttemplate instance id\n");
566             Dsymbol *st = (Dsymbol *)id;
567             TemplateInstance *ti = st->isTemplateInstance();
568             sm = s->search(loc, ti->name);
569             if (!sm)
570             {
571                 sm = s->search_correct(ti->name);
572                 if (sm)
573                     ::error(loc, "template identifier '%s' is not a member of %s '%s', did you mean %s '%s'?",
574                           ti->name->toChars(), s->kind(), s->toPrettyChars(), sm->kind(), sm->toChars());
575                 else
576                     ::error(loc, "template identifier '%s' is not a member of %s '%s'",
577                           ti->name->toChars(), s->kind(), s->toPrettyChars());
578                 return NULL;
579             }
580             sm = sm->toAlias();
581             TemplateDeclaration *td = sm->isTemplateDeclaration();
582             if (!td)
583             {
584                 ::error(loc, "%s.%s is not a template, it is a %s", s->toPrettyChars(), ti->name->toChars(), sm->kind());
585                 return NULL;
586             }
587             ti->tempdecl = td;
588             if (!ti->semanticRun)
589                 ti->semantic(sc);
590             sm = ti->toAlias();
591             break;
592         }
593 
594         case DYNCAST_TYPE:
595         case DYNCAST_EXPRESSION:
596         default:
597             assert(0);
598     }
599     return sm;
600 }
601 
overloadInsert(Dsymbol *)602 bool Dsymbol::overloadInsert(Dsymbol *)
603 {
604     //printf("Dsymbol::overloadInsert('%s')\n", s->toChars());
605     return false;
606 }
607 
size(Loc)608 d_uns64 Dsymbol::size(Loc)
609 {
610     error("Dsymbol '%s' has no size", toChars());
611     return SIZE_INVALID;
612 }
613 
isforwardRef()614 bool Dsymbol::isforwardRef()
615 {
616     return false;
617 }
618 
isThis()619 AggregateDeclaration *Dsymbol::isThis()
620 {
621     return NULL;
622 }
623 
isExport()624 bool Dsymbol::isExport() const
625 {
626     return false;
627 }
628 
isImportedSymbol()629 bool Dsymbol::isImportedSymbol() const
630 {
631     return false;
632 }
633 
isDeprecated()634 bool Dsymbol::isDeprecated()
635 {
636     return false;
637 }
638 
isOverloadable()639 bool Dsymbol::isOverloadable()
640 {
641     return false;
642 }
643 
isLabel()644 LabelDsymbol *Dsymbol::isLabel()                // is this a LabelDsymbol()?
645 {
646     return NULL;
647 }
648 
649 /// Returns an AggregateDeclaration when toParent() is that.
isMember()650 AggregateDeclaration *Dsymbol::isMember()
651 {
652     //printf("Dsymbol::isMember() %s\n", toChars());
653     Dsymbol *parent = toParent();
654     //printf("parent is %s %s\n", parent->kind(), parent->toChars());
655     return parent ? parent->isAggregateDeclaration() : NULL;
656 }
657 
658 /// Returns an AggregateDeclaration when toParent2() is that.
isMember2()659 AggregateDeclaration *Dsymbol::isMember2()
660 {
661     //printf("Dsymbol::isMember2() %s\n", toChars());
662     Dsymbol *parent = toParent2();
663     //printf("parent is %s %s\n", parent->kind(), parent->toChars());
664     return parent ? parent->isAggregateDeclaration() : NULL;
665 }
666 
667 // is this a member of a ClassDeclaration?
isClassMember()668 ClassDeclaration *Dsymbol::isClassMember()
669 {
670     AggregateDeclaration *ad = isMember();
671     return ad ? ad->isClassDeclaration() : NULL;
672 }
673 
getType()674 Type *Dsymbol::getType()
675 {
676     return NULL;
677 }
678 
needThis()679 bool Dsymbol::needThis()
680 {
681     return false;
682 }
683 
684 /*********************************
685  * Iterate this dsymbol or members of this scoped dsymbol, then
686  * call `fp` with the found symbol and `param`.
687  * Params:
688  *  fp = function pointer to process the iterated symbol.
689  *       If it returns nonzero, the iteration will be aborted.
690  *  param = a parameter passed to fp.
691  * Returns:
692  *  nonzero if the iteration is aborted by the return value of fp,
693  *  or 0 if it's completed.
694  */
apply(Dsymbol_apply_ft_t fp,void * param)695 int Dsymbol::apply(Dsymbol_apply_ft_t fp, void *param)
696 {
697     return (*fp)(this, param);
698 }
699 
addMember(Scope *,ScopeDsymbol * sds)700 void Dsymbol::addMember(Scope *, ScopeDsymbol *sds)
701 {
702     //printf("Dsymbol::addMember('%s')\n", toChars());
703     //printf("Dsymbol::addMember(this = %p, '%s' scopesym = '%s')\n", this, toChars(), sds->toChars());
704     //printf("Dsymbol::addMember(this = %p, '%s' sds = %p, sds->symtab = %p)\n", this, toChars(), sds, sds->symtab);
705     parent = sds;
706     if (!isAnonymous())         // no name, so can't add it to symbol table
707     {
708         if (!sds->symtabInsert(this))    // if name is already defined
709         {
710             Dsymbol *s2 = sds->symtabLookup(this, ident);
711             if (!s2->overloadInsert(this))
712             {
713                 sds->multiplyDefined(Loc(), this, s2);
714                 errors = true;
715             }
716         }
717         if (sds->isAggregateDeclaration() || sds->isEnumDeclaration())
718         {
719             if (ident == Id::__sizeof || ident == Id::__xalignof || ident == Id::_mangleof)
720             {
721                 error(".%s property cannot be redefined", ident->toChars());
722                 errors = true;
723             }
724         }
725     }
726 }
727 
error(const char * format,...)728 void Dsymbol::error(const char *format, ...)
729 {
730     va_list ap;
731     va_start(ap, format);
732     ::verror(getLoc(), format, ap, kind(), toPrettyChars());
733     va_end(ap);
734 }
735 
error(Loc loc,const char * format,...)736 void Dsymbol::error(Loc loc, const char *format, ...)
737 {
738     va_list ap;
739     va_start(ap, format);
740     ::verror(loc, format, ap, kind(), toPrettyChars());
741     va_end(ap);
742 }
743 
deprecation(Loc loc,const char * format,...)744 void Dsymbol::deprecation(Loc loc, const char *format, ...)
745 {
746     va_list ap;
747     va_start(ap, format);
748     ::vdeprecation(loc, format, ap, kind(), toPrettyChars());
749     va_end(ap);
750 }
751 
deprecation(const char * format,...)752 void Dsymbol::deprecation(const char *format, ...)
753 {
754     va_list ap;
755     va_start(ap, format);
756     ::vdeprecation(getLoc(), format, ap, kind(), toPrettyChars());
757     va_end(ap);
758 }
759 
checkDeprecated(Loc loc,Scope * sc)760 void Dsymbol::checkDeprecated(Loc loc, Scope *sc)
761 {
762     if (global.params.useDeprecated != DIAGNOSTICoff && isDeprecated())
763     {
764         // Don't complain if we're inside a deprecated symbol's scope
765         for (Dsymbol *sp = sc->parent; sp; sp = sp->parent)
766         {
767             if (sp->isDeprecated())
768                 goto L1;
769         }
770 
771         for (Scope *sc2 = sc; sc2; sc2 = sc2->enclosing)
772         {
773             if (sc2->scopesym && sc2->scopesym->isDeprecated())
774                 goto L1;
775 
776             // If inside a StorageClassDeclaration that is deprecated
777             if (sc2->stc & STCdeprecated)
778                 goto L1;
779         }
780 
781         const char *message = NULL;
782         for (Dsymbol *p = this; p; p = p->parent)
783         {
784             message = p->depdecl ? p->depdecl->getMessage() : NULL;
785             if (message)
786                 break;
787         }
788 
789         if (message)
790             deprecation(loc, "is deprecated - %s", message);
791         else
792             deprecation(loc, "is deprecated");
793     }
794 
795   L1:
796     Declaration *d = isDeclaration();
797     if (d && d->storage_class & STCdisable)
798     {
799         if (!(sc->func && sc->func->storage_class & STCdisable))
800         {
801             if (d->toParent() && d->isPostBlitDeclaration())
802                 d->toParent()->error(loc, "is not copyable because it is annotated with @disable");
803             else
804                 error(loc, "is not callable because it is annotated with @disable");
805         }
806     }
807 }
808 
809 /**********************************
810  * Determine which Module a Dsymbol is in.
811  */
812 
getModule()813 Module *Dsymbol::getModule()
814 {
815     //printf("Dsymbol::getModule()\n");
816     if (TemplateInstance *ti = isInstantiated())
817         return ti->tempdecl->getModule();
818 
819     Dsymbol *s = this;
820     while (s)
821     {
822         //printf("\ts = %s '%s'\n", s->kind(), s->toPrettyChars());
823         Module *m = s->isModule();
824         if (m)
825             return m;
826         s = s->parent;
827     }
828     return NULL;
829 }
830 
831 /**********************************
832  * Determine which Module a Dsymbol is in, as far as access rights go.
833  */
834 
getAccessModule()835 Module *Dsymbol::getAccessModule()
836 {
837     //printf("Dsymbol::getAccessModule()\n");
838     if (TemplateInstance *ti = isInstantiated())
839         return ti->tempdecl->getAccessModule();
840 
841     Dsymbol *s = this;
842     while (s)
843     {
844         //printf("\ts = %s '%s'\n", s->kind(), s->toPrettyChars());
845         Module *m = s->isModule();
846         if (m)
847             return m;
848         TemplateInstance *ti = s->isTemplateInstance();
849         if (ti && ti->enclosing)
850         {
851             /* Because of local template instantiation, the parent isn't where the access
852              * rights come from - it's the template declaration
853              */
854             s = ti->tempdecl;
855         }
856         else
857             s = s->parent;
858     }
859     return NULL;
860 }
861 
862 /*************************************
863  */
864 
prot()865 Prot Dsymbol::prot()
866 {
867     return Prot(PROTpublic);
868 }
869 
870 /*************************************
871  * Do syntax copy of an array of Dsymbol's.
872  */
873 
arraySyntaxCopy(Dsymbols * a)874 Dsymbols *Dsymbol::arraySyntaxCopy(Dsymbols *a)
875 {
876 
877     Dsymbols *b = NULL;
878     if (a)
879     {
880         b = a->copy();
881         for (size_t i = 0; i < b->dim; i++)
882         {
883             (*b)[i] = (*b)[i]->syntaxCopy(NULL);
884         }
885     }
886     return b;
887 }
888 
889 /****************************************
890  * Add documentation comment to Dsymbol.
891  * Ignore NULL comments.
892  */
893 
addComment(const utf8_t * comment)894 void Dsymbol::addComment(const utf8_t *comment)
895 {
896     //if (comment)
897         //printf("adding comment '%s' to symbol %p '%s'\n", comment, this, toChars());
898 
899     if (!this->comment)
900         this->comment = comment;
901     else if (comment && strcmp((const char *)comment, (const char *)this->comment) != 0)
902     {   // Concatenate the two
903         this->comment = Lexer::combineComments(this->comment, comment);
904     }
905 }
906 
907 /****************************************
908  * Returns true if this symbol is defined in a non-root module without instantiation.
909  */
inNonRoot()910 bool Dsymbol::inNonRoot()
911 {
912     Dsymbol *s = parent;
913     for (; s; s = s->toParent())
914     {
915         if (s->isTemplateInstance())
916         {
917             return false;
918         }
919         if (Module *m = s->isModule())
920         {
921             if (!m->isRoot())
922                 return true;
923             break;
924         }
925     }
926     return false;
927 }
928 
929 /********************************* OverloadSet ****************************/
930 
OverloadSet(Identifier * ident,OverloadSet * os)931 OverloadSet::OverloadSet(Identifier *ident, OverloadSet *os)
932     : Dsymbol(ident)
933 {
934     if (os)
935     {
936         for (size_t i = 0; i < os->a.dim; i++)
937         {
938             a.push(os->a[i]);
939         }
940     }
941 }
942 
push(Dsymbol * s)943 void OverloadSet::push(Dsymbol *s)
944 {
945     a.push(s);
946 }
947 
kind()948 const char *OverloadSet::kind() const
949 {
950     return "overloadset";
951 }
952 
953 
954 /********************************* ScopeDsymbol ****************************/
955 
ScopeDsymbol()956 ScopeDsymbol::ScopeDsymbol()
957     : Dsymbol()
958 {
959     members = NULL;
960     symtab = NULL;
961     endlinnum = 0;
962     importedScopes = NULL;
963     prots = NULL;
964 }
965 
ScopeDsymbol(Identifier * id)966 ScopeDsymbol::ScopeDsymbol(Identifier *id)
967     : Dsymbol(id)
968 {
969     members = NULL;
970     symtab = NULL;
971     endlinnum = 0;
972     importedScopes = NULL;
973     prots = NULL;
974 }
975 
syntaxCopy(Dsymbol * s)976 Dsymbol *ScopeDsymbol::syntaxCopy(Dsymbol *s)
977 {
978     //printf("ScopeDsymbol::syntaxCopy('%s')\n", toChars());
979     ScopeDsymbol *sds = s ? (ScopeDsymbol *)s : new ScopeDsymbol(ident);
980     sds->members = arraySyntaxCopy(members);
981     sds->endlinnum = endlinnum;
982     return sds;
983 }
984 
semantic(Scope *)985 void ScopeDsymbol::semantic(Scope *)
986 {
987 }
988 
989 /*****************************************
990  * This function is #1 on the list of functions that eat cpu time.
991  * Be very, very careful about slowing it down.
992  */
993 
search(const Loc & loc,Identifier * ident,int flags)994 Dsymbol *ScopeDsymbol::search(const Loc &loc, Identifier *ident, int flags)
995 {
996     //printf("%s->ScopeDsymbol::search(ident='%s', flags=x%x)\n", toChars(), ident->toChars(), flags);
997     //if (strcmp(ident->toChars(),"c") == 0) *(char*)0=0;
998 
999     // Look in symbols declared in this module
1000     if (symtab && !(flags & SearchImportsOnly))
1001     {
1002         //printf(" look in locals\n");
1003         Dsymbol *s1 = symtab->lookup(ident);
1004         if (s1)
1005         {
1006             //printf("\tfound in locals = '%s.%s'\n",toChars(),s1->toChars());
1007             return s1;
1008         }
1009     }
1010     //printf(" not found in locals\n");
1011 
1012     // Look in imported scopes
1013     if (importedScopes)
1014     {
1015         //printf(" look in imports\n");
1016         Dsymbol *s = NULL;
1017         OverloadSet *a = NULL;
1018 
1019         // Look in imported modules
1020         for (size_t i = 0; i < importedScopes->dim; i++)
1021         {
1022             // If private import, don't search it
1023             if ((flags & IgnorePrivateImports) && prots[i] == PROTprivate)
1024                 continue;
1025 
1026             int sflags = flags & (IgnoreErrors | IgnoreAmbiguous | IgnoreSymbolVisibility); // remember these in recursive searches
1027             Dsymbol *ss = (*importedScopes)[i];
1028 
1029             //printf("\tscanning import '%s', prots = %d, isModule = %p, isImport = %p\n", ss->toChars(), prots[i], ss->isModule(), ss->isImport());
1030 
1031             if (ss->isModule())
1032             {
1033                 if (flags & SearchLocalsOnly)
1034                     continue;
1035             }
1036             else // mixin template
1037             {
1038                 if (flags & SearchImportsOnly)
1039                     continue;
1040                 // compatibility with -transition=import (Bugzilla 15925)
1041                 // SearchLocalsOnly should always get set for new lookup rules
1042                 sflags |= (flags & SearchLocalsOnly);
1043             }
1044 
1045             /* Don't find private members if ss is a module
1046              */
1047             Dsymbol *s2 = ss->search(loc, ident, sflags | (ss->isModule() ? IgnorePrivateImports : IgnoreNone));
1048             if (!s2 || (!(flags & IgnoreSymbolVisibility) && !symbolIsVisible(this, s2)))
1049                 continue;
1050             if (!s)
1051             {
1052                 s = s2;
1053                 if (s && s->isOverloadSet())
1054                     a = mergeOverloadSet(ident, a, s);
1055             }
1056             else if (s2 && s != s2)
1057             {
1058                 if (s->toAlias() == s2->toAlias() ||
1059                     (s->getType() == s2->getType() && s->getType()))
1060                 {
1061                     /* After following aliases, we found the same
1062                      * symbol, so it's not an ambiguity.  But if one
1063                      * alias is deprecated or less accessible, prefer
1064                      * the other.
1065                      */
1066                     if (s->isDeprecated() ||
1067                         (s->prot().isMoreRestrictiveThan(s2->prot()) && s2->prot().kind != PROTnone))
1068                         s = s2;
1069                 }
1070                 else
1071                 {
1072                     /* Two imports of the same module should be regarded as
1073                      * the same.
1074                      */
1075                     Import *i1 = s->isImport();
1076                     Import *i2 = s2->isImport();
1077                     if (!(i1 && i2 &&
1078                           (i1->mod == i2->mod ||
1079                            (!i1->parent->isImport() && !i2->parent->isImport() &&
1080                             i1->ident->equals(i2->ident))
1081                           )
1082                          )
1083                        )
1084                     {
1085                         /* Bugzilla 8668:
1086                          * Public selective import adds AliasDeclaration in module.
1087                          * To make an overload set, resolve aliases in here and
1088                          * get actual overload roots which accessible via s and s2.
1089                          */
1090                         s = s->toAlias();
1091                         s2 = s2->toAlias();
1092 
1093                         /* If both s2 and s are overloadable (though we only
1094                          * need to check s once)
1095                          */
1096                         if ((s2->isOverloadSet() || s2->isOverloadable()) &&
1097                             (a || s->isOverloadable()))
1098                         {
1099                             a = mergeOverloadSet(ident, a, s2);
1100                             continue;
1101                         }
1102                         if (flags & IgnoreAmbiguous)    // if return NULL on ambiguity
1103                             return NULL;
1104                         if (!(flags & IgnoreErrors))
1105                             ScopeDsymbol::multiplyDefined(loc, s, s2);
1106                         break;
1107                     }
1108                 }
1109             }
1110         }
1111 
1112         if (s)
1113         {
1114             /* Build special symbol if we had multiple finds
1115              */
1116             if (a)
1117             {
1118                 if (!s->isOverloadSet())
1119                     a = mergeOverloadSet(ident, a, s);
1120                 s = a;
1121             }
1122 
1123             // TODO: remove once private symbol visibility has been deprecated
1124             if (!(flags & IgnoreErrors) && s->prot().kind == PROTprivate &&
1125                 !s->isOverloadable() && !s->parent->isTemplateMixin() && !s->parent->isNspace())
1126             {
1127                 AliasDeclaration *ad;
1128                 // accessing private selective and renamed imports is
1129                 // deprecated by restricting the symbol visibility
1130                 if (s->isImport() || ((ad = s->isAliasDeclaration()) != NULL && ad->_import != NULL))
1131                 {}
1132                 else
1133                     error(loc, "%s %s is private", s->kind(), s->toPrettyChars());
1134             }
1135             //printf("\tfound in imports %s.%s\n", toChars(), s.toChars());
1136             return s;
1137         }
1138         //printf(" not found in imports\n");
1139     }
1140 
1141     return NULL;
1142 }
1143 
mergeOverloadSet(Identifier * ident,OverloadSet * os,Dsymbol * s)1144 OverloadSet *ScopeDsymbol::mergeOverloadSet(Identifier *ident, OverloadSet *os, Dsymbol *s)
1145 {
1146     if (!os)
1147     {
1148         os = new OverloadSet(ident);
1149         os->parent = this;
1150     }
1151     if (OverloadSet *os2 = s->isOverloadSet())
1152     {
1153         // Merge the cross-module overload set 'os2' into 'os'
1154         if (os->a.dim == 0)
1155         {
1156             os->a.setDim(os2->a.dim);
1157             memcpy(os->a.tdata(), os2->a.tdata(), sizeof(os->a[0]) * os2->a.dim);
1158         }
1159         else
1160         {
1161             for (size_t i = 0; i < os2->a.dim; i++)
1162             {
1163                 os = mergeOverloadSet(ident, os, os2->a[i]);
1164             }
1165         }
1166     }
1167     else
1168     {
1169         assert(s->isOverloadable());
1170 
1171         /* Don't add to os[] if s is alias of previous sym
1172          */
1173         for (size_t j = 0; j < os->a.dim; j++)
1174         {
1175             Dsymbol *s2 = os->a[j];
1176             if (s->toAlias() == s2->toAlias())
1177             {
1178                 if (s2->isDeprecated() ||
1179                     (s2->prot().isMoreRestrictiveThan(s->prot()) &&
1180                      s->prot().kind != PROTnone))
1181                 {
1182                     os->a[j] = s;
1183                 }
1184                 goto Lcontinue;
1185             }
1186         }
1187         os->push(s);
1188     Lcontinue:
1189         ;
1190     }
1191     return os;
1192 }
1193 
importScope(Dsymbol * s,Prot protection)1194 void ScopeDsymbol::importScope(Dsymbol *s, Prot protection)
1195 {
1196     //printf("%s->ScopeDsymbol::importScope(%s, %d)\n", toChars(), s->toChars(), protection);
1197 
1198     // No circular or redundant import's
1199     if (s != this)
1200     {
1201         if (!importedScopes)
1202             importedScopes = new Dsymbols();
1203         else
1204         {
1205             for (size_t i = 0; i < importedScopes->dim; i++)
1206             {
1207                 Dsymbol *ss = (*importedScopes)[i];
1208                 if (ss == s)                    // if already imported
1209                 {
1210                     if (protection.kind > prots[i])
1211                         prots[i] = protection.kind;  // upgrade access
1212                     return;
1213                 }
1214             }
1215         }
1216         importedScopes->push(s);
1217         prots = (PROTKIND *)mem.xrealloc(prots, importedScopes->dim * sizeof(prots[0]));
1218         prots[importedScopes->dim - 1] = protection.kind;
1219     }
1220 }
1221 
1222 #define BITS_PER_INDEX (sizeof(size_t) * CHAR_BIT)
1223 
bitArraySet(BitArray * array,size_t idx)1224 static void bitArraySet(BitArray *array, size_t idx)
1225 {
1226     array->ptr[idx / BITS_PER_INDEX] |= 1ULL << (idx % BITS_PER_INDEX);
1227 }
1228 
bitArrayGet(BitArray * array,size_t idx)1229 static bool bitArrayGet(BitArray *array, size_t idx)
1230 {
1231     const size_t boffset = idx % BITS_PER_INDEX;
1232     return (array->ptr[idx / BITS_PER_INDEX] & (1ULL << boffset)) >> boffset;
1233 }
1234 
bitArrayLength(BitArray * array,size_t len)1235 static void bitArrayLength(BitArray *array, size_t len)
1236 {
1237     if (array->len < len)
1238     {
1239         const size_t obytes = (array->len + BITS_PER_INDEX - 1) / BITS_PER_INDEX;
1240         const size_t nbytes = (len + BITS_PER_INDEX - 1) / BITS_PER_INDEX;
1241 
1242         if (!array->ptr)
1243             array->ptr = (size_t *)mem.xmalloc(nbytes * sizeof(size_t));
1244         else
1245             array->ptr = (size_t *)mem.xrealloc(array->ptr, nbytes * sizeof(size_t));
1246 
1247         for (size_t i = obytes; i < nbytes; i++)
1248             array->ptr[i] = 0;
1249 
1250         array->len = nbytes * BITS_PER_INDEX;
1251     }
1252 }
1253 
addAccessiblePackage(Package * p,Prot protection)1254 void ScopeDsymbol::addAccessiblePackage(Package *p, Prot protection)
1255 {
1256     BitArray *pary = protection.kind == PROTprivate ? &privateAccessiblePackages : &accessiblePackages;
1257     if (pary->len <= p->tag)
1258         bitArrayLength(pary, p->tag + 1);
1259     bitArraySet(pary, p->tag);
1260 }
1261 
isPackageAccessible(Package * p,Prot protection,int)1262 bool ScopeDsymbol::isPackageAccessible(Package *p, Prot protection, int)
1263 {
1264     if ((p->tag < accessiblePackages.len && bitArrayGet(&accessiblePackages, p->tag)) ||
1265         (protection.kind == PROTprivate && p->tag < privateAccessiblePackages.len && bitArrayGet(&privateAccessiblePackages, p->tag)))
1266         return true;
1267     if (importedScopes)
1268     {
1269         for (size_t i = 0; i < importedScopes->dim; i++)
1270         {
1271             // only search visible scopes && imported modules should ignore private imports
1272             Dsymbol *ss = (*importedScopes)[i];
1273             if (protection.kind <= prots[i] &&
1274                 ss->isScopeDsymbol()->isPackageAccessible(p, protection, IgnorePrivateImports))
1275                 return true;
1276         }
1277     }
1278     return false;
1279 }
1280 
isforwardRef()1281 bool ScopeDsymbol::isforwardRef()
1282 {
1283     return (members == NULL);
1284 }
1285 
multiplyDefined(Loc loc,Dsymbol * s1,Dsymbol * s2)1286 void ScopeDsymbol::multiplyDefined(Loc loc, Dsymbol *s1, Dsymbol *s2)
1287 {
1288     if (loc.filename)
1289     {   ::error(loc, "%s at %s conflicts with %s at %s",
1290             s1->toPrettyChars(),
1291             s1->locToChars(),
1292             s2->toPrettyChars(),
1293             s2->locToChars());
1294     }
1295     else
1296     {
1297         s1->error(s1->loc, "conflicts with %s %s at %s",
1298             s2->kind(),
1299             s2->toPrettyChars(),
1300             s2->locToChars());
1301     }
1302 }
1303 
kind()1304 const char *ScopeDsymbol::kind() const
1305 {
1306     return "ScopeDsymbol";
1307 }
1308 
symtabInsert(Dsymbol * s)1309 Dsymbol *ScopeDsymbol::symtabInsert(Dsymbol *s)
1310 {
1311     return symtab->insert(s);
1312 }
1313 
1314 /****************************************
1315  * Look up identifier in symbol table.
1316  */
1317 
symtabLookup(Dsymbol *,Identifier * id)1318 Dsymbol *ScopeDsymbol::symtabLookup(Dsymbol *, Identifier *id)
1319 {
1320     return symtab->lookup(id);
1321 }
1322 
1323 /****************************************
1324  * Return true if any of the members are static ctors or static dtors, or if
1325  * any members have members that are.
1326  */
1327 
hasStaticCtorOrDtor()1328 bool ScopeDsymbol::hasStaticCtorOrDtor()
1329 {
1330     if (members)
1331     {
1332         for (size_t i = 0; i < members->dim; i++)
1333         {   Dsymbol *member = (*members)[i];
1334 
1335             if (member->hasStaticCtorOrDtor())
1336                 return true;
1337         }
1338     }
1339     return false;
1340 }
1341 
1342 /***************************************
1343  * Determine number of Dsymbols, folding in AttribDeclaration members.
1344  */
1345 
dimDg(void * ctx,size_t,Dsymbol *)1346 static int dimDg(void *ctx, size_t, Dsymbol *)
1347 {
1348     ++*(size_t *)ctx;
1349     return 0;
1350 }
1351 
dim(Dsymbols * members)1352 size_t ScopeDsymbol::dim(Dsymbols *members)
1353 {
1354     size_t n = 0;
1355     ScopeDsymbol_foreach(NULL, members, &dimDg, &n);
1356     return n;
1357 }
1358 
1359 /***************************************
1360  * Get nth Dsymbol, folding in AttribDeclaration members.
1361  * Returns:
1362  *      Dsymbol*        nth Dsymbol
1363  *      NULL            not found, *pn gets incremented by the number
1364  *                      of Dsymbols
1365  */
1366 
1367 struct GetNthSymbolCtx
1368 {
1369     size_t nth;
1370     Dsymbol *sym;
1371 };
1372 
getNthSymbolDg(void * ctx,size_t n,Dsymbol * sym)1373 static int getNthSymbolDg(void *ctx, size_t n, Dsymbol *sym)
1374 {
1375     GetNthSymbolCtx *p = (GetNthSymbolCtx *)ctx;
1376     if (n == p->nth)
1377     {   p->sym = sym;
1378         return 1;
1379     }
1380     return 0;
1381 }
1382 
getNth(Dsymbols * members,size_t nth,size_t *)1383 Dsymbol *ScopeDsymbol::getNth(Dsymbols *members, size_t nth, size_t *)
1384 {
1385     GetNthSymbolCtx ctx = { nth, NULL };
1386     int res = ScopeDsymbol_foreach(NULL, members, &getNthSymbolDg, &ctx);
1387     return res ? ctx.sym : NULL;
1388 }
1389 
1390 /***************************************
1391  * Expands attribute declarations in members in depth first
1392  * order. Calls dg(void *ctx, size_t symidx, Dsymbol *sym) for each
1393  * member.
1394  * If dg returns !=0, stops and returns that value else returns 0.
1395  * Use this function to avoid the O(N + N^2/2) complexity of
1396  * calculating dim and calling N times getNth.
1397  */
1398 
ScopeDsymbol_foreach(Scope * sc,Dsymbols * members,ForeachDg dg,void * ctx,size_t * pn)1399 int ScopeDsymbol_foreach(Scope *sc, Dsymbols *members, ForeachDg dg, void *ctx, size_t *pn)
1400 {
1401     assert(dg);
1402     if (!members)
1403         return 0;
1404 
1405     size_t n = pn ? *pn : 0; // take over index
1406     int result = 0;
1407     for (size_t i = 0; i < members->dim; i++)
1408     {   Dsymbol *s = (*members)[i];
1409 
1410         if (AttribDeclaration *a = s->isAttribDeclaration())
1411             result = ScopeDsymbol_foreach(sc, a->include(sc, NULL), dg, ctx, &n);
1412         else if (TemplateMixin *tm = s->isTemplateMixin())
1413             result = ScopeDsymbol_foreach(sc, tm->members, dg, ctx, &n);
1414         else if (s->isTemplateInstance())
1415             ;
1416         else if (s->isUnitTestDeclaration())
1417             ;
1418         else
1419             result = dg(ctx, n++, s);
1420 
1421         if (result)
1422             break;
1423     }
1424 
1425     if (pn)
1426         *pn = n; // update index
1427     return result;
1428 }
1429 
1430 /*******************************************
1431  * Look for member of the form:
1432  *      const(MemberInfo)[] getMembers(string);
1433  * Returns NULL if not found
1434  */
1435 
findGetMembers()1436 FuncDeclaration *ScopeDsymbol::findGetMembers()
1437 {
1438     Dsymbol *s = search_function(this, Id::getmembers);
1439     FuncDeclaration *fdx = s ? s->isFuncDeclaration() : NULL;
1440 
1441     if (fdx && fdx->isVirtual())
1442         fdx = NULL;
1443 
1444     return fdx;
1445 }
1446 
1447 
1448 /****************************** WithScopeSymbol ******************************/
1449 
WithScopeSymbol(WithStatement * withstate)1450 WithScopeSymbol::WithScopeSymbol(WithStatement *withstate)
1451     : ScopeDsymbol()
1452 {
1453     this->withstate = withstate;
1454 }
1455 
search(const Loc & loc,Identifier * ident,int flags)1456 Dsymbol *WithScopeSymbol::search(const Loc &loc, Identifier *ident, int flags)
1457 {
1458     //printf("WithScopeSymbol::search(%s)\n", ident->toChars());
1459     if (flags & SearchImportsOnly)
1460         return NULL;
1461 
1462     // Acts as proxy to the with class declaration
1463     Dsymbol *s = NULL;
1464     Expression *eold = NULL;
1465     for (Expression *e = withstate->exp; e != eold; e = resolveAliasThis(_scope, e))
1466     {
1467         if (e->op == TOKscope)
1468         {
1469             s = ((ScopeExp *)e)->sds;
1470         }
1471         else if (e->op == TOKtype)
1472         {
1473             s = e->type->toDsymbol(NULL);
1474         }
1475         else
1476         {
1477             Type *t = e->type->toBasetype();
1478             s = t->toDsymbol(NULL);
1479         }
1480         if (s)
1481         {
1482             s = s->search(loc, ident, flags);
1483             if (s)
1484                 return s;
1485         }
1486         eold = e;
1487     }
1488     return NULL;
1489 }
1490 
1491 /****************************** ArrayScopeSymbol ******************************/
1492 
ArrayScopeSymbol(Scope * sc,Expression * e)1493 ArrayScopeSymbol::ArrayScopeSymbol(Scope *sc, Expression *e)
1494     : ScopeDsymbol()
1495 {
1496     assert(e->op == TOKindex || e->op == TOKslice || e->op == TOKarray);
1497     exp = e;
1498     type = NULL;
1499     td = NULL;
1500     this->sc = sc;
1501 }
1502 
ArrayScopeSymbol(Scope * sc,TypeTuple * t)1503 ArrayScopeSymbol::ArrayScopeSymbol(Scope *sc, TypeTuple *t)
1504     : ScopeDsymbol()
1505 {
1506     exp = NULL;
1507     type = t;
1508     td = NULL;
1509     this->sc = sc;
1510 }
1511 
ArrayScopeSymbol(Scope * sc,TupleDeclaration * s)1512 ArrayScopeSymbol::ArrayScopeSymbol(Scope *sc, TupleDeclaration *s)
1513     : ScopeDsymbol()
1514 {
1515     exp = NULL;
1516     type = NULL;
1517     td = s;
1518     this->sc = sc;
1519 }
1520 
search(const Loc & loc,Identifier * ident,int)1521 Dsymbol *ArrayScopeSymbol::search(const Loc &loc, Identifier *ident, int)
1522 {
1523     //printf("ArrayScopeSymbol::search('%s', flags = %d)\n", ident->toChars(), flags);
1524     if (ident == Id::dollar)
1525     {
1526         VarDeclaration **pvar;
1527         Expression *ce;
1528 
1529     L1:
1530         if (td)
1531         {
1532             /* $ gives the number of elements in the tuple
1533              */
1534             VarDeclaration *v = new VarDeclaration(loc, Type::tsize_t, Id::dollar, NULL);
1535             Expression *e = new IntegerExp(Loc(), td->objects->dim, Type::tsize_t);
1536             v->_init = new ExpInitializer(Loc(), e);
1537             v->storage_class |= STCtemp | STCstatic | STCconst;
1538             v->semantic(sc);
1539             return v;
1540         }
1541 
1542         if (type)
1543         {
1544             /* $ gives the number of type entries in the type tuple
1545              */
1546             VarDeclaration *v = new VarDeclaration(loc, Type::tsize_t, Id::dollar, NULL);
1547             Expression *e = new IntegerExp(Loc(), type->arguments->dim, Type::tsize_t);
1548             v->_init = new ExpInitializer(Loc(), e);
1549             v->storage_class |= STCtemp | STCstatic | STCconst;
1550             v->semantic(sc);
1551             return v;
1552         }
1553 
1554         if (exp->op == TOKindex)
1555         {
1556             /* array[index] where index is some function of $
1557              */
1558             IndexExp *ie = (IndexExp *)exp;
1559             pvar = &ie->lengthVar;
1560             ce = ie->e1;
1561         }
1562         else if (exp->op == TOKslice)
1563         {
1564             /* array[lwr .. upr] where lwr or upr is some function of $
1565              */
1566             SliceExp *se = (SliceExp *)exp;
1567             pvar = &se->lengthVar;
1568             ce = se->e1;
1569         }
1570         else if (exp->op == TOKarray)
1571         {
1572             /* array[e0, e1, e2, e3] where e0, e1, e2 are some function of $
1573              * $ is a opDollar!(dim)() where dim is the dimension(0,1,2,...)
1574              */
1575             ArrayExp *ae = (ArrayExp *)exp;
1576             pvar = &ae->lengthVar;
1577             ce = ae->e1;
1578         }
1579         else
1580         {
1581             /* Didn't find $, look in enclosing scope(s).
1582              */
1583             return NULL;
1584         }
1585 
1586         while (ce->op == TOKcomma)
1587             ce = ((CommaExp *)ce)->e2;
1588 
1589         /* If we are indexing into an array that is really a type
1590          * tuple, rewrite this as an index into a type tuple and
1591          * try again.
1592          */
1593         if (ce->op == TOKtype)
1594         {
1595             Type *t = ((TypeExp *)ce)->type;
1596             if (t->ty == Ttuple)
1597             {
1598                 type = (TypeTuple *)t;
1599                 goto L1;
1600             }
1601         }
1602 
1603         /* *pvar is lazily initialized, so if we refer to $
1604          * multiple times, it gets set only once.
1605          */
1606         if (!*pvar)             // if not already initialized
1607         {
1608             /* Create variable v and set it to the value of $
1609              */
1610             VarDeclaration *v;
1611             Type *t;
1612             if (ce->op == TOKtuple)
1613             {
1614                 /* It is for an expression tuple, so the
1615                  * length will be a const.
1616                  */
1617                 Expression *e = new IntegerExp(Loc(), ((TupleExp *)ce)->exps->dim, Type::tsize_t);
1618                 v = new VarDeclaration(loc, Type::tsize_t, Id::dollar, new ExpInitializer(Loc(), e));
1619                 v->storage_class |= STCtemp | STCstatic | STCconst;
1620             }
1621             else if (ce->type && (t = ce->type->toBasetype()) != NULL &&
1622                      (t->ty == Tstruct || t->ty == Tclass))
1623             {
1624                 // Look for opDollar
1625                 assert(exp->op == TOKarray || exp->op == TOKslice);
1626                 AggregateDeclaration *ad = isAggregate(t);
1627                 assert(ad);
1628 
1629                 Dsymbol *s = ad->search(loc, Id::opDollar);
1630                 if (!s)  // no dollar exists -- search in higher scope
1631                     return NULL;
1632                 s = s->toAlias();
1633 
1634                 Expression *e = NULL;
1635                 // Check for multi-dimensional opDollar(dim) template.
1636                 if (TemplateDeclaration *td = s->isTemplateDeclaration())
1637                 {
1638                     dinteger_t dim = 0;
1639                     if (exp->op == TOKarray)
1640                     {
1641                         dim = ((ArrayExp *)exp)->currentDimension;
1642                     }
1643                     else if (exp->op == TOKslice)
1644                     {
1645                         dim = 0; // slices are currently always one-dimensional
1646                     }
1647                     else
1648                     {
1649                         assert(0);
1650                     }
1651 
1652                     Objects *tiargs = new Objects();
1653                     Expression *edim = new IntegerExp(Loc(), dim, Type::tsize_t);
1654                     edim = ::semantic(edim, sc);
1655                     tiargs->push(edim);
1656                     e = new DotTemplateInstanceExp(loc, ce, td->ident, tiargs);
1657                 }
1658                 else
1659                 {
1660                     /* opDollar exists, but it's not a template.
1661                      * This is acceptable ONLY for single-dimension indexing.
1662                      * Note that it's impossible to have both template & function opDollar,
1663                      * because both take no arguments.
1664                      */
1665                     if (exp->op == TOKarray && ((ArrayExp *)exp)->arguments->dim != 1)
1666                     {
1667                         exp->error("%s only defines opDollar for one dimension", ad->toChars());
1668                         return NULL;
1669                     }
1670                     Declaration *d = s->isDeclaration();
1671                     assert(d);
1672                     e = new DotVarExp(loc, ce, d);
1673                 }
1674                 e = ::semantic(e, sc);
1675                 if (!e->type)
1676                     exp->error("%s has no value", e->toChars());
1677                 t = e->type->toBasetype();
1678                 if (t && t->ty == Tfunction)
1679                     e = new CallExp(e->loc, e);
1680                 v = new VarDeclaration(loc, NULL, Id::dollar, new ExpInitializer(Loc(), e));
1681                 v->storage_class |= STCtemp | STCctfe | STCrvalue;
1682             }
1683             else
1684             {
1685                 /* For arrays, $ will either be a compile-time constant
1686                  * (in which case its value in set during constant-folding),
1687                  * or a variable (in which case an expression is created in
1688                  * toir.c).
1689                  */
1690                 VoidInitializer *e = new VoidInitializer(Loc());
1691                 e->type = Type::tsize_t;
1692                 v = new VarDeclaration(loc, Type::tsize_t, Id::dollar, e);
1693                 v->storage_class |= STCtemp | STCctfe; // it's never a true static variable
1694             }
1695             *pvar = v;
1696         }
1697         (*pvar)->semantic(sc);
1698         return (*pvar);
1699     }
1700     return NULL;
1701 }
1702 
1703 
1704 /****************************** DsymbolTable ******************************/
1705 
DsymbolTable()1706 DsymbolTable::DsymbolTable()
1707 {
1708     tab = NULL;
1709 }
1710 
lookup(Identifier const * const ident)1711 Dsymbol *DsymbolTable::lookup(Identifier const * const ident)
1712 {
1713     //printf("DsymbolTable::lookup(%s)\n", (char*)ident->string);
1714     return (Dsymbol *)dmd_aaGetRvalue(tab, const_cast<void *>((const void *)ident));
1715 }
1716 
insert(Dsymbol * s)1717 Dsymbol *DsymbolTable::insert(Dsymbol *s)
1718 {
1719     //printf("DsymbolTable::insert(this = %p, '%s')\n", this, s->ident->toChars());
1720     Identifier *ident = s->ident;
1721     Dsymbol **ps = (Dsymbol **)dmd_aaGet(&tab, (void *)ident);
1722     if (*ps)
1723         return NULL;            // already in table
1724     *ps = s;
1725     return s;
1726 }
1727 
insert(Identifier const * const ident,Dsymbol * s)1728 Dsymbol *DsymbolTable::insert(Identifier const * const ident, Dsymbol *s)
1729 {
1730     //printf("DsymbolTable::insert()\n");
1731     Dsymbol **ps = (Dsymbol **)dmd_aaGet(&tab, const_cast<void *>((const void *)ident));
1732     if (*ps)
1733         return NULL;            // already in table
1734     *ps = s;
1735     return s;
1736 }
1737 
update(Dsymbol * s)1738 Dsymbol *DsymbolTable::update(Dsymbol *s)
1739 {
1740     Identifier *ident = s->ident;
1741     Dsymbol **ps = (Dsymbol **)dmd_aaGet(&tab, (void *)ident);
1742     *ps = s;
1743     return s;
1744 }
1745 
1746 /****************************** Prot ******************************/
1747 
Prot()1748 Prot::Prot()
1749 {
1750     this->kind = PROTundefined;
1751     this->pkg = NULL;
1752 }
1753 
Prot(PROTKIND kind)1754 Prot::Prot(PROTKIND kind)
1755 {
1756     this->kind = kind;
1757     this->pkg = NULL;
1758 }
1759 
1760 /**
1761  * Checks if `this` is superset of `other` restrictions.
1762  * For example, "protected" is more restrictive than "public".
1763  */
isMoreRestrictiveThan(const Prot other)1764 bool Prot::isMoreRestrictiveThan(const Prot other) const
1765 {
1766     return this->kind < other.kind;
1767 }
1768 
1769 /**
1770  * Checks if `this` is absolutely identical protection attribute to `other`
1771  */
1772 bool Prot::operator==(const Prot& other) const
1773 {
1774     if (this->kind == other.kind)
1775     {
1776         if (this->kind == PROTpackage)
1777             return this->pkg == other.pkg;
1778         return true;
1779     }
1780     return false;
1781 }
1782 
1783 /**
1784  * Checks if parent defines different access restrictions than this one.
1785  *
1786  * Params:
1787  *  parent = protection attribute for scope that hosts this one
1788  *
1789  * Returns:
1790  *  'true' if parent is already more restrictive than this one and thus
1791  *  no differentiation is needed.
1792  */
isSubsetOf(const Prot & parent)1793 bool Prot::isSubsetOf(const Prot& parent) const
1794 {
1795     if (this->kind != parent.kind)
1796         return false;
1797 
1798     if (this->kind == PROTpackage)
1799     {
1800         if (!this->pkg)
1801             return true;
1802         if (!parent.pkg)
1803             return false;
1804         if (parent.pkg->isAncestorPackageOf(this->pkg))
1805             return true;
1806     }
1807 
1808     return true;
1809 }
1810