2 * Does name mangling for `extern(D)` symbols.
4 * Specification: $(LINK2 https://dlang.org/spec/abi.html#name_mangling, Name Mangling)
6 * Copyright: Copyright (C) 1999-2022 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/src/dmd/dmangle.d, _dmangle.d)
10 * Documentation: https://dlang.org/phobos/dmd_dmangle.html
11 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/dmangle.d
12 * References: https://dlang.org/blog/2017/12/20/ds-newfangled-name-mangling/
19 /******************************************************************************
20 * Returns exact mangled name of function.
22 extern (C++) const(char)* mangleExact(FuncDeclaration fd)
27 scope Mangler v = new Mangler(&buf);
29 fd.mangleString = buf.extractChars();
31 return fd.mangleString;
34 extern (C++) void mangleToBuffer(Type t, OutBuffer* buf)
37 buf.writestring(t.deco);
40 scope Mangler v = new Mangler(buf, t);
41 v.visitWithMask(t, 0);
45 extern (C++) void mangleToBuffer(Expression e, OutBuffer* buf)
47 scope Mangler v = new Mangler(buf);
51 extern (C++) void mangleToBuffer(Dsymbol s, OutBuffer* buf)
53 scope Mangler v = new Mangler(buf);
57 extern (C++) void mangleToBuffer(TemplateInstance ti, OutBuffer* buf)
59 scope Mangler v = new Mangler(buf);
60 v.mangleTemplateInstance(ti);
63 /// Returns: `true` if the given character is a valid mangled character
64 package bool isValidMangling(dchar c) nothrow
67 c >= 'A' && c <= 'Z' ||
68 c >= 'a' && c <= 'z' ||
69 c >= '0' && c <= '9' ||
70 c != 0 && strchr("$%().:?@[]_", c) ||
74 // valid mangled characters
77 assert('a'.isValidMangling);
78 assert('B'.isValidMangling);
79 assert('2'.isValidMangling);
80 assert('@'.isValidMangling);
81 assert('_'.isValidMangling);
84 // invalid mangled characters
87 assert(!'-'.isValidMangling);
88 assert(!0.isValidMangling);
89 assert(!'/'.isValidMangling);
90 assert(!'\\'.isValidMangling);
93 /**********************************************
94 * Convert a string representing a type (the deco) and
95 * return its equivalent Type.
97 * deco = string containing the deco
99 * null for failed to convert
103 public Type decoToType(const(char)[] deco)
105 //printf("decoToType(): %.*s\n", cast(int)deco.length, deco.ptr);
106 if (auto sv = Type.stringtable.lookup(deco))
110 Type t = cast(Type)sv.value;
119 /***************************************** private ***************************************/
124 import core.stdc.ctype;
125 import core.stdc.stdio;
126 import core.stdc.string;
128 import dmd.aggregate;
129 import dmd.arraytypes;
131 import dmd.declaration;
134 import dmd.dtemplate;
135 import dmd.expression;
139 import dmd.identifier;
141 import dmd.root.ctfloat;
142 import dmd.common.outbuffer;
144 import dmd.root.string;
145 import dmd.root.stringtable;
151 private immutable char[TMAX] mangleChar =
186 Tfunction : 'F', // D function
193 // M // has this, or scope
194 // N // Nh:vector Ng:wild Nn:noreturn
197 // Q // Type/symbol/identifier backward reference
202 // W // Windows function
203 // X // variadic T t...)
204 // Y // variadic T t,...)
205 // Z // not variadic, end of parameters
207 // '@' shouldn't appear anywhere in the deco'd names
219 Tnoreturn : '@', // becomes 'Nn'
224 foreach (i, mangle; mangleChar)
226 if (mangle == char.init)
228 fprintf(stderr, "ty = %u\n", cast(uint)i);
234 private extern (C++) final class Mangler : Visitor
236 alias visit = Visitor.visit;
238 static assert(Key.sizeof == size_t.sizeof);
243 extern (D) this(OutBuffer* buf, Type rootType = null)
246 this.backref = Backref(rootType);
249 void mangleSymbol(Dsymbol s)
254 void mangleType(Type t)
256 if (!backref.addRefToType(buf, t))
260 void mangleIdentifier(Identifier id, Dsymbol s)
262 if (!backref.addRefToIdentifier(buf, id))
263 toBuffer(buf, id.toString(), s);
266 ////////////////////////////////////////////////////////////////////////////
267 /**************************************************
270 void visitWithMask(Type t, ubyte modMask)
272 if (modMask != t.mod)
274 MODtoDecoBuffer(buf, t.mod);
279 override void visit(Type t)
281 tyToDecoBuffer(buf, t.ty);
284 override void visit(TypeNext t)
287 visitWithMask(t.next, t.mod);
290 override void visit(TypeVector t)
292 buf.writestring("Nh");
293 visitWithMask(t.basetype, t.mod);
296 override void visit(TypeSArray t)
300 buf.print(t.dim.toInteger());
302 visitWithMask(t.next, t.mod);
305 override void visit(TypeDArray t)
309 visitWithMask(t.next, t.mod);
312 override void visit(TypeAArray t)
315 visitWithMask(t.index, 0);
316 visitWithMask(t.next, t.mod);
319 override void visit(TypeFunction t)
321 //printf("TypeFunction.toDecoBuffer() t = %p %s\n", t, t.toChars());
322 //static int nest; if (++nest == 50) *(char*)0=0;
323 mangleFuncType(t, t, t.mod, t.next);
326 void mangleFuncType(TypeFunction t, TypeFunction ta, ubyte modMask, Type tret)
328 //printf("mangleFuncType() %s\n", t.toChars());
331 // printf("TypeFunction.mangleFuncType() t = %s inuse\n", t.toChars());
332 t.inuse = 2; // flag error to caller
336 if (modMask != t.mod)
337 MODtoDecoBuffer(buf, t.mod);
340 final switch (t.linkage)
364 buf.writestring("Na");
366 buf.writestring("Nb");
368 buf.writestring("Nc");
370 buf.writestring("Nd");
372 buf.writestring("Ni");
374 // `return scope` must be in that order
375 if (ta.isreturnscope && !ta.isreturninferred)
377 buf.writestring("NjNl");
381 // when return ref, the order is `scope return`
382 if (ta.isScopeQual && !ta.isscopeinferred)
383 buf.writestring("Nl");
385 if (ta.isreturn && !ta.isreturninferred)
386 buf.writestring("Nj");
390 buf.writestring("Nm");
395 buf.writestring("Ne");
398 buf.writestring("Nf");
404 // Write argument types
405 foreach (idx, param; t.parameterList)
406 mangleParameter(param);
407 //if (buf.data[buf.length - 1] == '@') assert(0);
408 buf.writeByte('Z' - t.parameterList.varargs); // mark end of arg list
410 visitWithMask(tret, 0);
414 override void visit(TypeIdentifier t)
417 auto name = t.ident.toString();
418 buf.print(cast(int)name.length);
419 buf.writestring(name);
422 override void visit(TypeEnum t)
428 override void visit(TypeStruct t)
430 //printf("TypeStruct.toDecoBuffer('%s') = '%s'\n", t.toChars(), name);
435 override void visit(TypeClass t)
437 //printf("TypeClass.toDecoBuffer('%s' mod=%x) = '%s'\n", t.toChars(), mod, name);
442 override void visit(TypeTuple t)
444 //printf("TypeTuple.toDecoBuffer() t = %p, %s\n", t, t.toChars());
446 Parameter._foreach(t.arguments, (idx, param) {
447 mangleParameter(param);
453 override void visit(TypeNull t)
458 override void visit(TypeNoreturn t)
460 buf.writestring("Nn");
463 ////////////////////////////////////////////////////////////////////////////
464 void mangleDecl(Declaration sthis)
468 mangleIdentifier(sthis.ident, sthis);
469 if (FuncDeclaration fd = sthis.isFuncDeclaration())
471 mangleFunc(fd, false);
475 visitWithMask(sthis.type, 0);
481 void mangleParent(Dsymbol s)
483 //printf("mangleParent() %s %s\n", s.kind(), s.toChars());
485 if (TemplateInstance ti = s.isTemplateInstance())
486 p = ti.isTemplateMixin() ? ti.parent : ti.tempdecl.parent;
491 uint localNum = s.localNum;
493 auto ti = p.isTemplateInstance();
494 if (ti && !ti.isTemplateMixin())
496 localNum = ti.tempdecl.localNum;
497 mangleTemplateInstance(ti);
499 else if (p.getIdent())
501 mangleIdentifier(p.ident, s);
502 if (FuncDeclaration f = p.isFuncDeclaration())
509 writeLocalParent(buf, localNum);
513 void mangleFunc(FuncDeclaration fd, bool inParent)
515 //printf("deco = '%s'\n", fd.type.deco ? fd.type.deco : "null");
516 //printf("fd.type = %s\n", fd.type.toChars());
517 if (fd.needThis() || fd.isNested())
520 if (!fd.type || fd.type.ty == Terror)
522 // never should have gotten here, but could be the result of
523 // failed speculative compilation
524 buf.writestring("9__error__FZ");
526 //printf("[%s] %s no type\n", fd.loc.toChars(), fd.toChars());
527 //assert(0); // don't mangle function until semantic3 done.
531 TypeFunction tf = fd.type.isTypeFunction();
532 TypeFunction tfo = fd.originalType.isTypeFunction();
533 mangleFuncType(tf, tfo, 0, null);
537 visitWithMask(fd.type, 0);
541 override void visit(Declaration d)
543 //printf("Declaration.mangle(this = %p, '%s', parent = '%s', linkage = %d)\n",
544 // d, d.toChars(), d.parent ? d.parent.toChars() : "null", d.linkage);
545 if (const id = externallyMangledIdentifier(d))
550 buf.writestring("_D");
554 const slice = (*buf)[];
555 assert(slice.length);
556 for (size_t pos; pos < slice.length; )
560 const s = utf_decodeChar(slice, pos, c);
561 assert(s is null, s);
562 assert(c.isValidMangling, "The mangled name '" ~ slice ~ "' " ~
563 "contains an invalid character: " ~ slice[ppos..pos]);
568 /******************************************************************************
569 * Normally FuncDeclaration and FuncAliasDeclaration have overloads.
570 * If and only if there is no overloads, mangle() could return
571 * exact mangled name.
574 * void foo(long) {} // _D4test3fooFlZv
575 * void foo(string) {} // _D4test3fooFAyaZv
577 * // from FuncDeclaration.mangle().
578 * pragma(msg, foo.mangleof); // prints unexact mangled name "4test3foo"
579 * // by calling Dsymbol.mangle()
581 * // from FuncAliasDeclaration.mangle()
582 * pragma(msg, __traits(getOverloads, test, "foo")[0].mangleof); // "_D4test3fooFlZv"
583 * pragma(msg, __traits(getOverloads, test, "foo")[1].mangleof); // "_D4test3fooFAyaZv"
585 * If a function has no overloads, .mangleof property still returns exact mangled name.
588 * pragma(msg, bar.mangleof); // still prints "_D4test3barFZv"
589 * // by calling FuncDeclaration.mangleExact().
591 override void visit(FuncDeclaration fd)
596 visit(cast(Dsymbol)fd);
600 override void visit(FuncAliasDeclaration fd)
602 FuncDeclaration f = fd.toAliasFunc();
603 FuncAliasDeclaration fa = f.isFuncAliasDeclaration();
604 if (!fd.hasOverloads && !fa)
614 visit(cast(Dsymbol)fd);
617 override void visit(OverDeclaration od)
621 visit(cast(Dsymbol)od);
624 if (FuncDeclaration fd = od.aliassym.isFuncDeclaration())
632 if (TemplateDeclaration td = od.aliassym.isTemplateDeclaration())
634 if (td.overnext is null)
640 visit(cast(Dsymbol)od);
643 void mangleExact(FuncDeclaration fd)
645 assert(!fd.isFuncAliasDeclaration());
646 if (fd.mangleOverride)
648 buf.writestring(fd.mangleOverride);
653 buf.writestring("_Dmain");
656 if (fd.isWinMain() || fd.isDllMain())
658 buf.writestring(fd.ident.toString());
661 visit(cast(Declaration)fd);
664 override void visit(VarDeclaration vd)
666 if (vd.mangleOverride)
668 buf.writestring(vd.mangleOverride);
671 visit(cast(Declaration)vd);
674 override void visit(AggregateDeclaration ad)
676 ClassDeclaration cd = ad.isClassDeclaration();
677 Dsymbol parentsave = ad.parent;
680 /* These are reserved to the compiler, so keep simple
683 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)
685 // Don't mangle parent
689 visit(cast(Dsymbol)ad);
690 ad.parent = parentsave;
693 override void visit(TemplateInstance ti)
697 printf("TemplateInstance.mangle() %p %s", ti, ti.toChars());
699 printf(" parent = %s %s", ti.parent.kind(), ti.parent.toChars());
703 ti.error("is not defined");
707 if (ti.isTemplateMixin() && ti.ident)
708 mangleIdentifier(ti.ident, ti);
710 mangleTemplateInstance(ti);
713 void mangleTemplateInstance(TemplateInstance ti)
715 TemplateDeclaration tempdecl = ti.tempdecl.isTemplateDeclaration();
718 // Use "__U" for the symbols declared inside template constraint.
719 const char T = ti.members ? 'T' : 'U';
720 buf.printf("__%c", T);
721 mangleIdentifier(tempdecl.ident, tempdecl);
723 auto args = ti.tiargs;
724 size_t nparams = tempdecl.parameters.dim - (tempdecl.isVariadic() ? 1 : 0);
725 for (size_t i = 0; i < args.dim; i++)
729 Expression ea = isExpression(o);
730 Dsymbol sa = isDsymbol(o);
731 Tuple va = isTuple(o);
732 //printf("\to [%d] %p ta %p ea %p sa %p va %p\n", i, o, ta, ea, sa, va);
733 if (i < nparams && (*tempdecl.parameters)[i].specialization())
734 buf.writeByte('H'); // https://issues.dlang.org/show_bug.cgi?id=6574
738 visitWithMask(ta, 0);
742 // Don't interpret it yet, it might actually be an alias template parameter.
743 // Only constfold manifest constants, not const/immutable lvalues, see https://issues.dlang.org/show_bug.cgi?id=17339.
744 enum keepLvalue = true;
745 ea = ea.optimize(WANTvalue, keepLvalue);
746 if (auto ev = ea.isVarExp())
752 if (auto et = ea.isThisExp())
758 if (auto ef = ea.isFuncExp())
768 if (ea.op == EXP.tuple)
770 ea.error("tuple is not a valid template value argument");
773 // Now that we know it is not an alias, we MUST obtain a value
774 uint olderr = global.errors;
775 ea = ea.ctfeInterpret();
776 if (ea.op == EXP.error || olderr != global.errors)
779 /* Use type mangling that matches what it would be for a function parameter
781 visitWithMask(ea.type, 0);
788 if (sa.isDeclaration() && !sa.isOverDeclaration())
790 Declaration d = sa.isDeclaration();
792 if (auto fad = d.isFuncAliasDeclaration())
793 d = fad.toAliasFunc();
794 if (d.mangleOverride)
797 toBuffer(buf, d.mangleOverride, d);
800 if (const id = externallyMangledIdentifier(d))
803 toBuffer(buf, id, d);
806 if (!d.type || !d.type.deco)
808 ti.error("forward reference of %s `%s`", d.kind(), d.toChars());
817 assert(i + 1 == args.dim); // must be last one
827 override void visit(Dsymbol s)
831 printf("Dsymbol.mangle() '%s'", s.toChars());
833 printf(" parent = %s %s", s.parent.kind(), s.parent.toChars());
836 if (s.parent && s.ident)
838 if (auto m = s.parent.isModule())
840 if (m.filetype == FileType.c)
842 /* C types at global level get mangled into the __C global namespace
843 * to get the same mangling regardless of which module it
844 * is declared in. This works because types are the same if the mangling
847 mangleIdentifier(Id.ImportC, s); // parent
848 mangleIdentifier(s.ident, s);
855 mangleIdentifier(s.ident, s);
857 toBuffer(buf, s.toString(), s);
858 //printf("Dsymbol.mangle() %s = %s\n", s.toChars(), id);
861 ////////////////////////////////////////////////////////////////////////////
862 override void visit(Expression e)
864 e.error("expression `%s` is not a valid template value argument", e.toChars());
867 override void visit(IntegerExp e)
869 const v = e.toInteger();
870 if (cast(sinteger_t)v < 0)
882 override void visit(RealExp e)
885 realToMangleBuffer(buf, e.value);
888 override void visit(ComplexExp e)
891 realToMangleBuffer(buf, e.toReal());
892 buf.writeByte('c'); // separate the two
893 realToMangleBuffer(buf, e.toImaginary());
896 override void visit(NullExp e)
901 override void visit(StringExp e)
906 /* Write string in UTF-8 format
917 const slice = e.peekWstring();
918 for (size_t u = 0; u < e.len;)
921 if (const s = utf_decodeWchar(slice, u, c))
922 e.error("%.*s", cast(int)s.length, s.ptr);
932 const slice = e.peekDstring();
935 if (!utf_isValidDchar(c))
936 e.error("invalid UCS-32 char \\U%08x", c);
947 buf.reserve(1 + 11 + 2 * q.length);
950 buf.writeByte('_'); // nbytes <= 11
951 auto slice = buf.allocate(2 * q.length);
954 char hi = (c >> 4) & 0xF;
955 slice[i * 2] = cast(char)(hi < 10 ? hi + '0' : hi - 10 + 'a');
957 slice[i * 2 + 1] = cast(char)(lo < 10 ? lo + '0' : lo - 10 + 'a');
961 override void visit(ArrayLiteralExp e)
963 const dim = e.elements ? e.elements.dim : 0;
966 foreach (i; 0 .. dim)
972 override void visit(AssocArrayLiteralExp e)
974 const dim = e.keys.dim;
977 foreach (i; 0 .. dim)
979 (*e.keys)[i].accept(this);
980 (*e.values)[i].accept(this);
984 override void visit(StructLiteralExp e)
986 const dim = e.elements ? e.elements.dim : 0;
989 foreach (i; 0 .. dim)
991 Expression ex = (*e.elements)[i];
995 buf.writeByte('v'); // 'v' for void
999 override void visit(FuncExp e)
1008 ////////////////////////////////////////////////////////////////////////////
1010 void mangleParameter(Parameter p)
1012 // https://dlang.org/spec/abi.html#Parameter
1014 auto stc = p.storageClass;
1016 // Inferred storage classes don't get mangled in
1017 if (stc & STC.scopeinferred)
1018 stc &= ~(STC.scope_ | STC.scopeinferred);
1019 if (stc & STC.returninferred)
1020 stc &= ~(STC.return_ | STC.returninferred);
1022 // much like hdrgen.stcToBuffer()
1024 const isout = (stc & STC.out_) != 0;
1025 final switch (buildScopeRef(stc))
1028 case ScopeRef.Scope:
1030 case ScopeRef.Return:
1031 case ScopeRef.RefScope:
1034 case ScopeRef.ReturnScope: rrs = "NkM"; goto L1; // return scope
1035 case ScopeRef.ReturnRef: rrs = isout ? "NkJ" : "NkK"; goto L1; // return ref
1036 case ScopeRef.ReturnRef_Scope: rrs = isout ? "MNkJ" : "MNkK"; goto L1; // scope return ref
1037 case ScopeRef.Ref_ReturnScope: rrs = isout ? "NkMJ" : "NkMK"; goto L1; // return scope ref
1039 buf.writestring(rrs);
1040 stc &= ~(STC.out_ | STC.scope_ | STC.ref_ | STC.return_);
1044 if (stc & STC.scope_)
1045 buf.writeByte('M'); // scope
1047 if (stc & STC.return_)
1048 buf.writestring("Nk"); // return
1050 switch (stc & (STC.IOR | STC.lazy_))
1057 case STC.in_ | STC.ref_:
1058 buf.writestring("IK");
1072 printf("storageClass = x%llx\n", stc & (STC.IOR | STC.lazy_));
1076 visitWithMask(p.type, (stc & STC.in_) ? MODFlags.const_ : 0);
1080 /***************************************
1081 * Manage back reference mangling
1083 private struct Backref
1086 * Back references a non-basic type
1088 * The encoded mangling is
1089 * 'Q' <relative position of first occurrence of type>
1092 * t = the type to encode via back referencing
1095 * true if the type was found. A back reference has been encoded.
1096 * false if the type was not found. The current position is saved for later back references.
1098 bool addRefToType(OutBuffer* buf, Type t)
1100 if (t.isTypeBasic())
1104 * https://issues.dlang.org/show_bug.cgi?id=21591
1106 * Special case for unmerged TypeFunctions: use the generic merged
1107 * function type as backref cache key to avoid missed backrefs.
1109 * Merging is based on mangling, so we need to avoid an infinite
1110 * recursion by excluding the case where `t` is the root type passed to
1111 * `mangleToBuffer()`.
1115 if (t.isFunction_Delegate_PtrToFunction())
1121 return backrefImpl(buf, types, t);
1125 * Back references a single identifier
1127 * The encoded mangling is
1128 * 'Q' <relative position of first occurrence of type>
1131 * id = the identifier to encode via back referencing
1134 * true if the identifier was found. A back reference has been encoded.
1135 * false if the identifier was not found. The current position is saved for later back references.
1137 bool addRefToIdentifier(OutBuffer* buf, Identifier id)
1139 return backrefImpl(buf, idents, id);
1144 extern(D) bool backrefImpl(T)(OutBuffer* buf, ref AssocArray!(T, size_t) aa, T key)
1146 auto p = aa.getLvalue(key);
1149 const offset = *p - 1;
1150 writeBackRef(buf, buf.length - offset);
1153 *p = buf.length + 1;
1157 Type rootType; /// avoid infinite recursion
1158 AssocArray!(Type, size_t) types; /// Type => (offset+1) in buf
1159 AssocArray!(Identifier, size_t) idents; /// Identifier => (offset+1) in buf
1163 /***********************
1164 * Mangle basic type ty to buf.
1167 private void tyToDecoBuffer(OutBuffer* buf, int ty)
1169 const c = mangleChar[ty];
1172 buf.writeByte(ty == Tint128 ? 'i' : 'k');
1175 /*********************************
1178 private void MODtoDecoBuffer(OutBuffer* buf, MOD mod)
1184 case MODFlags.const_:
1187 case MODFlags.immutable_:
1190 case MODFlags.shared_:
1193 case MODFlags.shared_ | MODFlags.const_:
1194 buf.writestring("Ox");
1197 buf.writestring("Ng");
1199 case MODFlags.wildconst:
1200 buf.writestring("Ngx");
1202 case MODFlags.shared_ | MODFlags.wild:
1203 buf.writestring("ONg");
1205 case MODFlags.shared_ | MODFlags.wildconst:
1206 buf.writestring("ONgx");
1215 * writes a back reference with the relative position encoded with base 26
1216 * using upper case letters for all digits but the last digit which uses
1217 * a lower case letter.
1218 * The decoder has to look up the referenced position to determine
1219 * whether the back reference is an identifier (starts with a digit)
1220 * or a type (starts with a letter).
1223 * buf = buffer to write to
1224 * pos = relative position to encode
1227 void writeBackRef(OutBuffer* buf, size_t pos)
1232 while (pos >= mul * base)
1236 auto dig = cast(ubyte)(pos / mul);
1237 buf.writeByte('A' + dig);
1241 buf.writeByte('a' + cast(ubyte)pos);
1245 /************************************************************
1246 * Write length prefixed string to buf.
1249 extern (D) void toBuffer(OutBuffer* buf, const(char)[] id, Dsymbol s)
1251 const len = id.length;
1252 if (buf.length + len >= 8 * 1024 * 1024) // 8 megs ought be enough for anyone
1253 s.error("excessive length %llu for symbol, possible recursive expansion?", cast(ulong)(buf.length + len));
1257 buf.writestring(id);
1263 * There can be multiple different declarations in the same
1264 * function that have the same mangled name.
1265 * This results in localNum having a non-zero number, which
1266 * is used to add a fake parent of the form `__Sddd` to make
1267 * the mangled names unique.
1268 * https://issues.dlang.org/show_bug.cgi?id=20565
1270 * buf = buffer to write to
1271 * localNum = local symbol number
1274 void writeLocalParent(OutBuffer* buf, uint localNum)
1283 buf.printf("%u__S%u", ndigits + 3, localNum);
1286 /*************************
1287 * Write real to buffer.
1289 * buf = buffer to write to
1290 * value = real to write
1293 void realToMangleBuffer(OutBuffer* buf, real_t value)
1295 /* Rely on %A to get portable mangling.
1296 * Must munge result to get only identifier characters.
1298 * Possible values from %A => mangled result
1302 * -0X1.1BC18BA997B95P+79 => N11BC18BA997B95P79
1305 if (CTFloat.isNaN(value))
1307 buf.writestring("NAN"); // no -NAN bugs
1311 if (value < CTFloat.zero)
1317 if (CTFloat.isInfinity(value))
1319 buf.writestring("INF");
1323 char[36] buffer = void;
1324 // 'A' format yields [-]0xh.hhhhp+-d
1325 const n = CTFloat.sprint(buffer.ptr, 'A', value);
1326 assert(n < buffer.length);
1327 foreach (const c; buffer[2 .. n])
1346 /************************************************************
1347 * Try to obtain an externally mangled identifier from a declaration.
1348 * If the declaration is at global scope or mixed in at global scope,
1349 * the user might want to call it externally, so an externally mangled
1350 * name is returned. Member functions or nested functions can't be called
1351 * externally in C, so in that case null is returned. C++ does support
1352 * namespaces, so extern(C++) always gives a C++ mangled name.
1354 * See also: https://issues.dlang.org/show_bug.cgi?id=20012
1357 * d = declaration to mangle
1360 * an externally mangled name or null if the declaration cannot be called externally
1363 extern (D) const(char)[] externallyMangledIdentifier(Declaration d)
1365 assert(!d.mangleOverride, "mangle overrides should have been handled earlier");
1367 const linkage = d.resolvedLinkage();
1368 const par = d.toParent(); //toParent() skips over mixin templates
1369 if (!par || par.isModule() || linkage == LINK.cpp ||
1370 (linkage == LINK.c && d.isCsymbol() &&
1371 (d.isFuncDeclaration() ||
1372 (d.isVarDeclaration() && d.isDataseg() && d.storage_class & STC.extern_))))
1374 if (linkage != LINK.d && d.localNum)
1375 d.error("the same declaration cannot be in multiple scopes with non-D linkage");
1377 final switch (linkage)
1384 return d.ident.toString();
1387 const p = target.cpp.toMangle(d);
1388 return p.toDString();
1391 d.error("forward declaration");
1392 return d.ident.toString();