Debian Codegraph @

gcc/d/dmd/mangle/package.d

raw
1 /**
2 * Does name mangling for `extern(D)` symbols.
3 *
4 * Specification: $(LINK2 https://dlang.org/spec/abi.html#name_mangling, Name Mangling)
5 *
6 * Copyright: Copyright (C) 1999-2025 by The D Language Foundation, All Rights Reserved
7 * Authors: Walter Bright, https://www.digitalmars.com
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/mangle/package.d, _dmangle.d)
10 * Documentation: https://dlang.org/phobos/dmd_dmangle.html
11 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/mangle/package.d
12 * References: https://dlang.org/blog/2017/12/20/ds-newfangled-name-mangling/
13 */
14
15 module dmd.mangle;
16
17
18 /******************************************************************************
19 * Returns exact mangled name of function.
20 */
21 const(char)* mangleExact(FuncDeclaration fd)
22 {
23 //printf("mangleExact()\n");
24 if (!fd.mangleString)
25 {
26 OutBuffer buf;
27 auto backref = Backref(null);
28 scope Mangler v = new Mangler(buf, &backref);
29 v.mangleExact(fd);
30 fd.mangleString = buf.extractChars();
31 }
32 return fd.mangleString;
33 }
34
35 void mangleToBuffer(Type t, ref OutBuffer buf)
36 {
37 //printf("mangleToBuffer t()\n");
38 if (t.deco)
39 buf.writestring(t.deco);
40 else
41 {
42 auto backref = Backref(t);
43 mangleType(t, 0, buf, backref);
44 //printf("%s\n", buf.peekChars());
45 }
46 }
47
48 void mangleToBuffer(Expression e, ref OutBuffer buf)
49 {
50 //printf("mangleToBuffer e()\n");
51 auto backref = Backref(null);
52 scope Mangler v = new Mangler(buf, &backref);
53 e.accept(v);
54 }
55
56 void mangleToBuffer(Dsymbol s, ref OutBuffer buf)
57 {
58 //printf("mangleToBuffer s(%s)\n", s.toChars());
59 auto backref = Backref(null);
60 scope Mangler v = new Mangler(buf, &backref);
61 s.accept(v);
62 }
63
64 void mangleToBuffer(TemplateInstance ti, ref OutBuffer buf)
65 {
66 //printf("mangleToBuffer ti()\n");
67 auto backref = Backref(null);
68 scope Mangler v = new Mangler(buf, &backref);
69 v.mangleTemplateInstance(ti);
70 }
71
72 /// Returns: `true` if the given character is a valid mangled character
73 package(dmd) bool isValidMangling(dchar c) nothrow
74 {
75 import dmd.common.charactertables;
76
77 return
78 c >= 'A' && c <= 'Z' ||
79 c >= 'a' && c <= 'z' ||
80 c >= '0' && c <= '9' ||
81 c != 0 && strchr("$%().:?@[]_", c) ||
82 isAnyIdentifierCharacter(c);
83 }
84
85 // valid mangled characters
86 unittest
87 {
88 assert('a'.isValidMangling);
89 assert('B'.isValidMangling);
90 assert('2'.isValidMangling);
91 assert('@'.isValidMangling);
92 assert('_'.isValidMangling);
93 }
94
95 // invalid mangled characters
96 unittest
97 {
98 assert(!'-'.isValidMangling);
99 assert(!0.isValidMangling);
100 assert(!'/'.isValidMangling);
101 assert(!'\\'.isValidMangling);
102 }
103
104 /**********************************************
105 * Convert a string representing a type (the deco) and
106 * return its equivalent Type.
107 * Params:
108 * deco = string containing the deco
109 * Returns:
110 * null for failed to convert
111 * Type for succeeded
112 */
113
114 public Type decoToType(const(char)[] deco)
115 {
116 //printf("decoToType(): %.*s\n", cast(int)deco.length, deco.ptr);
117 if (auto sv = Type.stringtable.lookup(deco))
118 {
119 if (sv.value)
120 {
121 Type t = cast(Type)sv.value;
122 assert(t.deco);
123 return t;
124 }
125 }
126 return null;
127 }
128
129
130 /***************************************** private ***************************************/
131
132 private:
133
134
135 import core.stdc.ctype;
136 import core.stdc.stdio;
137 import core.stdc.string;
138
139 import dmd.aggregate;
140 import dmd.arraytypes;
141 import dmd.astenums;
142 import dmd.mangle.basic;
143 import dmd.dclass;
144 import dmd.declaration;
145 import dmd.dinterpret;
146 import dmd.dmodule;
147 import dmd.dsymbol;
148 import dmd.dtemplate;
149 import dmd.errors;
150 import dmd.expression;
151 import dmd.func;
152 import dmd.funcsem;
153 import dmd.globals;
154 import dmd.id;
155 import dmd.identifier;
156 import dmd.mtype;
157 import dmd.root.ctfloat;
158 import dmd.common.outbuffer;
159 import dmd.optimize;
160 import dmd.root.aav;
161 import dmd.root.string;
162 import dmd.root.stringtable;
163 import dmd.root.utf;
164 import dmd.target;
165 import dmd.tokens;
166 import dmd.visitor;
167
168 /************************************************
169 * Append the mangling of type `t` to `buf`.
170 * Params:
171 * t = type to mangle
172 * modMask = mod bits currently applying to t
173 * buf = buffer to append mangling to
174 * backref = state of back references (updated)
175 */
176 void mangleType(Type t, ubyte modMask, ref OutBuffer buf, ref Backref backref)
177 {
178 void visitWithMask(Type t, ubyte modMask)
179 {
180 void mangleSymbol(Dsymbol s)
181 {
182 scope Mangler v = new Mangler(buf, &backref);
183 v.mangleSymbol(s);
184 }
185
186 void visitType(Type t)
187 {
188 tyToDecoBuffer(buf, t.ty);
189 }
190
191 void visitTypeNext(TypeNext t)
192 {
193 visitType(t);
194 visitWithMask(t.next, t.mod);
195 }
196
197 void visitTypeVector(TypeVector t)
198 {
199 buf.writestring("Nh");
200 visitWithMask(t.basetype, t.mod);
201 }
202
203 void visitTypeSArray(TypeSArray t)
204 {
205 visitType(t);
206 if (t.dim)
207 buf.print(t.dim.toInteger());
208 if (t.next)
209 visitWithMask(t.next, t.mod);
210 }
211
212 void visitTypeDArray(TypeDArray t)
213 {
214 visitType(t);
215 if (t.next)
216 visitWithMask(t.next, t.mod);
217 }
218
219 void visitTypeAArray(TypeAArray t)
220 {
221 visitType(t);
222 visitWithMask(t.index, 0);
223 visitWithMask(t.next, t.mod);
224 }
225
226 void visitTypeFunction(TypeFunction t)
227 {
228 //printf("TypeFunction.toDecoBuffer() t = %p %s\n", t, t.toChars());
229 //static int nest; if (++nest == 50) *(char*)0=0;
230 mangleFuncType(t, t, t.mod, t.next, buf, backref);
231 }
232
233 void visitTypeIdentifier(TypeIdentifier t)
234 {
235 visitType(t);
236 auto name = t.ident.toString();
237 buf.print(cast(int)name.length);
238 buf.writestring(name);
239 }
240
241 void visitTypeEnum(TypeEnum t)
242 {
243 visitType(t);
244 mangleSymbol(t.sym);
245 }
246
247 void visitTypeStruct(TypeStruct t)
248 {
249 //printf("TypeStruct.toDecoBuffer('%s') = '%s'\n", t.toChars(), name);
250 visitType(t);
251 mangleSymbol(t.sym);
252 }
253
254 void visitTypeClass(TypeClass t)
255 {
256 //printf("TypeClass.toDecoBuffer('%s' mod=%x) = '%s'\n", t.toChars(), mod, name);
257 visitType(t);
258 mangleSymbol(t.sym);
259 }
260
261 void visitTypeTuple(TypeTuple t)
262 {
263 //printf("TypeTuple.toDecoBuffer() t = %p, %s\n", t, t.toChars());
264 visitType(t);
265 Parameter._foreach(t.arguments, (idx, param) {
266 mangleParameter(param, buf, backref);
267 return 0;
268 });
269 buf.writeByte('Z');
270 }
271
272 void visitTypeNull(TypeNull t)
273 {
274 visitType(t);
275 }
276
277 void visitTypeNoreturn(TypeNoreturn t)
278 {
279 buf.writestring("Nn");
280 }
281
282 if (modMask != t.mod)
283 {
284 MODtoDecoBuffer(buf, t.mod);
285 }
286 if (backref.addRefToType(buf, t))
287 return;
288
289 switch (t.ty)
290 {
291 case Tpointer:
292 case Treference:
293 case Tdelegate:
294 case Tslice: visitTypeNext (cast(TypeNext)t); break;
295
296 case Tarray: visitTypeDArray (t.isTypeDArray()); break;
297 case Tsarray: visitTypeSArray (t.isTypeSArray()); break;
298 case Taarray: visitTypeAArray (t.isTypeAArray()); break;
299 case Tfunction: visitTypeFunction (t.isTypeFunction()); break;
300 case Tident: visitTypeIdentifier(t.isTypeIdentifier()); break;
301 case Tclass: visitTypeClass (t.isTypeClass()); break;
302 case Tstruct: visitTypeStruct (t.isTypeStruct()); break;
303 case Tenum: visitTypeEnum (t.isTypeEnum()); break;
304 case Ttuple: visitTypeTuple (t.isTypeTuple()); break;
305 case Tnull: visitTypeNull (t.isTypeNull()); break;
306 case Tvector: visitTypeVector (t.isTypeVector()); break;
307 case Tnoreturn: visitTypeNoreturn (t.isTypeNoreturn); break;
308
309 case Terror:
310 break; // ignore errors
311
312 default: visitType(t); break;
313 }
314 }
315
316 visitWithMask(t, modMask);
317 }
318
319
320 /*************************************************************
321 */
322 void mangleFuncType(TypeFunction t, TypeFunction ta, ubyte modMask, Type tret, ref OutBuffer buf, ref Backref backref)
323 {
324 //printf("mangleFuncType() %s\n", t.toChars());
325 if (t.inuse && tret)
326 {
327 // printf("TypeFunction.mangleFuncType() t = %s inuse\n", t.toChars());
328 t.inuse = 2; // flag error to caller
329 return;
330 }
331 t.inuse++;
332 if (modMask != t.mod)
333 MODtoDecoBuffer(buf, t.mod);
334
335 char mc;
336 final switch (t.linkage)
337 {
338 case LINK.default_:
339 case LINK.d:
340 mc = 'F';
341 break;
342 case LINK.c:
343 mc = 'U';
344 break;
345 case LINK.windows:
346 mc = 'W';
347 break;
348 case LINK.cpp:
349 mc = 'R';
350 break;
351 case LINK.objc:
352 mc = 'Y';
353 break;
354 case LINK.system:
355 assert(0);
356 }
357 buf.writeByte(mc);
358
359 if (ta.purity)
360 buf.writestring("Na");
361 if (ta.isNothrow)
362 buf.writestring("Nb");
363 if (ta.isRef)
364 buf.writestring("Nc");
365 if (ta.isProperty)
366 buf.writestring("Nd");
367 if (ta.isNogc)
368 buf.writestring("Ni");
369
370 // `return scope` must be in that order
371 if (ta.isReturnScope && !ta.isReturnInferred)
372 {
373 buf.writestring("NjNl");
374 }
375 else
376 {
377 // when return ref, the order is `scope return`
378 if (ta.isScopeQual && !ta.isScopeInferred)
379 buf.writestring("Nl");
380
381 if (ta.isReturn && !ta.isReturnInferred)
382 buf.writestring("Nj");
383 }
384
385 if (ta.isLive)
386 buf.writestring("Nm");
387
388 switch (ta.trust)
389 {
390 case TRUST.trusted:
391 buf.writestring("Ne");
392 break;
393 case TRUST.safe:
394 buf.writestring("Nf");
395 break;
396 default:
397 break;
398 }
399
400 // Write argument types
401 foreach (idx, param; t.parameterList)
402 mangleParameter(param, buf, backref);
403 //if (buf.data[buf.length - 1] == '@') assert(0);
404 buf.writeByte('Z' - t.parameterList.varargs); // mark end of arg list
405 if (tret !is null)
406 mangleType(tret, 0, buf, backref);
407 t.inuse--;
408 }
409
410 /*************************************************************
411 */
412 void mangleParameter(Parameter p, ref OutBuffer buf, ref Backref backref)
413 {
414 // https://dlang.org/spec/abi.html#Parameter
415
416 auto stc = p.storageClass;
417
418 // Inferred storage classes don't get mangled in
419 if (stc & STC.scopeinferred)
420 stc &= ~(STC.scope_ | STC.scopeinferred);
421 if (stc & STC.returninferred)
422 stc &= ~(STC.return_ | STC.returninferred);
423
424 // much like hdrgen.stcToBuffer()
425 string rrs;
426 const isout = (stc & STC.out_) != 0;
427 final switch (buildScopeRef(stc))
428 {
429 case ScopeRef.None:
430 case ScopeRef.Scope:
431 case ScopeRef.Ref:
432 case ScopeRef.Return:
433 case ScopeRef.RefScope:
434 break;
435
436 case ScopeRef.ReturnScope: rrs = "NkM"; goto L1; // return scope
437 case ScopeRef.ReturnRef: rrs = isout ? "NkJ" : "NkK"; goto L1; // return ref
438 case ScopeRef.ReturnRef_Scope: rrs = isout ? "MNkJ" : "MNkK"; goto L1; // scope return ref
439 case ScopeRef.Ref_ReturnScope: rrs = isout ? "NkMJ" : "NkMK"; goto L1; // return scope ref
440 L1:
441 buf.writestring(rrs);
442 stc &= ~(STC.out_ | STC.scope_ | STC.ref_ | STC.return_);
443 break;
444 }
445
446 if (stc & STC.scope_)
447 buf.writeByte('M'); // scope
448
449 if (stc & STC.return_)
450 buf.writestring("Nk"); // return
451
452 switch (stc & ((STC.IOR | STC.lazy_) & ~STC.constscoperef))
453 {
454 case STC.none:
455 break;
456 case STC.in_:
457 buf.writeByte('I');
458 break;
459 case STC.in_ | STC.ref_:
460 buf.writestring("IK");
461 break;
462 case STC.out_:
463 buf.writeByte('J');
464 break;
465 case STC.ref_:
466 buf.writeByte('K');
467 break;
468 case STC.lazy_:
469 buf.writeByte('L');
470 break;
471 default:
472 debug
473 {
474 printf("storageClass = x%llx\n", stc & (STC.IOR | STC.lazy_));
475 }
476 assert(0);
477 }
478 mangleType(p.type, (stc & STC.in_) ? MODFlags.const_ : 0, buf, backref);
479 }
480
481
482 private extern (C++) final class Mangler : Visitor
483 {
484 alias visit = Visitor.visit;
485 public:
486 static assert(Key.sizeof == size_t.sizeof);
487
488 OutBuffer* buf;
489 Backref* backref;
490
491 extern (D) this(ref OutBuffer buf, Backref* backref) @trusted
492 {
493 this.buf = &buf;
494 this.backref = backref;
495 }
496
497 void mangleSymbol(Dsymbol s)
498 {
499 s.accept(this);
500 }
501
502 void mangleIdentifier(Identifier id, Dsymbol s)
503 {
504 if (!backref.addRefToIdentifier(*buf, id))
505 toBuffer(*buf, id.toString(), s);
506 }
507
508 void mangleInteger(dinteger_t v)
509 {
510 if (cast(sinteger_t) v < 0)
511 {
512 buf.writeByte('N');
513 buf.print(-v);
514 }
515 else
516 {
517 buf.writeByte('i');
518 buf.print(v);
519 }
520 }
521
522 ////////////////////////////////////////////////////////////////////////////
523 void mangleDecl(Declaration sthis)
524 {
525 mangleParent(sthis);
526 assert(sthis.ident);
527 mangleIdentifier(sthis.ident, sthis);
528 if (FuncDeclaration fd = sthis.isFuncDeclaration())
529 {
530 mangleFunc(fd, false);
531 }
532 else if (sthis.type)
533 {
534 mangleType(sthis.type, 0, *buf, *backref);
535 }
536 else
537 assert(0);
538 }
539
540 void mangleParent(Dsymbol s)
541 {
542 //printf("mangleParent() %s %s\n", s.kind(), s.toChars());
543 Dsymbol p;
544 if (TemplateInstance ti = s.isTemplateInstance())
545 p = ti.isTemplateMixin() ? ti.parent : ti.tempdecl.parent;
546 else
547 p = s.parent;
548 if (p)
549 {
550 uint localNum = s.localNum;
551 mangleParent(p);
552 auto ti = p.isTemplateInstance();
553 if (ti && !ti.isTemplateMixin())
554 {
555 localNum = ti.tempdecl.localNum;
556 mangleTemplateInstance(ti);
557 }
558 else if (p.getIdent())
559 {
560 mangleIdentifier(p.ident, s);
561 if (FuncDeclaration f = p.isFuncDeclaration())
562 mangleFunc(f, true);
563 }
564 else
565 buf.writeByte('0');
566
567 if (localNum)
568 writeLocalParent(*buf, localNum);
569 }
570 }
571
572 void mangleFunc(FuncDeclaration fd, bool inParent)
573 {
574 //printf("deco = '%s'\n", fd.type.deco ? fd.type.deco : "null");
575 //printf("fd.type = %s\n", fd.type.toChars());
576 if (fd.needThis() || fd.isNested())
577 buf.writeByte('M');
578
579 if (!fd.type || fd.type.ty == Terror)
580 {
581 // never should have gotten here, but could be the result of
582 // failed speculative compilation
583 buf.writestring("9__error__FZ");
584
585 //printf("[%s] %s no type\n", fd.loc.toChars(), fd.toChars());
586 //assert(0); // don't mangle function until semantic3 done.
587 }
588 else if (inParent)
589 {
590 TypeFunction tf = fd.type.isTypeFunction();
591 TypeFunction tfo = fd.originalType.isTypeFunction();
592 mangleFuncType(tf, tfo, 0, null, *buf, *backref);
593 }
594 else
595 {
596 mangleType(fd.type, 0, *buf, *backref);
597 }
598 }
599
600 override void visit(Declaration d)
601 {
602 //printf("Declaration.mangle(this = %p, '%s', parent = '%s', linkage = %d)\n",
603 // d, d.toChars(), d.parent ? d.parent.toChars() : "null", d.linkage);
604 if (const id = externallyMangledIdentifier(d))
605 {
606 buf.writestring(id);
607 return;
608 }
609 buf.writestring("_D");
610 mangleDecl(d);
611 debug
612 {
613 const slice = (*buf)[];
614 assert(slice.length);
615 for (size_t pos; pos < slice.length; )
616 {
617 dchar c;
618 auto ppos = pos;
619 const s = utf_decodeChar(slice, pos, c);
620 assert(s is null, s);
621 assert(c.isValidMangling, "The mangled name '" ~ slice ~ "' " ~
622 "contains an invalid character: " ~ slice[ppos..pos]);
623 }
624 }
625 }
626
627 /******************************************************************************
628 * Normally FuncDeclaration and FuncAliasDeclaration have overloads.
629 * If and only if there is no overloads, mangle() could return
630 * exact mangled name.
631 *
632 * module test;
633 * void foo(long) {} // _D4test3fooFlZv
634 * void foo(string) {} // _D4test3fooFAyaZv
635 *
636 * // from FuncDeclaration.mangle().
637 * pragma(msg, foo.mangleof); // prints unexact mangled name "4test3foo"
638 * // by calling Dsymbol.mangle()
639 *
640 * // from FuncAliasDeclaration.mangle()
641 * pragma(msg, __traits(getOverloads, test, "foo")[0].mangleof); // "_D4test3fooFlZv"
642 * pragma(msg, __traits(getOverloads, test, "foo")[1].mangleof); // "_D4test3fooFAyaZv"
643 *
644 * If a function has no overloads, .mangleof property still returns exact mangled name.
645 *
646 * void bar() {}
647 * pragma(msg, bar.mangleof); // still prints "_D4test3barFZv"
648 * // by calling FuncDeclaration.mangleExact().
649 */
650 override void visit(FuncDeclaration fd)
651 {
652 if (fd.isUnique())
653 mangleExact(fd);
654 else
655 visit(cast(Dsymbol)fd);
656 }
657
658 // ditto
659 override void visit(FuncAliasDeclaration fd)
660 {
661 FuncDeclaration f = fd.toAliasFunc();
662 FuncAliasDeclaration fa = f.isFuncAliasDeclaration();
663 if (!fd.hasOverloads && !fa)
664 {
665 mangleExact(f);
666 return;
667 }
668 if (fa)
669 {
670 mangleSymbol(fa);
671 return;
672 }
673 visit(cast(Dsymbol)fd);
674 }
675
676 override void visit(OverDeclaration od)
677 {
678 if (od.overnext)
679 {
680 visit(cast(Dsymbol)od);
681 return;
682 }
683 if (FuncDeclaration fd = od.aliassym.isFuncDeclaration())
684 {
685 if (fd.isUnique())
686 {
687 mangleExact(fd);
688 return;
689 }
690 }
691 if (TemplateDeclaration td = od.aliassym.isTemplateDeclaration())
692 {
693 if (td.overnext is null)
694 {
695 mangleSymbol(td);
696 return;
697 }
698 }
699 visit(cast(Dsymbol)od);
700 }
701
702 void mangleExact(FuncDeclaration fd)
703 {
704 assert(!fd.isFuncAliasDeclaration());
705 if (fd.mangleOverride)
706 {
707 buf.writestring(fd.mangleOverride);
708 return;
709 }
710 if (fd.isMain())
711 {
712 buf.writestring("_Dmain");
713 return;
714 }
715 if (fd.isWinMain() || fd.isDllMain())
716 {
717 buf.writestring(fd.ident.toString());
718 return;
719 }
720 visit(cast(Declaration)fd);
721 }
722
723 override void visit(VarDeclaration vd)
724 {
725 if (vd.mangleOverride)
726 {
727 buf.writestring(vd.mangleOverride);
728 return;
729 }
730 visit(cast(Declaration)vd);
731 }
732
733 override void visit(AggregateDeclaration ad)
734 {
735 ClassDeclaration cd = ad.isClassDeclaration();
736 Dsymbol parentsave = ad.parent;
737 if (cd)
738 {
739 /* These are reserved to the compiler, so keep simple
740 * names for them.
741 */
742 if (cd.ident == Id.Exception && cd.parent.ident == Id.object || cd.ident == Id.TypeInfo || cd.ident == Id.TypeInfo_Struct || cd.ident == Id.TypeInfo_Class || cd.ident == Id.TypeInfo_Tuple || cd == ClassDeclaration.object || cd == Type.typeinfoclass || cd == Module.moduleinfo || strncmp(cd.ident.toChars(), "TypeInfo_", 9) == 0)
743 {
744 // Don't mangle parent
745 ad.parent = null;
746 }
747 }
748 visit(cast(Dsymbol)ad);
749 ad.parent = parentsave;
750 }
751
752 override void visit(TemplateInstance ti)
753 {
754 version (none)
755 {
756 printf("TemplateInstance.mangle() %p %s", ti, ti.toChars());
757 if (ti.parent)
758 printf(" parent = %s %s", ti.parent.kind(), ti.parent.toChars());
759 printf("\n");
760 }
761 if (!ti.tempdecl)
762 error(ti.loc, "%s `%s` is not defined", ti.kind, ti.toPrettyChars);
763 else
764 mangleParent(ti);
765
766 if (ti.isTemplateMixin() && ti.ident)
767 mangleIdentifier(ti.ident, ti);
768 else
769 mangleTemplateInstance(ti);
770 }
771
772 void mangleTemplateInstance(TemplateInstance ti)
773 {
774 TemplateDeclaration tempdecl = ti.tempdecl.isTemplateDeclaration();
775 assert(tempdecl);
776
777 // Use "__U" for the symbols declared inside template constraint.
778 const char T = ti.members ? 'T' : 'U';
779 buf.printf("__%c", T);
780 mangleIdentifier(tempdecl.ident, tempdecl);
781
782 auto args = ti.tiargs;
783 size_t nparams = tempdecl.parameters.length - (tempdecl.isVariadic() ? 1 : 0);
784 for (size_t i = 0; i < args.length; i++)
785 {
786 auto o = (*args)[i];
787 Type ta = isType(o);
788 Expression ea = isExpression(o);
789 Dsymbol sa = isDsymbol(o);
790 Tuple va = isTuple(o);
791 //printf("\to [%d] %p ta %p ea %p sa %p va %p\n", i, o, ta, ea, sa, va);
792 if (i < nparams && (*tempdecl.parameters)[i].specialization())
793 buf.writeByte('H'); // https://issues.dlang.org/show_bug.cgi?id=6574
794 if (ta)
795 {
796 buf.writeByte('T');
797 mangleType(ta, 0, *buf, *backref);
798 }
799 else if (ea)
800 {
801 // Don't interpret it yet, it might actually be an alias template parameter.
802 // Only constfold manifest constants, not const/immutable lvalues, see https://issues.dlang.org/show_bug.cgi?id=17339.
803 enum keepLvalue = true;
804 ea = ea.optimize(WANTvalue, keepLvalue);
805 if (auto ev = ea.isVarExp())
806 {
807 sa = ev.var;
808 ea = null;
809 goto Lsa;
810 }
811 if (auto et = ea.isThisExp())
812 {
813 sa = et.var;
814 ea = null;
815 goto Lsa;
816 }
817 if (auto ef = ea.isFuncExp())
818 {
819 if (ef.td)
820 sa = ef.td;
821 else
822 sa = ef.fd;
823 ea = null;
824 goto Lsa;
825 }
826 buf.writeByte('V');
827 if (ea.op == EXP.tuple)
828 {
829 error(ea.loc, "sequence is not a valid template value argument");
830 continue;
831 }
832 // Now that we know it is not an alias, we MUST obtain a value
833 const olderr = global.errors;
834 ea = ea.ctfeInterpret();
835 if (ea.op == EXP.error || olderr != global.errors)
836 continue;
837
838 /* Use type mangling that matches what it would be for a function parameter
839 */
840 mangleType(ea.type, 0, *buf, *backref);
841 ea.accept(this);
842 }
843 else if (sa)
844 {
845 Lsa:
846 sa = sa.toAlias();
847 if (sa.isDeclaration() && !sa.isOverDeclaration())
848 {
849 Declaration d = sa.isDeclaration();
850
851 if (auto fad = d.isFuncAliasDeclaration())
852 d = fad.toAliasFunc();
853 if (d.mangleOverride)
854 {
855 buf.writeByte('X');
856 toBuffer(*buf, d.mangleOverride, d);
857 continue;
858 }
859 if (const id = externallyMangledIdentifier(d))
860 {
861 buf.writeByte('X');
862 toBuffer(*buf, id, d);
863 continue;
864 }
865 if (!d.type || !d.type.deco)
866 {
867 error(ti.loc, "%s `%s` forward reference of %s `%s`", ti.kind, ti.toPrettyChars, d.kind(), d.toChars());
868 continue;
869 }
870 }
871 buf.writeByte('S');
872 mangleSymbol(sa);
873 }
874 else if (va)
875 {
876 assert(i + 1 == args.length); // must be last one
877 args = &va.objects;
878 i = -cast(size_t)1;
879 }
880 else
881 assert(0);
882 }
883 buf.writeByte('Z');
884 }
885
886 override void visit(Dsymbol s)
887 {
888 version (none)
889 {
890 printf("Dsymbol.mangle() '%s'", s.toChars());
891 if (s.parent)
892 printf(" parent = %s %s", s.parent.kind(), s.parent.toChars());
893 printf("\n");
894 }
895 if (s.parent && s.ident)
896 {
897 if (auto m = s.parent.isModule())
898 {
899 if (m.filetype == FileType.c)
900 {
901 /* C types at global level get mangled into the __C global namespace
902 * to get the same mangling regardless of which module it
903 * is declared in. This works because types are the same if the mangling
904 * is the same.
905 */
906 mangleIdentifier(Id.ImportC, s); // parent
907 mangleIdentifier(s.ident, s);
908 return;
909 }
910 }
911 }
912 mangleParent(s);
913 if (s.ident)
914 mangleIdentifier(s.ident, s);
915 else
916 toBuffer(*buf, s.toString(), s);
917 //printf("Dsymbol.mangle() %s = %s\n", s.toChars(), id);
918 }
919
920 ////////////////////////////////////////////////////////////////////////////
921 override void visit(Expression e)
922 {
923 if (!e.type.isTypeError())
924 error(e.loc, "expression `%s` is not a valid template value argument", e.toChars());
925 }
926
927 override void visit(IntegerExp e)
928 {
929 mangleInteger(e.toInteger());
930 }
931
932 override void visit(RealExp e)
933 {
934 buf.writeByte('e');
935 realToMangleBuffer(*buf, e.value);
936 }
937
938 override void visit(ComplexExp e)
939 {
940 buf.writeByte('c');
941 realToMangleBuffer(*buf, e.toReal());
942 buf.writeByte('c'); // separate the two
943 realToMangleBuffer(*buf, e.toImaginary());
944 }
945
946 override void visit(NullExp e)
947 {
948 buf.writeByte('n');
949 }
950
951 override void visit(StringExp e)
952 {
953 char m;
954 OutBuffer tmp;
955 const(char)[] q;
956
957 void mangleAsArray()
958 {
959 buf.writeByte('A');
960 buf.print(e.len);
961 foreach (i; 0 .. e.len)
962 mangleInteger(e.getIndex(i));
963 }
964
965 /* Write string in UTF-8 format
966 */
967 switch (e.sz)
968 {
969 case 1:
970 m = 'a';
971 q = e.peekString();
972 break;
973 case 2:
974 {
975 m = 'w';
976 const slice = e.peekWstring();
977 for (size_t u = 0; u < e.len;)
978 {
979 dchar c;
980 if (const s = utf_decodeWchar(slice, u, c))
981 return mangleAsArray();
982 else
983 tmp.writeUTF8(c);
984 }
985 q = tmp[];
986 break;
987 }
988 case 4:
989 {
990 m = 'd';
991 const slice = e.peekDstring();
992 foreach (c; slice)
993 {
994 if (!utf_isValidDchar(c))
995 return mangleAsArray();
996 else
997 tmp.writeUTF8(c);
998 }
999 q = tmp[];
1000 break;
1001 }
1002 case 8:
1003 // String of size 8 has to be hexstring cast to long[], mangle as array literal
1004 return mangleAsArray();
1005 default:
1006 assert(0);
1007 }
1008 buf.reserve(1 + 11 + 2 * q.length);
1009 buf.writeByte(m);
1010 buf.print(q.length);
1011 buf.writeByte('_'); // nbytes <= 11
1012 buf.writeHexString(cast(const(ubyte)[]) q, false);
1013 }
1014
1015 override void visit(ArrayLiteralExp e)
1016 {
1017 const dim = e.elements ? e.elements.length : 0;
1018 buf.writeByte('A');
1019 buf.print(dim);
1020 foreach (i; 0 .. dim)
1021 {
1022 e[i].accept(this);
1023 }
1024 }
1025
1026 override void visit(AssocArrayLiteralExp e)
1027 {
1028 const dim = e.keys.length;
1029 buf.writeByte('A');
1030 buf.print(dim);
1031 foreach (i; 0 .. dim)
1032 {
1033 (*e.keys)[i].accept(this);
1034 (*e.values)[i].accept(this);
1035 }
1036 }
1037
1038 override void visit(StructLiteralExp e)
1039 {
1040 const dim = e.elements ? e.elements.length : 0;
1041 buf.writeByte('S');
1042 buf.print(dim);
1043 foreach (i; 0 .. dim)
1044 {
1045 Expression ex = (*e.elements)[i];
1046 if (ex)
1047 ex.accept(this);
1048 else
1049 buf.writeByte('v'); // 'v' for void
1050 }
1051 }
1052
1053 override void visit(FuncExp e)
1054 {
1055 buf.writeByte('f');
1056 if (e.td)
1057 mangleSymbol(e.td);
1058 else
1059 mangleSymbol(e.fd);
1060 }
1061 }
1062
1063 /***************************************
1064 * Manage back reference mangling
1065 */
1066 private struct Backref
1067 {
1068 /**
1069 * Back references a non-basic type
1070 *
1071 * The encoded mangling is
1072 * 'Q' <relative position of first occurrence of type>
1073 *
1074 * Params:
1075 * t = the type to encode via back referencing
1076 *
1077 * Returns:
1078 * true if the type was found. A back reference has been encoded.
1079 * false if the type was not found. The current position is saved for later back references.
1080 */
1081 bool addRefToType(ref OutBuffer buf, Type t)
1082 {
1083 if (t.isTypeBasic())
1084 return false;
1085
1086 /**
1087 * https://issues.dlang.org/show_bug.cgi?id=21591
1088 *
1089 * Special case for unmerged TypeFunctions: use the generic merged
1090 * function type as backref cache key to avoid missed backrefs.
1091 *
1092 * Merging is based on mangling, so we need to avoid an infinite
1093 * recursion by excluding the case where `t` is the root type passed to
1094 * `mangleToBuffer()`.
1095 */
1096 if (t != rootType)
1097 {
1098 if (t.isFunction_Delegate_PtrToFunction())
1099 {
1100 import dmd.typesem : merge2;
1101 t = t.merge2();
1102 }
1103 }
1104
1105 return backrefImpl(buf, types, t);
1106 }
1107
1108 /**
1109 * Back references a single identifier
1110 *
1111 * The encoded mangling is
1112 * 'Q' <relative position of first occurrence of type>
1113 *
1114 * Params:
1115 * id = the identifier to encode via back referencing
1116 *
1117 * Returns:
1118 * true if the identifier was found. A back reference has been encoded.
1119 * false if the identifier was not found. The current position is saved for later back references.
1120 */
1121 bool addRefToIdentifier(ref OutBuffer buf, Identifier id)
1122 {
1123 return backrefImpl(buf, idents, id);
1124 }
1125
1126 private:
1127
1128 extern(D) bool backrefImpl(T)(ref OutBuffer buf, ref AssocArray!(T, size_t) aa, T key)
1129 {
1130 auto p = aa.getLvalue(key);
1131 if (*p)
1132 {
1133 const offset = *p - 1;
1134 writeBackRef(buf, buf.length - offset);
1135 return true;
1136 }
1137 *p = buf.length + 1;
1138 return false;
1139 }
1140
1141 Type rootType; /// avoid infinite recursion
1142 AssocArray!(Type, size_t) types; /// Type => (offset+1) in buf
1143 AssocArray!(Identifier, size_t) idents; /// Identifier => (offset+1) in buf
1144 }
1145
1146 /*********************************
1147 * Mangling for mod.
1148 */
1149 private void MODtoDecoBuffer(ref OutBuffer buf, MOD mod) @safe
1150 {
1151 switch (mod)
1152 {
1153 case 0:
1154 break;
1155 case MODFlags.const_:
1156 buf.writeByte('x');
1157 break;
1158 case MODFlags.immutable_:
1159 buf.writeByte('y');
1160 break;
1161 case MODFlags.shared_:
1162 buf.writeByte('O');
1163 break;
1164 case MODFlags.shared_ | MODFlags.const_:
1165 buf.writestring("Ox");
1166 break;
1167 case MODFlags.wild:
1168 buf.writestring("Ng");
1169 break;
1170 case MODFlags.wildconst:
1171 buf.writestring("Ngx");
1172 break;
1173 case MODFlags.shared_ | MODFlags.wild:
1174 buf.writestring("ONg");
1175 break;
1176 case MODFlags.shared_ | MODFlags.wildconst:
1177 buf.writestring("ONgx");
1178 break;
1179 default:
1180 assert(0);
1181 }
1182 }
1183
1184
1185 /**
1186 * writes a back reference with the relative position encoded with base 26
1187 * using upper case letters for all digits but the last digit which uses
1188 * a lower case letter.
1189 * The decoder has to look up the referenced position to determine
1190 * whether the back reference is an identifier (starts with a digit)
1191 * or a type (starts with a letter).
1192 *
1193 * Params:
1194 * buf = buffer to write to
1195 * pos = relative position to encode
1196 */
1197 private
1198 void writeBackRef(ref OutBuffer buf, size_t pos) @safe
1199 {
1200 buf.writeByte('Q');
1201 enum base = 26;
1202 size_t mul = 1;
1203 while (pos >= mul * base)
1204 mul *= base;
1205 while (mul >= base)
1206 {
1207 auto dig = cast(ubyte)(pos / mul);
1208 buf.writeByte('A' + dig);
1209 pos -= dig * mul;
1210 mul /= base;
1211 }
1212 buf.writeByte('a' + cast(ubyte)pos);
1213 }
1214
1215
1216 /************************************************************
1217 * Write length prefixed string to buf.
1218 */
1219 private
1220 extern (D) void toBuffer(ref OutBuffer buf, const(char)[] id, Dsymbol s)
1221 {
1222 const len = id.length;
1223 if (buf.length + len >= 8 * 1024 * 1024) // 8 megs ought be enough for anyone
1224 error(s.loc, "%s `%s` excessive length %llu for symbol, possible recursive expansion?", s.kind, s.toPrettyChars, cast(ulong)(buf.length + len));
1225 else
1226 {
1227 buf.print(len);
1228 buf.writestring(id);
1229 }
1230 }
1231
1232
1233 /*****
1234 * There can be multiple different declarations in the same
1235 * function that have the same mangled name.
1236 * This results in localNum having a non-zero number, which
1237 * is used to add a fake parent of the form `__Sddd` to make
1238 * the mangled names unique.
1239 * https://issues.dlang.org/show_bug.cgi?id=20565
1240 * Params:
1241 * buf = buffer to write to
1242 * localNum = local symbol number
1243 */
1244 private
1245 void writeLocalParent(ref OutBuffer buf, uint localNum)
1246 {
1247 uint ndigits = 1;
1248 auto n = localNum;
1249 while (n >= 10)
1250 {
1251 n /= 10;
1252 ++ndigits;
1253 }
1254 buf.printf("%u__S%u", ndigits + 3, localNum);
1255 }
1256
1257 /*************************
1258 * Write real to buffer.
1259 * Params:
1260 * buf = buffer to write to
1261 * value = real to write
1262 */
1263 private
1264 void realToMangleBuffer(ref OutBuffer buf, real_t value)
1265 {
1266 /* Rely on %A to get portable mangling.
1267 * Must munge result to get only identifier characters.
1268 *
1269 * Possible values from %A => mangled result
1270 * NAN => NAN
1271 * -INF => NINF
1272 * INF => INF
1273 * -0X1.1BC18BA997B95P+79 => N11BC18BA997B95P79
1274 * 0X1.9P+2 => 19P2
1275 */
1276 if (CTFloat.isNaN(value))
1277 {
1278 buf.writestring("NAN"); // no -NAN bugs
1279 return;
1280 }
1281
1282 if (value < CTFloat.zero)
1283 {
1284 buf.writeByte('N');
1285 value = -value;
1286 }
1287
1288 if (CTFloat.isInfinity(value))
1289 {
1290 buf.writestring("INF");
1291 return;
1292 }
1293
1294 char[36] buffer = void;
1295 // 'A' format yields [-]0xh.hhhhp+-d
1296 const n = CTFloat.sprint(buffer.ptr, buffer.length, 'A', value);
1297 assert(n < buffer.length);
1298 foreach (const c; buffer[2 .. n])
1299 {
1300 switch (c)
1301 {
1302 case '-':
1303 buf.writeByte('N');
1304 break;
1305
1306 case '+':
1307 case '.':
1308 break;
1309
1310 default:
1311 buf.writeByte(c);
1312 break;
1313 }
1314 }
1315 }
1316
1317 /************************************************************
1318 * Try to obtain an externally mangled identifier from a declaration.
1319 * If the declaration is at global scope or mixed in at global scope,
1320 * the user might want to call it externally, so an externally mangled
1321 * name is returned. Member functions or nested functions can't be called
1322 * externally in C, so in that case null is returned. C++ does support
1323 * namespaces, so extern(C++) always gives a C++ mangled name.
1324 *
1325 * See also: https://issues.dlang.org/show_bug.cgi?id=20012
1326 *
1327 * Params:
1328 * d = declaration to mangle
1329 *
1330 * Returns:
1331 * an externally mangled name or null if the declaration cannot be called externally
1332 */
1333 private
1334 extern (D) const(char)[] externallyMangledIdentifier(Declaration d)
1335 {
1336 assert(!d.mangleOverride, "mangle overrides should have been handled earlier");
1337
1338 const linkage = d.resolvedLinkage();
1339 const par = d.toParent(); //toParent() skips over mixin templates
1340 if (!par || par.isModule() || linkage == LINK.cpp ||
1341 (linkage == LINK.c && d.isCsymbol() &&
1342 (d.isFuncDeclaration() ||
1343 (d.isVarDeclaration() && d.isDataseg() && d.storage_class & STC.extern_))))
1344 {
1345 if (linkage != LINK.d && d.localNum)
1346 error(d.loc, "%s `%s` the same declaration cannot be in multiple scopes with non-D linkage", d.kind, d.toPrettyChars);
1347
1348 final switch (linkage)
1349 {
1350 case LINK.d:
1351 break;
1352 case LINK.c:
1353 case LINK.windows:
1354 case LINK.objc:
1355 return d.ident.toString();
1356 case LINK.cpp:
1357 {
1358 const p = target.cpp.toMangle(d);
1359 return p.toDString();
1360 }
1361 case LINK.default_:
1362 error(d.loc, "%s `%s` forward declaration", d.kind, d.toPrettyChars);
1363 return d.ident.toString();
1364 case LINK.system:
1365 assert(0);
1366 }
1367 }
1368 return null;
1369 }