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