/
dtemplate.d
8392 lines (7593 loc) · 290 KB
/
dtemplate.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
/**
* 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-2021 by The D Language Foundation, All Rights Reserved
* Authors: $(LINK2 http://www.digitalmars.com, Walter Bright)
* License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/dtemplate.d, _dtemplate.d)
* Documentation: https://dlang.org/phobos/dmd_dtemplate.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/dtemplate.d
*/
module dmd.dtemplate;
import core.stdc.stdio;
import core.stdc.string;
import dmd.aggregate;
import dmd.aliasthis;
import dmd.arraytypes;
import dmd.ast_node;
import dmd.dcast;
import dmd.dclass;
import dmd.declaration;
import dmd.dmangle;
import dmd.dmodule;
import dmd.dscope;
import dmd.dsymbol;
import dmd.dsymbolsem;
import dmd.errors;
import dmd.expression;
import dmd.expressionsem;
import dmd.func;
import dmd.globals;
import dmd.hdrgen;
import dmd.id;
import dmd.identifier;
import dmd.impcnvtab;
import dmd.init;
import dmd.initsem;
import dmd.mtype;
import dmd.opover;
import dmd.root.array;
import dmd.root.outbuffer;
import dmd.root.rootobject;
import dmd.semantic2;
import dmd.semantic3;
import dmd.tokens;
import dmd.typesem;
import dmd.visitor;
import dmd.templateparamsem;
//debug = FindExistingInstance; // print debug stats of findExistingInstance
private enum LOG = false;
enum IDX_NOTFOUND = 0x12345678;
pure nothrow @nogc
{
/********************************************
* These functions substitute for dynamic_cast. dynamic_cast does not work
* on earlier versions of gcc.
*/
extern (C++) inout(Expression) isExpression(inout RootObject o)
{
//return dynamic_cast<Expression *>(o);
if (!o || o.dyncast() != DYNCAST.expression)
return null;
return cast(inout(Expression))o;
}
extern (C++) inout(Dsymbol) isDsymbol(inout RootObject o)
{
//return dynamic_cast<Dsymbol *>(o);
if (!o || o.dyncast() != DYNCAST.dsymbol)
return null;
return cast(inout(Dsymbol))o;
}
extern (C++) inout(Type) isType(inout RootObject o)
{
//return dynamic_cast<Type *>(o);
if (!o || o.dyncast() != DYNCAST.type)
return null;
return cast(inout(Type))o;
}
extern (C++) inout(Tuple) isTuple(inout RootObject o)
{
//return dynamic_cast<Tuple *>(o);
if (!o || o.dyncast() != DYNCAST.tuple)
return null;
return cast(inout(Tuple))o;
}
extern (C++) inout(Parameter) isParameter(inout RootObject o)
{
//return dynamic_cast<Parameter *>(o);
if (!o || o.dyncast() != DYNCAST.parameter)
return null;
return cast(inout(Parameter))o;
}
extern (C++) inout(TemplateParameter) isTemplateParameter(inout RootObject o)
{
if (!o || o.dyncast() != DYNCAST.templateparameter)
return null;
return cast(inout(TemplateParameter))o;
}
/**************************************
* Is this Object an error?
*/
extern (C++) bool isError(const RootObject o)
{
if (const t = isType(o))
return (t.ty == Terror);
if (const e = isExpression(o))
return (e.op == TOK.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 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;
}
}
Dsymbol getDsymbol(RootObject oarg)
{
//printf("getDsymbol()\n");
//printf("e %p s %p t %p v %p\n", isExpression(oarg), isDsymbol(oarg), isType(oarg), isTuple(oarg));
if (auto ea = isExpression(oarg))
{
// Try to convert Expression to symbol
if (auto ve = ea.isVarExp())
return ve.var;
else if (auto fe = ea.isFuncExp())
return fe.td ? fe.td : fe.fd;
else if (auto te = ea.isTemplateExp())
return te.td;
else if (auto te = ea.isScopeExp())
return te.sds;
else
return null;
}
else
{
// Try to convert Type to symbol
if (auto ta = isType(oarg))
return ta.toDsymbol(null);
else
return isDsymbol(oarg); // if already a symbol
}
}
private Expression getValue(ref Dsymbol s)
{
if (s)
{
if (VarDeclaration v = s.isVarDeclaration())
{
if (v.storage_class & STC.manifest)
return v.getConstInitializer();
}
}
return null;
}
/***********************
* Try to get value from manifest constant
*/
private Expression getValue(Expression e)
{
if (e && e.op == TOK.variable)
{
VarDeclaration v = (cast(VarExp)e).var.isVarDeclaration();
if (v && v.storage_class & STC.manifest)
{
e = v.getConstInitializer();
}
}
return e;
}
private Expression getExpression(RootObject o)
{
auto s = isDsymbol(o);
return s ? .getValue(s) : .getValue(isExpression(o));
}
/******************************
* If o1 matches o2, return true.
* Else, return false.
*/
private bool match(RootObject o1, RootObject o2)
{
enum log = false;
static if (log)
{
printf("match() o1 = %p %s (%d), o2 = %p %s (%d)\n",
o1, o1.toChars(), o1.dyncast(), o2, o2.toChars(), o2.dyncast());
}
/* A proper implementation of the various equals() overrides
* should make it possible to just do o1.equals(o2), but
* we'll do that another day.
*/
/* Manifest constants should be compared by their values,
* at least in template arguments.
*/
if (auto t1 = isType(o1))
{
auto t2 = isType(o2);
if (!t2)
goto Lnomatch;
static if (log)
{
printf("\tt1 = %s\n", t1.toChars());
printf("\tt2 = %s\n", t2.toChars());
}
if (!t1.equals(t2))
goto Lnomatch;
goto Lmatch;
}
if (auto e1 = getExpression(o1))
{
auto e2 = getExpression(o2);
if (!e2)
goto Lnomatch;
static if (log)
{
printf("\te1 = %s '%s' %s\n", e1.type ? e1.type.toChars() : "null", Token.toChars(e1.op), e1.toChars());
printf("\te2 = %s '%s' %s\n", e2.type ? e2.type.toChars() : "null", Token.toChars(e2.op), e2.toChars());
}
// two expressions can be equal although they do not have the same
// type; that happens when they have the same value. So check type
// as well as expression equality to ensure templates are properly
// matched.
if (!(e1.type && e2.type && e1.type.equals(e2.type)) || !e1.equals(e2))
goto Lnomatch;
goto Lmatch;
}
if (auto s1 = isDsymbol(o1))
{
auto s2 = isDsymbol(o2);
if (!s2)
goto Lnomatch;
static if (log)
{
printf("\ts1 = %s \n", s1.kind(), s1.toChars());
printf("\ts2 = %s \n", s2.kind(), s2.toChars());
}
if (!s1.equals(s2))
goto Lnomatch;
if (s1.parent != s2.parent && !s1.isFuncDeclaration() && !s2.isFuncDeclaration())
goto Lnomatch;
goto Lmatch;
}
if (auto u1 = isTuple(o1))
{
auto u2 = isTuple(o2);
if (!u2)
goto Lnomatch;
static if (log)
{
printf("\tu1 = %s\n", u1.toChars());
printf("\tu2 = %s\n", u2.toChars());
}
if (!arrayObjectMatch(&u1.objects, &u2.objects))
goto Lnomatch;
goto Lmatch;
}
Lmatch:
static if (log)
printf("\t. match\n");
return true;
Lnomatch:
static if (log)
printf("\t. nomatch\n");
return false;
}
/************************************
* Match an array of them.
*/
private bool arrayObjectMatch(Objects* oa1, Objects* oa2)
{
if (oa1 == oa2)
return true;
if (oa1.dim != oa2.dim)
return false;
immutable oa1dim = oa1.dim;
auto oa1d = (*oa1)[].ptr;
auto oa2d = (*oa2)[].ptr;
foreach (j; 0 .. oa1dim)
{
RootObject o1 = oa1d[j];
RootObject o2 = oa2d[j];
if (!match(o1, o2))
{
return false;
}
}
return true;
}
/************************************
* Return hash of Objects.
*/
private size_t arrayObjectHash(Objects* oa1)
{
import dmd.root.hash : mixHash;
size_t hash = 0;
foreach (o1; *oa1)
{
/* Must follow the logic of match()
*/
if (auto t1 = isType(o1))
hash = mixHash(hash, cast(size_t)t1.deco);
else if (auto e1 = getExpression(o1))
hash = mixHash(hash, expressionHash(e1));
else if (auto s1 = isDsymbol(o1))
{
auto fa1 = s1.isFuncAliasDeclaration();
if (fa1)
s1 = fa1.toAliasFunc();
hash = mixHash(hash, mixHash(cast(size_t)cast(void*)s1.getIdent(), cast(size_t)cast(void*)s1.parent));
}
else if (auto u1 = isTuple(o1))
hash = mixHash(hash, arrayObjectHash(&u1.objects));
}
return hash;
}
/************************************
* Computes hash of expression.
* Handles all Expression classes and MUST match their equals method,
* i.e. e1.equals(e2) implies expressionHash(e1) == expressionHash(e2).
*/
private size_t expressionHash(Expression e)
{
import dmd.root.ctfloat : CTFloat;
import dmd.root.hash : calcHash, mixHash;
switch (e.op)
{
case TOK.int64:
return cast(size_t) (cast(IntegerExp)e).getInteger();
case TOK.float64:
return CTFloat.hash((cast(RealExp)e).value);
case TOK.complex80:
auto ce = cast(ComplexExp)e;
return mixHash(CTFloat.hash(ce.toReal), CTFloat.hash(ce.toImaginary));
case TOK.identifier:
return cast(size_t)cast(void*) (cast(IdentifierExp)e).ident;
case TOK.null_:
return cast(size_t)cast(void*) (cast(NullExp)e).type;
case TOK.string_:
return calcHash(e.isStringExp.peekData());
case TOK.tuple:
{
auto te = cast(TupleExp)e;
size_t hash = 0;
hash += te.e0 ? expressionHash(te.e0) : 0;
foreach (elem; *te.exps)
hash = mixHash(hash, expressionHash(elem));
return hash;
}
case TOK.arrayLiteral:
{
auto ae = cast(ArrayLiteralExp)e;
size_t hash;
foreach (i; 0 .. ae.elements.dim)
hash = mixHash(hash, expressionHash(ae[i]));
return hash;
}
case TOK.assocArrayLiteral:
{
auto ae = cast(AssocArrayLiteralExp)e;
size_t hash;
foreach (i; 0 .. ae.keys.dim)
// reduction needs associative op as keys are unsorted (use XOR)
hash ^= mixHash(expressionHash((*ae.keys)[i]), expressionHash((*ae.values)[i]));
return hash;
}
case TOK.structLiteral:
{
auto se = cast(StructLiteralExp)e;
size_t hash;
foreach (elem; *se.elements)
hash = mixHash(hash, elem ? expressionHash(elem) : 0);
return hash;
}
case TOK.variable:
return cast(size_t)cast(void*) (cast(VarExp)e).var;
case TOK.function_:
return cast(size_t)cast(void*) (cast(FuncExp)e).fd;
default:
// no custom equals for this expression
assert((&e.equals).funcptr is &RootObject.equals);
// equals based on identity
return cast(size_t)cast(void*) e;
}
}
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
TemplateInstance[TemplateInstanceBox] 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
Visibility visibility;
int inuse; /// for recursive expansion detection
// threaded list of previous instantiation attempts on stack
TemplatePrevious* previous;
private Expression lastConstraint; /// the constraint after the last failed evaluation
private Array!Expression lastConstraintNegs; /// its negative parts
private Objects* lastConstraintTiargs; /// template instance arguments for `lastConstraint`
extern (D) this(const ref Loc loc, Identifier ident, TemplateParameters* parameters, Expression constraint, Dsymbols* decldefs, bool ismixin = false, bool literal = false)
{
super(loc, ident);
static if (LOG)
{
printf("TemplateDeclaration(this = %p, id = '%s')\n", this, ident.toChars());
}
version (none)
{
if (parameters)
for (int i = 0; i < parameters.dim; 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.visibility = Visibility(Visibility.Kind.undefined);
// Compute in advance for Ddoc's use
// https://issues.dlang.org/show_bug.cgi?id=11153: ident could be NULL if parsing fails.
if (!members || !ident)
return;
Dsymbol s;
if (!Dsymbol.oneMembers(members, &s, ident) || !s)
return;
onemember = s;
s.parent = this;
/* Set isTrivialAliasSeq if this fits the pattern:
* template AliasSeq(T...) { alias AliasSeq = T; }
* or set isTrivialAlias if this fits the pattern:
* template Alias(T) { alias Alias = qualifiers(T); }
*/
if (!(parameters && parameters.length == 1))
return;
auto ad = s.isAliasDeclaration();
if (!ad || !ad.type)
return;
auto ti = ad.type.isTypeIdentifier();
if (!ti || ti.idents.length != 0)
return;
if (auto ttp = (*parameters)[0].isTemplateTupleParameter())
{
if (ti.ident is ttp.ident &&
ti.mod == 0)
{
//printf("found isTrivialAliasSeq %s %s\n", s.toChars(), ad.type.toChars());
isTrivialAliasSeq = true;
}
}
else if (auto ttp = (*parameters)[0].isTemplateTypeParameter())
{
if (ti.ident is ttp.ident)
{
//printf("found isTrivialAlias %s %s\n", s.toChars(), ad.type.toChars());
isTrivialAlias = true;
}
}
}
override TemplateDeclaration syntaxCopy(Dsymbol)
{
//printf("TemplateDeclaration.syntaxCopy()\n");
TemplateParameters* p = null;
if (parameters)
{
p = new TemplateParameters(parameters.dim);
foreach (i, ref param; *p)
param = (*parameters)[i].syntaxCopy();
}
return new TemplateDeclaration(loc, ident, p, constraint ? constraint.syntaxCopy() : null, Dsymbol.arraySyntaxCopy(members), ismixin, literal);
}
/**********************************
* Overload existing TemplateDeclaration 'this' with the new one 's'.
* Return true if successful; i.e. no conflict.
*/
override bool overloadInsert(Dsymbol s)
{
static if (LOG)
{
printf("TemplateDeclaration.overloadInsert('%s')\n", s.toChars());
}
FuncDeclaration fd = s.isFuncDeclaration();
if (fd)
{
if (funcroot)
return funcroot.overloadInsert(fd);
funcroot = fd;
return funcroot.overloadInsert(this);
}
// https://issues.dlang.org/show_bug.cgi?id=15795
// if candidate is an alias and its sema is not run then
// insertion can fail because the thing it alias is not known
if (AliasDeclaration ad = s.isAliasDeclaration())
{
if (s._scope)
aliasSemantic(ad, s._scope);
if (ad.aliassym && ad.aliassym is this)
return false;
}
TemplateDeclaration td = s.toAlias().isTemplateDeclaration();
if (!td)
return false;
TemplateDeclaration pthis = this;
TemplateDeclaration* ptd;
for (ptd = &pthis; *ptd; ptd = &(*ptd).overnext)
{
}
td.overroot = this;
*ptd = td;
static if (LOG)
{
printf("\ttrue: no conflict\n");
}
return true;
}
override bool hasStaticCtorOrDtor()
{
return false; // don't scan uninstantiated templates
}
override const(char)* kind() const
{
return (onemember && onemember.isAggregateDeclaration()) ? onemember.kind() : "template";
}
override const(char)* toChars() const
{
return toCharsMaybeConstraints(true);
}
/****************************
* Similar to `toChars`, but does not print the template constraints
*/
const(char)* toCharsNoConstraints() const
{
return toCharsMaybeConstraints(false);
}
const(char)* toCharsMaybeConstraints(bool includeConstraints) const
{
if (literal)
return Dsymbol.toChars();
OutBuffer buf;
HdrGenState hgs;
buf.writestring(ident.toString());
buf.writeByte('(');
foreach (i, const tp; *parameters)
{
if (i)
buf.writestring(", ");
.toCBuffer(tp, &buf, &hgs);
}
buf.writeByte(')');
if (onemember)
{
const FuncDeclaration fd = onemember.isFuncDeclaration();
if (fd && fd.type)
{
TypeFunction tf = cast(TypeFunction)fd.type;
buf.writestring(parametersTypeToChars(tf.parameterList));
}
}
if (includeConstraints &&
constraint)
{
buf.writestring(" if (");
.toCBuffer(constraint, &buf, &hgs);
buf.writeByte(')');
}
return buf.extractChars();
}
override Visibility visible() pure nothrow @nogc @safe
{
return visibility;
}
/****************************
* Check to see if constraint is satisfied.
*/
extern (D) bool evaluateConstraint(TemplateInstance ti, Scope* sc, Scope* paramscope, Objects* dedargs, FuncDeclaration fd)
{
/* Detect recursive attempts to instantiate this template declaration,
* https://issues.dlang.org/show_bug.cgi?id=4072
* void foo(T)(T x) if (is(typeof(foo(x)))) { }
* static assert(!is(typeof(foo(7))));
* Recursive attempts are regarded as a constraint failure.
*/
/* There's a chicken-and-egg problem here. We don't know yet if this template
* instantiation will be a local one (enclosing is set), and we won't know until
* after selecting the correct template. Thus, function we're nesting inside
* is not on the sc scope chain, and this can cause errors in FuncDeclaration.getLevel().
* Workaround the problem by setting a flag to relax the checking on frame errors.
*/
for (TemplatePrevious* p = previous; p; p = p.prev)
{
if (!arrayObjectMatch(p.dedargs, dedargs))
continue;
//printf("recursive, no match p.sc=%p %p %s\n", p.sc, this, this.toChars());
/* It must be a subscope of p.sc, other scope chains are not recursive
* instantiations.
* the chain of enclosing scopes is broken by paramscope (its enclosing
* scope is _scope, but paramscope.callsc is the instantiating scope). So
* it's good enough to check the chain of callsc
*/
for (Scope* scx = paramscope.callsc; scx; scx = scx.callsc)
{
// The first scx might be identical for nested eponymeous templates, e.g.
// template foo() { void foo()() {...} }
if (scx == p.sc && scx !is paramscope.callsc)
return false;
}
/* BUG: should also check for ref param differences
*/
}
TemplatePrevious pr;
pr.prev = previous;
pr.sc = paramscope.callsc;
pr.dedargs = dedargs;
previous = ≺ // add this to threaded list
Scope* scx = paramscope.push(ti);
scx.parent = ti;
scx.tinst = null;
scx.minst = null;
assert(!ti.symtab);
if (fd)
{
/* Declare all the function parameters as variables and add them to the scope
* Making parameters is similar to FuncDeclaration.semantic3
*/
TypeFunction tf = cast(TypeFunction)fd.type;
assert(tf.ty == Tfunction);
scx.parent = fd;
Parameters* fparameters = tf.parameterList.parameters;
const nfparams = tf.parameterList.length;
foreach (i, fparam; tf.parameterList)
{
fparam.storageClass &= (STC.IOR | STC.lazy_ | STC.final_ | STC.TYPECTOR | STC.nodtor);
fparam.storageClass |= STC.parameter;
if (tf.parameterList.varargs == VarArg.typesafe && i + 1 == nfparams)
{
fparam.storageClass |= STC.variadic;
/* Don't need to set STC.scope_ because this will only
* be evaluated at compile time
*/
}
}
foreach (fparam; *fparameters)
{
if (!fparam.ident)
continue;
// don't add it, if it has no name
auto v = new VarDeclaration(loc, fparam.type, fparam.ident, null);
fparam.storageClass |= STC.parameter;
v.storage_class = fparam.storageClass;
v.dsymbolSemantic(scx);
if (!ti.symtab)
ti.symtab = new DsymbolTable();
if (!scx.insert(v))
error("parameter `%s.%s` is already defined", toChars(), v.toChars());
else
v.parent = fd;
}
if (isstatic)
fd.storage_class |= STC.static_;
fd.declareThis(scx);
}
lastConstraint = constraint.syntaxCopy();
lastConstraintTiargs = ti.tiargs;
lastConstraintNegs.setDim(0);
import dmd.staticcond;
assert(ti.inst is null);
ti.inst = ti; // temporary instantiation to enable genIdent()
scx.flags |= SCOPE.constraint;
bool errors;
const bool result = evalStaticCondition(scx, constraint, lastConstraint, errors, &lastConstraintNegs);
if (result || errors)
{
lastConstraint = null;
lastConstraintTiargs = null;
lastConstraintNegs.setDim(0);
}
ti.inst = null;
ti.symtab = null;
scx = scx.pop();
previous = pr.prev; // unlink from threaded list
if (errors)
return false;
return result;
}
/****************************
* Destructively get the error message from the last constraint evaluation
* Params:
* tip = tip to show after printing all overloads
*/
const(char)* getConstraintEvalError(ref const(char)* tip)
{
import dmd.staticcond;
// there will be a full tree view in verbose mode, and more compact list in the usual
const full = global.params.verbose;
uint count;
const msg = visualizeStaticCondition(constraint, lastConstraint, lastConstraintNegs[], full, count);
scope (exit)
{
lastConstraint = null;
lastConstraintTiargs = null;
lastConstraintNegs.setDim(0);
}
if (!msg)
return null;
OutBuffer buf;
assert(parameters && lastConstraintTiargs);
if (parameters.length > 0)
{
formatParamsWithTiargs(*lastConstraintTiargs, buf);
buf.writenl();
}
if (!full)
{
// choosing singular/plural
const s = (count == 1) ?
" must satisfy the following constraint:" :
" must satisfy one of the following constraints:";
buf.writestring(s);
buf.writenl();
// the constraints
buf.writeByte('`');
buf.writestring(msg);
buf.writeByte('`');
}
else
{
buf.writestring(" whose parameters have the following constraints:");
buf.writenl();
const sep = " `~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`";
buf.writestring(sep);
buf.writenl();
// the constraints
buf.writeByte('`');
buf.writestring(msg);
buf.writeByte('`');
buf.writestring(sep);
tip = "not satisfied constraints are marked with `>`";
}
return buf.extractChars();
}
private void formatParamsWithTiargs(ref Objects tiargs, ref OutBuffer buf)
{
buf.writestring(" with `");
// write usual arguments line-by-line
// skips trailing default ones - they are not present in `tiargs`
const bool variadic = isVariadic() !is null;
const end = cast(int)parameters.length - (variadic ? 1 : 0);
uint i;
for (; i < tiargs.length && i < end; i++)
{
if (i > 0)
{
buf.writeByte(',');
buf.writenl();
buf.writestring(" ");
}
buf.write((*parameters)[i]);
buf.writestring(" = ");
buf.write(tiargs[i]);
}
// write remaining variadic arguments on the last line
if (variadic)
{
if (i > 0)
{
buf.writeByte(',');
buf.writenl();
buf.writestring(" ");
}
buf.write((*parameters)[end]);
buf.writestring(" = ");
buf.writeByte('(');
if (cast(int)tiargs.length - end > 0)
{
buf.write(tiargs[end]);
foreach (j; parameters.length .. tiargs.length)
{