2 /* Compiler implementation of the D programming language
3 * Copyright (C) 1999-2018 by The D Language Foundation, All Rights Reserved
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
11 // Handle template implementation
13 #include "root/dsystem.h"
14 #include "root/root.h"
16 #include "root/rmem.h"
17 #include "root/stringtable.h"
18 #include "root/hash.h"
24 #include "expression.h"
27 #include "aggregate.h"
28 #include "declaration.h"
32 #include "identifier.h"
38 #define IDX_NOTFOUND (0x12345678) // index is not found
40 Type
*rawTypeMerge(Type
*t1
, Type
*t2
);
41 bool MODimplicitConv(MOD modfrom
, MOD modto
);
42 MATCH
MODmethodConv(MOD modfrom
, MOD modto
);
43 MOD
MODmerge(MOD mod1
, MOD mod2
);
45 static size_t templateParameterLookup(Type
*tparam
, TemplateParameters
*parameters
);
46 static int arrayObjectMatch(Objects
*oa1
, Objects
*oa2
);
47 static unsigned char deduceWildHelper(Type
*t
, Type
**at
, Type
*tparam
);
48 static MATCH
deduceTypeHelper(Type
*t
, Type
**at
, Type
*tparam
);
49 static bool reliesOnTident(Type
*t
, TemplateParameters
*tparams
= NULL
, size_t iStart
= 0);
50 Expression
*semantic(Expression
*e
, Scope
*sc
);
51 bool evalStaticCondition(Scope
*sc
, Expression
*exp
, Expression
*e
, bool &errors
);
53 /********************************************
54 * These functions substitute for dynamic_cast. dynamic_cast does not work
55 * on earlier versions of gcc.
58 Expression
*isExpression(RootObject
*o
)
60 //return dynamic_cast<Expression *>(o);
61 if (!o
|| o
->dyncast() != DYNCAST_EXPRESSION
)
63 return (Expression
*)o
;
66 Dsymbol
*isDsymbol(RootObject
*o
)
68 //return dynamic_cast<Dsymbol *>(o);
69 if (!o
|| o
->dyncast() != DYNCAST_DSYMBOL
)
74 Type
*isType(RootObject
*o
)
76 //return dynamic_cast<Type *>(o);
77 if (!o
|| o
->dyncast() != DYNCAST_TYPE
)
82 Tuple
*isTuple(RootObject
*o
)
84 //return dynamic_cast<Tuple *>(o);
85 if (!o
|| o
->dyncast() != DYNCAST_TUPLE
)
90 Parameter
*isParameter(RootObject
*o
)
92 //return dynamic_cast<Parameter *>(o);
93 if (!o
|| o
->dyncast() != DYNCAST_PARAMETER
)
95 return (Parameter
*)o
;
98 /**************************************
99 * Is this Object an error?
101 bool isError(RootObject
*o
)
105 return (t
->ty
== Terror
);
106 Expression
*e
= isExpression(o
);
108 return (e
->op
== TOKerror
|| !e
->type
|| e
->type
->ty
== Terror
);
109 Tuple
*v
= isTuple(o
);
111 return arrayObjectIsError(&v
->objects
);
112 Dsymbol
*s
= isDsymbol(o
);
116 return s
->parent
? isError(s
->parent
) : false;
119 /**************************************
120 * Are any of the Objects an error?
122 bool arrayObjectIsError(Objects
*args
)
124 for (size_t i
= 0; i
< args
->dim
; i
++)
126 RootObject
*o
= (*args
)[i
];
133 /***********************
134 * Try to get arg as a type.
137 Type
*getType(RootObject
*o
)
142 Expression
*e
= isExpression(o
);
149 Dsymbol
*getDsymbol(RootObject
*oarg
)
151 //printf("getDsymbol()\n");
152 //printf("e %p s %p t %p v %p\n", isExpression(oarg), isDsymbol(oarg), isType(oarg), isTuple(oarg));
155 Expression
*ea
= isExpression(oarg
);
158 // Try to convert Expression to symbol
159 if (ea
->op
== TOKvar
)
160 sa
= ((VarExp
*)ea
)->var
;
161 else if (ea
->op
== TOKfunction
)
163 if (((FuncExp
*)ea
)->td
)
164 sa
= ((FuncExp
*)ea
)->td
;
166 sa
= ((FuncExp
*)ea
)->fd
;
168 else if (ea
->op
== TOKtemplate
)
169 sa
= ((TemplateExp
*)ea
)->td
;
175 // Try to convert Type to symbol
176 Type
*ta
= isType(oarg
);
178 sa
= ta
->toDsymbol(NULL
);
180 sa
= isDsymbol(oarg
); // if already a symbol
185 /***********************
186 * Try to get value from manifest constant
189 static Expression
*getValue(Expression
*e
)
191 if (e
&& e
->op
== TOKvar
)
193 VarDeclaration
*v
= ((VarExp
*)e
)->var
->isVarDeclaration();
194 if (v
&& v
->storage_class
& STCmanifest
)
196 e
= v
->getConstInitializer();
202 static Expression
*getValue(Dsymbol
*&s
)
204 Expression
*e
= NULL
;
207 VarDeclaration
*v
= s
->isVarDeclaration();
208 if (v
&& v
->storage_class
& STCmanifest
)
210 e
= v
->getConstInitializer();
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).
221 bool definitelyValueParameter(Expression
*e
)
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
)
231 if (e
->op
!= TOKdotvar
)
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
240 // x.y.f cannot be a value
241 FuncDeclaration
*f
= ((DotVarExp
*)e
)->var
->isFuncDeclaration();
245 while (e
->op
== TOKdotvar
)
247 e
= ((DotVarExp
*)e
)->e1
;
249 // this.x.y and super.x.y couldn't possibly be valid values.
250 if (e
->op
== TOKthis
|| e
->op
== TOKsuper
)
253 // e.type.x could be an alias
254 if (e
->op
== TOKdottype
)
257 // var.x.y is the only other possible form of alias
261 VarDeclaration
*v
= ((VarExp
*)e
)->var
->isVarDeclaration();
263 // func.x.y is not an alias
267 // TODO: Should we force CTFE if it is a global constant?
272 static Expression
*getExpression(RootObject
*o
)
274 Dsymbol
*s
= isDsymbol(o
);
275 return s
? getValue(s
) : getValue(isExpression(o
));
278 /******************************
279 * If o1 matches o2, return true.
280 * Else, return false.
283 static bool match(RootObject
*o1
, RootObject
*o2
)
285 //printf("match() o1 = %p %s (%d), o2 = %p %s (%d)\n",
286 // o1, o1->toChars(), o1->dyncast(), o2, o2->toChars(), o2->dyncast());
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.
293 /* Manifest constants should be compared by their values,
294 * at least in template arguments.
297 if (Type
*t1
= isType(o1
))
299 Type
*t2
= isType(o2
);
303 //printf("\tt1 = %s\n", t1->toChars());
304 //printf("\tt2 = %s\n", t2->toChars());
310 if (Expression
*e1
= getExpression(o1
))
312 Expression
*e2
= getExpression(o2
);
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());
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
323 if (!e1
->type
->equals(e2
->type
) || !e1
->equals(e2
))
328 if (Dsymbol
*s1
= isDsymbol(o1
))
330 Dsymbol
*s2
= isDsymbol(o2
);
334 //printf("\ts1 = %s\n", s1->toChars());
335 //printf("\ts2 = %s\n", s2->toChars());
338 if (s1
->parent
!= s2
->parent
&& !s1
->isFuncDeclaration() && !s2
->isFuncDeclaration())
343 if (Tuple
*u1
= isTuple(o1
))
345 Tuple
*u2
= isTuple(o2
);
349 //printf("\tu1 = %s\n", u1->toChars());
350 //printf("\tu2 = %s\n", u2->toChars());
351 if (!arrayObjectMatch(&u1
->objects
, &u2
->objects
))
357 //printf("\t-> match\n");
361 //printf("\t-> nomatch\n");
366 /************************************
367 * Match an array of them.
369 int arrayObjectMatch(Objects
*oa1
, Objects
*oa2
)
373 if (oa1
->dim
!= oa2
->dim
)
375 for (size_t j
= 0; j
< oa1
->dim
; j
++)
377 RootObject
*o1
= (*oa1
)[j
];
378 RootObject
*o2
= (*oa2
)[j
];
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).
393 static hash_t
expressionHash(Expression
*e
)
398 return (size_t) ((IntegerExp
*)e
)->getInteger();
401 return CTFloat::hash(((RealExp
*)e
)->value
);
405 ComplexExp
*ce
= (ComplexExp
*)e
;
406 return mixHash(CTFloat::hash(ce
->toReal()), CTFloat::hash(ce
->toImaginary()));
410 return (size_t)(void *) ((IdentifierExp
*)e
)->ident
;
413 return (size_t)(void *) ((NullExp
*)e
)->type
;
417 StringExp
*se
= (StringExp
*)e
;
418 return calcHash((const char *)se
->string
, se
->len
* se
->sz
);
423 TupleExp
*te
= (TupleExp
*)e
;
425 hash
+= te
->e0
? expressionHash(te
->e0
) : 0;
426 for (size_t i
= 0; i
< te
->exps
->dim
; i
++)
428 Expression
*elem
= (*te
->exps
)[i
];
429 hash
= mixHash(hash
, expressionHash(elem
));
434 case TOKarrayliteral
:
436 ArrayLiteralExp
*ae
= (ArrayLiteralExp
*)e
;
438 for (size_t i
= 0; i
< ae
->elements
->dim
; i
++)
439 hash
= mixHash(hash
, expressionHash(ae
->getElement(i
)));
443 case TOKassocarrayliteral
:
445 AssocArrayLiteralExp
*ae
= (AssocArrayLiteralExp
*)e
;
447 for (size_t i
= 0; i
< ae
->keys
->dim
; i
++)
448 // reduction needs associative op as keys are unsorted (use XOR)
449 hash
^= mixHash(expressionHash((*ae
->keys
)[i
]), expressionHash((*ae
->values
)[i
]));
453 case TOKstructliteral
:
455 StructLiteralExp
*se
= (StructLiteralExp
*)e
;
457 for (size_t i
= 0; i
< se
->elements
->dim
; i
++)
459 Expression
*elem
= (*se
->elements
)[i
];
460 hash
= mixHash(hash
, elem
? expressionHash(elem
) : 0);
466 return (size_t)(void *) ((VarExp
*)e
)->var
;
469 return (size_t)(void *) ((FuncExp
*)e
)->fd
;
472 // no custom equals for this expression
473 // equals based on identity
474 return (size_t)(void *) e
;
479 /************************************
480 * Return hash of Objects.
482 static hash_t
arrayObjectHash(Objects
*oa1
)
485 for (size_t j
= 0; j
< oa1
->dim
; j
++)
487 /* Must follow the logic of match()
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
))
496 FuncAliasDeclaration
*fa1
= s1
->isFuncAliasDeclaration();
498 s1
= fa1
->toAliasFunc();
499 hash
= mixHash(hash
, mixHash((size_t)(void *)s1
->getIdent(), (size_t)(void *)s1
->parent
));
501 else if (Tuple
*u1
= isTuple(o1
))
502 hash
= mixHash(hash
, arrayObjectHash(&u1
->objects
));
507 RootObject
*objectSyntaxCopy(RootObject
*o
)
511 if (Type
*t
= isType(o
))
512 return t
->syntaxCopy();
513 if (Expression
*e
= isExpression(o
))
514 return e
->syntaxCopy();
519 /* ======================== TemplateDeclaration ============================= */
521 TemplateDeclaration::TemplateDeclaration(Loc loc
, Identifier
*id
,
522 TemplateParameters
*parameters
, Expression
*constraint
, Dsymbols
*decldefs
, bool ismixin
, bool literal
)
526 this->parameters
= parameters
;
527 this->origParameters
= parameters
;
528 this->constraint
= constraint
;
529 this->members
= decldefs
;
530 this->overnext
= NULL
;
531 this->overroot
= NULL
;
532 this->funcroot
= NULL
;
533 this->onemember
= NULL
;
534 this->literal
= literal
;
535 this->ismixin
= ismixin
;
536 this->isstatic
= true;
537 this->previous
= NULL
;
538 this->protection
= Prot(PROTundefined
);
539 this->instances
= NULL
;
541 // Compute in advance for Ddoc's use
542 // Bugzilla 11153: ident could be NULL if parsing fails.
543 if (members
&& ident
)
546 if (Dsymbol::oneMembers(members
, &s
, ident
) && s
)
554 Dsymbol
*TemplateDeclaration::syntaxCopy(Dsymbol
*)
556 //printf("TemplateDeclaration::syntaxCopy()\n");
557 TemplateParameters
*p
= NULL
;
560 p
= new TemplateParameters();
561 p
->setDim(parameters
->dim
);
562 for (size_t i
= 0; i
< p
->dim
; i
++)
563 (*p
)[i
] = (*parameters
)[i
]->syntaxCopy();
565 return new TemplateDeclaration(loc
, ident
, p
,
566 constraint
? constraint
->syntaxCopy() : NULL
,
567 Dsymbol::arraySyntaxCopy(members
), ismixin
, literal
);
570 void TemplateDeclaration::semantic(Scope
*sc
)
572 if (semanticRun
!= PASSinit
)
573 return; // semantic() already run
575 // Remember templates defined in module object that we need to know about
576 if (sc
->_module
&& sc
->_module
->ident
== Id::object
)
578 if (ident
== Id::RTInfo
)
582 /* Remember Scope for later instantiations, but make
583 * a copy since attributes can change.
587 this->_scope
= sc
->copy();
588 this->_scope
->setNoFree();
591 semanticRun
= PASSsemantic
;
594 protection
= sc
->protection
;
595 isstatic
= toParent()->isModule() || (_scope
->stc
& STCstatic
);
599 if (AggregateDeclaration
*ad
= parent
->pastMixin()->isAggregateDeclaration())
603 // Set up scope for parameters
604 ScopeDsymbol
*paramsym
= new ScopeDsymbol();
605 paramsym
->parent
= parent
;
606 Scope
*paramscope
= sc
->push(paramsym
);
609 if (global
.params
.doDocComments
)
611 origParameters
= new TemplateParameters();
612 origParameters
->setDim(parameters
->dim
);
613 for (size_t i
= 0; i
< parameters
->dim
; i
++)
615 TemplateParameter
*tp
= (*parameters
)[i
];
616 (*origParameters
)[i
] = tp
->syntaxCopy();
620 for (size_t i
= 0; i
< parameters
->dim
; i
++)
622 TemplateParameter
*tp
= (*parameters
)[i
];
624 if (!tp
->declareParameter(paramscope
))
626 error(tp
->loc
, "parameter '%s' multiply defined", tp
->ident
->toChars());
629 if (!tp
->semantic(paramscope
, parameters
))
633 if (i
+ 1 != parameters
->dim
&& tp
->isTemplateTupleParameter())
635 error("template tuple parameter must be last one");
640 /* Calculate TemplateParameter::dependent
642 TemplateParameters tparams
;
644 for (size_t i
= 0; i
< parameters
->dim
; i
++)
646 TemplateParameter
*tp
= (*parameters
)[i
];
649 for (size_t j
= 0; j
< parameters
->dim
; j
++)
651 // Skip cases like: X(T : T)
655 if (TemplateTypeParameter
*ttp
= (*parameters
)[j
]->isTemplateTypeParameter())
657 if (reliesOnTident(ttp
->specType
, &tparams
))
658 tp
->dependent
= true;
660 else if (TemplateAliasParameter
*tap
= (*parameters
)[j
]->isTemplateAliasParameter())
662 if (reliesOnTident(tap
->specType
, &tparams
) ||
663 reliesOnTident(isType(tap
->specAlias
), &tparams
))
665 tp
->dependent
= true;
678 if (Dsymbol::oneMembers(members
, &s
, ident
) && s
)
685 /* BUG: should check:
686 * o no virtual functions or non-static data members of classes
690 const char *TemplateDeclaration::kind() const
692 return (onemember
&& onemember
->isAggregateDeclaration())
697 /**********************************
698 * Overload existing TemplateDeclaration 'this' with the new one 's'.
699 * Return true if successful; i.e. no conflict.
702 bool TemplateDeclaration::overloadInsert(Dsymbol
*s
)
704 FuncDeclaration
*fd
= s
->isFuncDeclaration();
708 return funcroot
->overloadInsert(fd
);
710 return funcroot
->overloadInsert(this);
713 TemplateDeclaration
*td
= s
->isTemplateDeclaration();
717 TemplateDeclaration
*pthis
= this;
718 TemplateDeclaration
**ptd
;
719 for (ptd
= &pthis
; *ptd
; ptd
= &(*ptd
)->overnext
)
728 /****************************
729 * Check to see if constraint is satisfied.
731 bool TemplateDeclaration::evaluateConstraint(
732 TemplateInstance
*ti
, Scope
*sc
, Scope
*paramscope
,
733 Objects
*dedargs
, FuncDeclaration
*fd
)
735 /* Detect recursive attempts to instantiate this template declaration,
737 * void foo(T)(T x) if (is(typeof(foo(x)))) { }
738 * static assert(!is(typeof(foo(7))));
739 * Recursive attempts are regarded as a constraint failure.
741 /* There's a chicken-and-egg problem here. We don't know yet if this template
742 * instantiation will be a local one (enclosing is set), and we won't know until
743 * after selecting the correct template. Thus, function we're nesting inside
744 * is not on the sc scope chain, and this can cause errors in FuncDeclaration::getLevel().
745 * Workaround the problem by setting a flag to relax the checking on frame errors.
748 for (TemplatePrevious
*p
= previous
; p
; p
= p
->prev
)
750 if (arrayObjectMatch(p
->dedargs
, dedargs
))
752 //printf("recursive, no match p->sc=%p %p %s\n", p->sc, this, this->toChars());
753 /* It must be a subscope of p->sc, other scope chains are not recursive
756 for (Scope
*scx
= sc
; scx
; scx
= scx
->enclosing
)
762 /* BUG: should also check for ref param differences
769 pr
.dedargs
= dedargs
;
770 previous
= &pr
; // add this to threaded list
772 Scope
*scx
= paramscope
->push(ti
);
780 /* Declare all the function parameters as variables and add them to the scope
781 * Making parameters is similar to FuncDeclaration::semantic3
783 TypeFunction
*tf
= (TypeFunction
*)fd
->type
;
784 assert(tf
->ty
== Tfunction
);
788 Parameters
*fparameters
= tf
->parameters
;
789 int fvarargs
= tf
->varargs
;
791 size_t nfparams
= Parameter::dim(fparameters
);
792 for (size_t i
= 0; i
< nfparams
; i
++)
794 Parameter
*fparam
= Parameter::getNth(fparameters
, i
);
795 fparam
->storageClass
&= (STCin
| STCout
| STCref
| STClazy
| STCfinal
| STC_TYPECTOR
| STCnodtor
);
796 fparam
->storageClass
|= STCparameter
;
797 if (fvarargs
== 2 && i
+ 1 == nfparams
)
798 fparam
->storageClass
|= STCvariadic
;
800 for (size_t i
= 0; i
< fparameters
->dim
; i
++)
802 Parameter
*fparam
= (*fparameters
)[i
];
804 continue; // don't add it, if it has no name
805 VarDeclaration
*v
= new VarDeclaration(loc
, fparam
->type
, fparam
->ident
, NULL
);
806 v
->storage_class
= fparam
->storageClass
;
809 ti
->symtab
= new DsymbolTable();
811 error("parameter %s.%s is already defined", toChars(), v
->toChars());
816 fd
->storage_class
|= STCstatic
;
818 fd
->vthis
= fd
->declareThis(scx
, fd
->isThis());
821 Expression
*e
= constraint
->syntaxCopy();
823 assert(ti
->inst
== NULL
);
824 ti
->inst
= ti
; // temporary instantiation to enable genIdent()
826 scx
->flags
|= SCOPEconstraint
;
828 bool result
= evalStaticCondition(scx
, constraint
, e
, errors
);
832 previous
= pr
.prev
; // unlink from threaded list
838 /***************************************
839 * Given that ti is an instance of this TemplateDeclaration,
840 * deduce the types of the parameters to this, and store
841 * those deduced types in dedtypes[].
843 * flag 1: don't do semantic() because of dummy types
844 * 2: don't change types in matchArg()
846 * dedtypes deduced arguments
847 * Return match level.
850 MATCH
TemplateDeclaration::matchWithInstance(Scope
*sc
, TemplateInstance
*ti
,
851 Objects
*dedtypes
, Expressions
*fargs
, int flag
)
854 size_t dedtypes_dim
= dedtypes
->dim
;
861 size_t parameters_dim
= parameters
->dim
;
862 int variadic
= isVariadic() != NULL
;
864 // If more arguments than parameters, no match
865 if (ti
->tiargs
->dim
> parameters_dim
&& !variadic
)
870 assert(dedtypes_dim
== parameters_dim
);
871 assert(dedtypes_dim
>= ti
->tiargs
->dim
|| variadic
);
875 // Set up scope for template parameters
876 ScopeDsymbol
*paramsym
= new ScopeDsymbol();
877 paramsym
->parent
= _scope
->parent
;
878 Scope
*paramscope
= _scope
->push(paramsym
);
879 paramscope
->tinst
= ti
;
880 paramscope
->minst
= sc
->minst
;
881 paramscope
->callsc
= sc
;
884 // Attempt type deduction
886 for (size_t i
= 0; i
< dedtypes_dim
; i
++)
889 TemplateParameter
*tp
= (*parameters
)[i
];
892 //printf("\targument [%d]\n", i);
893 m2
= tp
->matchArg(ti
->loc
, paramscope
, ti
->tiargs
, i
, parameters
, dedtypes
, &sparam
);
894 //printf("\tm2 = %d\n", m2);
896 if (m2
== MATCHnomatch
)
905 sparam
->semantic(paramscope
);
906 if (!paramscope
->insert(sparam
)) // TODO: This check can make more early
907 goto Lnomatch
; // in TemplateDeclaration::semantic, and
908 // then we don't need to make sparam if flags == 0
913 /* Any parameter left without a type gets the type of
914 * its corresponding arg
916 for (size_t i
= 0; i
< dedtypes_dim
; i
++)
920 assert(i
< ti
->tiargs
->dim
);
921 (*dedtypes
)[i
] = (Type
*)(*ti
->tiargs
)[i
];
926 if (m
> MATCHnomatch
&& constraint
&& !flag
)
928 if (ti
->hasNestedArgs(ti
->tiargs
, this->isstatic
)) // TODO: should gag error
929 ti
->parent
= ti
->enclosing
;
931 ti
->parent
= this->parent
;
933 // Similar to doHeaderInstantiation
934 FuncDeclaration
*fd
= onemember
? onemember
->isFuncDeclaration() : NULL
;
937 assert(fd
->type
->ty
== Tfunction
);
938 TypeFunction
*tf
= (TypeFunction
*)fd
->type
->syntaxCopy();
940 fd
= new FuncDeclaration(fd
->loc
, fd
->endloc
, fd
->ident
, fd
->storage_class
, tf
);
942 fd
->inferRetType
= true;
944 // Shouldn't run semantic on default arguments and return type.
945 for (size_t i
= 0; i
< tf
->parameters
->dim
; i
++)
946 (*tf
->parameters
)[i
]->defaultArg
= NULL
;
949 // Resolve parameter types and 'auto ref's.
951 unsigned olderrors
= global
.startGagging();
952 fd
->type
= tf
->semantic(loc
, paramscope
);
953 if (global
.endGagging(olderrors
))
955 assert(fd
->type
->ty
!= Tfunction
);
958 assert(fd
->type
->ty
== Tfunction
);
959 fd
->originalType
= fd
->type
; // for mangling
962 // TODO: dedtypes => ti->tiargs ?
963 if (!evaluateConstraint(ti
, sc
, paramscope
, dedtypes
, fd
))
977 /********************************************
978 * Determine partial specialization order of 'this' vs td2.
980 * match this is at least as specialized as td2
981 * 0 td2 is more specialized than this
984 MATCH
TemplateDeclaration::leastAsSpecialized(Scope
*sc
, TemplateDeclaration
*td2
, Expressions
*fargs
)
986 /* This works by taking the template parameters to this template
987 * declaration and feeding them to td2 as if it were a template
989 * If it works, then this template is at least as specialized
993 TemplateInstance
ti(Loc(), ident
); // create dummy template instance
994 // Set type arguments to dummy template instance to be types
995 // generated from the parameters to this template declaration
996 ti
.tiargs
= new Objects();
997 ti
.tiargs
->reserve(parameters
->dim
);
998 for (size_t i
= 0; i
< parameters
->dim
; i
++)
1000 TemplateParameter
*tp
= (*parameters
)[i
];
1003 RootObject
*p
= (RootObject
*)tp
->dummyArg();
1010 // Temporary Array to hold deduced types
1012 dedtypes
.setDim(td2
->parameters
->dim
);
1014 // Attempt a type deduction
1015 MATCH m
= td2
->matchWithInstance(sc
, &ti
, &dedtypes
, fargs
, 1);
1016 if (m
> MATCHnomatch
)
1018 /* A non-variadic template is more specialized than a
1021 TemplateTupleParameter
*tp
= isVariadic();
1022 if (tp
&& !tp
->dependent
&& !td2
->isVariadic())
1028 return MATCHnomatch
;
1031 static Expression
*emptyArrayElement
= NULL
;
1033 class TypeDeduced
: public Type
1037 Expressions argexps
; // corresponding expressions
1038 Types tparams
; // tparams[i]->mod
1040 TypeDeduced(Type
*tt
, Expression
*e
, Type
*tparam
)
1045 tparams
.push(tparam
);
1048 virtual ~TypeDeduced()
1052 void update(Expression
*e
, Type
*tparam
)
1055 tparams
.push(tparam
);
1057 void update(Type
*tt
, Expression
*e
, Type
*tparam
)
1061 tparams
.push(tparam
);
1063 MATCH
matchAll(Type
*tt
)
1065 MATCH match
= MATCHexact
;
1066 for (size_t j
= 0; j
< argexps
.dim
; j
++)
1068 Expression
*e
= argexps
[j
];
1070 if (e
== emptyArrayElement
)
1073 Type
*t
= tt
->addMod(tparams
[j
]->mod
)->substWildTo(MODconst
);
1075 MATCH m
= e
->implicitConvTo(t
);
1078 if (match
<= MATCHnomatch
)
1085 /*************************************************
1086 * Match function arguments against a specific template function.
1089 * sc instantiation scope
1091 * tthis 'this' argument if !NULL
1092 * fargs arguments to function
1094 * fd Partially instantiated function declaration
1095 * ti->tdtypes Expression/Type deduced template arguments
1098 * bit 0-3 Match template parameters by inferred template arguments
1099 * bit 4-7 Match template parameters by initial template arguments
1102 MATCH
TemplateDeclaration::deduceFunctionTemplateMatch(
1103 TemplateInstance
*ti
, Scope
*sc
,
1104 FuncDeclaration
*&fd
, Type
*tthis
, Expressions
*fargs
)
1108 size_t ntargs
; // array size of tiargs
1109 size_t fptupindex
= IDX_NOTFOUND
;
1110 MATCH match
= MATCHexact
;
1111 MATCH matchTiargs
= MATCHexact
;
1112 Parameters
*fparameters
; // function parameter list
1113 int fvarargs
; // function varargs
1114 unsigned wildmatch
= 0;
1115 size_t inferStart
= 0;
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
1124 dedargs
->setDim(parameters
->dim
);
1127 dedtypes
->setDim(parameters
->dim
);
1130 if (errors
|| fd
->errors
)
1131 return MATCHnomatch
;
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;
1142 TemplateTupleParameter
*tp
= isVariadic();
1143 Tuple
*declaredTuple
= NULL
;
1148 // Set initial template arguments
1149 ntargs
= tiargs
->dim
;
1150 size_t n
= parameters
->dim
;
1158 /* The extra initial template arguments
1159 * now form the tuple argument.
1161 Tuple
*t
= new Tuple();
1162 assert(parameters
->dim
);
1163 (*dedargs
)[parameters
->dim
- 1] = t
;
1165 t
->objects
.setDim(ntargs
- n
);
1166 for (size_t i
= 0; i
< t
->objects
.dim
; i
++)
1168 t
->objects
[i
] = (*tiargs
)[n
+ i
];
1170 declareParameter(paramscope
, tp
, t
);
1176 memcpy(dedargs
->tdata(), tiargs
->tdata(), n
* sizeof(*dedargs
->tdata()));
1178 for (size_t i
= 0; i
< n
; i
++)
1180 assert(i
< parameters
->dim
);
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
)
1186 if (m
< matchTiargs
)
1189 sparam
->semantic(paramscope
);
1190 if (!paramscope
->insert(sparam
))
1193 if (n
< parameters
->dim
&& !declaredTuple
)
1198 inferStart
= parameters
->dim
;
1199 //printf("tiargs matchTiargs = %d\n", matchTiargs);
1202 fparameters
= fd
->getParameters(&fvarargs
);
1203 nfparams
= Parameter::dim(fparameters
); // number of function parameters
1204 nfargs
= fargs
? fargs
->dim
: 0; // number of function arguments
1206 /* Check for match of function arguments with variadic template
1207 * parameter, such as:
1209 * void foo(T, A...)(T t, A a);
1210 * void main() { foo(1,2,3); }
1212 if (tp
) // if variadic
1214 // TemplateTupleParameter always makes most lesser matching.
1215 matchTiargs
= MATCHconvert
;
1217 if (nfparams
== 0 && nfargs
!= 0) // if no function parameters
1221 Tuple
*t
= new Tuple();
1222 //printf("t = %p\n", t);
1223 (*dedargs
)[parameters
->dim
- 1] = t
;
1224 declareParameter(paramscope
, tp
, t
);
1230 /* Figure out which of the function parameters matches
1231 * the tuple template parameter. Do this by matching
1233 * Set the index of this function parameter to fptupindex.
1235 for (fptupindex
= 0; fptupindex
< nfparams
; fptupindex
++)
1237 Parameter
*fparam
= (*fparameters
)[fptupindex
];
1238 if (fparam
->type
->ty
!= Tident
)
1240 TypeIdentifier
*tid
= (TypeIdentifier
*)fparam
->type
;
1241 if (!tp
->ident
->equals(tid
->ident
) || tid
->idents
.dim
)
1244 if (fvarargs
) // variadic function doesn't
1245 goto Lnomatch
; // go with variadic template
1249 fptupindex
= IDX_NOTFOUND
;
1255 if (toParent()->isModule() || (_scope
->stc
& STCstatic
))
1259 bool hasttp
= false;
1261 // Match 'tthis' to any TemplateThisParameter's
1262 for (size_t i
= 0; i
< parameters
->dim
; i
++)
1264 TemplateThisParameter
*ttp
= (*parameters
)[i
]->isTemplateThisParameter();
1269 Type
*t
= new TypeIdentifier(Loc(), ttp
->ident
);
1270 MATCH m
= deduceType(tthis
, paramscope
, t
, parameters
, dedtypes
);
1271 if (m
<= MATCHnomatch
)
1274 match
= m
; // pick worst match
1278 // Match attributes of tthis against attributes of fd
1279 if (fd
->type
&& !fd
->isCtorDeclaration())
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())
1286 AggregateDeclaration
*ad
= p
->isAggregateDeclaration();
1288 stc
|= ad
->storage_class
;
1290 unsigned char mod
= fd
->type
->mod
;
1291 if (stc
& STCimmutable
)
1295 if (stc
& (STCshared
| STCsynchronized
))
1303 unsigned char thismod
= tthis
->mod
;
1305 mod
= MODmerge(thismod
, mod
);
1306 MATCH m
= MODmethodConv(thismod
, mod
);
1307 if (m
<= MATCHnomatch
)
1314 // Loop through the function parameters
1316 //printf("%s\n\tnfargs = %d, nfparams = %d, tuple_dim = %d\n", toChars(), nfargs, nfparams, declaredTuple ? declaredTuple->objects.dim : 0);
1317 //printf("\ttp = %p, fptupindex = %d, found = %d, declaredTuple = %s\n", tp, fptupindex, fptupindex != IDX_NOTFOUND, declaredTuple ? declaredTuple->toChars() : NULL);
1319 size_t nfargs2
= nfargs
; // nfargs + supplied defaultArgs
1320 for (size_t parami
= 0; parami
< nfparams
; parami
++)
1322 Parameter
*fparam
= Parameter::getNth(fparameters
, parami
);
1324 // Apply function parameter storage classes to parameter types
1325 Type
*prmtype
= fparam
->type
->addStorageClass(fparam
->storageClass
);
1329 /* See function parameters which wound up
1330 * as part of a template tuple parameter.
1332 if (fptupindex
!= IDX_NOTFOUND
&& parami
== fptupindex
)
1334 assert(prmtype
->ty
== Tident
);
1335 TypeIdentifier
*tid
= (TypeIdentifier
*)prmtype
;
1338 /* The types of the function arguments
1339 * now form the tuple argument.
1341 declaredTuple
= new Tuple();
1342 (*dedargs
)[parameters
->dim
- 1] = declaredTuple
;
1344 /* Count function parameters following a tuple parameter.
1345 * void foo(U, T...)(int y, T, U, int) {} // rem == 2 (U, int)
1348 for (size_t j
= parami
+ 1; j
< nfparams
; j
++)
1350 Parameter
*p
= Parameter::getNth(fparameters
, j
);
1351 if (!reliesOnTident(p
->type
, parameters
, inferStart
))
1353 Type
*pt
= p
->type
->syntaxCopy()->semantic(fd
->loc
, paramscope
);
1354 rem
+= pt
->ty
== Ttuple
? ((TypeTuple
*)pt
)->arguments
->dim
: 1;
1362 if (nfargs2
- argi
< rem
)
1364 declaredTuple
->objects
.setDim(nfargs2
- argi
- rem
);
1365 for (size_t i
= 0; i
< declaredTuple
->objects
.dim
; i
++)
1367 farg
= (*fargs
)[argi
+ i
];
1369 // Check invalid arguments to detect errors early.
1370 if (farg
->op
== TOKerror
|| farg
->type
->ty
== Terror
)
1373 if (!(fparam
->storageClass
& STClazy
) && farg
->type
->ty
== Tvoid
)
1378 if (unsigned char wm
= deduceWildHelper(farg
->type
, &tt
, tid
))
1385 m
= deduceTypeHelper(farg
->type
, &tt
, tid
);
1387 if (m
<= MATCHnomatch
)
1392 /* Remove top const for dynamic array types and pointer types
1394 if ((tt
->ty
== Tarray
|| tt
->ty
== Tpointer
) &&
1396 (!(fparam
->storageClass
& STCref
) ||
1397 ((fparam
->storageClass
& STCauto
) && !farg
->isLvalue())))
1399 tt
= tt
->mutableOf();
1401 declaredTuple
->objects
[i
] = tt
;
1403 declareParameter(paramscope
, tp
, declaredTuple
);
1407 // Bugzilla 6810: If declared tuple is not a type tuple,
1408 // it cannot be function parameter types.
1409 for (size_t i
= 0; i
< declaredTuple
->objects
.dim
; i
++)
1411 if (!isType(declaredTuple
->objects
[i
]))
1415 assert(declaredTuple
);
1416 argi
+= declaredTuple
->objects
.dim
;
1420 // If parameter type doesn't depend on inferred template parameters,
1421 // semantic it to get actual type.
1422 if (!reliesOnTident(prmtype
, parameters
, inferStart
))
1424 // should copy prmtype to avoid affecting semantic result
1425 prmtype
= prmtype
->syntaxCopy()->semantic(fd
->loc
, paramscope
);
1427 if (prmtype
->ty
== Ttuple
)
1429 TypeTuple
*tt
= (TypeTuple
*)prmtype
;
1430 size_t tt_dim
= tt
->arguments
->dim
;
1431 for (size_t j
= 0; j
< tt_dim
; j
++, ++argi
)
1433 Parameter
*p
= (*tt
->arguments
)[j
];
1434 if (j
== tt_dim
- 1 && fvarargs
== 2 && parami
+ 1 == nfparams
&& argi
< nfargs
)
1445 farg
= (*fargs
)[argi
];
1446 if (!farg
->implicitConvTo(p
->type
))
1453 if (argi
>= nfargs
) // if not enough arguments
1455 if (!fparam
->defaultArg
)
1458 /* Bugzilla 2803: Before the starting of type deduction from the function
1459 * default arguments, set the already deduced parameters into paramscope.
1460 * It's necessary to avoid breaking existing acceptable code. Cases:
1462 * 1. Already deduced template parameters can appear in fparam->defaultArg:
1463 * auto foo(A, B)(A a, B b = A.stringof);
1465 * // at fparam == 'B b = A.string', A is equivalent with the deduced type 'int'
1467 * 2. If prmtype depends on default-specified template parameter, the
1468 * default type should be preferred.
1469 * auto foo(N = size_t, R)(R r, N start = 0)
1471 * // at fparam `N start = 0`, N should be 'size_t' before
1472 * // the deduction result from fparam->defaultArg.
1476 for (size_t i
= 0; i
< dedtypes
->dim
; i
++)
1478 Type
*at
= isType((*dedtypes
)[i
]);
1479 if (at
&& at
->ty
== Tnone
)
1481 TypeDeduced
*xt
= (TypeDeduced
*)at
;
1482 (*dedtypes
)[i
] = xt
->tded
; // 'unbox'
1486 for (size_t i
= ntargs
; i
< dedargs
->dim
; i
++)
1488 TemplateParameter
*tparam
= (*parameters
)[i
];
1490 RootObject
*oarg
= (*dedargs
)[i
];
1491 RootObject
*oded
= (*dedtypes
)[i
];
1496 if (tparam
->specialization() || !tparam
->isTemplateTypeParameter())
1498 /* The specialization can work as long as afterwards
1501 (*dedargs
)[i
] = oded
;
1502 MATCH m2
= tparam
->matchArg(instLoc
, paramscope
, dedargs
, i
, parameters
, dedtypes
, NULL
);
1503 //printf("m2 = %d\n", m2);
1504 if (m2
<= MATCHnomatch
)
1506 if (m2
< matchTiargs
)
1507 matchTiargs
= m2
; // pick worst match
1508 if (!(*dedtypes
)[i
]->equals(oded
))
1509 error("specialization not allowed for deduced parameter %s", tparam
->ident
->toChars());
1513 if (MATCHconvert
< matchTiargs
)
1514 matchTiargs
= MATCHconvert
;
1516 (*dedargs
)[i
] = declareParameter(paramscope
, tparam
, oded
);
1520 oded
= tparam
->defaultArg(instLoc
, paramscope
);
1522 (*dedargs
)[i
] = declareParameter(paramscope
, tparam
, oded
);
1529 /* If prmtype does not depend on any template parameters:
1531 * auto foo(T)(T v, double x = 0);
1533 * // at fparam == 'double x = 0'
1535 * or, if all template parameters in the prmtype are already deduced:
1537 * auto foo(R)(R range, ElementType!R sum = 0);
1539 * // at fparam == 'ElementType!R sum = 0'
1541 * Deducing prmtype from fparam->defaultArg is not necessary.
1543 if (prmtype
->deco
||
1544 prmtype
->syntaxCopy()->trySemantic(loc
, paramscope
))
1550 // Deduce prmtype from the defaultArg.
1551 farg
= fparam
->defaultArg
->syntaxCopy();
1552 farg
= ::semantic(farg
, paramscope
);
1553 farg
= resolveProperties(paramscope
, farg
);
1557 farg
= (*fargs
)[argi
];
1560 // Check invalid arguments to detect errors early.
1561 if (farg
->op
== TOKerror
|| farg
->type
->ty
== Terror
)
1566 Type
*argtype
= farg
->type
;
1568 if (!(fparam
->storageClass
& STClazy
) && argtype
->ty
== Tvoid
&& farg
->op
!= TOKfunction
)
1571 // Bugzilla 12876: optimize arugument to allow CT-known length matching
1572 farg
= farg
->optimize(WANTvalue
, (fparam
->storageClass
& (STCref
| STCout
)) != 0);
1573 //printf("farg = %s %s\n", farg->type->toChars(), farg->toChars());
1575 RootObject
*oarg
= farg
;
1576 if ((fparam
->storageClass
& STCref
) &&
1577 (!(fparam
->storageClass
& STCauto
) || farg
->isLvalue()))
1579 /* Allow expressions that have CT-known boundaries and type [] to match with [dim]
1582 if (argtype
->ty
== Tarray
&&
1583 (prmtype
->ty
== Tsarray
||
1584 (prmtype
->ty
== Taarray
&& (taai
= ((TypeAArray
*)prmtype
)->index
)->ty
== Tident
&&
1585 ((TypeIdentifier
*)taai
)->idents
.dim
== 0)))
1587 if (farg
->op
== TOKstring
)
1589 StringExp
*se
= (StringExp
*)farg
;
1590 argtype
= se
->type
->nextOf()->sarrayOf(se
->len
);
1592 else if (farg
->op
== TOKarrayliteral
)
1594 ArrayLiteralExp
*ae
= (ArrayLiteralExp
*)farg
;
1595 argtype
= ae
->type
->nextOf()->sarrayOf(ae
->elements
->dim
);
1597 else if (farg
->op
== TOKslice
)
1599 SliceExp
*se
= (SliceExp
*)farg
;
1600 if (Type
*tsa
= toStaticArrayType(se
))
1607 else if ((fparam
->storageClass
& STCout
) == 0 &&
1608 (argtype
->ty
== Tarray
|| argtype
->ty
== Tpointer
) &&
1609 templateParameterLookup(prmtype
, parameters
) != IDX_NOTFOUND
&&
1610 ((TypeIdentifier
*)prmtype
)->idents
.dim
== 0)
1612 /* The farg passing to the prmtype always make a copy. Therefore,
1613 * we can shrink the set of the deduced type arguments for prmtype
1614 * by adjusting top-qualifier of the argtype.
1616 * prmtype argtype ta
1617 * T <- const(E)[] const(E)[]
1618 * T <- const(E[]) const(E)[]
1619 * qualifier(T) <- const(E)[] const(E[])
1620 * qualifier(T) <- const(E[]) const(E[])
1622 Type
*ta
= argtype
->castMod(prmtype
->mod
? argtype
->nextOf()->mod
: 0);
1625 Expression
*ea
= farg
->copy();
1631 if (fvarargs
== 2 && parami
+ 1 == nfparams
&& argi
+ 1 < nfargs
)
1635 MATCH m
= deduceType(oarg
, paramscope
, prmtype
, parameters
, dedtypes
, &wm
, inferStart
);
1636 //printf("\tL%d deduceType m = %d, wm = x%x, wildmatch = x%x\n", __LINE__, m, wm, wildmatch);
1639 /* If no match, see if the argument can be matched by using
1640 * implicit conversions.
1642 if (m
== MATCHnomatch
&& prmtype
->deco
)
1643 m
= farg
->implicitConvTo(prmtype
);
1645 if (m
== MATCHnomatch
)
1647 AggregateDeclaration
*ad
= isAggregate(farg
->type
);
1648 if (ad
&& ad
->aliasthis
&& argtype
!= att
)
1650 if (!att
&& argtype
->checkAliasThisRec()) // Bugzilla 12537
1653 /* If a semantic error occurs while doing alias this,
1654 * eg purity(bug 7295), just regard it as not a match.
1656 if (Expression
*e
= resolveAliasThis(sc
, farg
, true))
1664 if (m
> MATCHnomatch
&& (fparam
->storageClass
& (STCref
| STCauto
)) == STCref
)
1666 if (!farg
->isLvalue())
1668 if ((farg
->op
== TOKstring
|| farg
->op
== TOKslice
) &&
1669 (prmtype
->ty
== Tsarray
|| prmtype
->ty
== Taarray
))
1671 // Allow conversion from T[lwr .. upr] to ref T[upr-lwr]
1677 if (m
> MATCHnomatch
&& (fparam
->storageClass
& STCout
))
1679 if (!farg
->isLvalue())
1681 if (!farg
->type
->isMutable()) // Bugzilla 11916
1684 if (m
== MATCHnomatch
&& (fparam
->storageClass
& STClazy
) && prmtype
->ty
== Tvoid
&&
1685 farg
->type
->ty
!= Tvoid
)
1688 if (m
!= MATCHnomatch
)
1691 match
= m
; // pick worst match
1698 /* The following code for variadic arguments closely
1699 * matches TypeFunction::callMatch()
1701 if (!(fvarargs
== 2 && parami
+ 1 == nfparams
))
1704 /* Check for match with function parameter T...
1706 Type
*tb
= prmtype
->toBasetype();
1709 // 6764 fix - TypeAArray may be TypeSArray have not yet run semantic().
1712 // Perhaps we can do better with this, see TypeFunction::callMatch()
1713 if (tb
->ty
== Tsarray
)
1715 TypeSArray
*tsa
= (TypeSArray
*)tb
;
1716 dinteger_t sz
= tsa
->dim
->toInteger();
1717 if (sz
!= nfargs
- argi
)
1720 else if (tb
->ty
== Taarray
)
1722 TypeAArray
*taa
= (TypeAArray
*)tb
;
1723 Expression
*dim
= new IntegerExp(instLoc
, nfargs
- argi
, Type::tsize_t
);
1725 size_t i
= templateParameterLookup(taa
->index
, parameters
);
1726 if (i
== IDX_NOTFOUND
)
1733 unsigned errors
= global
.startGagging();
1734 /* ref: https://issues.dlang.org/show_bug.cgi?id=11118
1735 * The parameter isn't part of the template
1736 * ones, let's try to find it in the
1737 * instantiation scope 'sc' and the one
1738 * belonging to the template itself. */
1740 taa
->index
->resolve(instLoc
, sco
, &e
, &t
, &s
);
1744 taa
->index
->resolve(instLoc
, sco
, &e
, &t
, &s
);
1746 global
.endGagging(errors
);
1753 e
= e
->ctfeInterpret();
1754 e
= e
->implicitCastTo(sco
, Type::tsize_t
);
1755 e
= e
->optimize(WANTvalue
);
1756 if (!dim
->equals(e
))
1761 // This code matches code in TypeInstance::deduceType()
1762 TemplateParameter
*tprm
= (*parameters
)[i
];
1763 TemplateValueParameter
*tvp
= tprm
->isTemplateValueParameter();
1766 Expression
*e
= (Expression
*)(*dedtypes
)[i
];
1769 if (!dim
->equals(e
))
1774 Type
*vt
= tvp
->valType
->semantic(Loc(), sc
);
1775 MATCH m
= (MATCH
)dim
->implicitConvTo(vt
);
1776 if (m
<= MATCHnomatch
)
1778 (*dedtypes
)[i
] = dim
;
1785 TypeArray
*ta
= (TypeArray
*)tb
;
1786 Type
*tret
= fparam
->isLazyArray();
1787 for (; argi
< nfargs
; argi
++)
1789 Expression
*arg
= (*fargs
)[argi
];
1793 /* If lazy array of delegates,
1794 * convert arg(s) to delegate(s)
1798 if (ta
->next
->equals(arg
->type
))
1804 m
= arg
->implicitConvTo(tret
);
1805 if (m
== MATCHnomatch
)
1807 if (tret
->toBasetype()->ty
== Tvoid
)
1815 m
= deduceType(arg
, paramscope
, ta
->next
, parameters
, dedtypes
, &wm
, inferStart
);
1818 if (m
== MATCHnomatch
)
1834 //printf("-> argi = %d, nfargs = %d, nfargs2 = %d\n", argi, nfargs, nfargs2);
1835 if (argi
!= nfargs2
&& !fvarargs
)
1841 for (size_t i
= 0; i
< dedtypes
->dim
; i
++)
1843 Type
*at
= isType((*dedtypes
)[i
]);
1846 if (at
->ty
== Tnone
)
1848 TypeDeduced
*xt
= (TypeDeduced
*)at
;
1849 at
= xt
->tded
; // 'unbox'
1852 (*dedtypes
)[i
] = at
->merge2();
1855 for (size_t i
= ntargs
; i
< dedargs
->dim
; i
++)
1857 TemplateParameter
*tparam
= (*parameters
)[i
];
1858 //printf("tparam[%d] = %s\n", i, tparam->ident->toChars());
1859 /* For T:T*, the dedargs is the T*, dedtypes is the T
1860 * But for function templates, we really need them to match
1862 RootObject
*oarg
= (*dedargs
)[i
];
1863 RootObject
*oded
= (*dedtypes
)[i
];
1864 //printf("1dedargs[%d] = %p, dedtypes[%d] = %p\n", i, oarg, i, oded);
1865 //if (oarg) printf("oarg: %s\n", oarg->toChars());
1866 //if (oded) printf("oded: %s\n", oded->toChars());
1871 if (tparam
->specialization() || !tparam
->isTemplateTypeParameter())
1873 /* The specialization can work as long as afterwards
1876 (*dedargs
)[i
] = oded
;
1877 MATCH m2
= tparam
->matchArg(instLoc
, paramscope
, dedargs
, i
, parameters
, dedtypes
, NULL
);
1878 //printf("m2 = %d\n", m2);
1879 if (m2
<= MATCHnomatch
)
1881 if (m2
< matchTiargs
)
1882 matchTiargs
= m2
; // pick worst match
1883 if (!(*dedtypes
)[i
]->equals(oded
))
1884 error("specialization not allowed for deduced parameter %s", tparam
->ident
->toChars());
1888 if (MATCHconvert
< matchTiargs
)
1889 matchTiargs
= MATCHconvert
;
1894 oded
= tparam
->defaultArg(instLoc
, paramscope
);
1897 // if tuple parameter and
1898 // tuple parameter was not in function parameter list and
1899 // we're one or more arguments short (i.e. no tuple argument)
1901 fptupindex
== IDX_NOTFOUND
&&
1902 ntargs
<= dedargs
->dim
- 1)
1904 // make tuple argument an empty tuple
1905 oded
= (RootObject
*)new Tuple();
1914 /* At the template parameter T, the picked default template argument
1915 * X!int should be matched to T in order to deduce dependent
1916 * template parameter A.
1917 * auto foo(T : X!A = X!int, A...)() { ... }
1918 * foo(); // T <-- X!int, A <-- (int)
1920 if (tparam
->specialization())
1922 (*dedargs
)[i
] = oded
;
1923 MATCH m2
= tparam
->matchArg(instLoc
, paramscope
, dedargs
, i
, parameters
, dedtypes
, NULL
);
1924 //printf("m2 = %d\n", m2);
1925 if (m2
<= MATCHnomatch
)
1927 if (m2
< matchTiargs
)
1928 matchTiargs
= m2
; // pick worst match
1929 if (!(*dedtypes
)[i
]->equals(oded
))
1930 error("specialization not allowed for deduced parameter %s", tparam
->ident
->toChars());
1933 oded
= declareParameter(paramscope
, tparam
, oded
);
1934 (*dedargs
)[i
] = oded
;
1938 /* Bugzilla 7469: As same as the code for 7469 in findBestMatch,
1939 * expand a Tuple in dedargs to normalize template arguments.
1941 if (size_t d
= dedargs
->dim
)
1943 if (Tuple
*va
= isTuple((*dedargs
)[d
- 1]))
1945 if (va
->objects
.dim
)
1947 dedargs
->setDim(d
- 1);
1948 dedargs
->insert(d
- 1, &va
->objects
);
1952 ti
->tiargs
= dedargs
; // update to the normalized template arguments.
1954 // Partially instantiate function for constraint and fd->leastAsSpecialized()
1957 Scope
*sc2
= _scope
;
1958 sc2
= sc2
->push(paramsym
);
1959 sc2
= sc2
->push(ti
);
1962 sc2
->minst
= sc
->minst
;
1964 fd
= doHeaderInstantiation(ti
, sc2
, fd
, tthis
, fargs
);
1975 if (!evaluateConstraint(ti
, sc
, paramscope
, dedargs
, fd
))
1980 //printf("\tmatch %d\n", match);
1981 return (MATCH
)(match
| (matchTiargs
<<4));
1985 //printf("\tnomatch\n");
1986 return MATCHnomatch
;
1988 Lerror
: // todo: for the future improvement
1990 //printf("\terror\n");
1991 return MATCHnomatch
;
1994 /**************************************************
1995 * Declare template parameter tp with value o, and install it in the scope sc.
1998 RootObject
*TemplateDeclaration::declareParameter(Scope
*sc
, TemplateParameter
*tp
, RootObject
*o
)
2000 //printf("TemplateDeclaration::declareParameter('%s', o = %p)\n", tp->ident->toChars(), o);
2002 Type
*ta
= isType(o
);
2003 Expression
*ea
= isExpression(o
);
2004 Dsymbol
*sa
= isDsymbol(o
);
2005 Tuple
*va
= isTuple(o
);
2008 VarDeclaration
*v
= NULL
;
2010 if (ea
&& ea
->op
== TOKtype
)
2012 else if (ea
&& ea
->op
== TOKscope
)
2013 sa
= ((ScopeExp
*)ea
)->sds
;
2014 else if (ea
&& (ea
->op
== TOKthis
|| ea
->op
== TOKsuper
))
2015 sa
= ((ThisExp
*)ea
)->var
;
2016 else if (ea
&& ea
->op
== TOKfunction
)
2018 if (((FuncExp
*)ea
)->td
)
2019 sa
= ((FuncExp
*)ea
)->td
;
2021 sa
= ((FuncExp
*)ea
)->fd
;
2026 //printf("type %s\n", ta->toChars());
2027 d
= new AliasDeclaration(Loc(), tp
->ident
, ta
);
2031 //printf("Alias %s %s;\n", sa->ident->toChars(), tp->ident->toChars());
2032 d
= new AliasDeclaration(Loc(), tp
->ident
, sa
);
2036 // tdtypes.data[i] always matches ea here
2037 Initializer
*init
= new ExpInitializer(loc
, ea
);
2038 TemplateValueParameter
*tvp
= tp
->isTemplateValueParameter();
2040 Type
*t
= tvp
? tvp
->valType
: NULL
;
2042 v
= new VarDeclaration(loc
, t
, tp
->ident
, init
);
2043 v
->storage_class
= STCmanifest
| STCtemplateparameter
;
2048 //printf("\ttuple\n");
2049 d
= new TupleDeclaration(loc
, tp
->ident
, &va
->objects
);
2056 d
->storage_class
|= STCtemplateparameter
;
2060 // consistent with Type::checkDeprecated()
2061 while (t
->ty
!= Tenum
)
2063 if (!t
->nextOf()) break;
2064 t
= ((TypeNext
*)t
)->next
;
2066 if (Dsymbol
*s
= t
->toDsymbol(sc
))
2068 if (s
->isDeprecated())
2069 d
->storage_class
|= STCdeprecated
;
2074 if (sa
->isDeprecated())
2075 d
->storage_class
|= STCdeprecated
;
2079 error("declaration %s is already defined", tp
->ident
->toChars());
2082 /* So the caller's o gets updated with the result of semantic() being run on o
2085 o
= initializerToExpression(v
->_init
);
2089 /**************************************
2090 * Determine if TemplateDeclaration is variadic.
2093 TemplateTupleParameter
*isVariadic(TemplateParameters
*parameters
)
2095 size_t dim
= parameters
->dim
;
2096 TemplateTupleParameter
*tp
= NULL
;
2099 tp
= ((*parameters
)[dim
- 1])->isTemplateTupleParameter();
2103 TemplateTupleParameter
*TemplateDeclaration::isVariadic()
2105 return ::isVariadic(parameters
);
2108 /***********************************
2109 * We can overload templates.
2112 bool TemplateDeclaration::isOverloadable()
2117 /*************************************************
2118 * Given function arguments, figure out which template function
2119 * to expand, and return matching result.
2122 * dstart the root of overloaded function templates
2123 * loc instantiation location
2124 * sc instantiation scope
2125 * tiargs initial list of template arguments
2126 * tthis if !NULL, the 'this' pointer argument
2127 * fargs arguments to function
2130 void functionResolve(Match
*m
, Dsymbol
*dstart
, Loc loc
, Scope
*sc
,
2131 Objects
*tiargs
, Type
*tthis
, Expressions
*fargs
)
2143 int property
; // 0: unintialized
2144 // 1: seen @property
2147 TemplateDeclaration
*td_best
;
2148 TemplateInstance
*ti_best
;
2152 static int fp(void *param
, Dsymbol
*s
)
2156 if (FuncDeclaration
*fd
= s
->isFuncDeclaration())
2157 return ((ParamDeduce
*)param
)->applyFunction(fd
);
2158 if (TemplateDeclaration
*td
= s
->isTemplateDeclaration())
2159 return ((ParamDeduce
*)param
)->applyTemplate(td
);
2163 int applyFunction(FuncDeclaration
*fd
)
2168 // explicitly specified tiargs never match to non template function
2169 if (tiargs
&& tiargs
->dim
> 0)
2172 if (fd
->semanticRun
== PASSinit
&& fd
->_scope
)
2174 Ungag ungag
= fd
->ungagSpeculative();
2175 fd
->semantic(fd
->_scope
);
2177 if (fd
->semanticRun
== PASSinit
)
2179 ::error(loc
, "forward reference to template %s", fd
->toChars());
2182 //printf("fd = %s %s, fargs = %s\n", fd->toChars(), fd->type->toChars(), fargs->toChars());
2184 TypeFunction
*tf
= (TypeFunction
*)fd
->type
;
2186 int prop
= (tf
->isproperty
) ? 1 : 2;
2189 else if (property
!= prop
)
2190 error(fd
->loc
, "cannot overload both property and non-property functions");
2192 /* For constructors, qualifier check will be opposite direction.
2193 * Qualified constructor always makes qualified object, then will be checked
2194 * that it is implicitly convertible to tthis.
2196 Type
*tthis_fd
= fd
->needThis() ? tthis
: NULL
;
2197 bool isCtorCall
= tthis_fd
&& fd
->isCtorDeclaration();
2200 //printf("%s tf->mod = x%x tthis_fd->mod = x%x %d\n", tf->toChars(),
2201 // tf->mod, tthis_fd->mod, fd->isolateReturn());
2202 if (MODimplicitConv(tf
->mod
, tthis_fd
->mod
) ||
2203 (tf
->isWild() && tf
->isShared() == tthis_fd
->isShared()) ||
2204 fd
->isolateReturn())
2206 /* && tf->isShared() == tthis_fd->isShared()*/
2207 // Uniquely constructed object can ignore shared qualifier.
2208 // TODO: Is this appropriate?
2212 return 0; // MATCHnomatch
2214 MATCH mfa
= tf
->callMatch(tthis_fd
, fargs
);
2215 //printf("test1: mfa = %d\n", mfa);
2216 if (mfa
> MATCHnomatch
)
2218 if (mfa
> m
->last
) goto LfIsBetter
;
2219 if (mfa
< m
->last
) goto LlastIsBetter
;
2221 /* See if one of the matches overrides the other.
2224 if (m
->lastf
->overrides(fd
)) goto LlastIsBetter
;
2225 if (fd
->overrides(m
->lastf
)) goto LfIsBetter
;
2227 /* Try to disambiguate using template-style partial ordering rules.
2228 * In essence, if f() and g() are ambiguous, if f() can call g(),
2229 * but g() cannot call f(), then pick f().
2230 * This is because f() is "more specialized."
2233 MATCH c1
= fd
->leastAsSpecialized(m
->lastf
);
2234 MATCH c2
= m
->lastf
->leastAsSpecialized(fd
);
2235 //printf("c1 = %d, c2 = %d\n", c1, c2);
2236 if (c1
> c2
) goto LfIsBetter
;
2237 if (c1
< c2
) goto LlastIsBetter
;
2240 /* The 'overrides' check above does covariant checking only
2241 * for virtual member functions. It should do it for all functions,
2242 * but in order to not risk breaking code we put it after
2243 * the 'leastAsSpecialized' check.
2244 * In the future try moving it before.
2245 * I.e. a not-the-same-but-covariant match is preferred,
2246 * as it is more restrictive.
2248 if (!m
->lastf
->type
->equals(fd
->type
))
2250 //printf("cov: %d %d\n", m->lastf->type->covariant(fd->type), fd->type->covariant(m->lastf->type));
2251 if (m
->lastf
->type
->covariant(fd
->type
) == 1) goto LlastIsBetter
;
2252 if (fd
->type
->covariant(m
->lastf
->type
) == 1) goto LfIsBetter
;
2255 /* If the two functions are the same function, like:
2257 * int foo(int x) { ... }
2258 * then pick the one with the body.
2260 if (tf
->equals(m
->lastf
->type
) &&
2261 fd
->storage_class
== m
->lastf
->storage_class
&&
2262 fd
->parent
== m
->lastf
->parent
&&
2263 fd
->protection
== m
->lastf
->protection
&&
2264 fd
->linkage
== m
->lastf
->linkage
)
2266 if ( fd
->fbody
&& !m
->lastf
->fbody
) goto LfIsBetter
;
2267 if (!fd
->fbody
&& m
->lastf
->fbody
) goto LlastIsBetter
;
2270 // Bugzilla 14450: Prefer exact qualified constructor for the creating object type
2271 if (isCtorCall
&& tf
->mod
!= m
->lastf
->type
->mod
)
2273 if (tthis
->mod
== tf
->mod
) goto LfIsBetter
;
2274 if (tthis
->mod
== m
->lastf
->type
->mod
) goto LlastIsBetter
;
2287 ta_last
= MATCHexact
;
2290 tthis_best
= tthis_fd
;
2298 int applyTemplate(TemplateDeclaration
*td
)
2300 //printf("applyTemplate()\n");
2306 sc
= td
->_scope
; // workaround for Type::aliasthisOf
2308 if (td
->semanticRun
== PASSinit
&& td
->_scope
)
2310 // Try to fix forward reference. Ungag errors while doing so.
2311 Ungag ungag
= td
->ungagSpeculative();
2312 td
->semantic(td
->_scope
);
2314 if (td
->semanticRun
== PASSinit
)
2316 ::error(loc
, "forward reference to template %s", td
->toChars());
2320 m
->last
= MATCHnomatch
;
2323 //printf("td = %s\n", td->toChars());
2326 f
= td
->onemember
? td
->onemember
->isFuncDeclaration() : NULL
;
2330 tiargs
= new Objects();
2331 TemplateInstance
*ti
= new TemplateInstance(loc
, td
, tiargs
);
2333 dedtypes
.setDim(td
->parameters
->dim
);
2334 assert(td
->semanticRun
!= PASSinit
);
2335 MATCH mta
= td
->matchWithInstance(sc
, ti
, &dedtypes
, fargs
, 0);
2336 //printf("matchWithInstance = %d\n", mta);
2337 if (mta
<= MATCHnomatch
|| mta
< ta_last
) // no match or less match
2340 ti
->semantic(sc
, fargs
);
2341 if (!ti
->inst
) // if template failed to expand
2344 Dsymbol
*s
= ti
->inst
->toAlias();
2345 FuncDeclaration
*fd
;
2346 if (TemplateDeclaration
*tdx
= s
->isTemplateDeclaration())
2348 Objects dedtypesX
; // empty tiargs
2350 // Bugzilla 11553: Check for recursive instantiation of tdx.
2351 for (TemplatePrevious
*p
= tdx
->previous
; p
; p
= p
->prev
)
2353 if (arrayObjectMatch(p
->dedargs
, &dedtypesX
))
2355 //printf("recursive, no match p->sc=%p %p %s\n", p->sc, this, this->toChars());
2356 /* It must be a subscope of p->sc, other scope chains are not recursive
2359 for (Scope
*scx
= sc
; scx
; scx
= scx
->enclosing
)
2363 error(loc
, "recursive template expansion while looking for %s.%s", ti
->toChars(), tdx
->toChars());
2368 /* BUG: should also check for ref param differences
2372 TemplatePrevious pr
;
2373 pr
.prev
= tdx
->previous
;
2375 pr
.dedargs
= &dedtypesX
;
2376 tdx
->previous
= &pr
; // add this to threaded list
2378 fd
= resolveFuncCall(loc
, sc
, s
, NULL
, tthis
, fargs
, 1);
2380 tdx
->previous
= pr
.prev
; // unlink from threaded list
2382 else if (s
->isFuncDeclaration())
2384 fd
= resolveFuncCall(loc
, sc
, s
, NULL
, tthis
, fargs
, 1);
2392 if (fd
->type
->ty
!= Tfunction
)
2394 m
->lastf
= fd
; // to propagate "error match"
2396 m
->last
= MATCHnomatch
;
2400 Type
*tthis_fd
= fd
->needThis() && !fd
->isCtorDeclaration() ? tthis
: NULL
;
2402 TypeFunction
*tf
= (TypeFunction
*)fd
->type
;
2403 MATCH mfa
= tf
->callMatch(tthis_fd
, fargs
);
2407 if (mta
< ta_last
) goto Ltd_best2
;
2408 if (mta
> ta_last
) goto Ltd2
;
2410 if (mfa
< m
->last
) goto Ltd_best2
;
2411 if (mfa
> m
->last
) goto Ltd2
;
2413 //printf("Lambig2\n");
2422 // td is the new best match
2426 property
= 0; // (backward compatibility)
2430 tthis_best
= tthis_fd
;
2437 //printf("td = %s\n", td->toChars());
2438 for (size_t ovi
= 0; f
; f
= f
->overnext0
, ovi
++)
2440 if (f
->type
->ty
!= Tfunction
|| f
->errors
)
2443 /* This is a 'dummy' instance to evaluate constraint properly.
2445 TemplateInstance
*ti
= new TemplateInstance(loc
, td
, tiargs
);
2446 ti
->parent
= td
->parent
; // Maybe calculating valid 'enclosing' is unnecessary.
2448 FuncDeclaration
*fd
= f
;
2449 int x
= td
->deduceFunctionTemplateMatch(ti
, sc
, fd
, tthis
, fargs
);
2450 MATCH mta
= (MATCH
)(x
>> 4);
2451 MATCH mfa
= (MATCH
)(x
& 0xF);
2452 //printf("match:t/f = %d/%d\n", mta, mfa);
2453 if (!fd
|| mfa
== MATCHnomatch
)
2456 Type
*tthis_fd
= fd
->needThis() ? tthis
: NULL
;
2458 bool isCtorCall
= tthis_fd
&& fd
->isCtorDeclaration();
2461 // Constructor call requires additional check.
2463 TypeFunction
*tf
= (TypeFunction
*)fd
->type
;
2465 if (MODimplicitConv(tf
->mod
, tthis_fd
->mod
) ||
2466 (tf
->isWild() && tf
->isShared() == tthis_fd
->isShared()) ||
2467 fd
->isolateReturn())
2472 continue; // MATCHnomatch
2475 if (mta
< ta_last
) goto Ltd_best
;
2476 if (mta
> ta_last
) goto Ltd
;
2478 if (mfa
< m
->last
) goto Ltd_best
;
2479 if (mfa
> m
->last
) goto Ltd
;
2483 // Disambiguate by picking the most specialized TemplateDeclaration
2484 MATCH c1
= td
->leastAsSpecialized(sc
, td_best
, fargs
);
2485 MATCH c2
= td_best
->leastAsSpecialized(sc
, td
, fargs
);
2486 //printf("1: c1 = %d, c2 = %d\n", c1, c2);
2487 if (c1
> c2
) goto Ltd
;
2488 if (c1
< c2
) goto Ltd_best
;
2490 assert(fd
&& m
->lastf
);
2492 // Disambiguate by tf->callMatch
2493 TypeFunction
*tf1
= (TypeFunction
*)fd
->type
;
2494 assert(tf1
->ty
== Tfunction
);
2495 TypeFunction
*tf2
= (TypeFunction
*)m
->lastf
->type
;
2496 assert(tf2
->ty
== Tfunction
);
2497 MATCH c1
= tf1
->callMatch(tthis_fd
, fargs
);
2498 MATCH c2
= tf2
->callMatch(tthis_best
, fargs
);
2499 //printf("2: c1 = %d, c2 = %d\n", c1, c2);
2500 if (c1
> c2
) goto Ltd
;
2501 if (c1
< c2
) goto Ltd_best
;
2504 // Disambiguate by picking the most specialized FunctionDeclaration
2505 MATCH c1
= fd
->leastAsSpecialized(m
->lastf
);
2506 MATCH c2
= m
->lastf
->leastAsSpecialized(fd
);
2507 //printf("3: c1 = %d, c2 = %d\n", c1, c2);
2508 if (c1
> c2
) goto Ltd
;
2509 if (c1
< c2
) goto Ltd_best
;
2512 // Bugzilla 14450: Prefer exact qualified constructor for the creating object type
2513 if (isCtorCall
&& fd
->type
->mod
!= m
->lastf
->type
->mod
)
2515 if (tthis
->mod
== fd
->type
->mod
) goto Ltd
;
2516 if (tthis
->mod
== m
->lastf
->type
->mod
) goto Ltd_best
;
2523 Ltd_best
: // td_best is the best match so far
2524 //printf("Ltd_best\n");
2527 Ltd
: // td is the new best match
2532 property
= 0; // (backward compatibility)
2536 tthis_best
= tthis_fd
;
2559 p
.ta_last
= m
->last
!= MATCHnomatch
? MATCHexact
: MATCHnomatch
;
2560 p
.tthis_best
= NULL
;
2562 TemplateDeclaration
*td
= dstart
->isTemplateDeclaration();
2563 if (td
&& td
->funcroot
)
2564 dstart
= td
->funcroot
;
2566 overloadApply(dstart
, &p
, &ParamDeduce::fp
);
2568 //printf("td_best = %p, m->lastf = %p\n", p.td_best, m->lastf);
2569 if (p
.td_best
&& p
.ti_best
&& m
->count
== 1)
2571 // Matches to template function
2572 assert(p
.td_best
->onemember
&& p
.td_best
->onemember
->isFuncDeclaration());
2574 /* The best match is td_best with arguments tdargs.
2575 * Now instantiate the template.
2577 assert(p
.td_best
->_scope
);
2579 sc
= p
.td_best
->_scope
; // workaround for Type::aliasthisOf
2581 TemplateInstance
*ti
= new TemplateInstance(loc
, p
.td_best
, p
.ti_best
->tiargs
);
2582 ti
->semantic(sc
, fargs
);
2584 m
->lastf
= ti
->toAlias()->isFuncDeclaration();
2592 m
->last
= MATCHnomatch
;
2596 // look forward instantiated overload function
2597 // Dsymbol::oneMembers is alredy called in TemplateInstance::semantic.
2598 // it has filled overnext0d
2599 while (p
.ov_index
--)
2601 m
->lastf
= m
->lastf
->overnext0
;
2605 p
.tthis_best
= m
->lastf
->needThis() && !m
->lastf
->isCtorDeclaration() ? tthis
: NULL
;
2607 TypeFunction
*tf
= (TypeFunction
*)m
->lastf
->type
;
2608 if (tf
->ty
== Terror
)
2610 assert(tf
->ty
== Tfunction
);
2611 if (!tf
->callMatch(p
.tthis_best
, fargs
))
2614 /* As Bugzilla 3682 shows, a template instance can be matched while instantiating
2615 * that same template. Thus, the function type can be incomplete. Complete it.
2617 * Bugzilla 9208: For auto function, completion should be deferred to the end of
2618 * its semantic3. Should not complete it in here.
2620 if (tf
->next
&& !m
->lastf
->inferRetType
)
2622 m
->lastf
->type
= tf
->semantic(loc
, sc
);
2627 // Matches to non template function,
2628 // or found matches were ambiguous.
2629 assert(m
->count
>= 1);
2636 m
->last
= MATCHnomatch
;
2640 /*************************************************
2641 * Limited function template instantiation for using fd->leastAsSpecialized()
2643 FuncDeclaration
*TemplateDeclaration::doHeaderInstantiation(
2644 TemplateInstance
*ti
, Scope
*sc2
,
2645 FuncDeclaration
*fd
, Type
*tthis
, Expressions
*fargs
)
2649 // function body and contracts are not need
2650 if (fd
->isCtorDeclaration())
2651 fd
= new CtorDeclaration(fd
->loc
, fd
->endloc
, fd
->storage_class
, fd
->type
->syntaxCopy());
2653 fd
= new FuncDeclaration(fd
->loc
, fd
->endloc
, fd
->ident
, fd
->storage_class
, fd
->type
->syntaxCopy());
2656 assert(fd
->type
->ty
== Tfunction
);
2657 TypeFunction
*tf
= (TypeFunction
*)fd
->type
;
2662 // Match 'tthis' to any TemplateThisParameter's
2663 bool hasttp
= false;
2664 for (size_t i
= 0; i
< parameters
->dim
; i
++)
2666 TemplateParameter
*tp
= (*parameters
)[i
];
2667 TemplateThisParameter
*ttp
= tp
->isTemplateThisParameter();
2673 tf
= (TypeFunction
*)tf
->addSTC(ModToStc(tthis
->mod
));
2678 Scope
*scx
= sc2
->push();
2680 // Shouldn't run semantic on default arguments and return type.
2681 for (size_t i
= 0; i
< tf
->parameters
->dim
; i
++)
2682 (*tf
->parameters
)[i
]->defaultArg
= NULL
;
2683 if (fd
->isCtorDeclaration())
2685 // For constructors, emitting return type is necessary for
2686 // isolateReturn() in functionResolve.
2687 scx
->flags
|= SCOPEctor
;
2689 Dsymbol
*parent
= toParent2();
2691 AggregateDeclaration
*ad
= parent
->isAggregateDeclaration();
2692 if (!ad
|| parent
->isUnionDeclaration())
2698 tret
= ad
->handleType();
2700 tret
= tret
->addStorageClass(fd
->storage_class
| scx
->stc
);
2701 tret
= tret
->addMod(tf
->mod
);
2704 if (ad
&& ad
->isStructDeclaration())
2706 //printf("tf = %s\n", tf->toChars());
2711 fd
->type
= fd
->type
->addSTC(scx
->stc
);
2712 fd
->type
= fd
->type
->semantic(fd
->loc
, scx
);
2715 if (fd
->type
->ty
!= Tfunction
)
2718 fd
->originalType
= fd
->type
; // for mangling
2719 //printf("\t[%s] fd->type = %s, mod = %x, ", loc.toChars(), fd->type->toChars(), fd->type->mod);
2720 //printf("fd->needThis() = %d\n", fd->needThis());
2725 bool TemplateDeclaration::hasStaticCtorOrDtor()
2727 return false; // don't scan uninstantiated templates
2730 const char *TemplateDeclaration::toChars()
2733 return Dsymbol::toChars();
2738 buf
.writestring(ident
->toChars());
2740 for (size_t i
= 0; i
< parameters
->dim
; i
++)
2742 TemplateParameter
*tp
= (*parameters
)[i
];
2744 buf
.writestring(", ");
2745 ::toCBuffer(tp
, &buf
, &hgs
);
2751 FuncDeclaration
*fd
= onemember
->isFuncDeclaration();
2754 TypeFunction
*tf
= (TypeFunction
*)fd
->type
;
2755 buf
.writestring(parametersTypeToChars(tf
->parameters
, tf
->varargs
));
2761 buf
.writestring(" if (");
2762 ::toCBuffer(constraint
, &buf
, &hgs
);
2765 return buf
.extractString();
2768 Prot
TemplateDeclaration::prot()
2773 /****************************************************
2774 * Given a new instance tithis of this TemplateDeclaration,
2775 * see if there already exists an instance.
2776 * If so, return that existing instance.
2779 TemplateInstance
*TemplateDeclaration::findExistingInstance(TemplateInstance
*tithis
, Expressions
*fargs
)
2781 //printf("findExistingInstance(%p)\n", tithis);
2782 tithis
->fargs
= fargs
;
2783 TemplateInstances
*tinstances
= (TemplateInstances
*)dmd_aaGetRvalue((AA
*)instances
, (void *)tithis
->toHash());
2786 for (size_t i
= 0; i
< tinstances
->dim
; i
++)
2788 TemplateInstance
*ti
= (*tinstances
)[i
];
2789 if (tithis
->compare(ti
) == 0)
2796 /********************************************
2797 * Add instance ti to TemplateDeclaration's table of instances.
2798 * Return a handle we can use to later remove it if it fails instantiation.
2801 TemplateInstance
*TemplateDeclaration::addInstance(TemplateInstance
*ti
)
2803 //printf("addInstance() %p %p\n", instances, ti);
2804 TemplateInstances
**ptinstances
= (TemplateInstances
**)dmd_aaGet((AA
**)&instances
, (void *)ti
->toHash());
2806 *ptinstances
= new TemplateInstances();
2807 (*ptinstances
)->push(ti
);
2811 /*******************************************
2812 * Remove TemplateInstance from table of instances.
2814 * handle returned by addInstance()
2817 void TemplateDeclaration::removeInstance(TemplateInstance
*handle
)
2819 //printf("removeInstance()\n");
2820 TemplateInstances
*tinstances
= (TemplateInstances
*)dmd_aaGetRvalue((AA
*)instances
, (void *)handle
->toHash());
2823 for (size_t i
= 0; i
< tinstances
->dim
; i
++)
2825 TemplateInstance
*ti
= (*tinstances
)[i
];
2828 tinstances
->remove(i
);
2835 /* ======================== Type ============================================ */
2838 * Given an identifier, figure out which TemplateParameter it is.
2839 * Return IDX_NOTFOUND if not found.
2842 static size_t templateIdentifierLookup(Identifier
*id
, TemplateParameters
*parameters
)
2844 for (size_t i
= 0; i
< parameters
->dim
; i
++)
2846 TemplateParameter
*tp
= (*parameters
)[i
];
2847 if (tp
->ident
->equals(id
))
2850 return IDX_NOTFOUND
;
2853 size_t templateParameterLookup(Type
*tparam
, TemplateParameters
*parameters
)
2855 if (tparam
->ty
== Tident
)
2857 TypeIdentifier
*tident
= (TypeIdentifier
*)tparam
;
2858 //printf("\ttident = '%s'\n", tident->toChars());
2859 return templateIdentifierLookup(tident
->ident
, parameters
);
2861 return IDX_NOTFOUND
;
2864 unsigned char deduceWildHelper(Type
*t
, Type
**at
, Type
*tparam
)
2866 if ((tparam
->mod
& MODwild
) == 0)
2871 #define X(U,T) ((U) << 4) | (T)
2872 switch (X(tparam
->mod
, t
->mod
))
2875 case X(MODwild
, MODconst
):
2876 case X(MODwild
, MODshared
):
2877 case X(MODwild
, MODshared
| MODconst
):
2878 case X(MODwild
, MODimmutable
):
2879 case X(MODwildconst
, 0):
2880 case X(MODwildconst
, MODconst
):
2881 case X(MODwildconst
, MODshared
):
2882 case X(MODwildconst
, MODshared
| MODconst
):
2883 case X(MODwildconst
, MODimmutable
):
2884 case X(MODshared
| MODwild
, MODshared
):
2885 case X(MODshared
| MODwild
, MODshared
| MODconst
):
2886 case X(MODshared
| MODwild
, MODimmutable
):
2887 case X(MODshared
| MODwildconst
, MODshared
):
2888 case X(MODshared
| MODwildconst
, MODshared
| MODconst
):
2889 case X(MODshared
| MODwildconst
, MODimmutable
):
2891 unsigned char wm
= (t
->mod
& ~MODshared
);
2894 unsigned char m
= (t
->mod
& (MODconst
| MODimmutable
)) | (tparam
->mod
& t
->mod
& MODshared
);
2895 *at
= t
->unqualify(m
);
2899 case X(MODwild
, MODwild
):
2900 case X(MODwild
, MODwildconst
):
2901 case X(MODwild
, MODshared
| MODwild
):
2902 case X(MODwild
, MODshared
| MODwildconst
):
2903 case X(MODwildconst
, MODwild
):
2904 case X(MODwildconst
, MODwildconst
):
2905 case X(MODwildconst
, MODshared
| MODwild
):
2906 case X(MODwildconst
, MODshared
| MODwildconst
):
2907 case X(MODshared
| MODwild
, MODshared
| MODwild
):
2908 case X(MODshared
| MODwild
, MODshared
| MODwildconst
):
2909 case X(MODshared
| MODwildconst
, MODshared
| MODwild
):
2910 case X(MODshared
| MODwildconst
, MODshared
| MODwildconst
):
2912 *at
= t
->unqualify(tparam
->mod
& t
->mod
);
2922 MATCH
deduceTypeHelper(Type
*t
, Type
**at
, Type
*tparam
)
2926 #define X(U,T) ((U) << 4) | (T)
2927 switch (X(tparam
->mod
, t
->mod
))
2930 case X(0, MODconst
):
2932 case X(0, MODwildconst
):
2933 case X(0, MODshared
):
2934 case X(0, MODshared
| MODconst
):
2935 case X(0, MODshared
| MODwild
):
2936 case X(0, MODshared
| MODwildconst
):
2937 case X(0, MODimmutable
):
2939 // foo(U) const(T) => const(T)
2940 // foo(U) inout(T) => inout(T)
2941 // foo(U) inout(const(T)) => inout(const(T))
2942 // foo(U) shared(T) => shared(T)
2943 // foo(U) shared(const(T)) => shared(const(T))
2944 // foo(U) shared(inout(T)) => shared(inout(T))
2945 // foo(U) shared(inout(const(T))) => shared(inout(const(T)))
2946 // foo(U) immutable(T) => immutable(T)
2952 case X(MODconst
, MODconst
):
2953 case X(MODwild
, MODwild
):
2954 case X(MODwildconst
, MODwildconst
):
2955 case X(MODshared
, MODshared
):
2956 case X(MODshared
| MODconst
, MODshared
| MODconst
):
2957 case X(MODshared
| MODwild
, MODshared
| MODwild
):
2958 case X(MODshared
| MODwildconst
, MODshared
| MODwildconst
):
2959 case X(MODimmutable
, MODimmutable
):
2960 // foo(const(U)) const(T) => T
2961 // foo(inout(U)) inout(T) => T
2962 // foo(inout(const(U))) inout(const(T)) => T
2963 // foo(shared(U)) shared(T) => T
2964 // foo(shared(const(U))) shared(const(T)) => T
2965 // foo(shared(inout(U))) shared(inout(T)) => T
2966 // foo(shared(inout(const(U)))) shared(inout(const(T))) => T
2967 // foo(immutable(U)) immutable(T) => T
2969 *at
= t
->mutableOf()->unSharedOf();
2973 case X(MODconst
, 0):
2974 case X(MODconst
, MODwild
):
2975 case X(MODconst
, MODwildconst
):
2976 case X(MODconst
, MODshared
| MODconst
):
2977 case X(MODconst
, MODshared
| MODwild
):
2978 case X(MODconst
, MODshared
| MODwildconst
):
2979 case X(MODconst
, MODimmutable
):
2980 case X(MODwild
, MODshared
| MODwild
):
2981 case X(MODwildconst
, MODshared
| MODwildconst
):
2982 case X(MODshared
| MODconst
, MODimmutable
):
2983 // foo(const(U)) T => T
2984 // foo(const(U)) inout(T) => T
2985 // foo(const(U)) inout(const(T)) => T
2986 // foo(const(U)) shared(const(T)) => shared(T)
2987 // foo(const(U)) shared(inout(T)) => shared(T)
2988 // foo(const(U)) shared(inout(const(T))) => shared(T)
2989 // foo(const(U)) immutable(T) => T
2990 // foo(inout(U)) shared(inout(T)) => shared(T)
2991 // foo(inout(const(U))) shared(inout(const(T))) => shared(T)
2992 // foo(shared(const(U))) immutable(T) => T
2994 *at
= t
->mutableOf();
2998 case X(MODconst
, MODshared
):
2999 // foo(const(U)) shared(T) => shared(T)
3005 case X(MODshared
, MODshared
| MODconst
):
3006 case X(MODshared
, MODshared
| MODwild
):
3007 case X(MODshared
, MODshared
| MODwildconst
):
3008 case X(MODshared
| MODconst
, MODshared
):
3009 // foo(shared(U)) shared(const(T)) => const(T)
3010 // foo(shared(U)) shared(inout(T)) => inout(T)
3011 // foo(shared(U)) shared(inout(const(T))) => inout(const(T))
3012 // foo(shared(const(U))) shared(T) => T
3014 *at
= t
->unSharedOf();
3018 case X(MODwildconst
, MODimmutable
):
3019 case X(MODshared
| MODconst
, MODshared
| MODwildconst
):
3020 case X(MODshared
| MODwildconst
, MODimmutable
):
3021 case X(MODshared
| MODwildconst
, MODshared
| MODwild
):
3022 // foo(inout(const(U))) immutable(T) => T
3023 // foo(shared(const(U))) shared(inout(const(T))) => T
3024 // foo(shared(inout(const(U)))) immutable(T) => T
3025 // foo(shared(inout(const(U)))) shared(inout(T)) => T
3027 *at
= t
->unSharedOf()->mutableOf();
3031 case X(MODshared
| MODconst
, MODshared
| MODwild
):
3032 // foo(shared(const(U))) shared(inout(T)) => T
3034 *at
= t
->unSharedOf()->mutableOf();
3039 case X(MODwild
, MODconst
):
3040 case X(MODwild
, MODwildconst
):
3041 case X(MODwild
, MODimmutable
):
3042 case X(MODwild
, MODshared
):
3043 case X(MODwild
, MODshared
| MODconst
):
3044 case X(MODwild
, MODshared
| MODwildconst
):
3045 case X(MODwildconst
, 0):
3046 case X(MODwildconst
, MODconst
):
3047 case X(MODwildconst
, MODwild
):
3048 case X(MODwildconst
, MODshared
):
3049 case X(MODwildconst
, MODshared
| MODconst
):
3050 case X(MODwildconst
, MODshared
| MODwild
):
3051 case X(MODshared
, 0):
3052 case X(MODshared
, MODconst
):
3053 case X(MODshared
, MODwild
):
3054 case X(MODshared
, MODwildconst
):
3055 case X(MODshared
, MODimmutable
):
3056 case X(MODshared
| MODconst
, 0):
3057 case X(MODshared
| MODconst
, MODconst
):
3058 case X(MODshared
| MODconst
, MODwild
):
3059 case X(MODshared
| MODconst
, MODwildconst
):
3060 case X(MODshared
| MODwild
, 0):
3061 case X(MODshared
| MODwild
, MODconst
):
3062 case X(MODshared
| MODwild
, MODwild
):
3063 case X(MODshared
| MODwild
, MODwildconst
):
3064 case X(MODshared
| MODwild
, MODimmutable
):
3065 case X(MODshared
| MODwild
, MODshared
):
3066 case X(MODshared
| MODwild
, MODshared
| MODconst
):
3067 case X(MODshared
| MODwild
, MODshared
| MODwildconst
):
3068 case X(MODshared
| MODwildconst
, 0):
3069 case X(MODshared
| MODwildconst
, MODconst
):
3070 case X(MODshared
| MODwildconst
, MODwild
):
3071 case X(MODshared
| MODwildconst
, MODwildconst
):
3072 case X(MODshared
| MODwildconst
, MODshared
):
3073 case X(MODshared
| MODwildconst
, MODshared
| MODconst
):
3074 case X(MODimmutable
, 0):
3075 case X(MODimmutable
, MODconst
):
3076 case X(MODimmutable
, MODwild
):
3077 case X(MODimmutable
, MODwildconst
):
3078 case X(MODimmutable
, MODshared
):
3079 case X(MODimmutable
, MODshared
| MODconst
):
3080 case X(MODimmutable
, MODshared
| MODwild
):
3081 case X(MODimmutable
, MODshared
| MODwildconst
):
3082 // foo(inout(U)) T => nomatch
3083 // foo(inout(U)) const(T) => nomatch
3084 // foo(inout(U)) inout(const(T)) => nomatch
3085 // foo(inout(U)) immutable(T) => nomatch
3086 // foo(inout(U)) shared(T) => nomatch
3087 // foo(inout(U)) shared(const(T)) => nomatch
3088 // foo(inout(U)) shared(inout(const(T))) => nomatch
3089 // foo(inout(const(U))) T => nomatch
3090 // foo(inout(const(U))) const(T) => nomatch
3091 // foo(inout(const(U))) inout(T) => nomatch
3092 // foo(inout(const(U))) shared(T) => nomatch
3093 // foo(inout(const(U))) shared(const(T)) => nomatch
3094 // foo(inout(const(U))) shared(inout(T)) => nomatch
3095 // foo(shared(U)) T => nomatch
3096 // foo(shared(U)) const(T) => nomatch
3097 // foo(shared(U)) inout(T) => nomatch
3098 // foo(shared(U)) inout(const(T)) => nomatch
3099 // foo(shared(U)) immutable(T) => nomatch
3100 // foo(shared(const(U))) T => nomatch
3101 // foo(shared(const(U))) const(T) => nomatch
3102 // foo(shared(const(U))) inout(T) => nomatch
3103 // foo(shared(const(U))) inout(const(T)) => nomatch
3104 // foo(shared(inout(U))) T => nomatch
3105 // foo(shared(inout(U))) const(T) => nomatch
3106 // foo(shared(inout(U))) inout(T) => nomatch
3107 // foo(shared(inout(U))) inout(const(T)) => nomatch
3108 // foo(shared(inout(U))) immutable(T) => nomatch
3109 // foo(shared(inout(U))) shared(T) => nomatch
3110 // foo(shared(inout(U))) shared(const(T)) => nomatch
3111 // foo(shared(inout(U))) shared(inout(const(T))) => nomatch
3112 // foo(shared(inout(const(U)))) T => nomatch
3113 // foo(shared(inout(const(U)))) const(T) => nomatch
3114 // foo(shared(inout(const(U)))) inout(T) => nomatch
3115 // foo(shared(inout(const(U)))) inout(const(T)) => nomatch
3116 // foo(shared(inout(const(U)))) shared(T) => nomatch
3117 // foo(shared(inout(const(U)))) shared(const(T)) => nomatch
3118 // foo(immutable(U)) T => nomatch
3119 // foo(immutable(U)) const(T) => nomatch
3120 // foo(immutable(U)) inout(T) => nomatch
3121 // foo(immutable(U)) inout(const(T)) => nomatch
3122 // foo(immutable(U)) shared(T) => nomatch
3123 // foo(immutable(U)) shared(const(T)) => nomatch
3124 // foo(immutable(U)) shared(inout(T)) => nomatch
3125 // foo(immutable(U)) shared(inout(const(T))) => nomatch
3126 return MATCHnomatch
;
3130 return MATCHnomatch
; // silence compiler warning about missing return
3135 /* These form the heart of template argument deduction.
3136 * Given 'this' being the type argument to the template instance,
3137 * it is matched against the template declaration parameter specialization
3138 * 'tparam' to determine the type to be used for the parameter.
3140 * template Foo(T:T*) // template declaration
3141 * Foo!(int*) // template instantiation
3145 * parameters = [ T:T* ] // Array of TemplateParameter's
3147 * dedtypes = [ int ] // Array of Expression/Type's
3149 MATCH
deduceType(RootObject
*o
, Scope
*sc
, Type
*tparam
, TemplateParameters
*parameters
,
3150 Objects
*dedtypes
, unsigned *wm
, size_t inferStart
)
3152 class DeduceType
: public Visitor
3157 TemplateParameters
*parameters
;
3163 DeduceType(Scope
*sc
, Type
*tparam
, TemplateParameters
*parameters
, Objects
*dedtypes
, unsigned *wm
, size_t inferStart
)
3164 : sc(sc
), tparam(tparam
), parameters(parameters
), dedtypes(dedtypes
), wm(wm
), inferStart(inferStart
)
3166 result
= MATCHnomatch
;
3177 if (tparam
->ty
== Tident
)
3179 // Determine which parameter tparam is
3180 size_t i
= templateParameterLookup(tparam
, parameters
);
3181 if (i
== IDX_NOTFOUND
)
3186 /* Need a loc to go with the semantic routine.
3189 if (parameters
->dim
)
3191 TemplateParameter
*tp
= (*parameters
)[0];
3195 /* BUG: what if tparam is a template instance, that
3196 * has as an argument another Tident?
3198 tparam
= tparam
->semantic(loc
, sc
);
3199 assert(tparam
->ty
!= Tident
);
3200 result
= deduceType(t
, sc
, tparam
, parameters
, dedtypes
, wm
);
3204 TemplateParameter
*tp
= (*parameters
)[i
];
3206 TypeIdentifier
*tident
= (TypeIdentifier
*)tparam
;
3207 if (tident
->idents
.dim
> 0)
3209 //printf("matching %s to %s\n", tparam->toChars(), t->toChars());
3210 Dsymbol
*s
= t
->toDsymbol(sc
);
3211 for (size_t j
= tident
->idents
.dim
; j
-- > 0; )
3213 RootObject
*id
= tident
->idents
[j
];
3214 if (id
->dyncast() == DYNCAST_IDENTIFIER
)
3216 if (!s
|| !s
->parent
)
3218 Dsymbol
*s2
= s
->parent
->search(Loc(), (Identifier
*)id
);
3222 //printf("[%d] s = %s %s, s2 = %s %s\n", j, s->kind(), s->toChars(), s2->kind(), s2->toChars());
3225 if (Type
*tx
= s2
->getType())
3227 if (s
!= tx
->toDsymbol(sc
))
3238 //printf("[e] s = %s\n", s?s->toChars():"(null)");
3239 if (tp
->isTemplateTypeParameter())
3241 Type
*tt
= s
->getType();
3244 Type
*at
= (Type
*)(*dedtypes
)[i
];
3245 if (at
&& at
->ty
== Tnone
)
3246 at
= ((TypeDeduced
*)at
)->tded
;
3247 if (!at
|| tt
->equals(at
))
3249 (*dedtypes
)[i
] = tt
;
3253 if (tp
->isTemplateAliasParameter())
3255 Dsymbol
*s2
= (Dsymbol
*)(*dedtypes
)[i
];
3265 // Found the corresponding parameter tp
3266 if (!tp
->isTemplateTypeParameter())
3269 Type
*at
= (Type
*)(*dedtypes
)[i
];
3271 if (unsigned char wx
= wm
? deduceWildHelper(t
, &tt
, tparam
) : 0)
3276 (*dedtypes
)[i
] = tt
;
3278 result
= MATCHconst
;
3282 // type vs expressions
3283 if (at
->ty
== Tnone
)
3285 TypeDeduced
*xt
= (TypeDeduced
*)at
;
3286 result
= xt
->matchAll(tt
);
3287 if (result
> MATCHnomatch
)
3289 (*dedtypes
)[i
] = tt
;
3290 if (result
> MATCHconst
)
3291 result
= MATCHconst
; // limit level for inout matches
3300 (*dedtypes
)[i
] = tt
; // Prefer current type match
3303 if (tt
->implicitConvTo(at
->constOf()))
3305 (*dedtypes
)[i
] = at
->constOf()->mutableOf();
3309 if (at
->implicitConvTo(tt
->constOf()))
3311 (*dedtypes
)[i
] = tt
->constOf()->mutableOf();
3317 else if (MATCH m
= deduceTypeHelper(t
, &tt
, tparam
))
3322 (*dedtypes
)[i
] = tt
;
3327 // type vs expressions
3328 if (at
->ty
== Tnone
)
3330 TypeDeduced
*xt
= (TypeDeduced
*)at
;
3331 result
= xt
->matchAll(tt
);
3332 if (result
> MATCHnomatch
)
3334 (*dedtypes
)[i
] = tt
;
3345 if (tt
->ty
== Tclass
&& at
->ty
== Tclass
)
3347 result
= tt
->implicitConvTo(at
);
3350 if (tt
->ty
== Tsarray
&& at
->ty
== Tarray
&&
3351 tt
->nextOf()->implicitConvTo(at
->nextOf()) >= MATCHconst
)
3359 if (tparam
->ty
== Ttypeof
)
3361 /* Need a loc to go with the semantic routine.
3364 if (parameters
->dim
)
3366 TemplateParameter
*tp
= (*parameters
)[0];
3370 tparam
= tparam
->semantic(loc
, sc
);
3372 if (t
->ty
!= tparam
->ty
)
3374 if (Dsymbol
*sym
= t
->toDsymbol(sc
))
3376 if (sym
->isforwardRef() && !tparam
->deco
)
3380 MATCH m
= t
->implicitConvTo(tparam
);
3381 if (m
== MATCHnomatch
)
3383 if (t
->ty
== Tclass
)
3385 TypeClass
*tc
= (TypeClass
*)t
;
3386 if (tc
->sym
->aliasthis
&& !(tc
->att
& RECtracingDT
))
3388 tc
->att
= (AliasThisRec
)(tc
->att
| RECtracingDT
);
3389 m
= deduceType(t
->aliasthisOf(), sc
, tparam
, parameters
, dedtypes
, wm
);
3390 tc
->att
= (AliasThisRec
)(tc
->att
& ~RECtracingDT
);
3393 else if (t
->ty
== Tstruct
)
3395 TypeStruct
*ts
= (TypeStruct
*)t
;
3396 if (ts
->sym
->aliasthis
&& !(ts
->att
& RECtracingDT
))
3398 ts
->att
= (AliasThisRec
)(ts
->att
| RECtracingDT
);
3399 m
= deduceType(t
->aliasthisOf(), sc
, tparam
, parameters
, dedtypes
, wm
);
3400 ts
->att
= (AliasThisRec
)(ts
->att
& ~RECtracingDT
);
3410 if (tparam
->deco
&& !tparam
->hasWild())
3412 result
= t
->implicitConvTo(tparam
);
3416 Type
*tpn
= tparam
->nextOf();
3417 if (wm
&& t
->ty
== Taarray
&& tparam
->isWild())
3419 // Bugzilla 12403: In IFTI, stop inout matching on transitive part of AA types.
3420 tpn
= tpn
->substWildTo(MODmutable
);
3423 result
= deduceType(t
->nextOf(), sc
, tpn
, parameters
, dedtypes
, wm
);
3428 result
= MATCHexact
;
3432 result
= MATCHnomatch
;
3436 result
= MATCHconst
;
3439 void visit(TypeVector
*t
)
3441 if (tparam
->ty
== Tvector
)
3443 TypeVector
*tp
= (TypeVector
*)tparam
;
3444 result
= deduceType(t
->basetype
, sc
, tp
->basetype
, parameters
, dedtypes
, wm
);
3450 void visit(TypeDArray
*t
)
3455 void visit(TypeSArray
*t
)
3457 // Extra check that array dimensions must match
3460 if (tparam
->ty
== Tarray
)
3462 MATCH m
= deduceType(t
->next
, sc
, tparam
->nextOf(), parameters
, dedtypes
, wm
);
3463 result
= (m
>= MATCHconst
) ? MATCHconvert
: MATCHnomatch
;
3467 TemplateParameter
*tp
= NULL
;
3468 Expression
*edim
= NULL
;
3470 if (tparam
->ty
== Tsarray
)
3472 TypeSArray
*tsa
= (TypeSArray
*)tparam
;
3473 if (tsa
->dim
->op
== TOKvar
&&
3474 ((VarExp
*)tsa
->dim
)->var
->storage_class
& STCtemplateparameter
)
3476 Identifier
*id
= ((VarExp
*)tsa
->dim
)->var
->ident
;
3477 i
= templateIdentifierLookup(id
, parameters
);
3478 assert(i
!= IDX_NOTFOUND
);
3479 tp
= (*parameters
)[i
];
3484 else if (tparam
->ty
== Taarray
)
3486 TypeAArray
*taa
= (TypeAArray
*)tparam
;
3487 i
= templateParameterLookup(taa
->index
, parameters
);
3488 if (i
!= IDX_NOTFOUND
)
3489 tp
= (*parameters
)[i
];
3495 taa
->index
->resolve(Loc(), sc
, &e
, &tx
, &s
);
3496 edim
= s
? getValue(s
) : getValue(e
);
3499 if ((tp
&& tp
->matchArg(sc
, t
->dim
, i
, parameters
, dedtypes
, NULL
)) ||
3500 (edim
&& edim
->toInteger() == t
->dim
->toInteger()))
3502 result
= deduceType(t
->next
, sc
, tparam
->nextOf(), parameters
, dedtypes
, wm
);
3509 result
= MATCHnomatch
;
3512 void visit(TypeAArray
*t
)
3514 // Extra check that index type must match
3515 if (tparam
&& tparam
->ty
== Taarray
)
3517 TypeAArray
*tp
= (TypeAArray
*)tparam
;
3518 if (!deduceType(t
->index
, sc
, tp
->index
, parameters
, dedtypes
))
3520 result
= MATCHnomatch
;
3527 void visit(TypeFunction
*t
)
3529 //printf("TypeFunction::deduceType()\n");
3530 //printf("\tthis = %d, ", t->ty); t->print();
3531 //printf("\ttparam = %d, ", tparam->ty); tparam->print();
3533 // Extra check that function characteristics must match
3534 if (tparam
&& tparam
->ty
== Tfunction
)
3536 TypeFunction
*tp
= (TypeFunction
*)tparam
;
3537 if (t
->varargs
!= tp
->varargs
||
3538 t
->linkage
!= tp
->linkage
)
3540 result
= MATCHnomatch
;
3544 size_t nfargs
= Parameter::dim(t
->parameters
);
3545 size_t nfparams
= Parameter::dim(tp
->parameters
);
3547 // bug 2579 fix: Apply function parameter storage classes to parameter types
3548 for (size_t i
= 0; i
< nfparams
; i
++)
3550 Parameter
*fparam
= Parameter::getNth(tp
->parameters
, i
);
3551 fparam
->type
= fparam
->type
->addStorageClass(fparam
->storageClass
);
3552 fparam
->storageClass
&= ~(STC_TYPECTOR
| STCin
);
3554 //printf("\t-> this = %d, ", t->ty); t->print();
3555 //printf("\t-> tparam = %d, ", tparam->ty); tparam->print();
3557 /* See if tuple match
3559 if (nfparams
> 0 && nfargs
>= nfparams
- 1)
3561 /* See if 'A' of the template parameter matches 'A'
3562 * of the type of the last function parameter.
3564 Parameter
*fparam
= Parameter::getNth(tp
->parameters
, nfparams
- 1);
3566 assert(fparam
->type
);
3567 if (fparam
->type
->ty
!= Tident
)
3569 TypeIdentifier
*tid
= (TypeIdentifier
*)fparam
->type
;
3570 if (tid
->idents
.dim
)
3573 /* Look through parameters to find tuple matching tid->ident
3578 if (tupi
== parameters
->dim
)
3580 TemplateParameter
*tx
= (*parameters
)[tupi
];
3581 TemplateTupleParameter
*tup
= tx
->isTemplateTupleParameter();
3582 if (tup
&& tup
->ident
->equals(tid
->ident
))
3586 /* The types of the function arguments [nfparams - 1 .. nfargs]
3587 * now form the tuple argument.
3589 size_t tuple_dim
= nfargs
- (nfparams
- 1);
3591 /* See if existing tuple, and whether it matches or not
3593 RootObject
*o
= (*dedtypes
)[tupi
];
3596 // Existing deduced argument must be a tuple, and must match
3597 Tuple
*tup
= isTuple(o
);
3598 if (!tup
|| tup
->objects
.dim
!= tuple_dim
)
3600 result
= MATCHnomatch
;
3603 for (size_t i
= 0; i
< tuple_dim
; i
++)
3605 Parameter
*arg
= Parameter::getNth(t
->parameters
, nfparams
- 1 + i
);
3606 if (!arg
->type
->equals(tup
->objects
[i
]))
3608 result
= MATCHnomatch
;
3616 Tuple
*tup
= new Tuple();
3617 tup
->objects
.setDim(tuple_dim
);
3618 for (size_t i
= 0; i
< tuple_dim
; i
++)
3620 Parameter
*arg
= Parameter::getNth(t
->parameters
, nfparams
- 1 + i
);
3621 tup
->objects
[i
] = arg
->type
;
3623 (*dedtypes
)[tupi
] = tup
;
3625 nfparams
--; // don't consider the last parameter for type deduction
3630 if (nfargs
!= nfparams
)
3632 result
= MATCHnomatch
;
3636 for (size_t i
= 0; i
< nfparams
; i
++)
3638 Parameter
*a
= Parameter::getNth(t
->parameters
, i
);
3639 Parameter
*ap
= Parameter::getNth(tp
->parameters
, i
);
3641 if (!a
->isCovariant(t
->isref
, ap
) ||
3642 !deduceType(a
->type
, sc
, ap
->type
, parameters
, dedtypes
))
3644 result
= MATCHnomatch
;
3652 void visit(TypeIdentifier
*t
)
3655 if (tparam
&& tparam
->ty
== Tident
)
3657 TypeIdentifier
*tp
= (TypeIdentifier
*)tparam
;
3659 for (size_t i
= 0; i
< t
->idents
.dim
; i
++)
3661 RootObject
*id1
= t
->idents
[i
];
3662 RootObject
*id2
= tp
->idents
[i
];
3664 if (!id1
->equals(id2
))
3666 result
= MATCHnomatch
;
3674 void visit(TypeInstance
*t
)
3677 if (tparam
&& tparam
->ty
== Tinstance
&& t
->tempinst
->tempdecl
)
3679 TemplateDeclaration
*tempdecl
= t
->tempinst
->tempdecl
->isTemplateDeclaration();
3682 TypeInstance
*tp
= (TypeInstance
*)tparam
;
3684 //printf("tempinst->tempdecl = %p\n", tempdecl);
3685 //printf("tp->tempinst->tempdecl = %p\n", tp->tempinst->tempdecl);
3686 if (!tp
->tempinst
->tempdecl
)
3688 //printf("tp->tempinst->name = '%s'\n", tp->tempinst->name->toChars());
3691 * template Foo(T : sa!(T), alias sa)
3693 size_t i
= templateIdentifierLookup(tp
->tempinst
->name
, parameters
);
3694 if (i
== IDX_NOTFOUND
)
3696 /* Didn't find it as a parameter identifier. Try looking
3697 * it up and seeing if is an alias. See Bugzilla 1454
3699 TypeIdentifier
*tid
= new TypeIdentifier(tp
->loc
, tp
->tempinst
->name
);
3703 tid
->resolve(tp
->loc
, sc
, &e
, &tx
, &s
);
3706 s
= tx
->toDsymbol(sc
);
3707 if (TemplateInstance
*ti
= s
? s
->parent
->isTemplateInstance() : NULL
)
3709 // Bugzilla 14290: Try to match with ti->tempecl,
3710 // only when ti is an enclosing instance.
3711 Dsymbol
*p
= sc
->parent
;
3712 while (p
&& p
!= ti
)
3721 TemplateDeclaration
*td
= s
->isTemplateDeclaration();
3726 for (; td
; td
= td
->overnext
)
3735 TemplateParameter
*tpx
= (*parameters
)[i
];
3736 if (!tpx
->matchArg(sc
, tempdecl
, i
, parameters
, dedtypes
, NULL
))
3739 else if (tempdecl
!= tp
->tempinst
->tempdecl
)
3744 for (size_t i
= 0; 1; i
++)
3746 //printf("\ttest: tempinst->tiargs[%d]\n", i);
3747 RootObject
*o1
= NULL
;
3748 if (i
< t
->tempinst
->tiargs
->dim
)
3749 o1
= (*t
->tempinst
->tiargs
)[i
];
3750 else if (i
< t
->tempinst
->tdtypes
.dim
&& i
< tp
->tempinst
->tiargs
->dim
)
3752 // Pick up default arg
3753 o1
= t
->tempinst
->tdtypes
[i
];
3755 else if (i
>= tp
->tempinst
->tiargs
->dim
)
3758 if (i
>= tp
->tempinst
->tiargs
->dim
)
3760 size_t dim
= tempdecl
->parameters
->dim
- (tempdecl
->isVariadic() ? 1 : 0);
3761 while (i
< dim
&& ((*tempdecl
->parameters
)[i
]->dependent
||
3762 (*tempdecl
->parameters
)[i
]->hasDefaultArg()))
3767 break; // match if all remained parameters are dependent
3771 RootObject
*o2
= (*tp
->tempinst
->tiargs
)[i
];
3772 Type
*t2
= isType(o2
);
3774 size_t j
= (t2
&& t2
->ty
== Tident
&& i
== tp
->tempinst
->tiargs
->dim
- 1)
3775 ? templateParameterLookup(t2
, parameters
) : IDX_NOTFOUND
;
3776 if (j
!= IDX_NOTFOUND
&& j
== parameters
->dim
- 1 &&
3777 (*parameters
)[j
]->isTemplateTupleParameter())
3781 * alias A!(int, float) X;
3782 * static if (is(X Y == A!(Z), Z...)) {}
3783 * deduce that Z is a tuple(int, float)
3786 /* Create tuple from remaining args
3788 Tuple
*vt
= new Tuple();
3789 size_t vtdim
= (tempdecl
->isVariadic()
3790 ? t
->tempinst
->tiargs
->dim
: t
->tempinst
->tdtypes
.dim
) - i
;
3791 vt
->objects
.setDim(vtdim
);
3792 for (size_t k
= 0; k
< vtdim
; k
++)
3795 if (k
< t
->tempinst
->tiargs
->dim
)
3796 o
= (*t
->tempinst
->tiargs
)[i
+ k
];
3797 else // Pick up default arg
3798 o
= t
->tempinst
->tdtypes
[i
+ k
];
3802 Tuple
*v
= (Tuple
*)(*dedtypes
)[j
];
3809 (*dedtypes
)[j
] = vt
;
3815 Type
*t1
= isType(o1
);
3816 Dsymbol
*s1
= isDsymbol(o1
);
3817 Dsymbol
*s2
= isDsymbol(o2
);
3818 Expression
*e1
= s1
? getValue(s1
) : getValue(isExpression(o1
));
3819 Expression
*e2
= isExpression(o2
);
3823 if (!deduceType(t1
, sc
, t2
, parameters
, dedtypes
))
3829 e1
= e1
->ctfeInterpret();
3831 /* If it is one of the template parameters for this template,
3832 * we should not attempt to interpret it. It already has a value.
3834 if (e2
->op
== TOKvar
&&
3835 (((VarExp
*)e2
)->var
->storage_class
& STCtemplateparameter
))
3838 * (T:Number!(e2), int e2)
3840 j
= templateIdentifierLookup(((VarExp
*)e2
)->var
->ident
, parameters
);
3841 if (j
!= IDX_NOTFOUND
)
3843 // The template parameter was not from this template
3844 // (it may be from a parent template, for example)
3847 e2
= ::semantic(e2
, sc
); // Bugzilla 13417
3848 e2
= e2
->ctfeInterpret();
3850 //printf("e1 = %s, type = %s %d\n", e1->toChars(), e1->type->toChars(), e1->type->ty);
3851 //printf("e2 = %s, type = %s %d\n", e2->toChars(), e2->type->toChars(), e2->type->ty);
3852 if (!e1
->equals(e2
))
3854 if (!e2
->implicitConvTo(e1
->type
))
3857 e2
= e2
->implicitCastTo(sc
, e1
->type
);
3858 e2
= e2
->ctfeInterpret();
3859 if (!e1
->equals(e2
))
3863 else if (e1
&& t2
&& t2
->ty
== Tident
)
3865 j
= templateParameterLookup(t2
, parameters
);
3867 if (j
== IDX_NOTFOUND
)
3869 t2
->resolve(((TypeIdentifier
*)t2
)->loc
, sc
, &e2
, &t2
, &s2
);
3874 if (!(*parameters
)[j
]->matchArg(sc
, e1
, j
, parameters
, dedtypes
, NULL
))
3880 if (!s1
->equals(s2
))
3883 else if (s1
&& t2
&& t2
->ty
== Tident
)
3885 j
= templateParameterLookup(t2
, parameters
);
3886 if (j
== IDX_NOTFOUND
)
3888 t2
->resolve(((TypeIdentifier
*)t2
)->loc
, sc
, &e2
, &t2
, &s2
);
3893 if (!(*parameters
)[j
]->matchArg(sc
, s1
, j
, parameters
, dedtypes
, NULL
))
3904 //printf("no match\n");
3905 result
= MATCHnomatch
;
3908 void visit(TypeStruct
*t
)
3910 /* If this struct is a template struct, and we're matching
3911 * it against a template instance, convert the struct type
3912 * to a template instance, too, and try again.
3914 TemplateInstance
*ti
= t
->sym
->parent
->isTemplateInstance();
3916 if (tparam
&& tparam
->ty
== Tinstance
)
3918 if (ti
&& ti
->toAlias() == t
->sym
)
3920 TypeInstance
*tx
= new TypeInstance(Loc(), ti
);
3921 result
= deduceType(tx
, sc
, tparam
, parameters
, dedtypes
, wm
);
3925 /* Match things like:
3928 TypeInstance
*tpi
= (TypeInstance
*)tparam
;
3929 if (tpi
->idents
.dim
)
3931 RootObject
*id
= tpi
->idents
[tpi
->idents
.dim
- 1];
3932 if (id
->dyncast() == DYNCAST_IDENTIFIER
&& t
->sym
->ident
->equals((Identifier
*)id
))
3934 Type
*tparent
= t
->sym
->parent
->getType();
3937 /* Slice off the .foo in S!(T).foo
3940 result
= deduceType(tparent
, sc
, tpi
, parameters
, dedtypes
, wm
);
3949 if (tparam
&& tparam
->ty
== Tstruct
)
3951 TypeStruct
*tp
= (TypeStruct
*)tparam
;
3953 //printf("\t%d\n", (MATCH) t->implicitConvTo(tp));
3954 if (wm
&& t
->deduceWild(tparam
, false))
3956 result
= MATCHconst
;
3959 result
= t
->implicitConvTo(tp
);
3965 void visit(TypeEnum
*t
)
3968 if (tparam
&& tparam
->ty
== Tenum
)
3970 TypeEnum
*tp
= (TypeEnum
*)tparam
;
3971 if (t
->sym
== tp
->sym
)
3974 result
= MATCHnomatch
;
3977 Type
*tb
= t
->toBasetype();
3978 if (tb
->ty
== tparam
->ty
||
3979 (tb
->ty
== Tsarray
&& tparam
->ty
== Taarray
))
3981 result
= deduceType(tb
, sc
, tparam
, parameters
, dedtypes
, wm
);
3987 /* Helper for TypeClass::deduceType().
3988 * Classes can match with implicit conversion to a base class or interface.
3989 * This is complicated, because there may be more than one base class which
3990 * matches. In such cases, one or more parameters remain ambiguous.
3993 * interface I(X, Y) {}
3994 * class C : I(uint, double), I(char, double) {}
3996 * foo(T, U)( I!(T, U) x)
3998 * deduces that U is double, but T remains ambiguous (could be char or uint).
4000 * Given a baseclass b, and initial deduced types 'dedtypes', this function
4001 * tries to match tparam with b, and also tries all base interfaces of b.
4002 * If a match occurs, numBaseClassMatches is incremented, and the new deduced
4003 * types are ANDed with the current 'best' estimate for dedtypes.
4005 static void deduceBaseClassParameters(BaseClass
*b
,
4006 Scope
*sc
, Type
*tparam
, TemplateParameters
*parameters
, Objects
*dedtypes
,
4007 Objects
*best
, int &numBaseClassMatches
)
4009 TemplateInstance
*parti
= b
->sym
? b
->sym
->parent
->isTemplateInstance() : NULL
;
4012 // Make a temporary copy of dedtypes so we don't destroy it
4013 Objects
*tmpdedtypes
= new Objects();
4014 tmpdedtypes
->setDim(dedtypes
->dim
);
4015 memcpy(tmpdedtypes
->tdata(), dedtypes
->tdata(), dedtypes
->dim
* sizeof(void *));
4017 TypeInstance
*t
= new TypeInstance(Loc(), parti
);
4018 MATCH m
= deduceType(t
, sc
, tparam
, parameters
, tmpdedtypes
);
4019 if (m
> MATCHnomatch
)
4021 // If this is the first ever match, it becomes our best estimate
4022 if (numBaseClassMatches
==0)
4023 memcpy(best
->tdata(), tmpdedtypes
->tdata(), tmpdedtypes
->dim
* sizeof(void *));
4024 else for (size_t k
= 0; k
< tmpdedtypes
->dim
; ++k
)
4026 // If we've found more than one possible type for a parameter,
4027 // mark it as unknown.
4028 if ((*tmpdedtypes
)[k
] != (*best
)[k
])
4029 (*best
)[k
] = (*dedtypes
)[k
];
4031 ++numBaseClassMatches
;
4034 // Now recursively test the inherited interfaces
4035 for (size_t j
= 0; j
< b
->baseInterfaces
.length
; ++j
)
4037 BaseClass
*bi
= &b
->baseInterfaces
.ptr
[j
];
4038 deduceBaseClassParameters(bi
,
4039 sc
, tparam
, parameters
, dedtypes
,
4040 best
, numBaseClassMatches
);
4045 void visit(TypeClass
*t
)
4047 //printf("TypeClass::deduceType(this = %s)\n", t->toChars());
4049 /* If this class is a template class, and we're matching
4050 * it against a template instance, convert the class type
4051 * to a template instance, too, and try again.
4053 TemplateInstance
*ti
= t
->sym
->parent
->isTemplateInstance();
4055 if (tparam
&& tparam
->ty
== Tinstance
)
4057 if (ti
&& ti
->toAlias() == t
->sym
)
4059 TypeInstance
*tx
= new TypeInstance(Loc(), ti
);
4060 MATCH m
= deduceType(tx
, sc
, tparam
, parameters
, dedtypes
, wm
);
4061 // Even if the match fails, there is still a chance it could match
4063 if (m
!= MATCHnomatch
)
4070 /* Match things like:
4073 TypeInstance
*tpi
= (TypeInstance
*)tparam
;
4074 if (tpi
->idents
.dim
)
4076 RootObject
*id
= tpi
->idents
[tpi
->idents
.dim
- 1];
4077 if (id
->dyncast() == DYNCAST_IDENTIFIER
&& t
->sym
->ident
->equals((Identifier
*)id
))
4079 Type
*tparent
= t
->sym
->parent
->getType();
4082 /* Slice off the .foo in S!(T).foo
4085 result
= deduceType(tparent
, sc
, tpi
, parameters
, dedtypes
, wm
);
4092 // If it matches exactly or via implicit conversion, we're done
4094 if (result
!= MATCHnomatch
)
4097 /* There is still a chance to match via implicit conversion to
4098 * a base class or interface. Because there could be more than one such
4099 * match, we need to check them all.
4102 int numBaseClassMatches
= 0; // Have we found an interface match?
4104 // Our best guess at dedtypes
4105 Objects
*best
= new Objects();
4106 best
->setDim(dedtypes
->dim
);
4108 ClassDeclaration
*s
= t
->sym
;
4109 while (s
&& s
->baseclasses
->dim
> 0)
4111 // Test the base class
4112 deduceBaseClassParameters((*s
->baseclasses
)[0],
4113 sc
, tparam
, parameters
, dedtypes
,
4114 best
, numBaseClassMatches
);
4116 // Test the interfaces inherited by the base class
4117 for (size_t i
= 0; i
< s
->interfaces
.length
; ++i
)
4119 BaseClass
*b
= s
->interfaces
.ptr
[i
];
4120 deduceBaseClassParameters(b
, sc
, tparam
, parameters
, dedtypes
,
4121 best
, numBaseClassMatches
);
4123 s
= (*s
->baseclasses
)[0]->sym
;
4126 if (numBaseClassMatches
== 0)
4128 result
= MATCHnomatch
;
4132 // If we got at least one match, copy the known types into dedtypes
4133 memcpy(dedtypes
->tdata(), best
->tdata(), best
->dim
* sizeof(void *));
4134 result
= MATCHconvert
;
4139 if (tparam
&& tparam
->ty
== Tclass
)
4141 TypeClass
*tp
= (TypeClass
*)tparam
;
4143 //printf("\t%d\n", (MATCH) t->implicitConvTo(tp));
4144 if (wm
&& t
->deduceWild(tparam
, false))
4146 result
= MATCHconst
;
4149 result
= t
->implicitConvTo(tp
);
4155 void visit(Expression
*e
)
4157 //printf("Expression::deduceType(e = %s)\n", e->toChars());
4158 size_t i
= templateParameterLookup(tparam
, parameters
);
4159 if (i
== IDX_NOTFOUND
|| ((TypeIdentifier
*)tparam
)->idents
.dim
> 0)
4161 if (e
== emptyArrayElement
&& tparam
->ty
== Tarray
)
4163 Type
*tn
= ((TypeNext
*)tparam
)->next
;
4164 result
= deduceType(emptyArrayElement
, sc
, tn
, parameters
, dedtypes
, wm
);
4167 e
->type
->accept(this);
4171 TemplateTypeParameter
*tp
= (*parameters
)[i
]->isTemplateTypeParameter();
4175 if (e
== emptyArrayElement
)
4179 result
= MATCHexact
;
4182 if (tp
->defaultType
)
4184 tp
->defaultType
->accept(this);
4189 Type
*at
= (Type
*)(*dedtypes
)[i
];
4191 if (unsigned char wx
= deduceWildHelper(e
->type
, &tt
, tparam
))
4194 result
= MATCHconst
;
4196 else if (MATCH m
= deduceTypeHelper(e
->type
, &tt
, tparam
))
4203 // expression vs (none)
4206 (*dedtypes
)[i
] = new TypeDeduced(tt
, e
, tparam
);
4210 TypeDeduced
*xt
= NULL
;
4211 if (at
->ty
== Tnone
)
4213 xt
= (TypeDeduced
*)at
;
4217 // From previous matched expressions to current deduced type
4218 MATCH match1
= xt
? xt
->matchAll(tt
) : MATCHnomatch
;
4220 // From current expresssion to previous deduced type
4221 Type
*pt
= at
->addMod(tparam
->mod
);
4223 pt
= pt
->substWildTo(*wm
);
4224 MATCH match2
= e
->implicitConvTo(pt
);
4226 if (match1
> MATCHnomatch
&& match2
> MATCHnomatch
)
4228 if (at
->implicitConvTo(tt
) <= MATCHnomatch
)
4229 match1
= MATCHnomatch
; // Prefer at
4230 else if (tt
->implicitConvTo(at
) <= MATCHnomatch
)
4231 match2
= MATCHnomatch
; // Prefer tt
4232 else if (tt
->isTypeBasic() && tt
->ty
== at
->ty
&& tt
->mod
!= at
->mod
)
4234 if (!tt
->isMutable() && !at
->isMutable())
4235 tt
= tt
->mutableOf()->addMod(MODmerge(tt
->mod
, at
->mod
));
4236 else if (tt
->isMutable())
4238 if (at
->mod
== 0) // Prefer unshared
4239 match1
= MATCHnomatch
;
4241 match2
= MATCHnomatch
;
4243 else if (at
->isMutable())
4245 if (tt
->mod
== 0) // Prefer unshared
4246 match2
= MATCHnomatch
;
4248 match1
= MATCHnomatch
;
4250 //printf("tt = %s, at = %s\n", tt->toChars(), at->toChars());
4254 match1
= MATCHnomatch
;
4255 match2
= MATCHnomatch
;
4258 if (match1
> MATCHnomatch
)
4260 // Prefer current match: tt
4262 xt
->update(tt
, e
, tparam
);
4264 (*dedtypes
)[i
] = tt
;
4268 if (match2
> MATCHnomatch
)
4270 // Prefer previous match: (*dedtypes)[i]
4272 xt
->update(e
, tparam
);
4277 /* Deduce common type
4279 if (Type
*t
= rawTypeMerge(at
, tt
))
4282 xt
->update(t
, e
, tparam
);
4286 pt
= tt
->addMod(tparam
->mod
);
4288 pt
= pt
->substWildTo(*wm
);
4289 result
= e
->implicitConvTo(pt
);
4293 result
= MATCHnomatch
;
4296 MATCH
deduceEmptyArrayElement()
4298 if (!emptyArrayElement
)
4300 emptyArrayElement
= new IdentifierExp(Loc(), Id::p
); // dummy
4301 emptyArrayElement
->type
= Type::tvoid
;
4303 assert(tparam
->ty
== Tarray
);
4305 Type
*tn
= ((TypeNext
*)tparam
)->next
;
4306 return deduceType(emptyArrayElement
, sc
, tn
, parameters
, dedtypes
, wm
);
4309 void visit(NullExp
*e
)
4311 if (tparam
->ty
== Tarray
&& e
->type
->ty
== Tnull
)
4313 // tparam:T[] <- e:null (void[])
4314 result
= deduceEmptyArrayElement();
4317 visit((Expression
*)e
);
4320 void visit(StringExp
*e
)
4323 if (e
->type
->ty
== Tarray
&&
4324 (tparam
->ty
== Tsarray
||
4325 (tparam
->ty
== Taarray
&& (taai
= ((TypeAArray
*)tparam
)->index
)->ty
== Tident
&&
4326 ((TypeIdentifier
*)taai
)->idents
.dim
== 0)))
4328 // Consider compile-time known boundaries
4329 e
->type
->nextOf()->sarrayOf(e
->len
)->accept(this);
4332 visit((Expression
*)e
);
4335 void visit(ArrayLiteralExp
*e
)
4337 if ((!e
->elements
|| !e
->elements
->dim
) &&
4338 e
->type
->toBasetype()->nextOf()->ty
== Tvoid
&&
4339 tparam
->ty
== Tarray
)
4341 // tparam:T[] <- e:[] (void[])
4342 result
= deduceEmptyArrayElement();
4346 if (tparam
->ty
== Tarray
&& e
->elements
&& e
->elements
->dim
)
4348 Type
*tn
= ((TypeDArray
*)tparam
)->next
;
4349 result
= MATCHexact
;
4352 MATCH m
= deduceType(e
->basis
, sc
, tn
, parameters
, dedtypes
, wm
);
4356 for (size_t i
= 0; i
< e
->elements
->dim
; i
++)
4358 if (result
<= MATCHnomatch
)
4360 Expression
*el
= (*e
->elements
)[i
];
4363 MATCH m
= deduceType(el
, sc
, tn
, parameters
, dedtypes
, wm
);
4371 if (e
->type
->ty
== Tarray
&&
4372 (tparam
->ty
== Tsarray
||
4373 (tparam
->ty
== Taarray
&& (taai
= ((TypeAArray
*)tparam
)->index
)->ty
== Tident
&&
4374 ((TypeIdentifier
*)taai
)->idents
.dim
== 0)))
4376 // Consider compile-time known boundaries
4377 e
->type
->nextOf()->sarrayOf(e
->elements
->dim
)->accept(this);
4380 visit((Expression
*)e
);
4383 void visit(AssocArrayLiteralExp
*e
)
4385 if (tparam
->ty
== Taarray
&& e
->keys
&& e
->keys
->dim
)
4387 TypeAArray
*taa
= (TypeAArray
*)tparam
;
4388 result
= MATCHexact
;
4389 for (size_t i
= 0; i
< e
->keys
->dim
; i
++)
4391 MATCH m1
= deduceType((*e
->keys
)[i
], sc
, taa
->index
, parameters
, dedtypes
, wm
);
4394 if (result
<= MATCHnomatch
)
4396 MATCH m2
= deduceType((*e
->values
)[i
], sc
, taa
->next
, parameters
, dedtypes
, wm
);
4399 if (result
<= MATCHnomatch
)
4404 visit((Expression
*)e
);
4407 void visit(FuncExp
*e
)
4409 //printf("e->type = %s, tparam = %s\n", e->type->toChars(), tparam->toChars());
4413 if (!to
->nextOf() || to
->nextOf()->ty
!= Tfunction
)
4415 TypeFunction
*tof
= (TypeFunction
*)to
->nextOf();
4417 // Parameter types inference from 'tof'
4418 assert(e
->td
->_scope
);
4419 TypeFunction
*tf
= (TypeFunction
*)e
->fd
->type
;
4420 //printf("\ttof = %s\n", tof->toChars());
4421 //printf("\ttf = %s\n", tf->toChars());
4422 size_t dim
= Parameter::dim(tf
->parameters
);
4424 if (Parameter::dim(tof
->parameters
) != dim
||
4425 tof
->varargs
!= tf
->varargs
)
4428 Objects
*tiargs
= new Objects();
4429 tiargs
->reserve(e
->td
->parameters
->dim
);
4431 for (size_t i
= 0; i
< e
->td
->parameters
->dim
; i
++)
4433 TemplateParameter
*tp
= (*e
->td
->parameters
)[i
];
4435 for (; u
< dim
; u
++)
4437 Parameter
*p
= Parameter::getNth(tf
->parameters
, u
);
4438 if (p
->type
->ty
== Tident
&&
4439 ((TypeIdentifier
*)p
->type
)->ident
== tp
->ident
)
4445 Parameter
*pto
= Parameter::getNth(tof
->parameters
, u
);
4448 Type
*t
= pto
->type
->syntaxCopy(); // Bugzilla 11774
4449 if (reliesOnTident(t
, parameters
, inferStart
))
4451 t
= t
->semantic(e
->loc
, sc
);
4452 if (t
->ty
== Terror
)
4457 // Set target of return type inference
4458 if (!tf
->next
&& tof
->next
)
4459 e
->fd
->treq
= tparam
;
4461 TemplateInstance
*ti
= new TemplateInstance(e
->loc
, e
->td
, tiargs
);
4462 Expression
*ex
= new ScopeExp(e
->loc
, ti
);
4463 ex
= ::semantic(ex
, e
->td
->_scope
);
4465 // Reset inference target for the later re-semantic
4468 if (ex
->op
== TOKerror
)
4470 if (ex
->op
!= TOKfunction
)
4478 if (t
->ty
== Tdelegate
&& tparam
->ty
== Tpointer
)
4481 // Allow conversion from implicit function pointer to delegate
4482 if (e
->tok
== TOKreserved
&&
4483 t
->ty
== Tpointer
&& tparam
->ty
== Tdelegate
)
4485 TypeFunction
*tf
= (TypeFunction
*)t
->nextOf();
4486 t
= (new TypeDelegate(tf
))->merge();
4488 //printf("tparam = %s <= e->type = %s, t = %s\n", tparam->toChars(), e->type->toChars(), t->toChars());
4492 void visit(SliceExp
*e
)
4495 if (e
->type
->ty
== Tarray
&&
4496 (tparam
->ty
== Tsarray
||
4497 (tparam
->ty
== Taarray
&& (taai
= ((TypeAArray
*)tparam
)->index
)->ty
== Tident
&&
4498 ((TypeIdentifier
*)taai
)->idents
.dim
== 0)))
4500 // Consider compile-time known boundaries
4501 if (Type
*tsa
= toStaticArrayType(e
))
4507 visit((Expression
*)e
);
4510 void visit(CommaExp
*e
)
4512 ((CommaExp
*)e
)->e2
->accept(this);
4516 DeduceType
v(sc
, tparam
, parameters
, dedtypes
, wm
, inferStart
);
4517 if (Type
*t
= isType(o
))
4521 assert(isExpression(o
) && wm
);
4522 ((Expression
*)o
)->accept(&v
);
4527 /*******************************
4529 * t Tested type, if NULL, returns NULL.
4530 * tparams Optional template parameters.
4532 * If one of the subtypes of this type is a TypeIdentifier,
4533 * i.e. it's an unresolved type, return that type.
4535 * Only when the TypeIdentifier is one of template parameters,
4539 bool reliesOnTident(Type
*t
, TemplateParameters
*tparams
, size_t iStart
)
4541 class ReliesOnTident
: public Visitor
4544 TemplateParameters
*tparams
;
4548 ReliesOnTident(TemplateParameters
*tparams
, size_t iStart
)
4549 : tparams(tparams
), iStart(iStart
)
4558 void visit(TypeNext
*t
)
4560 t
->next
->accept(this);
4563 void visit(TypeVector
*t
)
4565 t
->basetype
->accept(this);
4568 void visit(TypeAArray
*t
)
4570 visit((TypeNext
*)t
);
4572 t
->index
->accept(this);
4575 void visit(TypeFunction
*t
)
4577 size_t dim
= Parameter::dim(t
->parameters
);
4578 for (size_t i
= 0; i
< dim
; i
++)
4580 Parameter
*fparam
= Parameter::getNth(t
->parameters
, i
);
4581 fparam
->type
->accept(this);
4586 t
->next
->accept(this);
4589 void visit(TypeIdentifier
*t
)
4597 for (size_t i
= iStart
; i
< tparams
->dim
; i
++)
4599 TemplateParameter
*tp
= (*tparams
)[i
];
4600 if (tp
->ident
->equals(t
->ident
))
4608 void visit(TypeInstance
*t
)
4613 for (size_t i
= iStart
; i
< tparams
->dim
; i
++)
4615 TemplateParameter
*tp
= (*tparams
)[i
];
4616 if (t
->tempinst
->name
== tp
->ident
)
4622 if (!t
->tempinst
->tiargs
)
4624 for (size_t i
= 0; i
< t
->tempinst
->tiargs
->dim
; i
++)
4626 Type
*ta
= isType((*t
->tempinst
->tiargs
)[i
]);
4636 void visit(TypeTypeof
*t
)
4638 //printf("TypeTypeof::reliesOnTident('%s')\n", t->toChars());
4639 t
->exp
->accept(this);
4642 void visit(TypeTuple
*t
)
4646 for (size_t i
= 0; i
< t
->arguments
->dim
; i
++)
4648 Parameter
*arg
= (*t
->arguments
)[i
];
4649 arg
->type
->accept(this);
4656 void visit(Expression
*)
4658 //printf("Expression::reliesOnTident('%s')\n", e->toChars());
4661 void visit(IdentifierExp
*e
)
4663 //printf("IdentifierExp::reliesOnTident('%s')\n", e->toChars());
4664 for (size_t i
= iStart
; i
< tparams
->dim
; i
++)
4666 TemplateParameter
*tp
= (*tparams
)[i
];
4667 if (e
->ident
== tp
->ident
)
4675 void visit(TupleExp
*e
)
4677 //printf("TupleExp::reliesOnTident('%s')\n", e->toChars());
4680 for (size_t i
= 0; i
< e
->exps
->dim
; i
++)
4682 Expression
*ea
= (*e
->exps
)[i
];
4690 void visit(ArrayLiteralExp
*e
)
4692 //printf("ArrayLiteralExp::reliesOnTident('%s')\n", e->toChars());
4695 for (size_t i
= 0; i
< e
->elements
->dim
; i
++)
4697 Expression
*el
= (*e
->elements
)[i
];
4705 void visit(AssocArrayLiteralExp
*e
)
4707 //printf("AssocArrayLiteralExp::reliesOnTident('%s')\n", e->toChars());
4708 for (size_t i
= 0; i
< e
->keys
->dim
; i
++)
4710 Expression
*ek
= (*e
->keys
)[i
];
4715 for (size_t i
= 0; i
< e
->values
->dim
; i
++)
4717 Expression
*ev
= (*e
->values
)[i
];
4724 void visit(StructLiteralExp
*e
)
4726 //printf("StructLiteralExp::reliesOnTident('%s')\n", e->toChars());
4729 for (size_t i
= 0; i
< e
->elements
->dim
; i
++)
4731 Expression
*ea
= (*e
->elements
)[i
];
4739 void visit(TypeExp
*e
)
4741 //printf("TypeExp::reliesOnTident('%s')\n", e->toChars());
4742 e
->type
->accept(this);
4745 void visit(NewExp
*e
)
4747 //printf("NewExp::reliesOnTident('%s')\n", e->toChars());
4749 e
->thisexp
->accept(this);
4750 if (!result
&& e
->newargs
)
4752 for (size_t i
= 0; i
< e
->newargs
->dim
; i
++)
4754 Expression
*ea
= (*e
->newargs
)[i
];
4760 e
->newtype
->accept(this);
4761 if (!result
&& e
->arguments
)
4763 for (size_t i
= 0; i
< e
->arguments
->dim
; i
++)
4765 Expression
*ea
= (*e
->arguments
)[i
];
4773 void visit(NewAnonClassExp
*)
4775 //printf("NewAnonClassExp::reliesOnTident('%s')\n", e->toChars());
4779 void visit(FuncExp
*)
4781 //printf("FuncExp::reliesOnTident('%s')\n", e->toChars());
4785 void visit(TypeidExp
*e
)
4787 //printf("TypeidExp::reliesOnTident('%s')\n", e->toChars());
4788 if (Expression
*ea
= isExpression(e
->obj
))
4790 else if (Type
*ta
= isType(e
->obj
))
4794 void visit(TraitsExp
*e
)
4796 //printf("TraitsExp::reliesOnTident('%s')\n", e->toChars());
4799 for (size_t i
= 0; i
< e
->args
->dim
; i
++)
4801 RootObject
*oa
= (*e
->args
)[i
];
4802 if (Expression
*ea
= isExpression(oa
))
4804 else if (Type
*ta
= isType(oa
))
4812 void visit(IsExp
*e
)
4814 //printf("IsExp::reliesOnTident('%s')\n", e->toChars());
4815 e
->targ
->accept(this);
4818 void visit(UnaExp
*e
)
4820 //printf("UnaExp::reliesOnTident('%s')\n", e->toChars());
4821 e
->e1
->accept(this);
4824 void visit(DotTemplateInstanceExp
*e
)
4826 //printf("DotTemplateInstanceExp::reliesOnTident('%s')\n", e->toChars());
4828 if (!result
&& e
->ti
->tiargs
)
4830 for (size_t i
= 0; i
< e
->ti
->tiargs
->dim
; i
++)
4832 RootObject
*oa
= (*e
->ti
->tiargs
)[i
];
4833 if (Expression
*ea
= isExpression(oa
))
4835 else if (Type
*ta
= isType(oa
))
4843 void visit(CallExp
*e
)
4845 //printf("CallExp::reliesOnTident('%s')\n", e->toChars());
4847 if (!result
&& e
->arguments
)
4849 for (size_t i
= 0; i
< e
->arguments
->dim
; i
++)
4851 Expression
*ea
= (*e
->arguments
)[i
];
4859 void visit(CastExp
*e
)
4861 //printf("CastExp::reliesOnTident('%s')\n", e->toChars());
4863 // e.to can be null for cast() with no type
4864 if (!result
&& e
->to
)
4865 e
->to
->accept(this);
4868 void visit(SliceExp
*e
)
4870 //printf("SliceExp::reliesOnTident('%s')\n", e->toChars());
4872 if (!result
&& e
->lwr
)
4873 e
->lwr
->accept(this);
4874 if (!result
&& e
->upr
)
4875 e
->upr
->accept(this);
4878 void visit(IntervalExp
*e
)
4880 //printf("IntervalExp::reliesOnTident('%s')\n", e->toChars());
4881 e
->lwr
->accept(this);
4883 e
->upr
->accept(this);
4886 void visit(ArrayExp
*e
)
4888 //printf("ArrayExp::reliesOnTident('%s')\n", e->toChars());
4890 if (!result
&& e
->arguments
)
4892 for (size_t i
= 0; i
< e
->arguments
->dim
; i
++)
4894 Expression
*ea
= (*e
->arguments
)[i
];
4900 void visit(BinExp
*e
)
4902 //printf("BinExp::reliesOnTident('%s')\n", e->toChars());
4903 e
->e1
->accept(this);
4905 e
->e2
->accept(this);
4908 void visit(CondExp
*e
)
4910 //printf("BinExp::reliesOnTident('%s')\n", e->toChars());
4911 e
->econd
->accept(this);
4920 ReliesOnTident
v(tparams
, iStart
);
4925 /* ======================== TemplateParameter =============================== */
4927 TemplateParameter::TemplateParameter(Loc loc
, Identifier
*ident
)
4930 this->ident
= ident
;
4931 this->dependent
= false;
4934 TemplateTypeParameter
*TemplateParameter::isTemplateTypeParameter()
4939 TemplateValueParameter
*TemplateParameter::isTemplateValueParameter()
4944 TemplateAliasParameter
*TemplateParameter::isTemplateAliasParameter()
4949 TemplateTupleParameter
*TemplateParameter::isTemplateTupleParameter()
4954 TemplateThisParameter
*TemplateParameter::isTemplateThisParameter()
4959 /*******************************************
4960 * Match to a particular TemplateParameter.
4962 * instLoc location that the template is instantiated.
4963 * tiargs[] actual arguments to template instance
4965 * parameters[] template parameters
4966 * dedtypes[] deduced arguments to template instance
4967 * *psparam set to symbol declared and initialized to dedtypes[i]
4969 MATCH
TemplateParameter::matchArg(Loc instLoc
, Scope
*sc
, Objects
*tiargs
,
4970 size_t i
, TemplateParameters
*parameters
, Objects
*dedtypes
,
4971 Declaration
**psparam
)
4975 if (i
< tiargs
->dim
)
4976 oarg
= (*tiargs
)[i
];
4979 // Get default argument instead
4980 oarg
= defaultArg(instLoc
, sc
);
4983 assert(i
< dedtypes
->dim
);
4984 // It might have already been deduced
4985 oarg
= (*dedtypes
)[i
];
4990 return matchArg(sc
, oarg
, i
, parameters
, dedtypes
, psparam
);
4995 return MATCHnomatch
;
4998 /* ======================== TemplateTypeParameter =========================== */
5002 Type
*TemplateTypeParameter::tdummy
= NULL
;
5004 TemplateTypeParameter::TemplateTypeParameter(Loc loc
, Identifier
*ident
, Type
*specType
,
5006 : TemplateParameter(loc
, ident
)
5008 this->ident
= ident
;
5009 this->specType
= specType
;
5010 this->defaultType
= defaultType
;
5013 TemplateTypeParameter
*TemplateTypeParameter::isTemplateTypeParameter()
5018 TemplateParameter
*TemplateTypeParameter::syntaxCopy()
5020 return new TemplateTypeParameter(loc
, ident
,
5021 specType
? specType
->syntaxCopy() : NULL
,
5022 defaultType
? defaultType
->syntaxCopy() : NULL
);
5025 bool TemplateTypeParameter::declareParameter(Scope
*sc
)
5027 //printf("TemplateTypeParameter::declareParameter('%s')\n", ident->toChars());
5028 TypeIdentifier
*ti
= new TypeIdentifier(loc
, ident
);
5029 Declaration
*ad
= new AliasDeclaration(loc
, ident
, ti
);
5030 return sc
->insert(ad
) != NULL
;
5033 bool TemplateTypeParameter::semantic(Scope
*sc
, TemplateParameters
*parameters
)
5035 //printf("TemplateTypeParameter::semantic('%s')\n", ident->toChars());
5036 if (specType
&& !reliesOnTident(specType
, parameters
))
5038 specType
= specType
->semantic(loc
, sc
);
5040 return !(specType
&& isError(specType
));
5043 MATCH
TemplateTypeParameter::matchArg(Scope
*sc
, RootObject
*oarg
,
5044 size_t i
, TemplateParameters
*parameters
, Objects
*dedtypes
,
5045 Declaration
**psparam
)
5047 //printf("TemplateTypeParameter::matchArg('%s')\n", ident->toChars());
5048 MATCH m
= MATCHexact
;
5049 Type
*ta
= isType(oarg
);
5052 //printf("%s %p %p %p\n", oarg->toChars(), isExpression(oarg), isDsymbol(oarg), isTuple(oarg));
5055 //printf("ta is %s\n", ta->toChars());
5059 if (!ta
|| ta
== tdummy
)
5062 //printf("\tcalling deduceType(): ta is %s, specType is %s\n", ta->toChars(), specType->toChars());
5063 MATCH m2
= deduceType(ta
, sc
, specType
, parameters
, dedtypes
);
5064 if (m2
<= MATCHnomatch
)
5066 //printf("\tfailed deduceType\n");
5074 Type
*t
= (Type
*)(*dedtypes
)[i
];
5076 if (dependent
&& !t
->equals(ta
)) // Bugzilla 14357
5079 /* This is a self-dependent parameter. For example:
5080 * template X(T : T*) {}
5081 * template X(T : S!T, alias S) {}
5083 //printf("t = %s ta = %s\n", t->toChars(), ta->toChars());
5091 // Must match already deduced type
5092 Type
*t
= (Type
*)(*dedtypes
)[i
];
5096 //printf("t = %s ta = %s\n", t->toChars(), ta->toChars());
5102 // So that matches with specializations are better
5106 (*dedtypes
)[i
] = ta
;
5109 *psparam
= new AliasDeclaration(loc
, ident
, ta
);
5110 //printf("\tm = %d\n", m);
5111 return dependent
? MATCHexact
: m
;
5116 //printf("\tm = %d\n", MATCHnomatch);
5117 return MATCHnomatch
;
5121 void TemplateTypeParameter::print(RootObject
*oarg
, RootObject
*oded
)
5123 printf(" %s\n", ident
->toChars());
5125 Type
*t
= isType(oarg
);
5126 Type
*ta
= isType(oded
);
5131 printf("\tSpecialization: %s\n", specType
->toChars());
5133 printf("\tDefault: %s\n", defaultType
->toChars());
5134 printf("\tParameter: %s\n", t
? t
->toChars() : "NULL");
5135 printf("\tDeduced Type: %s\n", ta
->toChars());
5138 void *TemplateTypeParameter::dummyArg()
5143 // Use this for alias-parameter's too (?)
5145 tdummy
= new TypeIdentifier(loc
, ident
);
5152 RootObject
*TemplateTypeParameter::specialization()
5157 RootObject
*TemplateTypeParameter::defaultArg(Loc
, Scope
*sc
)
5159 Type
*t
= defaultType
;
5162 t
= t
->syntaxCopy();
5163 t
= t
->semantic(loc
, sc
); // use the parameter loc
5168 bool TemplateTypeParameter::hasDefaultArg()
5170 return defaultType
!= NULL
;
5173 /* ======================== TemplateThisParameter =========================== */
5177 TemplateThisParameter::TemplateThisParameter(Loc loc
, Identifier
*ident
,
5180 : TemplateTypeParameter(loc
, ident
, specType
, defaultType
)
5184 TemplateThisParameter
*TemplateThisParameter::isTemplateThisParameter()
5189 TemplateParameter
*TemplateThisParameter::syntaxCopy()
5191 return new TemplateThisParameter(loc
, ident
,
5192 specType
? specType
->syntaxCopy() : NULL
,
5193 defaultType
? defaultType
->syntaxCopy() : NULL
);
5196 /* ======================== TemplateAliasParameter ========================== */
5200 Dsymbol
*TemplateAliasParameter::sdummy
= NULL
;
5202 TemplateAliasParameter::TemplateAliasParameter(Loc loc
, Identifier
*ident
,
5203 Type
*specType
, RootObject
*specAlias
, RootObject
*defaultAlias
)
5204 : TemplateParameter(loc
, ident
)
5206 this->ident
= ident
;
5207 this->specType
= specType
;
5208 this->specAlias
= specAlias
;
5209 this->defaultAlias
= defaultAlias
;
5212 TemplateAliasParameter
*TemplateAliasParameter::isTemplateAliasParameter()
5217 TemplateParameter
*TemplateAliasParameter::syntaxCopy()
5219 return new TemplateAliasParameter(loc
, ident
,
5220 specType
? specType
->syntaxCopy() : NULL
,
5221 objectSyntaxCopy(specAlias
),
5222 objectSyntaxCopy(defaultAlias
));
5225 bool TemplateAliasParameter::declareParameter(Scope
*sc
)
5227 TypeIdentifier
*ti
= new TypeIdentifier(loc
, ident
);
5228 Declaration
*ad
= new AliasDeclaration(loc
, ident
, ti
);
5229 return sc
->insert(ad
) != NULL
;
5232 static RootObject
*aliasParameterSemantic(Loc loc
, Scope
*sc
, RootObject
*o
, TemplateParameters
*parameters
)
5236 Expression
*ea
= isExpression(o
);
5237 Type
*ta
= isType(o
);
5238 if (ta
&& (!parameters
|| !reliesOnTident(ta
, parameters
)))
5240 Dsymbol
*s
= ta
->toDsymbol(sc
);
5244 o
= ta
->semantic(loc
, sc
);
5248 sc
= sc
->startCTFE();
5249 ea
= ::semantic(ea
, sc
);
5251 o
= ea
->ctfeInterpret();
5257 bool TemplateAliasParameter::semantic(Scope
*sc
, TemplateParameters
*parameters
)
5259 if (specType
&& !reliesOnTident(specType
, parameters
))
5261 specType
= specType
->semantic(loc
, sc
);
5263 specAlias
= aliasParameterSemantic(loc
, sc
, specAlias
, parameters
);
5264 return !(specType
&& isError(specType
)) &&
5265 !(specAlias
&& isError(specAlias
));
5268 MATCH
TemplateAliasParameter::matchArg(Scope
*sc
, RootObject
*oarg
,
5269 size_t i
, TemplateParameters
*parameters
, Objects
*dedtypes
,
5270 Declaration
**psparam
)
5272 //printf("TemplateAliasParameter::matchArg('%s')\n", ident->toChars());
5273 MATCH m
= MATCHexact
;
5274 Type
*ta
= isType(oarg
);
5275 RootObject
*sa
= ta
&& !ta
->deco
? NULL
: getDsymbol(oarg
);
5276 Expression
*ea
= isExpression(oarg
);
5277 if (ea
&& (ea
->op
== TOKthis
|| ea
->op
== TOKsuper
))
5278 sa
= ((ThisExp
*)ea
)->var
;
5279 else if (ea
&& ea
->op
== TOKscope
)
5280 sa
= ((ScopeExp
*)ea
)->sds
;
5283 if (((Dsymbol
*)sa
)->isAggregateDeclaration())
5286 /* specType means the alias must be a declaration with a type
5287 * that matches specType.
5291 Declaration
*d
= ((Dsymbol
*)sa
)->isDeclaration();
5294 if (!d
->type
->equals(specType
))
5305 if (!ea
->type
->equals(specType
))
5309 else if (ta
&& ta
->ty
== Tinstance
&& !specAlias
)
5311 /* Bugzilla xxxxx: Specialized parameter should be prefeerd
5312 * match to the template type parameter.
5313 * template X(alias a) {} // a == this
5314 * template X(alias a : B!A, alias B, A...) {} // B!A => ta
5317 else if (sa
&& sa
== TemplateTypeParameter::tdummy
)
5319 /* Bugzilla 2025: Aggregate Types should preferentially
5320 * match to the template type parameter.
5321 * template X(alias a) {} // a == this
5322 * template X(T) {} // T => sa
5333 Dsymbol
*sx
= isDsymbol(sa
);
5334 if (sa
!= specAlias
&& sx
)
5336 Type
*talias
= isType(specAlias
);
5340 TemplateInstance
*ti
= sx
->isTemplateInstance();
5341 if (!ti
&& sx
->parent
)
5343 ti
= sx
->parent
->isTemplateInstance();
5344 if (ti
&& ti
->name
!= sx
->ident
)
5350 Type
*t
= new TypeInstance(Loc(), ti
);
5351 MATCH m2
= deduceType(t
, sc
, talias
, parameters
, dedtypes
);
5352 if (m2
<= MATCHnomatch
)
5356 else if ((*dedtypes
)[i
])
5358 // Must match already deduced symbol
5359 RootObject
*si
= (*dedtypes
)[i
];
5360 if (!sa
|| si
!= sa
)
5363 (*dedtypes
)[i
] = sa
;
5367 if (Dsymbol
*s
= isDsymbol(sa
))
5369 *psparam
= new AliasDeclaration(loc
, ident
, s
);
5371 else if (Type
*t
= isType(sa
))
5373 *psparam
= new AliasDeclaration(loc
, ident
, t
);
5379 // Declare manifest constant
5380 Initializer
*init
= new ExpInitializer(loc
, ea
);
5381 VarDeclaration
*v
= new VarDeclaration(loc
, NULL
, ident
, init
);
5382 v
->storage_class
= STCmanifest
;
5387 return dependent
? MATCHexact
: m
;
5392 //printf("\tm = %d\n", MATCHnomatch);
5393 return MATCHnomatch
;
5397 void TemplateAliasParameter::print(RootObject
*, RootObject
*oded
)
5399 printf(" %s\n", ident
->toChars());
5401 Dsymbol
*sa
= isDsymbol(oded
);
5404 printf("\tParameter alias: %s\n", sa
->toChars());
5407 void *TemplateAliasParameter::dummyArg()
5409 RootObject
*s
= specAlias
;
5413 sdummy
= new Dsymbol();
5420 RootObject
*TemplateAliasParameter::specialization()
5425 RootObject
*TemplateAliasParameter::defaultArg(Loc
, Scope
*sc
)
5427 RootObject
*da
= defaultAlias
;
5428 Type
*ta
= isType(defaultAlias
);
5431 if (ta
->ty
== Tinstance
)
5433 // If the default arg is a template, instantiate for each type
5434 da
= ta
->syntaxCopy();
5438 RootObject
*o
= aliasParameterSemantic(loc
, sc
, da
, NULL
); // use the parameter loc
5442 bool TemplateAliasParameter::hasDefaultArg()
5444 return defaultAlias
!= NULL
;
5447 /* ======================== TemplateValueParameter ========================== */
5451 AA
*TemplateValueParameter::edummies
= NULL
;
5453 TemplateValueParameter::TemplateValueParameter(Loc loc
, Identifier
*ident
, Type
*valType
,
5454 Expression
*specValue
, Expression
*defaultValue
)
5455 : TemplateParameter(loc
, ident
)
5457 this->ident
= ident
;
5458 this->valType
= valType
;
5459 this->specValue
= specValue
;
5460 this->defaultValue
= defaultValue
;
5463 TemplateValueParameter
*TemplateValueParameter::isTemplateValueParameter()
5468 TemplateParameter
*TemplateValueParameter::syntaxCopy()
5470 return new TemplateValueParameter(loc
, ident
,
5471 valType
->syntaxCopy(),
5472 specValue
? specValue
->syntaxCopy() : NULL
,
5473 defaultValue
? defaultValue
->syntaxCopy() : NULL
);
5476 bool TemplateValueParameter::declareParameter(Scope
*sc
)
5478 VarDeclaration
*v
= new VarDeclaration(loc
, valType
, ident
, NULL
);
5479 v
->storage_class
= STCtemplateparameter
;
5480 return sc
->insert(v
) != NULL
;
5483 bool TemplateValueParameter::semantic(Scope
*sc
, TemplateParameters
*)
5485 valType
= valType
->semantic(loc
, sc
);
5487 return !isError(valType
);
5490 MATCH
TemplateValueParameter::matchArg(Scope
*sc
, RootObject
*oarg
,
5491 size_t i
, TemplateParameters
*, Objects
*dedtypes
, Declaration
**psparam
)
5493 //printf("TemplateValueParameter::matchArg('%s')\n", ident->toChars());
5495 MATCH m
= MATCHexact
;
5497 Expression
*ei
= isExpression(oarg
);
5502 Dsymbol
*si
= isDsymbol(oarg
);
5503 FuncDeclaration
*f
= si
? si
->isFuncDeclaration() : NULL
;
5504 if (!f
|| !f
->fbody
|| f
->needThis())
5507 ei
= new VarExp(loc
, f
);
5508 ei
= ::semantic(ei
, sc
);
5510 /* If a function is really property-like, and then
5511 * it's CTFEable, ei will be a literal expression.
5513 unsigned int olderrors
= global
.startGagging();
5514 ei
= resolveProperties(sc
, ei
);
5515 ei
= ei
->ctfeInterpret();
5516 if (global
.endGagging(olderrors
) || ei
->op
== TOKerror
)
5519 /* Bugzilla 14520: A property-like function can match to both
5520 * TemplateAlias and ValueParameter. But for template overloads,
5521 * it should always prefer alias parameter to be consistent
5522 * template match result.
5524 * template X(alias f) { enum X = 1; }
5525 * template X(int val) { enum X = 2; }
5526 * int f1() { return 0; } // CTFEable
5527 * int f2(); // body-less function is not CTFEable
5528 * enum x1 = X!f1; // should be 1
5529 * enum x2 = X!f2; // should be 1
5531 * e.g. The x1 value must be same even if the f1 definition will be moved
5532 * into di while stripping body code.
5537 if (ei
&& ei
->op
== TOKvar
)
5539 // Resolve const variables that we had skipped earlier
5540 ei
= ei
->ctfeInterpret();
5543 //printf("\tvalType: %s, ty = %d\n", valType->toChars(), valType->ty);
5544 vt
= valType
->semantic(loc
, sc
);
5545 //printf("ei: %s, ei->type: %s\n", ei->toChars(), ei->type->toChars());
5546 //printf("vt = %s\n", vt->toChars());
5550 MATCH m2
= ei
->implicitConvTo(vt
);
5551 //printf("m: %d\n", m);
5554 if (m
<= MATCHnomatch
)
5556 ei
= ei
->implicitCastTo(sc
, vt
);
5557 ei
= ei
->ctfeInterpret();
5562 if (!ei
|| (Expression
*)dmd_aaGetRvalue(edummies
, (void *)ei
->type
) == ei
)
5565 Expression
*e
= specValue
;
5567 sc
= sc
->startCTFE();
5568 e
= ::semantic(e
, sc
);
5569 e
= resolveProperties(sc
, e
);
5571 e
= e
->implicitCastTo(sc
, vt
);
5572 e
= e
->ctfeInterpret();
5574 ei
= ei
->syntaxCopy();
5575 sc
= sc
->startCTFE();
5576 ei
= ::semantic(ei
, sc
);
5578 ei
= ei
->implicitCastTo(sc
, vt
);
5579 ei
= ei
->ctfeInterpret();
5580 //printf("\tei: %s, %s\n", ei->toChars(), ei->type->toChars());
5581 //printf("\te : %s, %s\n", e->toChars(), e->type->toChars());
5589 // Must match already deduced value
5590 Expression
*e
= (Expression
*)(*dedtypes
)[i
];
5592 if (!ei
|| !ei
->equals(e
))
5596 (*dedtypes
)[i
] = ei
;
5600 Initializer
*init
= new ExpInitializer(loc
, ei
);
5601 Declaration
*sparam
= new VarDeclaration(loc
, vt
, ident
, init
);
5602 sparam
->storage_class
= STCmanifest
;
5605 return dependent
? MATCHexact
: m
;
5608 //printf("\tno match\n");
5611 return MATCHnomatch
;
5615 void TemplateValueParameter::print(RootObject
*, RootObject
*oded
)
5617 printf(" %s\n", ident
->toChars());
5619 Expression
*ea
= isExpression(oded
);
5622 printf("\tSpecialization: %s\n", specValue
->toChars());
5623 printf("\tParameter Value: %s\n", ea
? ea
->toChars() : "NULL");
5626 void *TemplateValueParameter::dummyArg()
5628 Expression
*e
= specValue
;
5631 // Create a dummy value
5632 Expression
**pe
= (Expression
**)dmd_aaGet(&edummies
, (void *)valType
);
5634 *pe
= valType
->defaultInit();
5641 RootObject
*TemplateValueParameter::specialization()
5646 RootObject
*TemplateValueParameter::defaultArg(Loc instLoc
, Scope
*sc
)
5648 Expression
*e
= defaultValue
;
5651 e
= e
->syntaxCopy();
5652 if ((e
= ::semantic(e
, sc
)) == NULL
)
5654 if ((e
= resolveProperties(sc
, e
)) == NULL
)
5656 e
= e
->resolveLoc(instLoc
, sc
); // use the instantiated loc
5657 e
= e
->optimize(WANTvalue
);
5662 bool TemplateValueParameter::hasDefaultArg()
5664 return defaultValue
!= NULL
;
5667 /* ======================== TemplateTupleParameter ========================== */
5669 // variadic-parameter
5671 TemplateTupleParameter::TemplateTupleParameter(Loc loc
, Identifier
*ident
)
5672 : TemplateParameter(loc
, ident
)
5674 this->ident
= ident
;
5677 TemplateTupleParameter
*TemplateTupleParameter::isTemplateTupleParameter()
5682 TemplateParameter
*TemplateTupleParameter::syntaxCopy()
5684 return new TemplateTupleParameter(loc
, ident
);
5687 bool TemplateTupleParameter::declareParameter(Scope
*sc
)
5689 TypeIdentifier
*ti
= new TypeIdentifier(loc
, ident
);
5690 Declaration
*ad
= new AliasDeclaration(loc
, ident
, ti
);
5691 return sc
->insert(ad
) != NULL
;
5694 bool TemplateTupleParameter::semantic(Scope
*, TemplateParameters
*)
5699 MATCH
TemplateTupleParameter::matchArg(Loc
, Scope
*sc
, Objects
*tiargs
,
5700 size_t i
, TemplateParameters
*parameters
, Objects
*dedtypes
,
5701 Declaration
**psparam
)
5703 /* The rest of the actual arguments (tiargs[]) form the match
5704 * for the variadic parameter.
5706 assert(i
+ 1 == dedtypes
->dim
); // must be the last one
5709 if (Tuple
*u
= isTuple((*dedtypes
)[i
]))
5711 // It has already been deduced
5714 else if (i
+ 1 == tiargs
->dim
&& isTuple((*tiargs
)[i
]))
5715 ovar
= isTuple((*tiargs
)[i
]);
5719 //printf("ovar = %p\n", ovar);
5720 if (i
< tiargs
->dim
)
5722 //printf("i = %d, tiargs->dim = %d\n", i, tiargs->dim);
5723 ovar
->objects
.setDim(tiargs
->dim
- i
);
5724 for (size_t j
= 0; j
< ovar
->objects
.dim
; j
++)
5725 ovar
->objects
[j
] = (*tiargs
)[i
+ j
];
5728 return matchArg(sc
, ovar
, i
, parameters
, dedtypes
, psparam
);
5731 MATCH
TemplateTupleParameter::matchArg(Scope
*, RootObject
*oarg
,
5732 size_t i
, TemplateParameters
*, Objects
*dedtypes
, Declaration
**psparam
)
5734 //printf("TemplateTupleParameter::matchArg('%s')\n", ident->toChars());
5735 Tuple
*ovar
= isTuple(oarg
);
5737 return MATCHnomatch
;
5740 Tuple
*tup
= isTuple((*dedtypes
)[i
]);
5742 return MATCHnomatch
;
5743 if (!match(tup
, ovar
))
5744 return MATCHnomatch
;
5746 (*dedtypes
)[i
] = ovar
;
5749 *psparam
= new TupleDeclaration(loc
, ident
, &ovar
->objects
);
5750 return dependent
? MATCHexact
: MATCHconvert
;
5754 void TemplateTupleParameter::print(RootObject
*, RootObject
*oded
)
5756 printf(" %s... [", ident
->toChars());
5757 Tuple
*v
= isTuple(oded
);
5760 //printf("|%d| ", v->objects.dim);
5761 for (size_t i
= 0; i
< v
->objects
.dim
; i
++)
5766 RootObject
*o
= v
->objects
[i
];
5768 Dsymbol
*sa
= isDsymbol(o
);
5770 printf("alias: %s", sa
->toChars());
5772 Type
*ta
= isType(o
);
5774 printf("type: %s", ta
->toChars());
5776 Expression
*ea
= isExpression(o
);
5778 printf("exp: %s", ea
->toChars());
5780 assert(!isTuple(o
)); // no nested Tuple arguments
5786 void *TemplateTupleParameter::dummyArg()
5792 RootObject
*TemplateTupleParameter::specialization()
5797 RootObject
*TemplateTupleParameter::defaultArg(Loc
, Scope
*)
5802 bool TemplateTupleParameter::hasDefaultArg()
5807 /* ======================== TemplateInstance ================================ */
5809 TemplateInstance::TemplateInstance(Loc loc
, Identifier
*ident
)
5810 : ScopeDsymbol(NULL
)
5814 this->tiargs
= NULL
;
5815 this->tempdecl
= NULL
;
5820 this->deferred
= NULL
;
5821 this->memberOf
= NULL
;
5822 this->argsym
= NULL
;
5823 this->aliasdecl
= NULL
;
5824 this->semantictiargsdone
= false;
5827 this->havetempdecl
= false;
5828 this->enclosing
= NULL
;
5829 this->gagged
= false;
5835 * This constructor is only called when we figured out which function
5836 * template to instantiate.
5839 TemplateInstance::TemplateInstance(Loc loc
, TemplateDeclaration
*td
, Objects
*tiargs
)
5840 : ScopeDsymbol(NULL
)
5843 this->name
= td
->ident
;
5844 this->tiargs
= tiargs
;
5845 this->tempdecl
= td
;
5850 this->deferred
= NULL
;
5851 this->memberOf
= NULL
;
5852 this->argsym
= NULL
;
5853 this->aliasdecl
= NULL
;
5854 this->semantictiargsdone
= true;
5857 this->havetempdecl
= true;
5858 this->enclosing
= NULL
;
5859 this->gagged
= false;
5863 assert(tempdecl
->_scope
);
5867 Objects
*TemplateInstance::arraySyntaxCopy(Objects
*objs
)
5873 a
->setDim(objs
->dim
);
5874 for (size_t i
= 0; i
< objs
->dim
; i
++)
5875 (*a
)[i
] = objectSyntaxCopy((*objs
)[i
]);
5880 Dsymbol
*TemplateInstance::syntaxCopy(Dsymbol
*s
)
5882 TemplateInstance
*ti
=
5883 s
? (TemplateInstance
*)s
5884 : new TemplateInstance(loc
, name
);
5885 ti
->tiargs
= arraySyntaxCopy(tiargs
);
5886 TemplateDeclaration
*td
;
5887 if (inst
&& tempdecl
&& (td
= tempdecl
->isTemplateDeclaration()) != NULL
)
5888 td
->ScopeDsymbol::syntaxCopy(ti
);
5890 ScopeDsymbol::syntaxCopy(ti
);
5894 void TemplateInstance::semantic(Scope
*sc
)
5899 void TemplateInstance::expandMembers(Scope
*sc2
)
5901 for (size_t i
= 0; i
< members
->dim
; i
++)
5903 Dsymbol
*s
= (*members
)[i
];
5907 for (size_t i
= 0; i
< members
->dim
; i
++)
5909 Dsymbol
*s
= (*members
)[i
];
5913 for (size_t i
= 0; i
< members
->dim
; i
++)
5915 Dsymbol
*s
= (*members
)[i
];
5916 //printf("\t[%d] semantic on '%s' %p kind %s in '%s'\n", i, s->toChars(), s, s->kind(), this->toChars());
5917 //printf("test: enclosing = %d, sc2->parent = %s\n", enclosing, sc2->parent->toChars());
5919 // s->parent = sc->parent;
5920 //printf("test3: enclosing = %d, s->parent = %s\n", enclosing, s->parent->toChars());
5922 //printf("test4: enclosing = %d, s->parent = %s\n", enclosing, s->parent->toChars());
5923 Module::runDeferredSemantic();
5927 void TemplateInstance::tryExpandMembers(Scope
*sc2
)
5930 // extracted to a function to allow windows SEH to work without destructors in the same function
5931 //printf("%d\n", nest);
5934 global
.gag
= 0; // ensure error message gets printed
5935 error("recursive expansion");
5944 void TemplateInstance::trySemantic3(Scope
*sc2
)
5946 // extracted to a function to allow windows SEH to work without destructors in the same function
5948 //printf("%d\n", nest);
5951 global
.gag
= 0; // ensure error message gets printed
5952 error("recursive expansion");
5960 void TemplateInstance::semantic(Scope
*sc
, Expressions
*fargs
)
5962 //printf("[%s] TemplateInstance::semantic('%s', this=%p, gag = %d, sc = %p)\n", loc.toChars(), toChars(), this, global.gag, sc);
5963 if (inst
) // if semantic() was already run
5967 if (semanticRun
!= PASSinit
)
5969 Ungag
ungag(global
.gag
);
5972 error(loc
, "recursive template expansion");
5974 semanticRun
= PASSinit
;
5981 // Get the enclosing template instance from the scope tinst
5984 // Get the instantiating module from the scope minst
5986 // Bugzilla 10920: If the enclosing function is non-root symbol,
5987 // this instance should be speculative.
5988 if (!tinst
&& sc
->func
&& sc
->func
->inNonRoot())
5993 gagged
= (global
.gag
> 0);
5995 semanticRun
= PASSsemantic
;
5997 /* Find template declaration first,
5998 * then run semantic on each argument (place results in tiargs[]),
5999 * last find most specialized template from overload list/set.
6001 if (!findTempDecl(sc
, NULL
) ||
6002 !semanticTiargs(sc
) ||
6003 !findBestMatch(sc
, fargs
))
6008 // Bugzilla 13220: Rollback status for later semantic re-running.
6009 semanticRun
= PASSinit
;
6016 TemplateDeclaration
*tempdecl
= this->tempdecl
->isTemplateDeclaration();
6019 // If tempdecl is a mixin, disallow it
6020 if (tempdecl
->ismixin
)
6022 error("mixin templates are not regular templates");
6026 hasNestedArgs(tiargs
, tempdecl
->isstatic
);
6030 /* See if there is an existing TemplateInstantiation that already
6031 * implements the typeargs. If so, just refer to that one instead.
6033 inst
= tempdecl
->findExistingInstance(this, fargs
);
6034 TemplateInstance
*errinst
= NULL
;
6037 // So, we need to implement 'this' instance.
6039 else if (inst
->gagged
&& !gagged
&& inst
->errors
)
6041 // If the first instantiation had failed, re-run semantic,
6042 // so that error messages are shown.
6048 parent
= inst
->parent
;
6049 errors
= inst
->errors
;
6051 // If both this and the previous instantiation were gagged,
6052 // use the number of errors that happened last time.
6053 global
.errors
+= errors
;
6054 global
.gaggedErrors
+= errors
;
6056 // If the first instantiation was gagged, but this is not:
6059 // It had succeeded, mark it is a non-gagged instantiation,
6061 inst
->gagged
= gagged
;
6064 this->tnext
= inst
->tnext
;
6067 /* A module can have explicit template instance and its alias
6068 * in module scope (e,g, `alias Base64 = Base64Impl!('+', '/');`).
6069 * If the first instantiation 'inst' had happened in non-root module,
6070 * compiler can assume that its instantiated code would be included
6071 * in the separately compiled obj/lib file (e.g. phobos.lib).
6073 * However, if 'this' second instantiation happened in root module,
6074 * compiler might need to invoke its codegen (Bugzilla 2500 & 2644).
6075 * But whole import graph is not determined until all semantic pass finished,
6076 * so 'inst' should conservatively finish the semantic3 pass for the codegen.
6078 if (minst
&& minst
->isRoot() && !(inst
->minst
&& inst
->minst
->isRoot()))
6080 /* Swap the position of 'inst' and 'this' in the instantiation graph.
6081 * Then, the primary instance `inst` will be changed to a root instance.
6084 * non-root -> A!() -> B!()[inst] -> C!()
6086 * root -> D!() -> B!()[this]
6089 * non-root -> A!() -> B!()[this]
6091 * root -> D!() -> B!()[inst] -> C!()
6094 TemplateInstance
*ti
= tinst
;
6095 minst
= inst
->minst
;
6096 tinst
= inst
->tinst
;
6100 if (minst
) // if inst was not speculative
6102 /* Add 'inst' once again to the root module members[], then the
6103 * instance members will get codegen chances.
6105 inst
->appendToModuleMember();
6111 unsigned errorsave
= global
.errors
;
6114 parent
= enclosing
? enclosing
: tempdecl
->parent
;
6115 //printf("parent = '%s'\n", parent->kind());
6117 TemplateInstance
*tempdecl_instance_idx
= tempdecl
->addInstance(this);
6121 // Store the place we added it to in target_symbol_list(_idx) so we can
6122 // remove it later if we encounter an error.
6123 Dsymbols
*target_symbol_list
= appendToModuleMember();
6124 size_t target_symbol_list_idx
= target_symbol_list
? target_symbol_list
->dim
- 1 : 0;
6126 // Copy the syntax trees from the TemplateDeclaration
6127 members
= Dsymbol::arraySyntaxCopy(tempdecl
->members
);
6129 // resolve TemplateThisParameter
6130 for (size_t i
= 0; i
< tempdecl
->parameters
->dim
; i
++)
6132 if ((*tempdecl
->parameters
)[i
]->isTemplateThisParameter() == NULL
)
6134 Type
*t
= isType((*tiargs
)[i
]);
6136 if (StorageClass stc
= ModToStc(t
->mod
))
6138 //printf("t = %s, stc = x%llx\n", t->toChars(), stc);
6139 Dsymbols
*s
= new Dsymbols();
6140 s
->push(new StorageClassDeclaration(stc
, members
));
6146 // Create our own scope for the template parameters
6147 Scope
*scope
= tempdecl
->_scope
;
6148 if (tempdecl
->semanticRun
== PASSinit
)
6150 error("template instantiation %s forward references template declaration %s", toChars(), tempdecl
->toChars());
6154 argsym
= new ScopeDsymbol();
6155 argsym
->parent
= scope
->parent
;
6156 scope
= scope
->push(argsym
);
6157 scope
->tinst
= this;
6158 scope
->minst
= minst
;
6161 // Declare each template parameter as an alias for the argument type
6162 Scope
*paramscope
= scope
->push();
6163 paramscope
->stc
= 0;
6164 paramscope
->protection
= Prot(PROTpublic
); // Bugzilla 14169: template parameters should be public
6165 declareParameters(paramscope
);
6168 // Add members of template instance to template instance symbol table
6169 // parent = scope->scopesym;
6170 symtab
= new DsymbolTable();
6171 for (size_t i
= 0; i
< members
->dim
; i
++)
6173 Dsymbol
*s
= (*members
)[i
];
6174 s
->addMember(scope
, this);
6177 /* See if there is only one member of template instance, and that
6178 * member has the same name as the template instance.
6179 * If so, this template instance becomes an alias for that member.
6181 //printf("members->dim = %d\n", members->dim);
6185 if (Dsymbol::oneMembers(members
, &s
, tempdecl
->ident
) && s
)
6187 //printf("tempdecl->ident = %s, s = '%s'\n", tempdecl->ident->toChars(), s->kind(), s->toPrettyChars());
6188 //printf("setting aliasdecl\n");
6193 /* If function template declaration
6195 if (fargs
&& aliasdecl
)
6197 FuncDeclaration
*fd
= aliasdecl
->isFuncDeclaration();
6200 /* Transmit fargs to type so that TypeFunction::semantic() can
6201 * resolve any "auto ref" storage classes.
6203 TypeFunction
*tf
= (TypeFunction
*)fd
->type
;
6204 if (tf
&& tf
->ty
== Tfunction
)
6209 // Do semantic() analysis on template instance members
6211 sc2
= scope
->push(this);
6212 //printf("enclosing = %d, sc->parent = %s\n", enclosing, sc->parent->toChars());
6217 tryExpandMembers(sc2
);
6219 semanticRun
= PASSsemanticdone
;
6221 /* ConditionalDeclaration may introduce eponymous declaration,
6222 * so we should find it once again after semantic.
6227 if (Dsymbol::oneMembers(members
, &s
, tempdecl
->ident
) && s
)
6229 if (!aliasdecl
|| aliasdecl
!= s
)
6231 //printf("tempdecl->ident = %s, s = '%s'\n", tempdecl->ident->toChars(), s->kind(), s->toPrettyChars());
6232 //printf("setting aliasdecl 2\n");
6238 if (global
.errors
!= errorsave
)
6239 goto Laftersemantic
;
6241 /* If any of the instantiation members didn't get semantic() run
6242 * on them due to forward references, we cannot run semantic2()
6243 * or semantic3() yet.
6246 bool found_deferred_ad
= false;
6247 for (size_t i
= 0; i
< Module::deferred
.dim
; i
++)
6249 Dsymbol
*sd
= Module::deferred
[i
];
6250 AggregateDeclaration
*ad
= sd
->isAggregateDeclaration();
6251 if (ad
&& ad
->parent
&& ad
->parent
->isTemplateInstance())
6253 //printf("deferred template aggregate: %s %s\n",
6254 // sd->parent->toChars(), sd->toChars());
6255 found_deferred_ad
= true;
6256 if (ad
->parent
== this)
6258 ad
->deferred
= this;
6263 if (found_deferred_ad
|| Module::deferred
.dim
)
6264 goto Laftersemantic
;
6267 /* The problem is when to parse the initializer for a variable.
6268 * Perhaps VarDeclaration::semantic() should do it like it does
6269 * for initializers inside a function.
6271 //if (sc->parent->isFuncDeclaration())
6273 /* BUG 782: this has problems if the classes this depends on
6274 * are forward referenced. Find a way to defer semantic()
6279 if (global
.errors
!= errorsave
)
6280 goto Laftersemantic
;
6282 if ((sc
->func
|| (sc
->flags
& SCOPEfullinst
)) && !tinst
)
6284 /* If a template is instantiated inside function, the whole instantiation
6285 * should be done at that position. But, immediate running semantic3 of
6286 * dependent templates may cause unresolved forward reference (Bugzilla 9050).
6287 * To avoid the issue, don't run semantic3 until semantic and semantic2 done.
6289 TemplateInstances deferred
;
6290 this->deferred
= &deferred
;
6292 //printf("Run semantic3 on %s\n", toChars());
6295 for (size_t i
= 0; i
< deferred
.dim
; i
++)
6297 //printf("+ run deferred semantic3 on %s\n", deferred[i]->toChars());
6298 deferred
[i
]->semantic3(NULL
);
6301 this->deferred
= NULL
;
6305 bool doSemantic3
= false;
6306 if (sc
->func
&& aliasdecl
&& aliasdecl
->toAlias()->isFuncDeclaration())
6308 /* Template function instantiation should run semantic3 immediately
6309 * for attribute inference.
6315 /* A lambda function in template arguments might capture the
6316 * instantiated scope context. For the correct context inference,
6317 * all instantiated functions should run the semantic3 immediately.
6318 * See also compilable/test14973.d
6320 for (size_t i
= 0; i
< tdtypes
.dim
; i
++)
6322 RootObject
*oarg
= tdtypes
[i
];
6323 Dsymbol
*s
= getDsymbol(oarg
);
6327 if (TemplateDeclaration
*td
= s
->isTemplateDeclaration())
6331 assert(td
->members
&& td
->members
->dim
== 1);
6332 s
= (*td
->members
)[0];
6334 if (FuncLiteralDeclaration
*fld
= s
->isFuncLiteralDeclaration())
6336 if (fld
->tok
== TOKreserved
)
6343 //printf("[%s] %s doSemantic3 = %d\n", loc.toChars(), toChars(), doSemantic3);
6348 TemplateInstance
*ti
= tinst
;
6350 while (ti
&& !ti
->deferred
&& ti
->tinst
)
6355 global
.gag
= 0; // ensure error message gets printed
6356 error("recursive expansion");
6360 if (ti
&& ti
->deferred
)
6362 //printf("deferred semantic3 of %p %s, ti = %s, ti->deferred = %p\n", this, toChars(), ti->toChars());
6363 for (size_t i
= 0; ; i
++)
6365 if (i
== ti
->deferred
->dim
)
6367 ti
->deferred
->push(this);
6370 if ((*ti
->deferred
)[i
] == this)
6378 /* Bugzilla 13816: AliasDeclaration tries to resolve forward reference
6379 * twice (See inuse check in AliasDeclaration::toAlias()). It's
6380 * necessary to resolve mutual references of instantiated symbols, but
6381 * it will left a true recursive alias in tuple declaration - an
6382 * AliasDeclaration A refers TupleDeclaration B, and B contains A
6383 * in its elements. To correctly make it an error, we strictly need to
6384 * resolve the alias of eponymous member.
6386 aliasdecl
= aliasdecl
->toAlias2();
6394 // Give additional context info if error occurred during instantiation
6395 if (global
.errors
!= errorsave
)
6399 if (!tempdecl
->literal
)
6400 error(loc
, "error instantiating");
6402 tinst
->printInstantiationTrace();
6407 // Errors are gagged, so remove the template instance from the
6408 // instance/symbol lists we added it to and reset our state to
6409 // finish clean and so we can try to instantiate it again later
6410 // (see bugzilla 4302 and 6602).
6411 tempdecl
->removeInstance(tempdecl_instance_idx
);
6412 if (target_symbol_list
)
6414 // Because we added 'this' in the last position above, we
6415 // should be able to remove it without messing other indices up.
6416 assert((*target_symbol_list
)[target_symbol_list_idx
] == this);
6417 target_symbol_list
->remove(target_symbol_list_idx
);
6418 memberOf
= NULL
; // no longer a member
6420 semanticRun
= PASSinit
;
6427 /* Bugzilla 14541: If the previous gagged instance had failed by
6428 * circular references, currrent "error reproduction instantiation"
6429 * might succeed, because of the difference of instantiated context.
6430 * On such case, the cached error instance needs to be overridden by the
6431 * succeeded instance.
6433 //printf("replaceInstance()\n");
6434 TemplateInstances
*tinstances
= (TemplateInstances
*)dmd_aaGetRvalue((AA
*)tempdecl
->instances
, (void *)hash
);
6436 for (size_t i
= 0; i
< tinstances
->dim
; i
++)
6438 TemplateInstance
*ti
= (*tinstances
)[i
];
6441 (*tinstances
)[i
] = this; // override
6449 /**********************************************
6450 * Find template declaration corresponding to template instance.
6453 * false if finding fails.
6455 * This function is reentrant against error occurrence. If returns false,
6456 * any members of this object won't be modified, and repetition call will
6457 * reproduce same error.
6460 bool TemplateInstance::findTempDecl(Scope
*sc
, WithScopeSymbol
**pwithsym
)
6468 //printf("TemplateInstance::findTempDecl() %s\n", toChars());
6473 * figure out which TemplateDeclaration foo refers to.
6475 Identifier
*id
= name
;
6477 Dsymbol
*s
= sc
->search(loc
, id
, &scopesym
);
6480 s
= sc
->search_correct(id
);
6482 error("template '%s' is not defined, did you mean %s?", id
->toChars(), s
->toChars());
6484 error("template '%s' is not defined", id
->toChars());
6489 *pwithsym
= scopesym
->isWithScopeSymbol();
6491 /* We might have found an alias within a template when
6492 * we really want the template.
6494 TemplateInstance
*ti
;
6496 (ti
= s
->parent
->isTemplateInstance()) != NULL
)
6498 if (ti
->tempdecl
&& ti
->tempdecl
->ident
== id
)
6500 /* This is so that one can refer to the enclosing
6501 * template, even if it has the same name as a member
6502 * of the template, if it has a !(arguments)
6504 TemplateDeclaration
*td
= ti
->tempdecl
->isTemplateDeclaration();
6506 if (td
->overroot
) // if not start of overloaded list of TemplateDeclaration's
6507 td
= td
->overroot
; // then get the start
6512 if (!updateTempDecl(sc
, s
))
6521 static int fp(void *param
, Dsymbol
*s
)
6523 TemplateDeclaration
*td
= s
->isTemplateDeclaration();
6527 TemplateInstance
*ti
= (TemplateInstance
*)param
;
6528 if (td
->semanticRun
== PASSinit
)
6532 // Try to fix forward reference. Ungag errors while doing so.
6533 Ungag ungag
= td
->ungagSpeculative();
6534 td
->semantic(td
->_scope
);
6536 if (td
->semanticRun
== PASSinit
)
6538 ti
->error("%s forward references template declaration %s", ti
->toChars(), td
->toChars());
6545 // Look for forward references
6546 OverloadSet
*tovers
= tempdecl
->isOverloadSet();
6547 size_t overs_dim
= tovers
? tovers
->a
.dim
: 1;
6548 for (size_t oi
= 0; oi
< overs_dim
; oi
++)
6550 if (overloadApply(tovers
? tovers
->a
[oi
] : tempdecl
, (void *)this, &ParamFwdTi::fp
))
6556 /**********************************************
6557 * Confirm s is a valid template, then store it.
6560 * s candidate symbol of template. It may be:
6561 * TemplateDeclaration
6562 * FuncDeclaration with findTemplateDeclRoot() != NULL
6563 * OverloadSet which contains candidates
6565 * true if updating succeeds.
6568 bool TemplateInstance::updateTempDecl(Scope
*sc
, Dsymbol
*s
)
6572 Identifier
*id
= name
;
6575 /* If an OverloadSet, look for a unique member that is a template declaration
6577 OverloadSet
*os
= s
->isOverloadSet();
6581 for (size_t i
= 0; i
< os
->a
.dim
; i
++)
6583 Dsymbol
*s2
= os
->a
[i
];
6584 if (FuncDeclaration
*f
= s2
->isFuncDeclaration())
6585 s2
= f
->findTemplateDeclRoot();
6587 s2
= s2
->isTemplateDeclaration();
6600 error("template '%s' is not defined", id
->toChars());
6605 OverDeclaration
*od
= s
->isOverDeclaration();
6608 tempdecl
= od
; // TODO: more strict check
6612 /* It should be a TemplateDeclaration, not some other symbol
6614 if (FuncDeclaration
*f
= s
->isFuncDeclaration())
6615 tempdecl
= f
->findTemplateDeclRoot();
6617 tempdecl
= s
->isTemplateDeclaration();
6620 if (!s
->parent
&& global
.errors
)
6622 if (!s
->parent
&& s
->getType())
6624 Dsymbol
*s2
= s
->getType()->toDsymbol(sc
);
6627 error("%s is not a template declaration, it is a %s", id
->toChars(), s
->kind());
6632 //assert(s->parent);
6633 TemplateInstance
*ti
= s
->parent
? s
->parent
->isTemplateInstance() : NULL
;
6635 (ti
->name
== s
->ident
||
6636 ti
->toAlias()->ident
== s
->ident
)
6640 /* This is so that one can refer to the enclosing
6641 * template, even if it has the same name as a member
6642 * of the template, if it has a !(arguments)
6644 TemplateDeclaration
*td
= ti
->tempdecl
->isTemplateDeclaration();
6646 if (td
->overroot
) // if not start of overloaded list of TemplateDeclaration's
6647 td
= td
->overroot
; // then get the start
6652 error("%s is not a template declaration, it is a %s", id
->toChars(), s
->kind());
6657 return (tempdecl
!= NULL
);
6660 /**********************************
6661 * Run semantic on the elements of tiargs.
6665 * false if one or more arguments have errors.
6667 * This function is reentrant against error occurrence. If returns false,
6668 * all elements of tiargs won't be modified.
6671 bool TemplateInstance::semanticTiargs(Scope
*sc
)
6673 //printf("+TemplateInstance::semanticTiargs() %s\n", toChars());
6674 if (semantictiargsdone
)
6676 if (semanticTiargs(loc
, sc
, tiargs
, 0))
6678 // cache the result iff semantic analysis succeeded entirely
6679 semantictiargsdone
= 1;
6685 /**********************************
6686 * Run semantic of tiargs as arguments of template.
6690 * tiargs array of template arguments
6691 * flags 1: replace const variables with their initializers
6692 * 2: don't devolve Parameter to Type
6694 * false if one or more arguments have errors.
6697 bool TemplateInstance::semanticTiargs(Loc loc
, Scope
*sc
, Objects
*tiargs
, int flags
)
6699 // Run semantic on each argument, place results in tiargs[]
6700 //printf("+TemplateInstance::semanticTiargs()\n");
6704 for (size_t j
= 0; j
< tiargs
->dim
; j
++)
6706 RootObject
*o
= (*tiargs
)[j
];
6707 Type
*ta
= isType(o
);
6708 Expression
*ea
= isExpression(o
);
6709 Dsymbol
*sa
= isDsymbol(o
);
6711 //printf("1: (*tiargs)[%d] = %p, s=%p, v=%p, ea=%p, ta=%p\n", j, o, isDsymbol(o), isTuple(o), ea, ta);
6714 //printf("type %s\n", ta->toChars());
6715 // It might really be an Expression or an Alias
6716 ta
->resolve(loc
, sc
, &ea
, &ta
, &sa
);
6721 assert(global
.errors
);
6726 if (ta
->ty
== Ttuple
)
6729 TypeTuple
*tt
= (TypeTuple
*)ta
;
6730 size_t dim
= tt
->arguments
->dim
;
6734 tiargs
->reserve(dim
);
6735 for (size_t i
= 0; i
< dim
; i
++)
6737 Parameter
*arg
= (*tt
->arguments
)[i
];
6738 if (flags
& 2 && arg
->ident
)
6739 tiargs
->insert(j
+ i
, arg
);
6741 tiargs
->insert(j
+ i
, arg
->type
);
6747 if (ta
->ty
== Terror
)
6752 (*tiargs
)[j
] = ta
->merge2();
6757 //printf("+[%d] ea = %s %s\n", j, Token::toChars(ea->op), ea->toChars());
6758 if (flags
& 1) // only used by __traits
6760 ea
= ::semantic(ea
, sc
);
6762 // must not interpret the args, excepting template parameters
6763 if (ea
->op
!= TOKvar
||
6764 (((VarExp
*)ea
)->var
->storage_class
& STCtemplateparameter
))
6766 ea
= ea
->optimize(WANTvalue
);
6771 sc
= sc
->startCTFE();
6772 ea
= ::semantic(ea
, sc
);
6775 if (ea
->op
== TOKvar
)
6777 /* This test is to skip substituting a const var with
6778 * its initializer. The problem is the initializer won't
6779 * match with an 'alias' parameter. Instead, do the
6780 * const substitution in TemplateValueParameter::matchArg().
6783 else if (definitelyValueParameter(ea
))
6785 if (ea
->checkValue()) // check void expression
6786 ea
= new ErrorExp();
6787 unsigned int olderrs
= global
.errors
;
6788 ea
= ea
->ctfeInterpret();
6789 if (global
.errors
!= olderrs
)
6790 ea
= new ErrorExp();
6793 //printf("-[%d] ea = %s %s\n", j, Token::toChars(ea->op), ea->toChars());
6794 if (ea
->op
== TOKtuple
)
6797 TupleExp
*te
= (TupleExp
*)ea
;
6798 size_t dim
= te
->exps
->dim
;
6802 tiargs
->reserve(dim
);
6803 for (size_t i
= 0; i
< dim
; i
++)
6804 tiargs
->insert(j
+ i
, (*te
->exps
)[i
]);
6809 if (ea
->op
== TOKerror
)
6816 if (ea
->op
== TOKtype
)
6821 if (ea
->op
== TOKscope
)
6823 sa
= ((ScopeExp
*)ea
)->sds
;
6826 if (ea
->op
== TOKfunction
)
6828 FuncExp
*fe
= (FuncExp
*)ea
;
6829 /* A function literal, that is passed to template and
6830 * already semanticed as function pointer, never requires
6831 * outer frame. So convert it to global function is valid.
6833 if (fe
->fd
->tok
== TOKreserved
&& fe
->type
->ty
== Tpointer
)
6835 // change to non-nested
6836 fe
->fd
->tok
= TOKfunction
;
6837 fe
->fd
->vthis
= NULL
;
6841 /* If template argument is a template lambda,
6842 * get template declaration itself. */
6847 if (ea
->op
== TOKdotvar
)
6849 // translate expression to dsymbol.
6850 sa
= ((DotVarExp
*)ea
)->var
;
6853 if (ea
->op
== TOKtemplate
)
6855 sa
= ((TemplateExp
*)ea
)->td
;
6858 if (ea
->op
== TOKdottd
)
6860 // translate expression to dsymbol.
6861 sa
= ((DotTemplateExp
*)ea
)->td
;
6868 //printf("dsym %s %s\n", sa->kind(), sa->toChars());
6875 TupleDeclaration
*d
= sa
->toAlias()->isTupleDeclaration();
6880 tiargs
->insert(j
, d
->objects
);
6884 if (FuncAliasDeclaration
*fa
= sa
->isFuncAliasDeclaration())
6886 FuncDeclaration
*f
= fa
->toAliasFunc();
6887 if (!fa
->hasOverloads
&& f
->isUnique())
6889 // Strip FuncAlias only when the aliased function
6890 // does not have any overloads.
6896 TemplateDeclaration
*td
= sa
->isTemplateDeclaration();
6897 if (td
&& td
->semanticRun
== PASSinit
&& td
->literal
)
6901 FuncDeclaration
*fd
= sa
->isFuncDeclaration();
6903 fd
->functionSemantic();
6905 else if (isParameter(o
))
6912 //printf("1: (*tiargs)[%d] = %p\n", j, (*tiargs)[j]);
6917 bool TemplateInstance::findBestMatch(Scope
*sc
, Expressions
*fargs
)
6921 TemplateDeclaration
*tempdecl
= this->tempdecl
->isTemplateDeclaration();
6923 assert(tempdecl
->_scope
);
6925 tdtypes
.setDim(tempdecl
->parameters
->dim
);
6926 if (!tempdecl
->matchWithInstance(sc
, this, &tdtypes
, fargs
, 2))
6928 error("incompatible arguments for template instantiation");
6931 // TODO: Normalizing tiargs for bugzilla 7469 is necessary?
6935 unsigned errs
= global
.errors
;
6941 TemplateInstance
*ti
;
6944 TemplateDeclaration
*td_best
;
6945 TemplateDeclaration
*td_ambig
;
6948 static int fp(void *param
, Dsymbol
*s
)
6950 return ((ParamBest
*)param
)->fp(s
);
6954 TemplateDeclaration
*td
= s
->isTemplateDeclaration();
6958 if (td
== td_best
) // skip duplicates
6961 //printf("td = %s\n", td->toPrettyChars());
6963 // If more arguments than parameters,
6964 // then this is no match.
6965 if (td
->parameters
->dim
< ti
->tiargs
->dim
)
6967 if (!td
->isVariadic())
6971 dedtypes
.setDim(td
->parameters
->dim
);
6973 assert(td
->semanticRun
!= PASSinit
);
6974 MATCH m
= td
->matchWithInstance(sc
, ti
, &dedtypes
, ti
->fargs
, 0);
6975 //printf("matchWithInstance = %d\n", m);
6976 if (m
<= MATCHnomatch
) // no match at all
6979 if (m
< m_best
) goto Ltd_best
;
6980 if (m
> m_best
) goto Ltd
;
6983 // Disambiguate by picking the most specialized TemplateDeclaration
6984 MATCH c1
= td
->leastAsSpecialized(sc
, td_best
, ti
->fargs
);
6985 MATCH c2
= td_best
->leastAsSpecialized(sc
, td
, ti
->fargs
);
6986 //printf("c1 = %d, c2 = %d\n", c1, c2);
6987 if (c1
> c2
) goto Ltd
;
6988 if (c1
< c2
) goto Ltd_best
;
6994 Ltd_best
: // td_best is the best match so far
6998 Ltd
: // td is the new best match
7002 ti
->tdtypes
.setDim(dedtypes
.dim
);
7003 memcpy(ti
->tdtypes
.tdata(), dedtypes
.tdata(), ti
->tdtypes
.dim
* sizeof(void *));
7012 /* Since there can be multiple TemplateDeclaration's with the same
7013 * name, look for the best match.
7015 TemplateDeclaration
*td_last
= NULL
;
7017 OverloadSet
*tovers
= tempdecl
->isOverloadSet();
7018 size_t overs_dim
= tovers
? tovers
->a
.dim
: 1;
7019 for (size_t oi
= 0; oi
< overs_dim
; oi
++)
7024 p
.m_best
= MATCHnomatch
;
7025 overloadApply(tovers
? tovers
->a
[oi
] : tempdecl
, &p
, &ParamBest::fp
);
7029 ::error(loc
, "%s %s.%s matches more than one template declaration:\n%s: %s\nand\n%s: %s",
7030 p
.td_best
->kind(), p
.td_best
->parent
->toPrettyChars(), p
.td_best
->ident
->toChars(),
7031 p
.td_best
->loc
.toChars() , p
.td_best
->toChars(),
7032 p
.td_ambig
->loc
.toChars(), p
.td_ambig
->toChars());
7038 td_last
= p
.td_best
;
7039 else if (td_last
!= p
.td_best
)
7041 ScopeDsymbol::multiplyDefined(loc
, td_last
, p
.td_best
);
7049 /* Bugzilla 7469: Normalize tiargs by using corresponding deduced
7050 * template value parameters and tuples for the correct mangling.
7052 * By doing this before hasNestedArgs, CTFEable local variable will be
7053 * accepted as a value parameter. For example:
7056 * struct S(int n) {} // non-global template
7057 * const int num = 1; // CTFEable local variable
7058 * S!num s; // S!1 is instantiated, not S!num
7061 size_t dim
= td_last
->parameters
->dim
- (td_last
->isVariadic() ? 1 : 0);
7062 for (size_t i
= 0; i
< dim
; i
++)
7064 if (tiargs
->dim
<= i
)
7065 tiargs
->push(tdtypes
[i
]);
7066 assert(i
< tiargs
->dim
);
7068 TemplateValueParameter
*tvp
= (*td_last
->parameters
)[i
]->isTemplateValueParameter();
7072 // tdtypes[i] is already normalized to the required type in matchArg
7074 (*tiargs
)[i
] = tdtypes
[i
];
7076 if (td_last
->isVariadic() && tiargs
->dim
== dim
&& tdtypes
[dim
])
7078 Tuple
*va
= isTuple(tdtypes
[dim
]);
7080 for (size_t i
= 0; i
< va
->objects
.dim
; i
++)
7081 tiargs
->push(va
->objects
[i
]);
7084 else if (errors
&& inst
)
7086 // instantiation was failed with error reporting
7087 assert(global
.errors
);
7092 TemplateDeclaration
*tdecl
= tempdecl
->isTemplateDeclaration();
7094 if (errs
!= global
.errors
)
7095 errorSupplemental(loc
, "while looking for match for %s", toChars());
7096 else if (tdecl
&& !tdecl
->overnext
)
7098 // Only one template, so we can give better error message
7099 error("does not match template declaration %s", tdecl
->toChars());
7102 ::error(loc
, "%s %s.%s does not match any template declaration",
7103 tempdecl
->kind(), tempdecl
->parent
->toPrettyChars(), tempdecl
->ident
->toChars());
7107 /* The best match is td_last
7111 return (errs
== global
.errors
);
7114 /*****************************************************
7115 * Determine if template instance is really a template function,
7116 * and that template function needs to infer types from the function
7119 * Like findBestMatch, iterate possible template candidates,
7120 * but just looks only the necessity of type inference.
7123 bool TemplateInstance::needsTypeInference(Scope
*sc
, int flag
)
7125 //printf("TemplateInstance::needsTypeInference() %s\n", toChars());
7126 if (semanticRun
!= PASSinit
)
7129 struct ParamNeedsInf
7133 TemplateInstance
*ti
;
7139 static int fp(void *param
, Dsymbol
*s
)
7141 return ((ParamNeedsInf
*)param
)->fp(s
);
7145 TemplateDeclaration
*td
= s
->isTemplateDeclaration();
7151 /* If any of the overloaded template declarations need inference,
7154 FuncDeclaration
*fd
;
7157 if (TemplateDeclaration
*td2
= td
->onemember
->isTemplateDeclaration())
7159 if (!td2
->onemember
|| !td2
->onemember
->isFuncDeclaration())
7161 if (ti
->tiargs
->dim
>= td
->parameters
->dim
- (td
->isVariadic() ? 1 : 0))
7165 if ((fd
= td
->onemember
->isFuncDeclaration()) == NULL
||
7166 fd
->type
->ty
!= Tfunction
)
7171 for (size_t i
= 0; i
< td
->parameters
->dim
; i
++)
7173 if ((*td
->parameters
)[i
]->isTemplateThisParameter())
7177 /* Determine if the instance arguments, tiargs, are all that is necessary
7178 * to instantiate the template.
7180 //printf("tp = %p, td->parameters->dim = %d, tiargs->dim = %d\n", tp, td->parameters->dim, ti->tiargs->dim);
7181 TypeFunction
*tf
= (TypeFunction
*)fd
->type
;
7182 if (size_t dim
= Parameter::dim(tf
->parameters
))
7184 TemplateParameter
*tp
= td
->isVariadic();
7185 if (tp
&& td
->parameters
->dim
> 1)
7188 if (!tp
&& ti
->tiargs
->dim
< td
->parameters
->dim
)
7190 // Can remain tiargs be filled by default arguments?
7191 for (size_t i
= ti
->tiargs
->dim
; i
< td
->parameters
->dim
; i
++)
7193 if (!(*td
->parameters
)[i
]->hasDefaultArg())
7198 for (size_t i
= 0; i
< dim
; i
++)
7200 // 'auto ref' needs inference.
7201 if (Parameter::getNth(tf
->parameters
, i
)->storageClass
& STCauto
)
7208 /* Calculate the need for overload resolution.
7209 * When only one template can match with tiargs, inference is not necessary.
7211 dedtypes
.setDim(td
->parameters
->dim
);
7213 if (td
->semanticRun
== PASSinit
)
7217 // Try to fix forward reference. Ungag errors while doing so.
7218 Ungag ungag
= td
->ungagSpeculative();
7219 td
->semantic(td
->_scope
);
7221 if (td
->semanticRun
== PASSinit
)
7223 ti
->error("%s forward references template declaration %s", ti
->toChars(), td
->toChars());
7227 assert(td
->semanticRun
!= PASSinit
);
7228 MATCH m
= td
->matchWithInstance(sc
, ti
, &dedtypes
, NULL
, 0);
7229 if (m
<= MATCHnomatch
)
7233 /* If there is more than one function template which matches, we may
7234 * need type inference (see Bugzilla 4430)
7250 OverloadSet
*tovers
= tempdecl
->isOverloadSet();
7251 size_t overs_dim
= tovers
? tovers
->a
.dim
: 1;
7252 unsigned olderrs
= global
.errors
;
7253 for (size_t oi
= 0; oi
< overs_dim
; oi
++)
7255 if (overloadApply(tovers
? tovers
->a
[oi
] : tempdecl
, &p
, &ParamNeedsInf::fp
))
7258 if (olderrs
!= global
.errors
)
7262 errorSupplemental(loc
, "while looking for match for %s", toChars());
7263 semanticRun
= PASSsemanticdone
;
7268 //printf("false\n");
7273 /*****************************************
7274 * Determines if a TemplateInstance will need a nested
7275 * generation of the TemplateDeclaration.
7276 * Sets enclosing property if so, and returns != 0;
7279 bool TemplateInstance::hasNestedArgs(Objects
*args
, bool isstatic
)
7282 //printf("TemplateInstance::hasNestedArgs('%s')\n", tempdecl->ident->toChars());
7284 /* A nested instance happens when an argument references a local
7285 * symbol that is on the stack.
7287 for (size_t i
= 0; i
< args
->dim
; i
++)
7289 RootObject
*o
= (*args
)[i
];
7290 Expression
*ea
= isExpression(o
);
7291 Dsymbol
*sa
= isDsymbol(o
);
7292 Tuple
*va
= isTuple(o
);
7295 if (ea
->op
== TOKvar
)
7297 sa
= ((VarExp
*)ea
)->var
;
7300 if (ea
->op
== TOKthis
)
7302 sa
= ((ThisExp
*)ea
)->var
;
7305 if (ea
->op
== TOKfunction
)
7307 if (((FuncExp
*)ea
)->td
)
7308 sa
= ((FuncExp
*)ea
)->td
;
7310 sa
= ((FuncExp
*)ea
)->fd
;
7313 // Emulate Expression::toMangleBuffer call that had exist in TemplateInstance::genIdent.
7314 if (ea
->op
!= TOKint64
&&
7315 ea
->op
!= TOKfloat64
&&
7316 ea
->op
!= TOKcomplex80
&&
7317 ea
->op
!= TOKnull
&&
7318 ea
->op
!= TOKstring
&&
7319 ea
->op
!= TOKarrayliteral
&&
7320 ea
->op
!= TOKassocarrayliteral
&&
7321 ea
->op
!= TOKstructliteral
)
7323 ea
->error("expression %s is not a valid template value argument", ea
->toChars());
7331 TemplateDeclaration
*td
= sa
->isTemplateDeclaration();
7334 TemplateInstance
*ti
= sa
->toParent()->isTemplateInstance();
7335 if (ti
&& ti
->enclosing
)
7338 TemplateInstance
*ti
= sa
->isTemplateInstance();
7339 Declaration
*d
= sa
->isDeclaration();
7340 if ((td
&& td
->literal
) ||
7341 (ti
&& ti
->enclosing
) ||
7342 (d
&& !d
->isDataseg() &&
7343 !(d
->storage_class
& STCmanifest
) &&
7344 (!d
->isFuncDeclaration() || d
->isFuncDeclaration()->isNested()) &&
7348 // if module level template
7351 Dsymbol
*dparent
= sa
->toParent2();
7353 enclosing
= dparent
;
7354 else if (enclosing
!= dparent
)
7356 /* Select the more deeply nested of the two.
7357 * Error if one is not nested inside the other.
7359 for (Dsymbol
*p
= enclosing
; p
; p
= p
->parent
)
7362 goto L1
; // enclosing is most nested
7364 for (Dsymbol
*p
= dparent
; p
; p
= p
->parent
)
7368 enclosing
= dparent
;
7369 goto L1
; // dparent is most nested
7372 error("%s is nested in both %s and %s",
7373 toChars(), enclosing
->toChars(), dparent
->toChars());
7377 //printf("\tnested inside %s\n", enclosing->toChars());
7382 error("cannot use local '%s' as parameter to non-global template %s", sa
->toChars(), tempdecl
->toChars());
7389 nested
|= (int)hasNestedArgs(&va
->objects
, isstatic
);
7392 //printf("-TemplateInstance::hasNestedArgs('%s') = %d\n", tempdecl->ident->toChars(), nested);
7396 /*****************************************
7397 * Append 'this' to the specific module members[]
7399 Dsymbols
*TemplateInstance::appendToModuleMember()
7401 Module
*mi
= minst
; // instantiated -> inserted module
7403 if (global
.params
.useUnitTests
||
7404 global
.params
.debuglevel
)
7406 // Turn all non-root instances to speculative
7407 if (mi
&& !mi
->isRoot())
7411 //printf("%s->appendToModuleMember() enclosing = %s mi = %s\n",
7413 // enclosing ? enclosing->toPrettyChars() : NULL,
7414 // mi ? mi->toPrettyChars() : NULL);
7415 if (!mi
|| mi
->isRoot())
7417 /* If the instantiated module is speculative or root, insert to the
7418 * member of a root module. Then:
7419 * - semantic3 pass will get called on the instance members.
7420 * - codegen pass will get a selection chance to do/skip it.
7425 static Dsymbol
*getStrictEnclosing(TemplateInstance
*ti
)
7430 return ti
->enclosing
;
7431 ti
= ti
->tempdecl
->isInstantiated();
7437 Dsymbol
*enc
= N::getStrictEnclosing(this);
7439 // insert target is made stable by using the module
7440 // where tempdecl is declared.
7441 mi
= (enc
? enc
: tempdecl
)->getModule();
7443 mi
= mi
->importedFrom
;
7444 assert(mi
->isRoot());
7448 /* If the instantiated module is non-root, insert to the member of the
7449 * non-root module. Then:
7450 * - semantic3 pass won't be called on the instance.
7451 * - codegen pass won't reach to the instance.
7454 //printf("\t--> mi = %s\n", mi->toPrettyChars());
7456 if (memberOf
== mi
) // already a member
7461 Dsymbols
*a
= mi
->members
;
7464 if (mi
->semanticRun
>= PASSsemantic2done
&& mi
->isRoot())
7465 Module::addDeferredSemantic2(this);
7466 if (mi
->semanticRun
>= PASSsemantic3done
&& mi
->isRoot())
7467 Module::addDeferredSemantic3(this);
7471 /****************************************
7472 * This instance needs an identifier for name mangling purposes.
7473 * Create one by taking the template declaration name and adding
7474 * the type signature for it.
7477 Identifier
*TemplateInstance::genIdent(Objects
*args
)
7479 TemplateDeclaration
*tempdecl
= this->tempdecl
->isTemplateDeclaration();
7482 //printf("TemplateInstance::genIdent('%s')\n", tempdecl->ident->toChars());
7484 const char *id
= tempdecl
->ident
->toChars();
7487 // Use "__U" for the symbols declared inside template constraint.
7488 buf
.printf("__U%llu%s", (ulonglong
)strlen(id
), id
);
7491 buf
.printf("__T%llu%s", (ulonglong
)strlen(id
), id
);
7492 size_t nparams
= tempdecl
->parameters
->dim
- (tempdecl
->isVariadic() ? 1 : 0);
7493 for (size_t i
= 0; i
< args
->dim
; i
++)
7495 RootObject
*o
= (*args
)[i
];
7496 Type
*ta
= isType(o
);
7497 Expression
*ea
= isExpression(o
);
7498 Dsymbol
*sa
= isDsymbol(o
);
7499 Tuple
*va
= isTuple(o
);
7500 //printf("\to [%d] %p ta %p ea %p sa %p va %p\n", i, o, ta, ea, sa, va);
7501 if (i
< nparams
&& (*tempdecl
->parameters
)[i
]->specialization())
7502 buf
.writeByte('H'); // Bugzilla 6574
7507 buf
.writestring(ta
->deco
);
7510 assert(global
.errors
);
7515 // Don't interpret it yet, it might actually be an alias template parameter.
7516 // Only constfold manifest constants, not const/immutable lvalues, see https://issues.dlang.org/show_bug.cgi?id=17339.
7517 const bool keepLvalue
= true;
7518 ea
= ea
->optimize(WANTvalue
, keepLvalue
);
7519 if (ea
->op
== TOKvar
)
7521 sa
= ((VarExp
*)ea
)->var
;
7525 if (ea
->op
== TOKthis
)
7527 sa
= ((ThisExp
*)ea
)->var
;
7531 if (ea
->op
== TOKfunction
)
7533 if (((FuncExp
*)ea
)->td
)
7534 sa
= ((FuncExp
*)ea
)->td
;
7536 sa
= ((FuncExp
*)ea
)->fd
;
7541 if (ea
->op
== TOKtuple
)
7543 ea
->error("tuple is not a valid template value argument");
7546 // Now that we know it is not an alias, we MUST obtain a value
7547 unsigned olderr
= global
.errors
;
7548 ea
= ea
->ctfeInterpret();
7549 if (ea
->op
== TOKerror
|| olderr
!= global
.errors
)
7552 /* Use deco that matches what it would be for a function parameter
7554 buf
.writestring(ea
->type
->deco
);
7555 mangleToBuffer(ea
, &buf
);
7562 Declaration
*d
= sa
->isDeclaration();
7563 if (d
&& (!d
->type
|| !d
->type
->deco
))
7565 error("forward reference of %s %s", d
->kind(), d
->toChars());
7570 mangleToBuffer(sa
, &bufsa
);
7571 const char *s
= bufsa
.extractString();
7573 /* Bugzilla 3043: if the first character of s is a digit this
7574 * causes ambiguity issues because the digits of the two numbers are adjacent.
7575 * Current demanglers resolve this by trying various places to separate the
7576 * numbers until one gets a successful demangle.
7577 * Unfortunately, fixing this ambiguity will break existing binary
7578 * compatibility and the demanglers, so we'll leave it as is.
7580 buf
.printf("%u%s", (unsigned)strlen(s
), s
);
7584 assert(i
+ 1 == args
->dim
); // must be last one
7585 args
= &va
->objects
;
7592 id
= buf
.peekString();
7593 //printf("\tgenIdent = %s\n", id);
7594 return Identifier::idPool(id
);
7597 /*************************************
7598 * Lazily generate identifier for template instance.
7599 * This is because 75% of the ident's are never needed.
7602 Identifier
*TemplateInstance::getIdent()
7604 if (!ident
&& inst
&& !errors
)
7605 ident
= genIdent(tiargs
); // need an identifier for name mangling purposes.
7609 /****************************************************
7610 * Declare parameters of template instance, initialize them with the
7611 * template instance arguments.
7614 void TemplateInstance::declareParameters(Scope
*sc
)
7616 TemplateDeclaration
*tempdecl
= this->tempdecl
->isTemplateDeclaration();
7619 //printf("TemplateInstance::declareParameters()\n");
7620 for (size_t i
= 0; i
< tdtypes
.dim
; i
++)
7622 TemplateParameter
*tp
= (*tempdecl
->parameters
)[i
];
7623 //RootObject *o = (*tiargs)[i];
7624 RootObject
*o
= tdtypes
[i
]; // initializer for tp
7626 //printf("\ttdtypes[%d] = %p\n", i, o);
7627 tempdecl
->declareParameter(sc
, tp
, o
);
7631 void TemplateInstance::semantic2(Scope
*sc
)
7633 if (semanticRun
>= PASSsemantic2
)
7635 semanticRun
= PASSsemantic2
;
7636 if (!errors
&& members
)
7638 TemplateDeclaration
*tempdecl
= this->tempdecl
->isTemplateDeclaration();
7641 sc
= tempdecl
->_scope
;
7643 sc
= sc
->push(argsym
);
7644 sc
= sc
->push(this);
7648 int needGagging
= (gagged
&& !global
.gag
);
7649 unsigned int olderrors
= global
.errors
;
7650 int oldGaggedErrors
= -1; // dead-store to prevent spurious warning
7652 oldGaggedErrors
= global
.startGagging();
7654 for (size_t i
= 0; i
< members
->dim
; i
++)
7656 Dsymbol
*s
= (*members
)[i
];
7658 if (gagged
&& global
.errors
!= olderrors
)
7662 if (global
.errors
!= olderrors
)
7666 if (!tempdecl
->literal
)
7667 error(loc
, "error instantiating");
7669 tinst
->printInstantiationTrace();
7674 global
.endGagging(oldGaggedErrors
);
7681 void TemplateInstance::semantic3(Scope
*sc
)
7683 //if (toChars()[0] == 'D') *(char*)0=0;
7684 if (semanticRun
>= PASSsemantic3
)
7686 semanticRun
= PASSsemantic3
;
7687 if (!errors
&& members
)
7689 TemplateDeclaration
*tempdecl
= this->tempdecl
->isTemplateDeclaration();
7692 sc
= tempdecl
->_scope
;
7693 sc
= sc
->push(argsym
);
7694 sc
= sc
->push(this);
7698 int needGagging
= (gagged
&& !global
.gag
);
7699 unsigned int olderrors
= global
.errors
;
7700 int oldGaggedErrors
= -1; // dead-store to prevent spurious warning
7701 /* If this is a gagged instantiation, gag errors.
7702 * Future optimisation: If the results are actually needed, errors
7703 * would already be gagged, so we don't really need to run semantic
7707 oldGaggedErrors
= global
.startGagging();
7709 for (size_t i
= 0; i
< members
->dim
; i
++)
7711 Dsymbol
*s
= (*members
)[i
];
7713 if (gagged
&& global
.errors
!= olderrors
)
7717 if (global
.errors
!= olderrors
)
7721 if (!tempdecl
->literal
)
7722 error(loc
, "error instantiating");
7724 tinst
->printInstantiationTrace();
7729 global
.endGagging(oldGaggedErrors
);
7736 /**************************************
7737 * Given an error instantiating the TemplateInstance,
7738 * give the nested TemplateInstance instantiations that got
7739 * us here. Those are a list threaded into the nested scopes.
7741 void TemplateInstance::printInstantiationTrace()
7746 const unsigned max_shown
= 6;
7747 const char format
[] = "instantiated from here: %s";
7749 // determine instantiation depth and number of recursive instantiations
7750 unsigned n_instantiations
= 1;
7751 unsigned n_totalrecursions
= 0;
7752 for (TemplateInstance
*cur
= this; cur
; cur
= cur
->tinst
)
7755 // If two instantiations use the same declaration, they are recursive.
7756 // (this works even if they are instantiated from different places in the
7758 // In principle, we could also check for multiple-template recursion, but it's
7759 // probably not worthwhile.
7760 if (cur
->tinst
&& cur
->tempdecl
&& cur
->tinst
->tempdecl
7761 && cur
->tempdecl
->loc
.equals(cur
->tinst
->tempdecl
->loc
))
7762 ++n_totalrecursions
;
7765 // show full trace only if it's short or verbose is on
7766 if (n_instantiations
<= max_shown
|| global
.params
.verbose
)
7768 for (TemplateInstance
*cur
= this; cur
; cur
= cur
->tinst
)
7771 errorSupplemental(cur
->loc
, format
, cur
->toChars());
7774 else if (n_instantiations
- n_totalrecursions
<= max_shown
)
7776 // By collapsing recursive instantiations into a single line,
7777 // we can stay under the limit.
7778 int recursionDepth
=0;
7779 for (TemplateInstance
*cur
= this; cur
; cur
= cur
->tinst
)
7782 if (cur
->tinst
&& cur
->tempdecl
&& cur
->tinst
->tempdecl
7783 && cur
->tempdecl
->loc
.equals(cur
->tinst
->tempdecl
->loc
))
7790 errorSupplemental(cur
->loc
, "%d recursive instantiations from here: %s", recursionDepth
+2, cur
->toChars());
7792 errorSupplemental(cur
->loc
, format
, cur
->toChars());
7799 // Even after collapsing the recursions, the depth is too deep.
7800 // Just display the first few and last few instantiations.
7802 for (TemplateInstance
*cur
= this; cur
; cur
= cur
->tinst
)
7806 if (i
== max_shown
/ 2)
7807 errorSupplemental(cur
->loc
, "... (%d instantiations, -v to show) ...", n_instantiations
- max_shown
);
7809 if (i
< max_shown
/ 2 ||
7810 i
>= n_instantiations
- max_shown
+ max_shown
/ 2)
7811 errorSupplemental(cur
->loc
, format
, cur
->toChars());
7817 Dsymbol
*TemplateInstance::toAlias()
7821 // Maybe we can resolve it
7828 error("cannot resolve forward reference");
7835 return inst
->toAlias();
7839 return aliasdecl
->toAlias();
7845 const char *TemplateInstance::kind() const
7847 return "template instance";
7850 bool TemplateInstance::oneMember(Dsymbol
**ps
, Identifier
*)
7856 const char *TemplateInstance::toChars()
7859 toCBufferInstance(this, &buf
);
7860 return buf
.extractString();
7863 const char *TemplateInstance::toPrettyCharsHelper()
7866 toCBufferInstance(this, &buf
, true);
7867 return buf
.extractString();
7870 /*************************************
7871 * Compare proposed template instantiation with existing template instantiation.
7872 * Note that this is not commutative because of the auto ref check.
7874 * this = proposed template instantiation
7875 * o = existing template instantiation
7877 * 0 for match, 1 for no match
7879 int TemplateInstance::compare(RootObject
*o
)
7881 TemplateInstance
*ti
= (TemplateInstance
*)o
;
7883 //printf("this = %p, ti = %p\n", this, ti);
7884 assert(tdtypes
.dim
== ti
->tdtypes
.dim
);
7886 // Nesting must match
7887 if (enclosing
!= ti
->enclosing
)
7889 //printf("test2 enclosing %s ti->enclosing %s\n", enclosing ? enclosing->toChars() : "", ti->enclosing ? ti->enclosing->toChars() : "");
7892 //printf("parent = %s, ti->parent = %s\n", parent->toPrettyChars(), ti->parent->toPrettyChars());
7894 if (!arrayObjectMatch(&tdtypes
, &ti
->tdtypes
))
7897 /* Template functions may have different instantiations based on
7898 * "auto ref" parameters.
7900 if (FuncDeclaration
*fd
= ti
->toAlias()->isFuncDeclaration())
7904 Parameters
*fparameters
= fd
->getParameters(NULL
);
7905 size_t nfparams
= Parameter::dim(fparameters
); // Num function parameters
7906 for (size_t j
= 0; j
< nfparams
; j
++)
7908 Parameter
*fparam
= Parameter::getNth(fparameters
, j
);
7909 if (fparam
->storageClass
& STCautoref
) // if "auto ref"
7913 if (fargs
->dim
<= j
)
7915 Expression
*farg
= (*fargs
)[j
];
7916 if (farg
->isLvalue())
7918 if (!(fparam
->storageClass
& STCref
))
7919 goto Lnotequals
; // auto ref's don't match
7923 if (fparam
->storageClass
& STCref
)
7924 goto Lnotequals
; // auto ref's don't match
7936 hash_t
TemplateInstance::toHash()
7940 hash
= (size_t)(void *)enclosing
;
7941 hash
+= arrayObjectHash(&tdtypes
);
7947 /**************************************
7948 * IsExpression can evaluate the specified type speculatively, and even if
7949 * it instantiates any symbols, they are normally unnecessary for the
7951 * However, if those symbols leak to the actual code, compiler should remark
7952 * them as non-speculative to generate their code and link to the final executable.
7954 void unSpeculative(Scope
*sc
, RootObject
*o
)
7959 if (Tuple
*tup
= isTuple(o
))
7961 for (size_t i
= 0; i
< tup
->objects
.dim
; i
++)
7963 unSpeculative(sc
, tup
->objects
[i
]);
7968 Dsymbol
*s
= getDsymbol(o
);
7972 if (Declaration
*d
= s
->isDeclaration())
7974 if (VarDeclaration
*vd
= d
->isVarDeclaration())
7976 else if (AliasDeclaration
*ad
= d
->isAliasDeclaration())
7990 if (TemplateInstance
*ti
= s
->isTemplateInstance())
7992 // If the instance is already non-speculative,
7993 // or it is leaked to the speculative scope.
7994 if (ti
->minst
!= NULL
|| sc
->minst
== NULL
)
7997 // Remark as non-speculative instance.
7998 ti
->minst
= sc
->minst
;
8000 ti
->tinst
= sc
->tinst
;
8002 unSpeculative(sc
, ti
->tempdecl
);
8005 if (TemplateInstance
*ti
= s
->isInstantiated())
8006 unSpeculative(sc
, ti
);
8009 /***********************************************
8010 * Returns true if this is not instantiated in non-root module, and
8011 * is a part of non-speculative instantiatiation.
8013 * Note: minst does not stabilize until semantic analysis is completed,
8014 * so don't call this function during semantic analysis to return precise result.
8016 bool TemplateInstance::needsCodegen()
8018 // Now -allInst is just for the backward compatibility.
8019 if (global
.params
.allInst
)
8021 //printf("%s minst = %s, enclosing (%s)->isNonRoot = %d\n",
8022 // toPrettyChars(), minst ? minst->toChars() : NULL,
8023 // enclosing ? enclosing->toPrettyChars() : NULL, enclosing && enclosing->inNonRoot());
8026 // Bugzilla 14588: If the captured context is not a function
8027 // (e.g. class), the instance layout determination is guaranteed,
8028 // because the semantic/semantic2 pass will be executed
8029 // even for non-root instances.
8030 if (!enclosing
->isFuncDeclaration())
8033 // Bugzilla 14834: If the captured context is a function,
8034 // this excessive instantiation may cause ODR violation, because
8035 // -allInst and others doesn't guarantee the semantic3 execution
8036 // for that function.
8038 // If the enclosing is also an instantiated function,
8039 // we have to rely on the ancestor's needsCodegen() result.
8040 if (TemplateInstance
*ti
= enclosing
->isInstantiated())
8041 return ti
->needsCodegen();
8043 // Bugzilla 13415: If and only if the enclosing scope needs codegen,
8044 // this nested templates would also need code generation.
8045 return !enclosing
->inNonRoot();
8052 // If this is a speculative instantiation,
8053 // 1. do codegen if ancestors really needs codegen.
8054 // 2. become non-speculative if siblings are not speculative
8056 TemplateInstance
*tnext
= this->tnext
;
8057 TemplateInstance
*tinst
= this->tinst
;
8058 // At first, disconnect chain first to prevent infinite recursion.
8062 // Determine necessity of tinst before tnext.
8063 if (tinst
&& tinst
->needsCodegen())
8065 minst
= tinst
->minst
; // cache result
8067 assert(minst
->isRoot() || minst
->rootImports());
8070 if (tnext
&& (tnext
->needsCodegen() || tnext
->minst
))
8072 minst
= tnext
->minst
; // cache result
8074 return minst
->isRoot() || minst
->rootImports();
8077 // Elide codegen because this is really speculative.
8081 /* Even when this is reached to the codegen pass,
8082 * a non-root nested template should not generate code,
8083 * due to avoid ODR violation.
8085 if (enclosing
&& enclosing
->inNonRoot())
8089 bool r
= tinst
->needsCodegen();
8090 minst
= tinst
->minst
; // cache result
8095 bool r
= tnext
->needsCodegen();
8096 minst
= tnext
->minst
; // cache result
8102 /* The issue is that if the importee is compiled with a different -debug
8103 * setting than the importer, the importer may believe it exists
8104 * in the compiled importee when it does not, when the instantiation
8105 * is behind a conditional debug declaration.
8107 // workaround for Bugzilla 11239
8108 if (global
.params
.useUnitTests
||
8109 global
.params
.debuglevel
)
8111 // Prefer instantiations from root modules, to maximize link-ability.
8112 if (minst
->isRoot())
8115 TemplateInstance
*tnext
= this->tnext
;
8116 TemplateInstance
*tinst
= this->tinst
;
8120 if (tinst
&& tinst
->needsCodegen())
8122 minst
= tinst
->minst
; // cache result
8124 assert(minst
->isRoot() || minst
->rootImports());
8127 if (tnext
&& tnext
->needsCodegen())
8129 minst
= tnext
->minst
; // cache result
8131 assert(minst
->isRoot() || minst
->rootImports());
8135 // Bugzilla 2500 case
8136 if (minst
->rootImports())
8139 // Elide codegen because this is not included in root instances.
8144 // Prefer instantiations from non-root module, to minimize object code size.
8146 /* If a TemplateInstance is ever instantiated by non-root modules,
8147 * we do not have to generate code for it,
8148 * because it will be generated when the non-root module is compiled.
8150 * But, if the non-root 'minst' imports any root modules, it might still need codegen.
8152 * The problem is if A imports B, and B imports A, and both A
8153 * and B instantiate the same template, does the compilation of A
8154 * or the compilation of B do the actual instantiation?
8156 * See Bugzilla 2500.
8158 if (!minst
->isRoot() && !minst
->rootImports())
8161 TemplateInstance
*tnext
= this->tnext
;
8164 if (tnext
&& !tnext
->needsCodegen() && tnext
->minst
)
8166 minst
= tnext
->minst
; // cache result
8167 assert(!minst
->isRoot());
8171 // Do codegen because this is not included in non-root instances.
8176 /* ======================== TemplateMixin ================================ */
8178 TemplateMixin::TemplateMixin(Loc loc
, Identifier
*ident
, TypeQualified
*tqual
, Objects
*tiargs
)
8179 : TemplateInstance(loc
, tqual
->idents
.dim
? (Identifier
*)tqual
->idents
[tqual
->idents
.dim
- 1]
8180 : ((TypeIdentifier
*)tqual
)->ident
)
8182 //printf("TemplateMixin(ident = '%s')\n", ident ? ident->toChars() : "");
8183 this->ident
= ident
;
8184 this->tqual
= tqual
;
8185 this->tiargs
= tiargs
? tiargs
: new Objects();
8188 Dsymbol
*TemplateMixin::syntaxCopy(Dsymbol
*)
8190 TemplateMixin
*tm
= new TemplateMixin(loc
, ident
,
8191 (TypeQualified
*)tqual
->syntaxCopy(), tiargs
);
8192 return TemplateInstance::syntaxCopy(tm
);
8195 bool TemplateMixin::findTempDecl(Scope
*sc
)
8197 // Follow qualifications to find the TemplateDeclaration
8203 tqual
->resolve(loc
, sc
, &e
, &t
, &s
);
8206 error("is not defined");
8210 tempdecl
= s
->isTemplateDeclaration();
8211 OverloadSet
*os
= s
->isOverloadSet();
8213 /* If an OverloadSet, look for a unique member that is a template declaration
8218 for (size_t i
= 0; i
< os
->a
.dim
; i
++)
8220 Dsymbol
*s2
= os
->a
[i
]->isTemplateDeclaration();
8234 error("%s isn't a template", s
->toChars());
8240 struct ParamFwdResTm
8242 static int fp(void *param
, Dsymbol
*s
)
8244 TemplateDeclaration
*td
= s
->isTemplateDeclaration();
8248 TemplateMixin
*tm
= (TemplateMixin
*)param
;
8249 if (td
->semanticRun
== PASSinit
)
8252 td
->semantic(td
->_scope
);
8255 tm
->semanticRun
= PASSinit
;
8262 // Look for forward references
8263 OverloadSet
*tovers
= tempdecl
->isOverloadSet();
8264 size_t overs_dim
= tovers
? tovers
->a
.dim
: 1;
8265 for (size_t oi
= 0; oi
< overs_dim
; oi
++)
8267 if (overloadApply(tovers
? tovers
->a
[oi
] : tempdecl
, (void *)this, &ParamFwdResTm::fp
))
8273 void TemplateMixin::semantic(Scope
*sc
)
8275 if (semanticRun
!= PASSinit
)
8277 // When a class/struct contains mixin members, and is done over
8278 // because of forward references, never reach here so semanticRun
8279 // has been reset to PASSinit.
8282 semanticRun
= PASSsemantic
;
8288 scx
= _scope
; // save so we don't make redundant copies
8292 /* Run semantic on each argument, place results in tiargs[],
8293 * then find best match template with tiargs
8295 if (!findTempDecl(sc
) ||
8296 !semanticTiargs(sc
) ||
8297 !findBestMatch(sc
, NULL
))
8299 if (semanticRun
== PASSinit
) // forward reference had occured
8301 //printf("forward reference - deferring\n");
8302 _scope
= scx
? scx
: sc
->copy();
8303 _scope
->setNoFree();
8304 _scope
->_module
->addDeferredSemantic(this);
8310 return; // error recovery
8312 TemplateDeclaration
*tempdecl
= this->tempdecl
->isTemplateDeclaration();
8317 /* Assign scope local unique identifier, as same as lambdas.
8319 const char *s
= "__mixin";
8321 DsymbolTable
*symtab
;
8322 if (FuncDeclaration
*func
= sc
->parent
->isFuncDeclaration())
8324 symtab
= func
->localsymtab
;
8327 // Inside template constraint, symtab is not set yet.
8333 symtab
= sc
->parent
->isScopeDsymbol()->symtab
;
8336 int num
= (int)dmd_aaLen(symtab
->tab
) + 1;
8337 ident
= Identifier::generateId(s
, num
);
8338 symtab
->insert(this);
8343 parent
= sc
->parent
;
8345 /* Detect recursive mixin instantiations.
8347 for (Dsymbol
*s
= parent
; s
; s
= s
->parent
)
8349 //printf("\ts = '%s'\n", s->toChars());
8350 TemplateMixin
*tm
= s
->isTemplateMixin();
8351 if (!tm
|| tempdecl
!= tm
->tempdecl
)
8354 /* Different argument list lengths happen with variadic args
8356 if (tiargs
->dim
!= tm
->tiargs
->dim
)
8359 for (size_t i
= 0; i
< tiargs
->dim
; i
++)
8361 RootObject
*o
= (*tiargs
)[i
];
8362 Type
*ta
= isType(o
);
8363 Expression
*ea
= isExpression(o
);
8364 Dsymbol
*sa
= isDsymbol(o
);
8365 RootObject
*tmo
= (*tm
->tiargs
)[i
];
8368 Type
*tmta
= isType(tmo
);
8371 if (!ta
->equals(tmta
))
8376 Expression
*tme
= isExpression(tmo
);
8377 if (!tme
|| !ea
->equals(tme
))
8382 Dsymbol
*tmsa
= isDsymbol(tmo
);
8389 error("recursive mixin instantiation");
8396 // Copy the syntax trees from the TemplateDeclaration
8397 members
= Dsymbol::arraySyntaxCopy(tempdecl
->members
);
8401 symtab
= new DsymbolTable();
8403 for (Scope
*sce
= sc
; 1; sce
= sce
->enclosing
)
8405 ScopeDsymbol
*sds
= (ScopeDsymbol
*)sce
->scopesym
;
8408 sds
->importScope(this, Prot(PROTpublic
));
8413 Scope
*scy
= sc
->push(this);
8416 argsym
= new ScopeDsymbol();
8417 argsym
->parent
= scy
->parent
;
8418 Scope
*argscope
= scy
->push(argsym
);
8420 unsigned errorsave
= global
.errors
;
8422 // Declare each template parameter as an alias for the argument type
8423 declareParameters(argscope
);
8425 // Add members to enclosing scope, as well as this scope
8426 for (size_t i
= 0; i
< members
->dim
; i
++)
8428 Dsymbol
*s
= (*members
)[i
];
8429 s
->addMember(argscope
, this);
8430 //printf("sc->parent = %p, sc->scopesym = %p\n", sc->parent, sc->scopesym);
8431 //printf("s->parent = %s\n", s->parent->toChars());
8434 // Do semantic() analysis on template instance members
8435 Scope
*sc2
= argscope
->push(this);
8436 //size_t deferred_dim = Module::deferred.dim;
8439 //printf("%d\n", nest);
8442 global
.gag
= 0; // ensure error message gets printed
8443 error("recursive expansion");
8447 for (size_t i
= 0; i
< members
->dim
; i
++)
8449 Dsymbol
*s
= (*members
)[i
];
8453 for (size_t i
= 0; i
< members
->dim
; i
++)
8455 Dsymbol
*s
= (*members
)[i
];
8459 for (size_t i
= 0; i
< members
->dim
; i
++)
8461 Dsymbol
*s
= (*members
)[i
];
8467 /* In DeclDefs scope, TemplateMixin does not have to handle deferred symbols.
8468 * Because the members would already call Module::addDeferredSemantic() for themselves.
8469 * See Struct, Class, Interface, and EnumDeclaration::semantic().
8471 //if (!sc->func && Module::deferred.dim > deferred_dim) {}
8473 AggregateDeclaration
*ad
= toParent()->isAggregateDeclaration();
8474 if (sc
->func
&& !ad
)
8480 // Give additional context info if error occurred during instantiation
8481 if (global
.errors
!= errorsave
)
8483 error("error instantiating");
8492 void TemplateMixin::semantic2(Scope
*sc
)
8494 if (semanticRun
>= PASSsemantic2
)
8496 semanticRun
= PASSsemantic2
;
8500 sc
= sc
->push(argsym
);
8501 sc
= sc
->push(this);
8502 for (size_t i
= 0; i
< members
->dim
; i
++)
8504 Dsymbol
*s
= (*members
)[i
];
8512 void TemplateMixin::semantic3(Scope
*sc
)
8514 if (semanticRun
>= PASSsemantic3
)
8516 semanticRun
= PASSsemantic3
;
8519 sc
= sc
->push(argsym
);
8520 sc
= sc
->push(this);
8521 for (size_t i
= 0; i
< members
->dim
; i
++)
8523 Dsymbol
*s
= (*members
)[i
];
8531 const char *TemplateMixin::kind() const
8536 bool TemplateMixin::oneMember(Dsymbol
**ps
, Identifier
*ident
)
8538 return Dsymbol::oneMember(ps
, ident
);
8541 int TemplateMixin::apply(Dsymbol_apply_ft_t fp
, void *param
)
8543 if (_scope
) // if fwd reference
8544 semantic(NULL
); // try to resolve it
8547 for (size_t i
= 0; i
< members
->dim
; i
++)
8549 Dsymbol
*s
= (*members
)[i
];
8552 if (s
->apply(fp
, param
))
8560 bool TemplateMixin::hasPointers()
8562 //printf("TemplateMixin::hasPointers() %s\n", toChars());
8566 for (size_t i
= 0; i
< members
->dim
; i
++)
8568 Dsymbol
*s
= (*members
)[i
];
8569 //printf(" s = %s %s\n", s->kind(), s->toChars());
8570 if (s
->hasPointers())
8579 void TemplateMixin::setFieldOffset(AggregateDeclaration
*ad
, unsigned *poffset
, bool isunion
)
8581 //printf("TemplateMixin::setFieldOffset() %s\n", toChars());
8582 if (_scope
) // if fwd reference
8583 semantic(NULL
); // try to resolve it
8586 for (size_t i
= 0; i
< members
->dim
; i
++)
8588 Dsymbol
*s
= (*members
)[i
];
8589 //printf("\t%s\n", s->toChars());
8590 s
->setFieldOffset(ad
, poffset
, isunion
);
8595 const char *TemplateMixin::toChars()
8598 toCBufferInstance(this, &buf
);
8599 return buf
.extractString();