/
cppmangle.d
2629 lines (2421 loc) · 82.1 KB
/
cppmangle.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Do mangling for C++ linkage.
*
* This is the POSIX side of the implementation.
* It exports two functions to C++, `toCppMangleItanium` and `cppTypeInfoMangleItanium`.
*
* Copyright: Copyright (C) 1999-2024 by The D Language Foundation, All Rights Reserved
* Authors: Walter Bright, https://www.digitalmars.com
* License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/cppmangle.d, _cppmangle.d)
* Documentation: https://dlang.org/phobos/dmd_cppmangle.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/cppmangle.d
*
* References:
* Follows Itanium C++ ABI 1.86 section 5.1
* http://refspecs.linux-foundation.org/cxxabi-1.86.html#mangling
* which is where the grammar comments come from.
*
* Bugs:
* https://issues.dlang.org/query.cgi
* enter `C++, mangling` as the keywords.
*/
module dmd.cppmangle;
import core.stdc.stdio;
import dmd.arraytypes;
import dmd.astenums;
import dmd.attrib;
import dmd.declaration;
import dmd.dsymbol;
import dmd.dtemplate;
import dmd.errors;
import dmd.expression;
import dmd.func;
import dmd.globals;
import dmd.id;
import dmd.identifier;
import dmd.location;
import dmd.mtype;
import dmd.nspace;
import dmd.root.array;
import dmd.common.outbuffer;
import dmd.rootobject;
import dmd.root.string;
import dmd.target;
import dmd.typesem;
import dmd.visitor;
// C++ operators
enum CppOperator { Unknown, Cast, Assign, Eq, Index, Call, Unary, Binary, OpAssign }
/**************
* Check if id is a C++ operator
* Params:
* id = identifier to be checked
* Returns:
* CppOperator, or Unknown if not a C++ operator
*/
package CppOperator isCppOperator(const scope Identifier id)
{
with (Id) with (CppOperator)
{
return (id == _cast) ? Cast :
(id == assign) ? Assign :
(id == eq) ? Eq :
(id == index) ? Index :
(id == call) ? Call :
(id == opUnary) ? Unary :
(id == opBinary) ? Binary :
(id == opOpAssign) ? OpAssign :
Unknown ;
}
}
///
const(char)* toCppMangleItanium(Dsymbol s)
{
//printf("toCppMangleItanium(%s)\n", s.toChars());
OutBuffer buf;
scope CppMangleVisitor v = new CppMangleVisitor(&buf, s.loc);
v.mangleOf(s);
if (v.errors)
fatal();
return buf.extractChars();
}
///
const(char)* cppTypeInfoMangleItanium(Dsymbol s)
{
//printf("cppTypeInfoMangle(%s)\n", s.toChars());
OutBuffer buf;
buf.writestring("_ZTI"); // "TI" means typeinfo structure
scope CppMangleVisitor v = new CppMangleVisitor(&buf, s.loc);
v.cpp_mangle_name(s, false);
if (v.errors)
fatal();
return buf.extractChars();
}
///
const(char)* cppThunkMangleItanium(FuncDeclaration fd, int offset)
{
//printf("cppThunkMangleItanium(%s)\n", fd.toChars());
OutBuffer buf;
buf.printf("_ZThn%u_", offset); // "Th" means thunk, "n%u" is the call offset
scope CppMangleVisitor v = new CppMangleVisitor(&buf, fd.loc);
v.mangle_function_encoding(fd);
if (v.errors)
fatal();
return buf.extractChars();
}
/******************************
* Determine if sym is a full aggregate destructor.
* Params:
* sym = Dsymbol
* Returns:
* true if sym is an aggregate destructor
*/
bool isAggregateDtor(const Dsymbol sym)
{
const dtor = sym.isDtorDeclaration();
if (!dtor)
return false;
const ad = dtor.isMember();
assert(ad);
return dtor == ad.aggrDtor;
}
/// Context used when processing pre-semantic AST
private struct Context
{
/// Template instance of the function being mangled
TemplateInstance ti;
/// Function declaration we're mangling
FuncDeclaration fd;
/// Current type / expression being processed (semantically analyzed)
RootObject res;
@disable ref Context opAssign(ref Context other);
@disable ref Context opAssign(Context other);
/**
* Helper function to track `res`
*
* Params:
* next = Value to set `this.res` to.
* If `this.res` is `null`, the expression is not evalutated.
* This allow this code to be used even when no context is needed.
*
* Returns:
* The previous state of this `Context` object
*/
private Context push(lazy RootObject next) @safe
{
auto r = this.res;
if (r !is null)
this.res = next;
return Context(this.ti, this.fd, r);
}
/**
* Reset the context to a previous one, making any adjustment necessary
*/
private void pop(ref Context prev) @safe
{
this.res = prev.res;
}
}
private final class CppMangleVisitor : Visitor
{
/// Context used when processing pre-semantic AST
private Context context;
ABITagContainer abiTags; /// Container for already-written ABI tags
Objects components; /// array of components available for substitution
OutBuffer* buf; /// append the mangling to buf[]
Loc loc; /// location for use in error messages
bool errors; /// failed to mangle properly
/**
* Constructor
*
* Params:
* buf = `OutBuffer` to write the mangling to
* loc = `Loc` of the symbol being mangled
*/
this(OutBuffer* buf, Loc loc) scope
{
this.buf = buf;
this.loc = loc;
}
/*****
* Entry point. Append mangling to buf[]
* Params:
* s = symbol to mangle
*/
void mangleOf(Dsymbol s)
{
if (VarDeclaration vd = s.isVarDeclaration())
{
mangle_variable(vd, vd.cppnamespace !is null);
}
else if (FuncDeclaration fd = s.isFuncDeclaration())
{
mangle_function(fd);
}
else
{
assert(0);
}
}
/**
* Mangle the return type of a function
*
* This is called on a templated function type.
* Context is set to the `FuncDeclaration`.
*
* Params:
* preSemantic = the `FuncDeclaration`'s `originalType`
*/
void mangleReturnType(TypeFunction preSemantic)
{
auto tf = this.context.res.asFuncDecl().type.isTypeFunction();
Type rt = preSemantic.nextOf();
// https://issues.dlang.org/show_bug.cgi?id=22739
// auto return type means that rt is null.
// if so, just pick up the type from the instance
if (!rt)
rt = tf.nextOf();
if (tf.isref)
rt = rt.referenceTo();
auto prev = this.context.push(tf.nextOf());
scope (exit) this.context.pop(prev);
this.headOfType(rt);
}
/**
* Write a seq-id from an index number, excluding the terminating '_'
*
* Params:
* idx = the index in a substitution list.
* Note that index 0 has no value, and `S0_` would be the
* substitution at index 1 in the list.
*
* See-Also:
* https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.seq-id
*/
private void writeSequenceFromIndex(size_t idx) @safe
{
if (idx)
{
void write_seq_id(size_t i)
{
if (i >= 36)
{
write_seq_id(i / 36);
i %= 36;
}
i += (i < 10) ? '0' : 'A' - 10;
buf.writeByte(cast(char)i);
}
write_seq_id(idx - 1);
}
}
/**
* Attempt to perform substitution on `p`
*
* If `p` already appeared in the mangling, it is stored as
* a 'part', and short references in the form of `SX_` can be used.
* Note that `p` can be anything: template declaration, struct declaration,
* class declaration, namespace...
*
* Params:
* p = The object to attempt to substitute
* nested = Whether or not `p` is to be considered nested.
* When `true`, `N` will be prepended before the substitution.
*
* Returns:
* Whether `p` already appeared in the mangling,
* and substitution has been written to `this.buf`.
*/
bool substitute(RootObject p, bool nested = false)
{
//printf("substitute %s\n", p ? p.toChars() : null);
auto i = find(p);
if (i < 0)
return false;
//printf("\tmatch\n");
/* Sequence is S_, S0_, .., S9_, SA_, ..., SZ_, S10_, ...
*/
if (nested)
buf.writeByte('N');
buf.writeByte('S');
writeSequenceFromIndex(i);
buf.writeByte('_');
return true;
}
/******
* See if `p` exists in components[]
*
* Note that components can contain `null` entries,
* as the index used in mangling is based on the index in the array.
*
* If called with an object whose dynamic type is `Nspace`,
* calls the `find(Nspace)` overload.
*
* Returns:
* index if found, -1 if not
*/
int find(RootObject p)
{
//printf("find %p %d %s\n", p, p.dyncast(), p ? p.toChars() : null);
scope v = new ComponentVisitor(p);
foreach (i, component; components)
{
if (component)
component.visitObject(v);
if (v.result)
return cast(int)i;
}
return -1;
}
/*********************
* Append p to components[]
*/
void append(RootObject p)
{
//printf("append %p %d %s\n", p, p.dyncast(), p ? p.toChars() : "null");
components.push(p);
}
/**
* Write an identifier preceded by its length
*
* Params:
* ident = `Identifier` to write to `this.buf`
*/
void writeIdentifier(const ref Identifier ident)
{
const name = ident.toString();
this.buf.print(name.length);
this.buf.writestring(name);
}
/**
* Insert the leftover ABI tags to the buffer
*
* This inset ABI tags that hasn't already been written
* after the mangled name of the function.
* For more details, see the `abiTags` variable.
*
* Params:
* off = Offset to insert at
* tf = Type of the function to mangle the return type of
*/
void writeRemainingTags(size_t off, TypeFunction tf)
{
Array!StringExp toWrite;
leftOver(tf, &this.abiTags.written, &toWrite);
OutBuffer b2;
foreach (se; toWrite)
{
auto tag = se.peekString();
// We can only insert a slice, and each insert is a memmove,
// so use a temporary buffer to keep it efficient.
b2.reset();
b2.writestring("B");
b2.print(tag.length);
b2.writestring(tag);
this.buf.insert(off, b2[]);
off += b2.length;
}
}
/************************
* Determine if symbol is indeed the global ::std namespace.
* Params:
* s = symbol to check
* Returns:
* true if it is ::std
*/
static bool isStd(Dsymbol s)
{
if (!s)
return false;
if (auto cnd = s.isCPPNamespaceDeclaration())
return isStd(cnd);
return (s.ident == Id.std && // the right name
s.isNspace() && // g++ disallows global "std" for other than a namespace
!getQualifier(s)); // at global level
}
/// Ditto
static bool isStd(CPPNamespaceDeclaration s)
{
return s && s.cppnamespace is null && s.ident == Id.std;
}
/************************
* Determine if type is a C++ fundamental type.
* Params:
* t = type to check
* Returns:
* true if it is a fundamental type
*/
static bool isFundamentalType(Type t)
{
// First check the target whether some specific ABI is being followed.
bool isFundamental = void;
if (target.cpp.fundamentalType(t, isFundamental))
return isFundamental;
if (auto te = t.isTypeEnum())
{
// Peel off enum type from special types.
if (te.sym.isSpecial())
t = te.memType();
}
// Fundamental arithmetic types:
// 1. integral types: bool, char, int, ...
// 2. floating point types: float, double, real
// 3. void
// 4. null pointer: std::nullptr_t (since C++11)
if (t.ty == Tvoid || t.ty == Tbool)
return true;
else if (t.ty == Tnull && global.params.cplusplus >= CppStdRevision.cpp11)
return true;
else
return t.isTypeBasic() && (t.isintegral() || t.isreal());
}
/******************************
* Write the mangled representation of a template argument.
* Params:
* ti = the template instance
* arg = the template argument index
*/
void template_arg(TemplateInstance ti, size_t arg)
{
TemplateDeclaration td = ti.tempdecl.isTemplateDeclaration();
assert(td);
TemplateParameter tp = (*td.parameters)[arg];
RootObject o = (*ti.tiargs)[arg];
auto prev = this.context.push({
TemplateInstance parentti;
if (this.context.res.dyncast() == DYNCAST.dsymbol)
parentti = this.context.res.asFuncDecl().parent.isTemplateInstance();
else
{
auto parent = this.context.res.asType().toDsymbol(null).parent;
parentti = parent.isTemplateInstance();
// https://issues.dlang.org/show_bug.cgi?id=22760
// The template instance may sometimes have the form
// S1!int.S1, therefore the above instruction might yield null
if (parentti is null && parent.parent)
parentti = parent.parent.isTemplateInstance();
}
return (*parentti.tiargs)[arg];
}());
scope (exit) this.context.pop(prev);
if (tp.isTemplateTypeParameter())
{
Type t = isType(o);
assert(t);
t.accept(this);
}
else if (TemplateValueParameter tv = tp.isTemplateValueParameter())
{
// <expr-primary> ::= L <type> <value number> E # integer literal
if (tv.valType.isintegral())
{
Expression e = isExpression(o);
assert(e);
buf.writeByte('L');
tv.valType.accept(this);
auto val = e.toUInteger();
if (!tv.valType.isunsigned() && cast(sinteger_t)val < 0)
{
val = -val;
buf.writeByte('n');
}
buf.print(val);
buf.writeByte('E');
}
else
{
.error(ti.loc, "%s `%s` internal compiler error: C++ `%s` template value parameter is not supported", ti.kind, ti.toPrettyChars, tv.valType.toChars());
errors = true;
return;
}
}
else if (tp.isTemplateAliasParameter())
{
// Passing a function as alias parameter is the same as passing
// `&function`
Dsymbol d = isDsymbol(o);
Expression e = isExpression(o);
if (d && d.isFuncDeclaration())
{
// X .. E => template parameter is an expression
// 'ad' => unary operator ('&')
// L .. E => is a <expr-primary>
buf.writestring("XadL");
mangle_function(d.isFuncDeclaration());
buf.writestring("EE");
}
else if (e && e.isVarExp() && e.isVarExp().var.isVarDeclaration())
{
VarDeclaration vd = e.isVarExp().var.isVarDeclaration();
buf.writeByte('L');
mangle_variable(vd, true);
buf.writeByte('E');
}
else if (d && d.isTemplateDeclaration() && d.isTemplateDeclaration().onemember)
{
if (!substitute(d))
{
cpp_mangle_name(d, false);
}
}
else
{
.error(ti.loc, "%s `%s` internal compiler error: C++ `%s` template alias parameter is not supported", ti.kind, ti.toPrettyChars, o.toChars());
errors = true;
}
}
else if (tp.isTemplateThisParameter())
{
.error(ti.loc, "%s `%s` internal compiler error: C++ `%s` template this parameter is not supported", ti.kind, ti.toPrettyChars, o.toChars());
errors = true;
}
else
{
assert(0);
}
}
/******************************
* Write the mangled representation of the template arguments.
* Params:
* ti = the template instance
* firstArg = index of the first template argument to mangle
* (used for operator overloading)
* Returns:
* true if any arguments were written
*/
bool template_args(TemplateInstance ti, int firstArg = 0)
{
/* <template-args> ::= I <template-arg>+ E
*/
if (!ti || ti.tiargs.length <= firstArg) // could happen if std::basic_string is not a template
return false;
buf.writeByte('I');
foreach (i; firstArg .. ti.tiargs.length)
{
TemplateDeclaration td = ti.tempdecl.isTemplateDeclaration();
assert(td);
TemplateParameter tp = (*td.parameters)[i];
/*
* <template-arg> ::= <type> # type or template
* ::= X <expression> E # expression
* ::= <expr-primary> # simple expressions
* ::= J <template-arg>* E # argument pack
*
* Reference: https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.template-arg
*/
if (TemplateTupleParameter tt = tp.isTemplateTupleParameter())
{
buf.writeByte('J'); // argument pack
// mangle the rest of the arguments as types
foreach (j; i .. (*ti.tiargs).length)
{
Type t = isType((*ti.tiargs)[j]);
if (t is null)
{
.error(ti.loc, "%s `%s` internal compiler error: C++ `%s` template value parameter is not supported", ti.kind, ti.toPrettyChars, (*ti.tiargs)[j].toChars());
errors = true;
return false;
}
t.accept(this);
}
buf.writeByte('E');
break;
}
template_arg(ti, i);
}
buf.writeByte('E');
return true;
}
/**
* Write the symbol `p` if not null, then execute the delegate
*
* Params:
* p = Symbol to write
* dg = Delegate to execute
*/
void writeChained(Dsymbol p, scope void delegate() dg)
{
if (p && !p.isModule())
{
buf.writestring("N");
source_name(p, true);
dg();
buf.writestring("E");
}
else
dg();
}
/**
* Write the name of `s` to the buffer
*
* Params:
* s = Symbol to write the name of
* haveNE = Whether `N..E` is already part of the mangling
* Because `Nspace` and `CPPNamespaceAttribute` can be
* mixed, this is a mandatory hack.
*/
void source_name(Dsymbol s, bool haveNE = false)
{
version (none)
{
printf("source_name(%s)\n", s.toChars());
auto sl = this.buf.peekSlice();
assert(sl.length == 0 || haveNE || s.cppnamespace is null || sl != "_ZN");
}
auto ti = s.isTemplateInstance();
if (!ti)
{
auto ag = s.isAggregateDeclaration();
const ident = (ag && ag.pMangleOverride) ? ag.pMangleOverride.id : s.ident;
this.writeNamespace(s.cppnamespace, () {
this.writeIdentifier(ident);
this.abiTags.writeSymbol(s, this);
},
haveNE);
return;
}
bool needsTa = false;
// https://issues.dlang.org/show_bug.cgi?id=20413
// N..E is not needed when substituting members of the std namespace.
// This is observed in the GCC and Clang implementations.
// The Itanium specification is not clear enough on this specific case.
// References:
// https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.name
// https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling-compression
Dsymbol q = getQualifier(ti.tempdecl);
Dsymbol ns = ti.tempdecl.cppnamespace;
const inStd = ns && isStd(ns) || q && isStd(q);
const isNested = !inStd && (ns || q);
if (substitute(ti.tempdecl, !haveNE && isNested))
{
template_args(ti);
if (!haveNE && isNested)
buf.writeByte('E');
return;
}
else if (this.writeStdSubstitution(ti, needsTa))
{
this.abiTags.writeSymbol(ti, this);
if (needsTa)
template_args(ti);
return;
}
auto ag = ti.aliasdecl ? ti.aliasdecl.isAggregateDeclaration() : null;
if (ag && ag.pMangleOverride)
{
this.writeNamespace(
ti.toAlias().cppnamespace, () {
this.writeIdentifier(ag.pMangleOverride.id);
if (ag.pMangleOverride.agg && ag.pMangleOverride.agg.isInstantiated())
{
auto to = ag.pMangleOverride.agg.isInstantiated();
append(to);
this.abiTags.writeSymbol(to.tempdecl, this);
template_args(to);
}
}, haveNE);
}
else
{
this.writeNamespace(
s.cppnamespace, () {
this.writeIdentifier(ti.tempdecl.toAlias().ident);
append(ti.tempdecl);
this.abiTags.writeSymbol(ti.tempdecl, this);
template_args(ti);
}, haveNE);
}
}
/********
* See if s is actually an instance of a template
* Params:
* s = symbol
* Returns:
* if s is instance of a template, return the instance, otherwise return s
*/
static Dsymbol getInstance(Dsymbol s)
{
Dsymbol p = s.toParent();
if (p)
{
if (TemplateInstance ti = p.isTemplateInstance())
return ti;
}
return s;
}
/// Get the namespace of a template instance
CPPNamespaceDeclaration getTiNamespace(TemplateInstance ti)
{
// If we receive a pre-semantic `TemplateInstance`,
// `cppnamespace` is always `null`
return ti.tempdecl ? ti.cppnamespace
: this.context.res.asType().toDsymbol(null).cppnamespace;
}
/********
* Get qualifier for `s`, meaning the symbol
* that s is in the symbol table of.
* The module does not count as a qualifier, because C++
* does not have modules.
* Params:
* s = symbol that may have a qualifier
* s is rewritten to be TemplateInstance if s is one
* Returns:
* qualifier, null if none
*/
static Dsymbol getQualifier(Dsymbol s)
{
Dsymbol p = s.toParent();
return (p && !p.isModule()) ? p : null;
}
// Detect type char
static bool isChar(RootObject o)
{
Type t = isType(o);
return (t && t.equals(Type.tchar));
}
// Detect type ::std::char_traits<char>
bool isChar_traits_char(RootObject o)
{
return isIdent_char(Id.char_traits, o);
}
// Detect type ::std::allocator<char>
bool isAllocator_char(RootObject o)
{
return isIdent_char(Id.allocator, o);
}
// Detect type ::std::ident<char>
bool isIdent_char(Identifier ident, RootObject o)
{
Type t = isType(o);
if (!t || !t.isTypeStruct())
return false;
Dsymbol s = t.toDsymbol(null);
if (s.ident != ident)
return false;
Dsymbol p = s.toParent();
if (!p)
return false;
TemplateInstance ti = p.isTemplateInstance();
if (!ti)
return false;
Dsymbol q = getQualifier(ti);
const bool inStd = isStd(q) || isStd(this.getTiNamespace(ti));
return inStd && ti.tiargs.length == 1 && isChar((*ti.tiargs)[0]);
}
/***
* Detect template args <char, ::std::char_traits<char>>
* and write st if found.
* Returns:
* true if found
*/
bool char_std_char_traits_char(TemplateInstance ti, string st)
{
if (ti.tiargs.length == 2 &&
isChar((*ti.tiargs)[0]) &&
isChar_traits_char((*ti.tiargs)[1]))
{
buf.writestring(st.ptr);
return true;
}
return false;
}
void prefix_name(Dsymbol s)
{
//printf("prefix_name(%s)\n", s.toChars());
if (substitute(s))
return;
if (isStd(s))
return buf.writestring("St");
auto si = getInstance(s);
Dsymbol p = getQualifier(si);
if (p)
{
if (isStd(p))
{
bool needsTa;
auto ti = si.isTemplateInstance();
if (this.writeStdSubstitution(ti, needsTa))
{
this.abiTags.writeSymbol(ti, this);
if (needsTa)
{
template_args(ti);
append(ti);
}
return;
}
buf.writestring("St");
}
else
prefix_name(p);
}
source_name(si, true);
if (!isStd(si))
/* Do this after the source_name() call to keep components[]
* in the right order.
* https://issues.dlang.org/show_bug.cgi?id=17947
*/
append(si);
}
/**
* Write common substitution for standard types, such as std::allocator
*
* This function assumes that the symbol `ti` is in the namespace `std`.
*
* Params:
* ti = Template instance to consider
* needsTa = If this function returns `true`, this value indicates
* if additional template argument mangling is needed
*
* Returns:
* `true` if a special std symbol was found
*/
bool writeStdSubstitution(TemplateInstance ti, out bool needsTa)
{
if (!ti)
return false;
if (!isStd(this.getTiNamespace(ti)) && !isStd(getQualifier(ti)))
return false;
if (ti.name == Id.allocator)
{
buf.writestring("Sa");
needsTa = true;
return true;
}
if (ti.name == Id.basic_string)
{
// ::std::basic_string<char, ::std::char_traits<char>, ::std::allocator<char>>
if (ti.tiargs.length == 3 &&
isChar((*ti.tiargs)[0]) &&
isChar_traits_char((*ti.tiargs)[1]) &&
isAllocator_char((*ti.tiargs)[2]))
{
buf.writestring("Ss");
return true;
}
buf.writestring("Sb"); // ::std::basic_string
needsTa = true;
return true;
}
// ::std::basic_istream<char, ::std::char_traits<char>>
if (ti.name == Id.basic_istream &&
char_std_char_traits_char(ti, "Si"))
return true;
// ::std::basic_ostream<char, ::std::char_traits<char>>
if (ti.name == Id.basic_ostream &&
char_std_char_traits_char(ti, "So"))
return true;
// ::std::basic_iostream<char, ::std::char_traits<char>>
if (ti.name == Id.basic_iostream &&
char_std_char_traits_char(ti, "Sd"))
return true;
return false;
}
void cpp_mangle_name(Dsymbol s, bool qualified)
{
//printf("cpp_mangle_name(%s, %d)\n", s.toChars(), qualified);
Dsymbol p = s.toParent();
Dsymbol se = s;
bool write_prefix = true;
if (p && p.isTemplateInstance())
{
se = p;
if (find(p.isTemplateInstance().tempdecl) >= 0)
write_prefix = false;
p = p.toParent();
}
if (!p || p.isModule())
{
source_name(se, false);
append(s);
return;
}
if (!isStd(p) || qualified)
{
buf.writeByte('N');
if (write_prefix)
{
if (isStd(p))
buf.writestring("St");
else
prefix_name(p);
}
source_name(se, true);
buf.writeByte('E');
append(s);
return;
}
/* The N..E is not required if:
* 1. the parent is 'std'
* 2. 'std' is the initial qualifier
* 3. there is no CV-qualifier or a ref-qualifier for a member function
* ABI 5.1.8
*/
TemplateInstance ti = se.isTemplateInstance();
if (s.ident == Id.allocator)
{
buf.writestring("Sa"); // "Sa" is short for ::std::allocator
template_args(ti);
}
else if (s.ident == Id.basic_string)
{
// ::std::basic_string<char, ::std::char_traits<char>, ::std::allocator<char>>
if (ti.tiargs.length == 3 &&
isChar((*ti.tiargs)[0]) &&
isChar_traits_char((*ti.tiargs)[1]) &&
isAllocator_char((*ti.tiargs)[2]))
{
buf.writestring("Ss");
return;
}
buf.writestring("Sb"); // ::std::basic_string
template_args(ti);
}
else
{
// ::std::basic_istream<char, ::std::char_traits<char>>
if (s.ident == Id.basic_istream)
{
if (char_std_char_traits_char(ti, "Si"))
return;
}
else if (s.ident == Id.basic_ostream)
{
if (char_std_char_traits_char(ti, "So"))
return;
}
else if (s.ident == Id.basic_iostream)
{
if (char_std_char_traits_char(ti, "Sd"))
return;
}