]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/d/dmd/dtemplate.c
gcov-profile: use static pool for TOPN first
[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{
2cbc99d1 124 for (size_t i = 0; i < args->length; i++)
b4c522fa
IB
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;
2cbc99d1 373 if (oa1->length != oa2->length)
b4c522fa 374 return 0;
2cbc99d1 375 for (size_t j = 0; j < oa1->length; j++)
b4c522fa
IB
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;
2cbc99d1 426 for (size_t i = 0; i < te->exps->length; i++)
b4c522fa
IB
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;
2cbc99d1 438 for (size_t i = 0; i < ae->elements->length; i++)
b4c522fa
IB
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;
2cbc99d1 447 for (size_t i = 0; i < ae->keys->length; i++)
b4c522fa
IB
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;
2cbc99d1 457 for (size_t i = 0; i < se->elements->length; i++)
b4c522fa
IB
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;
2cbc99d1 485 for (size_t j = 0; j < oa1->length; j++)
b4c522fa
IB
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;
0a2ee409 538 this->protection = Prot(Prot::undefined);
b4c522fa
IB
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();
2cbc99d1
IB
561 p->setDim(parameters->length);
562 for (size_t i = 0; i < p->length; i++)
b4c522fa
IB
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();
2cbc99d1
IB
612 origParameters->setDim(parameters->length);
613 for (size_t i = 0; i < parameters->length; i++)
b4c522fa
IB
614 {
615 TemplateParameter *tp = (*parameters)[i];
616 (*origParameters)[i] = tp->syntaxCopy();
617 }
618 }
619
2cbc99d1 620 for (size_t i = 0; i < parameters->length; i++)
b4c522fa
IB
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 }
2cbc99d1 633 if (i + 1 != parameters->length && tp->isTemplateTupleParameter())
b4c522fa
IB
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);
2cbc99d1 644 for (size_t i = 0; i < parameters->length; i++)
b4c522fa
IB
645 {
646 TemplateParameter *tp = (*parameters)[i];
647 tparams[0] = tp;
648
2cbc99d1 649 for (size_t j = 0; j < parameters->length; j++)
b4c522fa
IB
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
c3a2ba10
IB
789 Parameters *fparameters = tf->parameterList.parameters;
790 VarArg fvarargs = tf->parameterList.varargs;
b4c522fa
IB
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;
c3a2ba10 798 if (fvarargs == VARARGtypesafe && i + 1 == nfparams)
b4c522fa
IB
799 fparam->storageClass |= STCvariadic;
800 }
2cbc99d1 801 for (size_t i = 0; i < fparameters->length; i++)
b4c522fa
IB
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;
2cbc99d1 855 size_t dedtypes_dim = dedtypes->length;
b4c522fa
IB
856
857 dedtypes->zero();
858
859 if (errors)
860 return MATCHnomatch;
861
2cbc99d1 862 size_t parameters_dim = parameters->length;
b4c522fa
IB
863 int variadic = isVariadic() != NULL;
864
865 // If more arguments than parameters, no match
2cbc99d1 866 if (ti->tiargs->length > parameters_dim && !variadic)
b4c522fa
IB
867 {
868 return MATCHnomatch;
869 }
870
871 assert(dedtypes_dim == parameters_dim);
2cbc99d1 872 assert(dedtypes_dim >= ti->tiargs->length || variadic);
b4c522fa
IB
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 {
2cbc99d1 921 assert(i < ti->tiargs->length);
b4c522fa
IB
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.
c3a2ba10
IB
946 for (size_t i = 0; i < tf->parameterList.parameters->length; i++)
947 (*tf->parameterList.parameters)[i]->defaultArg = NULL;
b4c522fa
IB
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();
2cbc99d1
IB
998 ti.tiargs->reserve(parameters->length);
999 for (size_t i = 0; i < parameters->length; i++)
b4c522fa
IB
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;
2cbc99d1 1013 dedtypes.setDim(td2->parameters->length);
b4c522fa
IB
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;
2cbc99d1 1067 for (size_t j = 0; j < argexps.length; j++)
b4c522fa
IB
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;
c3a2ba10 1113 ParameterList fparameters; // function parameter list
b4c522fa
IB
1114 unsigned wildmatch = 0;
1115 size_t inferStart = 0;
1116
1117 Loc instLoc = ti->loc;
1118 Objects *tiargs = ti->tiargs;
1119 Objects *dedargs = new Objects();
1120 Objects* dedtypes = &ti->tdtypes; // for T:T*, the dedargs is the T*, dedtypes is the T
1121
1122 assert(_scope);
1123
2cbc99d1 1124 dedargs->setDim(parameters->length);
b4c522fa
IB
1125 dedargs->zero();
1126
2cbc99d1 1127 dedtypes->setDim(parameters->length);
b4c522fa
IB
1128 dedtypes->zero();
1129
1130 if (errors || fd->errors)
1131 return MATCHnomatch;
1132
1133 // Set up scope for parameters
1134 ScopeDsymbol *paramsym = new ScopeDsymbol();
1135 paramsym->parent = _scope->parent; // should use hasnestedArgs and enclosing?
1136 Scope *paramscope = _scope->push(paramsym);
1137 paramscope->tinst = ti;
1138 paramscope->minst = sc->minst;
1139 paramscope->callsc = sc;
1140 paramscope->stc = 0;
1141
1142 TemplateTupleParameter *tp = isVariadic();
1143 Tuple *declaredTuple = NULL;
1144
1145 ntargs = 0;
1146 if (tiargs)
1147 {
1148 // Set initial template arguments
2cbc99d1
IB
1149 ntargs = tiargs->length;
1150 size_t n = parameters->length;
b4c522fa
IB
1151 if (tp)
1152 n--;
1153 if (ntargs > n)
1154 {
1155 if (!tp)
1156 goto Lnomatch;
1157
1158 /* The extra initial template arguments
1159 * now form the tuple argument.
1160 */
1161 Tuple *t = new Tuple();
2cbc99d1
IB
1162 assert(parameters->length);
1163 (*dedargs)[parameters->length - 1] = t;
b4c522fa
IB
1164
1165 t->objects.setDim(ntargs - n);
2cbc99d1 1166 for (size_t i = 0; i < t->objects.length; i++)
b4c522fa
IB
1167 {
1168 t->objects[i] = (*tiargs)[n + i];
1169 }
1170 declareParameter(paramscope, tp, t);
1171 declaredTuple = t;
1172 }
1173 else
1174 n = ntargs;
1175
1176 memcpy(dedargs->tdata(), tiargs->tdata(), n * sizeof(*dedargs->tdata()));
1177
1178 for (size_t i = 0; i < n; i++)
1179 {
2cbc99d1 1180 assert(i < parameters->length);
b4c522fa
IB
1181 Declaration *sparam = NULL;
1182 MATCH m = (*parameters)[i]->matchArg(instLoc, paramscope, dedargs, i, parameters, dedtypes, &sparam);
1183 //printf("\tdeduceType m = %d\n", m);
1184 if (m <= MATCHnomatch)
1185 goto Lnomatch;
1186 if (m < matchTiargs)
1187 matchTiargs = m;
1188
1189 sparam->semantic(paramscope);
1190 if (!paramscope->insert(sparam))
1191 goto Lnomatch;
1192 }
2cbc99d1 1193 if (n < parameters->length && !declaredTuple)
b4c522fa
IB
1194 {
1195 inferStart = n;
1196 }
1197 else
2cbc99d1 1198 inferStart = parameters->length;
b4c522fa
IB
1199 //printf("tiargs matchTiargs = %d\n", matchTiargs);
1200 }
1201
c3a2ba10
IB
1202 fparameters = fd->getParameterList();
1203 nfparams = fparameters.length(); // number of function parameters
1204 nfargs = fargs ? fargs->length : 0; // number of function arguments
b4c522fa
IB
1205
1206 /* Check for match of function arguments with variadic template
1207 * parameter, such as:
1208 *
1209 * void foo(T, A...)(T t, A a);
1210 * void main() { foo(1,2,3); }
1211 */
1212 if (tp) // if variadic
1213 {
1214 // TemplateTupleParameter always makes most lesser matching.
1215 matchTiargs = MATCHconvert;
1216
1217 if (nfparams == 0 && nfargs != 0) // if no function parameters
1218 {
1219 if (!declaredTuple)
1220 {
1221 Tuple *t = new Tuple();
1222 //printf("t = %p\n", t);
2cbc99d1 1223 (*dedargs)[parameters->length - 1] = t;
b4c522fa
IB
1224 declareParameter(paramscope, tp, t);
1225 declaredTuple = t;
1226 }
1227 }
1228 else
1229 {
1230 /* Figure out which of the function parameters matches
1231 * the tuple template parameter. Do this by matching
1232 * type identifiers.
1233 * Set the index of this function parameter to fptupindex.
1234 */
1235 for (fptupindex = 0; fptupindex < nfparams; fptupindex++)
1236 {
c3a2ba10 1237 Parameter *fparam = (*fparameters.parameters)[fptupindex];
b4c522fa
IB
1238 if (fparam->type->ty != Tident)
1239 continue;
1240 TypeIdentifier *tid = (TypeIdentifier *)fparam->type;
2cbc99d1 1241 if (!tp->ident->equals(tid->ident) || tid->idents.length)
b4c522fa
IB
1242 continue;
1243
c3a2ba10 1244 if (fparameters.varargs != VARARGnone) // variadic function doesn't
b4c522fa
IB
1245 goto Lnomatch; // go with variadic template
1246
1247 goto L1;
1248 }
1249 fptupindex = IDX_NOTFOUND;
1250 L1:
1251 ;
1252 }
1253 }
1254
1255 if (toParent()->isModule() || (_scope->stc & STCstatic))
1256 tthis = NULL;
1257 if (tthis)
1258 {
1259 bool hasttp = false;
1260
1261 // Match 'tthis' to any TemplateThisParameter's
2cbc99d1 1262 for (size_t i = 0; i < parameters->length; i++)
b4c522fa
IB
1263 {
1264 TemplateThisParameter *ttp = (*parameters)[i]->isTemplateThisParameter();
1265 if (ttp)
1266 {
1267 hasttp = true;
1268
1269 Type *t = new TypeIdentifier(Loc(), ttp->ident);
1270 MATCH m = deduceType(tthis, paramscope, t, parameters, dedtypes);
1271 if (m <= MATCHnomatch)
1272 goto Lnomatch;
1273 if (m < match)
1274 match = m; // pick worst match
1275 }
1276 }
1277
1278 // Match attributes of tthis against attributes of fd
1279 if (fd->type && !fd->isCtorDeclaration())
1280 {
1281 StorageClass stc = _scope->stc | fd->storage_class2;
1282 // Propagate parent storage class (see bug 5504)
1283 Dsymbol *p = parent;
1284 while (p->isTemplateDeclaration() || p->isTemplateInstance())
1285 p = p->parent;
1286 AggregateDeclaration *ad = p->isAggregateDeclaration();
1287 if (ad)
1288 stc |= ad->storage_class;
1289
1290 unsigned char mod = fd->type->mod;
1291 if (stc & STCimmutable)
1292 mod = MODimmutable;
1293 else
1294 {
1295 if (stc & (STCshared | STCsynchronized))
1296 mod |= MODshared;
1297 if (stc & STCconst)
1298 mod |= MODconst;
1299 if (stc & STCwild)
1300 mod |= MODwild;
1301 }
1302
1303 unsigned char thismod = tthis->mod;
1304 if (hasttp)
1305 mod = MODmerge(thismod, mod);
1306 MATCH m = MODmethodConv(thismod, mod);
1307 if (m <= MATCHnomatch)
1308 goto Lnomatch;
1309 if (m < match)
1310 match = m;
1311 }
1312 }
1313
1314 // Loop through the function parameters
1315 {
2cbc99d1 1316 //printf("%s\n\tnfargs = %d, nfparams = %d, tuple_dim = %d\n", toChars(), nfargs, nfparams, declaredTuple ? declaredTuple->objects.length : 0);
b4c522fa
IB
1317 //printf("\ttp = %p, fptupindex = %d, found = %d, declaredTuple = %s\n", tp, fptupindex, fptupindex != IDX_NOTFOUND, declaredTuple ? declaredTuple->toChars() : NULL);
1318 size_t argi = 0;
1319 size_t nfargs2 = nfargs; // nfargs + supplied defaultArgs
1320 for (size_t parami = 0; parami < nfparams; parami++)
1321 {
c3a2ba10 1322 Parameter *fparam = fparameters[parami];
b4c522fa
IB
1323
1324 // Apply function parameter storage classes to parameter types
1325 Type *prmtype = fparam->type->addStorageClass(fparam->storageClass);
1326
1327 Expression *farg;
1328
1329 /* See function parameters which wound up
1330 * as part of a template tuple parameter.
1331 */
1332 if (fptupindex != IDX_NOTFOUND && parami == fptupindex)
1333 {
1334 assert(prmtype->ty == Tident);
1335 TypeIdentifier *tid = (TypeIdentifier *)prmtype;
1336 if (!declaredTuple)
1337 {
1338 /* The types of the function arguments
1339 * now form the tuple argument.
1340 */
1341 declaredTuple = new Tuple();
2cbc99d1 1342 (*dedargs)[parameters->length - 1] = declaredTuple;
b4c522fa
IB
1343
1344 /* Count function parameters following a tuple parameter.
1345 * void foo(U, T...)(int y, T, U, int) {} // rem == 2 (U, int)
1346 */
1347 size_t rem = 0;
1348 for (size_t j = parami + 1; j < nfparams; j++)
1349 {
c3a2ba10 1350 Parameter *p = fparameters[j];
b4c522fa
IB
1351 if (!reliesOnTident(p->type, parameters, inferStart))
1352 {
1353 Type *pt = p->type->syntaxCopy()->semantic(fd->loc, paramscope);
2cbc99d1 1354 rem += pt->ty == Ttuple ? ((TypeTuple *)pt)->arguments->length : 1;
b4c522fa
IB
1355 }
1356 else
1357 {
1358 ++rem;
1359 }
1360 }
1361
1362 if (nfargs2 - argi < rem)
1363 goto Lnomatch;
1364 declaredTuple->objects.setDim(nfargs2 - argi - rem);
2cbc99d1 1365 for (size_t i = 0; i < declaredTuple->objects.length; i++)
b4c522fa
IB
1366 {
1367 farg = (*fargs)[argi + i];
1368
1369 // Check invalid arguments to detect errors early.
1370 if (farg->op == TOKerror || farg->type->ty == Terror)
1371 goto Lnomatch;
1372
1373 if (!(fparam->storageClass & STClazy) && farg->type->ty == Tvoid)
1374 goto Lnomatch;
1375
1376 Type *tt;
1377 MATCH m;
1378 if (unsigned char wm = deduceWildHelper(farg->type, &tt, tid))
1379 {
1380 wildmatch |= wm;
1381 m = MATCHconst;
1382 }
1383 else
1384 {
1385 m = deduceTypeHelper(farg->type, &tt, tid);
1386 }
1387 if (m <= MATCHnomatch)
1388 goto Lnomatch;
1389 if (m < match)
1390 match = m;
1391
1392 /* Remove top const for dynamic array types and pointer types
1393 */
1394 if ((tt->ty == Tarray || tt->ty == Tpointer) &&
1395 !tt->isMutable() &&
1396 (!(fparam->storageClass & STCref) ||
1397 ((fparam->storageClass & STCauto) && !farg->isLvalue())))
1398 {
1399 tt = tt->mutableOf();
1400 }
1401 declaredTuple->objects[i] = tt;
1402 }
1403 declareParameter(paramscope, tp, declaredTuple);
1404 }
1405 else
1406 {
1407 // Bugzilla 6810: If declared tuple is not a type tuple,
1408 // it cannot be function parameter types.
2cbc99d1 1409 for (size_t i = 0; i < declaredTuple->objects.length; i++)
b4c522fa
IB
1410 {
1411 if (!isType(declaredTuple->objects[i]))
1412 goto Lnomatch;
1413 }
1414 }
1415 assert(declaredTuple);
2cbc99d1 1416 argi += declaredTuple->objects.length;
b4c522fa
IB
1417 continue;
1418 }
1419
1420 // If parameter type doesn't depend on inferred template parameters,
1421 // semantic it to get actual type.
1422 if (!reliesOnTident(prmtype, parameters, inferStart))
1423 {
1424 // should copy prmtype to avoid affecting semantic result
1425 prmtype = prmtype->syntaxCopy()->semantic(fd->loc, paramscope);
1426
1427 if (prmtype->ty == Ttuple)
1428 {
1429 TypeTuple *tt = (TypeTuple *)prmtype;
2cbc99d1 1430 size_t tt_dim = tt->arguments->length;
b4c522fa
IB
1431 for (size_t j = 0; j < tt_dim; j++, ++argi)
1432 {
1433 Parameter *p = (*tt->arguments)[j];
c3a2ba10
IB
1434 if (j == tt_dim - 1 && fparameters.varargs == VARARGtypesafe &&
1435 parami + 1 == nfparams && argi < nfargs)
b4c522fa
IB
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 {
2cbc99d1 1477 for (size_t i = 0; i < dedtypes->length; i++)
b4c522fa
IB
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 }
2cbc99d1 1487 for (size_t i = ntargs; i < dedargs->length; i++)
b4c522fa
IB
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 &&
2cbc99d1 1586 ((TypeIdentifier *)taai)->idents.length == 0)))
b4c522fa
IB
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;
2cbc99d1 1596 argtype = ae->type->nextOf()->sarrayOf(ae->elements->length);
b4c522fa
IB
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 &&
2cbc99d1 1611 ((TypeIdentifier *)prmtype)->idents.length == 0)
b4c522fa
IB
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
c3a2ba10 1632 if (fparameters.varargs == VARARGtypesafe && parami + 1 == nfparams && argi + 1 < nfargs)
b4c522fa
IB
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 */
c3a2ba10 1702 if (!(fparameters.varargs == VARARGtypesafe && parami + 1 == nfparams))
b4c522fa
IB
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);
c3a2ba10 1836 if (argi != nfargs2 && fparameters.varargs == VARARGnone)
b4c522fa
IB
1837 goto Lnomatch;
1838 }
1839
1840Lmatch:
1841
2cbc99d1 1842 for (size_t i = 0; i < dedtypes->length; i++)
b4c522fa
IB
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 }
2cbc99d1 1856 for (size_t i = ntargs; i < dedargs->length; i++)
b4c522fa
IB
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 &&
2cbc99d1 1903 ntargs <= dedargs->length - 1)
b4c522fa
IB
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 */
2cbc99d1 1942 if (size_t d = dedargs->length)
b4c522fa
IB
1943 {
1944 if (Tuple *va = isTuple((*dedargs)[d - 1]))
1945 {
2cbc99d1 1946 if (va->objects.length)
b4c522fa
IB
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{
2cbc99d1 2096 size_t dim = parameters->length;
b4c522fa
IB
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
2cbc99d1 2170 if (tiargs && tiargs->length > 0)
b4c522fa
IB
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;
2cbc99d1 2336 dedtypes.setDim(td->parameters->length);
b4c522fa
IB
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;
2cbc99d1 2667 for (size_t i = 0; i < parameters->length; i++)
b4c522fa
IB
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.
c3a2ba10
IB
2684 for (size_t i = 0; i < tf->parameterList.parameters->length; i++)
2685 (*tf->parameterList.parameters)[i]->defaultArg = NULL;
b4c522fa
IB
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('(');
2cbc99d1 2743 for (size_t i = 0; i < parameters->length; i++)
b4c522fa
IB
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;
c3a2ba10 2758 buf.writestring(parametersTypeToChars(tf->parameterList));
b4c522fa
IB
2759 }
2760 }
2761
2762 if (constraint)
2763 {
2764 buf.writestring(" if (");
2765 ::toCBuffer(constraint, &buf, &hgs);
2766 buf.writeByte(')');
2767 }
fced594b 2768 return buf.extractChars();
b4c522fa
IB
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 {
2cbc99d1 2789 for (size_t i = 0; i < tinstances->length; i++)
b4c522fa
IB
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 {
2cbc99d1 2826 for (size_t i = 0; i < tinstances->length; i++)
b4c522fa
IB
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{
2cbc99d1 2847 for (size_t i = 0; i < parameters->length; i++)
b4c522fa
IB
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;
2cbc99d1 3192 if (parameters->length)
b4c522fa
IB
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;
2cbc99d1 3210 if (tident->idents.length > 0)
b4c522fa
IB
3211 {
3212 //printf("matching %s to %s\n", tparam->toChars(), t->toChars());
3213 Dsymbol *s = t->toDsymbol(sc);
2cbc99d1 3214 for (size_t j = tident->idents.length; j-- > 0; )
b4c522fa
IB
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;
2cbc99d1 3367 if (parameters->length)
b4c522fa
IB
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;
c3a2ba10 3540 if (t->parameterList.varargs != tp->parameterList.varargs ||
b4c522fa
IB
3541 t->linkage != tp->linkage)
3542 {
3543 result = MATCHnomatch;
3544 return;
3545 }
3546
c3a2ba10
IB
3547 size_t nfargs = t->parameterList.length();
3548 size_t nfparams = tp->parameterList.length();
b4c522fa
IB
3549
3550 // bug 2579 fix: Apply function parameter storage classes to parameter types
3551 for (size_t i = 0; i < nfparams; i++)
3552 {
c3a2ba10 3553 Parameter *fparam = tp->parameterList[i];
b4c522fa
IB
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 */
c3a2ba10 3567 Parameter *fparam = tp->parameterList[nfparams - 1];
b4c522fa
IB
3568 assert(fparam);
3569 assert(fparam->type);
3570 if (fparam->type->ty != Tident)
3571 goto L1;
3572 TypeIdentifier *tid = (TypeIdentifier *)fparam->type;
2cbc99d1 3573 if (tid->idents.length)
b4c522fa
IB
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 {
2cbc99d1 3581 if (tupi == parameters->length)
b4c522fa
IB
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);
2cbc99d1 3601 if (!tup || tup->objects.length != tuple_dim)
b4c522fa
IB
3602 {
3603 result = MATCHnomatch;
3604 return;
3605 }
3606 for (size_t i = 0; i < tuple_dim; i++)
3607 {
c3a2ba10 3608 Parameter *arg = t->parameterList[nfparams - 1 + i];
b4c522fa
IB
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 {
c3a2ba10 3623 Parameter *arg = t->parameterList[nfparams - 1 + i];
b4c522fa
IB
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 {
c3a2ba10
IB
3641 Parameter *a = t->parameterList[i];
3642 Parameter *ap = tp->parameterList[i];
b4c522fa
IB
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
2cbc99d1 3662 for (size_t i = 0; i < t->idents.length; i++)
b4c522fa
IB
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;
2cbc99d1 3751 if (i < t->tempinst->tiargs->length)
b4c522fa 3752 o1 = (*t->tempinst->tiargs)[i];
2cbc99d1 3753 else if (i < t->tempinst->tdtypes.length && i < tp->tempinst->tiargs->length)
b4c522fa
IB
3754 {
3755 // Pick up default arg
3756 o1 = t->tempinst->tdtypes[i];
3757 }
2cbc99d1 3758 else if (i >= tp->tempinst->tiargs->length)
b4c522fa
IB
3759 break;
3760
2cbc99d1 3761 if (i >= tp->tempinst->tiargs->length)
b4c522fa 3762 {
2cbc99d1 3763 size_t dim = tempdecl->parameters->length - (tempdecl->isVariadic() ? 1 : 0);
b4c522fa
IB
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
2cbc99d1 3777 size_t j = (t2 && t2->ty == Tident && i == tp->tempinst->tiargs->length - 1)
b4c522fa 3778 ? templateParameterLookup(t2, parameters) : IDX_NOTFOUND;
2cbc99d1 3779 if (j != IDX_NOTFOUND && j == parameters->length - 1 &&
b4c522fa
IB
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()
2cbc99d1 3793 ? t->tempinst->tiargs->length : t->tempinst->tdtypes.length) - i;
b4c522fa
IB
3794 vt->objects.setDim(vtdim);
3795 for (size_t k = 0; k < vtdim; k++)
3796 {
3797 RootObject *o;
2cbc99d1 3798 if (k < t->tempinst->tiargs->length)
b4c522fa
IB
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;
2cbc99d1 3932 if (tpi->idents.length)
b4c522fa 3933 {
2cbc99d1 3934 RootObject *id = tpi->idents[tpi->idents.length - 1];
b4c522fa
IB
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 */
2cbc99d1 3942 tpi->idents.length--;
b4c522fa 3943 result = deduceType(tparent, sc, tpi, parameters, dedtypes, wm);
2cbc99d1 3944 tpi->idents.length++;
b4c522fa
IB
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();
2cbc99d1
IB
4017 tmpdedtypes->setDim(dedtypes->length);
4018 memcpy(tmpdedtypes->tdata(), dedtypes->tdata(), dedtypes->length * sizeof(void *));
b4c522fa
IB
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)
2cbc99d1
IB
4026 memcpy(best->tdata(), tmpdedtypes->tdata(), tmpdedtypes->length * sizeof(void *));
4027 else for (size_t k = 0; k < tmpdedtypes->length; ++k)
b4c522fa
IB
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;
2cbc99d1 4077 if (tpi->idents.length)
b4c522fa 4078 {
2cbc99d1 4079 RootObject *id = tpi->idents[tpi->idents.length - 1];
b4c522fa
IB
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 */
2cbc99d1 4087 tpi->idents.length--;
b4c522fa 4088 result = deduceType(tparent, sc, tpi, parameters, dedtypes, wm);
2cbc99d1 4089 tpi->idents.length++;
b4c522fa
IB
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();
2cbc99d1 4109 best->setDim(dedtypes->length);
b4c522fa
IB
4110
4111 ClassDeclaration *s = t->sym;
2cbc99d1 4112 while (s && s->baseclasses->length > 0)
b4c522fa
IB
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
2cbc99d1 4136 memcpy(dedtypes->tdata(), best->tdata(), best->length * sizeof(void *));
b4c522fa
IB
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);
2cbc99d1 4162 if (i == IDX_NOTFOUND || ((TypeIdentifier *)tparam)->idents.length > 0)
b4c522fa
IB
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 &&
2cbc99d1 4329 ((TypeIdentifier *)taai)->idents.length == 0)))
b4c522fa
IB
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 {
0f5c98b6
IB
4340 // https://issues.dlang.org/show_bug.cgi?id=20092
4341 if (e->elements && e->elements->length &&
4342 e->type->toBasetype()->nextOf()->ty == Tvoid)
4343 {
4344 result = deduceEmptyArrayElement();
4345 return;
4346 }
2cbc99d1 4347 if ((!e->elements || !e->elements->length) &&
b4c522fa
IB
4348 e->type->toBasetype()->nextOf()->ty == Tvoid &&
4349 tparam->ty == Tarray)
4350 {
4351 // tparam:T[] <- e:[] (void[])
4352 result = deduceEmptyArrayElement();
4353 return;
4354 }
4355
2cbc99d1 4356 if (tparam->ty == Tarray && e->elements && e->elements->length)
b4c522fa
IB
4357 {
4358 Type *tn = ((TypeDArray *)tparam)->next;
4359 result = MATCHexact;
4360 if (e->basis)
4361 {
4362 MATCH m = deduceType(e->basis, sc, tn, parameters, dedtypes, wm);
4363 if (m < result)
4364 result = m;
4365 }
2cbc99d1 4366 for (size_t i = 0; i < e->elements->length; i++)
b4c522fa
IB
4367 {
4368 if (result <= MATCHnomatch)
4369 break;
4370 Expression *el = (*e->elements)[i];
4371 if (!el)
4372 continue;
4373 MATCH m = deduceType(el, sc, tn, parameters, dedtypes, wm);
4374 if (m < result)
4375 result = m;
4376 }
4377 return;
4378 }
4379
4380 Type *taai;
4381 if (e->type->ty == Tarray &&
4382 (tparam->ty == Tsarray ||
4383 (tparam->ty == Taarray && (taai = ((TypeAArray *)tparam)->index)->ty == Tident &&
2cbc99d1 4384 ((TypeIdentifier *)taai)->idents.length == 0)))
b4c522fa
IB
4385 {
4386 // Consider compile-time known boundaries
2cbc99d1 4387 e->type->nextOf()->sarrayOf(e->elements->length)->accept(this);
b4c522fa
IB
4388 return;
4389 }
4390 visit((Expression *)e);
4391 }
4392
4393 void visit(AssocArrayLiteralExp *e)
4394 {
2cbc99d1 4395 if (tparam->ty == Taarray && e->keys && e->keys->length)
b4c522fa
IB
4396 {
4397 TypeAArray *taa = (TypeAArray *)tparam;
4398 result = MATCHexact;
2cbc99d1 4399 for (size_t i = 0; i < e->keys->length; i++)
b4c522fa
IB
4400 {
4401 MATCH m1 = deduceType((*e->keys)[i], sc, taa->index, parameters, dedtypes, wm);
4402 if (m1 < result)
4403 result = m1;
4404 if (result <= MATCHnomatch)
4405 break;
4406 MATCH m2 = deduceType((*e->values)[i], sc, taa->next, parameters, dedtypes, wm);
4407 if (m2 < result)
4408 result = m2;
4409 if (result <= MATCHnomatch)
4410 break;
4411 }
4412 return;
4413 }
4414 visit((Expression *)e);
4415 }
4416
4417 void visit(FuncExp *e)
4418 {
4419 //printf("e->type = %s, tparam = %s\n", e->type->toChars(), tparam->toChars());
4420 if (e->td)
4421 {
4422 Type *to = tparam;
4423 if (!to->nextOf() || to->nextOf()->ty != Tfunction)
4424 return;
4425 TypeFunction *tof = (TypeFunction *)to->nextOf();
4426
4427 // Parameter types inference from 'tof'
4428 assert(e->td->_scope);
4429 TypeFunction *tf = (TypeFunction *)e->fd->type;
4430 //printf("\ttof = %s\n", tof->toChars());
4431 //printf("\ttf = %s\n", tf->toChars());
c3a2ba10 4432 size_t dim = tf->parameterList.length();
b4c522fa 4433
c3a2ba10
IB
4434 if (tof->parameterList.length() != dim ||
4435 tof->parameterList.varargs != tf->parameterList.varargs)
b4c522fa
IB
4436 return;
4437
4438 Objects *tiargs = new Objects();
2cbc99d1 4439 tiargs->reserve(e->td->parameters->length);
b4c522fa 4440
2cbc99d1 4441 for (size_t i = 0; i < e->td->parameters->length; i++)
b4c522fa
IB
4442 {
4443 TemplateParameter *tp = (*e->td->parameters)[i];
4444 size_t u = 0;
4445 for (; u < dim; u++)
4446 {
c3a2ba10 4447 Parameter *p = tf->parameterList[u];
b4c522fa
IB
4448 if (p->type->ty == Tident &&
4449 ((TypeIdentifier *)p->type)->ident == tp->ident)
4450 {
4451 break;
4452 }
4453 }
4454 assert(u < dim);
c3a2ba10 4455 Parameter *pto = tof->parameterList[u];
b4c522fa
IB
4456 if (!pto)
4457 break;
4458 Type *t = pto->type->syntaxCopy(); // Bugzilla 11774
4459 if (reliesOnTident(t, parameters, inferStart))
4460 return;
4461 t = t->semantic(e->loc, sc);
4462 if (t->ty == Terror)
4463 return;
4464 tiargs->push(t);
4465 }
4466
4467 // Set target of return type inference
4468 if (!tf->next && tof->next)
4469 e->fd->treq = tparam;
4470
4471 TemplateInstance *ti = new TemplateInstance(e->loc, e->td, tiargs);
4472 Expression *ex = new ScopeExp(e->loc, ti);
4473 ex = ::semantic(ex, e->td->_scope);
4474
4475 // Reset inference target for the later re-semantic
4476 e->fd->treq = NULL;
4477
4478 if (ex->op == TOKerror)
4479 return;
4480 if (ex->op != TOKfunction)
4481 return;
4482 visit(ex->type);
4483 return;
4484 }
4485
4486 Type *t = e->type;
4487
4488 if (t->ty == Tdelegate && tparam->ty == Tpointer)
4489 return;
4490
4491 // Allow conversion from implicit function pointer to delegate
4492 if (e->tok == TOKreserved &&
4493 t->ty == Tpointer && tparam->ty == Tdelegate)
4494 {
4495 TypeFunction *tf = (TypeFunction *)t->nextOf();
4496 t = (new TypeDelegate(tf))->merge();
4497 }
4498 //printf("tparam = %s <= e->type = %s, t = %s\n", tparam->toChars(), e->type->toChars(), t->toChars());
4499 visit(t);
4500 }
4501
4502 void visit(SliceExp *e)
4503 {
4504 Type *taai;
4505 if (e->type->ty == Tarray &&
4506 (tparam->ty == Tsarray ||
4507 (tparam->ty == Taarray && (taai = ((TypeAArray *)tparam)->index)->ty == Tident &&
2cbc99d1 4508 ((TypeIdentifier *)taai)->idents.length == 0)))
b4c522fa
IB
4509 {
4510 // Consider compile-time known boundaries
4511 if (Type *tsa = toStaticArrayType(e))
4512 {
4513 tsa->accept(this);
4514 return;
4515 }
4516 }
4517 visit((Expression *)e);
4518 }
4519
4520 void visit(CommaExp *e)
4521 {
4522 ((CommaExp *)e)->e2->accept(this);
4523 }
4524 };
4525
4526 DeduceType v(sc, tparam, parameters, dedtypes, wm, inferStart);
4527 if (Type *t = isType(o))
4528 t->accept(&v);
4529 else
4530 {
4531 assert(isExpression(o) && wm);
4532 ((Expression *)o)->accept(&v);
4533 }
4534 return v.result;
4535}
4536
4537/*******************************
4538 * Input:
4539 * t Tested type, if NULL, returns NULL.
4540 * tparams Optional template parameters.
4541 * == NULL:
4542 * If one of the subtypes of this type is a TypeIdentifier,
4543 * i.e. it's an unresolved type, return that type.
4544 * != NULL:
4545 * Only when the TypeIdentifier is one of template parameters,
4546 * return that type.
4547 */
4548
4549bool reliesOnTident(Type *t, TemplateParameters *tparams, size_t iStart)
4550{
4551 class ReliesOnTident : public Visitor
4552 {
4553 public:
4554 TemplateParameters *tparams;
4555 size_t iStart;
4556 bool result;
4557
4558 ReliesOnTident(TemplateParameters *tparams, size_t iStart)
4559 : tparams(tparams), iStart(iStart)
4560 {
4561 result = false;
4562 }
4563
4564 void visit(Type *)
4565 {
4566 }
4567
4568 void visit(TypeNext *t)
4569 {
4570 t->next->accept(this);
4571 }
4572
4573 void visit(TypeVector *t)
4574 {
4575 t->basetype->accept(this);
4576 }
4577
4578 void visit(TypeAArray *t)
4579 {
4580 visit((TypeNext *)t);
4581 if (!result)
4582 t->index->accept(this);
4583 }
4584
4585 void visit(TypeFunction *t)
4586 {
c3a2ba10 4587 size_t dim = t->parameterList.length();
b4c522fa
IB
4588 for (size_t i = 0; i < dim; i++)
4589 {
c3a2ba10 4590 Parameter *fparam = t->parameterList[i];
b4c522fa
IB
4591 fparam->type->accept(this);
4592 if (result)
4593 return;
4594 }
4595 if (t->next)
4596 t->next->accept(this);
4597 }
4598
4599 void visit(TypeIdentifier *t)
4600 {
4601 if (!tparams)
4602 {
4603 result = true;
4604 return;
4605 }
4606
2cbc99d1 4607 for (size_t i = iStart; i < tparams->length; i++)
b4c522fa
IB
4608 {
4609 TemplateParameter *tp = (*tparams)[i];
4610 if (tp->ident->equals(t->ident))
4611 {
4612 result = true;
4613 return;
4614 }
4615 }
4616 }
4617
4618 void visit(TypeInstance *t)
4619 {
4620 if (!tparams)
4621 return;
4622
2cbc99d1 4623 for (size_t i = iStart; i < tparams->length; i++)
b4c522fa
IB
4624 {
4625 TemplateParameter *tp = (*tparams)[i];
4626 if (t->tempinst->name == tp->ident)
4627 {
4628 result = true;
4629 return;
4630 }
4631 }
4632 if (!t->tempinst->tiargs)
4633 return;
2cbc99d1 4634 for (size_t i = 0; i < t->tempinst->tiargs->length; i++)
b4c522fa
IB
4635 {
4636 Type *ta = isType((*t->tempinst->tiargs)[i]);
4637 if (ta)
4638 {
4639 ta->accept(this);
4640 if (result)
4641 return;
4642 }
4643 }
4644 }
4645
4646 void visit(TypeTypeof *t)
4647 {
4648 //printf("TypeTypeof::reliesOnTident('%s')\n", t->toChars());
4649 t->exp->accept(this);
4650 }
4651
4652 void visit(TypeTuple *t)
4653 {
4654 if (t->arguments)
4655 {
2cbc99d1 4656 for (size_t i = 0; i < t->arguments->length; i++)
b4c522fa
IB
4657 {
4658 Parameter *arg = (*t->arguments)[i];
4659 arg->type->accept(this);
4660 if (result)
4661 return;
4662 }
4663 }
4664 }
4665
4666 void visit(Expression *)
4667 {
4668 //printf("Expression::reliesOnTident('%s')\n", e->toChars());
4669 }
4670
4671 void visit(IdentifierExp *e)
4672 {
4673 //printf("IdentifierExp::reliesOnTident('%s')\n", e->toChars());
2cbc99d1 4674 for (size_t i = iStart; i < tparams->length; i++)
b4c522fa
IB
4675 {
4676 TemplateParameter *tp = (*tparams)[i];
4677 if (e->ident == tp->ident)
4678 {
4679 result = true;
4680 return;
4681 }
4682 }
4683 }
4684
4685 void visit(TupleExp *e)
4686 {
4687 //printf("TupleExp::reliesOnTident('%s')\n", e->toChars());
4688 if (e->exps)
4689 {
2cbc99d1 4690 for (size_t i = 0; i < e->exps->length; i++)
b4c522fa
IB
4691 {
4692 Expression *ea = (*e->exps)[i];
4693 ea->accept(this);
4694 if (result)
4695 return;
4696 }
4697 }
4698 }
4699
4700 void visit(ArrayLiteralExp *e)
4701 {
4702 //printf("ArrayLiteralExp::reliesOnTident('%s')\n", e->toChars());
4703 if (e->elements)
4704 {
2cbc99d1 4705 for (size_t i = 0; i < e->elements->length; i++)
b4c522fa
IB
4706 {
4707 Expression *el = (*e->elements)[i];
4708 el->accept(this);
4709 if (result)
4710 return;
4711 }
4712 }
4713 }
4714
4715 void visit(AssocArrayLiteralExp *e)
4716 {
4717 //printf("AssocArrayLiteralExp::reliesOnTident('%s')\n", e->toChars());
2cbc99d1 4718 for (size_t i = 0; i < e->keys->length; i++)
b4c522fa
IB
4719 {
4720 Expression *ek = (*e->keys)[i];
4721 ek->accept(this);
4722 if (result)
4723 return;
4724 }
2cbc99d1 4725 for (size_t i = 0; i < e->values->length; i++)
b4c522fa
IB
4726 {
4727 Expression *ev = (*e->values)[i];
4728 ev->accept(this);
4729 if (result)
4730 return;
4731 }
4732 }
4733
4734 void visit(StructLiteralExp *e)
4735 {
4736 //printf("StructLiteralExp::reliesOnTident('%s')\n", e->toChars());
4737 if (e->elements)
4738 {
2cbc99d1 4739 for (size_t i = 0; i < e->elements->length; i++)
b4c522fa
IB
4740 {
4741 Expression *ea = (*e->elements)[i];
4742 ea->accept(this);
4743 if (result)
4744 return;
4745 }
4746 }
4747 }
4748
4749 void visit(TypeExp *e)
4750 {
4751 //printf("TypeExp::reliesOnTident('%s')\n", e->toChars());
4752 e->type->accept(this);
4753 }
4754
4755 void visit(NewExp *e)
4756 {
4757 //printf("NewExp::reliesOnTident('%s')\n", e->toChars());
4758 if (e->thisexp)
4759 e->thisexp->accept(this);
4760 if (!result && e->newargs)
4761 {
2cbc99d1 4762 for (size_t i = 0; i < e->newargs->length; i++)
b4c522fa
IB
4763 {
4764 Expression *ea = (*e->newargs)[i];
4765 ea->accept(this);
4766 if (result)
4767 return;
4768 }
4769 }
4770 e->newtype->accept(this);
4771 if (!result && e->arguments)
4772 {
2cbc99d1 4773 for (size_t i = 0; i < e->arguments->length; i++)
b4c522fa
IB
4774 {
4775 Expression *ea = (*e->arguments)[i];
4776 ea->accept(this);
4777 if (result)
4778 return;
4779 }
4780 }
4781 }
4782
4783 void visit(NewAnonClassExp *)
4784 {
4785 //printf("NewAnonClassExp::reliesOnTident('%s')\n", e->toChars());
4786 result = true;
4787 }
4788
4789 void visit(FuncExp *)
4790 {
4791 //printf("FuncExp::reliesOnTident('%s')\n", e->toChars());
4792 result = true;
4793 }
4794
4795 void visit(TypeidExp *e)
4796 {
4797 //printf("TypeidExp::reliesOnTident('%s')\n", e->toChars());
4798 if (Expression *ea = isExpression(e->obj))
4799 ea->accept(this);
4800 else if (Type *ta = isType(e->obj))
4801 ta->accept(this);
4802 }
4803
4804 void visit(TraitsExp *e)
4805 {
4806 //printf("TraitsExp::reliesOnTident('%s')\n", e->toChars());
4807 if (e->args)
4808 {
2cbc99d1 4809 for (size_t i = 0; i < e->args->length; i++)
b4c522fa
IB
4810 {
4811 RootObject *oa = (*e->args)[i];
4812 if (Expression *ea = isExpression(oa))
4813 ea->accept(this);
4814 else if (Type *ta = isType(oa))
4815 ta->accept(this);
4816 if (result)
4817 return;
4818 }
4819 }
4820 }
4821
4822 void visit(IsExp *e)
4823 {
4824 //printf("IsExp::reliesOnTident('%s')\n", e->toChars());
4825 e->targ->accept(this);
4826 }
4827
4828 void visit(UnaExp *e)
4829 {
4830 //printf("UnaExp::reliesOnTident('%s')\n", e->toChars());
4831 e->e1->accept(this);
4832 }
4833
4834 void visit(DotTemplateInstanceExp *e)
4835 {
4836 //printf("DotTemplateInstanceExp::reliesOnTident('%s')\n", e->toChars());
4837 visit((UnaExp *)e);
4838 if (!result && e->ti->tiargs)
4839 {
2cbc99d1 4840 for (size_t i = 0; i < e->ti->tiargs->length; i++)
b4c522fa
IB
4841 {
4842 RootObject *oa = (*e->ti->tiargs)[i];
4843 if (Expression *ea = isExpression(oa))
4844 ea->accept(this);
4845 else if (Type *ta = isType(oa))
4846 ta->accept(this);
4847 if (result)
4848 return;
4849 }
4850 }
4851 }
4852
4853 void visit(CallExp *e)
4854 {
4855 //printf("CallExp::reliesOnTident('%s')\n", e->toChars());
4856 visit((UnaExp *)e);
4857 if (!result && e->arguments)
4858 {
2cbc99d1 4859 for (size_t i = 0; i < e->arguments->length; i++)
b4c522fa
IB
4860 {
4861 Expression *ea = (*e->arguments)[i];
4862 ea->accept(this);
4863 if (result)
4864 return;
4865 }
4866 }
4867 }
4868
4869 void visit(CastExp *e)
4870 {
4871 //printf("CastExp::reliesOnTident('%s')\n", e->toChars());
4872 visit((UnaExp *)e);
4873 // e.to can be null for cast() with no type
4874 if (!result && e->to)
4875 e->to->accept(this);
4876 }
4877
4878 void visit(SliceExp *e)
4879 {
4880 //printf("SliceExp::reliesOnTident('%s')\n", e->toChars());
4881 visit((UnaExp *)e);
4882 if (!result && e->lwr)
4883 e->lwr->accept(this);
4884 if (!result && e->upr)
4885 e->upr->accept(this);
4886 }
4887
4888 void visit(IntervalExp *e)
4889 {
4890 //printf("IntervalExp::reliesOnTident('%s')\n", e->toChars());
4891 e->lwr->accept(this);
4892 if (!result)
4893 e->upr->accept(this);
4894 }
4895
4896 void visit(ArrayExp *e)
4897 {
4898 //printf("ArrayExp::reliesOnTident('%s')\n", e->toChars());
4899 visit((UnaExp *)e);
4900 if (!result && e->arguments)
4901 {
2cbc99d1 4902 for (size_t i = 0; i < e->arguments->length; i++)
b4c522fa
IB
4903 {
4904 Expression *ea = (*e->arguments)[i];
4905 ea->accept(this);
4906 }
4907 }
4908 }
4909
4910 void visit(BinExp *e)
4911 {
4912 //printf("BinExp::reliesOnTident('%s')\n", e->toChars());
4913 e->e1->accept(this);
4914 if (!result)
4915 e->e2->accept(this);
4916 }
4917
4918 void visit(CondExp *e)
4919 {
4920 //printf("BinExp::reliesOnTident('%s')\n", e->toChars());
4921 e->econd->accept(this);
4922 if (!result)
4923 visit((BinExp *)e);
4924 }
4925 };
4926
4927 if (!t)
4928 return false;
4929
4930 ReliesOnTident v(tparams, iStart);
4931 t->accept(&v);
4932 return v.result;
4933}
4934
4935/* ======================== TemplateParameter =============================== */
4936
4937TemplateParameter::TemplateParameter(Loc loc, Identifier *ident)
4938{
4939 this->loc = loc;
4940 this->ident = ident;
4941 this->dependent = false;
4942}
4943
4944TemplateTypeParameter *TemplateParameter::isTemplateTypeParameter()
4945{
4946 return NULL;
4947}
4948
4949TemplateValueParameter *TemplateParameter::isTemplateValueParameter()
4950{
4951 return NULL;
4952}
4953
4954TemplateAliasParameter *TemplateParameter::isTemplateAliasParameter()
4955{
4956 return NULL;
4957}
4958
4959TemplateTupleParameter *TemplateParameter::isTemplateTupleParameter()
4960{
4961 return NULL;
4962}
4963
4964TemplateThisParameter *TemplateParameter::isTemplateThisParameter()
4965{
4966 return NULL;
4967}
4968
4969/*******************************************
4970 * Match to a particular TemplateParameter.
4971 * Input:
4972 * instLoc location that the template is instantiated.
4973 * tiargs[] actual arguments to template instance
4974 * i i'th argument
4975 * parameters[] template parameters
4976 * dedtypes[] deduced arguments to template instance
4977 * *psparam set to symbol declared and initialized to dedtypes[i]
4978 */
4979MATCH TemplateParameter::matchArg(Loc instLoc, Scope *sc, Objects *tiargs,
4980 size_t i, TemplateParameters *parameters, Objects *dedtypes,
4981 Declaration **psparam)
4982{
4983 RootObject *oarg;
4984
2cbc99d1 4985 if (i < tiargs->length)
b4c522fa
IB
4986 oarg = (*tiargs)[i];
4987 else
4988 {
4989 // Get default argument instead
4990 oarg = defaultArg(instLoc, sc);
4991 if (!oarg)
4992 {
2cbc99d1 4993 assert(i < dedtypes->length);
b4c522fa
IB
4994 // It might have already been deduced
4995 oarg = (*dedtypes)[i];
4996 if (!oarg)
4997 goto Lnomatch;
4998 }
4999 }
5000 return matchArg(sc, oarg, i, parameters, dedtypes, psparam);
5001
5002Lnomatch:
5003 if (psparam)
5004 *psparam = NULL;
5005 return MATCHnomatch;
5006}
5007
5008/* ======================== TemplateTypeParameter =========================== */
5009
5010// type-parameter
5011
5012Type *TemplateTypeParameter::tdummy = NULL;
5013
5014TemplateTypeParameter::TemplateTypeParameter(Loc loc, Identifier *ident, Type *specType,
5015 Type *defaultType)
5016 : TemplateParameter(loc, ident)
5017{
5018 this->ident = ident;
5019 this->specType = specType;
5020 this->defaultType = defaultType;
5021}
5022
5023TemplateTypeParameter *TemplateTypeParameter::isTemplateTypeParameter()
5024{
5025 return this;
5026}
5027
5028TemplateParameter *TemplateTypeParameter::syntaxCopy()
5029{
5030 return new TemplateTypeParameter(loc, ident,
5031 specType ? specType->syntaxCopy() : NULL,
5032 defaultType ? defaultType->syntaxCopy() : NULL);
5033}
5034
5035bool TemplateTypeParameter::declareParameter(Scope *sc)
5036{
5037 //printf("TemplateTypeParameter::declareParameter('%s')\n", ident->toChars());
5038 TypeIdentifier *ti = new TypeIdentifier(loc, ident);
5039 Declaration *ad = new AliasDeclaration(loc, ident, ti);
5040 return sc->insert(ad) != NULL;
5041}
5042
5043bool TemplateTypeParameter::semantic(Scope *sc, TemplateParameters *parameters)
5044{
5045 //printf("TemplateTypeParameter::semantic('%s')\n", ident->toChars());
5046 if (specType && !reliesOnTident(specType, parameters))
5047 {
5048 specType = specType->semantic(loc, sc);
5049 }
5050 return !(specType && isError(specType));
5051}
5052
5053MATCH TemplateTypeParameter::matchArg(Scope *sc, RootObject *oarg,
5054 size_t i, TemplateParameters *parameters, Objects *dedtypes,
5055 Declaration **psparam)
5056{
5057 //printf("TemplateTypeParameter::matchArg('%s')\n", ident->toChars());
5058 MATCH m = MATCHexact;
5059 Type *ta = isType(oarg);
5060 if (!ta)
5061 {
5062 //printf("%s %p %p %p\n", oarg->toChars(), isExpression(oarg), isDsymbol(oarg), isTuple(oarg));
5063 goto Lnomatch;
5064 }
5065 //printf("ta is %s\n", ta->toChars());
5066
5067 if (specType)
5068 {
5069 if (!ta || ta == tdummy)
5070 goto Lnomatch;
5071
5072 //printf("\tcalling deduceType(): ta is %s, specType is %s\n", ta->toChars(), specType->toChars());
5073 MATCH m2 = deduceType(ta, sc, specType, parameters, dedtypes);
5074 if (m2 <= MATCHnomatch)
5075 {
5076 //printf("\tfailed deduceType\n");
5077 goto Lnomatch;
5078 }
5079
5080 if (m2 < m)
5081 m = m2;
5082 if ((*dedtypes)[i])
5083 {
5084 Type *t = (Type *)(*dedtypes)[i];
5085
5086 if (dependent && !t->equals(ta)) // Bugzilla 14357
5087 goto Lnomatch;
5088
5089 /* This is a self-dependent parameter. For example:
5090 * template X(T : T*) {}
5091 * template X(T : S!T, alias S) {}
5092 */
5093 //printf("t = %s ta = %s\n", t->toChars(), ta->toChars());
5094 ta = t;
5095 }
5096 }
5097 else
5098 {
5099 if ((*dedtypes)[i])
5100 {
5101 // Must match already deduced type
5102 Type *t = (Type *)(*dedtypes)[i];
5103
5104 if (!t->equals(ta))
5105 {
5106 //printf("t = %s ta = %s\n", t->toChars(), ta->toChars());
5107 goto Lnomatch;
5108 }
5109 }
5110 else
5111 {
5112 // So that matches with specializations are better
5113 m = MATCHconvert;
5114 }
5115 }
5116 (*dedtypes)[i] = ta;
5117
5118 if (psparam)
5119 *psparam = new AliasDeclaration(loc, ident, ta);
5120 //printf("\tm = %d\n", m);
5121 return dependent ? MATCHexact : m;
5122
5123Lnomatch:
5124 if (psparam)
5125 *psparam = NULL;
5126 //printf("\tm = %d\n", MATCHnomatch);
5127 return MATCHnomatch;
5128}
5129
5130
5131void TemplateTypeParameter::print(RootObject *oarg, RootObject *oded)
5132{
5133 printf(" %s\n", ident->toChars());
5134
5135 Type *t = isType(oarg);
5136 Type *ta = isType(oded);
5137
5138 assert(ta);
5139
5140 if (specType)
5141 printf("\tSpecialization: %s\n", specType->toChars());
5142 if (defaultType)
5143 printf("\tDefault: %s\n", defaultType->toChars());
5144 printf("\tParameter: %s\n", t ? t->toChars() : "NULL");
5145 printf("\tDeduced Type: %s\n", ta->toChars());
5146}
5147
5148void *TemplateTypeParameter::dummyArg()
5149{
5150 Type *t = specType;
5151 if (!t)
5152 {
5153 // Use this for alias-parameter's too (?)
5154 if (!tdummy)
5155 tdummy = new TypeIdentifier(loc, ident);
5156 t = tdummy;
5157 }
5158 return (void *)t;
5159}
5160
5161
5162RootObject *TemplateTypeParameter::specialization()
5163{
5164 return specType;
5165}
5166
5167RootObject *TemplateTypeParameter::defaultArg(Loc, Scope *sc)
5168{
5169 Type *t = defaultType;
5170 if (t)
5171 {
5172 t = t->syntaxCopy();
5173 t = t->semantic(loc, sc); // use the parameter loc
5174 }
5175 return t;
5176}
5177
5178bool TemplateTypeParameter::hasDefaultArg()
5179{
5180 return defaultType != NULL;
5181}
5182
5183/* ======================== TemplateThisParameter =========================== */
5184
5185// this-parameter
5186
5187TemplateThisParameter::TemplateThisParameter(Loc loc, Identifier *ident,
5188 Type *specType,
5189 Type *defaultType)
5190 : TemplateTypeParameter(loc, ident, specType, defaultType)
5191{
5192}
5193
5194TemplateThisParameter *TemplateThisParameter::isTemplateThisParameter()
5195{
5196 return this;
5197}
5198
5199TemplateParameter *TemplateThisParameter::syntaxCopy()
5200{
5201 return new TemplateThisParameter(loc, ident,
5202 specType ? specType->syntaxCopy() : NULL,
5203 defaultType ? defaultType->syntaxCopy() : NULL);
5204}
5205
5206/* ======================== TemplateAliasParameter ========================== */
5207
5208// alias-parameter
5209
5210Dsymbol *TemplateAliasParameter::sdummy = NULL;
5211
5212TemplateAliasParameter::TemplateAliasParameter(Loc loc, Identifier *ident,
5213 Type *specType, RootObject *specAlias, RootObject *defaultAlias)
5214 : TemplateParameter(loc, ident)
5215{
5216 this->ident = ident;
5217 this->specType = specType;
5218 this->specAlias = specAlias;
5219 this->defaultAlias = defaultAlias;
5220}
5221
5222TemplateAliasParameter *TemplateAliasParameter::isTemplateAliasParameter()
5223{
5224 return this;
5225}
5226
5227TemplateParameter *TemplateAliasParameter::syntaxCopy()
5228{
5229 return new TemplateAliasParameter(loc, ident,
5230 specType ? specType->syntaxCopy() : NULL,
5231 objectSyntaxCopy(specAlias),
5232 objectSyntaxCopy(defaultAlias));
5233}
5234
5235bool TemplateAliasParameter::declareParameter(Scope *sc)
5236{
5237 TypeIdentifier *ti = new TypeIdentifier(loc, ident);
5238 Declaration *ad = new AliasDeclaration(loc, ident, ti);
5239 return sc->insert(ad) != NULL;
5240}
5241
5242static RootObject *aliasParameterSemantic(Loc loc, Scope *sc, RootObject *o, TemplateParameters *parameters)
5243{
5244 if (o)
5245 {
5246 Expression *ea = isExpression(o);
5247 Type *ta = isType(o);
5248 if (ta && (!parameters || !reliesOnTident(ta, parameters)))
5249 {
5250 Dsymbol *s = ta->toDsymbol(sc);
5251 if (s)
5252 o = s;
5253 else
5254 o = ta->semantic(loc, sc);
5255 }
5256 else if (ea)
5257 {
5258 sc = sc->startCTFE();
5259 ea = ::semantic(ea, sc);
5260 sc = sc->endCTFE();
5261 o = ea->ctfeInterpret();
5262 }
5263 }
5264 return o;
5265}
5266
5267bool TemplateAliasParameter::semantic(Scope *sc, TemplateParameters *parameters)
5268{
5269 if (specType && !reliesOnTident(specType, parameters))
5270 {
5271 specType = specType->semantic(loc, sc);
5272 }
5273 specAlias = aliasParameterSemantic(loc, sc, specAlias, parameters);
5274 return !(specType && isError(specType)) &&
5275 !(specAlias && isError(specAlias));
5276}
5277
5278MATCH TemplateAliasParameter::matchArg(Scope *sc, RootObject *oarg,
5279 size_t i, TemplateParameters *parameters, Objects *dedtypes,
5280 Declaration **psparam)
5281{
5282 //printf("TemplateAliasParameter::matchArg('%s')\n", ident->toChars());
5283 MATCH m = MATCHexact;
5284 Type *ta = isType(oarg);
5285 RootObject *sa = ta && !ta->deco ? NULL : getDsymbol(oarg);
5286 Expression *ea = isExpression(oarg);
5287 if (ea && (ea->op == TOKthis || ea->op == TOKsuper))
5288 sa = ((ThisExp *)ea)->var;
5289 else if (ea && ea->op == TOKscope)
5290 sa = ((ScopeExp *)ea)->sds;
5291 if (sa)
5292 {
5293 if (((Dsymbol *)sa)->isAggregateDeclaration())
5294 m = MATCHconvert;
5295
5296 /* specType means the alias must be a declaration with a type
5297 * that matches specType.
5298 */
5299 if (specType)
5300 {
5301 Declaration *d = ((Dsymbol *)sa)->isDeclaration();
5302 if (!d)
5303 goto Lnomatch;
5304 if (!d->type->equals(specType))
5305 goto Lnomatch;
5306 }
5307 }
5308 else
5309 {
5310 sa = oarg;
5311 if (ea)
5312 {
5313 if (specType)
5314 {
5315 if (!ea->type->equals(specType))
5316 goto Lnomatch;
5317 }
5318 }
5319 else if (ta && ta->ty == Tinstance && !specAlias)
5320 {
5321 /* Bugzilla xxxxx: Specialized parameter should be prefeerd
5322 * match to the template type parameter.
5323 * template X(alias a) {} // a == this
5324 * template X(alias a : B!A, alias B, A...) {} // B!A => ta
5325 */
5326 }
5327 else if (sa && sa == TemplateTypeParameter::tdummy)
5328 {
5329 /* Bugzilla 2025: Aggregate Types should preferentially
5330 * match to the template type parameter.
5331 * template X(alias a) {} // a == this
5332 * template X(T) {} // T => sa
5333 */
5334 }
5335 else
5336 goto Lnomatch;
5337 }
5338
5339 if (specAlias)
5340 {
5341 if (sa == sdummy)
5342 goto Lnomatch;
5343 Dsymbol *sx = isDsymbol(sa);
5344 if (sa != specAlias && sx)
5345 {
5346 Type *talias = isType(specAlias);
5347 if (!talias)
5348 goto Lnomatch;
5349
5350 TemplateInstance *ti = sx->isTemplateInstance();
5351 if (!ti && sx->parent)
5352 {
5353 ti = sx->parent->isTemplateInstance();
5354 if (ti && ti->name != sx->ident)
5355 goto Lnomatch;
5356 }
5357 if (!ti)
5358 goto Lnomatch;
5359
5360 Type *t = new TypeInstance(Loc(), ti);
5361 MATCH m2 = deduceType(t, sc, talias, parameters, dedtypes);
5362 if (m2 <= MATCHnomatch)
5363 goto Lnomatch;
5364 }
5365 }
5366 else if ((*dedtypes)[i])
5367 {
5368 // Must match already deduced symbol
5369 RootObject *si = (*dedtypes)[i];
5370 if (!sa || si != sa)
5371 goto Lnomatch;
5372 }
5373 (*dedtypes)[i] = sa;
5374
5375 if (psparam)
5376 {
5377 if (Dsymbol *s = isDsymbol(sa))
5378 {
5379 *psparam = new AliasDeclaration(loc, ident, s);
5380 }
5381 else if (Type *t = isType(sa))
5382 {
5383 *psparam = new AliasDeclaration(loc, ident, t);
5384 }
5385 else
5386 {
5387 assert(ea);
5388
5389 // Declare manifest constant
5390 Initializer *init = new ExpInitializer(loc, ea);
5391 VarDeclaration *v = new VarDeclaration(loc, NULL, ident, init);
5392 v->storage_class = STCmanifest;
5393 v->semantic(sc);
5394 *psparam = v;
5395 }
5396 }
5397 return dependent ? MATCHexact : m;
5398
5399Lnomatch:
5400 if (psparam)
5401 *psparam = NULL;
5402 //printf("\tm = %d\n", MATCHnomatch);
5403 return MATCHnomatch;
5404}
5405
5406
5407void TemplateAliasParameter::print(RootObject *, RootObject *oded)
5408{
5409 printf(" %s\n", ident->toChars());
5410
5411 Dsymbol *sa = isDsymbol(oded);
5412 assert(sa);
5413
5414 printf("\tParameter alias: %s\n", sa->toChars());
5415}
5416
5417void *TemplateAliasParameter::dummyArg()
5418{
5419 RootObject *s = specAlias;
5420 if (!s)
5421 {
5422 if (!sdummy)
5423 sdummy = new Dsymbol();
5424 s = sdummy;
5425 }
5426 return (void*)s;
5427}
5428
5429
5430RootObject *TemplateAliasParameter::specialization()
5431{
5432 return specAlias;
5433}
5434
5435RootObject *TemplateAliasParameter::defaultArg(Loc, Scope *sc)
5436{
5437 RootObject *da = defaultAlias;
5438 Type *ta = isType(defaultAlias);
5439 if (ta)
5440 {
5441 if (ta->ty == Tinstance)
5442 {
5443 // If the default arg is a template, instantiate for each type
5444 da = ta->syntaxCopy();
5445 }
5446 }
5447
5448 RootObject *o = aliasParameterSemantic(loc, sc, da, NULL); // use the parameter loc
5449 return o;
5450}
5451
5452bool TemplateAliasParameter::hasDefaultArg()
5453{
5454 return defaultAlias != NULL;
5455}
5456
5457/* ======================== TemplateValueParameter ========================== */
5458
5459// value-parameter
5460
5461AA *TemplateValueParameter::edummies = NULL;
5462
5463TemplateValueParameter::TemplateValueParameter(Loc loc, Identifier *ident, Type *valType,
5464 Expression *specValue, Expression *defaultValue)
5465 : TemplateParameter(loc, ident)
5466{
5467 this->ident = ident;
5468 this->valType = valType;
5469 this->specValue = specValue;
5470 this->defaultValue = defaultValue;
5471}
5472
5473TemplateValueParameter *TemplateValueParameter::isTemplateValueParameter()
5474{
5475 return this;
5476}
5477
5478TemplateParameter *TemplateValueParameter::syntaxCopy()
5479{
5480 return new TemplateValueParameter(loc, ident,
5481 valType->syntaxCopy(),
5482 specValue ? specValue->syntaxCopy() : NULL,
5483 defaultValue ? defaultValue->syntaxCopy() : NULL);
5484}
5485
5486bool TemplateValueParameter::declareParameter(Scope *sc)
5487{
5488 VarDeclaration *v = new VarDeclaration(loc, valType, ident, NULL);
5489 v->storage_class = STCtemplateparameter;
5490 return sc->insert(v) != NULL;
5491}
5492
5493bool TemplateValueParameter::semantic(Scope *sc, TemplateParameters *)
5494{
5495 valType = valType->semantic(loc, sc);
5496
5497 return !isError(valType);
5498}
5499
5500MATCH TemplateValueParameter::matchArg(Scope *sc, RootObject *oarg,
5501 size_t i, TemplateParameters *, Objects *dedtypes, Declaration **psparam)
5502{
5503 //printf("TemplateValueParameter::matchArg('%s')\n", ident->toChars());
5504
5505 MATCH m = MATCHexact;
5506
5507 Expression *ei = isExpression(oarg);
5508 Type *vt;
5509
5510 if (!ei && oarg)
5511 {
5512 Dsymbol *si = isDsymbol(oarg);
5513 FuncDeclaration *f = si ? si->isFuncDeclaration() : NULL;
5514 if (!f || !f->fbody || f->needThis())
5515 goto Lnomatch;
5516
5517 ei = new VarExp(loc, f);
5518 ei = ::semantic(ei, sc);
5519
5520 /* If a function is really property-like, and then
5521 * it's CTFEable, ei will be a literal expression.
5522 */
5523 unsigned int olderrors = global.startGagging();
5524 ei = resolveProperties(sc, ei);
5525 ei = ei->ctfeInterpret();
5526 if (global.endGagging(olderrors) || ei->op == TOKerror)
5527 goto Lnomatch;
5528
5529 /* Bugzilla 14520: A property-like function can match to both
5530 * TemplateAlias and ValueParameter. But for template overloads,
5531 * it should always prefer alias parameter to be consistent
5532 * template match result.
5533 *
5534 * template X(alias f) { enum X = 1; }
5535 * template X(int val) { enum X = 2; }
5536 * int f1() { return 0; } // CTFEable
5537 * int f2(); // body-less function is not CTFEable
5538 * enum x1 = X!f1; // should be 1
5539 * enum x2 = X!f2; // should be 1
5540 *
5541 * e.g. The x1 value must be same even if the f1 definition will be moved
5542 * into di while stripping body code.
5543 */
5544 m = MATCHconvert;
5545 }
5546
5547 if (ei && ei->op == TOKvar)
5548 {
5549 // Resolve const variables that we had skipped earlier
5550 ei = ei->ctfeInterpret();
5551 }
5552
5553 //printf("\tvalType: %s, ty = %d\n", valType->toChars(), valType->ty);
5554 vt = valType->semantic(loc, sc);
5555 //printf("ei: %s, ei->type: %s\n", ei->toChars(), ei->type->toChars());
5556 //printf("vt = %s\n", vt->toChars());
5557
5558 if (ei->type)
5559 {
5560 MATCH m2 = ei->implicitConvTo(vt);
5561 //printf("m: %d\n", m);
5562 if (m2 < m)
5563 m = m2;
5564 if (m <= MATCHnomatch)
5565 goto Lnomatch;
5566 ei = ei->implicitCastTo(sc, vt);
5567 ei = ei->ctfeInterpret();
5568 }
5569
5570 if (specValue)
5571 {
5572 if (!ei || (Expression *)dmd_aaGetRvalue(edummies, (void *)ei->type) == ei)
5573 goto Lnomatch;
5574
5575 Expression *e = specValue;
5576
5577 sc = sc->startCTFE();
5578 e = ::semantic(e, sc);
5579 e = resolveProperties(sc, e);
5580 sc = sc->endCTFE();
5581 e = e->implicitCastTo(sc, vt);
5582 e = e->ctfeInterpret();
5583
5584 ei = ei->syntaxCopy();
5585 sc = sc->startCTFE();
5586 ei = ::semantic(ei, sc);
5587 sc = sc->endCTFE();
5588 ei = ei->implicitCastTo(sc, vt);
5589 ei = ei->ctfeInterpret();
5590 //printf("\tei: %s, %s\n", ei->toChars(), ei->type->toChars());
5591 //printf("\te : %s, %s\n", e->toChars(), e->type->toChars());
5592 if (!ei->equals(e))
5593 goto Lnomatch;
5594 }
5595 else
5596 {
5597 if ((*dedtypes)[i])
5598 {
5599 // Must match already deduced value
5600 Expression *e = (Expression *)(*dedtypes)[i];
5601
5602 if (!ei || !ei->equals(e))
5603 goto Lnomatch;
5604 }
5605 }
5606 (*dedtypes)[i] = ei;
5607
5608 if (psparam)
5609 {
5610 Initializer *init = new ExpInitializer(loc, ei);
5611 Declaration *sparam = new VarDeclaration(loc, vt, ident, init);
5612 sparam->storage_class = STCmanifest;
5613 *psparam = sparam;
5614 }
5615 return dependent ? MATCHexact : m;
5616
5617Lnomatch:
5618 //printf("\tno match\n");
5619 if (psparam)
5620 *psparam = NULL;
5621 return MATCHnomatch;
5622}
5623
5624
5625void TemplateValueParameter::print(RootObject *, RootObject *oded)
5626{
5627 printf(" %s\n", ident->toChars());
5628
5629 Expression *ea = isExpression(oded);
5630
5631 if (specValue)
5632 printf("\tSpecialization: %s\n", specValue->toChars());
5633 printf("\tParameter Value: %s\n", ea ? ea->toChars() : "NULL");
5634}
5635
5636void *TemplateValueParameter::dummyArg()
5637{
5638 Expression *e = specValue;
5639 if (!e)
5640 {
5641 // Create a dummy value
5642 Expression **pe = (Expression **)dmd_aaGet(&edummies, (void *)valType);
5643 if (!*pe)
5644 *pe = valType->defaultInit();
5645 e = *pe;
5646 }
5647 return (void *)e;
5648}
5649
5650
5651RootObject *TemplateValueParameter::specialization()
5652{
5653 return specValue;
5654}
5655
5656RootObject *TemplateValueParameter::defaultArg(Loc instLoc, Scope *sc)
5657{
5658 Expression *e = defaultValue;
5659 if (e)
5660 {
5661 e = e->syntaxCopy();
5662 if ((e = ::semantic(e, sc)) == NULL)
5663 return NULL;
5664 if ((e = resolveProperties(sc, e)) == NULL)
5665 return NULL;
5666 e = e->resolveLoc(instLoc, sc); // use the instantiated loc
5667 e = e->optimize(WANTvalue);
5668 }
5669 return e;
5670}
5671
5672bool TemplateValueParameter::hasDefaultArg()
5673{
5674 return defaultValue != NULL;
5675}
5676
5677/* ======================== TemplateTupleParameter ========================== */
5678
5679// variadic-parameter
5680
5681TemplateTupleParameter::TemplateTupleParameter(Loc loc, Identifier *ident)
5682 : TemplateParameter(loc, ident)
5683{
5684 this->ident = ident;
5685}
5686
5687TemplateTupleParameter *TemplateTupleParameter::isTemplateTupleParameter()
5688{
5689 return this;
5690}
5691
5692TemplateParameter *TemplateTupleParameter::syntaxCopy()
5693{
5694 return new TemplateTupleParameter(loc, ident);
5695}
5696
5697bool TemplateTupleParameter::declareParameter(Scope *sc)
5698{
5699 TypeIdentifier *ti = new TypeIdentifier(loc, ident);
5700 Declaration *ad = new AliasDeclaration(loc, ident, ti);
5701 return sc->insert(ad) != NULL;
5702}
5703
5704bool TemplateTupleParameter::semantic(Scope *, TemplateParameters *)
5705{
5706 return true;
5707}
5708
5709MATCH TemplateTupleParameter::matchArg(Loc, Scope *sc, Objects *tiargs,
5710 size_t i, TemplateParameters *parameters, Objects *dedtypes,
5711 Declaration **psparam)
5712{
5713 /* The rest of the actual arguments (tiargs[]) form the match
5714 * for the variadic parameter.
5715 */
2cbc99d1 5716 assert(i + 1 == dedtypes->length); // must be the last one
b4c522fa
IB
5717 Tuple *ovar;
5718
5719 if (Tuple *u = isTuple((*dedtypes)[i]))
5720 {
5721 // It has already been deduced
5722 ovar = u;
5723 }
2cbc99d1 5724 else if (i + 1 == tiargs->length && isTuple((*tiargs)[i]))
b4c522fa
IB
5725 ovar = isTuple((*tiargs)[i]);
5726 else
5727 {
5728 ovar = new Tuple();
5729 //printf("ovar = %p\n", ovar);
2cbc99d1 5730 if (i < tiargs->length)
b4c522fa 5731 {
2cbc99d1
IB
5732 //printf("i = %d, tiargs->length = %d\n", i, tiargs->length);
5733 ovar->objects.setDim(tiargs->length - i);
5734 for (size_t j = 0; j < ovar->objects.length; j++)
b4c522fa
IB
5735 ovar->objects[j] = (*tiargs)[i + j];
5736 }
5737 }
5738 return matchArg(sc, ovar, i, parameters, dedtypes, psparam);
5739}
5740
5741MATCH TemplateTupleParameter::matchArg(Scope *, RootObject *oarg,
5742 size_t i, TemplateParameters *, Objects *dedtypes, Declaration **psparam)
5743{
5744 //printf("TemplateTupleParameter::matchArg('%s')\n", ident->toChars());
5745 Tuple *ovar = isTuple(oarg);
5746 if (!ovar)
5747 return MATCHnomatch;
5748 if ((*dedtypes)[i])
5749 {
5750 Tuple *tup = isTuple((*dedtypes)[i]);
5751 if (!tup)
5752 return MATCHnomatch;
5753 if (!match(tup, ovar))
5754 return MATCHnomatch;
5755 }
5756 (*dedtypes)[i] = ovar;
5757
5758 if (psparam)
5759 *psparam = new TupleDeclaration(loc, ident, &ovar->objects);
5760 return dependent ? MATCHexact : MATCHconvert;
5761}
5762
5763
5764void TemplateTupleParameter::print(RootObject *, RootObject *oded)
5765{
5766 printf(" %s... [", ident->toChars());
5767 Tuple *v = isTuple(oded);
5768 assert(v);
5769
2cbc99d1
IB
5770 //printf("|%d| ", v->objects.length);
5771 for (size_t i = 0; i < v->objects.length; i++)
b4c522fa
IB
5772 {
5773 if (i)
5774 printf(", ");
5775
5776 RootObject *o = v->objects[i];
5777
5778 Dsymbol *sa = isDsymbol(o);
5779 if (sa)
5780 printf("alias: %s", sa->toChars());
5781
5782 Type *ta = isType(o);
5783 if (ta)
5784 printf("type: %s", ta->toChars());
5785
5786 Expression *ea = isExpression(o);
5787 if (ea)
5788 printf("exp: %s", ea->toChars());
5789
5790 assert(!isTuple(o)); // no nested Tuple arguments
5791 }
5792
5793 printf("]\n");
5794}
5795
5796void *TemplateTupleParameter::dummyArg()
5797{
5798 return NULL;
5799}
5800
5801
5802RootObject *TemplateTupleParameter::specialization()
5803{
5804 return NULL;
5805}
5806
5807RootObject *TemplateTupleParameter::defaultArg(Loc, Scope *)
5808{
5809 return NULL;
5810}
5811
5812bool TemplateTupleParameter::hasDefaultArg()
5813{
5814 return false;
5815}
5816
5817/* ======================== TemplateInstance ================================ */
5818
5819TemplateInstance::TemplateInstance(Loc loc, Identifier *ident)
5820 : ScopeDsymbol(NULL)
5821{
5822 this->loc = loc;
5823 this->name = ident;
5824 this->tiargs = NULL;
5825 this->tempdecl = NULL;
5826 this->inst = NULL;
5827 this->tinst = NULL;
5828 this->tnext = NULL;
5829 this->minst = NULL;
5830 this->deferred = NULL;
5831 this->memberOf = NULL;
5832 this->argsym = NULL;
5833 this->aliasdecl = NULL;
5834 this->semantictiargsdone = false;
5835 this->inuse = 0;
5836 this->nest = 0;
5837 this->havetempdecl = false;
5838 this->enclosing = NULL;
5839 this->gagged = false;
5840 this->hash = 0;
5841 this->fargs = NULL;
5842}
5843
5844/*****************
5845 * This constructor is only called when we figured out which function
5846 * template to instantiate.
5847 */
5848
5849TemplateInstance::TemplateInstance(Loc loc, TemplateDeclaration *td, Objects *tiargs)
5850 : ScopeDsymbol(NULL)
5851{
5852 this->loc = loc;
5853 this->name = td->ident;
5854 this->tiargs = tiargs;
5855 this->tempdecl = td;
5856 this->inst = NULL;
5857 this->tinst = NULL;
5858 this->tnext = NULL;
5859 this->minst = NULL;
5860 this->deferred = NULL;
5861 this->memberOf = NULL;
5862 this->argsym = NULL;
5863 this->aliasdecl = NULL;
5864 this->semantictiargsdone = true;
5865 this->inuse = 0;
5866 this->nest = 0;
5867 this->havetempdecl = true;
5868 this->enclosing = NULL;
5869 this->gagged = false;
5870 this->hash = 0;
5871 this->fargs = NULL;
5872
5873 assert(tempdecl->_scope);
5874}
5875
5876
5877Objects *TemplateInstance::arraySyntaxCopy(Objects *objs)
5878{
5879 Objects *a = NULL;
5880 if (objs)
5881 {
5882 a = new Objects();
2cbc99d1
IB
5883 a->setDim(objs->length);
5884 for (size_t i = 0; i < objs->length; i++)
b4c522fa
IB
5885 (*a)[i] = objectSyntaxCopy((*objs)[i]);
5886 }
5887 return a;
5888}
5889
5890Dsymbol *TemplateInstance::syntaxCopy(Dsymbol *s)
5891{
5892 TemplateInstance *ti =
5893 s ? (TemplateInstance *)s
5894 : new TemplateInstance(loc, name);
5895 ti->tiargs = arraySyntaxCopy(tiargs);
5896 TemplateDeclaration *td;
5897 if (inst && tempdecl && (td = tempdecl->isTemplateDeclaration()) != NULL)
5898 td->ScopeDsymbol::syntaxCopy(ti);
5899 else
5900 ScopeDsymbol::syntaxCopy(ti);
5901 return ti;
5902}
5903
5904void TemplateInstance::semantic(Scope *sc)
5905{
5906 semantic(sc, NULL);
5907}
5908
5909void TemplateInstance::expandMembers(Scope *sc2)
5910{
2cbc99d1 5911 for (size_t i = 0; i < members->length; i++)
b4c522fa
IB
5912 {
5913 Dsymbol *s = (*members)[i];
5914 s->setScope(sc2);
5915 }
5916
2cbc99d1 5917 for (size_t i = 0; i < members->length; i++)
b4c522fa
IB
5918 {
5919 Dsymbol *s = (*members)[i];
5920 s->importAll(sc2);
5921 }
5922
2cbc99d1 5923 for (size_t i = 0; i < members->length; i++)
b4c522fa
IB
5924 {
5925 Dsymbol *s = (*members)[i];
5926 //printf("\t[%d] semantic on '%s' %p kind %s in '%s'\n", i, s->toChars(), s, s->kind(), this->toChars());
5927 //printf("test: enclosing = %d, sc2->parent = %s\n", enclosing, sc2->parent->toChars());
5928// if (enclosing)
5929// s->parent = sc->parent;
5930 //printf("test3: enclosing = %d, s->parent = %s\n", enclosing, s->parent->toChars());
5931 s->semantic(sc2);
5932 //printf("test4: enclosing = %d, s->parent = %s\n", enclosing, s->parent->toChars());
5933 Module::runDeferredSemantic();
5934 }
5935}
5936
5937void TemplateInstance::tryExpandMembers(Scope *sc2)
5938{
5939 static int nest;
5940 // extracted to a function to allow windows SEH to work without destructors in the same function
5941 //printf("%d\n", nest);
0f5c98b6 5942 if (++nest > global.recursionLimit)
b4c522fa
IB
5943 {
5944 global.gag = 0; // ensure error message gets printed
0f5c98b6 5945 error("recursive expansion exceeded allowed nesting limit");
b4c522fa
IB
5946 fatal();
5947 }
5948
5949 expandMembers(sc2);
5950
5951 nest--;
5952}
5953
5954void TemplateInstance::trySemantic3(Scope *sc2)
5955{
5956 // extracted to a function to allow windows SEH to work without destructors in the same function
5957 static int nest;
5958 //printf("%d\n", nest);
0f5c98b6 5959 if (++nest > global.recursionLimit)
b4c522fa
IB
5960 {
5961 global.gag = 0; // ensure error message gets printed
0f5c98b6 5962 error("recursive expansion exceeded allowed nesting limit");
b4c522fa
IB
5963 fatal();
5964 }
5965 semantic3(sc2);
5966
5967 --nest;
5968}
5969
5970void TemplateInstance::semantic(Scope *sc, Expressions *fargs)
5971{
5972 //printf("[%s] TemplateInstance::semantic('%s', this=%p, gag = %d, sc = %p)\n", loc.toChars(), toChars(), this, global.gag, sc);
5973 if (inst) // if semantic() was already run
5974 {
5975 return;
5976 }
5977 if (semanticRun != PASSinit)
5978 {
5979 Ungag ungag(global.gag);
5980 if (!gagged)
5981 global.gag = 0;
5982 error(loc, "recursive template expansion");
5983 if (gagged)
5984 semanticRun = PASSinit;
5985 else
5986 inst = this;
5987 errors = true;
5988 return;
5989 }
5990
5991 // Get the enclosing template instance from the scope tinst
5992 tinst = sc->tinst;
5993
5994 // Get the instantiating module from the scope minst
5995 minst = sc->minst;
5996 // Bugzilla 10920: If the enclosing function is non-root symbol,
5997 // this instance should be speculative.
5998 if (!tinst && sc->func && sc->func->inNonRoot())
5999 {
6000 minst = NULL;
6001 }
6002
6003 gagged = (global.gag > 0);
6004
6005 semanticRun = PASSsemantic;
6006
6007 /* Find template declaration first,
6008 * then run semantic on each argument (place results in tiargs[]),
6009 * last find most specialized template from overload list/set.
6010 */
6011 if (!findTempDecl(sc, NULL) ||
6012 !semanticTiargs(sc) ||
6013 !findBestMatch(sc, fargs))
6014 {
6015Lerror:
6016 if (gagged)
6017 {
6018 // Bugzilla 13220: Rollback status for later semantic re-running.
6019 semanticRun = PASSinit;
6020 }
6021 else
6022 inst = this;
6023 errors = true;
6024 return;
6025 }
6026 TemplateDeclaration *tempdecl = this->tempdecl->isTemplateDeclaration();
6027 assert(tempdecl);
6028
6029 // If tempdecl is a mixin, disallow it
6030 if (tempdecl->ismixin)
6031 {
6032 error("mixin templates are not regular templates");
6033 goto Lerror;
6034 }
6035
6036 hasNestedArgs(tiargs, tempdecl->isstatic);
6037 if (errors)
6038 goto Lerror;
6039
6040 /* See if there is an existing TemplateInstantiation that already
6041 * implements the typeargs. If so, just refer to that one instead.
6042 */
6043 inst = tempdecl->findExistingInstance(this, fargs);
6044 TemplateInstance *errinst = NULL;
6045 if (!inst)
6046 {
6047 // So, we need to implement 'this' instance.
6048 }
6049 else if (inst->gagged && !gagged && inst->errors)
6050 {
6051 // If the first instantiation had failed, re-run semantic,
6052 // so that error messages are shown.
6053 errinst = inst;
6054 }
6055 else
6056 {
6057 // It's a match
6058 parent = inst->parent;
6059 errors = inst->errors;
6060
6061 // If both this and the previous instantiation were gagged,
6062 // use the number of errors that happened last time.
6063 global.errors += errors;
6064 global.gaggedErrors += errors;
6065
6066 // If the first instantiation was gagged, but this is not:
6067 if (inst->gagged)
6068 {
6069 // It had succeeded, mark it is a non-gagged instantiation,
6070 // and reuse it.
6071 inst->gagged = gagged;
6072 }
6073
6074 this->tnext = inst->tnext;
6075 inst->tnext = this;
6076
6077 /* A module can have explicit template instance and its alias
6078 * in module scope (e,g, `alias Base64 = Base64Impl!('+', '/');`).
6079 * If the first instantiation 'inst' had happened in non-root module,
6080 * compiler can assume that its instantiated code would be included
6081 * in the separately compiled obj/lib file (e.g. phobos.lib).
6082 *
6083 * However, if 'this' second instantiation happened in root module,
6084 * compiler might need to invoke its codegen (Bugzilla 2500 & 2644).
6085 * But whole import graph is not determined until all semantic pass finished,
6086 * so 'inst' should conservatively finish the semantic3 pass for the codegen.
6087 */
6088 if (minst && minst->isRoot() && !(inst->minst && inst->minst->isRoot()))
6089 {
6090 /* Swap the position of 'inst' and 'this' in the instantiation graph.
6091 * Then, the primary instance `inst` will be changed to a root instance.
6092 *
6093 * Before:
6094 * non-root -> A!() -> B!()[inst] -> C!()
6095 * |
6096 * root -> D!() -> B!()[this]
6097 *
6098 * After:
6099 * non-root -> A!() -> B!()[this]
6100 * |
6101 * root -> D!() -> B!()[inst] -> C!()
6102 */
6103 Module *mi = minst;
6104 TemplateInstance *ti = tinst;
6105 minst = inst->minst;
6106 tinst = inst->tinst;
6107 inst->minst = mi;
6108 inst->tinst = ti;
6109
6110 if (minst) // if inst was not speculative
6111 {
6112 /* Add 'inst' once again to the root module members[], then the
6113 * instance members will get codegen chances.
6114 */
6115 inst->appendToModuleMember();
6116 }
6117 }
6118
6119 return;
6120 }
6121 unsigned errorsave = global.errors;
6122
6123 inst = this;
6124 parent = enclosing ? enclosing : tempdecl->parent;
6125 //printf("parent = '%s'\n", parent->kind());
6126
6127 TemplateInstance *tempdecl_instance_idx = tempdecl->addInstance(this);
6128
6129 //getIdent();
6130
6131 // Store the place we added it to in target_symbol_list(_idx) so we can
6132 // remove it later if we encounter an error.
6133 Dsymbols *target_symbol_list = appendToModuleMember();
2cbc99d1 6134 size_t target_symbol_list_idx = target_symbol_list ? target_symbol_list->length - 1 : 0;
b4c522fa
IB
6135
6136 // Copy the syntax trees from the TemplateDeclaration
6137 members = Dsymbol::arraySyntaxCopy(tempdecl->members);
6138
6139 // resolve TemplateThisParameter
2cbc99d1 6140 for (size_t i = 0; i < tempdecl->parameters->length; i++)
b4c522fa
IB
6141 {
6142 if ((*tempdecl->parameters)[i]->isTemplateThisParameter() == NULL)
6143 continue;
6144 Type *t = isType((*tiargs)[i]);
6145 assert(t);
6146 if (StorageClass stc = ModToStc(t->mod))
6147 {
6148 //printf("t = %s, stc = x%llx\n", t->toChars(), stc);
6149 Dsymbols *s = new Dsymbols();
6150 s->push(new StorageClassDeclaration(stc, members));
6151 members = s;
6152 }
6153 break;
6154 }
6155
6156 // Create our own scope for the template parameters
6157 Scope *scope = tempdecl->_scope;
6158 if (tempdecl->semanticRun == PASSinit)
6159 {
6160 error("template instantiation %s forward references template declaration %s", toChars(), tempdecl->toChars());
6161 return;
6162 }
6163
6164 argsym = new ScopeDsymbol();
6165 argsym->parent = scope->parent;
6166 scope = scope->push(argsym);
6167 scope->tinst = this;
6168 scope->minst = minst;
6169 //scope->stc = 0;
6170
6171 // Declare each template parameter as an alias for the argument type
6172 Scope *paramscope = scope->push();
6173 paramscope->stc = 0;
0a2ee409 6174 paramscope->protection = Prot(Prot::public_); // Bugzilla 14169: template parameters should be public
b4c522fa
IB
6175 declareParameters(paramscope);
6176 paramscope->pop();
6177
6178 // Add members of template instance to template instance symbol table
6179// parent = scope->scopesym;
6180 symtab = new DsymbolTable();
2cbc99d1 6181 for (size_t i = 0; i < members->length; i++)
b4c522fa
IB
6182 {
6183 Dsymbol *s = (*members)[i];
6184 s->addMember(scope, this);
6185 }
6186
6187 /* See if there is only one member of template instance, and that
6188 * member has the same name as the template instance.
6189 * If so, this template instance becomes an alias for that member.
6190 */
2cbc99d1
IB
6191 //printf("members->length = %d\n", members->length);
6192 if (members->length)
b4c522fa
IB
6193 {
6194 Dsymbol *s;
6195 if (Dsymbol::oneMembers(members, &s, tempdecl->ident) && s)
6196 {
6197 //printf("tempdecl->ident = %s, s = '%s'\n", tempdecl->ident->toChars(), s->kind(), s->toPrettyChars());
6198 //printf("setting aliasdecl\n");
6199 aliasdecl = s;
6200 }
6201 }
6202
6203 /* If function template declaration
6204 */
6205 if (fargs && aliasdecl)
6206 {
6207 FuncDeclaration *fd = aliasdecl->isFuncDeclaration();
6208 if (fd)
6209 {
6210 /* Transmit fargs to type so that TypeFunction::semantic() can
6211 * resolve any "auto ref" storage classes.
6212 */
6213 TypeFunction *tf = (TypeFunction *)fd->type;
6214 if (tf && tf->ty == Tfunction)
6215 tf->fargs = fargs;
6216 }
6217 }
6218
6219 // Do semantic() analysis on template instance members
6220 Scope *sc2;
6221 sc2 = scope->push(this);
6222 //printf("enclosing = %d, sc->parent = %s\n", enclosing, sc->parent->toChars());
6223 sc2->parent = this;
6224 sc2->tinst = this;
6225 sc2->minst = minst;
6226
6227 tryExpandMembers(sc2);
6228
6229 semanticRun = PASSsemanticdone;
6230
6231 /* ConditionalDeclaration may introduce eponymous declaration,
6232 * so we should find it once again after semantic.
6233 */
2cbc99d1 6234 if (members->length)
b4c522fa
IB
6235 {
6236 Dsymbol *s;
6237 if (Dsymbol::oneMembers(members, &s, tempdecl->ident) && s)
6238 {
6239 if (!aliasdecl || aliasdecl != s)
6240 {
6241 //printf("tempdecl->ident = %s, s = '%s'\n", tempdecl->ident->toChars(), s->kind(), s->toPrettyChars());
6242 //printf("setting aliasdecl 2\n");
6243 aliasdecl = s;
6244 }
6245 }
6246 }
6247
6248 if (global.errors != errorsave)
6249 goto Laftersemantic;
6250
6251 /* If any of the instantiation members didn't get semantic() run
6252 * on them due to forward references, we cannot run semantic2()
6253 * or semantic3() yet.
6254 */
6255 {
6256 bool found_deferred_ad = false;
2cbc99d1 6257 for (size_t i = 0; i < Module::deferred.length; i++)
b4c522fa
IB
6258 {
6259 Dsymbol *sd = Module::deferred[i];
6260 AggregateDeclaration *ad = sd->isAggregateDeclaration();
6261 if (ad && ad->parent && ad->parent->isTemplateInstance())
6262 {
6263 //printf("deferred template aggregate: %s %s\n",
6264 // sd->parent->toChars(), sd->toChars());
6265 found_deferred_ad = true;
6266 if (ad->parent == this)
6267 {
6268 ad->deferred = this;
6269 break;
6270 }
6271 }
6272 }
2cbc99d1 6273 if (found_deferred_ad || Module::deferred.length)
b4c522fa
IB
6274 goto Laftersemantic;
6275 }
6276
6277 /* The problem is when to parse the initializer for a variable.
6278 * Perhaps VarDeclaration::semantic() should do it like it does
6279 * for initializers inside a function.
6280 */
6281 //if (sc->parent->isFuncDeclaration())
6282 {
6283 /* BUG 782: this has problems if the classes this depends on
6284 * are forward referenced. Find a way to defer semantic()
6285 * on this template.
6286 */
6287 semantic2(sc2);
6288 }
6289 if (global.errors != errorsave)
6290 goto Laftersemantic;
6291
6292 if ((sc->func || (sc->flags & SCOPEfullinst)) && !tinst)
6293 {
6294 /* If a template is instantiated inside function, the whole instantiation
6295 * should be done at that position. But, immediate running semantic3 of
6296 * dependent templates may cause unresolved forward reference (Bugzilla 9050).
6297 * To avoid the issue, don't run semantic3 until semantic and semantic2 done.
6298 */
6299 TemplateInstances deferred;
6300 this->deferred = &deferred;
6301
6302 //printf("Run semantic3 on %s\n", toChars());
6303 trySemantic3(sc2);
6304
2cbc99d1 6305 for (size_t i = 0; i < deferred.length; i++)
b4c522fa
IB
6306 {
6307 //printf("+ run deferred semantic3 on %s\n", deferred[i]->toChars());
6308 deferred[i]->semantic3(NULL);
6309 }
6310
6311 this->deferred = NULL;
6312 }
6313 else if (tinst)
6314 {
6315 bool doSemantic3 = false;
6316 if (sc->func && aliasdecl && aliasdecl->toAlias()->isFuncDeclaration())
6317 {
6318 /* Template function instantiation should run semantic3 immediately
6319 * for attribute inference.
6320 */
6321 trySemantic3(sc2);
6322 }
6323 else if (sc->func)
6324 {
6325 /* A lambda function in template arguments might capture the
6326 * instantiated scope context. For the correct context inference,
6327 * all instantiated functions should run the semantic3 immediately.
6328 * See also compilable/test14973.d
6329 */
2cbc99d1 6330 for (size_t i = 0; i < tdtypes.length; i++)
b4c522fa
IB
6331 {
6332 RootObject *oarg = tdtypes[i];
6333 Dsymbol *s = getDsymbol(oarg);
6334 if (!s)
6335 continue;
6336
6337 if (TemplateDeclaration *td = s->isTemplateDeclaration())
6338 {
6339 if (!td->literal)
6340 continue;
2cbc99d1 6341 assert(td->members && td->members->length == 1);
b4c522fa
IB
6342 s = (*td->members)[0];
6343 }
6344 if (FuncLiteralDeclaration *fld = s->isFuncLiteralDeclaration())
6345 {
6346 if (fld->tok == TOKreserved)
6347 {
6348 doSemantic3 = true;
6349 break;
6350 }
6351 }
6352 }
6353 //printf("[%s] %s doSemantic3 = %d\n", loc.toChars(), toChars(), doSemantic3);
6354 }
6355 if (doSemantic3)
6356 trySemantic3(sc2);
6357
6358 TemplateInstance *ti = tinst;
6359 int nest = 0;
6360 while (ti && !ti->deferred && ti->tinst)
6361 {
6362 ti = ti->tinst;
0f5c98b6 6363 if (++nest > global.recursionLimit)
b4c522fa
IB
6364 {
6365 global.gag = 0; // ensure error message gets printed
6366 error("recursive expansion");
6367 fatal();
6368 }
6369 }
6370 if (ti && ti->deferred)
6371 {
6372 //printf("deferred semantic3 of %p %s, ti = %s, ti->deferred = %p\n", this, toChars(), ti->toChars());
6373 for (size_t i = 0; ; i++)
6374 {
2cbc99d1 6375 if (i == ti->deferred->length)
b4c522fa
IB
6376 {
6377 ti->deferred->push(this);
6378 break;
6379 }
6380 if ((*ti->deferred)[i] == this)
6381 break;
6382 }
6383 }
6384 }
6385
6386 if (aliasdecl)
6387 {
6388 /* Bugzilla 13816: AliasDeclaration tries to resolve forward reference
6389 * twice (See inuse check in AliasDeclaration::toAlias()). It's
6390 * necessary to resolve mutual references of instantiated symbols, but
6391 * it will left a true recursive alias in tuple declaration - an
6392 * AliasDeclaration A refers TupleDeclaration B, and B contains A
6393 * in its elements. To correctly make it an error, we strictly need to
6394 * resolve the alias of eponymous member.
6395 */
6396 aliasdecl = aliasdecl->toAlias2();
6397 }
6398
6399 Laftersemantic:
6400 sc2->pop();
6401
6402 scope->pop();
6403
6404 // Give additional context info if error occurred during instantiation
6405 if (global.errors != errorsave)
6406 {
6407 if (!errors)
6408 {
6409 if (!tempdecl->literal)
6410 error(loc, "error instantiating");
6411 if (tinst)
6412 tinst->printInstantiationTrace();
6413 }
6414 errors = true;
6415 if (gagged)
6416 {
6417 // Errors are gagged, so remove the template instance from the
6418 // instance/symbol lists we added it to and reset our state to
6419 // finish clean and so we can try to instantiate it again later
6420 // (see bugzilla 4302 and 6602).
6421 tempdecl->removeInstance(tempdecl_instance_idx);
6422 if (target_symbol_list)
6423 {
6424 // Because we added 'this' in the last position above, we
6425 // should be able to remove it without messing other indices up.
6426 assert((*target_symbol_list)[target_symbol_list_idx] == this);
6427 target_symbol_list->remove(target_symbol_list_idx);
6428 memberOf = NULL; // no longer a member
6429 }
6430 semanticRun = PASSinit;
6431 inst = NULL;
6432 symtab = NULL;
6433 }
6434 }
6435 else if (errinst)
6436 {
6437 /* Bugzilla 14541: If the previous gagged instance had failed by
6438 * circular references, currrent "error reproduction instantiation"
6439 * might succeed, because of the difference of instantiated context.
6440 * On such case, the cached error instance needs to be overridden by the
6441 * succeeded instance.
6442 */
6443 //printf("replaceInstance()\n");
6444 TemplateInstances *tinstances = (TemplateInstances *)dmd_aaGetRvalue((AA *)tempdecl->instances, (void *)hash);
6445 assert(tinstances);
2cbc99d1 6446 for (size_t i = 0; i < tinstances->length; i++)
b4c522fa
IB
6447 {
6448 TemplateInstance *ti = (*tinstances)[i];
6449 if (ti == errinst)
6450 {
6451 (*tinstances)[i] = this; // override
6452 break;
6453 }
6454 }
6455 }
6456}
6457
6458
6459/**********************************************
6460 * Find template declaration corresponding to template instance.
6461 *
6462 * Returns:
6463 * false if finding fails.
6464 * Note:
6465 * This function is reentrant against error occurrence. If returns false,
6466 * any members of this object won't be modified, and repetition call will
6467 * reproduce same error.
6468 */
6469
6470bool TemplateInstance::findTempDecl(Scope *sc, WithScopeSymbol **pwithsym)
6471{
6472 if (pwithsym)
6473 *pwithsym = NULL;
6474
6475 if (havetempdecl)
6476 return true;
6477
6478 //printf("TemplateInstance::findTempDecl() %s\n", toChars());
6479 if (!tempdecl)
6480 {
6481 /* Given:
6482 * foo!( ... )
6483 * figure out which TemplateDeclaration foo refers to.
6484 */
6485 Identifier *id = name;
6486 Dsymbol *scopesym;
6487 Dsymbol *s = sc->search(loc, id, &scopesym);
6488 if (!s)
6489 {
6490 s = sc->search_correct(id);
6491 if (s)
6492 error("template '%s' is not defined, did you mean %s?", id->toChars(), s->toChars());
6493 else
6494 error("template '%s' is not defined", id->toChars());
6495 return false;
6496 }
6497
6498 if (pwithsym)
6499 *pwithsym = scopesym->isWithScopeSymbol();
6500
6501 /* We might have found an alias within a template when
6502 * we really want the template.
6503 */
6504 TemplateInstance *ti;
6505 if (s->parent &&
6506 (ti = s->parent->isTemplateInstance()) != NULL)
6507 {
6508 if (ti->tempdecl && ti->tempdecl->ident == id)
6509 {
6510 /* This is so that one can refer to the enclosing
6511 * template, even if it has the same name as a member
6512 * of the template, if it has a !(arguments)
6513 */
6514 TemplateDeclaration *td = ti->tempdecl->isTemplateDeclaration();
6515 assert(td);
6516 if (td->overroot) // if not start of overloaded list of TemplateDeclaration's
6517 td = td->overroot; // then get the start
6518 s = td;
6519 }
6520 }
6521
6522 if (!updateTempDecl(sc, s))
6523 {
6524 return false;
6525 }
6526 }
6527 assert(tempdecl);
6528
6529 struct ParamFwdTi
6530 {
6531 static int fp(void *param, Dsymbol *s)
6532 {
6533 TemplateDeclaration *td = s->isTemplateDeclaration();
6534 if (!td)
6535 return 0;
6536
6537 TemplateInstance *ti = (TemplateInstance *)param;
6538 if (td->semanticRun == PASSinit)
6539 {
6540 if (td->_scope)
6541 {
6542 // Try to fix forward reference. Ungag errors while doing so.
6543 Ungag ungag = td->ungagSpeculative();
6544 td->semantic(td->_scope);
6545 }
6546 if (td->semanticRun == PASSinit)
6547 {
6548 ti->error("%s forward references template declaration %s", ti->toChars(), td->toChars());
6549 return 1;
6550 }
6551 }
6552 return 0;
6553 }
6554 };
6555 // Look for forward references
6556 OverloadSet *tovers = tempdecl->isOverloadSet();
2cbc99d1 6557 size_t overs_dim = tovers ? tovers->a.length : 1;
b4c522fa
IB
6558 for (size_t oi = 0; oi < overs_dim; oi++)
6559 {
6560 if (overloadApply(tovers ? tovers->a[oi] : tempdecl, (void *)this, &ParamFwdTi::fp))
6561 return false;
6562 }
6563 return true;
6564}
6565
6566/**********************************************
6567 * Confirm s is a valid template, then store it.
6568 * Input:
6569 * sc
6570 * s candidate symbol of template. It may be:
6571 * TemplateDeclaration
6572 * FuncDeclaration with findTemplateDeclRoot() != NULL
6573 * OverloadSet which contains candidates
6574 * Returns:
6575 * true if updating succeeds.
6576 */
6577
6578bool TemplateInstance::updateTempDecl(Scope *sc, Dsymbol *s)
6579{
6580 if (s)
6581 {
6582 Identifier *id = name;
6583 s = s->toAlias();
6584
6585 /* If an OverloadSet, look for a unique member that is a template declaration
6586 */
6587 OverloadSet *os = s->isOverloadSet();
6588 if (os)
6589 {
6590 s = NULL;
2cbc99d1 6591 for (size_t i = 0; i < os->a.length; i++)
b4c522fa
IB
6592 {
6593 Dsymbol *s2 = os->a[i];
6594 if (FuncDeclaration *f = s2->isFuncDeclaration())
6595 s2 = f->findTemplateDeclRoot();
6596 else
6597 s2 = s2->isTemplateDeclaration();
6598 if (s2)
6599 {
6600 if (s)
6601 {
6602 tempdecl = os;
6603 return true;
6604 }
6605 s = s2;
6606 }
6607 }
6608 if (!s)
6609 {
6610 error("template '%s' is not defined", id->toChars());
6611 return false;
6612 }
6613 }
6614
6615 OverDeclaration *od = s->isOverDeclaration();
6616 if (od)
6617 {
6618 tempdecl = od; // TODO: more strict check
6619 return true;
6620 }
6621
6622 /* It should be a TemplateDeclaration, not some other symbol
6623 */
6624 if (FuncDeclaration *f = s->isFuncDeclaration())
6625 tempdecl = f->findTemplateDeclRoot();
6626 else
6627 tempdecl = s->isTemplateDeclaration();
6628 if (!tempdecl)
6629 {
6630 if (!s->parent && global.errors)
6631 return false;
6632 if (!s->parent && s->getType())
6633 {
6634 Dsymbol *s2 = s->getType()->toDsymbol(sc);
6635 if (!s2)
6636 {
6637 error("%s is not a template declaration, it is a %s", id->toChars(), s->kind());
6638 return false;
6639 }
6640 s = s2;
6641 }
6642 //assert(s->parent);
6643 TemplateInstance *ti = s->parent ? s->parent->isTemplateInstance() : NULL;
6644 if (ti &&
6645 (ti->name == s->ident ||
6646 ti->toAlias()->ident == s->ident)
6647 &&
6648 ti->tempdecl)
6649 {
6650 /* This is so that one can refer to the enclosing
6651 * template, even if it has the same name as a member
6652 * of the template, if it has a !(arguments)
6653 */
6654 TemplateDeclaration *td = ti->tempdecl->isTemplateDeclaration();
6655 assert(td);
6656 if (td->overroot) // if not start of overloaded list of TemplateDeclaration's
6657 td = td->overroot; // then get the start
6658 tempdecl = td;
6659 }
6660 else
6661 {
6662 error("%s is not a template declaration, it is a %s", id->toChars(), s->kind());
6663 return false;
6664 }
6665 }
6666 }
6667 return (tempdecl != NULL);
6668}
6669
6670/**********************************
6671 * Run semantic on the elements of tiargs.
6672 * Input:
6673 * sc
6674 * Returns:
6675 * false if one or more arguments have errors.
6676 * Note:
6677 * This function is reentrant against error occurrence. If returns false,
6678 * all elements of tiargs won't be modified.
6679 */
6680
6681bool TemplateInstance::semanticTiargs(Scope *sc)
6682{
6683 //printf("+TemplateInstance::semanticTiargs() %s\n", toChars());
6684 if (semantictiargsdone)
6685 return true;
6686 if (semanticTiargs(loc, sc, tiargs, 0))
6687 {
6688 // cache the result iff semantic analysis succeeded entirely
6689 semantictiargsdone = 1;
6690 return true;
6691 }
6692 return false;
6693}
6694
6695/**********************************
6696 * Run semantic of tiargs as arguments of template.
6697 * Input:
6698 * loc
6699 * sc
6700 * tiargs array of template arguments
6701 * flags 1: replace const variables with their initializers
6702 * 2: don't devolve Parameter to Type
6703 * Returns:
6704 * false if one or more arguments have errors.
6705 */
6706
6707bool TemplateInstance::semanticTiargs(Loc loc, Scope *sc, Objects *tiargs, int flags)
6708{
6709 // Run semantic on each argument, place results in tiargs[]
6710 //printf("+TemplateInstance::semanticTiargs()\n");
6711 if (!tiargs)
6712 return true;
6713 bool err = false;
2cbc99d1 6714 for (size_t j = 0; j < tiargs->length; j++)
b4c522fa
IB
6715 {
6716 RootObject *o = (*tiargs)[j];
6717 Type *ta = isType(o);
6718 Expression *ea = isExpression(o);
6719 Dsymbol *sa = isDsymbol(o);
6720
6721 //printf("1: (*tiargs)[%d] = %p, s=%p, v=%p, ea=%p, ta=%p\n", j, o, isDsymbol(o), isTuple(o), ea, ta);
6722 if (ta)
6723 {
6724 //printf("type %s\n", ta->toChars());
6725 // It might really be an Expression or an Alias
6726 ta->resolve(loc, sc, &ea, &ta, &sa);
6727 if (ea) goto Lexpr;
6728 if (sa) goto Ldsym;
6729 if (ta == NULL)
6730 {
6731 assert(global.errors);
6732 ta = Type::terror;
6733 }
6734
6735 Ltype:
6736 if (ta->ty == Ttuple)
6737 {
6738 // Expand tuple
6739 TypeTuple *tt = (TypeTuple *)ta;
2cbc99d1 6740 size_t dim = tt->arguments->length;
b4c522fa
IB
6741 tiargs->remove(j);
6742 if (dim)
6743 {
6744 tiargs->reserve(dim);
6745 for (size_t i = 0; i < dim; i++)
6746 {
6747 Parameter *arg = (*tt->arguments)[i];
6748 if (flags & 2 && arg->ident)
6749 tiargs->insert(j + i, arg);
6750 else
6751 tiargs->insert(j + i, arg->type);
6752 }
6753 }
6754 j--;
6755 continue;
6756 }
6757 if (ta->ty == Terror)
6758 {
6759 err = true;
6760 continue;
6761 }
6762 (*tiargs)[j] = ta->merge2();
6763 }
6764 else if (ea)
6765 {
6766 Lexpr:
6767 //printf("+[%d] ea = %s %s\n", j, Token::toChars(ea->op), ea->toChars());
6768 if (flags & 1) // only used by __traits
6769 {
6770 ea = ::semantic(ea, sc);
6771
6772 // must not interpret the args, excepting template parameters
6773 if (ea->op != TOKvar ||
6774 (((VarExp *)ea)->var->storage_class & STCtemplateparameter))
6775 {
6776 ea = ea->optimize(WANTvalue);
6777 }
6778 }
6779 else
6780 {
6781 sc = sc->startCTFE();
6782 ea = ::semantic(ea, sc);
6783 sc = sc->endCTFE();
6784
6785 if (ea->op == TOKvar)
6786 {
6787 /* This test is to skip substituting a const var with
6788 * its initializer. The problem is the initializer won't
6789 * match with an 'alias' parameter. Instead, do the
6790 * const substitution in TemplateValueParameter::matchArg().
6791 */
6792 }
6793 else if (definitelyValueParameter(ea))
6794 {
6795 if (ea->checkValue()) // check void expression
6796 ea = new ErrorExp();
6797 unsigned int olderrs = global.errors;
6798 ea = ea->ctfeInterpret();
6799 if (global.errors != olderrs)
6800 ea = new ErrorExp();
6801 }
6802 }
6803 //printf("-[%d] ea = %s %s\n", j, Token::toChars(ea->op), ea->toChars());
6804 if (ea->op == TOKtuple)
6805 {
6806 // Expand tuple
6807 TupleExp *te = (TupleExp *)ea;
2cbc99d1 6808 size_t dim = te->exps->length;
b4c522fa
IB
6809 tiargs->remove(j);
6810 if (dim)
6811 {
6812 tiargs->reserve(dim);
6813 for (size_t i = 0; i < dim; i++)
6814 tiargs->insert(j + i, (*te->exps)[i]);
6815 }
6816 j--;
6817 continue;
6818 }
6819 if (ea->op == TOKerror)
6820 {
6821 err = true;
6822 continue;
6823 }
6824 (*tiargs)[j] = ea;
6825
6826 if (ea->op == TOKtype)
6827 {
6828 ta = ea->type;
6829 goto Ltype;
6830 }
6831 if (ea->op == TOKscope)
6832 {
6833 sa = ((ScopeExp *)ea)->sds;
6834 goto Ldsym;
6835 }
6836 if (ea->op == TOKfunction)
6837 {
6838 FuncExp *fe = (FuncExp *)ea;
6839 /* A function literal, that is passed to template and
6840 * already semanticed as function pointer, never requires
6841 * outer frame. So convert it to global function is valid.
6842 */
6843 if (fe->fd->tok == TOKreserved && fe->type->ty == Tpointer)
6844 {
6845 // change to non-nested
6846 fe->fd->tok = TOKfunction;
6847 fe->fd->vthis = NULL;
6848 }
6849 else if (fe->td)
6850 {
6851 /* If template argument is a template lambda,
6852 * get template declaration itself. */
6853 //sa = fe->td;
6854 //goto Ldsym;
6855 }
6856 }
6857 if (ea->op == TOKdotvar)
6858 {
6859 // translate expression to dsymbol.
6860 sa = ((DotVarExp *)ea)->var;
6861 goto Ldsym;
6862 }
6863 if (ea->op == TOKtemplate)
6864 {
6865 sa = ((TemplateExp *)ea)->td;
6866 goto Ldsym;
6867 }
6868 if (ea->op == TOKdottd)
6869 {
6870 // translate expression to dsymbol.
6871 sa = ((DotTemplateExp *)ea)->td;
6872 goto Ldsym;
6873 }
6874 }
6875 else if (sa)
6876 {
6877 Ldsym:
6878 //printf("dsym %s %s\n", sa->kind(), sa->toChars());
6879 if (sa->errors)
6880 {
6881 err = true;
6882 continue;
6883 }
6884
6885 TupleDeclaration *d = sa->toAlias()->isTupleDeclaration();
6886 if (d)
6887 {
6888 // Expand tuple
6889 tiargs->remove(j);
6890 tiargs->insert(j, d->objects);
6891 j--;
6892 continue;
6893 }
6894 if (FuncAliasDeclaration *fa = sa->isFuncAliasDeclaration())
6895 {
6896 FuncDeclaration *f = fa->toAliasFunc();
6897 if (!fa->hasOverloads && f->isUnique())
6898 {
6899 // Strip FuncAlias only when the aliased function
6900 // does not have any overloads.
6901 sa = f;
6902 }
6903 }
6904 (*tiargs)[j] = sa;
6905
6906 TemplateDeclaration *td = sa->isTemplateDeclaration();
6907 if (td && td->semanticRun == PASSinit && td->literal)
6908 {
6909 td->semantic(sc);
6910 }
6911 FuncDeclaration *fd = sa->isFuncDeclaration();
6912 if (fd)
6913 fd->functionSemantic();
6914 }
6915 else if (isParameter(o))
6916 {
6917 }
6918 else
6919 {
6920 assert(0);
6921 }
6922 //printf("1: (*tiargs)[%d] = %p\n", j, (*tiargs)[j]);
6923 }
6924 return !err;
6925}
6926
6927bool TemplateInstance::findBestMatch(Scope *sc, Expressions *fargs)
6928{
6929 if (havetempdecl)
6930 {
6931 TemplateDeclaration *tempdecl = this->tempdecl->isTemplateDeclaration();
6932 assert(tempdecl);
6933 assert(tempdecl->_scope);
6934 // Deduce tdtypes
2cbc99d1 6935 tdtypes.setDim(tempdecl->parameters->length);
b4c522fa
IB
6936 if (!tempdecl->matchWithInstance(sc, this, &tdtypes, fargs, 2))
6937 {
6938 error("incompatible arguments for template instantiation");
6939 return false;
6940 }
6941 // TODO: Normalizing tiargs for bugzilla 7469 is necessary?
6942 return true;
6943 }
6944
6945 unsigned errs = global.errors;
6946
6947 struct ParamBest
6948 {
6949 // context
6950 Scope *sc;
6951 TemplateInstance *ti;
6952 Objects dedtypes;
6953 // result
6954 TemplateDeclaration *td_best;
6955 TemplateDeclaration *td_ambig;
6956 MATCH m_best;
6957
6958 static int fp(void *param, Dsymbol *s)
6959 {
6960 return ((ParamBest *)param)->fp(s);
6961 }
6962 int fp(Dsymbol *s)
6963 {
6964 TemplateDeclaration *td = s->isTemplateDeclaration();
6965 if (!td)
6966 return 0;
6967
6968 if (td == td_best) // skip duplicates
6969 return 0;
6970
6971 //printf("td = %s\n", td->toPrettyChars());
6972
6973 // If more arguments than parameters,
6974 // then this is no match.
2cbc99d1 6975 if (td->parameters->length < ti->tiargs->length)
b4c522fa
IB
6976 {
6977 if (!td->isVariadic())
6978 return 0;
6979 }
6980
2cbc99d1 6981 dedtypes.setDim(td->parameters->length);
b4c522fa
IB
6982 dedtypes.zero();
6983 assert(td->semanticRun != PASSinit);
6984 MATCH m = td->matchWithInstance(sc, ti, &dedtypes, ti->fargs, 0);
6985 //printf("matchWithInstance = %d\n", m);
6986 if (m <= MATCHnomatch) // no match at all
6987 return 0;
6988
6989 if (m < m_best) goto Ltd_best;
6990 if (m > m_best) goto Ltd;
6991
6992 {
6993 // Disambiguate by picking the most specialized TemplateDeclaration
6994 MATCH c1 = td->leastAsSpecialized(sc, td_best, ti->fargs);
6995 MATCH c2 = td_best->leastAsSpecialized(sc, td, ti->fargs);
6996 //printf("c1 = %d, c2 = %d\n", c1, c2);
6997 if (c1 > c2) goto Ltd;
6998 if (c1 < c2) goto Ltd_best;
6999 }
7000
7001 td_ambig = td;
7002 return 0;
7003
7004 Ltd_best: // td_best is the best match so far
7005 td_ambig = NULL;
7006 return 0;
7007
7008 Ltd: // td is the new best match
7009 td_ambig = NULL;
7010 td_best = td;
7011 m_best = m;
2cbc99d1
IB
7012 ti->tdtypes.setDim(dedtypes.length);
7013 memcpy(ti->tdtypes.tdata(), dedtypes.tdata(), ti->tdtypes.length * sizeof(void *));
b4c522fa
IB
7014 return 0;
7015 }
7016 };
7017 ParamBest p;
7018 // context
7019 p.ti = this;
7020 p.sc = sc;
7021
7022 /* Since there can be multiple TemplateDeclaration's with the same
7023 * name, look for the best match.
7024 */
7025 TemplateDeclaration *td_last = NULL;
7026
7027 OverloadSet *tovers = tempdecl->isOverloadSet();
2cbc99d1 7028 size_t overs_dim = tovers ? tovers->a.length : 1;
b4c522fa
IB
7029 for (size_t oi = 0; oi < overs_dim; oi++)
7030 {
7031 // result
7032 p.td_best = NULL;
7033 p.td_ambig = NULL;
7034 p.m_best = MATCHnomatch;
7035 overloadApply(tovers ? tovers->a[oi] : tempdecl, &p, &ParamBest::fp);
7036
7037 if (p.td_ambig)
7038 {
7039 ::error(loc, "%s %s.%s matches more than one template declaration:\n%s: %s\nand\n%s: %s",
7040 p.td_best->kind(), p.td_best->parent->toPrettyChars(), p.td_best->ident->toChars(),
7041 p.td_best->loc.toChars() , p.td_best->toChars(),
7042 p.td_ambig->loc.toChars(), p.td_ambig->toChars());
7043 return false;
7044 }
7045 if (p.td_best)
7046 {
7047 if (!td_last)
7048 td_last = p.td_best;
7049 else if (td_last != p.td_best)
7050 {
7051 ScopeDsymbol::multiplyDefined(loc, td_last, p.td_best);
7052 return false;
7053 }
7054 }
7055 }
7056
7057 if (td_last)
7058 {
7059 /* Bugzilla 7469: Normalize tiargs by using corresponding deduced
7060 * template value parameters and tuples for the correct mangling.
7061 *
7062 * By doing this before hasNestedArgs, CTFEable local variable will be
7063 * accepted as a value parameter. For example:
7064 *
7065 * void foo() {
7066 * struct S(int n) {} // non-global template
7067 * const int num = 1; // CTFEable local variable
7068 * S!num s; // S!1 is instantiated, not S!num
7069 * }
7070 */
2cbc99d1 7071 size_t dim = td_last->parameters->length - (td_last->isVariadic() ? 1 : 0);
b4c522fa
IB
7072 for (size_t i = 0; i < dim; i++)
7073 {
2cbc99d1 7074 if (tiargs->length <= i)
b4c522fa 7075 tiargs->push(tdtypes[i]);
2cbc99d1 7076 assert(i < tiargs->length);
b4c522fa
IB
7077
7078 TemplateValueParameter *tvp = (*td_last->parameters)[i]->isTemplateValueParameter();
7079 if (!tvp)
7080 continue;
7081 assert(tdtypes[i]);
7082 // tdtypes[i] is already normalized to the required type in matchArg
7083
7084 (*tiargs)[i] = tdtypes[i];
7085 }
2cbc99d1 7086 if (td_last->isVariadic() && tiargs->length == dim && tdtypes[dim])
b4c522fa
IB
7087 {
7088 Tuple *va = isTuple(tdtypes[dim]);
7089 assert(va);
2cbc99d1 7090 for (size_t i = 0; i < va->objects.length; i++)
b4c522fa
IB
7091 tiargs->push(va->objects[i]);
7092 }
7093 }
7094 else if (errors && inst)
7095 {
7096 // instantiation was failed with error reporting
7097 assert(global.errors);
7098 return false;
7099 }
7100 else
7101 {
7102 TemplateDeclaration *tdecl = tempdecl->isTemplateDeclaration();
7103
7104 if (errs != global.errors)
7105 errorSupplemental(loc, "while looking for match for %s", toChars());
7106 else if (tdecl && !tdecl->overnext)
7107 {
7108 // Only one template, so we can give better error message
7109 error("does not match template declaration %s", tdecl->toChars());
7110 }
7111 else
7112 ::error(loc, "%s %s.%s does not match any template declaration",
7113 tempdecl->kind(), tempdecl->parent->toPrettyChars(), tempdecl->ident->toChars());
7114 return false;
7115 }
7116
7117 /* The best match is td_last
7118 */
7119 tempdecl = td_last;
7120
7121 return (errs == global.errors);
7122}
7123
7124/*****************************************************
7125 * Determine if template instance is really a template function,
7126 * and that template function needs to infer types from the function
7127 * arguments.
7128 *
7129 * Like findBestMatch, iterate possible template candidates,
7130 * but just looks only the necessity of type inference.
7131 */
7132
7133bool TemplateInstance::needsTypeInference(Scope *sc, int flag)
7134{
7135 //printf("TemplateInstance::needsTypeInference() %s\n", toChars());
7136 if (semanticRun != PASSinit)
7137 return false;
7138
7139 struct ParamNeedsInf
7140 {
7141 // context
7142 Scope *sc;
7143 TemplateInstance *ti;
7144 int flag;
7145 // result
7146 Objects dedtypes;
7147 size_t count;
7148
7149 static int fp(void *param, Dsymbol *s)
7150 {
7151 return ((ParamNeedsInf *)param)->fp(s);
7152 }
7153 int fp(Dsymbol *s)
7154 {
7155 TemplateDeclaration *td = s->isTemplateDeclaration();
7156 if (!td)
7157 {
7158 return 0;
7159 }
7160
7161 /* If any of the overloaded template declarations need inference,
7162 * then return true
7163 */
7164 FuncDeclaration *fd;
7165 if (!td->onemember)
7166 return 0;
7167 if (TemplateDeclaration *td2 = td->onemember->isTemplateDeclaration())
7168 {
7169 if (!td2->onemember || !td2->onemember->isFuncDeclaration())
7170 return 0;
2cbc99d1 7171 if (ti->tiargs->length >= td->parameters->length - (td->isVariadic() ? 1 : 0))
b4c522fa
IB
7172 return 0;
7173 return 1;
7174 }
7175 if ((fd = td->onemember->isFuncDeclaration()) == NULL ||
7176 fd->type->ty != Tfunction)
7177 {
7178 return 0;
7179 }
7180
2cbc99d1 7181 for (size_t i = 0; i < td->parameters->length; i++)
b4c522fa
IB
7182 {
7183 if ((*td->parameters)[i]->isTemplateThisParameter())
7184 return 1;
7185 }
7186
7187 /* Determine if the instance arguments, tiargs, are all that is necessary
7188 * to instantiate the template.
7189 */
2cbc99d1 7190 //printf("tp = %p, td->parameters->length = %d, tiargs->length = %d\n", tp, td->parameters->length, ti->tiargs->length);
b4c522fa 7191 TypeFunction *tf = (TypeFunction *)fd->type;
c3a2ba10 7192 if (size_t dim = tf->parameterList.length())
b4c522fa
IB
7193 {
7194 TemplateParameter *tp = td->isVariadic();
2cbc99d1 7195 if (tp && td->parameters->length > 1)
b4c522fa
IB
7196 return 1;
7197
2cbc99d1 7198 if (!tp && ti->tiargs->length < td->parameters->length)
b4c522fa
IB
7199 {
7200 // Can remain tiargs be filled by default arguments?
2cbc99d1 7201 for (size_t i = ti->tiargs->length; i < td->parameters->length; i++)
b4c522fa
IB
7202 {
7203 if (!(*td->parameters)[i]->hasDefaultArg())
7204 return 1;
7205 }
7206 }
7207
7208 for (size_t i = 0; i < dim; i++)
7209 {
7210 // 'auto ref' needs inference.
c3a2ba10 7211 if (tf->parameterList[i]->storageClass & STCauto)
b4c522fa
IB
7212 return 1;
7213 }
7214 }
7215
7216 if (!flag)
7217 {
7218 /* Calculate the need for overload resolution.
7219 * When only one template can match with tiargs, inference is not necessary.
7220 */
2cbc99d1 7221 dedtypes.setDim(td->parameters->length);
b4c522fa
IB
7222 dedtypes.zero();
7223 if (td->semanticRun == PASSinit)
7224 {
7225 if (td->_scope)
7226 {
7227 // Try to fix forward reference. Ungag errors while doing so.
7228 Ungag ungag = td->ungagSpeculative();
7229 td->semantic(td->_scope);
7230 }
7231 if (td->semanticRun == PASSinit)
7232 {
7233 ti->error("%s forward references template declaration %s", ti->toChars(), td->toChars());
7234 return 1;
7235 }
7236 }
7237 assert(td->semanticRun != PASSinit);
7238 MATCH m = td->matchWithInstance(sc, ti, &dedtypes, NULL, 0);
7239 if (m <= MATCHnomatch)
7240 return 0;
7241 }
7242
7243 /* If there is more than one function template which matches, we may
7244 * need type inference (see Bugzilla 4430)
7245 */
7246 if (++count > 1)
7247 return 1;
7248
7249 return 0;
7250 }
7251 };
7252 ParamNeedsInf p;
7253 // context
7254 p.ti = this;
7255 p.sc = sc;
7256 p.flag = flag;
7257 // result
7258 p.count = 0;
7259
7260 OverloadSet *tovers = tempdecl->isOverloadSet();
2cbc99d1 7261 size_t overs_dim = tovers ? tovers->a.length : 1;
b4c522fa
IB
7262 unsigned olderrs = global.errors;
7263 for (size_t oi = 0; oi < overs_dim; oi++)
7264 {
7265 if (overloadApply(tovers ? tovers->a[oi] : tempdecl, &p, &ParamNeedsInf::fp))
7266 return true;
7267 }
7268 if (olderrs != global.errors)
7269 {
7270 if (!global.gag)
7271 {
7272 errorSupplemental(loc, "while looking for match for %s", toChars());
7273 semanticRun = PASSsemanticdone;
7274 inst = this;
7275 }
7276 errors = true;
7277 }
7278 //printf("false\n");
7279 return false;
7280}
7281
7282
7283/*****************************************
7284 * Determines if a TemplateInstance will need a nested
7285 * generation of the TemplateDeclaration.
7286 * Sets enclosing property if so, and returns != 0;
7287 */
7288
7289bool TemplateInstance::hasNestedArgs(Objects *args, bool isstatic)
7290{
7291 int nested = 0;
7292 //printf("TemplateInstance::hasNestedArgs('%s')\n", tempdecl->ident->toChars());
7293
7294 /* A nested instance happens when an argument references a local
7295 * symbol that is on the stack.
7296 */
2cbc99d1 7297 for (size_t i = 0; i < args->length; i++)
b4c522fa
IB
7298 {
7299 RootObject *o = (*args)[i];
7300 Expression *ea = isExpression(o);
7301 Dsymbol *sa = isDsymbol(o);
7302 Tuple *va = isTuple(o);
7303 if (ea)
7304 {
7305 if (ea->op == TOKvar)
7306 {
7307 sa = ((VarExp *)ea)->var;
7308 goto Lsa;
7309 }
7310 if (ea->op == TOKthis)
7311 {
7312 sa = ((ThisExp *)ea)->var;
7313 goto Lsa;
7314 }
7315 if (ea->op == TOKfunction)
7316 {
7317 if (((FuncExp *)ea)->td)
7318 sa = ((FuncExp *)ea)->td;
7319 else
7320 sa = ((FuncExp *)ea)->fd;
7321 goto Lsa;
7322 }
7323 // Emulate Expression::toMangleBuffer call that had exist in TemplateInstance::genIdent.
7324 if (ea->op != TOKint64 &&
7325 ea->op != TOKfloat64 &&
7326 ea->op != TOKcomplex80 &&
7327 ea->op != TOKnull &&
7328 ea->op != TOKstring &&
7329 ea->op != TOKarrayliteral &&
7330 ea->op != TOKassocarrayliteral &&
7331 ea->op != TOKstructliteral)
7332 {
7333 ea->error("expression %s is not a valid template value argument", ea->toChars());
7334 errors = true;
7335 }
7336 }
7337 else if (sa)
7338 {
7339 Lsa:
7340 sa = sa->toAlias();
7341 TemplateDeclaration *td = sa->isTemplateDeclaration();
7342 if (td)
7343 {
7344 TemplateInstance *ti = sa->toParent()->isTemplateInstance();
7345 if (ti && ti->enclosing)
7346 sa = ti;
7347 }
7348 TemplateInstance *ti = sa->isTemplateInstance();
7349 Declaration *d = sa->isDeclaration();
7350 if ((td && td->literal) ||
7351 (ti && ti->enclosing) ||
7352 (d && !d->isDataseg() &&
7353 !(d->storage_class & STCmanifest) &&
7354 (!d->isFuncDeclaration() || d->isFuncDeclaration()->isNested()) &&
7355 !isTemplateMixin()
7356 ))
7357 {
7358 // if module level template
7359 if (isstatic)
7360 {
7361 Dsymbol *dparent = sa->toParent2();
7362 if (!enclosing)
7363 enclosing = dparent;
7364 else if (enclosing != dparent)
7365 {
7366 /* Select the more deeply nested of the two.
7367 * Error if one is not nested inside the other.
7368 */
7369 for (Dsymbol *p = enclosing; p; p = p->parent)
7370 {
7371 if (p == dparent)
7372 goto L1; // enclosing is most nested
7373 }
7374 for (Dsymbol *p = dparent; p; p = p->parent)
7375 {
7376 if (p == enclosing)
7377 {
7378 enclosing = dparent;
7379 goto L1; // dparent is most nested
7380 }
7381 }
7382 error("%s is nested in both %s and %s",
7383 toChars(), enclosing->toChars(), dparent->toChars());
7384 errors = true;
7385 }
7386 L1:
7387 //printf("\tnested inside %s\n", enclosing->toChars());
7388 nested |= 1;
7389 }
7390 else
7391 {
7392 error("cannot use local '%s' as parameter to non-global template %s", sa->toChars(), tempdecl->toChars());
7393 errors = true;
7394 }
7395 }
7396 }
7397 else if (va)
7398 {
7399 nested |= (int)hasNestedArgs(&va->objects, isstatic);
7400 }
7401 }
7402 //printf("-TemplateInstance::hasNestedArgs('%s') = %d\n", tempdecl->ident->toChars(), nested);
7403 return nested != 0;
7404}
7405
7406/*****************************************
7407 * Append 'this' to the specific module members[]
7408 */
7409Dsymbols *TemplateInstance::appendToModuleMember()
7410{
7411 Module *mi = minst; // instantiated -> inserted module
7412
7413 if (global.params.useUnitTests ||
7414 global.params.debuglevel)
7415 {
7416 // Turn all non-root instances to speculative
7417 if (mi && !mi->isRoot())
7418 mi = NULL;
7419 }
7420
7421 //printf("%s->appendToModuleMember() enclosing = %s mi = %s\n",
7422 // toPrettyChars(),
7423 // enclosing ? enclosing->toPrettyChars() : NULL,
7424 // mi ? mi->toPrettyChars() : NULL);
7425 if (!mi || mi->isRoot())
7426 {
7427 /* If the instantiated module is speculative or root, insert to the
7428 * member of a root module. Then:
7429 * - semantic3 pass will get called on the instance members.
7430 * - codegen pass will get a selection chance to do/skip it.
7431 */
7432
7433 struct N
7434 {
7435 static Dsymbol *getStrictEnclosing(TemplateInstance *ti)
7436 {
7437 do
7438 {
7439 if (ti->enclosing)
7440 return ti->enclosing;
7441 ti = ti->tempdecl->isInstantiated();
7442 }
7443 while (ti);
7444 return NULL;
7445 }
7446 };
7447 Dsymbol *enc = N::getStrictEnclosing(this);
7448
7449 // insert target is made stable by using the module
7450 // where tempdecl is declared.
7451 mi = (enc ? enc : tempdecl)->getModule();
7452 if (!mi->isRoot())
7453 mi = mi->importedFrom;
7454 assert(mi->isRoot());
7455 }
7456 else
7457 {
7458 /* If the instantiated module is non-root, insert to the member of the
7459 * non-root module. Then:
7460 * - semantic3 pass won't be called on the instance.
7461 * - codegen pass won't reach to the instance.
7462 */
7463 }
7464 //printf("\t--> mi = %s\n", mi->toPrettyChars());
7465
7466 if (memberOf == mi) // already a member
7467 {
7468 return NULL;
7469 }
7470
7471 Dsymbols *a = mi->members;
7472 a->push(this);
7473 memberOf = mi;
7474 if (mi->semanticRun >= PASSsemantic2done && mi->isRoot())
7475 Module::addDeferredSemantic2(this);
7476 if (mi->semanticRun >= PASSsemantic3done && mi->isRoot())
7477 Module::addDeferredSemantic3(this);
7478 return a;
7479}
7480
7481/****************************************
7482 * This instance needs an identifier for name mangling purposes.
7483 * Create one by taking the template declaration name and adding
7484 * the type signature for it.
7485 */
7486
7487Identifier *TemplateInstance::genIdent(Objects *args)
7488{
7489 TemplateDeclaration *tempdecl = this->tempdecl->isTemplateDeclaration();
7490 assert(tempdecl);
7491
7492 //printf("TemplateInstance::genIdent('%s')\n", tempdecl->ident->toChars());
7493 OutBuffer buf;
7494 const char *id = tempdecl->ident->toChars();
7495 if (!members)
7496 {
7497 // Use "__U" for the symbols declared inside template constraint.
7498 buf.printf("__U%llu%s", (ulonglong)strlen(id), id);
7499 }
7500 else
7501 buf.printf("__T%llu%s", (ulonglong)strlen(id), id);
2cbc99d1
IB
7502 size_t nparams = tempdecl->parameters->length - (tempdecl->isVariadic() ? 1 : 0);
7503 for (size_t i = 0; i < args->length; i++)
b4c522fa
IB
7504 {
7505 RootObject *o = (*args)[i];
7506 Type *ta = isType(o);
7507 Expression *ea = isExpression(o);
7508 Dsymbol *sa = isDsymbol(o);
7509 Tuple *va = isTuple(o);
7510 //printf("\to [%d] %p ta %p ea %p sa %p va %p\n", i, o, ta, ea, sa, va);
7511 if (i < nparams && (*tempdecl->parameters)[i]->specialization())
7512 buf.writeByte('H'); // Bugzilla 6574
7513 if (ta)
7514 {
7515 buf.writeByte('T');
7516 if (ta->deco)
7517 buf.writestring(ta->deco);
7518 else
7519 {
7520 assert(global.errors);
7521 }
7522 }
7523 else if (ea)
7524 {
7525 // Don't interpret it yet, it might actually be an alias template parameter.
7526 // Only constfold manifest constants, not const/immutable lvalues, see https://issues.dlang.org/show_bug.cgi?id=17339.
7527 const bool keepLvalue = true;
7528 ea = ea->optimize(WANTvalue, keepLvalue);
7529 if (ea->op == TOKvar)
7530 {
7531 sa = ((VarExp *)ea)->var;
7532 ea = NULL;
7533 goto Lsa;
7534 }
7535 if (ea->op == TOKthis)
7536 {
7537 sa = ((ThisExp *)ea)->var;
7538 ea = NULL;
7539 goto Lsa;
7540 }
7541 if (ea->op == TOKfunction)
7542 {
7543 if (((FuncExp *)ea)->td)
7544 sa = ((FuncExp *)ea)->td;
7545 else
7546 sa = ((FuncExp *)ea)->fd;
7547 ea = NULL;
7548 goto Lsa;
7549 }
7550 buf.writeByte('V');
7551 if (ea->op == TOKtuple)
7552 {
7553 ea->error("tuple is not a valid template value argument");
7554 continue;
7555 }
7556 // Now that we know it is not an alias, we MUST obtain a value
7557 unsigned olderr = global.errors;
7558 ea = ea->ctfeInterpret();
7559 if (ea->op == TOKerror || olderr != global.errors)
7560 continue;
7561
7562 /* Use deco that matches what it would be for a function parameter
7563 */
7564 buf.writestring(ea->type->deco);
7565 mangleToBuffer(ea, &buf);
7566 }
7567 else if (sa)
7568 {
7569 Lsa:
7570 buf.writeByte('S');
7571 sa = sa->toAlias();
7572 Declaration *d = sa->isDeclaration();
7573 if (d && (!d->type || !d->type->deco))
7574 {
7575 error("forward reference of %s %s", d->kind(), d->toChars());
7576 continue;
7577 }
7578
7579 OutBuffer bufsa;
7580 mangleToBuffer(sa, &bufsa);
fced594b 7581 const char *s = bufsa.extractChars();
b4c522fa
IB
7582
7583 /* Bugzilla 3043: if the first character of s is a digit this
7584 * causes ambiguity issues because the digits of the two numbers are adjacent.
7585 * Current demanglers resolve this by trying various places to separate the
7586 * numbers until one gets a successful demangle.
7587 * Unfortunately, fixing this ambiguity will break existing binary
7588 * compatibility and the demanglers, so we'll leave it as is.
7589 */
7590 buf.printf("%u%s", (unsigned)strlen(s), s);
7591 }
7592 else if (va)
7593 {
2cbc99d1 7594 assert(i + 1 == args->length); // must be last one
b4c522fa
IB
7595 args = &va->objects;
7596 i = -(size_t)1;
7597 }
7598 else
7599 assert(0);
7600 }
7601 buf.writeByte('Z');
fced594b 7602 id = buf.peekChars();
b4c522fa
IB
7603 //printf("\tgenIdent = %s\n", id);
7604 return Identifier::idPool(id);
7605}
7606
7607/*************************************
7608 * Lazily generate identifier for template instance.
7609 * This is because 75% of the ident's are never needed.
7610 */
7611
7612Identifier *TemplateInstance::getIdent()
7613{
7614 if (!ident && inst && !errors)
7615 ident = genIdent(tiargs); // need an identifier for name mangling purposes.
7616 return ident;
7617}
7618
7619/****************************************************
7620 * Declare parameters of template instance, initialize them with the
7621 * template instance arguments.
7622 */
7623
7624void TemplateInstance::declareParameters(Scope *sc)
7625{
7626 TemplateDeclaration *tempdecl = this->tempdecl->isTemplateDeclaration();
7627 assert(tempdecl);
7628
7629 //printf("TemplateInstance::declareParameters()\n");
2cbc99d1 7630 for (size_t i = 0; i < tdtypes.length; i++)
b4c522fa
IB
7631 {
7632 TemplateParameter *tp = (*tempdecl->parameters)[i];
7633 //RootObject *o = (*tiargs)[i];
7634 RootObject *o = tdtypes[i]; // initializer for tp
7635
7636 //printf("\ttdtypes[%d] = %p\n", i, o);
7637 tempdecl->declareParameter(sc, tp, o);
7638 }
7639}
7640
7641void TemplateInstance::semantic2(Scope *sc)
7642{
7643 if (semanticRun >= PASSsemantic2)
7644 return;
7645 semanticRun = PASSsemantic2;
7646 if (!errors && members)
7647 {
7648 TemplateDeclaration *tempdecl = this->tempdecl->isTemplateDeclaration();
7649 assert(tempdecl);
7650
7651 sc = tempdecl->_scope;
7652 assert(sc);
7653 sc = sc->push(argsym);
7654 sc = sc->push(this);
7655 sc->tinst = this;
7656 sc->minst = minst;
7657
7658 int needGagging = (gagged && !global.gag);
7659 unsigned int olderrors = global.errors;
7660 int oldGaggedErrors = -1; // dead-store to prevent spurious warning
7661 if (needGagging)
7662 oldGaggedErrors = global.startGagging();
7663
2cbc99d1 7664 for (size_t i = 0; i < members->length; i++)
b4c522fa
IB
7665 {
7666 Dsymbol *s = (*members)[i];
7667 s->semantic2(sc);
7668 if (gagged && global.errors != olderrors)
7669 break;
7670 }
7671
7672 if (global.errors != olderrors)
7673 {
7674 if (!errors)
7675 {
7676 if (!tempdecl->literal)
7677 error(loc, "error instantiating");
7678 if (tinst)
7679 tinst->printInstantiationTrace();
7680 }
7681 errors = true;
7682 }
7683 if (needGagging)
7684 global.endGagging(oldGaggedErrors);
7685
7686 sc = sc->pop();
7687 sc->pop();
7688 }
7689}
7690
7691void TemplateInstance::semantic3(Scope *sc)
7692{
7693//if (toChars()[0] == 'D') *(char*)0=0;
7694 if (semanticRun >= PASSsemantic3)
7695 return;
7696 semanticRun = PASSsemantic3;
7697 if (!errors && members)
7698 {
7699 TemplateDeclaration *tempdecl = this->tempdecl->isTemplateDeclaration();
7700 assert(tempdecl);
7701
7702 sc = tempdecl->_scope;
7703 sc = sc->push(argsym);
7704 sc = sc->push(this);
7705 sc->tinst = this;
7706 sc->minst = minst;
7707
7708 int needGagging = (gagged && !global.gag);
7709 unsigned int olderrors = global.errors;
7710 int oldGaggedErrors = -1; // dead-store to prevent spurious warning
7711 /* If this is a gagged instantiation, gag errors.
7712 * Future optimisation: If the results are actually needed, errors
7713 * would already be gagged, so we don't really need to run semantic
7714 * on the members.
7715 */
7716 if (needGagging)
7717 oldGaggedErrors = global.startGagging();
7718
2cbc99d1 7719 for (size_t i = 0; i < members->length; i++)
b4c522fa
IB
7720 {
7721 Dsymbol *s = (*members)[i];
7722 s->semantic3(sc);
7723 if (gagged && global.errors != olderrors)
7724 break;
7725 }
7726
7727 if (global.errors != olderrors)
7728 {
7729 if (!errors)
7730 {
7731 if (!tempdecl->literal)
7732 error(loc, "error instantiating");
7733 if (tinst)
7734 tinst->printInstantiationTrace();
7735 }
7736 errors = true;
7737 }
7738 if (needGagging)
7739 global.endGagging(oldGaggedErrors);
7740
7741 sc = sc->pop();
7742 sc->pop();
7743 }
7744}
7745
7746/**************************************
7747 * Given an error instantiating the TemplateInstance,
7748 * give the nested TemplateInstance instantiations that got
7749 * us here. Those are a list threaded into the nested scopes.
7750 */
7751void TemplateInstance::printInstantiationTrace()
7752{
7753 if (global.gag)
7754 return;
7755
7756 const unsigned max_shown = 6;
7757 const char format[] = "instantiated from here: %s";
7758
7759 // determine instantiation depth and number of recursive instantiations
7760 unsigned n_instantiations = 1;
7761 unsigned n_totalrecursions = 0;
7762 for (TemplateInstance *cur = this; cur; cur = cur->tinst)
7763 {
7764 ++n_instantiations;
7765 // If two instantiations use the same declaration, they are recursive.
7766 // (this works even if they are instantiated from different places in the
7767 // same template).
7768 // In principle, we could also check for multiple-template recursion, but it's
7769 // probably not worthwhile.
7770 if (cur->tinst && cur->tempdecl && cur->tinst->tempdecl
7771 && cur->tempdecl->loc.equals(cur->tinst->tempdecl->loc))
7772 ++n_totalrecursions;
7773 }
7774
7775 // show full trace only if it's short or verbose is on
7776 if (n_instantiations <= max_shown || global.params.verbose)
7777 {
7778 for (TemplateInstance *cur = this; cur; cur = cur->tinst)
7779 {
7780 cur->errors = true;
7781 errorSupplemental(cur->loc, format, cur->toChars());
7782 }
7783 }
7784 else if (n_instantiations - n_totalrecursions <= max_shown)
7785 {
7786 // By collapsing recursive instantiations into a single line,
7787 // we can stay under the limit.
7788 int recursionDepth=0;
7789 for (TemplateInstance *cur = this; cur; cur = cur->tinst)
7790 {
7791 cur->errors = true;
7792 if (cur->tinst && cur->tempdecl && cur->tinst->tempdecl
7793 && cur->tempdecl->loc.equals(cur->tinst->tempdecl->loc))
7794 {
7795 ++recursionDepth;
7796 }
7797 else
7798 {
7799 if (recursionDepth)
7800 errorSupplemental(cur->loc, "%d recursive instantiations from here: %s", recursionDepth+2, cur->toChars());
7801 else
7802 errorSupplemental(cur->loc, format, cur->toChars());
7803 recursionDepth = 0;
7804 }
7805 }
7806 }
7807 else
7808 {
7809 // Even after collapsing the recursions, the depth is too deep.
7810 // Just display the first few and last few instantiations.
7811 unsigned i = 0;
7812 for (TemplateInstance *cur = this; cur; cur = cur->tinst)
7813 {
7814 cur->errors = true;
7815
7816 if (i == max_shown / 2)
7817 errorSupplemental(cur->loc, "... (%d instantiations, -v to show) ...", n_instantiations - max_shown);
7818
7819 if (i < max_shown / 2 ||
7820 i >= n_instantiations - max_shown + max_shown / 2)
7821 errorSupplemental(cur->loc, format, cur->toChars());
7822 ++i;
7823 }
7824 }
7825}
7826
7827Dsymbol *TemplateInstance::toAlias()
7828{
7829 if (!inst)
7830 {
7831 // Maybe we can resolve it
7832 if (_scope)
7833 {
7834 semantic(_scope);
7835 }
7836 if (!inst)
7837 {
7838 error("cannot resolve forward reference");
7839 errors = true;
7840 return this;
7841 }
7842 }
7843
7844 if (inst != this)
7845 return inst->toAlias();
7846
7847 if (aliasdecl)
7848 {
7849 return aliasdecl->toAlias();
7850 }
7851
7852 return inst;
7853}
7854
f9ab59ff 7855const char *TemplateInstance::kind() const
b4c522fa
IB
7856{
7857 return "template instance";
7858}
7859
7860bool TemplateInstance::oneMember(Dsymbol **ps, Identifier *)
7861{
7862 *ps = NULL;
7863 return true;
7864}
7865
7866const char *TemplateInstance::toChars()
7867{
7868 OutBuffer buf;
7869 toCBufferInstance(this, &buf);
fced594b 7870 return buf.extractChars();
b4c522fa
IB
7871}
7872
7873const char *TemplateInstance::toPrettyCharsHelper()
7874{
7875 OutBuffer buf;
7876 toCBufferInstance(this, &buf, true);
fced594b 7877 return buf.extractChars();
b4c522fa
IB
7878}
7879
7880/*************************************
7881 * Compare proposed template instantiation with existing template instantiation.
7882 * Note that this is not commutative because of the auto ref check.
7883 * Params:
7884 * this = proposed template instantiation
7885 * o = existing template instantiation
7886 * Returns:
7887 * 0 for match, 1 for no match
7888 */
7889int TemplateInstance::compare(RootObject *o)
7890{
7891 TemplateInstance *ti = (TemplateInstance *)o;
7892
7893 //printf("this = %p, ti = %p\n", this, ti);
2cbc99d1 7894 assert(tdtypes.length == ti->tdtypes.length);
b4c522fa
IB
7895
7896 // Nesting must match
7897 if (enclosing != ti->enclosing)
7898 {
7899 //printf("test2 enclosing %s ti->enclosing %s\n", enclosing ? enclosing->toChars() : "", ti->enclosing ? ti->enclosing->toChars() : "");
7900 goto Lnotequals;
7901 }
7902 //printf("parent = %s, ti->parent = %s\n", parent->toPrettyChars(), ti->parent->toPrettyChars());
7903
7904 if (!arrayObjectMatch(&tdtypes, &ti->tdtypes))
7905 goto Lnotequals;
7906
7907 /* Template functions may have different instantiations based on
7908 * "auto ref" parameters.
7909 */
7910 if (FuncDeclaration *fd = ti->toAlias()->isFuncDeclaration())
7911 {
7912 if (!fd->errors)
7913 {
c3a2ba10
IB
7914 ParameterList fparameters = fd->getParameterList();
7915 size_t nfparams = fparameters.length(); // Num function parameters
b4c522fa
IB
7916 for (size_t j = 0; j < nfparams; j++)
7917 {
c3a2ba10 7918 Parameter *fparam = fparameters[j];
b4c522fa
IB
7919 if (fparam->storageClass & STCautoref) // if "auto ref"
7920 {
7921 if (!fargs)
7922 goto Lnotequals;
2cbc99d1 7923 if (fargs->length <= j)
b4c522fa
IB
7924 break;
7925 Expression *farg = (*fargs)[j];
7926 if (farg->isLvalue())
7927 {
7928 if (!(fparam->storageClass & STCref))
7929 goto Lnotequals; // auto ref's don't match
7930 }
7931 else
7932 {
7933 if (fparam->storageClass & STCref)
7934 goto Lnotequals; // auto ref's don't match
7935 }
7936 }
7937 }
7938 }
7939 }
7940 return 0;
7941
7942 Lnotequals:
7943 return 1;
7944}
7945
7946hash_t TemplateInstance::toHash()
7947{
7948 if (!hash)
7949 {
7950 hash = (size_t)(void *)enclosing;
7951 hash += arrayObjectHash(&tdtypes);
7952 hash += hash == 0;
7953 }
7954 return hash;
7955}
7956
7957/**************************************
7958 * IsExpression can evaluate the specified type speculatively, and even if
7959 * it instantiates any symbols, they are normally unnecessary for the
7960 * final executable.
7961 * However, if those symbols leak to the actual code, compiler should remark
7962 * them as non-speculative to generate their code and link to the final executable.
7963 */
7964void unSpeculative(Scope *sc, RootObject *o)
7965{
7966 if (!o)
7967 return;
7968
7969 if (Tuple *tup = isTuple(o))
7970 {
2cbc99d1 7971 for (size_t i = 0; i < tup->objects.length; i++)
b4c522fa
IB
7972 {
7973 unSpeculative(sc, tup->objects[i]);
7974 }
7975 return;
7976 }
7977
7978 Dsymbol *s = getDsymbol(o);
7979 if (!s)
7980 return;
7981
7982 if (Declaration *d = s->isDeclaration())
7983 {
7984 if (VarDeclaration *vd = d->isVarDeclaration())
7985 o = vd->type;
7986 else if (AliasDeclaration *ad = d->isAliasDeclaration())
7987 {
7988 o = ad->getType();
7989 if (!o)
7990 o = ad->toAlias();
7991 }
7992 else
7993 o = d->toAlias();
7994
7995 s = getDsymbol(o);
7996 if (!s)
7997 return;
7998 }
7999
8000 if (TemplateInstance *ti = s->isTemplateInstance())
8001 {
8002 // If the instance is already non-speculative,
8003 // or it is leaked to the speculative scope.
8004 if (ti->minst != NULL || sc->minst == NULL)
8005 return;
8006
8007 // Remark as non-speculative instance.
8008 ti->minst = sc->minst;
8009 if (!ti->tinst)
8010 ti->tinst = sc->tinst;
8011
8012 unSpeculative(sc, ti->tempdecl);
8013 }
8014
8015 if (TemplateInstance *ti = s->isInstantiated())
8016 unSpeculative(sc, ti);
8017}
8018
8019/***********************************************
8020 * Returns true if this is not instantiated in non-root module, and
8021 * is a part of non-speculative instantiatiation.
8022 *
8023 * Note: minst does not stabilize until semantic analysis is completed,
8024 * so don't call this function during semantic analysis to return precise result.
8025 */
8026bool TemplateInstance::needsCodegen()
8027{
8028 // Now -allInst is just for the backward compatibility.
8029 if (global.params.allInst)
8030 {
8031 //printf("%s minst = %s, enclosing (%s)->isNonRoot = %d\n",
8032 // toPrettyChars(), minst ? minst->toChars() : NULL,
8033 // enclosing ? enclosing->toPrettyChars() : NULL, enclosing && enclosing->inNonRoot());
8034 if (enclosing)
8035 {
8036 // Bugzilla 14588: If the captured context is not a function
8037 // (e.g. class), the instance layout determination is guaranteed,
8038 // because the semantic/semantic2 pass will be executed
8039 // even for non-root instances.
8040 if (!enclosing->isFuncDeclaration())
8041 return true;
8042
8043 // Bugzilla 14834: If the captured context is a function,
8044 // this excessive instantiation may cause ODR violation, because
8045 // -allInst and others doesn't guarantee the semantic3 execution
8046 // for that function.
8047
8048 // If the enclosing is also an instantiated function,
8049 // we have to rely on the ancestor's needsCodegen() result.
8050 if (TemplateInstance *ti = enclosing->isInstantiated())
8051 return ti->needsCodegen();
8052
8053 // Bugzilla 13415: If and only if the enclosing scope needs codegen,
8054 // this nested templates would also need code generation.
8055 return !enclosing->inNonRoot();
8056 }
8057 return true;
8058 }
8059
8060 if (!minst)
8061 {
8062 // If this is a speculative instantiation,
8063 // 1. do codegen if ancestors really needs codegen.
8064 // 2. become non-speculative if siblings are not speculative
8065
8066 TemplateInstance *tnext = this->tnext;
8067 TemplateInstance *tinst = this->tinst;
8068 // At first, disconnect chain first to prevent infinite recursion.
8069 this->tnext = NULL;
8070 this->tinst = NULL;
8071
8072 // Determine necessity of tinst before tnext.
8073 if (tinst && tinst->needsCodegen())
8074 {
8075 minst = tinst->minst; // cache result
8076 assert(minst);
8077 assert(minst->isRoot() || minst->rootImports());
8078 return true;
8079 }
8080 if (tnext && (tnext->needsCodegen() || tnext->minst))
8081 {
8082 minst = tnext->minst; // cache result
8083 assert(minst);
8084 return minst->isRoot() || minst->rootImports();
8085 }
8086
8087 // Elide codegen because this is really speculative.
8088 return false;
8089 }
8090
8091 /* Even when this is reached to the codegen pass,
8092 * a non-root nested template should not generate code,
8093 * due to avoid ODR violation.
8094 */
8095 if (enclosing && enclosing->inNonRoot())
8096 {
8097 if (tinst)
8098 {
8099 bool r = tinst->needsCodegen();
8100 minst = tinst->minst; // cache result
8101 return r;
8102 }
8103 if (tnext)
8104 {
8105 bool r = tnext->needsCodegen();
8106 minst = tnext->minst; // cache result
8107 return r;
8108 }
8109 return false;
8110 }
8111
8112 /* The issue is that if the importee is compiled with a different -debug
8113 * setting than the importer, the importer may believe it exists
8114 * in the compiled importee when it does not, when the instantiation
8115 * is behind a conditional debug declaration.
8116 */
8117 // workaround for Bugzilla 11239
8118 if (global.params.useUnitTests ||
8119 global.params.debuglevel)
8120 {
8121 // Prefer instantiations from root modules, to maximize link-ability.
8122 if (minst->isRoot())
8123 return true;
8124
8125 TemplateInstance *tnext = this->tnext;
8126 TemplateInstance *tinst = this->tinst;
8127 this->tnext = NULL;
8128 this->tinst = NULL;
8129
8130 if (tinst && tinst->needsCodegen())
8131 {
8132 minst = tinst->minst; // cache result
8133 assert(minst);
8134 assert(minst->isRoot() || minst->rootImports());
8135 return true;
8136 }
8137 if (tnext && tnext->needsCodegen())
8138 {
8139 minst = tnext->minst; // cache result
8140 assert(minst);
8141 assert(minst->isRoot() || minst->rootImports());
8142 return true;
8143 }
8144
8145 // Bugzilla 2500 case
8146 if (minst->rootImports())
8147 return true;
8148
8149 // Elide codegen because this is not included in root instances.
8150 return false;
8151 }
8152 else
8153 {
8154 // Prefer instantiations from non-root module, to minimize object code size.
8155
8156 /* If a TemplateInstance is ever instantiated by non-root modules,
8157 * we do not have to generate code for it,
8158 * because it will be generated when the non-root module is compiled.
8159 *
8160 * But, if the non-root 'minst' imports any root modules, it might still need codegen.
8161 *
8162 * The problem is if A imports B, and B imports A, and both A
8163 * and B instantiate the same template, does the compilation of A
8164 * or the compilation of B do the actual instantiation?
8165 *
8166 * See Bugzilla 2500.
8167 */
8168 if (!minst->isRoot() && !minst->rootImports())
8169 return false;
8170
8171 TemplateInstance *tnext = this->tnext;
8172 this->tnext = NULL;
8173
8174 if (tnext && !tnext->needsCodegen() && tnext->minst)
8175 {
8176 minst = tnext->minst; // cache result
8177 assert(!minst->isRoot());
8178 return false;
8179 }
8180
8181 // Do codegen because this is not included in non-root instances.
8182 return true;
8183 }
8184}
8185
8186/* ======================== TemplateMixin ================================ */
8187
8188TemplateMixin::TemplateMixin(Loc loc, Identifier *ident, TypeQualified *tqual, Objects *tiargs)
2cbc99d1 8189 : TemplateInstance(loc, tqual->idents.length ? (Identifier *)tqual->idents[tqual->idents.length - 1]
b4c522fa
IB
8190 : ((TypeIdentifier *)tqual)->ident)
8191{
8192 //printf("TemplateMixin(ident = '%s')\n", ident ? ident->toChars() : "");
8193 this->ident = ident;
8194 this->tqual = tqual;
8195 this->tiargs = tiargs ? tiargs : new Objects();
8196}
8197
8198Dsymbol *TemplateMixin::syntaxCopy(Dsymbol *)
8199{
8200 TemplateMixin *tm = new TemplateMixin(loc, ident,
8201 (TypeQualified *)tqual->syntaxCopy(), tiargs);
8202 return TemplateInstance::syntaxCopy(tm);
8203}
8204
8205bool TemplateMixin::findTempDecl(Scope *sc)
8206{
8207 // Follow qualifications to find the TemplateDeclaration
8208 if (!tempdecl)
8209 {
8210 Expression *e;
8211 Type *t;
8212 Dsymbol *s;
8213 tqual->resolve(loc, sc, &e, &t, &s);
8214 if (!s)
8215 {
8216 error("is not defined");
8217 return false;
8218 }
8219 s = s->toAlias();
8220 tempdecl = s->isTemplateDeclaration();
8221 OverloadSet *os = s->isOverloadSet();
8222
8223 /* If an OverloadSet, look for a unique member that is a template declaration
8224 */
8225 if (os)
8226 {
8227 Dsymbol *ds = NULL;
2cbc99d1 8228 for (size_t i = 0; i < os->a.length; i++)
b4c522fa
IB
8229 {
8230 Dsymbol *s2 = os->a[i]->isTemplateDeclaration();
8231 if (s2)
8232 {
8233 if (ds)
8234 {
8235 tempdecl = os;
8236 break;
8237 }
8238 ds = s2;
8239 }
8240 }
8241 }
8242 if (!tempdecl)
8243 {
8244 error("%s isn't a template", s->toChars());
8245 return false;
8246 }
8247 }
8248 assert(tempdecl);
8249
8250 struct ParamFwdResTm
8251 {
8252 static int fp(void *param, Dsymbol *s)
8253 {
8254 TemplateDeclaration *td = s->isTemplateDeclaration();
8255 if (!td)
8256 return 0;
8257
8258 TemplateMixin *tm = (TemplateMixin *)param;
8259 if (td->semanticRun == PASSinit)
8260 {
8261 if (td->_scope)
8262 td->semantic(td->_scope);
8263 else
8264 {
8265 tm->semanticRun = PASSinit;
8266 return 1;
8267 }
8268 }
8269 return 0;
8270 }
8271 };
8272 // Look for forward references
8273 OverloadSet *tovers = tempdecl->isOverloadSet();
2cbc99d1 8274 size_t overs_dim = tovers ? tovers->a.length : 1;
b4c522fa
IB
8275 for (size_t oi = 0; oi < overs_dim; oi++)
8276 {
8277 if (overloadApply(tovers ? tovers->a[oi] : tempdecl, (void *)this, &ParamFwdResTm::fp))
8278 return false;
8279 }
8280 return true;
8281}
8282
8283void TemplateMixin::semantic(Scope *sc)
8284{
8285 if (semanticRun != PASSinit)
8286 {
8287 // When a class/struct contains mixin members, and is done over
8288 // because of forward references, never reach here so semanticRun
8289 // has been reset to PASSinit.
8290 return;
8291 }
8292 semanticRun = PASSsemantic;
8293
8294 Scope *scx = NULL;
8295 if (_scope)
8296 {
8297 sc = _scope;
8298 scx = _scope; // save so we don't make redundant copies
8299 _scope = NULL;
8300 }
8301
8302 /* Run semantic on each argument, place results in tiargs[],
8303 * then find best match template with tiargs
8304 */
8305 if (!findTempDecl(sc) ||
8306 !semanticTiargs(sc) ||
8307 !findBestMatch(sc, NULL))
8308 {
8309 if (semanticRun == PASSinit) // forward reference had occured
8310 {
8311 //printf("forward reference - deferring\n");
8312 _scope = scx ? scx : sc->copy();
8313 _scope->setNoFree();
8314 _scope->_module->addDeferredSemantic(this);
8315 return;
8316 }
8317
8318 inst = this;
8319 errors = true;
8320 return; // error recovery
8321 }
8322 TemplateDeclaration *tempdecl = this->tempdecl->isTemplateDeclaration();
8323 assert(tempdecl);
8324
8325 if (!ident)
8326 {
8327 /* Assign scope local unique identifier, as same as lambdas.
8328 */
8329 const char *s = "__mixin";
8330
8331 DsymbolTable *symtab;
8332 if (FuncDeclaration *func = sc->parent->isFuncDeclaration())
8333 {
8334 symtab = func->localsymtab;
8335 if (symtab)
8336 {
8337 // Inside template constraint, symtab is not set yet.
8338 goto L1;
8339 }
8340 }
8341 else
8342 {
8343 symtab = sc->parent->isScopeDsymbol()->symtab;
8344 L1:
8345 assert(symtab);
8346 int num = (int)dmd_aaLen(symtab->tab) + 1;
8347 ident = Identifier::generateId(s, num);
8348 symtab->insert(this);
8349 }
8350 }
8351
8352 inst = this;
8353 parent = sc->parent;
8354
8355 /* Detect recursive mixin instantiations.
8356 */
8357 for (Dsymbol *s = parent; s; s = s->parent)
8358 {
8359 //printf("\ts = '%s'\n", s->toChars());
8360 TemplateMixin *tm = s->isTemplateMixin();
8361 if (!tm || tempdecl != tm->tempdecl)
8362 continue;
8363
8364 /* Different argument list lengths happen with variadic args
8365 */
2cbc99d1 8366 if (tiargs->length != tm->tiargs->length)
b4c522fa
IB
8367 continue;
8368
2cbc99d1 8369 for (size_t i = 0; i < tiargs->length; i++)
b4c522fa
IB
8370 {
8371 RootObject *o = (*tiargs)[i];
8372 Type *ta = isType(o);
8373 Expression *ea = isExpression(o);
8374 Dsymbol *sa = isDsymbol(o);
8375 RootObject *tmo = (*tm->tiargs)[i];
8376 if (ta)
8377 {
8378 Type *tmta = isType(tmo);
8379 if (!tmta)
8380 goto Lcontinue;
8381 if (!ta->equals(tmta))
8382 goto Lcontinue;
8383 }
8384 else if (ea)
8385 {
8386 Expression *tme = isExpression(tmo);
8387 if (!tme || !ea->equals(tme))
8388 goto Lcontinue;
8389 }
8390 else if (sa)
8391 {
8392 Dsymbol *tmsa = isDsymbol(tmo);
8393 if (sa != tmsa)
8394 goto Lcontinue;
8395 }
8396 else
8397 assert(0);
8398 }
8399 error("recursive mixin instantiation");
8400 return;
8401
8402 Lcontinue:
8403 continue;
8404 }
8405
8406 // Copy the syntax trees from the TemplateDeclaration
8407 members = Dsymbol::arraySyntaxCopy(tempdecl->members);
8408 if (!members)
8409 return;
8410
8411 symtab = new DsymbolTable();
8412
8413 for (Scope *sce = sc; 1; sce = sce->enclosing)
8414 {
8415 ScopeDsymbol *sds = (ScopeDsymbol *)sce->scopesym;
8416 if (sds)
8417 {
0a2ee409 8418 sds->importScope(this, Prot(Prot::public_));
b4c522fa
IB
8419 break;
8420 }
8421 }
8422
8423 Scope *scy = sc->push(this);
8424 scy->parent = this;
8425
8426 argsym = new ScopeDsymbol();
8427 argsym->parent = scy->parent;
8428 Scope *argscope = scy->push(argsym);
8429
8430 unsigned errorsave = global.errors;
8431
8432 // Declare each template parameter as an alias for the argument type
8433 declareParameters(argscope);
8434
8435 // Add members to enclosing scope, as well as this scope
2cbc99d1 8436 for (size_t i = 0; i < members->length; i++)
b4c522fa
IB
8437 {
8438 Dsymbol *s = (*members)[i];
8439 s->addMember(argscope, this);
8440 //printf("sc->parent = %p, sc->scopesym = %p\n", sc->parent, sc->scopesym);
8441 //printf("s->parent = %s\n", s->parent->toChars());
8442 }
8443
8444 // Do semantic() analysis on template instance members
8445 Scope *sc2 = argscope->push(this);
2cbc99d1 8446 //size_t deferred_dim = Module::deferred.length;
b4c522fa
IB
8447
8448 static int nest;
8449 //printf("%d\n", nest);
0f5c98b6 8450 if (++nest > global.recursionLimit)
b4c522fa
IB
8451 {
8452 global.gag = 0; // ensure error message gets printed
8453 error("recursive expansion");
8454 fatal();
8455 }
8456
2cbc99d1 8457 for (size_t i = 0; i < members->length; i++)
b4c522fa
IB
8458 {
8459 Dsymbol *s = (*members)[i];
8460 s->setScope(sc2);
8461 }
8462
2cbc99d1 8463 for (size_t i = 0; i < members->length; i++)
b4c522fa
IB
8464 {
8465 Dsymbol *s = (*members)[i];
8466 s->importAll(sc2);
8467 }
8468
2cbc99d1 8469 for (size_t i = 0; i < members->length; i++)
b4c522fa
IB
8470 {
8471 Dsymbol *s = (*members)[i];
8472 s->semantic(sc2);
8473 }
8474
8475 nest--;
8476
8477 /* In DeclDefs scope, TemplateMixin does not have to handle deferred symbols.
8478 * Because the members would already call Module::addDeferredSemantic() for themselves.
8479 * See Struct, Class, Interface, and EnumDeclaration::semantic().
8480 */
2cbc99d1 8481 //if (!sc->func && Module::deferred.length > deferred_dim) {}
b4c522fa
IB
8482
8483 AggregateDeclaration *ad = toParent()->isAggregateDeclaration();
8484 if (sc->func && !ad)
8485 {
8486 semantic2(sc2);
8487 semantic3(sc2);
8488 }
8489
8490 // Give additional context info if error occurred during instantiation
8491 if (global.errors != errorsave)
8492 {
8493 error("error instantiating");
8494 errors = true;
8495 }
8496
8497 sc2->pop();
8498 argscope->pop();
8499 scy->pop();
8500}
8501
8502void TemplateMixin::semantic2(Scope *sc)
8503{
8504 if (semanticRun >= PASSsemantic2)
8505 return;
8506 semanticRun = PASSsemantic2;
8507 if (members)
8508 {
8509 assert(sc);
8510 sc = sc->push(argsym);
8511 sc = sc->push(this);
2cbc99d1 8512 for (size_t i = 0; i < members->length; i++)
b4c522fa
IB
8513 {
8514 Dsymbol *s = (*members)[i];
8515 s->semantic2(sc);
8516 }
8517 sc = sc->pop();
8518 sc->pop();
8519 }
8520}
8521
8522void TemplateMixin::semantic3(Scope *sc)
8523{
8524 if (semanticRun >= PASSsemantic3)
8525 return;
8526 semanticRun = PASSsemantic3;
8527 if (members)
8528 {
8529 sc = sc->push(argsym);
8530 sc = sc->push(this);
2cbc99d1 8531 for (size_t i = 0; i < members->length; i++)
b4c522fa
IB
8532 {
8533 Dsymbol *s = (*members)[i];
8534 s->semantic3(sc);
8535 }
8536 sc = sc->pop();
8537 sc->pop();
8538 }
8539}
8540
f9ab59ff 8541const char *TemplateMixin::kind() const
b4c522fa
IB
8542{
8543 return "mixin";
8544}
8545
8546bool TemplateMixin::oneMember(Dsymbol **ps, Identifier *ident)
8547{
8548 return Dsymbol::oneMember(ps, ident);
8549}
8550
8551int TemplateMixin::apply(Dsymbol_apply_ft_t fp, void *param)
8552{
8553 if (_scope) // if fwd reference
8554 semantic(NULL); // try to resolve it
8555 if (members)
8556 {
2cbc99d1 8557 for (size_t i = 0; i < members->length; i++)
b4c522fa
IB
8558 {
8559 Dsymbol *s = (*members)[i];
8560 if (s)
8561 {
8562 if (s->apply(fp, param))
8563 return 1;
8564 }
8565 }
8566 }
8567 return 0;
8568}
8569
8570bool TemplateMixin::hasPointers()
8571{
8572 //printf("TemplateMixin::hasPointers() %s\n", toChars());
8573
8574 if (members)
8575 {
2cbc99d1 8576 for (size_t i = 0; i < members->length; i++)
b4c522fa
IB
8577 {
8578 Dsymbol *s = (*members)[i];
8579 //printf(" s = %s %s\n", s->kind(), s->toChars());
8580 if (s->hasPointers())
8581 {
8582 return true;
8583 }
8584 }
8585 }
8586 return false;
8587}
8588
8589void TemplateMixin::setFieldOffset(AggregateDeclaration *ad, unsigned *poffset, bool isunion)
8590{
8591 //printf("TemplateMixin::setFieldOffset() %s\n", toChars());
8592 if (_scope) // if fwd reference
8593 semantic(NULL); // try to resolve it
8594 if (members)
8595 {
2cbc99d1 8596 for (size_t i = 0; i < members->length; i++)
b4c522fa
IB
8597 {
8598 Dsymbol *s = (*members)[i];
8599 //printf("\t%s\n", s->toChars());
8600 s->setFieldOffset(ad, poffset, isunion);
8601 }
8602 }
8603}
8604
8605const char *TemplateMixin::toChars()
8606{
8607 OutBuffer buf;
8608 toCBufferInstance(this, &buf);
fced594b 8609 return buf.extractChars();
b4c522fa 8610}