comparison dmd/TemplateDeclaration.d @ 0:10317f0c89a5

Initial commit
author korDen
date Sat, 24 Oct 2009 08:42:06 +0400
parents
children d42cd5917df4
comparison
equal deleted inserted replaced
-1:000000000000 0:10317f0c89a5
1 module dmd.TemplateDeclaration;
2
3 import dmd.Loc;
4 import dmd.ScopeDsymbol;
5 import dmd.ArrayTypes;
6 import dmd.Dsymbol;
7 import dmd.STC;
8 import dmd.TemplateThisParameter;
9 import dmd.Global;
10 import dmd.Array;
11 import dmd.Identifier;
12 import dmd.TypeArray;
13 import dmd.Expression;
14 import dmd.Scope;
15 import dmd.TypeIdentifier;
16 import dmd.TypeDelegate;
17 import dmd.IntegerExp;
18 import dmd.TypeSArray;
19 import dmd.StringExp;
20 import dmd.TOK;
21 import dmd.Argument;
22 import dmd.CtorDeclaration;
23 import dmd.TypeFunction;
24 import dmd.TY;
25 import dmd.OutBuffer;
26 import dmd.Declaration;
27 import dmd.HdrGenState;
28 import dmd.TemplateInstance;
29 import dmd.WANT;
30 import dmd.FuncDeclaration;
31 import dmd.TemplateTupleParameter;
32 import dmd.MATCH;
33 import dmd.Type;
34 import dmd.Tuple;
35 import dmd.TupleDeclaration;
36 import dmd.Initializer;
37 import dmd.ExpInitializer;
38 import dmd.TemplateValueParameter;
39 import dmd.AliasDeclaration;
40 import dmd.VarDeclaration;
41 import dmd.TemplateParameter;
42 import dmd.TemplateTypeParameter;
43
44 import dmd.expression.Util;
45
46 import std.stdio;
47
48 /**************************************
49 * Determine if TemplateDeclaration is variadic.
50 */
51
52 TemplateTupleParameter isVariadic(TemplateParameters parameters)
53 {
54 size_t dim = parameters.dim;
55 TemplateTupleParameter tp = null;
56
57 if (dim)
58 tp = (cast(TemplateParameter)parameters.data[dim - 1]).isTemplateTupleParameter();
59
60 return tp;
61 }
62
63 void ObjectToCBuffer(OutBuffer buf, HdrGenState* hgs, Object oarg)
64 {
65 //printf("ObjectToCBuffer()\n");
66 Type t = isType(oarg);
67 Expression e = isExpression(oarg);
68 Dsymbol s = isDsymbol(oarg);
69 Tuple v = isTuple(oarg);
70 if (t)
71 {
72 //printf("\tt: %s ty = %d\n", t.toChars(), t.ty);
73 t.toCBuffer(buf, null, hgs);
74 }
75 else if (e)
76 e.toCBuffer(buf, hgs);
77 else if (s)
78 {
79 string p = s.ident ? s.ident.toChars() : s.toChars();
80 buf.writestring(p);
81 }
82 else if (v)
83 {
84 Objects args = v.objects;
85 for (size_t i = 0; i < args.dim; i++)
86 {
87 if (i)
88 buf.writeByte(',');
89 Object o = cast(Object)args.data[i];
90 ObjectToCBuffer(buf, hgs, o);
91 }
92 }
93 else if (!oarg)
94 {
95 buf.writestring("null");
96 }
97 else
98 {
99 debug writef("bad Object = %p\n", oarg);
100 assert(0);
101 }
102 }
103
104 class TemplateDeclaration : ScopeDsymbol
105 {
106 TemplateParameters parameters; // array of TemplateParameter's
107
108 TemplateParameters origParameters; // originals for Ddoc
109 Expression constraint;
110 Array instances; // array of TemplateInstance's
111
112 TemplateDeclaration overnext; // next overloaded TemplateDeclaration
113 TemplateDeclaration overroot; // first in overnext list
114
115 int semanticRun; // 1 semantic() run
116
117 Dsymbol onemember; // if !=NULL then one member of this template
118
119 int literal; // this template declaration is a literal
120
121 this(Loc loc, Identifier id, TemplateParameters parameters, Expression constraint, Array decldefs)
122 {
123 super(id);
124
125 version (LOG) {
126 printf("TemplateDeclaration(this = %p, id = '%s')\n", this, id.toChars());
127 }
128 static if (false) {
129 if (parameters)
130 for (int i = 0; i < parameters.dim; i++)
131 {
132 TemplateParameter tp = cast(TemplateParameter)parameters.data[i];
133 //printf("\tparameter[%d] = %p\n", i, tp);
134 TemplateTypeParameter ttp = tp.isTemplateTypeParameter();
135
136 if (ttp)
137 {
138 printf("\tparameter[%d] = %s : %s\n", i, tp.ident.toChars(), ttp.specType ? ttp.specType.toChars() : "");
139 }
140 }
141 }
142
143 this.loc = loc;
144 this.parameters = parameters;
145 this.origParameters = parameters;
146 this.constraint = constraint;
147 this.members = decldefs;
148
149 instances = new Array();
150 }
151
152 Dsymbol syntaxCopy(Dsymbol)
153 {
154 assert(false);
155 }
156
157 void semantic(Scope sc)
158 {
159 version (LOG) {
160 printf("TemplateDeclaration.semantic(this = %p, id = '%s')\n", this, ident.toChars());
161 }
162 if (semanticRun)
163 return; // semantic() already run
164 semanticRun = 1;
165
166 if (sc.func)
167 {
168 version (DMDV1) {
169 error("cannot declare template at function scope %s", sc.func.toChars());
170 }
171 }
172
173 if (/*global.params.useArrayBounds &&*/ sc.module_)
174 {
175 // Generate this function as it may be used
176 // when template is instantiated in other modules
177 sc.module_.toModuleArray();
178 }
179
180 if (/*global.params.useAssert &&*/ sc.module_)
181 {
182 // Generate this function as it may be used
183 // when template is instantiated in other modules
184 sc.module_.toModuleAssert();
185 }
186
187 /* Remember Scope for later instantiations, but make
188 * a copy since attributes can change.
189 */
190 this.scope_ = new Scope(sc); /// A light copy
191 this.scope_.setNoFree();
192
193 // Set up scope for parameters
194 ScopeDsymbol paramsym = new ScopeDsymbol();
195 paramsym.parent = sc.parent;
196 Scope paramscope = sc.push(paramsym);
197 paramscope.parameterSpecialization = 1;
198 paramscope.stc = STCundefined;
199
200 if (!parent)
201 parent = sc.parent;
202
203 if (global.params.doDocComments)
204 {
205 origParameters = new TemplateParameters();
206 origParameters.setDim(parameters.dim);
207 for (int i = 0; i < parameters.dim; i++)
208 {
209 TemplateParameter tp = cast(TemplateParameter)parameters.data[i];
210 origParameters.data[i] = cast(void*)tp.syntaxCopy();
211 }
212 }
213
214 for (int i = 0; i < parameters.dim; i++)
215 {
216 TemplateParameter tp = cast(TemplateParameter)parameters.data[i];
217 tp.declareParameter(paramscope);
218 }
219
220 for (int i = 0; i < parameters.dim; i++)
221 {
222 TemplateParameter tp = cast(TemplateParameter)parameters.data[i];
223
224 tp.semantic(paramscope);
225 if (i + 1 != parameters.dim && tp.isTemplateTupleParameter())
226 error("template tuple parameter must be last one");
227 }
228
229 paramscope.pop();
230
231 if (members)
232 {
233 Dsymbol s;
234 if (Dsymbol.oneMembers(members, &s))
235 {
236 if (s && s.ident && s.ident.equals(ident))
237 {
238 onemember = s;
239 s.parent = this;
240 }
241 }
242 }
243
244 /* BUG: should check:
245 * o no virtual functions or non-static data members of classes
246 */
247 }
248
249 bool overloadInsert(Dsymbol s)
250 {
251 assert(false);
252 }
253
254 void toCBuffer(OutBuffer buf, HdrGenState* hgs)
255 {
256 assert(false);
257 }
258
259 string kind()
260 {
261 assert(false);
262 }
263
264 string toChars()
265 {
266 assert(false);
267 }
268
269 void emitComment(Scope sc)
270 {
271 assert(false);
272 }
273
274 // void toDocBuffer(OutBuffer *buf);
275
276 /***************************************
277 * Given that ti is an instance of this TemplateDeclaration,
278 * deduce the types of the parameters to this, and store
279 * those deduced types in dedtypes[].
280 * Input:
281 * flag 1: don't do semantic() because of dummy types
282 * 2: don't change types in matchArg()
283 * Output:
284 * dedtypes deduced arguments
285 * Return match level.
286 */
287 MATCH matchWithInstance(TemplateInstance ti, Objects dedtypes, int flag)
288 {
289 MATCH m;
290 int dedtypes_dim = dedtypes.dim;
291
292 version (LOGM) {
293 printf("\n+TemplateDeclaration.matchWithInstance(this = %s, ti = %s, flag = %d)\n", toChars(), ti.toChars(), flag);
294 }
295
296 static if (false) {
297 printf("dedtypes.dim = %d, parameters.dim = %d\n", dedtypes_dim, parameters.dim);
298 if (ti.tiargs.dim)
299 printf("ti.tiargs.dim = %d, [0] = %p\n", ti.tiargs.dim, ti.tiargs.data[0]);
300 }
301 dedtypes.zero();
302
303 int parameters_dim = parameters.dim;
304 int variadic = isVariadic() !is null;
305
306 // If more arguments than parameters, no match
307 if (ti.tiargs.dim > parameters_dim && !variadic)
308 {
309 version (LOGM) {
310 printf(" no match: more arguments than parameters\n");
311 }
312 return MATCHnomatch;
313 }
314
315 assert(dedtypes_dim == parameters_dim);
316 assert(dedtypes_dim >= ti.tiargs.dim || variadic);
317
318 // Set up scope for parameters
319 assert(cast(size_t)cast(void*)scope_ > 0x10000);
320 ScopeDsymbol paramsym = new ScopeDsymbol();
321 paramsym.parent = scope_.parent;
322 Scope paramscope = scope_.push(paramsym);
323 paramscope.stc = STCundefined;
324
325 // Attempt type deduction
326 m = MATCHexact;
327 for (int i = 0; i < dedtypes_dim; i++)
328 {
329 MATCH m2;
330 TemplateParameter tp = cast(TemplateParameter)parameters.data[i];
331 Declaration sparam;
332
333 //printf("\targument [%d]\n", i);
334 version (LOGM) {
335 //printf("\targument [%d] is %s\n", i, oarg ? oarg.toChars() : "null");
336 TemplateTypeParameter *ttp = tp.isTemplateTypeParameter();
337 if (ttp)
338 printf("\tparameter[%d] is %s : %s\n", i, tp.ident.toChars(), ttp.specType ? ttp.specType.toChars() : "");
339 }
340
341 version (DMDV1) {
342 m2 = tp.matchArg(paramscope, ti.tiargs, i, parameters, dedtypes, &sparam);
343 } else {
344 m2 = tp.matchArg(paramscope, ti.tiargs, i, parameters, dedtypes, &sparam, (flag & 2) ? 1 : 0);
345 }
346 //printf("\tm2 = %d\n", m2);
347
348 if (m2 == MATCHnomatch)
349 {
350 static if (false) {
351 printf("\tmatchArg() for parameter %i failed\n", i);
352 }
353 goto Lnomatch;
354 }
355
356 if (m2 < m)
357 m = m2;
358
359 if (!flag)
360 sparam.semantic(paramscope);
361 if (!paramscope.insert(sparam))
362 goto Lnomatch;
363 }
364
365 if (!flag)
366 {
367 /* Any parameter left without a type gets the type of
368 * its corresponding arg
369 */
370 for (int i = 0; i < dedtypes_dim; i++)
371 {
372 if (!dedtypes.data[i])
373 {
374 assert(i < ti.tiargs.dim);
375 dedtypes.data[i] = ti.tiargs.data[i];
376 }
377 }
378 }
379
380 version (DMDV2) {
381 if (m && constraint && !(flag & 1))
382 { /* Check to see if constraint is satisfied.
383 */
384 Expression e = constraint.syntaxCopy();
385 paramscope.flags |= SCOPE.SCOPEstaticif;
386 e = e.semantic(paramscope);
387 e = e.optimize(WANTvalue | WANTinterpret);
388 if (e.isBool(true)) {
389 ;
390 } else if (e.isBool(false))
391 goto Lnomatch;
392 else
393 {
394 e.error("constraint %s is not constant or does not evaluate to a bool", e.toChars());
395 }
396 }
397 }
398
399 version (LOGM) {
400 // Print out the results
401 printf("--------------------------\n");
402 printf("template %s\n", toChars());
403 printf("instance %s\n", ti.toChars());
404 if (m)
405 {
406 for (int i = 0; i < dedtypes_dim; i++)
407 {
408 TemplateParameter tp = cast(TemplateParameter)parameters.data[i];
409 Object oarg;
410
411 printf(" [%d]", i);
412
413 if (i < ti.tiargs.dim)
414 oarg = cast(Object)ti.tiargs.data[i];
415 else
416 oarg = null;
417 tp.print(oarg, cast(Object)dedtypes.data[i]);
418 }
419 }
420 else
421 goto Lnomatch;
422 }
423
424 version (LOGM) {
425 printf(" match = %d\n", m);
426 }
427 goto Lret;
428
429 Lnomatch:
430 version (LOGM) {
431 printf(" no match\n");
432 }
433 m = MATCHnomatch;
434
435 Lret:
436 paramscope.pop();
437 version (LOGM) {
438 printf("-TemplateDeclaration.matchWithInstance(this = %p, ti = %p) = %d\n", this, ti, m);
439 }
440 return m;
441 }
442
443 MATCH leastAsSpecialized(TemplateDeclaration td2)
444 {
445 assert(false);
446 }
447
448 /*************************************************
449 * Match function arguments against a specific template function.
450 * Input:
451 * loc instantiation location
452 * targsi Expression/Type initial list of template arguments
453 * ethis 'this' argument if !null
454 * fargs arguments to function
455 * Output:
456 * dedargs Expression/Type deduced template arguments
457 * Returns:
458 * match level
459 */
460 MATCH deduceFunctionTemplateMatch(Loc loc, Objects targsi, Expression ethis, Expressions fargs, Objects dedargs)
461 {
462 size_t nfparams;
463 size_t nfargs;
464 size_t nargsi; // array size of targsi
465 int fptupindex = -1;
466 int tuple_dim = 0;
467 MATCH match = MATCHexact;
468 FuncDeclaration fd = onemember.toAlias().isFuncDeclaration();
469 Arguments fparameters; // function parameter list
470 int fvarargs; // function varargs
471 scope Objects dedtypes = new Objects(); // for T:T*, the dedargs is the T*, dedtypes is the T
472
473 static if (false) {
474 printf("\nTemplateDeclaration.deduceFunctionTemplateMatch() %s\n", toChars());
475 for (i = 0; i < fargs.dim; i++)
476 {
477 Expression e = cast(Expression)fargs.data[i];
478 printf("\tfarg[%d] is %s, type is %s\n", i, e.toChars(), e.type.toChars());
479 }
480 printf("fd = %s\n", fd.toChars());
481 printf("fd.type = %p\n", fd.type);
482 }
483
484 assert(cast(size_t)cast(void*)scope_ > 0x10000);
485
486 dedargs.setDim(parameters.dim);
487 dedargs.zero();
488
489 dedtypes.setDim(parameters.dim);
490 dedtypes.zero();
491
492 // Set up scope for parameters
493 ScopeDsymbol paramsym = new ScopeDsymbol();
494 paramsym.parent = scope_.parent;
495 Scope paramscope = scope_.push(paramsym);
496
497 TemplateTupleParameter tp = isVariadic();
498
499 static if (false) {
500 for (i = 0; i < dedargs.dim; i++)
501 {
502 printf("\tdedarg[%d] = ", i);
503 Object oarg = cast(Object)dedargs.data[i];
504 if (oarg) printf("%s", oarg.toChars());
505 printf("\n");
506 }
507 }
508
509
510 nargsi = 0;
511 if (targsi)
512 { // Set initial template arguments
513 size_t n;
514
515 nargsi = targsi.dim;
516 n = parameters.dim;
517 if (tp)
518 n--;
519 if (nargsi > n)
520 {
521 if (!tp)
522 goto Lnomatch;
523
524 /* The extra initial template arguments
525 * now form the tuple argument.
526 */
527 Tuple t = new Tuple();
528 assert(parameters.dim);
529 dedargs.data[parameters.dim - 1] = cast(void*)t;
530
531 tuple_dim = nargsi - n;
532 t.objects.setDim(tuple_dim);
533 for (size_t i = 0; i < tuple_dim; i++)
534 {
535 t.objects.data[i] = cast(void*)targsi.data[n + i];
536 }
537 declareParameter(paramscope, tp, t);
538 }
539 else
540 n = nargsi;
541
542 memcpy(dedargs.data, targsi.data, n * (*dedargs.data).sizeof);
543
544 for (size_t i = 0; i < n; i++)
545 {
546 assert(i < parameters.dim);
547 TemplateParameter tp2 = cast(TemplateParameter)parameters.data[i];
548 MATCH m;
549 Declaration sparam = null;
550
551 m = tp2.matchArg(paramscope, dedargs, i, parameters, dedtypes, &sparam);
552 //printf("\tdeduceType m = %d\n", m);
553 if (m == MATCHnomatch)
554 goto Lnomatch;
555 if (m < match)
556 match = m;
557
558 sparam.semantic(paramscope);
559 if (!paramscope.insert(sparam))
560 goto Lnomatch;
561 }
562 }
563 static if (false) {
564 for (i = 0; i < dedargs.dim; i++)
565 {
566 printf("\tdedarg[%d] = ", i);
567 Object oarg = cast(Object)dedargs.data[i];
568 if (oarg) printf("%s", oarg.toChars());
569 printf("\n");
570 }
571 }
572
573 if (fd.type)
574 {
575 assert(fd.type.ty == Tfunction);
576 TypeFunction fdtype = cast(TypeFunction)fd.type;
577 fparameters = fdtype.parameters;
578 fvarargs = fdtype.varargs;
579 }
580 else
581 {
582 CtorDeclaration fctor = fd.isCtorDeclaration();
583 assert(fctor);
584 fparameters = fctor.arguments;
585 fvarargs = fctor.varargs;
586 }
587
588 nfparams = Argument.dim(fparameters); // number of function parameters
589 nfargs = fargs ? fargs.dim : 0; // number of function arguments
590
591 /* Check for match of function arguments with variadic template
592 * parameter, such as:
593 *
594 * template Foo(T, A...) { void Foo(T t, A a); }
595 * void main() { Foo(1,2,3); }
596 */
597 if (tp) // if variadic
598 {
599 if (nfparams == 0) // if no function parameters
600 {
601 Tuple t = new Tuple();
602 //printf("t = %p\n", t);
603 dedargs.data[parameters.dim - 1] = cast(void*)t;
604 declareParameter(paramscope, tp, t);
605 goto L2;
606 }
607 else if (nfargs < nfparams - 1)
608 goto L1;
609 else
610 {
611 /* Figure out which of the function parameters matches
612 * the tuple template parameter. Do this by matching
613 * type identifiers.
614 * Set the index of this function parameter to fptupindex.
615 */
616 for (fptupindex = 0; fptupindex < nfparams; fptupindex++)
617 {
618 Argument fparam = cast(Argument)fparameters.data[fptupindex];
619 if (fparam.type.ty != Tident)
620 continue;
621 TypeIdentifier tid = cast(TypeIdentifier)fparam.type;
622 if (!tp.ident.equals(tid.ident) || tid.idents.dim)
623 continue;
624
625 if (fvarargs) // variadic function doesn't
626 goto Lnomatch; // go with variadic template
627
628 /* The types of the function arguments
629 * now form the tuple argument.
630 */
631 Tuple t = new Tuple();
632 dedargs.data[parameters.dim - 1] = cast(void*)t;
633
634 tuple_dim = nfargs - (nfparams - 1);
635 t.objects.setDim(tuple_dim);
636 for (size_t i = 0; i < tuple_dim; i++)
637 {
638 Expression farg = cast(Expression)fargs.data[fptupindex + i];
639 t.objects.data[i] = cast(void*)farg.type;
640 }
641 declareParameter(paramscope, tp, t);
642 goto L2;
643 }
644 fptupindex = -1;
645 }
646 }
647
648 L1:
649 if (nfparams == nfargs) {
650 ;
651 } else if (nfargs > nfparams) {
652 if (fvarargs == 0)
653 goto Lnomatch; // too many args, no match
654 match = MATCHconvert; // match ... with a conversion
655 }
656
657 L2:
658 version (DMDV2) {
659 // Match 'ethis' to any TemplateThisParameter's
660 if (ethis)
661 {
662 for (size_t i = 0; i < parameters.dim; i++)
663 {
664 TemplateParameter tp2 = cast(TemplateParameter)parameters.data[i];
665 TemplateThisParameter ttp = tp2.isTemplateThisParameter();
666 if (ttp)
667 {
668 MATCH m;
669
670 Type t = new TypeIdentifier(Loc(0), ttp.ident);
671 m = ethis.type.deduceType(paramscope, t, parameters, dedtypes);
672 if (!m)
673 goto Lnomatch;
674 if (m < match)
675 match = m; // pick worst match
676 }
677 }
678 }
679 }
680
681 // Loop through the function parameters
682 for (size_t i = 0; i < nfparams; i++)
683 {
684 /* Skip over function parameters which wound up
685 * as part of a template tuple parameter.
686 */
687 if (i == fptupindex)
688 {
689 if (fptupindex == nfparams - 1)
690 break;
691 i += tuple_dim - 1;
692 continue;
693 }
694
695 Argument fparam = Argument.getNth(fparameters, i);
696
697 if (i >= nfargs) // if not enough arguments
698 {
699 if (fparam.defaultArg)
700 {
701 /* Default arguments do not participate in template argument
702 * deduction.
703 */
704 goto Lmatch;
705 }
706 }
707 else
708 {
709 Expression farg = cast(Expression)fargs.data[i];
710 static if (false) {
711 printf("\tfarg.type = %s\n", farg.type.toChars());
712 printf("\tfparam.type = %s\n", fparam.type.toChars());
713 }
714 Type argtype = farg.type;
715
716 version (DMDV2) {
717 /* Allow string literals which are type [] to match with [dim]
718 */
719 if (farg.op == TOKstring)
720 {
721 StringExp se = cast(StringExp)farg;
722 if (!se.committed && argtype.ty == Tarray &&
723 fparam.type.toBasetype().ty == Tsarray)
724 {
725 argtype = new TypeSArray(argtype.nextOf(), new IntegerExp(se.loc, se.len, Type.tindex));
726 argtype = argtype.semantic(se.loc, null);
727 argtype = argtype.invariantOf();
728 }
729 }
730 }
731
732 MATCH m;
733 m = argtype.deduceType(paramscope, fparam.type, parameters, dedtypes);
734 //printf("\tdeduceType m = %d\n", m);
735
736 /* If no match, see if there's a conversion to a delegate
737 */
738 if (!m && fparam.type.toBasetype().ty == Tdelegate)
739 {
740 TypeDelegate td = cast(TypeDelegate)fparam.type.toBasetype();
741 TypeFunction tf = cast(TypeFunction)td.next;
742
743 if (!tf.varargs && Argument.dim(tf.parameters) == 0)
744 {
745 m = farg.type.deduceType(paramscope, tf.next, parameters, dedtypes);
746 if (!m && tf.next.toBasetype().ty == Tvoid)
747 m = MATCHconvert;
748 }
749 //printf("\tm2 = %d\n", m);
750 }
751
752 if (m)
753 {
754 if (m < match)
755 match = m; // pick worst match
756 continue;
757 }
758 }
759
760 /* The following code for variadic arguments closely
761 * matches TypeFunction.callMatch()
762 */
763 if (!(fvarargs == 2 && i + 1 == nfparams))
764 goto Lnomatch;
765
766 /* Check for match with function parameter T...
767 */
768 Type tb = fparam.type.toBasetype();
769 switch (tb.ty)
770 {
771 // Perhaps we can do better with this, see TypeFunction.callMatch()
772 case Tsarray:
773 {
774 TypeSArray tsa = cast(TypeSArray)tb;
775 ulong sz = tsa.dim.toInteger();
776 if (sz != nfargs - i)
777 goto Lnomatch;
778 }
779 case Tarray:
780 {
781 TypeArray ta = cast(TypeArray)tb;
782 for (; i < nfargs; i++)
783 {
784 Expression arg = cast(Expression)fargs.data[i];
785 assert(arg);
786 MATCH m;
787 /* If lazy array of delegates,
788 * convert arg(s) to delegate(s)
789 */
790 Type tret = fparam.isLazyArray();
791 if (tret)
792 {
793 if (ta.next.equals(arg.type))
794 {
795 m = MATCHexact;
796 }
797 else
798 {
799 m = arg.implicitConvTo(tret);
800 if (m == MATCHnomatch)
801 {
802 if (tret.toBasetype().ty == Tvoid)
803 m = MATCHconvert;
804 }
805 }
806 }
807 else
808 {
809 m = arg.type.deduceType(paramscope, ta.next, parameters, dedtypes);
810 //m = arg.implicitConvTo(ta.next);
811 }
812 if (m == MATCHnomatch)
813 goto Lnomatch;
814 if (m < match)
815 match = m;
816 }
817 goto Lmatch;
818 }
819 case Tclass:
820 case Tident:
821 goto Lmatch;
822
823 default:
824 goto Lnomatch;
825 }
826 }
827
828 Lmatch:
829
830 /* Fill in any missing arguments with their defaults.
831 */
832 for (size_t i = nargsi; i < dedargs.dim; i++)
833 {
834 TemplateParameter tp2 = cast(TemplateParameter)parameters.data[i];
835 //printf("tp2[%d] = %s\n", i, tp2.ident.toChars());
836 /* For T:T*, the dedargs is the T*, dedtypes is the T
837 * But for function templates, we really need them to match
838 */
839 Object oarg = cast(Object)dedargs.data[i];
840 Object oded = cast(Object)dedtypes.data[i];
841 //printf("1dedargs[%d] = %p, dedtypes[%d] = %p\n", i, oarg, i, oded);
842 //if (oarg) printf("oarg: %s\n", oarg.toChars());
843 //if (oded) printf("oded: %s\n", oded.toChars());
844 if (!oarg)
845 {
846 if (oded)
847 {
848 if (tp2.specialization())
849 {
850 /* The specialization can work as long as afterwards
851 * the oded == oarg
852 */
853 Declaration sparam;
854 dedargs.data[i] = cast(void*)oded;
855 MATCH m2 = tp2.matchArg(paramscope, dedargs, i, parameters, dedtypes, &sparam, 0);
856 //printf("m2 = %d\n", m2);
857 if (!m2)
858 goto Lnomatch;
859 if (m2 < match)
860 match = m2; // pick worst match
861 if (dedtypes.data[i] !is cast(void*)oded)
862 error("specialization not allowed for deduced parameter %s", tp2.ident.toChars());
863 }
864 }
865 else
866 {
867 oded = tp2.defaultArg(loc, paramscope);
868 if (!oded)
869 goto Lnomatch;
870 }
871 declareParameter(paramscope, tp2, oded);
872 dedargs.data[i] = cast(void*)oded;
873 }
874 }
875
876 version (DMDV2) {
877 if (constraint)
878 { /* Check to see if constraint is satisfied.
879 */
880 Expression e = constraint.syntaxCopy();
881 paramscope.flags |= SCOPE.SCOPEstaticif;
882 e = e.semantic(paramscope);
883 e = e.optimize(WANTvalue | WANTinterpret);
884 if (e.isBool(true)) {
885 ;
886 } else if (e.isBool(false))
887 goto Lnomatch;
888 else
889 {
890 e.error("constraint %s is not constant or does not evaluate to a bool", e.toChars());
891 }
892 }
893 }
894
895 static if (false) {
896 for (i = 0; i < dedargs.dim; i++)
897 {
898 Type t = cast(Type)dedargs.data[i];
899 printf("\tdedargs[%d] = %d, %s\n", i, t.dyncast(), t.toChars());
900 }
901 }
902
903 paramscope.pop();
904 //printf("\tmatch %d\n", match);
905 return match;
906
907 Lnomatch:
908 paramscope.pop();
909 //printf("\tnomatch\n");
910 return MATCHnomatch;
911 }
912
913 /*************************************************
914 * Given function arguments, figure out which template function
915 * to expand, and return that function.
916 * If no match, give error message and return null.
917 * Input:
918 * sc instantiation scope
919 * loc instantiation location
920 * targsi initial list of template arguments
921 * ethis if !null, the 'this' pointer argument
922 * fargs arguments to function
923 * flags 1: do not issue error message on no match, just return null
924 */
925 FuncDeclaration deduceFunctionTemplate(Scope sc, Loc loc, Objects targsi, Expression ethis, Expressions fargs, int flags = 0)
926 {
927 MATCH m_best = MATCHnomatch;
928 TemplateDeclaration td_ambig = null;
929 TemplateDeclaration td_best = null;
930 Objects tdargs = new Objects();
931 TemplateInstance ti;
932 FuncDeclaration fd;
933
934 static if (false) {
935 printf("TemplateDeclaration.deduceFunctionTemplate() %s\n", toChars());
936 printf(" targsi:\n");
937 if (targsi)
938 {
939 for (int i = 0; i < targsi.dim; i++)
940 {
941 Object arg = cast(Object)targsi.data[i];
942 printf("\t%s\n", arg.toChars());
943 }
944 }
945 printf(" fargs:\n");
946 for (int i = 0; i < fargs.dim; i++)
947 {
948 Expression arg = cast(Expression)fargs.data[i];
949 printf("\t%s %s\n", arg.type.toChars(), arg.toChars());
950 //printf("\tty = %d\n", arg.type.ty);
951 }
952 }
953
954 for (TemplateDeclaration td = this; td; td = td.overnext)
955 {
956 if (!td.semanticRun)
957 {
958 error("forward reference to template %s", td.toChars());
959 goto Lerror;
960 }
961 if (!td.onemember || !td.onemember.toAlias().isFuncDeclaration())
962 {
963 error("is not a function template");
964 goto Lerror;
965 }
966
967 MATCH m;
968 scope Objects dedargs = new Objects();
969
970 m = td.deduceFunctionTemplateMatch(loc, targsi, ethis, fargs, dedargs);
971 //printf("deduceFunctionTemplateMatch = %d\n", m);
972 if (!m) // if no match
973 continue;
974
975 if (m < m_best)
976 goto Ltd_best;
977 if (m > m_best)
978 goto Ltd;
979
980 {
981 // Disambiguate by picking the most specialized TemplateDeclaration
982 MATCH c1 = td.leastAsSpecialized(td_best);
983 MATCH c2 = td_best.leastAsSpecialized(td);
984 //printf("c1 = %d, c2 = %d\n", c1, c2);
985
986 if (c1 > c2)
987 goto Ltd;
988 else if (c1 < c2)
989 goto Ltd_best;
990 else
991 goto Lambig;
992 }
993
994 Lambig: // td_best and td are ambiguous
995 td_ambig = td;
996 continue;
997
998 Ltd_best: // td_best is the best match so far
999 td_ambig = null;
1000 continue;
1001
1002 Ltd: // td is the new best match
1003 td_ambig = null;
1004 assert(cast(size_t)cast(void*)td.scope_ > 0x10000);
1005 td_best = td;
1006 m_best = m;
1007 tdargs.setDim(dedargs.dim);
1008 memcpy(tdargs.data, dedargs.data, tdargs.dim * (void*).sizeof);
1009 continue;
1010 }
1011 if (!td_best)
1012 {
1013 if (!(flags & 1))
1014 error(loc, "does not match any function template declaration");
1015 goto Lerror;
1016 }
1017 if (td_ambig)
1018 {
1019 error(loc, "matches more than one function template declaration:\n %s\nand:\n %s",
1020 td_best.toChars(), td_ambig.toChars());
1021 }
1022
1023 /* The best match is td_best with arguments tdargs.
1024 * Now instantiate the template.
1025 */
1026 assert(cast(size_t)cast(void*)td_best.scope_ > 0x10000);
1027 ti = new TemplateInstance(loc, td_best, tdargs);
1028 ti.semantic(sc);
1029 fd = ti.toAlias().isFuncDeclaration();
1030 if (!fd)
1031 goto Lerror;
1032 return fd;
1033
1034 Lerror:
1035 /// version (DMDV2) {
1036 if (!(flags & 1))
1037 /// }
1038 {
1039 HdrGenState hgs;
1040
1041 scope OutBuffer bufa = new OutBuffer();
1042 Objects args = targsi;
1043 if (args)
1044 {
1045 for (int i = 0; i < args.dim; i++)
1046 {
1047 if (i)
1048 bufa.writeByte(',');
1049 Object oarg = cast(Object)args.data[i];
1050 ObjectToCBuffer(bufa, &hgs, oarg);
1051 }
1052 }
1053
1054 scope OutBuffer buf = new OutBuffer();
1055 argExpTypesToCBuffer(buf, fargs, &hgs);
1056 error(loc, "cannot deduce template function from argument types !(%s)(%s)", bufa.toChars(), buf.toChars());
1057 }
1058 return null;
1059 }
1060
1061 /**************************************************
1062 * Declare template parameter tp with value o, and install it in the scope sc.
1063 */
1064 void declareParameter(Scope sc, TemplateParameter tp, Object o)
1065 {
1066 //printf("TemplateDeclaration.declareParameter('%s', o = %p)\n", tp.ident.toChars(), o);
1067
1068 Type targ = isType(o);
1069 Expression ea = isExpression(o);
1070 Dsymbol sa = isDsymbol(o);
1071 Tuple va = isTuple(o);
1072
1073 Dsymbol s;
1074
1075 // See if tp.ident already exists with a matching definition
1076 Dsymbol scopesym;
1077 s = sc.search(loc, tp.ident, &scopesym);
1078 if (s && scopesym == sc.scopesym)
1079 {
1080 TupleDeclaration td = s.isTupleDeclaration();
1081 if (va && td)
1082 {
1083 Tuple tup = new Tuple();
1084 assert(false); // < not implemented
1085 ///tup.objects = *td.objects;
1086 if (match(va, tup, this, sc))
1087 {
1088 return;
1089 }
1090 }
1091 }
1092
1093 if (targ)
1094 {
1095 //printf("type %s\n", targ.toChars());
1096 s = new AliasDeclaration(Loc(0), tp.ident, targ);
1097 }
1098 else if (sa)
1099 {
1100 //printf("Alias %s %s;\n", sa.ident.toChars(), tp.ident.toChars());
1101 s = new AliasDeclaration(Loc(0), tp.ident, sa);
1102 }
1103 else if (ea)
1104 {
1105 // tdtypes.data[i] always matches ea here
1106 Initializer init = new ExpInitializer(loc, ea);
1107 TemplateValueParameter tvp = tp.isTemplateValueParameter();
1108
1109 Type t = tvp ? tvp.valType : null;
1110
1111 VarDeclaration v = new VarDeclaration(loc, t, tp.ident, init);
1112 v.storage_class = STCmanifest;
1113 s = v;
1114 }
1115 else if (va)
1116 {
1117 //printf("\ttuple\n");
1118 s = new TupleDeclaration(loc, tp.ident, va.objects);
1119 }
1120 else
1121 {
1122 debug writefln(o.toString());
1123 assert(0);
1124 }
1125
1126 if (!sc.insert(s))
1127 error("declaration %s is already defined", tp.ident.toChars());
1128
1129 s.semantic(sc);
1130 }
1131
1132 TemplateDeclaration isTemplateDeclaration() { return this; }
1133
1134 TemplateTupleParameter isVariadic()
1135 {
1136 return .isVariadic(parameters);
1137 }
1138
1139 bool isOverloadable()
1140 {
1141 assert(false);
1142 }
1143 }