1
2 /* Compiler implementation of the D programming language
3 * Copyright (C) 1999-2019 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/cast.c
9 */
10
11 #include "root/dsystem.h" // mem{set|cpy}()
12 #include "root/rmem.h"
13
14 #include "mars.h"
15 #include "expression.h"
16 #include "mtype.h"
17 #include "utf.h"
18 #include "declaration.h"
19 #include "aggregate.h"
20 #include "template.h"
21 #include "scope.h"
22 #include "id.h"
23 #include "init.h"
24 #include "tokens.h"
25
26 FuncDeclaration *isFuncAddress(Expression *e, bool *hasOverloads = NULL);
27 bool isCommutative(TOK op);
28 MOD MODmerge(MOD mod1, MOD mod2);
29 Expression *semantic(Expression *e, Scope *sc);
30
31 /* ==================== implicitCast ====================== */
32
33 /**************************************
34 * Do an implicit cast.
35 * Issue error if it can't be done.
36 */
37
38
implicitCastTo(Expression * e,Scope * sc,Type * t)39 Expression *implicitCastTo(Expression *e, Scope *sc, Type *t)
40 {
41 class ImplicitCastTo : public Visitor
42 {
43 public:
44 Type *t;
45 Scope *sc;
46 Expression *result;
47
48 ImplicitCastTo(Scope *sc, Type *t)
49 : t(t), sc(sc)
50 {
51 result = NULL;
52 }
53
54 void visit(Expression *e)
55 {
56 //printf("Expression::implicitCastTo(%s of type %s) => %s\n", e->toChars(), e->type->toChars(), t->toChars());
57
58 MATCH match = e->implicitConvTo(t);
59 if (match)
60 {
61 if (match == MATCHconst &&
62 (e->type->constConv(t) ||
63 (!e->isLvalue() && e->type->equivalent(t))))
64 {
65 /* Do not emit CastExp for const conversions and
66 * unique conversions on rvalue.
67 */
68 result = e->copy();
69 result->type = t;
70 return;
71 }
72 result = e->castTo(sc, t);
73 return;
74 }
75
76 result = e->optimize(WANTvalue);
77 if (result != e)
78 {
79 result->accept(this);
80 return;
81 }
82
83 if (t->ty != Terror && e->type->ty != Terror)
84 {
85 if (!t->deco)
86 {
87 e->error("forward reference to type %s", t->toChars());
88 }
89 else
90 {
91 //printf("type %p ty %d deco %p\n", type, type->ty, type->deco);
92 //type = type->semantic(loc, sc);
93 //printf("type %s t %s\n", type->deco, t->deco);
94 e->error("cannot implicitly convert expression (%s) of type %s to %s",
95 e->toChars(), e->type->toChars(), t->toChars());
96 }
97 }
98 result = new ErrorExp();
99 }
100
101 void visit(StringExp *e)
102 {
103 //printf("StringExp::implicitCastTo(%s of type %s) => %s\n", e->toChars(), e->type->toChars(), t->toChars());
104 visit((Expression *)e);
105 if (result->op == TOKstring)
106 {
107 // Retain polysemous nature if it started out that way
108 ((StringExp *)result)->committed = e->committed;
109 }
110 }
111
112 void visit(ErrorExp *e)
113 {
114 result = e;
115 }
116
117 void visit(FuncExp *e)
118 {
119 //printf("FuncExp::implicitCastTo type = %p %s, t = %s\n", e->type, e->type ? e->type->toChars() : NULL, t->toChars());
120 FuncExp *fe;
121 if (e->matchType(t, sc, &fe) > MATCHnomatch)
122 {
123 result = fe;
124 return;
125 }
126 visit((Expression *)e);
127 }
128
129 void visit(ArrayLiteralExp *e)
130 {
131 visit((Expression *)e);
132
133 Type *tb = result->type->toBasetype();
134 if (tb->ty == Tarray && global.params.useTypeInfo && Type::dtypeinfo)
135 semanticTypeInfo(sc, ((TypeDArray *)tb)->next);
136 }
137
138 void visit(SliceExp *e)
139 {
140 visit((Expression *)e);
141 if (result->op != TOKslice)
142 return;
143
144 e = (SliceExp *)result;
145 if (e->e1->op == TOKarrayliteral)
146 {
147 ArrayLiteralExp *ale = (ArrayLiteralExp *)e->e1;
148 Type *tb = t->toBasetype();
149 Type *tx;
150 if (tb->ty == Tsarray)
151 tx = tb->nextOf()->sarrayOf(ale->elements ? ale->elements->dim : 0);
152 else
153 tx = tb->nextOf()->arrayOf();
154 e->e1 = ale->implicitCastTo(sc, tx);
155 }
156 }
157 };
158
159 ImplicitCastTo v(sc, t);
160 e->accept(&v);
161 return v.result;
162 }
163
164 /*******************************************
165 * Return MATCH level of implicitly converting e to type t.
166 * Don't do the actual cast; don't change e.
167 */
168
implicitConvTo(Expression * e,Type * t)169 MATCH implicitConvTo(Expression *e, Type *t)
170 {
171 class ImplicitConvTo : public Visitor
172 {
173 public:
174 Type *t;
175 MATCH result;
176
177 ImplicitConvTo(Type *t)
178 : t(t)
179 {
180 result = MATCHnomatch;
181 }
182
183 void visit(Expression *e)
184 {
185 //static int nest; if (++nest == 10) halt();
186 if (t == Type::terror)
187 return;
188 if (!e->type)
189 {
190 e->error("%s is not an expression", e->toChars());
191 e->type = Type::terror;
192 }
193 Expression *ex = e->optimize(WANTvalue);
194 if (ex->type->equals(t))
195 {
196 result = MATCHexact;
197 return;
198 }
199 if (ex != e)
200 {
201 //printf("\toptimized to %s of type %s\n", e->toChars(), e->type->toChars());
202 result = ex->implicitConvTo(t);
203 return;
204 }
205 MATCH match = e->type->implicitConvTo(t);
206 if (match != MATCHnomatch)
207 {
208 result = match;
209 return;
210 }
211
212 /* See if we can do integral narrowing conversions
213 */
214 if (e->type->isintegral() && t->isintegral() &&
215 e->type->isTypeBasic() && t->isTypeBasic())
216 {
217 IntRange src = getIntRange(e);
218 IntRange target = IntRange::fromType(t);
219 if (target.contains(src))
220 {
221 result = MATCHconvert;
222 return;
223 }
224 }
225 }
226
227 /******
228 * Given expression e of type t, see if we can implicitly convert e
229 * to type tprime, where tprime is type t with mod bits added.
230 * Returns:
231 * match level
232 */
233 static MATCH implicitMod(Expression *e, Type *t, MOD mod)
234 {
235 Type *tprime;
236 if (t->ty == Tpointer)
237 tprime = t->nextOf()->castMod(mod)->pointerTo();
238 else if (t->ty == Tarray)
239 tprime = t->nextOf()->castMod(mod)->arrayOf();
240 else if (t->ty == Tsarray)
241 tprime = t->nextOf()->castMod(mod)->sarrayOf(t->size() / t->nextOf()->size());
242 else
243 tprime = t->castMod(mod);
244
245 return e->implicitConvTo(tprime);
246 }
247
248 static MATCH implicitConvToAddMin(BinExp *e, Type *t)
249 {
250 /* Is this (ptr +- offset)? If so, then ask ptr
251 * if the conversion can be done.
252 * This is to support doing things like implicitly converting a mutable unique
253 * pointer to an immutable pointer.
254 */
255
256 Type *typeb = e->type->toBasetype();
257 Type *tb = t->toBasetype();
258 if (typeb->ty != Tpointer || tb->ty != Tpointer)
259 return MATCHnomatch;
260
261 Type *t1b = e->e1->type->toBasetype();
262 Type *t2b = e->e2->type->toBasetype();
263 if (t1b->ty == Tpointer && t2b->isintegral() &&
264 t1b->equivalent(tb))
265 {
266 // ptr + offset
267 // ptr - offset
268 MATCH m = e->e1->implicitConvTo(t);
269 return (m > MATCHconst) ? MATCHconst : m;
270 }
271 if (t2b->ty == Tpointer && t1b->isintegral() &&
272 t2b->equivalent(tb))
273 {
274 // offset + ptr
275 MATCH m = e->e2->implicitConvTo(t);
276 return (m > MATCHconst) ? MATCHconst : m;
277 }
278
279 return MATCHnomatch;
280 }
281
282 void visit(AddExp *e)
283 {
284 visit((Expression *)e);
285 if (result == MATCHnomatch)
286 result = implicitConvToAddMin(e, t);
287 }
288
289 void visit(MinExp *e)
290 {
291 visit((Expression *)e);
292 if (result == MATCHnomatch)
293 result = implicitConvToAddMin(e, t);
294 }
295
296 void visit(IntegerExp *e)
297 {
298 MATCH m = e->type->implicitConvTo(t);
299 if (m >= MATCHconst)
300 {
301 result = m;
302 return;
303 }
304
305 TY ty = e->type->toBasetype()->ty;
306 TY toty = t->toBasetype()->ty;
307 TY oldty = ty;
308
309 if (m == MATCHnomatch && t->ty == Tenum)
310 return;
311
312 if (t->ty == Tvector)
313 {
314 TypeVector *tv = (TypeVector *)t;
315 TypeBasic *tb = tv->elementType();
316 if (tb->ty == Tvoid)
317 return;
318 toty = tb->ty;
319 }
320
321 switch (ty)
322 {
323 case Tbool:
324 case Tint8:
325 case Tchar:
326 case Tuns8:
327 case Tint16:
328 case Tuns16:
329 case Twchar:
330 ty = Tint32;
331 break;
332
333 case Tdchar:
334 ty = Tuns32;
335 break;
336
337 default:
338 break;
339 }
340
341 // Only allow conversion if no change in value
342 dinteger_t value = e->toInteger();
343 switch (toty)
344 {
345 case Tbool:
346 if ((value & 1) != value)
347 return;
348 break;
349
350 case Tint8:
351 if (ty == Tuns64 && value & ~0x7FUL)
352 return;
353 else if ((signed char)value != (sinteger_t)value)
354 return;
355 break;
356
357 case Tchar:
358 if ((oldty == Twchar || oldty == Tdchar) && value > 0x7F)
359 return;
360 /* fall through */
361 case Tuns8:
362 //printf("value = %llu %llu\n", (dinteger_t)(unsigned char)value, value);
363 if ((unsigned char)value != value)
364 return;
365 break;
366
367 case Tint16:
368 if (ty == Tuns64 && value & ~0x7FFFUL)
369 return;
370 else if ((short)value != (sinteger_t)value)
371 return;
372 break;
373
374 case Twchar:
375 if (oldty == Tdchar && value > 0xD7FF && value < 0xE000)
376 return;
377 /* fall through */
378 case Tuns16:
379 if ((unsigned short)value != value)
380 return;
381 break;
382
383 case Tint32:
384 if (ty == Tuns32)
385 {
386 }
387 else if (ty == Tuns64 && value & ~0x7FFFFFFFUL)
388 return;
389 else if ((int)value != (sinteger_t)value)
390 return;
391 break;
392
393 case Tuns32:
394 if (ty == Tint32)
395 {
396 }
397 else if ((unsigned)value != value)
398 return;
399 break;
400
401 case Tdchar:
402 if (value > 0x10FFFFUL)
403 return;
404 break;
405
406 case Tfloat32:
407 {
408 volatile float f;
409 if (e->type->isunsigned())
410 {
411 f = (float)value;
412 if (f != value)
413 return;
414 }
415 else
416 {
417 f = (float)(sinteger_t)value;
418 if (f != (sinteger_t)value)
419 return;
420 }
421 break;
422 }
423
424 case Tfloat64:
425 {
426 volatile double f;
427 if (e->type->isunsigned())
428 {
429 f = (double)value;
430 if (f != value)
431 return;
432 }
433 else
434 {
435 f = (double)(sinteger_t)value;
436 if (f != (sinteger_t)value)
437 return;
438 }
439 break;
440 }
441
442 case Tfloat80:
443 {
444 volatile_longdouble f;
445 if (e->type->isunsigned())
446 {
447 f = ldouble(value);
448 if ((dinteger_t)f != value) // isn't this a noop, because the compiler prefers ld
449 return;
450 }
451 else
452 {
453 f = ldouble((sinteger_t)value);
454 if ((sinteger_t)f != (sinteger_t)value)
455 return;
456 }
457 break;
458 }
459
460 case Tpointer:
461 //printf("type = %s\n", type->toBasetype()->toChars());
462 //printf("t = %s\n", t->toBasetype()->toChars());
463 if (ty == Tpointer &&
464 e->type->toBasetype()->nextOf()->ty == t->toBasetype()->nextOf()->ty)
465 {
466 /* Allow things like:
467 * const char* P = cast(char *)3;
468 * char* q = P;
469 */
470 break;
471 }
472 /* fall through */
473
474 default:
475 visit((Expression *)e);
476 return;
477 }
478
479 //printf("MATCHconvert\n");
480 result = MATCHconvert;
481 }
482
483 void visit(ErrorExp *)
484 {
485 // no match
486 }
487
488 void visit(NullExp *e)
489 {
490 if (e->type->equals(t))
491 {
492 result = MATCHexact;
493 return;
494 }
495
496 /* Allow implicit conversions from immutable to mutable|const,
497 * and mutable to immutable. It works because, after all, a null
498 * doesn't actually point to anything.
499 */
500 if (t->equivalent(e->type))
501 {
502 result = MATCHconst;
503 return;
504 }
505
506 visit((Expression *)e);
507 }
508
509 void visit(StructLiteralExp *e)
510 {
511 visit((Expression *)e);
512 if (result != MATCHnomatch)
513 return;
514 if (e->type->ty == t->ty && e->type->ty == Tstruct &&
515 ((TypeStruct *)e->type)->sym == ((TypeStruct *)t)->sym)
516 {
517 result = MATCHconst;
518 for (size_t i = 0; i < e->elements->dim; i++)
519 {
520 Expression *el = (*e->elements)[i];
521 if (!el)
522 continue;
523 Type *te = el->type;
524 te = e->sd->fields[i]->type->addMod(t->mod);
525 MATCH m2 = el->implicitConvTo(te);
526 //printf("\t%s => %s, match = %d\n", el->toChars(), te->toChars(), m2);
527 if (m2 < result)
528 result = m2;
529 }
530 }
531 }
532
533 void visit(StringExp *e)
534 {
535 if (!e->committed && t->ty == Tpointer && t->nextOf()->ty == Tvoid)
536 return;
537
538 if (e->type->ty == Tsarray || e->type->ty == Tarray || e->type->ty == Tpointer)
539 {
540 TY tyn = e->type->nextOf()->ty;
541 if (tyn == Tchar || tyn == Twchar || tyn == Tdchar)
542 {
543 switch (t->ty)
544 {
545 case Tsarray:
546 if (e->type->ty == Tsarray)
547 {
548 TY tynto = t->nextOf()->ty;
549 if (tynto == tyn)
550 {
551 if (((TypeSArray *)e->type)->dim->toInteger() ==
552 ((TypeSArray *)t)->dim->toInteger())
553 {
554 result = MATCHexact;
555 }
556 return;
557 }
558 if (tynto == Tchar || tynto == Twchar || tynto == Tdchar)
559 {
560 if (e->committed && tynto != tyn)
561 return;
562 size_t fromlen = e->numberOfCodeUnits(tynto);
563 size_t tolen = (size_t)((TypeSArray *)t)->dim->toInteger();
564 if (tolen < fromlen)
565 return;
566 if (tolen != fromlen)
567 {
568 // implicit length extending
569 result = MATCHconvert;
570 return;
571 }
572 }
573 if (!e->committed && (tynto == Tchar || tynto == Twchar || tynto == Tdchar))
574 {
575 result = MATCHexact;
576 return;
577 }
578 }
579 else if (e->type->ty == Tarray)
580 {
581 TY tynto = t->nextOf()->ty;
582 if (tynto == Tchar || tynto == Twchar || tynto == Tdchar)
583 {
584 if (e->committed && tynto != tyn)
585 return;
586 size_t fromlen = e->numberOfCodeUnits(tynto);
587 size_t tolen = (size_t)((TypeSArray *)t)->dim->toInteger();
588 if (tolen < fromlen)
589 return;
590 if (tolen != fromlen)
591 {
592 // implicit length extending
593 result = MATCHconvert;
594 return;
595 }
596 }
597 if (tynto == tyn)
598 {
599 result = MATCHexact;
600 return;
601 }
602 if (!e->committed && (tynto == Tchar || tynto == Twchar || tynto == Tdchar))
603 {
604 result = MATCHexact;
605 return;
606 }
607 }
608 /* fall through */
609 case Tarray:
610 case Tpointer:
611 Type *tn = t->nextOf();
612 MATCH m = MATCHexact;
613 if (e->type->nextOf()->mod != tn->mod)
614 {
615 if (!tn->isConst())
616 return;
617 m = MATCHconst;
618 }
619 if (!e->committed)
620 {
621 switch (tn->ty)
622 {
623 case Tchar:
624 if (e->postfix == 'w' || e->postfix == 'd')
625 m = MATCHconvert;
626 result = m;
627 return;
628 case Twchar:
629 if (e->postfix != 'w')
630 m = MATCHconvert;
631 result = m;
632 return;
633 case Tdchar:
634 if (e->postfix != 'd')
635 m = MATCHconvert;
636 result = m;
637 return;
638 }
639 }
640 break;
641 }
642 }
643 }
644
645 visit((Expression *)e);
646 }
647
648 void visit(ArrayLiteralExp *e)
649 {
650 Type *typeb = e->type->toBasetype();
651 Type *tb = t->toBasetype();
652 if ((tb->ty == Tarray || tb->ty == Tsarray) &&
653 (typeb->ty == Tarray || typeb->ty == Tsarray))
654 {
655 result = MATCHexact;
656 Type *typen = typeb->nextOf()->toBasetype();
657
658 if (tb->ty == Tsarray)
659 {
660 TypeSArray *tsa = (TypeSArray *)tb;
661 if (e->elements->dim != tsa->dim->toInteger())
662 result = MATCHnomatch;
663 }
664
665 Type *telement = tb->nextOf();
666 if (!e->elements->dim)
667 {
668 if (typen->ty != Tvoid)
669 result = typen->implicitConvTo(telement);
670 }
671 else
672 {
673 if (e->basis)
674 {
675 MATCH m = e->basis->implicitConvTo(telement);
676 if (m < result)
677 result = m;
678 }
679 for (size_t i = 0; i < e->elements->dim; i++)
680 {
681 Expression *el = (*e->elements)[i];
682 if (result == MATCHnomatch)
683 break;
684 if (!el)
685 continue;
686 MATCH m = el->implicitConvTo(telement);
687 if (m < result)
688 result = m; // remember worst match
689 }
690 }
691
692 if (!result)
693 result = e->type->implicitConvTo(t);
694
695 return;
696 }
697 else if (tb->ty == Tvector &&
698 (typeb->ty == Tarray || typeb->ty == Tsarray))
699 {
700 result = MATCHexact;
701 // Convert array literal to vector type
702 TypeVector *tv = (TypeVector *)tb;
703 TypeSArray *tbase = (TypeSArray *)tv->basetype;
704 assert(tbase->ty == Tsarray);
705 const size_t edim = e->elements->dim;
706 const size_t tbasedim = tbase->dim->toInteger();
707 if (edim > tbasedim)
708 {
709 result = MATCHnomatch;
710 return;
711 }
712
713 Type *telement = tv->elementType();
714 if (edim < tbasedim)
715 {
716 Expression *el = typeb->nextOf()->defaultInitLiteral(e->loc);
717 MATCH m = el->implicitConvTo(telement);
718 if (m < result)
719 result = m; // remember worst match
720 }
721 for (size_t i = 0; i < edim; i++)
722 {
723 Expression *el = (*e->elements)[i];
724 MATCH m = el->implicitConvTo(telement);
725 if (m < result)
726 result = m; // remember worst match
727 if (result == MATCHnomatch)
728 break; // no need to check for worse
729 }
730 return;
731 }
732
733 visit((Expression *)e);
734 }
735
736 void visit(AssocArrayLiteralExp *e)
737 {
738 Type *typeb = e->type->toBasetype();
739 Type *tb = t->toBasetype();
740 if (tb->ty == Taarray && typeb->ty == Taarray)
741 {
742 result = MATCHexact;
743 for (size_t i = 0; i < e->keys->dim; i++)
744 {
745 Expression *el = (*e->keys)[i];
746 MATCH m = el->implicitConvTo(((TypeAArray *)tb)->index);
747 if (m < result)
748 result = m; // remember worst match
749 if (result == MATCHnomatch)
750 break; // no need to check for worse
751 el = (*e->values)[i];
752 m = el->implicitConvTo(tb->nextOf());
753 if (m < result)
754 result = m; // remember worst match
755 if (result == MATCHnomatch)
756 break; // no need to check for worse
757 }
758 return;
759 }
760 else
761 visit((Expression *)e);
762 }
763
764 void visit(CallExp *e)
765 {
766 visit((Expression *)e);
767 if (result != MATCHnomatch)
768 return;
769
770 /* Allow the result of strongly pure functions to
771 * convert to immutable
772 */
773 if (e->f && e->f->isolateReturn())
774 {
775 result = e->type->immutableOf()->implicitConvTo(t);
776 if (result > MATCHconst) // Match level is MATCHconst at best.
777 result = MATCHconst;
778 return;
779 }
780
781 /* Conversion is 'const' conversion if:
782 * 1. function is pure (weakly pure is ok)
783 * 2. implicit conversion only fails because of mod bits
784 * 3. each function parameter can be implicitly converted to the mod bits
785 */
786 Type *tx = e->f ? e->f->type : e->e1->type;
787 tx = tx->toBasetype();
788 if (tx->ty != Tfunction)
789 return;
790 TypeFunction *tf = (TypeFunction *)tx;
791
792 if (tf->purity == PUREimpure)
793 return;
794 if (e->f && e->f->isNested())
795 return;
796
797 /* See if fail only because of mod bits.
798 *
799 * Bugzilla 14155: All pure functions can access global immutable data.
800 * So the returned pointer may refer an immutable global data,
801 * and then the returned pointer that points non-mutable object
802 * cannot be unique pointer.
803 *
804 * Example:
805 * immutable g;
806 * static this() { g = 1; }
807 * const(int*) foo() pure { return &g; }
808 * void test() {
809 * immutable(int*) ip = foo(); // OK
810 * int* mp = foo(); // should be disallowed
811 * }
812 */
813 if (e->type->immutableOf()->implicitConvTo(t) < MATCHconst &&
814 e->type->addMod(MODshared)->implicitConvTo(t) < MATCHconst &&
815 e->type->implicitConvTo(t->addMod(MODshared)) < MATCHconst)
816 {
817 return;
818 }
819 // Allow a conversion to immutable type, or
820 // conversions of mutable types between thread-local and shared.
821
822 /* Get mod bits of what we're converting to
823 */
824 Type *tb = t->toBasetype();
825 MOD mod = tb->mod;
826 if (tf->isref)
827 ;
828 else
829 {
830 Type *ti = getIndirection(t);
831 if (ti)
832 mod = ti->mod;
833 }
834 if (mod & MODwild)
835 return; // not sure what to do with this
836
837 /* Apply mod bits to each function parameter,
838 * and see if we can convert the function argument to the modded type
839 */
840
841 size_t nparams = Parameter::dim(tf->parameters);
842 size_t j = (tf->linkage == LINKd && tf->varargs == 1); // if TypeInfoArray was prepended
843 if (e->e1->op == TOKdotvar)
844 {
845 /* Treat 'this' as just another function argument
846 */
847 DotVarExp *dve = (DotVarExp *)e->e1;
848 Type *targ = dve->e1->type;
849 if (targ->constConv(targ->castMod(mod)) == MATCHnomatch)
850 return;
851 }
852 for (size_t i = j; i < e->arguments->dim; ++i)
853 {
854 Expression *earg = (*e->arguments)[i];
855 Type *targ = earg->type->toBasetype();
856 if (i - j < nparams)
857 {
858 Parameter *fparam = Parameter::getNth(tf->parameters, i - j);
859 if (fparam->storageClass & STClazy)
860 return; // not sure what to do with this
861 Type *tparam = fparam->type;
862 if (!tparam)
863 continue;
864 if (fparam->storageClass & (STCout | STCref))
865 {
866 if (targ->constConv(tparam->castMod(mod)) == MATCHnomatch)
867 return;
868 continue;
869 }
870 }
871
872 if (implicitMod(earg, targ, mod) == MATCHnomatch)
873 return;
874 }
875
876 /* Success
877 */
878 result = MATCHconst;
879 }
880
881 void visit(AddrExp *e)
882 {
883 result = e->type->implicitConvTo(t);
884 //printf("\tresult = %d\n", result);
885
886 if (result != MATCHnomatch)
887 return;
888
889 // Look for pointers to functions where the functions are overloaded.
890
891 t = t->toBasetype();
892
893 if (e->e1->op == TOKoverloadset &&
894 (t->ty == Tpointer || t->ty == Tdelegate) && t->nextOf()->ty == Tfunction)
895 {
896 OverExp *eo = (OverExp *)e->e1;
897 FuncDeclaration *f = NULL;
898 for (size_t i = 0; i < eo->vars->a.dim; i++)
899 {
900 Dsymbol *s = eo->vars->a[i];
901 FuncDeclaration *f2 = s->isFuncDeclaration();
902 assert(f2);
903 if (f2->overloadExactMatch(t->nextOf()))
904 {
905 if (f)
906 {
907 /* Error if match in more than one overload set,
908 * even if one is a 'better' match than the other.
909 */
910 ScopeDsymbol::multiplyDefined(e->loc, f, f2);
911 }
912 else
913 f = f2;
914 result = MATCHexact;
915 }
916 }
917 }
918
919 if (e->type->ty == Tpointer && e->type->nextOf()->ty == Tfunction &&
920 t->ty == Tpointer && t->nextOf()->ty == Tfunction &&
921 e->e1->op == TOKvar)
922 {
923 /* I don't think this can ever happen -
924 * it should have been
925 * converted to a SymOffExp.
926 */
927 assert(0);
928 }
929
930 //printf("\tresult = %d\n", result);
931 }
932
933 void visit(SymOffExp *e)
934 {
935 result = e->type->implicitConvTo(t);
936 //printf("\tresult = %d\n", result);
937 if (result != MATCHnomatch)
938 return;
939
940 // Look for pointers to functions where the functions are overloaded.
941 t = t->toBasetype();
942 if (e->type->ty == Tpointer && e->type->nextOf()->ty == Tfunction &&
943 (t->ty == Tpointer || t->ty == Tdelegate) && t->nextOf()->ty == Tfunction)
944 {
945 if (FuncDeclaration *f = e->var->isFuncDeclaration())
946 {
947 f = f->overloadExactMatch(t->nextOf());
948 if (f)
949 {
950 if ((t->ty == Tdelegate && (f->needThis() || f->isNested())) ||
951 (t->ty == Tpointer && !(f->needThis() || f->isNested())))
952 {
953 result = MATCHexact;
954 }
955 }
956 }
957 }
958 //printf("\tresult = %d\n", result);
959 }
960
961 void visit(DelegateExp *e)
962 {
963 result = e->type->implicitConvTo(t);
964 if (result != MATCHnomatch)
965 return;
966
967 // Look for pointers to functions where the functions are overloaded.
968 t = t->toBasetype();
969 if (e->type->ty == Tdelegate &&
970 t->ty == Tdelegate)
971 {
972 if (e->func && e->func->overloadExactMatch(t->nextOf()))
973 result = MATCHexact;
974 }
975 }
976
977 void visit(FuncExp *e)
978 {
979 //printf("FuncExp::implicitConvTo type = %p %s, t = %s\n", e->type, e->type ? e->type->toChars() : NULL, t->toChars());
980 MATCH m = e->matchType(t, NULL, NULL, 1);
981 if (m > MATCHnomatch)
982 {
983 result = m;
984 return;
985 }
986 visit((Expression *)e);
987 }
988
989 void visit(AndExp *e)
990 {
991 visit((Expression *)e);
992 if (result != MATCHnomatch)
993 return;
994
995 MATCH m1 = e->e1->implicitConvTo(t);
996 MATCH m2 = e->e2->implicitConvTo(t);
997
998 // Pick the worst match
999 result = (m1 < m2) ? m1 : m2;
1000 }
1001
1002 void visit(OrExp *e)
1003 {
1004 visit((Expression *)e);
1005 if (result != MATCHnomatch)
1006 return;
1007
1008 MATCH m1 = e->e1->implicitConvTo(t);
1009 MATCH m2 = e->e2->implicitConvTo(t);
1010
1011 // Pick the worst match
1012 result = (m1 < m2) ? m1 : m2;
1013 }
1014
1015 void visit(XorExp *e)
1016 {
1017 visit((Expression *)e);
1018 if (result != MATCHnomatch)
1019 return;
1020
1021 MATCH m1 = e->e1->implicitConvTo(t);
1022 MATCH m2 = e->e2->implicitConvTo(t);
1023
1024 // Pick the worst match
1025 result = (m1 < m2) ? m1 : m2;
1026 }
1027
1028 void visit(CondExp *e)
1029 {
1030 MATCH m1 = e->e1->implicitConvTo(t);
1031 MATCH m2 = e->e2->implicitConvTo(t);
1032 //printf("CondExp: m1 %d m2 %d\n", m1, m2);
1033
1034 // Pick the worst match
1035 result = (m1 < m2) ? m1 : m2;
1036 }
1037
1038 void visit(CommaExp *e)
1039 {
1040 e->e2->accept(this);
1041 }
1042
1043 void visit(CastExp *e)
1044 {
1045 result = e->type->implicitConvTo(t);
1046 if (result != MATCHnomatch)
1047 return;
1048
1049 if (t->isintegral() &&
1050 e->e1->type->isintegral() &&
1051 e->e1->implicitConvTo(t) != MATCHnomatch)
1052 result = MATCHconvert;
1053 else
1054 visit((Expression *)e);
1055 }
1056
1057 void visit(NewExp *e)
1058 {
1059 visit((Expression *)e);
1060 if (result != MATCHnomatch)
1061 return;
1062
1063 /* Calling new() is like calling a pure function. We can implicitly convert the
1064 * return from new() to t using the same algorithm as in CallExp, with the function
1065 * 'arguments' being:
1066 * thisexp
1067 * newargs
1068 * arguments
1069 * .init
1070 * 'member' and 'allocator' need to be pure.
1071 */
1072
1073 /* See if fail only because of mod bits
1074 */
1075 if (e->type->immutableOf()->implicitConvTo(t->immutableOf()) == MATCHnomatch)
1076 return;
1077
1078 /* Get mod bits of what we're converting to
1079 */
1080 Type *tb = t->toBasetype();
1081 MOD mod = tb->mod;
1082 if (Type *ti = getIndirection(t))
1083 mod = ti->mod;
1084 if (mod & MODwild)
1085 return; // not sure what to do with this
1086
1087 /* Apply mod bits to each argument,
1088 * and see if we can convert the argument to the modded type
1089 */
1090
1091 if (e->thisexp)
1092 {
1093 /* Treat 'this' as just another function argument
1094 */
1095 Type *targ = e->thisexp->type;
1096 if (targ->constConv(targ->castMod(mod)) == MATCHnomatch)
1097 return;
1098 }
1099
1100 /* Check call to 'allocator', then 'member'
1101 */
1102 FuncDeclaration *fd = e->allocator;
1103 for (int count = 0; count < 2; ++count, (fd = e->member))
1104 {
1105 if (!fd)
1106 continue;
1107 if (fd->errors || fd->type->ty != Tfunction)
1108 return; // error
1109 TypeFunction *tf = (TypeFunction *)fd->type;
1110 if (tf->purity == PUREimpure)
1111 return; // impure
1112
1113 if (fd == e->member)
1114 {
1115 if (e->type->immutableOf()->implicitConvTo(t) < MATCHconst &&
1116 e->type->addMod(MODshared)->implicitConvTo(t) < MATCHconst &&
1117 e->type->implicitConvTo(t->addMod(MODshared)) < MATCHconst)
1118 {
1119 return;
1120 }
1121 // Allow a conversion to immutable type, or
1122 // conversions of mutable types between thread-local and shared.
1123 }
1124
1125 Expressions *args = (fd == e->allocator) ? e->newargs : e->arguments;
1126
1127 size_t nparams = Parameter::dim(tf->parameters);
1128 size_t j = (tf->linkage == LINKd && tf->varargs == 1); // if TypeInfoArray was prepended
1129 for (size_t i = j; i < e->arguments->dim; ++i)
1130 {
1131 Expression *earg = (*args)[i];
1132 Type *targ = earg->type->toBasetype();
1133 if (i - j < nparams)
1134 {
1135 Parameter *fparam = Parameter::getNth(tf->parameters, i - j);
1136 if (fparam->storageClass & STClazy)
1137 return; // not sure what to do with this
1138 Type *tparam = fparam->type;
1139 if (!tparam)
1140 continue;
1141 if (fparam->storageClass & (STCout | STCref))
1142 {
1143 if (targ->constConv(tparam->castMod(mod)) == MATCHnomatch)
1144 return;
1145 continue;
1146 }
1147 }
1148
1149 if (implicitMod(earg, targ, mod) == MATCHnomatch)
1150 return;
1151 }
1152 }
1153
1154 /* If no 'member', then construction is by simple assignment,
1155 * and just straight check 'arguments'
1156 */
1157 if (!e->member && e->arguments)
1158 {
1159 for (size_t i = 0; i < e->arguments->dim; ++i)
1160 {
1161 Expression *earg = (*e->arguments)[i];
1162 if (!earg) // Bugzilla 14853: if it's on overlapped field
1163 continue;
1164 Type *targ = earg->type->toBasetype();
1165 if (implicitMod(earg, targ, mod) == MATCHnomatch)
1166 return;
1167 }
1168 }
1169
1170 /* Consider the .init expression as an argument
1171 */
1172 Type *ntb = e->newtype->toBasetype();
1173 if (ntb->ty == Tarray)
1174 ntb = ntb->nextOf()->toBasetype();
1175 if (ntb->ty == Tstruct)
1176 {
1177 // Don't allow nested structs - uplevel reference may not be convertible
1178 StructDeclaration *sd = ((TypeStruct *)ntb)->sym;
1179 sd->size(e->loc); // resolve any forward references
1180 if (sd->isNested())
1181 return;
1182 }
1183 if (ntb->isZeroInit(e->loc))
1184 {
1185 /* Zeros are implicitly convertible, except for special cases.
1186 */
1187 if (ntb->ty == Tclass)
1188 {
1189 /* With new() must look at the class instance initializer.
1190 */
1191 ClassDeclaration *cd = ((TypeClass *)ntb)->sym;
1192
1193 cd->size(e->loc); // resolve any forward references
1194
1195 if (cd->isNested())
1196 return; // uplevel reference may not be convertible
1197
1198 assert(!cd->isInterfaceDeclaration());
1199
1200 struct ClassCheck
1201 {
1202 static bool convertible(Loc loc, ClassDeclaration *cd, MOD mod)
1203 {
1204 for (size_t i = 0; i < cd->fields.dim; i++)
1205 {
1206 VarDeclaration *v = cd->fields[i];
1207 Initializer *init = v->_init;
1208 if (init)
1209 {
1210 if (init->isVoidInitializer())
1211 ;
1212 else if (ExpInitializer *ei = init->isExpInitializer())
1213 {
1214 Type *tb = v->type->toBasetype();
1215 if (implicitMod(ei->exp, tb, mod) == MATCHnomatch)
1216 return false;
1217 }
1218 else
1219 {
1220 /* Enhancement: handle StructInitializer and ArrayInitializer
1221 */
1222 return false;
1223 }
1224 }
1225 else if (!v->type->isZeroInit(loc))
1226 return false;
1227 }
1228 return cd->baseClass ? convertible(loc, cd->baseClass, mod) : true;
1229 }
1230 };
1231
1232 if (!ClassCheck::convertible(e->loc, cd, mod))
1233 return;
1234 }
1235 }
1236 else
1237 {
1238 Expression *earg = e->newtype->defaultInitLiteral(e->loc);
1239 Type *targ = e->newtype->toBasetype();
1240
1241 if (implicitMod(earg, targ, mod) == MATCHnomatch)
1242 return;
1243 }
1244
1245 /* Success
1246 */
1247 result = MATCHconst;
1248 }
1249
1250 void visit(SliceExp *e)
1251 {
1252 //printf("SliceExp::implicitConvTo e = %s, type = %s\n", e->toChars(), e->type->toChars());
1253 visit((Expression *)e);
1254 if (result != MATCHnomatch)
1255 return;
1256
1257 Type *tb = t->toBasetype();
1258 Type *typeb = e->type->toBasetype();
1259 if (tb->ty == Tsarray && typeb->ty == Tarray)
1260 {
1261 typeb = toStaticArrayType(e);
1262 if (typeb)
1263 result = typeb->implicitConvTo(t);
1264 return;
1265 }
1266
1267 /* If the only reason it won't convert is because of the mod bits,
1268 * then test for conversion by seeing if e1 can be converted with those
1269 * same mod bits.
1270 */
1271 Type *t1b = e->e1->type->toBasetype();
1272 if (tb->ty == Tarray && typeb->equivalent(tb))
1273 {
1274 Type *tbn = tb->nextOf();
1275 Type *tx = NULL;
1276
1277 /* If e->e1 is dynamic array or pointer, the uniqueness of e->e1
1278 * is equivalent with the uniqueness of the referred data. And in here
1279 * we can have arbitrary typed reference for that.
1280 */
1281 if (t1b->ty == Tarray)
1282 tx = tbn->arrayOf();
1283 if (t1b->ty == Tpointer)
1284 tx = tbn->pointerTo();
1285
1286 /* If e->e1 is static array, at least it should be an rvalue.
1287 * If not, e->e1 is a reference, and its uniqueness does not link
1288 * to the uniqueness of the referred data.
1289 */
1290 if (t1b->ty == Tsarray && !e->e1->isLvalue())
1291 tx = tbn->sarrayOf(t1b->size() / tbn->size());
1292
1293 if (tx)
1294 {
1295 result = e->e1->implicitConvTo(tx);
1296 if (result > MATCHconst) // Match level is MATCHconst at best.
1297 result = MATCHconst;
1298 }
1299 }
1300
1301 // Enhancement 10724
1302 if (tb->ty == Tpointer && e->e1->op == TOKstring)
1303 e->e1->accept(this);
1304 }
1305 };
1306
1307 ImplicitConvTo v(t);
1308 e->accept(&v);
1309 return v.result;
1310 }
1311
toStaticArrayType(SliceExp * e)1312 Type *toStaticArrayType(SliceExp *e)
1313 {
1314 if (e->lwr && e->upr)
1315 {
1316 // For the following code to work, e should be optimized beforehand.
1317 // (eg. $ in lwr and upr should be already resolved, if possible)
1318 Expression *lwr = e->lwr->optimize(WANTvalue);
1319 Expression *upr = e->upr->optimize(WANTvalue);
1320 if (lwr->isConst() && upr->isConst())
1321 {
1322 size_t len = (size_t)(upr->toUInteger() - lwr->toUInteger());
1323 return e->type->toBasetype()->nextOf()->sarrayOf(len);
1324 }
1325 }
1326 else
1327 {
1328 Type *t1b = e->e1->type->toBasetype();
1329 if (t1b->ty == Tsarray)
1330 return t1b;
1331 }
1332 return NULL;
1333 }
1334
1335 /* ==================== castTo ====================== */
1336
1337 /**************************************
1338 * Do an explicit cast.
1339 * Assume that the 'this' expression does not have any indirections.
1340 */
1341
castTo(Expression * e,Scope * sc,Type * t)1342 Expression *castTo(Expression *e, Scope *sc, Type *t)
1343 {
1344 class CastTo : public Visitor
1345 {
1346 public:
1347 Type *t;
1348 Scope *sc;
1349 Expression *result;
1350
1351 CastTo(Scope *sc, Type *t)
1352 : t(t), sc(sc)
1353 {
1354 result = NULL;
1355 }
1356
1357 void visit(Expression *e)
1358 {
1359 //printf("Expression::castTo(this=%s, t=%s)\n", e->toChars(), t->toChars());
1360 if (e->type->equals(t))
1361 {
1362 result = e;
1363 return;
1364 }
1365 if (e->op == TOKvar)
1366 {
1367 VarDeclaration *v = ((VarExp *)e)->var->isVarDeclaration();
1368 if (v && v->storage_class & STCmanifest)
1369 {
1370 result = e->ctfeInterpret();
1371 result = result->castTo(sc, t);
1372 return;
1373 }
1374 }
1375
1376 Type *tob = t->toBasetype();
1377 Type *t1b = e->type->toBasetype();
1378 if (tob->equals(t1b))
1379 {
1380 result = e->copy(); // because of COW for assignment to e->type
1381 result->type = t;
1382 return;
1383 }
1384
1385 /* Make semantic error against invalid cast between concrete types.
1386 * Assume that 'e' is never be any placeholder expressions.
1387 * The result of these checks should be consistent with CastExp::toElem().
1388 */
1389
1390 // Fat Value types
1391 const bool tob_isFV = (tob->ty == Tstruct || tob->ty == Tsarray || tob->ty == Tvector);
1392 const bool t1b_isFV = (t1b->ty == Tstruct || t1b->ty == Tsarray || t1b->ty == Tvector);
1393
1394 // Fat Reference types
1395 const bool tob_isFR = (tob->ty == Tarray || tob->ty == Tdelegate);
1396 const bool t1b_isFR = (t1b->ty == Tarray || t1b->ty == Tdelegate);
1397
1398 // Reference types
1399 const bool tob_isR = (tob_isFR || tob->ty == Tpointer || tob->ty == Taarray || tob->ty == Tclass);
1400 const bool t1b_isR = (t1b_isFR || t1b->ty == Tpointer || t1b->ty == Taarray || t1b->ty == Tclass);
1401
1402 // Arithmetic types (== valueable basic types)
1403 const bool tob_isA = ((tob->isintegral() || tob->isfloating()) && tob->ty != Tvector);
1404 const bool t1b_isA = ((t1b->isintegral() || t1b->isfloating()) && t1b->ty != Tvector);
1405
1406 if (AggregateDeclaration *t1ad = isAggregate(t1b))
1407 {
1408 AggregateDeclaration *toad = isAggregate(tob);
1409 if (t1ad != toad && t1ad->aliasthis)
1410 {
1411 if (t1b->ty == Tclass && tob->ty == Tclass)
1412 {
1413 ClassDeclaration *t1cd = t1b->isClassHandle();
1414 ClassDeclaration *tocd = tob->isClassHandle();
1415 int offset;
1416 if (tocd->isBaseOf(t1cd, &offset))
1417 goto Lok;
1418 }
1419
1420 /* Forward the cast to our alias this member, rewrite to:
1421 * cast(to)e1.aliasthis
1422 */
1423 result = resolveAliasThis(sc, e);
1424 result = result->castTo(sc, t);
1425 return;
1426 }
1427 }
1428 else if (tob->ty == Tvector && t1b->ty != Tvector)
1429 {
1430 //printf("test1 e = %s, e->type = %s, tob = %s\n", e->toChars(), e->type->toChars(), tob->toChars());
1431 TypeVector *tv = (TypeVector *)tob;
1432 result = new CastExp(e->loc, e, tv->elementType());
1433 result = new VectorExp(e->loc, result, tob);
1434 result = ::semantic(result, sc);
1435 return;
1436 }
1437 else if (tob->ty != Tvector && t1b->ty == Tvector)
1438 {
1439 // T[n] <-- __vector(U[m])
1440 if (tob->ty == Tsarray)
1441 {
1442 if (t1b->size(e->loc) == tob->size(e->loc))
1443 goto Lok;
1444 }
1445 goto Lfail;
1446 }
1447 else if (t1b->implicitConvTo(tob) == MATCHconst && t->equals(e->type->constOf()))
1448 {
1449 result = e->copy();
1450 result->type = t;
1451 return;
1452 }
1453
1454 // arithmetic values vs. other arithmetic values
1455 // arithmetic values vs. T*
1456 if ((tob_isA && (t1b_isA || t1b->ty == Tpointer)) ||
1457 (t1b_isA && (tob_isA || tob->ty == Tpointer)))
1458 {
1459 goto Lok;
1460 }
1461
1462 // arithmetic values vs. references or fat values
1463 if ((tob_isA && (t1b_isR || t1b_isFV)) ||
1464 (t1b_isA && (tob_isR || tob_isFV)))
1465 {
1466 goto Lfail;
1467 }
1468
1469 // Bugzlla 3133: A cast between fat values is possible only when the sizes match.
1470 if (tob_isFV && t1b_isFV)
1471 {
1472 if (t1b->size(e->loc) == tob->size(e->loc))
1473 goto Lok;
1474 e->error("cannot cast expression %s of type %s to %s because of different sizes",
1475 e->toChars(), e->type->toChars(), t->toChars());
1476 result = new ErrorExp();
1477 return;
1478 }
1479
1480 // Fat values vs. null or references
1481 if ((tob_isFV && (t1b->ty == Tnull || t1b_isR)) ||
1482 (t1b_isFV && (tob->ty == Tnull || tob_isR)))
1483 {
1484 if (tob->ty == Tpointer && t1b->ty == Tsarray)
1485 {
1486 // T[n] sa;
1487 // cast(U*)sa; // ==> cast(U*)sa.ptr;
1488 result = new AddrExp(e->loc, e, t);
1489 return;
1490 }
1491 if (tob->ty == Tarray && t1b->ty == Tsarray)
1492 {
1493 // T[n] sa;
1494 // cast(U[])sa; // ==> cast(U[])sa[];
1495 d_uns64 fsize = t1b->nextOf()->size();
1496 d_uns64 tsize = tob->nextOf()->size();
1497 if ((((TypeSArray *)t1b)->dim->toInteger() * fsize) % tsize != 0)
1498 {
1499 // copied from sarray_toDarray() in e2ir.c
1500 e->error("cannot cast expression %s of type %s to %s since sizes don't line up",
1501 e->toChars(), e->type->toChars(), t->toChars());
1502 result = new ErrorExp();
1503 return;
1504 }
1505 goto Lok;
1506 }
1507 goto Lfail;
1508 }
1509
1510 /* For references, any reinterpret casts are allowed to same 'ty' type.
1511 * T* to U*
1512 * R1 function(P1) to R2 function(P2)
1513 * R1 delegate(P1) to R2 delegate(P2)
1514 * T[] to U[]
1515 * V1[K1] to V2[K2]
1516 * class/interface A to B (will be a dynamic cast if possible)
1517 */
1518 if (tob->ty == t1b->ty && tob_isR && t1b_isR)
1519 goto Lok;
1520
1521 // typeof(null) <-- non-null references or values
1522 if (tob->ty == Tnull && t1b->ty != Tnull)
1523 goto Lfail; // Bugzilla 14629
1524 // typeof(null) --> non-null references or arithmetic values
1525 if (t1b->ty == Tnull && tob->ty != Tnull)
1526 goto Lok;
1527
1528 // Check size mismatch of references.
1529 // Tarray and Tdelegate are (void*).sizeof*2, but others have (void*).sizeof.
1530 if ((tob_isFR && t1b_isR) || (t1b_isFR && tob_isR))
1531 {
1532 if (tob->ty == Tpointer && t1b->ty == Tarray)
1533 {
1534 // T[] da;
1535 // cast(U*)da; // ==> cast(U*)da.ptr;
1536 goto Lok;
1537 }
1538 if (tob->ty == Tpointer && t1b->ty == Tdelegate)
1539 {
1540 // void delegate() dg;
1541 // cast(U*)dg; // ==> cast(U*)dg.ptr;
1542 // Note that it happens even when U is a Tfunction!
1543 e->deprecation("casting from %s to %s is deprecated", e->type->toChars(), t->toChars());
1544 goto Lok;
1545 }
1546 goto Lfail;
1547 }
1548
1549 if (t1b->ty == Tvoid && tob->ty != Tvoid)
1550 {
1551 Lfail:
1552 e->error("cannot cast expression %s of type %s to %s",
1553 e->toChars(), e->type->toChars(), t->toChars());
1554 result = new ErrorExp();
1555 return;
1556 }
1557
1558 Lok:
1559 result = new CastExp(e->loc, e, t);
1560 result->type = t; // Don't call semantic()
1561 //printf("Returning: %s\n", result->toChars());
1562 }
1563
1564 void visit(ErrorExp *e)
1565 {
1566 result = e;
1567 }
1568
1569 void visit(RealExp *e)
1570 {
1571 if (!e->type->equals(t))
1572 {
1573 if ((e->type->isreal() && t->isreal()) ||
1574 (e->type->isimaginary() && t->isimaginary())
1575 )
1576 {
1577 result = e->copy();
1578 result->type = t;
1579 }
1580 else
1581 visit((Expression *)e);
1582 return;
1583 }
1584 result = e;
1585 }
1586
1587 void visit(ComplexExp *e)
1588 {
1589 if (!e->type->equals(t))
1590 {
1591 if (e->type->iscomplex() && t->iscomplex())
1592 {
1593 result = e->copy();
1594 result->type = t;
1595 }
1596 else
1597 visit((Expression *)e);
1598 return;
1599 }
1600 result = e;
1601 }
1602
1603 void visit(NullExp *e)
1604 {
1605 //printf("NullExp::castTo(t = %s) %s\n", t->toChars(), toChars());
1606 visit((Expression *)e);
1607 if (result->op == TOKnull)
1608 {
1609 NullExp *ex = (NullExp *)result;
1610 ex->committed = 1;
1611 return;
1612 }
1613 }
1614
1615 void visit(StructLiteralExp *e)
1616 {
1617 visit((Expression *)e);
1618 if (result->op == TOKstructliteral)
1619 ((StructLiteralExp *)result)->stype = t; // commit type
1620 }
1621
1622 void visit(StringExp *e)
1623 {
1624 /* This follows copy-on-write; any changes to 'this'
1625 * will result in a copy.
1626 * The this->string member is considered immutable.
1627 */
1628 int copied = 0;
1629
1630 //printf("StringExp::castTo(t = %s), '%s' committed = %d\n", t->toChars(), e->toChars(), e->committed);
1631
1632 if (!e->committed && t->ty == Tpointer && t->nextOf()->ty == Tvoid)
1633 {
1634 e->error("cannot convert string literal to void*");
1635 result = new ErrorExp();
1636 return;
1637 }
1638
1639 StringExp *se = e;
1640 if (!e->committed)
1641 {
1642 se = (StringExp *)e->copy();
1643 se->committed = 1;
1644 copied = 1;
1645 }
1646
1647 if (e->type->equals(t))
1648 {
1649 result = se;
1650 return;
1651 }
1652
1653 Type *tb = t->toBasetype();
1654 //printf("\ttype = %s\n", e->type->toChars());
1655 if (tb->ty == Tdelegate && e->type->toBasetype()->ty != Tdelegate)
1656 {
1657 visit((Expression *)e);
1658 return;
1659 }
1660
1661 Type *typeb = e->type->toBasetype();
1662 if (typeb->equals(tb))
1663 {
1664 if (!copied)
1665 {
1666 se = (StringExp *)e->copy();
1667 copied = 1;
1668 }
1669 se->type = t;
1670 result = se;
1671 return;
1672 }
1673
1674 /* Handle reinterpret casts:
1675 * cast(wchar[3])"abcd"c --> [\u6261, \u6463, \u0000]
1676 * cast(wchar[2])"abcd"c --> [\u6261, \u6463]
1677 * cast(wchar[1])"abcd"c --> [\u6261]
1678 */
1679 if (e->committed && tb->ty == Tsarray && typeb->ty == Tarray)
1680 {
1681 se = (StringExp *)e->copy();
1682 d_uns64 szx = tb->nextOf()->size();
1683 assert(szx <= 255);
1684 se->sz = (unsigned char)szx;
1685 se->len = (size_t)((TypeSArray *)tb)->dim->toInteger();
1686 se->committed = 1;
1687 se->type = t;
1688
1689 /* Assure space for terminating 0
1690 */
1691 if ((se->len + 1) * se->sz > (e->len + 1) * e->sz)
1692 {
1693 void *s = (void *)mem.xmalloc((se->len + 1) * se->sz);
1694 memcpy(s, se->string, se->len * se->sz);
1695 memset((char *)s + se->len * se->sz, 0, se->sz);
1696 se->string = s;
1697 }
1698 result = se;
1699 return;
1700 }
1701
1702 if (tb->ty != Tsarray && tb->ty != Tarray && tb->ty != Tpointer)
1703 {
1704 if (!copied)
1705 {
1706 se = (StringExp *)e->copy();
1707 copied = 1;
1708 }
1709 goto Lcast;
1710 }
1711 if (typeb->ty != Tsarray && typeb->ty != Tarray && typeb->ty != Tpointer)
1712 {
1713 if (!copied)
1714 {
1715 se = (StringExp *)e->copy();
1716 copied = 1;
1717 }
1718 goto Lcast;
1719 }
1720
1721 if (typeb->nextOf()->size() == tb->nextOf()->size())
1722 {
1723 if (!copied)
1724 {
1725 se = (StringExp *)e->copy();
1726 copied = 1;
1727 }
1728 if (tb->ty == Tsarray)
1729 goto L2; // handle possible change in static array dimension
1730 se->type = t;
1731 result = se;
1732 return;
1733 }
1734
1735 if (e->committed)
1736 goto Lcast;
1737
1738 #define X(tf,tt) ((int)(tf) * 256 + (int)(tt))
1739 {
1740 OutBuffer buffer;
1741 size_t newlen = 0;
1742 int tfty = typeb->nextOf()->toBasetype()->ty;
1743 int ttty = tb->nextOf()->toBasetype()->ty;
1744 switch (X(tfty, ttty))
1745 {
1746 case X(Tchar, Tchar):
1747 case X(Twchar,Twchar):
1748 case X(Tdchar,Tdchar):
1749 break;
1750
1751 case X(Tchar, Twchar):
1752 for (size_t u = 0; u < e->len;)
1753 {
1754 unsigned c;
1755 const char *p = utf_decodeChar((utf8_t *)se->string, e->len, &u, &c);
1756 if (p)
1757 e->error("%s", p);
1758 else
1759 buffer.writeUTF16(c);
1760 }
1761 newlen = buffer.offset / 2;
1762 buffer.writeUTF16(0);
1763 goto L1;
1764
1765 case X(Tchar, Tdchar):
1766 for (size_t u = 0; u < e->len;)
1767 {
1768 unsigned c;
1769 const char *p = utf_decodeChar((utf8_t *)se->string, e->len, &u, &c);
1770 if (p)
1771 e->error("%s", p);
1772 buffer.write4(c);
1773 newlen++;
1774 }
1775 buffer.write4(0);
1776 goto L1;
1777
1778 case X(Twchar,Tchar):
1779 for (size_t u = 0; u < e->len;)
1780 {
1781 unsigned c;
1782 const char *p = utf_decodeWchar((unsigned short *)se->string, e->len, &u, &c);
1783 if (p)
1784 e->error("%s", p);
1785 else
1786 buffer.writeUTF8(c);
1787 }
1788 newlen = buffer.offset;
1789 buffer.writeUTF8(0);
1790 goto L1;
1791
1792 case X(Twchar,Tdchar):
1793 for (size_t u = 0; u < e->len;)
1794 {
1795 unsigned c;
1796 const char *p = utf_decodeWchar((unsigned short *)se->string, e->len, &u, &c);
1797 if (p)
1798 e->error("%s", p);
1799 buffer.write4(c);
1800 newlen++;
1801 }
1802 buffer.write4(0);
1803 goto L1;
1804
1805 case X(Tdchar,Tchar):
1806 for (size_t u = 0; u < e->len; u++)
1807 {
1808 unsigned c = ((unsigned *)se->string)[u];
1809 if (!utf_isValidDchar(c))
1810 e->error("invalid UCS-32 char \\U%08x", c);
1811 else
1812 buffer.writeUTF8(c);
1813 newlen++;
1814 }
1815 newlen = buffer.offset;
1816 buffer.writeUTF8(0);
1817 goto L1;
1818
1819 case X(Tdchar,Twchar):
1820 for (size_t u = 0; u < e->len; u++)
1821 {
1822 unsigned c = ((unsigned *)se->string)[u];
1823 if (!utf_isValidDchar(c))
1824 e->error("invalid UCS-32 char \\U%08x", c);
1825 else
1826 buffer.writeUTF16(c);
1827 newlen++;
1828 }
1829 newlen = buffer.offset / 2;
1830 buffer.writeUTF16(0);
1831 goto L1;
1832
1833 L1:
1834 if (!copied)
1835 {
1836 se = (StringExp *)e->copy();
1837 copied = 1;
1838 }
1839 se->string = buffer.extractData();
1840 se->len = newlen;
1841
1842 {
1843 d_uns64 szx = tb->nextOf()->size();
1844 assert(szx <= 255);
1845 se->sz = (unsigned char)szx;
1846 }
1847 break;
1848
1849 default:
1850 assert(typeb->nextOf()->size() != tb->nextOf()->size());
1851 goto Lcast;
1852 }
1853 }
1854 #undef X
1855 L2:
1856 assert(copied);
1857
1858 // See if need to truncate or extend the literal
1859 if (tb->ty == Tsarray)
1860 {
1861 size_t dim2 = (size_t)((TypeSArray *)tb)->dim->toInteger();
1862
1863 //printf("dim from = %d, to = %d\n", (int)se->len, (int)dim2);
1864
1865 // Changing dimensions
1866 if (dim2 != se->len)
1867 {
1868 // Copy when changing the string literal
1869 size_t newsz = se->sz;
1870 size_t d = (dim2 < se->len) ? dim2 : se->len;
1871 void *s = (void *)mem.xmalloc((dim2 + 1) * newsz);
1872 memcpy(s, se->string, d * newsz);
1873 // Extend with 0, add terminating 0
1874 memset((char *)s + d * newsz, 0, (dim2 + 1 - d) * newsz);
1875 se->string = s;
1876 se->len = dim2;
1877 }
1878 }
1879 se->type = t;
1880 result = se;
1881 return;
1882
1883 Lcast:
1884 result = new CastExp(e->loc, se, t);
1885 result->type = t; // so semantic() won't be run on e
1886 }
1887
1888 void visit(AddrExp *e)
1889 {
1890 Type *tb;
1891
1892 result = e;
1893
1894 tb = t->toBasetype();
1895 e->type = e->type->toBasetype();
1896 if (!tb->equals(e->type))
1897 {
1898 // Look for pointers to functions where the functions are overloaded.
1899
1900 if (e->e1->op == TOKoverloadset &&
1901 (t->ty == Tpointer || t->ty == Tdelegate) && t->nextOf()->ty == Tfunction)
1902 {
1903 OverExp *eo = (OverExp *)e->e1;
1904 FuncDeclaration *f = NULL;
1905 for (size_t i = 0; i < eo->vars->a.dim; i++)
1906 {
1907 Dsymbol *s = eo->vars->a[i];
1908 FuncDeclaration *f2 = s->isFuncDeclaration();
1909 assert(f2);
1910 if (f2->overloadExactMatch(t->nextOf()))
1911 {
1912 if (f)
1913 {
1914 /* Error if match in more than one overload set,
1915 * even if one is a 'better' match than the other.
1916 */
1917 ScopeDsymbol::multiplyDefined(e->loc, f, f2);
1918 }
1919 else
1920 f = f2;
1921 }
1922 }
1923 if (f)
1924 {
1925 f->tookAddressOf++;
1926 SymOffExp *se = new SymOffExp(e->loc, f, 0, false);
1927 ::semantic(se, sc);
1928 // Let SymOffExp::castTo() do the heavy lifting
1929 visit(se);
1930 return;
1931 }
1932 }
1933
1934 if (e->type->ty == Tpointer && e->type->nextOf()->ty == Tfunction &&
1935 tb->ty == Tpointer && tb->nextOf()->ty == Tfunction &&
1936 e->e1->op == TOKvar)
1937 {
1938 VarExp *ve = (VarExp *)e->e1;
1939 FuncDeclaration *f = ve->var->isFuncDeclaration();
1940 if (f)
1941 {
1942 assert(f->isImportedSymbol());
1943 f = f->overloadExactMatch(tb->nextOf());
1944 if (f)
1945 {
1946 result = new VarExp(e->loc, f, false);
1947 result->type = f->type;
1948 result = new AddrExp(e->loc, result, t);
1949 return;
1950 }
1951 }
1952 }
1953
1954 if (FuncDeclaration *f = isFuncAddress(e))
1955 {
1956 if (f->checkForwardRef(e->loc))
1957 {
1958 result = new ErrorExp();
1959 return;
1960 }
1961 }
1962
1963 visit((Expression *)e);
1964 }
1965 result->type = t;
1966 }
1967
1968 void visit(TupleExp *e)
1969 {
1970 if (e->type->equals(t))
1971 {
1972 result = e;
1973 return;
1974 }
1975
1976 TupleExp *te = (TupleExp *)e->copy();
1977 te->e0 = e->e0 ? e->e0->copy() : NULL;
1978 te->exps = (Expressions *)e->exps->copy();
1979 for (size_t i = 0; i < te->exps->dim; i++)
1980 {
1981 Expression *ex = (*te->exps)[i];
1982 ex = ex->castTo(sc, t);
1983 (*te->exps)[i] = ex;
1984 }
1985 result = te;
1986
1987 /* Questionable behavior: In here, result->type is not set to t.
1988 * Therefoe:
1989 * TypeTuple!(int, int) values;
1990 * auto values2 = cast(long)values;
1991 * // typeof(values2) == TypeTuple!(int, int) !!
1992 *
1993 * Only when the casted tuple is immediately expanded, it would work.
1994 * auto arr = [cast(long)values];
1995 * // typeof(arr) == long[]
1996 */
1997 }
1998
1999 void visit(ArrayLiteralExp *e)
2000 {
2001 if (e->type == t)
2002 {
2003 result = e;
2004 return;
2005 }
2006 ArrayLiteralExp *ae = e;
2007 Type *typeb = e->type->toBasetype();
2008 Type *tb = t->toBasetype();
2009 if ((tb->ty == Tarray || tb->ty == Tsarray) &&
2010 (typeb->ty == Tarray || typeb->ty == Tsarray))
2011 {
2012 if (tb->nextOf()->toBasetype()->ty == Tvoid && typeb->nextOf()->toBasetype()->ty != Tvoid)
2013 {
2014 // Don't do anything to cast non-void[] to void[]
2015 }
2016 else if (typeb->ty == Tsarray && typeb->nextOf()->toBasetype()->ty == Tvoid)
2017 {
2018 // Don't do anything for casting void[n] to others
2019 }
2020 else
2021 {
2022 if (tb->ty == Tsarray)
2023 {
2024 TypeSArray *tsa = (TypeSArray *)tb;
2025 if (e->elements->dim != tsa->dim->toInteger())
2026 goto L1;
2027 }
2028
2029 ae = (ArrayLiteralExp *)e->copy();
2030 if (e->basis)
2031 ae->basis = e->basis->castTo(sc, tb->nextOf());
2032 ae->elements = e->elements->copy();
2033 for (size_t i = 0; i < e->elements->dim; i++)
2034 {
2035 Expression *ex = (*e->elements)[i];
2036 if (!ex)
2037 continue;
2038 ex = ex->castTo(sc, tb->nextOf());
2039 (*ae->elements)[i] = ex;
2040 }
2041 ae->type = t;
2042 result = ae;
2043 return;
2044 }
2045 }
2046 else if (tb->ty == Tpointer && typeb->ty == Tsarray)
2047 {
2048 Type *tp = typeb->nextOf()->pointerTo();
2049 if (!tp->equals(ae->type))
2050 {
2051 ae = (ArrayLiteralExp *)e->copy();
2052 ae->type = tp;
2053 }
2054 }
2055 else if (tb->ty == Tvector &&
2056 (typeb->ty == Tarray || typeb->ty == Tsarray))
2057 {
2058 // Convert array literal to vector type
2059 TypeVector *tv = (TypeVector *)tb;
2060 TypeSArray *tbase = (TypeSArray *)tv->basetype;
2061 assert(tbase->ty == Tsarray);
2062 const size_t edim = e->elements->dim;
2063 const size_t tbasedim = tbase->dim->toInteger();
2064 if (edim > tbasedim)
2065 goto L1;
2066
2067 ae = (ArrayLiteralExp *)e->copy();
2068 ae->type = tbase; // Bugzilla 12642
2069 ae->elements = e->elements->copy();
2070 Type *telement = tv->elementType();
2071 for (size_t i = 0; i < edim; i++)
2072 {
2073 Expression *ex = (*e->elements)[i];
2074 ex = ex->castTo(sc, telement);
2075 (*ae->elements)[i] = ex;
2076 }
2077 // Fill in the rest with the default initializer
2078 ae->elements->setDim(tbasedim);
2079 for (size_t i = edim; i < tbasedim; i++)
2080 {
2081 Expression *ex = typeb->nextOf()->defaultInitLiteral(e->loc);
2082 ex = ex->castTo(sc, telement);
2083 (*ae->elements)[i] = ex;
2084 }
2085 Expression *ev = new VectorExp(e->loc, ae, tb);
2086 ev = ::semantic(ev, sc);
2087 result = ev;
2088 return;
2089 }
2090 L1:
2091 visit((Expression *)ae);
2092 }
2093
2094 void visit(AssocArrayLiteralExp *e)
2095 {
2096 if (e->type == t)
2097 {
2098 result = e;
2099 return;
2100 }
2101 Type *typeb = e->type->toBasetype();
2102 Type *tb = t->toBasetype();
2103 if (tb->ty == Taarray && typeb->ty == Taarray &&
2104 tb->nextOf()->toBasetype()->ty != Tvoid)
2105 {
2106 AssocArrayLiteralExp *ae = (AssocArrayLiteralExp *)e->copy();
2107 ae->keys = e->keys->copy();
2108 ae->values = e->values->copy();
2109 assert(e->keys->dim == e->values->dim);
2110 for (size_t i = 0; i < e->keys->dim; i++)
2111 {
2112 Expression *ex = (*e->values)[i];
2113 ex = ex->castTo(sc, tb->nextOf());
2114 (*ae->values)[i] = ex;
2115
2116 ex = (*e->keys)[i];
2117 ex = ex->castTo(sc, ((TypeAArray *)tb)->index);
2118 (*ae->keys)[i] = ex;
2119 }
2120 ae->type = t;
2121 result = ae;
2122 return;
2123 }
2124 visit((Expression *)e);
2125 }
2126
2127 void visit(SymOffExp *e)
2128 {
2129 if (e->type == t && !e->hasOverloads)
2130 {
2131 result = e;
2132 return;
2133 }
2134 Type *tb = t->toBasetype();
2135 Type *typeb = e->type->toBasetype();
2136
2137 if (tb->equals(typeb))
2138 {
2139 result = e->copy();
2140 result->type = t;
2141 ((SymOffExp *)result)->hasOverloads = false;
2142 return;
2143 }
2144
2145 // Look for pointers to functions where the functions are overloaded.
2146 if (e->hasOverloads &&
2147 typeb->ty == Tpointer && typeb->nextOf()->ty == Tfunction &&
2148 (tb->ty == Tpointer || tb->ty == Tdelegate) && tb->nextOf()->ty == Tfunction)
2149 {
2150 FuncDeclaration *f = e->var->isFuncDeclaration();
2151 f = f ? f->overloadExactMatch(tb->nextOf()) : NULL;
2152 if (f)
2153 {
2154 if (tb->ty == Tdelegate)
2155 {
2156 if (f->needThis() && hasThis(sc))
2157 {
2158 result = new DelegateExp(e->loc, new ThisExp(e->loc), f, false);
2159 result = ::semantic(result, sc);
2160 }
2161 else if (f->isNested())
2162 {
2163 result = new DelegateExp(e->loc, new IntegerExp(0), f, false);
2164 result = ::semantic(result, sc);
2165 }
2166 else if (f->needThis())
2167 {
2168 e->error("no 'this' to create delegate for %s", f->toChars());
2169 result = new ErrorExp();
2170 return;
2171 }
2172 else
2173 {
2174 e->error("cannot cast from function pointer to delegate");
2175 result = new ErrorExp();
2176 return;
2177 }
2178 }
2179 else
2180 {
2181 result = new SymOffExp(e->loc, f, 0, false);
2182 result->type = t;
2183 }
2184 f->tookAddressOf++;
2185 return;
2186 }
2187 }
2188
2189 if (FuncDeclaration *f = isFuncAddress(e))
2190 {
2191 if (f->checkForwardRef(e->loc))
2192 {
2193 result = new ErrorExp();
2194 return;
2195 }
2196 }
2197
2198 visit((Expression *)e);
2199 }
2200
2201 void visit(DelegateExp *e)
2202 {
2203 static const char msg[] = "cannot form delegate due to covariant return type";
2204
2205 Type *tb = t->toBasetype();
2206 Type *typeb = e->type->toBasetype();
2207 if (!tb->equals(typeb) || e->hasOverloads)
2208 {
2209 // Look for delegates to functions where the functions are overloaded.
2210 if (typeb->ty == Tdelegate &&
2211 tb->ty == Tdelegate)
2212 {
2213 if (e->func)
2214 {
2215 FuncDeclaration *f = e->func->overloadExactMatch(tb->nextOf());
2216 if (f)
2217 {
2218 int offset;
2219 if (f->tintro && f->tintro->nextOf()->isBaseOf(f->type->nextOf(), &offset) && offset)
2220 e->error("%s", msg);
2221 if (f != e->func) // if address not already marked as taken
2222 f->tookAddressOf++;
2223 result = new DelegateExp(e->loc, e->e1, f, false);
2224 result->type = t;
2225 return;
2226 }
2227 if (e->func->tintro)
2228 e->error("%s", msg);
2229 }
2230 }
2231
2232 if (FuncDeclaration *f = isFuncAddress(e))
2233 {
2234 if (f->checkForwardRef(e->loc))
2235 {
2236 result = new ErrorExp();
2237 return;
2238 }
2239 }
2240
2241 visit((Expression *)e);
2242 }
2243 else
2244 {
2245 int offset;
2246 e->func->tookAddressOf++;
2247 if (e->func->tintro && e->func->tintro->nextOf()->isBaseOf(e->func->type->nextOf(), &offset) && offset)
2248 e->error("%s", msg);
2249 result = e->copy();
2250 result->type = t;
2251 }
2252 }
2253
2254 void visit(FuncExp *e)
2255 {
2256 //printf("FuncExp::castTo type = %s, t = %s\n", e->type->toChars(), t->toChars());
2257 FuncExp *fe;
2258 if (e->matchType(t, sc, &fe, 1) > MATCHnomatch)
2259 {
2260 result = fe;
2261 return;
2262 }
2263 visit((Expression *)e);
2264 }
2265
2266 void visit(CondExp *e)
2267 {
2268 if (!e->type->equals(t))
2269 {
2270 result = new CondExp(e->loc, e->econd, e->e1->castTo(sc, t), e->e2->castTo(sc, t));
2271 result->type = t;
2272 return;
2273 }
2274 result = e;
2275 }
2276
2277 void visit(CommaExp *e)
2278 {
2279 Expression *e2c = e->e2->castTo(sc, t);
2280
2281 if (e2c != e->e2)
2282 {
2283 result = new CommaExp(e->loc, e->e1, e2c);
2284 result->type = e2c->type;
2285 }
2286 else
2287 {
2288 result = e;
2289 result->type = e->e2->type;
2290 }
2291 }
2292
2293 void visit(SliceExp *e)
2294 {
2295 //printf("SliceExp::castTo e = %s, type = %s, t = %s\n", e->toChars(), e->type->toChars(), t->toChars());
2296 Type *typeb = e->type->toBasetype();
2297 Type *tb = t->toBasetype();
2298 if (e->type->equals(t) || typeb->ty != Tarray ||
2299 (tb->ty != Tarray && tb->ty != Tsarray))
2300 {
2301 visit((Expression *)e);
2302 return;
2303 }
2304
2305 if (tb->ty == Tarray)
2306 {
2307 if (typeb->nextOf()->equivalent(tb->nextOf()))
2308 {
2309 // T[] to const(T)[]
2310 result = e->copy();
2311 result->type = t;
2312 }
2313 else
2314 {
2315 visit((Expression *)e);
2316 }
2317 return;
2318 }
2319
2320 // Handle the cast from Tarray to Tsarray with CT-known slicing
2321
2322 TypeSArray *tsa = (TypeSArray *)toStaticArrayType(e);
2323 if (tsa && tsa->size(e->loc) == tb->size(e->loc))
2324 {
2325 /* Match if the sarray sizes are equal:
2326 * T[a .. b] to const(T)[b-a]
2327 * T[a .. b] to U[dim] if (T.sizeof*(b-a) == U.sizeof*dim)
2328 *
2329 * If a SliceExp has Tsarray, it will become lvalue.
2330 * That's handled in SliceExp::isLvalue and toLvalue
2331 */
2332 result = e->copy();
2333 result->type = t;
2334 return;
2335 }
2336 if (tsa && tsa->dim->equals(((TypeSArray *)tb)->dim))
2337 {
2338 /* Match if the dimensions are equal
2339 * with the implicit conversion of e->e1:
2340 * cast(float[2]) [2.0, 1.0, 0.0][0..2];
2341 */
2342 Type *t1b = e->e1->type->toBasetype();
2343 if (t1b->ty == Tsarray)
2344 t1b = tb->nextOf()->sarrayOf(((TypeSArray *)t1b)->dim->toInteger());
2345 else if (t1b->ty == Tarray)
2346 t1b = tb->nextOf()->arrayOf();
2347 else if (t1b->ty == Tpointer)
2348 t1b = tb->nextOf()->pointerTo();
2349 else
2350 assert(0);
2351 if (e->e1->implicitConvTo(t1b) > MATCHnomatch)
2352 {
2353 Expression *e1x = e->e1->implicitCastTo(sc, t1b);
2354 assert(e1x->op != TOKerror);
2355 e = (SliceExp *)e->copy();
2356 e->e1 = e1x;
2357 e->type = t;
2358 result = e;
2359 return;
2360 }
2361 }
2362 e->error("cannot cast expression %s of type %s to %s",
2363 e->toChars(), tsa ? tsa->toChars() : e->type->toChars(),
2364 t->toChars());
2365 result = new ErrorExp();
2366 }
2367 };
2368
2369 CastTo v(sc, t);
2370 e->accept(&v);
2371 return v.result;
2372 }
2373
2374 /* ==================== inferType ====================== */
2375
2376 /****************************************
2377 * Set type inference target
2378 * t Target type
2379 * flag 1: don't put an error when inference fails
2380 */
2381
inferType(Expression * e,Type * t,int flag)2382 Expression *inferType(Expression *e, Type *t, int flag)
2383 {
2384 class InferType : public Visitor
2385 {
2386 public:
2387 Type *t;
2388 int flag;
2389 Expression *result;
2390
2391 InferType(Type *t, int flag)
2392 : t(t), flag(flag)
2393 {
2394 result = NULL;
2395 }
2396
2397
2398 void visit(Expression *e)
2399 {
2400 result = e;
2401 }
2402
2403 void visit(ArrayLiteralExp *ale)
2404 {
2405 Type *tb = t->toBasetype();
2406 if (tb->ty == Tarray || tb->ty == Tsarray)
2407 {
2408 Type *tn = tb->nextOf();
2409 if (ale->basis)
2410 ale->basis = inferType(ale->basis, tn, flag);
2411 for (size_t i = 0; i < ale->elements->dim; i++)
2412 {
2413 Expression *e = (*ale->elements)[i];
2414 if (e)
2415 {
2416 e = inferType(e, tn, flag);
2417 (*ale->elements)[i] = e;
2418 }
2419 }
2420 }
2421 result = ale;
2422 }
2423
2424 void visit(AssocArrayLiteralExp *aale)
2425 {
2426 Type *tb = t->toBasetype();
2427 if (tb->ty == Taarray)
2428 {
2429 TypeAArray *taa = (TypeAArray *)tb;
2430 Type *ti = taa->index;
2431 Type *tv = taa->nextOf();
2432 for (size_t i = 0; i < aale->keys->dim; i++)
2433 {
2434 Expression *e = (*aale->keys)[i];
2435 if (e)
2436 {
2437 e = inferType(e, ti, flag);
2438 (*aale->keys)[i] = e;
2439 }
2440 }
2441 for (size_t i = 0; i < aale->values->dim; i++)
2442 {
2443 Expression *e = (*aale->values)[i];
2444 if (e)
2445 {
2446 e = inferType(e, tv, flag);
2447 (*aale->values)[i] = e;
2448 }
2449 }
2450 }
2451 result = aale;
2452 }
2453
2454 void visit(FuncExp *fe)
2455 {
2456 //printf("FuncExp::inferType('%s'), to=%s\n", fe->type ? fe->type->toChars() : "null", t->toChars());
2457 if (t->ty == Tdelegate ||
2458 (t->ty == Tpointer && t->nextOf()->ty == Tfunction))
2459 {
2460 fe->fd->treq = t;
2461 }
2462 result = fe;
2463 }
2464
2465 void visit(CondExp *ce)
2466 {
2467 Type *tb = t->toBasetype();
2468 ce->e1 = inferType(ce->e1, tb, flag);
2469 ce->e2 = inferType(ce->e2, tb, flag);
2470 result = ce;
2471 }
2472 };
2473
2474 if (!t)
2475 return e;
2476
2477 InferType v(t, flag);
2478 e->accept(&v);
2479 return v.result;
2480 }
2481
2482 /* ==================== ====================== */
2483
2484 /****************************************
2485 * Scale addition/subtraction to/from pointer.
2486 */
2487
scaleFactor(BinExp * be,Scope * sc)2488 Expression *scaleFactor(BinExp *be, Scope *sc)
2489 {
2490 Type *t1b = be->e1->type->toBasetype();
2491 Type *t2b = be->e2->type->toBasetype();
2492 Expression *eoff;
2493
2494 if (t1b->ty == Tpointer && t2b->isintegral())
2495 {
2496 // Need to adjust operator by the stride
2497 // Replace (ptr + int) with (ptr + (int * stride))
2498 Type *t = Type::tptrdiff_t;
2499
2500 d_uns64 stride = t1b->nextOf()->size(be->loc);
2501 if (!t->equals(t2b))
2502 be->e2 = be->e2->castTo(sc, t);
2503 eoff = be->e2;
2504 be->e2 = new MulExp(be->loc, be->e2, new IntegerExp(Loc(), stride, t));
2505 be->e2->type = t;
2506 be->type = be->e1->type;
2507 }
2508 else if (t2b->ty == Tpointer && t1b->isintegral())
2509 {
2510 // Need to adjust operator by the stride
2511 // Replace (int + ptr) with (ptr + (int * stride))
2512 Type *t = Type::tptrdiff_t;
2513 Expression *e;
2514
2515 d_uns64 stride = t2b->nextOf()->size(be->loc);
2516 if (!t->equals(t1b))
2517 e = be->e1->castTo(sc, t);
2518 else
2519 e = be->e1;
2520 eoff = e;
2521 e = new MulExp(be->loc, e, new IntegerExp(Loc(), stride, t));
2522 e->type = t;
2523 be->type = be->e2->type;
2524 be->e1 = be->e2;
2525 be->e2 = e;
2526 }
2527 else
2528 assert(0);
2529
2530 if (sc->func && !sc->intypeof)
2531 {
2532 eoff = eoff->optimize(WANTvalue);
2533 if (eoff->op == TOKint64 && eoff->toInteger() == 0)
2534 ;
2535 else if (sc->func->setUnsafe())
2536 {
2537 be->error("pointer arithmetic not allowed in @safe functions");
2538 return new ErrorExp();
2539 }
2540 }
2541
2542 return be;
2543 }
2544
2545 /**************************************
2546 * Return true if e is an empty array literal with dimensionality
2547 * equal to or less than type of other array.
2548 * [], [[]], [[[]]], etc.
2549 * I.e., make sure that [1,2] is compatible with [],
2550 * [[1,2]] is compatible with [[]], etc.
2551 */
isVoidArrayLiteral(Expression * e,Type * other)2552 bool isVoidArrayLiteral(Expression *e, Type *other)
2553 {
2554 while (e->op == TOKarrayliteral && e->type->ty == Tarray
2555 && (((ArrayLiteralExp *)e)->elements->dim == 1))
2556 {
2557 ArrayLiteralExp *ale = (ArrayLiteralExp *)e;
2558 e = ale->getElement(0);
2559 if (other->ty == Tsarray || other->ty == Tarray)
2560 other = other->nextOf();
2561 else
2562 return false;
2563 }
2564 if (other->ty != Tsarray && other->ty != Tarray)
2565 return false;
2566 Type *t = e->type;
2567 return (e->op == TOKarrayliteral && t->ty == Tarray &&
2568 t->nextOf()->ty == Tvoid &&
2569 ((ArrayLiteralExp *)e)->elements->dim == 0);
2570 }
2571
2572 // used by deduceType()
rawTypeMerge(Type * t1,Type * t2)2573 Type *rawTypeMerge(Type *t1, Type *t2)
2574 {
2575 if (t1->equals(t2))
2576 return t1;
2577 if (t1->equivalent(t2))
2578 return t1->castMod(MODmerge(t1->mod, t2->mod));
2579
2580 Type *t1b = t1->toBasetype();
2581 Type *t2b = t2->toBasetype();
2582 if (t1b->equals(t2b))
2583 return t1b;
2584 if (t1b->equivalent(t2b))
2585 return t1b->castMod(MODmerge(t1b->mod, t2b->mod));
2586
2587 TY ty = (TY)impcnvResult[t1b->ty][t2b->ty];
2588 if (ty != Terror)
2589 return Type::basic[ty];
2590
2591 return NULL;
2592 }
2593
2594 /**************************************
2595 * Combine types.
2596 * Output:
2597 * *pt merged type, if *pt is not NULL
2598 * *pe1 rewritten e1
2599 * *pe2 rewritten e2
2600 * Returns:
2601 * true success
2602 * false failed
2603 */
2604
typeMerge(Scope * sc,TOK op,Type ** pt,Expression ** pe1,Expression ** pe2)2605 bool typeMerge(Scope *sc, TOK op, Type **pt, Expression **pe1, Expression **pe2)
2606 {
2607 //printf("typeMerge() %s op %s\n", (*pe1)->toChars(), (*pe2)->toChars());
2608
2609 MATCH m;
2610 Expression *e1 = *pe1;
2611 Expression *e2 = *pe2;
2612 Type *t1b = e1->type->toBasetype();
2613 Type *t2b = e2->type->toBasetype();
2614
2615 if (op != TOKquestion ||
2616 (t1b->ty != t2b->ty && (t1b->isTypeBasic() && t2b->isTypeBasic())))
2617 {
2618 e1 = integralPromotions(e1, sc);
2619 e2 = integralPromotions(e2, sc);
2620 }
2621
2622 Type *t1 = e1->type;
2623 Type *t2 = e2->type;
2624 assert(t1);
2625 Type *t = t1;
2626
2627 /* The start type of alias this type recursion.
2628 * In following case, we should save A, and stop recursion
2629 * if it appears again.
2630 * X -> Y -> [A] -> B -> A -> B -> ...
2631 */
2632 Type *att1 = NULL;
2633 Type *att2 = NULL;
2634
2635 //if (t1) printf("\tt1 = %s\n", t1->toChars());
2636 //if (t2) printf("\tt2 = %s\n", t2->toChars());
2637 assert(t2);
2638
2639 if (t1->mod != t2->mod &&
2640 t1->ty == Tenum && t2->ty == Tenum &&
2641 ((TypeEnum *)t1)->sym == ((TypeEnum *)t2)->sym)
2642 {
2643 unsigned char mod = MODmerge(t1->mod, t2->mod);
2644 t1 = t1->castMod(mod);
2645 t2 = t2->castMod(mod);
2646 }
2647
2648 Lagain:
2649 t1b = t1->toBasetype();
2650 t2b = t2->toBasetype();
2651
2652 TY ty = (TY)impcnvResult[t1b->ty][t2b->ty];
2653 if (ty != Terror)
2654 {
2655 TY ty1 = (TY)impcnvType1[t1b->ty][t2b->ty];
2656 TY ty2 = (TY)impcnvType2[t1b->ty][t2b->ty];
2657
2658 if (t1b->ty == ty1) // if no promotions
2659 {
2660 if (t1->equals(t2))
2661 {
2662 t = t1;
2663 goto Lret;
2664 }
2665
2666 if (t1b->equals(t2b))
2667 {
2668 t = t1b;
2669 goto Lret;
2670 }
2671 }
2672
2673 t = Type::basic[ty];
2674
2675 t1 = Type::basic[ty1];
2676 t2 = Type::basic[ty2];
2677 e1 = e1->castTo(sc, t1);
2678 e2 = e2->castTo(sc, t2);
2679 //printf("after typeCombine():\n");
2680 //print();
2681 //printf("ty = %d, ty1 = %d, ty2 = %d\n", ty, ty1, ty2);
2682 goto Lret;
2683 }
2684
2685 t1 = t1b;
2686 t2 = t2b;
2687
2688 if (t1->ty == Ttuple || t2->ty == Ttuple)
2689 goto Lincompatible;
2690
2691 if (t1->equals(t2))
2692 {
2693 // merging can not result in new enum type
2694 if (t->ty == Tenum)
2695 t = t1b;
2696 }
2697 else if ((t1->ty == Tpointer && t2->ty == Tpointer) ||
2698 (t1->ty == Tdelegate && t2->ty == Tdelegate))
2699 {
2700 // Bring pointers to compatible type
2701 Type *t1n = t1->nextOf();
2702 Type *t2n = t2->nextOf();
2703
2704 if (t1n->equals(t2n))
2705 ;
2706 else if (t1n->ty == Tvoid) // pointers to void are always compatible
2707 t = t2;
2708 else if (t2n->ty == Tvoid)
2709 ;
2710 else if (t1->implicitConvTo(t2))
2711 {
2712 goto Lt2;
2713 }
2714 else if (t2->implicitConvTo(t1))
2715 {
2716 goto Lt1;
2717 }
2718 else if (t1n->ty == Tfunction && t2n->ty == Tfunction)
2719 {
2720 TypeFunction *tf1 = (TypeFunction *)t1n;
2721 TypeFunction *tf2 = (TypeFunction *)t2n;
2722 tf1->purityLevel();
2723 tf2->purityLevel();
2724
2725 TypeFunction *d = (TypeFunction *)tf1->syntaxCopy();
2726
2727 if (tf1->purity != tf2->purity)
2728 d->purity = PUREimpure;
2729 assert(d->purity != PUREfwdref);
2730
2731 d->isnothrow = (tf1->isnothrow && tf2->isnothrow);
2732 d->isnogc = (tf1->isnogc && tf2->isnogc);
2733
2734 if (tf1->trust == tf2->trust)
2735 d->trust = tf1->trust;
2736 else if (tf1->trust <= TRUSTsystem || tf2->trust <= TRUSTsystem)
2737 d->trust = TRUSTsystem;
2738 else
2739 d->trust = TRUSTtrusted;
2740
2741 Type *tx = NULL;
2742 if (t1->ty == Tdelegate)
2743 {
2744 tx = new TypeDelegate(d);
2745 }
2746 else
2747 tx = d->pointerTo();
2748
2749 tx = tx->semantic(e1->loc, sc);
2750
2751 if (t1->implicitConvTo(tx) && t2->implicitConvTo(tx))
2752 {
2753 t = tx;
2754 e1 = e1->castTo(sc, t);
2755 e2 = e2->castTo(sc, t);
2756 goto Lret;
2757 }
2758 goto Lincompatible;
2759 }
2760 else if (t1n->mod != t2n->mod)
2761 {
2762 if (!t1n->isImmutable() && !t2n->isImmutable() && t1n->isShared() != t2n->isShared())
2763 goto Lincompatible;
2764 unsigned char mod = MODmerge(t1n->mod, t2n->mod);
2765 t1 = t1n->castMod(mod)->pointerTo();
2766 t2 = t2n->castMod(mod)->pointerTo();
2767 t = t1;
2768 goto Lagain;
2769 }
2770 else if (t1n->ty == Tclass && t2n->ty == Tclass)
2771 {
2772 ClassDeclaration *cd1 = t1n->isClassHandle();
2773 ClassDeclaration *cd2 = t2n->isClassHandle();
2774 int offset;
2775
2776 if (cd1->isBaseOf(cd2, &offset))
2777 {
2778 if (offset)
2779 e2 = e2->castTo(sc, t);
2780 }
2781 else if (cd2->isBaseOf(cd1, &offset))
2782 {
2783 t = t2;
2784 if (offset)
2785 e1 = e1->castTo(sc, t);
2786 }
2787 else
2788 goto Lincompatible;
2789 }
2790 else
2791 {
2792 t1 = t1n->constOf()->pointerTo();
2793 t2 = t2n->constOf()->pointerTo();
2794 if (t1->implicitConvTo(t2))
2795 {
2796 goto Lt2;
2797 }
2798 else if (t2->implicitConvTo(t1))
2799 {
2800 goto Lt1;
2801 }
2802 goto Lincompatible;
2803 }
2804 }
2805 else if ((t1->ty == Tsarray || t1->ty == Tarray) &&
2806 ((e2->op == TOKnull && t2->ty == Tpointer && t2->nextOf()->ty == Tvoid) ||
2807 (e2->op == TOKarrayliteral && t2->ty == Tsarray && t2->nextOf()->ty == Tvoid && ((TypeSArray *)t2)->dim->toInteger() == 0) ||
2808 (isVoidArrayLiteral(e2, t1)))
2809 )
2810 {
2811 /* (T[n] op void*) => T[]
2812 * (T[] op void*) => T[]
2813 * (T[n] op void[0]) => T[]
2814 * (T[] op void[0]) => T[]
2815 * (T[n] op void[]) => T[]
2816 * (T[] op void[]) => T[]
2817 */
2818 goto Lx1;
2819 }
2820 else if ((t2->ty == Tsarray || t2->ty == Tarray) &&
2821 ((e1->op == TOKnull && t1->ty == Tpointer && t1->nextOf()->ty == Tvoid) ||
2822 (e1->op == TOKarrayliteral && t1->ty == Tsarray && t1->nextOf()->ty == Tvoid && ((TypeSArray *)t1)->dim->toInteger() == 0) ||
2823 (isVoidArrayLiteral(e1, t2)))
2824 )
2825 {
2826 /* (void* op T[n]) => T[]
2827 * (void* op T[]) => T[]
2828 * (void[0] op T[n]) => T[]
2829 * (void[0] op T[]) => T[]
2830 * (void[] op T[n]) => T[]
2831 * (void[] op T[]) => T[]
2832 */
2833 goto Lx2;
2834 }
2835 else if ((t1->ty == Tsarray || t1->ty == Tarray) &&
2836 (m = t1->implicitConvTo(t2)) != MATCHnomatch)
2837 {
2838 // Bugzilla 7285: Tsarray op [x, y, ...] should to be Tsarray
2839 // Bugzilla 14737: Tsarray ~ [x, y, ...] should to be Tarray
2840 if (t1->ty == Tsarray && e2->op == TOKarrayliteral && op != TOKcat)
2841 goto Lt1;
2842 if (m == MATCHconst &&
2843 (op == TOKaddass || op == TOKminass || op == TOKmulass ||
2844 op == TOKdivass || op == TOKmodass || op == TOKpowass ||
2845 op == TOKandass || op == TOKorass || op == TOKxorass)
2846 )
2847 {
2848 // Don't make the lvalue const
2849 t = t2;
2850 goto Lret;
2851 }
2852 goto Lt2;
2853 }
2854 else if ((t2->ty == Tsarray || t2->ty == Tarray) && t2->implicitConvTo(t1))
2855 {
2856 // Bugzilla 7285 & 14737
2857 if (t2->ty == Tsarray && e1->op == TOKarrayliteral && op != TOKcat)
2858 goto Lt2;
2859 goto Lt1;
2860 }
2861 else if ((t1->ty == Tsarray || t1->ty == Tarray || t1->ty == Tpointer) &&
2862 (t2->ty == Tsarray || t2->ty == Tarray || t2->ty == Tpointer) &&
2863 t1->nextOf()->mod != t2->nextOf()->mod
2864 )
2865 {
2866 /* If one is mutable and the other invariant, then retry
2867 * with both of them as const
2868 */
2869 Type *t1n = t1->nextOf();
2870 Type *t2n = t2->nextOf();
2871 unsigned char mod;
2872 if (e1->op == TOKnull && e2->op != TOKnull)
2873 mod = t2n->mod;
2874 else if (e1->op != TOKnull && e2->op == TOKnull)
2875 mod = t1n->mod;
2876 else if (!t1n->isImmutable() && !t2n->isImmutable() && t1n->isShared() != t2n->isShared())
2877 goto Lincompatible;
2878 else
2879 mod = MODmerge(t1n->mod, t2n->mod);
2880
2881 if (t1->ty == Tpointer)
2882 t1 = t1n->castMod(mod)->pointerTo();
2883 else
2884 t1 = t1n->castMod(mod)->arrayOf();
2885
2886 if (t2->ty == Tpointer)
2887 t2 = t2n->castMod(mod)->pointerTo();
2888 else
2889 t2 = t2n->castMod(mod)->arrayOf();
2890 t = t1;
2891 goto Lagain;
2892 }
2893 else if (t1->ty == Tclass && t2->ty == Tclass)
2894 {
2895 if (t1->mod != t2->mod)
2896 {
2897 unsigned char mod;
2898 if (e1->op == TOKnull && e2->op != TOKnull)
2899 mod = t2->mod;
2900 else if (e1->op != TOKnull && e2->op == TOKnull)
2901 mod = t1->mod;
2902 else if (!t1->isImmutable() && !t2->isImmutable() && t1->isShared() != t2->isShared())
2903 goto Lincompatible;
2904 else
2905 mod = MODmerge(t1->mod, t2->mod);
2906 t1 = t1->castMod(mod);
2907 t2 = t2->castMod(mod);
2908 t = t1;
2909 goto Lagain;
2910 }
2911 goto Lcc;
2912 }
2913 else if (t1->ty == Tclass || t2->ty == Tclass)
2914 {
2915 Lcc:
2916 while (1)
2917 {
2918 MATCH i1 = e2->implicitConvTo(t1);
2919 MATCH i2 = e1->implicitConvTo(t2);
2920
2921 if (i1 && i2)
2922 {
2923 // We have the case of class vs. void*, so pick class
2924 if (t1->ty == Tpointer)
2925 i1 = MATCHnomatch;
2926 else if (t2->ty == Tpointer)
2927 i2 = MATCHnomatch;
2928 }
2929
2930 if (i2)
2931 {
2932 e2 = e2->castTo(sc, t2);
2933 goto Lt2;
2934 }
2935 else if (i1)
2936 {
2937 e1 = e1->castTo(sc, t1);
2938 goto Lt1;
2939 }
2940 else if (t1->ty == Tclass && t2->ty == Tclass)
2941 {
2942 TypeClass *tc1 = (TypeClass *)t1;
2943 TypeClass *tc2 = (TypeClass *)t2;
2944
2945 /* Pick 'tightest' type
2946 */
2947 ClassDeclaration *cd1 = tc1->sym->baseClass;
2948 ClassDeclaration *cd2 = tc2->sym->baseClass;
2949
2950 if (cd1 && cd2)
2951 {
2952 t1 = cd1->type->castMod(t1->mod);
2953 t2 = cd2->type->castMod(t2->mod);
2954 }
2955 else if (cd1)
2956 t1 = cd1->type;
2957 else if (cd2)
2958 t2 = cd2->type;
2959 else
2960 goto Lincompatible;
2961 }
2962 else if (t1->ty == Tstruct && ((TypeStruct *)t1)->sym->aliasthis)
2963 {
2964 if (att1 && e1->type == att1)
2965 goto Lincompatible;
2966 if (!att1 && e1->type->checkAliasThisRec())
2967 att1 = e1->type;
2968 //printf("att tmerge(c || c) e1 = %s\n", e1->type->toChars());
2969 e1 = resolveAliasThis(sc, e1);
2970 t1 = e1->type;
2971 continue;
2972 }
2973 else if (t2->ty == Tstruct && ((TypeStruct *)t2)->sym->aliasthis)
2974 {
2975 if (att2 && e2->type == att2)
2976 goto Lincompatible;
2977 if (!att2 && e2->type->checkAliasThisRec())
2978 att2 = e2->type;
2979 //printf("att tmerge(c || c) e2 = %s\n", e2->type->toChars());
2980 e2 = resolveAliasThis(sc, e2);
2981 t2 = e2->type;
2982 continue;
2983 }
2984 else
2985 goto Lincompatible;
2986 }
2987 }
2988 else if (t1->ty == Tstruct && t2->ty == Tstruct)
2989 {
2990 if (t1->mod != t2->mod)
2991 {
2992 if (!t1->isImmutable() && !t2->isImmutable() && t1->isShared() != t2->isShared())
2993 goto Lincompatible;
2994 unsigned char mod = MODmerge(t1->mod, t2->mod);
2995 t1 = t1->castMod(mod);
2996 t2 = t2->castMod(mod);
2997 t = t1;
2998 goto Lagain;
2999 }
3000
3001 TypeStruct *ts1 = (TypeStruct *)t1;
3002 TypeStruct *ts2 = (TypeStruct *)t2;
3003 if (ts1->sym != ts2->sym)
3004 {
3005 if (!ts1->sym->aliasthis && !ts2->sym->aliasthis)
3006 goto Lincompatible;
3007
3008 MATCH i1 = MATCHnomatch;
3009 MATCH i2 = MATCHnomatch;
3010
3011 Expression *e1b = NULL;
3012 Expression *e2b = NULL;
3013 if (ts2->sym->aliasthis)
3014 {
3015 if (att2 && e2->type == att2)
3016 goto Lincompatible;
3017 if (!att2 && e2->type->checkAliasThisRec())
3018 att2 = e2->type;
3019 //printf("att tmerge(s && s) e2 = %s\n", e2->type->toChars());
3020 e2b = resolveAliasThis(sc, e2);
3021 i1 = e2b->implicitConvTo(t1);
3022 }
3023 if (ts1->sym->aliasthis)
3024 {
3025 if (att1 && e1->type == att1)
3026 goto Lincompatible;
3027 if (!att1 && e1->type->checkAliasThisRec())
3028 att1 = e1->type;
3029 //printf("att tmerge(s && s) e1 = %s\n", e1->type->toChars());
3030 e1b = resolveAliasThis(sc, e1);
3031 i2 = e1b->implicitConvTo(t2);
3032 }
3033 if (i1 && i2)
3034 goto Lincompatible;
3035
3036 if (i1)
3037 goto Lt1;
3038 else if (i2)
3039 goto Lt2;
3040
3041 if (e1b)
3042 {
3043 e1 = e1b;
3044 t1 = e1b->type->toBasetype();
3045 }
3046 if (e2b)
3047 {
3048 e2 = e2b;
3049 t2 = e2b->type->toBasetype();
3050 }
3051 t = t1;
3052 goto Lagain;
3053 }
3054 }
3055 else if (t1->ty == Tstruct || t2->ty == Tstruct)
3056 {
3057 if (t1->ty == Tstruct && ((TypeStruct *)t1)->sym->aliasthis)
3058 {
3059 if (att1 && e1->type == att1)
3060 goto Lincompatible;
3061 if (!att1 && e1->type->checkAliasThisRec())
3062 att1 = e1->type;
3063 //printf("att tmerge(s || s) e1 = %s\n", e1->type->toChars());
3064 e1 = resolveAliasThis(sc, e1);
3065 t1 = e1->type;
3066 t = t1;
3067 goto Lagain;
3068 }
3069 if (t2->ty == Tstruct && ((TypeStruct *)t2)->sym->aliasthis)
3070 {
3071 if (att2 && e2->type == att2)
3072 goto Lincompatible;
3073 if (!att2 && e2->type->checkAliasThisRec())
3074 att2 = e2->type;
3075 //printf("att tmerge(s || s) e2 = %s\n", e2->type->toChars());
3076 e2 = resolveAliasThis(sc, e2);
3077 t2 = e2->type;
3078 t = t2;
3079 goto Lagain;
3080 }
3081 goto Lincompatible;
3082 }
3083 else if ((e1->op == TOKstring || e1->op == TOKnull) && e1->implicitConvTo(t2))
3084 {
3085 goto Lt2;
3086 }
3087 else if ((e2->op == TOKstring || e2->op == TOKnull) && e2->implicitConvTo(t1))
3088 {
3089 goto Lt1;
3090 }
3091 else if (t1->ty == Tsarray && t2->ty == Tsarray &&
3092 e2->implicitConvTo(t1->nextOf()->arrayOf()))
3093 {
3094 Lx1:
3095 t = t1->nextOf()->arrayOf(); // T[]
3096 e1 = e1->castTo(sc, t);
3097 e2 = e2->castTo(sc, t);
3098 }
3099 else if (t1->ty == Tsarray && t2->ty == Tsarray &&
3100 e1->implicitConvTo(t2->nextOf()->arrayOf()))
3101 {
3102 Lx2:
3103 t = t2->nextOf()->arrayOf();
3104 e1 = e1->castTo(sc, t);
3105 e2 = e2->castTo(sc, t);
3106 }
3107 else if (t1->ty == Tvector && t2->ty == Tvector)
3108 {
3109 // Bugzilla 13841, all vector types should have no common types between
3110 // different vectors, even though their sizes are same.
3111 TypeVector *tv1 = (TypeVector *)t1;
3112 TypeVector *tv2 = (TypeVector *)t2;
3113 if (!tv1->basetype->equals(tv2->basetype))
3114 goto Lincompatible;
3115
3116 goto LmodCompare;
3117 }
3118 else if (t1->ty == Tvector && t2->ty != Tvector &&
3119 e2->implicitConvTo(t1))
3120 {
3121 e2 = e2->castTo(sc, t1);
3122 t2 = t1;
3123 t = t1;
3124 goto Lagain;
3125 }
3126 else if (t2->ty == Tvector && t1->ty != Tvector &&
3127 e1->implicitConvTo(t2))
3128 {
3129 e1 = e1->castTo(sc, t2);
3130 t1 = t2;
3131 t = t1;
3132 goto Lagain;
3133 }
3134 else if (t1->isintegral() && t2->isintegral())
3135 {
3136 if (t1->ty != t2->ty)
3137 {
3138 if (t1->ty == Tvector || t2->ty == Tvector)
3139 goto Lincompatible;
3140 e1 = integralPromotions(e1, sc);
3141 e2 = integralPromotions(e2, sc);
3142 t1 = e1->type;
3143 t2 = e2->type;
3144 goto Lagain;
3145 }
3146 assert(t1->ty == t2->ty);
3147 LmodCompare:
3148 if (!t1->isImmutable() && !t2->isImmutable() && t1->isShared() != t2->isShared())
3149 goto Lincompatible;
3150 unsigned char mod = MODmerge(t1->mod, t2->mod);
3151
3152 t1 = t1->castMod(mod);
3153 t2 = t2->castMod(mod);
3154 t = t1;
3155 e1 = e1->castTo(sc, t);
3156 e2 = e2->castTo(sc, t);
3157 goto Lagain;
3158 }
3159 else if (t1->ty == Tnull && t2->ty == Tnull)
3160 {
3161 unsigned char mod = MODmerge(t1->mod, t2->mod);
3162
3163 t = t1->castMod(mod);
3164 e1 = e1->castTo(sc, t);
3165 e2 = e2->castTo(sc, t);
3166 goto Lret;
3167 }
3168 else if (t2->ty == Tnull &&
3169 (t1->ty == Tpointer || t1->ty == Taarray || t1->ty == Tarray))
3170 {
3171 goto Lt1;
3172 }
3173 else if (t1->ty == Tnull &&
3174 (t2->ty == Tpointer || t2->ty == Taarray || t2->ty == Tarray))
3175 {
3176 goto Lt2;
3177 }
3178 else if (t1->ty == Tarray && isBinArrayOp(op) && isArrayOpOperand(e1))
3179 {
3180 if (e2->implicitConvTo(t1->nextOf()))
3181 {
3182 // T[] op T
3183 // T[] op cast(T)U
3184 e2 = e2->castTo(sc, t1->nextOf());
3185 t = t1->nextOf()->arrayOf();
3186 }
3187 else if (t1->nextOf()->implicitConvTo(e2->type))
3188 {
3189 // (cast(T)U)[] op T (Bugzilla 12780)
3190 // e1 is left as U[], it will be handled in arrayOp() later.
3191 t = e2->type->arrayOf();
3192 }
3193 else if (t2->ty == Tarray && isArrayOpOperand(e2))
3194 {
3195 if (t1->nextOf()->implicitConvTo(t2->nextOf()))
3196 {
3197 // (cast(T)U)[] op T[] (Bugzilla 12780)
3198 // e1 is left as U[], it will be handled in arrayOp() later.
3199 t = t2->nextOf()->arrayOf();
3200 }
3201 else if (t2->nextOf()->implicitConvTo(t1->nextOf()))
3202 {
3203 // T[] op (cast(T)U)[] (Bugzilla 12780)
3204 // e2 is left as U[], it will be handled in arrayOp() later.
3205 t = t1->nextOf()->arrayOf();
3206 }
3207 else
3208 goto Lincompatible;
3209 }
3210 else
3211 goto Lincompatible;
3212 }
3213 else if (t2->ty == Tarray && isBinArrayOp(op) && isArrayOpOperand(e2))
3214 {
3215 if (e1->implicitConvTo(t2->nextOf()))
3216 {
3217 // T op T[]
3218 // cast(T)U op T[]
3219 e1 = e1->castTo(sc, t2->nextOf());
3220 t = t2->nextOf()->arrayOf();
3221 }
3222 else if (t2->nextOf()->implicitConvTo(e1->type))
3223 {
3224 // T op (cast(T)U)[] (Bugzilla 12780)
3225 // e2 is left as U[], it will be handled in arrayOp() later.
3226 t = e1->type->arrayOf();
3227 }
3228 else
3229 goto Lincompatible;
3230
3231 //printf("test %s\n", Token::toChars(op));
3232 e1 = e1->optimize(WANTvalue);
3233 if (isCommutative(op) && e1->isConst())
3234 {
3235 /* Swap operands to minimize number of functions generated
3236 */
3237 //printf("swap %s\n", Token::toChars(op));
3238 Expression *tmp = e1;
3239 e1 = e2;
3240 e2 = tmp;
3241 }
3242 }
3243 else
3244 {
3245 Lincompatible:
3246 return false;
3247 }
3248 Lret:
3249 if (!*pt)
3250 *pt = t;
3251 *pe1 = e1;
3252 *pe2 = e2;
3253 //print();
3254 return true;
3255
3256
3257 Lt1:
3258 e2 = e2->castTo(sc, t1);
3259 t = t1;
3260 goto Lret;
3261
3262 Lt2:
3263 e1 = e1->castTo(sc, t2);
3264 t = t2;
3265 goto Lret;
3266 }
3267
3268 /************************************
3269 * Bring leaves to common type.
3270 * Returns ErrorExp if error occurs. otherwise returns NULL.
3271 */
3272
typeCombine(BinExp * be,Scope * sc)3273 Expression *typeCombine(BinExp *be, Scope *sc)
3274 {
3275 Type *t1 = be->e1->type->toBasetype();
3276 Type *t2 = be->e2->type->toBasetype();
3277
3278 if (be->op == TOKmin || be->op == TOKadd)
3279 {
3280 // struct+struct, and class+class are errors
3281 if (t1->ty == Tstruct && t2->ty == Tstruct)
3282 goto Lerror;
3283 else if (t1->ty == Tclass && t2->ty == Tclass)
3284 goto Lerror;
3285 else if (t1->ty == Taarray && t2->ty == Taarray)
3286 goto Lerror;
3287 }
3288
3289 if (!typeMerge(sc, be->op, &be->type, &be->e1, &be->e2))
3290 goto Lerror;
3291 // If the types have no value, return an error
3292 if (be->e1->op == TOKerror)
3293 return be->e1;
3294 if (be->e2->op == TOKerror)
3295 return be->e2;
3296 return NULL;
3297
3298 Lerror:
3299 Expression *ex = be->incompatibleTypes();
3300 if (ex->op == TOKerror)
3301 return ex;
3302 return new ErrorExp();
3303 }
3304
3305 /***********************************
3306 * Do integral promotions (convertchk).
3307 * Don't convert <array of> to <pointer to>
3308 */
3309
integralPromotions(Expression * e,Scope * sc)3310 Expression *integralPromotions(Expression *e, Scope *sc)
3311 {
3312 //printf("integralPromotions %s %s\n", e->toChars(), e->type->toChars());
3313 switch (e->type->toBasetype()->ty)
3314 {
3315 case Tvoid:
3316 e->error("void has no value");
3317 return new ErrorExp();
3318
3319 case Tint8:
3320 case Tuns8:
3321 case Tint16:
3322 case Tuns16:
3323 case Tbool:
3324 case Tchar:
3325 case Twchar:
3326 e = e->castTo(sc, Type::tint32);
3327 break;
3328
3329 case Tdchar:
3330 e = e->castTo(sc, Type::tuns32);
3331 break;
3332 default:
3333 break;
3334 }
3335 return e;
3336 }
3337
3338 /***********************************
3339 * See if both types are arrays that can be compared
3340 * for equality. Return true if so.
3341 * If they are arrays, but incompatible, issue error.
3342 * This is to enable comparing things like an immutable
3343 * array with a mutable one.
3344 */
3345
arrayTypeCompatible(Loc loc,Type * t1,Type * t2)3346 bool arrayTypeCompatible(Loc loc, Type *t1, Type *t2)
3347 {
3348 t1 = t1->toBasetype()->merge2();
3349 t2 = t2->toBasetype()->merge2();
3350
3351 if ((t1->ty == Tarray || t1->ty == Tsarray || t1->ty == Tpointer) &&
3352 (t2->ty == Tarray || t2->ty == Tsarray || t2->ty == Tpointer))
3353 {
3354 if (t1->nextOf()->implicitConvTo(t2->nextOf()) < MATCHconst &&
3355 t2->nextOf()->implicitConvTo(t1->nextOf()) < MATCHconst &&
3356 (t1->nextOf()->ty != Tvoid && t2->nextOf()->ty != Tvoid))
3357 {
3358 error(loc, "array equality comparison type mismatch, %s vs %s", t1->toChars(), t2->toChars());
3359 }
3360 return true;
3361 }
3362 return false;
3363 }
3364
3365 /***********************************
3366 * See if both types are arrays that can be compared
3367 * for equality without any casting. Return true if so.
3368 * This is to enable comparing things like an immutable
3369 * array with a mutable one.
3370 */
arrayTypeCompatibleWithoutCasting(Type * t1,Type * t2)3371 bool arrayTypeCompatibleWithoutCasting(Type *t1, Type *t2)
3372 {
3373 t1 = t1->toBasetype();
3374 t2 = t2->toBasetype();
3375
3376 if ((t1->ty == Tarray || t1->ty == Tsarray || t1->ty == Tpointer) &&
3377 t2->ty == t1->ty)
3378 {
3379 if (t1->nextOf()->implicitConvTo(t2->nextOf()) >= MATCHconst ||
3380 t2->nextOf()->implicitConvTo(t1->nextOf()) >= MATCHconst)
3381 return true;
3382 }
3383 return false;
3384 }
3385
3386 /******************************************************************/
3387
3388 /* Determine the integral ranges of an expression.
3389 * This is used to determine if implicit narrowing conversions will
3390 * be allowed.
3391 */
3392
getIntRange(Expression * e)3393 IntRange getIntRange(Expression *e)
3394 {
3395 class IntRangeVisitor : public Visitor
3396 {
3397 public:
3398 IntRange range;
3399
3400 void visit(Expression *e)
3401 {
3402 range = IntRange::fromType(e->type);
3403 }
3404
3405 void visit(IntegerExp *e)
3406 {
3407 range = IntRange(SignExtendedNumber(e->getInteger())).cast(e->type);
3408 }
3409
3410 void visit(CastExp *e)
3411 {
3412 range = getIntRange(e->e1).cast(e->type);
3413 }
3414
3415 void visit(AddExp *e)
3416 {
3417 IntRange ir1 = getIntRange(e->e1);
3418 IntRange ir2 = getIntRange(e->e2);
3419 range = (ir1 + ir2).cast(e->type);
3420 }
3421
3422 void visit(MinExp *e)
3423 {
3424 IntRange ir1 = getIntRange(e->e1);
3425 IntRange ir2 = getIntRange(e->e2);
3426 range = (ir1 - ir2).cast(e->type);
3427 }
3428
3429 void visit(DivExp *e)
3430 {
3431 IntRange ir1 = getIntRange(e->e1);
3432 IntRange ir2 = getIntRange(e->e2);
3433
3434 range = (ir1 / ir2).cast(e->type);
3435 }
3436
3437 void visit(MulExp *e)
3438 {
3439 IntRange ir1 = getIntRange(e->e1);
3440 IntRange ir2 = getIntRange(e->e2);
3441
3442 range = (ir1 * ir2).cast(e->type);
3443 }
3444
3445 void visit(ModExp *e)
3446 {
3447 IntRange ir1 = getIntRange(e->e1);
3448 IntRange ir2 = getIntRange(e->e2);
3449
3450 // Modding on 0 is invalid anyway.
3451 if (!ir2.absNeg().imin.negative)
3452 {
3453 visit((Expression *)e);
3454 return;
3455 }
3456 range = (ir1 % ir2).cast(e->type);
3457 }
3458
3459 void visit(AndExp *e)
3460 {
3461 IntRange result;
3462 bool hasResult = false;
3463 result.unionOrAssign(getIntRange(e->e1) & getIntRange(e->e2), hasResult);
3464
3465 assert(hasResult);
3466 range = result.cast(e->type);
3467 }
3468
3469 void visit(OrExp *e)
3470 {
3471 IntRange result;
3472 bool hasResult = false;
3473 result.unionOrAssign(getIntRange(e->e1) | getIntRange(e->e2), hasResult);
3474
3475 assert(hasResult);
3476 range = result.cast(e->type);
3477 }
3478
3479 void visit(XorExp *e)
3480 {
3481 IntRange result;
3482 bool hasResult = false;
3483 result.unionOrAssign(getIntRange(e->e1) ^ getIntRange(e->e2), hasResult);
3484
3485 assert(hasResult);
3486 range = result.cast(e->type);
3487 }
3488
3489 void visit(ShlExp *e)
3490 {
3491 IntRange ir1 = getIntRange(e->e1);
3492 IntRange ir2 = getIntRange(e->e2);
3493
3494 range = (ir1 << ir2).cast(e->type);
3495 }
3496
3497 void visit(ShrExp *e)
3498 {
3499 IntRange ir1 = getIntRange(e->e1);
3500 IntRange ir2 = getIntRange(e->e2);
3501
3502 range = (ir1 >> ir2).cast(e->type);
3503 }
3504
3505 void visit(UshrExp *e)
3506 {
3507 IntRange ir1 = getIntRange(e->e1).castUnsigned(e->e1->type);
3508 IntRange ir2 = getIntRange(e->e2);
3509
3510 range = (ir1 >> ir2).cast(e->type);
3511 }
3512
3513 void visit(AssignExp *e)
3514 {
3515 range = getIntRange(e->e2).cast(e->type);
3516 }
3517
3518 void visit(CondExp *e)
3519 {
3520 // No need to check e->econd; assume caller has called optimize()
3521 IntRange ir1 = getIntRange(e->e1);
3522 IntRange ir2 = getIntRange(e->e2);
3523 range = ir1.unionWith(ir2).cast(e->type);
3524 }
3525
3526 void visit(VarExp *e)
3527 {
3528 Expression *ie;
3529 VarDeclaration* vd = e->var->isVarDeclaration();
3530 if (vd && vd->range)
3531 range = vd->range->cast(e->type);
3532 else if (vd && vd->_init && !vd->type->isMutable() &&
3533 (ie = vd->getConstInitializer()) != NULL)
3534 ie->accept(this);
3535 else
3536 visit((Expression *)e);
3537 }
3538
3539 void visit(CommaExp *e)
3540 {
3541 e->e2->accept(this);
3542 }
3543
3544 void visit(ComExp *e)
3545 {
3546 IntRange ir = getIntRange(e->e1);
3547 range = IntRange(SignExtendedNumber(~ir.imax.value, !ir.imax.negative),
3548 SignExtendedNumber(~ir.imin.value, !ir.imin.negative)).cast(e->type);
3549 }
3550
3551 void visit(NegExp *e)
3552 {
3553 IntRange ir = getIntRange(e->e1);
3554 range = (-ir).cast(e->type);
3555 }
3556 };
3557
3558 IntRangeVisitor v;
3559 e->accept(&v);
3560 return v.range;
3561 }
3562