comparison dmd/expression/Util.d @ 0:10317f0c89a5

Initial commit
author korDen
date Sat, 24 Oct 2009 08:42:06 +0400
parents
children 5c9b78899f5d
comparison
equal deleted inserted replaced
-1:000000000000 0:10317f0c89a5
1 module dmd.expression.Util;
2
3 import dmd.Expression;
4 import dmd.Loc;
5 import dmd.BUILTIN;
6 import dmd.Scope;
7 import dmd.FuncExp;
8 import dmd.DelegateExp;
9 import dmd.LINK;
10 import dmd.NullExp;
11 import dmd.SymOffExp;
12 import dmd.ExpInitializer;
13 import dmd.Lexer;
14 import dmd.TypeSArray;
15 import dmd.TypeArray;
16 import dmd.VarDeclaration;
17 import dmd.VoidInitializer;
18 import dmd.DeclarationExp;
19 import dmd.VarExp;
20 import dmd.NewExp;
21 import dmd.STC;
22 import dmd.WANT;
23 import dmd.IndexExp;
24 import dmd.AssignExp;
25 import dmd.CommaExp;
26 import dmd.Argument;
27 import dmd.DefaultInitExp;
28 import dmd.Identifier;
29 import dmd.Dsymbol;
30 import dmd.Global;
31 import dmd.ScopeDsymbol;
32 import dmd.DotIdExp;
33 import dmd.DotVarExp;
34 import dmd.CallExp;
35 import dmd.TY;
36 import dmd.MATCH;
37 import dmd.TypeFunction;
38 import dmd.declaration.Match;
39 import dmd.ArrayTypes;
40 import dmd.Declaration;
41 import dmd.FuncAliasDeclaration;
42 import dmd.AliasDeclaration;
43 import dmd.FuncDeclaration;
44 import dmd.TemplateDeclaration;
45 import dmd.AggregateDeclaration;
46 import dmd.IntegerExp;
47 import dmd.Type;
48 import dmd.TOK;
49 import dmd.TypeExp;
50 import dmd.TypeTuple;
51 import dmd.TupleExp;
52 import dmd.OutBuffer;
53 import dmd.HdrGenState;
54 import dmd.ClassDeclaration;
55 import dmd.TypeClass;
56 import dmd.StructDeclaration;
57 import dmd.TypeStruct;
58 import dmd.MOD;
59 import dmd.PROT;
60 import dmd.PREC;
61 import dmd.Util;
62 import dmd.TypeAArray;
63 import dmd.Id;
64
65 import std.stdio : writef;
66
67
68 /***********************************
69 * Utility to build a function call out of this reference and argument.
70 */
71 Expression build_overload(Loc loc, Scope sc, Expression ethis, Expression earg, Identifier id)
72 {
73 Expression e;
74
75 //printf("build_overload(id = '%s')\n", id.toChars());
76 //earg.print();
77 //earg.type.print();
78 e = new DotIdExp(loc, ethis, id);
79
80 if (earg)
81 e = new CallExp(loc, e, earg);
82 else
83 e = new CallExp(loc, e);
84
85 e = e.semantic(sc);
86 return e;
87 }
88
89 /***************************************
90 * Search for function funcid in aggregate ad.
91 */
92
93 Dsymbol search_function(ScopeDsymbol ad, Identifier funcid)
94 {
95 Dsymbol s;
96 FuncDeclaration fd;
97 TemplateDeclaration td;
98
99 s = ad.search(Loc(0), funcid, 0);
100 if (s)
101 {
102 Dsymbol s2;
103
104 //printf("search_function: s = '%s'\n", s.kind());
105 s2 = s.toAlias();
106 //printf("search_function: s2 = '%s'\n", s2.kind());
107 fd = s2.isFuncDeclaration();
108 if (fd && fd.type.ty == TY.Tfunction)
109 return fd;
110
111 td = s2.isTemplateDeclaration();
112 if (td)
113 return td;
114 }
115
116 return null;
117 }
118
119 /********************************************
120 * Find function in overload list that exactly matches t.
121 */
122
123 /***************************************************
124 * Visit each overloaded function in turn, and call
125 * dg(param, f) on it.
126 * Exit when no more, or dg(param, f) returns 1.
127 * Returns:
128 * 0 continue
129 * 1 done
130 */
131
132 int overloadApply(FuncDeclaration fstart, int delegate(FuncDeclaration) dg)
133 {
134 FuncDeclaration f;
135 Declaration d;
136 Declaration next;
137
138 for (d = fstart; d; d = next)
139 {
140 FuncAliasDeclaration fa = d.isFuncAliasDeclaration();
141
142 if (fa)
143 {
144 if (overloadApply(fa.funcalias, dg))
145 return 1;
146 next = fa.overnext;
147 }
148 else
149 {
150 AliasDeclaration a = d.isAliasDeclaration();
151
152 if (a)
153 {
154 Dsymbol s = a.toAlias();
155 next = s.isDeclaration();
156 if (next is a)
157 break;
158 if (next is fstart)
159 break;
160 }
161 else
162 {
163 f = d.isFuncDeclaration();
164 if (f is null)
165 {
166 d.error("is aliased to a function");
167 break; // BUG: should print error message?
168 }
169 if (dg(f))
170 return 1;
171
172 next = f.overnext;
173 }
174 }
175 }
176 return 0;
177 }
178
179 /********************************************
180 * Decide which function matches the arguments best.
181 */
182
183 struct Param2
184 {
185 Match* m;
186 Expression ethis;
187 Expressions arguments;
188
189 int fp2(FuncDeclaration f)
190 {
191 MATCH match;
192
193 if (f != m.lastf) // skip duplicates
194 {
195 m.anyf = f;
196 TypeFunction tf = cast(TypeFunction)f.type;
197 match = tf.callMatch(f.needThis() ? ethis : null, arguments);
198 //printf("match = %d\n", match);
199 if (match != MATCH.MATCHnomatch)
200 {
201 if (match > m.last)
202 goto LfIsBetter;
203
204 if (match < m.last)
205 goto LlastIsBetter;
206
207 /* See if one of the matches overrides the other.
208 */
209 if (m.lastf.overrides(f))
210 goto LlastIsBetter;
211 else if (f.overrides(m.lastf))
212 goto LfIsBetter;
213
214 /* Try to disambiguate using template-style partial ordering rules.
215 * In essence, if f() and g() are ambiguous, if f() can call g(),
216 * but g() cannot call f(), then pick f().
217 * This is because f() is "more specialized."
218 */
219 {
220 MATCH c1 = f.leastAsSpecialized(m.lastf);
221 MATCH c2 = m.lastf.leastAsSpecialized(f);
222 //printf("c1 = %d, c2 = %d\n", c1, c2);
223 if (c1 > c2)
224 goto LfIsBetter;
225 if (c1 < c2)
226 goto LlastIsBetter;
227 }
228
229 Lambiguous:
230 m.nextf = f;
231 m.count++;
232 return 0;
233
234 LfIsBetter:
235 m.last = match;
236 m.lastf = f;
237 m.count = 1;
238 return 0;
239
240 LlastIsBetter:
241 return 0;
242 }
243 }
244 return 0;
245 }
246 }
247
248 struct Param1
249 {
250 Type t; // type to match
251 FuncDeclaration f; // return value
252
253 int fp1(FuncDeclaration f)
254 {
255 if (t.equals(f.type))
256 {
257 this.f = f;
258 return 1;
259 }
260
261 version (DMDV2) {
262 /* Allow covariant matches, if it's just a const conversion
263 * of the return type
264 */
265 if (t.ty == Tfunction)
266 {
267 TypeFunction tf = cast(TypeFunction)f.type;
268 if (tf.covariant(t) == 1 &&
269 tf.nextOf().implicitConvTo(t.nextOf()) >= MATCHconst)
270 {
271 this.f = f;
272 return 1;
273 }
274 }
275 }
276 return 0;
277 }
278 }
279
280 void overloadResolveX(Match* m, FuncDeclaration fstart, Expression ethis, Expressions arguments)
281 {
282 Param2 p;
283 p.m = m;
284 p.ethis = ethis;
285 p.arguments = arguments;
286 overloadApply(fstart, &p.fp2);
287 }
288
289 void templateResolve(Match* m, TemplateDeclaration td, Scope sc, Loc loc, Objects targsi, Expression ethis, Expressions arguments)
290 {
291 FuncDeclaration fd;
292
293 assert(td);
294 fd = td.deduceFunctionTemplate(sc, loc, targsi, ethis, arguments);
295 if (!fd)
296 return;
297 m.anyf = fd;
298 if (m.last >= MATCH.MATCHexact)
299 {
300 m.nextf = fd;
301 m.count++;
302 }
303 else
304 {
305 m.last = MATCH.MATCHexact;
306 m.lastf = fd;
307 m.count = 1;
308 }
309 }
310
311 /******************************
312 * Perform semantic() on an array of Expressions.
313 */
314
315 void arrayExpressionSemantic(Expressions exps, Scope sc)
316 {
317 if (exps)
318 {
319 for (size_t i = 0; i < exps.dim; i++)
320 {
321 Expression e = cast(Expression)exps.data[i];
322
323 e = e.semantic(sc);
324 exps.data[i] = cast(void*)e;
325 }
326 }
327 }
328
329 /****************************************
330 * Preprocess arguments to function.
331 */
332
333 void preFunctionArguments(Loc loc, Scope sc, Expressions exps)
334 {
335 if (exps)
336 {
337 expandTuples(exps);
338
339 for (size_t i = 0; i < exps.dim; i++)
340 {
341 Expression arg = cast(Expression)exps.data[i];
342
343 if (!arg.type)
344 {
345 debug {
346 if (!global.gag)
347 writef("1: \n");
348 }
349 arg.error("%s is not an expression", arg.toChars());
350 arg = new IntegerExp(arg.loc, 0, Type.tint32);
351 }
352
353 arg = resolveProperties(sc, arg);
354 exps.data[i] = cast(void*) arg;
355
356 //arg.rvalue();
357 static if (false) {
358 if (arg.type.ty == TY.Tfunction)
359 {
360 arg = new AddrExp(arg.loc, arg);
361 arg = arg.semantic(sc);
362 exps.data[i] = cast(void*) arg;
363 }
364 }
365 }
366 }
367 }
368
369 /*************************************************************
370 * Given var, we need to get the
371 * right 'this' pointer if var is in an outer class, but our
372 * existing 'this' pointer is in an inner class.
373 * Input:
374 * e1 existing 'this'
375 * ad struct or class we need the correct 'this' for
376 * var the specific member of ad we're accessing
377 */
378
379 Expression getRightThis(Loc loc, Scope sc, AggregateDeclaration ad, Expression e1, Declaration var)
380 {
381 //printf("\ngetRightThis(e1 = %s, ad = %s, var = %s)\n", e1.toChars(), ad.toChars(), var.toChars());
382 L1:
383 Type t = e1.type.toBasetype();
384 //printf("e1.type = %s, var.type = %s\n", e1.type.toChars(), var.type.toChars());
385
386 /* If e1 is not the 'this' pointer for ad
387 */
388 if (ad && !(t.ty == TY.Tpointer && t.nextOf().ty == TY.Tstruct && (cast(TypeStruct)t.nextOf()).sym == ad) && !(t.ty == TY.Tstruct && (cast(TypeStruct)t).sym == ad))
389 {
390 ClassDeclaration cd = ad.isClassDeclaration();
391 ClassDeclaration tcd = t.isClassHandle();
392
393 /* e1 is the right this if ad is a base class of e1
394 */
395 if (!cd || !tcd || !(tcd == cd || cd.isBaseOf(tcd, null)))
396 {
397 /* Only classes can be inner classes with an 'outer'
398 * member pointing to the enclosing class instance
399 */
400 if (tcd && tcd.isNested())
401 {
402 /* e1 is the 'this' pointer for an inner class: tcd.
403 * Rewrite it as the 'this' pointer for the outer class.
404 */
405
406 e1 = new DotVarExp(loc, e1, tcd.vthis);
407 e1.type = tcd.vthis.type;
408 // Do not call checkNestedRef()
409 //e1 = e1.semantic(sc);
410
411 // Skip up over nested functions, and get the enclosing
412 // class type.
413 int n = 0;
414 Dsymbol s;
415 for (s = tcd.toParent(); s && s.isFuncDeclaration(); s = s.toParent())
416 {
417 FuncDeclaration f = s.isFuncDeclaration();
418 if (f.vthis)
419 {
420 //printf("rewriting e1 to %s's this\n", f.toChars());
421 n++;
422 e1 = new VarExp(loc, f.vthis);
423 }
424 }
425 if (s && s.isClassDeclaration())
426 {
427 e1.type = s.isClassDeclaration().type;
428 if (n > 1)
429 e1 = e1.semantic(sc);
430 }
431 else
432 e1 = e1.semantic(sc);
433 goto L1;
434 }
435 /* Can't find a path from e1 to ad
436 */
437 e1.error("this for %s needs to be type %s not type %s", var.toChars(), ad.toChars(), t.toChars());
438 }
439 }
440 return e1;
441 }
442
443 /*******************************************
444 * Given a symbol that could be either a FuncDeclaration or
445 * a function template, resolve it to a function symbol.
446 * sc instantiation scope
447 * loc instantiation location
448 * targsi initial list of template arguments
449 * ethis if !null, the 'this' pointer argument
450 * fargs arguments to function
451 * flags 1: do not issue error message on no match, just return null
452 */
453
454 FuncDeclaration resolveFuncCall(Scope sc, Loc loc, Dsymbol s,
455 Objects tiargs,
456 Expression ethis,
457 Expressions arguments,
458 int flags)
459 {
460 if (!s)
461 return null; // no match
462 FuncDeclaration f = s.isFuncDeclaration();
463 if (f)
464 f = f.overloadResolve(loc, ethis, arguments);
465 else
466 {
467 TemplateDeclaration td = s.isTemplateDeclaration();
468 assert(td);
469 f = td.deduceFunctionTemplate(sc, loc, tiargs, null, arguments, flags);
470 }
471 return f;
472 }
473
474 /****************************************
475 * Now that we know the exact type of the function we're calling,
476 * the arguments[] need to be adjusted:
477 * 1. implicitly convert argument to the corresponding parameter type
478 * 2. add default arguments for any missing arguments
479 * 3. do default promotions on arguments corresponding to ...
480 * 4. add hidden _arguments[] argument
481 * 5. call copy constructor for struct value arguments
482 */
483
484 void functionArguments(Loc loc, Scope sc, TypeFunction tf, Expressions arguments)
485 {
486 uint n;
487
488 //printf("functionArguments()\n");
489 assert(arguments);
490 size_t nargs = arguments ? arguments.dim : 0;
491 size_t nparams = Argument.dim(tf.parameters);
492
493 if (nargs > nparams && tf.varargs == 0)
494 error(loc, "expected %zu arguments, not %zu for non-variadic function type %s", nparams, nargs, tf.toChars());
495
496 n = (nargs > nparams) ? nargs : nparams; // n = max(nargs, nparams)
497
498 int done = 0;
499 for (size_t i = 0; i < n; i++)
500 {
501 Expression arg;
502
503 if (i < nargs)
504 arg = cast(Expression)arguments.data[i];
505 else
506 arg = null;
507
508 Type tb;
509
510 if (i < nparams)
511 {
512 Argument p = Argument.getNth(tf.parameters, i);
513
514 if (!arg)
515 {
516 if (!p.defaultArg)
517 {
518 if (tf.varargs == 2 && i + 1 == nparams)
519 goto L2;
520
521 error(loc, "expected %d function arguments, not %d", nparams, nargs);
522 break;
523 }
524 arg = p.defaultArg;
525 version (DMDV2) {
526 if (arg.op == TOK.TOKdefault)
527 {
528 DefaultInitExp de = cast(DefaultInitExp)arg;
529 arg = de.resolve(loc, sc);
530 }
531 else
532 {
533 arg = arg.copy();
534 }
535 } else {
536 arg = arg.copy();
537 }
538 arguments.push(cast(void*)arg);
539 nargs++;
540 }
541
542 if (tf.varargs == 2 && i + 1 == nparams)
543 {
544 //printf("\t\tvarargs == 2, p.type = '%s'\n", p.type.toChars());
545 if (arg.implicitConvTo(p.type))
546 {
547 if (nargs != nparams)
548 error(loc, "expected %zu function arguments, not %zu", nparams, nargs);
549 goto L1;
550 }
551 L2:
552 tb = p.type.toBasetype(); ///
553 Type tret = p.isLazyArray();
554 switch (tb.ty)
555 {
556 case TY.Tsarray:
557 case TY.Tarray:
558 { // Create a static array variable v of type arg.type
559 version (IN_GCC) {
560 /* GCC 4.0 does not like zero length arrays used like
561 this; pass a null array value instead. Could also
562 just make a one-element array. */
563 if (nargs - i == 0)
564 {
565 arg = new NullExp(loc);
566 break;
567 }
568 }
569 Identifier id = Lexer.uniqueId("__arrayArg");
570 Type t = new TypeSArray((cast(TypeArray)tb).next, new IntegerExp(nargs - i));
571 t = t.semantic(loc, sc);
572 VarDeclaration v = new VarDeclaration(loc, t, id, new VoidInitializer(loc));
573 v.semantic(sc);
574 v.parent = sc.parent;
575 //sc.insert(v);
576
577 Expression c = new DeclarationExp(Loc(0), v);
578 c.type = v.type;
579
580 for (size_t u = i; u < nargs; u++)
581 {
582 Expression a = cast(Expression)arguments.data[u];
583 if (tret && !(cast(TypeArray)tb).next.equals(a.type))
584 a = a.toDelegate(sc, tret);
585
586 Expression e = new VarExp(loc, v);
587 e = new IndexExp(loc, e, new IntegerExp(u + 1 - nparams));
588 AssignExp ae = new AssignExp(loc, e, a);
589
590 version (DMDV2) {
591 ae.op = TOK.TOKconstruct;
592 }
593
594 if (c)
595 c = new CommaExp(loc, c, ae);
596 else
597 c = ae;
598 }
599
600 arg = new VarExp(loc, v);
601 if (c)
602 arg = new CommaExp(loc, c, arg);
603 break;
604 }
605
606 case TY.Tclass:
607 { /* Set arg to be:
608 * new Tclass(arg0, arg1, ..., argn)
609 */
610 Expressions args = new Expressions();
611 args.setDim(nargs - i);
612 for (size_t u = i; u < nargs; u++)
613 args.data[u - i] = arguments.data[u];
614 arg = new NewExp(loc, null, null, p.type, args);
615 break;
616 }
617
618 default:
619 if (!arg)
620 {
621 error(loc, "not enough arguments");
622 return;
623 }
624 break;
625 }
626
627 arg = arg.semantic(sc);
628 //printf("\targ = '%s'\n", arg.toChars());
629 arguments.setDim(i + 1);
630 done = 1;
631 }
632
633 L1:
634 if (!(p.storageClass & STC.STClazy && p.type.ty == TY.Tvoid))
635 {
636 if (p.type != arg.type)
637 {
638 //printf("arg.type = %s, p.type = %s\n", arg.type.toChars(), p.type.toChars());
639 arg = arg.implicitCastTo(sc, p.type);
640 arg = arg.optimize(WANT.WANTvalue);
641 }
642 }
643 if (p.storageClass & STC.STCref)
644 {
645 arg = arg.toLvalue(sc, arg);
646 }
647 else if (p.storageClass & STC.STCout)
648 {
649 arg = arg.modifiableLvalue(sc, arg);
650 }
651
652 // Convert static arrays to pointers
653 tb = arg.type.toBasetype();
654 if (tb.ty == TY.Tsarray)
655 {
656 arg = arg.checkToPointer();
657 }
658 version (DMDV2) {
659 if (tb.ty == TY.Tstruct && !(p.storageClass & (STC.STCref | STC.STCout)))
660 {
661 arg = callCpCtor(loc, sc, arg);
662 }
663 }
664
665 // Convert lazy argument to a delegate
666 if (p.storageClass & STC.STClazy)
667 {
668 arg = arg.toDelegate(sc, p.type);
669 }
670 version (DMDV2) {
671 /* Look for arguments that cannot 'escape' from the called
672 * function.
673 */
674 if (!tf.parameterEscapes(p))
675 {
676 /* Function literals can only appear once, so if this
677 * appearance was scoped, there cannot be any others.
678 */
679 if (arg.op == TOK.TOKfunction)
680 {
681 FuncExp fe = cast(FuncExp)arg;
682 fe.fd.tookAddressOf = 0;
683 }
684
685 /* For passing a delegate to a scoped parameter,
686 * this doesn't count as taking the address of it.
687 * We only worry about 'escaping' references to the function.
688 */
689 else if (arg.op == TOK.TOKdelegate)
690 {
691 DelegateExp de = cast(DelegateExp)arg;
692 if (de.e1.op == TOK.TOKvar)
693 {
694 VarExp ve = cast(VarExp)de.e1;
695 FuncDeclaration f = ve.var.isFuncDeclaration();
696 if (f)
697 {
698 f.tookAddressOf--;
699 //printf("tookAddressOf = %d\n", f.tookAddressOf);
700 }
701 }
702 }
703 }
704 }
705 }
706 else
707 {
708 // If not D linkage, do promotions
709 if (tf.linkage != LINK.LINKd)
710 {
711 // Promote bytes, words, etc., to ints
712 arg = arg.integralPromotions(sc);
713
714 // Promote floats to doubles
715 switch (arg.type.ty)
716 {
717 case TY.Tfloat32:
718 arg = arg.castTo(sc, Type.tfloat64);
719 break;
720
721 case TY.Timaginary32:
722 arg = arg.castTo(sc, Type.timaginary64);
723 break;
724 default:
725 break;
726 }
727 }
728
729 // Convert static arrays to dynamic arrays
730 tb = arg.type.toBasetype();
731 if (tb.ty == TY.Tsarray)
732 {
733 TypeSArray ts = cast(TypeSArray)tb;
734 Type ta = ts.next.arrayOf();
735 if (ts.size(arg.loc) == 0)
736 {
737 arg = new NullExp(arg.loc);
738 arg.type = ta;
739 }
740 else
741 {
742 arg = arg.castTo(sc, ta);
743 }
744 }
745 version (DMDV2) {
746 if (tb.ty == TY.Tstruct)
747 {
748 arg = callCpCtor(loc, sc, arg);
749 }
750
751 // Give error for overloaded function addresses
752 if (arg.op == TOK.TOKsymoff)
753 {
754 SymOffExp se = cast(SymOffExp)arg;
755 if (se.hasOverloads && !se.var.isFuncDeclaration().isUnique())
756 arg.error("function %s is overloaded", arg.toChars());
757 }
758 }
759 arg.rvalue();
760 }
761 arg = arg.optimize(WANT.WANTvalue);
762 arguments.data[i] = cast(void*) arg;
763 if (done)
764 break;
765 }
766
767 // If D linkage and variadic, add _arguments[] as first argument
768 if (tf.linkage == LINK.LINKd && tf.varargs == 1)
769 {
770 Expression e = createTypeInfoArray(sc, cast(Expression*)&arguments.data[nparams], arguments.dim - nparams);
771 arguments.insert(0, cast(void*)e);
772 }
773 }
774
775 /****************************************
776 * Expand tuples.
777 */
778
779 void expandTuples(Expressions exps)
780 {
781 //printf("expandTuples()\n");
782 if (exps)
783 {
784 for (size_t i = 0; i < exps.dim; i++)
785 {
786 Expression arg = cast(Expression)exps.data[i];
787 if (!arg)
788 continue;
789
790 // Look for tuple with 0 members
791 if (arg.op == TOK.TOKtype)
792 {
793 TypeExp e = cast(TypeExp)arg;
794 if (e.type.toBasetype().ty == TY.Ttuple)
795 {
796 TypeTuple tt = cast(TypeTuple)e.type.toBasetype();
797
798 if (!tt.arguments || tt.arguments.dim == 0)
799 {
800 exps.remove(i);
801 if (i == exps.dim)
802 return;
803 i--;
804 continue;
805 }
806 }
807 }
808
809 // Inline expand all the tuples
810 while (arg.op == TOK.TOKtuple)
811 {
812 TupleExp te = cast(TupleExp)arg;
813
814 exps.remove(i); // remove arg
815 exps.insert(i, cast(void*)te.exps); // replace with tuple contents
816
817 if (i == exps.dim)
818 return; // empty tuple, no more arguments
819
820 arg = cast(Expression)exps.data[i];
821 }
822 }
823 }
824 }
825
826 /**************************************************
827 * Write out argument types to buf.
828 */
829
830 void argExpTypesToCBuffer(OutBuffer buf, Expressions arguments, HdrGenState* hgs)
831 {
832 if (arguments)
833 {
834 scope OutBuffer argbuf = new OutBuffer();
835
836 for (size_t i = 0; i < arguments.dim; i++)
837 {
838 Expression arg = cast(Expression)arguments.data[i];
839
840 if (i)
841 buf.writeByte(',');
842
843 argbuf.reset();
844 arg.type.toCBuffer2(argbuf, hgs, MOD.MODundefined);
845 buf.write(argbuf);
846 }
847 }
848 }
849
850 /****************************************
851 * Determine if scope sc has package level access to s.
852 */
853
854 bool hasPackageAccess(Scope sc, Dsymbol s)
855 {
856 version (LOG) {
857 printf("hasPackageAccess(s = '%s', sc = '%p')\n", s.toChars(), sc);
858 }
859
860 for (; s; s = s.parent)
861 {
862 if (s.isPackage() && !s.isModule())
863 break;
864 }
865 version (LOG) {
866 if (s)
867 printf("\tthis is in package '%s'\n", s.toChars());
868 }
869
870 if (s && s == sc.module_.parent)
871 {
872 version (LOG) {
873 printf("\ts is in same package as sc\n");
874 }
875 return true;
876 }
877
878
879 version (LOG) {
880 printf("\tno package access\n");
881 }
882
883 return false;
884 }
885
886 /*********************************************
887 * Call copy constructor for struct value argument.
888 */
889 version (DMDV2) {
890 Expression callCpCtor(Loc loc, Scope sc, Expression e)
891 {
892 Type tb = e.type.toBasetype();
893 assert(tb.ty == Tstruct);
894 StructDeclaration sd = (cast(TypeStruct)tb).sym;
895 if (sd.cpctor)
896 {
897 /* Create a variable tmp, and replace the argument e with:
898 * (tmp = e),tmp
899 * and let AssignExp() handle the construction.
900 * This is not the most efficent, ideally tmp would be constructed
901 * directly onto the stack.
902 */
903 Identifier idtmp = Lexer.uniqueId("__tmp");
904 VarDeclaration tmp = new VarDeclaration(loc, tb, idtmp, new ExpInitializer(Loc(0), e));
905 Expression ae = new DeclarationExp(loc, tmp);
906 e = new CommaExp(loc, ae, new VarExp(loc, tmp));
907 e = e.semantic(sc);
908 }
909 return e;
910 }
911 }
912
913 /***************************************
914 * Create a static array of TypeInfo references
915 * corresponding to an array of Expression's.
916 * Used to supply hidden _arguments[] value for variadic D functions.
917 */
918
919 Expression createTypeInfoArray(Scope sc, Expression* exps, int dim)
920 {
921 assert(false);
922 }
923
924 /**************************************
925 * Evaluate builtin function.
926 * Return result: null if cannot evaluate it.
927 */
928
929 Expression eval_builtin(BUILTIN builtin, Expressions arguments)
930 {
931 assert(false);
932 }
933
934 Expression fromConstInitializer(int result, Expression e1)
935 {
936 //printf("fromConstInitializer(result = %x, %s)\n", result, e1.toChars());
937 //static int xx; if (xx++ == 10) assert(0);
938 Expression e = e1;
939 if (e1.op == TOK.TOKvar)
940 {
941 VarExp ve = cast(VarExp)e1;
942 VarDeclaration v = ve.var.isVarDeclaration();
943 e = expandVar(result, v);
944 if (e)
945 {
946 if (e.type != e1.type)
947 {
948 // Type 'paint' operation
949 e = e.copy();
950 e.type = e1.type;
951 }
952 }
953 else
954 {
955 e = e1;
956 }
957 }
958 return e;
959 }
960
961 /*************************************
962 * If variable has a const initializer,
963 * return that initializer.
964 */
965
966 Expression expandVar(int result, VarDeclaration v)
967 {
968 //printf("expandVar(result = %d, v = %p, %s)\n", result, v, v ? v.toChars() : "null");
969
970 Expression e = null;
971 if (!v)
972 return e;
973
974 if (v.isConst() || v.isInvariant() || v.storage_class & STC.STCmanifest)
975 {
976 if (!v.type)
977 {
978 //error("ICE");
979 return e;
980 }
981
982 Type tb = v.type.toBasetype();
983 if (result & WANT.WANTinterpret || v.storage_class & STC.STCmanifest || (tb.ty != TY.Tsarray && tb.ty != TY.Tstruct))
984 {
985 if (v.init)
986 {
987 if (v.inuse)
988 {
989 if (v.storage_class & STC.STCmanifest)
990 v.error("recursive initialization of constant");
991 goto L1;
992 }
993 Expression ei = v.init.toExpression();
994 if (!ei)
995 goto L1;
996 if (ei.op == TOK.TOKconstruct || ei.op == TOK.TOKblit)
997 {
998 AssignExp ae = cast(AssignExp)ei;
999 ei = ae.e2;
1000 if (ei.isConst() != 1 && ei.op != TOK.TOKstring)
1001 goto L1;
1002 if (ei.type != v.type)
1003 goto L1;
1004 }
1005 if (v.scope_)
1006 {
1007 v.inuse++;
1008 e = ei.syntaxCopy();
1009 e = e.semantic(v.scope_);
1010 e = e.implicitCastTo(v.scope_, v.type);
1011 // enabling this line causes test22 in test suite to fail
1012 //ei.type = e.type;
1013 v.scope_ = null;
1014 v.inuse--;
1015 }
1016 else if (!ei.type)
1017 {
1018 goto L1;
1019 }
1020 else
1021 // Should remove the copy() operation by
1022 // making all mods to expressions copy-on-write
1023 e = ei.copy();
1024 }
1025 else
1026 {
1027 static if (true) {
1028 goto L1;
1029 } else {
1030 // BUG: what if const is initialized in constructor?
1031 e = v.type.defaultInit();
1032 e.loc = e1.loc;
1033 }
1034 }
1035 if (e.type != v.type)
1036 {
1037 e = e.castTo(null, v.type);
1038 }
1039 v.inuse++;
1040 e = e.optimize(result);
1041 v.inuse--;
1042 }
1043 }
1044 L1:
1045 //if (e) printf("\te = %s, e.type = %s\n", e.toChars(), e.type.toChars());
1046 return e;
1047 }
1048
1049 /****************************************
1050 * Check access to d for expression e.d
1051 */
1052
1053 void accessCheck(Loc loc, Scope sc, Expression e, Declaration d)
1054 {
1055 version (LOG) {
1056 if (e)
1057 {
1058 printf("accessCheck(%s . %s)\n", e.toChars(), d.toChars());
1059 printf("\te.type = %s\n", e.type.toChars());
1060 }
1061 else
1062 {
1063 //printf("accessCheck(%s)\n", d.toChars());
1064 }
1065 }
1066 if (!e)
1067 {
1068 if (d.prot() == PROT.PROTprivate && d.getModule() != sc.module_ ||
1069 d.prot() == PROT.PROTpackage && !hasPackageAccess(sc, d))
1070
1071 error(loc, "%s %s.%s is not accessible from %s",
1072 d.kind(), d.getModule().toChars(), d.toChars(), sc.module_.toChars());
1073 }
1074 else if (e.type.ty == TY.Tclass)
1075 {
1076 // Do access check
1077 ClassDeclaration cd;
1078
1079 cd = cast(ClassDeclaration)((cast(TypeClass)e.type).sym);
1080 static if (true) {
1081 if (e.op == TOK.TOKsuper)
1082 {
1083 ClassDeclaration cd2 = sc.func.toParent().isClassDeclaration();
1084 if (cd2)
1085 cd = cd2;
1086 }
1087 }
1088 cd.accessCheck(loc, sc, d);
1089 }
1090 else if (e.type.ty == TY.Tstruct)
1091 {
1092 // Do access check
1093 StructDeclaration cd = cast(StructDeclaration)((cast(TypeStruct)e.type).sym);
1094 cd.accessCheck(loc, sc, d);
1095 }
1096 }
1097
1098 /*****************************************
1099 * Given array of arguments and an aggregate type,
1100 * if any of the argument types are missing, attempt to infer
1101 * them from the aggregate type.
1102 */
1103
1104 void inferApplyArgTypes(TOK op, Arguments arguments, Expression aggr)
1105 {
1106 if (!arguments || !arguments.dim)
1107 return;
1108
1109 /* Return if no arguments need types.
1110 */
1111 for (size_t u = 0; 1; u++)
1112 {
1113 if (u == arguments.dim)
1114 return;
1115
1116 Argument arg = cast(Argument)arguments.data[u];
1117 if (!arg.type)
1118 break;
1119 }
1120
1121 AggregateDeclaration ad;
1122
1123 Argument arg = cast(Argument)arguments.data[0];
1124 Type taggr = aggr.type;
1125 if (!taggr)
1126 return;
1127 Type tab = taggr.toBasetype();
1128 switch (tab.ty)
1129 {
1130 case TY.Tarray:
1131 case TY.Tsarray:
1132 case TY.Ttuple:
1133 if (arguments.dim == 2)
1134 {
1135 if (!arg.type)
1136 arg.type = Type.tsize_t; // key type
1137 arg = cast(Argument)arguments.data[1];
1138 }
1139 if (!arg.type && tab.ty != TY.Ttuple)
1140 arg.type = tab.nextOf(); // value type
1141 break;
1142
1143 case TY.Taarray:
1144 {
1145 TypeAArray taa = cast(TypeAArray)tab;
1146
1147 if (arguments.dim == 2)
1148 {
1149 if (!arg.type)
1150 arg.type = taa.index; // key type
1151 arg = cast(Argument)arguments.data[1];
1152 }
1153 if (!arg.type)
1154 arg.type = taa.next; // value type
1155 break;
1156 }
1157
1158 case TY.Tclass:
1159 ad = (cast(TypeClass)tab).sym;
1160 goto Laggr;
1161
1162 case TY.Tstruct:
1163 ad = (cast(TypeStruct)tab).sym;
1164 goto Laggr;
1165
1166 Laggr:
1167 if (arguments.dim == 1)
1168 {
1169 if (!arg.type)
1170 {
1171 /* Look for a head() or rear() overload
1172 */
1173 Identifier id = (op == TOK.TOKforeach) ? Id.Fhead : Id.Ftoe;
1174 Dsymbol s = search_function(ad, id);
1175 FuncDeclaration fd = s ? s.isFuncDeclaration() : null;
1176 if (!fd)
1177 {
1178 if (s && s.isTemplateDeclaration())
1179 break;
1180 goto Lapply;
1181 }
1182 arg.type = fd.type.nextOf();
1183 }
1184 break;
1185 }
1186
1187 Lapply:
1188 { /* Look for an
1189 * int opApply(int delegate(ref Type [, ...]) dg);
1190 * overload
1191 */
1192 Dsymbol s = search_function(ad, (op == TOK.TOKforeach_reverse) ? Id.applyReverse : Id.apply);
1193 if (s)
1194 {
1195 FuncDeclaration fd = s.isFuncDeclaration();
1196 if (fd)
1197 {
1198 inferApplyArgTypesX(fd, arguments);
1199 break;
1200 }
1201 static if (false) {
1202 TemplateDeclaration td = s.isTemplateDeclaration();
1203 if (td)
1204 {
1205 inferApplyArgTypesZ(td, arguments);
1206 break;
1207 }
1208 }
1209 }
1210 break;
1211 }
1212
1213 case TY.Tdelegate:
1214 {
1215 if (0 && aggr.op == TOK.TOKdelegate)
1216 {
1217 DelegateExp de = cast(DelegateExp)aggr;
1218
1219 FuncDeclaration fd = de.func.isFuncDeclaration();
1220 if (fd)
1221 inferApplyArgTypesX(fd, arguments);
1222 }
1223 else
1224 {
1225 inferApplyArgTypesY(cast(TypeFunction)tab.nextOf(), arguments);
1226 }
1227 break;
1228 }
1229
1230 default:
1231 break; // ignore error, caught later
1232 }
1233 }
1234
1235 struct Param3
1236 {
1237 /********************************
1238 * Recursive helper function,
1239 * analogous to func.overloadResolveX().
1240 */
1241
1242 int fp3(FuncDeclaration f)
1243 {
1244 TypeFunction tf = cast(TypeFunction)f.type;
1245 if (inferApplyArgTypesY(tf, arguments) == 1)
1246 return 0;
1247
1248 if (arguments.dim == 0)
1249 return 1;
1250
1251 return 0;
1252 }
1253
1254 Arguments arguments;
1255 }
1256
1257 void inferApplyArgTypesX(FuncDeclaration fstart, Arguments arguments)
1258 {
1259 Param3 p3;
1260 p3.arguments = arguments;
1261 overloadApply(fstart, &p3.fp3);
1262 }
1263
1264 /******************************
1265 * Infer arguments from type of function.
1266 * Returns:
1267 * 0 match for this function
1268 * 1 no match for this function
1269 */
1270
1271 int inferApplyArgTypesY(TypeFunction tf, Arguments arguments)
1272 {
1273 size_t nparams;
1274 Argument p;
1275
1276 if (Argument.dim(tf.parameters) != 1)
1277 goto Lnomatch;
1278
1279 p = Argument.getNth(tf.parameters, 0);
1280 if (p.type.ty != TY.Tdelegate)
1281 goto Lnomatch;
1282
1283 tf = cast(TypeFunction)p.type.nextOf();
1284 assert(tf.ty == TY.Tfunction);
1285
1286 /* We now have tf, the type of the delegate. Match it against
1287 * the arguments, filling in missing argument types.
1288 */
1289 nparams = Argument.dim(tf.parameters);
1290 if (nparams == 0 || tf.varargs)
1291 goto Lnomatch; // not enough parameters
1292 if (arguments.dim != nparams)
1293 goto Lnomatch; // not enough parameters
1294
1295 for (size_t u = 0; u < nparams; u++)
1296 {
1297 Argument arg = cast(Argument)arguments.data[u];
1298 Argument param = Argument.getNth(tf.parameters, u);
1299 if (arg.type)
1300 {
1301 if (!arg.type.equals(param.type))
1302 {
1303 /* Cannot resolve argument types. Indicate an
1304 * error by setting the number of arguments to 0.
1305 */
1306 arguments.dim = 0;
1307 goto Lmatch;
1308 }
1309 continue;
1310 }
1311 arg.type = param.type;
1312 }
1313
1314 Lmatch:
1315 return 0;
1316
1317 Lnomatch:
1318 return 1;
1319 }
1320
1321 /**************************************************
1322 * Write expression out to buf, but wrap it
1323 * in ( ) if its precedence is less than pr.
1324 */
1325
1326 void expToCBuffer(OutBuffer buf, HdrGenState* hgs, Expression e, PREC pr)
1327 {
1328 //if (precedence[e.op] == 0) e.dump(0);
1329 if (precedence[e.op] < pr ||
1330 /* Despite precedence, we don't allow a<b<c expressions.
1331 * They must be parenthesized.
1332 */
1333 (pr == PREC.PREC_rel && precedence[e.op] == pr))
1334 {
1335 buf.writeByte('(');
1336 e.toCBuffer(buf, hgs);
1337 buf.writeByte(')');
1338 }
1339 else
1340 e.toCBuffer(buf, hgs);
1341 }
1342
1343 /**************************************************
1344 * Write out argument list to buf.
1345 */
1346
1347 void argsToCBuffer(OutBuffer buf, Expressions arguments, HdrGenState* hgs)
1348 {
1349 if (arguments)
1350 {
1351 for (size_t i = 0; i < arguments.dim; i++)
1352 {
1353 Expression arg = cast(Expression)arguments.data[i];
1354
1355 if (arg)
1356 {
1357 if (i)
1358 buf.writeByte(',');
1359 expToCBuffer(buf, hgs, arg, PREC.PREC_assign);
1360 }
1361 }
1362 }
1363 }