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