-
-
Notifications
You must be signed in to change notification settings - Fork 702
Expand file tree
/
Copy pathdtemplate.d
More file actions
1283 lines (1115 loc) Β· 37.6 KB
/
dtemplate.d
File metadata and controls
1283 lines (1115 loc) Β· 37.6 KB
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
/**
* Defines `TemplateDeclaration`, `TemplateInstance` and a few utilities
*
* This modules holds the two main template types:
* `TemplateDeclaration`, which is the user-provided declaration of a template,
* and `TemplateInstance`, which is an instance of a `TemplateDeclaration`
* with specific arguments.
*
* Template_Parameter:
* Additionally, the classes for template parameters are defined in this module.
* The base class, `TemplateParameter`, is inherited by:
* - `TemplateTypeParameter`
* - `TemplateThisParameter`
* - `TemplateValueParameter`
* - `TemplateAliasParameter`
* - `TemplateTupleParameter`
*
* Templates_semantic:
* The start of the template instantiation process looks like this:
* - A `TypeInstance` or `TypeIdentifier` is encountered.
* `TypeInstance` have a bang (e.g. `Foo!(arg)`) while `TypeIdentifier` don't.
* - A `TemplateInstance` is instantiated
* - Semantic is run on the `TemplateInstance` (see `dmd.dsymbolsem`)
* - The `TemplateInstance` search for its `TemplateDeclaration`,
* runs semantic on the template arguments and deduce the best match
* among the possible overloads.
* - The `TemplateInstance` search for existing instances with the same
* arguments, and uses it if found.
* - Otherwise, the rest of semantic is run on the `TemplateInstance`.
*
* Copyright: Copyright (C) 1999-2026 by The D Language Foundation, All Rights Reserved
* Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
* License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/compiler/src/dmd/dtemplate.d, _dtemplate.d)
* Documentation: https://dlang.org/phobos/dmd_dtemplate.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/dtemplate.d
*/
module dmd.dtemplate;
import core.stdc.stdio;
import core.stdc.string;
import dmd.arraytypes;
import dmd.astenums;
import dmd.ast_node;
import dmd.declaration;
import dmd.dmodule;
import dmd.dscope;
import dmd.dsymbol;
import dmd.errors;
import dmd.errorsink;
import dmd.expression;
import dmd.func;
import dmd.globals;
import dmd.hdrgen;
import dmd.identifier;
import dmd.location;
import dmd.mangle;
import dmd.mtype;
import dmd.root.array;
import dmd.common.outbuffer;
import dmd.rootobject;
import dmd.tokens;
import dmd.visitor;
//debug = FindExistingInstance; // print debug stats of findExistingInstance
private enum LOG = false;
enum IDX_NOTFOUND = 0x12345678;
pure nothrow @nogc @trusted
{
/********************************************
* These functions substitute for dynamic_cast. dynamic_cast does not work
* on earlier versions of gcc.
*/
inout(Expression) isExpression(inout RootObject o)
{
//return dynamic_cast<Expression *>(o);
if (!o || o.dyncast() != DYNCAST.expression)
return null;
return cast(inout(Expression))o;
}
inout(Dsymbol) isDsymbol(inout RootObject o)
{
//return dynamic_cast<Dsymbol *>(o);
if (!o || o.dyncast() != DYNCAST.dsymbol)
return null;
return cast(inout(Dsymbol))o;
}
inout(Type) isType(inout RootObject o)
{
//return dynamic_cast<Type *>(o);
if (!o || o.dyncast() != DYNCAST.type)
return null;
return cast(inout(Type))o;
}
inout(Tuple) isTuple(inout RootObject o)
{
//return dynamic_cast<Tuple *>(o);
if (!o || o.dyncast() != DYNCAST.tuple)
return null;
return cast(inout(Tuple))o;
}
inout(Parameter) isParameter(inout RootObject o)
{
//return dynamic_cast<Parameter *>(o);
if (!o || o.dyncast() != DYNCAST.parameter)
return null;
return cast(inout(Parameter))o;
}
inout(Identifier) isIdentifier(inout RootObject o)
{
if (!o || o.dyncast() != DYNCAST.identifier)
return null;
return cast(inout(Identifier))o;
}
inout(TemplateParameter) isTemplateParameter(inout RootObject o)
{
if (!o || o.dyncast() != DYNCAST.templateparameter)
return null;
return cast(inout(TemplateParameter))o;
}
} // end @trusted casts
pure nothrow @nogc @safe
{
/**************************************
* Is this Object an error?
*/
bool isError(const RootObject o)
{
if (const t = isType(o))
return (t.ty == Terror);
if (const e = isExpression(o))
return (e.op == EXP.error || !e.type || e.type.ty == Terror);
if (const v = isTuple(o))
return arrayObjectIsError(v.objects);
const s = isDsymbol(o);
assert(s);
if (s.errors)
return true;
return s.parent ? isError(s.parent) : false;
}
/**************************************
* Are any of the Objects an error?
*/
bool arrayObjectIsError(const ref Objects args)
{
foreach (const o; args)
{
if (isError(o))
return true;
}
return false;
}
/***********************
* Try to get arg as a type.
*/
inout(Type) getType(inout RootObject o)
{
inout t = isType(o);
if (!t)
{
if (inout e = isExpression(o))
return e.type;
}
return t;
}
}
RootObject objectSyntaxCopy(RootObject o)
{
if (!o)
return null;
if (Type t = isType(o))
return t.syntaxCopy();
if (Expression e = isExpression(o))
return e.syntaxCopy();
return o;
}
extern (C++) final class Tuple : RootObject
{
Objects objects;
extern (D) this() {}
/**
Params:
numObjects = The initial number of objects.
*/
extern (D) this(size_t numObjects)
{
objects.setDim(numObjects);
}
// kludge for template.isType()
override DYNCAST dyncast() const
{
return DYNCAST.tuple;
}
override const(char)* toChars() const
{
return objects.toChars();
}
}
struct TemplatePrevious
{
TemplatePrevious* prev;
Scope* sc;
Objects* dedargs;
}
/***********************************************************
* [mixin] template Identifier (parameters) [Constraint]
* https://dlang.org/spec/template.html
* https://dlang.org/spec/template-mixin.html
*/
extern (C++) final class TemplateDeclaration : ScopeDsymbol
{
import dmd.root.array : Array;
TemplateParameters* parameters; // array of TemplateParameter's
TemplateParameters* origParameters; // originals for Ddoc
Expression constraint;
// Hash table to look up TemplateInstance's of this TemplateDeclaration
void* instances;
TemplateDeclaration overnext; // next overloaded TemplateDeclaration
TemplateDeclaration overroot; // first in overnext list
FuncDeclaration funcroot; // first function in unified overload list
Dsymbol onemember; // if !=null then one member of this template
bool literal; // this template declaration is a literal
bool ismixin; // this is a mixin template declaration
bool isstatic; // this is static template declaration
bool isTrivialAliasSeq; /// matches pattern `template AliasSeq(T...) { alias AliasSeq = T; }`
bool isTrivialAlias; /// matches pattern `template Alias(T) { alias Alias = qualifiers(T); }`
bool deprecated_; /// this template declaration is deprecated
bool isCmacro; /// Whether this template is a translation of a C macro
bool haveComputedOneMember; /// Whether computeOneMeber has been called
Visibility visibility;
// threaded list of previous instantiation attempts on stack
TemplatePrevious* previous;
Expression lastConstraint; /// the constraint after the last failed evaluation
Array!Expression lastConstraintNegs; /// its negative parts
Objects* lastConstraintTiargs; /// template instance arguments for `lastConstraint`
extern (D) this(Loc loc, Identifier ident, TemplateParameters* parameters, Expression constraint, Dsymbols* decldefs, bool ismixin = false, bool literal = false)
{
super(loc, ident);
this.dsym = DSYM.templateDeclaration;
static if (LOG)
{
printf("TemplateDeclaration(this = %p, id = '%s')\n", this, ident.toChars());
}
version (none)
{
if (parameters)
for (int i = 0; i < parameters.length; i++)
{
TemplateParameter tp = (*parameters)[i];
//printf("\tparameter[%d] = %p\n", i, tp);
TemplateTypeParameter ttp = tp.isTemplateTypeParameter();
if (ttp)
{
printf("\tparameter[%d] = %s : %s\n", i, tp.ident.toChars(), ttp.specType ? ttp.specType.toChars() : "");
}
}
}
this.parameters = parameters;
this.origParameters = parameters;
this.constraint = constraint;
this.members = decldefs;
this.literal = literal;
this.ismixin = ismixin;
this.isstatic = true;
this.haveComputedOneMember = false;
this.visibility = Visibility(Visibility.Kind.undefined);
}
override TemplateDeclaration syntaxCopy(Dsymbol)
{
//printf("TemplateDeclaration.syntaxCopy()\n");
TemplateParameters* p = null;
if (parameters)
{
p = new TemplateParameters(parameters.length);
foreach (i, ref param; *p)
param = (*parameters)[i].syntaxCopy();
}
return new TemplateDeclaration(loc, ident, p, constraint ? constraint.syntaxCopy() : null, Dsymbol.arraySyntaxCopy(members), ismixin, literal);
}
override const(char)* kind() const
{
return (onemember && onemember.isAggregateDeclaration()) ? onemember.kind() : "template";
}
/****************************
* Similar to `toChars`, but does not print the template constraints
*/
const(char)* toCharsNoConstraints() const
{
HdrGenState hgs = { skipConstraints: true };
OutBuffer buf;
toCharsMaybeConstraints(this, buf, hgs);
return buf.extractChars();
}
override Visibility visible() pure nothrow @nogc @safe
{
return visibility;
}
/**
* Check if the last template parameter is a tuple one,
* and returns it if so, else returns `null`.
*
* Returns:
* The last template parameter if it's a `TemplateTupleParameter`
*/
extern (D) TemplateTupleParameter isVariadic()
{
const dim = parameters.length;
if (dim == 0)
return null;
return (*parameters)[dim - 1].isTemplateTupleParameter();
}
extern(C++) override bool isDeprecated() const
{
return this.deprecated_;
}
/***********************************
* We can overload templates.
*/
override bool isOverloadable() const
{
return true;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
extern (C++) final class TypeDeduced : Type
{
Type tded;
Expressions argexps; // corresponding expressions
Types tparams; // tparams[i].mod
extern (D) this(Type tt, Expression e, Type tparam)
{
super(Tnone);
tded = tt;
argexps.push(e);
tparams.push(tparam);
}
void update(Expression e, Type tparam)
{
argexps.push(e);
tparams.push(tparam);
}
void update(Type tt, Expression e, Type tparam)
{
tded = tt;
argexps.push(e);
tparams.push(tparam);
}
}
/***********************************************************
* https://dlang.org/spec/template.html#TemplateParameter
*/
extern (C++) class TemplateParameter : ASTNode
{
Loc loc;
Identifier ident;
/* True if this is a part of precedent parameter specialization pattern.
*
* template A(T : X!TL, alias X, TL...) {}
* // X and TL are dependent template parameter
*
* A dependent template parameter should return MATCH.exact in matchArg()
* to respect the match level of the corresponding precedent parameter.
*/
bool dependent;
/* ======================== TemplateParameter =============================== */
extern (D) this(Loc loc, Identifier ident) @safe
{
this.loc = loc;
this.ident = ident;
}
TemplateTypeParameter isTemplateTypeParameter()
{
return null;
}
TemplateValueParameter isTemplateValueParameter()
{
return null;
}
TemplateAliasParameter isTemplateAliasParameter()
{
return null;
}
TemplateThisParameter isTemplateThisParameter()
{
return null;
}
TemplateTupleParameter isTemplateTupleParameter()
{
return null;
}
abstract TemplateParameter syntaxCopy();
abstract void print(RootObject oarg, RootObject oded);
abstract RootObject specialization();
abstract bool hasDefaultArg();
override const(char)* toChars() const
{
return this.ident.toChars();
}
override DYNCAST dyncast() const
{
return DYNCAST.templateparameter;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
* https://dlang.org/spec/template.html#TemplateTypeParameter
* Syntax:
* ident : specType = defaultType
*/
extern (C++) class TemplateTypeParameter : TemplateParameter
{
Type specType; // if !=null, this is the type specialization
Type defaultType;
extern (D) __gshared Type tdummy = null;
extern (D) this(Loc loc, Identifier ident, Type specType, Type defaultType) @safe
{
super(loc, ident);
this.specType = specType;
this.defaultType = defaultType;
}
override final TemplateTypeParameter isTemplateTypeParameter()
{
return this;
}
override TemplateTypeParameter syntaxCopy()
{
return new TemplateTypeParameter(loc, ident, specType ? specType.syntaxCopy() : null, defaultType ? defaultType.syntaxCopy() : null);
}
override final void print(RootObject oarg, RootObject oded)
{
printf(" %s\n", ident.toChars());
Type t = isType(oarg);
Type ta = isType(oded);
assert(ta);
if (specType)
printf("\tSpecialization: %s\n", specType.toChars());
if (defaultType)
printf("\tDefault: %s\n", defaultType.toChars());
printf("\tParameter: %s\n", t ? t.toChars() : "NULL");
printf("\tDeduced Type: %s\n", ta.toChars());
}
override final RootObject specialization()
{
return specType;
}
override final bool hasDefaultArg()
{
return defaultType !is null;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
* https://dlang.org/spec/template.html#TemplateThisParameter
* Syntax:
* this ident : specType = defaultType
*/
extern (C++) final class TemplateThisParameter : TemplateTypeParameter
{
extern (D) this(Loc loc, Identifier ident, Type specType, Type defaultType) @safe
{
super(loc, ident, specType, defaultType);
}
override TemplateThisParameter isTemplateThisParameter()
{
return this;
}
override TemplateThisParameter syntaxCopy()
{
return new TemplateThisParameter(loc, ident, specType ? specType.syntaxCopy() : null, defaultType ? defaultType.syntaxCopy() : null);
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
* https://dlang.org/spec/template.html#TemplateValueParameter
* Syntax:
* valType ident : specValue = defaultValue
*/
extern (C++) final class TemplateValueParameter : TemplateParameter
{
Type valType;
Expression specValue;
Expression defaultValue;
extern (D) __gshared Expression[void*] edummies;
extern (D) this(Loc loc, Identifier ident, Type valType,
Expression specValue, Expression defaultValue) @safe
{
super(loc, ident);
this.valType = valType;
this.specValue = specValue;
this.defaultValue = defaultValue;
}
override TemplateValueParameter isTemplateValueParameter()
{
return this;
}
override TemplateValueParameter syntaxCopy()
{
return new TemplateValueParameter(loc, ident,
valType.syntaxCopy(),
specValue ? specValue.syntaxCopy() : null,
defaultValue ? defaultValue.syntaxCopy() : null);
}
override void print(RootObject oarg, RootObject oded)
{
printf(" %s\n", ident.toChars());
Expression ea = isExpression(oded);
if (specValue)
printf("\tSpecialization: %s\n", specValue.toChars());
printf("\tParameter Value: %s\n", ea ? ea.toChars() : "NULL");
}
override RootObject specialization()
{
return specValue;
}
override bool hasDefaultArg()
{
return defaultValue !is null;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
* https://dlang.org/spec/template.html#TemplateAliasParameter
* Syntax:
* specType ident : specAlias = defaultAlias
*/
extern (C++) final class TemplateAliasParameter : TemplateParameter
{
Type specType;
RootObject specAlias;
RootObject defaultAlias;
extern (D) __gshared Dsymbol sdummy = null;
extern (D) this(Loc loc, Identifier ident, Type specType, RootObject specAlias, RootObject defaultAlias) @safe
{
super(loc, ident);
this.specType = specType;
this.specAlias = specAlias;
this.defaultAlias = defaultAlias;
}
override TemplateAliasParameter isTemplateAliasParameter()
{
return this;
}
override TemplateAliasParameter syntaxCopy()
{
return new TemplateAliasParameter(loc, ident, specType ? specType.syntaxCopy() : null, objectSyntaxCopy(specAlias), objectSyntaxCopy(defaultAlias));
}
override void print(RootObject oarg, RootObject oded)
{
printf(" %s\n", ident.toChars());
Dsymbol sa = isDsymbol(oded);
assert(sa);
printf("\tParameter alias: %s\n", sa.toChars());
}
override RootObject specialization()
{
return specAlias;
}
override bool hasDefaultArg()
{
return defaultAlias !is null;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
* https://dlang.org/spec/template.html#TemplateSequenceParameter
* Syntax:
* ident ...
*/
extern (C++) final class TemplateTupleParameter : TemplateParameter
{
extern (D) this(Loc loc, Identifier ident) @safe
{
super(loc, ident);
}
override TemplateTupleParameter isTemplateTupleParameter()
{
return this;
}
override TemplateTupleParameter syntaxCopy()
{
return new TemplateTupleParameter(loc, ident);
}
override void print(RootObject oarg, RootObject oded)
{
printf(" %s... [", ident.toChars());
Tuple v = isTuple(oded);
assert(v);
//printf("|%d| ", v.objects.length);
foreach (i, o; v.objects)
{
if (i)
printf(", ");
Dsymbol sa = isDsymbol(o);
if (sa)
printf("alias: %s", sa.toChars());
Type ta = isType(o);
if (ta)
printf("type: %s", ta.toChars());
Expression ea = isExpression(o);
if (ea)
printf("exp: %s", ea.toChars());
assert(!isTuple(o)); // no nested Tuple arguments
}
printf("]\n");
}
override RootObject specialization()
{
return null;
}
override bool hasDefaultArg()
{
return false;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
* https://dlang.org/spec/template.html#explicit_tmp_instantiation
* Given:
* foo!(args) =>
* name = foo
* tiargs = args
*/
extern (C++) class TemplateInstance : ScopeDsymbol
{
Identifier name;
// Array of Types/Expressions of template
// instance arguments [int*, char, 10*10]
Objects* tiargs;
// Array of Types/Expressions corresponding
// to TemplateDeclaration.parameters
// [int, char, 100]
Objects tdtypes;
// Modules imported by this template instance
Modules importedModules;
Dsymbol tempdecl; // referenced by foo.bar.abc
Dsymbol enclosing; // if referencing local symbols, this is the context
Dsymbol aliasdecl; // !=null if instance is an alias for its sole member
/**
If this is not null and it has a value that is not the current object,
then this field points to an existing template instance
and that object has been duplicated into us.
If this object is a duplicate,
the ``memberOf`` field will be set to a root module (passed on CLI).
This information is useful to deduplicate analysis that may occur
after semantic 3 has completed.
See_Also: memberOf
*/
TemplateInstance inst;
ScopeDsymbol argsym; // argument symbol table
/// For function template, these are the function fnames(name and loc of it) and arguments
/// Relevant because different resolutions of `auto ref` parameters
/// create different template instances even with the same template arguments
Expressions* fargs;
ArgumentLabels* fnames;
TemplateInstances* deferred;
/**
If this is not null then this template instance appears in a root module's members.
Note: This is not useful for determining duplication status of this template instance.
Use the field ``inst`` for determining if a template instance has been duplicated into this object.
See_Also: inst
*/
Module memberOf;
// Used to determine the instance needs code generation.
// Note that these are inaccurate until semantic analysis phase completed.
TemplateInstance tinst; // enclosing template instance
TemplateInstance tnext; // non-first instantiated instances
Module minst; // the top module that instantiated this instance
private ushort _nest; // for recursive pretty printing detection, 3 MSBs reserved for flags (below)
ubyte inuse; // for recursive expansion detection
private enum Flag : uint
{
semantictiargsdone = 1u << (_nest.sizeof * 8 - 1), // MSB of _nest
havetempdecl = semantictiargsdone >> 1,
gagged = semantictiargsdone >> 2,
available = gagged - 1 // always last flag minus one, 1s for all available bits
}
extern(D) final @safe @property pure nothrow @nogc
{
ushort nest() const { return _nest & Flag.available; }
void nestUp() { assert(nest() < Flag.available); ++_nest; }
void nestDown() { assert(nest() > 0); --_nest; }
/// has semanticTiargs() been done?
bool semantictiargsdone() const { return (_nest & Flag.semantictiargsdone) != 0; }
void semantictiargsdone(bool x)
{
if (x) _nest |= Flag.semantictiargsdone;
else _nest &= ~Flag.semantictiargsdone;
}
/// if used second constructor
bool havetempdecl() const { return (_nest & Flag.havetempdecl) != 0; }
void havetempdecl(bool x)
{
if (x) _nest |= Flag.havetempdecl;
else _nest &= ~Flag.havetempdecl;
}
/// if the instantiation is done with error gagging
bool gagged() const { return (_nest & Flag.gagged) != 0; }
void gagged(bool x)
{
if (x) _nest |= Flag.gagged;
else _nest &= ~Flag.gagged;
}
}
extern (D) this(Loc loc, Identifier ident, Objects* tiargs) scope
{
super(loc, null);
static if (LOG)
{
printf("TemplateInstance(this = %p, ident = '%s')\n", this, ident ? ident.toChars() : "null");
}
this.dsym = DSYM.templateInstance;
this.name = ident;
this.tiargs = tiargs;
}
/*****************
* This constructor is only called when we figured out which function
* template to instantiate.
*/
extern (D) this(Loc loc, TemplateDeclaration td, Objects* tiargs) scope
{
super(loc, null);
static if (LOG)
{
printf("TemplateInstance(this = %p, tempdecl = '%s')\n", this, td.toChars());
}
this.dsym = DSYM.templateInstance;
this.name = td.ident;
this.tiargs = tiargs;
this.tempdecl = td;
this.semantictiargsdone = true;
this.havetempdecl = true;
assert(tempdecl._scope);
}
extern (D) static Objects* arraySyntaxCopy(Objects* objs)
{
Objects* a = null;
if (objs)
{
a = new Objects(objs.length);
foreach (i, o; *objs)
(*a)[i] = objectSyntaxCopy(o);
}
return a;
}
override TemplateInstance syntaxCopy(Dsymbol s)
{
TemplateInstance ti = s ? cast(TemplateInstance)s : new TemplateInstance(loc, name, null);
ti.tiargs = arraySyntaxCopy(tiargs);
TemplateDeclaration td;
if (inst && tempdecl && (td = tempdecl.isTemplateDeclaration()) !is null)
td.ScopeDsymbol.syntaxCopy(ti);
else
ScopeDsymbol.syntaxCopy(ti);
return ti;
}
override const(char)* kind() const
{
return "template instance";
}
override final const(char)* toPrettyCharsHelper()
{
OutBuffer buf;
toCBufferInstance(this, buf, true);
return buf.extractChars();
}
/**************************************
* Given an error instantiating the TemplateInstance,
* give the nested TemplateInstance instantiations that got
* us here. Those are a list threaded into the nested scopes.
* Params:
* cl = classification of this trace as printing either errors or deprecations
* max_shown = maximum number of trace elements printed (controlled with -v/-verror-limit)
*/
extern(D) final void printInstantiationTrace(Classification cl = Classification.error,
const(uint) max_shown = global.params.v.errorSupplementCount())
{
if (global.gag)
return;
// Print full trace for verbose mode, otherwise only short traces
const(char)* format = "instantiated from here: `%s`";
// This returns a function pointer
scope printFn = () {
final switch (cl)
{
case Classification.error:
return &errorSupplemental;
case Classification.deprecation:
return &deprecationSupplemental;
case Classification.gagged, Classification.tip, Classification.warning:
assert(0);
}
}();
// determine instantiation depth and number of recursive instantiations
int n_instantiations = 1;
int n_totalrecursions = 0;
for (TemplateInstance cur = this; cur; cur = cur.tinst)
{
++n_instantiations;
// Set error here as we don't want it to depend on the number of
// entries that are being printed.
if (cl == Classification.error ||
(cl == Classification.warning && global.params.useWarnings == DiagnosticReporting.error) ||
(cl == Classification.deprecation && global.params.useDeprecated == DiagnosticReporting.error))
cur.errors = true;
// If two instantiations use the same declaration, they are recursive.
// (this works even if they are instantiated from different places in the
// same template).
// In principle, we could also check for multiple-template recursion, but it's
// probably not worthwhile.
if (cur.tinst && cur.tempdecl && cur.tinst.tempdecl && cur.tempdecl.loc.equals(cur.tinst.tempdecl.loc))
++n_totalrecursions;
}
if (n_instantiations <= max_shown)
{
for (TemplateInstance cur = this; cur; cur = cur.tinst)
printFn(cur.loc, format, cur.toErrMsg());
}
else if (n_instantiations - n_totalrecursions <= max_shown)
{
// By collapsing recursive instantiations into a single line,
// we can stay under the limit.
int recursionDepth = 0;
for (TemplateInstance cur = this; cur; cur = cur.tinst)
{
if (cur.tinst && cur.tempdecl && cur.tinst.tempdecl && cur.tempdecl.loc.equals(cur.tinst.tempdecl.loc))
{
++recursionDepth;
}
else
{
if (recursionDepth)
printFn(cur.loc, "%d recursive instantiations from here: `%s`", recursionDepth + 2, cur.toChars());
else
printFn(cur.loc, format, cur.toChars());
recursionDepth = 0;
}
}
}
else
{
// Even after collapsing the recursions, the depth is too deep.
// Just display the first few and last few instantiations.
uint i = 0;
for (TemplateInstance cur = this; cur; cur = cur.tinst)
{