]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/d/dmd/dtemplate.c
d: Merge upstream dmd 47ed0330f
[thirdparty/gcc.git] / gcc / d / dmd / dtemplate.c
CommitLineData
b4c522fa
IB
1
2/* Compiler implementation of the D programming language
8e788ac6 3 * Copyright (C) 1999-2020 by The D Language Foundation, All Rights Reserved
b4c522fa
IB
4 * written by Walter Bright
5 * http://www.digitalmars.com
6 * Distributed under the Boost Software License, Version 1.0.
7 * http://www.boost.org/LICENSE_1_0.txt
8 * https://github.com/D-Programming-Language/dmd/blob/master/src/template.c
9 */
10
11// Handle template implementation
12
f9ab59ff 13#include "root/dsystem.h"
b4c522fa
IB
14#include "root/root.h"
15#include "root/aav.h"
16#include "root/rmem.h"
17#include "root/stringtable.h"
18#include "root/hash.h"
19
20#include "mangle.h"
21#include "mtype.h"
22#include "template.h"
23#include "init.h"
24#include "expression.h"
25#include "scope.h"
26#include "module.h"
27#include "aggregate.h"
28#include "declaration.h"
29#include "dsymbol.h"
30#include "mars.h"
31#include "dsymbol.h"
32#include "identifier.h"
33#include "hdrgen.h"
34#include "id.h"
35#include "attrib.h"
36#include "tokens.h"
37
38#define IDX_NOTFOUND (0x12345678) // index is not found
39
40Type *rawTypeMerge(Type *t1, Type *t2);
41bool MODimplicitConv(MOD modfrom, MOD modto);
42MATCH MODmethodConv(MOD modfrom, MOD modto);
43MOD MODmerge(MOD mod1, MOD mod2);
44
45static size_t templateParameterLookup(Type *tparam, TemplateParameters *parameters);
46static int arrayObjectMatch(Objects *oa1, Objects *oa2);
47static unsigned char deduceWildHelper(Type *t, Type **at, Type *tparam);
48static MATCH deduceTypeHelper(Type *t, Type **at, Type *tparam);
49static bool reliesOnTident(Type *t, TemplateParameters *tparams = NULL, size_t iStart = 0);
50Expression *semantic(Expression *e, Scope *sc);
51bool evalStaticCondition(Scope *sc, Expression *exp, Expression *e, bool &errors);
52
53/********************************************
54 * These functions substitute for dynamic_cast. dynamic_cast does not work
55 * on earlier versions of gcc.
56 */
57
58Expression *isExpression(RootObject *o)
59{
60 //return dynamic_cast<Expression *>(o);
61 if (!o || o->dyncast() != DYNCAST_EXPRESSION)
62 return NULL;
63 return (Expression *)o;
64}
65
66Dsymbol *isDsymbol(RootObject *o)
67{
68 //return dynamic_cast<Dsymbol *>(o);
69 if (!o || o->dyncast() != DYNCAST_DSYMBOL)
70 return NULL;
71 return (Dsymbol *)o;
72}
73
74Type *isType(RootObject *o)
75{
76 //return dynamic_cast<Type *>(o);
77 if (!o || o->dyncast() != DYNCAST_TYPE)
78 return NULL;
79 return (Type *)o;
80}
81
82Tuple *isTuple(RootObject *o)
83{
84 //return dynamic_cast<Tuple *>(o);
85 if (!o || o->dyncast() != DYNCAST_TUPLE)
86 return NULL;
87 return (Tuple *)o;
88}
89
90Parameter *isParameter(RootObject *o)
91{
92 //return dynamic_cast<Parameter *>(o);
93 if (!o || o->dyncast() != DYNCAST_PARAMETER)
94 return NULL;
95 return (Parameter *)o;
96}
97
98/**************************************
99 * Is this Object an error?
100 */
101bool isError(RootObject *o)
102{
103 Type *t = isType(o);
104 if (t)
105 return (t->ty == Terror);
106 Expression *e = isExpression(o);
107 if (e)
108 return (e->op == TOKerror || !e->type || e->type->ty == Terror);
109 Tuple *v = isTuple(o);
110 if (v)
111 return arrayObjectIsError(&v->objects);
112 Dsymbol *s = isDsymbol(o);
113 assert(s);
114 if (s->errors)
115 return true;
116 return s->parent ? isError(s->parent) : false;
117}
118
119/**************************************
120 * Are any of the Objects an error?
121 */
122bool arrayObjectIsError(Objects *args)
123{
124 for (size_t i = 0; i < args->dim; i++)
125 {
126 RootObject *o = (*args)[i];
127 if (isError(o))
128 return true;
129 }
130 return false;
131}
132
133/***********************
134 * Try to get arg as a type.
135 */
136
137Type *getType(RootObject *o)
138{
139 Type *t = isType(o);
140 if (!t)
141 {
142 Expression *e = isExpression(o);
143 if (e)
144 t = e->type;
145 }
146 return t;
147}
148
149Dsymbol *getDsymbol(RootObject *oarg)
150{
151 //printf("getDsymbol()\n");
152 //printf("e %p s %p t %p v %p\n", isExpression(oarg), isDsymbol(oarg), isType(oarg), isTuple(oarg));
153
154 Dsymbol *sa;
155 Expression *ea = isExpression(oarg);
156 if (ea)
157 {
158 // Try to convert Expression to symbol
159 if (ea->op == TOKvar)
160 sa = ((VarExp *)ea)->var;
161 else if (ea->op == TOKfunction)
162 {
163 if (((FuncExp *)ea)->td)
164 sa = ((FuncExp *)ea)->td;
165 else
166 sa = ((FuncExp *)ea)->fd;
167 }
168 else if (ea->op == TOKtemplate)
169 sa = ((TemplateExp *)ea)->td;
170 else
171 sa = NULL;
172 }
173 else
174 {
175 // Try to convert Type to symbol
176 Type *ta = isType(oarg);
177 if (ta)
178 sa = ta->toDsymbol(NULL);
179 else
180 sa = isDsymbol(oarg); // if already a symbol
181 }
182 return sa;
183}
184
185/***********************
186 * Try to get value from manifest constant
187 */
188
189static Expression *getValue(Expression *e)
190{
191 if (e && e->op == TOKvar)
192 {
193 VarDeclaration *v = ((VarExp *)e)->var->isVarDeclaration();
194 if (v && v->storage_class & STCmanifest)
195 {
196 e = v->getConstInitializer();
197 }
198 }
199 return e;
200}
201
202static Expression *getValue(Dsymbol *&s)
203{
204 Expression *e = NULL;
205 if (s)
206 {
207 VarDeclaration *v = s->isVarDeclaration();
208 if (v && v->storage_class & STCmanifest)
209 {
210 e = v->getConstInitializer();
211 }
212 }
213 return e;
214}
215
216/**********************************
217 * Return true if e could be valid only as a template value parameter.
218 * Return false if it might be an alias or tuple.
219 * (Note that even in this case, it could still turn out to be a value).
220 */
221bool definitelyValueParameter(Expression *e)
222{
223 // None of these can be value parameters
224 if (e->op == TOKtuple || e->op == TOKscope ||
225 e->op == TOKtype || e->op == TOKdottype ||
226 e->op == TOKtemplate || e->op == TOKdottd ||
227 e->op == TOKfunction || e->op == TOKerror ||
228 e->op == TOKthis || e->op == TOKsuper)
229 return false;
230
231 if (e->op != TOKdotvar)
232 return true;
233
234 /* Template instantiations involving a DotVar expression are difficult.
235 * In most cases, they should be treated as a value parameter, and interpreted.
236 * But they might also just be a fully qualified name, which should be treated
237 * as an alias.
238 */
239
240 // x.y.f cannot be a value
241 FuncDeclaration *f = ((DotVarExp *)e)->var->isFuncDeclaration();
242 if (f)
243 return false;
244
245 while (e->op == TOKdotvar)
246 {
247 e = ((DotVarExp *)e)->e1;
248 }
249 // this.x.y and super.x.y couldn't possibly be valid values.
250 if (e->op == TOKthis || e->op == TOKsuper)
251 return false;
252
253 // e.type.x could be an alias
254 if (e->op == TOKdottype)
255 return false;
256
257 // var.x.y is the only other possible form of alias
258 if (e->op != TOKvar)
259 return true;
260
261 VarDeclaration *v = ((VarExp *)e)->var->isVarDeclaration();
262
263 // func.x.y is not an alias
264 if (!v)
265 return true;
266
267 // TODO: Should we force CTFE if it is a global constant?
268
269 return false;
270}
271
272static Expression *getExpression(RootObject *o)
273{
274 Dsymbol *s = isDsymbol(o);
275 return s ? getValue(s) : getValue(isExpression(o));
276}
277
278/******************************
279 * If o1 matches o2, return true.
280 * Else, return false.
281 */
282
283static bool match(RootObject *o1, RootObject *o2)
284{
285 //printf("match() o1 = %p %s (%d), o2 = %p %s (%d)\n",
286 // o1, o1->toChars(), o1->dyncast(), o2, o2->toChars(), o2->dyncast());
287
288 /* A proper implementation of the various equals() overrides
289 * should make it possible to just do o1->equals(o2), but
290 * we'll do that another day.
291 */
292
293 /* Manifest constants should be compared by their values,
294 * at least in template arguments.
295 */
296
297 if (Type *t1 = isType(o1))
298 {
299 Type *t2 = isType(o2);
300 if (!t2)
301 goto Lnomatch;
302
303 //printf("\tt1 = %s\n", t1->toChars());
304 //printf("\tt2 = %s\n", t2->toChars());
305 if (!t1->equals(t2))
306 goto Lnomatch;
307
308 goto Lmatch;
309 }
310 if (Expression *e1 = getExpression(o1))
311 {
312 Expression *e2 = getExpression(o2);
313 if (!e2)
314 goto Lnomatch;
315
316 //printf("\te1 = %s %s %s\n", e1->type->toChars(), Token::toChars(e1->op), e1->toChars());
317 //printf("\te2 = %s %s %s\n", e2->type->toChars(), Token::toChars(e2->op), e2->toChars());
318
319 // two expressions can be equal although they do not have the same
320 // type; that happens when they have the same value. So check type
321 // as well as expression equality to ensure templates are properly
322 // matched.
323 if (!e1->type->equals(e2->type) || !e1->equals(e2))
324 goto Lnomatch;
325
326 goto Lmatch;
327 }
328 if (Dsymbol *s1 = isDsymbol(o1))
329 {
330 Dsymbol *s2 = isDsymbol(o2);
331 if (!s2)
332 goto Lnomatch;
333
334 //printf("\ts1 = %s\n", s1->toChars());
335 //printf("\ts2 = %s\n", s2->toChars());
336 if (!s1->equals(s2))
337 goto Lnomatch;
338 if (s1->parent != s2->parent && !s1->isFuncDeclaration() && !s2->isFuncDeclaration())
339 goto Lnomatch;
340
341 goto Lmatch;
342 }
343 if (Tuple *u1 = isTuple(o1))
344 {
345 Tuple *u2 = isTuple(o2);
346 if (!u2)
347 goto Lnomatch;
348
349 //printf("\tu1 = %s\n", u1->toChars());
350 //printf("\tu2 = %s\n", u2->toChars());
351 if (!arrayObjectMatch(&u1->objects, &u2->objects))
352 goto Lnomatch;
353
354 goto Lmatch;
355 }
356Lmatch:
357 //printf("\t-> match\n");
358 return true;
359
360Lnomatch:
361 //printf("\t-> nomatch\n");
362 return false;
363}
364
365
366/************************************
367 * Match an array of them.
368 */
369int arrayObjectMatch(Objects *oa1, Objects *oa2)
370{
371 if (oa1 == oa2)
372 return 1;
373 if (oa1->dim != oa2->dim)
374 return 0;
375 for (size_t j = 0; j < oa1->dim; j++)
376 {
377 RootObject *o1 = (*oa1)[j];
378 RootObject *o2 = (*oa2)[j];
379 if (!match(o1, o2))
380 {
381 return 0;
382 }
383 }
384 return 1;
385}
386
387
388/************************************
389 * Computes hash of expression.
390 * Handles all Expression classes and MUST match their equals method,
391 * i.e. e1->equals(e2) implies expressionHash(e1) == expressionHash(e2).
392 */
393static hash_t expressionHash(Expression *e)
394{
395 switch (e->op)
396 {
397 case TOKint64:
398 return (size_t) ((IntegerExp *)e)->getInteger();
399
400 case TOKfloat64:
401 return CTFloat::hash(((RealExp *)e)->value);
402
403 case TOKcomplex80:
404 {
405 ComplexExp *ce = (ComplexExp *)e;
406 return mixHash(CTFloat::hash(ce->toReal()), CTFloat::hash(ce->toImaginary()));
407 }
408
409 case TOKidentifier:
410 return (size_t)(void *) ((IdentifierExp *)e)->ident;
411
412 case TOKnull:
413 return (size_t)(void *) ((NullExp *)e)->type;
414
415 case TOKstring:
416 {
417 StringExp *se = (StringExp *)e;
418 return calcHash((const char *)se->string, se->len * se->sz);
419 }
420
421 case TOKtuple:
422 {
423 TupleExp *te = (TupleExp *)e;
424 size_t hash = 0;
425 hash += te->e0 ? expressionHash(te->e0) : 0;
426 for (size_t i = 0; i < te->exps->dim; i++)
427 {
428 Expression *elem = (*te->exps)[i];
429 hash = mixHash(hash, expressionHash(elem));
430 }
431 return hash;
432 }
433
434 case TOKarrayliteral:
435 {
436 ArrayLiteralExp *ae = (ArrayLiteralExp *)e;
437 size_t hash = 0;
438 for (size_t i = 0; i < ae->elements->dim; i++)
439 hash = mixHash(hash, expressionHash(ae->getElement(i)));
440 return hash;
441 }
442
443 case TOKassocarrayliteral:
444 {
445 AssocArrayLiteralExp *ae = (AssocArrayLiteralExp *)e;
446 size_t hash = 0;
447 for (size_t i = 0; i < ae->keys->dim; i++)
448 // reduction needs associative op as keys are unsorted (use XOR)
449 hash ^= mixHash(expressionHash((*ae->keys)[i]), expressionHash((*ae->values)[i]));
450 return hash;
451 }
452
453 case TOKstructliteral:
454 {
455 StructLiteralExp *se = (StructLiteralExp *)e;
456 size_t hash = 0;
457 for (size_t i = 0; i < se->elements->dim; i++)
458 {
459 Expression *elem = (*se->elements)[i];
460 hash = mixHash(hash, elem ? expressionHash(elem) : 0);
461 }
462 return hash;
463 }
464
465 case TOKvar:
466 return (size_t)(void *) ((VarExp *)e)->var;
467
468 case TOKfunction:
469 return (size_t)(void *) ((FuncExp *)e)->fd;
470
471 default:
472 // no custom equals for this expression
473 // equals based on identity
474 return (size_t)(void *) e;
475 }
476}
477
478
479/************************************
480 * Return hash of Objects.
481 */
482static hash_t arrayObjectHash(Objects *oa1)
483{
484 hash_t hash = 0;
485 for (size_t j = 0; j < oa1->dim; j++)
486 {
487 /* Must follow the logic of match()
488 */
489 RootObject *o1 = (*oa1)[j];
490 if (Type *t1 = isType(o1))
491 hash = mixHash(hash, (size_t)t1->deco);
492 else if (Expression *e1 = getExpression(o1))
493 hash = mixHash(hash, expressionHash(e1));
494 else if (Dsymbol *s1 = isDsymbol(o1))
495 {
496 FuncAliasDeclaration *fa1 = s1->isFuncAliasDeclaration();
497 if (fa1)
498 s1 = fa1->toAliasFunc();
499 hash = mixHash(hash, mixHash((size_t)(void *)s1->getIdent(), (size_t)(void *)s1->parent));
500 }
501 else if (Tuple *u1 = isTuple(o1))
502 hash = mixHash(hash, arrayObjectHash(&u1->objects));
503 }
504 return hash;
505}
506
507RootObject *objectSyntaxCopy(RootObject *o)
508{
509 if (!o)
510 return NULL;
511 if (Type *t = isType(o))
512 return t->syntaxCopy();
513 if (Expression *e = isExpression(o))
514 return e->syntaxCopy();
515 return o;
516}
517
518
519/* ======================== TemplateDeclaration ============================= */
520
521TemplateDeclaration::TemplateDeclaration(Loc loc, Identifier *id,
522 TemplateParameters *parameters, Expression *constraint, Dsymbols *decldefs, bool ismixin, bool literal)
523 : ScopeDsymbol(id)
524{
525 this->loc = loc;
526 this->parameters = parameters;
527 this->origParameters = parameters;
528 this->constraint = constraint;
529 this->members = decldefs;
530 this->overnext = NULL;
531 this->overroot = NULL;
532 this->funcroot = NULL;
533 this->onemember = NULL;
534 this->literal = literal;
535 this->ismixin = ismixin;
536 this->isstatic = true;
537 this->previous = NULL;
538 this->protection = Prot(PROTundefined);
539 this->instances = NULL;
540
541 // Compute in advance for Ddoc's use
542 // Bugzilla 11153: ident could be NULL if parsing fails.
543 if (members && ident)
544 {
545 Dsymbol *s;
546 if (Dsymbol::oneMembers(members, &s, ident) && s)
547 {
548 onemember = s;
549 s->parent = this;
550 }
551 }
552}
553
554Dsymbol *TemplateDeclaration::syntaxCopy(Dsymbol *)
555{
556 //printf("TemplateDeclaration::syntaxCopy()\n");
557 TemplateParameters *p = NULL;
558 if (parameters)
559 {
560 p = new TemplateParameters();
561 p->setDim(parameters->dim);
562 for (size_t i = 0; i < p->dim; i++)
563 (*p)[i] = (*parameters)[i]->syntaxCopy();
564 }
565 return new TemplateDeclaration(loc, ident, p,
566 constraint ? constraint->syntaxCopy() : NULL,
567 Dsymbol::arraySyntaxCopy(members), ismixin, literal);
568}
569
570void TemplateDeclaration::semantic(Scope *sc)
571{
572 if (semanticRun != PASSinit)
573 return; // semantic() already run
574
575 // Remember templates defined in module object that we need to know about
576 if (sc->_module && sc->_module->ident == Id::object)
577 {
578 if (ident == Id::RTInfo)
579 Type::rtinfo = this;
580 }
581
582 /* Remember Scope for later instantiations, but make
583 * a copy since attributes can change.
584 */
585 if (!this->_scope)
586 {
587 this->_scope = sc->copy();
588 this->_scope->setNoFree();
589 }
590
591 semanticRun = PASSsemantic;
592
593 parent = sc->parent;
594 protection = sc->protection;
595 isstatic = toParent()->isModule() || (_scope->stc & STCstatic);
596
597 if (!isstatic)
598 {
599 if (AggregateDeclaration *ad = parent->pastMixin()->isAggregateDeclaration())
600 ad->makeNested();
601 }
602
603 // Set up scope for parameters
604 ScopeDsymbol *paramsym = new ScopeDsymbol();
605 paramsym->parent = parent;
606 Scope *paramscope = sc->push(paramsym);
607 paramscope->stc = 0;
608
609 if (global.params.doDocComments)
610 {
611 origParameters = new TemplateParameters();
612 origParameters->setDim(parameters->dim);
613 for (size_t i = 0; i < parameters->dim; i++)
614 {
615 TemplateParameter *tp = (*parameters)[i];
616 (*origParameters)[i] = tp->syntaxCopy();
617 }
618 }
619
620 for (size_t i = 0; i < parameters->dim; i++)
621 {
622 TemplateParameter *tp = (*parameters)[i];
623
624 if (!tp->declareParameter(paramscope))
625 {
626 error(tp->loc, "parameter '%s' multiply defined", tp->ident->toChars());
627 errors = true;
628 }
629 if (!tp->semantic(paramscope, parameters))
630 {
631 errors = true;
632 }
633 if (i + 1 != parameters->dim && tp->isTemplateTupleParameter())
634 {
635 error("template tuple parameter must be last one");
636 errors = true;
637 }
638 }
639
640 /* Calculate TemplateParameter::dependent
641 */
642 TemplateParameters tparams;
643 tparams.setDim(1);
644 for (size_t i = 0; i < parameters->dim; i++)
645 {
646 TemplateParameter *tp = (*parameters)[i];
647 tparams[0] = tp;
648
649 for (size_t j = 0; j < parameters->dim; j++)
650 {
651 // Skip cases like: X(T : T)
652 if (i == j)
653 continue;
654
655 if (TemplateTypeParameter *ttp = (*parameters)[j]->isTemplateTypeParameter())
656 {
657 if (reliesOnTident(ttp->specType, &tparams))
658 tp->dependent = true;
659 }
660 else if (TemplateAliasParameter *tap = (*parameters)[j]->isTemplateAliasParameter())
661 {
662 if (reliesOnTident(tap->specType, &tparams) ||
663 reliesOnTident(isType(tap->specAlias), &tparams))
664 {
665 tp->dependent = true;
666 }
667 }
668 }
669 }
670
671 paramscope->pop();
672
673 // Compute again
674 onemember = NULL;
675 if (members)
676 {
677 Dsymbol *s;
678 if (Dsymbol::oneMembers(members, &s, ident) && s)
679 {
680 onemember = s;
681 s->parent = this;
682 }
683 }
684
685 /* BUG: should check:
686 * o no virtual functions or non-static data members of classes
687 */
956fba45 688 semanticRun = PASSsemanticdone;
b4c522fa
IB
689}
690
f9ab59ff 691const char *TemplateDeclaration::kind() const
b4c522fa
IB
692{
693 return (onemember && onemember->isAggregateDeclaration())
694 ? onemember->kind()
695 : "template";
696}
697
698/**********************************
699 * Overload existing TemplateDeclaration 'this' with the new one 's'.
700 * Return true if successful; i.e. no conflict.
701 */
702
703bool TemplateDeclaration::overloadInsert(Dsymbol *s)
704{
705 FuncDeclaration *fd = s->isFuncDeclaration();
706 if (fd)
707 {
708 if (funcroot)
709 return funcroot->overloadInsert(fd);
710 funcroot = fd;
711 return funcroot->overloadInsert(this);
712 }
713
714 TemplateDeclaration *td = s->isTemplateDeclaration();
715 if (!td)
716 return false;
717
718 TemplateDeclaration *pthis = this;
719 TemplateDeclaration **ptd;
720 for (ptd = &pthis; *ptd; ptd = &(*ptd)->overnext)
721 {
722 }
723
724 td->overroot = this;
725 *ptd = td;
726 return true;
727}
728
729/****************************
730 * Check to see if constraint is satisfied.
731 */
732bool TemplateDeclaration::evaluateConstraint(
733 TemplateInstance *ti, Scope *sc, Scope *paramscope,
734 Objects *dedargs, FuncDeclaration *fd)
735{
736 /* Detect recursive attempts to instantiate this template declaration,
737 * Bugzilla 4072
738 * void foo(T)(T x) if (is(typeof(foo(x)))) { }
739 * static assert(!is(typeof(foo(7))));
740 * Recursive attempts are regarded as a constraint failure.
741 */
742 /* There's a chicken-and-egg problem here. We don't know yet if this template
743 * instantiation will be a local one (enclosing is set), and we won't know until
744 * after selecting the correct template. Thus, function we're nesting inside
745 * is not on the sc scope chain, and this can cause errors in FuncDeclaration::getLevel().
746 * Workaround the problem by setting a flag to relax the checking on frame errors.
747 */
748
749 for (TemplatePrevious *p = previous; p; p = p->prev)
750 {
751 if (arrayObjectMatch(p->dedargs, dedargs))
752 {
753 //printf("recursive, no match p->sc=%p %p %s\n", p->sc, this, this->toChars());
754 /* It must be a subscope of p->sc, other scope chains are not recursive
755 * instantiations.
756 */
757 for (Scope *scx = sc; scx; scx = scx->enclosing)
758 {
759 if (scx == p->sc)
760 return false;
761 }
762 }
763 /* BUG: should also check for ref param differences
764 */
765 }
766
767 TemplatePrevious pr;
768 pr.prev = previous;
769 pr.sc = paramscope;
770 pr.dedargs = dedargs;
771 previous = &pr; // add this to threaded list
772
773 Scope *scx = paramscope->push(ti);
774 scx->parent = ti;
775 scx->tinst = NULL;
776 scx->minst = NULL;
777
778 assert(!ti->symtab);
779 if (fd)
780 {
781 /* Declare all the function parameters as variables and add them to the scope
782 * Making parameters is similar to FuncDeclaration::semantic3
783 */
784 TypeFunction *tf = (TypeFunction *)fd->type;
785 assert(tf->ty == Tfunction);
786
787 scx->parent = fd;
788
789 Parameters *fparameters = tf->parameters;
790 int fvarargs = tf->varargs;
791
792 size_t nfparams = Parameter::dim(fparameters);
793 for (size_t i = 0; i < nfparams; i++)
794 {
795 Parameter *fparam = Parameter::getNth(fparameters, i);
796 fparam->storageClass &= (STCin | STCout | STCref | STClazy | STCfinal | STC_TYPECTOR | STCnodtor);
797 fparam->storageClass |= STCparameter;
798 if (fvarargs == 2 && i + 1 == nfparams)
799 fparam->storageClass |= STCvariadic;
800 }
801 for (size_t i = 0; i < fparameters->dim; i++)
802 {
803 Parameter *fparam = (*fparameters)[i];
804 if (!fparam->ident)
805 continue; // don't add it, if it has no name
806 VarDeclaration *v = new VarDeclaration(loc, fparam->type, fparam->ident, NULL);
807 v->storage_class = fparam->storageClass;
808 v->semantic(scx);
809 if (!ti->symtab)
810 ti->symtab = new DsymbolTable();
811 if (!scx->insert(v))
812 error("parameter %s.%s is already defined", toChars(), v->toChars());
813 else
814 v->parent = fd;
815 }
816 if (isstatic)
817 fd->storage_class |= STCstatic;
818
819 fd->vthis = fd->declareThis(scx, fd->isThis());
820 }
821
822 Expression *e = constraint->syntaxCopy();
823
824 assert(ti->inst == NULL);
825 ti->inst = ti; // temporary instantiation to enable genIdent()
826
827 scx->flags |= SCOPEconstraint;
828 bool errors = false;
829 bool result = evalStaticCondition(scx, constraint, e, errors);
830 ti->inst = NULL;
831 ti->symtab = NULL;
832 scx = scx->pop();
833 previous = pr.prev; // unlink from threaded list
834 if (errors)
835 return false;
836 return result;
837}
838
839/***************************************
840 * Given that ti is an instance of this TemplateDeclaration,
841 * deduce the types of the parameters to this, and store
842 * those deduced types in dedtypes[].
843 * Input:
844 * flag 1: don't do semantic() because of dummy types
845 * 2: don't change types in matchArg()
846 * Output:
847 * dedtypes deduced arguments
848 * Return match level.
849 */
850
851MATCH TemplateDeclaration::matchWithInstance(Scope *sc, TemplateInstance *ti,
852 Objects *dedtypes, Expressions *fargs, int flag)
853{
854 MATCH m;
855 size_t dedtypes_dim = dedtypes->dim;
856
857 dedtypes->zero();
858
859 if (errors)
860 return MATCHnomatch;
861
862 size_t parameters_dim = parameters->dim;
863 int variadic = isVariadic() != NULL;
864
865 // If more arguments than parameters, no match
866 if (ti->tiargs->dim > parameters_dim && !variadic)
867 {
868 return MATCHnomatch;
869 }
870
871 assert(dedtypes_dim == parameters_dim);
872 assert(dedtypes_dim >= ti->tiargs->dim || variadic);
873
874 assert(_scope);
875
876 // Set up scope for template parameters
877 ScopeDsymbol *paramsym = new ScopeDsymbol();
878 paramsym->parent = _scope->parent;
879 Scope *paramscope = _scope->push(paramsym);
880 paramscope->tinst = ti;
881 paramscope->minst = sc->minst;
882 paramscope->callsc = sc;
883 paramscope->stc = 0;
884
885 // Attempt type deduction
886 m = MATCHexact;
887 for (size_t i = 0; i < dedtypes_dim; i++)
888 {
889 MATCH m2;
890 TemplateParameter *tp = (*parameters)[i];
891 Declaration *sparam;
892
893 //printf("\targument [%d]\n", i);
894 m2 = tp->matchArg(ti->loc, paramscope, ti->tiargs, i, parameters, dedtypes, &sparam);
895 //printf("\tm2 = %d\n", m2);
896
897 if (m2 == MATCHnomatch)
898 {
899 goto Lnomatch;
900 }
901
902 if (m2 < m)
903 m = m2;
904
905 if (!flag)
906 sparam->semantic(paramscope);
907 if (!paramscope->insert(sparam)) // TODO: This check can make more early
908 goto Lnomatch; // in TemplateDeclaration::semantic, and
909 // then we don't need to make sparam if flags == 0
910 }
911
912 if (!flag)
913 {
914 /* Any parameter left without a type gets the type of
915 * its corresponding arg
916 */
917 for (size_t i = 0; i < dedtypes_dim; i++)
918 {
919 if (!(*dedtypes)[i])
920 {
921 assert(i < ti->tiargs->dim);
922 (*dedtypes)[i] = (Type *)(*ti->tiargs)[i];
923 }
924 }
925 }
926
927 if (m > MATCHnomatch && constraint && !flag)
928 {
929 if (ti->hasNestedArgs(ti->tiargs, this->isstatic)) // TODO: should gag error
930 ti->parent = ti->enclosing;
931 else
932 ti->parent = this->parent;
933
934 // Similar to doHeaderInstantiation
935 FuncDeclaration *fd = onemember ? onemember->isFuncDeclaration() : NULL;
936 if (fd)
937 {
938 assert(fd->type->ty == Tfunction);
939 TypeFunction *tf = (TypeFunction *)fd->type->syntaxCopy();
940
941 fd = new FuncDeclaration(fd->loc, fd->endloc, fd->ident, fd->storage_class, tf);
942 fd->parent = ti;
943 fd->inferRetType = true;
944
945 // Shouldn't run semantic on default arguments and return type.
946 for (size_t i = 0; i < tf->parameters->dim; i++)
947 (*tf->parameters)[i]->defaultArg = NULL;
948 tf->next = NULL;
949
950 // Resolve parameter types and 'auto ref's.
951 tf->fargs = fargs;
952 unsigned olderrors = global.startGagging();
953 fd->type = tf->semantic(loc, paramscope);
954 if (global.endGagging(olderrors))
955 {
956 assert(fd->type->ty != Tfunction);
957 goto Lnomatch;
958 }
959 assert(fd->type->ty == Tfunction);
960 fd->originalType = fd->type; // for mangling
961 }
962
963 // TODO: dedtypes => ti->tiargs ?
964 if (!evaluateConstraint(ti, sc, paramscope, dedtypes, fd))
965 goto Lnomatch;
966 }
967
968 goto Lret;
969
970Lnomatch:
971 m = MATCHnomatch;
972
973Lret:
974 paramscope->pop();
975 return m;
976}
977
978/********************************************
979 * Determine partial specialization order of 'this' vs td2.
980 * Returns:
981 * match this is at least as specialized as td2
982 * 0 td2 is more specialized than this
983 */
984
985MATCH TemplateDeclaration::leastAsSpecialized(Scope *sc, TemplateDeclaration *td2, Expressions *fargs)
986{
987 /* This works by taking the template parameters to this template
988 * declaration and feeding them to td2 as if it were a template
989 * instance.
990 * If it works, then this template is at least as specialized
991 * as td2.
992 */
993
994 TemplateInstance ti(Loc(), ident); // create dummy template instance
995 // Set type arguments to dummy template instance to be types
996 // generated from the parameters to this template declaration
997 ti.tiargs = new Objects();
998 ti.tiargs->reserve(parameters->dim);
999 for (size_t i = 0; i < parameters->dim; i++)
1000 {
1001 TemplateParameter *tp = (*parameters)[i];
1002 if (tp->dependent)
1003 break;
1004 RootObject *p = (RootObject *)tp->dummyArg();
1005 if (!p)
1006 break;
1007
1008 ti.tiargs->push(p);
1009 }
1010
1011 // Temporary Array to hold deduced types
1012 Objects dedtypes;
1013 dedtypes.setDim(td2->parameters->dim);
1014
1015 // Attempt a type deduction
1016 MATCH m = td2->matchWithInstance(sc, &ti, &dedtypes, fargs, 1);
1017 if (m > MATCHnomatch)
1018 {
1019 /* A non-variadic template is more specialized than a
1020 * variadic one.
1021 */
1022 TemplateTupleParameter *tp = isVariadic();
1023 if (tp && !tp->dependent && !td2->isVariadic())
1024 goto L1;
1025
1026 return m;
1027 }
1028 L1:
1029 return MATCHnomatch;
1030}
1031
1032static Expression *emptyArrayElement = NULL;
1033
1034class TypeDeduced : public Type
1035{
1036public:
1037 Type *tded;
1038 Expressions argexps; // corresponding expressions
1039 Types tparams; // tparams[i]->mod
1040
1041 TypeDeduced(Type *tt, Expression *e, Type *tparam)
1042 : Type(Tnone)
1043 {
1044 tded = tt;
1045 argexps.push(e);
1046 tparams.push(tparam);
1047 }
1048
1049 virtual ~TypeDeduced()
1050 {
1051 }
1052
1053 void update(Expression *e, Type *tparam)
1054 {
1055 argexps.push(e);
1056 tparams.push(tparam);
1057 }
1058 void update(Type *tt, Expression *e, Type *tparam)
1059 {
1060 tded = tt;
1061 argexps.push(e);
1062 tparams.push(tparam);
1063 }
1064 MATCH matchAll(Type *tt)
1065 {
1066 MATCH match = MATCHexact;
1067 for (size_t j = 0; j < argexps.dim; j++)
1068 {
1069 Expression *e = argexps[j];
1070 assert(e);
1071 if (e == emptyArrayElement)
1072 continue;
1073
1074 Type *t = tt->addMod(tparams[j]->mod)->substWildTo(MODconst);
1075
1076 MATCH m = e->implicitConvTo(t);
1077 if (match > m)
1078 match = m;
1079 if (match <= MATCHnomatch)
1080 break;
1081 }
1082 return match;
1083 }
1084};
1085
1086/*************************************************
1087 * Match function arguments against a specific template function.
1088 * Input:
1089 * ti
1090 * sc instantiation scope
1091 * fd
1092 * tthis 'this' argument if !NULL
1093 * fargs arguments to function
1094 * Output:
1095 * fd Partially instantiated function declaration
1096 * ti->tdtypes Expression/Type deduced template arguments
1097 * Returns:
1098 * match level
1099 * bit 0-3 Match template parameters by inferred template arguments
1100 * bit 4-7 Match template parameters by initial template arguments
1101 */
1102
1103MATCH TemplateDeclaration::deduceFunctionTemplateMatch(
1104 TemplateInstance *ti, Scope *sc,
1105 FuncDeclaration *&fd, Type *tthis, Expressions *fargs)
1106{
1107 size_t nfparams;
1108 size_t nfargs;
1109 size_t ntargs; // array size of tiargs
1110 size_t fptupindex = IDX_NOTFOUND;
1111 MATCH match = MATCHexact;
1112 MATCH matchTiargs = MATCHexact;
1113 Parameters *fparameters; // function parameter list
1114 int fvarargs; // function varargs
1115 unsigned wildmatch = 0;
1116 size_t inferStart = 0;
1117
1118 Loc instLoc = ti->loc;
1119 Objects *tiargs = ti->tiargs;
1120 Objects *dedargs = new Objects();
1121 Objects* dedtypes = &ti->tdtypes; // for T:T*, the dedargs is the T*, dedtypes is the T
1122
1123 assert(_scope);
1124
1125 dedargs->setDim(parameters->dim);
1126 dedargs->zero();
1127
1128 dedtypes->setDim(parameters->dim);
1129 dedtypes->zero();
1130
1131 if (errors || fd->errors)
1132 return MATCHnomatch;
1133
1134 // Set up scope for parameters
1135 ScopeDsymbol *paramsym = new ScopeDsymbol();
1136 paramsym->parent = _scope->parent; // should use hasnestedArgs and enclosing?
1137 Scope *paramscope = _scope->push(paramsym);
1138 paramscope->tinst = ti;
1139 paramscope->minst = sc->minst;
1140 paramscope->callsc = sc;
1141 paramscope->stc = 0;
1142
1143 TemplateTupleParameter *tp = isVariadic();
1144 Tuple *declaredTuple = NULL;
1145
1146 ntargs = 0;
1147 if (tiargs)
1148 {
1149 // Set initial template arguments
1150 ntargs = tiargs->dim;
1151 size_t n = parameters->dim;
1152 if (tp)
1153 n--;
1154 if (ntargs > n)
1155 {
1156 if (!tp)
1157 goto Lnomatch;
1158
1159 /* The extra initial template arguments
1160 * now form the tuple argument.
1161 */
1162 Tuple *t = new Tuple();
1163 assert(parameters->dim);
1164 (*dedargs)[parameters->dim - 1] = t;
1165
1166 t->objects.setDim(ntargs - n);
1167 for (size_t i = 0; i < t->objects.dim; i++)
1168 {
1169 t->objects[i] = (*tiargs)[n + i];
1170 }
1171 declareParameter(paramscope, tp, t);
1172 declaredTuple = t;
1173 }
1174 else
1175 n = ntargs;
1176
1177 memcpy(dedargs->tdata(), tiargs->tdata(), n * sizeof(*dedargs->tdata()));
1178
1179 for (size_t i = 0; i < n; i++)
1180 {
1181 assert(i < parameters->dim);
1182 Declaration *sparam = NULL;
1183 MATCH m = (*parameters)[i]->matchArg(instLoc, paramscope, dedargs, i, parameters, dedtypes, &sparam);
1184 //printf("\tdeduceType m = %d\n", m);
1185 if (m <= MATCHnomatch)
1186 goto Lnomatch;
1187 if (m < matchTiargs)
1188 matchTiargs = m;
1189
1190 sparam->semantic(paramscope);
1191 if (!paramscope->insert(sparam))
1192 goto Lnomatch;
1193 }
1194 if (n < parameters->dim && !declaredTuple)
1195 {
1196 inferStart = n;
1197 }
1198 else
1199 inferStart = parameters->dim;
1200 //printf("tiargs matchTiargs = %d\n", matchTiargs);
1201 }
1202
1203 fparameters = fd->getParameters(&fvarargs);
1204 nfparams = Parameter::dim(fparameters); // number of function parameters
1205 nfargs = fargs ? fargs->dim : 0; // number of function arguments
1206
1207 /* Check for match of function arguments with variadic template
1208 * parameter, such as:
1209 *
1210 * void foo(T, A...)(T t, A a);
1211 * void main() { foo(1,2,3); }
1212 */
1213 if (tp) // if variadic
1214 {
1215 // TemplateTupleParameter always makes most lesser matching.
1216 matchTiargs = MATCHconvert;
1217
1218 if (nfparams == 0 && nfargs != 0) // if no function parameters
1219 {
1220 if (!declaredTuple)
1221 {
1222 Tuple *t = new Tuple();
1223 //printf("t = %p\n", t);
1224 (*dedargs)[parameters->dim - 1] = t;
1225 declareParameter(paramscope, tp, t);
1226 declaredTuple = t;
1227 }
1228 }
1229 else
1230 {
1231 /* Figure out which of the function parameters matches
1232 * the tuple template parameter. Do this by matching
1233 * type identifiers.
1234 * Set the index of this function parameter to fptupindex.
1235 */
1236 for (fptupindex = 0; fptupindex < nfparams; fptupindex++)
1237 {
1238 Parameter *fparam = (*fparameters)[fptupindex];
1239 if (fparam->type->ty != Tident)
1240 continue;
1241 TypeIdentifier *tid = (TypeIdentifier *)fparam->type;
1242 if (!tp->ident->equals(tid->ident) || tid->idents.dim)
1243 continue;
1244
1245 if (fvarargs) // variadic function doesn't
1246 goto Lnomatch; // go with variadic template
1247
1248 goto L1;
1249 }
1250 fptupindex = IDX_NOTFOUND;
1251 L1:
1252 ;
1253 }
1254 }
1255
1256 if (toParent()->isModule() || (_scope->stc & STCstatic))
1257 tthis = NULL;
1258 if (tthis)
1259 {
1260 bool hasttp = false;
1261
1262 // Match 'tthis' to any TemplateThisParameter's
1263 for (size_t i = 0; i < parameters->dim; i++)
1264 {
1265 TemplateThisParameter *ttp = (*parameters)[i]->isTemplateThisParameter();
1266 if (ttp)
1267 {
1268 hasttp = true;
1269
1270 Type *t = new TypeIdentifier(Loc(), ttp->ident);
1271 MATCH m = deduceType(tthis, paramscope, t, parameters, dedtypes);
1272 if (m <= MATCHnomatch)
1273 goto Lnomatch;
1274 if (m < match)
1275 match = m; // pick worst match
1276 }
1277 }
1278
1279 // Match attributes of tthis against attributes of fd
1280 if (fd->type && !fd->isCtorDeclaration())
1281 {
1282 StorageClass stc = _scope->stc | fd->storage_class2;
1283 // Propagate parent storage class (see bug 5504)
1284 Dsymbol *p = parent;
1285 while (p->isTemplateDeclaration() || p->isTemplateInstance())
1286 p = p->parent;
1287 AggregateDeclaration *ad = p->isAggregateDeclaration();
1288 if (ad)
1289 stc |= ad->storage_class;
1290
1291 unsigned char mod = fd->type->mod;
1292 if (stc & STCimmutable)
1293 mod = MODimmutable;
1294 else
1295 {
1296 if (stc & (STCshared | STCsynchronized))
1297 mod |= MODshared;
1298 if (stc & STCconst)
1299 mod |= MODconst;
1300 if (stc & STCwild)
1301 mod |= MODwild;
1302 }
1303
1304 unsigned char thismod = tthis->mod;
1305 if (hasttp)
1306 mod = MODmerge(thismod, mod);
1307 MATCH m = MODmethodConv(thismod, mod);
1308 if (m <= MATCHnomatch)
1309 goto Lnomatch;
1310 if (m < match)
1311 match = m;
1312 }
1313 }
1314
1315 // Loop through the function parameters
1316 {
1317 //printf("%s\n\tnfargs = %d, nfparams = %d, tuple_dim = %d\n", toChars(), nfargs, nfparams, declaredTuple ? declaredTuple->objects.dim : 0);
1318 //printf("\ttp = %p, fptupindex = %d, found = %d, declaredTuple = %s\n", tp, fptupindex, fptupindex != IDX_NOTFOUND, declaredTuple ? declaredTuple->toChars() : NULL);
1319 size_t argi = 0;
1320 size_t nfargs2 = nfargs; // nfargs + supplied defaultArgs
1321 for (size_t parami = 0; parami < nfparams; parami++)
1322 {
1323 Parameter *fparam = Parameter::getNth(fparameters, parami);
1324
1325 // Apply function parameter storage classes to parameter types
1326 Type *prmtype = fparam->type->addStorageClass(fparam->storageClass);
1327
1328 Expression *farg;
1329
1330 /* See function parameters which wound up
1331 * as part of a template tuple parameter.
1332 */
1333 if (fptupindex != IDX_NOTFOUND && parami == fptupindex)
1334 {
1335 assert(prmtype->ty == Tident);
1336 TypeIdentifier *tid = (TypeIdentifier *)prmtype;
1337 if (!declaredTuple)
1338 {
1339 /* The types of the function arguments
1340 * now form the tuple argument.
1341 */
1342 declaredTuple = new Tuple();
1343 (*dedargs)[parameters->dim - 1] = declaredTuple;
1344
1345 /* Count function parameters following a tuple parameter.
1346 * void foo(U, T...)(int y, T, U, int) {} // rem == 2 (U, int)
1347 */
1348 size_t rem = 0;
1349 for (size_t j = parami + 1; j < nfparams; j++)
1350 {
1351 Parameter *p = Parameter::getNth(fparameters, j);
1352 if (!reliesOnTident(p->type, parameters, inferStart))
1353 {
1354 Type *pt = p->type->syntaxCopy()->semantic(fd->loc, paramscope);
1355 rem += pt->ty == Ttuple ? ((TypeTuple *)pt)->arguments->dim : 1;
1356 }
1357 else
1358 {
1359 ++rem;
1360 }
1361 }
1362
1363 if (nfargs2 - argi < rem)
1364 goto Lnomatch;
1365 declaredTuple->objects.setDim(nfargs2 - argi - rem);
1366 for (size_t i = 0; i < declaredTuple->objects.dim; i++)
1367 {
1368 farg = (*fargs)[argi + i];
1369
1370 // Check invalid arguments to detect errors early.
1371 if (farg->op == TOKerror || farg->type->ty == Terror)
1372 goto Lnomatch;
1373
1374 if (!(fparam->storageClass & STClazy) && farg->type->ty == Tvoid)
1375 goto Lnomatch;
1376
1377 Type *tt;
1378 MATCH m;
1379 if (unsigned char wm = deduceWildHelper(farg->type, &tt, tid))
1380 {
1381 wildmatch |= wm;
1382 m = MATCHconst;
1383 }
1384 else
1385 {
1386 m = deduceTypeHelper(farg->type, &tt, tid);
1387 }
1388 if (m <= MATCHnomatch)
1389 goto Lnomatch;
1390 if (m < match)
1391 match = m;
1392
1393 /* Remove top const for dynamic array types and pointer types
1394 */
1395 if ((tt->ty == Tarray || tt->ty == Tpointer) &&
1396 !tt->isMutable() &&
1397 (!(fparam->storageClass & STCref) ||
1398 ((fparam->storageClass & STCauto) && !farg->isLvalue())))
1399 {
1400 tt = tt->mutableOf();
1401 }
1402 declaredTuple->objects[i] = tt;
1403 }
1404 declareParameter(paramscope, tp, declaredTuple);
1405 }
1406 else
1407 {
1408 // Bugzilla 6810: If declared tuple is not a type tuple,
1409 // it cannot be function parameter types.
1410 for (size_t i = 0; i < declaredTuple->objects.dim; i++)
1411 {
1412 if (!isType(declaredTuple->objects[i]))
1413 goto Lnomatch;
1414 }
1415 }
1416 assert(declaredTuple);
1417 argi += declaredTuple->objects.dim;
1418 continue;
1419 }
1420
1421 // If parameter type doesn't depend on inferred template parameters,
1422 // semantic it to get actual type.
1423 if (!reliesOnTident(prmtype, parameters, inferStart))
1424 {
1425 // should copy prmtype to avoid affecting semantic result
1426 prmtype = prmtype->syntaxCopy()->semantic(fd->loc, paramscope);
1427
1428 if (prmtype->ty == Ttuple)
1429 {
1430 TypeTuple *tt = (TypeTuple *)prmtype;
1431 size_t tt_dim = tt->arguments->dim;
1432 for (size_t j = 0; j < tt_dim; j++, ++argi)
1433 {
1434 Parameter *p = (*tt->arguments)[j];
1435 if (j == tt_dim - 1 && fvarargs == 2 && parami + 1 == nfparams && argi < nfargs)
1436 {
1437 prmtype = p->type;
1438 goto Lvarargs;
1439 }
1440 if (argi >= nfargs)
1441 {
1442 if (p->defaultArg)
1443 continue;
1444 goto Lnomatch;
1445 }
1446 farg = (*fargs)[argi];
1447 if (!farg->implicitConvTo(p->type))
1448 goto Lnomatch;
1449 }
1450 continue;
1451 }
1452 }
1453
1454 if (argi >= nfargs) // if not enough arguments
1455 {
1456 if (!fparam->defaultArg)
1457 goto Lvarargs;
1458
1459 /* Bugzilla 2803: Before the starting of type deduction from the function
1460 * default arguments, set the already deduced parameters into paramscope.
1461 * It's necessary to avoid breaking existing acceptable code. Cases:
1462 *
1463 * 1. Already deduced template parameters can appear in fparam->defaultArg:
1464 * auto foo(A, B)(A a, B b = A.stringof);
1465 * foo(1);
1466 * // at fparam == 'B b = A.string', A is equivalent with the deduced type 'int'
1467 *
1468 * 2. If prmtype depends on default-specified template parameter, the
1469 * default type should be preferred.
1470 * auto foo(N = size_t, R)(R r, N start = 0)
1471 * foo([1,2,3]);
1472 * // at fparam `N start = 0`, N should be 'size_t' before
1473 * // the deduction result from fparam->defaultArg.
1474 */
1475 if (argi == nfargs)
1476 {
1477 for (size_t i = 0; i < dedtypes->dim; i++)
1478 {
1479 Type *at = isType((*dedtypes)[i]);
1480 if (at && at->ty == Tnone)
1481 {
1482 TypeDeduced *xt = (TypeDeduced *)at;
1483 (*dedtypes)[i] = xt->tded; // 'unbox'
1484 delete xt;
1485 }
1486 }
1487 for (size_t i = ntargs; i < dedargs->dim; i++)
1488 {
1489 TemplateParameter *tparam = (*parameters)[i];
1490
1491 RootObject *oarg = (*dedargs)[i];
1492 RootObject *oded = (*dedtypes)[i];
1493 if (!oarg)
1494 {
1495 if (oded)
1496 {
1497 if (tparam->specialization() || !tparam->isTemplateTypeParameter())
1498 {
1499 /* The specialization can work as long as afterwards
1500 * the oded == oarg
1501 */
1502 (*dedargs)[i] = oded;
1503 MATCH m2 = tparam->matchArg(instLoc, paramscope, dedargs, i, parameters, dedtypes, NULL);
1504 //printf("m2 = %d\n", m2);
1505 if (m2 <= MATCHnomatch)
1506 goto Lnomatch;
1507 if (m2 < matchTiargs)
1508 matchTiargs = m2; // pick worst match
1509 if (!(*dedtypes)[i]->equals(oded))
1510 error("specialization not allowed for deduced parameter %s", tparam->ident->toChars());
1511 }
1512 else
1513 {
1514 if (MATCHconvert < matchTiargs)
1515 matchTiargs = MATCHconvert;
1516 }
1517 (*dedargs)[i] = declareParameter(paramscope, tparam, oded);
1518 }
1519 else
1520 {
1521 oded = tparam->defaultArg(instLoc, paramscope);
1522 if (oded)
1523 (*dedargs)[i] = declareParameter(paramscope, tparam, oded);
1524 }
1525 }
1526 }
1527 }
1528 nfargs2 = argi + 1;
1529
1530 /* If prmtype does not depend on any template parameters:
1531 *
1532 * auto foo(T)(T v, double x = 0);
1533 * foo("str");
1534 * // at fparam == 'double x = 0'
1535 *
1536 * or, if all template parameters in the prmtype are already deduced:
1537 *
1538 * auto foo(R)(R range, ElementType!R sum = 0);
1539 * foo([1,2,3]);
1540 * // at fparam == 'ElementType!R sum = 0'
1541 *
1542 * Deducing prmtype from fparam->defaultArg is not necessary.
1543 */
1544 if (prmtype->deco ||
1545 prmtype->syntaxCopy()->trySemantic(loc, paramscope))
1546 {
1547 ++argi;
1548 continue;
1549 }
1550
1551 // Deduce prmtype from the defaultArg.
1552 farg = fparam->defaultArg->syntaxCopy();
1553 farg = ::semantic(farg, paramscope);
1554 farg = resolveProperties(paramscope, farg);
1555 }
1556 else
1557 {
1558 farg = (*fargs)[argi];
1559 }
1560 {
1561 // Check invalid arguments to detect errors early.
1562 if (farg->op == TOKerror || farg->type->ty == Terror)
1563 goto Lnomatch;
1564
1565 Type *att = NULL;
1566 Lretry:
1567 Type *argtype = farg->type;
1568
1569 if (!(fparam->storageClass & STClazy) && argtype->ty == Tvoid && farg->op != TOKfunction)
1570 goto Lnomatch;
1571
1572 // Bugzilla 12876: optimize arugument to allow CT-known length matching
1573 farg = farg->optimize(WANTvalue, (fparam->storageClass & (STCref | STCout)) != 0);
1574 //printf("farg = %s %s\n", farg->type->toChars(), farg->toChars());
1575
1576 RootObject *oarg = farg;
1577 if ((fparam->storageClass & STCref) &&
1578 (!(fparam->storageClass & STCauto) || farg->isLvalue()))
1579 {
1580 /* Allow expressions that have CT-known boundaries and type [] to match with [dim]
1581 */
1582 Type *taai;
1583 if (argtype->ty == Tarray &&
1584 (prmtype->ty == Tsarray ||
1585 (prmtype->ty == Taarray && (taai = ((TypeAArray *)prmtype)->index)->ty == Tident &&
1586 ((TypeIdentifier *)taai)->idents.dim == 0)))
1587 {
1588 if (farg->op == TOKstring)
1589 {
1590 StringExp *se = (StringExp *)farg;
1591 argtype = se->type->nextOf()->sarrayOf(se->len);
1592 }
1593 else if (farg->op == TOKarrayliteral)
1594 {
1595 ArrayLiteralExp *ae = (ArrayLiteralExp *)farg;
1596 argtype = ae->type->nextOf()->sarrayOf(ae->elements->dim);
1597 }
1598 else if (farg->op == TOKslice)
1599 {
1600 SliceExp *se = (SliceExp *)farg;
1601 if (Type *tsa = toStaticArrayType(se))
1602 argtype = tsa;
1603 }
1604 }
1605
1606 oarg = argtype;
1607 }
1608 else if ((fparam->storageClass & STCout) == 0 &&
1609 (argtype->ty == Tarray || argtype->ty == Tpointer) &&
1610 templateParameterLookup(prmtype, parameters) != IDX_NOTFOUND &&
1611 ((TypeIdentifier *)prmtype)->idents.dim == 0)
1612 {
1613 /* The farg passing to the prmtype always make a copy. Therefore,
1614 * we can shrink the set of the deduced type arguments for prmtype
1615 * by adjusting top-qualifier of the argtype.
1616 *
1617 * prmtype argtype ta
1618 * T <- const(E)[] const(E)[]
1619 * T <- const(E[]) const(E)[]
1620 * qualifier(T) <- const(E)[] const(E[])
1621 * qualifier(T) <- const(E[]) const(E[])
1622 */
1623 Type *ta = argtype->castMod(prmtype->mod ? argtype->nextOf()->mod : 0);
1624 if (ta != argtype)
1625 {
1626 Expression *ea = farg->copy();
1627 ea->type = ta;
1628 oarg = ea;
1629 }
1630 }
1631
1632 if (fvarargs == 2 && parami + 1 == nfparams && argi + 1 < nfargs)
1633 goto Lvarargs;
1634
1635 unsigned wm = 0;
1636 MATCH m = deduceType(oarg, paramscope, prmtype, parameters, dedtypes, &wm, inferStart);
1637 //printf("\tL%d deduceType m = %d, wm = x%x, wildmatch = x%x\n", __LINE__, m, wm, wildmatch);
1638 wildmatch |= wm;
1639
1640 /* If no match, see if the argument can be matched by using
1641 * implicit conversions.
1642 */
1643 if (m == MATCHnomatch && prmtype->deco)
1644 m = farg->implicitConvTo(prmtype);
1645
1646 if (m == MATCHnomatch)
1647 {
1648 AggregateDeclaration *ad = isAggregate(farg->type);
1649 if (ad && ad->aliasthis && argtype != att)
1650 {
1651 if (!att && argtype->checkAliasThisRec()) // Bugzilla 12537
1652 att = argtype;
1653
1654 /* If a semantic error occurs while doing alias this,
1655 * eg purity(bug 7295), just regard it as not a match.
1656 */
1657 if (Expression *e = resolveAliasThis(sc, farg, true))
1658 {
1659 farg = e;
1660 goto Lretry;
1661 }
1662 }
1663 }
1664
1665 if (m > MATCHnomatch && (fparam->storageClass & (STCref | STCauto)) == STCref)
1666 {
1667 if (!farg->isLvalue())
1668 {
1669 if ((farg->op == TOKstring || farg->op == TOKslice) &&
1670 (prmtype->ty == Tsarray || prmtype->ty == Taarray))
1671 {
1672 // Allow conversion from T[lwr .. upr] to ref T[upr-lwr]
1673 }
1674 else
1675 goto Lnomatch;
1676 }
1677 }
1678 if (m > MATCHnomatch && (fparam->storageClass & STCout))
1679 {
1680 if (!farg->isLvalue())
1681 goto Lnomatch;
1682 if (!farg->type->isMutable()) // Bugzilla 11916
1683 goto Lnomatch;
1684 }
1685 if (m == MATCHnomatch && (fparam->storageClass & STClazy) && prmtype->ty == Tvoid &&
1686 farg->type->ty != Tvoid)
1687 m = MATCHconvert;
1688
1689 if (m != MATCHnomatch)
1690 {
1691 if (m < match)
1692 match = m; // pick worst match
1693 argi++;
1694 continue;
1695 }
1696 }
1697
1698 Lvarargs:
1699 /* The following code for variadic arguments closely
1700 * matches TypeFunction::callMatch()
1701 */
1702 if (!(fvarargs == 2 && parami + 1 == nfparams))
1703 goto Lnomatch;
1704
1705 /* Check for match with function parameter T...
1706 */
1707 Type *tb = prmtype->toBasetype();
1708 switch (tb->ty)
1709 {
1710 // 6764 fix - TypeAArray may be TypeSArray have not yet run semantic().
1711 case Tsarray:
1712 case Taarray:
1713 // Perhaps we can do better with this, see TypeFunction::callMatch()
1714 if (tb->ty == Tsarray)
1715 {
1716 TypeSArray *tsa = (TypeSArray *)tb;
1717 dinteger_t sz = tsa->dim->toInteger();
1718 if (sz != nfargs - argi)
1719 goto Lnomatch;
1720 }
1721 else if (tb->ty == Taarray)
1722 {
1723 TypeAArray *taa = (TypeAArray *)tb;
1724 Expression *dim = new IntegerExp(instLoc, nfargs - argi, Type::tsize_t);
1725
1726 size_t i = templateParameterLookup(taa->index, parameters);
1727 if (i == IDX_NOTFOUND)
1728 {
1729 Expression *e;
1730 Type *t;
1731 Dsymbol *s;
1732 Scope *sco;
1733
1734 unsigned errors = global.startGagging();
1735 /* ref: https://issues.dlang.org/show_bug.cgi?id=11118
1736 * The parameter isn't part of the template
1737 * ones, let's try to find it in the
1738 * instantiation scope 'sc' and the one
1739 * belonging to the template itself. */
1740 sco = sc;
1741 taa->index->resolve(instLoc, sco, &e, &t, &s);
1742 if (!e)
1743 {
1744 sco = paramscope;
1745 taa->index->resolve(instLoc, sco, &e, &t, &s);
1746 }
1747 global.endGagging(errors);
1748
1749 if (!e)
1750 {
1751 goto Lnomatch;
1752 }
1753
1754 e = e->ctfeInterpret();
1755 e = e->implicitCastTo(sco, Type::tsize_t);
1756 e = e->optimize(WANTvalue);
1757 if (!dim->equals(e))
1758 goto Lnomatch;
1759 }
1760 else
1761 {
1762 // This code matches code in TypeInstance::deduceType()
1763 TemplateParameter *tprm = (*parameters)[i];
1764 TemplateValueParameter *tvp = tprm->isTemplateValueParameter();
1765 if (!tvp)
1766 goto Lnomatch;
1767 Expression *e = (Expression *)(*dedtypes)[i];
1768 if (e)
1769 {
1770 if (!dim->equals(e))
1771 goto Lnomatch;
1772 }
1773 else
1774 {
1775 Type *vt = tvp->valType->semantic(Loc(), sc);
1776 MATCH m = (MATCH)dim->implicitConvTo(vt);
1777 if (m <= MATCHnomatch)
1778 goto Lnomatch;
1779 (*dedtypes)[i] = dim;
1780 }
1781 }
1782 }
1783 /* fall through */
1784 case Tarray:
1785 {
1786 TypeArray *ta = (TypeArray *)tb;
1787 Type *tret = fparam->isLazyArray();
1788 for (; argi < nfargs; argi++)
1789 {
1790 Expression *arg = (*fargs)[argi];
1791 assert(arg);
1792
1793 MATCH m;
1794 /* If lazy array of delegates,
1795 * convert arg(s) to delegate(s)
1796 */
1797 if (tret)
1798 {
1799 if (ta->next->equals(arg->type))
1800 {
1801 m = MATCHexact;
1802 }
1803 else
1804 {
1805 m = arg->implicitConvTo(tret);
1806 if (m == MATCHnomatch)
1807 {
1808 if (tret->toBasetype()->ty == Tvoid)
1809 m = MATCHconvert;
1810 }
1811 }
1812 }
1813 else
1814 {
1815 unsigned wm = 0;
1816 m = deduceType(arg, paramscope, ta->next, parameters, dedtypes, &wm, inferStart);
1817 wildmatch |= wm;
1818 }
1819 if (m == MATCHnomatch)
1820 goto Lnomatch;
1821 if (m < match)
1822 match = m;
1823 }
1824 goto Lmatch;
1825 }
1826 case Tclass:
1827 case Tident:
1828 goto Lmatch;
1829
1830 default:
1831 goto Lnomatch;
1832 }
1833 ++argi;
1834 }
1835 //printf("-> argi = %d, nfargs = %d, nfargs2 = %d\n", argi, nfargs, nfargs2);
1836 if (argi != nfargs2 && !fvarargs)
1837 goto Lnomatch;
1838 }
1839
1840Lmatch:
1841
1842 for (size_t i = 0; i < dedtypes->dim; i++)
1843 {
1844 Type *at = isType((*dedtypes)[i]);
1845 if (at)
1846 {
1847 if (at->ty == Tnone)
1848 {
1849 TypeDeduced *xt = (TypeDeduced *)at;
1850 at = xt->tded; // 'unbox'
1851 delete xt;
1852 }
1853 (*dedtypes)[i] = at->merge2();
1854 }
1855 }
1856 for (size_t i = ntargs; i < dedargs->dim; i++)
1857 {
1858 TemplateParameter *tparam = (*parameters)[i];
1859 //printf("tparam[%d] = %s\n", i, tparam->ident->toChars());
1860 /* For T:T*, the dedargs is the T*, dedtypes is the T
1861 * But for function templates, we really need them to match
1862 */
1863 RootObject *oarg = (*dedargs)[i];
1864 RootObject *oded = (*dedtypes)[i];
1865 //printf("1dedargs[%d] = %p, dedtypes[%d] = %p\n", i, oarg, i, oded);
1866 //if (oarg) printf("oarg: %s\n", oarg->toChars());
1867 //if (oded) printf("oded: %s\n", oded->toChars());
1868 if (!oarg)
1869 {
1870 if (oded)
1871 {
1872 if (tparam->specialization() || !tparam->isTemplateTypeParameter())
1873 {
1874 /* The specialization can work as long as afterwards
1875 * the oded == oarg
1876 */
1877 (*dedargs)[i] = oded;
1878 MATCH m2 = tparam->matchArg(instLoc, paramscope, dedargs, i, parameters, dedtypes, NULL);
1879 //printf("m2 = %d\n", m2);
1880 if (m2 <= MATCHnomatch)
1881 goto Lnomatch;
1882 if (m2 < matchTiargs)
1883 matchTiargs = m2; // pick worst match
1884 if (!(*dedtypes)[i]->equals(oded))
1885 error("specialization not allowed for deduced parameter %s", tparam->ident->toChars());
1886 }
1887 else
1888 {
1889 if (MATCHconvert < matchTiargs)
1890 matchTiargs = MATCHconvert;
1891 }
1892 }
1893 else
1894 {
1895 oded = tparam->defaultArg(instLoc, paramscope);
1896 if (!oded)
1897 {
1898 // if tuple parameter and
1899 // tuple parameter was not in function parameter list and
1900 // we're one or more arguments short (i.e. no tuple argument)
1901 if (tparam == tp &&
1902 fptupindex == IDX_NOTFOUND &&
1903 ntargs <= dedargs->dim - 1)
1904 {
1905 // make tuple argument an empty tuple
1906 oded = (RootObject *)new Tuple();
1907 }
1908 else
1909 goto Lnomatch;
1910 }
1911 if (isError(oded))
1912 goto Lerror;
1913 ntargs++;
1914
1915 /* At the template parameter T, the picked default template argument
1916 * X!int should be matched to T in order to deduce dependent
1917 * template parameter A.
1918 * auto foo(T : X!A = X!int, A...)() { ... }
1919 * foo(); // T <-- X!int, A <-- (int)
1920 */
1921 if (tparam->specialization())
1922 {
1923 (*dedargs)[i] = oded;
1924 MATCH m2 = tparam->matchArg(instLoc, paramscope, dedargs, i, parameters, dedtypes, NULL);
1925 //printf("m2 = %d\n", m2);
1926 if (m2 <= MATCHnomatch)
1927 goto Lnomatch;
1928 if (m2 < matchTiargs)
1929 matchTiargs = m2; // pick worst match
1930 if (!(*dedtypes)[i]->equals(oded))
1931 error("specialization not allowed for deduced parameter %s", tparam->ident->toChars());
1932 }
1933 }
1934 oded = declareParameter(paramscope, tparam, oded);
1935 (*dedargs)[i] = oded;
1936 }
1937 }
1938
1939 /* Bugzilla 7469: As same as the code for 7469 in findBestMatch,
1940 * expand a Tuple in dedargs to normalize template arguments.
1941 */
1942 if (size_t d = dedargs->dim)
1943 {
1944 if (Tuple *va = isTuple((*dedargs)[d - 1]))
1945 {
1946 if (va->objects.dim)
1947 {
1948 dedargs->setDim(d - 1);
1949 dedargs->insert(d - 1, &va->objects);
1950 }
1951 }
1952 }
1953 ti->tiargs = dedargs; // update to the normalized template arguments.
1954
1955 // Partially instantiate function for constraint and fd->leastAsSpecialized()
1956 {
1957 assert(paramsym);
1958 Scope *sc2 = _scope;
1959 sc2 = sc2->push(paramsym);
1960 sc2 = sc2->push(ti);
1961 sc2->parent = ti;
1962 sc2->tinst = ti;
1963 sc2->minst = sc->minst;
1964
1965 fd = doHeaderInstantiation(ti, sc2, fd, tthis, fargs);
1966
1967 sc2 = sc2->pop();
1968 sc2 = sc2->pop();
1969
1970 if (!fd)
1971 goto Lnomatch;
1972 }
1973
1974 if (constraint)
1975 {
1976 if (!evaluateConstraint(ti, sc, paramscope, dedargs, fd))
1977 goto Lnomatch;
1978 }
1979
1980 paramscope->pop();
1981 //printf("\tmatch %d\n", match);
1982 return (MATCH)(match | (matchTiargs<<4));
1983
1984Lnomatch:
1985 paramscope->pop();
1986 //printf("\tnomatch\n");
1987 return MATCHnomatch;
1988
1989Lerror: // todo: for the future improvement
1990 paramscope->pop();
1991 //printf("\terror\n");
1992 return MATCHnomatch;
1993}
1994
1995/**************************************************
1996 * Declare template parameter tp with value o, and install it in the scope sc.
1997 */
1998
1999RootObject *TemplateDeclaration::declareParameter(Scope *sc, TemplateParameter *tp, RootObject *o)
2000{
2001 //printf("TemplateDeclaration::declareParameter('%s', o = %p)\n", tp->ident->toChars(), o);
2002
2003 Type *ta = isType(o);
2004 Expression *ea = isExpression(o);
2005 Dsymbol *sa = isDsymbol(o);
2006 Tuple *va = isTuple(o);
2007
2008 Declaration *d;
2009 VarDeclaration *v = NULL;
2010
2011 if (ea && ea->op == TOKtype)
2012 ta = ea->type;
2013 else if (ea && ea->op == TOKscope)
2014 sa = ((ScopeExp *)ea)->sds;
2015 else if (ea && (ea->op == TOKthis || ea->op == TOKsuper))
2016 sa = ((ThisExp *)ea)->var;
2017 else if (ea && ea->op == TOKfunction)
2018 {
2019 if (((FuncExp *)ea)->td)
2020 sa = ((FuncExp *)ea)->td;
2021 else
2022 sa = ((FuncExp *)ea)->fd;
2023 }
2024
2025 if (ta)
2026 {
2027 //printf("type %s\n", ta->toChars());
2028 d = new AliasDeclaration(Loc(), tp->ident, ta);
2029 }
2030 else if (sa)
2031 {
2032 //printf("Alias %s %s;\n", sa->ident->toChars(), tp->ident->toChars());
2033 d = new AliasDeclaration(Loc(), tp->ident, sa);
2034 }
2035 else if (ea)
2036 {
2037 // tdtypes.data[i] always matches ea here
2038 Initializer *init = new ExpInitializer(loc, ea);
2039 TemplateValueParameter *tvp = tp->isTemplateValueParameter();
2040
2041 Type *t = tvp ? tvp->valType : NULL;
2042
2043 v = new VarDeclaration(loc, t, tp->ident, init);
2044 v->storage_class = STCmanifest | STCtemplateparameter;
2045 d = v;
2046 }
2047 else if (va)
2048 {
2049 //printf("\ttuple\n");
2050 d = new TupleDeclaration(loc, tp->ident, &va->objects);
2051 }
2052 else
2053 {
2054 assert(0);
2055 }
2056
2057 d->storage_class |= STCtemplateparameter;
2058 if (ta)
2059 {
2060 Type *t = ta;
2061 // consistent with Type::checkDeprecated()
2062 while (t->ty != Tenum)
2063 {
2064 if (!t->nextOf()) break;
2065 t = ((TypeNext *)t)->next;
2066 }
2067 if (Dsymbol *s = t->toDsymbol(sc))
2068 {
2069 if (s->isDeprecated())
2070 d->storage_class |= STCdeprecated;
2071 }
2072 }
2073 else if (sa)
2074 {
2075 if (sa->isDeprecated())
2076 d->storage_class |= STCdeprecated;
2077 }
2078
2079 if (!sc->insert(d))
2080 error("declaration %s is already defined", tp->ident->toChars());
2081 d->semantic(sc);
2082
2083 /* So the caller's o gets updated with the result of semantic() being run on o
2084 */
2085 if (v)
2086 o = initializerToExpression(v->_init);
2087 return o;
2088}
2089
2090/**************************************
2091 * Determine if TemplateDeclaration is variadic.
2092 */
2093
2094TemplateTupleParameter *isVariadic(TemplateParameters *parameters)
2095{
2096 size_t dim = parameters->dim;
2097 TemplateTupleParameter *tp = NULL;
2098
2099 if (dim)
2100 tp = ((*parameters)[dim - 1])->isTemplateTupleParameter();
2101 return tp;
2102}
2103
2104TemplateTupleParameter *TemplateDeclaration::isVariadic()
2105{
2106 return ::isVariadic(parameters);
2107}
2108
2109/***********************************
2110 * We can overload templates.
2111 */
2112
2113bool TemplateDeclaration::isOverloadable()
2114{
2115 return true;
2116}
2117
2118/*************************************************
2119 * Given function arguments, figure out which template function
2120 * to expand, and return matching result.
2121 * Input:
2122 * m matching result
2123 * dstart the root of overloaded function templates
2124 * loc instantiation location
2125 * sc instantiation scope
2126 * tiargs initial list of template arguments
2127 * tthis if !NULL, the 'this' pointer argument
2128 * fargs arguments to function
2129 */
2130
2131void functionResolve(Match *m, Dsymbol *dstart, Loc loc, Scope *sc,
2132 Objects *tiargs, Type *tthis, Expressions *fargs)
2133{
2134 struct ParamDeduce
2135 {
2136 // context
2137 Loc loc;
2138 Scope *sc;
2139 Type *tthis;
2140 Objects *tiargs;
2141 Expressions *fargs;
2142 // result
2143 Match *m;
2144 int property; // 0: unintialized
2145 // 1: seen @property
2146 // 2: not @property
2147 size_t ov_index;
2148 TemplateDeclaration *td_best;
2149 TemplateInstance *ti_best;
2150 MATCH ta_last;
2151 Type *tthis_best;
2152
2153 static int fp(void *param, Dsymbol *s)
2154 {
2155 if (s->errors)
2156 return 0;
2157 if (FuncDeclaration *fd = s->isFuncDeclaration())
2158 return ((ParamDeduce *)param)->applyFunction(fd);
2159 if (TemplateDeclaration *td = s->isTemplateDeclaration())
2160 return ((ParamDeduce *)param)->applyTemplate(td);
2161 return 0;
2162 }
2163
2164 int applyFunction(FuncDeclaration *fd)
2165 {
2166 // skip duplicates
2167 if (fd == m->lastf)
2168 return 0;
2169 // explicitly specified tiargs never match to non template function
2170 if (tiargs && tiargs->dim > 0)
2171 return 0;
2172
956fba45
IB
2173 // constructors need a valid scope in order to detect semantic errors
2174 if (!fd->isCtorDeclaration() &&
2175 fd->semanticRun < PASSsemanticdone)
b4c522fa
IB
2176 {
2177 Ungag ungag = fd->ungagSpeculative();
956fba45 2178 fd->semantic(NULL);
b4c522fa 2179 }
956fba45 2180 if (fd->semanticRun < PASSsemanticdone)
b4c522fa
IB
2181 {
2182 ::error(loc, "forward reference to template %s", fd->toChars());
2183 return 1;
2184 }
2185 //printf("fd = %s %s, fargs = %s\n", fd->toChars(), fd->type->toChars(), fargs->toChars());
2186 m->anyf = fd;
2187 TypeFunction *tf = (TypeFunction *)fd->type;
2188
2189 int prop = (tf->isproperty) ? 1 : 2;
2190 if (property == 0)
2191 property = prop;
2192 else if (property != prop)
2193 error(fd->loc, "cannot overload both property and non-property functions");
2194
2195 /* For constructors, qualifier check will be opposite direction.
2196 * Qualified constructor always makes qualified object, then will be checked
2197 * that it is implicitly convertible to tthis.
2198 */
2199 Type *tthis_fd = fd->needThis() ? tthis : NULL;
2200 bool isCtorCall = tthis_fd && fd->isCtorDeclaration();
2201 if (isCtorCall)
2202 {
2203 //printf("%s tf->mod = x%x tthis_fd->mod = x%x %d\n", tf->toChars(),
2204 // tf->mod, tthis_fd->mod, fd->isolateReturn());
2205 if (MODimplicitConv(tf->mod, tthis_fd->mod) ||
2206 (tf->isWild() && tf->isShared() == tthis_fd->isShared()) ||
2207 fd->isolateReturn())
2208 {
2209 /* && tf->isShared() == tthis_fd->isShared()*/
2210 // Uniquely constructed object can ignore shared qualifier.
2211 // TODO: Is this appropriate?
2212 tthis_fd = NULL;
2213 }
2214 else
2215 return 0; // MATCHnomatch
2216 }
2217 MATCH mfa = tf->callMatch(tthis_fd, fargs);
2218 //printf("test1: mfa = %d\n", mfa);
2219 if (mfa > MATCHnomatch)
2220 {
2221 if (mfa > m->last) goto LfIsBetter;
2222 if (mfa < m->last) goto LlastIsBetter;
2223
2224 /* See if one of the matches overrides the other.
2225 */
2226 assert(m->lastf);
2227 if (m->lastf->overrides(fd)) goto LlastIsBetter;
2228 if (fd->overrides(m->lastf)) goto LfIsBetter;
2229
2230 /* Try to disambiguate using template-style partial ordering rules.
2231 * In essence, if f() and g() are ambiguous, if f() can call g(),
2232 * but g() cannot call f(), then pick f().
2233 * This is because f() is "more specialized."
2234 */
2235 {
2236 MATCH c1 = fd->leastAsSpecialized(m->lastf);
2237 MATCH c2 = m->lastf->leastAsSpecialized(fd);
2238 //printf("c1 = %d, c2 = %d\n", c1, c2);
2239 if (c1 > c2) goto LfIsBetter;
2240 if (c1 < c2) goto LlastIsBetter;
2241 }
2242
2243 /* The 'overrides' check above does covariant checking only
2244 * for virtual member functions. It should do it for all functions,
2245 * but in order to not risk breaking code we put it after
2246 * the 'leastAsSpecialized' check.
2247 * In the future try moving it before.
2248 * I.e. a not-the-same-but-covariant match is preferred,
2249 * as it is more restrictive.
2250 */
2251 if (!m->lastf->type->equals(fd->type))
2252 {
2253 //printf("cov: %d %d\n", m->lastf->type->covariant(fd->type), fd->type->covariant(m->lastf->type));
2254 if (m->lastf->type->covariant(fd->type) == 1) goto LlastIsBetter;
2255 if (fd->type->covariant(m->lastf->type) == 1) goto LfIsBetter;
2256 }
2257
2258 /* If the two functions are the same function, like:
2259 * int foo(int);
2260 * int foo(int x) { ... }
2261 * then pick the one with the body.
2262 */
2263 if (tf->equals(m->lastf->type) &&
2264 fd->storage_class == m->lastf->storage_class &&
2265 fd->parent == m->lastf->parent &&
2266 fd->protection == m->lastf->protection &&
2267 fd->linkage == m->lastf->linkage)
2268 {
2269 if ( fd->fbody && !m->lastf->fbody) goto LfIsBetter;
2270 if (!fd->fbody && m->lastf->fbody) goto LlastIsBetter;
2271 }
2272
2273 // Bugzilla 14450: Prefer exact qualified constructor for the creating object type
2274 if (isCtorCall && tf->mod != m->lastf->type->mod)
2275 {
2276 if (tthis->mod == tf->mod) goto LfIsBetter;
2277 if (tthis->mod == m->lastf->type->mod) goto LlastIsBetter;
2278 }
2279
2280 m->nextf = fd;
2281 m->count++;
2282 return 0;
2283
2284 LlastIsBetter:
2285 return 0;
2286
2287 LfIsBetter:
2288 td_best = NULL;
2289 ti_best = NULL;
2290 ta_last = MATCHexact;
2291 m->last = mfa;
2292 m->lastf = fd;
2293 tthis_best = tthis_fd;
2294 ov_index = 0;
2295 m->count = 1;
2296 return 0;
2297 }
2298 return 0;
2299 }
2300
2301 int applyTemplate(TemplateDeclaration *td)
2302 {
2303 //printf("applyTemplate()\n");
2304 // skip duplicates
2305 if (td == td_best)
2306 return 0;
2307
2308 if (!sc)
2309 sc = td->_scope; // workaround for Type::aliasthisOf
2310
2311 if (td->semanticRun == PASSinit && td->_scope)
2312 {
2313 // Try to fix forward reference. Ungag errors while doing so.
2314 Ungag ungag = td->ungagSpeculative();
2315 td->semantic(td->_scope);
2316 }
2317 if (td->semanticRun == PASSinit)
2318 {
2319 ::error(loc, "forward reference to template %s", td->toChars());
2320 Lerror:
2321 m->lastf = NULL;
2322 m->count = 0;
2323 m->last = MATCHnomatch;
2324 return 1;
2325 }
2326 //printf("td = %s\n", td->toChars());
2327
2328 FuncDeclaration *f;
2329 f = td->onemember ? td->onemember->isFuncDeclaration() : NULL;
2330 if (!f)
2331 {
2332 if (!tiargs)
2333 tiargs = new Objects();
2334 TemplateInstance *ti = new TemplateInstance(loc, td, tiargs);
2335 Objects dedtypes;
2336 dedtypes.setDim(td->parameters->dim);
2337 assert(td->semanticRun != PASSinit);
2338 MATCH mta = td->matchWithInstance(sc, ti, &dedtypes, fargs, 0);
2339 //printf("matchWithInstance = %d\n", mta);
2340 if (mta <= MATCHnomatch || mta < ta_last) // no match or less match
2341 return 0;
2342
2343 ti->semantic(sc, fargs);
2344 if (!ti->inst) // if template failed to expand
2345 return 0;
2346
2347 Dsymbol *s = ti->inst->toAlias();
2348 FuncDeclaration *fd;
2349 if (TemplateDeclaration *tdx = s->isTemplateDeclaration())
2350 {
2351 Objects dedtypesX; // empty tiargs
2352
2353 // Bugzilla 11553: Check for recursive instantiation of tdx.
2354 for (TemplatePrevious *p = tdx->previous; p; p = p->prev)
2355 {
2356 if (arrayObjectMatch(p->dedargs, &dedtypesX))
2357 {
2358 //printf("recursive, no match p->sc=%p %p %s\n", p->sc, this, this->toChars());
2359 /* It must be a subscope of p->sc, other scope chains are not recursive
2360 * instantiations.
2361 */
2362 for (Scope *scx = sc; scx; scx = scx->enclosing)
2363 {
2364 if (scx == p->sc)
2365 {
2366 error(loc, "recursive template expansion while looking for %s.%s", ti->toChars(), tdx->toChars());
2367 goto Lerror;
2368 }
2369 }
2370 }
2371 /* BUG: should also check for ref param differences
2372 */
2373 }
2374
2375 TemplatePrevious pr;
2376 pr.prev = tdx->previous;
2377 pr.sc = sc;
2378 pr.dedargs = &dedtypesX;
2379 tdx->previous = &pr; // add this to threaded list
2380
2381 fd = resolveFuncCall(loc, sc, s, NULL, tthis, fargs, 1);
2382
2383 tdx->previous = pr.prev; // unlink from threaded list
2384 }
2385 else if (s->isFuncDeclaration())
2386 {
2387 fd = resolveFuncCall(loc, sc, s, NULL, tthis, fargs, 1);
2388 }
2389 else
2390 goto Lerror;
2391
2392 if (!fd)
2393 return 0;
2394
2395 if (fd->type->ty != Tfunction)
2396 {
2397 m->lastf = fd; // to propagate "error match"
2398 m->count = 1;
2399 m->last = MATCHnomatch;
2400 return 1;
2401 }
2402
2403 Type *tthis_fd = fd->needThis() && !fd->isCtorDeclaration() ? tthis : NULL;
2404
2405 TypeFunction *tf = (TypeFunction *)fd->type;
2406 MATCH mfa = tf->callMatch(tthis_fd, fargs);
2407 if (mfa < m->last)
2408 return 0;
2409
2410 if (mta < ta_last) goto Ltd_best2;
2411 if (mta > ta_last) goto Ltd2;
2412
2413 if (mfa < m->last) goto Ltd_best2;
2414 if (mfa > m->last) goto Ltd2;
2415
2416 //printf("Lambig2\n");
2417 m->nextf = fd;
2418 m->count++;
2419 return 0;
2420
2421 Ltd_best2:
2422 return 0;
2423
2424 Ltd2:
2425 // td is the new best match
2426 assert(td->_scope);
2427 td_best = td;
2428 ti_best = NULL;
2429 property = 0; // (backward compatibility)
2430 ta_last = mta;
2431 m->last = mfa;
2432 m->lastf = fd;
2433 tthis_best = tthis_fd;
2434 ov_index = 0;
2435 m->nextf = NULL;
2436 m->count = 1;
2437 return 0;
2438 }
2439
2440 //printf("td = %s\n", td->toChars());
2441 for (size_t ovi = 0; f; f = f->overnext0, ovi++)
2442 {
2443 if (f->type->ty != Tfunction || f->errors)
2444 goto Lerror;
2445
2446 /* This is a 'dummy' instance to evaluate constraint properly.
2447 */
2448 TemplateInstance *ti = new TemplateInstance(loc, td, tiargs);
2449 ti->parent = td->parent; // Maybe calculating valid 'enclosing' is unnecessary.
2450
2451 FuncDeclaration *fd = f;
2452 int x = td->deduceFunctionTemplateMatch(ti, sc, fd, tthis, fargs);
2453 MATCH mta = (MATCH)(x >> 4);
2454 MATCH mfa = (MATCH)(x & 0xF);
2455 //printf("match:t/f = %d/%d\n", mta, mfa);
2456 if (!fd || mfa == MATCHnomatch)
2457 continue;
2458
2459 Type *tthis_fd = fd->needThis() ? tthis : NULL;
2460
2461 bool isCtorCall = tthis_fd && fd->isCtorDeclaration();
2462 if (isCtorCall)
2463 {
2464 // Constructor call requires additional check.
2465
2466 TypeFunction *tf = (TypeFunction *)fd->type;
2467 assert(tf->next);
2468 if (MODimplicitConv(tf->mod, tthis_fd->mod) ||
2469 (tf->isWild() && tf->isShared() == tthis_fd->isShared()) ||
2470 fd->isolateReturn())
2471 {
2472 tthis_fd = NULL;
2473 }
2474 else
2475 continue; // MATCHnomatch
2476 }
2477
2478 if (mta < ta_last) goto Ltd_best;
2479 if (mta > ta_last) goto Ltd;
2480
2481 if (mfa < m->last) goto Ltd_best;
2482 if (mfa > m->last) goto Ltd;
2483
2484 if (td_best)
2485 {
2486 // Disambiguate by picking the most specialized TemplateDeclaration
2487 MATCH c1 = td->leastAsSpecialized(sc, td_best, fargs);
2488 MATCH c2 = td_best->leastAsSpecialized(sc, td, fargs);
2489 //printf("1: c1 = %d, c2 = %d\n", c1, c2);
2490 if (c1 > c2) goto Ltd;
2491 if (c1 < c2) goto Ltd_best;
2492 }
2493 assert(fd && m->lastf);
2494 {
2495 // Disambiguate by tf->callMatch
2496 TypeFunction *tf1 = (TypeFunction *)fd->type;
2497 assert(tf1->ty == Tfunction);
2498 TypeFunction *tf2 = (TypeFunction *)m->lastf->type;
2499 assert(tf2->ty == Tfunction);
2500 MATCH c1 = tf1->callMatch(tthis_fd, fargs);
2501 MATCH c2 = tf2->callMatch(tthis_best, fargs);
2502 //printf("2: c1 = %d, c2 = %d\n", c1, c2);
2503 if (c1 > c2) goto Ltd;
2504 if (c1 < c2) goto Ltd_best;
2505 }
2506 {
2507 // Disambiguate by picking the most specialized FunctionDeclaration
2508 MATCH c1 = fd->leastAsSpecialized(m->lastf);
2509 MATCH c2 = m->lastf->leastAsSpecialized(fd);
2510 //printf("3: c1 = %d, c2 = %d\n", c1, c2);
2511 if (c1 > c2) goto Ltd;
2512 if (c1 < c2) goto Ltd_best;
2513 }
2514
2515 // Bugzilla 14450: Prefer exact qualified constructor for the creating object type
2516 if (isCtorCall && fd->type->mod != m->lastf->type->mod)
2517 {
2518 if (tthis->mod == fd->type->mod) goto Ltd;
2519 if (tthis->mod == m->lastf->type->mod) goto Ltd_best;
2520 }
2521
2522 m->nextf = fd;
2523 m->count++;
2524 continue;
2525
2526 Ltd_best: // td_best is the best match so far
2527 //printf("Ltd_best\n");
2528 continue;
2529
2530 Ltd: // td is the new best match
2531 //printf("Ltd\n");
2532 assert(td->_scope);
2533 td_best = td;
2534 ti_best = ti;
2535 property = 0; // (backward compatibility)
2536 ta_last = mta;
2537 m->last = mfa;
2538 m->lastf = fd;
2539 tthis_best = tthis_fd;
2540 ov_index = ovi;
2541 m->nextf = NULL;
2542 m->count = 1;
2543 continue;
2544 }
2545 return 0;
2546 }
2547 };
2548 ParamDeduce p;
2549 // context
2550 p.loc = loc;
2551 p.sc = sc;
2552 p.tthis = tthis;
2553 p.tiargs = tiargs;
2554 p.fargs = fargs;
2555
2556 // result
2557 p.m = m;
2558 p.property = 0;
2559 p.ov_index = 0;
2560 p.td_best = NULL;
2561 p.ti_best = NULL;
2562 p.ta_last = m->last != MATCHnomatch ? MATCHexact : MATCHnomatch;
2563 p.tthis_best = NULL;
2564
2565 TemplateDeclaration *td = dstart->isTemplateDeclaration();
2566 if (td && td->funcroot)
2567 dstart = td->funcroot;
2568
2569 overloadApply(dstart, &p, &ParamDeduce::fp);
2570
2571 //printf("td_best = %p, m->lastf = %p\n", p.td_best, m->lastf);
2572 if (p.td_best && p.ti_best && m->count == 1)
2573 {
2574 // Matches to template function
2575 assert(p.td_best->onemember && p.td_best->onemember->isFuncDeclaration());
2576
2577 /* The best match is td_best with arguments tdargs.
2578 * Now instantiate the template.
2579 */
2580 assert(p.td_best->_scope);
2581 if (!sc)
2582 sc = p.td_best->_scope; // workaround for Type::aliasthisOf
2583
2584 TemplateInstance *ti = new TemplateInstance(loc, p.td_best, p.ti_best->tiargs);
2585 ti->semantic(sc, fargs);
2586
2587 m->lastf = ti->toAlias()->isFuncDeclaration();
2588 if (!m->lastf)
2589 goto Lnomatch;
2590 if (ti->errors)
2591 {
2592 Lerror:
2593 m->count = 1;
2594 assert(m->lastf);
2595 m->last = MATCHnomatch;
2596 return;
2597 }
2598
2599 // look forward instantiated overload function
2600 // Dsymbol::oneMembers is alredy called in TemplateInstance::semantic.
2601 // it has filled overnext0d
2602 while (p.ov_index--)
2603 {
2604 m->lastf = m->lastf->overnext0;
2605 assert(m->lastf);
2606 }
2607
2608 p.tthis_best = m->lastf->needThis() && !m->lastf->isCtorDeclaration() ? tthis : NULL;
2609
2610 TypeFunction *tf = (TypeFunction *)m->lastf->type;
2611 if (tf->ty == Terror)
2612 goto Lerror;
2613 assert(tf->ty == Tfunction);
2614 if (!tf->callMatch(p.tthis_best, fargs))
2615 goto Lnomatch;
2616
2617 /* As Bugzilla 3682 shows, a template instance can be matched while instantiating
2618 * that same template. Thus, the function type can be incomplete. Complete it.
2619 *
2620 * Bugzilla 9208: For auto function, completion should be deferred to the end of
2621 * its semantic3. Should not complete it in here.
2622 */
2623 if (tf->next && !m->lastf->inferRetType)
2624 {
2625 m->lastf->type = tf->semantic(loc, sc);
2626 }
2627 }
2628 else if (m->lastf)
2629 {
2630 // Matches to non template function,
2631 // or found matches were ambiguous.
2632 assert(m->count >= 1);
2633 }
2634 else
2635 {
2636 Lnomatch:
2637 m->count = 0;
2638 m->lastf = NULL;
2639 m->last = MATCHnomatch;
2640 }
2641}
2642
2643/*************************************************
2644 * Limited function template instantiation for using fd->leastAsSpecialized()
2645 */
2646FuncDeclaration *TemplateDeclaration::doHeaderInstantiation(
2647 TemplateInstance *ti, Scope *sc2,
2648 FuncDeclaration *fd, Type *tthis, Expressions *fargs)
2649{
2650 assert(fd);
2651
2652 // function body and contracts are not need
2653 if (fd->isCtorDeclaration())
2654 fd = new CtorDeclaration(fd->loc, fd->endloc, fd->storage_class, fd->type->syntaxCopy());
2655 else
2656 fd = new FuncDeclaration(fd->loc, fd->endloc, fd->ident, fd->storage_class, fd->type->syntaxCopy());
2657 fd->parent = ti;
2658
2659 assert(fd->type->ty == Tfunction);
2660 TypeFunction *tf = (TypeFunction *)fd->type;
2661 tf->fargs = fargs;
2662
2663 if (tthis)
2664 {
2665 // Match 'tthis' to any TemplateThisParameter's
2666 bool hasttp = false;
2667 for (size_t i = 0; i < parameters->dim; i++)
2668 {
2669 TemplateParameter *tp = (*parameters)[i];
2670 TemplateThisParameter *ttp = tp->isTemplateThisParameter();
2671 if (ttp)
2672 hasttp = true;
2673 }
2674 if (hasttp)
2675 {
2676 tf = (TypeFunction *)tf->addSTC(ModToStc(tthis->mod));
2677 assert(!tf->deco);
2678 }
2679 }
2680
2681 Scope *scx = sc2->push();
2682
2683 // Shouldn't run semantic on default arguments and return type.
2684 for (size_t i = 0; i < tf->parameters->dim; i++)
2685 (*tf->parameters)[i]->defaultArg = NULL;
2686 if (fd->isCtorDeclaration())
2687 {
2688 // For constructors, emitting return type is necessary for
2689 // isolateReturn() in functionResolve.
2690 scx->flags |= SCOPEctor;
2691
2692 Dsymbol *parent = toParent2();
2693 Type *tret;
2694 AggregateDeclaration *ad = parent->isAggregateDeclaration();
2695 if (!ad || parent->isUnionDeclaration())
2696 {
2697 tret = Type::tvoid;
2698 }
2699 else
2700 {
2701 tret = ad->handleType();
2702 assert(tret);
2703 tret = tret->addStorageClass(fd->storage_class | scx->stc);
2704 tret = tret->addMod(tf->mod);
2705 }
2706 tf->next = tret;
2707 if (ad && ad->isStructDeclaration())
2708 tf->isref = 1;
2709 //printf("tf = %s\n", tf->toChars());
2710 }
2711 else
2712 tf->next = NULL;
2713 fd->type = tf;
2714 fd->type = fd->type->addSTC(scx->stc);
2715 fd->type = fd->type->semantic(fd->loc, scx);
2716 scx = scx->pop();
2717
2718 if (fd->type->ty != Tfunction)
2719 return NULL;
2720
2721 fd->originalType = fd->type; // for mangling
2722 //printf("\t[%s] fd->type = %s, mod = %x, ", loc.toChars(), fd->type->toChars(), fd->type->mod);
2723 //printf("fd->needThis() = %d\n", fd->needThis());
2724
2725 return fd;
2726}
2727
2728bool TemplateDeclaration::hasStaticCtorOrDtor()
2729{
2730 return false; // don't scan uninstantiated templates
2731}
2732
2733const char *TemplateDeclaration::toChars()
2734{
2735 if (literal)
2736 return Dsymbol::toChars();
2737
2738 OutBuffer buf;
2739 HdrGenState hgs;
2740
2741 buf.writestring(ident->toChars());
2742 buf.writeByte('(');
2743 for (size_t i = 0; i < parameters->dim; i++)
2744 {
2745 TemplateParameter *tp = (*parameters)[i];
2746 if (i)
2747 buf.writestring(", ");
2748 ::toCBuffer(tp, &buf, &hgs);
2749 }
2750 buf.writeByte(')');
2751
2752 if (onemember)
2753 {
2754 FuncDeclaration *fd = onemember->isFuncDeclaration();
2755 if (fd && fd->type)
2756 {
2757 TypeFunction *tf = (TypeFunction *)fd->type;
2758 buf.writestring(parametersTypeToChars(tf->parameters, tf->varargs));
2759 }
2760 }
2761
2762 if (constraint)
2763 {
2764 buf.writestring(" if (");
2765 ::toCBuffer(constraint, &buf, &hgs);
2766 buf.writeByte(')');
2767 }
2768 return buf.extractString();
2769}
2770
2771Prot TemplateDeclaration::prot()
2772{
2773 return protection;
2774}
2775
2776/****************************************************
2777 * Given a new instance tithis of this TemplateDeclaration,
2778 * see if there already exists an instance.
2779 * If so, return that existing instance.
2780 */
2781
2782TemplateInstance *TemplateDeclaration::findExistingInstance(TemplateInstance *tithis, Expressions *fargs)
2783{
2784 //printf("findExistingInstance(%p)\n", tithis);
2785 tithis->fargs = fargs;
2786 TemplateInstances *tinstances = (TemplateInstances *)dmd_aaGetRvalue((AA *)instances, (void *)tithis->toHash());
2787 if (tinstances)
2788 {
2789 for (size_t i = 0; i < tinstances->dim; i++)
2790 {
2791 TemplateInstance *ti = (*tinstances)[i];
2792 if (tithis->compare(ti) == 0)
2793 return ti;
2794 }
2795 }
2796 return NULL;
2797}
2798
2799/********************************************
2800 * Add instance ti to TemplateDeclaration's table of instances.
2801 * Return a handle we can use to later remove it if it fails instantiation.
2802 */
2803
2804TemplateInstance *TemplateDeclaration::addInstance(TemplateInstance *ti)
2805{
2806 //printf("addInstance() %p %p\n", instances, ti);
2807 TemplateInstances **ptinstances = (TemplateInstances **)dmd_aaGet((AA **)&instances, (void *)ti->toHash());
2808 if (!*ptinstances)
2809 *ptinstances = new TemplateInstances();
2810 (*ptinstances)->push(ti);
2811 return ti;
2812}
2813
2814/*******************************************
2815 * Remove TemplateInstance from table of instances.
2816 * Input:
2817 * handle returned by addInstance()
2818 */
2819
2820void TemplateDeclaration::removeInstance(TemplateInstance *handle)
2821{
2822 //printf("removeInstance()\n");
2823 TemplateInstances *tinstances = (TemplateInstances *)dmd_aaGetRvalue((AA *)instances, (void *)handle->toHash());
2824 if (tinstances)
2825 {
2826 for (size_t i = 0; i < tinstances->dim; i++)
2827 {
2828 TemplateInstance *ti = (*tinstances)[i];
2829 if (handle == ti)
2830 {
2831 tinstances->remove(i);
2832 break;
2833 }
2834 }
2835 }
2836}
2837
2838/* ======================== Type ============================================ */
2839
2840/****
2841 * Given an identifier, figure out which TemplateParameter it is.
2842 * Return IDX_NOTFOUND if not found.
2843 */
2844
2845static size_t templateIdentifierLookup(Identifier *id, TemplateParameters *parameters)
2846{
2847 for (size_t i = 0; i < parameters->dim; i++)
2848 {
2849 TemplateParameter *tp = (*parameters)[i];
2850 if (tp->ident->equals(id))
2851 return i;
2852 }
2853 return IDX_NOTFOUND;
2854}
2855
2856size_t templateParameterLookup(Type *tparam, TemplateParameters *parameters)
2857{
2858 if (tparam->ty == Tident)
2859 {
2860 TypeIdentifier *tident = (TypeIdentifier *)tparam;
2861 //printf("\ttident = '%s'\n", tident->toChars());
2862 return templateIdentifierLookup(tident->ident, parameters);
2863 }
2864 return IDX_NOTFOUND;
2865}
2866
2867unsigned char deduceWildHelper(Type *t, Type **at, Type *tparam)
2868{
2869 if ((tparam->mod & MODwild) == 0)
2870 return 0;
2871
2872 *at = NULL;
2873
2874 #define X(U,T) ((U) << 4) | (T)
2875 switch (X(tparam->mod, t->mod))
2876 {
2877 case X(MODwild, 0):
2878 case X(MODwild, MODconst):
2879 case X(MODwild, MODshared):
2880 case X(MODwild, MODshared | MODconst):
2881 case X(MODwild, MODimmutable):
2882 case X(MODwildconst, 0):
2883 case X(MODwildconst, MODconst):
2884 case X(MODwildconst, MODshared):
2885 case X(MODwildconst, MODshared | MODconst):
2886 case X(MODwildconst, MODimmutable):
2887 case X(MODshared | MODwild, MODshared):
2888 case X(MODshared | MODwild, MODshared | MODconst):
2889 case X(MODshared | MODwild, MODimmutable):
2890 case X(MODshared | MODwildconst, MODshared):
2891 case X(MODshared | MODwildconst, MODshared | MODconst):
2892 case X(MODshared | MODwildconst, MODimmutable):
2893 {
2894 unsigned char wm = (t->mod & ~MODshared);
2895 if (wm == 0)
2896 wm = MODmutable;
2897 unsigned char m = (t->mod & (MODconst | MODimmutable)) | (tparam->mod & t->mod & MODshared);
2898 *at = t->unqualify(m);
2899 return wm;
2900 }
2901
2902 case X(MODwild, MODwild):
2903 case X(MODwild, MODwildconst):
2904 case X(MODwild, MODshared | MODwild):
2905 case X(MODwild, MODshared | MODwildconst):
2906 case X(MODwildconst, MODwild):
2907 case X(MODwildconst, MODwildconst):
2908 case X(MODwildconst, MODshared | MODwild):
2909 case X(MODwildconst, MODshared | MODwildconst):
2910 case X(MODshared | MODwild, MODshared | MODwild):
2911 case X(MODshared | MODwild, MODshared | MODwildconst):
2912 case X(MODshared | MODwildconst, MODshared | MODwild):
2913 case X(MODshared | MODwildconst, MODshared | MODwildconst):
2914 {
2915 *at = t->unqualify(tparam->mod & t->mod);
2916 return MODwild;
2917 }
2918
2919 default:
2920 return 0;
2921 }
2922 #undef X
2923}
2924
2925MATCH deduceTypeHelper(Type *t, Type **at, Type *tparam)
2926{
2927 // 9*9 == 81 cases
2928
2929 #define X(U,T) ((U) << 4) | (T)
2930 switch (X(tparam->mod, t->mod))
2931 {
2932 case X(0, 0):
2933 case X(0, MODconst):
2934 case X(0, MODwild):
2935 case X(0, MODwildconst):
2936 case X(0, MODshared):
2937 case X(0, MODshared | MODconst):
2938 case X(0, MODshared | MODwild):
2939 case X(0, MODshared | MODwildconst):
2940 case X(0, MODimmutable):
2941 // foo(U) T => T
2942 // foo(U) const(T) => const(T)
2943 // foo(U) inout(T) => inout(T)
2944 // foo(U) inout(const(T)) => inout(const(T))
2945 // foo(U) shared(T) => shared(T)
2946 // foo(U) shared(const(T)) => shared(const(T))
2947 // foo(U) shared(inout(T)) => shared(inout(T))
2948 // foo(U) shared(inout(const(T))) => shared(inout(const(T)))
2949 // foo(U) immutable(T) => immutable(T)
2950 {
2951 *at = t;
2952 return MATCHexact;
2953 }
2954
2955 case X(MODconst, MODconst):
2956 case X(MODwild, MODwild):
2957 case X(MODwildconst, MODwildconst):
2958 case X(MODshared, MODshared):
2959 case X(MODshared | MODconst, MODshared | MODconst):
2960 case X(MODshared | MODwild, MODshared | MODwild):
2961 case X(MODshared | MODwildconst, MODshared | MODwildconst):
2962 case X(MODimmutable, MODimmutable):
2963 // foo(const(U)) const(T) => T
2964 // foo(inout(U)) inout(T) => T
2965 // foo(inout(const(U))) inout(const(T)) => T
2966 // foo(shared(U)) shared(T) => T
2967 // foo(shared(const(U))) shared(const(T)) => T
2968 // foo(shared(inout(U))) shared(inout(T)) => T
2969 // foo(shared(inout(const(U)))) shared(inout(const(T))) => T
2970 // foo(immutable(U)) immutable(T) => T
2971 {
2972 *at = t->mutableOf()->unSharedOf();
2973 return MATCHexact;
2974 }
2975
2976 case X(MODconst, 0):
2977 case X(MODconst, MODwild):
2978 case X(MODconst, MODwildconst):
2979 case X(MODconst, MODshared | MODconst):
2980 case X(MODconst, MODshared | MODwild):
2981 case X(MODconst, MODshared | MODwildconst):
2982 case X(MODconst, MODimmutable):
2983 case X(MODwild, MODshared | MODwild):
2984 case X(MODwildconst, MODshared | MODwildconst):
2985 case X(MODshared | MODconst, MODimmutable):
2986 // foo(const(U)) T => T
2987 // foo(const(U)) inout(T) => T
2988 // foo(const(U)) inout(const(T)) => T
2989 // foo(const(U)) shared(const(T)) => shared(T)
2990 // foo(const(U)) shared(inout(T)) => shared(T)
2991 // foo(const(U)) shared(inout(const(T))) => shared(T)
2992 // foo(const(U)) immutable(T) => T
2993 // foo(inout(U)) shared(inout(T)) => shared(T)
2994 // foo(inout(const(U))) shared(inout(const(T))) => shared(T)
2995 // foo(shared(const(U))) immutable(T) => T
2996 {
2997 *at = t->mutableOf();
2998 return MATCHconst;
2999 }
3000
3001 case X(MODconst, MODshared):
3002 // foo(const(U)) shared(T) => shared(T)
3003 {
3004 *at = t;
3005 return MATCHconst;
3006 }
3007
3008 case X(MODshared, MODshared | MODconst):
3009 case X(MODshared, MODshared | MODwild):
3010 case X(MODshared, MODshared | MODwildconst):
3011 case X(MODshared | MODconst, MODshared):
3012 // foo(shared(U)) shared(const(T)) => const(T)
3013 // foo(shared(U)) shared(inout(T)) => inout(T)
3014 // foo(shared(U)) shared(inout(const(T))) => inout(const(T))
3015 // foo(shared(const(U))) shared(T) => T
3016 {
3017 *at = t->unSharedOf();
3018 return MATCHconst;
3019 }
3020
3021 case X(MODwildconst, MODimmutable):
3022 case X(MODshared | MODconst, MODshared | MODwildconst):
3023 case X(MODshared | MODwildconst, MODimmutable):
3024 case X(MODshared | MODwildconst, MODshared | MODwild):
3025 // foo(inout(const(U))) immutable(T) => T
3026 // foo(shared(const(U))) shared(inout(const(T))) => T
3027 // foo(shared(inout(const(U)))) immutable(T) => T
3028 // foo(shared(inout(const(U)))) shared(inout(T)) => T
3029 {
3030 *at = t->unSharedOf()->mutableOf();
3031 return MATCHconst;
3032 }
3033
3034 case X(MODshared | MODconst, MODshared | MODwild):
3035 // foo(shared(const(U))) shared(inout(T)) => T
3036 {
3037 *at = t->unSharedOf()->mutableOf();
3038 return MATCHconst;
3039 }
3040
3041 case X(MODwild, 0):
3042 case X(MODwild, MODconst):
3043 case X(MODwild, MODwildconst):
3044 case X(MODwild, MODimmutable):
3045 case X(MODwild, MODshared):
3046 case X(MODwild, MODshared | MODconst):
3047 case X(MODwild, MODshared | MODwildconst):
3048 case X(MODwildconst, 0):
3049 case X(MODwildconst, MODconst):
3050 case X(MODwildconst, MODwild):
3051 case X(MODwildconst, MODshared):
3052 case X(MODwildconst, MODshared | MODconst):
3053 case X(MODwildconst, MODshared | MODwild):
3054 case X(MODshared, 0):
3055 case X(MODshared, MODconst):
3056 case X(MODshared, MODwild):
3057 case X(MODshared, MODwildconst):
3058 case X(MODshared, MODimmutable):
3059 case X(MODshared | MODconst, 0):
3060 case X(MODshared | MODconst, MODconst):
3061 case X(MODshared | MODconst, MODwild):
3062 case X(MODshared | MODconst, MODwildconst):
3063 case X(MODshared | MODwild, 0):
3064 case X(MODshared | MODwild, MODconst):
3065 case X(MODshared | MODwild, MODwild):
3066 case X(MODshared | MODwild, MODwildconst):
3067 case X(MODshared | MODwild, MODimmutable):
3068 case X(MODshared | MODwild, MODshared):
3069 case X(MODshared | MODwild, MODshared | MODconst):
3070 case X(MODshared | MODwild, MODshared | MODwildconst):
3071 case X(MODshared | MODwildconst, 0):
3072 case X(MODshared | MODwildconst, MODconst):
3073 case X(MODshared | MODwildconst, MODwild):
3074 case X(MODshared | MODwildconst, MODwildconst):
3075 case X(MODshared | MODwildconst, MODshared):
3076 case X(MODshared | MODwildconst, MODshared | MODconst):
3077 case X(MODimmutable, 0):
3078 case X(MODimmutable, MODconst):
3079 case X(MODimmutable, MODwild):
3080 case X(MODimmutable, MODwildconst):
3081 case X(MODimmutable, MODshared):
3082 case X(MODimmutable, MODshared | MODconst):
3083 case X(MODimmutable, MODshared | MODwild):
3084 case X(MODimmutable, MODshared | MODwildconst):
3085 // foo(inout(U)) T => nomatch
3086 // foo(inout(U)) const(T) => nomatch
3087 // foo(inout(U)) inout(const(T)) => nomatch
3088 // foo(inout(U)) immutable(T) => nomatch
3089 // foo(inout(U)) shared(T) => nomatch
3090 // foo(inout(U)) shared(const(T)) => nomatch
3091 // foo(inout(U)) shared(inout(const(T))) => nomatch
3092 // foo(inout(const(U))) T => nomatch
3093 // foo(inout(const(U))) const(T) => nomatch
3094 // foo(inout(const(U))) inout(T) => nomatch
3095 // foo(inout(const(U))) shared(T) => nomatch
3096 // foo(inout(const(U))) shared(const(T)) => nomatch
3097 // foo(inout(const(U))) shared(inout(T)) => nomatch
3098 // foo(shared(U)) T => nomatch
3099 // foo(shared(U)) const(T) => nomatch
3100 // foo(shared(U)) inout(T) => nomatch
3101 // foo(shared(U)) inout(const(T)) => nomatch
3102 // foo(shared(U)) immutable(T) => nomatch
3103 // foo(shared(const(U))) T => nomatch
3104 // foo(shared(const(U))) const(T) => nomatch
3105 // foo(shared(const(U))) inout(T) => nomatch
3106 // foo(shared(const(U))) inout(const(T)) => nomatch
3107 // foo(shared(inout(U))) T => nomatch
3108 // foo(shared(inout(U))) const(T) => nomatch
3109 // foo(shared(inout(U))) inout(T) => nomatch
3110 // foo(shared(inout(U))) inout(const(T)) => nomatch
3111 // foo(shared(inout(U))) immutable(T) => nomatch
3112 // foo(shared(inout(U))) shared(T) => nomatch
3113 // foo(shared(inout(U))) shared(const(T)) => nomatch
3114 // foo(shared(inout(U))) shared(inout(const(T))) => nomatch
3115 // foo(shared(inout(const(U)))) T => nomatch
3116 // foo(shared(inout(const(U)))) const(T) => nomatch
3117 // foo(shared(inout(const(U)))) inout(T) => nomatch
3118 // foo(shared(inout(const(U)))) inout(const(T)) => nomatch
3119 // foo(shared(inout(const(U)))) shared(T) => nomatch
3120 // foo(shared(inout(const(U)))) shared(const(T)) => nomatch
3121 // foo(immutable(U)) T => nomatch
3122 // foo(immutable(U)) const(T) => nomatch
3123 // foo(immutable(U)) inout(T) => nomatch
3124 // foo(immutable(U)) inout(const(T)) => nomatch
3125 // foo(immutable(U)) shared(T) => nomatch
3126 // foo(immutable(U)) shared(const(T)) => nomatch
3127 // foo(immutable(U)) shared(inout(T)) => nomatch
3128 // foo(immutable(U)) shared(inout(const(T))) => nomatch
3129 return MATCHnomatch;
3130
3131 default:
3132 assert(0);
3133 return MATCHnomatch; // silence compiler warning about missing return
3134 }
3135 #undef X
3136}
3137
3138/* These form the heart of template argument deduction.
3139 * Given 'this' being the type argument to the template instance,
3140 * it is matched against the template declaration parameter specialization
3141 * 'tparam' to determine the type to be used for the parameter.
3142 * Example:
3143 * template Foo(T:T*) // template declaration
3144 * Foo!(int*) // template instantiation
3145 * Input:
3146 * this = int*
3147 * tparam = T*
3148 * parameters = [ T:T* ] // Array of TemplateParameter's
3149 * Output:
3150 * dedtypes = [ int ] // Array of Expression/Type's
3151 */
3152MATCH deduceType(RootObject *o, Scope *sc, Type *tparam, TemplateParameters *parameters,
3153 Objects *dedtypes, unsigned *wm, size_t inferStart)
3154{
3155 class DeduceType : public Visitor
3156 {
3157 public:
3158 Scope *sc;
3159 Type *tparam;
3160 TemplateParameters *parameters;
3161 Objects *dedtypes;
3162 unsigned *wm;
3163 size_t inferStart;
3164 MATCH result;
3165
3166 DeduceType(Scope *sc, Type *tparam, TemplateParameters *parameters, Objects *dedtypes, unsigned *wm, size_t inferStart)
3167 : sc(sc), tparam(tparam), parameters(parameters), dedtypes(dedtypes), wm(wm), inferStart(inferStart)
3168 {
3169 result = MATCHnomatch;
3170 }
3171
3172 void visit(Type *t)
3173 {
3174 if (!tparam)
3175 goto Lnomatch;
3176
3177 if (t == tparam)
3178 goto Lexact;
3179
3180 if (tparam->ty == Tident)
3181 {
3182 // Determine which parameter tparam is
3183 size_t i = templateParameterLookup(tparam, parameters);
3184 if (i == IDX_NOTFOUND)
3185 {
3186 if (!sc)
3187 goto Lnomatch;
3188
3189 /* Need a loc to go with the semantic routine.
3190 */
3191 Loc loc;
3192 if (parameters->dim)
3193 {
3194 TemplateParameter *tp = (*parameters)[0];
3195 loc = tp->loc;
3196 }
3197
3198 /* BUG: what if tparam is a template instance, that
3199 * has as an argument another Tident?
3200 */
3201 tparam = tparam->semantic(loc, sc);
3202 assert(tparam->ty != Tident);
3203 result = deduceType(t, sc, tparam, parameters, dedtypes, wm);
3204 return;
3205 }
3206
3207 TemplateParameter *tp = (*parameters)[i];
3208
3209 TypeIdentifier *tident = (TypeIdentifier *)tparam;
3210 if (tident->idents.dim > 0)
3211 {
3212 //printf("matching %s to %s\n", tparam->toChars(), t->toChars());
3213 Dsymbol *s = t->toDsymbol(sc);
3214 for (size_t j = tident->idents.dim; j-- > 0; )
3215 {
3216 RootObject *id = tident->idents[j];
3217 if (id->dyncast() == DYNCAST_IDENTIFIER)
3218 {
3219 if (!s || !s->parent)
3220 goto Lnomatch;
3221 Dsymbol *s2 = s->parent->search(Loc(), (Identifier *)id);
3222 if (!s2)
3223 goto Lnomatch;
3224 s2 = s2->toAlias();
3225 //printf("[%d] s = %s %s, s2 = %s %s\n", j, s->kind(), s->toChars(), s2->kind(), s2->toChars());
3226 if (s != s2)
3227 {
3228 if (Type *tx = s2->getType())
3229 {
3230 if (s != tx->toDsymbol(sc))
3231 goto Lnomatch;
3232 }
3233 else
3234 goto Lnomatch;
3235 }
3236 s = s->parent;
3237 }
3238 else
3239 goto Lnomatch;
3240 }
3241 //printf("[e] s = %s\n", s?s->toChars():"(null)");
3242 if (tp->isTemplateTypeParameter())
3243 {
3244 Type *tt = s->getType();
3245 if (!tt)
3246 goto Lnomatch;
3247 Type *at = (Type *)(*dedtypes)[i];
3248 if (at && at->ty == Tnone)
3249 at = ((TypeDeduced *)at)->tded;
3250 if (!at || tt->equals(at))
3251 {
3252 (*dedtypes)[i] = tt;
3253 goto Lexact;
3254 }
3255 }
3256 if (tp->isTemplateAliasParameter())
3257 {
3258 Dsymbol *s2 = (Dsymbol *)(*dedtypes)[i];
3259 if (!s2 || s == s2)
3260 {
3261 (*dedtypes)[i] = s;
3262 goto Lexact;
3263 }
3264 }
3265 goto Lnomatch;
3266 }
3267
3268 // Found the corresponding parameter tp
3269 if (!tp->isTemplateTypeParameter())
3270 goto Lnomatch;
3271
3272 Type *at = (Type *)(*dedtypes)[i];
3273 Type *tt;
3274 if (unsigned char wx = wm ? deduceWildHelper(t, &tt, tparam) : 0)
3275 {
3276 // type vs (none)
3277 if (!at)
3278 {
3279 (*dedtypes)[i] = tt;
3280 *wm |= wx;
3281 result = MATCHconst;
3282 return;
3283 }
3284
3285 // type vs expressions
3286 if (at->ty == Tnone)
3287 {
3288 TypeDeduced *xt = (TypeDeduced *)at;
3289 result = xt->matchAll(tt);
3290 if (result > MATCHnomatch)
3291 {
3292 (*dedtypes)[i] = tt;
3293 if (result > MATCHconst)
3294 result = MATCHconst; // limit level for inout matches
3295 delete xt;
3296 }
3297 return;
3298 }
3299
3300 // type vs type
3301 if (tt->equals(at))
3302 {
3303 (*dedtypes)[i] = tt; // Prefer current type match
3304 goto Lconst;
3305 }
3306 if (tt->implicitConvTo(at->constOf()))
3307 {
3308 (*dedtypes)[i] = at->constOf()->mutableOf();
3309 *wm |= MODconst;
3310 goto Lconst;
3311 }
3312 if (at->implicitConvTo(tt->constOf()))
3313 {
3314 (*dedtypes)[i] = tt->constOf()->mutableOf();
3315 *wm |= MODconst;
3316 goto Lconst;
3317 }
3318 goto Lnomatch;
3319 }
3320 else if (MATCH m = deduceTypeHelper(t, &tt, tparam))
3321 {
3322 // type vs (none)
3323 if (!at)
3324 {
3325 (*dedtypes)[i] = tt;
3326 result = m;
3327 return;
3328 }
3329
3330 // type vs expressions
3331 if (at->ty == Tnone)
3332 {
3333 TypeDeduced *xt = (TypeDeduced *)at;
3334 result = xt->matchAll(tt);
3335 if (result > MATCHnomatch)
3336 {
3337 (*dedtypes)[i] = tt;
3338 delete xt;
3339 }
3340 return;
3341 }
3342
3343 // type vs type
3344 if (tt->equals(at))
3345 {
3346 goto Lexact;
3347 }
3348 if (tt->ty == Tclass && at->ty == Tclass)
3349 {
3350 result = tt->implicitConvTo(at);
3351 return;
3352 }
3353 if (tt->ty == Tsarray && at->ty == Tarray &&
3354 tt->nextOf()->implicitConvTo(at->nextOf()) >= MATCHconst)
3355 {
3356 goto Lexact;
3357 }
3358 }
3359 goto Lnomatch;
3360 }
3361
3362 if (tparam->ty == Ttypeof)
3363 {
3364 /* Need a loc to go with the semantic routine.
3365 */
3366 Loc loc;
3367 if (parameters->dim)
3368 {
3369 TemplateParameter *tp = (*parameters)[0];
3370 loc = tp->loc;
3371 }
3372
3373 tparam = tparam->semantic(loc, sc);
3374 }
3375 if (t->ty != tparam->ty)
3376 {
3377 if (Dsymbol *sym = t->toDsymbol(sc))
3378 {
3379 if (sym->isforwardRef() && !tparam->deco)
3380 goto Lnomatch;
3381 }
3382
3383 MATCH m = t->implicitConvTo(tparam);
3384 if (m == MATCHnomatch)
3385 {
3386 if (t->ty == Tclass)
3387 {
3388 TypeClass *tc = (TypeClass *)t;
3389 if (tc->sym->aliasthis && !(tc->att & RECtracingDT))
3390 {
3391 tc->att = (AliasThisRec)(tc->att | RECtracingDT);
3392 m = deduceType(t->aliasthisOf(), sc, tparam, parameters, dedtypes, wm);
3393 tc->att = (AliasThisRec)(tc->att & ~RECtracingDT);
3394 }
3395 }
3396 else if (t->ty == Tstruct)
3397 {
3398 TypeStruct *ts = (TypeStruct *)t;
3399 if (ts->sym->aliasthis && !(ts->att & RECtracingDT))
3400 {
3401 ts->att = (AliasThisRec)(ts->att | RECtracingDT);
3402 m = deduceType(t->aliasthisOf(), sc, tparam, parameters, dedtypes, wm);
3403 ts->att = (AliasThisRec)(ts->att & ~RECtracingDT);
3404 }
3405 }
3406 }
3407 result = m;
3408 return;
3409 }
3410
3411 if (t->nextOf())
3412 {
3413 if (tparam->deco && !tparam->hasWild())
3414 {
3415 result = t->implicitConvTo(tparam);
3416 return;
3417 }
3418
3419 Type *tpn = tparam->nextOf();
3420 if (wm && t->ty == Taarray && tparam->isWild())
3421 {
3422 // Bugzilla 12403: In IFTI, stop inout matching on transitive part of AA types.
3423 tpn = tpn->substWildTo(MODmutable);
3424 }
3425
3426 result = deduceType(t->nextOf(), sc, tpn, parameters, dedtypes, wm);
3427 return;
3428 }
3429
3430 Lexact:
3431 result = MATCHexact;
3432 return;
3433
3434 Lnomatch:
3435 result = MATCHnomatch;
3436 return;
3437
3438 Lconst:
3439 result = MATCHconst;
3440 }
3441
3442 void visit(TypeVector *t)
3443 {
3444 if (tparam->ty == Tvector)
3445 {
3446 TypeVector *tp = (TypeVector *)tparam;
3447 result = deduceType(t->basetype, sc, tp->basetype, parameters, dedtypes, wm);
3448 return;
3449 }
3450 visit((Type *)t);
3451 }
3452
3453 void visit(TypeDArray *t)
3454 {
3455 visit((Type *)t);
3456 }
3457
3458 void visit(TypeSArray *t)
3459 {
3460 // Extra check that array dimensions must match
3461 if (tparam)
3462 {
3463 if (tparam->ty == Tarray)
3464 {
3465 MATCH m = deduceType(t->next, sc, tparam->nextOf(), parameters, dedtypes, wm);
3466 result = (m >= MATCHconst) ? MATCHconvert : MATCHnomatch;
3467 return;
3468 }
3469
3470 TemplateParameter *tp = NULL;
3471 Expression *edim = NULL;
3472 size_t i;
3473 if (tparam->ty == Tsarray)
3474 {
3475 TypeSArray *tsa = (TypeSArray *)tparam;
3476 if (tsa->dim->op == TOKvar &&
3477 ((VarExp *)tsa->dim)->var->storage_class & STCtemplateparameter)
3478 {
3479 Identifier *id = ((VarExp *)tsa->dim)->var->ident;
3480 i = templateIdentifierLookup(id, parameters);
3481 assert(i != IDX_NOTFOUND);
3482 tp = (*parameters)[i];
3483 }
3484 else
3485 edim = tsa->dim;
3486 }
3487 else if (tparam->ty == Taarray)
3488 {
3489 TypeAArray *taa = (TypeAArray *)tparam;
3490 i = templateParameterLookup(taa->index, parameters);
3491 if (i != IDX_NOTFOUND)
3492 tp = (*parameters)[i];
3493 else
3494 {
3495 Expression *e;
3496 Type *tx;
3497 Dsymbol *s;
3498 taa->index->resolve(Loc(), sc, &e, &tx, &s);
3499 edim = s ? getValue(s) : getValue(e);
3500 }
3501 }
3502 if ((tp && tp->matchArg(sc, t->dim, i, parameters, dedtypes, NULL)) ||
3503 (edim && edim->toInteger() == t->dim->toInteger()))
3504 {
3505 result = deduceType(t->next, sc, tparam->nextOf(), parameters, dedtypes, wm);
3506 return;
3507 }
3508 }
3509 visit((Type *)t);
3510 return;
3511
3512 result = MATCHnomatch;
3513 }
3514
3515 void visit(TypeAArray *t)
3516 {
3517 // Extra check that index type must match
3518 if (tparam && tparam->ty == Taarray)
3519 {
3520 TypeAArray *tp = (TypeAArray *)tparam;
3521 if (!deduceType(t->index, sc, tp->index, parameters, dedtypes))
3522 {
3523 result = MATCHnomatch;
3524 return;
3525 }
3526 }
3527 visit((Type *)t);
3528 }
3529
3530 void visit(TypeFunction *t)
3531 {
3532 //printf("TypeFunction::deduceType()\n");
3533 //printf("\tthis = %d, ", t->ty); t->print();
3534 //printf("\ttparam = %d, ", tparam->ty); tparam->print();
3535
3536 // Extra check that function characteristics must match
3537 if (tparam && tparam->ty == Tfunction)
3538 {
3539 TypeFunction *tp = (TypeFunction *)tparam;
3540 if (t->varargs != tp->varargs ||
3541 t->linkage != tp->linkage)
3542 {
3543 result = MATCHnomatch;
3544 return;
3545 }
3546
3547 size_t nfargs = Parameter::dim(t->parameters);
3548 size_t nfparams = Parameter::dim(tp->parameters);
3549
3550 // bug 2579 fix: Apply function parameter storage classes to parameter types
3551 for (size_t i = 0; i < nfparams; i++)
3552 {
3553 Parameter *fparam = Parameter::getNth(tp->parameters, i);
3554 fparam->type = fparam->type->addStorageClass(fparam->storageClass);
3555 fparam->storageClass &= ~(STC_TYPECTOR | STCin);
3556 }
3557 //printf("\t-> this = %d, ", t->ty); t->print();
3558 //printf("\t-> tparam = %d, ", tparam->ty); tparam->print();
3559
3560 /* See if tuple match
3561 */
3562 if (nfparams > 0 && nfargs >= nfparams - 1)
3563 {
3564 /* See if 'A' of the template parameter matches 'A'
3565 * of the type of the last function parameter.
3566 */
3567 Parameter *fparam = Parameter::getNth(tp->parameters, nfparams - 1);
3568 assert(fparam);
3569 assert(fparam->type);
3570 if (fparam->type->ty != Tident)
3571 goto L1;
3572 TypeIdentifier *tid = (TypeIdentifier *)fparam->type;
3573 if (tid->idents.dim)
3574 goto L1;
3575
3576 /* Look through parameters to find tuple matching tid->ident
3577 */
3578 size_t tupi = 0;
3579 for (; 1; tupi++)
3580 {
3581 if (tupi == parameters->dim)
3582 goto L1;
3583 TemplateParameter *tx = (*parameters)[tupi];
3584 TemplateTupleParameter *tup = tx->isTemplateTupleParameter();
3585 if (tup && tup->ident->equals(tid->ident))
3586 break;
3587 }
3588
3589 /* The types of the function arguments [nfparams - 1 .. nfargs]
3590 * now form the tuple argument.
3591 */
3592 size_t tuple_dim = nfargs - (nfparams - 1);
3593
3594 /* See if existing tuple, and whether it matches or not
3595 */
3596 RootObject *o = (*dedtypes)[tupi];
3597 if (o)
3598 {
3599 // Existing deduced argument must be a tuple, and must match
3600 Tuple *tup = isTuple(o);
3601 if (!tup || tup->objects.dim != tuple_dim)
3602 {
3603 result = MATCHnomatch;
3604 return;
3605 }
3606 for (size_t i = 0; i < tuple_dim; i++)
3607 {
3608 Parameter *arg = Parameter::getNth(t->parameters, nfparams - 1 + i);
3609 if (!arg->type->equals(tup->objects[i]))
3610 {
3611 result = MATCHnomatch;
3612 return;
3613 }
3614 }
3615 }
3616 else
3617 {
3618 // Create new tuple
3619 Tuple *tup = new Tuple();
3620 tup->objects.setDim(tuple_dim);
3621 for (size_t i = 0; i < tuple_dim; i++)
3622 {
3623 Parameter *arg = Parameter::getNth(t->parameters, nfparams - 1 + i);
3624 tup->objects[i] = arg->type;
3625 }
3626 (*dedtypes)[tupi] = tup;
3627 }
3628 nfparams--; // don't consider the last parameter for type deduction
3629 goto L2;
3630 }
3631
3632 L1:
3633 if (nfargs != nfparams)
3634 {
3635 result = MATCHnomatch;
3636 return;
3637 }
3638 L2:
3639 for (size_t i = 0; i < nfparams; i++)
3640 {
3641 Parameter *a = Parameter::getNth(t->parameters, i);
3642 Parameter *ap = Parameter::getNth(tp->parameters, i);
3643
3644 if (!a->isCovariant(t->isref, ap) ||
3645 !deduceType(a->type, sc, ap->type, parameters, dedtypes))
3646 {
3647 result = MATCHnomatch;
3648 return;
3649 }
3650 }
3651 }
3652 visit((Type *)t);
3653 }
3654
3655 void visit(TypeIdentifier *t)
3656 {
3657 // Extra check
3658 if (tparam && tparam->ty == Tident)
3659 {
3660 TypeIdentifier *tp = (TypeIdentifier *)tparam;
3661
3662 for (size_t i = 0; i < t->idents.dim; i++)
3663 {
3664 RootObject *id1 = t->idents[i];
3665 RootObject *id2 = tp->idents[i];
3666
3667 if (!id1->equals(id2))
3668 {
3669 result = MATCHnomatch;
3670 return;
3671 }
3672 }
3673 }
3674 visit((Type *)t);
3675 }
3676
3677 void visit(TypeInstance *t)
3678 {
3679 // Extra check
3680 if (tparam && tparam->ty == Tinstance && t->tempinst->tempdecl)
3681 {
3682 TemplateDeclaration *tempdecl = t->tempinst->tempdecl->isTemplateDeclaration();
3683 assert(tempdecl);
3684
3685 TypeInstance *tp = (TypeInstance *)tparam;
3686
3687 //printf("tempinst->tempdecl = %p\n", tempdecl);
3688 //printf("tp->tempinst->tempdecl = %p\n", tp->tempinst->tempdecl);
3689 if (!tp->tempinst->tempdecl)
3690 {
3691 //printf("tp->tempinst->name = '%s'\n", tp->tempinst->name->toChars());
3692
3693 /* Handle case of:
3694 * template Foo(T : sa!(T), alias sa)
3695 */
3696 size_t i = templateIdentifierLookup(tp->tempinst->name, parameters);
3697 if (i == IDX_NOTFOUND)
3698 {
3699 /* Didn't find it as a parameter identifier. Try looking
3700 * it up and seeing if is an alias. See Bugzilla 1454
3701 */
3702 TypeIdentifier *tid = new TypeIdentifier(tp->loc, tp->tempinst->name);
3703 Type *tx;
3704 Expression *e;
3705 Dsymbol *s;
3706 tid->resolve(tp->loc, sc, &e, &tx, &s);
3707 if (tx)
3708 {
3709 s = tx->toDsymbol(sc);
3710 if (TemplateInstance *ti = s ? s->parent->isTemplateInstance() : NULL)
3711 {
3712 // Bugzilla 14290: Try to match with ti->tempecl,
3713 // only when ti is an enclosing instance.
3714 Dsymbol *p = sc->parent;
3715 while (p && p != ti)
3716 p = p->parent;
3717 if (p)
3718 s = ti->tempdecl;
3719 }
3720 }
3721 if (s)
3722 {
3723 s = s->toAlias();
3724 TemplateDeclaration *td = s->isTemplateDeclaration();
3725 if (td)
3726 {
3727 if (td->overroot)
3728 td = td->overroot;
3729 for (; td; td = td->overnext)
3730 {
3731 if (td == tempdecl)
3732 goto L2;
3733 }
3734 }
3735 }
3736 goto Lnomatch;
3737 }
3738 TemplateParameter *tpx = (*parameters)[i];
3739 if (!tpx->matchArg(sc, tempdecl, i, parameters, dedtypes, NULL))
3740 goto Lnomatch;
3741 }
3742 else if (tempdecl != tp->tempinst->tempdecl)
3743 goto Lnomatch;
3744
3745 L2:
3746
3747 for (size_t i = 0; 1; i++)
3748 {
3749 //printf("\ttest: tempinst->tiargs[%d]\n", i);
3750 RootObject *o1 = NULL;
3751 if (i < t->tempinst->tiargs->dim)
3752 o1 = (*t->tempinst->tiargs)[i];
3753 else if (i < t->tempinst->tdtypes.dim && i < tp->tempinst->tiargs->dim)
3754 {
3755 // Pick up default arg
3756 o1 = t->tempinst->tdtypes[i];
3757 }
3758 else if (i >= tp->tempinst->tiargs->dim)
3759 break;
3760
3761 if (i >= tp->tempinst->tiargs->dim)
3762 {
3763 size_t dim = tempdecl->parameters->dim - (tempdecl->isVariadic() ? 1 : 0);
3764 while (i < dim && ((*tempdecl->parameters)[i]->dependent ||
3765 (*tempdecl->parameters)[i]->hasDefaultArg()))
3766 {
3767 i++;
3768 }
3769 if (i >= dim)
3770 break; // match if all remained parameters are dependent
3771 goto Lnomatch;
3772 }
3773
3774 RootObject *o2 = (*tp->tempinst->tiargs)[i];
3775 Type *t2 = isType(o2);
3776
3777 size_t j = (t2 && t2->ty == Tident && i == tp->tempinst->tiargs->dim - 1)
3778 ? templateParameterLookup(t2, parameters) : IDX_NOTFOUND;
3779 if (j != IDX_NOTFOUND && j == parameters->dim - 1 &&
3780 (*parameters)[j]->isTemplateTupleParameter())
3781 {
3782 /* Given:
3783 * struct A(B...) {}
3784 * alias A!(int, float) X;
3785 * static if (is(X Y == A!(Z), Z...)) {}
3786 * deduce that Z is a tuple(int, float)
3787 */
3788
3789 /* Create tuple from remaining args
3790 */
3791 Tuple *vt = new Tuple();
3792 size_t vtdim = (tempdecl->isVariadic()
3793 ? t->tempinst->tiargs->dim : t->tempinst->tdtypes.dim) - i;
3794 vt->objects.setDim(vtdim);
3795 for (size_t k = 0; k < vtdim; k++)
3796 {
3797 RootObject *o;
3798 if (k < t->tempinst->tiargs->dim)
3799 o = (*t->tempinst->tiargs)[i + k];
3800 else // Pick up default arg
3801 o = t->tempinst->tdtypes[i + k];
3802 vt->objects[k] = o;
3803 }
3804
3805 Tuple *v = (Tuple *)(*dedtypes)[j];
3806 if (v)
3807 {
3808 if (!match(v, vt))
3809 goto Lnomatch;
3810 }
3811 else
3812 (*dedtypes)[j] = vt;
3813 break;
3814 }
3815 else if (!o1)
3816 break;
3817
3818 Type *t1 = isType(o1);
3819 Dsymbol *s1 = isDsymbol(o1);
3820 Dsymbol *s2 = isDsymbol(o2);
3821 Expression *e1 = s1 ? getValue(s1) : getValue(isExpression(o1));
3822 Expression *e2 = isExpression(o2);
3823
3824 if (t1 && t2)
3825 {
3826 if (!deduceType(t1, sc, t2, parameters, dedtypes))
3827 goto Lnomatch;
3828 }
3829 else if (e1 && e2)
3830 {
3831 Le:
3832 e1 = e1->ctfeInterpret();
3833
3834 /* If it is one of the template parameters for this template,
3835 * we should not attempt to interpret it. It already has a value.
3836 */
3837 if (e2->op == TOKvar &&
3838 (((VarExp *)e2)->var->storage_class & STCtemplateparameter))
3839 {
3840 /*
3841 * (T:Number!(e2), int e2)
3842 */
3843 j = templateIdentifierLookup(((VarExp *)e2)->var->ident, parameters);
3844 if (j != IDX_NOTFOUND)
3845 goto L1;
3846 // The template parameter was not from this template
3847 // (it may be from a parent template, for example)
3848 }
3849
3850 e2 = ::semantic(e2, sc); // Bugzilla 13417
3851 e2 = e2->ctfeInterpret();
3852
3853 //printf("e1 = %s, type = %s %d\n", e1->toChars(), e1->type->toChars(), e1->type->ty);
3854 //printf("e2 = %s, type = %s %d\n", e2->toChars(), e2->type->toChars(), e2->type->ty);
3855 if (!e1->equals(e2))
3856 {
3857 if (!e2->implicitConvTo(e1->type))
3858 goto Lnomatch;
3859
3860 e2 = e2->implicitCastTo(sc, e1->type);
3861 e2 = e2->ctfeInterpret();
3862 if (!e1->equals(e2))
3863 goto Lnomatch;
3864 }
3865 }
3866 else if (e1 && t2 && t2->ty == Tident)
3867 {
3868 j = templateParameterLookup(t2, parameters);
3869 L1:
3870 if (j == IDX_NOTFOUND)
3871 {
3872 t2->resolve(((TypeIdentifier *)t2)->loc, sc, &e2, &t2, &s2);
3873 if (e2)
3874 goto Le;
3875 goto Lnomatch;
3876 }
3877 if (!(*parameters)[j]->matchArg(sc, e1, j, parameters, dedtypes, NULL))
3878 goto Lnomatch;
3879 }
3880 else if (s1 && s2)
3881 {
3882 Ls:
3883 if (!s1->equals(s2))
3884 goto Lnomatch;
3885 }
3886 else if (s1 && t2 && t2->ty == Tident)
3887 {
3888 j = templateParameterLookup(t2, parameters);
3889 if (j == IDX_NOTFOUND)
3890 {
3891 t2->resolve(((TypeIdentifier *)t2)->loc, sc, &e2, &t2, &s2);
3892 if (s2)
3893 goto Ls;
3894 goto Lnomatch;
3895 }
3896 if (!(*parameters)[j]->matchArg(sc, s1, j, parameters, dedtypes, NULL))
3897 goto Lnomatch;
3898 }
3899 else
3900 goto Lnomatch;
3901 }
3902 }
3903 visit((Type *)t);
3904 return;
3905
3906 Lnomatch:
3907 //printf("no match\n");
3908 result = MATCHnomatch;
3909 }
3910
3911 void visit(TypeStruct *t)
3912 {
3913 /* If this struct is a template struct, and we're matching
3914 * it against a template instance, convert the struct type
3915 * to a template instance, too, and try again.
3916 */
3917 TemplateInstance *ti = t->sym->parent->isTemplateInstance();
3918
3919 if (tparam && tparam->ty == Tinstance)
3920 {
3921 if (ti && ti->toAlias() == t->sym)
3922 {
3923 TypeInstance *tx = new TypeInstance(Loc(), ti);
3924 result = deduceType(tx, sc, tparam, parameters, dedtypes, wm);
3925 return;
3926 }
3927
3928 /* Match things like:
3929 * S!(T).foo
3930 */
3931 TypeInstance *tpi = (TypeInstance *)tparam;
3932 if (tpi->idents.dim)
3933 {
3934 RootObject *id = tpi->idents[tpi->idents.dim - 1];
3935 if (id->dyncast() == DYNCAST_IDENTIFIER && t->sym->ident->equals((Identifier *)id))
3936 {
3937 Type *tparent = t->sym->parent->getType();
3938 if (tparent)
3939 {
3940 /* Slice off the .foo in S!(T).foo
3941 */
3942 tpi->idents.dim--;
3943 result = deduceType(tparent, sc, tpi, parameters, dedtypes, wm);
3944 tpi->idents.dim++;
3945 return;
3946 }
3947 }
3948 }
3949 }
3950
3951 // Extra check
3952 if (tparam && tparam->ty == Tstruct)
3953 {
3954 TypeStruct *tp = (TypeStruct *)tparam;
3955
3956 //printf("\t%d\n", (MATCH) t->implicitConvTo(tp));
3957 if (wm && t->deduceWild(tparam, false))
3958 {
3959 result = MATCHconst;
3960 return;
3961 }
3962 result = t->implicitConvTo(tp);
3963 return;
3964 }
3965 visit((Type *)t);
3966 }
3967
3968 void visit(TypeEnum *t)
3969 {
3970 // Extra check
3971 if (tparam && tparam->ty == Tenum)
3972 {
3973 TypeEnum *tp = (TypeEnum *)tparam;
3974 if (t->sym == tp->sym)
3975 visit((Type *)t);
3976 else
3977 result = MATCHnomatch;
3978 return;
3979 }
3980 Type *tb = t->toBasetype();
3981 if (tb->ty == tparam->ty ||
3982 (tb->ty == Tsarray && tparam->ty == Taarray))
3983 {
3984 result = deduceType(tb, sc, tparam, parameters, dedtypes, wm);
3985 return;
3986 }
3987 visit((Type *)t);
3988 }
3989
3990 /* Helper for TypeClass::deduceType().
3991 * Classes can match with implicit conversion to a base class or interface.
3992 * This is complicated, because there may be more than one base class which
3993 * matches. In such cases, one or more parameters remain ambiguous.
3994 * For example,
3995 *
3996 * interface I(X, Y) {}
3997 * class C : I(uint, double), I(char, double) {}
3998 * C x;
3999 * foo(T, U)( I!(T, U) x)
4000 *
4001 * deduces that U is double, but T remains ambiguous (could be char or uint).
4002 *
4003 * Given a baseclass b, and initial deduced types 'dedtypes', this function
4004 * tries to match tparam with b, and also tries all base interfaces of b.
4005 * If a match occurs, numBaseClassMatches is incremented, and the new deduced
4006 * types are ANDed with the current 'best' estimate for dedtypes.
4007 */
4008 static void deduceBaseClassParameters(BaseClass *b,
4009 Scope *sc, Type *tparam, TemplateParameters *parameters, Objects *dedtypes,
4010 Objects *best, int &numBaseClassMatches)
4011 {
4012 TemplateInstance *parti = b->sym ? b->sym->parent->isTemplateInstance() : NULL;
4013 if (parti)
4014 {
4015 // Make a temporary copy of dedtypes so we don't destroy it
4016 Objects *tmpdedtypes = new Objects();
4017 tmpdedtypes->setDim(dedtypes->dim);
4018 memcpy(tmpdedtypes->tdata(), dedtypes->tdata(), dedtypes->dim * sizeof(void *));
4019
4020 TypeInstance *t = new TypeInstance(Loc(), parti);
4021 MATCH m = deduceType(t, sc, tparam, parameters, tmpdedtypes);
4022 if (m > MATCHnomatch)
4023 {
4024 // If this is the first ever match, it becomes our best estimate
4025 if (numBaseClassMatches==0)
4026 memcpy(best->tdata(), tmpdedtypes->tdata(), tmpdedtypes->dim * sizeof(void *));
4027 else for (size_t k = 0; k < tmpdedtypes->dim; ++k)
4028 {
4029 // If we've found more than one possible type for a parameter,
4030 // mark it as unknown.
4031 if ((*tmpdedtypes)[k] != (*best)[k])
4032 (*best)[k] = (*dedtypes)[k];
4033 }
4034 ++numBaseClassMatches;
4035 }
4036 }
4037 // Now recursively test the inherited interfaces
4038 for (size_t j = 0; j < b->baseInterfaces.length; ++j)
4039 {
4040 BaseClass *bi = &b->baseInterfaces.ptr[j];
4041 deduceBaseClassParameters(bi,
4042 sc, tparam, parameters, dedtypes,
4043 best, numBaseClassMatches);
4044 }
4045
4046 }
4047
4048 void visit(TypeClass *t)
4049 {
4050 //printf("TypeClass::deduceType(this = %s)\n", t->toChars());
4051
4052 /* If this class is a template class, and we're matching
4053 * it against a template instance, convert the class type
4054 * to a template instance, too, and try again.
4055 */
4056 TemplateInstance *ti = t->sym->parent->isTemplateInstance();
4057
4058 if (tparam && tparam->ty == Tinstance)
4059 {
4060 if (ti && ti->toAlias() == t->sym)
4061 {
4062 TypeInstance *tx = new TypeInstance(Loc(), ti);
4063 MATCH m = deduceType(tx, sc, tparam, parameters, dedtypes, wm);
4064 // Even if the match fails, there is still a chance it could match
4065 // a base class.
4066 if (m != MATCHnomatch)
4067 {
4068 result = m;
4069 return;
4070 }
4071 }
4072
4073 /* Match things like:
4074 * S!(T).foo
4075 */
4076 TypeInstance *tpi = (TypeInstance *)tparam;
4077 if (tpi->idents.dim)
4078 {
4079 RootObject *id = tpi->idents[tpi->idents.dim - 1];
4080 if (id->dyncast() == DYNCAST_IDENTIFIER && t->sym->ident->equals((Identifier *)id))
4081 {
4082 Type *tparent = t->sym->parent->getType();
4083 if (tparent)
4084 {
4085 /* Slice off the .foo in S!(T).foo
4086 */
4087 tpi->idents.dim--;
4088 result = deduceType(tparent, sc, tpi, parameters, dedtypes, wm);
4089 tpi->idents.dim++;
4090 return;
4091 }
4092 }
4093 }
4094
4095 // If it matches exactly or via implicit conversion, we're done
4096 visit((Type *)t);
4097 if (result != MATCHnomatch)
4098 return;
4099
4100 /* There is still a chance to match via implicit conversion to
4101 * a base class or interface. Because there could be more than one such
4102 * match, we need to check them all.
4103 */
4104
4105 int numBaseClassMatches = 0; // Have we found an interface match?
4106
4107 // Our best guess at dedtypes
4108 Objects *best = new Objects();
4109 best->setDim(dedtypes->dim);
4110
4111 ClassDeclaration *s = t->sym;
4112 while (s && s->baseclasses->dim > 0)
4113 {
4114 // Test the base class
4115 deduceBaseClassParameters((*s->baseclasses)[0],
4116 sc, tparam, parameters, dedtypes,
4117 best, numBaseClassMatches);
4118
4119 // Test the interfaces inherited by the base class
4120 for (size_t i = 0; i < s->interfaces.length; ++i)
4121 {
4122 BaseClass *b = s->interfaces.ptr[i];
4123 deduceBaseClassParameters(b, sc, tparam, parameters, dedtypes,
4124 best, numBaseClassMatches);
4125 }
4126 s = (*s->baseclasses)[0]->sym;
4127 }
4128
4129 if (numBaseClassMatches == 0)
4130 {
4131 result = MATCHnomatch;
4132 return;
4133 }
4134
4135 // If we got at least one match, copy the known types into dedtypes
4136 memcpy(dedtypes->tdata(), best->tdata(), best->dim * sizeof(void *));
4137 result = MATCHconvert;
4138 return;
4139 }
4140
4141 // Extra check
4142 if (tparam && tparam->ty == Tclass)
4143 {
4144 TypeClass *tp = (TypeClass *)tparam;
4145
4146 //printf("\t%d\n", (MATCH) t->implicitConvTo(tp));
4147 if (wm && t->deduceWild(tparam, false))
4148 {
4149 result = MATCHconst;
4150 return;
4151 }
4152 result = t->implicitConvTo(tp);
4153 return;
4154 }
4155 visit((Type *)t);
4156 }
4157
4158 void visit(Expression *e)
4159 {
4160 //printf("Expression::deduceType(e = %s)\n", e->toChars());
4161 size_t i = templateParameterLookup(tparam, parameters);
4162 if (i == IDX_NOTFOUND || ((TypeIdentifier *)tparam)->idents.dim > 0)
4163 {
4164 if (e == emptyArrayElement && tparam->ty == Tarray)
4165 {
4166 Type *tn = ((TypeNext *)tparam)->next;
4167 result = deduceType(emptyArrayElement, sc, tn, parameters, dedtypes, wm);
4168 return;
4169 }
4170 e->type->accept(this);
4171 return;
4172 }
4173
4174 TemplateTypeParameter *tp = (*parameters)[i]->isTemplateTypeParameter();
4175 if (!tp)
4176 return; // nomatch
4177
4178 if (e == emptyArrayElement)
4179 {
4180 if ((*dedtypes)[i])
4181 {
4182 result = MATCHexact;
4183 return;
4184 }
4185 if (tp->defaultType)
4186 {
4187 tp->defaultType->accept(this);
4188 return;
4189 }
4190 }
4191
4192 Type *at = (Type *)(*dedtypes)[i];
4193 Type *tt;
4194 if (unsigned char wx = deduceWildHelper(e->type, &tt, tparam))
4195 {
4196 *wm |= wx;
4197 result = MATCHconst;
4198 }
4199 else if (MATCH m = deduceTypeHelper(e->type, &tt, tparam))
4200 {
4201 result = m;
4202 }
4203 else
4204 return; // nomatch
4205
4206 // expression vs (none)
4207 if (!at)
4208 {
4209 (*dedtypes)[i] = new TypeDeduced(tt, e, tparam);
4210 return;
4211 }
4212
4213 TypeDeduced *xt = NULL;
4214 if (at->ty == Tnone)
4215 {
4216 xt = (TypeDeduced *)at;
4217 at = xt->tded;
4218 }
4219
4220 // From previous matched expressions to current deduced type
4221 MATCH match1 = xt ? xt->matchAll(tt) : MATCHnomatch;
4222
4223 // From current expresssion to previous deduced type
4224 Type *pt = at->addMod(tparam->mod);
4225 if (*wm)
4226 pt = pt->substWildTo(*wm);
4227 MATCH match2 = e->implicitConvTo(pt);
4228
4229 if (match1 > MATCHnomatch && match2 > MATCHnomatch)
4230 {
4231 if (at->implicitConvTo(tt) <= MATCHnomatch)
4232 match1 = MATCHnomatch; // Prefer at
4233 else if (tt->implicitConvTo(at) <= MATCHnomatch)
4234 match2 = MATCHnomatch; // Prefer tt
4235 else if (tt->isTypeBasic() && tt->ty == at->ty && tt->mod != at->mod)
4236 {
4237 if (!tt->isMutable() && !at->isMutable())
4238 tt = tt->mutableOf()->addMod(MODmerge(tt->mod, at->mod));
4239 else if (tt->isMutable())
4240 {
4241 if (at->mod == 0) // Prefer unshared
4242 match1 = MATCHnomatch;
4243 else
4244 match2 = MATCHnomatch;
4245 }
4246 else if (at->isMutable())
4247 {
4248 if (tt->mod == 0) // Prefer unshared
4249 match2 = MATCHnomatch;
4250 else
4251 match1 = MATCHnomatch;
4252 }
4253 //printf("tt = %s, at = %s\n", tt->toChars(), at->toChars());
4254 }
4255 else
4256 {
4257 match1 = MATCHnomatch;
4258 match2 = MATCHnomatch;
4259 }
4260 }
4261 if (match1 > MATCHnomatch)
4262 {
4263 // Prefer current match: tt
4264 if (xt)
4265 xt->update(tt, e, tparam);
4266 else
4267 (*dedtypes)[i] = tt;
4268 result = match1;
4269 return;
4270 }
4271 if (match2 > MATCHnomatch)
4272 {
4273 // Prefer previous match: (*dedtypes)[i]
4274 if (xt)
4275 xt->update(e, tparam);
4276 result = match2;
4277 return;
4278 }
4279
4280 /* Deduce common type
4281 */
4282 if (Type *t = rawTypeMerge(at, tt))
4283 {
4284 if (xt)
4285 xt->update(t, e, tparam);
4286 else
4287 (*dedtypes)[i] = t;
4288
4289 pt = tt->addMod(tparam->mod);
4290 if (*wm)
4291 pt = pt->substWildTo(*wm);
4292 result = e->implicitConvTo(pt);
4293 return;
4294 }
4295
4296 result = MATCHnomatch;
4297 }
4298
4299 MATCH deduceEmptyArrayElement()
4300 {
4301 if (!emptyArrayElement)
4302 {
4303 emptyArrayElement = new IdentifierExp(Loc(), Id::p); // dummy
4304 emptyArrayElement->type = Type::tvoid;
4305 }
4306 assert(tparam->ty == Tarray);
4307
4308 Type *tn = ((TypeNext *)tparam)->next;
4309 return deduceType(emptyArrayElement, sc, tn, parameters, dedtypes, wm);
4310 }
4311
4312 void visit(NullExp *e)
4313 {
4314 if (tparam->ty == Tarray && e->type->ty == Tnull)
4315 {
4316 // tparam:T[] <- e:null (void[])
4317 result = deduceEmptyArrayElement();
4318 return;
4319 }
4320 visit((Expression *)e);
4321 }
4322
4323 void visit(StringExp *e)
4324 {
4325 Type *taai;
4326 if (e->type->ty == Tarray &&
4327 (tparam->ty == Tsarray ||
4328 (tparam->ty == Taarray && (taai = ((TypeAArray *)tparam)->index)->ty == Tident &&
4329 ((TypeIdentifier *)taai)->idents.dim == 0)))
4330 {
4331 // Consider compile-time known boundaries
4332 e->type->nextOf()->sarrayOf(e->len)->accept(this);
4333 return;
4334 }
4335 visit((Expression *)e);
4336 }
4337
4338 void visit(ArrayLiteralExp *e)
4339 {
4340 if ((!e->elements || !e->elements->dim) &&
4341 e->type->toBasetype()->nextOf()->ty == Tvoid &&
4342 tparam->ty == Tarray)
4343 {
4344 // tparam:T[] <- e:[] (void[])
4345 result = deduceEmptyArrayElement();
4346 return;
4347 }
4348
4349 if (tparam->ty == Tarray && e->elements && e->elements->dim)
4350 {
4351 Type *tn = ((TypeDArray *)tparam)->next;
4352 result = MATCHexact;
4353 if (e->basis)
4354 {
4355 MATCH m = deduceType(e->basis, sc, tn, parameters, dedtypes, wm);
4356 if (m < result)
4357 result = m;
4358 }
4359 for (size_t i = 0; i < e->elements->dim; i++)
4360 {
4361 if (result <= MATCHnomatch)
4362 break;
4363 Expression *el = (*e->elements)[i];
4364 if (!el)
4365 continue;
4366 MATCH m = deduceType(el, sc, tn, parameters, dedtypes, wm);
4367 if (m < result)
4368 result = m;
4369 }
4370 return;
4371 }
4372
4373 Type *taai;
4374 if (e->type->ty == Tarray &&
4375 (tparam->ty == Tsarray ||
4376 (tparam->ty == Taarray && (taai = ((TypeAArray *)tparam)->index)->ty == Tident &&
4377 ((TypeIdentifier *)taai)->idents.dim == 0)))
4378 {
4379 // Consider compile-time known boundaries
4380 e->type->nextOf()->sarrayOf(e->elements->dim)->accept(this);
4381 return;
4382 }
4383 visit((Expression *)e);
4384 }
4385
4386 void visit(AssocArrayLiteralExp *e)
4387 {
4388 if (tparam->ty == Taarray && e->keys && e->keys->dim)
4389 {
4390 TypeAArray *taa = (TypeAArray *)tparam;
4391 result = MATCHexact;
4392 for (size_t i = 0; i < e->keys->dim; i++)
4393 {
4394 MATCH m1 = deduceType((*e->keys)[i], sc, taa->index, parameters, dedtypes, wm);
4395 if (m1 < result)
4396 result = m1;
4397 if (result <= MATCHnomatch)
4398 break;
4399 MATCH m2 = deduceType((*e->values)[i], sc, taa->next, parameters, dedtypes, wm);
4400 if (m2 < result)
4401 result = m2;
4402 if (result <= MATCHnomatch)
4403 break;
4404 }
4405 return;
4406 }
4407 visit((Expression *)e);
4408 }
4409
4410 void visit(FuncExp *e)
4411 {
4412 //printf("e->type = %s, tparam = %s\n", e->type->toChars(), tparam->toChars());
4413 if (e->td)
4414 {
4415 Type *to = tparam;
4416 if (!to->nextOf() || to->nextOf()->ty != Tfunction)
4417 return;
4418 TypeFunction *tof = (TypeFunction *)to->nextOf();
4419
4420 // Parameter types inference from 'tof'
4421 assert(e->td->_scope);
4422 TypeFunction *tf = (TypeFunction *)e->fd->type;
4423 //printf("\ttof = %s\n", tof->toChars());
4424 //printf("\ttf = %s\n", tf->toChars());
4425 size_t dim = Parameter::dim(tf->parameters);
4426
4427 if (Parameter::dim(tof->parameters) != dim ||
4428 tof->varargs != tf->varargs)
4429 return;
4430
4431 Objects *tiargs = new Objects();
4432 tiargs->reserve(e->td->parameters->dim);
4433
4434 for (size_t i = 0; i < e->td->parameters->dim; i++)
4435 {
4436 TemplateParameter *tp = (*e->td->parameters)[i];
4437 size_t u = 0;
4438 for (; u < dim; u++)
4439 {
4440 Parameter *p = Parameter::getNth(tf->parameters, u);
4441 if (p->type->ty == Tident &&
4442 ((TypeIdentifier *)p->type)->ident == tp->ident)
4443 {
4444 break;
4445 }
4446 }
4447 assert(u < dim);
4448 Parameter *pto = Parameter::getNth(tof->parameters, u);
4449 if (!pto)
4450 break;
4451 Type *t = pto->type->syntaxCopy(); // Bugzilla 11774
4452 if (reliesOnTident(t, parameters, inferStart))
4453 return;
4454 t = t->semantic(e->loc, sc);
4455 if (t->ty == Terror)
4456 return;
4457 tiargs->push(t);
4458 }
4459
4460 // Set target of return type inference
4461 if (!tf->next && tof->next)
4462 e->fd->treq = tparam;
4463
4464 TemplateInstance *ti = new TemplateInstance(e->loc, e->td, tiargs);
4465 Expression *ex = new ScopeExp(e->loc, ti);
4466 ex = ::semantic(ex, e->td->_scope);
4467
4468 // Reset inference target for the later re-semantic
4469 e->fd->treq = NULL;
4470
4471 if (ex->op == TOKerror)
4472 return;
4473 if (ex->op != TOKfunction)
4474 return;
4475 visit(ex->type);
4476 return;
4477 }
4478
4479 Type *t = e->type;
4480
4481 if (t->ty == Tdelegate && tparam->ty == Tpointer)
4482 return;
4483
4484 // Allow conversion from implicit function pointer to delegate
4485 if (e->tok == TOKreserved &&
4486 t->ty == Tpointer && tparam->ty == Tdelegate)
4487 {
4488 TypeFunction *tf = (TypeFunction *)t->nextOf();
4489 t = (new TypeDelegate(tf))->merge();
4490 }
4491 //printf("tparam = %s <= e->type = %s, t = %s\n", tparam->toChars(), e->type->toChars(), t->toChars());
4492 visit(t);
4493 }
4494
4495 void visit(SliceExp *e)
4496 {
4497 Type *taai;
4498 if (e->type->ty == Tarray &&
4499 (tparam->ty == Tsarray ||
4500 (tparam->ty == Taarray && (taai = ((TypeAArray *)tparam)->index)->ty == Tident &&
4501 ((TypeIdentifier *)taai)->idents.dim == 0)))
4502 {
4503 // Consider compile-time known boundaries
4504 if (Type *tsa = toStaticArrayType(e))
4505 {
4506 tsa->accept(this);
4507 return;
4508 }
4509 }
4510 visit((Expression *)e);
4511 }
4512
4513 void visit(CommaExp *e)
4514 {
4515 ((CommaExp *)e)->e2->accept(this);
4516 }
4517 };
4518
4519 DeduceType v(sc, tparam, parameters, dedtypes, wm, inferStart);
4520 if (Type *t = isType(o))
4521 t->accept(&v);
4522 else
4523 {
4524 assert(isExpression(o) && wm);
4525 ((Expression *)o)->accept(&v);
4526 }
4527 return v.result;
4528}
4529
4530/*******************************
4531 * Input:
4532 * t Tested type, if NULL, returns NULL.
4533 * tparams Optional template parameters.
4534 * == NULL:
4535 * If one of the subtypes of this type is a TypeIdentifier,
4536 * i.e. it's an unresolved type, return that type.
4537 * != NULL:
4538 * Only when the TypeIdentifier is one of template parameters,
4539 * return that type.
4540 */
4541
4542bool reliesOnTident(Type *t, TemplateParameters *tparams, size_t iStart)
4543{
4544 class ReliesOnTident : public Visitor
4545 {
4546 public:
4547 TemplateParameters *tparams;
4548 size_t iStart;
4549 bool result;
4550
4551 ReliesOnTident(TemplateParameters *tparams, size_t iStart)
4552 : tparams(tparams), iStart(iStart)
4553 {
4554 result = false;
4555 }
4556
4557 void visit(Type *)
4558 {
4559 }
4560
4561 void visit(TypeNext *t)
4562 {
4563 t->next->accept(this);
4564 }
4565
4566 void visit(TypeVector *t)
4567 {
4568 t->basetype->accept(this);
4569 }
4570
4571 void visit(TypeAArray *t)
4572 {
4573 visit((TypeNext *)t);
4574 if (!result)
4575 t->index->accept(this);
4576 }
4577
4578 void visit(TypeFunction *t)
4579 {
4580 size_t dim = Parameter::dim(t->parameters);
4581 for (size_t i = 0; i < dim; i++)
4582 {
4583 Parameter *fparam = Parameter::getNth(t->parameters, i);
4584 fparam->type->accept(this);
4585 if (result)
4586 return;
4587 }
4588 if (t->next)
4589 t->next->accept(this);
4590 }
4591
4592 void visit(TypeIdentifier *t)
4593 {
4594 if (!tparams)
4595 {
4596 result = true;
4597 return;
4598 }
4599
4600 for (size_t i = iStart; i < tparams->dim; i++)
4601 {
4602 TemplateParameter *tp = (*tparams)[i];
4603 if (tp->ident->equals(t->ident))
4604 {
4605 result = true;
4606 return;
4607 }
4608 }
4609 }
4610
4611 void visit(TypeInstance *t)
4612 {
4613 if (!tparams)
4614 return;
4615
4616 for (size_t i = iStart; i < tparams->dim; i++)
4617 {
4618 TemplateParameter *tp = (*tparams)[i];
4619 if (t->tempinst->name == tp->ident)
4620 {
4621 result = true;
4622 return;
4623 }
4624 }
4625 if (!t->tempinst->tiargs)
4626 return;
4627 for (size_t i = 0; i < t->tempinst->tiargs->dim; i++)
4628 {
4629 Type *ta = isType((*t->tempinst->tiargs)[i]);
4630 if (ta)
4631 {
4632 ta->accept(this);
4633 if (result)
4634 return;
4635 }
4636 }
4637 }
4638
4639 void visit(TypeTypeof *t)
4640 {
4641 //printf("TypeTypeof::reliesOnTident('%s')\n", t->toChars());
4642 t->exp->accept(this);
4643 }
4644
4645 void visit(TypeTuple *t)
4646 {
4647 if (t->arguments)
4648 {
4649 for (size_t i = 0; i < t->arguments->dim; i++)
4650 {
4651 Parameter *arg = (*t->arguments)[i];
4652 arg->type->accept(this);
4653 if (result)
4654 return;
4655 }
4656 }
4657 }
4658
4659 void visit(Expression *)
4660 {
4661 //printf("Expression::reliesOnTident('%s')\n", e->toChars());
4662 }
4663
4664 void visit(IdentifierExp *e)
4665 {
4666 //printf("IdentifierExp::reliesOnTident('%s')\n", e->toChars());
4667 for (size_t i = iStart; i < tparams->dim; i++)
4668 {
4669 TemplateParameter *tp = (*tparams)[i];
4670 if (e->ident == tp->ident)
4671 {
4672 result = true;
4673 return;
4674 }
4675 }
4676 }
4677
4678 void visit(TupleExp *e)
4679 {
4680 //printf("TupleExp::reliesOnTident('%s')\n", e->toChars());
4681 if (e->exps)
4682 {
4683 for (size_t i = 0; i < e->exps->dim; i++)
4684 {
4685 Expression *ea = (*e->exps)[i];
4686 ea->accept(this);
4687 if (result)
4688 return;
4689 }
4690 }
4691 }
4692
4693 void visit(ArrayLiteralExp *e)
4694 {
4695 //printf("ArrayLiteralExp::reliesOnTident('%s')\n", e->toChars());
4696 if (e->elements)
4697 {
4698 for (size_t i = 0; i < e->elements->dim; i++)
4699 {
4700 Expression *el = (*e->elements)[i];
4701 el->accept(this);
4702 if (result)
4703 return;
4704 }
4705 }
4706 }
4707
4708 void visit(AssocArrayLiteralExp *e)
4709 {
4710 //printf("AssocArrayLiteralExp::reliesOnTident('%s')\n", e->toChars());
4711 for (size_t i = 0; i < e->keys->dim; i++)
4712 {
4713 Expression *ek = (*e->keys)[i];
4714 ek->accept(this);
4715 if (result)
4716 return;
4717 }
4718 for (size_t i = 0; i < e->values->dim; i++)
4719 {
4720 Expression *ev = (*e->values)[i];
4721 ev->accept(this);
4722 if (result)
4723 return;
4724 }
4725 }
4726
4727 void visit(StructLiteralExp *e)
4728 {
4729 //printf("StructLiteralExp::reliesOnTident('%s')\n", e->toChars());
4730 if (e->elements)
4731 {
4732 for (size_t i = 0; i < e->elements->dim; i++)
4733 {
4734 Expression *ea = (*e->elements)[i];
4735 ea->accept(this);
4736 if (result)
4737 return;
4738 }
4739 }
4740 }
4741
4742 void visit(TypeExp *e)
4743 {
4744 //printf("TypeExp::reliesOnTident('%s')\n", e->toChars());
4745 e->type->accept(this);
4746 }
4747
4748 void visit(NewExp *e)
4749 {
4750 //printf("NewExp::reliesOnTident('%s')\n", e->toChars());
4751 if (e->thisexp)
4752 e->thisexp->accept(this);
4753 if (!result && e->newargs)
4754 {
4755 for (size_t i = 0; i < e->newargs->dim; i++)
4756 {
4757 Expression *ea = (*e->newargs)[i];
4758 ea->accept(this);
4759 if (result)
4760 return;
4761 }
4762 }
4763 e->newtype->accept(this);
4764 if (!result && e->arguments)
4765 {
4766 for (size_t i = 0; i < e->arguments->dim; i++)
4767 {
4768 Expression *ea = (*e->arguments)[i];
4769 ea->accept(this);
4770 if (result)
4771 return;
4772 }
4773 }
4774 }
4775
4776 void visit(NewAnonClassExp *)
4777 {
4778 //printf("NewAnonClassExp::reliesOnTident('%s')\n", e->toChars());
4779 result = true;
4780 }
4781
4782 void visit(FuncExp *)
4783 {
4784 //printf("FuncExp::reliesOnTident('%s')\n", e->toChars());
4785 result = true;
4786 }
4787
4788 void visit(TypeidExp *e)
4789 {
4790 //printf("TypeidExp::reliesOnTident('%s')\n", e->toChars());
4791 if (Expression *ea = isExpression(e->obj))
4792 ea->accept(this);
4793 else if (Type *ta = isType(e->obj))
4794 ta->accept(this);
4795 }
4796
4797 void visit(TraitsExp *e)
4798 {
4799 //printf("TraitsExp::reliesOnTident('%s')\n", e->toChars());
4800 if (e->args)
4801 {
4802 for (size_t i = 0; i < e->args->dim; i++)
4803 {
4804 RootObject *oa = (*e->args)[i];
4805 if (Expression *ea = isExpression(oa))
4806 ea->accept(this);
4807 else if (Type *ta = isType(oa))
4808 ta->accept(this);
4809 if (result)
4810 return;
4811 }
4812 }
4813 }
4814
4815 void visit(IsExp *e)
4816 {
4817 //printf("IsExp::reliesOnTident('%s')\n", e->toChars());
4818 e->targ->accept(this);
4819 }
4820
4821 void visit(UnaExp *e)
4822 {
4823 //printf("UnaExp::reliesOnTident('%s')\n", e->toChars());
4824 e->e1->accept(this);
4825 }
4826
4827 void visit(DotTemplateInstanceExp *e)
4828 {
4829 //printf("DotTemplateInstanceExp::reliesOnTident('%s')\n", e->toChars());
4830 visit((UnaExp *)e);
4831 if (!result && e->ti->tiargs)
4832 {
4833 for (size_t i = 0; i < e->ti->tiargs->dim; i++)
4834 {
4835 RootObject *oa = (*e->ti->tiargs)[i];
4836 if (Expression *ea = isExpression(oa))
4837 ea->accept(this);
4838 else if (Type *ta = isType(oa))
4839 ta->accept(this);
4840 if (result)
4841 return;
4842 }
4843 }
4844 }
4845
4846 void visit(CallExp *e)
4847 {
4848 //printf("CallExp::reliesOnTident('%s')\n", e->toChars());
4849 visit((UnaExp *)e);
4850 if (!result && e->arguments)
4851 {
4852 for (size_t i = 0; i < e->arguments->dim; i++)
4853 {
4854 Expression *ea = (*e->arguments)[i];
4855 ea->accept(this);
4856 if (result)
4857 return;
4858 }
4859 }
4860 }
4861
4862 void visit(CastExp *e)
4863 {
4864 //printf("CastExp::reliesOnTident('%s')\n", e->toChars());
4865 visit((UnaExp *)e);
4866 // e.to can be null for cast() with no type
4867 if (!result && e->to)
4868 e->to->accept(this);
4869 }
4870
4871 void visit(SliceExp *e)
4872 {
4873 //printf("SliceExp::reliesOnTident('%s')\n", e->toChars());
4874 visit((UnaExp *)e);
4875 if (!result && e->lwr)
4876 e->lwr->accept(this);
4877 if (!result && e->upr)
4878 e->upr->accept(this);
4879 }
4880
4881 void visit(IntervalExp *e)
4882 {
4883 //printf("IntervalExp::reliesOnTident('%s')\n", e->toChars());
4884 e->lwr->accept(this);
4885 if (!result)
4886 e->upr->accept(this);
4887 }
4888
4889 void visit(ArrayExp *e)
4890 {
4891 //printf("ArrayExp::reliesOnTident('%s')\n", e->toChars());
4892 visit((UnaExp *)e);
4893 if (!result && e->arguments)
4894 {
4895 for (size_t i = 0; i < e->arguments->dim; i++)
4896 {
4897 Expression *ea = (*e->arguments)[i];
4898 ea->accept(this);
4899 }
4900 }
4901 }
4902
4903 void visit(BinExp *e)
4904 {
4905 //printf("BinExp::reliesOnTident('%s')\n", e->toChars());
4906 e->e1->accept(this);
4907 if (!result)
4908 e->e2->accept(this);
4909 }
4910
4911 void visit(CondExp *e)
4912 {
4913 //printf("BinExp::reliesOnTident('%s')\n", e->toChars());
4914 e->econd->accept(this);
4915 if (!result)
4916 visit((BinExp *)e);
4917 }
4918 };
4919
4920 if (!t)
4921 return false;
4922
4923 ReliesOnTident v(tparams, iStart);
4924 t->accept(&v);
4925 return v.result;
4926}
4927
4928/* ======================== TemplateParameter =============================== */
4929
4930TemplateParameter::TemplateParameter(Loc loc, Identifier *ident)
4931{
4932 this->loc = loc;
4933 this->ident = ident;
4934 this->dependent = false;
4935}
4936
4937TemplateTypeParameter *TemplateParameter::isTemplateTypeParameter()
4938{
4939 return NULL;
4940}
4941
4942TemplateValueParameter *TemplateParameter::isTemplateValueParameter()
4943{
4944 return NULL;
4945}
4946
4947TemplateAliasParameter *TemplateParameter::isTemplateAliasParameter()
4948{
4949 return NULL;
4950}
4951
4952TemplateTupleParameter *TemplateParameter::isTemplateTupleParameter()
4953{
4954 return NULL;
4955}
4956
4957TemplateThisParameter *TemplateParameter::isTemplateThisParameter()
4958{
4959 return NULL;
4960}
4961
4962/*******************************************
4963 * Match to a particular TemplateParameter.
4964 * Input:
4965 * instLoc location that the template is instantiated.
4966 * tiargs[] actual arguments to template instance
4967 * i i'th argument
4968 * parameters[] template parameters
4969 * dedtypes[] deduced arguments to template instance
4970 * *psparam set to symbol declared and initialized to dedtypes[i]
4971 */
4972MATCH TemplateParameter::matchArg(Loc instLoc, Scope *sc, Objects *tiargs,
4973 size_t i, TemplateParameters *parameters, Objects *dedtypes,
4974 Declaration **psparam)
4975{
4976 RootObject *oarg;
4977
4978 if (i < tiargs->dim)
4979 oarg = (*tiargs)[i];
4980 else
4981 {
4982 // Get default argument instead
4983 oarg = defaultArg(instLoc, sc);
4984 if (!oarg)
4985 {
4986 assert(i < dedtypes->dim);
4987 // It might have already been deduced
4988 oarg = (*dedtypes)[i];
4989 if (!oarg)
4990 goto Lnomatch;
4991 }
4992 }
4993 return matchArg(sc, oarg, i, parameters, dedtypes, psparam);
4994
4995Lnomatch:
4996 if (psparam)
4997 *psparam = NULL;
4998 return MATCHnomatch;
4999}
5000
5001/* ======================== TemplateTypeParameter =========================== */
5002
5003// type-parameter
5004
5005Type *TemplateTypeParameter::tdummy = NULL;
5006
5007TemplateTypeParameter::TemplateTypeParameter(Loc loc, Identifier *ident, Type *specType,
5008 Type *defaultType)
5009 : TemplateParameter(loc, ident)
5010{
5011 this->ident = ident;
5012 this->specType = specType;
5013 this->defaultType = defaultType;
5014}
5015
5016TemplateTypeParameter *TemplateTypeParameter::isTemplateTypeParameter()
5017{
5018 return this;
5019}
5020
5021TemplateParameter *TemplateTypeParameter::syntaxCopy()
5022{
5023 return new TemplateTypeParameter(loc, ident,
5024 specType ? specType->syntaxCopy() : NULL,
5025 defaultType ? defaultType->syntaxCopy() : NULL);
5026}
5027
5028bool TemplateTypeParameter::declareParameter(Scope *sc)
5029{
5030 //printf("TemplateTypeParameter::declareParameter('%s')\n", ident->toChars());
5031 TypeIdentifier *ti = new TypeIdentifier(loc, ident);
5032 Declaration *ad = new AliasDeclaration(loc, ident, ti);
5033 return sc->insert(ad) != NULL;
5034}
5035
5036bool TemplateTypeParameter::semantic(Scope *sc, TemplateParameters *parameters)
5037{
5038 //printf("TemplateTypeParameter::semantic('%s')\n", ident->toChars());
5039 if (specType && !reliesOnTident(specType, parameters))
5040 {
5041 specType = specType->semantic(loc, sc);
5042 }
5043 return !(specType && isError(specType));
5044}
5045
5046MATCH TemplateTypeParameter::matchArg(Scope *sc, RootObject *oarg,
5047 size_t i, TemplateParameters *parameters, Objects *dedtypes,
5048 Declaration **psparam)
5049{
5050 //printf("TemplateTypeParameter::matchArg('%s')\n", ident->toChars());
5051 MATCH m = MATCHexact;
5052 Type *ta = isType(oarg);
5053 if (!ta)
5054 {
5055 //printf("%s %p %p %p\n", oarg->toChars(), isExpression(oarg), isDsymbol(oarg), isTuple(oarg));
5056 goto Lnomatch;
5057 }
5058 //printf("ta is %s\n", ta->toChars());
5059
5060 if (specType)
5061 {
5062 if (!ta || ta == tdummy)
5063 goto Lnomatch;
5064
5065 //printf("\tcalling deduceType(): ta is %s, specType is %s\n", ta->toChars(), specType->toChars());
5066 MATCH m2 = deduceType(ta, sc, specType, parameters, dedtypes);
5067 if (m2 <= MATCHnomatch)
5068 {
5069 //printf("\tfailed deduceType\n");
5070 goto Lnomatch;
5071 }
5072
5073 if (m2 < m)
5074 m = m2;
5075 if ((*dedtypes)[i])
5076 {
5077 Type *t = (Type *)(*dedtypes)[i];
5078
5079 if (dependent && !t->equals(ta)) // Bugzilla 14357
5080 goto Lnomatch;
5081
5082 /* This is a self-dependent parameter. For example:
5083 * template X(T : T*) {}
5084 * template X(T : S!T, alias S) {}
5085 */
5086 //printf("t = %s ta = %s\n", t->toChars(), ta->toChars());
5087 ta = t;
5088 }
5089 }
5090 else
5091 {
5092 if ((*dedtypes)[i])
5093 {
5094 // Must match already deduced type
5095 Type *t = (Type *)(*dedtypes)[i];
5096
5097 if (!t->equals(ta))
5098 {
5099 //printf("t = %s ta = %s\n", t->toChars(), ta->toChars());
5100 goto Lnomatch;
5101 }
5102 }
5103 else
5104 {
5105 // So that matches with specializations are better
5106 m = MATCHconvert;
5107 }
5108 }
5109 (*dedtypes)[i] = ta;
5110
5111 if (psparam)
5112 *psparam = new AliasDeclaration(loc, ident, ta);
5113 //printf("\tm = %d\n", m);
5114 return dependent ? MATCHexact : m;
5115
5116Lnomatch:
5117 if (psparam)
5118 *psparam = NULL;
5119 //printf("\tm = %d\n", MATCHnomatch);
5120 return MATCHnomatch;
5121}
5122
5123
5124void TemplateTypeParameter::print(RootObject *oarg, RootObject *oded)
5125{
5126 printf(" %s\n", ident->toChars());
5127
5128 Type *t = isType(oarg);
5129 Type *ta = isType(oded);
5130
5131 assert(ta);
5132
5133 if (specType)
5134 printf("\tSpecialization: %s\n", specType->toChars());
5135 if (defaultType)
5136 printf("\tDefault: %s\n", defaultType->toChars());
5137 printf("\tParameter: %s\n", t ? t->toChars() : "NULL");
5138 printf("\tDeduced Type: %s\n", ta->toChars());
5139}
5140
5141void *TemplateTypeParameter::dummyArg()
5142{
5143 Type *t = specType;
5144 if (!t)
5145 {
5146 // Use this for alias-parameter's too (?)
5147 if (!tdummy)
5148 tdummy = new TypeIdentifier(loc, ident);
5149 t = tdummy;
5150 }
5151 return (void *)t;
5152}
5153
5154
5155RootObject *TemplateTypeParameter::specialization()
5156{
5157 return specType;
5158}
5159
5160RootObject *TemplateTypeParameter::defaultArg(Loc, Scope *sc)
5161{
5162 Type *t = defaultType;
5163 if (t)
5164 {
5165 t = t->syntaxCopy();
5166 t = t->semantic(loc, sc); // use the parameter loc
5167 }
5168 return t;
5169}
5170
5171bool TemplateTypeParameter::hasDefaultArg()
5172{
5173 return defaultType != NULL;
5174}
5175
5176/* ======================== TemplateThisParameter =========================== */
5177
5178// this-parameter
5179
5180TemplateThisParameter::TemplateThisParameter(Loc loc, Identifier *ident,
5181 Type *specType,
5182 Type *defaultType)
5183 : TemplateTypeParameter(loc, ident, specType, defaultType)
5184{
5185}
5186
5187TemplateThisParameter *TemplateThisParameter::isTemplateThisParameter()
5188{
5189 return this;
5190}
5191
5192TemplateParameter *TemplateThisParameter::syntaxCopy()
5193{
5194 return new TemplateThisParameter(loc, ident,
5195 specType ? specType->syntaxCopy() : NULL,
5196 defaultType ? defaultType->syntaxCopy() : NULL);
5197}
5198
5199/* ======================== TemplateAliasParameter ========================== */
5200
5201// alias-parameter
5202
5203Dsymbol *TemplateAliasParameter::sdummy = NULL;
5204
5205TemplateAliasParameter::TemplateAliasParameter(Loc loc, Identifier *ident,
5206 Type *specType, RootObject *specAlias, RootObject *defaultAlias)
5207 : TemplateParameter(loc, ident)
5208{
5209 this->ident = ident;
5210 this->specType = specType;
5211 this->specAlias = specAlias;
5212 this->defaultAlias = defaultAlias;
5213}
5214
5215TemplateAliasParameter *TemplateAliasParameter::isTemplateAliasParameter()
5216{
5217 return this;
5218}
5219
5220TemplateParameter *TemplateAliasParameter::syntaxCopy()
5221{
5222 return new TemplateAliasParameter(loc, ident,
5223 specType ? specType->syntaxCopy() : NULL,
5224 objectSyntaxCopy(specAlias),
5225 objectSyntaxCopy(defaultAlias));
5226}
5227
5228bool TemplateAliasParameter::declareParameter(Scope *sc)
5229{
5230 TypeIdentifier *ti = new TypeIdentifier(loc, ident);
5231 Declaration *ad = new AliasDeclaration(loc, ident, ti);
5232 return sc->insert(ad) != NULL;
5233}
5234
5235static RootObject *aliasParameterSemantic(Loc loc, Scope *sc, RootObject *o, TemplateParameters *parameters)
5236{
5237 if (o)
5238 {
5239 Expression *ea = isExpression(o);
5240 Type *ta = isType(o);
5241 if (ta && (!parameters || !reliesOnTident(ta, parameters)))
5242 {
5243 Dsymbol *s = ta->toDsymbol(sc);
5244 if (s)
5245 o = s;
5246 else
5247 o = ta->semantic(loc, sc);
5248 }
5249 else if (ea)
5250 {
5251 sc = sc->startCTFE();
5252 ea = ::semantic(ea, sc);
5253 sc = sc->endCTFE();
5254 o = ea->ctfeInterpret();
5255 }
5256 }
5257 return o;
5258}
5259
5260bool TemplateAliasParameter::semantic(Scope *sc, TemplateParameters *parameters)
5261{
5262 if (specType && !reliesOnTident(specType, parameters))
5263 {
5264 specType = specType->semantic(loc, sc);
5265 }
5266 specAlias = aliasParameterSemantic(loc, sc, specAlias, parameters);
5267 return !(specType && isError(specType)) &&
5268 !(specAlias && isError(specAlias));
5269}
5270
5271MATCH TemplateAliasParameter::matchArg(Scope *sc, RootObject *oarg,
5272 size_t i, TemplateParameters *parameters, Objects *dedtypes,
5273 Declaration **psparam)
5274{
5275 //printf("TemplateAliasParameter::matchArg('%s')\n", ident->toChars());
5276 MATCH m = MATCHexact;
5277 Type *ta = isType(oarg);
5278 RootObject *sa = ta && !ta->deco ? NULL : getDsymbol(oarg);
5279 Expression *ea = isExpression(oarg);
5280 if (ea && (ea->op == TOKthis || ea->op == TOKsuper))
5281 sa = ((ThisExp *)ea)->var;
5282 else if (ea && ea->op == TOKscope)
5283 sa = ((ScopeExp *)ea)->sds;
5284 if (sa)
5285 {
5286 if (((Dsymbol *)sa)->isAggregateDeclaration())
5287 m = MATCHconvert;
5288
5289 /* specType means the alias must be a declaration with a type
5290 * that matches specType.
5291 */
5292 if (specType)
5293 {
5294 Declaration *d = ((Dsymbol *)sa)->isDeclaration();
5295 if (!d)
5296 goto Lnomatch;
5297 if (!d->type->equals(specType))
5298 goto Lnomatch;
5299 }
5300 }
5301 else
5302 {
5303 sa = oarg;
5304 if (ea)
5305 {
5306 if (specType)
5307 {
5308 if (!ea->type->equals(specType))
5309 goto Lnomatch;
5310 }
5311 }
5312 else if (ta && ta->ty == Tinstance && !specAlias)
5313 {
5314 /* Bugzilla xxxxx: Specialized parameter should be prefeerd
5315 * match to the template type parameter.
5316 * template X(alias a) {} // a == this
5317 * template X(alias a : B!A, alias B, A...) {} // B!A => ta
5318 */
5319 }
5320 else if (sa && sa == TemplateTypeParameter::tdummy)
5321 {
5322 /* Bugzilla 2025: Aggregate Types should preferentially
5323 * match to the template type parameter.
5324 * template X(alias a) {} // a == this
5325 * template X(T) {} // T => sa
5326 */
5327 }
5328 else
5329 goto Lnomatch;
5330 }
5331
5332 if (specAlias)
5333 {
5334 if (sa == sdummy)
5335 goto Lnomatch;
5336 Dsymbol *sx = isDsymbol(sa);
5337 if (sa != specAlias && sx)
5338 {
5339 Type *talias = isType(specAlias);
5340 if (!talias)
5341 goto Lnomatch;
5342
5343 TemplateInstance *ti = sx->isTemplateInstance();
5344 if (!ti && sx->parent)
5345 {
5346 ti = sx->parent->isTemplateInstance();
5347 if (ti && ti->name != sx->ident)
5348 goto Lnomatch;
5349 }
5350 if (!ti)
5351 goto Lnomatch;
5352
5353 Type *t = new TypeInstance(Loc(), ti);
5354 MATCH m2 = deduceType(t, sc, talias, parameters, dedtypes);
5355 if (m2 <= MATCHnomatch)
5356 goto Lnomatch;
5357 }
5358 }
5359 else if ((*dedtypes)[i])
5360 {
5361 // Must match already deduced symbol
5362 RootObject *si = (*dedtypes)[i];
5363 if (!sa || si != sa)
5364 goto Lnomatch;
5365 }
5366 (*dedtypes)[i] = sa;
5367
5368 if (psparam)
5369 {
5370 if (Dsymbol *s = isDsymbol(sa))
5371 {
5372 *psparam = new AliasDeclaration(loc, ident, s);
5373 }
5374 else if (Type *t = isType(sa))
5375 {
5376 *psparam = new AliasDeclaration(loc, ident, t);
5377 }
5378 else
5379 {
5380 assert(ea);
5381
5382 // Declare manifest constant
5383 Initializer *init = new ExpInitializer(loc, ea);
5384 VarDeclaration *v = new VarDeclaration(loc, NULL, ident, init);
5385 v->storage_class = STCmanifest;
5386 v->semantic(sc);
5387 *psparam = v;
5388 }
5389 }
5390 return dependent ? MATCHexact : m;
5391
5392Lnomatch:
5393 if (psparam)
5394 *psparam = NULL;
5395 //printf("\tm = %d\n", MATCHnomatch);
5396 return MATCHnomatch;
5397}
5398
5399
5400void TemplateAliasParameter::print(RootObject *, RootObject *oded)
5401{
5402 printf(" %s\n", ident->toChars());
5403
5404 Dsymbol *sa = isDsymbol(oded);
5405 assert(sa);
5406
5407 printf("\tParameter alias: %s\n", sa->toChars());
5408}
5409
5410void *TemplateAliasParameter::dummyArg()
5411{
5412 RootObject *s = specAlias;
5413 if (!s)
5414 {
5415 if (!sdummy)
5416 sdummy = new Dsymbol();
5417 s = sdummy;
5418 }
5419 return (void*)s;
5420}
5421
5422
5423RootObject *TemplateAliasParameter::specialization()
5424{
5425 return specAlias;
5426}
5427
5428RootObject *TemplateAliasParameter::defaultArg(Loc, Scope *sc)
5429{
5430 RootObject *da = defaultAlias;
5431 Type *ta = isType(defaultAlias);
5432 if (ta)
5433 {
5434 if (ta->ty == Tinstance)
5435 {
5436 // If the default arg is a template, instantiate for each type
5437 da = ta->syntaxCopy();
5438 }
5439 }
5440
5441 RootObject *o = aliasParameterSemantic(loc, sc, da, NULL); // use the parameter loc
5442 return o;
5443}
5444
5445bool TemplateAliasParameter::hasDefaultArg()
5446{
5447 return defaultAlias != NULL;
5448}
5449
5450/* ======================== TemplateValueParameter ========================== */
5451
5452// value-parameter
5453
5454AA *TemplateValueParameter::edummies = NULL;
5455
5456TemplateValueParameter::TemplateValueParameter(Loc loc, Identifier *ident, Type *valType,
5457 Expression *specValue, Expression *defaultValue)
5458 : TemplateParameter(loc, ident)
5459{
5460 this->ident = ident;
5461 this->valType = valType;
5462 this->specValue = specValue;
5463 this->defaultValue = defaultValue;
5464}
5465
5466TemplateValueParameter *TemplateValueParameter::isTemplateValueParameter()
5467{
5468 return this;
5469}
5470
5471TemplateParameter *TemplateValueParameter::syntaxCopy()
5472{
5473 return new TemplateValueParameter(loc, ident,
5474 valType->syntaxCopy(),
5475 specValue ? specValue->syntaxCopy() : NULL,
5476 defaultValue ? defaultValue->syntaxCopy() : NULL);
5477}
5478
5479bool TemplateValueParameter::declareParameter(Scope *sc)
5480{
5481 VarDeclaration *v = new VarDeclaration(loc, valType, ident, NULL);
5482 v->storage_class = STCtemplateparameter;
5483 return sc->insert(v) != NULL;
5484}
5485
5486bool TemplateValueParameter::semantic(Scope *sc, TemplateParameters *)
5487{
5488 valType = valType->semantic(loc, sc);
5489
5490 return !isError(valType);
5491}
5492
5493MATCH TemplateValueParameter::matchArg(Scope *sc, RootObject *oarg,
5494 size_t i, TemplateParameters *, Objects *dedtypes, Declaration **psparam)
5495{
5496 //printf("TemplateValueParameter::matchArg('%s')\n", ident->toChars());
5497
5498 MATCH m = MATCHexact;
5499
5500 Expression *ei = isExpression(oarg);
5501 Type *vt;
5502
5503 if (!ei && oarg)
5504 {
5505 Dsymbol *si = isDsymbol(oarg);
5506 FuncDeclaration *f = si ? si->isFuncDeclaration() : NULL;
5507 if (!f || !f->fbody || f->needThis())
5508 goto Lnomatch;
5509
5510 ei = new VarExp(loc, f);
5511 ei = ::semantic(ei, sc);
5512
5513 /* If a function is really property-like, and then
5514 * it's CTFEable, ei will be a literal expression.
5515 */
5516 unsigned int olderrors = global.startGagging();
5517 ei = resolveProperties(sc, ei);
5518 ei = ei->ctfeInterpret();
5519 if (global.endGagging(olderrors) || ei->op == TOKerror)
5520 goto Lnomatch;
5521
5522 /* Bugzilla 14520: A property-like function can match to both
5523 * TemplateAlias and ValueParameter. But for template overloads,
5524 * it should always prefer alias parameter to be consistent
5525 * template match result.
5526 *
5527 * template X(alias f) { enum X = 1; }
5528 * template X(int val) { enum X = 2; }
5529 * int f1() { return 0; } // CTFEable
5530 * int f2(); // body-less function is not CTFEable
5531 * enum x1 = X!f1; // should be 1
5532 * enum x2 = X!f2; // should be 1
5533 *
5534 * e.g. The x1 value must be same even if the f1 definition will be moved
5535 * into di while stripping body code.
5536 */
5537 m = MATCHconvert;
5538 }
5539
5540 if (ei && ei->op == TOKvar)
5541 {
5542 // Resolve const variables that we had skipped earlier
5543 ei = ei->ctfeInterpret();
5544 }
5545
5546 //printf("\tvalType: %s, ty = %d\n", valType->toChars(), valType->ty);
5547 vt = valType->semantic(loc, sc);
5548 //printf("ei: %s, ei->type: %s\n", ei->toChars(), ei->type->toChars());
5549 //printf("vt = %s\n", vt->toChars());
5550
5551 if (ei->type)
5552 {
5553 MATCH m2 = ei->implicitConvTo(vt);
5554 //printf("m: %d\n", m);
5555 if (m2 < m)
5556 m = m2;
5557 if (m <= MATCHnomatch)
5558 goto Lnomatch;
5559 ei = ei->implicitCastTo(sc, vt);
5560 ei = ei->ctfeInterpret();
5561 }
5562
5563 if (specValue)
5564 {
5565 if (!ei || (Expression *)dmd_aaGetRvalue(edummies, (void *)ei->type) == ei)
5566 goto Lnomatch;
5567
5568 Expression *e = specValue;
5569
5570 sc = sc->startCTFE();
5571 e = ::semantic(e, sc);
5572 e = resolveProperties(sc, e);
5573 sc = sc->endCTFE();
5574 e = e->implicitCastTo(sc, vt);
5575 e = e->ctfeInterpret();
5576
5577 ei = ei->syntaxCopy();
5578 sc = sc->startCTFE();
5579 ei = ::semantic(ei, sc);
5580 sc = sc->endCTFE();
5581 ei = ei->implicitCastTo(sc, vt);
5582 ei = ei->ctfeInterpret();
5583 //printf("\tei: %s, %s\n", ei->toChars(), ei->type->toChars());
5584 //printf("\te : %s, %s\n", e->toChars(), e->type->toChars());
5585 if (!ei->equals(e))
5586 goto Lnomatch;
5587 }
5588 else
5589 {
5590 if ((*dedtypes)[i])
5591 {
5592 // Must match already deduced value
5593 Expression *e = (Expression *)(*dedtypes)[i];
5594
5595 if (!ei || !ei->equals(e))
5596 goto Lnomatch;
5597 }
5598 }
5599 (*dedtypes)[i] = ei;
5600
5601 if (psparam)
5602 {
5603 Initializer *init = new ExpInitializer(loc, ei);
5604 Declaration *sparam = new VarDeclaration(loc, vt, ident, init);
5605 sparam->storage_class = STCmanifest;
5606 *psparam = sparam;
5607 }
5608 return dependent ? MATCHexact : m;
5609
5610Lnomatch:
5611 //printf("\tno match\n");
5612 if (psparam)
5613 *psparam = NULL;
5614 return MATCHnomatch;
5615}
5616
5617
5618void TemplateValueParameter::print(RootObject *, RootObject *oded)
5619{
5620 printf(" %s\n", ident->toChars());
5621
5622 Expression *ea = isExpression(oded);
5623
5624 if (specValue)
5625 printf("\tSpecialization: %s\n", specValue->toChars());
5626 printf("\tParameter Value: %s\n", ea ? ea->toChars() : "NULL");
5627}
5628
5629void *TemplateValueParameter::dummyArg()
5630{
5631 Expression *e = specValue;
5632 if (!e)
5633 {
5634 // Create a dummy value
5635 Expression **pe = (Expression **)dmd_aaGet(&edummies, (void *)valType);
5636 if (!*pe)
5637 *pe = valType->defaultInit();
5638 e = *pe;
5639 }
5640 return (void *)e;
5641}
5642
5643
5644RootObject *TemplateValueParameter::specialization()
5645{
5646 return specValue;
5647}
5648
5649RootObject *TemplateValueParameter::defaultArg(Loc instLoc, Scope *sc)
5650{
5651 Expression *e = defaultValue;
5652 if (e)
5653 {
5654 e = e->syntaxCopy();
5655 if ((e = ::semantic(e, sc)) == NULL)
5656 return NULL;
5657 if ((e = resolveProperties(sc, e)) == NULL)
5658 return NULL;
5659 e = e->resolveLoc(instLoc, sc); // use the instantiated loc
5660 e = e->optimize(WANTvalue);
5661 }
5662 return e;
5663}
5664
5665bool TemplateValueParameter::hasDefaultArg()
5666{
5667 return defaultValue != NULL;
5668}
5669
5670/* ======================== TemplateTupleParameter ========================== */
5671
5672// variadic-parameter
5673
5674TemplateTupleParameter::TemplateTupleParameter(Loc loc, Identifier *ident)
5675 : TemplateParameter(loc, ident)
5676{
5677 this->ident = ident;
5678}
5679
5680TemplateTupleParameter *TemplateTupleParameter::isTemplateTupleParameter()
5681{
5682 return this;
5683}
5684
5685TemplateParameter *TemplateTupleParameter::syntaxCopy()
5686{
5687 return new TemplateTupleParameter(loc, ident);
5688}
5689
5690bool TemplateTupleParameter::declareParameter(Scope *sc)
5691{
5692 TypeIdentifier *ti = new TypeIdentifier(loc, ident);
5693 Declaration *ad = new AliasDeclaration(loc, ident, ti);
5694 return sc->insert(ad) != NULL;
5695}
5696
5697bool TemplateTupleParameter::semantic(Scope *, TemplateParameters *)
5698{
5699 return true;
5700}
5701
5702MATCH TemplateTupleParameter::matchArg(Loc, Scope *sc, Objects *tiargs,
5703 size_t i, TemplateParameters *parameters, Objects *dedtypes,
5704 Declaration **psparam)
5705{
5706 /* The rest of the actual arguments (tiargs[]) form the match
5707 * for the variadic parameter.
5708 */
5709 assert(i + 1 == dedtypes->dim); // must be the last one
5710 Tuple *ovar;
5711
5712 if (Tuple *u = isTuple((*dedtypes)[i]))
5713 {
5714 // It has already been deduced
5715 ovar = u;
5716 }
5717 else if (i + 1 == tiargs->dim && isTuple((*tiargs)[i]))
5718 ovar = isTuple((*tiargs)[i]);
5719 else
5720 {
5721 ovar = new Tuple();
5722 //printf("ovar = %p\n", ovar);
5723 if (i < tiargs->dim)
5724 {
5725 //printf("i = %d, tiargs->dim = %d\n", i, tiargs->dim);
5726 ovar->objects.setDim(tiargs->dim - i);
5727 for (size_t j = 0; j < ovar->objects.dim; j++)
5728 ovar->objects[j] = (*tiargs)[i + j];
5729 }
5730 }
5731 return matchArg(sc, ovar, i, parameters, dedtypes, psparam);
5732}
5733
5734MATCH TemplateTupleParameter::matchArg(Scope *, RootObject *oarg,
5735 size_t i, TemplateParameters *, Objects *dedtypes, Declaration **psparam)
5736{
5737 //printf("TemplateTupleParameter::matchArg('%s')\n", ident->toChars());
5738 Tuple *ovar = isTuple(oarg);
5739 if (!ovar)
5740 return MATCHnomatch;
5741 if ((*dedtypes)[i])
5742 {
5743 Tuple *tup = isTuple((*dedtypes)[i]);
5744 if (!tup)
5745 return MATCHnomatch;
5746 if (!match(tup, ovar))
5747 return MATCHnomatch;
5748 }
5749 (*dedtypes)[i] = ovar;
5750
5751 if (psparam)
5752 *psparam = new TupleDeclaration(loc, ident, &ovar->objects);
5753 return dependent ? MATCHexact : MATCHconvert;
5754}
5755
5756
5757void TemplateTupleParameter::print(RootObject *, RootObject *oded)
5758{
5759 printf(" %s... [", ident->toChars());
5760 Tuple *v = isTuple(oded);
5761 assert(v);
5762
5763 //printf("|%d| ", v->objects.dim);
5764 for (size_t i = 0; i < v->objects.dim; i++)
5765 {
5766 if (i)
5767 printf(", ");
5768
5769 RootObject *o = v->objects[i];
5770
5771 Dsymbol *sa = isDsymbol(o);
5772 if (sa)
5773 printf("alias: %s", sa->toChars());
5774
5775 Type *ta = isType(o);
5776 if (ta)
5777 printf("type: %s", ta->toChars());
5778
5779 Expression *ea = isExpression(o);
5780 if (ea)
5781 printf("exp: %s", ea->toChars());
5782
5783 assert(!isTuple(o)); // no nested Tuple arguments
5784 }
5785
5786 printf("]\n");
5787}
5788
5789void *TemplateTupleParameter::dummyArg()
5790{
5791 return NULL;
5792}
5793
5794
5795RootObject *TemplateTupleParameter::specialization()
5796{
5797 return NULL;
5798}
5799
5800RootObject *TemplateTupleParameter::defaultArg(Loc, Scope *)
5801{
5802 return NULL;
5803}
5804
5805bool TemplateTupleParameter::hasDefaultArg()
5806{
5807 return false;
5808}
5809
5810/* ======================== TemplateInstance ================================ */
5811
5812TemplateInstance::TemplateInstance(Loc loc, Identifier *ident)
5813 : ScopeDsymbol(NULL)
5814{
5815 this->loc = loc;
5816 this->name = ident;
5817 this->tiargs = NULL;
5818 this->tempdecl = NULL;
5819 this->inst = NULL;
5820 this->tinst = NULL;
5821 this->tnext = NULL;
5822 this->minst = NULL;
5823 this->deferred = NULL;
5824 this->memberOf = NULL;
5825 this->argsym = NULL;
5826 this->aliasdecl = NULL;
5827 this->semantictiargsdone = false;
5828 this->inuse = 0;
5829 this->nest = 0;
5830 this->havetempdecl = false;
5831 this->enclosing = NULL;
5832 this->gagged = false;
5833 this->hash = 0;
5834 this->fargs = NULL;
5835}
5836
5837/*****************
5838 * This constructor is only called when we figured out which function
5839 * template to instantiate.
5840 */
5841
5842TemplateInstance::TemplateInstance(Loc loc, TemplateDeclaration *td, Objects *tiargs)
5843 : ScopeDsymbol(NULL)
5844{
5845 this->loc = loc;
5846 this->name = td->ident;
5847 this->tiargs = tiargs;
5848 this->tempdecl = td;
5849 this->inst = NULL;
5850 this->tinst = NULL;
5851 this->tnext = NULL;
5852 this->minst = NULL;
5853 this->deferred = NULL;
5854 this->memberOf = NULL;
5855 this->argsym = NULL;
5856 this->aliasdecl = NULL;
5857 this->semantictiargsdone = true;
5858 this->inuse = 0;
5859 this->nest = 0;
5860 this->havetempdecl = true;
5861 this->enclosing = NULL;
5862 this->gagged = false;
5863 this->hash = 0;
5864 this->fargs = NULL;
5865
5866 assert(tempdecl->_scope);
5867}
5868
5869
5870Objects *TemplateInstance::arraySyntaxCopy(Objects *objs)
5871{
5872 Objects *a = NULL;
5873 if (objs)
5874 {
5875 a = new Objects();
5876 a->setDim(objs->dim);
5877 for (size_t i = 0; i < objs->dim; i++)
5878 (*a)[i] = objectSyntaxCopy((*objs)[i]);
5879 }
5880 return a;
5881}
5882
5883Dsymbol *TemplateInstance::syntaxCopy(Dsymbol *s)
5884{
5885 TemplateInstance *ti =
5886 s ? (TemplateInstance *)s
5887 : new TemplateInstance(loc, name);
5888 ti->tiargs = arraySyntaxCopy(tiargs);
5889 TemplateDeclaration *td;
5890 if (inst && tempdecl && (td = tempdecl->isTemplateDeclaration()) != NULL)
5891 td->ScopeDsymbol::syntaxCopy(ti);
5892 else
5893 ScopeDsymbol::syntaxCopy(ti);
5894 return ti;
5895}
5896
5897void TemplateInstance::semantic(Scope *sc)
5898{
5899 semantic(sc, NULL);
5900}
5901
5902void TemplateInstance::expandMembers(Scope *sc2)
5903{
5904 for (size_t i = 0; i < members->dim; i++)
5905 {
5906 Dsymbol *s = (*members)[i];
5907 s->setScope(sc2);
5908 }
5909
5910 for (size_t i = 0; i < members->dim; i++)
5911 {
5912 Dsymbol *s = (*members)[i];
5913 s->importAll(sc2);
5914 }
5915
5916 for (size_t i = 0; i < members->dim; i++)
5917 {
5918 Dsymbol *s = (*members)[i];
5919 //printf("\t[%d] semantic on '%s' %p kind %s in '%s'\n", i, s->toChars(), s, s->kind(), this->toChars());
5920 //printf("test: enclosing = %d, sc2->parent = %s\n", enclosing, sc2->parent->toChars());
5921// if (enclosing)
5922// s->parent = sc->parent;
5923 //printf("test3: enclosing = %d, s->parent = %s\n", enclosing, s->parent->toChars());
5924 s->semantic(sc2);
5925 //printf("test4: enclosing = %d, s->parent = %s\n", enclosing, s->parent->toChars());
5926 Module::runDeferredSemantic();
5927 }
5928}
5929
5930void TemplateInstance::tryExpandMembers(Scope *sc2)
5931{
5932 static int nest;
5933 // extracted to a function to allow windows SEH to work without destructors in the same function
5934 //printf("%d\n", nest);
5935 if (++nest > 500)
5936 {
5937 global.gag = 0; // ensure error message gets printed
5938 error("recursive expansion");
5939 fatal();
5940 }
5941
5942 expandMembers(sc2);
5943
5944 nest--;
5945}
5946
5947void TemplateInstance::trySemantic3(Scope *sc2)
5948{
5949 // extracted to a function to allow windows SEH to work without destructors in the same function
5950 static int nest;
5951 //printf("%d\n", nest);
5952 if (++nest > 300)
5953 {
5954 global.gag = 0; // ensure error message gets printed
5955 error("recursive expansion");
5956 fatal();
5957 }
5958 semantic3(sc2);
5959
5960 --nest;
5961}
5962
5963void TemplateInstance::semantic(Scope *sc, Expressions *fargs)
5964{
5965 //printf("[%s] TemplateInstance::semantic('%s', this=%p, gag = %d, sc = %p)\n", loc.toChars(), toChars(), this, global.gag, sc);
5966 if (inst) // if semantic() was already run
5967 {
5968 return;
5969 }
5970 if (semanticRun != PASSinit)
5971 {
5972 Ungag ungag(global.gag);
5973 if (!gagged)
5974 global.gag = 0;
5975 error(loc, "recursive template expansion");
5976 if (gagged)
5977 semanticRun = PASSinit;
5978 else
5979 inst = this;
5980 errors = true;
5981 return;
5982 }
5983
5984 // Get the enclosing template instance from the scope tinst
5985 tinst = sc->tinst;
5986
5987 // Get the instantiating module from the scope minst
5988 minst = sc->minst;
5989 // Bugzilla 10920: If the enclosing function is non-root symbol,
5990 // this instance should be speculative.
5991 if (!tinst && sc->func && sc->func->inNonRoot())
5992 {
5993 minst = NULL;
5994 }
5995
5996 gagged = (global.gag > 0);
5997
5998 semanticRun = PASSsemantic;
5999
6000 /* Find template declaration first,
6001 * then run semantic on each argument (place results in tiargs[]),
6002 * last find most specialized template from overload list/set.
6003 */
6004 if (!findTempDecl(sc, NULL) ||
6005 !semanticTiargs(sc) ||
6006 !findBestMatch(sc, fargs))
6007 {
6008Lerror:
6009 if (gagged)
6010 {
6011 // Bugzilla 13220: Rollback status for later semantic re-running.
6012 semanticRun = PASSinit;
6013 }
6014 else
6015 inst = this;
6016 errors = true;
6017 return;
6018 }
6019 TemplateDeclaration *tempdecl = this->tempdecl->isTemplateDeclaration();
6020 assert(tempdecl);
6021
6022 // If tempdecl is a mixin, disallow it
6023 if (tempdecl->ismixin)
6024 {
6025 error("mixin templates are not regular templates");
6026 goto Lerror;
6027 }
6028
6029 hasNestedArgs(tiargs, tempdecl->isstatic);
6030 if (errors)
6031 goto Lerror;
6032
6033 /* See if there is an existing TemplateInstantiation that already
6034 * implements the typeargs. If so, just refer to that one instead.
6035 */
6036 inst = tempdecl->findExistingInstance(this, fargs);
6037 TemplateInstance *errinst = NULL;
6038 if (!inst)
6039 {
6040 // So, we need to implement 'this' instance.
6041 }
6042 else if (inst->gagged && !gagged && inst->errors)
6043 {
6044 // If the first instantiation had failed, re-run semantic,
6045 // so that error messages are shown.
6046 errinst = inst;
6047 }
6048 else
6049 {
6050 // It's a match
6051 parent = inst->parent;
6052 errors = inst->errors;
6053
6054 // If both this and the previous instantiation were gagged,
6055 // use the number of errors that happened last time.
6056 global.errors += errors;
6057 global.gaggedErrors += errors;
6058
6059 // If the first instantiation was gagged, but this is not:
6060 if (inst->gagged)
6061 {
6062 // It had succeeded, mark it is a non-gagged instantiation,
6063 // and reuse it.
6064 inst->gagged = gagged;
6065 }
6066
6067 this->tnext = inst->tnext;
6068 inst->tnext = this;
6069
6070 /* A module can have explicit template instance and its alias
6071 * in module scope (e,g, `alias Base64 = Base64Impl!('+', '/');`).
6072 * If the first instantiation 'inst' had happened in non-root module,
6073 * compiler can assume that its instantiated code would be included
6074 * in the separately compiled obj/lib file (e.g. phobos.lib).
6075 *
6076 * However, if 'this' second instantiation happened in root module,
6077 * compiler might need to invoke its codegen (Bugzilla 2500 & 2644).
6078 * But whole import graph is not determined until all semantic pass finished,
6079 * so 'inst' should conservatively finish the semantic3 pass for the codegen.
6080 */
6081 if (minst && minst->isRoot() && !(inst->minst && inst->minst->isRoot()))
6082 {
6083 /* Swap the position of 'inst' and 'this' in the instantiation graph.
6084 * Then, the primary instance `inst` will be changed to a root instance.
6085 *
6086 * Before:
6087 * non-root -> A!() -> B!()[inst] -> C!()
6088 * |
6089 * root -> D!() -> B!()[this]
6090 *
6091 * After:
6092 * non-root -> A!() -> B!()[this]
6093 * |
6094 * root -> D!() -> B!()[inst] -> C!()
6095 */
6096 Module *mi = minst;
6097 TemplateInstance *ti = tinst;
6098 minst = inst->minst;
6099 tinst = inst->tinst;
6100 inst->minst = mi;
6101 inst->tinst = ti;
6102
6103 if (minst) // if inst was not speculative
6104 {
6105 /* Add 'inst' once again to the root module members[], then the
6106 * instance members will get codegen chances.
6107 */
6108 inst->appendToModuleMember();
6109 }
6110 }
6111
6112 return;
6113 }
6114 unsigned errorsave = global.errors;
6115
6116 inst = this;
6117 parent = enclosing ? enclosing : tempdecl->parent;
6118 //printf("parent = '%s'\n", parent->kind());
6119
6120 TemplateInstance *tempdecl_instance_idx = tempdecl->addInstance(this);
6121
6122 //getIdent();
6123
6124 // Store the place we added it to in target_symbol_list(_idx) so we can
6125 // remove it later if we encounter an error.
6126 Dsymbols *target_symbol_list = appendToModuleMember();
6127 size_t target_symbol_list_idx = target_symbol_list ? target_symbol_list->dim - 1 : 0;
6128
6129 // Copy the syntax trees from the TemplateDeclaration
6130 members = Dsymbol::arraySyntaxCopy(tempdecl->members);
6131
6132 // resolve TemplateThisParameter
6133 for (size_t i = 0; i < tempdecl->parameters->dim; i++)
6134 {
6135 if ((*tempdecl->parameters)[i]->isTemplateThisParameter() == NULL)
6136 continue;
6137 Type *t = isType((*tiargs)[i]);
6138 assert(t);
6139 if (StorageClass stc = ModToStc(t->mod))
6140 {
6141 //printf("t = %s, stc = x%llx\n", t->toChars(), stc);
6142 Dsymbols *s = new Dsymbols();
6143 s->push(new StorageClassDeclaration(stc, members));
6144 members = s;
6145 }
6146 break;
6147 }
6148
6149 // Create our own scope for the template parameters
6150 Scope *scope = tempdecl->_scope;
6151 if (tempdecl->semanticRun == PASSinit)
6152 {
6153 error("template instantiation %s forward references template declaration %s", toChars(), tempdecl->toChars());
6154 return;
6155 }
6156
6157 argsym = new ScopeDsymbol();
6158 argsym->parent = scope->parent;
6159 scope = scope->push(argsym);
6160 scope->tinst = this;
6161 scope->minst = minst;
6162 //scope->stc = 0;
6163
6164 // Declare each template parameter as an alias for the argument type
6165 Scope *paramscope = scope->push();
6166 paramscope->stc = 0;
6167 paramscope->protection = Prot(PROTpublic); // Bugzilla 14169: template parameters should be public
6168 declareParameters(paramscope);
6169 paramscope->pop();
6170
6171 // Add members of template instance to template instance symbol table
6172// parent = scope->scopesym;
6173 symtab = new DsymbolTable();
6174 for (size_t i = 0; i < members->dim; i++)
6175 {
6176 Dsymbol *s = (*members)[i];
6177 s->addMember(scope, this);
6178 }
6179
6180 /* See if there is only one member of template instance, and that
6181 * member has the same name as the template instance.
6182 * If so, this template instance becomes an alias for that member.
6183 */
6184 //printf("members->dim = %d\n", members->dim);
6185 if (members->dim)
6186 {
6187 Dsymbol *s;
6188 if (Dsymbol::oneMembers(members, &s, tempdecl->ident) && s)
6189 {
6190 //printf("tempdecl->ident = %s, s = '%s'\n", tempdecl->ident->toChars(), s->kind(), s->toPrettyChars());
6191 //printf("setting aliasdecl\n");
6192 aliasdecl = s;
6193 }
6194 }
6195
6196 /* If function template declaration
6197 */
6198 if (fargs && aliasdecl)
6199 {
6200 FuncDeclaration *fd = aliasdecl->isFuncDeclaration();
6201 if (fd)
6202 {
6203 /* Transmit fargs to type so that TypeFunction::semantic() can
6204 * resolve any "auto ref" storage classes.
6205 */
6206 TypeFunction *tf = (TypeFunction *)fd->type;
6207 if (tf && tf->ty == Tfunction)
6208 tf->fargs = fargs;
6209 }
6210 }
6211
6212 // Do semantic() analysis on template instance members
6213 Scope *sc2;
6214 sc2 = scope->push(this);
6215 //printf("enclosing = %d, sc->parent = %s\n", enclosing, sc->parent->toChars());
6216 sc2->parent = this;
6217 sc2->tinst = this;
6218 sc2->minst = minst;
6219
6220 tryExpandMembers(sc2);
6221
6222 semanticRun = PASSsemanticdone;
6223
6224 /* ConditionalDeclaration may introduce eponymous declaration,
6225 * so we should find it once again after semantic.
6226 */
6227 if (members->dim)
6228 {
6229 Dsymbol *s;
6230 if (Dsymbol::oneMembers(members, &s, tempdecl->ident) && s)
6231 {
6232 if (!aliasdecl || aliasdecl != s)
6233 {
6234 //printf("tempdecl->ident = %s, s = '%s'\n", tempdecl->ident->toChars(), s->kind(), s->toPrettyChars());
6235 //printf("setting aliasdecl 2\n");
6236 aliasdecl = s;
6237 }
6238 }
6239 }
6240
6241 if (global.errors != errorsave)
6242 goto Laftersemantic;
6243
6244 /* If any of the instantiation members didn't get semantic() run
6245 * on them due to forward references, we cannot run semantic2()
6246 * or semantic3() yet.
6247 */
6248 {
6249 bool found_deferred_ad = false;
6250 for (size_t i = 0; i < Module::deferred.dim; i++)
6251 {
6252 Dsymbol *sd = Module::deferred[i];
6253 AggregateDeclaration *ad = sd->isAggregateDeclaration();
6254 if (ad && ad->parent && ad->parent->isTemplateInstance())
6255 {
6256 //printf("deferred template aggregate: %s %s\n",
6257 // sd->parent->toChars(), sd->toChars());
6258 found_deferred_ad = true;
6259 if (ad->parent == this)
6260 {
6261 ad->deferred = this;
6262 break;
6263 }
6264 }
6265 }
6266 if (found_deferred_ad || Module::deferred.dim)
6267 goto Laftersemantic;
6268 }
6269
6270 /* The problem is when to parse the initializer for a variable.
6271 * Perhaps VarDeclaration::semantic() should do it like it does
6272 * for initializers inside a function.
6273 */
6274 //if (sc->parent->isFuncDeclaration())
6275 {
6276 /* BUG 782: this has problems if the classes this depends on
6277 * are forward referenced. Find a way to defer semantic()
6278 * on this template.
6279 */
6280 semantic2(sc2);
6281 }
6282 if (global.errors != errorsave)
6283 goto Laftersemantic;
6284
6285 if ((sc->func || (sc->flags & SCOPEfullinst)) && !tinst)
6286 {
6287 /* If a template is instantiated inside function, the whole instantiation
6288 * should be done at that position. But, immediate running semantic3 of
6289 * dependent templates may cause unresolved forward reference (Bugzilla 9050).
6290 * To avoid the issue, don't run semantic3 until semantic and semantic2 done.
6291 */
6292 TemplateInstances deferred;
6293 this->deferred = &deferred;
6294
6295 //printf("Run semantic3 on %s\n", toChars());
6296 trySemantic3(sc2);
6297
6298 for (size_t i = 0; i < deferred.dim; i++)
6299 {
6300 //printf("+ run deferred semantic3 on %s\n", deferred[i]->toChars());
6301 deferred[i]->semantic3(NULL);
6302 }
6303
6304 this->deferred = NULL;
6305 }
6306 else if (tinst)
6307 {
6308 bool doSemantic3 = false;
6309 if (sc->func && aliasdecl && aliasdecl->toAlias()->isFuncDeclaration())
6310 {
6311 /* Template function instantiation should run semantic3 immediately
6312 * for attribute inference.
6313 */
6314 trySemantic3(sc2);
6315 }
6316 else if (sc->func)
6317 {
6318 /* A lambda function in template arguments might capture the
6319 * instantiated scope context. For the correct context inference,
6320 * all instantiated functions should run the semantic3 immediately.
6321 * See also compilable/test14973.d
6322 */
6323 for (size_t i = 0; i < tdtypes.dim; i++)
6324 {
6325 RootObject *oarg = tdtypes[i];
6326 Dsymbol *s = getDsymbol(oarg);
6327 if (!s)
6328 continue;
6329
6330 if (TemplateDeclaration *td = s->isTemplateDeclaration())
6331 {
6332 if (!td->literal)
6333 continue;
6334 assert(td->members && td->members->dim == 1);
6335 s = (*td->members)[0];
6336 }
6337 if (FuncLiteralDeclaration *fld = s->isFuncLiteralDeclaration())
6338 {
6339 if (fld->tok == TOKreserved)
6340 {
6341 doSemantic3 = true;
6342 break;
6343 }
6344 }
6345 }
6346 //printf("[%s] %s doSemantic3 = %d\n", loc.toChars(), toChars(), doSemantic3);
6347 }
6348 if (doSemantic3)
6349 trySemantic3(sc2);
6350
6351 TemplateInstance *ti = tinst;
6352 int nest = 0;
6353 while (ti && !ti->deferred && ti->tinst)
6354 {
6355 ti = ti->tinst;
6356 if (++nest > 500)
6357 {
6358 global.gag = 0; // ensure error message gets printed
6359 error("recursive expansion");
6360 fatal();
6361 }
6362 }
6363 if (ti && ti->deferred)
6364 {
6365 //printf("deferred semantic3 of %p %s, ti = %s, ti->deferred = %p\n", this, toChars(), ti->toChars());
6366 for (size_t i = 0; ; i++)
6367 {
6368 if (i == ti->deferred->dim)
6369 {
6370 ti->deferred->push(this);
6371 break;
6372 }
6373 if ((*ti->deferred)[i] == this)
6374 break;
6375 }
6376 }
6377 }
6378
6379 if (aliasdecl)
6380 {
6381 /* Bugzilla 13816: AliasDeclaration tries to resolve forward reference
6382 * twice (See inuse check in AliasDeclaration::toAlias()). It's
6383 * necessary to resolve mutual references of instantiated symbols, but
6384 * it will left a true recursive alias in tuple declaration - an
6385 * AliasDeclaration A refers TupleDeclaration B, and B contains A
6386 * in its elements. To correctly make it an error, we strictly need to
6387 * resolve the alias of eponymous member.
6388 */
6389 aliasdecl = aliasdecl->toAlias2();
6390 }
6391
6392 Laftersemantic:
6393 sc2->pop();
6394
6395 scope->pop();
6396
6397 // Give additional context info if error occurred during instantiation
6398 if (global.errors != errorsave)
6399 {
6400 if (!errors)
6401 {
6402 if (!tempdecl->literal)
6403 error(loc, "error instantiating");
6404 if (tinst)
6405 tinst->printInstantiationTrace();
6406 }
6407 errors = true;
6408 if (gagged)
6409 {
6410 // Errors are gagged, so remove the template instance from the
6411 // instance/symbol lists we added it to and reset our state to
6412 // finish clean and so we can try to instantiate it again later
6413 // (see bugzilla 4302 and 6602).
6414 tempdecl->removeInstance(tempdecl_instance_idx);
6415 if (target_symbol_list)
6416 {
6417 // Because we added 'this' in the last position above, we
6418 // should be able to remove it without messing other indices up.
6419 assert((*target_symbol_list)[target_symbol_list_idx] == this);
6420 target_symbol_list->remove(target_symbol_list_idx);
6421 memberOf = NULL; // no longer a member
6422 }
6423 semanticRun = PASSinit;
6424 inst = NULL;
6425 symtab = NULL;
6426 }
6427 }
6428 else if (errinst)
6429 {
6430 /* Bugzilla 14541: If the previous gagged instance had failed by
6431 * circular references, currrent "error reproduction instantiation"
6432 * might succeed, because of the difference of instantiated context.
6433 * On such case, the cached error instance needs to be overridden by the
6434 * succeeded instance.
6435 */
6436 //printf("replaceInstance()\n");
6437 TemplateInstances *tinstances = (TemplateInstances *)dmd_aaGetRvalue((AA *)tempdecl->instances, (void *)hash);
6438 assert(tinstances);
6439 for (size_t i = 0; i < tinstances->dim; i++)
6440 {
6441 TemplateInstance *ti = (*tinstances)[i];
6442 if (ti == errinst)
6443 {
6444 (*tinstances)[i] = this; // override
6445 break;
6446 }
6447 }
6448 }
6449}
6450
6451
6452/**********************************************
6453 * Find template declaration corresponding to template instance.
6454 *
6455 * Returns:
6456 * false if finding fails.
6457 * Note:
6458 * This function is reentrant against error occurrence. If returns false,
6459 * any members of this object won't be modified, and repetition call will
6460 * reproduce same error.
6461 */
6462
6463bool TemplateInstance::findTempDecl(Scope *sc, WithScopeSymbol **pwithsym)
6464{
6465 if (pwithsym)
6466 *pwithsym = NULL;
6467
6468 if (havetempdecl)
6469 return true;
6470
6471 //printf("TemplateInstance::findTempDecl() %s\n", toChars());
6472 if (!tempdecl)
6473 {
6474 /* Given:
6475 * foo!( ... )
6476 * figure out which TemplateDeclaration foo refers to.
6477 */
6478 Identifier *id = name;
6479 Dsymbol *scopesym;
6480 Dsymbol *s = sc->search(loc, id, &scopesym);
6481 if (!s)
6482 {
6483 s = sc->search_correct(id);
6484 if (s)
6485 error("template '%s' is not defined, did you mean %s?", id->toChars(), s->toChars());
6486 else
6487 error("template '%s' is not defined", id->toChars());
6488 return false;
6489 }
6490
6491 if (pwithsym)
6492 *pwithsym = scopesym->isWithScopeSymbol();
6493
6494 /* We might have found an alias within a template when
6495 * we really want the template.
6496 */
6497 TemplateInstance *ti;
6498 if (s->parent &&
6499 (ti = s->parent->isTemplateInstance()) != NULL)
6500 {
6501 if (ti->tempdecl && ti->tempdecl->ident == id)
6502 {
6503 /* This is so that one can refer to the enclosing
6504 * template, even if it has the same name as a member
6505 * of the template, if it has a !(arguments)
6506 */
6507 TemplateDeclaration *td = ti->tempdecl->isTemplateDeclaration();
6508 assert(td);
6509 if (td->overroot) // if not start of overloaded list of TemplateDeclaration's
6510 td = td->overroot; // then get the start
6511 s = td;
6512 }
6513 }
6514
6515 if (!updateTempDecl(sc, s))
6516 {
6517 return false;
6518 }
6519 }
6520 assert(tempdecl);
6521
6522 struct ParamFwdTi
6523 {
6524 static int fp(void *param, Dsymbol *s)
6525 {
6526 TemplateDeclaration *td = s->isTemplateDeclaration();
6527 if (!td)
6528 return 0;
6529
6530 TemplateInstance *ti = (TemplateInstance *)param;
6531 if (td->semanticRun == PASSinit)
6532 {
6533 if (td->_scope)
6534 {
6535 // Try to fix forward reference. Ungag errors while doing so.
6536 Ungag ungag = td->ungagSpeculative();
6537 td->semantic(td->_scope);
6538 }
6539 if (td->semanticRun == PASSinit)
6540 {
6541 ti->error("%s forward references template declaration %s", ti->toChars(), td->toChars());
6542 return 1;
6543 }
6544 }
6545 return 0;
6546 }
6547 };
6548 // Look for forward references
6549 OverloadSet *tovers = tempdecl->isOverloadSet();
6550 size_t overs_dim = tovers ? tovers->a.dim : 1;
6551 for (size_t oi = 0; oi < overs_dim; oi++)
6552 {
6553 if (overloadApply(tovers ? tovers->a[oi] : tempdecl, (void *)this, &ParamFwdTi::fp))
6554 return false;
6555 }
6556 return true;
6557}
6558
6559/**********************************************
6560 * Confirm s is a valid template, then store it.
6561 * Input:
6562 * sc
6563 * s candidate symbol of template. It may be:
6564 * TemplateDeclaration
6565 * FuncDeclaration with findTemplateDeclRoot() != NULL
6566 * OverloadSet which contains candidates
6567 * Returns:
6568 * true if updating succeeds.
6569 */
6570
6571bool TemplateInstance::updateTempDecl(Scope *sc, Dsymbol *s)
6572{
6573 if (s)
6574 {
6575 Identifier *id = name;
6576 s = s->toAlias();
6577
6578 /* If an OverloadSet, look for a unique member that is a template declaration
6579 */
6580 OverloadSet *os = s->isOverloadSet();
6581 if (os)
6582 {
6583 s = NULL;
6584 for (size_t i = 0; i < os->a.dim; i++)
6585 {
6586 Dsymbol *s2 = os->a[i];
6587 if (FuncDeclaration *f = s2->isFuncDeclaration())
6588 s2 = f->findTemplateDeclRoot();
6589 else
6590 s2 = s2->isTemplateDeclaration();
6591 if (s2)
6592 {
6593 if (s)
6594 {
6595 tempdecl = os;
6596 return true;
6597 }
6598 s = s2;
6599 }
6600 }
6601 if (!s)
6602 {
6603 error("template '%s' is not defined", id->toChars());
6604 return false;
6605 }
6606 }
6607
6608 OverDeclaration *od = s->isOverDeclaration();
6609 if (od)
6610 {
6611 tempdecl = od; // TODO: more strict check
6612 return true;
6613 }
6614
6615 /* It should be a TemplateDeclaration, not some other symbol
6616 */
6617 if (FuncDeclaration *f = s->isFuncDeclaration())
6618 tempdecl = f->findTemplateDeclRoot();
6619 else
6620 tempdecl = s->isTemplateDeclaration();
6621 if (!tempdecl)
6622 {
6623 if (!s->parent && global.errors)
6624 return false;
6625 if (!s->parent && s->getType())
6626 {
6627 Dsymbol *s2 = s->getType()->toDsymbol(sc);
6628 if (!s2)
6629 {
6630 error("%s is not a template declaration, it is a %s", id->toChars(), s->kind());
6631 return false;
6632 }
6633 s = s2;
6634 }
6635 //assert(s->parent);
6636 TemplateInstance *ti = s->parent ? s->parent->isTemplateInstance() : NULL;
6637 if (ti &&
6638 (ti->name == s->ident ||
6639 ti->toAlias()->ident == s->ident)
6640 &&
6641 ti->tempdecl)
6642 {
6643 /* This is so that one can refer to the enclosing
6644 * template, even if it has the same name as a member
6645 * of the template, if it has a !(arguments)
6646 */
6647 TemplateDeclaration *td = ti->tempdecl->isTemplateDeclaration();
6648 assert(td);
6649 if (td->overroot) // if not start of overloaded list of TemplateDeclaration's
6650 td = td->overroot; // then get the start
6651 tempdecl = td;
6652 }
6653 else
6654 {
6655 error("%s is not a template declaration, it is a %s", id->toChars(), s->kind());
6656 return false;
6657 }
6658 }
6659 }
6660 return (tempdecl != NULL);
6661}
6662
6663/**********************************
6664 * Run semantic on the elements of tiargs.
6665 * Input:
6666 * sc
6667 * Returns:
6668 * false if one or more arguments have errors.
6669 * Note:
6670 * This function is reentrant against error occurrence. If returns false,
6671 * all elements of tiargs won't be modified.
6672 */
6673
6674bool TemplateInstance::semanticTiargs(Scope *sc)
6675{
6676 //printf("+TemplateInstance::semanticTiargs() %s\n", toChars());
6677 if (semantictiargsdone)
6678 return true;
6679 if (semanticTiargs(loc, sc, tiargs, 0))
6680 {
6681 // cache the result iff semantic analysis succeeded entirely
6682 semantictiargsdone = 1;
6683 return true;
6684 }
6685 return false;
6686}
6687
6688/**********************************
6689 * Run semantic of tiargs as arguments of template.
6690 * Input:
6691 * loc
6692 * sc
6693 * tiargs array of template arguments
6694 * flags 1: replace const variables with their initializers
6695 * 2: don't devolve Parameter to Type
6696 * Returns:
6697 * false if one or more arguments have errors.
6698 */
6699
6700bool TemplateInstance::semanticTiargs(Loc loc, Scope *sc, Objects *tiargs, int flags)
6701{
6702 // Run semantic on each argument, place results in tiargs[]
6703 //printf("+TemplateInstance::semanticTiargs()\n");
6704 if (!tiargs)
6705 return true;
6706 bool err = false;
6707 for (size_t j = 0; j < tiargs->dim; j++)
6708 {
6709 RootObject *o = (*tiargs)[j];
6710 Type *ta = isType(o);
6711 Expression *ea = isExpression(o);
6712 Dsymbol *sa = isDsymbol(o);
6713
6714 //printf("1: (*tiargs)[%d] = %p, s=%p, v=%p, ea=%p, ta=%p\n", j, o, isDsymbol(o), isTuple(o), ea, ta);
6715 if (ta)
6716 {
6717 //printf("type %s\n", ta->toChars());
6718 // It might really be an Expression or an Alias
6719 ta->resolve(loc, sc, &ea, &ta, &sa);
6720 if (ea) goto Lexpr;
6721 if (sa) goto Ldsym;
6722 if (ta == NULL)
6723 {
6724 assert(global.errors);
6725 ta = Type::terror;
6726 }
6727
6728 Ltype:
6729 if (ta->ty == Ttuple)
6730 {
6731 // Expand tuple
6732 TypeTuple *tt = (TypeTuple *)ta;
6733 size_t dim = tt->arguments->dim;
6734 tiargs->remove(j);
6735 if (dim)
6736 {
6737 tiargs->reserve(dim);
6738 for (size_t i = 0; i < dim; i++)
6739 {
6740 Parameter *arg = (*tt->arguments)[i];
6741 if (flags & 2 && arg->ident)
6742 tiargs->insert(j + i, arg);
6743 else
6744 tiargs->insert(j + i, arg->type);
6745 }
6746 }
6747 j--;
6748 continue;
6749 }
6750 if (ta->ty == Terror)
6751 {
6752 err = true;
6753 continue;
6754 }
6755 (*tiargs)[j] = ta->merge2();
6756 }
6757 else if (ea)
6758 {
6759 Lexpr:
6760 //printf("+[%d] ea = %s %s\n", j, Token::toChars(ea->op), ea->toChars());
6761 if (flags & 1) // only used by __traits
6762 {
6763 ea = ::semantic(ea, sc);
6764
6765 // must not interpret the args, excepting template parameters
6766 if (ea->op != TOKvar ||
6767 (((VarExp *)ea)->var->storage_class & STCtemplateparameter))
6768 {
6769 ea = ea->optimize(WANTvalue);
6770 }
6771 }
6772 else
6773 {
6774 sc = sc->startCTFE();
6775 ea = ::semantic(ea, sc);
6776 sc = sc->endCTFE();
6777
6778 if (ea->op == TOKvar)
6779 {
6780 /* This test is to skip substituting a const var with
6781 * its initializer. The problem is the initializer won't
6782 * match with an 'alias' parameter. Instead, do the
6783 * const substitution in TemplateValueParameter::matchArg().
6784 */
6785 }
6786 else if (definitelyValueParameter(ea))
6787 {
6788 if (ea->checkValue()) // check void expression
6789 ea = new ErrorExp();
6790 unsigned int olderrs = global.errors;
6791 ea = ea->ctfeInterpret();
6792 if (global.errors != olderrs)
6793 ea = new ErrorExp();
6794 }
6795 }
6796 //printf("-[%d] ea = %s %s\n", j, Token::toChars(ea->op), ea->toChars());
6797 if (ea->op == TOKtuple)
6798 {
6799 // Expand tuple
6800 TupleExp *te = (TupleExp *)ea;
6801 size_t dim = te->exps->dim;
6802 tiargs->remove(j);
6803 if (dim)
6804 {
6805 tiargs->reserve(dim);
6806 for (size_t i = 0; i < dim; i++)
6807 tiargs->insert(j + i, (*te->exps)[i]);
6808 }
6809 j--;
6810 continue;
6811 }
6812 if (ea->op == TOKerror)
6813 {
6814 err = true;
6815 continue;
6816 }
6817 (*tiargs)[j] = ea;
6818
6819 if (ea->op == TOKtype)
6820 {
6821 ta = ea->type;
6822 goto Ltype;
6823 }
6824 if (ea->op == TOKscope)
6825 {
6826 sa = ((ScopeExp *)ea)->sds;
6827 goto Ldsym;
6828 }
6829 if (ea->op == TOKfunction)
6830 {
6831 FuncExp *fe = (FuncExp *)ea;
6832 /* A function literal, that is passed to template and
6833 * already semanticed as function pointer, never requires
6834 * outer frame. So convert it to global function is valid.
6835 */
6836 if (fe->fd->tok == TOKreserved && fe->type->ty == Tpointer)
6837 {
6838 // change to non-nested
6839 fe->fd->tok = TOKfunction;
6840 fe->fd->vthis = NULL;
6841 }
6842 else if (fe->td)
6843 {
6844 /* If template argument is a template lambda,
6845 * get template declaration itself. */
6846 //sa = fe->td;
6847 //goto Ldsym;
6848 }
6849 }
6850 if (ea->op == TOKdotvar)
6851 {
6852 // translate expression to dsymbol.
6853 sa = ((DotVarExp *)ea)->var;
6854 goto Ldsym;
6855 }
6856 if (ea->op == TOKtemplate)
6857 {
6858 sa = ((TemplateExp *)ea)->td;
6859 goto Ldsym;
6860 }
6861 if (ea->op == TOKdottd)
6862 {
6863 // translate expression to dsymbol.
6864 sa = ((DotTemplateExp *)ea)->td;
6865 goto Ldsym;
6866 }
6867 }
6868 else if (sa)
6869 {
6870 Ldsym:
6871 //printf("dsym %s %s\n", sa->kind(), sa->toChars());
6872 if (sa->errors)
6873 {
6874 err = true;
6875 continue;
6876 }
6877
6878 TupleDeclaration *d = sa->toAlias()->isTupleDeclaration();
6879 if (d)
6880 {
6881 // Expand tuple
6882 tiargs->remove(j);
6883 tiargs->insert(j, d->objects);
6884 j--;
6885 continue;
6886 }
6887 if (FuncAliasDeclaration *fa = sa->isFuncAliasDeclaration())
6888 {
6889 FuncDeclaration *f = fa->toAliasFunc();
6890 if (!fa->hasOverloads && f->isUnique())
6891 {
6892 // Strip FuncAlias only when the aliased function
6893 // does not have any overloads.
6894 sa = f;
6895 }
6896 }
6897 (*tiargs)[j] = sa;
6898
6899 TemplateDeclaration *td = sa->isTemplateDeclaration();
6900 if (td && td->semanticRun == PASSinit && td->literal)
6901 {
6902 td->semantic(sc);
6903 }
6904 FuncDeclaration *fd = sa->isFuncDeclaration();
6905 if (fd)
6906 fd->functionSemantic();
6907 }
6908 else if (isParameter(o))
6909 {
6910 }
6911 else
6912 {
6913 assert(0);
6914 }
6915 //printf("1: (*tiargs)[%d] = %p\n", j, (*tiargs)[j]);
6916 }
6917 return !err;
6918}
6919
6920bool TemplateInstance::findBestMatch(Scope *sc, Expressions *fargs)
6921{
6922 if (havetempdecl)
6923 {
6924 TemplateDeclaration *tempdecl = this->tempdecl->isTemplateDeclaration();
6925 assert(tempdecl);
6926 assert(tempdecl->_scope);
6927 // Deduce tdtypes
6928 tdtypes.setDim(tempdecl->parameters->dim);
6929 if (!tempdecl->matchWithInstance(sc, this, &tdtypes, fargs, 2))
6930 {
6931 error("incompatible arguments for template instantiation");
6932 return false;
6933 }
6934 // TODO: Normalizing tiargs for bugzilla 7469 is necessary?
6935 return true;
6936 }
6937
6938 unsigned errs = global.errors;
6939
6940 struct ParamBest
6941 {
6942 // context
6943 Scope *sc;
6944 TemplateInstance *ti;
6945 Objects dedtypes;
6946 // result
6947 TemplateDeclaration *td_best;
6948 TemplateDeclaration *td_ambig;
6949 MATCH m_best;
6950
6951 static int fp(void *param, Dsymbol *s)
6952 {
6953 return ((ParamBest *)param)->fp(s);
6954 }
6955 int fp(Dsymbol *s)
6956 {
6957 TemplateDeclaration *td = s->isTemplateDeclaration();
6958 if (!td)
6959 return 0;
6960
6961 if (td == td_best) // skip duplicates
6962 return 0;
6963
6964 //printf("td = %s\n", td->toPrettyChars());
6965
6966 // If more arguments than parameters,
6967 // then this is no match.
6968 if (td->parameters->dim < ti->tiargs->dim)
6969 {
6970 if (!td->isVariadic())
6971 return 0;
6972 }
6973
6974 dedtypes.setDim(td->parameters->dim);
6975 dedtypes.zero();
6976 assert(td->semanticRun != PASSinit);
6977 MATCH m = td->matchWithInstance(sc, ti, &dedtypes, ti->fargs, 0);
6978 //printf("matchWithInstance = %d\n", m);
6979 if (m <= MATCHnomatch) // no match at all
6980 return 0;
6981
6982 if (m < m_best) goto Ltd_best;
6983 if (m > m_best) goto Ltd;
6984
6985 {
6986 // Disambiguate by picking the most specialized TemplateDeclaration
6987 MATCH c1 = td->leastAsSpecialized(sc, td_best, ti->fargs);
6988 MATCH c2 = td_best->leastAsSpecialized(sc, td, ti->fargs);
6989 //printf("c1 = %d, c2 = %d\n", c1, c2);
6990 if (c1 > c2) goto Ltd;
6991 if (c1 < c2) goto Ltd_best;
6992 }
6993
6994 td_ambig = td;
6995 return 0;
6996
6997 Ltd_best: // td_best is the best match so far
6998 td_ambig = NULL;
6999 return 0;
7000
7001 Ltd: // td is the new best match
7002 td_ambig = NULL;
7003 td_best = td;
7004 m_best = m;
7005 ti->tdtypes.setDim(dedtypes.dim);
7006 memcpy(ti->tdtypes.tdata(), dedtypes.tdata(), ti->tdtypes.dim * sizeof(void *));
7007 return 0;
7008 }
7009 };
7010 ParamBest p;
7011 // context
7012 p.ti = this;
7013 p.sc = sc;
7014
7015 /* Since there can be multiple TemplateDeclaration's with the same
7016 * name, look for the best match.
7017 */
7018 TemplateDeclaration *td_last = NULL;
7019
7020 OverloadSet *tovers = tempdecl->isOverloadSet();
7021 size_t overs_dim = tovers ? tovers->a.dim : 1;
7022 for (size_t oi = 0; oi < overs_dim; oi++)
7023 {
7024 // result
7025 p.td_best = NULL;
7026 p.td_ambig = NULL;
7027 p.m_best = MATCHnomatch;
7028 overloadApply(tovers ? tovers->a[oi] : tempdecl, &p, &ParamBest::fp);
7029
7030 if (p.td_ambig)
7031 {
7032 ::error(loc, "%s %s.%s matches more than one template declaration:\n%s: %s\nand\n%s: %s",
7033 p.td_best->kind(), p.td_best->parent->toPrettyChars(), p.td_best->ident->toChars(),
7034 p.td_best->loc.toChars() , p.td_best->toChars(),
7035 p.td_ambig->loc.toChars(), p.td_ambig->toChars());
7036 return false;
7037 }
7038 if (p.td_best)
7039 {
7040 if (!td_last)
7041 td_last = p.td_best;
7042 else if (td_last != p.td_best)
7043 {
7044 ScopeDsymbol::multiplyDefined(loc, td_last, p.td_best);
7045 return false;
7046 }
7047 }
7048 }
7049
7050 if (td_last)
7051 {
7052 /* Bugzilla 7469: Normalize tiargs by using corresponding deduced
7053 * template value parameters and tuples for the correct mangling.
7054 *
7055 * By doing this before hasNestedArgs, CTFEable local variable will be
7056 * accepted as a value parameter. For example:
7057 *
7058 * void foo() {
7059 * struct S(int n) {} // non-global template
7060 * const int num = 1; // CTFEable local variable
7061 * S!num s; // S!1 is instantiated, not S!num
7062 * }
7063 */
7064 size_t dim = td_last->parameters->dim - (td_last->isVariadic() ? 1 : 0);
7065 for (size_t i = 0; i < dim; i++)
7066 {
7067 if (tiargs->dim <= i)
7068 tiargs->push(tdtypes[i]);
7069 assert(i < tiargs->dim);
7070
7071 TemplateValueParameter *tvp = (*td_last->parameters)[i]->isTemplateValueParameter();
7072 if (!tvp)
7073 continue;
7074 assert(tdtypes[i]);
7075 // tdtypes[i] is already normalized to the required type in matchArg
7076
7077 (*tiargs)[i] = tdtypes[i];
7078 }
7079 if (td_last->isVariadic() && tiargs->dim == dim && tdtypes[dim])
7080 {
7081 Tuple *va = isTuple(tdtypes[dim]);
7082 assert(va);
7083 for (size_t i = 0; i < va->objects.dim; i++)
7084 tiargs->push(va->objects[i]);
7085 }
7086 }
7087 else if (errors && inst)
7088 {
7089 // instantiation was failed with error reporting
7090 assert(global.errors);
7091 return false;
7092 }
7093 else
7094 {
7095 TemplateDeclaration *tdecl = tempdecl->isTemplateDeclaration();
7096
7097 if (errs != global.errors)
7098 errorSupplemental(loc, "while looking for match for %s", toChars());
7099 else if (tdecl && !tdecl->overnext)
7100 {
7101 // Only one template, so we can give better error message
7102 error("does not match template declaration %s", tdecl->toChars());
7103 }
7104 else
7105 ::error(loc, "%s %s.%s does not match any template declaration",
7106 tempdecl->kind(), tempdecl->parent->toPrettyChars(), tempdecl->ident->toChars());
7107 return false;
7108 }
7109
7110 /* The best match is td_last
7111 */
7112 tempdecl = td_last;
7113
7114 return (errs == global.errors);
7115}
7116
7117/*****************************************************
7118 * Determine if template instance is really a template function,
7119 * and that template function needs to infer types from the function
7120 * arguments.
7121 *
7122 * Like findBestMatch, iterate possible template candidates,
7123 * but just looks only the necessity of type inference.
7124 */
7125
7126bool TemplateInstance::needsTypeInference(Scope *sc, int flag)
7127{
7128 //printf("TemplateInstance::needsTypeInference() %s\n", toChars());
7129 if (semanticRun != PASSinit)
7130 return false;
7131
7132 struct ParamNeedsInf
7133 {
7134 // context
7135 Scope *sc;
7136 TemplateInstance *ti;
7137 int flag;
7138 // result
7139 Objects dedtypes;
7140 size_t count;
7141
7142 static int fp(void *param, Dsymbol *s)
7143 {
7144 return ((ParamNeedsInf *)param)->fp(s);
7145 }
7146 int fp(Dsymbol *s)
7147 {
7148 TemplateDeclaration *td = s->isTemplateDeclaration();
7149 if (!td)
7150 {
7151 return 0;
7152 }
7153
7154 /* If any of the overloaded template declarations need inference,
7155 * then return true
7156 */
7157 FuncDeclaration *fd;
7158 if (!td->onemember)
7159 return 0;
7160 if (TemplateDeclaration *td2 = td->onemember->isTemplateDeclaration())
7161 {
7162 if (!td2->onemember || !td2->onemember->isFuncDeclaration())
7163 return 0;
7164 if (ti->tiargs->dim >= td->parameters->dim - (td->isVariadic() ? 1 : 0))
7165 return 0;
7166 return 1;
7167 }
7168 if ((fd = td->onemember->isFuncDeclaration()) == NULL ||
7169 fd->type->ty != Tfunction)
7170 {
7171 return 0;
7172 }
7173
7174 for (size_t i = 0; i < td->parameters->dim; i++)
7175 {
7176 if ((*td->parameters)[i]->isTemplateThisParameter())
7177 return 1;
7178 }
7179
7180 /* Determine if the instance arguments, tiargs, are all that is necessary
7181 * to instantiate the template.
7182 */
7183 //printf("tp = %p, td->parameters->dim = %d, tiargs->dim = %d\n", tp, td->parameters->dim, ti->tiargs->dim);
7184 TypeFunction *tf = (TypeFunction *)fd->type;
7185 if (size_t dim = Parameter::dim(tf->parameters))
7186 {
7187 TemplateParameter *tp = td->isVariadic();
7188 if (tp && td->parameters->dim > 1)
7189 return 1;
7190
7191 if (!tp && ti->tiargs->dim < td->parameters->dim)
7192 {
7193 // Can remain tiargs be filled by default arguments?
7194 for (size_t i = ti->tiargs->dim; i < td->parameters->dim; i++)
7195 {
7196 if (!(*td->parameters)[i]->hasDefaultArg())
7197 return 1;
7198 }
7199 }
7200
7201 for (size_t i = 0; i < dim; i++)
7202 {
7203 // 'auto ref' needs inference.
7204 if (Parameter::getNth(tf->parameters, i)->storageClass & STCauto)
7205 return 1;
7206 }
7207 }
7208
7209 if (!flag)
7210 {
7211 /* Calculate the need for overload resolution.
7212 * When only one template can match with tiargs, inference is not necessary.
7213 */
7214 dedtypes.setDim(td->parameters->dim);
7215 dedtypes.zero();
7216 if (td->semanticRun == PASSinit)
7217 {
7218 if (td->_scope)
7219 {
7220 // Try to fix forward reference. Ungag errors while doing so.
7221 Ungag ungag = td->ungagSpeculative();
7222 td->semantic(td->_scope);
7223 }
7224 if (td->semanticRun == PASSinit)
7225 {
7226 ti->error("%s forward references template declaration %s", ti->toChars(), td->toChars());
7227 return 1;
7228 }
7229 }
7230 assert(td->semanticRun != PASSinit);
7231 MATCH m = td->matchWithInstance(sc, ti, &dedtypes, NULL, 0);
7232 if (m <= MATCHnomatch)
7233 return 0;
7234 }
7235
7236 /* If there is more than one function template which matches, we may
7237 * need type inference (see Bugzilla 4430)
7238 */
7239 if (++count > 1)
7240 return 1;
7241
7242 return 0;
7243 }
7244 };
7245 ParamNeedsInf p;
7246 // context
7247 p.ti = this;
7248 p.sc = sc;
7249 p.flag = flag;
7250 // result
7251 p.count = 0;
7252
7253 OverloadSet *tovers = tempdecl->isOverloadSet();
7254 size_t overs_dim = tovers ? tovers->a.dim : 1;
7255 unsigned olderrs = global.errors;
7256 for (size_t oi = 0; oi < overs_dim; oi++)
7257 {
7258 if (overloadApply(tovers ? tovers->a[oi] : tempdecl, &p, &ParamNeedsInf::fp))
7259 return true;
7260 }
7261 if (olderrs != global.errors)
7262 {
7263 if (!global.gag)
7264 {
7265 errorSupplemental(loc, "while looking for match for %s", toChars());
7266 semanticRun = PASSsemanticdone;
7267 inst = this;
7268 }
7269 errors = true;
7270 }
7271 //printf("false\n");
7272 return false;
7273}
7274
7275
7276/*****************************************
7277 * Determines if a TemplateInstance will need a nested
7278 * generation of the TemplateDeclaration.
7279 * Sets enclosing property if so, and returns != 0;
7280 */
7281
7282bool TemplateInstance::hasNestedArgs(Objects *args, bool isstatic)
7283{
7284 int nested = 0;
7285 //printf("TemplateInstance::hasNestedArgs('%s')\n", tempdecl->ident->toChars());
7286
7287 /* A nested instance happens when an argument references a local
7288 * symbol that is on the stack.
7289 */
7290 for (size_t i = 0; i < args->dim; i++)
7291 {
7292 RootObject *o = (*args)[i];
7293 Expression *ea = isExpression(o);
7294 Dsymbol *sa = isDsymbol(o);
7295 Tuple *va = isTuple(o);
7296 if (ea)
7297 {
7298 if (ea->op == TOKvar)
7299 {
7300 sa = ((VarExp *)ea)->var;
7301 goto Lsa;
7302 }
7303 if (ea->op == TOKthis)
7304 {
7305 sa = ((ThisExp *)ea)->var;
7306 goto Lsa;
7307 }
7308 if (ea->op == TOKfunction)
7309 {
7310 if (((FuncExp *)ea)->td)
7311 sa = ((FuncExp *)ea)->td;
7312 else
7313 sa = ((FuncExp *)ea)->fd;
7314 goto Lsa;
7315 }
7316 // Emulate Expression::toMangleBuffer call that had exist in TemplateInstance::genIdent.
7317 if (ea->op != TOKint64 &&
7318 ea->op != TOKfloat64 &&
7319 ea->op != TOKcomplex80 &&
7320 ea->op != TOKnull &&
7321 ea->op != TOKstring &&
7322 ea->op != TOKarrayliteral &&
7323 ea->op != TOKassocarrayliteral &&
7324 ea->op != TOKstructliteral)
7325 {
7326 ea->error("expression %s is not a valid template value argument", ea->toChars());
7327 errors = true;
7328 }
7329 }
7330 else if (sa)
7331 {
7332 Lsa:
7333 sa = sa->toAlias();
7334 TemplateDeclaration *td = sa->isTemplateDeclaration();
7335 if (td)
7336 {
7337 TemplateInstance *ti = sa->toParent()->isTemplateInstance();
7338 if (ti && ti->enclosing)
7339 sa = ti;
7340 }
7341 TemplateInstance *ti = sa->isTemplateInstance();
7342 Declaration *d = sa->isDeclaration();
7343 if ((td && td->literal) ||
7344 (ti && ti->enclosing) ||
7345 (d && !d->isDataseg() &&
7346 !(d->storage_class & STCmanifest) &&
7347 (!d->isFuncDeclaration() || d->isFuncDeclaration()->isNested()) &&
7348 !isTemplateMixin()
7349 ))
7350 {
7351 // if module level template
7352 if (isstatic)
7353 {
7354 Dsymbol *dparent = sa->toParent2();
7355 if (!enclosing)
7356 enclosing = dparent;
7357 else if (enclosing != dparent)
7358 {
7359 /* Select the more deeply nested of the two.
7360 * Error if one is not nested inside the other.
7361 */
7362 for (Dsymbol *p = enclosing; p; p = p->parent)
7363 {
7364 if (p == dparent)
7365 goto L1; // enclosing is most nested
7366 }
7367 for (Dsymbol *p = dparent; p; p = p->parent)
7368 {
7369 if (p == enclosing)
7370 {
7371 enclosing = dparent;
7372 goto L1; // dparent is most nested
7373 }
7374 }
7375 error("%s is nested in both %s and %s",
7376 toChars(), enclosing->toChars(), dparent->toChars());
7377 errors = true;
7378 }
7379 L1:
7380 //printf("\tnested inside %s\n", enclosing->toChars());
7381 nested |= 1;
7382 }
7383 else
7384 {
7385 error("cannot use local '%s' as parameter to non-global template %s", sa->toChars(), tempdecl->toChars());
7386 errors = true;
7387 }
7388 }
7389 }
7390 else if (va)
7391 {
7392 nested |= (int)hasNestedArgs(&va->objects, isstatic);
7393 }
7394 }
7395 //printf("-TemplateInstance::hasNestedArgs('%s') = %d\n", tempdecl->ident->toChars(), nested);
7396 return nested != 0;
7397}
7398
7399/*****************************************
7400 * Append 'this' to the specific module members[]
7401 */
7402Dsymbols *TemplateInstance::appendToModuleMember()
7403{
7404 Module *mi = minst; // instantiated -> inserted module
7405
7406 if (global.params.useUnitTests ||
7407 global.params.debuglevel)
7408 {
7409 // Turn all non-root instances to speculative
7410 if (mi && !mi->isRoot())
7411 mi = NULL;
7412 }
7413
7414 //printf("%s->appendToModuleMember() enclosing = %s mi = %s\n",
7415 // toPrettyChars(),
7416 // enclosing ? enclosing->toPrettyChars() : NULL,
7417 // mi ? mi->toPrettyChars() : NULL);
7418 if (!mi || mi->isRoot())
7419 {
7420 /* If the instantiated module is speculative or root, insert to the
7421 * member of a root module. Then:
7422 * - semantic3 pass will get called on the instance members.
7423 * - codegen pass will get a selection chance to do/skip it.
7424 */
7425
7426 struct N
7427 {
7428 static Dsymbol *getStrictEnclosing(TemplateInstance *ti)
7429 {
7430 do
7431 {
7432 if (ti->enclosing)
7433 return ti->enclosing;
7434 ti = ti->tempdecl->isInstantiated();
7435 }
7436 while (ti);
7437 return NULL;
7438 }
7439 };
7440 Dsymbol *enc = N::getStrictEnclosing(this);
7441
7442 // insert target is made stable by using the module
7443 // where tempdecl is declared.
7444 mi = (enc ? enc : tempdecl)->getModule();
7445 if (!mi->isRoot())
7446 mi = mi->importedFrom;
7447 assert(mi->isRoot());
7448 }
7449 else
7450 {
7451 /* If the instantiated module is non-root, insert to the member of the
7452 * non-root module. Then:
7453 * - semantic3 pass won't be called on the instance.
7454 * - codegen pass won't reach to the instance.
7455 */
7456 }
7457 //printf("\t--> mi = %s\n", mi->toPrettyChars());
7458
7459 if (memberOf == mi) // already a member
7460 {
7461 return NULL;
7462 }
7463
7464 Dsymbols *a = mi->members;
7465 a->push(this);
7466 memberOf = mi;
7467 if (mi->semanticRun >= PASSsemantic2done && mi->isRoot())
7468 Module::addDeferredSemantic2(this);
7469 if (mi->semanticRun >= PASSsemantic3done && mi->isRoot())
7470 Module::addDeferredSemantic3(this);
7471 return a;
7472}
7473
7474/****************************************
7475 * This instance needs an identifier for name mangling purposes.
7476 * Create one by taking the template declaration name and adding
7477 * the type signature for it.
7478 */
7479
7480Identifier *TemplateInstance::genIdent(Objects *args)
7481{
7482 TemplateDeclaration *tempdecl = this->tempdecl->isTemplateDeclaration();
7483 assert(tempdecl);
7484
7485 //printf("TemplateInstance::genIdent('%s')\n", tempdecl->ident->toChars());
7486 OutBuffer buf;
7487 const char *id = tempdecl->ident->toChars();
7488 if (!members)
7489 {
7490 // Use "__U" for the symbols declared inside template constraint.
7491 buf.printf("__U%llu%s", (ulonglong)strlen(id), id);
7492 }
7493 else
7494 buf.printf("__T%llu%s", (ulonglong)strlen(id), id);
7495 size_t nparams = tempdecl->parameters->dim - (tempdecl->isVariadic() ? 1 : 0);
7496 for (size_t i = 0; i < args->dim; i++)
7497 {
7498 RootObject *o = (*args)[i];
7499 Type *ta = isType(o);
7500 Expression *ea = isExpression(o);
7501 Dsymbol *sa = isDsymbol(o);
7502 Tuple *va = isTuple(o);
7503 //printf("\to [%d] %p ta %p ea %p sa %p va %p\n", i, o, ta, ea, sa, va);
7504 if (i < nparams && (*tempdecl->parameters)[i]->specialization())
7505 buf.writeByte('H'); // Bugzilla 6574
7506 if (ta)
7507 {
7508 buf.writeByte('T');
7509 if (ta->deco)
7510 buf.writestring(ta->deco);
7511 else
7512 {
7513 assert(global.errors);
7514 }
7515 }
7516 else if (ea)
7517 {
7518 // Don't interpret it yet, it might actually be an alias template parameter.
7519 // Only constfold manifest constants, not const/immutable lvalues, see https://issues.dlang.org/show_bug.cgi?id=17339.
7520 const bool keepLvalue = true;
7521 ea = ea->optimize(WANTvalue, keepLvalue);
7522 if (ea->op == TOKvar)
7523 {
7524 sa = ((VarExp *)ea)->var;
7525 ea = NULL;
7526 goto Lsa;
7527 }
7528 if (ea->op == TOKthis)
7529 {
7530 sa = ((ThisExp *)ea)->var;
7531 ea = NULL;
7532 goto Lsa;
7533 }
7534 if (ea->op == TOKfunction)
7535 {
7536 if (((FuncExp *)ea)->td)
7537 sa = ((FuncExp *)ea)->td;
7538 else
7539 sa = ((FuncExp *)ea)->fd;
7540 ea = NULL;
7541 goto Lsa;
7542 }
7543 buf.writeByte('V');
7544 if (ea->op == TOKtuple)
7545 {
7546 ea->error("tuple is not a valid template value argument");
7547 continue;
7548 }
7549 // Now that we know it is not an alias, we MUST obtain a value
7550 unsigned olderr = global.errors;
7551 ea = ea->ctfeInterpret();
7552 if (ea->op == TOKerror || olderr != global.errors)
7553 continue;
7554
7555 /* Use deco that matches what it would be for a function parameter
7556 */
7557 buf.writestring(ea->type->deco);
7558 mangleToBuffer(ea, &buf);
7559 }
7560 else if (sa)
7561 {
7562 Lsa:
7563 buf.writeByte('S');
7564 sa = sa->toAlias();
7565 Declaration *d = sa->isDeclaration();
7566 if (d && (!d->type || !d->type->deco))
7567 {
7568 error("forward reference of %s %s", d->kind(), d->toChars());
7569 continue;
7570 }
7571
7572 OutBuffer bufsa;
7573 mangleToBuffer(sa, &bufsa);
7574 const char *s = bufsa.extractString();
7575
7576 /* Bugzilla 3043: if the first character of s is a digit this
7577 * causes ambiguity issues because the digits of the two numbers are adjacent.
7578 * Current demanglers resolve this by trying various places to separate the
7579 * numbers until one gets a successful demangle.
7580 * Unfortunately, fixing this ambiguity will break existing binary
7581 * compatibility and the demanglers, so we'll leave it as is.
7582 */
7583 buf.printf("%u%s", (unsigned)strlen(s), s);
7584 }
7585 else if (va)
7586 {
7587 assert(i + 1 == args->dim); // must be last one
7588 args = &va->objects;
7589 i = -(size_t)1;
7590 }
7591 else
7592 assert(0);
7593 }
7594 buf.writeByte('Z');
7595 id = buf.peekString();
7596 //printf("\tgenIdent = %s\n", id);
7597 return Identifier::idPool(id);
7598}
7599
7600/*************************************
7601 * Lazily generate identifier for template instance.
7602 * This is because 75% of the ident's are never needed.
7603 */
7604
7605Identifier *TemplateInstance::getIdent()
7606{
7607 if (!ident && inst && !errors)
7608 ident = genIdent(tiargs); // need an identifier for name mangling purposes.
7609 return ident;
7610}
7611
7612/****************************************************
7613 * Declare parameters of template instance, initialize them with the
7614 * template instance arguments.
7615 */
7616
7617void TemplateInstance::declareParameters(Scope *sc)
7618{
7619 TemplateDeclaration *tempdecl = this->tempdecl->isTemplateDeclaration();
7620 assert(tempdecl);
7621
7622 //printf("TemplateInstance::declareParameters()\n");
7623 for (size_t i = 0; i < tdtypes.dim; i++)
7624 {
7625 TemplateParameter *tp = (*tempdecl->parameters)[i];
7626 //RootObject *o = (*tiargs)[i];
7627 RootObject *o = tdtypes[i]; // initializer for tp
7628
7629 //printf("\ttdtypes[%d] = %p\n", i, o);
7630 tempdecl->declareParameter(sc, tp, o);
7631 }
7632}
7633
7634void TemplateInstance::semantic2(Scope *sc)
7635{
7636 if (semanticRun >= PASSsemantic2)
7637 return;
7638 semanticRun = PASSsemantic2;
7639 if (!errors && members)
7640 {
7641 TemplateDeclaration *tempdecl = this->tempdecl->isTemplateDeclaration();
7642 assert(tempdecl);
7643
7644 sc = tempdecl->_scope;
7645 assert(sc);
7646 sc = sc->push(argsym);
7647 sc = sc->push(this);
7648 sc->tinst = this;
7649 sc->minst = minst;
7650
7651 int needGagging = (gagged && !global.gag);
7652 unsigned int olderrors = global.errors;
7653 int oldGaggedErrors = -1; // dead-store to prevent spurious warning
7654 if (needGagging)
7655 oldGaggedErrors = global.startGagging();
7656
7657 for (size_t i = 0; i < members->dim; i++)
7658 {
7659 Dsymbol *s = (*members)[i];
7660 s->semantic2(sc);
7661 if (gagged && global.errors != olderrors)
7662 break;
7663 }
7664
7665 if (global.errors != olderrors)
7666 {
7667 if (!errors)
7668 {
7669 if (!tempdecl->literal)
7670 error(loc, "error instantiating");
7671 if (tinst)
7672 tinst->printInstantiationTrace();
7673 }
7674 errors = true;
7675 }
7676 if (needGagging)
7677 global.endGagging(oldGaggedErrors);
7678
7679 sc = sc->pop();
7680 sc->pop();
7681 }
7682}
7683
7684void TemplateInstance::semantic3(Scope *sc)
7685{
7686//if (toChars()[0] == 'D') *(char*)0=0;
7687 if (semanticRun >= PASSsemantic3)
7688 return;
7689 semanticRun = PASSsemantic3;
7690 if (!errors && members)
7691 {
7692 TemplateDeclaration *tempdecl = this->tempdecl->isTemplateDeclaration();
7693 assert(tempdecl);
7694
7695 sc = tempdecl->_scope;
7696 sc = sc->push(argsym);
7697 sc = sc->push(this);
7698 sc->tinst = this;
7699 sc->minst = minst;
7700
7701 int needGagging = (gagged && !global.gag);
7702 unsigned int olderrors = global.errors;
7703 int oldGaggedErrors = -1; // dead-store to prevent spurious warning
7704 /* If this is a gagged instantiation, gag errors.
7705 * Future optimisation: If the results are actually needed, errors
7706 * would already be gagged, so we don't really need to run semantic
7707 * on the members.
7708 */
7709 if (needGagging)
7710 oldGaggedErrors = global.startGagging();
7711
7712 for (size_t i = 0; i < members->dim; i++)
7713 {
7714 Dsymbol *s = (*members)[i];
7715 s->semantic3(sc);
7716 if (gagged && global.errors != olderrors)
7717 break;
7718 }
7719
7720 if (global.errors != olderrors)
7721 {
7722 if (!errors)
7723 {
7724 if (!tempdecl->literal)
7725 error(loc, "error instantiating");
7726 if (tinst)
7727 tinst->printInstantiationTrace();
7728 }
7729 errors = true;
7730 }
7731 if (needGagging)
7732 global.endGagging(oldGaggedErrors);
7733
7734 sc = sc->pop();
7735 sc->pop();
7736 }
7737}
7738
7739/**************************************
7740 * Given an error instantiating the TemplateInstance,
7741 * give the nested TemplateInstance instantiations that got
7742 * us here. Those are a list threaded into the nested scopes.
7743 */
7744void TemplateInstance::printInstantiationTrace()
7745{
7746 if (global.gag)
7747 return;
7748
7749 const unsigned max_shown = 6;
7750 const char format[] = "instantiated from here: %s";
7751
7752 // determine instantiation depth and number of recursive instantiations
7753 unsigned n_instantiations = 1;
7754 unsigned n_totalrecursions = 0;
7755 for (TemplateInstance *cur = this; cur; cur = cur->tinst)
7756 {
7757 ++n_instantiations;
7758 // If two instantiations use the same declaration, they are recursive.
7759 // (this works even if they are instantiated from different places in the
7760 // same template).
7761 // In principle, we could also check for multiple-template recursion, but it's
7762 // probably not worthwhile.
7763 if (cur->tinst && cur->tempdecl && cur->tinst->tempdecl
7764 && cur->tempdecl->loc.equals(cur->tinst->tempdecl->loc))
7765 ++n_totalrecursions;
7766 }
7767
7768 // show full trace only if it's short or verbose is on
7769 if (n_instantiations <= max_shown || global.params.verbose)
7770 {
7771 for (TemplateInstance *cur = this; cur; cur = cur->tinst)
7772 {
7773 cur->errors = true;
7774 errorSupplemental(cur->loc, format, cur->toChars());
7775 }
7776 }
7777 else if (n_instantiations - n_totalrecursions <= max_shown)
7778 {
7779 // By collapsing recursive instantiations into a single line,
7780 // we can stay under the limit.
7781 int recursionDepth=0;
7782 for (TemplateInstance *cur = this; cur; cur = cur->tinst)
7783 {
7784 cur->errors = true;
7785 if (cur->tinst && cur->tempdecl && cur->tinst->tempdecl
7786 && cur->tempdecl->loc.equals(cur->tinst->tempdecl->loc))
7787 {
7788 ++recursionDepth;
7789 }
7790 else
7791 {
7792 if (recursionDepth)
7793 errorSupplemental(cur->loc, "%d recursive instantiations from here: %s", recursionDepth+2, cur->toChars());
7794 else
7795 errorSupplemental(cur->loc, format, cur->toChars());
7796 recursionDepth = 0;
7797 }
7798 }
7799 }
7800 else
7801 {
7802 // Even after collapsing the recursions, the depth is too deep.
7803 // Just display the first few and last few instantiations.
7804 unsigned i = 0;
7805 for (TemplateInstance *cur = this; cur; cur = cur->tinst)
7806 {
7807 cur->errors = true;
7808
7809 if (i == max_shown / 2)
7810 errorSupplemental(cur->loc, "... (%d instantiations, -v to show) ...", n_instantiations - max_shown);
7811
7812 if (i < max_shown / 2 ||
7813 i >= n_instantiations - max_shown + max_shown / 2)
7814 errorSupplemental(cur->loc, format, cur->toChars());
7815 ++i;
7816 }
7817 }
7818}
7819
7820Dsymbol *TemplateInstance::toAlias()
7821{
7822 if (!inst)
7823 {
7824 // Maybe we can resolve it
7825 if (_scope)
7826 {
7827 semantic(_scope);
7828 }
7829 if (!inst)
7830 {
7831 error("cannot resolve forward reference");
7832 errors = true;
7833 return this;
7834 }
7835 }
7836
7837 if (inst != this)
7838 return inst->toAlias();
7839
7840 if (aliasdecl)
7841 {
7842 return aliasdecl->toAlias();
7843 }
7844
7845 return inst;
7846}
7847
f9ab59ff 7848const char *TemplateInstance::kind() const
b4c522fa
IB
7849{
7850 return "template instance";
7851}
7852
7853bool TemplateInstance::oneMember(Dsymbol **ps, Identifier *)
7854{
7855 *ps = NULL;
7856 return true;
7857}
7858
7859const char *TemplateInstance::toChars()
7860{
7861 OutBuffer buf;
7862 toCBufferInstance(this, &buf);
7863 return buf.extractString();
7864}
7865
7866const char *TemplateInstance::toPrettyCharsHelper()
7867{
7868 OutBuffer buf;
7869 toCBufferInstance(this, &buf, true);
7870 return buf.extractString();
7871}
7872
7873/*************************************
7874 * Compare proposed template instantiation with existing template instantiation.
7875 * Note that this is not commutative because of the auto ref check.
7876 * Params:
7877 * this = proposed template instantiation
7878 * o = existing template instantiation
7879 * Returns:
7880 * 0 for match, 1 for no match
7881 */
7882int TemplateInstance::compare(RootObject *o)
7883{
7884 TemplateInstance *ti = (TemplateInstance *)o;
7885
7886 //printf("this = %p, ti = %p\n", this, ti);
7887 assert(tdtypes.dim == ti->tdtypes.dim);
7888
7889 // Nesting must match
7890 if (enclosing != ti->enclosing)
7891 {
7892 //printf("test2 enclosing %s ti->enclosing %s\n", enclosing ? enclosing->toChars() : "", ti->enclosing ? ti->enclosing->toChars() : "");
7893 goto Lnotequals;
7894 }
7895 //printf("parent = %s, ti->parent = %s\n", parent->toPrettyChars(), ti->parent->toPrettyChars());
7896
7897 if (!arrayObjectMatch(&tdtypes, &ti->tdtypes))
7898 goto Lnotequals;
7899
7900 /* Template functions may have different instantiations based on
7901 * "auto ref" parameters.
7902 */
7903 if (FuncDeclaration *fd = ti->toAlias()->isFuncDeclaration())
7904 {
7905 if (!fd->errors)
7906 {
7907 Parameters *fparameters = fd->getParameters(NULL);
7908 size_t nfparams = Parameter::dim(fparameters); // Num function parameters
7909 for (size_t j = 0; j < nfparams; j++)
7910 {
7911 Parameter *fparam = Parameter::getNth(fparameters, j);
7912 if (fparam->storageClass & STCautoref) // if "auto ref"
7913 {
7914 if (!fargs)
7915 goto Lnotequals;
7916 if (fargs->dim <= j)
7917 break;
7918 Expression *farg = (*fargs)[j];
7919 if (farg->isLvalue())
7920 {
7921 if (!(fparam->storageClass & STCref))
7922 goto Lnotequals; // auto ref's don't match
7923 }
7924 else
7925 {
7926 if (fparam->storageClass & STCref)
7927 goto Lnotequals; // auto ref's don't match
7928 }
7929 }
7930 }
7931 }
7932 }
7933 return 0;
7934
7935 Lnotequals:
7936 return 1;
7937}
7938
7939hash_t TemplateInstance::toHash()
7940{
7941 if (!hash)
7942 {
7943 hash = (size_t)(void *)enclosing;
7944 hash += arrayObjectHash(&tdtypes);
7945 hash += hash == 0;
7946 }
7947 return hash;
7948}
7949
7950/**************************************
7951 * IsExpression can evaluate the specified type speculatively, and even if
7952 * it instantiates any symbols, they are normally unnecessary for the
7953 * final executable.
7954 * However, if those symbols leak to the actual code, compiler should remark
7955 * them as non-speculative to generate their code and link to the final executable.
7956 */
7957void unSpeculative(Scope *sc, RootObject *o)
7958{
7959 if (!o)
7960 return;
7961
7962 if (Tuple *tup = isTuple(o))
7963 {
7964 for (size_t i = 0; i < tup->objects.dim; i++)
7965 {
7966 unSpeculative(sc, tup->objects[i]);
7967 }
7968 return;
7969 }
7970
7971 Dsymbol *s = getDsymbol(o);
7972 if (!s)
7973 return;
7974
7975 if (Declaration *d = s->isDeclaration())
7976 {
7977 if (VarDeclaration *vd = d->isVarDeclaration())
7978 o = vd->type;
7979 else if (AliasDeclaration *ad = d->isAliasDeclaration())
7980 {
7981 o = ad->getType();
7982 if (!o)
7983 o = ad->toAlias();
7984 }
7985 else
7986 o = d->toAlias();
7987
7988 s = getDsymbol(o);
7989 if (!s)
7990 return;
7991 }
7992
7993 if (TemplateInstance *ti = s->isTemplateInstance())
7994 {
7995 // If the instance is already non-speculative,
7996 // or it is leaked to the speculative scope.
7997 if (ti->minst != NULL || sc->minst == NULL)
7998 return;
7999
8000 // Remark as non-speculative instance.
8001 ti->minst = sc->minst;
8002 if (!ti->tinst)
8003 ti->tinst = sc->tinst;
8004
8005 unSpeculative(sc, ti->tempdecl);
8006 }
8007
8008 if (TemplateInstance *ti = s->isInstantiated())
8009 unSpeculative(sc, ti);
8010}
8011
8012/***********************************************
8013 * Returns true if this is not instantiated in non-root module, and
8014 * is a part of non-speculative instantiatiation.
8015 *
8016 * Note: minst does not stabilize until semantic analysis is completed,
8017 * so don't call this function during semantic analysis to return precise result.
8018 */
8019bool TemplateInstance::needsCodegen()
8020{
8021 // Now -allInst is just for the backward compatibility.
8022 if (global.params.allInst)
8023 {
8024 //printf("%s minst = %s, enclosing (%s)->isNonRoot = %d\n",
8025 // toPrettyChars(), minst ? minst->toChars() : NULL,
8026 // enclosing ? enclosing->toPrettyChars() : NULL, enclosing && enclosing->inNonRoot());
8027 if (enclosing)
8028 {
8029 // Bugzilla 14588: If the captured context is not a function
8030 // (e.g. class), the instance layout determination is guaranteed,
8031 // because the semantic/semantic2 pass will be executed
8032 // even for non-root instances.
8033 if (!enclosing->isFuncDeclaration())
8034 return true;
8035
8036 // Bugzilla 14834: If the captured context is a function,
8037 // this excessive instantiation may cause ODR violation, because
8038 // -allInst and others doesn't guarantee the semantic3 execution
8039 // for that function.
8040
8041 // If the enclosing is also an instantiated function,
8042 // we have to rely on the ancestor's needsCodegen() result.
8043 if (TemplateInstance *ti = enclosing->isInstantiated())
8044 return ti->needsCodegen();
8045
8046 // Bugzilla 13415: If and only if the enclosing scope needs codegen,
8047 // this nested templates would also need code generation.
8048 return !enclosing->inNonRoot();
8049 }
8050 return true;
8051 }
8052
8053 if (!minst)
8054 {
8055 // If this is a speculative instantiation,
8056 // 1. do codegen if ancestors really needs codegen.
8057 // 2. become non-speculative if siblings are not speculative
8058
8059 TemplateInstance *tnext = this->tnext;
8060 TemplateInstance *tinst = this->tinst;
8061 // At first, disconnect chain first to prevent infinite recursion.
8062 this->tnext = NULL;
8063 this->tinst = NULL;
8064
8065 // Determine necessity of tinst before tnext.
8066 if (tinst && tinst->needsCodegen())
8067 {
8068 minst = tinst->minst; // cache result
8069 assert(minst);
8070 assert(minst->isRoot() || minst->rootImports());
8071 return true;
8072 }
8073 if (tnext && (tnext->needsCodegen() || tnext->minst))
8074 {
8075 minst = tnext->minst; // cache result
8076 assert(minst);
8077 return minst->isRoot() || minst->rootImports();
8078 }
8079
8080 // Elide codegen because this is really speculative.
8081 return false;
8082 }
8083
8084 /* Even when this is reached to the codegen pass,
8085 * a non-root nested template should not generate code,
8086 * due to avoid ODR violation.
8087 */
8088 if (enclosing && enclosing->inNonRoot())
8089 {
8090 if (tinst)
8091 {
8092 bool r = tinst->needsCodegen();
8093 minst = tinst->minst; // cache result
8094 return r;
8095 }
8096 if (tnext)
8097 {
8098 bool r = tnext->needsCodegen();
8099 minst = tnext->minst; // cache result
8100 return r;
8101 }
8102 return false;
8103 }
8104
8105 /* The issue is that if the importee is compiled with a different -debug
8106 * setting than the importer, the importer may believe it exists
8107 * in the compiled importee when it does not, when the instantiation
8108 * is behind a conditional debug declaration.
8109 */
8110 // workaround for Bugzilla 11239
8111 if (global.params.useUnitTests ||
8112 global.params.debuglevel)
8113 {
8114 // Prefer instantiations from root modules, to maximize link-ability.
8115 if (minst->isRoot())
8116 return true;
8117
8118 TemplateInstance *tnext = this->tnext;
8119 TemplateInstance *tinst = this->tinst;
8120 this->tnext = NULL;
8121 this->tinst = NULL;
8122
8123 if (tinst && tinst->needsCodegen())
8124 {
8125 minst = tinst->minst; // cache result
8126 assert(minst);
8127 assert(minst->isRoot() || minst->rootImports());
8128 return true;
8129 }
8130 if (tnext && tnext->needsCodegen())
8131 {
8132 minst = tnext->minst; // cache result
8133 assert(minst);
8134 assert(minst->isRoot() || minst->rootImports());
8135 return true;
8136 }
8137
8138 // Bugzilla 2500 case
8139 if (minst->rootImports())
8140 return true;
8141
8142 // Elide codegen because this is not included in root instances.
8143 return false;
8144 }
8145 else
8146 {
8147 // Prefer instantiations from non-root module, to minimize object code size.
8148
8149 /* If a TemplateInstance is ever instantiated by non-root modules,
8150 * we do not have to generate code for it,
8151 * because it will be generated when the non-root module is compiled.
8152 *
8153 * But, if the non-root 'minst' imports any root modules, it might still need codegen.
8154 *
8155 * The problem is if A imports B, and B imports A, and both A
8156 * and B instantiate the same template, does the compilation of A
8157 * or the compilation of B do the actual instantiation?
8158 *
8159 * See Bugzilla 2500.
8160 */
8161 if (!minst->isRoot() && !minst->rootImports())
8162 return false;
8163
8164 TemplateInstance *tnext = this->tnext;
8165 this->tnext = NULL;
8166
8167 if (tnext && !tnext->needsCodegen() && tnext->minst)
8168 {
8169 minst = tnext->minst; // cache result
8170 assert(!minst->isRoot());
8171 return false;
8172 }
8173
8174 // Do codegen because this is not included in non-root instances.
8175 return true;
8176 }
8177}
8178
8179/* ======================== TemplateMixin ================================ */
8180
8181TemplateMixin::TemplateMixin(Loc loc, Identifier *ident, TypeQualified *tqual, Objects *tiargs)
8182 : TemplateInstance(loc, tqual->idents.dim ? (Identifier *)tqual->idents[tqual->idents.dim - 1]
8183 : ((TypeIdentifier *)tqual)->ident)
8184{
8185 //printf("TemplateMixin(ident = '%s')\n", ident ? ident->toChars() : "");
8186 this->ident = ident;
8187 this->tqual = tqual;
8188 this->tiargs = tiargs ? tiargs : new Objects();
8189}
8190
8191Dsymbol *TemplateMixin::syntaxCopy(Dsymbol *)
8192{
8193 TemplateMixin *tm = new TemplateMixin(loc, ident,
8194 (TypeQualified *)tqual->syntaxCopy(), tiargs);
8195 return TemplateInstance::syntaxCopy(tm);
8196}
8197
8198bool TemplateMixin::findTempDecl(Scope *sc)
8199{
8200 // Follow qualifications to find the TemplateDeclaration
8201 if (!tempdecl)
8202 {
8203 Expression *e;
8204 Type *t;
8205 Dsymbol *s;
8206 tqual->resolve(loc, sc, &e, &t, &s);
8207 if (!s)
8208 {
8209 error("is not defined");
8210 return false;
8211 }
8212 s = s->toAlias();
8213 tempdecl = s->isTemplateDeclaration();
8214 OverloadSet *os = s->isOverloadSet();
8215
8216 /* If an OverloadSet, look for a unique member that is a template declaration
8217 */
8218 if (os)
8219 {
8220 Dsymbol *ds = NULL;
8221 for (size_t i = 0; i < os->a.dim; i++)
8222 {
8223 Dsymbol *s2 = os->a[i]->isTemplateDeclaration();
8224 if (s2)
8225 {
8226 if (ds)
8227 {
8228 tempdecl = os;
8229 break;
8230 }
8231 ds = s2;
8232 }
8233 }
8234 }
8235 if (!tempdecl)
8236 {
8237 error("%s isn't a template", s->toChars());
8238 return false;
8239 }
8240 }
8241 assert(tempdecl);
8242
8243 struct ParamFwdResTm
8244 {
8245 static int fp(void *param, Dsymbol *s)
8246 {
8247 TemplateDeclaration *td = s->isTemplateDeclaration();
8248 if (!td)
8249 return 0;
8250
8251 TemplateMixin *tm = (TemplateMixin *)param;
8252 if (td->semanticRun == PASSinit)
8253 {
8254 if (td->_scope)
8255 td->semantic(td->_scope);
8256 else
8257 {
8258 tm->semanticRun = PASSinit;
8259 return 1;
8260 }
8261 }
8262 return 0;
8263 }
8264 };
8265 // Look for forward references
8266 OverloadSet *tovers = tempdecl->isOverloadSet();
8267 size_t overs_dim = tovers ? tovers->a.dim : 1;
8268 for (size_t oi = 0; oi < overs_dim; oi++)
8269 {
8270 if (overloadApply(tovers ? tovers->a[oi] : tempdecl, (void *)this, &ParamFwdResTm::fp))
8271 return false;
8272 }
8273 return true;
8274}
8275
8276void TemplateMixin::semantic(Scope *sc)
8277{
8278 if (semanticRun != PASSinit)
8279 {
8280 // When a class/struct contains mixin members, and is done over
8281 // because of forward references, never reach here so semanticRun
8282 // has been reset to PASSinit.
8283 return;
8284 }
8285 semanticRun = PASSsemantic;
8286
8287 Scope *scx = NULL;
8288 if (_scope)
8289 {
8290 sc = _scope;
8291 scx = _scope; // save so we don't make redundant copies
8292 _scope = NULL;
8293 }
8294
8295 /* Run semantic on each argument, place results in tiargs[],
8296 * then find best match template with tiargs
8297 */
8298 if (!findTempDecl(sc) ||
8299 !semanticTiargs(sc) ||
8300 !findBestMatch(sc, NULL))
8301 {
8302 if (semanticRun == PASSinit) // forward reference had occured
8303 {
8304 //printf("forward reference - deferring\n");
8305 _scope = scx ? scx : sc->copy();
8306 _scope->setNoFree();
8307 _scope->_module->addDeferredSemantic(this);
8308 return;
8309 }
8310
8311 inst = this;
8312 errors = true;
8313 return; // error recovery
8314 }
8315 TemplateDeclaration *tempdecl = this->tempdecl->isTemplateDeclaration();
8316 assert(tempdecl);
8317
8318 if (!ident)
8319 {
8320 /* Assign scope local unique identifier, as same as lambdas.
8321 */
8322 const char *s = "__mixin";
8323
8324 DsymbolTable *symtab;
8325 if (FuncDeclaration *func = sc->parent->isFuncDeclaration())
8326 {
8327 symtab = func->localsymtab;
8328 if (symtab)
8329 {
8330 // Inside template constraint, symtab is not set yet.
8331 goto L1;
8332 }
8333 }
8334 else
8335 {
8336 symtab = sc->parent->isScopeDsymbol()->symtab;
8337 L1:
8338 assert(symtab);
8339 int num = (int)dmd_aaLen(symtab->tab) + 1;
8340 ident = Identifier::generateId(s, num);
8341 symtab->insert(this);
8342 }
8343 }
8344
8345 inst = this;
8346 parent = sc->parent;
8347
8348 /* Detect recursive mixin instantiations.
8349 */
8350 for (Dsymbol *s = parent; s; s = s->parent)
8351 {
8352 //printf("\ts = '%s'\n", s->toChars());
8353 TemplateMixin *tm = s->isTemplateMixin();
8354 if (!tm || tempdecl != tm->tempdecl)
8355 continue;
8356
8357 /* Different argument list lengths happen with variadic args
8358 */
8359 if (tiargs->dim != tm->tiargs->dim)
8360 continue;
8361
8362 for (size_t i = 0; i < tiargs->dim; i++)
8363 {
8364 RootObject *o = (*tiargs)[i];
8365 Type *ta = isType(o);
8366 Expression *ea = isExpression(o);
8367 Dsymbol *sa = isDsymbol(o);
8368 RootObject *tmo = (*tm->tiargs)[i];
8369 if (ta)
8370 {
8371 Type *tmta = isType(tmo);
8372 if (!tmta)
8373 goto Lcontinue;
8374 if (!ta->equals(tmta))
8375 goto Lcontinue;
8376 }
8377 else if (ea)
8378 {
8379 Expression *tme = isExpression(tmo);
8380 if (!tme || !ea->equals(tme))
8381 goto Lcontinue;
8382 }
8383 else if (sa)
8384 {
8385 Dsymbol *tmsa = isDsymbol(tmo);
8386 if (sa != tmsa)
8387 goto Lcontinue;
8388 }
8389 else
8390 assert(0);
8391 }
8392 error("recursive mixin instantiation");
8393 return;
8394
8395 Lcontinue:
8396 continue;
8397 }
8398
8399 // Copy the syntax trees from the TemplateDeclaration
8400 members = Dsymbol::arraySyntaxCopy(tempdecl->members);
8401 if (!members)
8402 return;
8403
8404 symtab = new DsymbolTable();
8405
8406 for (Scope *sce = sc; 1; sce = sce->enclosing)
8407 {
8408 ScopeDsymbol *sds = (ScopeDsymbol *)sce->scopesym;
8409 if (sds)
8410 {
8411 sds->importScope(this, Prot(PROTpublic));
8412 break;
8413 }
8414 }
8415
8416 Scope *scy = sc->push(this);
8417 scy->parent = this;
8418
8419 argsym = new ScopeDsymbol();
8420 argsym->parent = scy->parent;
8421 Scope *argscope = scy->push(argsym);
8422
8423 unsigned errorsave = global.errors;
8424
8425 // Declare each template parameter as an alias for the argument type
8426 declareParameters(argscope);
8427
8428 // Add members to enclosing scope, as well as this scope
8429 for (size_t i = 0; i < members->dim; i++)
8430 {
8431 Dsymbol *s = (*members)[i];
8432 s->addMember(argscope, this);
8433 //printf("sc->parent = %p, sc->scopesym = %p\n", sc->parent, sc->scopesym);
8434 //printf("s->parent = %s\n", s->parent->toChars());
8435 }
8436
8437 // Do semantic() analysis on template instance members
8438 Scope *sc2 = argscope->push(this);
8439 //size_t deferred_dim = Module::deferred.dim;
8440
8441 static int nest;
8442 //printf("%d\n", nest);
8443 if (++nest > 500)
8444 {
8445 global.gag = 0; // ensure error message gets printed
8446 error("recursive expansion");
8447 fatal();
8448 }
8449
8450 for (size_t i = 0; i < members->dim; i++)
8451 {
8452 Dsymbol *s = (*members)[i];
8453 s->setScope(sc2);
8454 }
8455
8456 for (size_t i = 0; i < members->dim; i++)
8457 {
8458 Dsymbol *s = (*members)[i];
8459 s->importAll(sc2);
8460 }
8461
8462 for (size_t i = 0; i < members->dim; i++)
8463 {
8464 Dsymbol *s = (*members)[i];
8465 s->semantic(sc2);
8466 }
8467
8468 nest--;
8469
8470 /* In DeclDefs scope, TemplateMixin does not have to handle deferred symbols.
8471 * Because the members would already call Module::addDeferredSemantic() for themselves.
8472 * See Struct, Class, Interface, and EnumDeclaration::semantic().
8473 */
8474 //if (!sc->func && Module::deferred.dim > deferred_dim) {}
8475
8476 AggregateDeclaration *ad = toParent()->isAggregateDeclaration();
8477 if (sc->func && !ad)
8478 {
8479 semantic2(sc2);
8480 semantic3(sc2);
8481 }
8482
8483 // Give additional context info if error occurred during instantiation
8484 if (global.errors != errorsave)
8485 {
8486 error("error instantiating");
8487 errors = true;
8488 }
8489
8490 sc2->pop();
8491 argscope->pop();
8492 scy->pop();
8493}
8494
8495void TemplateMixin::semantic2(Scope *sc)
8496{
8497 if (semanticRun >= PASSsemantic2)
8498 return;
8499 semanticRun = PASSsemantic2;
8500 if (members)
8501 {
8502 assert(sc);
8503 sc = sc->push(argsym);
8504 sc = sc->push(this);
8505 for (size_t i = 0; i < members->dim; i++)
8506 {
8507 Dsymbol *s = (*members)[i];
8508 s->semantic2(sc);
8509 }
8510 sc = sc->pop();
8511 sc->pop();
8512 }
8513}
8514
8515void TemplateMixin::semantic3(Scope *sc)
8516{
8517 if (semanticRun >= PASSsemantic3)
8518 return;
8519 semanticRun = PASSsemantic3;
8520 if (members)
8521 {
8522 sc = sc->push(argsym);
8523 sc = sc->push(this);
8524 for (size_t i = 0; i < members->dim; i++)
8525 {
8526 Dsymbol *s = (*members)[i];
8527 s->semantic3(sc);
8528 }
8529 sc = sc->pop();
8530 sc->pop();
8531 }
8532}
8533
f9ab59ff 8534const char *TemplateMixin::kind() const
b4c522fa
IB
8535{
8536 return "mixin";
8537}
8538
8539bool TemplateMixin::oneMember(Dsymbol **ps, Identifier *ident)
8540{
8541 return Dsymbol::oneMember(ps, ident);
8542}
8543
8544int TemplateMixin::apply(Dsymbol_apply_ft_t fp, void *param)
8545{
8546 if (_scope) // if fwd reference
8547 semantic(NULL); // try to resolve it
8548 if (members)
8549 {
8550 for (size_t i = 0; i < members->dim; i++)
8551 {
8552 Dsymbol *s = (*members)[i];
8553 if (s)
8554 {
8555 if (s->apply(fp, param))
8556 return 1;
8557 }
8558 }
8559 }
8560 return 0;
8561}
8562
8563bool TemplateMixin::hasPointers()
8564{
8565 //printf("TemplateMixin::hasPointers() %s\n", toChars());
8566
8567 if (members)
8568 {
8569 for (size_t i = 0; i < members->dim; i++)
8570 {
8571 Dsymbol *s = (*members)[i];
8572 //printf(" s = %s %s\n", s->kind(), s->toChars());
8573 if (s->hasPointers())
8574 {
8575 return true;
8576 }
8577 }
8578 }
8579 return false;
8580}
8581
8582void TemplateMixin::setFieldOffset(AggregateDeclaration *ad, unsigned *poffset, bool isunion)
8583{
8584 //printf("TemplateMixin::setFieldOffset() %s\n", toChars());
8585 if (_scope) // if fwd reference
8586 semantic(NULL); // try to resolve it
8587 if (members)
8588 {
8589 for (size_t i = 0; i < members->dim; i++)
8590 {
8591 Dsymbol *s = (*members)[i];
8592 //printf("\t%s\n", s->toChars());
8593 s->setFieldOffset(ad, poffset, isunion);
8594 }
8595 }
8596}
8597
8598const char *TemplateMixin::toChars()
8599{
8600 OutBuffer buf;
8601 toCBufferInstance(this, &buf);
8602 return buf.extractString();
8603}