Debian Codegraph @

gcc/d/dmd/dscope.d

raw
1 /**
2 * A scope as defined by curly braces `{}`.
3 *
4 * Not to be confused with the `scope` storage class.
5 *
6 * Copyright: Copyright (C) 1999-2025 by The D Language Foundation, All Rights Reserved
7 * Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
8 * License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
9 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/compiler/src/dmd/dscope.d, _dscope.d)
10 * Documentation: https://dlang.org/phobos/dmd_dscope.html
11 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/dscope.d
12 */
13
14 module dmd.dscope;
15
16 import core.stdc.stdio;
17 import core.stdc.string;
18 import dmd.aggregate;
19 import dmd.arraytypes;
20 import dmd.astenums;
21 import dmd.attrib;
22 import dmd.ctorflow;
23 import dmd.dclass;
24 import dmd.declaration;
25 import dmd.dmodule;
26 import dmd.doc;
27 import dmd.dstruct;
28 import dmd.dsymbol;
29 import dmd.dsymbolsem;
30 import dmd.dtemplate;
31 import dmd.expression;
32 import dmd.errors;
33 import dmd.errorsink;
34 import dmd.func;
35 import dmd.globals;
36 import dmd.id;
37 import dmd.identifier;
38 import dmd.importc;
39 import dmd.location;
40 import dmd.common.outbuffer;
41 import dmd.root.rmem;
42 import dmd.root.speller;
43 import dmd.statement;
44 import dmd.target;
45 import dmd.tokens;
46
47 //version=LOGSEARCH;
48
49 /// What kind of contract function we're in, if any
50 enum Contract : ubyte
51 {
52 none = 0,
53 invariant_ = 1,
54 require = 2, // in contract
55 ensure = 3, // out contract
56 }
57
58 private extern (D) struct BitFields
59 {
60 bool ctor; /// constructor type
61 bool noAccessCheck; /// don't do access checks
62 bool condition; /// inside static if/assert condition
63 bool debug_; /// inside debug conditional
64 bool inTemplateConstraint; /// inside template constraint
65 Contract contract;
66 bool ctfe; /// inside a ctfe-only expression
67 bool traitsCompiles; /// inside __traits(compile)
68 /// ignore symbol visibility
69 /// https://issues.dlang.org/show_bug.cgi?id=15907
70 bool ignoresymbolvisibility;
71 bool inCfile; /// C semantics apply
72 bool canFree; /// is on free list
73 bool fullinst; /// fully instantiate templates
74 bool ctfeBlock; /// inside a `if (__ctfe)` block
75 }
76
77 /// State of -preview switches
78 ///
79 /// By making them part of a Scope, we reduce reliance on dmd.globals,
80 /// and can enable/disable them per module / edition.
81 private struct Previews
82 {
83 // Run `dmd -preview=h` for the meaning of these switches
84 private extern (D) static struct BitFields
85 {
86 bool bitfields;
87 bool dip1000;
88 bool dip1008;
89 bool dip1021;
90 bool dip25;
91 bool fieldwise;
92 bool fixAliasThis;
93 bool fixImmutableConv;
94 bool in_;
95 bool inclusiveInContracts;
96 bool noSharedAccess;
97 bool rvalueRefParam;
98 bool safer;
99 FeatureState systemVariables;
100 }
101
102 import dmd.common.bitfields : generateBitFields;
103 mixin(generateBitFields!(BitFields, ushort));
104
105 void setFromParams(ref Param params) @nogc nothrow pure @safe
106 {
107 this.bitfields = params.bitfields;
108 this.dip1000 = params.useDIP1000 == FeatureState.enabled;
109 this.dip1008 = params.ehnogc;
110 this.dip1021 = params.useDIP1021; // == FeatureState.enabled;
111 this.dip25 = params.useDIP25 == FeatureState.enabled;
112 this.fixAliasThis = params.fixAliasThis;
113 this.fixImmutableConv = params.fixImmutableConv;
114 this.in_ = params.previewIn;
115 this.inclusiveInContracts = params.inclusiveInContracts;
116 this.noSharedAccess = params.noSharedAccess == FeatureState.enabled;
117 this.rvalueRefParam = params.rvalueRefParam == FeatureState.enabled;
118 this.safer = params.safer == FeatureState.enabled;
119 this.systemVariables = params.systemVariables;
120 this.fieldwise = params.fieldwise == FeatureState.enabled;
121 }
122 }
123
124 extern (C++) struct Scope
125 {
126 Scope* enclosing; /// enclosing Scope
127
128 Module _module; /// Root module
129 ScopeDsymbol scopesym; /// current symbol
130 FuncDeclaration func; /// function we are in
131 VarDeclaration varDecl; /// variable we are in during semantic2
132 Dsymbol parent; /// parent to use
133 LabelStatement slabel; /// enclosing labelled statement
134 SwitchStatement switchStatement;/// enclosing switch statement
135 Statement tryBody; /// enclosing _body of TryCatchStatement or TryFinallyStatement
136 TryFinallyStatement tryFinally; /// enclosing try finally statement
137 ScopeGuardStatement scopeGuard; /// enclosing scope(xxx) statement
138 Statement sbreak; /// enclosing statement that supports "break"
139 Statement scontinue; /// enclosing statement that supports "continue"
140 ForeachStatement fes; /// if nested function for ForeachStatement, this is it
141 Scope* callsc; /// used for __FUNCTION__, __PRETTY_FUNCTION__ and __MODULE__
142 Dsymbol inunion; /// != null if processing members of a union
143 bool nofree; /// true if shouldn't free it
144 bool inLoop; /// true if inside a loop (where constructor calls aren't allowed)
145 bool inDefaultArg; /// true if inside a default argument (where __FILE__, etc are evaluated at the call site)
146 int intypeof; /// in typeof(exp)
147 VarDeclaration lastVar; /// Previous symbol used to prevent goto-skips-init
148 ErrorSink eSink; /// sink for error messages
149
150 /* If minst && !tinst, it's in definitely non-speculative scope (eg. module member scope).
151 * If !minst && !tinst, it's in definitely speculative scope (eg. template constraint).
152 * If minst && tinst, it's in instantiated code scope without speculation.
153 * If !minst && tinst, it's in instantiated code scope with speculation.
154 */
155 Module minst; /// root module where the instantiated templates should belong to
156 TemplateInstance tinst; /// enclosing template instance
157
158 CtorFlow ctorflow; /// flow analysis for constructors
159
160 /// alignment for struct members
161 AlignDeclaration aligndecl;
162
163 /// C++ namespace this symbol is in
164 CPPNamespaceDeclaration namespace;
165
166 /// linkage for external functions
167 LINK linkage = LINK.d;
168
169 /// mangle type
170 CPPMANGLE cppmangle = CPPMANGLE.def;
171
172 /// inlining strategy for functions
173 PragmaDeclaration inlining;
174
175 /// visibility for class members
176 Visibility visibility = Visibility(Visibility.Kind.public_);
177 int explicitVisibility; /// set if in an explicit visibility attribute
178
179 STC stc; /// storage class
180
181 DeprecatedDeclaration depdecl; /// customized deprecation message
182
183 import dmd.common.bitfields : generateBitFields;
184 mixin(generateBitFields!(BitFields, ushort));
185
186 Previews previews;
187
188 // user defined attributes
189 UserAttributeDeclaration userAttribDecl;
190
191 DocComment* lastdc; /// documentation comment for last symbol at this scope
192 uint[void*] anchorCounts; /// lookup duplicate anchor name count
193 Identifier prevAnchor; /// qualified symbol name of last doc anchor
194
195 AliasDeclaration aliasAsg; /// if set, then aliasAsg is being assigned a new value,
196 /// do not set wasRead for it
197 StructDeclaration argStruct; /// elimiate recursion when looking for rvalue construction
198
199 extern (D) __gshared Scope* freelist;
200
201 extern (D) static Scope* alloc()
202 {
203 if (freelist)
204 {
205 Scope* s = freelist;
206 freelist = s.enclosing;
207 //printf("freelist %p\n", s);
208 assert(s.canFree);
209 s.canFree = false;
210 return s;
211 }
212 return new Scope();
213 }
214
215 extern (D) static Scope* createGlobal(Module _module, ErrorSink eSink)
216 {
217 Scope* sc = Scope.alloc();
218 *sc = Scope.init;
219 sc._module = _module;
220 sc.minst = _module;
221 sc.scopesym = new ScopeDsymbol();
222 sc.scopesym.symtab = new DsymbolTable();
223 sc.eSink = eSink;
224 assert(eSink);
225 // Add top level package as member of this global scope
226 Dsymbol m = _module;
227 while (m.parent)
228 m = m.parent;
229 m.addMember(null, sc.scopesym);
230 m.parent = null; // got changed by addMember()
231 sc.previews.setFromParams(global.params);
232
233 if (_module.filetype == FileType.c)
234 sc.inCfile = true;
235 // Create the module scope underneath the global scope
236 sc = sc.push(_module);
237 sc.parent = _module;
238 return sc;
239 }
240
241 extern (D) Scope* copy()
242 {
243 Scope* sc = Scope.alloc();
244 *sc = this;
245 /* https://issues.dlang.org/show_bug.cgi?id=11777
246 * The copied scope should not inherit fieldinit.
247 */
248 sc.ctorflow.fieldinit = null;
249 return sc;
250 }
251
252 extern (D) Scope* push()
253 {
254 Scope* s = copy();
255 //printf("Scope::push(this = %p) new = %p\n", this, s);
256 assert(!this.canFree);
257 s.scopesym = null;
258 s.enclosing = &this;
259 debug
260 {
261 if (enclosing)
262 assert(!enclosing.canFree);
263 if (s == enclosing)
264 {
265 printf("this = %p, enclosing = %p, enclosing.enclosing = %p\n", s, &this, enclosing);
266 }
267 assert(s != enclosing);
268 }
269 s.slabel = null;
270 s.nofree = false;
271 s.ctorflow.fieldinit = ctorflow.fieldinit.arraydup;
272
273 // Only keep persistent flags
274 s.resetAllFlags();
275 s.contract = this.contract;
276 s.debug_ = this.debug_;
277 s.ctfe = this.ctfe;
278 s.traitsCompiles = this.traitsCompiles;
279 s.inTemplateConstraint = this.inTemplateConstraint;
280 s.noAccessCheck = this.noAccessCheck;
281 s.ignoresymbolvisibility = this.ignoresymbolvisibility;
282 s.inCfile = this.inCfile;
283 s.ctfeBlock = this.ctfeBlock;
284 s.previews = this.previews;
285 s.lastdc = null;
286 assert(&this != s);
287 return s;
288 }
289
290 /// Copy flags from scope `other`
291 extern(D) void copyFlagsFrom(Scope* other) @safe
292 {
293 this.bitFields = other.bitFields;
294 }
295
296 /// Set all scope flags to their initial value
297 extern(D) void resetAllFlags() @safe
298 {
299 this.bitFields = 0;
300 }
301
302 extern (D) Scope* push(ScopeDsymbol ss)
303 {
304 //printf("Scope::push(%s)\n", ss.toChars());
305 Scope* s = push();
306 s.scopesym = ss;
307 return s;
308 }
309
310 extern (D) Scope* pop()
311 {
312 //printf("Scope::pop() %p nofree = %d\n", this, nofree);
313 if (enclosing)
314 enclosing.ctorflow.OR(ctorflow);
315 ctorflow.freeFieldinit();
316
317 Scope* enc = enclosing;
318 if (!nofree)
319 {
320 if (mem.isGCEnabled)
321 this = this.init;
322 enclosing = freelist;
323 freelist = &this;
324 this.canFree = true;
325 }
326 return enc;
327 }
328
329 /*************************
330 * Similar to pop(), but the results in `this` are not folded
331 * into `enclosing`.
332 */
333 extern (D) void detach()
334 {
335 ctorflow.freeFieldinit();
336 enclosing = null;
337 pop();
338 }
339
340 extern (D) Scope* startCTFE()
341 {
342 Scope* sc = this.push();
343 sc.copyFlagsFrom(&this);
344 sc.ctfe = true;
345 version (none)
346 {
347 /* TODO: Currently this is not possible, because we need to
348 * unspeculative some types and symbols if they are necessary for the
349 * final executable. Consider:
350 *
351 * struct S(T) {
352 * string toString() const { return "instantiated"; }
353 * }
354 * enum x = S!int();
355 * void main() {
356 * // To call x.toString in runtime, compiler should unspeculative S!int.
357 * assert(x.toString() == "instantiated");
358 * }
359 *
360 * This results in an undefined reference to `RTInfoImpl`:
361 * class C { int a,b,c; int* p,q; }
362 * void test() { C c = new C(); }
363 */
364 // If a template is instantiated from CT evaluated expression,
365 // compiler can elide its code generation.
366 sc.tinst = null;
367 sc.minst = null;
368 }
369 return sc;
370 }
371
372 extern (D) Scope* endCTFE()
373 {
374 assert(this.ctfe);
375 return pop();
376 }
377
378
379 /*******************************
380 * Merge results of `ctorflow` into `this`.
381 * Params:
382 * loc = for error messages
383 * ctorflow = flow results to merge in
384 */
385 extern (D) void merge(Loc loc, const ref CtorFlow ctorflow)
386 {
387 if (!mergeCallSuper(this.ctorflow.callSuper, ctorflow.callSuper))
388 error(loc, "one path skips constructor");
389
390 const fies = ctorflow.fieldinit;
391 if (!this.ctorflow.fieldinit.length || !fies.length)
392 return;
393 FuncDeclaration f = func;
394 if (fes)
395 f = fes.func;
396 auto ad = f.isMemberDecl();
397 assert(ad);
398 foreach (i, v; ad.fields)
399 {
400 bool mustInit = (v.storage_class & STC.nodefaultctor || v.type.needsNested());
401 auto fieldInit = &this.ctorflow.fieldinit[i];
402 const fiesCurrent = fies[i];
403 if (fieldInit.loc is Loc.init)
404 fieldInit.loc = fiesCurrent.loc;
405 if (!mergeFieldInit(this.ctorflow.fieldinit[i].csx, fiesCurrent.csx) && mustInit)
406 {
407 error(loc, "one path skips field `%s`", v.toChars());
408 }
409 }
410 }
411
412 /************************************
413 * Perform unqualified name lookup by following the chain of scopes up
414 * until found.
415 *
416 * Params:
417 * loc = location to use for error messages
418 * ident = name to look up
419 * pscopesym = if supplied and name is found, set to scope that ident was found in, otherwise set to null
420 * flags = modify search based on flags
421 *
422 * Returns:
423 * symbol if found, null if not
424 */
425 extern (C++) Dsymbol search(Loc loc, Identifier ident, out Dsymbol pscopesym, SearchOptFlags flags = SearchOpt.all)
426 {
427 version (LOGSEARCH)
428 {
429 printf("Scope.search(%p, '%s' flags=x%x)\n", &this, ident.toChars(), flags);
430 // Print scope chain
431 for (Scope* sc = &this; sc; sc = sc.enclosing)
432 {
433 if (!sc.scopesym)
434 continue;
435 printf("\tscope %s\n", sc.scopesym.toChars());
436 }
437
438 static void printMsg(string txt, Dsymbol s)
439 {
440 printf("%.*s %s.%s, kind = '%s'\n", cast(int)txt.length, txt.ptr,
441 s.parent ? s.parent.toChars() : "", s.toChars(), s.kind());
442 }
443 }
444
445 // This function is called only for unqualified lookup
446 assert(!(flags & (SearchOpt.localsOnly | SearchOpt.importsOnly)));
447
448 /* If ident is "start at module scope", only look at module scope
449 */
450 if (ident == Id.empty)
451 {
452 // Look for module scope
453 for (Scope* sc = &this; sc; sc = sc.enclosing)
454 {
455 assert(sc != sc.enclosing);
456 if (!sc.scopesym)
457 continue;
458 if (Dsymbol s = sc.scopesym.isModule())
459 {
460 //printMsg("\tfound", s);
461 pscopesym = sc.scopesym;
462 return s;
463 }
464 }
465 return null;
466 }
467
468 Dsymbol checkAliasThis(AggregateDeclaration ad, Identifier ident, SearchOptFlags flags, Expression* exp)
469 {
470 import dmd.mtype;
471 if (!ad || !ad.aliasthis)
472 return null;
473
474 Declaration decl = ad.aliasthis.sym.isDeclaration();
475 if (!decl)
476 return null;
477
478 Type t = decl.type;
479 ScopeDsymbol sds;
480 TypeClass tc;
481 TypeStruct ts;
482 switch(t.ty)
483 {
484 case Tstruct:
485 ts = cast(TypeStruct)t;
486 sds = ts.sym;
487 break;
488 case Tclass:
489 tc = cast(TypeClass)t;
490 sds = tc.sym;
491 break;
492 case Tinstance:
493 sds = (cast(TypeInstance)t).tempinst;
494 break;
495 case Tenum:
496 sds = (cast(TypeEnum)t).sym;
497 break;
498 default: break;
499 }
500
501 if (!sds)
502 return null;
503
504 Dsymbol ret = sds.search(loc, ident, flags);
505 if (ret)
506 {
507 *exp = new DotIdExp(loc, *exp, ad.aliasthis.ident);
508 *exp = new DotIdExp(loc, *exp, ident);
509 return ret;
510 }
511
512 if (!ts && !tc)
513 return null;
514
515 Dsymbol s;
516 *exp = new DotIdExp(loc, *exp, ad.aliasthis.ident);
517 if (ts && !(ts.att & AliasThisRec.tracing))
518 {
519 ts.att = cast(AliasThisRec)(ts.att | AliasThisRec.tracing);
520 s = checkAliasThis(sds.isAggregateDeclaration(), ident, flags, exp);
521 ts.att = cast(AliasThisRec)(ts.att & ~AliasThisRec.tracing);
522 }
523 else if(tc && !(tc.att & AliasThisRec.tracing))
524 {
525 tc.att = cast(AliasThisRec)(tc.att | AliasThisRec.tracing);
526 s = checkAliasThis(sds.isAggregateDeclaration(), ident, flags, exp);
527 tc.att = cast(AliasThisRec)(tc.att & ~AliasThisRec.tracing);
528 }
529 return s;
530 }
531
532 Dsymbol searchScopes(SearchOptFlags flags)
533 {
534 for (Scope* sc = &this; sc; sc = sc.enclosing)
535 {
536 assert(sc != sc.enclosing);
537 if (!sc.scopesym)
538 continue;
539 //printf("\tlooking in scopesym '%s', kind = '%s', flags = x%x\n", sc.scopesym.toChars(), sc.scopesym.kind(), flags);
540
541 if (sc.scopesym.isModule())
542 flags |= SearchOpt.unqualifiedModule; // tell Module.search() that SearchOpt.localsOnly is to be obeyed
543 else if (sc.inCfile && sc.scopesym.isStructDeclaration())
544 continue; // C doesn't have struct scope
545
546 if (Dsymbol s = sc.scopesym.search(loc, ident, flags))
547 {
548 if (flags & SearchOpt.tagNameSpace)
549 {
550 // ImportC: if symbol is not a tag, look for it in tag table
551 if (!s.isScopeDsymbol())
552 {
553 auto ps = cast(void*)s in sc._module.tagSymTab;
554 if (!ps)
555 goto NotFound;
556 s = *ps;
557 }
558 }
559 //printMsg("\tfound local", s);
560 pscopesym = sc.scopesym;
561 return s;
562 }
563
564 NotFound:
565 if (sc.previews.fixAliasThis)
566 {
567 Expression exp = new ThisExp(loc);
568 if (Dsymbol aliasSym = checkAliasThis(sc.scopesym.isAggregateDeclaration(), ident, flags, &exp))
569 {
570 //printf("found aliassym: %s\n", aliasSym.toChars());
571 pscopesym = new ExpressionDsymbol(exp);
572 return aliasSym;
573 }
574 }
575
576 // Stop when we hit a module, but keep going if that is not just under the global scope
577 if (sc.scopesym.isModule() && !(sc.enclosing && !sc.enclosing.enclosing))
578 break;
579 }
580 return null;
581 }
582
583 if (this.ignoresymbolvisibility)
584 flags |= SearchOpt.ignoreVisibility;
585
586 // First look in local scopes
587 Dsymbol s = searchScopes(flags | SearchOpt.localsOnly);
588 version (LOGSEARCH) if (s) printMsg("-Scope.search() found local", s);
589 if (!s)
590 {
591 // Second look in imported modules
592 s = searchScopes(flags | SearchOpt.importsOnly);
593 version (LOGSEARCH) if (s) printMsg("-Scope.search() found import", s);
594 }
595 return s;
596 }
597
598 extern (D) Dsymbol search_correct(Identifier ident)
599 {
600 if (global.gag)
601 return null; // don't do it for speculative compiles; too time consuming
602
603 /************************************************
604 * Given the failed search attempt, try to find
605 * one with a close spelling.
606 * Params:
607 * seed = identifier to search for
608 * cost = set to the cost, which rises with each outer scope
609 * Returns:
610 * Dsymbol if found, null if not
611 */
612 extern (D) Dsymbol scope_search_fp(const(char)[] seed, out int cost)
613 {
614 //printf("scope_search_fp('%s')\n", seed);
615 /* If not in the lexer's string table, it certainly isn't in the symbol table.
616 * Doing this first is a lot faster.
617 */
618 if (!seed.length)
619 return null;
620 Identifier id = Identifier.lookup(seed);
621 if (!id)
622 return null;
623 Scope* sc = &this;
624 Module.clearCache();
625 Dsymbol scopesym;
626 Dsymbol s = sc.search(Loc.initial, id, scopesym, SearchOpt.ignoreErrors);
627 if (!s)
628 return null;
629
630 // Do not show `@disable`d declarations
631 if (auto decl = s.isDeclaration())
632 if (decl.storage_class & STC.disable)
633 return null;
634 // Or `deprecated` ones if we're not in a deprecated scope
635 if (s.isDeprecated() && !sc.isDeprecated())
636 return null;
637
638 for (cost = 0; sc; sc = sc.enclosing, ++cost)
639 if (sc.scopesym == scopesym)
640 break;
641 if (scopesym != s.parent)
642 {
643 ++cost; // got to the symbol through an import
644 if (s.visible().kind == Visibility.Kind.private_)
645 return null;
646 }
647 return s;
648 }
649
650 Dsymbol scopesym;
651 // search for exact name first
652 if (auto s = search(Loc.initial, ident, scopesym, SearchOpt.ignoreErrors))
653 return s;
654 return speller!scope_search_fp(ident.toString());
655 }
656
657 /************************************
658 * Maybe `ident` was a C or C++ name. Check for that,
659 * and suggest the D equivalent.
660 * Params:
661 * ident = unknown identifier
662 * Returns:
663 * D identifier string if found, null if not
664 */
665 extern (D) static const(char)* search_correct_C(Identifier ident)
666 {
667 import dmd.astenums : Twchar;
668 TOK tok;
669 if (ident == Id.NULL)
670 tok = TOK.null_;
671 else if (ident == Id.TRUE)
672 tok = TOK.true_;
673 else if (ident == Id.FALSE)
674 tok = TOK.false_;
675 else if (ident == Id.unsigned)
676 tok = TOK.uns32;
677 else if (ident == Id.wchar_t)
678 tok = target.c.wchar_tsize == 2 ? TOK.wchar_ : TOK.dchar_;
679 else
680 return null;
681 return Token.toChars(tok);
682 }
683
684 /***************************
685 * Find the innermost scope with a symbol table.
686 * Returns:
687 * innermost scope, null if none
688 */
689 extern (D) Scope* inner() return @safe
690 {
691 for (Scope* sc = &this; sc; sc = sc.enclosing)
692 {
693 if (sc.scopesym)
694 return sc;
695 }
696 return null;
697 }
698
699 /******************************
700 * Add symbol s to innermost symbol table.
701 * Params:
702 * s = symbol to insert
703 * Returns:
704 * null if already in table, `s` if not
705 */
706 extern (D) Dsymbol insert(Dsymbol s)
707 {
708 //printf("insert() %s\n", s.toChars());
709 if (VarDeclaration vd = s.isVarDeclaration())
710 {
711 if (lastVar)
712 vd.lastVar = lastVar;
713 lastVar = vd;
714 }
715 else if (WithScopeSymbol ss = s.isWithScopeSymbol())
716 {
717 if (VarDeclaration vd = ss.withstate.wthis)
718 {
719 if (lastVar)
720 vd.lastVar = lastVar;
721 lastVar = vd;
722 }
723 return null;
724 }
725
726 auto scopesym = inner().scopesym;
727 //printf("\t\tscopesym = %p\n", scopesym);
728 if (!scopesym.symtab)
729 scopesym.symtab = new DsymbolTable();
730 if (!this.inCfile)
731 return scopesym.symtabInsert(s);
732
733 // ImportC insert
734 if (!scopesym.symtabInsert(s)) // if already in table
735 {
736 Dsymbol s2 = scopesym.symtabLookup(s, s.ident); // s2 is existing entry
737 return handleTagSymbols(this, s, s2, scopesym);
738 }
739 return s; // inserted
740 }
741
742 /********************************************
743 * Search enclosing scopes for ScopeDsymbol.
744 */
745 extern (D) ScopeDsymbol getScopesym() @safe
746 {
747 for (Scope* sc = &this; sc; sc = sc.enclosing)
748 {
749 if (sc.scopesym)
750 return sc.scopesym;
751 }
752 return null; // not found
753 }
754
755 /********************************************
756 * Search enclosing scopes for ClassDeclaration.
757 */
758 extern (D) ClassDeclaration getClassScope() @safe
759 {
760 for (Scope* sc = &this; sc; sc = sc.enclosing)
761 {
762 if (!sc.scopesym)
763 continue;
764 if (ClassDeclaration cd = sc.scopesym.isClassDeclaration())
765 return cd;
766 }
767 return null;
768 }
769
770 /********************************************
771 * Search enclosing scopes for ClassDeclaration or StructDeclaration.
772 */
773 extern (D) AggregateDeclaration getStructClassScope() @safe
774 {
775 for (Scope* sc = &this; sc; sc = sc.enclosing)
776 {
777 if (!sc.scopesym)
778 continue;
779 if (AggregateDeclaration ad = sc.scopesym.isClassDeclaration())
780 return ad;
781 if (AggregateDeclaration ad = sc.scopesym.isStructDeclaration())
782 return ad;
783 }
784 return null;
785 }
786
787 /********************************************
788 * Find the lexically enclosing function (if any).
789 *
790 * This function skips through generated FuncDeclarations,
791 * e.g. rewritten foreach bodies.
792 *
793 * Returns: the function or null
794 */
795 extern (D) inout(FuncDeclaration) getEnclosingFunction() inout
796 {
797 if (!this.func)
798 return null;
799
800 auto fd = cast(FuncDeclaration) this.func;
801
802 // Look through foreach bodies rewritten as delegates
803 while (fd.fes)
804 {
805 assert(fd.fes.func);
806 fd = fd.fes.func;
807 }
808
809 return cast(inout(FuncDeclaration)) fd;
810 }
811
812 /*******************************************
813 * For TemplateDeclarations, we need to remember the Scope
814 * where it was declared. So mark the Scope as not
815 * to be free'd.
816 */
817 extern (D) void setNoFree() @safe
818 {
819 //int i = 0;
820 //printf("Scope::setNoFree(this = %p)\n", this);
821 for (Scope* sc = &this; sc; sc = sc.enclosing)
822 {
823 //printf("\tsc = %p\n", sc);
824 sc.nofree = true;
825 assert(!this.canFree);
826 //assert(sc != sc.enclosing);
827 //assert(!sc.enclosing || sc != sc.enclosing.enclosing);
828 //if (++i == 10)
829 // assert(0);
830 }
831 }
832 /******************************
833 */
834 extern (D) structalign_t alignment()
835 {
836 if (aligndecl)
837 {
838 auto ad = aligndecl.getAlignment(&this);
839 return ad.salign;
840 }
841 else
842 {
843 structalign_t sa;
844 sa.setDefault();
845 return sa;
846 }
847 }
848 @safe @nogc pure nothrow const:
849 /**********************************
850 * Checks whether the current scope (or any of its parents) is deprecated.
851 *
852 * Returns: `true` if this or any parent scope is deprecated, `false` otherwise`
853 */
854 extern (D) bool isDeprecated()
855 {
856 for (const(Dsymbol)* sp = &(this.parent); *sp; sp = &(sp.parent))
857 {
858 if (sp.isDeprecated())
859 return true;
860 }
861 for (const(Scope)* sc2 = &this; sc2; sc2 = sc2.enclosing)
862 {
863 if (sc2.scopesym && sc2.scopesym.isDeprecated())
864 return true;
865
866 // If inside a StorageClassDeclaration that is deprecated
867 if (sc2.stc & STC.deprecated_)
868 return true;
869 }
870 if (_module.md && _module.md.isdeprecated)
871 {
872 return true;
873 }
874 return false;
875 }
876 /**
877 * dmd relies on mutation of state during semantic analysis, however
878 * sometimes semantic is being performed in a speculative context that should
879 * not have any visible effect on the rest of the compilation: for example when compiling
880 * a typeof() or __traits(compiles).
881 *
882 * Returns: `true` if this `Scope` is known to be from one of these speculative contexts
883 */
884 extern (D) bool isFromSpeculativeSemanticContext() scope
885 {
886 return this.intypeof || this.traitsCompiles;
887 }
888
889
890 /**
891 * Returns: true if the code needs to go all the way through to code generation.
892 * This implies things like needing lowering to simpler forms.
893 */
894 extern (D) bool needsCodegen()
895 {
896 return !this.ctfe && !this.ctfeBlock && !this.traitsCompiles;
897 }
898
899 /// Returns: whether to raise DIP1000 warnings (FeatureStabe.default) or errors (FeatureState.enabled)
900 extern (D) FeatureState useDIP1000()
901 {
902 return (this.previews.dip1000 || hasEdition(Edition.v2024)) ? FeatureState.enabled : FeatureState.disabled;
903 }
904
905 /// Returns: whether to raise DIP25 warnings (FeatureStabe.default) or errors (FeatureState.enabled)
906 extern (D) FeatureState useDIP25()
907 {
908 return (this.previews.dip25 || hasEdition(Edition.v2024)) ? FeatureState.enabled : FeatureState.disabled;
909 }
910
911 /// Returns: whether this scope compiles with `edition` or later
912 extern (D) bool hasEdition(Edition edition)
913 {
914 return _module && _module.edition >= edition;
915 }
916 }