Debian Codegraph @

gcc/d/dmd/dtemplate.d

raw
1 /**
2 * Defines `TemplateDeclaration`, `TemplateInstance` and a few utilities
3 *
4 * This modules holds the two main template types:
5 * `TemplateDeclaration`, which is the user-provided declaration of a template,
6 * and `TemplateInstance`, which is an instance of a `TemplateDeclaration`
7 * with specific arguments.
8 *
9 * Template_Parameter:
10 * Additionally, the classes for template parameters are defined in this module.
11 * The base class, `TemplateParameter`, is inherited by:
12 * - `TemplateTypeParameter`
13 * - `TemplateThisParameter`
14 * - `TemplateValueParameter`
15 * - `TemplateAliasParameter`
16 * - `TemplateTupleParameter`
17 *
18 * Templates_semantic:
19 * The start of the template instantiation process looks like this:
20 * - A `TypeInstance` or `TypeIdentifier` is encountered.
21 * `TypeInstance` have a bang (e.g. `Foo!(arg)`) while `TypeIdentifier` don't.
22 * - A `TemplateInstance` is instantiated
23 * - Semantic is run on the `TemplateInstance` (see `dmd.dsymbolsem`)
24 * - The `TemplateInstance` search for its `TemplateDeclaration`,
25 * runs semantic on the template arguments and deduce the best match
26 * among the possible overloads.
27 * - The `TemplateInstance` search for existing instances with the same
28 * arguments, and uses it if found.
29 * - Otherwise, the rest of semantic is run on the `TemplateInstance`.
30 *
31 * Copyright: Copyright (C) 1999-2025 by The D Language Foundation, All Rights Reserved
32 * Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
33 * License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
34 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/compiler/src/dmd/dtemplate.d, _dtemplate.d)
35 * Documentation: https://dlang.org/phobos/dmd_dtemplate.html
36 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/dtemplate.d
37 */
38
39 module dmd.dtemplate;
40
41 import core.stdc.stdio;
42 import core.stdc.string;
43 import dmd.aggregate;
44 import dmd.aliasthis;
45 import dmd.arraytypes;
46 import dmd.astenums;
47 import dmd.ast_node;
48 import dmd.attrib;
49 import dmd.dcast;
50 import dmd.dclass;
51 import dmd.declaration;
52 import dmd.dinterpret;
53 import dmd.dmodule;
54 import dmd.dscope;
55 import dmd.dsymbol;
56 import dmd.dsymbolsem : dsymbolSemantic, checkDeprecated, aliasSemantic, search, search_correct, setScope, importAll, include, hasStaticCtorOrDtor;
57 import dmd.errors;
58 import dmd.errorsink;
59 import dmd.expression;
60 import dmd.expressionsem : resolveLoc, expressionSemantic, resolveProperties, checkValue;
61 import dmd.func;
62 import dmd.funcsem : functionSemantic, leastAsSpecialized, overloadApply;
63 import dmd.globals;
64 import dmd.hdrgen;
65 import dmd.id;
66 import dmd.identifier;
67 import dmd.impcnvtab;
68 import dmd.init;
69 import dmd.location;
70 import dmd.mangle;
71 import dmd.mtype;
72 import dmd.opover;
73 import dmd.optimize;
74 import dmd.root.array;
75 import dmd.common.outbuffer;
76 import dmd.rootobject;
77 import dmd.semantic3 : semantic3;
78 import dmd.templatesem : matchWithInstance, formatParamsWithTiargs, leastAsSpecialized, declareParameter;
79 import dmd.tokens;
80 import dmd.typesem : hasPointers, typeSemantic, merge, merge2, resolve, toDsymbol,
81 addStorageClass, isBaseOf, equivalent, sarrayOf, constOf, mutableOf, unSharedOf,
82 unqualify, aliasthisOf, castMod, substWildTo, addMod;
83 import dmd.visitor;
84
85 import dmd.templateparamsem;
86
87 //debug = FindExistingInstance; // print debug stats of findExistingInstance
88 private enum LOG = false;
89
90 enum IDX_NOTFOUND = 0x12345678;
91
92 pure nothrow @nogc @trusted
93 {
94
95 /********************************************
96 * These functions substitute for dynamic_cast. dynamic_cast does not work
97 * on earlier versions of gcc.
98 */
99 inout(Expression) isExpression(inout RootObject o)
100 {
101 //return dynamic_cast<Expression *>(o);
102 if (!o || o.dyncast() != DYNCAST.expression)
103 return null;
104 return cast(inout(Expression))o;
105 }
106
107 inout(Dsymbol) isDsymbol(inout RootObject o)
108 {
109 //return dynamic_cast<Dsymbol *>(o);
110 if (!o || o.dyncast() != DYNCAST.dsymbol)
111 return null;
112 return cast(inout(Dsymbol))o;
113 }
114
115 inout(Type) isType(inout RootObject o)
116 {
117 //return dynamic_cast<Type *>(o);
118 if (!o || o.dyncast() != DYNCAST.type)
119 return null;
120 return cast(inout(Type))o;
121 }
122
123 inout(Tuple) isTuple(inout RootObject o)
124 {
125 //return dynamic_cast<Tuple *>(o);
126 if (!o || o.dyncast() != DYNCAST.tuple)
127 return null;
128 return cast(inout(Tuple))o;
129 }
130
131 inout(Parameter) isParameter(inout RootObject o)
132 {
133 //return dynamic_cast<Parameter *>(o);
134 if (!o || o.dyncast() != DYNCAST.parameter)
135 return null;
136 return cast(inout(Parameter))o;
137 }
138
139 inout(Identifier) isIdentifier(inout RootObject o)
140 {
141 if (!o || o.dyncast() != DYNCAST.identifier)
142 return null;
143 return cast(inout(Identifier))o;
144 }
145
146 inout(TemplateParameter) isTemplateParameter(inout RootObject o)
147 {
148 if (!o || o.dyncast() != DYNCAST.templateparameter)
149 return null;
150 return cast(inout(TemplateParameter))o;
151 }
152
153 } // end @trusted casts
154
155 pure nothrow @nogc @safe
156 {
157
158 /**************************************
159 * Is this Object an error?
160 */
161 bool isError(const RootObject o)
162 {
163 if (const t = isType(o))
164 return (t.ty == Terror);
165 if (const e = isExpression(o))
166 return (e.op == EXP.error || !e.type || e.type.ty == Terror);
167 if (const v = isTuple(o))
168 return arrayObjectIsError(v.objects);
169 const s = isDsymbol(o);
170 assert(s);
171 if (s.errors)
172 return true;
173 return s.parent ? isError(s.parent) : false;
174 }
175
176 /**************************************
177 * Are any of the Objects an error?
178 */
179 bool arrayObjectIsError(const ref Objects args)
180 {
181 foreach (const o; args)
182 {
183 if (isError(o))
184 return true;
185 }
186 return false;
187 }
188
189 /***********************
190 * Try to get arg as a type.
191 */
192 inout(Type) getType(inout RootObject o)
193 {
194 inout t = isType(o);
195 if (!t)
196 {
197 if (inout e = isExpression(o))
198 return e.type;
199 }
200 return t;
201 }
202
203 }
204
205 /***********************************
206 * If oarg represents a Dsymbol, return that Dsymbol
207 * Params:
208 * oarg = argument to check
209 * Returns:
210 * Dsymbol if a symbol, null if not
211 */
212 Dsymbol getDsymbol(RootObject oarg)
213 {
214 //printf("getDsymbol()\n");
215 //printf("e %p s %p t %p v %p\n", isExpression(oarg), isDsymbol(oarg), isType(oarg), isTuple(oarg));
216 if (auto ea = isExpression(oarg))
217 {
218 // Try to convert Expression to symbol
219 if (auto ve = ea.isVarExp())
220 return ve.var;
221 if (auto fe = ea.isFuncExp())
222 return fe.td ? fe.td : fe.fd;
223 if (auto te = ea.isTemplateExp())
224 return te.td;
225 if (auto te = ea.isScopeExp())
226 return te.sds;
227 return null;
228 }
229 // Try to convert Type to symbol
230 if (auto ta = isType(oarg))
231 return ta.toDsymbol(null);
232 return isDsymbol(oarg); // if already a symbol
233 }
234
235
236 private Expression getValue(ref Dsymbol s)
237 {
238 if (s)
239 {
240 if (VarDeclaration v = s.isVarDeclaration())
241 {
242 if (v.storage_class & STC.manifest)
243 return v.getConstInitializer();
244 }
245 }
246 return null;
247 }
248
249 /***********************
250 * Try to get value from manifest constant
251 */
252 private Expression getValue(Expression e)
253 {
254 if (!e)
255 return null;
256 if (auto ve = e.isVarExp())
257 {
258 if (auto v = ve.var.isVarDeclaration())
259 {
260 if (v.storage_class & STC.manifest)
261 {
262 e = v.getConstInitializer();
263 }
264 }
265 }
266 return e;
267 }
268
269 private Expression getExpression(RootObject o)
270 {
271 auto s = isDsymbol(o);
272 return s ? .getValue(s) : .getValue(isExpression(o));
273 }
274
275 /******************************
276 * See if two objects match
277 * Params:
278 * o1 = first object
279 * o2 = second object
280 * Returns: true if they match
281 */
282 private bool match(RootObject o1, RootObject o2)
283 {
284 enum log = false;
285
286 static if (log)
287 {
288 printf("match() o1 = %p %s (%d), o2 = %p %s (%d)\n",
289 o1, o1.toChars(), o1.dyncast(), o2, o2.toChars(), o2.dyncast());
290 }
291
292 bool yes()
293 {
294 static if (log)
295 printf("\t. match\n");
296 return true;
297 }
298 bool no()
299 {
300 static if (log)
301 printf("\t. nomatch\n");
302 return false;
303 }
304 /* A proper implementation of the various equals() overrides
305 * should make it possible to just do o1.equals(o2), but
306 * we'll do that another day.
307 */
308 /* Manifest constants should be compared by their values,
309 * at least in template arguments.
310 */
311
312 if (auto t1 = isType(o1))
313 {
314 auto t2 = isType(o2);
315 if (!t2)
316 return no();
317
318 static if (log)
319 {
320 printf("\tt1 = %s\n", t1.toChars());
321 printf("\tt2 = %s\n", t2.toChars());
322 }
323 if (!t1.equals(t2))
324 return no();
325
326 return yes();
327 }
328 if (auto e1 = getExpression(o1))
329 {
330 auto e2 = getExpression(o2);
331 if (!e2)
332 return no();
333
334 static if (log)
335 {
336 printf("\te1 = %s '%s' %s\n", e1.type ? e1.type.toChars() : "null", EXPtoString(e1.op).ptr, e1.toChars());
337 printf("\te2 = %s '%s' %s\n", e2.type ? e2.type.toChars() : "null", EXPtoString(e2.op).ptr, e2.toChars());
338 }
339
340 // two expressions can be equal although they do not have the same
341 // type; that happens when they have the same value. So check type
342 // as well as expression equality to ensure templates are properly
343 // matched.
344 if (!(e1.type && e2.type && e1.type.equals(e2.type)) || !e1.equals(e2))
345 return no();
346
347 return yes();
348 }
349 if (auto s1 = isDsymbol(o1))
350 {
351 auto s2 = isDsymbol(o2);
352 if (!s2)
353 return no();
354
355 static if (log)
356 {
357 printf("\ts1 = %s \n", s1.kind(), s1.toChars());
358 printf("\ts2 = %s \n", s2.kind(), s2.toChars());
359 }
360 if (!s1.equals(s2))
361 return no();
362 if (s1.parent != s2.parent && !s1.isFuncDeclaration() && !s2.isFuncDeclaration())
363 return no();
364
365 return yes();
366 }
367 if (auto u1 = isTuple(o1))
368 {
369 auto u2 = isTuple(o2);
370 if (!u2)
371 return no();
372
373 static if (log)
374 {
375 printf("\tu1 = %s\n", u1.toChars());
376 printf("\tu2 = %s\n", u2.toChars());
377 }
378 if (!arrayObjectMatch(u1.objects, u2.objects))
379 return no();
380
381 return yes();
382 }
383 return yes();
384 }
385
386 /************************************
387 * Match an array of them.
388 */
389 bool arrayObjectMatch(ref Objects oa1, ref Objects oa2)
390 {
391 if (&oa1 == &oa2)
392 return true;
393 if (oa1.length != oa2.length)
394 return false;
395 immutable oa1dim = oa1.length;
396 auto oa1d = oa1[].ptr;
397 auto oa2d = oa2[].ptr;
398 foreach (j; 0 .. oa1dim)
399 {
400 RootObject o1 = oa1d[j];
401 RootObject o2 = oa2d[j];
402 if (!match(o1, o2))
403 {
404 return false;
405 }
406 }
407 return true;
408 }
409
410 /************************************
411 * Return hash of Objects.
412 */
413 private size_t arrayObjectHash(ref Objects oa1)
414 {
415 import dmd.root.hash : mixHash;
416
417 size_t hash = 0;
418 foreach (o1; oa1)
419 {
420 /* Must follow the logic of match()
421 */
422 if (auto t1 = isType(o1))
423 hash = mixHash(hash, cast(size_t)t1.deco);
424 else if (auto e1 = getExpression(o1))
425 hash = mixHash(hash, expressionHash(e1));
426 else if (auto s1 = isDsymbol(o1))
427 {
428 if (auto fa1 = s1.isFuncAliasDeclaration())
429 s1 = fa1.toAliasFunc();
430 hash = mixHash(hash, mixHash(cast(size_t)cast(void*)s1.getIdent(), cast(size_t)cast(void*)s1.parent));
431 }
432 else if (auto u1 = isTuple(o1))
433 hash = mixHash(hash, arrayObjectHash(u1.objects));
434 }
435 return hash;
436 }
437
438
439 /************************************
440 * Computes hash of expression.
441 * Handles all Expression classes and MUST match their equals method,
442 * i.e. e1.equals(e2) implies expressionHash(e1) == expressionHash(e2).
443 */
444 private size_t expressionHash(Expression e)
445 {
446 import dmd.root.ctfloat : CTFloat;
447 import dmd.root.hash : calcHash, mixHash;
448
449 switch (e.op)
450 {
451 case EXP.int64:
452 return cast(size_t) e.isIntegerExp().getInteger();
453
454 case EXP.float64:
455 return CTFloat.hash(e.isRealExp().value);
456
457 case EXP.complex80:
458 auto ce = e.isComplexExp();
459 return mixHash(CTFloat.hash(ce.toReal), CTFloat.hash(ce.toImaginary));
460
461 case EXP.identifier:
462 return cast(size_t)cast(void*) e.isIdentifierExp().ident;
463
464 case EXP.null_:
465 return cast(size_t)cast(void*) e.isNullExp().type;
466
467 case EXP.string_:
468 return calcHash(e.isStringExp.peekData());
469
470 case EXP.tuple:
471 {
472 auto te = e.isTupleExp();
473 size_t hash = 0;
474 hash += te.e0 ? expressionHash(te.e0) : 0;
475 foreach (elem; *te.exps)
476 hash = mixHash(hash, expressionHash(elem));
477 return hash;
478 }
479
480 case EXP.arrayLiteral:
481 {
482 auto ae = e.isArrayLiteralExp();
483 size_t hash;
484 foreach (i; 0 .. ae.elements.length)
485 hash = mixHash(hash, expressionHash(ae[i]));
486 return hash;
487 }
488
489 case EXP.assocArrayLiteral:
490 {
491 auto ae = e.isAssocArrayLiteralExp();
492 size_t hash;
493 foreach (i; 0 .. ae.keys.length)
494 // reduction needs associative op as keys are unsorted (use XOR)
495 hash ^= mixHash(expressionHash((*ae.keys)[i]), expressionHash((*ae.values)[i]));
496 return hash;
497 }
498
499 case EXP.structLiteral:
500 {
501 auto se = e.isStructLiteralExp();
502 size_t hash;
503 foreach (elem; *se.elements)
504 hash = mixHash(hash, elem ? expressionHash(elem) : 0);
505 return hash;
506 }
507
508 case EXP.variable:
509 return cast(size_t)cast(void*) e.isVarExp().var;
510
511 case EXP.function_:
512 return cast(size_t)cast(void*) e.isFuncExp().fd;
513
514 default:
515 // no custom equals for this expression
516 assert((&e.equals).funcptr is &RootObject.equals);
517 // equals based on identity
518 return cast(size_t)cast(void*) e;
519 }
520 }
521
522 RootObject objectSyntaxCopy(RootObject o)
523 {
524 if (!o)
525 return null;
526 if (Type t = isType(o))
527 return t.syntaxCopy();
528 if (Expression e = isExpression(o))
529 return e.syntaxCopy();
530 return o;
531 }
532
533 extern (C++) final class Tuple : RootObject
534 {
535 Objects objects;
536
537 extern (D) this() {}
538
539 /**
540 Params:
541 numObjects = The initial number of objects.
542 */
543 extern (D) this(size_t numObjects)
544 {
545 objects.setDim(numObjects);
546 }
547
548 // kludge for template.isType()
549 override DYNCAST dyncast() const
550 {
551 return DYNCAST.tuple;
552 }
553
554 override const(char)* toChars() const
555 {
556 return objects.toChars();
557 }
558 }
559
560 struct TemplatePrevious
561 {
562 TemplatePrevious* prev;
563 Scope* sc;
564 Objects* dedargs;
565 }
566
567 /***********************************************************
568 * [mixin] template Identifier (parameters) [Constraint]
569 * https://dlang.org/spec/template.html
570 * https://dlang.org/spec/template-mixin.html
571 */
572 extern (C++) final class TemplateDeclaration : ScopeDsymbol
573 {
574 import dmd.root.array : Array;
575
576 TemplateParameters* parameters; // array of TemplateParameter's
577 TemplateParameters* origParameters; // originals for Ddoc
578
579 Expression constraint;
580
581 // Hash table to look up TemplateInstance's of this TemplateDeclaration
582 TemplateInstance[TemplateInstanceBox] instances;
583
584 TemplateDeclaration overnext; // next overloaded TemplateDeclaration
585 TemplateDeclaration overroot; // first in overnext list
586 FuncDeclaration funcroot; // first function in unified overload list
587
588 Dsymbol onemember; // if !=null then one member of this template
589
590 bool literal; // this template declaration is a literal
591 bool ismixin; // this is a mixin template declaration
592 bool isstatic; // this is static template declaration
593 bool isTrivialAliasSeq; /// matches pattern `template AliasSeq(T...) { alias AliasSeq = T; }`
594 bool isTrivialAlias; /// matches pattern `template Alias(T) { alias Alias = qualifiers(T); }`
595 bool deprecated_; /// this template declaration is deprecated
596 Visibility visibility;
597
598 // threaded list of previous instantiation attempts on stack
599 TemplatePrevious* previous;
600
601 Expression lastConstraint; /// the constraint after the last failed evaluation
602 Array!Expression lastConstraintNegs; /// its negative parts
603 Objects* lastConstraintTiargs; /// template instance arguments for `lastConstraint`
604
605 extern (D) this(Loc loc, Identifier ident, TemplateParameters* parameters, Expression constraint, Dsymbols* decldefs, bool ismixin = false, bool literal = false)
606 {
607 super(loc, ident);
608 this.dsym = DSYM.templateDeclaration;
609 static if (LOG)
610 {
611 printf("TemplateDeclaration(this = %p, id = '%s')\n", this, ident.toChars());
612 }
613 version (none)
614 {
615 if (parameters)
616 for (int i = 0; i < parameters.length; i++)
617 {
618 TemplateParameter tp = (*parameters)[i];
619 //printf("\tparameter[%d] = %p\n", i, tp);
620 TemplateTypeParameter ttp = tp.isTemplateTypeParameter();
621 if (ttp)
622 {
623 printf("\tparameter[%d] = %s : %s\n", i, tp.ident.toChars(), ttp.specType ? ttp.specType.toChars() : "");
624 }
625 }
626 }
627 this.parameters = parameters;
628 this.origParameters = parameters;
629 this.constraint = constraint;
630 this.members = decldefs;
631 this.literal = literal;
632 this.ismixin = ismixin;
633 this.isstatic = true;
634 this.visibility = Visibility(Visibility.Kind.undefined);
635
636 // Compute in advance for Ddoc's use
637 // https://issues.dlang.org/show_bug.cgi?id=11153: ident could be NULL if parsing fails.
638 if (!members || !ident)
639 return;
640
641 Dsymbol s;
642 if (!Dsymbol.oneMembers(members, s, ident) || !s)
643 return;
644
645 onemember = s;
646 s.parent = this;
647
648 /* Set isTrivialAliasSeq if this fits the pattern:
649 * template AliasSeq(T...) { alias AliasSeq = T; }
650 * or set isTrivialAlias if this fits the pattern:
651 * template Alias(T) { alias Alias = qualifiers(T); }
652 */
653 if (!(parameters && parameters.length == 1))
654 return;
655
656 auto ad = s.isAliasDeclaration();
657 if (!ad || !ad.type)
658 return;
659
660 auto ti = ad.type.isTypeIdentifier();
661
662 if (!ti || ti.idents.length != 0)
663 return;
664
665 if (auto ttp = (*parameters)[0].isTemplateTupleParameter())
666 {
667 if (ti.ident is ttp.ident &&
668 ti.mod == 0)
669 {
670 //printf("found isTrivialAliasSeq %s %s\n", s.toChars(), ad.type.toChars());
671 isTrivialAliasSeq = true;
672 }
673 }
674 else if (auto ttp = (*parameters)[0].isTemplateTypeParameter())
675 {
676 if (ti.ident is ttp.ident)
677 {
678 //printf("found isTrivialAlias %s %s\n", s.toChars(), ad.type.toChars());
679 isTrivialAlias = true;
680 }
681 }
682 }
683
684 override TemplateDeclaration syntaxCopy(Dsymbol)
685 {
686 //printf("TemplateDeclaration.syntaxCopy()\n");
687 TemplateParameters* p = null;
688 if (parameters)
689 {
690 p = new TemplateParameters(parameters.length);
691 foreach (i, ref param; *p)
692 param = (*parameters)[i].syntaxCopy();
693 }
694 return new TemplateDeclaration(loc, ident, p, constraint ? constraint.syntaxCopy() : null, Dsymbol.arraySyntaxCopy(members), ismixin, literal);
695 }
696
697 /**********************************
698 * Overload existing TemplateDeclaration 'this' with the new one 's'.
699 * Params:
700 * s = symbol to be inserted
701 * Return: true if successful; i.e. no conflict.
702 */
703 override bool overloadInsert(Dsymbol s)
704 {
705 static if (LOG)
706 {
707 printf("TemplateDeclaration.overloadInsert('%s')\n", s.toChars());
708 }
709 FuncDeclaration fd = s.isFuncDeclaration();
710 if (fd)
711 {
712 if (funcroot)
713 return funcroot.overloadInsert(fd);
714 funcroot = fd;
715 return funcroot.overloadInsert(this);
716 }
717
718 // https://issues.dlang.org/show_bug.cgi?id=15795
719 // if candidate is an alias and its sema is not run then
720 // insertion can fail because the thing it alias is not known
721 if (AliasDeclaration ad = s.isAliasDeclaration())
722 {
723 if (s._scope)
724 aliasSemantic(ad, s._scope);
725 if (ad.aliassym && ad.aliassym is this)
726 return false;
727 }
728 TemplateDeclaration td = s.toAlias().isTemplateDeclaration();
729 if (!td)
730 return false;
731
732 TemplateDeclaration pthis = this;
733 TemplateDeclaration* ptd;
734 for (ptd = &pthis; *ptd; ptd = &(*ptd).overnext)
735 {
736 }
737
738 td.overroot = this;
739 *ptd = td;
740 static if (LOG)
741 {
742 printf("\ttrue: no conflict\n");
743 }
744 return true;
745 }
746
747 override const(char)* kind() const
748 {
749 return (onemember && onemember.isAggregateDeclaration()) ? onemember.kind() : "template";
750 }
751
752 /****************************
753 * Similar to `toChars`, but does not print the template constraints
754 */
755 const(char)* toCharsNoConstraints() const
756 {
757 HdrGenState hgs = { skipConstraints: true };
758 OutBuffer buf;
759 toCharsMaybeConstraints(this, buf, hgs);
760 return buf.extractChars();
761 }
762
763 override Visibility visible() pure nothrow @nogc @safe
764 {
765 return visibility;
766 }
767
768 /****************************
769 * Destructively get the error message from the last constraint evaluation
770 * Params:
771 * tip = tip to show after printing all overloads
772 */
773 const(char)* getConstraintEvalError(ref const(char)* tip)
774 {
775 import dmd.staticcond;
776
777 // there will be a full tree view in verbose mode, and more compact list in the usual
778 const full = global.params.v.verbose;
779 uint count;
780 const msg = visualizeStaticCondition(constraint, lastConstraint, lastConstraintNegs[], full, count);
781 scope (exit)
782 {
783 lastConstraint = null;
784 lastConstraintTiargs = null;
785 lastConstraintNegs.setDim(0);
786 }
787 if (!msg)
788 return null;
789
790 OutBuffer buf;
791
792 assert(parameters && lastConstraintTiargs);
793 if (parameters.length > 0)
794 {
795 formatParamsWithTiargs(*parameters, *lastConstraintTiargs, isVariadic() !is null, buf);
796 buf.writenl();
797 }
798 if (!full)
799 {
800 // choosing singular/plural
801 const s = (count == 1) ?
802 " must satisfy the following constraint:" :
803 " must satisfy one of the following constraints:";
804 buf.writestring(s);
805 buf.writenl();
806 // the constraints
807 buf.writeByte('`');
808 buf.writestring(msg);
809 buf.writeByte('`');
810 }
811 else
812 {
813 buf.writestring(" whose parameters have the following constraints:");
814 buf.writenl();
815 const sep = " `~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`";
816 buf.writestring(sep);
817 buf.writenl();
818 // the constraints
819 buf.writeByte('`');
820 buf.writestring(msg);
821 buf.writeByte('`');
822 buf.writestring(sep);
823 tip = "not satisfied constraints are marked with `>`";
824 }
825 return buf.extractChars();
826 }
827
828 debug (FindExistingInstance)
829 {
830 __gshared uint nFound, nNotFound, nAdded, nRemoved;
831
832 shared static ~this()
833 {
834 printf("debug (FindExistingInstance) nFound %u, nNotFound: %u, nAdded: %u, nRemoved: %u\n",
835 nFound, nNotFound, nAdded, nRemoved);
836 }
837 }
838
839 /****************************************************
840 * Given a new instance `tithis` of this TemplateDeclaration,
841 * see if there already exists an instance.
842 *
843 * Params:
844 * tithis = template instance to check
845 * argumentList = For function templates, needed because different
846 * `auto ref` resolutions create different instances,
847 * even when template parameters are identical
848 *
849 * Returns: that existing instance, or `null` when it doesn't exist
850 */
851 extern (D) TemplateInstance findExistingInstance(TemplateInstance tithis, ArgumentList argumentList)
852 {
853 //printf("findExistingInstance() %s\n", tithis.toChars());
854 tithis.fargs = argumentList.arguments;
855 tithis.fnames = argumentList.names;
856 auto tibox = TemplateInstanceBox(tithis);
857 auto p = tibox in this.instances;
858 debug (FindExistingInstance) ++(p ? nFound : nNotFound);
859 //if (p) printf("\tfound %p\n", *p); else printf("\tnot found\n");
860 return p ? *p : null;
861 }
862
863 /********************************************
864 * Add instance ti to TemplateDeclaration's table of instances.
865 * Return a handle we can use to later remove it if it fails instantiation.
866 */
867 extern (D) TemplateInstance addInstance(TemplateInstance ti)
868 {
869 //printf("addInstance() %p %s\n", instances, ti.toChars());
870 auto tibox = TemplateInstanceBox(ti);
871 instances[tibox] = ti;
872 debug (FindExistingInstance) ++nAdded;
873 return ti;
874 }
875
876 /*******************************************
877 * Remove TemplateInstance from table of instances.
878 * Input:
879 * handle returned by addInstance()
880 */
881 extern (D) void removeInstance(TemplateInstance ti)
882 {
883 //printf("removeInstance() %s\n", ti.toChars());
884 auto tibox = TemplateInstanceBox(ti);
885 debug (FindExistingInstance) ++nRemoved;
886 instances.remove(tibox);
887 }
888
889 /**
890 * Check if the last template parameter is a tuple one,
891 * and returns it if so, else returns `null`.
892 *
893 * Returns:
894 * The last template parameter if it's a `TemplateTupleParameter`
895 */
896 extern (D) TemplateTupleParameter isVariadic()
897 {
898 const dim = parameters.length;
899 if (dim == 0)
900 return null;
901 return (*parameters)[dim - 1].isTemplateTupleParameter();
902 }
903
904 extern(C++) override bool isDeprecated() const
905 {
906 return this.deprecated_;
907 }
908
909 /***********************************
910 * We can overload templates.
911 */
912 override bool isOverloadable() const
913 {
914 return true;
915 }
916
917 override void accept(Visitor v)
918 {
919 v.visit(this);
920 }
921 }
922
923 extern (C++) final class TypeDeduced : Type
924 {
925 Type tded;
926 Expressions argexps; // corresponding expressions
927 Types tparams; // tparams[i].mod
928
929 extern (D) this(Type tt, Expression e, Type tparam)
930 {
931 super(Tnone);
932 tded = tt;
933 argexps.push(e);
934 tparams.push(tparam);
935 }
936
937 void update(Expression e, Type tparam)
938 {
939 argexps.push(e);
940 tparams.push(tparam);
941 }
942
943 void update(Type tt, Expression e, Type tparam)
944 {
945 tded = tt;
946 argexps.push(e);
947 tparams.push(tparam);
948 }
949
950 MATCH matchAll(Type tt)
951 {
952 MATCH match = MATCH.exact;
953 foreach (j, e; argexps)
954 {
955 assert(e);
956 if (e == emptyArrayElement)
957 continue;
958
959 Type t = tt.addMod(tparams[j].mod).substWildTo(MODFlags.const_);
960
961 MATCH m = e.implicitConvTo(t);
962 if (match > m)
963 match = m;
964 if (match == MATCH.nomatch)
965 break;
966 }
967 return match;
968 }
969 }
970
971
972 /* ======================== Type ============================================ */
973
974 /****
975 * Given an identifier, figure out which TemplateParameter it is.
976 * Return IDX_NOTFOUND if not found.
977 */
978 private size_t templateIdentifierLookup(Identifier id, TemplateParameters* parameters)
979 {
980 for (size_t i = 0; i < parameters.length; i++)
981 {
982 TemplateParameter tp = (*parameters)[i];
983 if (tp.ident.equals(id))
984 return i;
985 }
986 return IDX_NOTFOUND;
987 }
988
989 size_t templateParameterLookup(Type tparam, TemplateParameters* parameters)
990 {
991 if (TypeIdentifier tident = tparam.isTypeIdentifier())
992 {
993 //printf("\ttident = '%s'\n", tident.toChars());
994 return templateIdentifierLookup(tident.ident, parameters);
995 }
996 return IDX_NOTFOUND;
997 }
998
999 private auto X(T, U)(T m, U n)
1000 {
1001 return (m << 4) | n;
1002 }
1003
1004 ubyte deduceWildHelper(Type t, Type* at, Type tparam)
1005 {
1006 if ((tparam.mod & MODFlags.wild) == 0)
1007 return 0;
1008
1009 *at = null;
1010
1011 switch (X(tparam.mod, t.mod))
1012 {
1013 case X(MODFlags.wild, 0):
1014 case X(MODFlags.wild, MODFlags.const_):
1015 case X(MODFlags.wild, MODFlags.shared_):
1016 case X(MODFlags.wild, MODFlags.shared_ | MODFlags.const_):
1017 case X(MODFlags.wild, MODFlags.immutable_):
1018 case X(MODFlags.wildconst, 0):
1019 case X(MODFlags.wildconst, MODFlags.const_):
1020 case X(MODFlags.wildconst, MODFlags.shared_):
1021 case X(MODFlags.wildconst, MODFlags.shared_ | MODFlags.const_):
1022 case X(MODFlags.wildconst, MODFlags.immutable_):
1023 case X(MODFlags.shared_ | MODFlags.wild, MODFlags.shared_):
1024 case X(MODFlags.shared_ | MODFlags.wild, MODFlags.shared_ | MODFlags.const_):
1025 case X(MODFlags.shared_ | MODFlags.wild, MODFlags.immutable_):
1026 case X(MODFlags.shared_ | MODFlags.wildconst, MODFlags.shared_):
1027 case X(MODFlags.shared_ | MODFlags.wildconst, MODFlags.shared_ | MODFlags.const_):
1028 case X(MODFlags.shared_ | MODFlags.wildconst, MODFlags.immutable_):
1029 {
1030 ubyte wm = (t.mod & ~MODFlags.shared_);
1031 if (wm == 0)
1032 wm = MODFlags.mutable;
1033 ubyte m = (t.mod & (MODFlags.const_ | MODFlags.immutable_)) | (tparam.mod & t.mod & MODFlags.shared_);
1034 *at = t.unqualify(m);
1035 return wm;
1036 }
1037 case X(MODFlags.wild, MODFlags.wild):
1038 case X(MODFlags.wild, MODFlags.wildconst):
1039 case X(MODFlags.wild, MODFlags.shared_ | MODFlags.wild):
1040 case X(MODFlags.wild, MODFlags.shared_ | MODFlags.wildconst):
1041 case X(MODFlags.wildconst, MODFlags.wild):
1042 case X(MODFlags.wildconst, MODFlags.wildconst):
1043 case X(MODFlags.wildconst, MODFlags.shared_ | MODFlags.wild):
1044 case X(MODFlags.wildconst, MODFlags.shared_ | MODFlags.wildconst):
1045 case X(MODFlags.shared_ | MODFlags.wild, MODFlags.shared_ | MODFlags.wild):
1046 case X(MODFlags.shared_ | MODFlags.wild, MODFlags.shared_ | MODFlags.wildconst):
1047 case X(MODFlags.shared_ | MODFlags.wildconst, MODFlags.shared_ | MODFlags.wild):
1048 case X(MODFlags.shared_ | MODFlags.wildconst, MODFlags.shared_ | MODFlags.wildconst):
1049 {
1050 *at = t.unqualify(tparam.mod & t.mod);
1051 return MODFlags.wild;
1052 }
1053 default:
1054 return 0;
1055 }
1056 }
1057
1058 /**
1059 * Returns the common type of the 2 types.
1060 */
1061 private Type rawTypeMerge(Type t1, Type t2)
1062 {
1063 if (t1.equals(t2))
1064 return t1;
1065 if (t1.equivalent(t2))
1066 return t1.castMod(MODmerge(t1.mod, t2.mod));
1067
1068 auto t1b = t1.toBasetype();
1069 auto t2b = t2.toBasetype();
1070 if (t1b.equals(t2b))
1071 return t1b;
1072 if (t1b.equivalent(t2b))
1073 return t1b.castMod(MODmerge(t1b.mod, t2b.mod));
1074
1075 auto ty = implicitConvCommonTy(t1b.ty, t2b.ty);
1076 if (ty != Terror)
1077 return Type.basic[ty];
1078
1079 return null;
1080 }
1081
1082 MATCH deduceTypeHelper(Type t, out Type at, Type tparam)
1083 {
1084 // 9*9 == 81 cases
1085 switch (X(tparam.mod, t.mod))
1086 {
1087 case X(0, 0):
1088 case X(0, MODFlags.const_):
1089 case X(0, MODFlags.wild):
1090 case X(0, MODFlags.wildconst):
1091 case X(0, MODFlags.shared_):
1092 case X(0, MODFlags.shared_ | MODFlags.const_):
1093 case X(0, MODFlags.shared_ | MODFlags.wild):
1094 case X(0, MODFlags.shared_ | MODFlags.wildconst):
1095 case X(0, MODFlags.immutable_):
1096 // foo(U) T => T
1097 // foo(U) const(T) => const(T)
1098 // foo(U) inout(T) => inout(T)
1099 // foo(U) inout(const(T)) => inout(const(T))
1100 // foo(U) shared(T) => shared(T)
1101 // foo(U) shared(const(T)) => shared(const(T))
1102 // foo(U) shared(inout(T)) => shared(inout(T))
1103 // foo(U) shared(inout(const(T))) => shared(inout(const(T)))
1104 // foo(U) immutable(T) => immutable(T)
1105 {
1106 at = t;
1107 return MATCH.exact;
1108 }
1109 case X(MODFlags.const_, MODFlags.const_):
1110 case X(MODFlags.wild, MODFlags.wild):
1111 case X(MODFlags.wildconst, MODFlags.wildconst):
1112 case X(MODFlags.shared_, MODFlags.shared_):
1113 case X(MODFlags.shared_ | MODFlags.const_, MODFlags.shared_ | MODFlags.const_):
1114 case X(MODFlags.shared_ | MODFlags.wild, MODFlags.shared_ | MODFlags.wild):
1115 case X(MODFlags.shared_ | MODFlags.wildconst, MODFlags.shared_ | MODFlags.wildconst):
1116 case X(MODFlags.immutable_, MODFlags.immutable_):
1117 // foo(const(U)) const(T) => T
1118 // foo(inout(U)) inout(T) => T
1119 // foo(inout(const(U))) inout(const(T)) => T
1120 // foo(shared(U)) shared(T) => T
1121 // foo(shared(const(U))) shared(const(T)) => T
1122 // foo(shared(inout(U))) shared(inout(T)) => T
1123 // foo(shared(inout(const(U)))) shared(inout(const(T))) => T
1124 // foo(immutable(U)) immutable(T) => T
1125 {
1126 at = t.mutableOf().unSharedOf();
1127 return MATCH.exact;
1128 }
1129 case X(MODFlags.const_, MODFlags.shared_ | MODFlags.const_):
1130 case X(MODFlags.wild, MODFlags.shared_ | MODFlags.wild):
1131 case X(MODFlags.wildconst, MODFlags.shared_ | MODFlags.wildconst):
1132 // foo(const(U)) shared(const(T)) => shared(T)
1133 // foo(inout(U)) shared(inout(T)) => shared(T)
1134 // foo(inout(const(U))) shared(inout(const(T))) => shared(T)
1135 {
1136 at = t.mutableOf();
1137 return MATCH.exact;
1138 }
1139 case X(MODFlags.const_, 0):
1140 case X(MODFlags.const_, MODFlags.wild):
1141 case X(MODFlags.const_, MODFlags.wildconst):
1142 case X(MODFlags.const_, MODFlags.shared_ | MODFlags.wild):
1143 case X(MODFlags.const_, MODFlags.shared_ | MODFlags.wildconst):
1144 case X(MODFlags.const_, MODFlags.immutable_):
1145 case X(MODFlags.shared_ | MODFlags.const_, MODFlags.immutable_):
1146 // foo(const(U)) T => T
1147 // foo(const(U)) inout(T) => T
1148 // foo(const(U)) inout(const(T)) => T
1149 // foo(const(U)) shared(inout(T)) => shared(T)
1150 // foo(const(U)) shared(inout(const(T))) => shared(T)
1151 // foo(const(U)) immutable(T) => T
1152 // foo(shared(const(U))) immutable(T) => T
1153 {
1154 at = t.mutableOf();
1155 return MATCH.constant;
1156 }
1157 case X(MODFlags.const_, MODFlags.shared_):
1158 // foo(const(U)) shared(T) => shared(T)
1159 {
1160 at = t;
1161 return MATCH.constant;
1162 }
1163 case X(MODFlags.shared_, MODFlags.shared_ | MODFlags.const_):
1164 case X(MODFlags.shared_, MODFlags.shared_ | MODFlags.wild):
1165 case X(MODFlags.shared_, MODFlags.shared_ | MODFlags.wildconst):
1166 // foo(shared(U)) shared(const(T)) => const(T)
1167 // foo(shared(U)) shared(inout(T)) => inout(T)
1168 // foo(shared(U)) shared(inout(const(T))) => inout(const(T))
1169 {
1170 at = t.unSharedOf();
1171 return MATCH.exact;
1172 }
1173 case X(MODFlags.shared_ | MODFlags.const_, MODFlags.shared_):
1174 // foo(shared(const(U))) shared(T) => T
1175 {
1176 at = t.unSharedOf();
1177 return MATCH.constant;
1178 }
1179 case X(MODFlags.wildconst, MODFlags.immutable_):
1180 case X(MODFlags.shared_ | MODFlags.const_, MODFlags.shared_ | MODFlags.wildconst):
1181 case X(MODFlags.shared_ | MODFlags.wildconst, MODFlags.immutable_):
1182 case X(MODFlags.shared_ | MODFlags.wildconst, MODFlags.shared_ | MODFlags.wild):
1183 // foo(inout(const(U))) immutable(T) => T
1184 // foo(shared(const(U))) shared(inout(const(T))) => T
1185 // foo(shared(inout(const(U)))) immutable(T) => T
1186 // foo(shared(inout(const(U)))) shared(inout(T)) => T
1187 {
1188 at = t.unSharedOf().mutableOf();
1189 return MATCH.constant;
1190 }
1191 case X(MODFlags.shared_ | MODFlags.const_, MODFlags.shared_ | MODFlags.wild):
1192 // foo(shared(const(U))) shared(inout(T)) => T
1193 {
1194 at = t.unSharedOf().mutableOf();
1195 return MATCH.constant;
1196 }
1197 case X(MODFlags.wild, 0):
1198 case X(MODFlags.wild, MODFlags.const_):
1199 case X(MODFlags.wild, MODFlags.wildconst):
1200 case X(MODFlags.wild, MODFlags.immutable_):
1201 case X(MODFlags.wild, MODFlags.shared_):
1202 case X(MODFlags.wild, MODFlags.shared_ | MODFlags.const_):
1203 case X(MODFlags.wild, MODFlags.shared_ | MODFlags.wildconst):
1204 case X(MODFlags.wildconst, 0):
1205 case X(MODFlags.wildconst, MODFlags.const_):
1206 case X(MODFlags.wildconst, MODFlags.wild):
1207 case X(MODFlags.wildconst, MODFlags.shared_):
1208 case X(MODFlags.wildconst, MODFlags.shared_ | MODFlags.const_):
1209 case X(MODFlags.wildconst, MODFlags.shared_ | MODFlags.wild):
1210 case X(MODFlags.shared_, 0):
1211 case X(MODFlags.shared_, MODFlags.const_):
1212 case X(MODFlags.shared_, MODFlags.wild):
1213 case X(MODFlags.shared_, MODFlags.wildconst):
1214 case X(MODFlags.shared_, MODFlags.immutable_):
1215 case X(MODFlags.shared_ | MODFlags.const_, 0):
1216 case X(MODFlags.shared_ | MODFlags.const_, MODFlags.const_):
1217 case X(MODFlags.shared_ | MODFlags.const_, MODFlags.wild):
1218 case X(MODFlags.shared_ | MODFlags.const_, MODFlags.wildconst):
1219 case X(MODFlags.shared_ | MODFlags.wild, 0):
1220 case X(MODFlags.shared_ | MODFlags.wild, MODFlags.const_):
1221 case X(MODFlags.shared_ | MODFlags.wild, MODFlags.wild):
1222 case X(MODFlags.shared_ | MODFlags.wild, MODFlags.wildconst):
1223 case X(MODFlags.shared_ | MODFlags.wild, MODFlags.immutable_):
1224 case X(MODFlags.shared_ | MODFlags.wild, MODFlags.shared_):
1225 case X(MODFlags.shared_ | MODFlags.wild, MODFlags.shared_ | MODFlags.const_):
1226 case X(MODFlags.shared_ | MODFlags.wild, MODFlags.shared_ | MODFlags.wildconst):
1227 case X(MODFlags.shared_ | MODFlags.wildconst, 0):
1228 case X(MODFlags.shared_ | MODFlags.wildconst, MODFlags.const_):
1229 case X(MODFlags.shared_ | MODFlags.wildconst, MODFlags.wild):
1230 case X(MODFlags.shared_ | MODFlags.wildconst, MODFlags.wildconst):
1231 case X(MODFlags.shared_ | MODFlags.wildconst, MODFlags.shared_):
1232 case X(MODFlags.shared_ | MODFlags.wildconst, MODFlags.shared_ | MODFlags.const_):
1233 case X(MODFlags.immutable_, 0):
1234 case X(MODFlags.immutable_, MODFlags.const_):
1235 case X(MODFlags.immutable_, MODFlags.wild):
1236 case X(MODFlags.immutable_, MODFlags.wildconst):
1237 case X(MODFlags.immutable_, MODFlags.shared_):
1238 case X(MODFlags.immutable_, MODFlags.shared_ | MODFlags.const_):
1239 case X(MODFlags.immutable_, MODFlags.shared_ | MODFlags.wild):
1240 case X(MODFlags.immutable_, MODFlags.shared_ | MODFlags.wildconst):
1241 // foo(inout(U)) T => nomatch
1242 // foo(inout(U)) const(T) => nomatch
1243 // foo(inout(U)) inout(const(T)) => nomatch
1244 // foo(inout(U)) immutable(T) => nomatch
1245 // foo(inout(U)) shared(T) => nomatch
1246 // foo(inout(U)) shared(const(T)) => nomatch
1247 // foo(inout(U)) shared(inout(const(T))) => nomatch
1248 // foo(inout(const(U))) T => nomatch
1249 // foo(inout(const(U))) const(T) => nomatch
1250 // foo(inout(const(U))) inout(T) => nomatch
1251 // foo(inout(const(U))) shared(T) => nomatch
1252 // foo(inout(const(U))) shared(const(T)) => nomatch
1253 // foo(inout(const(U))) shared(inout(T)) => nomatch
1254 // foo(shared(U)) T => nomatch
1255 // foo(shared(U)) const(T) => nomatch
1256 // foo(shared(U)) inout(T) => nomatch
1257 // foo(shared(U)) inout(const(T)) => nomatch
1258 // foo(shared(U)) immutable(T) => nomatch
1259 // foo(shared(const(U))) T => nomatch
1260 // foo(shared(const(U))) const(T) => nomatch
1261 // foo(shared(const(U))) inout(T) => nomatch
1262 // foo(shared(const(U))) inout(const(T)) => nomatch
1263 // foo(shared(inout(U))) T => nomatch
1264 // foo(shared(inout(U))) const(T) => nomatch
1265 // foo(shared(inout(U))) inout(T) => nomatch
1266 // foo(shared(inout(U))) inout(const(T)) => nomatch
1267 // foo(shared(inout(U))) immutable(T) => nomatch
1268 // foo(shared(inout(U))) shared(T) => nomatch
1269 // foo(shared(inout(U))) shared(const(T)) => nomatch
1270 // foo(shared(inout(U))) shared(inout(const(T))) => nomatch
1271 // foo(shared(inout(const(U)))) T => nomatch
1272 // foo(shared(inout(const(U)))) const(T) => nomatch
1273 // foo(shared(inout(const(U)))) inout(T) => nomatch
1274 // foo(shared(inout(const(U)))) inout(const(T)) => nomatch
1275 // foo(shared(inout(const(U)))) shared(T) => nomatch
1276 // foo(shared(inout(const(U)))) shared(const(T)) => nomatch
1277 // foo(immutable(U)) T => nomatch
1278 // foo(immutable(U)) const(T) => nomatch
1279 // foo(immutable(U)) inout(T) => nomatch
1280 // foo(immutable(U)) inout(const(T)) => nomatch
1281 // foo(immutable(U)) shared(T) => nomatch
1282 // foo(immutable(U)) shared(const(T)) => nomatch
1283 // foo(immutable(U)) shared(inout(T)) => nomatch
1284 // foo(immutable(U)) shared(inout(const(T))) => nomatch
1285 return MATCH.nomatch;
1286
1287 default:
1288 assert(0);
1289 }
1290 }
1291
1292 __gshared Expression emptyArrayElement = null;
1293
1294 /* These form the heart of template argument deduction.
1295 * Given 'this' being the type argument to the template instance,
1296 * it is matched against the template declaration parameter specialization
1297 * 'tparam' to determine the type to be used for the parameter.
1298 * Example:
1299 * template Foo(T:T*) // template declaration
1300 * Foo!(int*) // template instantiation
1301 * Input:
1302 * this = int*
1303 * tparam = T*
1304 * parameters = [ T:T* ] // Array of TemplateParameter's
1305 * Output:
1306 * dedtypes = [ int ] // Array of Expression/Type's
1307 */
1308 MATCH deduceType(RootObject o, Scope* sc, Type tparam, ref TemplateParameters parameters, ref Objects dedtypes, uint* wm = null, size_t inferStart = 0, bool ignoreAliasThis = false)
1309 {
1310 extern (C++) final class DeduceType : Visitor
1311 {
1312 alias visit = Visitor.visit;
1313 public:
1314 MATCH result;
1315
1316 extern (D) this() @safe
1317 {
1318 result = MATCH.nomatch;
1319 }
1320
1321 override void visit(Type t)
1322 {
1323 if (!tparam)
1324 goto Lnomatch;
1325
1326 if (t == tparam)
1327 goto Lexact;
1328
1329 if (tparam.ty == Tident)
1330 {
1331 // Determine which parameter tparam is
1332 size_t i = templateParameterLookup(tparam, &parameters);
1333 if (i == IDX_NOTFOUND)
1334 {
1335 if (!sc)
1336 goto Lnomatch;
1337
1338 /* Need a loc to go with the semantic routine.
1339 */
1340 Loc loc;
1341 if (parameters.length)
1342 {
1343 TemplateParameter tp = parameters[0];
1344 loc = tp.loc;
1345 }
1346
1347 /* BUG: what if tparam is a template instance, that
1348 * has as an argument another Tident?
1349 */
1350 tparam = tparam.typeSemantic(loc, sc);
1351 assert(tparam.ty != Tident);
1352 result = deduceType(t, sc, tparam, parameters, dedtypes, wm);
1353 return;
1354 }
1355
1356 TemplateParameter tp = parameters[i];
1357
1358 TypeIdentifier tident = tparam.isTypeIdentifier();
1359 if (tident.idents.length > 0)
1360 {
1361 //printf("matching %s to %s\n", tparam.toChars(), t.toChars());
1362 Dsymbol s = t.toDsymbol(sc);
1363 for (size_t j = tident.idents.length; j-- > 0;)
1364 {
1365 RootObject id = tident.idents[j];
1366 if (id.dyncast() == DYNCAST.identifier)
1367 {
1368 if (!s || !s.parent)
1369 goto Lnomatch;
1370 Dsymbol s2 = s.parent.search(Loc.initial, cast(Identifier)id);
1371 if (!s2)
1372 goto Lnomatch;
1373 s2 = s2.toAlias();
1374 //printf("[%d] s = %s %s, s2 = %s %s\n", j, s.kind(), s.toChars(), s2.kind(), s2.toChars());
1375 if (s != s2)
1376 {
1377 if (Type tx = s2.getType())
1378 {
1379 if (s != tx.toDsymbol(sc))
1380 goto Lnomatch;
1381 }
1382 else
1383 goto Lnomatch;
1384 }
1385 s = s.parent;
1386 }
1387 else
1388 goto Lnomatch;
1389 }
1390 //printf("[e] s = %s\n", s?s.toChars():"(null)");
1391 if (tp.isTemplateTypeParameter())
1392 {
1393 Type tt = s.getType();
1394 if (!tt)
1395 goto Lnomatch;
1396 Type at = cast(Type)dedtypes[i];
1397 if (at && at.ty == Tnone)
1398 at = (cast(TypeDeduced)at).tded;
1399 if (!at || tt.equals(at))
1400 {
1401 dedtypes[i] = tt;
1402 goto Lexact;
1403 }
1404 }
1405 if (tp.isTemplateAliasParameter())
1406 {
1407 Dsymbol s2 = cast(Dsymbol)dedtypes[i];
1408 if (!s2 || s == s2)
1409 {
1410 dedtypes[i] = s;
1411 goto Lexact;
1412 }
1413 }
1414 goto Lnomatch;
1415 }
1416
1417 // Found the corresponding parameter tp
1418 /+
1419 https://issues.dlang.org/show_bug.cgi?id=23578
1420 To pattern match:
1421 static if (is(S!int == S!av, alias av))
1422
1423 We eventually need to deduce `int` (Tint32 [0]) and `av` (Tident).
1424 Previously this would not get pattern matched at all, but now we check if the
1425 template parameter `av` came from.
1426
1427 This note has been left to serve as a hint for further explorers into
1428 how IsExp matching works.
1429 +/
1430 if (auto ta = tp.isTemplateAliasParameter())
1431 {
1432 dedtypes[i] = t;
1433 goto Lexact;
1434 }
1435 // (23578) - ensure previous behaviour for non-alias template params
1436 if (!tp.isTemplateTypeParameter())
1437 {
1438 goto Lnomatch;
1439 }
1440
1441 Type at = cast(Type)dedtypes[i];
1442 Type tt;
1443 if (ubyte wx = wm ? deduceWildHelper(t, &tt, tparam) : 0)
1444 {
1445 // type vs (none)
1446 if (!at)
1447 {
1448 dedtypes[i] = tt;
1449 *wm |= wx;
1450 result = MATCH.constant;
1451 return;
1452 }
1453
1454 // type vs expressions
1455 if (at.ty == Tnone)
1456 {
1457 auto xt = cast(TypeDeduced)at;
1458 result = xt.matchAll(tt);
1459 if (result > MATCH.nomatch)
1460 {
1461 dedtypes[i] = tt;
1462 if (result > MATCH.constant)
1463 result = MATCH.constant; // limit level for inout matches
1464 }
1465 return;
1466 }
1467
1468 // type vs type
1469 if (tt.equals(at))
1470 {
1471 dedtypes[i] = tt; // Prefer current type match
1472 goto Lconst;
1473 }
1474 if (tt.implicitConvTo(at.constOf()))
1475 {
1476 dedtypes[i] = at.constOf().mutableOf();
1477 *wm |= MODFlags.const_;
1478 goto Lconst;
1479 }
1480 if (at.implicitConvTo(tt.constOf()))
1481 {
1482 dedtypes[i] = tt.constOf().mutableOf();
1483 *wm |= MODFlags.const_;
1484 goto Lconst;
1485 }
1486 goto Lnomatch;
1487 }
1488 else if (MATCH m = deduceTypeHelper(t, tt, tparam))
1489 {
1490 // type vs (none)
1491 if (!at)
1492 {
1493 dedtypes[i] = tt;
1494 result = m;
1495 return;
1496 }
1497
1498 // type vs expressions
1499 if (at.ty == Tnone)
1500 {
1501 auto xt = cast(TypeDeduced)at;
1502 result = xt.matchAll(tt);
1503 if (result > MATCH.nomatch)
1504 {
1505 dedtypes[i] = tt;
1506 }
1507 return;
1508 }
1509
1510 // type vs type
1511 if (tt.equals(at))
1512 {
1513 goto Lexact;
1514 }
1515 if (tt.ty == Tclass && at.ty == Tclass)
1516 {
1517 result = tt.implicitConvTo(at);
1518 return;
1519 }
1520 if (tt.ty == Tsarray && at.ty == Tarray && tt.nextOf().implicitConvTo(at.nextOf()) >= MATCH.constant)
1521 {
1522 goto Lexact;
1523 }
1524 }
1525 goto Lnomatch;
1526 }
1527
1528 if (tparam.ty == Ttypeof)
1529 {
1530 /* Need a loc to go with the semantic routine.
1531 */
1532 Loc loc;
1533 if (parameters.length)
1534 {
1535 TemplateParameter tp = parameters[0];
1536 loc = tp.loc;
1537 }
1538
1539 tparam = tparam.typeSemantic(loc, sc);
1540 }
1541 if (t.ty != tparam.ty)
1542 {
1543 if (Dsymbol sym = t.toDsymbol(sc))
1544 {
1545 if (sym.isforwardRef() && !tparam.deco)
1546 goto Lnomatch;
1547 }
1548
1549 MATCH m = t.implicitConvTo(tparam);
1550 if (m == MATCH.nomatch && !ignoreAliasThis)
1551 {
1552 if (auto tc = t.isTypeClass())
1553 {
1554 if (tc.sym.aliasthis && !(tc.att & AliasThisRec.tracingDT))
1555 {
1556 if (auto ato = t.aliasthisOf())
1557 {
1558 tc.att = cast(AliasThisRec)(tc.att | AliasThisRec.tracingDT);
1559 m = deduceType(ato, sc, tparam, parameters, dedtypes, wm);
1560 tc.att = cast(AliasThisRec)(tc.att & ~AliasThisRec.tracingDT);
1561 }
1562 }
1563 }
1564 else if (auto ts = t.isTypeStruct())
1565 {
1566 if (ts.sym.aliasthis && !(ts.att & AliasThisRec.tracingDT))
1567 {
1568 if (auto ato = t.aliasthisOf())
1569 {
1570 ts.att = cast(AliasThisRec)(ts.att | AliasThisRec.tracingDT);
1571 m = deduceType(ato, sc, tparam, parameters, dedtypes, wm);
1572 ts.att = cast(AliasThisRec)(ts.att & ~AliasThisRec.tracingDT);
1573 }
1574 }
1575 }
1576 }
1577 result = m;
1578 return;
1579 }
1580
1581 if (t.nextOf())
1582 {
1583 if (tparam.deco && !tparam.hasWild())
1584 {
1585 result = t.implicitConvTo(tparam);
1586 return;
1587 }
1588
1589 Type tpn = tparam.nextOf();
1590 if (wm && t.ty == Taarray && tparam.isWild())
1591 {
1592 // https://issues.dlang.org/show_bug.cgi?id=12403
1593 // In IFTI, stop inout matching on transitive part of AA types.
1594 tpn = tpn.substWildTo(MODFlags.mutable);
1595 }
1596
1597 result = deduceType(t.nextOf(), sc, tpn, parameters, dedtypes, wm);
1598 return;
1599 }
1600
1601 Lexact:
1602 result = MATCH.exact;
1603 return;
1604
1605 Lnomatch:
1606 result = MATCH.nomatch;
1607 return;
1608
1609 Lconst:
1610 result = MATCH.constant;
1611 }
1612
1613 override void visit(TypeVector t)
1614 {
1615 if (auto tp = tparam.isTypeVector())
1616 {
1617 result = deduceType(t.basetype, sc, tp.basetype, parameters, dedtypes, wm);
1618 return;
1619 }
1620 visit(cast(Type)t);
1621 }
1622
1623 override void visit(TypeDArray t)
1624 {
1625 visit(cast(Type)t);
1626 }
1627
1628 override void visit(TypeSArray t)
1629 {
1630 // Extra check that array dimensions must match
1631 if (!tparam)
1632 {
1633 visit(cast(Type)t);
1634 return;
1635 }
1636
1637 if (tparam.ty == Tarray)
1638 {
1639 MATCH m = deduceType(t.next, sc, tparam.nextOf(), parameters, dedtypes, wm);
1640 result = (m >= MATCH.constant) ? MATCH.convert : MATCH.nomatch;
1641 return;
1642 }
1643
1644 TemplateParameter tp = null;
1645 Expression edim = null;
1646 size_t i;
1647 if (auto tsa = tparam.isTypeSArray())
1648 {
1649 if (tsa.dim.isVarExp() && tsa.dim.isVarExp().var.storage_class & STC.templateparameter)
1650 {
1651 Identifier id = tsa.dim.isVarExp().var.ident;
1652 i = templateIdentifierLookup(id, &parameters);
1653 assert(i != IDX_NOTFOUND);
1654 tp = parameters[i];
1655 }
1656 else
1657 edim = tsa.dim;
1658 }
1659 else if (auto taa = tparam.isTypeAArray())
1660 {
1661 i = templateParameterLookup(taa.index, &parameters);
1662 if (i != IDX_NOTFOUND)
1663 tp = parameters[i];
1664 else
1665 {
1666 Loc loc;
1667 // The "type" (it hasn't been resolved yet) of the function parameter
1668 // does not have a location but the parameter it is related to does,
1669 // so we use that for the resolution (better error message).
1670 if (inferStart < parameters.length)
1671 {
1672 TemplateParameter loctp = parameters[inferStart];
1673 loc = loctp.loc;
1674 }
1675
1676 Expression e;
1677 Type tx;
1678 Dsymbol s;
1679 taa.index.resolve(loc, sc, e, tx, s);
1680 edim = s ? getValue(s) : getValue(e);
1681 }
1682 }
1683 if ((tp && tp.matchArg(sc, t.dim, i, &parameters, dedtypes, null)) ||
1684 (edim && edim.isIntegerExp() && edim.toInteger() == t.dim.toInteger())
1685 )
1686 {
1687 result = deduceType(t.next, sc, tparam.nextOf(), parameters, dedtypes, wm);
1688 return;
1689 }
1690
1691 visit(cast(Type)t);
1692 }
1693
1694 override void visit(TypeAArray t)
1695 {
1696 // Extra check that index type must match
1697 if (tparam && tparam.ty == Taarray)
1698 {
1699 TypeAArray tp = tparam.isTypeAArray();
1700 if (!deduceType(t.index, sc, tp.index, parameters, dedtypes))
1701 {
1702 result = MATCH.nomatch;
1703 return;
1704 }
1705 }
1706 visit(cast(Type)t);
1707 }
1708
1709 override void visit(TypeFunction t)
1710 {
1711 // Extra check that function characteristics must match
1712 if (!tparam)
1713 return visit(cast(Type)t);
1714
1715 auto tp = tparam.isTypeFunction();
1716 if (!tp)
1717 {
1718 visit(cast(Type)t);
1719 return;
1720 }
1721
1722 if (t.parameterList.varargs != tp.parameterList.varargs || t.linkage != tp.linkage)
1723 {
1724 result = MATCH.nomatch;
1725 return;
1726 }
1727
1728 foreach (fparam; *tp.parameterList.parameters)
1729 {
1730 // https://issues.dlang.org/show_bug.cgi?id=2579
1731 // Apply function parameter storage classes to parameter types
1732 fparam.type = fparam.type.addStorageClass(fparam.storageClass);
1733 fparam.storageClass &= ~STC.TYPECTOR;
1734
1735 // https://issues.dlang.org/show_bug.cgi?id=15243
1736 // Resolve parameter type if it's not related with template parameters
1737 if (!reliesOnTemplateParameters(fparam.type, parameters[inferStart .. parameters.length]))
1738 {
1739 auto tx = fparam.type.typeSemantic(Loc.initial, sc);
1740 if (tx.ty == Terror)
1741 {
1742 result = MATCH.nomatch;
1743 return;
1744 }
1745 fparam.type = tx;
1746 }
1747 }
1748
1749 const size_t nfargs = t.parameterList.length;
1750 size_t nfparams = tp.parameterList.length;
1751
1752 /* See if tuple match
1753 */
1754 if (nfparams > 0 && nfargs >= nfparams - 1)
1755 {
1756 /* See if 'A' of the template parameter matches 'A'
1757 * of the type of the last function parameter.
1758 */
1759 Parameter fparam = tp.parameterList[nfparams - 1];
1760 assert(fparam);
1761 assert(fparam.type);
1762 if (fparam.type.ty != Tident)
1763 goto L1;
1764 TypeIdentifier tid = fparam.type.isTypeIdentifier();
1765 if (tid.idents.length)
1766 goto L1;
1767
1768 /* Look through parameters to find tuple matching tid.ident
1769 */
1770 size_t tupi = 0;
1771 for (; 1; tupi++)
1772 {
1773 if (tupi == parameters.length)
1774 goto L1;
1775 TemplateParameter tx = parameters[tupi];
1776 TemplateTupleParameter tup = tx.isTemplateTupleParameter();
1777 if (tup && tup.ident.equals(tid.ident))
1778 break;
1779 }
1780
1781 /* The types of the function arguments [nfparams - 1 .. nfargs]
1782 * now form the tuple argument.
1783 */
1784 size_t tuple_dim = nfargs - (nfparams - 1);
1785
1786 /* See if existing tuple, and whether it matches or not
1787 */
1788 RootObject o = dedtypes[tupi];
1789 if (o)
1790 {
1791 // Existing deduced argument must be a tuple, and must match
1792 Tuple tup = isTuple(o);
1793 if (!tup || tup.objects.length != tuple_dim)
1794 {
1795 result = MATCH.nomatch;
1796 return;
1797 }
1798 for (size_t i = 0; i < tuple_dim; i++)
1799 {
1800 Parameter arg = t.parameterList[nfparams - 1 + i];
1801 if (!arg.type.equals(tup.objects[i]))
1802 {
1803 result = MATCH.nomatch;
1804 return;
1805 }
1806 }
1807 }
1808 else
1809 {
1810 // Create new tuple
1811 auto tup = new Tuple(tuple_dim);
1812 for (size_t i = 0; i < tuple_dim; i++)
1813 {
1814 Parameter arg = t.parameterList[nfparams - 1 + i];
1815 tup.objects[i] = arg.type;
1816 }
1817 dedtypes[tupi] = tup;
1818 }
1819 nfparams--; // don't consider the last parameter for type deduction
1820 goto L2;
1821 }
1822
1823 L1:
1824 if (nfargs != nfparams)
1825 {
1826 result = MATCH.nomatch;
1827 return;
1828 }
1829 L2:
1830 assert(nfparams <= tp.parameterList.length);
1831 foreach (i, ap; tp.parameterList)
1832 {
1833 if (i == nfparams)
1834 break;
1835
1836 Parameter a = t.parameterList[i];
1837
1838 if (!a.isCovariant(t.isRef, ap) ||
1839 !deduceType(a.type, sc, ap.type, parameters, dedtypes))
1840 {
1841 result = MATCH.nomatch;
1842 return;
1843 }
1844 }
1845
1846 visit(cast(Type)t);
1847 }
1848
1849 override void visit(TypeIdentifier t)
1850 {
1851 // Extra check
1852 if (tparam && tparam.ty == Tident)
1853 {
1854 TypeIdentifier tp = tparam.isTypeIdentifier();
1855 for (size_t i = 0; i < t.idents.length; i++)
1856 {
1857 RootObject id1 = t.idents[i];
1858 RootObject id2 = tp.idents[i];
1859 if (!id1.equals(id2))
1860 {
1861 result = MATCH.nomatch;
1862 return;
1863 }
1864 }
1865 }
1866 visit(cast(Type)t);
1867 }
1868
1869 override void visit(TypeInstance t)
1870 {
1871 // Extra check
1872 if (!tparam || tparam.ty != Tinstance || !t.tempinst.tempdecl)
1873 {
1874 visit(cast(Type)t);
1875 return;
1876 }
1877
1878 TemplateDeclaration tempdecl = t.tempinst.tempdecl.isTemplateDeclaration();
1879 assert(tempdecl);
1880
1881 TypeInstance tp = tparam.isTypeInstance();
1882
1883 //printf("tempinst.tempdecl = %p\n", tempdecl);
1884 //printf("tp.tempinst.tempdecl = %p\n", tp.tempinst.tempdecl);
1885 if (!tp.tempinst.tempdecl)
1886 {
1887 //printf("tp.tempinst.name = '%s'\n", tp.tempinst.name.toChars());
1888
1889 /* Handle case of:
1890 * template Foo(T : sa!(T), alias sa)
1891 */
1892 size_t i = templateIdentifierLookup(tp.tempinst.name, &parameters);
1893 if (i == IDX_NOTFOUND)
1894 {
1895 /* Didn't find it as a parameter identifier. Try looking
1896 * it up and seeing if is an alias.
1897 * https://issues.dlang.org/show_bug.cgi?id=1454
1898 */
1899 auto tid = new TypeIdentifier(tp.loc, tp.tempinst.name);
1900 Type tx;
1901 Expression e;
1902 Dsymbol s;
1903 tid.resolve(tp.loc, sc, e, tx, s);
1904 if (tx)
1905 {
1906 s = tx.toDsymbol(sc);
1907 if (TemplateInstance ti = s ? s.parent.isTemplateInstance() : null)
1908 {
1909 // https://issues.dlang.org/show_bug.cgi?id=14290
1910 // Try to match with ti.tempecl,
1911 // only when ti is an enclosing instance.
1912 Dsymbol p = sc.parent;
1913 while (p && p != ti)
1914 p = p.parent;
1915 if (p)
1916 s = ti.tempdecl;
1917 }
1918 }
1919 if (s)
1920 {
1921 s = s.toAlias();
1922 TemplateDeclaration td = s.isTemplateDeclaration();
1923 if (td)
1924 {
1925 if (td.overroot)
1926 td = td.overroot;
1927 for (; td; td = td.overnext)
1928 {
1929 if (td == tempdecl)
1930 goto L2;
1931 }
1932 }
1933 }
1934 goto Lnomatch;
1935 }
1936
1937 TemplateParameter tpx = parameters[i];
1938 if (!tpx.matchArg(sc, tempdecl, i, &parameters, dedtypes, null))
1939 goto Lnomatch;
1940 }
1941 else if (tempdecl != tp.tempinst.tempdecl)
1942 goto Lnomatch;
1943
1944 L2:
1945 if (!resolveTemplateInstantiation(sc, &parameters, t.tempinst.tiargs, &t.tempinst.tdtypes, tempdecl, tp, &dedtypes))
1946 goto Lnomatch;
1947
1948 visit(cast(Type)t);
1949 return;
1950
1951 Lnomatch:
1952 //printf("no match\n");
1953 result = MATCH.nomatch;
1954 }
1955
1956 override void visit(TypeStruct t)
1957 {
1958 /* If this struct is a template struct, and we're matching
1959 * it against a template instance, convert the struct type
1960 * to a template instance, too, and try again.
1961 */
1962 TemplateInstance ti = t.sym.parent.isTemplateInstance();
1963
1964 if (tparam && tparam.ty == Tinstance)
1965 {
1966 if (ti && ti.toAlias() == t.sym)
1967 {
1968 auto tx = new TypeInstance(Loc.initial, ti);
1969 auto m = deduceType(tx, sc, tparam, parameters, dedtypes, wm);
1970 // if we have a no match we still need to check alias this
1971 if (m != MATCH.nomatch)
1972 {
1973 result = m;
1974 return;
1975 }
1976 }
1977
1978 /* Match things like:
1979 * S!(T).foo
1980 */
1981 TypeInstance tpi = tparam.isTypeInstance();
1982 if (tpi.idents.length)
1983 {
1984 RootObject id = tpi.idents[tpi.idents.length - 1];
1985 if (id.dyncast() == DYNCAST.identifier && t.sym.ident.equals(cast(Identifier)id))
1986 {
1987 Type tparent = t.sym.parent.getType();
1988 if (tparent)
1989 {
1990 /* Slice off the .foo in S!(T).foo
1991 */
1992 tpi.idents.length--;
1993 result = deduceType(tparent, sc, tpi, parameters, dedtypes, wm);
1994 tpi.idents.length++;
1995 return;
1996 }
1997 }
1998 }
1999 }
2000
2001 // Extra check
2002 if (tparam && tparam.ty == Tstruct)
2003 {
2004 TypeStruct tp = tparam.isTypeStruct();
2005
2006 //printf("\t%d\n", cast(MATCH) t.implicitConvTo(tp));
2007 if (wm && t.deduceWild(tparam, false))
2008 {
2009 result = MATCH.constant;
2010 return;
2011 }
2012 result = t.implicitConvTo(tp);
2013 return;
2014 }
2015 visit(cast(Type)t);
2016 }
2017
2018 override void visit(TypeEnum t)
2019 {
2020 // Extra check
2021 if (tparam && tparam.ty == Tenum)
2022 {
2023 TypeEnum tp = tparam.isTypeEnum();
2024 if (t.sym == tp.sym)
2025 visit(cast(Type)t);
2026 else
2027 result = MATCH.nomatch;
2028 return;
2029 }
2030 Type tb = t.toBasetype();
2031 if (tb.ty == tparam.ty || tb.ty == Tsarray && tparam.ty == Taarray)
2032 {
2033 result = deduceType(tb, sc, tparam, parameters, dedtypes, wm);
2034 if (result == MATCH.exact)
2035 result = MATCH.convert;
2036 return;
2037 }
2038 visit(cast(Type)t);
2039 }
2040
2041 override void visit(TypeClass t)
2042 {
2043 //printf("TypeClass.deduceType(this = %s)\n", t.toChars());
2044
2045 /* If this class is a template class, and we're matching
2046 * it against a template instance, convert the class type
2047 * to a template instance, too, and try again.
2048 */
2049 TemplateInstance ti = t.sym.parent.isTemplateInstance();
2050
2051 if (tparam && tparam.ty == Tinstance)
2052 {
2053 if (ti && ti.toAlias() == t.sym)
2054 {
2055 auto tx = new TypeInstance(Loc.initial, ti);
2056 MATCH m = deduceType(tx, sc, tparam, parameters, dedtypes, wm);
2057 // Even if the match fails, there is still a chance it could match
2058 // a base class.
2059 if (m != MATCH.nomatch)
2060 {
2061 result = m;
2062 return;
2063 }
2064 }
2065
2066 /* Match things like:
2067 * S!(T).foo
2068 */
2069 TypeInstance tpi = tparam.isTypeInstance();
2070 if (tpi.idents.length)
2071 {
2072 RootObject id = tpi.idents[tpi.idents.length - 1];
2073 if (id.dyncast() == DYNCAST.identifier && t.sym.ident.equals(cast(Identifier)id))
2074 {
2075 Type tparent = t.sym.parent.getType();
2076 if (tparent)
2077 {
2078 /* Slice off the .foo in S!(T).foo
2079 */
2080 tpi.idents.length--;
2081 result = deduceType(tparent, sc, tpi, parameters, dedtypes, wm);
2082 tpi.idents.length++;
2083 return;
2084 }
2085 }
2086 }
2087
2088 // If it matches exactly or via implicit conversion, we're done
2089 visit(cast(Type)t);
2090 if (result != MATCH.nomatch)
2091 return;
2092
2093 /* There is still a chance to match via implicit conversion to
2094 * a base class or interface. Because there could be more than one such
2095 * match, we need to check them all.
2096 */
2097
2098 int numBaseClassMatches = 0; // Have we found an interface match?
2099
2100 // Our best guess at dedtypes
2101 auto best = new Objects(dedtypes.length);
2102
2103 ClassDeclaration s = t.sym;
2104 while (s && s.baseclasses.length > 0)
2105 {
2106 // Test the base class
2107 deduceBaseClassParameters(*(*s.baseclasses)[0], sc, tparam, parameters, dedtypes, *best, numBaseClassMatches);
2108
2109 // Test the interfaces inherited by the base class
2110 foreach (b; s.interfaces)
2111 {
2112 deduceBaseClassParameters(*b, sc, tparam, parameters, dedtypes, *best, numBaseClassMatches);
2113 }
2114 s = (*s.baseclasses)[0].sym;
2115 }
2116
2117 if (numBaseClassMatches == 0)
2118 {
2119 result = MATCH.nomatch;
2120 return;
2121 }
2122
2123 // If we got at least one match, copy the known types into dedtypes
2124 memcpy(dedtypes.tdata(), best.tdata(), best.length * (void*).sizeof);
2125 result = MATCH.convert;
2126 return;
2127 }
2128
2129 // Extra check
2130 if (tparam && tparam.ty == Tclass)
2131 {
2132 TypeClass tp = tparam.isTypeClass();
2133
2134 //printf("\t%d\n", cast(MATCH) t.implicitConvTo(tp));
2135 if (wm && t.deduceWild(tparam, false))
2136 {
2137 result = MATCH.constant;
2138 return;
2139 }
2140 result = t.implicitConvTo(tp);
2141 return;
2142 }
2143 visit(cast(Type)t);
2144 }
2145
2146 override void visit(Expression e)
2147 {
2148 //printf("Expression.deduceType(e = %s)\n", e.toChars());
2149 size_t i = templateParameterLookup(tparam, &parameters);
2150 if (i == IDX_NOTFOUND || tparam.isTypeIdentifier().idents.length > 0)
2151 {
2152 if (e == emptyArrayElement && tparam.ty == Tarray)
2153 {
2154 Type tn = (cast(TypeNext)tparam).next;
2155 result = deduceType(emptyArrayElement, sc, tn, parameters, dedtypes, wm);
2156 return;
2157 }
2158 e.type.accept(this);
2159 return;
2160 }
2161
2162 TemplateTypeParameter tp = parameters[i].isTemplateTypeParameter();
2163 if (!tp)
2164 return; // nomatch
2165
2166 if (e == emptyArrayElement)
2167 {
2168 if (dedtypes[i])
2169 {
2170 result = MATCH.exact;
2171 return;
2172 }
2173 if (tp.defaultType)
2174 {
2175 tp.defaultType.accept(this);
2176 return;
2177 }
2178 }
2179
2180 /* Returns `true` if `t` is a reference type, or an array of reference types
2181 */
2182 bool isTopRef(Type t)
2183 {
2184 auto tb = t.baseElemOf();
2185 return tb.ty == Tclass ||
2186 tb.ty == Taarray ||
2187 tb.ty == Tstruct && tb.hasPointers();
2188 }
2189
2190 Type at = cast(Type)dedtypes[i];
2191 Type tt;
2192 if (ubyte wx = deduceWildHelper(e.type, &tt, tparam))
2193 {
2194 *wm |= wx;
2195 result = MATCH.constant;
2196 }
2197 else if (MATCH m = deduceTypeHelper(e.type, tt, tparam))
2198 {
2199 result = m;
2200 }
2201 else if (!isTopRef(e.type))
2202 {
2203 /* https://issues.dlang.org/show_bug.cgi?id=15653
2204 * In IFTI, recognize top-qualifier conversions
2205 * through the value copy, e.g.
2206 * int --> immutable(int)
2207 * immutable(string[]) --> immutable(string)[]
2208 */
2209 tt = e.type.mutableOf();
2210 result = MATCH.convert;
2211 }
2212 else
2213 return; // nomatch
2214
2215 // expression vs (none)
2216 if (!at)
2217 {
2218 dedtypes[i] = new TypeDeduced(tt, e, tparam);
2219 return;
2220 }
2221
2222 TypeDeduced xt = null;
2223 if (at.ty == Tnone)
2224 {
2225 xt = cast(TypeDeduced)at;
2226 at = xt.tded;
2227 }
2228
2229 // From previous matched expressions to current deduced type
2230 MATCH match1 = xt ? xt.matchAll(tt) : MATCH.nomatch;
2231
2232 // From current expressions to previous deduced type
2233 Type pt = at.addMod(tparam.mod);
2234 if (*wm)
2235 pt = pt.substWildTo(*wm);
2236 MATCH match2 = e.implicitConvTo(pt);
2237
2238 if (match1 > MATCH.nomatch && match2 > MATCH.nomatch)
2239 {
2240 if (at.implicitConvTo(tt) == MATCH.nomatch)
2241 match1 = MATCH.nomatch; // Prefer at
2242 else if (tt.implicitConvTo(at) == MATCH.nomatch)
2243 match2 = MATCH.nomatch; // Prefer tt
2244 else if (tt.isTypeBasic() && tt.ty == at.ty && tt.mod != at.mod)
2245 {
2246 if (!tt.isMutable() && !at.isMutable())
2247 tt = tt.mutableOf().addMod(MODmerge(tt.mod, at.mod));
2248 else if (tt.isMutable())
2249 {
2250 if (at.mod == 0) // Prefer unshared
2251 match1 = MATCH.nomatch;
2252 else
2253 match2 = MATCH.nomatch;
2254 }
2255 else if (at.isMutable())
2256 {
2257 if (tt.mod == 0) // Prefer unshared
2258 match2 = MATCH.nomatch;
2259 else
2260 match1 = MATCH.nomatch;
2261 }
2262 //printf("tt = %s, at = %s\n", tt.toChars(), at.toChars());
2263 }
2264 else
2265 {
2266 match1 = MATCH.nomatch;
2267 match2 = MATCH.nomatch;
2268 }
2269 }
2270 if (match1 > MATCH.nomatch)
2271 {
2272 // Prefer current match: tt
2273 if (xt)
2274 xt.update(tt, e, tparam);
2275 else
2276 dedtypes[i] = tt;
2277 result = match1;
2278 return;
2279 }
2280 if (match2 > MATCH.nomatch)
2281 {
2282 // Prefer previous match: (*dedtypes)[i]
2283 if (xt)
2284 xt.update(e, tparam);
2285 result = match2;
2286 return;
2287 }
2288
2289 /* Deduce common type
2290 */
2291 if (Type t = rawTypeMerge(at, tt))
2292 {
2293 if (xt)
2294 xt.update(t, e, tparam);
2295 else
2296 dedtypes[i] = t;
2297
2298 pt = tt.addMod(tparam.mod);
2299 if (*wm)
2300 pt = pt.substWildTo(*wm);
2301 result = e.implicitConvTo(pt);
2302 return;
2303 }
2304
2305 result = MATCH.nomatch;
2306 }
2307
2308 MATCH deduceEmptyArrayElement()
2309 {
2310 if (!emptyArrayElement)
2311 {
2312 emptyArrayElement = new IdentifierExp(Loc.initial, Id.p); // dummy
2313 emptyArrayElement.type = Type.tvoid;
2314 }
2315 assert(tparam.ty == Tarray);
2316
2317 Type tn = (cast(TypeNext)tparam).next;
2318 return deduceType(emptyArrayElement, sc, tn, parameters, dedtypes, wm);
2319 }
2320
2321 override void visit(NullExp e)
2322 {
2323 if (tparam.ty == Tarray && e.type.ty == Tnull)
2324 {
2325 // tparam:T[] <- e:null (void[])
2326 result = deduceEmptyArrayElement();
2327 return;
2328 }
2329 visit(cast(Expression)e);
2330 }
2331
2332 override void visit(StringExp e)
2333 {
2334 Type taai;
2335 if (e.type.ty == Tarray && (tparam.ty == Tsarray || tparam.ty == Taarray && (taai = (cast(TypeAArray)tparam).index).ty == Tident && (cast(TypeIdentifier)taai).idents.length == 0))
2336 {
2337 // Consider compile-time known boundaries
2338 e.type.nextOf().sarrayOf(e.len).accept(this);
2339 return;
2340 }
2341 visit(cast(Expression)e);
2342 }
2343
2344 override void visit(ArrayLiteralExp e)
2345 {
2346 // https://issues.dlang.org/show_bug.cgi?id=20092
2347 if (e.elements && e.elements.length && e.type.toBasetype().nextOf().ty == Tvoid)
2348 {
2349 result = deduceEmptyArrayElement();
2350 return;
2351 }
2352 if ((!e.elements || !e.elements.length) && e.type.toBasetype().nextOf().ty == Tvoid && tparam.ty == Tarray)
2353 {
2354 // tparam:T[] <- e:[] (void[])
2355 result = deduceEmptyArrayElement();
2356 return;
2357 }
2358
2359 if (tparam.ty == Tarray && e.elements && e.elements.length)
2360 {
2361 Type tn = (cast(TypeDArray)tparam).next;
2362 result = MATCH.exact;
2363 if (e.basis)
2364 {
2365 MATCH m = deduceType(e.basis, sc, tn, parameters, dedtypes, wm);
2366 if (m < result)
2367 result = m;
2368 }
2369 foreach (el; *e.elements)
2370 {
2371 if (result == MATCH.nomatch)
2372 break;
2373 if (!el)
2374 continue;
2375 MATCH m = deduceType(el, sc, tn, parameters, dedtypes, wm);
2376 if (m < result)
2377 result = m;
2378 }
2379 return;
2380 }
2381
2382 Type taai;
2383 if (e.type.ty == Tarray && (tparam.ty == Tsarray || tparam.ty == Taarray && (taai = (cast(TypeAArray)tparam).index).ty == Tident && (cast(TypeIdentifier)taai).idents.length == 0))
2384 {
2385 // Consider compile-time known boundaries
2386 e.type.nextOf().sarrayOf(e.elements.length).accept(this);
2387 return;
2388 }
2389 visit(cast(Expression)e);
2390 }
2391
2392 override void visit(AssocArrayLiteralExp e)
2393 {
2394 if (tparam.ty == Taarray && e.keys && e.keys.length)
2395 {
2396 TypeAArray taa = cast(TypeAArray)tparam;
2397 result = MATCH.exact;
2398 foreach (i, key; *e.keys)
2399 {
2400 MATCH m1 = deduceType(key, sc, taa.index, parameters, dedtypes, wm);
2401 if (m1 < result)
2402 result = m1;
2403 if (result == MATCH.nomatch)
2404 break;
2405 MATCH m2 = deduceType((*e.values)[i], sc, taa.next, parameters, dedtypes, wm);
2406 if (m2 < result)
2407 result = m2;
2408 if (result == MATCH.nomatch)
2409 break;
2410 }
2411 return;
2412 }
2413 visit(cast(Expression)e);
2414 }
2415
2416 override void visit(FuncExp e)
2417 {
2418 //printf("e.type = %s, tparam = %s\n", e.type.toChars(), tparam.toChars());
2419 if (e.td)
2420 {
2421 Type to = tparam;
2422 if (!to.nextOf())
2423 return;
2424 auto tof = to.nextOf().isTypeFunction();
2425 if (!tof)
2426 return;
2427
2428 // Parameter types inference from 'tof'
2429 assert(e.td._scope);
2430 TypeFunction tf = e.fd.type.isTypeFunction();
2431 //printf("\ttof = %s\n", tof.toChars());
2432 //printf("\ttf = %s\n", tf.toChars());
2433 const dim = tf.parameterList.length;
2434
2435 if (tof.parameterList.length != dim || tof.parameterList.varargs != tf.parameterList.varargs)
2436 return;
2437
2438 auto tiargs = new Objects();
2439 tiargs.reserve(e.td.parameters.length);
2440
2441 foreach (tp; *e.td.parameters)
2442 {
2443 size_t u = 0;
2444 foreach (i, p; tf.parameterList)
2445 {
2446 if (p.type.ty == Tident && (cast(TypeIdentifier)p.type).ident == tp.ident)
2447 break;
2448 ++u;
2449 }
2450 assert(u < dim);
2451 Parameter pto = tof.parameterList[u];
2452 if (!pto)
2453 break;
2454 Type t = pto.type.syntaxCopy(); // https://issues.dlang.org/show_bug.cgi?id=11774
2455 if (reliesOnTemplateParameters(t, parameters[inferStart .. parameters.length]))
2456 return;
2457 t = t.typeSemantic(e.loc, sc);
2458 if (t.ty == Terror)
2459 return;
2460 tiargs.push(t);
2461 }
2462
2463 // Set target of return type inference
2464 if (!tf.next && tof.next)
2465 e.fd.treq = tparam;
2466
2467 auto ti = new TemplateInstance(e.loc, e.td, tiargs);
2468 Expression ex = (new ScopeExp(e.loc, ti)).expressionSemantic(e.td._scope);
2469
2470 // Reset inference target for the later re-semantic
2471 e.fd.treq = null;
2472
2473 if (ex.op == EXP.error)
2474 return;
2475 if (ex.op != EXP.function_)
2476 return;
2477 visit(ex.type);
2478 return;
2479 }
2480
2481 Type t = e.type;
2482
2483 if (t.ty == Tdelegate && tparam.ty == Tpointer)
2484 return;
2485
2486 // Allow conversion from implicit function pointer to delegate
2487 if (e.tok == TOK.reserved && t.ty == Tpointer && tparam.ty == Tdelegate)
2488 {
2489 TypeFunction tf = t.nextOf().isTypeFunction();
2490 t = (new TypeDelegate(tf)).merge();
2491 }
2492 //printf("tparam = %s <= e.type = %s, t = %s\n", tparam.toChars(), e.type.toChars(), t.toChars());
2493 visit(t);
2494 }
2495
2496 override void visit(SliceExp e)
2497 {
2498 Type taai;
2499 if (e.type.ty == Tarray && (tparam.ty == Tsarray || tparam.ty == Taarray && (taai = (cast(TypeAArray)tparam).index).ty == Tident && (cast(TypeIdentifier)taai).idents.length == 0))
2500 {
2501 // Consider compile-time known boundaries
2502 if (Type tsa = toStaticArrayType(e))
2503 {
2504 tsa.accept(this);
2505 if (result > MATCH.convert)
2506 result = MATCH.convert; // match with implicit conversion at most
2507 return;
2508 }
2509 }
2510 visit(cast(Expression)e);
2511 }
2512
2513 override void visit(CommaExp e)
2514 {
2515 e.e2.accept(this);
2516 }
2517 }
2518
2519 scope DeduceType v = new DeduceType();
2520 if (Type t = isType(o))
2521 t.accept(v);
2522 else if (Expression e = isExpression(o))
2523 {
2524 assert(wm);
2525 e.accept(v);
2526 }
2527 else
2528 assert(0);
2529 return v.result;
2530 }
2531
2532
2533 /* Helper for TypeClass.deduceType().
2534 * Classes can match with implicit conversion to a base class or interface.
2535 * This is complicated, because there may be more than one base class which
2536 * matches. In such cases, one or more parameters remain ambiguous.
2537 * For example,
2538 *
2539 * interface I(X, Y) {}
2540 * class C : I(uint, double), I(char, double) {}
2541 * C x;
2542 * foo(T, U)( I!(T, U) x)
2543 *
2544 * deduces that U is double, but T remains ambiguous (could be char or uint).
2545 *
2546 * Given a baseclass b, and initial deduced types 'dedtypes', this function
2547 * tries to match tparam with b, and also tries all base interfaces of b.
2548 * If a match occurs, numBaseClassMatches is incremented, and the new deduced
2549 * types are ANDed with the current 'best' estimate for dedtypes.
2550 */
2551 private void deduceBaseClassParameters(ref BaseClass b, Scope* sc, Type tparam, ref TemplateParameters parameters, ref Objects dedtypes, ref Objects best, ref int numBaseClassMatches)
2552 {
2553 if (TemplateInstance parti = b.sym ? b.sym.parent.isTemplateInstance() : null)
2554 {
2555 // Make a temporary copy of dedtypes so we don't destroy it
2556 auto tmpdedtypes = new Objects(dedtypes.length);
2557 memcpy(tmpdedtypes.tdata(), dedtypes.tdata(), dedtypes.length * (void*).sizeof);
2558
2559 auto t = new TypeInstance(Loc.initial, parti);
2560 MATCH m = deduceType(t, sc, tparam, parameters, *tmpdedtypes);
2561 if (m > MATCH.nomatch)
2562 {
2563 // If this is the first ever match, it becomes our best estimate
2564 if (numBaseClassMatches == 0)
2565 memcpy(best.tdata(), tmpdedtypes.tdata(), tmpdedtypes.length * (void*).sizeof);
2566 else
2567 for (size_t k = 0; k < tmpdedtypes.length; ++k)
2568 {
2569 // If we've found more than one possible type for a parameter,
2570 // mark it as unknown.
2571 if ((*tmpdedtypes)[k] != best[k])
2572 best[k] = dedtypes[k];
2573 }
2574 ++numBaseClassMatches;
2575 }
2576 }
2577
2578 // Now recursively test the inherited interfaces
2579 foreach (ref bi; b.baseInterfaces)
2580 {
2581 deduceBaseClassParameters(bi, sc, tparam, parameters, dedtypes, best, numBaseClassMatches);
2582 }
2583 }
2584
2585 /********************
2586 * Match template `parameters` to the target template instance.
2587 * Example:
2588 * struct Temp(U, int Z) {}
2589 * void foo(T)(Temp!(T, 3));
2590 * foo(Temp!(int, 3)());
2591 * Input:
2592 * sc = context
2593 * parameters = template params of foo -> [T]
2594 * tiargs = <Temp!(int, 3)>.tiargs -> [int, 3]
2595 * tdtypes = <Temp!(int, 3)>.tdtypes -> [int, 3]
2596 * tempdecl = <struct Temp!(T, int Z)> -> [T, Z]
2597 * tp = <Temp!(T, 3)>
2598 * Output:
2599 * dedtypes = deduced params of `foo(Temp!(int, 3)())` -> [int]
2600 */
2601 private bool resolveTemplateInstantiation(Scope* sc, TemplateParameters* parameters, Objects* tiargs, Objects* tdtypes, TemplateDeclaration tempdecl, TypeInstance tp, Objects* dedtypes)
2602 {
2603 for (size_t i = 0; 1; i++)
2604 {
2605 //printf("\ttest: tempinst.tiargs[%zu]\n", i);
2606 RootObject o1 = null;
2607 if (i < tiargs.length)
2608 o1 = (*tiargs)[i];
2609 else if (i < tdtypes.length && i < tp.tempinst.tiargs.length)
2610 {
2611 // Pick up default arg
2612 o1 = (*tdtypes)[i];
2613 }
2614 else if (i >= tp.tempinst.tiargs.length)
2615 break;
2616 //printf("\ttest: o1 = %s\n", o1.toChars());
2617 if (i >= tp.tempinst.tiargs.length)
2618 {
2619 size_t dim = tempdecl.parameters.length - (tempdecl.isVariadic() ? 1 : 0);
2620 while (i < dim && ((*tempdecl.parameters)[i].dependent || (*tempdecl.parameters)[i].hasDefaultArg()))
2621 {
2622 i++;
2623 }
2624 if (i >= dim)
2625 break; // match if all remained parameters are dependent
2626 return false;
2627 }
2628
2629 RootObject o2 = (*tp.tempinst.tiargs)[i];
2630 Type t2 = isType(o2);
2631 //printf("\ttest: o2 = %s\n", o2.toChars());
2632 size_t j = (t2 && t2.ty == Tident && i == tp.tempinst.tiargs.length - 1)
2633 ? templateParameterLookup(t2, parameters) : IDX_NOTFOUND;
2634 if (j != IDX_NOTFOUND && j == parameters.length - 1 &&
2635 (*parameters)[j].isTemplateTupleParameter())
2636 {
2637 /* Given:
2638 * struct A(B...) {}
2639 * alias A!(int, float) X;
2640 * static if (is(X Y == A!(Z), Z...)) {}
2641 * deduce that Z is a tuple(int, float)
2642 */
2643
2644 /* Create tuple from remaining args
2645 */
2646 size_t vtdim = (tempdecl.isVariadic() ? tiargs.length : tdtypes.length) - i;
2647 auto vt = new Tuple(vtdim);
2648 for (size_t k = 0; k < vtdim; k++)
2649 {
2650 RootObject o;
2651 if (k < tiargs.length)
2652 o = (*tiargs)[i + k];
2653 else // Pick up default arg
2654 o = (*tdtypes)[i + k];
2655 vt.objects[k] = o;
2656 }
2657
2658 Tuple v = cast(Tuple)(*dedtypes)[j];
2659 if (v)
2660 {
2661 if (!match(v, vt))
2662 return false;
2663 }
2664 else
2665 (*dedtypes)[j] = vt;
2666 break;
2667 }
2668 else if (!o1)
2669 break;
2670
2671 Type t1 = isType(o1);
2672 Dsymbol s1 = isDsymbol(o1);
2673 Dsymbol s2 = isDsymbol(o2);
2674 Expression e1 = s1 ? getValue(s1) : getValue(isExpression(o1));
2675 Expression e2 = isExpression(o2);
2676 version (none)
2677 {
2678 Tuple v1 = isTuple(o1);
2679 Tuple v2 = isTuple(o2);
2680 if (t1)
2681 printf("t1 = %s\n", t1.toChars());
2682 if (t2)
2683 printf("t2 = %s\n", t2.toChars());
2684 if (e1)
2685 printf("e1 = %s\n", e1.toChars());
2686 if (e2)
2687 printf("e2 = %s\n", e2.toChars());
2688 if (s1)
2689 printf("s1 = %s\n", s1.toChars());
2690 if (s2)
2691 printf("s2 = %s\n", s2.toChars());
2692 if (v1)
2693 printf("v1 = %s\n", v1.toChars());
2694 if (v2)
2695 printf("v2 = %s\n", v2.toChars());
2696 }
2697
2698 if (t1 && t2)
2699 {
2700 if (!deduceType(t1, sc, t2, *parameters, *dedtypes))
2701 return false;
2702 }
2703 else if (e1 && e2)
2704 {
2705 Le:
2706 e1 = e1.ctfeInterpret();
2707
2708 /* If it is one of the template parameters for this template,
2709 * we should not attempt to interpret it. It already has a value.
2710 */
2711 if (e2.op == EXP.variable && (e2.isVarExp().var.storage_class & STC.templateparameter))
2712 {
2713 /*
2714 * (T:Number!(e2), int e2)
2715 */
2716 j = templateIdentifierLookup(e2.isVarExp().var.ident, parameters);
2717 if (j != IDX_NOTFOUND)
2718 goto L1;
2719 // The template parameter was not from this template
2720 // (it may be from a parent template, for example)
2721 }
2722
2723 e2 = e2.expressionSemantic(sc); // https://issues.dlang.org/show_bug.cgi?id=13417
2724 e2 = e2.ctfeInterpret();
2725
2726 //printf("e1 = %s, type = %s %d\n", e1.toChars(), e1.type.toChars(), e1.type.ty);
2727 //printf("e2 = %s, type = %s %d\n", e2.toChars(), e2.type.toChars(), e2.type.ty);
2728 if (!e1.equals(e2))
2729 {
2730 if (!e2.implicitConvTo(e1.type))
2731 return false;
2732
2733 e2 = e2.implicitCastTo(sc, e1.type);
2734 e2 = e2.ctfeInterpret();
2735 if (!e1.equals(e2))
2736 return false;
2737 }
2738 }
2739 else if (e1 && t2 && t2.ty == Tident)
2740 {
2741 j = templateParameterLookup(t2, parameters);
2742 L1:
2743 if (j == IDX_NOTFOUND)
2744 {
2745 t2.resolve((cast(TypeIdentifier)t2).loc, sc, e2, t2, s2);
2746 if (e2)
2747 goto Le;
2748 return false;
2749 }
2750 if (!(*parameters)[j].matchArg(sc, e1, j, parameters, *dedtypes, null))
2751 return false;
2752 }
2753 else if (s1 && s2)
2754 {
2755 Ls:
2756 if (!s1.equals(s2))
2757 return false;
2758 }
2759 else if (s1 && t2 && t2.ty == Tident)
2760 {
2761 j = templateParameterLookup(t2, parameters);
2762 if (j == IDX_NOTFOUND)
2763 {
2764 t2.resolve((cast(TypeIdentifier)t2).loc, sc, e2, t2, s2);
2765 if (s2)
2766 goto Ls;
2767 return false;
2768 }
2769 if (!(*parameters)[j].matchArg(sc, s1, j, parameters, *dedtypes, null))
2770 return false;
2771 }
2772 else
2773 return false;
2774 }
2775 return true;
2776 }
2777
2778
2779 /***********************************************************
2780 * Check whether the type t representation relies on one or more the template parameters.
2781 * Params:
2782 * t = Tested type, if null, returns false.
2783 * tparams = Template parameters.
2784 * iStart = Start index of tparams to limit the tested parameters. If it's
2785 * nonzero, tparams[0..iStart] will be excluded from the test target.
2786 */
2787 bool reliesOnTident(Type t, TemplateParameters* tparams, size_t iStart = 0)
2788 {
2789 return reliesOnTemplateParameters(t, (*tparams)[0 .. tparams.length]);
2790 }
2791
2792 /***********************************************************
2793 * Check whether the type t representation relies on one or more the template parameters.
2794 * Params:
2795 * t = Tested type, if null, returns false.
2796 * tparams = Template parameters.
2797 */
2798 bool reliesOnTemplateParameters(Type t, TemplateParameter[] tparams)
2799 {
2800 bool visitVector(TypeVector t)
2801 {
2802 return t.basetype.reliesOnTemplateParameters(tparams);
2803 }
2804
2805 bool visitAArray(TypeAArray t)
2806 {
2807 return t.next.reliesOnTemplateParameters(tparams) ||
2808 t.index.reliesOnTemplateParameters(tparams);
2809 }
2810
2811 bool visitFunction(TypeFunction t)
2812 {
2813 foreach (i, fparam; t.parameterList)
2814 {
2815 if (fparam.type.reliesOnTemplateParameters(tparams))
2816 return true;
2817 }
2818 return t.next.reliesOnTemplateParameters(tparams);
2819 }
2820
2821 bool visitIdentifier(TypeIdentifier t)
2822 {
2823 foreach (tp; tparams)
2824 {
2825 if (tp.ident.equals(t.ident))
2826 return true;
2827 }
2828 return false;
2829 }
2830
2831 bool visitInstance(TypeInstance t)
2832 {
2833 foreach (tp; tparams)
2834 {
2835 if (t.tempinst.name == tp.ident)
2836 return true;
2837 }
2838
2839 if (t.tempinst.tiargs)
2840 foreach (arg; *t.tempinst.tiargs)
2841 {
2842 if (Type ta = isType(arg))
2843 {
2844 if (ta.reliesOnTemplateParameters(tparams))
2845 return true;
2846 }
2847 }
2848
2849 return false;
2850 }
2851
2852 bool visitTypeof(TypeTypeof t)
2853 {
2854 //printf("TypeTypeof.reliesOnTemplateParameters('%s')\n", t.toChars());
2855 return t.exp.reliesOnTemplateParameters(tparams);
2856 }
2857
2858 bool visitTuple(TypeTuple t)
2859 {
2860 if (t.arguments)
2861 foreach (arg; *t.arguments)
2862 {
2863 if (arg.type.reliesOnTemplateParameters(tparams))
2864 return true;
2865 }
2866
2867 return false;
2868 }
2869
2870 if (!t)
2871 return false;
2872
2873 Type tb = t.toBasetype();
2874 switch (tb.ty)
2875 {
2876 case Tvector: return visitVector(tb.isTypeVector());
2877 case Taarray: return visitAArray(tb.isTypeAArray());
2878 case Tfunction: return visitFunction(tb.isTypeFunction());
2879 case Tident: return visitIdentifier(tb.isTypeIdentifier());
2880 case Tinstance: return visitInstance(tb.isTypeInstance());
2881 case Ttypeof: return visitTypeof(tb.isTypeTypeof());
2882 case Ttuple: return visitTuple(tb.isTypeTuple());
2883 case Tenum: return false;
2884 default: return tb.nextOf().reliesOnTemplateParameters(tparams);
2885 }
2886 }
2887
2888 /***********************************************************
2889 * Check whether the expression representation relies on one or more the template parameters.
2890 * Params:
2891 * e = expression to test
2892 * tparams = Template parameters.
2893 * Returns:
2894 * true if it does
2895 */
2896 private bool reliesOnTemplateParameters(Expression e, TemplateParameter[] tparams)
2897 {
2898 extern (C++) final class ReliesOnTemplateParameters : Visitor
2899 {
2900 alias visit = Visitor.visit;
2901 public:
2902 TemplateParameter[] tparams;
2903 bool result;
2904
2905 extern (D) this(TemplateParameter[] tparams) @safe
2906 {
2907 this.tparams = tparams;
2908 }
2909
2910 override void visit(Expression e)
2911 {
2912 //printf("Expression.reliesOnTemplateParameters('%s')\n", e.toChars());
2913 }
2914
2915 override void visit(IdentifierExp e)
2916 {
2917 //printf("IdentifierExp.reliesOnTemplateParameters('%s')\n", e.toChars());
2918 foreach (tp; tparams)
2919 {
2920 if (e.ident == tp.ident)
2921 {
2922 result = true;
2923 return;
2924 }
2925 }
2926 }
2927
2928 override void visit(TupleExp e)
2929 {
2930 //printf("TupleExp.reliesOnTemplateParameters('%s')\n", e.toChars());
2931 if (e.exps)
2932 {
2933 foreach (ea; *e.exps)
2934 {
2935 ea.accept(this);
2936 if (result)
2937 return;
2938 }
2939 }
2940 }
2941
2942 override void visit(ArrayLiteralExp e)
2943 {
2944 //printf("ArrayLiteralExp.reliesOnTemplateParameters('%s')\n", e.toChars());
2945 if (e.elements)
2946 {
2947 foreach (el; *e.elements)
2948 {
2949 el.accept(this);
2950 if (result)
2951 return;
2952 }
2953 }
2954 }
2955
2956 override void visit(AssocArrayLiteralExp e)
2957 {
2958 //printf("AssocArrayLiteralExp.reliesOnTemplateParameters('%s')\n", e.toChars());
2959 foreach (ek; *e.keys)
2960 {
2961 ek.accept(this);
2962 if (result)
2963 return;
2964 }
2965 foreach (ev; *e.values)
2966 {
2967 ev.accept(this);
2968 if (result)
2969 return;
2970 }
2971 }
2972
2973 override void visit(StructLiteralExp e)
2974 {
2975 //printf("StructLiteralExp.reliesOnTemplateParameters('%s')\n", e.toChars());
2976 if (e.elements)
2977 {
2978 foreach (ea; *e.elements)
2979 {
2980 ea.accept(this);
2981 if (result)
2982 return;
2983 }
2984 }
2985 }
2986
2987 override void visit(TypeExp e)
2988 {
2989 //printf("TypeExp.reliesOnTemplateParameters('%s')\n", e.toChars());
2990 result = e.type.reliesOnTemplateParameters(tparams);
2991 }
2992
2993 override void visit(NewExp e)
2994 {
2995 //printf("NewExp.reliesOnTemplateParameters('%s')\n", e.toChars());
2996 if (e.placement)
2997 e.placement.accept(this);
2998 if (e.thisexp)
2999 e.thisexp.accept(this);
3000 result = e.newtype.reliesOnTemplateParameters(tparams);
3001 if (!result && e.arguments)
3002 {
3003 foreach (ea; *e.arguments)
3004 {
3005 ea.accept(this);
3006 if (result)
3007 return;
3008 }
3009 }
3010 }
3011
3012 override void visit(NewAnonClassExp e)
3013 {
3014 //printf("NewAnonClassExp.reliesOnTemplateParameters('%s')\n", e.toChars());
3015 result = true;
3016 }
3017
3018 override void visit(FuncExp e)
3019 {
3020 //printf("FuncExp.reliesOnTemplateParameters('%s')\n", e.toChars());
3021 result = true;
3022 }
3023
3024 override void visit(TypeidExp e)
3025 {
3026 //printf("TypeidExp.reliesOnTemplateParameters('%s')\n", e.toChars());
3027 if (auto ea = isExpression(e.obj))
3028 ea.accept(this);
3029 else if (auto ta = isType(e.obj))
3030 result = ta.reliesOnTemplateParameters(tparams);
3031 }
3032
3033 override void visit(TraitsExp e)
3034 {
3035 //printf("TraitsExp.reliesOnTemplateParameters('%s')\n", e.toChars());
3036 if (e.args)
3037 {
3038 foreach (oa; *e.args)
3039 {
3040 if (auto ea = isExpression(oa))
3041 ea.accept(this);
3042 else if (auto ta = isType(oa))
3043 result = ta.reliesOnTemplateParameters(tparams);
3044 if (result)
3045 return;
3046 }
3047 }
3048 }
3049
3050 override void visit(IsExp e)
3051 {
3052 //printf("IsExp.reliesOnTemplateParameters('%s')\n", e.toChars());
3053 result = e.targ.reliesOnTemplateParameters(tparams);
3054 }
3055
3056 override void visit(UnaExp e)
3057 {
3058 //printf("UnaExp.reliesOnTemplateParameters('%s')\n", e.toChars());
3059 e.e1.accept(this);
3060 }
3061
3062 override void visit(DotTemplateInstanceExp e)
3063 {
3064 //printf("DotTemplateInstanceExp.reliesOnTemplateParameters('%s')\n", e.toChars());
3065 visit(e.isUnaExp());
3066 if (!result && e.ti.tiargs)
3067 {
3068 foreach (oa; *e.ti.tiargs)
3069 {
3070 if (auto ea = isExpression(oa))
3071 ea.accept(this);
3072 else if (auto ta = isType(oa))
3073 result = ta.reliesOnTemplateParameters(tparams);
3074 if (result)
3075 return;
3076 }
3077 }
3078 }
3079
3080 override void visit(CallExp e)
3081 {
3082 //printf("CallExp.reliesOnTemplateParameters('%s')\n", e.toChars());
3083 visit(e.isUnaExp());
3084 if (!result && e.arguments)
3085 {
3086 foreach (ea; *e.arguments)
3087 {
3088 ea.accept(this);
3089 if (result)
3090 return;
3091 }
3092 }
3093 }
3094
3095 override void visit(CastExp e)
3096 {
3097 //printf("CallExp.reliesOnTemplateParameters('%s')\n", e.toChars());
3098 visit(e.isUnaExp());
3099 // e.to can be null for cast() with no type
3100 if (!result && e.to)
3101 result = e.to.reliesOnTemplateParameters(tparams);
3102 }
3103
3104 override void visit(SliceExp e)
3105 {
3106 //printf("SliceExp.reliesOnTemplateParameters('%s')\n", e.toChars());
3107 visit(e.isUnaExp());
3108 if (!result && e.lwr)
3109 e.lwr.accept(this);
3110 if (!result && e.upr)
3111 e.upr.accept(this);
3112 }
3113
3114 override void visit(IntervalExp e)
3115 {
3116 //printf("IntervalExp.reliesOnTemplateParameters('%s')\n", e.toChars());
3117 e.lwr.accept(this);
3118 if (!result)
3119 e.upr.accept(this);
3120 }
3121
3122 override void visit(ArrayExp e)
3123 {
3124 //printf("ArrayExp.reliesOnTemplateParameters('%s')\n", e.toChars());
3125 visit(e.isUnaExp());
3126 if (!result && e.arguments)
3127 {
3128 foreach (ea; *e.arguments)
3129 ea.accept(this);
3130 }
3131 }
3132
3133 override void visit(BinExp e)
3134 {
3135 //printf("BinExp.reliesOnTemplateParameters('%s')\n", e.toChars());
3136 e.e1.accept(this);
3137 if (!result)
3138 e.e2.accept(this);
3139 }
3140
3141 override void visit(CondExp e)
3142 {
3143 //printf("BinExp.reliesOnTemplateParameters('%s')\n", e.toChars());
3144 e.econd.accept(this);
3145 if (!result)
3146 visit(e.isBinExp());
3147 }
3148 }
3149
3150 scope ReliesOnTemplateParameters v = new ReliesOnTemplateParameters(tparams);
3151 e.accept(v);
3152 return v.result;
3153 }
3154
3155 /***********************************************************
3156 * https://dlang.org/spec/template.html#TemplateParameter
3157 */
3158 extern (C++) class TemplateParameter : ASTNode
3159 {
3160 Loc loc;
3161 Identifier ident;
3162
3163 /* True if this is a part of precedent parameter specialization pattern.
3164 *
3165 * template A(T : X!TL, alias X, TL...) {}
3166 * // X and TL are dependent template parameter
3167 *
3168 * A dependent template parameter should return MATCH.exact in matchArg()
3169 * to respect the match level of the corresponding precedent parameter.
3170 */
3171 bool dependent;
3172
3173 /* ======================== TemplateParameter =============================== */
3174 extern (D) this(Loc loc, Identifier ident) @safe
3175 {
3176 this.loc = loc;
3177 this.ident = ident;
3178 }
3179
3180 TemplateTypeParameter isTemplateTypeParameter()
3181 {
3182 return null;
3183 }
3184
3185 TemplateValueParameter isTemplateValueParameter()
3186 {
3187 return null;
3188 }
3189
3190 TemplateAliasParameter isTemplateAliasParameter()
3191 {
3192 return null;
3193 }
3194
3195 TemplateThisParameter isTemplateThisParameter()
3196 {
3197 return null;
3198 }
3199
3200 TemplateTupleParameter isTemplateTupleParameter()
3201 {
3202 return null;
3203 }
3204
3205 abstract TemplateParameter syntaxCopy();
3206
3207 abstract bool declareParameter(Scope* sc);
3208
3209 abstract void print(RootObject oarg, RootObject oded);
3210
3211 abstract RootObject specialization();
3212
3213 abstract RootObject defaultArg(Loc instLoc, Scope* sc);
3214
3215 abstract bool hasDefaultArg();
3216
3217 override const(char)* toChars() const
3218 {
3219 return this.ident.toChars();
3220 }
3221
3222 override DYNCAST dyncast() const
3223 {
3224 return DYNCAST.templateparameter;
3225 }
3226
3227 override void accept(Visitor v)
3228 {
3229 v.visit(this);
3230 }
3231 }
3232
3233 /***********************************************************
3234 * https://dlang.org/spec/template.html#TemplateTypeParameter
3235 * Syntax:
3236 * ident : specType = defaultType
3237 */
3238 extern (C++) class TemplateTypeParameter : TemplateParameter
3239 {
3240 Type specType; // if !=null, this is the type specialization
3241 Type defaultType;
3242
3243 extern (D) __gshared Type tdummy = null;
3244
3245 extern (D) this(Loc loc, Identifier ident, Type specType, Type defaultType) @safe
3246 {
3247 super(loc, ident);
3248 this.specType = specType;
3249 this.defaultType = defaultType;
3250 }
3251
3252 override final TemplateTypeParameter isTemplateTypeParameter()
3253 {
3254 return this;
3255 }
3256
3257 override TemplateTypeParameter syntaxCopy()
3258 {
3259 return new TemplateTypeParameter(loc, ident, specType ? specType.syntaxCopy() : null, defaultType ? defaultType.syntaxCopy() : null);
3260 }
3261
3262 override final bool declareParameter(Scope* sc)
3263 {
3264 //printf("TemplateTypeParameter.declareParameter('%s')\n", ident.toChars());
3265 auto ti = new TypeIdentifier(loc, ident);
3266 Declaration ad = new AliasDeclaration(loc, ident, ti);
3267 return sc.insert(ad) !is null;
3268 }
3269
3270 override final void print(RootObject oarg, RootObject oded)
3271 {
3272 printf(" %s\n", ident.toChars());
3273
3274 Type t = isType(oarg);
3275 Type ta = isType(oded);
3276 assert(ta);
3277
3278 if (specType)
3279 printf("\tSpecialization: %s\n", specType.toChars());
3280 if (defaultType)
3281 printf("\tDefault: %s\n", defaultType.toChars());
3282 printf("\tParameter: %s\n", t ? t.toChars() : "NULL");
3283 printf("\tDeduced Type: %s\n", ta.toChars());
3284 }
3285
3286 override final RootObject specialization()
3287 {
3288 return specType;
3289 }
3290
3291 override final RootObject defaultArg(Loc instLoc, Scope* sc)
3292 {
3293 Type t = defaultType;
3294 if (t)
3295 {
3296 t = t.syntaxCopy();
3297 t = t.typeSemantic(loc, sc); // use the parameter loc
3298 }
3299 return t;
3300 }
3301
3302 override final bool hasDefaultArg()
3303 {
3304 return defaultType !is null;
3305 }
3306
3307 override void accept(Visitor v)
3308 {
3309 v.visit(this);
3310 }
3311 }
3312
3313 /***********************************************************
3314 * https://dlang.org/spec/template.html#TemplateThisParameter
3315 * Syntax:
3316 * this ident : specType = defaultType
3317 */
3318 extern (C++) final class TemplateThisParameter : TemplateTypeParameter
3319 {
3320 extern (D) this(Loc loc, Identifier ident, Type specType, Type defaultType) @safe
3321 {
3322 super(loc, ident, specType, defaultType);
3323 }
3324
3325 override TemplateThisParameter isTemplateThisParameter()
3326 {
3327 return this;
3328 }
3329
3330 override TemplateThisParameter syntaxCopy()
3331 {
3332 return new TemplateThisParameter(loc, ident, specType ? specType.syntaxCopy() : null, defaultType ? defaultType.syntaxCopy() : null);
3333 }
3334
3335 override void accept(Visitor v)
3336 {
3337 v.visit(this);
3338 }
3339 }
3340
3341 /***********************************************************
3342 * https://dlang.org/spec/template.html#TemplateValueParameter
3343 * Syntax:
3344 * valType ident : specValue = defaultValue
3345 */
3346 extern (C++) final class TemplateValueParameter : TemplateParameter
3347 {
3348 Type valType;
3349 Expression specValue;
3350 Expression defaultValue;
3351
3352 extern (D) __gshared Expression[void*] edummies;
3353
3354 extern (D) this(Loc loc, Identifier ident, Type valType,
3355 Expression specValue, Expression defaultValue) @safe
3356 {
3357 super(loc, ident);
3358 this.valType = valType;
3359 this.specValue = specValue;
3360 this.defaultValue = defaultValue;
3361 }
3362
3363 override TemplateValueParameter isTemplateValueParameter()
3364 {
3365 return this;
3366 }
3367
3368 override TemplateValueParameter syntaxCopy()
3369 {
3370 return new TemplateValueParameter(loc, ident,
3371 valType.syntaxCopy(),
3372 specValue ? specValue.syntaxCopy() : null,
3373 defaultValue ? defaultValue.syntaxCopy() : null);
3374 }
3375
3376 override bool declareParameter(Scope* sc)
3377 {
3378 /*
3379 Do type semantic earlier.
3380
3381 This means for certain erroneous value parameters
3382 their "type" can be known earlier and thus a better
3383 error message given.
3384
3385 For example:
3386 `template test(x* x) {}`
3387 now yields "undefined identifier" rather than the opaque
3388 "variable `x` is used as a type".
3389 */
3390 if (valType)
3391 valType = valType.typeSemantic(loc, sc);
3392 auto v = new VarDeclaration(loc, valType, ident, null);
3393 v.storage_class = STC.templateparameter;
3394 return sc.insert(v) !is null;
3395 }
3396
3397 override void print(RootObject oarg, RootObject oded)
3398 {
3399 printf(" %s\n", ident.toChars());
3400 Expression ea = isExpression(oded);
3401 if (specValue)
3402 printf("\tSpecialization: %s\n", specValue.toChars());
3403 printf("\tParameter Value: %s\n", ea ? ea.toChars() : "NULL");
3404 }
3405
3406 override RootObject specialization()
3407 {
3408 return specValue;
3409 }
3410
3411 override RootObject defaultArg(Loc instLoc, Scope* sc)
3412 {
3413 Expression e = defaultValue;
3414 if (!e)
3415 return null;
3416
3417 e = e.syntaxCopy();
3418 Scope* sc2 = sc.push();
3419 sc2.inDefaultArg = true;
3420 e = e.expressionSemantic(sc2);
3421 sc2.pop();
3422 if (e is null)
3423 return null;
3424 if (auto te = e.isTemplateExp())
3425 {
3426 assert(sc && sc.tinst);
3427 if (te.td == sc.tinst.tempdecl)
3428 {
3429 // defaultValue is a reference to its template declaration
3430 // i.e: `template T(int arg = T)`
3431 // Raise error now before calling resolveProperties otherwise we'll
3432 // start looping on the expansion of the template instance.
3433 auto td = sc.tinst.tempdecl;
3434 .error(td.loc, "%s `%s` recursive template expansion", td.kind, td.toPrettyChars);
3435 return ErrorExp.get();
3436 }
3437 }
3438 if ((e = resolveProperties(sc, e)) is null)
3439 return null;
3440 e = e.resolveLoc(instLoc, sc); // use the instantiated loc
3441 e = e.optimize(WANTvalue);
3442
3443 return e;
3444 }
3445
3446 override bool hasDefaultArg()
3447 {
3448 return defaultValue !is null;
3449 }
3450
3451 override void accept(Visitor v)
3452 {
3453 v.visit(this);
3454 }
3455 }
3456
3457 /***********************************************************
3458 * https://dlang.org/spec/template.html#TemplateAliasParameter
3459 * Syntax:
3460 * specType ident : specAlias = defaultAlias
3461 */
3462 extern (C++) final class TemplateAliasParameter : TemplateParameter
3463 {
3464 Type specType;
3465 RootObject specAlias;
3466 RootObject defaultAlias;
3467
3468 extern (D) __gshared Dsymbol sdummy = null;
3469
3470 extern (D) this(Loc loc, Identifier ident, Type specType, RootObject specAlias, RootObject defaultAlias) @safe
3471 {
3472 super(loc, ident);
3473 this.specType = specType;
3474 this.specAlias = specAlias;
3475 this.defaultAlias = defaultAlias;
3476 }
3477
3478 override TemplateAliasParameter isTemplateAliasParameter()
3479 {
3480 return this;
3481 }
3482
3483 override TemplateAliasParameter syntaxCopy()
3484 {
3485 return new TemplateAliasParameter(loc, ident, specType ? specType.syntaxCopy() : null, objectSyntaxCopy(specAlias), objectSyntaxCopy(defaultAlias));
3486 }
3487
3488 override bool declareParameter(Scope* sc)
3489 {
3490 auto ti = new TypeIdentifier(loc, ident);
3491 Declaration ad = new AliasDeclaration(loc, ident, ti);
3492 return sc.insert(ad) !is null;
3493 }
3494
3495 override void print(RootObject oarg, RootObject oded)
3496 {
3497 printf(" %s\n", ident.toChars());
3498 Dsymbol sa = isDsymbol(oded);
3499 assert(sa);
3500 printf("\tParameter alias: %s\n", sa.toChars());
3501 }
3502
3503 override RootObject specialization()
3504 {
3505 return specAlias;
3506 }
3507
3508 override RootObject defaultArg(Loc instLoc, Scope* sc)
3509 {
3510 RootObject da = defaultAlias;
3511 if (auto ta = isType(defaultAlias))
3512 {
3513 switch (ta.ty)
3514 {
3515 // If the default arg is a template, instantiate for each type
3516 case Tinstance :
3517 // same if the default arg is a mixin, traits, typeof
3518 // since the content might rely on a previous parameter
3519 // (https://issues.dlang.org/show_bug.cgi?id=23686)
3520 case Tmixin, Ttypeof, Ttraits :
3521 da = ta.syntaxCopy();
3522 break;
3523 default:
3524 }
3525 }
3526
3527 RootObject o = aliasParameterSemantic(loc, sc, da, null); // use the parameter loc
3528 return o;
3529 }
3530
3531 override bool hasDefaultArg()
3532 {
3533 return defaultAlias !is null;
3534 }
3535
3536 override void accept(Visitor v)
3537 {
3538 v.visit(this);
3539 }
3540 }
3541
3542 /***********************************************************
3543 * https://dlang.org/spec/template.html#TemplateSequenceParameter
3544 * Syntax:
3545 * ident ...
3546 */
3547 extern (C++) final class TemplateTupleParameter : TemplateParameter
3548 {
3549 extern (D) this(Loc loc, Identifier ident) @safe
3550 {
3551 super(loc, ident);
3552 }
3553
3554 override TemplateTupleParameter isTemplateTupleParameter()
3555 {
3556 return this;
3557 }
3558
3559 override TemplateTupleParameter syntaxCopy()
3560 {
3561 return new TemplateTupleParameter(loc, ident);
3562 }
3563
3564 override bool declareParameter(Scope* sc)
3565 {
3566 auto ti = new TypeIdentifier(loc, ident);
3567 Declaration ad = new AliasDeclaration(loc, ident, ti);
3568 return sc.insert(ad) !is null;
3569 }
3570
3571 override void print(RootObject oarg, RootObject oded)
3572 {
3573 printf(" %s... [", ident.toChars());
3574 Tuple v = isTuple(oded);
3575 assert(v);
3576
3577 //printf("|%d| ", v.objects.length);
3578 foreach (i, o; v.objects)
3579 {
3580 if (i)
3581 printf(", ");
3582
3583 Dsymbol sa = isDsymbol(o);
3584 if (sa)
3585 printf("alias: %s", sa.toChars());
3586 Type ta = isType(o);
3587 if (ta)
3588 printf("type: %s", ta.toChars());
3589 Expression ea = isExpression(o);
3590 if (ea)
3591 printf("exp: %s", ea.toChars());
3592
3593 assert(!isTuple(o)); // no nested Tuple arguments
3594 }
3595 printf("]\n");
3596 }
3597
3598 override RootObject specialization()
3599 {
3600 return null;
3601 }
3602
3603 override RootObject defaultArg(Loc instLoc, Scope* sc)
3604 {
3605 return null;
3606 }
3607
3608 override bool hasDefaultArg()
3609 {
3610 return false;
3611 }
3612
3613 override void accept(Visitor v)
3614 {
3615 v.visit(this);
3616 }
3617 }
3618
3619 /***********************************************************
3620 * https://dlang.org/spec/template.html#explicit_tmp_instantiation
3621 * Given:
3622 * foo!(args) =>
3623 * name = foo
3624 * tiargs = args
3625 */
3626 extern (C++) class TemplateInstance : ScopeDsymbol
3627 {
3628 Identifier name;
3629
3630 // Array of Types/Expressions of template
3631 // instance arguments [int*, char, 10*10]
3632 Objects* tiargs;
3633
3634 // Array of Types/Expressions corresponding
3635 // to TemplateDeclaration.parameters
3636 // [int, char, 100]
3637 Objects tdtypes;
3638
3639 // Modules imported by this template instance
3640 Modules importedModules;
3641
3642 Dsymbol tempdecl; // referenced by foo.bar.abc
3643 Dsymbol enclosing; // if referencing local symbols, this is the context
3644 Dsymbol aliasdecl; // !=null if instance is an alias for its sole member
3645
3646 /**
3647 If this is not null and it has a value that is not the current object,
3648 then this field points to an existing template instance
3649 and that object has been duplicated into us.
3650
3651 If this object is a duplicate,
3652 the ``memberOf`` field will be set to a root module (passed on CLI).
3653
3654 This information is useful to deduplicate analysis that may occur
3655 after semantic 3 has completed.
3656
3657 See_Also: memberOf
3658 */
3659 TemplateInstance inst;
3660
3661 ScopeDsymbol argsym; // argument symbol table
3662 size_t hash; // cached result of toHash()
3663
3664 /// For function template, these are the function names and arguments
3665 /// Relevant because different resolutions of `auto ref` parameters
3666 /// create different template instances even with the same template arguments
3667 Expressions* fargs;
3668 Identifiers* fnames;
3669
3670 TemplateInstances* deferred;
3671
3672 /**
3673 If this is not null then this template instance appears in a root module's members.
3674
3675 Note: This is not useful for determining duplication status of this template instance.
3676 Use the field ``inst`` for determining if a template instance has been duplicated into this object.
3677
3678 See_Also: inst
3679 */
3680 Module memberOf;
3681
3682 // Used to determine the instance needs code generation.
3683 // Note that these are inaccurate until semantic analysis phase completed.
3684 TemplateInstance tinst; // enclosing template instance
3685 TemplateInstance tnext; // non-first instantiated instances
3686 Module minst; // the top module that instantiated this instance
3687
3688 private ushort _nest; // for recursive pretty printing detection, 3 MSBs reserved for flags (below)
3689 ubyte inuse; // for recursive expansion detection
3690
3691 private enum Flag : uint
3692 {
3693 semantictiargsdone = 1u << (_nest.sizeof * 8 - 1), // MSB of _nest
3694 havetempdecl = semantictiargsdone >> 1,
3695 gagged = semantictiargsdone >> 2,
3696 available = gagged - 1 // always last flag minus one, 1s for all available bits
3697 }
3698
3699 extern(D) final @safe @property pure nothrow @nogc
3700 {
3701 ushort nest() const { return _nest & Flag.available; }
3702 void nestUp() { assert(nest() < Flag.available); ++_nest; }
3703 void nestDown() { assert(nest() > 0); --_nest; }
3704 /// has semanticTiargs() been done?
3705 bool semantictiargsdone() const { return (_nest & Flag.semantictiargsdone) != 0; }
3706 void semantictiargsdone(bool x)
3707 {
3708 if (x) _nest |= Flag.semantictiargsdone;
3709 else _nest &= ~Flag.semantictiargsdone;
3710 }
3711 /// if used second constructor
3712 bool havetempdecl() const { return (_nest & Flag.havetempdecl) != 0; }
3713 void havetempdecl(bool x)
3714 {
3715 if (x) _nest |= Flag.havetempdecl;
3716 else _nest &= ~Flag.havetempdecl;
3717 }
3718 /// if the instantiation is done with error gagging
3719 bool gagged() const { return (_nest & Flag.gagged) != 0; }
3720 void gagged(bool x)
3721 {
3722 if (x) _nest |= Flag.gagged;
3723 else _nest &= ~Flag.gagged;
3724 }
3725 }
3726
3727 extern (D) this(Loc loc, Identifier ident, Objects* tiargs) scope
3728 {
3729 super(loc, null);
3730 static if (LOG)
3731 {
3732 printf("TemplateInstance(this = %p, ident = '%s')\n", this, ident ? ident.toChars() : "null");
3733 }
3734 this.dsym = DSYM.templateInstance;
3735 this.name = ident;
3736 this.tiargs = tiargs;
3737 }
3738
3739 /*****************
3740 * This constructor is only called when we figured out which function
3741 * template to instantiate.
3742 */
3743 extern (D) this(Loc loc, TemplateDeclaration td, Objects* tiargs) scope
3744 {
3745 super(loc, null);
3746 static if (LOG)
3747 {
3748 printf("TemplateInstance(this = %p, tempdecl = '%s')\n", this, td.toChars());
3749 }
3750 this.dsym = DSYM.templateInstance;
3751 this.name = td.ident;
3752 this.tiargs = tiargs;
3753 this.tempdecl = td;
3754 this.semantictiargsdone = true;
3755 this.havetempdecl = true;
3756 assert(tempdecl._scope);
3757 }
3758
3759 extern (D) static Objects* arraySyntaxCopy(Objects* objs)
3760 {
3761 Objects* a = null;
3762 if (objs)
3763 {
3764 a = new Objects(objs.length);
3765 foreach (i, o; *objs)
3766 (*a)[i] = objectSyntaxCopy(o);
3767 }
3768 return a;
3769 }
3770
3771 override TemplateInstance syntaxCopy(Dsymbol s)
3772 {
3773 TemplateInstance ti = s ? cast(TemplateInstance)s : new TemplateInstance(loc, name, null);
3774 ti.tiargs = arraySyntaxCopy(tiargs);
3775 TemplateDeclaration td;
3776 if (inst && tempdecl && (td = tempdecl.isTemplateDeclaration()) !is null)
3777 td.ScopeDsymbol.syntaxCopy(ti);
3778 else
3779 ScopeDsymbol.syntaxCopy(ti);
3780 return ti;
3781 }
3782
3783 // resolve real symbol
3784 override final Dsymbol toAlias()
3785 {
3786 static if (LOG)
3787 {
3788 printf("TemplateInstance.toAlias()\n");
3789 }
3790 if (!inst)
3791 {
3792 // Maybe we can resolve it
3793 if (_scope)
3794 {
3795 dsymbolSemantic(this, _scope);
3796 }
3797 if (!inst)
3798 {
3799 .error(loc, "%s `%s` cannot resolve forward reference", kind, toPrettyChars);
3800 errors = true;
3801 return this;
3802 }
3803 }
3804
3805 if (inst != this)
3806 return inst.toAlias();
3807
3808 if (aliasdecl)
3809 {
3810 return aliasdecl.toAlias();
3811 }
3812
3813 return inst;
3814 }
3815
3816 override const(char)* kind() const
3817 {
3818 return "template instance";
3819 }
3820
3821 override final const(char)* toPrettyCharsHelper()
3822 {
3823 OutBuffer buf;
3824 toCBufferInstance(this, buf, true);
3825 return buf.extractChars();
3826 }
3827
3828 /**************************************
3829 * Given an error instantiating the TemplateInstance,
3830 * give the nested TemplateInstance instantiations that got
3831 * us here. Those are a list threaded into the nested scopes.
3832 * Params:
3833 * cl = classification of this trace as printing either errors or deprecations
3834 * max_shown = maximum number of trace elements printed (controlled with -v/-verror-limit)
3835 */
3836 extern(D) final void printInstantiationTrace(Classification cl = Classification.error,
3837 const(uint) max_shown = global.params.v.errorSupplementCount())
3838 {
3839 if (global.gag)
3840 return;
3841
3842 // Print full trace for verbose mode, otherwise only short traces
3843 const(char)* format = "instantiated from here: `%s`";
3844
3845 // This returns a function pointer
3846 scope printFn = () {
3847 final switch (cl)
3848 {
3849 case Classification.error:
3850 return &errorSupplemental;
3851 case Classification.deprecation:
3852 return &deprecationSupplemental;
3853 case Classification.gagged, Classification.tip, Classification.warning:
3854 assert(0);
3855 }
3856 }();
3857
3858 // determine instantiation depth and number of recursive instantiations
3859 int n_instantiations = 1;
3860 int n_totalrecursions = 0;
3861 for (TemplateInstance cur = this; cur; cur = cur.tinst)
3862 {
3863 ++n_instantiations;
3864 // Set error here as we don't want it to depend on the number of
3865 // entries that are being printed.
3866 if (cl == Classification.error ||
3867 (cl == Classification.warning && global.params.useWarnings == DiagnosticReporting.error) ||
3868 (cl == Classification.deprecation && global.params.useDeprecated == DiagnosticReporting.error))
3869 cur.errors = true;
3870
3871 // If two instantiations use the same declaration, they are recursive.
3872 // (this works even if they are instantiated from different places in the
3873 // same template).
3874 // In principle, we could also check for multiple-template recursion, but it's
3875 // probably not worthwhile.
3876 if (cur.tinst && cur.tempdecl && cur.tinst.tempdecl && cur.tempdecl.loc.equals(cur.tinst.tempdecl.loc))
3877 ++n_totalrecursions;
3878 }
3879
3880 if (n_instantiations <= max_shown)
3881 {
3882 for (TemplateInstance cur = this; cur; cur = cur.tinst)
3883 printFn(cur.loc, format, cur.toErrMsg());
3884 }
3885 else if (n_instantiations - n_totalrecursions <= max_shown)
3886 {
3887 // By collapsing recursive instantiations into a single line,
3888 // we can stay under the limit.
3889 int recursionDepth = 0;
3890 for (TemplateInstance cur = this; cur; cur = cur.tinst)
3891 {
3892 if (cur.tinst && cur.tempdecl && cur.tinst.tempdecl && cur.tempdecl.loc.equals(cur.tinst.tempdecl.loc))
3893 {
3894 ++recursionDepth;
3895 }
3896 else
3897 {
3898 if (recursionDepth)
3899 printFn(cur.loc, "%d recursive instantiations from here: `%s`", recursionDepth + 2, cur.toChars());
3900 else
3901 printFn(cur.loc, format, cur.toChars());
3902 recursionDepth = 0;
3903 }
3904 }
3905 }
3906 else
3907 {
3908 // Even after collapsing the recursions, the depth is too deep.
3909 // Just display the first few and last few instantiations.
3910 uint i = 0;
3911 for (TemplateInstance cur = this; cur; cur = cur.tinst)
3912 {
3913 if (i == max_shown / 2)
3914 printFn(cur.loc, "... (%d instantiations, -v to show) ...", n_instantiations - max_shown);
3915
3916 if (i < max_shown / 2 || i >= n_instantiations - max_shown + max_shown / 2)
3917 printFn(cur.loc, format, cur.toChars());
3918 ++i;
3919 }
3920 }
3921 }
3922
3923 /*************************************
3924 * Lazily generate identifier for template instance.
3925 * This is because 75% of the ident's are never needed.
3926 */
3927 override final Identifier getIdent()
3928 {
3929 if (!ident && inst && !errors)
3930 ident = genIdent(tiargs); // need an identifier for name mangling purposes.
3931 return ident;
3932 }
3933
3934 /*************************************
3935 * Compare proposed template instantiation with existing template instantiation.
3936 * Note that this is not commutative because of the auto ref check.
3937 * Params:
3938 * ti = existing template instantiation
3939 * Returns:
3940 * true for match
3941 */
3942 final bool equalsx(TemplateInstance ti)
3943 {
3944 //printf("this = %p, ti = %p\n", this, ti);
3945 assert(tdtypes.length == ti.tdtypes.length);
3946
3947 // Nesting must match
3948 if (enclosing != ti.enclosing)
3949 {
3950 //printf("test2 enclosing %s ti.enclosing %s\n", enclosing ? enclosing.toChars() : "", ti.enclosing ? ti.enclosing.toChars() : "");
3951 return false;
3952 }
3953 //printf("parent = %s, ti.parent = %s\n", parent.toPrettyChars(), ti.parent.toPrettyChars());
3954
3955 if (!arrayObjectMatch(tdtypes, ti.tdtypes))
3956 return false;
3957
3958 /* Template functions may have different instantiations based on
3959 * "auto ref" parameters.
3960 */
3961 auto fd = ti.toAlias().isFuncDeclaration();
3962 if (!fd)
3963 return true;
3964 if (fd.errors)
3965 return true;
3966
3967 auto resolvedArgs = fd.type.isTypeFunction().resolveNamedArgs(
3968 ArgumentList(this.fargs, this.fnames), null);
3969
3970 // resolvedArgs can be null when there's an error: fail_compilation/fail14669.d
3971 // In that case, equalsx returns true to prevent endless template instantiations
3972 // However, it can also mean the function was explicitly instantiated
3973 // without function arguments: fail_compilation/fail14669
3974 // Hence the following check:
3975 if (this.fargs && !resolvedArgs)
3976 return true;
3977
3978 Expression[] args = resolvedArgs ? (*resolvedArgs)[] : [];
3979
3980 auto fparameters = fd.getParameterList();
3981 size_t nfparams = fparameters.length; // Num function parameters
3982 for (size_t j = 0; j < nfparams; j++)
3983 {
3984 Parameter fparam = fparameters[j];
3985 if (!(fparam.storageClass & STC.autoref) ) // if "auto ref"
3986 continue;
3987
3988 Expression farg = (j < args.length) ? args[j] : fparam.defaultArg;
3989 // resolveNamedArgs strips trailing nulls / default params
3990 // when it doesn't anymore, the ternary can be replaced with:
3991 // assert(j < resolvedArgs.length);
3992 if (!farg)
3993 farg = fparam.defaultArg;
3994 if (!farg)
3995 return false;
3996 if (farg.isLvalue())
3997 {
3998 if (!(fparam.storageClass & STC.ref_))
3999 return false; // auto ref's don't match
4000 }
4001 else
4002 {
4003 if (fparam.storageClass & STC.ref_)
4004 return false; // auto ref's don't match
4005 }
4006 }
4007 return true;
4008 }
4009
4010 extern (D) final size_t toHash()
4011 {
4012 if (!hash)
4013 {
4014 hash = cast(size_t)cast(void*)enclosing;
4015 hash += arrayObjectHash(tdtypes);
4016 hash += hash == 0;
4017 }
4018 return hash;
4019 }
4020
4021 /**
4022 Returns: true if the instances' innards are discardable.
4023
4024 The idea of this function is to see if the template instantiation
4025 can be 100% replaced with its eponymous member. All other members
4026 can be discarded, even in the compiler to free memory (for example,
4027 the template could be expanded in a region allocator, deemed trivial,
4028 the end result copied back out independently and the entire region freed),
4029 and can be elided entirely from the binary.
4030
4031 The current implementation affects code that generally looks like:
4032
4033 ---
4034 template foo(args...) {
4035 some_basic_type_or_string helper() { .... }
4036 enum foo = helper();
4037 }
4038 ---
4039
4040 since it was the easiest starting point of implementation but it can and
4041 should be expanded more later.
4042 */
4043 final bool isDiscardable()
4044 {
4045 if (aliasdecl is null)
4046 return false;
4047
4048 auto v = aliasdecl.isVarDeclaration();
4049 if (v is null)
4050 return false;
4051
4052 if (!(v.storage_class & STC.manifest))
4053 return false;
4054
4055 // Currently only doing basic types here because it is the easiest proof-of-concept
4056 // implementation with minimal risk of side effects, but it could likely be
4057 // expanded to any type that already exists outside this particular instance.
4058 if (!(v.type.equals(Type.tstring) || (v.type.isTypeBasic() !is null)))
4059 return false;
4060
4061 // Static ctors and dtors, even in an eponymous enum template, are still run,
4062 // so if any of them are in here, we'd better not assume it is trivial lest
4063 // we break useful code
4064 foreach(member; *members)
4065 {
4066 if(member.hasStaticCtorOrDtor())
4067 return false;
4068 if(member.isStaticDtorDeclaration())
4069 return false;
4070 if(member.isStaticCtorDeclaration())
4071 return false;
4072 }
4073
4074 // but if it passes through this gauntlet... it should be fine. D code will
4075 // see only the eponymous member, outside stuff can never access it, even through
4076 // reflection; the outside world ought to be none the wiser. Even dmd should be
4077 // able to simply free the memory of everything except the final result.
4078
4079 return true;
4080 }
4081
4082
4083 /***********************************************
4084 * Returns true if this is not instantiated in non-root module, and
4085 * is a part of non-speculative instantiatiation.
4086 *
4087 * Note: minst does not stabilize until semantic analysis is completed,
4088 * so don't call this function during semantic analysis to return precise result.
4089 */
4090 final bool needsCodegen()
4091 {
4092 //printf("needsCodegen() %s\n", toChars());
4093
4094 // minst is finalized after the 1st invocation.
4095 // tnext is only needed for the 1st invocation and
4096 // cleared for further invocations.
4097 TemplateInstance tnext = this.tnext;
4098 TemplateInstance tinst = this.tinst;
4099 this.tnext = null;
4100
4101 // Don't do codegen if the instance has errors,
4102 // is a dummy instance (see evaluateConstraint),
4103 // or is determined to be discardable.
4104 if (errors || inst is null || inst.isDiscardable())
4105 {
4106 minst = null; // mark as speculative
4107 return false;
4108 }
4109
4110 // This should only be called on the primary instantiation.
4111 assert(this is inst);
4112
4113 if (global.params.allInst)
4114 {
4115 // Do codegen if there is an instantiation from a root module, to maximize link-ability.
4116 static ThreeState needsCodegenAllInst(TemplateInstance tithis, TemplateInstance tinst)
4117 {
4118 // Do codegen if `this` is instantiated from a root module.
4119 if (tithis.minst && tithis.minst.isRoot())
4120 return ThreeState.yes;
4121
4122 // Do codegen if the ancestor needs it.
4123 if (tinst && tinst.inst && tinst.inst.needsCodegen())
4124 {
4125 tithis.minst = tinst.inst.minst; // cache result
4126 assert(tithis.minst);
4127 assert(tithis.minst.isRoot());
4128 return ThreeState.yes;
4129 }
4130 return ThreeState.none;
4131 }
4132
4133 if (const needsCodegen = needsCodegenAllInst(this, tinst))
4134 return needsCodegen == ThreeState.yes ? true : false;
4135
4136 // Do codegen if a sibling needs it.
4137 for (; tnext; tnext = tnext.tnext)
4138 {
4139 const needsCodegen = needsCodegenAllInst(tnext, tnext.tinst);
4140 if (needsCodegen == ThreeState.yes)
4141 {
4142 minst = tnext.minst; // cache result
4143 assert(minst);
4144 assert(minst.isRoot());
4145 return true;
4146 }
4147 else if (!minst && tnext.minst)
4148 {
4149 minst = tnext.minst; // cache result from non-speculative sibling
4150 // continue searching
4151 }
4152 else if (needsCodegen != ThreeState.none)
4153 break;
4154 }
4155
4156 // Elide codegen because there's no instantiation from any root modules.
4157 return false;
4158 }
4159
4160 // Prefer instantiations from non-root modules, to minimize object code size.
4161
4162 /* If a TemplateInstance is ever instantiated from a non-root module,
4163 * we do not have to generate code for it,
4164 * because it will be generated when the non-root module is compiled.
4165 *
4166 * But, if the non-root 'minst' imports any root modules, it might still need codegen.
4167 *
4168 * The problem is if A imports B, and B imports A, and both A
4169 * and B instantiate the same template, does the compilation of A
4170 * or the compilation of B do the actual instantiation?
4171 *
4172 * See https://issues.dlang.org/show_bug.cgi?id=2500.
4173 *
4174 * => Elide codegen if there is at least one instantiation from a non-root module
4175 * which doesn't import any root modules.
4176 */
4177 static ThreeState needsCodegenRootOnly(TemplateInstance tithis, TemplateInstance tinst)
4178 {
4179 // If the ancestor isn't speculative,
4180 // 1. do codegen if the ancestor needs it
4181 // 2. elide codegen if the ancestor doesn't need it (non-root instantiation of ancestor incl. subtree)
4182 if (tinst && tinst.inst)
4183 {
4184 tinst = tinst.inst;
4185 const needsCodegen = tinst.needsCodegen(); // sets tinst.minst
4186 if (tinst.minst) // not speculative
4187 {
4188 tithis.minst = tinst.minst; // cache result
4189 return needsCodegen ? ThreeState.yes : ThreeState.no;
4190 }
4191 }
4192
4193 // Elide codegen if `this` doesn't need it.
4194 if (tithis.minst && !tithis.minst.isRoot() && !tithis.minst.rootImports())
4195 return ThreeState.no;
4196
4197 return ThreeState.none;
4198 }
4199
4200 if (const needsCodegen = needsCodegenRootOnly(this, tinst))
4201 return needsCodegen == ThreeState.yes ? true : false;
4202
4203 // Elide codegen if a (non-speculative) sibling doesn't need it.
4204 for (; tnext; tnext = tnext.tnext)
4205 {
4206 const needsCodegen = needsCodegenRootOnly(tnext, tnext.tinst); // sets tnext.minst
4207 if (tnext.minst) // not speculative
4208 {
4209 if (needsCodegen == ThreeState.no)
4210 {
4211 minst = tnext.minst; // cache result
4212 assert(!minst.isRoot() && !minst.rootImports());
4213 return false;
4214 }
4215 else if (!minst)
4216 {
4217 minst = tnext.minst; // cache result from non-speculative sibling
4218 // continue searching
4219 }
4220 else if (needsCodegen != ThreeState.none)
4221 break;
4222 }
4223 }
4224
4225 // Unless `this` is still speculative (=> all further siblings speculative too),
4226 // do codegen because we found no guaranteed-codegen'd non-root instantiation.
4227 return minst !is null;
4228 }
4229
4230 /**********************************************
4231 * Find template declaration corresponding to template instance.
4232 *
4233 * Returns:
4234 * false if finding fails.
4235 * Note:
4236 * This function is reentrant against error occurrence. If returns false,
4237 * any members of this object won't be modified, and repetition call will
4238 * reproduce same error.
4239 */
4240 extern (D) final bool findTempDecl(Scope* sc, WithScopeSymbol* pwithsym)
4241 {
4242 if (pwithsym)
4243 *pwithsym = null;
4244
4245 if (havetempdecl)
4246 return true;
4247
4248 //printf("TemplateInstance.findTempDecl() %s\n", toChars());
4249 if (!tempdecl)
4250 {
4251 /* Given:
4252 * foo!( ... )
4253 * figure out which TemplateDeclaration foo refers to.
4254 */
4255 Identifier id = name;
4256 Dsymbol scopesym;
4257 Dsymbol s = sc.search(loc, id, scopesym);
4258 if (!s)
4259 {
4260 s = sc.search_correct(id);
4261 if (s)
4262 .error(loc, "%s `%s` template `%s` is not defined, did you mean %s?", kind, toPrettyChars, id.toChars(), s.toChars());
4263 else
4264 .error(loc, "%s `%s` template `%s` is not defined", kind, toPrettyChars, id.toChars());
4265 return false;
4266 }
4267 static if (LOG)
4268 {
4269 printf("It's an instance of '%s' kind '%s'\n", s.toChars(), s.kind());
4270 if (s.parent)
4271 printf("s.parent = '%s'\n", s.parent.toChars());
4272 }
4273 if (pwithsym)
4274 *pwithsym = scopesym.isWithScopeSymbol();
4275
4276 /* We might have found an alias within a template when
4277 * we really want the template.
4278 */
4279 TemplateInstance ti;
4280 if (s.parent && (ti = s.parent.isTemplateInstance()) !is null)
4281 {
4282 if (ti.tempdecl && ti.tempdecl.ident == id)
4283 {
4284 /* This is so that one can refer to the enclosing
4285 * template, even if it has the same name as a member
4286 * of the template, if it has a !(arguments)
4287 */
4288 TemplateDeclaration td = ti.tempdecl.isTemplateDeclaration();
4289 assert(td);
4290 if (td.overroot) // if not start of overloaded list of TemplateDeclaration's
4291 td = td.overroot; // then get the start
4292 s = td;
4293 }
4294 }
4295
4296 // The template might originate from a selective import which implies that
4297 // s is a lowered AliasDeclaration of the actual TemplateDeclaration.
4298 // This is the last place where we see the deprecated alias because it is
4299 // stripped below, so check if the selective import was deprecated.
4300 // See https://issues.dlang.org/show_bug.cgi?id=20840.
4301 if (s.isAliasDeclaration())
4302 s.checkDeprecated(this.loc, sc);
4303
4304 if (!updateTempDecl(sc, s))
4305 {
4306 return false;
4307 }
4308 }
4309 assert(tempdecl);
4310
4311 // Look for forward references
4312 auto tovers = tempdecl.isOverloadSet();
4313 foreach (size_t oi; 0 .. tovers ? tovers.a.length : 1)
4314 {
4315 Dsymbol dstart = tovers ? tovers.a[oi] : tempdecl;
4316 int r = overloadApply(dstart, (Dsymbol s)
4317 {
4318 auto td = s.isTemplateDeclaration();
4319 if (!td)
4320 return 0;
4321
4322 if (td.semanticRun == PASS.initial)
4323 {
4324 if (td._scope)
4325 {
4326 // Try to fix forward reference. Ungag errors while doing so.
4327 Ungag ungag = td.ungagSpeculative();
4328 td.dsymbolSemantic(td._scope);
4329 }
4330 if (td.semanticRun == PASS.initial)
4331 {
4332 .error(loc, "%s `%s` `%s` forward references template declaration `%s`", kind, toPrettyChars,
4333 toChars(), td.toChars());
4334 return 1;
4335 }
4336 }
4337 return 0;
4338 });
4339 if (r)
4340 return false;
4341 }
4342 return true;
4343 }
4344
4345 /**********************************************
4346 * Confirm s is a valid template, then store it.
4347 * Input:
4348 * sc
4349 * s candidate symbol of template. It may be:
4350 * TemplateDeclaration
4351 * FuncDeclaration with findTemplateDeclRoot() != NULL
4352 * OverloadSet which contains candidates
4353 * Returns:
4354 * true if updating succeeds.
4355 */
4356 extern (D) final bool updateTempDecl(Scope* sc, Dsymbol s)
4357 {
4358 if (!s)
4359 return tempdecl !is null;
4360
4361 Identifier id = name;
4362 s = s.toAlias();
4363
4364 /* If an OverloadSet, look for a unique member that is a template declaration
4365 */
4366 if (OverloadSet os = s.isOverloadSet())
4367 {
4368 s = null;
4369 foreach (s2; os.a)
4370 {
4371 if (FuncDeclaration f = s2.isFuncDeclaration())
4372 s2 = f.findTemplateDeclRoot();
4373 else
4374 s2 = s2.isTemplateDeclaration();
4375 if (s2)
4376 {
4377 if (s)
4378 {
4379 tempdecl = os;
4380 return true;
4381 }
4382 s = s2;
4383 }
4384 }
4385 if (!s)
4386 {
4387 .error(loc, "%s `%s` template `%s` is not defined", kind, toPrettyChars, id.toChars());
4388 return false;
4389 }
4390 }
4391
4392 if (OverDeclaration od = s.isOverDeclaration())
4393 {
4394 tempdecl = od; // TODO: more strict check
4395 return true;
4396 }
4397
4398 /* It should be a TemplateDeclaration, not some other symbol
4399 */
4400 if (FuncDeclaration f = s.isFuncDeclaration())
4401 tempdecl = f.findTemplateDeclRoot();
4402 else
4403 tempdecl = s.isTemplateDeclaration();
4404
4405 // We're done
4406 if (tempdecl)
4407 return true;
4408
4409 // Error already issued, just return `false`
4410 if (!s.parent && global.errors)
4411 return false;
4412
4413 if (!s.parent && s.getType())
4414 {
4415 Dsymbol s2 = s.getType().toDsymbol(sc);
4416 if (!s2)
4417 {
4418 .error(loc, "`%s` is not a valid template instance, because `%s` is not a template declaration but a type (`%s == %s`)", toChars(), id.toChars(), id.toChars(), s.getType.kind());
4419 return false;
4420 }
4421 // because s can be the alias created for a TemplateParameter
4422 const AliasDeclaration ad = s.isAliasDeclaration();
4423 version (none)
4424 {
4425 if (ad && ad.isAliasedTemplateParameter())
4426 printf("`%s` is an alias created from a template parameter\n", s.toChars());
4427 }
4428 if (!ad || !ad.isAliasedTemplateParameter())
4429 s = s2;
4430 }
4431
4432 TemplateInstance ti = s.parent ? s.parent.isTemplateInstance() : null;
4433
4434 /* This avoids the VarDeclaration.toAlias() which runs semantic() too soon
4435 */
4436 static bool matchId(TemplateInstance ti, Identifier id)
4437 {
4438 if (ti.aliasdecl && ti.aliasdecl.isVarDeclaration())
4439 return ti.aliasdecl.isVarDeclaration().ident == id;
4440 return ti.toAlias().ident == id;
4441 }
4442
4443 if (ti && (ti.name == s.ident || matchId(ti, s.ident)) && ti.tempdecl)
4444 {
4445 /* This is so that one can refer to the enclosing
4446 * template, even if it has the same name as a member
4447 * of the template, if it has a !(arguments)
4448 */
4449 TemplateDeclaration td = ti.tempdecl.isTemplateDeclaration();
4450 assert(td);
4451 if (td.overroot) // if not start of overloaded list of TemplateDeclaration's
4452 td = td.overroot; // then get the start
4453 tempdecl = td;
4454 return true;
4455 }
4456 else
4457 {
4458 .error(loc, "%s `%s` `%s` is not a template declaration, it is a %s", kind, toPrettyChars, id.toChars(), s.kind());
4459 return false;
4460 }
4461 }
4462
4463 /**********************************
4464 * Run semantic of tiargs as arguments of template.
4465 * Input:
4466 * loc
4467 * sc
4468 * tiargs array of template arguments
4469 * flags 1: replace const variables with their initializers
4470 * 2: don't devolve Parameter to Type
4471 * atd tuple being optimized. If found, it's not expanded here
4472 * but in AliasAssign semantic.
4473 * Returns:
4474 * false if one or more arguments have errors.
4475 */
4476 extern (D) static bool semanticTiargs(Loc loc, Scope* sc, Objects* tiargs, int flags, TupleDeclaration atd = null)
4477 {
4478 // Run semantic on each argument, place results in tiargs[]
4479 //printf("+TemplateInstance.semanticTiargs()\n");
4480 if (!tiargs)
4481 return true;
4482 bool err = false;
4483
4484 // The arguments are not treated as part of a default argument,
4485 // because they are evaluated at compile time.
4486 const inCondition = sc.condition;
4487 sc = sc.push();
4488 sc.inDefaultArg = false;
4489
4490 // https://issues.dlang.org/show_bug.cgi?id=24699
4491 sc.condition = inCondition;
4492
4493 for (size_t j = 0; j < tiargs.length; j++)
4494 {
4495 RootObject o = (*tiargs)[j];
4496 Type ta = isType(o);
4497 Expression ea = isExpression(o);
4498 Dsymbol sa = isDsymbol(o);
4499
4500 //printf("1: (*tiargs)[%d] = %p, s=%p, v=%p, ea=%p, ta=%p\n", j, o, isDsymbol(o), isTuple(o), ea, ta);
4501 if (ta)
4502 {
4503 //printf("type %s\n", ta.toChars());
4504
4505 // It might really be an Expression or an Alias
4506 ta.resolve(loc, sc, ea, ta, sa, (flags & 1) != 0);
4507 if (ea)
4508 goto Lexpr;
4509 if (sa)
4510 goto Ldsym;
4511 if (ta is null)
4512 {
4513 assert(global.errors);
4514 ta = Type.terror;
4515 }
4516
4517 Ltype:
4518 if (TypeTuple tt = ta.isTypeTuple())
4519 {
4520 // Expand tuple
4521 size_t dim = tt.arguments.length;
4522 tiargs.remove(j);
4523 if (dim)
4524 {
4525 tiargs.reserve(dim);
4526 foreach (i, arg; *tt.arguments)
4527 {
4528 if (flags & 2 && (arg.storageClass & STC.parameter))
4529 tiargs.insert(j + i, arg);
4530 else
4531 tiargs.insert(j + i, arg.type);
4532 }
4533 }
4534 j--;
4535 continue;
4536 }
4537 if (ta.ty == Terror)
4538 {
4539 err = true;
4540 continue;
4541 }
4542 (*tiargs)[j] = ta.merge2();
4543 }
4544 else if (ea)
4545 {
4546 Lexpr:
4547 //printf("+[%d] ea = %s %s\n", j, EXPtoString(ea.op).ptr, ea.toChars());
4548 if (flags & 1) // only used by __traits
4549 {
4550 ea = ea.expressionSemantic(sc);
4551
4552 // must not interpret the args, excepting template parameters
4553 if (!ea.isVarExp() || (ea.isVarExp().var.storage_class & STC.templateparameter))
4554 {
4555 ea = ea.optimize(WANTvalue);
4556 }
4557 }
4558 else
4559 {
4560 sc = sc.startCTFE();
4561 ea = ea.expressionSemantic(sc);
4562 sc = sc.endCTFE();
4563
4564 if (auto varExp = ea.isVarExp())
4565 {
4566 /* If the parameter is a function that is not called
4567 * explicitly, i.e. `foo!func` as opposed to `foo!func()`,
4568 * then it is a dsymbol, not the return value of `func()`
4569 */
4570 Declaration vd = varExp.var;
4571 if (auto fd = vd.isFuncDeclaration())
4572 {
4573 sa = fd;
4574 goto Ldsym;
4575 }
4576 /* Otherwise skip substituting a const var with
4577 * its initializer. The problem is the initializer won't
4578 * match with an 'alias' parameter. Instead, do the
4579 * const substitution in TemplateValueParameter.matchArg().
4580 */
4581 }
4582 else if (definitelyValueParameter(ea))
4583 {
4584 if (ea.checkValue()) // check void expression
4585 ea = ErrorExp.get();
4586 const olderrs = global.errors;
4587 ea = ea.ctfeInterpret();
4588 if (global.errors != olderrs)
4589 ea = ErrorExp.get();
4590 }
4591 }
4592 //printf("-[%d] ea = %s %s\n", j, EXPtoString(ea.op).ptr, ea.toChars());
4593 if (TupleExp te = ea.isTupleExp())
4594 {
4595 // Expand tuple
4596 size_t dim = te.exps.length;
4597 tiargs.remove(j);
4598 if (dim)
4599 {
4600 tiargs.reserve(dim);
4601 foreach (i, exp; *te.exps)
4602 tiargs.insert(j + i, exp);
4603 }
4604 j--;
4605 continue;
4606 }
4607 if (ea.op == EXP.error)
4608 {
4609 err = true;
4610 continue;
4611 }
4612 (*tiargs)[j] = ea;
4613
4614 if (ea.op == EXP.type)
4615 {
4616 ta = ea.type;
4617 goto Ltype;
4618 }
4619 if (ea.op == EXP.scope_)
4620 {
4621 sa = ea.isScopeExp().sds;
4622 goto Ldsym;
4623 }
4624 if (FuncExp fe = ea.isFuncExp())
4625 {
4626 /* A function literal, that is passed to template and
4627 * already semanticed as function pointer, never requires
4628 * outer frame. So convert it to global function is valid.
4629 */
4630 if (fe.fd.tok == TOK.reserved && fe.type.ty == Tpointer)
4631 {
4632 // change to non-nested
4633 fe.fd.tok = TOK.function_;
4634 fe.fd.vthis = null;
4635 }
4636 else if (fe.td)
4637 {
4638 /* If template argument is a template lambda,
4639 * get template declaration itself. */
4640 //sa = fe.td;
4641 //goto Ldsym;
4642 }
4643 }
4644 if (ea.op == EXP.dotVariable && !(flags & 1))
4645 {
4646 // translate expression to dsymbol.
4647 sa = ea.isDotVarExp().var;
4648 goto Ldsym;
4649 }
4650 if (auto te = ea.isTemplateExp())
4651 {
4652 sa = te.td;
4653 goto Ldsym;
4654 }
4655 if (ea.op == EXP.dotTemplateDeclaration && !(flags & 1))
4656 {
4657 // translate expression to dsymbol.
4658 sa = ea.isDotTemplateExp().td;
4659 goto Ldsym;
4660 }
4661 if (auto de = ea.isDotExp())
4662 {
4663 if (auto se = de.e2.isScopeExp())
4664 {
4665 sa = se.sds;
4666 goto Ldsym;
4667 }
4668 }
4669 }
4670 else if (sa)
4671 {
4672 Ldsym:
4673 //printf("dsym %s %s\n", sa.kind(), sa.toChars());
4674 if (sa.errors)
4675 {
4676 err = true;
4677 continue;
4678 }
4679
4680 TupleDeclaration d = sa.toAlias().isTupleDeclaration();
4681 if (d)
4682 {
4683 if (d is atd)
4684 {
4685 (*tiargs)[j] = d;
4686 continue;
4687 }
4688 // Expand tuple
4689 tiargs.remove(j);
4690 tiargs.insert(j, d.objects);
4691 j--;
4692 continue;
4693 }
4694 if (FuncAliasDeclaration fa = sa.isFuncAliasDeclaration())
4695 {
4696 FuncDeclaration f = fa.toAliasFunc();
4697 if (!fa.hasOverloads && f.isUnique())
4698 {
4699 // Strip FuncAlias only when the aliased function
4700 // does not have any overloads.
4701 sa = f;
4702 }
4703 }
4704 (*tiargs)[j] = sa;
4705
4706 TemplateDeclaration td = sa.isTemplateDeclaration();
4707 if (td && td.semanticRun == PASS.initial && td.literal)
4708 {
4709 td.dsymbolSemantic(sc);
4710 }
4711 FuncDeclaration fd = sa.isFuncDeclaration();
4712 if (fd)
4713 functionSemantic(fd);
4714 }
4715 else if (isParameter(o))
4716 {
4717 }
4718 else
4719 {
4720 assert(0);
4721 }
4722 //printf("1: (*tiargs)[%d] = %p\n", j, (*tiargs)[j]);
4723 }
4724 sc.pop();
4725 version (none)
4726 {
4727 printf("-TemplateInstance.semanticTiargs()\n");
4728 for (size_t j = 0; j < tiargs.length; j++)
4729 {
4730 RootObject o = (*tiargs)[j];
4731 Type ta = isType(o);
4732 Expression ea = isExpression(o);
4733 Dsymbol sa = isDsymbol(o);
4734 Tuple va = isTuple(o);
4735 printf("\ttiargs[%d] = ta %p, ea %p, sa %p, va %p\n", j, ta, ea, sa, va);
4736 }
4737 }
4738 return !err;
4739 }
4740
4741 /**********************************
4742 * Run semantic on the elements of tiargs.
4743 * Input:
4744 * sc
4745 * Returns:
4746 * false if one or more arguments have errors.
4747 * Note:
4748 * This function is reentrant against error occurrence. If returns false,
4749 * all elements of tiargs won't be modified.
4750 */
4751 extern (D) final bool semanticTiargs(Scope* sc)
4752 {
4753 //printf("+TemplateInstance.semanticTiargs() %s\n", toChars());
4754 if (semantictiargsdone)
4755 return true;
4756 if (semanticTiargs(loc, sc, tiargs, 0))
4757 {
4758 // cache the result iff semantic analysis succeeded entirely
4759 semantictiargsdone = 1;
4760 return true;
4761 }
4762 return false;
4763 }
4764
4765 /**********************************
4766 * Find the TemplateDeclaration that matches this TemplateInstance best.
4767 *
4768 * Params:
4769 * sc = the scope this TemplateInstance resides in
4770 * argumentList = function arguments in case of a template function
4771 *
4772 * Returns:
4773 * `true` if a match was found, `false` otherwise
4774 */
4775 extern (D) final bool findBestMatch(Scope* sc, ArgumentList argumentList)
4776 {
4777 if (havetempdecl)
4778 {
4779 TemplateDeclaration tempdecl = this.tempdecl.isTemplateDeclaration();
4780 assert(tempdecl);
4781 assert(tempdecl._scope);
4782 // Deduce tdtypes
4783 tdtypes.setDim(tempdecl.parameters.length);
4784 if (!matchWithInstance(sc, tempdecl, this, tdtypes, argumentList, 2))
4785 {
4786 .error(loc, "%s `%s` incompatible arguments for template instantiation", kind, toPrettyChars);
4787 return false;
4788 }
4789 // TODO: Normalizing tiargs for https://issues.dlang.org/show_bug.cgi?id=7469 is necessary?
4790 return true;
4791 }
4792
4793 static if (LOG)
4794 {
4795 printf("TemplateInstance.findBestMatch()\n");
4796 }
4797
4798 const errs = global.errors;
4799 TemplateDeclaration td_last = null;
4800 Objects dedtypes;
4801
4802 /* Since there can be multiple TemplateDeclaration's with the same
4803 * name, look for the best match.
4804 */
4805 auto tovers = tempdecl.isOverloadSet();
4806 foreach (size_t oi; 0 .. tovers ? tovers.a.length : 1)
4807 {
4808 TemplateDeclaration td_best;
4809 TemplateDeclaration td_ambig;
4810 MATCH m_best = MATCH.nomatch;
4811
4812 Dsymbol dstart = tovers ? tovers.a[oi] : tempdecl;
4813 overloadApply(dstart, (Dsymbol s)
4814 {
4815 auto td = s.isTemplateDeclaration();
4816 if (!td)
4817 return 0;
4818 if (td == td_best) // skip duplicates
4819 return 0;
4820
4821 //printf("td = %s\n", td.toPrettyChars());
4822 // If more arguments than parameters,
4823 // then this is no match.
4824 if (td.parameters.length < tiargs.length)
4825 {
4826 if (!td.isVariadic())
4827 return 0;
4828 }
4829
4830 dedtypes.setDim(td.parameters.length);
4831 dedtypes.zero();
4832 assert(td.semanticRun != PASS.initial);
4833
4834 MATCH m = matchWithInstance(sc, td, this, dedtypes, argumentList, 0);
4835 //printf("matchWithInstance = %d\n", m);
4836 if (m == MATCH.nomatch) // no match at all
4837 return 0;
4838 if (m < m_best) goto Ltd_best;
4839 if (m > m_best) goto Ltd;
4840
4841 // Disambiguate by picking the most specialized TemplateDeclaration
4842 {
4843 MATCH c1 = leastAsSpecialized(sc, td, td_best, argumentList);
4844 MATCH c2 = leastAsSpecialized(sc, td_best, td, argumentList);
4845 //printf("c1 = %d, c2 = %d\n", c1, c2);
4846 if (c1 > c2) goto Ltd;
4847 if (c1 < c2) goto Ltd_best;
4848 }
4849
4850 td_ambig = td;
4851 return 0;
4852
4853 Ltd_best:
4854 // td_best is the best match so far
4855 td_ambig = null;
4856 return 0;
4857
4858 Ltd:
4859 // td is the new best match
4860 td_ambig = null;
4861 td_best = td;
4862 m_best = m;
4863 tdtypes.setDim(dedtypes.length);
4864 memcpy(tdtypes.tdata(), dedtypes.tdata(), tdtypes.length * (void*).sizeof);
4865 return 0;
4866 });
4867
4868 if (td_ambig)
4869 {
4870 .error(loc, "%s `%s.%s` matches more than one template declaration:",
4871 td_best.kind(), td_best.parent.toPrettyChars(), td_best.ident.toChars());
4872 .errorSupplemental(td_best.loc, "`%s`\nand:", td_best.toChars());
4873 .errorSupplemental(td_ambig.loc, "`%s`", td_ambig.toChars());
4874 return false;
4875 }
4876 if (td_best)
4877 {
4878 if (!td_last)
4879 td_last = td_best;
4880 else if (td_last != td_best)
4881 {
4882 ScopeDsymbol.multiplyDefined(loc, td_last, td_best);
4883 return false;
4884 }
4885 }
4886 }
4887
4888 if (td_last)
4889 {
4890 /* https://issues.dlang.org/show_bug.cgi?id=7469
4891 * Normalize tiargs by using corresponding deduced
4892 * template value parameters and tuples for the correct mangling.
4893 *
4894 * By doing this before hasNestedArgs, CTFEable local variable will be
4895 * accepted as a value parameter. For example:
4896 *
4897 * void foo() {
4898 * struct S(int n) {} // non-global template
4899 * const int num = 1; // CTFEable local variable
4900 * S!num s; // S!1 is instantiated, not S!num
4901 * }
4902 */
4903 size_t dim = td_last.parameters.length - (td_last.isVariadic() ? 1 : 0);
4904 for (size_t i = 0; i < dim; i++)
4905 {
4906 if (tiargs.length <= i)
4907 tiargs.push(tdtypes[i]);
4908 assert(i < tiargs.length);
4909
4910 auto tvp = (*td_last.parameters)[i].isTemplateValueParameter();
4911 if (!tvp)
4912 continue;
4913 assert(tdtypes[i]);
4914 // tdtypes[i] is already normalized to the required type in matchArg
4915
4916 (*tiargs)[i] = tdtypes[i];
4917 }
4918 if (td_last.isVariadic() && tiargs.length == dim && tdtypes[dim])
4919 {
4920 Tuple va = isTuple(tdtypes[dim]);
4921 assert(va);
4922 tiargs.pushSlice(va.objects[]);
4923 }
4924 }
4925 else if (errors && inst)
4926 {
4927 // instantiation was failed with error reporting
4928 assert(global.errors);
4929 return false;
4930 }
4931 else
4932 {
4933 auto tdecl = tempdecl.isTemplateDeclaration();
4934
4935 if (errs != global.errors)
4936 errorSupplemental(loc, "while looking for match for `%s`", toChars());
4937 else if (tdecl && !tdecl.overnext)
4938 {
4939 // Only one template, so we can give better error message
4940 const(char)* msg = "does not match template declaration";
4941 const(char)* tip;
4942 OutBuffer buf;
4943 HdrGenState hgs;
4944 hgs.skipConstraints = true;
4945 toCharsMaybeConstraints(tdecl, buf, hgs);
4946 const tmsg = buf.peekChars();
4947 const cmsg = tdecl.getConstraintEvalError(tip);
4948 if (cmsg)
4949 {
4950 .error(loc, "%s `%s` %s `%s`\n%s", kind, toPrettyChars, msg, tmsg, cmsg);
4951 if (tip)
4952 .tip(tip);
4953 }
4954 else
4955 {
4956 .error(loc, "%s `%s` %s `%s`", kind, toPrettyChars, msg, tmsg);
4957
4958 if (tdecl.parameters.length == tiargs.length)
4959 {
4960 // https://issues.dlang.org/show_bug.cgi?id=7352
4961 // print additional information, e.g. `foo` is not a type
4962 foreach (i, param; *tdecl.parameters)
4963 {
4964 MATCH match = param.matchArg(loc, sc, tiargs, i, tdecl.parameters, dedtypes, null);
4965 auto arg = (*tiargs)[i];
4966 auto sym = arg.isDsymbol;
4967 auto exp = arg.isExpression;
4968
4969 if (exp)
4970 exp = exp.optimize(WANTvalue);
4971
4972 if (match == MATCH.nomatch &&
4973 ((sym && sym.isFuncDeclaration) ||
4974 (exp && exp.isVarExp)))
4975 {
4976 if (param.isTemplateTypeParameter)
4977 errorSupplemental(loc, "`%s` is not a type", arg.toChars);
4978 else if (auto tvp = param.isTemplateValueParameter)
4979 errorSupplemental(loc, "`%s` is not of a value of type `%s`",
4980 arg.toChars, tvp.valType.toChars);
4981
4982 }
4983 }
4984 }
4985 }
4986 }
4987 else
4988 {
4989 .error(loc, "%s `%s` does not match any template declaration", kind(), toPrettyChars());
4990 bool found;
4991 overloadApply(tempdecl, (s){
4992 if (!found)
4993 errorSupplemental(loc, "Candidates are:");
4994 found = true;
4995 errorSupplemental(s.loc, "%s", s.toChars());
4996 return 0;
4997 });
4998 }
4999 return false;
5000 }
5001
5002 /* The best match is td_last
5003 */
5004 tempdecl = td_last;
5005
5006 static if (LOG)
5007 {
5008 printf("\tIt's a match with template declaration '%s'\n", tempdecl.toChars());
5009 }
5010 return (errs == global.errors);
5011 }
5012
5013 /*****************************************
5014 * Determines if a TemplateInstance will need a nested
5015 * generation of the TemplateDeclaration.
5016 * Sets enclosing property if so, and returns != 0;
5017 */
5018 extern (D) final bool hasNestedArgs(Objects* args, bool isstatic)
5019 {
5020 int nested = 0;
5021 //printf("TemplateInstance.hasNestedArgs('%s')\n", tempdecl.ident.toChars());
5022
5023 // arguments from parent instances are also accessible
5024 if (!enclosing)
5025 {
5026 if (TemplateInstance ti = tempdecl.toParent().isTemplateInstance())
5027 enclosing = ti.enclosing;
5028 }
5029
5030 /* A nested instance happens when an argument references a local
5031 * symbol that is on the stack.
5032 */
5033 foreach (o; *args)
5034 {
5035 Expression ea = isExpression(o);
5036 Dsymbol sa = isDsymbol(o);
5037 Tuple va = isTuple(o);
5038 if (ea)
5039 {
5040 if (auto ve = ea.isVarExp())
5041 {
5042 sa = ve.var;
5043 goto Lsa;
5044 }
5045 if (auto te = ea.isThisExp())
5046 {
5047 sa = te.var;
5048 goto Lsa;
5049 }
5050 if (auto fe = ea.isFuncExp())
5051 {
5052 if (fe.td)
5053 sa = fe.td;
5054 else
5055 sa = fe.fd;
5056 goto Lsa;
5057 }
5058 // Emulate Expression.toMangleBuffer call that had exist in TemplateInstance.genIdent.
5059 if (ea.op != EXP.int64 && ea.op != EXP.float64 && ea.op != EXP.complex80 && ea.op != EXP.null_ && ea.op != EXP.string_ && ea.op != EXP.arrayLiteral && ea.op != EXP.assocArrayLiteral && ea.op != EXP.structLiteral)
5060 {
5061 if (!ea.type.isTypeError())
5062 .error(ea.loc, "%s `%s` expression `%s` is not a valid template value argument", kind, toPrettyChars, ea.toChars());
5063 errors = true;
5064 }
5065 }
5066 else if (sa)
5067 {
5068 Lsa:
5069 sa = sa.toAlias();
5070 TemplateDeclaration td = sa.isTemplateDeclaration();
5071 if (td)
5072 {
5073 TemplateInstance ti = sa.toParent().isTemplateInstance();
5074 if (ti && ti.enclosing)
5075 sa = ti;
5076 }
5077 TemplateInstance ti = sa.isTemplateInstance();
5078 Declaration d = sa.isDeclaration();
5079 if ((td && td.literal) || (ti && ti.enclosing) || (d && !d.isDataseg() && !(d.storage_class & STC.manifest) && (!d.isFuncDeclaration() || d.isFuncDeclaration().isNested()) && !isTemplateMixin()))
5080 {
5081 Dsymbol dparent = sa.toParent2();
5082 if (!dparent || dparent.isModule)
5083 goto L1;
5084 else if (!enclosing)
5085 enclosing = dparent;
5086 else if (enclosing != dparent)
5087 {
5088 /* Select the more deeply nested of the two.
5089 * Error if one is not nested inside the other.
5090 */
5091 for (Dsymbol p = enclosing; p; p = p.parent)
5092 {
5093 if (p == dparent)
5094 goto L1; // enclosing is most nested
5095 }
5096 for (Dsymbol p = dparent; p; p = p.parent)
5097 {
5098 if (p == enclosing)
5099 {
5100 enclosing = dparent;
5101 goto L1; // dparent is most nested
5102 }
5103 }
5104 //https://issues.dlang.org/show_bug.cgi?id=17870
5105 if (dparent.isClassDeclaration() && enclosing.isClassDeclaration())
5106 {
5107 auto pc = dparent.isClassDeclaration();
5108 auto ec = enclosing.isClassDeclaration();
5109 if (pc.isBaseOf(ec, null))
5110 goto L1;
5111 else if (ec.isBaseOf(pc, null))
5112 {
5113 enclosing = dparent;
5114 goto L1;
5115 }
5116 }
5117 .error(loc, "%s `%s` `%s` is nested in both `%s` and `%s`", kind, toPrettyChars, toChars(), enclosing.toChars(), dparent.toChars());
5118 errors = true;
5119 }
5120 L1:
5121 //printf("\tnested inside %s as it references %s\n", enclosing.toChars(), sa.toChars());
5122 nested |= 1;
5123 }
5124 }
5125 else if (va)
5126 {
5127 nested |= cast(int)hasNestedArgs(&va.objects, isstatic);
5128 }
5129 }
5130 //printf("-TemplateInstance.hasNestedArgs('%s') = %d\n", tempdecl.ident.toChars(), nested);
5131 return nested != 0;
5132 }
5133
5134 /*****************************************
5135 * Append 'this' to the specific module members[]
5136 */
5137 extern (D) final Dsymbols* appendToModuleMember()
5138 {
5139 Module mi = minst; // instantiated . inserted module
5140
5141 //printf("%s.appendToModuleMember() enclosing = %s mi = %s\n",
5142 // toPrettyChars(),
5143 // enclosing ? enclosing.toPrettyChars() : null,
5144 // mi ? mi.toPrettyChars() : null);
5145 if (global.params.allInst || !mi || mi.isRoot())
5146 {
5147 /* If the instantiated module is speculative or root, insert to the
5148 * member of a root module. Then:
5149 * - semantic3 pass will get called on the instance members.
5150 * - codegen pass will get a selection chance to do/skip it (needsCodegen()).
5151 */
5152 static Dsymbol getStrictEnclosing(TemplateInstance ti)
5153 {
5154 do
5155 {
5156 if (ti.enclosing)
5157 return ti.enclosing;
5158 ti = ti.tempdecl.isInstantiated();
5159 } while (ti);
5160 return null;
5161 }
5162
5163 Dsymbol enc = getStrictEnclosing(this);
5164 // insert target is made stable by using the module
5165 // where tempdecl is declared.
5166 mi = (enc ? enc : tempdecl).getModule();
5167 if (!mi.isRoot())
5168 {
5169 if (mi.importedFrom)
5170 {
5171 mi = mi.importedFrom;
5172 assert(mi.isRoot());
5173 }
5174 else
5175 {
5176 // This can happen when using the frontend as a library.
5177 // Append it to the non-root module.
5178 }
5179 }
5180 }
5181 else
5182 {
5183 /* If the instantiated module is non-root, insert to the member of the
5184 * non-root module. Then:
5185 * - semantic3 pass won't be called on the instance.
5186 * - codegen pass won't reach to the instance.
5187 * Unless it is re-appended to a root module later (with changed minst).
5188 */
5189 }
5190 //printf("\t-. mi = %s\n", mi.toPrettyChars());
5191
5192 if (memberOf) // already appended to some module
5193 {
5194 assert(mi.isRoot(), "can only re-append to a root module");
5195 if (memberOf.isRoot())
5196 return null; // no need to move to another root module
5197 }
5198
5199 Dsymbols* a = mi.members;
5200 a.push(this);
5201 memberOf = mi;
5202 if (mi.semanticRun >= PASS.semantic2done && mi.isRoot())
5203 Module.addDeferredSemantic2(this);
5204 if (mi.semanticRun >= PASS.semantic3done && mi.isRoot())
5205 Module.addDeferredSemantic3(this);
5206 return a;
5207 }
5208
5209 /****************************************************
5210 * Declare parameters of template instance, initialize them with the
5211 * template instance arguments.
5212 */
5213 extern (D) final void declareParameters(Scope* sc)
5214 {
5215 TemplateDeclaration tempdecl = this.tempdecl.isTemplateDeclaration();
5216 assert(tempdecl);
5217
5218 //printf("TemplateInstance.declareParameters()\n");
5219 foreach (i, o; tdtypes) // initializer for tp
5220 {
5221 TemplateParameter tp = (*tempdecl.parameters)[i];
5222 //printf("\ttdtypes[%d] = %p\n", i, o);
5223 declareParameter(tempdecl, sc, tp, o);
5224 }
5225 }
5226
5227 /****************************************
5228 * This instance needs an identifier for name mangling purposes.
5229 * Create one by taking the template declaration name and adding
5230 * the type signature for it.
5231 */
5232 extern (D) final Identifier genIdent(Objects* args)
5233 {
5234 //printf("TemplateInstance.genIdent('%s')\n", tempdecl.ident.toChars());
5235 assert(args is tiargs);
5236 OutBuffer buf;
5237 mangleToBuffer(this, buf);
5238 //printf("\tgenIdent = %s\n", buf.peekChars());
5239 return Identifier.idPool(buf[]);
5240 }
5241
5242 extern (D) final void expandMembers(Scope* sc2)
5243 {
5244 members.foreachDsymbol( (s) { s.setScope (sc2); } );
5245
5246 members.foreachDsymbol( (s) { s.importAll(sc2); } );
5247
5248 if (!aliasdecl)
5249 {
5250 /* static if's are crucial to evaluating aliasdecl correctly. But
5251 * evaluating the if/else bodies may require aliasdecl.
5252 * So, evaluate the condition for static if's, but not their if/else bodies.
5253 * Then try to set aliasdecl.
5254 * Later do the if/else bodies.
5255 * https://issues.dlang.org/show_bug.cgi?id=23598
5256 * It might be better to do this by attaching a lambda to the StaticIfDeclaration
5257 * to do the oneMembers call after the sid.include(sc2) is run as part of dsymbolSemantic().
5258 */
5259 bool done;
5260 void staticIfDg(Dsymbol s)
5261 {
5262 if (done || aliasdecl)
5263 return;
5264 //printf("\t staticIfDg on '%s %s' in '%s'\n", s.kind(), s.toChars(), this.toChars());
5265 if (!s.isStaticIfDeclaration())
5266 {
5267 //s.dsymbolSemantic(sc2);
5268 done = true;
5269 return;
5270 }
5271 auto sid = s.isStaticIfDeclaration();
5272 sid.include(sc2);
5273 if (members.length)
5274 {
5275 Dsymbol sa;
5276 if (Dsymbol.oneMembers(members, sa, tempdecl.ident) && sa)
5277 aliasdecl = sa;
5278 }
5279 done = true;
5280 }
5281
5282 members.foreachDsymbol(&staticIfDg);
5283 }
5284
5285 void symbolDg(Dsymbol s)
5286 {
5287 //printf("\t semantic on '%s' %p kind %s in '%s'\n", s.toChars(), s, s.kind(), this.toChars());
5288 //printf("test: enclosing = %d, sc2.parent = %s\n", enclosing, sc2.parent.toChars());
5289 //if (enclosing)
5290 // s.parent = sc.parent;
5291 //printf("test3: enclosing = %d, s.parent = %s\n", enclosing, s.parent.toChars());
5292 s.dsymbolSemantic(sc2);
5293 //printf("test4: enclosing = %d, s.parent = %s\n", enclosing, s.parent.toChars());
5294 Module.runDeferredSemantic();
5295 }
5296
5297 members.foreachDsymbol(&symbolDg);
5298 }
5299
5300 extern (D) final void tryExpandMembers(Scope* sc2)
5301 {
5302 __gshared int nest;
5303 // extracted to a function to allow windows SEH to work without destructors in the same function
5304 //printf("%d\n", nest);
5305 if (++nest > global.recursionLimit)
5306 {
5307 global.gag = 0; // ensure error message gets printed
5308 .error(loc, "%s `%s` recursive expansion exceeded allowed nesting limit", kind, toPrettyChars);
5309 fatal();
5310 }
5311
5312 expandMembers(sc2);
5313
5314 nest--;
5315 }
5316
5317 extern (D) final void trySemantic3(Scope* sc2)
5318 {
5319 // extracted to a function to allow windows SEH to work without destructors in the same function
5320 __gshared int nest;
5321 //printf("%d\n", nest);
5322 if (++nest > global.recursionLimit)
5323 {
5324 global.gag = 0; // ensure error message gets printed
5325 .error(loc, "%s `%s` recursive expansion exceeded allowed nesting limit", kind, toPrettyChars);
5326 fatal();
5327 }
5328
5329 semantic3(this, sc2);
5330
5331 --nest;
5332 }
5333
5334 override void accept(Visitor v)
5335 {
5336 v.visit(this);
5337 }
5338 }
5339
5340 /**************************************
5341 * IsExpression can evaluate the specified type speculatively, and even if
5342 * it instantiates any symbols, they are normally unnecessary for the
5343 * final executable.
5344 * However, if those symbols leak to the actual code, compiler should remark
5345 * them as non-speculative to generate their code and link to the final executable.
5346 */
5347 void unSpeculative(Scope* sc, RootObject o)
5348 {
5349 if (!o)
5350 return;
5351
5352 if (Tuple tup = isTuple(o))
5353 {
5354 foreach (obj; tup.objects)
5355 {
5356 unSpeculative(sc, obj);
5357 }
5358 return;
5359 }
5360
5361 Dsymbol s = getDsymbol(o);
5362 if (!s)
5363 return;
5364
5365 if (Declaration d = s.isDeclaration())
5366 {
5367 if (VarDeclaration vd = d.isVarDeclaration())
5368 o = vd.type;
5369 else if (AliasDeclaration ad = d.isAliasDeclaration())
5370 {
5371 o = ad.getType();
5372 if (!o)
5373 o = ad.toAlias();
5374 }
5375 else
5376 o = d.toAlias();
5377
5378 s = getDsymbol(o);
5379 if (!s)
5380 return;
5381 }
5382
5383 if (TemplateInstance ti = s.isTemplateInstance())
5384 {
5385 // If the instance is already non-speculative,
5386 // or it is leaked to the speculative scope.
5387 if (ti.minst !is null || sc.minst is null)
5388 return;
5389
5390 // Remark as non-speculative instance.
5391 ti.minst = sc.minst;
5392 if (!ti.tinst)
5393 ti.tinst = sc.tinst;
5394
5395 unSpeculative(sc, ti.tempdecl);
5396 }
5397
5398 if (TemplateInstance ti = s.isInstantiated())
5399 unSpeculative(sc, ti);
5400 }
5401
5402 /**********************************
5403 * Return true if e could be valid only as a template value parameter.
5404 * Return false if it might be an alias or tuple.
5405 * (Note that even in this case, it could still turn out to be a value).
5406 */
5407 bool definitelyValueParameter(Expression e) @safe
5408 {
5409 // None of these can be value parameters
5410 if (e.op == EXP.tuple || e.op == EXP.scope_ ||
5411 e.op == EXP.type || e.op == EXP.dotType ||
5412 e.op == EXP.template_ || e.op == EXP.dotTemplateDeclaration ||
5413 e.op == EXP.function_ || e.op == EXP.error ||
5414 e.op == EXP.this_ || e.op == EXP.super_ ||
5415 e.op == EXP.dot)
5416 return false;
5417
5418 if (e.op != EXP.dotVariable)
5419 return true;
5420
5421 /* Template instantiations involving a DotVar expression are difficult.
5422 * In most cases, they should be treated as a value parameter, and interpreted.
5423 * But they might also just be a fully qualified name, which should be treated
5424 * as an alias.
5425 */
5426
5427 // x.y.f cannot be a value
5428 FuncDeclaration f = e.isDotVarExp().var.isFuncDeclaration();
5429 if (f)
5430 return false;
5431
5432 while (e.op == EXP.dotVariable)
5433 {
5434 e = e.isDotVarExp().e1;
5435 }
5436 // this.x.y and super.x.y couldn't possibly be valid values.
5437 if (e.op == EXP.this_ || e.op == EXP.super_)
5438 return false;
5439
5440 // e.type.x could be an alias
5441 if (e.op == EXP.dotType)
5442 return false;
5443
5444 // var.x.y is the only other possible form of alias
5445 if (e.op != EXP.variable)
5446 return true;
5447
5448 VarDeclaration v = e.isVarExp().var.isVarDeclaration();
5449 // func.x.y is not an alias
5450 if (!v)
5451 return true;
5452
5453 // https://issues.dlang.org/show_bug.cgi?id=16685
5454 // var.x.y where var is a constant available at compile time
5455 if (v.storage_class & STC.manifest)
5456 return true;
5457
5458 // TODO: Should we force CTFE if it is a global constant?
5459 return false;
5460 }
5461
5462 /***********************************************************
5463 * https://dlang.org/spec/template-mixin.html
5464 * Syntax:
5465 * mixin MixinTemplateName [TemplateArguments] [Identifier];
5466 */
5467 extern (C++) final class TemplateMixin : TemplateInstance
5468 {
5469 TypeQualified tqual;
5470
5471 extern (D) this(Loc loc, Identifier ident, TypeQualified tqual, Objects* tiargs)
5472 {
5473 super(loc,
5474 tqual.idents.length ? cast(Identifier)tqual.idents[tqual.idents.length - 1] : (cast(TypeIdentifier)tqual).ident,
5475 tiargs ? tiargs : new Objects());
5476 //printf("TemplateMixin(ident = '%s')\n", ident ? ident.toChars() : "");
5477 this.dsym = DSYM.templateMixin;
5478 this.ident = ident;
5479 this.tqual = tqual;
5480 }
5481
5482 override TemplateInstance syntaxCopy(Dsymbol s)
5483 {
5484 auto tm = new TemplateMixin(loc, ident, tqual.syntaxCopy(), tiargs);
5485 return TemplateInstance.syntaxCopy(tm);
5486 }
5487
5488 override const(char)* kind() const
5489 {
5490 return "mixin";
5491 }
5492
5493 override bool hasPointers()
5494 {
5495 //printf("TemplateMixin.hasPointers() %s\n", toChars());
5496 return members.foreachDsymbol( (s) { return s.hasPointers(); } ) != 0;
5497 }
5498
5499 extern (D) bool findTempDecl(Scope* sc)
5500 {
5501 // Follow qualifications to find the TemplateDeclaration
5502 if (!tempdecl)
5503 {
5504 Expression e;
5505 Type t;
5506 Dsymbol s;
5507 tqual.resolve(loc, sc, e, t, s);
5508 if (!s)
5509 {
5510 .error(loc, "%s `%s` is not defined", kind, toPrettyChars);
5511 return false;
5512 }
5513 s = s.toAlias();
5514 tempdecl = s.isTemplateDeclaration();
5515 OverloadSet os = s.isOverloadSet();
5516
5517 /* If an OverloadSet, look for a unique member that is a template declaration
5518 */
5519 if (os)
5520 {
5521 Dsymbol ds = null;
5522 foreach (i, sym; os.a)
5523 {
5524 Dsymbol s2 = sym.isTemplateDeclaration();
5525 if (s2)
5526 {
5527 if (ds)
5528 {
5529 tempdecl = os;
5530 break;
5531 }
5532 ds = s2;
5533 }
5534 }
5535 }
5536 if (!tempdecl)
5537 {
5538 .error(loc, "%s `%s` - `%s` is a %s, not a template", kind, toPrettyChars, s.toChars(), s.kind());
5539 return false;
5540 }
5541 }
5542 assert(tempdecl);
5543
5544 // Look for forward references
5545 auto tovers = tempdecl.isOverloadSet();
5546 foreach (size_t oi; 0 .. tovers ? tovers.a.length : 1)
5547 {
5548 Dsymbol dstart = tovers ? tovers.a[oi] : tempdecl;
5549 int r = overloadApply(dstart, (Dsymbol s)
5550 {
5551 auto td = s.isTemplateDeclaration();
5552 if (!td)
5553 return 0;
5554
5555 if (td.semanticRun == PASS.initial)
5556 {
5557 if (td._scope)
5558 td.dsymbolSemantic(td._scope);
5559 else
5560 {
5561 semanticRun = PASS.initial;
5562 return 1;
5563 }
5564 }
5565 return 0;
5566 });
5567 if (r)
5568 return false;
5569 }
5570 return true;
5571 }
5572
5573 override void accept(Visitor v)
5574 {
5575 v.visit(this);
5576 }
5577 }
5578
5579 /************************************
5580 * This struct is needed for TemplateInstance to be the key in an associative array.
5581 * Fixing https://issues.dlang.org/show_bug.cgi?id=15813 would make it unnecessary.
5582 */
5583 struct TemplateInstanceBox
5584 {
5585 TemplateInstance ti;
5586
5587 this(TemplateInstance ti)
5588 {
5589 this.ti = ti;
5590 this.ti.toHash();
5591 assert(this.ti.hash);
5592 }
5593
5594 size_t toHash() const @safe pure nothrow
5595 {
5596 assert(ti.hash);
5597 return ti.hash;
5598 }
5599
5600 bool opEquals(ref const TemplateInstanceBox s) @trusted const
5601 {
5602 bool res = void;
5603 if (ti.inst && s.ti.inst)
5604 {
5605 /* This clause is only used when an instance with errors
5606 * is replaced with a correct instance.
5607 */
5608 res = ti is s.ti;
5609 }
5610 else
5611 {
5612 /* Used when a proposed instance is used to see if there's
5613 * an existing instance.
5614 */
5615 static if (__VERSION__ < 2099) // https://issues.dlang.org/show_bug.cgi?id=22717
5616 res = (cast()s.ti).equalsx(cast()ti);
5617 else
5618 res = (cast()ti).equalsx(cast()s.ti);
5619 }
5620
5621 debug (FindExistingInstance) ++(res ? nHits : nCollisions);
5622 return res;
5623 }
5624
5625 debug (FindExistingInstance)
5626 {
5627 __gshared uint nHits, nCollisions;
5628
5629 shared static ~this()
5630 {
5631 printf("debug (FindExistingInstance) TemplateInstanceBox.equals hits: %u collisions: %u\n",
5632 nHits, nCollisions);
5633 }
5634 }
5635 }
5636
5637 /*******************************************
5638 * Match to a particular TemplateParameter.
5639 * Input:
5640 * instLoc location that the template is instantiated.
5641 * tiargs[] actual arguments to template instance
5642 * i i'th argument
5643 * parameters[] template parameters
5644 * dedtypes[] deduced arguments to template instance
5645 * *psparam set to symbol declared and initialized to dedtypes[i]
5646 */
5647 MATCH matchArg(TemplateParameter tp, Loc instLoc, Scope* sc, Objects* tiargs, size_t i, TemplateParameters* parameters, ref Objects dedtypes, Declaration* psparam)
5648 {
5649 MATCH matchArgNoMatch()
5650 {
5651 if (psparam)
5652 *psparam = null;
5653 return MATCH.nomatch;
5654 }
5655
5656 MATCH matchArgParameter()
5657 {
5658 RootObject oarg;
5659
5660 if (i < tiargs.length)
5661 oarg = (*tiargs)[i];
5662 else
5663 {
5664 // Get default argument instead
5665 oarg = tp.defaultArg(instLoc, sc);
5666 if (!oarg)
5667 {
5668 assert(i < dedtypes.length);
5669 // It might have already been deduced
5670 oarg = dedtypes[i];
5671 if (!oarg)
5672 return matchArgNoMatch();
5673 }
5674 }
5675 return tp.matchArg(sc, oarg, i, parameters, dedtypes, psparam);
5676 }
5677
5678 MATCH matchArgTuple(TemplateTupleParameter ttp)
5679 {
5680 /* The rest of the actual arguments (tiargs[]) form the match
5681 * for the variadic parameter.
5682 */
5683 assert(i + 1 == dedtypes.length); // must be the last one
5684 Tuple ovar;
5685
5686 if (Tuple u = isTuple(dedtypes[i]))
5687 {
5688 // It has already been deduced
5689 ovar = u;
5690 }
5691 else if (i + 1 == tiargs.length && isTuple((*tiargs)[i]))
5692 ovar = isTuple((*tiargs)[i]);
5693 else
5694 {
5695 ovar = new Tuple();
5696 //printf("ovar = %p\n", ovar);
5697 if (i < tiargs.length)
5698 {
5699 //printf("i = %d, tiargs.length = %d\n", i, tiargs.length);
5700 ovar.objects.setDim(tiargs.length - i);
5701 foreach (j, ref obj; ovar.objects)
5702 obj = (*tiargs)[i + j];
5703 }
5704 }
5705 return ttp.matchArg(sc, ovar, i, parameters, dedtypes, psparam);
5706 }
5707
5708 if (auto ttp = tp.isTemplateTupleParameter())
5709 return matchArgTuple(ttp);
5710
5711 return matchArgParameter();
5712 }
5713
5714 MATCH matchArg(TemplateParameter tp, Scope* sc, RootObject oarg, size_t i, TemplateParameters* parameters, ref Objects dedtypes, Declaration* psparam)
5715 {
5716 MATCH matchArgNoMatch()
5717 {
5718 //printf("\tm = %d\n", MATCH.nomatch);
5719 if (psparam)
5720 *psparam = null;
5721 return MATCH.nomatch;
5722 }
5723
5724 MATCH matchArgType(TemplateTypeParameter ttp)
5725 {
5726 //printf("TemplateTypeParameter.matchArg('%s')\n", ttp.ident.toChars());
5727 MATCH m = MATCH.exact;
5728 Type ta = isType(oarg);
5729 if (!ta)
5730 {
5731 //printf("%s %p %p %p\n", oarg.toChars(), isExpression(oarg), isDsymbol(oarg), isTuple(oarg));
5732 return matchArgNoMatch();
5733 }
5734 //printf("ta is %s\n", ta.toChars());
5735
5736 if (ttp.specType)
5737 {
5738 if (!ta || ta == TemplateTypeParameter.tdummy)
5739 return matchArgNoMatch();
5740
5741 //printf("\tcalling deduceType(): ta is %s, specType is %s\n", ta.toChars(), ttp.specType.toChars());
5742 MATCH m2 = deduceType(ta, sc, ttp.specType, *parameters, dedtypes);
5743 if (m2 == MATCH.nomatch)
5744 {
5745 //printf("\tfailed deduceType\n");
5746 return matchArgNoMatch();
5747 }
5748
5749 if (m2 < m)
5750 m = m2;
5751 if (dedtypes[i])
5752 {
5753 Type t = cast(Type)dedtypes[i];
5754
5755 if (ttp.dependent && !t.equals(ta)) // https://issues.dlang.org/show_bug.cgi?id=14357
5756 return matchArgNoMatch();
5757
5758 /* This is a self-dependent parameter. For example:
5759 * template X(T : T*) {}
5760 * template X(T : S!T, alias S) {}
5761 */
5762 //printf("t = %s ta = %s\n", t.toChars(), ta.toChars());
5763 ta = t;
5764 }
5765 }
5766 else
5767 {
5768 if (dedtypes[i])
5769 {
5770 // Must match already deduced type
5771 Type t = cast(Type)dedtypes[i];
5772
5773 if (!t.equals(ta))
5774 {
5775 //printf("t = %s ta = %s\n", t.toChars(), ta.toChars());
5776 return matchArgNoMatch();
5777 }
5778 }
5779 else
5780 {
5781 // So that matches with specializations are better
5782 m = MATCH.convert;
5783 }
5784 }
5785 dedtypes[i] = ta;
5786
5787 if (psparam)
5788 *psparam = new AliasDeclaration(ttp.loc, ttp.ident, ta);
5789 //printf("\tm = %d\n", m);
5790 return ttp.dependent ? MATCH.exact : m;
5791 }
5792
5793 MATCH matchArgValue(TemplateValueParameter tvp)
5794 {
5795 //printf("TemplateValueParameter.matchArg('%s')\n", tvp.ident.toChars());
5796 MATCH m = MATCH.exact;
5797
5798 Expression ei = isExpression(oarg);
5799 Type vt;
5800
5801 if (!ei && oarg)
5802 {
5803 Dsymbol si = isDsymbol(oarg);
5804 FuncDeclaration f = si ? si.isFuncDeclaration() : null;
5805 if (!f || !f.fbody || f.needThis())
5806 return matchArgNoMatch();
5807
5808 ei = new VarExp(tvp.loc, f);
5809 ei = ei.expressionSemantic(sc);
5810
5811 /* If a function is really property-like, and then
5812 * it's CTFEable, ei will be a literal expression.
5813 */
5814 const olderrors = global.startGagging();
5815 ei = resolveProperties(sc, ei);
5816 ei = ei.ctfeInterpret();
5817 if (global.endGagging(olderrors) || ei.op == EXP.error)
5818 return matchArgNoMatch();
5819
5820 /* https://issues.dlang.org/show_bug.cgi?id=14520
5821 * A property-like function can match to both
5822 * TemplateAlias and ValueParameter. But for template overloads,
5823 * it should always prefer alias parameter to be consistent
5824 * template match result.
5825 *
5826 * template X(alias f) { enum X = 1; }
5827 * template X(int val) { enum X = 2; }
5828 * int f1() { return 0; } // CTFEable
5829 * int f2(); // body-less function is not CTFEable
5830 * enum x1 = X!f1; // should be 1
5831 * enum x2 = X!f2; // should be 1
5832 *
5833 * e.g. The x1 value must be same even if the f1 definition will be moved
5834 * into di while stripping body code.
5835 */
5836 m = MATCH.convert;
5837 }
5838
5839 if (ei && ei.op == EXP.variable)
5840 {
5841 // Resolve const variables that we had skipped earlier
5842 ei = ei.ctfeInterpret();
5843 }
5844
5845 //printf("\tvalType: %s, ty = %d\n", tvp.valType.toChars(), tvp.valType.ty);
5846 vt = tvp.valType.typeSemantic(tvp.loc, sc);
5847 //printf("ei: %s, ei.type: %s\n", ei.toChars(), ei.type.toChars());
5848 //printf("vt = %s\n", vt.toChars());
5849
5850 if (ei.type)
5851 {
5852 MATCH m2 = ei.implicitConvTo(vt);
5853 //printf("m: %d\n", m);
5854 if (m2 < m)
5855 m = m2;
5856 if (m == MATCH.nomatch)
5857 return matchArgNoMatch();
5858 ei = ei.implicitCastTo(sc, vt);
5859 ei = ei.ctfeInterpret();
5860 }
5861
5862 if (tvp.specValue)
5863 {
5864 if (ei is null || (cast(void*)ei.type in TemplateValueParameter.edummies &&
5865 TemplateValueParameter.edummies[cast(void*)ei.type] == ei))
5866 return matchArgNoMatch();
5867
5868 Expression e = tvp.specValue;
5869
5870 sc = sc.startCTFE();
5871 e = e.expressionSemantic(sc);
5872 e = resolveProperties(sc, e);
5873 sc = sc.endCTFE();
5874 e = e.implicitCastTo(sc, vt);
5875 e = e.ctfeInterpret();
5876
5877 ei = ei.syntaxCopy();
5878 sc = sc.startCTFE();
5879 ei = ei.expressionSemantic(sc);
5880 sc = sc.endCTFE();
5881 ei = ei.implicitCastTo(sc, vt);
5882 ei = ei.ctfeInterpret();
5883 //printf("\tei: %s, %s\n", ei.toChars(), ei.type.toChars());
5884 //printf("\te : %s, %s\n", e.toChars(), e.type.toChars());
5885 if (!ei.equals(e))
5886 return matchArgNoMatch();
5887 }
5888 else
5889 {
5890 if (dedtypes[i])
5891 {
5892 // Must match already deduced value
5893 Expression e = cast(Expression)dedtypes[i];
5894 if (!ei || !ei.equals(e))
5895 return matchArgNoMatch();
5896 }
5897 }
5898 dedtypes[i] = ei;
5899
5900 if (psparam)
5901 {
5902 Initializer _init = new ExpInitializer(tvp.loc, ei);
5903 Declaration sparam = new VarDeclaration(tvp.loc, vt, tvp.ident, _init);
5904 sparam.storage_class = STC.manifest;
5905 *psparam = sparam;
5906 }
5907 return tvp.dependent ? MATCH.exact : m;
5908 }
5909
5910 MATCH matchArgAlias(TemplateAliasParameter tap)
5911 {
5912 //printf("TemplateAliasParameter.matchArg('%s')\n", tap.ident.toChars());
5913 MATCH m = MATCH.exact;
5914 Type ta = isType(oarg);
5915 RootObject sa = ta && !ta.deco ? null : getDsymbol(oarg);
5916 Expression ea = isExpression(oarg);
5917 if (ea)
5918 {
5919 if (auto te = ea.isThisExp())
5920 sa = te.var;
5921 else if (auto se = ea.isSuperExp())
5922 sa = se.var;
5923 else if (auto se = ea.isScopeExp())
5924 sa = se.sds;
5925 }
5926 if (sa)
5927 {
5928 if ((cast(Dsymbol)sa).isAggregateDeclaration())
5929 m = MATCH.convert;
5930
5931 /* specType means the alias must be a declaration with a type
5932 * that matches specType.
5933 */
5934 if (tap.specType)
5935 {
5936 tap.specType = typeSemantic(tap.specType, tap.loc, sc);
5937 Declaration d = (cast(Dsymbol)sa).isDeclaration();
5938 if (!d)
5939 return matchArgNoMatch();
5940 if (!d.type.equals(tap.specType))
5941 return matchArgNoMatch();
5942 }
5943 }
5944 else
5945 {
5946 sa = oarg;
5947 if (ea)
5948 {
5949 if (tap.specType)
5950 {
5951 if (!ea.type.equals(tap.specType))
5952 return matchArgNoMatch();
5953 }
5954 }
5955 else if (ta && ta.ty == Tinstance && !tap.specAlias)
5956 {
5957 /* Specialized parameter should be preferred
5958 * match to the template type parameter.
5959 * template X(alias a) {} // a == this
5960 * template X(alias a : B!A, alias B, A...) {} // B!A => ta
5961 */
5962 }
5963 else if (sa && sa == TemplateTypeParameter.tdummy)
5964 {
5965 /* https://issues.dlang.org/show_bug.cgi?id=2025
5966 * Aggregate Types should preferentially
5967 * match to the template type parameter.
5968 * template X(alias a) {} // a == this
5969 * template X(T) {} // T => sa
5970 */
5971 }
5972 else if (ta && ta.ty != Tident)
5973 {
5974 /* Match any type that's not a TypeIdentifier to alias parameters,
5975 * but prefer type parameter.
5976 * template X(alias a) { } // a == ta
5977 *
5978 * TypeIdentifiers are excluded because they might be not yet resolved aliases.
5979 */
5980 m = MATCH.convert;
5981 }
5982 else
5983 return matchArgNoMatch();
5984 }
5985
5986 if (tap.specAlias)
5987 {
5988 if (sa == TemplateAliasParameter.sdummy)
5989 return matchArgNoMatch();
5990 // check specialization if template arg is a symbol
5991 Dsymbol sx = isDsymbol(sa);
5992 if (sa != tap.specAlias && sx)
5993 {
5994 Type talias = isType(tap.specAlias);
5995 if (!talias)
5996 return matchArgNoMatch();
5997
5998 TemplateInstance ti = sx.isTemplateInstance();
5999 if (!ti && sx.parent)
6000 {
6001 ti = sx.parent.isTemplateInstance();
6002 if (ti && ti.name != sx.ident)
6003 return matchArgNoMatch();
6004 }
6005 if (!ti)
6006 return matchArgNoMatch();
6007
6008 Type t = new TypeInstance(Loc.initial, ti);
6009 MATCH m2 = deduceType(t, sc, talias, *parameters, dedtypes);
6010 if (m2 == MATCH.nomatch)
6011 return matchArgNoMatch();
6012 }
6013 // check specialization if template arg is a type
6014 else if (ta)
6015 {
6016 if (Type tspec = isType(tap.specAlias))
6017 {
6018 MATCH m2 = ta.implicitConvTo(tspec);
6019 if (m2 == MATCH.nomatch)
6020 return matchArgNoMatch();
6021 }
6022 else
6023 {
6024 error(tap.loc, "template parameter specialization for a type must be a type and not `%s`",
6025 tap.specAlias.toChars());
6026 return matchArgNoMatch();
6027 }
6028 }
6029 }
6030 else if (dedtypes[i])
6031 {
6032 // Must match already deduced symbol
6033 RootObject si = dedtypes[i];
6034 if (!sa || si != sa)
6035 return matchArgNoMatch();
6036 }
6037 dedtypes[i] = sa;
6038
6039 if (psparam)
6040 {
6041 if (Dsymbol s = isDsymbol(sa))
6042 {
6043 *psparam = new AliasDeclaration(tap.loc, tap.ident, s);
6044 }
6045 else if (Type t = isType(sa))
6046 {
6047 *psparam = new AliasDeclaration(tap.loc, tap.ident, t);
6048 }
6049 else
6050 {
6051 assert(ea);
6052
6053 // Declare manifest constant
6054 Initializer _init = new ExpInitializer(tap.loc, ea);
6055 auto v = new VarDeclaration(tap.loc, null, tap.ident, _init);
6056 v.storage_class = STC.manifest;
6057 v.dsymbolSemantic(sc);
6058 *psparam = v;
6059 }
6060 }
6061 return tap.dependent ? MATCH.exact : m;
6062 }
6063
6064 MATCH matchArgTuple(TemplateTupleParameter ttp)
6065 {
6066 //printf("TemplateTupleParameter.matchArg('%s')\n", ttp.ident.toChars());
6067 Tuple ovar = isTuple(oarg);
6068 if (!ovar)
6069 return MATCH.nomatch;
6070 if (dedtypes[i])
6071 {
6072 Tuple tup = isTuple(dedtypes[i]);
6073 if (!tup)
6074 return MATCH.nomatch;
6075 if (!match(tup, ovar))
6076 return MATCH.nomatch;
6077 }
6078 dedtypes[i] = ovar;
6079
6080 if (psparam)
6081 *psparam = new TupleDeclaration(ttp.loc, ttp.ident, &ovar.objects);
6082 return ttp.dependent ? MATCH.exact : MATCH.convert;
6083 }
6084
6085 if (auto ttp = tp.isTemplateTypeParameter())
6086 return matchArgType(ttp);
6087 if (auto tvp = tp.isTemplateValueParameter())
6088 return matchArgValue(tvp);
6089 if (auto tap = tp.isTemplateAliasParameter())
6090 return matchArgAlias(tap);
6091 if (auto ttp = tp.isTemplateTupleParameter())
6092 return matchArgTuple(ttp);
6093 assert(0);
6094 }
6095
6096
6097 /***********************************************
6098 * Collect and print statistics on template instantiations.
6099 */
6100 struct TemplateStats
6101 {
6102 __gshared TemplateStats[const void*] stats;
6103
6104 uint numInstantiations; // number of instantiations of the template
6105 uint uniqueInstantiations; // number of unique instantiations of the template
6106
6107 TemplateInstances* allInstances;
6108
6109 /*******************************
6110 * Add this instance
6111 * Params:
6112 * td = template declaration
6113 * ti = instance of td
6114 * listInstances = keep track of instances of templates
6115 */
6116 static void incInstance(const TemplateDeclaration td,
6117 const TemplateInstance ti,
6118 bool listInstances)
6119 {
6120 void log(ref TemplateStats ts)
6121 {
6122 if (ts.allInstances is null)
6123 ts.allInstances = new TemplateInstances();
6124 if (listInstances)
6125 ts.allInstances.push(cast() ti);
6126 }
6127
6128 // message(ti.loc, "incInstance %p %p", td, ti);
6129 if (!td)
6130 return;
6131 assert(ti);
6132 if (auto ts = cast(const void*) td in stats)
6133 {
6134 log(*ts);
6135 ++ts.numInstantiations;
6136 }
6137 else
6138 {
6139 stats[cast(const void*) td] = TemplateStats(1, 0);
6140 log(stats[cast(const void*) td]);
6141 }
6142 }
6143
6144 /*******************************
6145 * Add this unique instance
6146 */
6147 static void incUnique(const TemplateDeclaration td,
6148 const TemplateInstance ti)
6149 {
6150 // message(ti.loc, "incUnique %p %p", td, ti);
6151 if (!td)
6152 return;
6153 assert(ti);
6154 if (auto ts = cast(const void*) td in stats)
6155 ++ts.uniqueInstantiations;
6156 else
6157 stats[cast(const void*) td] = TemplateStats(0, 1);
6158 }
6159 }
6160
6161 /********************************
6162 * Print informational statistics on template instantiations.
6163 * Params:
6164 * listInstances = list instances of templates
6165 * eSink = where the print is sent
6166 */
6167 void printTemplateStats(bool listInstances, ErrorSink eSink)
6168 {
6169 static struct TemplateDeclarationStats
6170 {
6171 TemplateDeclaration td;
6172 TemplateStats ts;
6173 static int compare(scope const TemplateDeclarationStats* a,
6174 scope const TemplateDeclarationStats* b) @safe nothrow @nogc pure
6175 {
6176 auto diff = b.ts.uniqueInstantiations - a.ts.uniqueInstantiations;
6177 if (diff)
6178 return diff;
6179
6180 return b.ts.numInstantiations - a.ts.numInstantiations;
6181 }
6182 }
6183
6184 const stats_length = TemplateStats.stats.length;
6185 if (!stats_length)
6186 return; // nothing to report
6187
6188 Array!(TemplateDeclarationStats) sortedStats;
6189 sortedStats.reserve(stats_length);
6190 foreach (td_, ref ts; TemplateStats.stats)
6191 {
6192 sortedStats.push(TemplateDeclarationStats(cast(TemplateDeclaration) td_, ts));
6193 }
6194
6195 sortedStats.sort!(TemplateDeclarationStats.compare);
6196
6197 OutBuffer buf;
6198 foreach (const ref ss; sortedStats[])
6199 {
6200 buf.reset();
6201 HdrGenState hgs;
6202 hgs.skipConstraints = true;
6203 toCharsMaybeConstraints(ss.td, buf, hgs);
6204 const tchars = buf.peekChars();
6205 if (listInstances && ss.ts.allInstances)
6206 {
6207 eSink.message(ss.td.loc,
6208 "vtemplate: %u (%u distinct) instantiation(s) of template `%s` found, they are:",
6209 ss.ts.numInstantiations,
6210 ss.ts.uniqueInstantiations,
6211 tchars);
6212 foreach (const ti; (*ss.ts.allInstances)[])
6213 {
6214 if (ti.tinst) // if has enclosing instance
6215 eSink.message(ti.loc, "vtemplate: implicit instance `%s`", ti.toChars());
6216 else
6217 eSink.message(ti.loc, "vtemplate: explicit instance `%s`", ti.toChars());
6218 }
6219 }
6220 else
6221 {
6222 eSink.message(ss.td.loc,
6223 "vtemplate: %u (%u distinct) instantiation(s) of template `%s` found",
6224 ss.ts.numInstantiations,
6225 ss.ts.uniqueInstantiations,
6226 tchars);
6227 }
6228 }
6229 }
6230
6231 /// Pair of MATCHes
6232 struct MATCHpair
6233 {
6234 MATCH mta; /// match template parameters by initial template arguments
6235 MATCH mfa; /// match template parameters by inferred template arguments
6236
6237 debug this(MATCH mta, MATCH mfa)
6238 {
6239 assert(MATCH.min <= mta && mta <= MATCH.max);
6240 assert(MATCH.min <= mfa && mfa <= MATCH.max);
6241 this.mta = mta;
6242 this.mfa = mfa;
6243 }
6244 }
6245
6246 void write(ref OutBuffer buf, RootObject obj)
6247 {
6248 if (obj)
6249 {
6250 if (auto e = isExpression(obj))
6251 buf.writestring(e.toErrMsg());
6252 else
6253 buf.writestring(obj.toChars());
6254 }
6255 }