1 /**
2  * Performs the semantic2 stage, which deals with initializer expressions.
3  *
4  * Copyright:   Copyright (C) 1999-2021 by The D Language Foundation, All Rights Reserved
5  * Authors:     $(LINK2 http://www.digitalmars.com, Walter Bright)
6  * License:     $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
7  * Source:      $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/semantic2.d, _semantic2.d)
8  * Documentation:  https://dlang.org/phobos/dmd_semantic2.html
9  * Coverage:    https://codecov.io/gh/dlang/dmd/src/master/src/dmd/semantic2.d
10  */
11 
12 module dmd.semantic2;
13 
14 import core.stdc.stdio;
15 import core.stdc.string;
16 
17 import dmd.aggregate;
18 import dmd.aliasthis;
19 import dmd.arraytypes;
20 import dmd.astcodegen;
21 import dmd.astenums;
22 import dmd.attrib;
23 import dmd.blockexit;
24 import dmd.clone;
25 import dmd.dcast;
26 import dmd.dclass;
27 import dmd.declaration;
28 import dmd.denum;
29 import dmd.dimport;
30 import dmd.dinterpret;
31 import dmd.dmodule;
32 import dmd.dscope;
33 import dmd.dstruct;
34 import dmd.dsymbol;
35 import dmd.dsymbolsem;
36 import dmd.dtemplate;
37 import dmd.dversion;
38 import dmd.errors;
39 import dmd.escape;
40 import dmd.expression;
41 import dmd.expressionsem;
42 import dmd.func;
43 import dmd.globals;
44 import dmd.id;
45 import dmd.identifier;
46 import dmd.init;
47 import dmd.initsem;
48 import dmd.hdrgen;
49 import dmd.mtype;
50 import dmd.nogc;
51 import dmd.nspace;
52 import dmd.objc;
53 import dmd.opover;
54 import dmd.parse;
55 import dmd.root.filename;
56 import dmd.root.outbuffer;
57 import dmd.root.rmem;
58 import dmd.root.rootobject;
59 import dmd.sideeffect;
60 import dmd.statementsem;
61 import dmd.staticassert;
62 import dmd.tokens;
63 import dmd.utf;
64 import dmd.statement;
65 import dmd.target;
66 import dmd.templateparamsem;
67 import dmd.typesem;
68 import dmd.visitor;
69 
70 enum LOG = false;
71 
72 
73 /*************************************
74  * Does semantic analysis on initializers and members of aggregates.
75  */
semantic2(Dsymbol dsym,Scope * sc)76 extern(C++) void semantic2(Dsymbol dsym, Scope* sc)
77 {
78     scope v = new Semantic2Visitor(sc);
79     dsym.accept(v);
80 }
81 
82 private extern(C++) final class Semantic2Visitor : Visitor
83 {
84     alias visit = Visitor.visit;
85     Scope* sc;
this(Scope * sc)86     this(Scope* sc)
87     {
88         this.sc = sc;
89     }
90 
visit(Dsymbol)91     override void visit(Dsymbol) {}
92 
visit(StaticAssert sa)93     override void visit(StaticAssert sa)
94     {
95         //printf("StaticAssert::semantic2() %s\n", sa.toChars());
96         auto sds = new ScopeDsymbol();
97         sc = sc.push(sds);
98         sc.tinst = null;
99         sc.minst = null;
100 
101         import dmd.staticcond;
102         bool errors;
103         bool result = evalStaticCondition(sc, sa.exp, sa.exp, errors);
104         sc = sc.pop();
105         if (errors)
106         {
107             errorSupplemental(sa.loc, "while evaluating: `static assert(%s)`", sa.exp.toChars());
108             return;
109         }
110         else if (result)
111             return;
112 
113         if (sa.msg)
114         {
115             sc = sc.startCTFE();
116             sa.msg = sa.msg.expressionSemantic(sc);
117             sa.msg = resolveProperties(sc, sa.msg);
118             sc = sc.endCTFE();
119             sa.msg = sa.msg.ctfeInterpret();
120             if (StringExp se = sa.msg.toStringExp())
121             {
122                 // same with pragma(msg)
123                 const slice = se.toUTF8(sc).peekString();
124                 error(sa.loc, "static assert:  \"%.*s\"", cast(int)slice.length, slice.ptr);
125             }
126             else
127                 error(sa.loc, "static assert:  %s", sa.msg.toChars());
128         }
129         else
130             error(sa.loc, "static assert:  `%s` is false", sa.exp.toChars());
131         if (sc.tinst)
132             sc.tinst.printInstantiationTrace();
133         if (!global.gag)
134             fatal();
135     }
136 
visit(TemplateInstance tempinst)137     override void visit(TemplateInstance tempinst)
138     {
139         if (tempinst.semanticRun >= PASS.semantic2)
140             return;
141         tempinst.semanticRun = PASS.semantic2;
142         static if (LOG)
143         {
144             printf("+TemplateInstance.semantic2('%s')\n", tempinst.toChars());
145             scope(exit) printf("-TemplateInstance.semantic2('%s')\n", tempinst.toChars());
146         }
147         if (tempinst.errors || !tempinst.members)
148             return;
149 
150         TemplateDeclaration tempdecl = tempinst.tempdecl.isTemplateDeclaration();
151         assert(tempdecl);
152 
153         sc = tempdecl._scope;
154         assert(sc);
155         sc = sc.push(tempinst.argsym);
156         sc = sc.push(tempinst);
157         sc.tinst = tempinst;
158         sc.minst = tempinst.minst;
159 
160         int needGagging = (tempinst.gagged && !global.gag);
161         uint olderrors = global.errors;
162         int oldGaggedErrors = -1; // dead-store to prevent spurious warning
163         if (needGagging)
164             oldGaggedErrors = global.startGagging();
165 
166         for (size_t i = 0; i < tempinst.members.dim; i++)
167         {
168             Dsymbol s = (*tempinst.members)[i];
169             static if (LOG)
170             {
171                 printf("\tmember '%s', kind = '%s'\n", s.toChars(), s.kind());
172             }
173             s.semantic2(sc);
174             if (tempinst.gagged && global.errors != olderrors)
175                 break;
176         }
177 
178         if (global.errors != olderrors)
179         {
180             if (!tempinst.errors)
181             {
182                 if (!tempdecl.literal)
183                     tempinst.error(tempinst.loc, "error instantiating");
184                 if (tempinst.tinst)
185                     tempinst.tinst.printInstantiationTrace();
186             }
187             tempinst.errors = true;
188         }
189         if (needGagging)
190             global.endGagging(oldGaggedErrors);
191 
192         sc = sc.pop();
193         sc.pop();
194     }
195 
visit(TemplateMixin tmix)196     override void visit(TemplateMixin tmix)
197     {
198         if (tmix.semanticRun >= PASS.semantic2)
199             return;
200         tmix.semanticRun = PASS.semantic2;
201         static if (LOG)
202         {
203             printf("+TemplateMixin.semantic2('%s')\n", tmix.toChars());
204             scope(exit) printf("-TemplateMixin.semantic2('%s')\n", tmix.toChars());
205         }
206         if (!tmix.members)
207             return;
208 
209         assert(sc);
210         sc = sc.push(tmix.argsym);
211         sc = sc.push(tmix);
212         sc.tinst = tmix;
213         sc.minst = tmix.minst;
214         for (size_t i = 0; i < tmix.members.dim; i++)
215         {
216             Dsymbol s = (*tmix.members)[i];
217             static if (LOG)
218             {
219                 printf("\tmember '%s', kind = '%s'\n", s.toChars(), s.kind());
220             }
221             s.semantic2(sc);
222         }
223         sc = sc.pop();
224         sc.pop();
225     }
226 
visit(VarDeclaration vd)227     override void visit(VarDeclaration vd)
228     {
229         if (vd.semanticRun < PASS.semanticdone && vd.inuse)
230             return;
231 
232         //printf("VarDeclaration::semantic2('%s')\n", toChars());
233 
234         if (vd.aliassym)        // if it's a tuple
235         {
236             vd.aliassym.accept(this);
237             vd.semanticRun = PASS.semantic2done;
238             return;
239         }
240 
241         UserAttributeDeclaration.checkGNUABITag(vd, vd.linkage);
242 
243         if (vd._init && !vd.toParent().isFuncDeclaration())
244         {
245             vd.inuse++;
246 
247             /* https://issues.dlang.org/show_bug.cgi?id=20280
248              *
249              * Template instances may import modules that have not
250              * finished semantic1.
251              */
252             if (!vd.type)
253                 vd.dsymbolSemantic(sc);
254 
255 
256             // https://issues.dlang.org/show_bug.cgi?id=14166
257             // https://issues.dlang.org/show_bug.cgi?id=20417
258             // Don't run CTFE for the temporary variables inside typeof or __traits(compiles)
259             vd._init = vd._init.initializerSemantic(sc, vd.type, sc.intypeof == 1 || sc.flags & SCOPE.compile ? INITnointerpret : INITinterpret);
260             vd.inuse--;
261         }
262         if (vd._init && vd.storage_class & STC.manifest)
263         {
264             /* Cannot initializer enums with CTFE classreferences and addresses of struct literals.
265              * Scan initializer looking for them. Issue error if found.
266              */
267             if (ExpInitializer ei = vd._init.isExpInitializer())
268             {
269                 static bool hasInvalidEnumInitializer(Expression e)
270                 {
271                     static bool arrayHasInvalidEnumInitializer(Expressions* elems)
272                     {
273                         foreach (e; *elems)
274                         {
275                             if (e && hasInvalidEnumInitializer(e))
276                                 return true;
277                         }
278                         return false;
279                     }
280 
281                     if (e.op == TOK.classReference)
282                         return true;
283                     if (e.op == TOK.address && (cast(AddrExp)e).e1.op == TOK.structLiteral)
284                         return true;
285                     if (e.op == TOK.arrayLiteral)
286                         return arrayHasInvalidEnumInitializer((cast(ArrayLiteralExp)e).elements);
287                     if (e.op == TOK.structLiteral)
288                         return arrayHasInvalidEnumInitializer((cast(StructLiteralExp)e).elements);
289                     if (e.op == TOK.assocArrayLiteral)
290                     {
291                         AssocArrayLiteralExp ae = cast(AssocArrayLiteralExp)e;
292                         return arrayHasInvalidEnumInitializer(ae.values) ||
293                                arrayHasInvalidEnumInitializer(ae.keys);
294                     }
295                     return false;
296                 }
297 
298                 if (hasInvalidEnumInitializer(ei.exp))
299                     vd.error(": Unable to initialize enum with class or pointer to struct. Use static const variable instead.");
300             }
301         }
302         else if (vd._init && vd.isThreadlocal())
303         {
304             // Cannot initialize a thread-local class or pointer to struct variable with a literal
305             // that itself is a thread-local reference and would need dynamic initialization also.
306             if ((vd.type.ty == Tclass) && vd.type.isMutable() && !vd.type.isShared())
307             {
308                 ExpInitializer ei = vd._init.isExpInitializer();
309                 if (ei && ei.exp.op == TOK.classReference)
310                     vd.error("is a thread-local class and cannot have a static initializer. Use `static this()` to initialize instead.");
311             }
312             else if (vd.type.ty == Tpointer && vd.type.nextOf().ty == Tstruct && vd.type.nextOf().isMutable() && !vd.type.nextOf().isShared())
313             {
314                 ExpInitializer ei = vd._init.isExpInitializer();
315                 if (ei && ei.exp.op == TOK.address && (cast(AddrExp)ei.exp).e1.op == TOK.structLiteral)
316                     vd.error("is a thread-local pointer to struct and cannot have a static initializer. Use `static this()` to initialize instead.");
317             }
318         }
319         vd.semanticRun = PASS.semantic2done;
320     }
321 
visit(Module mod)322     override void visit(Module mod)
323     {
324         //printf("Module::semantic2('%s'): parent = %p\n", toChars(), parent);
325         if (mod.semanticRun != PASS.semanticdone) // semantic() not completed yet - could be recursive call
326             return;
327         mod.semanticRun = PASS.semantic2;
328         // Note that modules get their own scope, from scratch.
329         // This is so regardless of where in the syntax a module
330         // gets imported, it is unaffected by context.
331         Scope* sc = Scope.createGlobal(mod); // create root scope
332         //printf("Module = %p\n", sc.scopesym);
333         // Pass 2 semantic routines: do initializers and function bodies
334         for (size_t i = 0; i < mod.members.dim; i++)
335         {
336             Dsymbol s = (*mod.members)[i];
337             s.semantic2(sc);
338         }
339         if (mod.userAttribDecl)
340         {
341             mod.userAttribDecl.semantic2(sc);
342         }
343         sc = sc.pop();
344         sc.pop();
345         mod.semanticRun = PASS.semantic2done;
346         //printf("-Module::semantic2('%s'): parent = %p\n", toChars(), parent);
347     }
348 
visit(FuncDeclaration fd)349     override void visit(FuncDeclaration fd)
350     {
351         if (fd.semanticRun >= PASS.semantic2done)
352             return;
353 
354         if (fd.semanticRun < PASS.semanticdone && !fd.errors)
355         {
356             /* https://issues.dlang.org/show_bug.cgi?id=21614
357              *
358              * Template instances may import modules that have not
359              * finished semantic1.
360              */
361             fd.dsymbolSemantic(sc);
362         }
363         assert(fd.semanticRun <= PASS.semantic2);
364         fd.semanticRun = PASS.semantic2;
365 
366         //printf("FuncDeclaration::semantic2 [%s] fd0 = %s %s\n", loc.toChars(), toChars(), type.toChars());
367 
368         // Only check valid functions which have a body to avoid errors
369         // for multiple declarations, e.g.
370         // void foo();
371         // void foo();
372         if (fd.fbody && fd.overnext && !fd.errors)
373         {
374             // Always starts the lookup from 'this', because the conflicts with
375             // previous overloads are already reported.
376             alias f1 = fd;
377             auto tf1 = cast(TypeFunction) f1.type;
378             auto parent1 = f1.toParent2();
379 
380             overloadApply(f1, (Dsymbol s)
381             {
382                 auto f2 = s.isFuncDeclaration();
383                 if (!f2 || f1 == f2 || f2.errors)
384                     return 0;
385 
386                 // Don't have to check conflict between declaration and definition.
387                 if (f2.fbody is null)
388                     return 0;
389 
390                 // Functions with different manglings can never conflict
391                 if (f1.linkage != f2.linkage)
392                     return 0;
393 
394                 // Functions with different names never conflict
395                 // (they can form overloads sets introduced by an alias)
396                 if (f1.ident != f2.ident)
397                     return 0;
398 
399                 // Functions with different parents never conflict
400                 // (E.g. when aliasing a free function into a struct)
401                 if (parent1 != f2.toParent2())
402                     return 0;
403 
404                 /* Check for overload merging with base class member functions.
405                  *
406                  *  class B { void foo() {} }
407                  *  class D : B {
408                  *    override void foo() {}    // B.foo appears as f2
409                  *    alias foo = B.foo;
410                  *  }
411                  */
412                 if (f1.overrides(f2))
413                     return 0;
414 
415                 auto tf2 = cast(TypeFunction) f2.type;
416 
417                 // Overloading based on storage classes
418                 if (tf1.mod != tf2.mod || ((f1.storage_class ^ f2.storage_class) & STC.static_))
419                     return 0;
420 
421                 const sameAttr = tf1.attributesEqual(tf2);
422                 const sameParams = tf1.parameterList == tf2.parameterList;
423 
424                 // Allow the hack to declare overloads with different parameters/STC's
425                 // @@@DEPRECATED_2.094@@@
426                 // Deprecated in 2020-08, make this an error in 2.104
427                 if (parent1.isModule() &&
428                     f1.linkage != LINK.d && f1.linkage != LINK.cpp &&
429                     (!sameAttr || !sameParams)
430                 )
431                 {
432                     f2.deprecation("cannot overload `extern(%s)` function at %s",
433                             linkageToChars(f1.linkage),
434                             f1.loc.toChars());
435                     return 0;
436                 }
437 
438                 // Different parameters don't conflict in extern(C++/D)
439                 if (!sameParams)
440                     return 0;
441 
442                 // Different attributes don't conflict in extern(D)
443                 if (!sameAttr && f1.linkage == LINK.d)
444                     return 0;
445 
446                 error(f2.loc, "%s `%s%s` conflicts with previous declaration at %s",
447                         f2.kind(),
448                         f2.toPrettyChars(),
449                         parametersTypeToChars(tf2.parameterList),
450                         f1.loc.toChars());
451                 f2.type = Type.terror;
452                 f2.errors = true;
453                 return 0;
454             });
455         }
456         if (!fd.type || fd.type.ty != Tfunction)
457             return;
458         TypeFunction f = cast(TypeFunction) fd.type;
459 
460         UserAttributeDeclaration.checkGNUABITag(fd, fd.linkage);
461         //semantic for parameters' UDAs
462         foreach (i, param; f.parameterList)
463         {
464             if (param && param.userAttribDecl)
465                 param.userAttribDecl.semantic2(sc);
466         }
467     }
468 
visit(Import i)469     override void visit(Import i)
470     {
471         //printf("Import::semantic2('%s')\n", toChars());
472         if (!i.mod)
473             return;
474 
475         i.mod.semantic2(null);
476         if (i.mod.needmoduleinfo)
477         {
478             //printf("module5 %s because of %s\n", sc.module.toChars(), mod.toChars());
479             if (sc)
480                 sc._module.needmoduleinfo = 1;
481         }
482     }
483 
visit(Nspace ns)484     override void visit(Nspace ns)
485     {
486         if (ns.semanticRun >= PASS.semantic2)
487             return;
488         ns.semanticRun = PASS.semantic2;
489         static if (LOG)
490         {
491             printf("+Nspace::semantic2('%s')\n", ns.toChars());
492             scope(exit) printf("-Nspace::semantic2('%s')\n", ns.toChars());
493         }
494         UserAttributeDeclaration.checkGNUABITag(ns, LINK.cpp);
495         if (!ns.members)
496             return;
497 
498         assert(sc);
499         sc = sc.push(ns);
500         sc.linkage = LINK.cpp;
501         foreach (s; *ns.members)
502         {
503             static if (LOG)
504             {
505                 printf("\tmember '%s', kind = '%s'\n", s.toChars(), s.kind());
506             }
507             s.semantic2(sc);
508         }
509         sc.pop();
510     }
511 
visit(AttribDeclaration ad)512     override void visit(AttribDeclaration ad)
513     {
514         Dsymbols* d = ad.include(sc);
515         if (!d)
516             return;
517 
518         Scope* sc2 = ad.newScope(sc);
519         for (size_t i = 0; i < d.dim; i++)
520         {
521             Dsymbol s = (*d)[i];
522             s.semantic2(sc2);
523         }
524         if (sc2 != sc)
525             sc2.pop();
526     }
527 
528     /**
529      * Run the DeprecatedDeclaration's semantic2 phase then its members.
530      *
531      * The message set via a `DeprecatedDeclaration` can be either of:
532      * - a string literal
533      * - an enum
534      * - a static immutable
535      * So we need to call ctfe to resolve it.
536      * Afterward forwards to the members' semantic2.
537      */
visit(DeprecatedDeclaration dd)538     override void visit(DeprecatedDeclaration dd)
539     {
540         getMessage(dd);
541         visit(cast(AttribDeclaration)dd);
542     }
543 
visit(AlignDeclaration ad)544     override void visit(AlignDeclaration ad)
545     {
546         ad.getAlignment(sc);
547         visit(cast(AttribDeclaration)ad);
548     }
549 
visit(CPPNamespaceDeclaration decl)550     override void visit(CPPNamespaceDeclaration decl)
551     {
552         UserAttributeDeclaration.checkGNUABITag(decl, LINK.cpp);
553         visit(cast(AttribDeclaration)decl);
554     }
555 
visit(UserAttributeDeclaration uad)556     override void visit(UserAttributeDeclaration uad)
557     {
558         if (!uad.decl || !uad.atts || !uad.atts.dim || !uad._scope)
559             return visit(cast(AttribDeclaration)uad);
560 
561         Expression* lastTag;
562         static void eval(Scope* sc, Expressions* exps, ref Expression* lastTag)
563         {
564             foreach (ref Expression e; *exps)
565             {
566                 if (!e)
567                     continue;
568 
569                 e = e.expressionSemantic(sc);
570                 if (definitelyValueParameter(e))
571                     e = e.ctfeInterpret();
572                 if (e.op == TOK.tuple)
573                 {
574                     TupleExp te = cast(TupleExp)e;
575                     eval(sc, te.exps, lastTag);
576                 }
577 
578                 // Handles compiler-recognized `core.attribute.gnuAbiTag`
579                 if (UserAttributeDeclaration.isGNUABITag(e))
580                     doGNUABITagSemantic(e, lastTag);
581             }
582         }
583 
584         uad._scope = null;
585         eval(sc, uad.atts, lastTag);
586         visit(cast(AttribDeclaration)uad);
587     }
588 
visit(AggregateDeclaration ad)589     override void visit(AggregateDeclaration ad)
590     {
591         //printf("AggregateDeclaration::semantic2(%s) type = %s, errors = %d\n", ad.toChars(), ad.type.toChars(), ad.errors);
592         if (!ad.members)
593             return;
594 
595         if (ad._scope)
596         {
597             ad.error("has forward references");
598             return;
599         }
600 
601         UserAttributeDeclaration.checkGNUABITag(
602             ad, ad.classKind == ClassKind.cpp ? LINK.cpp : LINK.d);
603 
604         auto sc2 = ad.newScope(sc);
605 
606         ad.determineSize(ad.loc);
607 
608         for (size_t i = 0; i < ad.members.dim; i++)
609         {
610             Dsymbol s = (*ad.members)[i];
611             //printf("\t[%d] %s\n", i, s.toChars());
612             s.semantic2(sc2);
613         }
614 
615         sc2.pop();
616     }
617 
visit(ClassDeclaration cd)618     override void visit(ClassDeclaration cd)
619     {
620         /// Checks that the given class implements all methods of its interfaces.
621         static void checkInterfaceImplementations(ClassDeclaration cd)
622         {
623             foreach (base; cd.interfaces)
624             {
625                 // first entry is ClassInfo reference
626                 auto methods = base.sym.vtbl[base.sym.vtblOffset .. $];
627 
628                 foreach (m; methods)
629                 {
630                     auto ifd = m.isFuncDeclaration;
631                     assert(ifd);
632 
633                     if (ifd.objc.isOptional)
634                         continue;
635 
636                     auto type = ifd.type.toTypeFunction();
637                     auto fd = cd.findFunc(ifd.ident, type);
638 
639                     if (fd && !fd.isAbstract)
640                     {
641                         //printf("            found\n");
642                         // Check that calling conventions match
643                         if (fd.linkage != ifd.linkage)
644                             fd.error("linkage doesn't match interface function");
645 
646                         // Check that it is current
647                         //printf("newinstance = %d fd.toParent() = %s ifd.toParent() = %s\n",
648                             //newinstance, fd.toParent().toChars(), ifd.toParent().toChars());
649                         if (fd.toParent() != cd && ifd.toParent() == base.sym)
650                             cd.error("interface function `%s` is not implemented", ifd.toFullSignature());
651                     }
652                     else
653                     {
654                         //printf("            not found %p\n", fd);
655                         // BUG: should mark this class as abstract?
656                         if (!cd.isAbstract())
657                             cd.error("interface function `%s` is not implemented", ifd.toFullSignature());
658                     }
659                 }
660             }
661         }
662 
663         if (cd.semanticRun >= PASS.semantic2done)
664             return;
665         assert(cd.semanticRun <= PASS.semantic2);
666         cd.semanticRun = PASS.semantic2;
667 
668         checkInterfaceImplementations(cd);
669         visit(cast(AggregateDeclaration) cd);
670     }
671 
visit(InterfaceDeclaration cd)672     override void visit(InterfaceDeclaration cd)
673     {
674         visit(cast(AggregateDeclaration) cd);
675     }
676 }
677 
678 /**
679  * Perform semantic analysis specific to the GNU ABI tags
680  *
681  * The GNU ABI tags are a feature introduced in C++11, specific to g++
682  * and the Itanium ABI.
683  * They are mandatory for C++ interfacing, simply because the templated struct
684  *`std::basic_string`, of which the ubiquitous `std::string` is a instantiation
685  * of, uses them.
686  *
687  * Params:
688  *   e = Expression to perform semantic on
689  *       See `Semantic2Visitor.visit(UserAttributeDeclaration)`
690  *   lastTag = When `!is null`, we already saw an ABI tag.
691  *            To simplify implementation and reflection code,
692  *            only one ABI tag object is allowed per symbol
693  *            (but it can have multiple tags as it's an array exp).
694  */
doGNUABITagSemantic(ref Expression e,ref Expression * lastTag)695 private void doGNUABITagSemantic(ref Expression e, ref Expression* lastTag)
696 {
697     import dmd.dmangle;
698 
699     // When `@gnuAbiTag` is used, the type will be the UDA, not the struct literal
700     if (e.op == TOK.type)
701     {
702         e.error("`@%s` at least one argument expected", Id.udaGNUAbiTag.toChars());
703         return;
704     }
705 
706     // Definition is in `core.attributes`. If it's not a struct literal,
707     // it shouldn't have passed semantic, hence the `assert`.
708     auto sle = e.isStructLiteralExp();
709     if (sle is null)
710     {
711         assert(global.errors);
712         return;
713     }
714     // The definition of `gnuAttributes` only have 1 member, `string[] tags`
715     assert(sle.elements && sle.elements.length == 1);
716     // `gnuAbiTag`'s constructor is defined as `this(string[] tags...)`
717     auto ale = (*sle.elements)[0].isArrayLiteralExp();
718     if (ale is null)
719     {
720         e.error("`@%s` at least one argument expected", Id.udaGNUAbiTag.toChars());
721         return;
722     }
723 
724     // Check that it's the only tag on the symbol
725     if (lastTag !is null)
726     {
727         const str1 = (*lastTag.isStructLiteralExp().elements)[0].toString();
728         const str2 = ale.toString();
729         e.error("only one `@%s` allowed per symbol", Id.udaGNUAbiTag.toChars());
730         e.errorSupplemental("instead of `@%s @%s`, use `@%s(%.*s, %.*s)`",
731             lastTag.toChars(), e.toChars(), Id.udaGNUAbiTag.toChars(),
732             // Avoid [ ... ]
733             cast(int)str1.length - 2, str1.ptr + 1,
734             cast(int)str2.length - 2, str2.ptr + 1);
735         return;
736     }
737     lastTag = &e;
738 
739     // We already know we have a valid array literal of strings.
740     // Now checks that elements are valid.
741     foreach (idx, elem; *ale.elements)
742     {
743         const str = elem.toStringExp().peekString();
744         if (!str.length)
745         {
746             e.error("argument `%d` to `@%s` cannot be %s", cast(int)(idx + 1),
747                     Id.udaGNUAbiTag.toChars(),
748                     elem.isNullExp() ? "`null`".ptr : "empty".ptr);
749             continue;
750         }
751 
752         foreach (c; str)
753         {
754             if (!c.isValidMangling())
755             {
756                 e.error("`@%s` char `0x%02x` not allowed in mangling",
757                         Id.udaGNUAbiTag.toChars(), c);
758                 break;
759             }
760         }
761         // Valid element
762     }
763     // Since ABI tags need to be sorted, we sort them in place
764     // It might be surprising for users that inspects the UDAs,
765     // but it's a concession to practicality.
766     // Casts are unfortunately necessary as `implicitConvTo` is not
767     // `const` (and nor is `StringExp`, by extension).
768     static int predicate(const scope Expression* e1, const scope Expression* e2) nothrow
769     {
770         scope(failure) assert(0, "An exception was thrown");
771         return (cast(Expression*)e1).toStringExp().compare((cast(Expression*)e2).toStringExp());
772     }
773     ale.elements.sort!predicate;
774 }
775