Debian Codegraph @

gcc/d/dmd/dcast.d

raw
1 /**
2 * Semantic analysis for cast-expressions.
3 *
4 * Copyright: Copyright (C) 1999-2025 by The D Language Foundation, All Rights Reserved
5 * Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
6 * License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
7 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/compiler/src/dmd/dcast.d, _dcast.d)
8 * Documentation: https://dlang.org/phobos/dmd_dcast.html
9 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/dcast.d
10 */
11
12 module dmd.dcast;
13
14 import core.stdc.stdio;
15 import core.stdc.string;
16 import dmd.aggregate;
17 import dmd.aliasthis;
18 import dmd.arrayop;
19 import dmd.arraytypes;
20 import dmd.astenums;
21 import dmd.dclass;
22 import dmd.declaration;
23 import dmd.denum;
24 import dmd.dinterpret;
25 import dmd.dscope;
26 import dmd.dstruct;
27 import dmd.dsymbol;
28 import dmd.dsymbolsem;
29 import dmd.errors;
30 import dmd.escape;
31 import dmd.expression;
32 import dmd.expressionsem;
33 import dmd.func;
34 import dmd.funcsem;
35 import dmd.globals;
36 import dmd.hdrgen;
37 import dmd.location;
38 import dmd.impcnvtab;
39 import dmd.importc;
40 import dmd.init;
41 import dmd.intrange;
42 import dmd.mtype;
43 import dmd.opover;
44 import dmd.optimize;
45 import dmd.root.ctfloat;
46 import dmd.common.outbuffer;
47 import dmd.root.rmem;
48 import dmd.root.utf;
49 import dmd.safe : setUnsafe;
50 import dmd.tokens;
51 import dmd.typesem;
52
53 enum LOG = false;
54
55 /**
56 * Attempt to implicitly cast the expression into type `t`.
57 *
58 * This routine will change `e`. To check the matching level,
59 * use `implicitConvTo`.
60 *
61 * Params:
62 * e = Expression that is to be casted
63 * sc = Current scope
64 * t = Expected resulting type
65 *
66 * Returns:
67 * The resulting casted expression (mutating `e`), or `ErrorExp`
68 * if such an implicit conversion is not possible.
69 */
70 Expression implicitCastTo(Expression e, Scope* sc, Type t)
71 {
72 Expression visit(Expression e)
73 {
74 //printf("Expression.implicitCastTo(%s of type %s) => %s\n", e.toChars(), e.type.toChars(), t.toChars());
75 if (const match = (sc && sc.inCfile) ? e.cimplicitConvTo(t) : e.implicitConvTo(t))
76 {
77 // no need for an extra cast when matching is exact
78
79 if (match == MATCH.convert && e.type.isTypeNoreturn() && e.op != EXP.type)
80 {
81 return specialNoreturnCast(e, t);
82 }
83 if (match == MATCH.constant && (e.type.constConv(t) || !e.isLvalue() && e.type.equivalent(t)))
84 {
85 /* Do not emit CastExp for const conversions and
86 * unique conversions on rvalue.
87 */
88 auto result = e.copy();
89 result.type = t;
90 return result;
91 }
92
93 auto ad = isAggregate(e.type);
94 if (ad && ad.aliasthis)
95 {
96 if (!ad.type || ad.type.isTypeError())
97 return e;
98 auto ts = ad.type.isTypeStruct();
99 const adMatch = ts
100 ? ts.implicitConvToWithoutAliasThis(t)
101 : ad.type.isTypeClass().implicitConvToWithoutAliasThis(t);
102
103 if (!adMatch)
104 {
105 Type tob = t.toBasetype();
106 Type t1b = e.type.toBasetype();
107 if (ad != isAggregate(tob))
108 {
109 if (t1b.ty == Tclass && tob.ty == Tclass)
110 {
111 ClassDeclaration t1cd = t1b.isClassHandle();
112 ClassDeclaration tocd = tob.isClassHandle();
113 int offset;
114 if (tocd.isBaseOf(t1cd, &offset))
115 {
116 auto result = new CastExp(e.loc, e, t);
117 result.type = t;
118 return result;
119 }
120 }
121
122 /* Forward the cast to our alias this member, rewrite to:
123 * cast(to)e1.aliasthis
124 */
125 auto result = resolveAliasThis(sc, e);
126 return result.castTo(sc, t);
127 }
128 }
129 }
130
131 return e.castTo(sc, t);
132 }
133
134 auto result = e.optimize(WANTvalue);
135 if (result != e)
136 {
137 return implicitCastTo(result, sc, t);
138 }
139
140 if (t.ty != Terror && e.type.ty != Terror)
141 {
142 if (!t.deco)
143 {
144 error(e.loc, "forward reference to type `%s`", t.toChars());
145 }
146 else
147 {
148 //printf("type %p ty %d deco %p\n", type, type.ty, type.deco);
149 //type = type.typeSemantic(loc, sc);
150 //printf("type %s t %s\n", type.deco, t.deco);
151 auto ts = toAutoQualChars(e.type, t);
152 error(e.loc, "cannot implicitly convert expression `%s` of type `%s` to `%s`",
153 e.toErrMsg(), ts[0], ts[1]);
154 }
155 }
156 return ErrorExp.get();
157 }
158
159 Expression visitString(StringExp e)
160 {
161 //printf("StringExp::implicitCastTo(%s of type %s) => %s\n", e.toChars(), e.type.toChars(), t.toChars());
162 auto result = visit(e);
163 if (auto se = result.isStringExp())
164 {
165 // Retain polysemous nature if it started out that way
166 se.committed = e.committed;
167 }
168 return result;
169 }
170
171 Expression visitError(ErrorExp e)
172 {
173 return e;
174 }
175
176 Expression visitFunc(FuncExp e)
177 {
178 //printf("FuncExp::implicitCastTo type = %p %s, t = %s\n", e.type, e.type ? e.type.toChars() : NULL, t.toChars());
179 FuncExp fe;
180 if (e.matchType(t, sc, &fe, global.errorSink) > MATCH.nomatch)
181 {
182 return fe;
183 }
184 return visit(e);
185 }
186
187 Expression visitArrayLiteral(ArrayLiteralExp e)
188 {
189 auto result = visit(e);
190
191 Type tb = result.type.toBasetype();
192 if (auto ta = tb.isTypeDArray())
193 if (global.params.useTypeInfo && Type.dtypeinfo)
194 semanticTypeInfo(sc, ta.next);
195 return result;
196 }
197
198 Expression visitSlice(SliceExp e)
199 {
200 auto result = visit(e);
201
202 if (auto se = result.isSliceExp())
203 if (auto ale = se.e1.isArrayLiteralExp())
204 {
205 Type tb = t.toBasetype();
206 Type tx = (tb.ty == Tsarray)
207 ? tb.nextOf().sarrayOf(ale.elements ? ale.elements.length : 0)
208 : tb.nextOf().arrayOf();
209 se.e1 = ale.implicitCastTo(sc, tx);
210 }
211
212 return result;
213 }
214
215 switch (e.op)
216 {
217 default : return visit (e);
218 case EXP.string_ : return visitString (e.isStringExp());
219 case EXP.error : return visitError (e.isErrorExp());
220 case EXP.function_ : return visitFunc (e.isFuncExp());
221 case EXP.arrayLiteral: return visitArrayLiteral(e.isArrayLiteralExp());
222 case EXP.slice : return visitSlice (e.isSliceExp());
223 }
224 }
225
226 /**
227 * Checks whether or not an expression can be implicitly converted
228 * to type `t`.
229 *
230 * Unlike `implicitCastTo`, this routine does not perform the actual cast,
231 * but only checks up to what `MATCH` level the conversion would be possible.
232 *
233 * Params:
234 * e = Expression that is to be casted
235 * t = Expected resulting type
236 *
237 * Returns:
238 * The `MATCH` level between `e.type` and `t`.
239 */
240 MATCH implicitConvTo(Expression e, Type t)
241 {
242 MATCH visit(Expression e)
243 {
244 version (none)
245 {
246 printf("Expression::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars());
247 }
248 //static int nest; if (++nest == 10) assert(0);
249 if (t == Type.terror)
250 return MATCH.nomatch;
251 if (!e.type)
252 {
253 error(e.loc, "`%s` is not an expression", e.toChars());
254 e.type = Type.terror;
255 }
256
257 Expression ex = e.optimize(WANTvalue);
258 if (ex.type.equals(t))
259 {
260 return MATCH.exact;
261 }
262 if (ex != e)
263 {
264 //printf("\toptimized to %s of type %s\n", e.toChars(), e.type.toChars());
265 return ex.implicitConvTo(t);
266 }
267
268 MATCH match = e.type.implicitConvTo(t);
269 if (match != MATCH.nomatch)
270 {
271 return match;
272 }
273
274 /* See if we can do integral narrowing conversions
275 */
276 if (e.type.isIntegral() && t.isIntegral() && e.type.isTypeBasic() && t.isTypeBasic())
277 {
278 IntRange src = getIntRange(e);
279 IntRange target = IntRange.fromType(t);
280 if (target.contains(src))
281 {
282 return MATCH.convert;
283 }
284 }
285 return MATCH.nomatch;
286 }
287
288 /******
289 * Given expression e of type t, see if we can implicitly convert e
290 * to type tprime, where tprime is type t with mod bits added.
291 * Returns:
292 * match level
293 */
294 static MATCH implicitMod(Expression e, Type t, MOD mod)
295 {
296 Type tprime;
297 if (t.ty == Tpointer)
298 tprime = t.nextOf().castMod(mod).pointerTo();
299 else if (t.ty == Tarray)
300 tprime = t.nextOf().castMod(mod).arrayOf();
301 else if (t.ty == Tsarray)
302 tprime = t.nextOf().castMod(mod).sarrayOf(t.size() / t.nextOf().size());
303 else
304 tprime = t.castMod(mod);
305
306 return e.implicitConvTo(tprime);
307 }
308
309 static MATCH implicitConvToAddMin(BinExp e, Type t)
310 {
311 /* Is this (ptr +- offset)? If so, then ask ptr
312 * if the conversion can be done.
313 * This is to support doing things like implicitly converting a mutable unique
314 * pointer to an immutable pointer.
315 */
316
317 Type tb = t.toBasetype();
318 Type typeb = e.type.toBasetype();
319
320 if (typeb.ty != Tpointer || tb.ty != Tpointer)
321 return MATCH.nomatch;
322
323 Type t1b = e.e1.type.toBasetype();
324 Type t2b = e.e2.type.toBasetype();
325 if (t1b.ty == Tpointer && t2b.isIntegral() && t1b.equivalent(tb))
326 {
327 // ptr + offset
328 // ptr - offset
329 MATCH m = e.e1.implicitConvTo(t);
330 return (m > MATCH.constant) ? MATCH.constant : m;
331 }
332 if (t2b.ty == Tpointer && t1b.isIntegral() && t2b.equivalent(tb))
333 {
334 // offset + ptr
335 MATCH m = e.e2.implicitConvTo(t);
336 return (m > MATCH.constant) ? MATCH.constant : m;
337 }
338
339 return MATCH.nomatch;
340 }
341
342 // Apply mod bits to each function parameter,
343 // and see if we can convert the function argument to the modded type
344 static bool parametersModMatch(Expressions* args, TypeFunction tf, MOD mod)
345 {
346 const size_t nparams = tf.parameterList.length;
347 const size_t j = tf.isDstyleVariadic(); // if TypeInfoArray was prepended
348 foreach (const i; j .. args.length)
349 {
350 Expression earg = (*args)[i];
351 Type targ = earg.type.toBasetype();
352 static if (LOG)
353 {
354 printf("[%d] earg: %s, targ: %s\n", cast(int)i, earg.toChars(), targ.toChars());
355 }
356 if (i - j < nparams)
357 {
358 Parameter fparam = tf.parameterList[i - j];
359 if (fparam.isLazy())
360 return false; // not sure what to do with this
361 Type tparam = fparam.type;
362 if (!tparam)
363 continue;
364 if (fparam.isReference())
365 {
366 if (targ.constConv(tparam.castMod(mod)) == MATCH.nomatch)
367 return false;
368 continue;
369 }
370 }
371 static if (LOG)
372 {
373 printf("[%d] earg: %s, targm: %s\n", cast(int)i, earg.toChars(), targ.addMod(mod).toChars());
374 }
375 if (implicitMod(earg, targ, mod) == MATCH.nomatch)
376 return false;
377 }
378 return true;
379 }
380
381 MATCH visitAdd(AddExp e)
382 {
383 version (none)
384 {
385 printf("AddExp::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars());
386 }
387 auto result = visit(e);
388 if (result == MATCH.nomatch)
389 result = implicitConvToAddMin(e, t);
390 return result;
391 }
392
393 MATCH visitMin(MinExp e)
394 {
395 version (none)
396 {
397 printf("MinExp::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars());
398 }
399 auto result = visit(e);
400 if (result == MATCH.nomatch)
401 result = implicitConvToAddMin(e, t);
402 return result;
403 }
404
405 MATCH visitInteger(IntegerExp e)
406 {
407 version (none)
408 {
409 printf("IntegerExp::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars());
410 }
411 MATCH m = e.type.implicitConvTo(t);
412 if (m >= MATCH.constant)
413 {
414 return m;
415 }
416
417 TY ty = e.type.toBasetype().ty;
418 TY toty = t.toBasetype().ty;
419 TY oldty = ty;
420
421 if (m == MATCH.nomatch && t.ty == Tenum)
422 return MATCH.nomatch;
423
424 if (auto tv = t.isTypeVector())
425 {
426 TypeBasic tb = tv.elementType();
427 if (tb.ty == Tvoid)
428 return MATCH.nomatch;
429 toty = tb.ty;
430 }
431
432 switch (ty)
433 {
434 case Tbool:
435 case Tint8:
436 case Tchar:
437 case Tuns8:
438 case Tint16:
439 case Tuns16:
440 case Twchar:
441 ty = Tint32;
442 break;
443
444 case Tdchar:
445 ty = Tuns32;
446 break;
447
448 default:
449 break;
450 }
451
452 // Only allow conversion if no change in value
453 immutable dinteger_t value = e.toInteger();
454
455 bool isLosslesslyConvertibleToFP(T)()
456 {
457 if (e.type.isUnsigned())
458 {
459 const f = cast(T) value;
460 return cast(dinteger_t) f == value;
461 }
462
463 const f = cast(T) cast(sinteger_t) value;
464 return cast(sinteger_t) f == cast(sinteger_t) value;
465 }
466
467 switch (toty)
468 {
469 case Tbool:
470 if ((value & 1) != value)
471 return MATCH.nomatch;
472 break;
473
474 case Tint8:
475 if (ty == Tuns64 && value & ~0x7FU)
476 return MATCH.nomatch;
477 if (cast(byte)value != value)
478 return MATCH.nomatch;
479 break;
480
481 case Tchar:
482 if ((oldty == Twchar || oldty == Tdchar) && value > 0x7F)
483 return MATCH.nomatch;
484 goto case Tuns8;
485 case Tuns8:
486 //printf("value = %llu %llu\n", cast(dinteger_t)cast(ubyte)value, value);
487 if (cast(ubyte)value != value)
488 return MATCH.nomatch;
489 break;
490
491 case Tint16:
492 if (ty == Tuns64 && value & ~0x7FFFU)
493 return MATCH.nomatch;
494 if (cast(short)value != value)
495 return MATCH.nomatch;
496 break;
497
498 case Twchar:
499 if (oldty == Tdchar && value > 0xD7FF && value < 0xE000)
500 return MATCH.nomatch;
501 goto case Tuns16;
502 case Tuns16:
503 if (cast(ushort)value != value)
504 return MATCH.nomatch;
505 break;
506
507 case Tint32:
508 if (ty == Tuns32)
509 {
510 }
511 else if (ty == Tuns64 && value & ~0x7FFFFFFFU)
512 return MATCH.nomatch;
513 else if (cast(int)value != value)
514 return MATCH.nomatch;
515 break;
516
517 case Tuns32:
518 if (ty == Tint32)
519 {
520 }
521 else if (cast(uint)value != value)
522 return MATCH.nomatch;
523 break;
524
525 case Tdchar:
526 if (value > 0x10FFFFU)
527 return MATCH.nomatch;
528 break;
529
530 case Tfloat32:
531 if (!isLosslesslyConvertibleToFP!float)
532 return MATCH.nomatch;
533 break;
534
535 case Tfloat64:
536 if (!isLosslesslyConvertibleToFP!double)
537 return MATCH.nomatch;
538 break;
539
540 case Tfloat80:
541 if (!isLosslesslyConvertibleToFP!real_t)
542 return MATCH.nomatch;
543 break;
544
545 case Tpointer:
546 //printf("type = %s\n", type.toBasetype().toChars());
547 //printf("t = %s\n", t.toBasetype().toChars());
548 if (ty == Tpointer && e.type.toBasetype().nextOf().ty == t.toBasetype().nextOf().ty)
549 {
550 /* Allow things like:
551 * const char* P = cast(char *)3;
552 * char* q = P;
553 */
554 break;
555 }
556 goto default;
557
558 default:
559 return visit(e);
560 }
561
562 //printf("MATCH.convert\n");
563 return MATCH.convert;
564 }
565
566 MATCH visitError(ErrorExp e)
567 {
568 return MATCH.nomatch;
569 }
570
571 MATCH visitNull(NullExp e)
572 {
573 version (none)
574 {
575 printf("NullExp::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars());
576 }
577 if (e.type.equals(t))
578 {
579 return MATCH.exact;
580 }
581
582 /* Allow implicit conversions from immutable to mutable|const,
583 * and mutable to immutable. It works because, after all, a null
584 * doesn't actually point to anything.
585 */
586 if (t.equivalent(e.type))
587 {
588 return MATCH.constant;
589 }
590
591 return visit(e);
592 }
593
594 MATCH visitStructLiteral(StructLiteralExp e)
595 {
596 version (none)
597 {
598 printf("StructLiteralExp::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars());
599 }
600 auto result = visit(e);
601 if (result != MATCH.nomatch)
602 return result;
603 if (e.type.ty == t.ty && e.type.isTypeStruct() && e.type.isTypeStruct().sym == t.isTypeStruct().sym)
604 {
605 result = MATCH.constant;
606 foreach (i, el; (*e.elements)[])
607 {
608 if (!el)
609 continue;
610 Type te = e.sd.fields[i].type.addMod(t.mod);
611 MATCH m2 = el.implicitConvTo(te);
612 //printf("\t%s => %s, match = %d\n", el.toChars(), te.toChars(), m2);
613 if (m2 < result)
614 result = m2;
615 }
616 }
617 return result;
618 }
619
620 MATCH visitString(StringExp e)
621 {
622 version (none)
623 {
624 printf("StringExp::implicitConvTo(this=%s, committed=%d, type=%s, t=%s)\n", e.toChars(), e.committed, e.type.toChars(), t.toChars());
625 }
626 if (!e.committed && t.ty == Tpointer && t.nextOf().ty == Tvoid)
627 return MATCH.nomatch;
628
629 if (!(e.type.isStaticOrDynamicArray() || e.type.ty == Tpointer))
630 return visit(e);
631
632 TY tyn = e.type.nextOf().ty;
633
634 if (!tyn.isSomeChar && !e.hexString)
635 return visit(e);
636
637 switch (t.ty)
638 {
639 case Tsarray:
640 if (e.type.ty == Tsarray)
641 {
642 TY tynto = t.nextOf().ty;
643 if (tynto == tyn)
644 {
645 if (e.type.isTypeSArray().dim.toInteger() == t.isTypeSArray().dim.toInteger())
646 {
647 return MATCH.exact;
648 }
649 return MATCH.nomatch;
650 }
651 if (tynto.isSomeChar)
652 {
653 if (e.committed && tynto != tyn)
654 return MATCH.nomatch;
655 size_t fromlen = e.numberOfCodeUnits(tynto);
656 size_t tolen = cast(size_t)t.isTypeSArray().dim.toInteger();
657 if (tolen < fromlen)
658 return MATCH.nomatch;
659 if (tolen != fromlen)
660 {
661 // implicit length extending
662 return MATCH.convert;
663 }
664 }
665 if (!e.committed && tynto.isSomeChar)
666 {
667 return MATCH.exact;
668 }
669 }
670 else if (e.type.ty == Tarray)
671 {
672 TY tynto = t.nextOf().ty;
673 if (tynto.isSomeChar)
674 {
675 if (e.committed && tynto != tyn)
676 return MATCH.nomatch;
677 size_t fromlen = e.numberOfCodeUnits(tynto);
678 size_t tolen = cast(size_t)t.isTypeSArray().dim.toInteger();
679 if (tolen < fromlen)
680 return MATCH.nomatch;
681 if (tolen != fromlen)
682 {
683 // implicit length extending
684 return MATCH.convert;
685 }
686 }
687 if (tynto == tyn)
688 {
689 return MATCH.exact;
690 }
691 if (!e.committed && tynto.isSomeChar)
692 {
693 return MATCH.exact;
694 }
695 }
696 goto case; /+ fall through +/
697 case Tarray:
698 case Tpointer:
699 Type tn = t.nextOf();
700 MATCH m = MATCH.exact;
701 if (e.type.nextOf().mod != tn.mod)
702 {
703 // https://issues.dlang.org/show_bug.cgi?id=16183
704 if (!tn.isConst() && !tn.isImmutable())
705 return MATCH.nomatch;
706 m = MATCH.constant;
707
708 // After converting e.g. ubyte[] to const(ubyte)[], don't change
709 // to MATCH.convert, return MATCH.constant
710 // https://github.com/dlang/dmd/issues/20635
711 if (e.type.ty == t.ty && e.type.nextOf().ty == tn.ty)
712 return m;
713 }
714 if (e.type != t && e.hexString && tn.isIntegral && (tn.size == e.sz || (!e.committed && (e.len % tn.size) == 0)))
715 {
716 m = MATCH.convert;
717 return m;
718 }
719 if (!e.committed)
720 {
721 switch (tn.ty)
722 {
723 case Tchar:
724 if (e.postfix == 'w' || e.postfix == 'd')
725 m = MATCH.convert;
726 return m;
727 case Twchar:
728 if (e.postfix != 'w')
729 m = MATCH.convert;
730 return m;
731 case Tdchar:
732 if (e.postfix != 'd')
733 m = MATCH.convert;
734 return m;
735 case Tenum:
736 if (tn.isTypeEnum().sym.isSpecial())
737 {
738 /* Allow string literal -> const(wchar_t)[]
739 */
740 if (TypeBasic tob = tn.toBasetype().isTypeBasic())
741 return tn.implicitConvTo(tob);
742 }
743 break;
744 default:
745 break;
746 }
747 }
748 break;
749
750 default:
751 break;
752 }
753
754 return visit(e);
755 }
756
757 MATCH visitArrayLiteral(ArrayLiteralExp e)
758 {
759 version (none)
760 {
761 printf("ArrayLiteralExp::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars());
762 }
763 Type tb = t.toBasetype();
764 Type typeb = e.type.toBasetype();
765
766 auto result = MATCH.nomatch;
767 if (tb.isStaticOrDynamicArray() && typeb.isStaticOrDynamicArray())
768 {
769 result = MATCH.exact;
770 Type typen = typeb.nextOf().toBasetype();
771
772 if (auto tsa = tb.isTypeSArray())
773 {
774 if (e.elements.length != tsa.dim.toInteger())
775 result = MATCH.nomatch;
776 }
777
778 Type telement = tb.nextOf();
779 if (!e.elements.length)
780 {
781 if (typen.ty != Tvoid)
782 result = typen.implicitConvTo(telement);
783 }
784 else
785 {
786 if (e.basis)
787 {
788 MATCH m = e.basis.implicitConvTo(telement);
789 if (m < result)
790 result = m;
791 }
792 for (size_t i = 0; i < e.elements.length; i++)
793 {
794 Expression el = (*e.elements)[i];
795 if (result == MATCH.nomatch)
796 break;
797 if (!el)
798 continue;
799 MATCH m = el.implicitConvTo(telement);
800 if (m < result)
801 result = m; // remember worst match
802 }
803 }
804
805 if (!result)
806 result = e.type.implicitConvTo(t);
807
808 return result;
809 }
810 else if (tb.ty == Tvector && (typeb.isStaticOrDynamicArray() || typeb.ty == Tpointer))
811 { // Tpointer because ImportC eagerly converts Tsarray to Tpointer
812 result = MATCH.exact;
813 // Convert array literal to vector type
814 TypeVector tv = tb.isTypeVector();
815 TypeSArray tbase = tv.basetype.isTypeSArray();
816 assert(tbase);
817 const edim = e.elements.length;
818 const tbasedim = tbase.dim.toInteger();
819 if (edim > tbasedim)
820 {
821 return MATCH.nomatch;
822 }
823
824 Type telement = tv.elementType();
825 if (edim < tbasedim)
826 {
827 Expression el = typeb.nextOf.defaultInitLiteral(e.loc);
828 MATCH m = el.implicitConvTo(telement);
829 if (m < result)
830 result = m; // remember worst match
831 }
832 foreach (el; (*e.elements)[])
833 {
834 MATCH m = el.implicitConvTo(telement);
835 if (m < result)
836 result = m; // remember worst match
837 if (result == MATCH.nomatch)
838 break; // no need to check for worse
839 }
840 return result;
841 }
842
843 return visit(e);
844 }
845
846 MATCH visitAssocArrayLiteral(AssocArrayLiteralExp e)
847 {
848 auto taa = t.toBasetype().isTypeAArray();
849 Type typeb = e.type.toBasetype();
850
851 if (!(taa && typeb.ty == Taarray))
852 return visit(e);
853
854 auto result = MATCH.exact;
855 foreach (i, el; (*e.keys)[])
856 {
857 MATCH m = el.implicitConvTo(taa.index);
858 if (m < result)
859 result = m; // remember worst match
860 if (result == MATCH.nomatch)
861 break; // no need to check for worse
862 el = (*e.values)[i];
863 m = el.implicitConvTo(taa.nextOf());
864 if (m < result)
865 result = m; // remember worst match
866 if (result == MATCH.nomatch)
867 break; // no need to check for worse
868 }
869 return result;
870 }
871
872 MATCH visitCall(CallExp e)
873 {
874 enum LOG = false;
875 static if (LOG)
876 {
877 printf("CallExp::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars());
878 }
879
880 auto result = visit(e);
881 if (result != MATCH.nomatch)
882 return result;
883
884 /* Allow the result of strongly pure functions to
885 * convert to immutable
886 */
887 if (e.f &&
888 (!global.params.fixImmutableConv || e.f.isPure() >= PURE.const_) &&
889 e.f.isReturnIsolated() // check isReturnIsolated last, because it is potentially expensive.
890 )
891 {
892 result = e.type.immutableOf().implicitConvTo(t);
893 if (result > MATCH.constant) // Match level is MATCH.constant at best.
894 result = MATCH.constant;
895 return result;
896 }
897
898 /* Conversion is 'const' conversion if:
899 * 1. function is pure (weakly pure is ok)
900 * 2. implicit conversion only fails because of mod bits
901 * 3. each function parameter can be implicitly converted to the mod bits
902 */
903 auto tf = (e.f ? e.f.type : e.e1.type).toBasetype().isTypeFunction();
904 if (!tf)
905 return result;
906
907 if (tf.purity == PURE.impure)
908 return result;
909 if (e.f && e.f.isNested())
910 return result;
911
912 /* See if fail only because of mod bits.
913 *
914 * https://issues.dlang.org/show_bug.cgi?id=14155
915 * All pure functions can access global immutable data.
916 * So the returned pointer may refer an immutable global data,
917 * and then the returned pointer that points non-mutable object
918 * cannot be unique pointer.
919 *
920 * Example:
921 * immutable g;
922 * static this() { g = 1; }
923 * const(int*) foo() pure { return &g; }
924 * void test() {
925 * immutable(int*) ip = foo(); // OK
926 * int* mp = foo(); // should be disallowed
927 * }
928 */
929 if (e.type.immutableOf().implicitConvTo(t) < MATCH.constant && e.type.addMod(MODFlags.shared_).implicitConvTo(t) < MATCH.constant && e.type.implicitConvTo(t.addMod(MODFlags.shared_)) < MATCH.constant)
930 {
931 return result;
932 }
933 // Allow a conversion to immutable type, or
934 // conversions of mutable types between thread-local and shared.
935
936 /* Get mod bits of what we're converting to
937 */
938 Type tb = t.toBasetype();
939 MOD mod = tb.mod;
940 if (tf.isRef)
941 {
942 }
943 else
944 {
945 if (Type ti = getIndirection(t))
946 mod = ti.mod;
947 }
948 static if (LOG)
949 {
950 printf("mod = x%x\n", mod);
951 }
952 if (mod & MODFlags.wild)
953 return result; // not sure what to do with this
954
955 /* Apply mod bits to each function parameter,
956 * and see if we can convert the function argument to the modded type
957 */
958 if (auto dve = e.e1.isDotVarExp())
959 {
960 /* Treat 'this' as just another function argument
961 */
962 Type targ = dve.e1.type;
963 if (targ.constConv(targ.castMod(mod)) == MATCH.nomatch)
964 return result;
965 }
966
967 if (!parametersModMatch(e.arguments, tf, mod))
968 return result;
969
970 /* Success
971 */
972 return MATCH.constant;
973 }
974
975 MATCH visitAddr(AddrExp e)
976 {
977 version (none)
978 {
979 printf("AddrExp::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars());
980 }
981 auto result = e.type.implicitConvTo(t);
982 //printf("\tresult = %d\n", result);
983
984 if (result != MATCH.nomatch)
985 return result;
986
987 Type tb = t.toBasetype();
988 Type typeb = e.type.toBasetype();
989
990 // Look for pointers to functions where the functions are overloaded.
991 if (e.e1.op == EXP.overloadSet &&
992 (tb.ty == Tpointer || tb.ty == Tdelegate) && tb.nextOf().ty == Tfunction)
993 {
994 OverExp eo = e.e1.isOverExp();
995 FuncDeclaration f = null;
996 foreach (s; eo.vars.a[])
997 {
998 FuncDeclaration f2 = s.isFuncDeclaration();
999 assert(f2);
1000 if (f2.overloadExactMatch(tb.nextOf()))
1001 {
1002 if (f)
1003 {
1004 /* Error if match in more than one overload set,
1005 * even if one is a 'better' match than the other.
1006 */
1007 ScopeDsymbol.multiplyDefined(e.loc, f, f2);
1008 }
1009 else
1010 f = f2;
1011 result = MATCH.exact;
1012 }
1013 }
1014 }
1015
1016 if (e.e1.op == EXP.variable &&
1017 typeb.ty == Tpointer && typeb.nextOf().ty == Tfunction &&
1018 tb.ty == Tpointer && tb.nextOf().ty == Tfunction)
1019 {
1020 /* I don't think this can ever happen -
1021 * it should have been
1022 * converted to a SymOffExp.
1023 */
1024 assert(0);
1025 }
1026
1027 //printf("\tresult = %d\n", result);
1028 return result;
1029 }
1030
1031 MATCH visitSymOff(SymOffExp e)
1032 {
1033 version (none)
1034 {
1035 printf("SymOffExp::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars());
1036 }
1037 auto result = e.type.implicitConvTo(t);
1038 //printf("\tresult = %d\n", result);
1039 if (result != MATCH.nomatch)
1040 return result;
1041
1042 Type tb = t.toBasetype();
1043 Type typeb = e.type.toBasetype();
1044
1045 // Look for pointers to functions where the functions are overloaded.
1046 if (typeb.ty == Tpointer && typeb.nextOf().ty == Tfunction &&
1047 (tb.ty == Tpointer || tb.ty == Tdelegate) && tb.nextOf().ty == Tfunction)
1048 {
1049 if (FuncDeclaration f = e.var.isFuncDeclaration())
1050 {
1051 f = f.overloadExactMatch(tb.nextOf());
1052 if (f)
1053 {
1054 if ((tb.ty == Tdelegate && (f.needThis() || f.isNested())) ||
1055 (tb.ty == Tpointer && !(f.needThis() || f.isNested())))
1056 {
1057 result = MATCH.exact;
1058 }
1059 }
1060 }
1061 }
1062 //printf("\tresult = %d\n", result);
1063 return result;
1064 }
1065
1066 MATCH visitDelegate(DelegateExp e)
1067 {
1068 version (none)
1069 {
1070 printf("DelegateExp::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars());
1071 }
1072 auto result = e.type.implicitConvTo(t);
1073 if (result != MATCH.nomatch)
1074 return result;
1075
1076 Type tb = t.toBasetype();
1077 Type typeb = e.type.toBasetype();
1078
1079 // Look for pointers to functions where the functions are overloaded.
1080 if (typeb.ty == Tdelegate && tb.ty == Tdelegate)
1081 {
1082 if (e.func && e.func.overloadExactMatch(tb.nextOf()))
1083 result = MATCH.exact;
1084 }
1085 return result;
1086 }
1087
1088 MATCH visitFunc(FuncExp e)
1089 {
1090 //printf("FuncExp::implicitConvTo type = %p %s, t = %s\n", e.type, e.type ? e.type.toChars() : NULL, t.toChars());
1091 MATCH m = e.matchType(t, null, null, global.errorSinkNull);
1092 if (m > MATCH.nomatch)
1093 {
1094 return m;
1095 }
1096 return visit(e);
1097 }
1098
1099 MATCH visitAnd(AndExp e)
1100 {
1101 auto result = visit(e);
1102 if (result != MATCH.nomatch)
1103 return result;
1104
1105 MATCH m1 = e.e1.implicitConvTo(t);
1106 MATCH m2 = e.e2.implicitConvTo(t);
1107
1108 // Pick the worst match
1109 return (m1 < m2) ? m1 : m2;
1110 }
1111
1112 MATCH visitOr(OrExp e)
1113 {
1114 auto result = visit(e);
1115 if (result != MATCH.nomatch)
1116 return result;
1117
1118 MATCH m1 = e.e1.implicitConvTo(t);
1119 MATCH m2 = e.e2.implicitConvTo(t);
1120
1121 // Pick the worst match
1122 return (m1 < m2) ? m1 : m2;
1123 }
1124
1125 MATCH visitXor(XorExp e)
1126 {
1127 auto result = visit(e);
1128 if (result != MATCH.nomatch)
1129 return result;
1130
1131 MATCH m1 = e.e1.implicitConvTo(t);
1132 MATCH m2 = e.e2.implicitConvTo(t);
1133
1134 // Pick the worst match
1135 return (m1 < m2) ? m1 : m2;
1136 }
1137
1138 MATCH visitCond(CondExp e)
1139 {
1140 e.econd = e.econd.optimize(WANTvalue);
1141 const opt = e.econd.toBool();
1142 if (opt.isPresent())
1143 {
1144 auto result = visit(e);
1145 if (result != MATCH.nomatch)
1146 return result;
1147 }
1148
1149 MATCH m1 = e.e1.implicitConvTo(t);
1150 MATCH m2 = e.e2.implicitConvTo(t);
1151 //printf("CondExp: m1 %d m2 %d\n", m1, m2);
1152
1153 // Pick the worst match
1154 return (m1 < m2) ? m1 : m2;
1155 }
1156
1157 MATCH visitComma(CommaExp e)
1158 {
1159 return e.e2.implicitConvTo(t);
1160 }
1161
1162 MATCH visitCast(CastExp e)
1163 {
1164 version (none)
1165 {
1166 printf("CastExp::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars());
1167 }
1168 auto result = e.type.implicitConvTo(t);
1169 if (result != MATCH.nomatch)
1170 return result;
1171
1172 if (t.isIntegral() && e.e1.type.isIntegral() && e.e1.implicitConvTo(t) != MATCH.nomatch)
1173 result = MATCH.convert;
1174 else
1175 result = visit(e);
1176 return result;
1177 }
1178
1179 MATCH visitNew(NewExp e)
1180 {
1181 version (none)
1182 {
1183 printf("NewExp::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars());
1184 }
1185 auto result = visit(e);
1186 if (result != MATCH.nomatch)
1187 return result;
1188
1189 /* Calling new() is like calling a pure function. We can implicitly convert the
1190 * return from new() to t using the same algorithm as in CallExp, with the function
1191 * 'arguments' being:
1192 * thisexp
1193 * arguments
1194 * .init
1195 * 'member' need to be pure.
1196 */
1197
1198 /* See if fail only because of mod bits
1199 */
1200 if (e.type.immutableOf().implicitConvTo(t.immutableOf()) == MATCH.nomatch)
1201 return MATCH.nomatch;
1202
1203 /* Get mod bits of what we're converting to
1204 */
1205 Type tb = t.toBasetype();
1206 MOD mod = tb.mod;
1207 if (Type ti = getIndirection(t))
1208 mod = ti.mod;
1209 static if (LOG)
1210 {
1211 printf("mod = x%x\n", mod);
1212 }
1213 if (mod & MODFlags.wild)
1214 return MATCH.nomatch; // not sure what to do with this
1215
1216 /* Apply mod bits to each argument,
1217 * and see if we can convert the argument to the modded type
1218 */
1219
1220 if (e.thisexp)
1221 {
1222 /* Treat 'this' as just another function argument
1223 */
1224 Type targ = e.thisexp.type;
1225 if (targ.constConv(targ.castMod(mod)) == MATCH.nomatch)
1226 return MATCH.nomatch;
1227 }
1228
1229 /* Check call to 'member'
1230 */
1231 if (e.member)
1232 {
1233 FuncDeclaration fd = e.member;
1234 if (fd.errors || fd.type.ty != Tfunction)
1235 return MATCH.nomatch; // error
1236 TypeFunction tf = fd.type.isTypeFunction();
1237 if (tf.purity == PURE.impure)
1238 return MATCH.nomatch; // impure
1239
1240 // Allow a conversion to immutable type, or
1241 // conversions of mutable types between thread-local and shared.
1242 if (e.type.immutableOf().implicitConvTo(t) < MATCH.constant && e.type.addMod(MODFlags.shared_).implicitConvTo(t) < MATCH.constant && e.type.implicitConvTo(t.addMod(MODFlags.shared_)) < MATCH.constant)
1243 {
1244 return MATCH.nomatch;
1245 }
1246
1247 if (!parametersModMatch(e.arguments, tf, mod))
1248 {
1249 return MATCH.nomatch;
1250 }
1251 }
1252
1253 /* If no 'member', then construction is by simple assignment,
1254 * and just straight check 'arguments'
1255 */
1256 if (!e.member && e.arguments)
1257 {
1258 for (size_t i = 0; i < e.arguments.length; ++i)
1259 {
1260 Expression earg = (*e.arguments)[i];
1261 if (!earg) // https://issues.dlang.org/show_bug.cgi?id=14853
1262 // if it's on overlapped field
1263 continue;
1264 Type targ = earg.type.toBasetype();
1265 static if (LOG)
1266 {
1267 printf("[%d] earg: %s, targ: %s\n", cast(int)i, earg.toChars(), targ.toChars());
1268 printf("[%d] earg: %s, targm: %s\n", cast(int)i, earg.toChars(), targ.addMod(mod).toChars());
1269 }
1270 if (implicitMod(earg, targ, mod) == MATCH.nomatch)
1271 return MATCH.nomatch;
1272 }
1273 }
1274
1275 /* Consider the .init expression as an argument
1276 */
1277 Type ntb = e.newtype.toBasetype();
1278 if (ntb.ty == Tarray)
1279 ntb = ntb.nextOf().toBasetype();
1280 if (auto ts = ntb.isTypeStruct())
1281 {
1282 // Don't allow nested structs - uplevel reference may not be convertible
1283 StructDeclaration sd = ts.sym;
1284 sd.size(e.loc); // resolve any forward references
1285 if (sd.isNested())
1286 return MATCH.nomatch;
1287 }
1288 if (ntb.isZeroInit(e.loc))
1289 {
1290 /* Zeros are implicitly convertible, except for special cases.
1291 */
1292 if (auto tc = ntb.isTypeClass())
1293 {
1294 /* With new() must look at the class instance initializer.
1295 */
1296 ClassDeclaration cd = tc.sym;
1297
1298 cd.size(e.loc); // resolve any forward references
1299
1300 if (cd.isNested())
1301 return MATCH.nomatch; // uplevel reference may not be convertible
1302
1303 assert(!cd.isInterfaceDeclaration());
1304
1305 struct ClassCheck
1306 {
1307 extern (C++) static bool convertible(Expression e, ClassDeclaration cd, MOD mod)
1308 {
1309 for (size_t i = 0; i < cd.fields.length; i++)
1310 {
1311 VarDeclaration v = cd.fields[i];
1312 Initializer _init = v._init;
1313 if (_init)
1314 {
1315 if (_init.isVoidInitializer())
1316 {
1317 }
1318 else if (ExpInitializer ei = _init.isExpInitializer())
1319 {
1320 // https://issues.dlang.org/show_bug.cgi?id=21319
1321 // This is to prevent re-analyzing the same expression
1322 // over and over again.
1323 if (ei.exp == e)
1324 return false;
1325 Type tb = v.type.toBasetype();
1326 if (implicitMod(ei.exp, tb, mod) == MATCH.nomatch)
1327 return false;
1328 }
1329 else
1330 {
1331 /* Enhancement: handle StructInitializer and ArrayInitializer
1332 */
1333 return false;
1334 }
1335 }
1336 else if (!v.type.isZeroInit(e.loc))
1337 return false;
1338 }
1339 return cd.baseClass ? convertible(e, cd.baseClass, mod) : true;
1340 }
1341 }
1342
1343 if (!ClassCheck.convertible(e, cd, mod))
1344 return MATCH.nomatch;
1345 }
1346 }
1347 else
1348 {
1349 Expression earg = e.newtype.defaultInitLiteral(e.loc);
1350 Type targ = e.newtype.toBasetype();
1351
1352 if (implicitMod(earg, targ, mod) == MATCH.nomatch)
1353 return MATCH.nomatch;
1354 }
1355
1356 /* Success
1357 */
1358 return MATCH.constant;
1359 }
1360
1361 MATCH visitSlice(SliceExp e)
1362 {
1363 //printf("SliceExp::implicitConvTo e = %s, type = %s\n", e.toChars(), e.type.toChars());
1364 auto result = visit(e);
1365 if (result != MATCH.nomatch)
1366 return result;
1367
1368 Type tb = t.toBasetype();
1369 Type typeb = e.type.toBasetype();
1370
1371 if (tb.ty == Tsarray && typeb.ty == Tarray)
1372 {
1373 typeb = toStaticArrayType(e);
1374 if (typeb)
1375 {
1376 // Try: T[] -> T[dim]
1377 // (Slice with compile-time known boundaries to static array)
1378 result = typeb.implicitConvTo(t);
1379 if (result > MATCH.convert)
1380 result = MATCH.convert; // match with implicit conversion at most
1381 }
1382 return result;
1383 }
1384
1385 /* If the only reason it won't convert is because of the mod bits,
1386 * then test for conversion by seeing if e1 can be converted with those
1387 * same mod bits.
1388 */
1389 Type t1b = e.e1.type.toBasetype();
1390 if (tb.ty == Tarray && typeb.equivalent(tb))
1391 {
1392 Type tbn = tb.nextOf();
1393 Type tx = null;
1394
1395 /* If e.e1 is dynamic array or pointer, the uniqueness of e.e1
1396 * is equivalent with the uniqueness of the referred data. And in here
1397 * we can have arbitrary typed reference for that.
1398 */
1399 if (t1b.ty == Tarray)
1400 tx = tbn.arrayOf();
1401 if (t1b.ty == Tpointer)
1402 tx = tbn.pointerTo();
1403
1404 /* If e.e1 is static array, at least it should be an rvalue.
1405 * If not, e.e1 is a reference, and its uniqueness does not link
1406 * to the uniqueness of the referred data.
1407 */
1408 if (t1b.ty == Tsarray && !e.e1.isLvalue())
1409 tx = tbn.sarrayOf(t1b.size() / tbn.size());
1410
1411 if (tx)
1412 {
1413 result = e.e1.implicitConvTo(tx);
1414 if (result > MATCH.constant) // Match level is MATCH.constant at best.
1415 result = MATCH.constant;
1416 }
1417 }
1418
1419 // Enhancement 10724
1420 if (tb.ty == Tpointer && e.e1.op == EXP.string_)
1421 result = e.e1.implicitConvTo(t);
1422 return result;
1423 }
1424
1425 MATCH visitTuple(TupleExp e)
1426 {
1427 auto result = e.type.implicitConvTo(t);
1428 if (result != MATCH.nomatch)
1429 return result;
1430
1431 /* If target type is a tuple of same length, test conversion of
1432 * each expression to the corresponding type in the tuple.
1433 */
1434 TypeTuple totuple = t.isTypeTuple();
1435 if (totuple && e.exps.length == totuple.arguments.length)
1436 {
1437 result = MATCH.exact;
1438 foreach (i, ex; *e.exps)
1439 {
1440 auto to = (*totuple.arguments)[i].type;
1441 MATCH mi = ex.implicitConvTo(to);
1442 if (mi < result)
1443 result = mi;
1444 }
1445 }
1446 return result;
1447 }
1448
1449 switch (e.op)
1450 {
1451 default : return visit(e);
1452 case EXP.add : return visitAdd(e.isAddExp());
1453 case EXP.min : return visitMin(e.isMinExp());
1454 case EXP.int64 : return visitInteger(e.isIntegerExp());
1455 case EXP.error : return visitError(e.isErrorExp());
1456 case EXP.null_ : return visitNull(e.isNullExp());
1457 case EXP.structLiteral : return visitStructLiteral(e.isStructLiteralExp());
1458 case EXP.string_ : return visitString(e.isStringExp());
1459 case EXP.arrayLiteral : return visitArrayLiteral(e.isArrayLiteralExp());
1460 case EXP.assocArrayLiteral: return visitAssocArrayLiteral(e.isAssocArrayLiteralExp());
1461 case EXP.call : return visitCall(e.isCallExp());
1462 case EXP.address : return visitAddr(e.isAddrExp());
1463 case EXP.symbolOffset : return visitSymOff(e.isSymOffExp());
1464 case EXP.delegate_ : return visitDelegate(e.isDelegateExp());
1465 case EXP.function_ : return visitFunc(e.isFuncExp());
1466 case EXP.and : return visitAnd(e.isAndExp());
1467 case EXP.or : return visitOr(e.isOrExp());
1468 case EXP.xor : return visitXor(e.isXorExp());
1469 case EXP.question : return visitCond(e.isCondExp());
1470 case EXP.comma : return visitComma(e.isCommaExp());
1471 case EXP.cast_ : return visitCast(e.isCastExp());
1472 case EXP.new_ : return visitNew(e.isNewExp());
1473 case EXP.slice : return visitSlice(e.isSliceExp());
1474 case EXP.tuple : return visitTuple(e.isTupleExp());
1475 }
1476 }
1477
1478 /********************************
1479 * Determine if 'from' can be implicitly converted
1480 * to type 'to'.
1481 * Returns:
1482 * MATCH.nomatch, MATCH.convert, MATCH.constant, MATCH.exact
1483 */
1484 MATCH implicitConvTo(Type from, Type to)
1485 {
1486 MATCH visitType(Type from)
1487 {
1488 //printf("Type::implicitConvTo(this=%p, to=%p)\n", this, to);
1489 //printf("from: %s\n", from.toChars());
1490 //printf("to : %s\n", to.toChars());
1491 if (from.equals(to))
1492 return MATCH.exact;
1493 return MATCH.nomatch;
1494
1495 }
1496
1497 MATCH visitBasic(TypeBasic from)
1498 {
1499 //printf("TypeBasic::implicitConvTo(%s) from %s\n", to.toChars(), from.toChars());
1500 if (from == to)
1501 return MATCH.exact;
1502
1503 if (from.ty == to.ty)
1504 {
1505 if (from.mod == to.mod)
1506 return MATCH.exact;
1507 if (MODimplicitConv(from.mod, to.mod))
1508 return MATCH.constant;
1509 if (!((from.mod ^ to.mod) & MODFlags.shared_)) // for wild matching
1510 return MATCH.constant;
1511 return MATCH.convert;
1512 }
1513
1514 if (from.ty == Tvoid || to.ty == Tvoid)
1515 return MATCH.nomatch;
1516 if (to.ty == Tbool)
1517 return MATCH.nomatch;
1518
1519 TypeBasic tob;
1520 if (to.ty == Tvector && to.deco)
1521 {
1522 TypeVector tv = cast(TypeVector)to;
1523 tob = tv.elementType();
1524 }
1525 else if (auto te = to.isTypeEnum())
1526 {
1527 EnumDeclaration ed = te.sym;
1528 if (ed.isSpecial())
1529 {
1530 /* Special enums that allow implicit conversions to them
1531 * with a MATCH.convert
1532 */
1533 tob = to.toBasetype().isTypeBasic();
1534 }
1535 else
1536 return MATCH.nomatch;
1537 }
1538 else
1539 tob = to.isTypeBasic();
1540 if (!tob)
1541 return MATCH.nomatch;
1542
1543 if (from.flags & TFlags.integral)
1544 {
1545 // Disallow implicit conversion of integers to imaginary or complex
1546 if (tob.flags & (TFlags.imaginary | TFlags.complex))
1547 return MATCH.nomatch;
1548
1549 // If converting from integral to integral
1550 if (tob.flags & TFlags.integral)
1551 {
1552 const sz = size(from, Loc.initial);
1553 const tosz = tob.size(Loc.initial);
1554
1555 /* Can't convert to smaller size
1556 */
1557 if (sz > tosz)
1558 return MATCH.nomatch;
1559 /* Can't change sign if same size
1560 */
1561 //if (sz == tosz && (flags ^ tob.flags) & TFlags.unsigned)
1562 // return MATCH.nomatch;
1563 }
1564 }
1565 else if (from.flags & TFlags.floating)
1566 {
1567 // Disallow implicit conversion of floating point to integer
1568 if (tob.flags & TFlags.integral)
1569 return MATCH.nomatch;
1570
1571 assert(tob.flags & TFlags.floating || to.ty == Tvector);
1572
1573 // Disallow implicit conversion from complex to non-complex
1574 if (from.flags & TFlags.complex && !(tob.flags & TFlags.complex))
1575 return MATCH.nomatch;
1576
1577 // Disallow implicit conversion of real or imaginary to complex
1578 if (from.flags & (TFlags.real_ | TFlags.imaginary) && tob.flags & TFlags.complex)
1579 return MATCH.nomatch;
1580
1581 // Disallow implicit conversion to-from real and imaginary
1582 if ((from.flags & (TFlags.real_ | TFlags.imaginary)) != (tob.flags & (TFlags.real_ | TFlags.imaginary)))
1583 return MATCH.nomatch;
1584 }
1585 return MATCH.convert;
1586
1587 }
1588
1589 MATCH visitVector(TypeVector from)
1590 {
1591 //printf("TypeVector::implicitConvTo(%s) from %s\n", to.toChars(), from.toChars());
1592 if (from == to)
1593 return MATCH.exact;
1594 if (to.ty != Tvector)
1595 return MATCH.nomatch;
1596
1597 TypeVector tv = cast(TypeVector)to;
1598 assert(from.basetype.ty == Tsarray && tv.basetype.ty == Tsarray);
1599
1600 // Can't convert to a vector which has different size.
1601 if (from.basetype.size() != tv.basetype.size())
1602 return MATCH.nomatch;
1603
1604 // Allow conversion to void[]
1605 if (tv.basetype.nextOf().ty == Tvoid)
1606 return MATCH.convert;
1607
1608 // Otherwise implicitly convertible only if basetypes are.
1609 return from.basetype.implicitConvTo(tv.basetype);
1610 }
1611
1612 MATCH visitSArray(TypeSArray from)
1613 {
1614 //printf("TypeSArray::implicitConvTo(to = %s) this = %s\n", to.toChars(), from.toChars());
1615 if (auto ta = to.isTypeDArray())
1616 {
1617 if (!MODimplicitConv(from.next.mod, ta.next.mod))
1618 return MATCH.nomatch;
1619
1620 /* Allow conversion to void[]
1621 */
1622 if (ta.next.ty == Tvoid)
1623 {
1624 return MATCH.convert;
1625 }
1626
1627 MATCH m = from.next.constConv(ta.next);
1628 if (m > MATCH.nomatch)
1629 {
1630 return MATCH.convert;
1631 }
1632 return MATCH.nomatch;
1633 }
1634 if (auto tsa = to.isTypeSArray())
1635 {
1636 if (from == to)
1637 return MATCH.exact;
1638
1639 if (from.dim.equals(tsa.dim))
1640 {
1641 MATCH m = from.next.implicitConvTo(tsa.next);
1642
1643 /* Allow conversion to non-interface base class.
1644 */
1645 if (m == MATCH.convert &&
1646 from.next.ty == Tclass)
1647 {
1648 if (auto toc = tsa.next.isTypeClass)
1649 {
1650 if (!toc.sym.isInterfaceDeclaration)
1651 return MATCH.convert;
1652 }
1653 }
1654
1655 /* Since static arrays are value types, allow
1656 * conversions from const elements to non-const
1657 * ones, just like we allow conversion from const int
1658 * to int.
1659 */
1660 if (m >= MATCH.constant)
1661 {
1662 if (from.mod != to.mod)
1663 m = MATCH.constant;
1664 return m;
1665 }
1666 }
1667 }
1668 return MATCH.nomatch;
1669 }
1670
1671 MATCH visitDArray(TypeDArray from)
1672 {
1673 //printf("TypeDArray::implicitConvTo(to = %s) this = %s\n", to.toChars(), from.toChars());
1674 if (from.equals(to))
1675 return MATCH.exact;
1676
1677 if (auto ta = to.isTypeDArray())
1678 {
1679 if (!MODimplicitConv(from.next.mod, ta.next.mod))
1680 return MATCH.nomatch; // not const-compatible
1681
1682 /* Allow conversion to void[]
1683 */
1684 if (from.next.ty != Tvoid && ta.next.ty == Tvoid)
1685 {
1686 return MATCH.convert;
1687 }
1688
1689 MATCH m = from.next.constConv(ta.next);
1690 if (m > MATCH.nomatch)
1691 {
1692 if (m == MATCH.exact && from.mod != to.mod)
1693 m = MATCH.constant;
1694 return m;
1695 }
1696 }
1697
1698 return visitType(from);
1699 }
1700
1701 MATCH visitAArray(TypeAArray from)
1702 {
1703 //printf("TypeAArray::implicitConvTo(to = %s) this = %s\n", to.toChars(), from.toChars());
1704 if (from.equals(to))
1705 return MATCH.exact;
1706
1707 if (auto ta = to.isTypeAArray())
1708 {
1709 if (!MODimplicitConv(from.next.mod, ta.next.mod))
1710 return MATCH.nomatch; // not const-compatible
1711
1712 if (!MODimplicitConv(from.index.mod, ta.index.mod))
1713 return MATCH.nomatch; // not const-compatible
1714
1715 MATCH m = from.next.constConv(ta.next);
1716 MATCH mi = from.index.constConv(ta.index);
1717 if (m > MATCH.nomatch && mi > MATCH.nomatch)
1718 {
1719 return MODimplicitConv(from.mod, to.mod) ? MATCH.constant : MATCH.nomatch;
1720 }
1721 }
1722 return visitType(from);
1723 }
1724
1725 /+
1726 + Checks whether this function type is convertible to ` to`
1727 + when used in a function pointer / delegate.
1728 +
1729 + Params:
1730 + to = target type
1731 +
1732 + Returns:
1733 + MATCH.nomatch: `to` is not a covaraint function
1734 + MATCH.convert: `to` is a covaraint function
1735 + MATCH.exact: `to` is identical to this function
1736 +/
1737 MATCH implicitPointerConv(TypeFunction tf, Type to)
1738 {
1739 assert(to);
1740
1741 if (tf.equals(to))
1742 return MATCH.constant;
1743
1744 if (tf.covariant(to) == Covariant.yes)
1745 {
1746 Type tret = tf.nextOf();
1747 Type toret = to.nextOf();
1748 if (tret.ty == Tclass && toret.ty == Tclass)
1749 {
1750 /* https://issues.dlang.org/show_bug.cgi?id=10219
1751 * Check covariant interface return with offset tweaking.
1752 * interface I {}
1753 * class C : Object, I {}
1754 * I function() dg = function C() {} // should be error
1755 */
1756 int offset = 0;
1757 if (toret.isBaseOf(tret, &offset) && offset != 0)
1758 return MATCH.nomatch;
1759 }
1760 return MATCH.convert;
1761 }
1762
1763 return MATCH.nomatch;
1764 }
1765
1766 MATCH visitPointer(TypePointer from)
1767 {
1768 //printf("TypePointer::implicitConvTo(to = %s) %s\n", to.toChars(), from.toChars());
1769 if (from.equals(to))
1770 return MATCH.exact;
1771
1772 // Only convert between pointers
1773 auto tp = to.isTypePointer();
1774 if (!tp)
1775 return MATCH.nomatch;
1776
1777 assert(from.next);
1778 assert(tp.next);
1779
1780 // Conversion to void*
1781 if (tp.next.ty == Tvoid)
1782 {
1783 // Function pointer conversion doesn't check constness?
1784 if (from.next.ty == Tfunction)
1785 return MATCH.convert;
1786
1787 if (!MODimplicitConv(from.next.mod, tp.next.mod))
1788 return MATCH.nomatch; // not const-compatible
1789
1790 return from.next.ty == Tvoid ? MATCH.constant : MATCH.convert;
1791 }
1792
1793 // Conversion between function pointers
1794 if (auto thisTf = from.next.isTypeFunction())
1795 return implicitPointerConv(thisTf, tp.next);
1796
1797 // Default, no implicit conversion between the pointer targets
1798 MATCH m = from.next.constConv(tp.next);
1799
1800 if (m == MATCH.exact && from.mod != to.mod)
1801 m = MATCH.constant;
1802 return m;
1803 }
1804
1805 MATCH visitDelegate(TypeDelegate from)
1806 {
1807 //printf("TypeDelegate.implicitConvTo(this=%p, to=%p)\n", from, to);
1808 //printf("from: %s\n", from.toChars());
1809 //printf("to : %s\n", to.toChars());
1810 if (from.equals(to))
1811 return MATCH.exact;
1812
1813 if (auto toDg = to.isTypeDelegate())
1814 {
1815 MATCH m = implicitPointerConv(from.next.isTypeFunction(), toDg.next);
1816
1817 // Retain the old behaviour for this refactoring
1818 // Should probably be changed to constant to match function pointers
1819 if (m > MATCH.convert)
1820 m = MATCH.convert;
1821
1822 return m;
1823 }
1824
1825 return MATCH.nomatch;
1826 }
1827
1828 MATCH visitStruct(TypeStruct from)
1829 {
1830 //printf("TypeStruct::implicitConvTo(%s => %s)\n", from.toChars(), to.toChars());
1831 MATCH m = from.implicitConvToWithoutAliasThis(to);
1832 return m == MATCH.nomatch ? from.implicitConvToThroughAliasThis(to) : m;
1833 }
1834
1835 MATCH visitEnum(TypeEnum from)
1836 {
1837 import dmd.enumsem : getMemtype;
1838
1839 MATCH m;
1840 //printf("TypeEnum::implicitConvTo() %s to %s\n", from.toChars(), to.toChars());
1841 if (from.ty == to.ty && from.sym == (cast(TypeEnum)to).sym)
1842 m = (from.mod == to.mod) ? MATCH.exact : MATCH.constant;
1843 else if (from.sym.getMemtype(Loc.initial).implicitConvTo(to))
1844 m = MATCH.convert; // match with conversions
1845 else
1846 m = MATCH.nomatch; // no match
1847 return m;
1848 }
1849
1850 MATCH visitClass(TypeClass from)
1851 {
1852 //printf("TypeClass::implicitConvTo(to = '%s') %s\n", to.toChars(), from.toChars());
1853 MATCH m = from.implicitConvToWithoutAliasThis(to);
1854 return m ? m : from.implicitConvToThroughAliasThis(to);
1855 }
1856
1857 MATCH visitTuple(TypeTuple from)
1858 {
1859 if (from == to)
1860 return MATCH.exact;
1861 if (auto tt = to.isTypeTuple())
1862 {
1863 if (from.arguments.length == tt.arguments.length)
1864 {
1865 MATCH m = MATCH.exact;
1866 for (size_t i = 0; i < tt.arguments.length; i++)
1867 {
1868 Parameter arg1 = (*from.arguments)[i];
1869 Parameter arg2 = (*tt.arguments)[i];
1870 MATCH mi = arg1.type.implicitConvTo(arg2.type);
1871 if (mi < m)
1872 m = mi;
1873 }
1874 return m;
1875 }
1876 }
1877 return MATCH.nomatch;
1878 }
1879
1880 MATCH visitNull(TypeNull from)
1881 {
1882 //printf("TypeNull::implicitConvTo(this=%p, to=%p)\n", from, to);
1883 //printf("from: %s\n", from.toChars());
1884 //printf("to : %s\n", to.toChars());
1885 MATCH m = visitType(cast(Type)from);
1886 if (m != MATCH.nomatch)
1887 return m;
1888
1889 //NULL implicitly converts to any pointer type or dynamic array
1890 //if (type.ty == Tpointer && type.nextOf().ty == Tvoid)
1891 {
1892 Type tb = to.toBasetype();
1893 if (tb.ty == Tnull || tb.ty == Tpointer || tb.ty == Tarray || tb.ty == Taarray || tb.ty == Tclass || tb.ty == Tdelegate)
1894 return MATCH.constant;
1895 }
1896
1897 return MATCH.nomatch;
1898 }
1899
1900 MATCH visitNoreturn(TypeNoreturn from)
1901 {
1902 //printf("TypeNoreturn::implicitConvTo(this=%p, to=%p)\n", from, to);
1903 //printf("from: %s\n", from.toChars());
1904 //printf("to : %s\n", to.toChars());
1905 if (from.equals(to))
1906 return MATCH.exact;
1907
1908 // Different qualifiers?
1909 if (to.ty == Tnoreturn)
1910 return MATCH.constant;
1911
1912 // Implicitly convertible to any type
1913 return MATCH.convert;
1914 }
1915
1916 switch(from.ty)
1917 {
1918 default: return from.isTypeBasic() ? visitBasic(from.isTypeBasic()) : visitType(from);
1919 case Tvector: return visitVector(from.isTypeVector());
1920 case Tsarray: return visitSArray(from.isTypeSArray());
1921 case Tarray: return visitDArray(from.isTypeDArray());
1922 case Taarray: return visitAArray(from.isTypeAArray());
1923 case Tpointer: return visitPointer(from.isTypePointer());
1924 case Tdelegate: return visitDelegate(from.isTypeDelegate());
1925 case Tstruct: return visitStruct(from.isTypeStruct());
1926 case Tenum: return visitEnum(from.isTypeEnum());
1927 case Tclass: return visitClass(from.isTypeClass());
1928 case Ttuple: return visitTuple(from.isTypeTuple());
1929 case Tnull: return visitNull(from.isTypeNull());
1930 case Tnoreturn: return visitNoreturn(from.isTypeNoreturn());
1931 }
1932 }
1933
1934 /**
1935 * Same as implicitConvTo(); except follow C11 rules, which are quite a bit
1936 * more permissive than D.
1937 * C11 6.3 and 6.5.16.1
1938 * Params:
1939 * e = Expression that is to be casted
1940 * t = Expected resulting type
1941 * Returns:
1942 * The `MATCH` level between `e.type` and `t`.
1943 */
1944 MATCH cimplicitConvTo(Expression e, Type t)
1945 {
1946 Type tb = t.toBasetype();
1947 Type typeb = e.type.toBasetype();
1948
1949 if (tb.equals(typeb))
1950 return MATCH.exact;
1951
1952 if (tb.isTypeVector() || typeb.isTypeVector())
1953 return implicitConvTo(e, t); // permissive checking doesn't apply to vectors
1954
1955 if ((typeb.isIntegral() || typeb.isFloating()) &&
1956 (tb.isIntegral() || tb.isFloating()))
1957 return MATCH.convert;
1958 if (tb.ty == Tpointer && typeb.isIntegral()) // C11 6.3.2.3-5
1959 return MATCH.convert;
1960 if (tb.isIntegral() && typeb.ty == Tpointer) // C11 6.3.2.3-6
1961 return MATCH.convert;
1962 if (tb.ty == Tpointer && typeb.ty == Tpointer) // C11 6.3.2.3-7
1963 return MATCH.convert;
1964
1965 return implicitConvTo(e, t);
1966 }
1967
1968 /*****************************************
1969 */
1970 Type toStaticArrayType(SliceExp e)
1971 {
1972 if (e.lwr && e.upr)
1973 {
1974 // For the following code to work, e should be optimized beforehand.
1975 // (eg. $ in lwr and upr should be already resolved, if possible)
1976 Expression lwr = e.lwr.optimize(WANTvalue);
1977 Expression upr = e.upr.optimize(WANTvalue);
1978 if (lwr.isConst() && upr.isConst())
1979 {
1980 size_t len = cast(size_t)(upr.toUInteger() - lwr.toUInteger());
1981 return e.type.toBasetype().nextOf().sarrayOf(len);
1982 }
1983 }
1984 else
1985 {
1986 Type t1b = e.e1.type.toBasetype();
1987 if (t1b.ty == Tsarray)
1988 return t1b;
1989 }
1990 return null;
1991 }
1992
1993 /**************************************
1994 * Do an explicit cast.
1995 * Assume that the expression `e` does not have any indirections.
1996 * (Parameter 'att' is used to stop 'alias this' recursion)
1997 */
1998 Expression castTo(Expression e, Scope* sc, Type t, Type att = null)
1999 {
2000 //printf("castTo(e: %s from: %s to: %s\n", e.toChars(), e.type.toChars(), t.toChars());
2001
2002 Expression visit(Expression e)
2003 {
2004 //printf("Expression::castTo(this=%s, t=%s)\n", e.toChars(), t.toChars());
2005 version (none)
2006 {
2007 printf("Expression::castTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars());
2008 }
2009 if (e.type.equals(t))
2010 {
2011 return e;
2012 }
2013 if (e.type.isTypeNoreturn() && e.op != EXP.type)
2014 {
2015 return specialNoreturnCast(e, t);
2016 }
2017 if (auto ve = e.isVarExp())
2018 {
2019 VarDeclaration v = ve.var.isVarDeclaration();
2020 if (v && v.storage_class & STC.manifest)
2021 {
2022 auto result = e.ctfeInterpret();
2023 /* https://issues.dlang.org/show_bug.cgi?id=18236
2024 *
2025 * The expression returned by ctfeInterpret points
2026 * to the line where the manifest constant was declared
2027 * so we need to update the location before trying to cast
2028 */
2029 result.loc = e.loc;
2030 return result.castTo(sc, t);
2031 }
2032 }
2033
2034 Type tob = t.toBasetype();
2035 Type t1b = e.type.toBasetype();
2036 if (tob.equals(t1b))
2037 {
2038 auto result = e.copy(); // because of COW for assignment to e.type
2039 result.type = t;
2040 return result;
2041 }
2042
2043 /* Make semantic error against invalid cast between concrete types.
2044 * Assume that 'e' is never be any placeholder expressions.
2045 * The result of these checks should be consistent with CastExp::toElem().
2046 */
2047
2048 // Fat Value types
2049 const(bool) tob_isFV = (tob.ty == Tstruct || tob.ty == Tsarray || tob.ty == Tvector);
2050 const(bool) t1b_isFV = (t1b.ty == Tstruct || t1b.ty == Tsarray || t1b.ty == Tvector);
2051
2052 // Fat Reference types
2053 const(bool) tob_isFR = (tob.ty == Tarray || tob.ty == Tdelegate);
2054 const(bool) t1b_isFR = (t1b.ty == Tarray || t1b.ty == Tdelegate);
2055
2056 // Reference types
2057 const(bool) tob_isR = (tob_isFR || tob.ty == Tpointer || tob.ty == Taarray || tob.ty == Tclass);
2058 const(bool) t1b_isR = (t1b_isFR || t1b.ty == Tpointer || t1b.ty == Taarray || t1b.ty == Tclass);
2059
2060 // Arithmetic types (== valueable basic types)
2061 const(bool) tob_isA = ((tob.isIntegral() || tob.isFloating()) && tob.ty != Tvector);
2062 const(bool) t1b_isA = ((t1b.isIntegral() || t1b.isFloating()) && t1b.ty != Tvector);
2063
2064 // Try casting the alias this member.
2065 // Return the expression if it succeeds, null otherwise.
2066 Expression tryAliasThisCast()
2067 {
2068 if (isRecursiveAliasThis(att, t1b))
2069 return null;
2070
2071 /* Forward the cast to our alias this member, rewrite to:
2072 * cast(to)e1.aliasthis
2073 */
2074 auto exp = resolveAliasThis(sc, e);
2075 const errors = global.startGagging();
2076 exp = castTo(exp, sc, t, att);
2077 return global.endGagging(errors) ? null : exp;
2078 }
2079
2080 bool hasAliasThis;
2081 if (AggregateDeclaration t1ad = isAggregate(t1b))
2082 {
2083 AggregateDeclaration toad = isAggregate(tob);
2084 if (t1ad != toad && t1ad.aliasthis)
2085 {
2086 if (t1b.ty == Tclass && tob.ty == Tclass)
2087 {
2088 ClassDeclaration t1cd = t1b.isClassHandle();
2089 ClassDeclaration tocd = tob.isClassHandle();
2090 int offset;
2091 if (tocd.isBaseOf(t1cd, &offset))
2092 goto Lok;
2093 }
2094 hasAliasThis = true;
2095 }
2096 }
2097 else if (tob.ty == Tvector && t1b.ty != Tvector)
2098 {
2099 if (t1b.ty == Tsarray)
2100 {
2101 // Casting static array to vector with same size, e.g. `cast(int4) int[4]`
2102 if (t1b.size(e.loc) != tob.size(e.loc))
2103 goto Lfail;
2104 return new VectorExp(e.loc, e, tob).expressionSemantic(sc);
2105 }
2106 //printf("test1 e = %s, e.type = %s, tob = %s\n", e.toChars(), e.type.toChars(), tob.toChars());
2107 TypeVector tv = tob.isTypeVector();
2108 Expression result = new CastExp(e.loc, e, tv.elementType());
2109 result = new VectorExp(e.loc, result, tob);
2110 result = result.expressionSemantic(sc);
2111 return result;
2112 }
2113 else if (tob.ty != Tvector && t1b.ty == Tvector)
2114 {
2115 // T[n] <-- __vector(U[m])
2116 if (tob.ty == Tsarray)
2117 {
2118 if (t1b.size(e.loc) == tob.size(e.loc))
2119 goto Lok;
2120 }
2121 goto Lfail;
2122 }
2123 else if (t1b.implicitConvTo(tob) == MATCH.constant && t.equals(e.type.constOf()))
2124 {
2125 auto result = e.copy();
2126 result.type = t;
2127 return result;
2128 }
2129
2130 // arithmetic values vs. other arithmetic values
2131 // arithmetic values vs. T*
2132 if (tob_isA && (t1b_isA || t1b.ty == Tpointer) || t1b_isA && (tob_isA || tob.ty == Tpointer))
2133 {
2134 goto Lok;
2135 }
2136
2137 // arithmetic values vs. references or fat values
2138 if (tob_isA && (t1b_isR || t1b_isFV) || t1b_isA && (tob_isR || tob_isFV))
2139 {
2140 goto Lfail;
2141 }
2142
2143 // Bugzlla 3133: A cast between fat values is possible only when the sizes match.
2144 if (tob_isFV && t1b_isFV)
2145 {
2146 if (hasAliasThis)
2147 {
2148 if (auto result = tryAliasThisCast())
2149 return result;
2150 }
2151
2152 if (t1b.size(e.loc) == tob.size(e.loc))
2153 goto Lok;
2154
2155 auto ts = toAutoQualChars(e.type, t);
2156 error(e.loc, "cannot cast expression `%s` of type `%s` to `%s` because of different sizes",
2157 e.toChars(), ts[0], ts[1]);
2158 return ErrorExp.get();
2159 }
2160
2161 // Fat values vs. null or references
2162 if (tob_isFV && (t1b.ty == Tnull || t1b_isR) || t1b_isFV && (tob.ty == Tnull || tob_isR))
2163 {
2164 if (tob.ty == Tpointer && t1b.ty == Tsarray)
2165 {
2166 // T[n] sa;
2167 // cast(U*)sa; // ==> cast(U*)sa.ptr;
2168 return new AddrExp(e.loc, e, t);
2169 }
2170 if (tob.ty == Tarray && t1b.ty == Tsarray)
2171 {
2172 // T[n] sa;
2173 // cast(U[])sa; // ==> cast(U[])sa[];
2174 const fsize = t1b.nextOf().size();
2175 const tsize = tob.nextOf().size();
2176 if (fsize == SIZE_INVALID || tsize == SIZE_INVALID)
2177 {
2178 return ErrorExp.get();
2179 }
2180 if (fsize != tsize)
2181 {
2182 const dim = t1b.isTypeSArray().dim.toInteger();
2183 if (tsize == 0 || (dim * fsize) % tsize != 0)
2184 {
2185 error(e.loc, "cannot cast expression `%s` of type `%s` to `%s` since sizes don't line up",
2186 e.toChars(), e.type.toChars(), t.toChars());
2187 return ErrorExp.get();
2188 }
2189 }
2190 goto Lok;
2191 }
2192 goto Lfail;
2193 }
2194
2195 /* For references, any reinterpret casts are allowed to same 'ty' type.
2196 * T* to U*
2197 * R1 function(P1) to R2 function(P2)
2198 * R1 delegate(P1) to R2 delegate(P2)
2199 * T[] to U[]
2200 * V1[K1] to V2[K2]
2201 * class/interface A to B (will be a dynamic cast if possible)
2202 */
2203 if (tob.ty == t1b.ty && tob_isR && t1b_isR)
2204 goto Lok;
2205
2206 // typeof(null) <-- non-null references or values
2207 if (tob.ty == Tnull && t1b.ty != Tnull)
2208 goto Lfail; // https://issues.dlang.org/show_bug.cgi?id=14629
2209 // typeof(null) --> non-null references or arithmetic values
2210 if (t1b.ty == Tnull && tob.ty != Tnull)
2211 goto Lok;
2212
2213 // Check size mismatch of references.
2214 // Tarray and Tdelegate are (void*).sizeof*2, but others have (void*).sizeof.
2215 if (tob_isFR && t1b_isR || t1b_isFR && tob_isR)
2216 {
2217 if (tob.ty == Tpointer && t1b.ty == Tarray)
2218 {
2219 // T[] da;
2220 // cast(U*)da; // ==> cast(U*)da.ptr;
2221 goto Lok;
2222 }
2223 if (tob.ty == Tpointer && t1b.ty == Tdelegate)
2224 {
2225 // void delegate() dg;
2226 // cast(U*)dg; // ==> cast(U*)dg.ptr;
2227 // Note that it happens even when U is a Tfunction!
2228 deprecation(e.loc, "casting from %s to %s is deprecated", e.type.toChars(), t.toChars());
2229 goto Lok;
2230 }
2231 goto Lfail;
2232 }
2233
2234 if (t1b.ty == Tvoid && tob.ty != Tvoid)
2235 {
2236 Lfail:
2237 /* if the cast cannot be performed, maybe there is an alias
2238 * this that can be used for casting.
2239 */
2240 if (hasAliasThis)
2241 {
2242 if (auto result = tryAliasThisCast())
2243 return result;
2244 }
2245 error(e.loc, "cannot cast expression `%s` of type `%s` to `%s`", e.toChars(), e.type.toChars(), t.toChars());
2246 return ErrorExp.get();
2247 }
2248
2249 Lok:
2250 auto result = new CastExp(e.loc, e, t);
2251 result.type = t; // Don't call semantic()
2252 //printf("Returning: %s\n", result.toChars());
2253 return result;
2254 }
2255
2256 Expression visitError(ErrorExp e)
2257 {
2258 return e;
2259 }
2260
2261 Expression visitReal(RealExp e)
2262 {
2263 if (!e.type.equals(t))
2264 {
2265 if ((e.type.isReal() && t.isReal()) || (e.type.isImaginary() && t.isImaginary()))
2266 {
2267 auto result = e.copy();
2268 result.type = t;
2269 return result;
2270 }
2271 else
2272 return visit(e);
2273 }
2274 return e;
2275 }
2276
2277 Expression visitComplex(ComplexExp e)
2278 {
2279 if (!e.type.equals(t))
2280 {
2281 if (e.type.isComplex() && t.isComplex())
2282 {
2283 auto result = e.copy();
2284 result.type = t;
2285 return result;
2286 }
2287 else
2288 return visit(e);
2289 }
2290 return e;
2291 }
2292
2293 Expression visitStructLiteral(StructLiteralExp e)
2294 {
2295 auto result = visit(e);
2296 if (auto sle = result.isStructLiteralExp())
2297 sle.stype = t; // commit type
2298 return result;
2299 }
2300
2301 Expression visitString(StringExp e)
2302 {
2303 /* This follows copy-on-write; any changes to 'this'
2304 * will result in a copy.
2305 * The this.string member is considered immutable.
2306 */
2307 int copied = 0;
2308
2309 //printf("StringExp::castTo(t = %s), '%s' committed = %d\n", t.toChars(), e.toChars(), e.committed);
2310
2311 if (!e.committed && t.ty == Tpointer && t.nextOf().ty == Tvoid &&
2312 (!sc || !sc.inCfile))
2313 {
2314 error(e.loc, "cannot convert string literal to `void*`");
2315 return ErrorExp.get();
2316 }
2317
2318 StringExp se = e;
2319
2320 Expression lcast()
2321 {
2322 auto result = new CastExp(e.loc, se, t);
2323 result.type = t; // so semantic() won't be run on e
2324 return result;
2325 }
2326
2327 if (!e.committed)
2328 {
2329 se = e.copy().isStringExp();
2330 se.committed = true;
2331 copied = 1;
2332 }
2333
2334 if (e.type.equals(t))
2335 {
2336 return se;
2337 }
2338
2339 Type tb = t.toBasetype();
2340 Type typeb = e.type.toBasetype();
2341
2342 if (e.hexString && !e.committed && tb.nextOf().isIntegral)
2343 {
2344 const szx = cast(ubyte) tb.nextOf().size();
2345 if (szx != se.sz && (e.len % szx) == 0)
2346 {
2347 import dmd.utils: arrayCastBigEndian;
2348 const data = e.peekData();
2349 se.setData(arrayCastBigEndian(data, szx).ptr, data.length / szx, szx);
2350 se.type = t;
2351 return se;
2352 }
2353 }
2354
2355 //printf("\ttype = %s\n", e.type.toChars());
2356 if (tb.ty == Tdelegate && typeb.ty != Tdelegate)
2357 {
2358 return visit(e);
2359 }
2360
2361 if (typeb.equals(tb))
2362 {
2363 if (!copied)
2364 {
2365 se = e.copy().isStringExp();
2366 copied = 1;
2367 }
2368 se.type = t;
2369 return se;
2370 }
2371
2372 /* Handle reinterpret casts:
2373 * cast(wchar[3])"abcd"c --> [\u6261, \u6463, \u0000]
2374 * cast(wchar[2])"abcd"c --> [\u6261, \u6463]
2375 * cast(wchar[1])"abcd"c --> [\u6261]
2376 * cast(char[4])"a" --> ['a', 0, 0, 0]
2377 */
2378 if (e.committed && tb.ty == Tsarray && typeb.ty == Tarray)
2379 {
2380 se = e.copy().isStringExp();
2381 uinteger_t szx = tb.nextOf().size();
2382 assert(szx <= 255);
2383 se.sz = cast(ubyte)szx;
2384 se.len = cast(size_t)tb.isTypeSArray().dim.toInteger();
2385 se.committed = true;
2386 se.type = t;
2387
2388 /* If larger than source, pad with zeros.
2389 */
2390 const fullSize = (se.len + 1) * se.sz; // incl. terminating 0
2391 if (fullSize > (e.len + 1) * e.sz)
2392 {
2393 void* s = mem.xmalloc(fullSize);
2394 const srcSize = e.len * e.sz;
2395 const data = se.peekData();
2396 memcpy(s, data.ptr, srcSize);
2397 memset(s + srcSize, 0, fullSize - srcSize);
2398 se.setData(s, se.len, se.sz);
2399 }
2400 return se;
2401 }
2402
2403 if (tb.ty != Tsarray && tb.ty != Tarray && tb.ty != Tpointer)
2404 {
2405 if (!copied)
2406 {
2407 se = e.copy().isStringExp();
2408 copied = 1;
2409 }
2410 return lcast();
2411 }
2412 if (typeb.ty != Tsarray && typeb.ty != Tarray && typeb.ty != Tpointer)
2413 {
2414 if (!copied)
2415 {
2416 se = e.copy().isStringExp();
2417 copied = 1;
2418 }
2419 return lcast();
2420 }
2421
2422 const nextSz = typeb.nextOf().size();
2423 if (nextSz == SIZE_INVALID)
2424 {
2425 return ErrorExp.get();
2426 }
2427 if (nextSz == tb.nextOf().size())
2428 {
2429 if (!copied)
2430 {
2431 se = e.copy().isStringExp();
2432 copied = 1;
2433 }
2434 if (tb.ty == Tsarray)
2435 goto L2; // handle possible change in static array dimension
2436 se.type = t;
2437 return se;
2438 }
2439
2440 if (e.committed)
2441 goto Lcast;
2442
2443 static auto X(T, U)(T tf, U tt)
2444 {
2445 return cast(int)tf * 256 + cast(int)tt;
2446 }
2447
2448 {
2449 OutBuffer buffer;
2450 size_t newlen = 0;
2451 int tfty = typeb.nextOf().toBasetype().ty;
2452 int ttty = tb.nextOf().toBasetype().ty;
2453 switch (X(tfty, ttty))
2454 {
2455 case X(Tchar, Tchar):
2456 case X(Twchar, Twchar):
2457 case X(Tdchar, Tdchar):
2458 break;
2459
2460 case X(Tchar, Twchar):
2461 for (size_t u = 0; u < e.len;)
2462 {
2463 dchar c;
2464 if (const s = utf_decodeChar(se.peekString(), u, c))
2465 error(e.loc, "%.*s", cast(int)s.length, s.ptr);
2466 else
2467 buffer.writeUTF16(c);
2468 }
2469 newlen = buffer.length / 2;
2470 buffer.writeUTF16(0);
2471 goto L1;
2472
2473 case X(Tchar, Tdchar):
2474 for (size_t u = 0; u < e.len;)
2475 {
2476 dchar c;
2477 if (const s = utf_decodeChar(se.peekString(), u, c))
2478 error(e.loc, "%.*s", cast(int)s.length, s.ptr);
2479 buffer.write4(c);
2480 newlen++;
2481 }
2482 buffer.write4(0);
2483 goto L1;
2484
2485 case X(Twchar, Tchar):
2486 for (size_t u = 0; u < e.len;)
2487 {
2488 dchar c;
2489 if (const s = utf_decodeWchar(se.peekWstring(), u, c))
2490 error(e.loc, "%.*s", cast(int)s.length, s.ptr);
2491 else
2492 buffer.writeUTF8(c);
2493 }
2494 newlen = buffer.length;
2495 buffer.writeUTF8(0);
2496 goto L1;
2497
2498 case X(Twchar, Tdchar):
2499 for (size_t u = 0; u < e.len;)
2500 {
2501 dchar c;
2502 if (const s = utf_decodeWchar(se.peekWstring(), u, c))
2503 error(e.loc, "%.*s", cast(int)s.length, s.ptr);
2504 buffer.write4(c);
2505 newlen++;
2506 }
2507 buffer.write4(0);
2508 goto L1;
2509
2510 case X(Tdchar, Tchar):
2511 for (size_t u = 0; u < e.len; u++)
2512 {
2513 uint c = se.peekDstring()[u];
2514 if (!utf_isValidDchar(c))
2515 error(e.loc, "invalid UCS-32 char \\U%08x", c);
2516 else
2517 buffer.writeUTF8(c);
2518 newlen++;
2519 }
2520 newlen = buffer.length;
2521 buffer.writeUTF8(0);
2522 goto L1;
2523
2524 case X(Tdchar, Twchar):
2525 for (size_t u = 0; u < e.len; u++)
2526 {
2527 uint c = se.peekDstring()[u];
2528 if (!utf_isValidDchar(c))
2529 error(e.loc, "invalid UCS-32 char \\U%08x", c);
2530 else
2531 buffer.writeUTF16(c);
2532 newlen++;
2533 }
2534 newlen = buffer.length / 2;
2535 buffer.writeUTF16(0);
2536 goto L1;
2537
2538 L1:
2539 if (!copied)
2540 {
2541 se = e.copy().isStringExp();
2542 copied = 1;
2543 }
2544
2545 {
2546 uinteger_t szx = tb.nextOf().size();
2547 assert(szx <= 255);
2548 se.setData(buffer.extractSlice().ptr, newlen, cast(ubyte)szx);
2549 }
2550 break;
2551
2552 default:
2553 assert(typeb.nextOf().size() != tb.nextOf().size());
2554 goto Lcast;
2555 }
2556 }
2557 L2:
2558 assert(copied);
2559
2560 // See if need to truncate or extend the literal
2561 if (auto tsa = tb.isTypeSArray())
2562 {
2563 const dim2 = cast(size_t)tsa.dim.toInteger();
2564 //printf("dim from = %d, to = %d\n", cast(int)se.len, cast(int)dim2);
2565
2566 // Changing dimensions
2567 if (dim2 != se.len)
2568 {
2569 // Copy when changing the string literal
2570 const newsz = se.sz;
2571 const d = (dim2 < se.len) ? dim2 : se.len;
2572 void* s = mem.xmalloc((dim2 + 1) * newsz);
2573 memcpy(s, se.peekData().ptr, d * newsz);
2574 // Extend with 0, add terminating 0
2575 memset(s + d * newsz, 0, (dim2 + 1 - d) * newsz);
2576 se.setData(s, dim2, newsz);
2577 }
2578 }
2579 se.type = t;
2580 return se;
2581
2582 Lcast:
2583 auto result = new CastExp(e.loc, se, t);
2584 result.type = t; // so semantic() won't be run on e
2585 return result;
2586 }
2587
2588 Expression visitAddr(AddrExp e)
2589 {
2590 version (none)
2591 {
2592 printf("AddrExp::castTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars());
2593 }
2594 Type tb = t.toBasetype();
2595 Type typeb = e.type.toBasetype();
2596
2597 if (tb.equals(typeb))
2598 {
2599 auto result = e.copy();
2600 result.type = t;
2601 return result;
2602 }
2603
2604 // Look for pointers to functions where the functions are overloaded.
2605 if (e.e1.isOverExp() &&
2606 (tb.ty == Tpointer || tb.ty == Tdelegate) && tb.nextOf().ty == Tfunction)
2607 {
2608 OverExp eo = e.e1.isOverExp();
2609 FuncDeclaration f = null;
2610 for (size_t i = 0; i < eo.vars.a.length; i++)
2611 {
2612 auto s = eo.vars.a[i];
2613 auto f2 = s.isFuncDeclaration();
2614 assert(f2);
2615 if (f2.overloadExactMatch(tb.nextOf()))
2616 {
2617 if (f)
2618 {
2619 /* Error if match in more than one overload set,
2620 * even if one is a 'better' match than the other.
2621 */
2622 ScopeDsymbol.multiplyDefined(e.loc, f, f2);
2623 }
2624 else
2625 f = f2;
2626 }
2627 }
2628 if (f)
2629 {
2630 f.tookAddressOf++;
2631 auto se = new SymOffExp(e.loc, f, 0, false);
2632 auto se2 = se.expressionSemantic(sc);
2633 // Let SymOffExp::castTo() do the heavy lifting
2634 return visit(se2);
2635 }
2636 }
2637
2638 if (e.e1.isVarExp() &&
2639 typeb.ty == Tpointer && typeb.nextOf().ty == Tfunction &&
2640 tb.ty == Tpointer && tb.nextOf().ty == Tfunction)
2641 {
2642 auto ve = e.e1.isVarExp();
2643 if (auto f = ve.var.isFuncDeclaration())
2644 {
2645 assert(f.isImportedSymbol());
2646 f = f.overloadExactMatch(tb.nextOf());
2647 if (f)
2648 {
2649 Expression result = new VarExp(e.loc, f, false);
2650 result.type = f.type;
2651 result = new AddrExp(e.loc, result, t);
2652 return result;
2653 }
2654 }
2655 }
2656
2657 if (auto f = isFuncAddress(e))
2658 {
2659 if (checkForwardRef(f, e.loc))
2660 {
2661 return ErrorExp.get();
2662 }
2663 }
2664
2665 return visit(e);
2666 }
2667
2668 Expression visitTuple(TupleExp e)
2669 {
2670 if (e.type.equals(t))
2671 {
2672 return e;
2673 }
2674
2675 /* If target type is a tuple of same length, cast each expression to
2676 * the corresponding type in the tuple.
2677 */
2678 TypeTuple totuple;
2679 if (auto tt = t.isTypeTuple())
2680 totuple = e.exps.length == tt.arguments.length ? tt : null;
2681
2682 TupleExp te = e.copy().isTupleExp();
2683 te.e0 = e.e0 ? e.e0.copy() : null;
2684 te.exps = e.exps.copy();
2685 for (size_t i = 0; i < te.exps.length; i++)
2686 {
2687 Expression ex = (*te.exps)[i];
2688 ex = ex.castTo(sc, totuple ? (*totuple.arguments)[i].type : t);
2689 (*te.exps)[i] = ex;
2690 }
2691 if (totuple)
2692 te.type = totuple;
2693 return te;
2694
2695 /* Questionable behavior: In here, result.type is not set to t
2696 * if target type is not a tuple of same length.
2697 * Therefoe:
2698 * TypeTuple!(int, int) values;
2699 * auto values2 = cast(long)values;
2700 * // typeof(values2) == TypeTuple!(int, int) !!
2701 *
2702 * Only when the casted tuple is immediately expanded, it would work.
2703 * auto arr = [cast(long)values];
2704 * // typeof(arr) == long[]
2705 */
2706 }
2707
2708 Expression visitArrayLiteral(ArrayLiteralExp e)
2709 {
2710 version (none)
2711 {
2712 printf("ArrayLiteralExp::castTo(this=%s, type=%s, => %s)\n", e.toChars(), e.type.toChars(), t.toChars());
2713 }
2714
2715 ArrayLiteralExp ae = e;
2716
2717 Type tb = t.toBasetype();
2718 if (tb.ty == Tarray)
2719 {
2720 if (checkArrayLiteralEscape(*sc, ae, false))
2721 {
2722 return ErrorExp.get();
2723 }
2724 }
2725
2726 if (e.type == t)
2727 {
2728 return e;
2729 }
2730 Type typeb = e.type.toBasetype();
2731
2732 if (tb.isStaticOrDynamicArray() && typeb.isStaticOrDynamicArray())
2733 {
2734 if (tb.nextOf().toBasetype().ty == Tvoid && typeb.nextOf().toBasetype().ty != Tvoid)
2735 {
2736 // Don't do anything to cast non-void[] to void[]
2737 }
2738 else if (typeb.ty == Tsarray && typeb.nextOf().toBasetype().ty == Tvoid)
2739 {
2740 // Don't do anything for casting void[n] to others
2741 }
2742 else
2743 {
2744 if (auto tsa = tb.isTypeSArray())
2745 {
2746 if (e.elements.length != tsa.dim.toInteger())
2747 return visit(ae);
2748 }
2749
2750 ae = e.copy().isArrayLiteralExp();
2751 if (e.basis)
2752 ae.basis = e.basis.castTo(sc, tb.nextOf());
2753 ae.elements = e.elements.copy();
2754 for (size_t i = 0; i < e.elements.length; i++)
2755 {
2756 Expression ex = (*e.elements)[i];
2757 if (!ex)
2758 continue;
2759 ex = ex.castTo(sc, tb.nextOf());
2760 (*ae.elements)[i] = ex;
2761 }
2762 ae.type = t;
2763 return ae;
2764 }
2765 }
2766 else if (tb.ty == Tpointer && typeb.ty == Tsarray)
2767 {
2768 Type tp = typeb.nextOf().pointerTo();
2769 if (!tp.equals(ae.type))
2770 {
2771 ae = e.copy().isArrayLiteralExp();
2772 ae.type = tp;
2773 }
2774 }
2775 else if (tb.ty == Tvector && (typeb.isStaticOrDynamicArray() || typeb.ty == Tpointer))
2776 {
2777 // Convert array literal to vector type
2778 // The Tpointer case comes from C eagerly converting Tsarray to Tpointer
2779 TypeVector tv = tb.isTypeVector();
2780 TypeSArray tbase = tv.basetype.isTypeSArray();
2781 assert(tbase.ty == Tsarray);
2782 const edim = e.elements.length;
2783 const tbasedim = tbase.dim.toInteger();
2784 if (edim > tbasedim)
2785 return visit(ae);
2786
2787 ae = e.copy().isArrayLiteralExp();
2788 ae.type = tbase; // https://issues.dlang.org/show_bug.cgi?id=12642
2789 ae.elements = e.elements.copy();
2790 Type telement = tv.elementType();
2791 foreach (i; 0 .. edim)
2792 {
2793 Expression ex = (*e.elements)[i];
2794 ex = ex.castTo(sc, telement);
2795 (*ae.elements)[i] = ex;
2796 }
2797 // Fill in the rest with the default initializer
2798 ae.elements.setDim(cast(size_t)tbasedim);
2799 foreach (i; edim .. cast(size_t)tbasedim)
2800 {
2801 Expression ex = typeb.nextOf.defaultInitLiteral(e.loc);
2802 ex = ex.castTo(sc, telement);
2803 (*ae.elements)[i] = ex;
2804 }
2805 Expression ev = new VectorExp(e.loc, ae, tb);
2806 ev = ev.expressionSemantic(sc);
2807 return ev;
2808 }
2809 return visit(ae);
2810 }
2811
2812 Expression visitAssocArrayLiteral(AssocArrayLiteralExp e)
2813 {
2814 //printf("AssocArrayLiteralExp::castTo(this=%s, type=%s, => %s)\n", e.toChars(), e.type.toChars(), t.toChars());
2815 if (e.type == t)
2816 {
2817 return e;
2818 }
2819
2820 Type tb = t.toBasetype();
2821 Type typeb = e.type.toBasetype();
2822
2823 if (tb.ty == Taarray && typeb.ty == Taarray &&
2824 tb.nextOf().toBasetype().ty != Tvoid)
2825 {
2826 AssocArrayLiteralExp ae = e.copy().isAssocArrayLiteralExp();
2827 ae.keys = e.keys.copy();
2828 ae.values = e.values.copy();
2829 assert(e.keys.length == e.values.length);
2830 for (size_t i = 0; i < e.keys.length; i++)
2831 {
2832 Expression ex = (*e.values)[i];
2833 ex = ex.castTo(sc, tb.nextOf());
2834 (*ae.values)[i] = ex;
2835
2836 ex = (*e.keys)[i];
2837 ex = ex.castTo(sc, tb.isTypeAArray().index);
2838 (*ae.keys)[i] = ex;
2839 }
2840 ae.type = t;
2841 semanticTypeInfo(sc, ae.type);
2842 return ae;
2843 }
2844 return visit(e);
2845 }
2846
2847 Expression visitSymOff(SymOffExp e)
2848 {
2849 version (none)
2850 {
2851 printf("SymOffExp::castTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars());
2852 }
2853 if (e.type == t && !e.hasOverloads)
2854 {
2855 return e;
2856 }
2857
2858 Type tb = t.toBasetype();
2859 Type typeb = e.type.toBasetype();
2860
2861 if (tb.equals(typeb))
2862 {
2863 auto result = e.copy();
2864 result.type = t;
2865 result.isSymOffExp().hasOverloads = false;
2866 return result;
2867 }
2868
2869 // Look for pointers to functions where the functions are overloaded.
2870 if (e.hasOverloads &&
2871 typeb.ty == Tpointer && typeb.nextOf().ty == Tfunction &&
2872 (tb.ty == Tpointer || tb.ty == Tdelegate) && tb.nextOf().ty == Tfunction)
2873 {
2874 FuncDeclaration f = e.var.isFuncDeclaration();
2875 f = f ? f.overloadExactMatch(tb.nextOf()) : null;
2876 if (f)
2877 {
2878 Expression result;
2879 if (tb.ty == Tdelegate)
2880 {
2881 if (f.needThis() && hasThis(sc))
2882 {
2883 result = new DelegateExp(e.loc, new ThisExp(e.loc), f, false);
2884 result = result.expressionSemantic(sc);
2885 }
2886 else if (f.needThis())
2887 {
2888 error(e.loc, "no `this` to create delegate for `%s`", f.toChars());
2889 return ErrorExp.get();
2890 }
2891 else if (f.isNested())
2892 {
2893 result = new DelegateExp(e.loc, IntegerExp.literal!0, f, false);
2894 result = result.expressionSemantic(sc);
2895 }
2896 else
2897 {
2898 error(e.loc, "cannot cast from function pointer to delegate");
2899 return ErrorExp.get();
2900 }
2901 }
2902 else
2903 {
2904 result = new SymOffExp(e.loc, f, 0, false);
2905 result.type = t;
2906 }
2907 f.tookAddressOf++;
2908 return result;
2909 }
2910 }
2911
2912 if (auto f = isFuncAddress(e))
2913 {
2914 if (checkForwardRef(f, e.loc))
2915 {
2916 return ErrorExp.get();
2917 }
2918 }
2919
2920 return visit(e);
2921 }
2922
2923 Expression visitDelegate(DelegateExp e)
2924 {
2925 version (none)
2926 {
2927 printf("DelegateExp::castTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars());
2928 }
2929 void errorCovariantReturnType()
2930 {
2931 error(e.loc, "cannot form delegate due to covariant return type");
2932 }
2933
2934 Type tb = t.toBasetype();
2935 Type typeb = e.type.toBasetype();
2936
2937 if (tb.equals(typeb) && !e.hasOverloads)
2938 {
2939 int offset;
2940 e.func.tookAddressOf++;
2941 if (e.func.tintro && e.func.tintro.nextOf().isBaseOf(e.func.type.nextOf(), &offset) && offset)
2942 errorCovariantReturnType();
2943 auto result = e.copy();
2944 result.type = t;
2945 return result;
2946 }
2947
2948 // Look for delegates to functions where the functions are overloaded.
2949 if (typeb.ty == Tdelegate && tb.ty == Tdelegate)
2950 {
2951 if (e.func)
2952 {
2953 if (auto f = e.func.overloadExactMatch(tb.nextOf()))
2954 {
2955 int offset;
2956 if (f.tintro && f.tintro.nextOf().isBaseOf(f.type.nextOf(), &offset) && offset)
2957 errorCovariantReturnType();
2958 if (f != e.func) // if address not already marked as taken
2959 f.tookAddressOf++;
2960 auto result = new DelegateExp(e.loc, e.e1, f, false, e.vthis2);
2961 result.type = t;
2962 return result;
2963 }
2964 if (e.func.tintro)
2965 errorCovariantReturnType();
2966 }
2967 }
2968
2969 if (auto f = isFuncAddress(e))
2970 {
2971 if (checkForwardRef(f, e.loc))
2972 {
2973 return ErrorExp.get();
2974 }
2975 }
2976
2977 return visit(e);
2978 }
2979
2980 Expression visitFunc(FuncExp e)
2981 {
2982 //printf("FuncExp::castTo type = %s, t = %s\n", e.type.toChars(), t.toChars());
2983 FuncExp fe;
2984 if (e.matchType(t, sc, &fe, global.errorSinkNull) > MATCH.nomatch)
2985 {
2986 return fe;
2987 }
2988 return visit(e);
2989 }
2990
2991 Expression visitCond(CondExp e)
2992 {
2993 if (!e.type.equals(t))
2994 {
2995 auto result = new CondExp(e.loc, e.econd, e.e1.castTo(sc, t), e.e2.castTo(sc, t));
2996 result.type = t;
2997 return result;
2998 }
2999 return e;
3000 }
3001
3002 Expression visitComma(CommaExp e)
3003 {
3004 Expression e2c = e.e2.castTo(sc, t);
3005
3006 if (e2c != e.e2)
3007 {
3008 auto result = new CommaExp(e.loc, e.e1, e2c);
3009 result.type = e2c.type;
3010 return result;
3011 }
3012 else
3013 {
3014 e.type = e.e2.type;
3015 return e;
3016 }
3017 }
3018
3019 Expression visitSlice(SliceExp e)
3020 {
3021 //printf("SliceExp::castTo e = %s, type = %s, t = %s\n", e.toChars(), e.type.toChars(), t.toChars());
3022
3023 Type tb = t.toBasetype();
3024 Type typeb = e.type.toBasetype();
3025
3026 if (e.type.equals(t) || typeb.ty != Tarray ||
3027 (tb.ty != Tarray && tb.ty != Tsarray))
3028 {
3029 return visit(e);
3030 }
3031
3032 if (tb.ty == Tarray)
3033 {
3034 if (typeb.nextOf().equivalent(tb.nextOf()))
3035 {
3036 // T[] to const(T)[]
3037 auto result = e.copy();
3038 result.type = t;
3039 return result;
3040 }
3041 else
3042 {
3043 return visit(e);
3044 }
3045 }
3046
3047 // Handle the cast from Tarray to Tsarray with CT-known slicing
3048
3049 TypeSArray tsa;
3050 {
3051 Type t = toStaticArrayType(e);
3052 tsa = t ? t.isTypeSArray() : null;
3053 }
3054
3055 if (tsa && tsa.size(e.loc) == tb.size(e.loc))
3056 {
3057 /* Match if the sarray sizes are equal:
3058 * T[a .. b] to const(T)[b-a]
3059 * T[a .. b] to U[dim] if (T.sizeof*(b-a) == U.sizeof*dim)
3060 *
3061 * If a SliceExp has Tsarray, it will become lvalue.
3062 * That's handled in SliceExp::isLvalue and toLvalue
3063 */
3064 auto result = e.copy();
3065 result.type = t;
3066 return result;
3067 }
3068 if (tsa && tsa.dim.equals(tb.isTypeSArray().dim))
3069 {
3070 /* Match if the dimensions are equal
3071 * with the implicit conversion of e.e1:
3072 * cast(float[2]) [2.0, 1.0, 0.0][0..2];
3073 */
3074 Type t1b = e.e1.type.toBasetype();
3075 if (t1b.ty == Tsarray)
3076 t1b = tb.nextOf().sarrayOf(t1b.isTypeSArray().dim.toInteger());
3077 else if (t1b.ty == Tarray)
3078 t1b = tb.nextOf().arrayOf();
3079 else if (t1b.ty == Tpointer)
3080 t1b = tb.nextOf().pointerTo();
3081 else
3082 assert(0);
3083 if (e.e1.implicitConvTo(t1b) > MATCH.nomatch)
3084 {
3085 Expression e1x = e.e1.implicitCastTo(sc, t1b);
3086 assert(e1x.op != EXP.error);
3087 e = e.copy().isSliceExp();
3088 e.e1 = e1x;
3089 e.type = t;
3090 return e;
3091 }
3092 }
3093 auto ts = toAutoQualChars(tsa ? tsa : e.type, t);
3094 error(e.loc, "cannot cast expression `%s` of type `%s` to `%s`",
3095 e.toChars(), ts[0], ts[1]);
3096 return ErrorExp.get();
3097 }
3098
3099 // Casting to noreturn isn't an actual cast
3100 // Rewrite cast(<qual> noreturn) <exp>
3101 // as <exp>, assert(false)
3102 if (t.isTypeNoreturn())
3103 {
3104 // Don't generate an unreachable assert(false) if e will abort
3105 if (e.type.isTypeNoreturn())
3106 {
3107 // Paint e to accomodate for different type qualifiers
3108 e.type = t;
3109 return e;
3110 }
3111
3112 auto ini = t.defaultInitLiteral(e.loc);
3113 return Expression.combine(e, ini);
3114 }
3115
3116 switch (e.op)
3117 {
3118 default : return visit(e);
3119 case EXP.error : return visitError(e.isErrorExp());
3120 case EXP.float64 : return visitReal(e.isRealExp());
3121 case EXP.complex80 : return visitComplex(e.isComplexExp());
3122 case EXP.structLiteral : return visitStructLiteral(e.isStructLiteralExp());
3123 case EXP.string_ : return visitString(e.isStringExp());
3124 case EXP.address : return visitAddr(e.isAddrExp());
3125 case EXP.tuple : return visitTuple(e.isTupleExp());
3126 case EXP.arrayLiteral : return visitArrayLiteral(e.isArrayLiteralExp());
3127 case EXP.assocArrayLiteral: return visitAssocArrayLiteral(e.isAssocArrayLiteralExp());
3128 case EXP.symbolOffset : return visitSymOff(e.isSymOffExp());
3129 case EXP.delegate_ : return visitDelegate(e.isDelegateExp());
3130 case EXP.function_ : return visitFunc(e.isFuncExp());
3131 case EXP.question : return visitCond(e.isCondExp());
3132 case EXP.comma : return visitComma(e.isCommaExp());
3133 case EXP.slice : return visitSlice(e.isSliceExp());
3134 }
3135 }
3136
3137 /****************************************
3138 * Set type inference target
3139 * t Target type
3140 * flag 1: don't put an error when inference fails
3141 */
3142 Expression inferType(Expression e, Type t, int flag = 0)
3143 {
3144 Expression visitAle(ArrayLiteralExp ale)
3145 {
3146 Type tb = t.toBasetype();
3147 if (tb.isStaticOrDynamicArray())
3148 {
3149 Type tn = tb.nextOf();
3150 if (ale.basis)
3151 ale.basis = inferType(ale.basis, tn, flag);
3152 for (size_t i = 0; i < ale.elements.length; i++)
3153 {
3154 if (Expression e = (*ale.elements)[i])
3155 {
3156 e = inferType(e, tn, flag);
3157 (*ale.elements)[i] = e;
3158 }
3159 }
3160 }
3161 return ale;
3162 }
3163
3164 Expression visitAar(AssocArrayLiteralExp aale)
3165 {
3166 Type tb = t.toBasetype();
3167 if (auto taa = tb.isTypeAArray())
3168 {
3169 Type ti = taa.index;
3170 Type tv = taa.nextOf();
3171 for (size_t i = 0; i < aale.keys.length; i++)
3172 {
3173 if (Expression e = (*aale.keys)[i])
3174 {
3175 e = inferType(e, ti, flag);
3176 (*aale.keys)[i] = e;
3177 }
3178 }
3179 for (size_t i = 0; i < aale.values.length; i++)
3180 {
3181 if (Expression e = (*aale.values)[i])
3182 {
3183 e = inferType(e, tv, flag);
3184 (*aale.values)[i] = e;
3185 }
3186 }
3187 }
3188 return aale;
3189 }
3190
3191 Expression visitFun(FuncExp fe)
3192 {
3193 //printf("FuncExp::inferType('%s'), to=%s\n", fe.type ? fe.type.toChars() : "null", t.toChars());
3194 if (t.ty == Tdelegate || t.ty == Tpointer && t.nextOf().ty == Tfunction)
3195 {
3196 fe.fd.treq = t;
3197 }
3198 return fe;
3199 }
3200
3201 Expression visitTer(CondExp ce)
3202 {
3203 Type tb = t.toBasetype();
3204 ce.e1 = inferType(ce.e1, tb, flag);
3205 ce.e2 = inferType(ce.e2, tb, flag);
3206 return ce;
3207 }
3208
3209 if (t) switch (e.op)
3210 {
3211 case EXP.arrayLiteral: return visitAle(e.isArrayLiteralExp());
3212 case EXP.assocArrayLiteral: return visitAar(e.isAssocArrayLiteralExp());
3213 case EXP.function_: return visitFun(e.isFuncExp());
3214 case EXP.question: return visitTer(e.isCondExp());
3215 default:
3216 }
3217 return e;
3218 }
3219
3220 /****************************************
3221 * Scale addition/subtraction to/from pointer.
3222 */
3223 Expression scaleFactor(BinExp be, Scope* sc)
3224 {
3225 Type t1b = be.e1.type.toBasetype();
3226 Type t2b = be.e2.type.toBasetype();
3227 Expression eoff;
3228
3229 if (t1b.ty == Tpointer && t2b.isIntegral())
3230 {
3231 // Need to adjust operator by the stride
3232 // Replace (ptr + int) with (ptr + (int * stride))
3233 Type t = Type.tptrdiff_t;
3234
3235 uinteger_t stride = t1b.nextOf().size(be.loc);
3236 if (!t.equals(t2b))
3237 be.e2 = be.e2.castTo(sc, t);
3238 eoff = be.e2;
3239 be.e2 = new MulExp(be.loc, be.e2, new IntegerExp(Loc.initial, stride, t));
3240 be.e2.type = t;
3241 be.type = be.e1.type;
3242 }
3243 else if (t2b.ty == Tpointer && t1b.isIntegral())
3244 {
3245 // Need to adjust operator by the stride
3246 // Replace (int + ptr) with (ptr + (int * stride))
3247 Type t = Type.tptrdiff_t;
3248 Expression e;
3249
3250 uinteger_t stride = t2b.nextOf().size(be.loc);
3251 if (!t.equals(t1b))
3252 e = be.e1.castTo(sc, t);
3253 else
3254 e = be.e1;
3255 eoff = e;
3256 e = new MulExp(be.loc, e, new IntegerExp(Loc.initial, stride, t));
3257 e.type = t;
3258 be.type = be.e2.type;
3259 be.e1 = be.e2;
3260 be.e2 = e;
3261 }
3262 else
3263 assert(0);
3264
3265
3266 eoff = eoff.optimize(WANTvalue);
3267 if (eoff.op == EXP.int64 && eoff.toInteger() == 0)
3268 {
3269 }
3270 else if (sc.setUnsafe(false, be.loc, "pointer arithmetic"))
3271 {
3272 return ErrorExp.get();
3273 }
3274
3275 return be;
3276 }
3277
3278 /**************************************
3279 * Return true if e is an empty array literal with dimensionality
3280 * equal to or less than type of other array.
3281 * [], [[]], [[[]]], etc.
3282 * I.e., make sure that [1,2] is compatible with [],
3283 * [[1,2]] is compatible with [[]], etc.
3284 */
3285 private bool isVoidArrayLiteral(Expression e, Type other)
3286 {
3287 while (e.op == EXP.arrayLiteral && e.type.ty == Tarray && (e.isArrayLiteralExp().elements.length == 1))
3288 {
3289 auto ale = e.isArrayLiteralExp();
3290 e = ale[0];
3291 if (other.isStaticOrDynamicArray())
3292 other = other.nextOf();
3293 else
3294 return false;
3295 }
3296 if (other.ty != Tsarray && other.ty != Tarray)
3297 return false;
3298 Type t = e.type;
3299 return (e.op == EXP.arrayLiteral && t.ty == Tarray && t.nextOf().ty == Tvoid && e.isArrayLiteralExp().elements.length == 0);
3300 }
3301
3302 /**
3303 * Merge types of `e1` and `e2` into a common subset
3304 *
3305 * Parameters `e1` and `e2` will be rewritten in place as needed.
3306 *
3307 * Params:
3308 * sc = Current scope
3309 * op = Operator such as `e1 op e2`. In practice, either EXP.question
3310 * or one of the binary operator.
3311 * pe1 = The LHS of the operation, will be rewritten
3312 * pe2 = The RHS of the operation, will be rewritten
3313 *
3314 * Returns:
3315 * The resulting type in case of success, `null` in case of error
3316 */
3317 Type typeMerge(Scope* sc, EXP op, ref Expression pe1, ref Expression pe2)
3318 {
3319 //printf("typeMerge() %s op %s\n", pe1.toChars(), pe2.toChars());
3320
3321 Expression e1 = pe1;
3322 Expression e2 = pe2;
3323
3324 // ImportC: do array/function conversions
3325 if (sc)
3326 {
3327 e1 = e1.arrayFuncConv(sc);
3328 e2 = e2.arrayFuncConv(sc);
3329 }
3330
3331 Type Lret(Type result)
3332 {
3333 pe1 = e1;
3334 pe2 = e2;
3335
3336 version (none)
3337 {
3338 printf("-typeMerge() %s op %s\n", e1.toChars(), e2.toChars());
3339 if (e1.type)
3340 printf("\tt1 = %s\n", e1.type.toChars());
3341 if (e2.type)
3342 printf("\tt2 = %s\n", e2.type.toChars());
3343 printf("\ttype = %s\n", result.toChars());
3344 }
3345 return result;
3346 }
3347
3348 /// Converts one of the expression to the other
3349 Type convert(ref Expression from, Type to)
3350 {
3351 from = from.castTo(sc, to);
3352 return Lret(to);
3353 }
3354
3355 /// Converts both expression to a third type
3356 Type coerce(Type towards)
3357 {
3358 e1 = e1.castTo(sc, towards);
3359 e2 = e2.castTo(sc, towards);
3360 return Lret(towards);
3361 }
3362
3363 Type t1b = e1.type.toBasetype();
3364 Type t2b = e2.type.toBasetype();
3365
3366 if (sc && sc.inCfile)
3367 {
3368 // Integral types can be implicitly converted to pointers
3369 if ((t1b.ty == Tpointer) != (t2b.ty == Tpointer))
3370 {
3371 if (t1b.isIntegral())
3372 {
3373 return convert(e1, t2b);
3374 }
3375 else if (t2b.isIntegral())
3376 {
3377 return convert(e2, t1b);
3378 }
3379 }
3380 }
3381
3382 if (op != EXP.question || t1b.ty != t2b.ty && (t1b.isTypeBasic() && t2b.isTypeBasic()))
3383 {
3384 if (op == EXP.question && t1b.ty.isSomeChar() && t2b.ty.isSomeChar())
3385 {
3386 e1 = e1.castTo(sc, Type.tdchar);
3387 e2 = e2.castTo(sc, Type.tdchar);
3388 }
3389 else
3390 {
3391 e1 = integralPromotions(e1, sc);
3392 e2 = integralPromotions(e2, sc);
3393 }
3394 }
3395
3396 MATCH m;
3397 Type t1 = e1.type;
3398 Type t2 = e2.type;
3399 assert(t1);
3400 Type t = t1;
3401
3402 /* The start type of alias this type recursion.
3403 * In following case, we should save A, and stop recursion
3404 * if it appears again.
3405 * X -> Y -> [A] -> B -> A -> B -> ...
3406 */
3407 Type att1 = null;
3408 Type att2 = null;
3409
3410 if (t1.mod != t2.mod &&
3411 t1.ty == Tenum && t2.ty == Tenum &&
3412 t1.isTypeEnum().sym == t2.isTypeEnum().sym)
3413 {
3414 ubyte mod = MODmerge(t1.mod, t2.mod);
3415 t1 = t1.castMod(mod);
3416 t2 = t2.castMod(mod);
3417 return Lret(t1);
3418 }
3419
3420 Lagain:
3421 t1b = t1.toBasetype();
3422 t2b = t2.toBasetype();
3423
3424 const ty = implicitConvCommonTy(t1b.ty, t2b.ty);
3425 if (ty != Terror)
3426 {
3427 const ty1 = implicitConvTy1(t1b.ty, t2b.ty);
3428 const ty2 = implicitConvTy1(t2b.ty, t1b.ty);
3429
3430 if (t1b.ty == ty1) // if no promotions
3431 {
3432 if (t1.equals(t2))
3433 return Lret(t1);
3434
3435 if (t1b.equals(t2b))
3436 return Lret(t1b);
3437 }
3438
3439 t1 = Type.basic[ty1];
3440 t2 = Type.basic[ty2];
3441
3442 if (!(t1 && t2))
3443 return null;
3444 e1 = e1.castTo(sc, t1);
3445 e2 = e2.castTo(sc, t2);
3446 return Lret(Type.basic[ty]);
3447 }
3448
3449 t1 = t1b;
3450 t2 = t2b;
3451
3452 if (t1.ty == Ttuple || t2.ty == Ttuple)
3453 return null;
3454
3455 if (t1.equals(t2))
3456 {
3457 // merging can not result in new enum type
3458 if (t.ty == Tenum)
3459 return Lret(t1b);
3460 return Lret(t);
3461 }
3462
3463 if ((t1.ty == Tpointer && t2.ty == Tpointer) || (t1.ty == Tdelegate && t2.ty == Tdelegate))
3464 {
3465 // Bring pointers to compatible type
3466 Type t1n = t1.nextOf();
3467 Type t2n = t2.nextOf();
3468
3469 if (t1n.equals(t2n))
3470 return Lret(t);
3471
3472 if (t1n.ty == Tvoid) // pointers to void are always compatible
3473 return Lret(t1);
3474
3475 if (t2n.ty == Tvoid)
3476 return Lret(t2);
3477
3478 if (t1.implicitConvTo(t2))
3479 return convert(e1, t2);
3480
3481 if (t2.implicitConvTo(t1))
3482 return convert(e2, t1);
3483
3484 if (t1n.ty == Tfunction && t2n.ty == Tfunction)
3485 {
3486 TypeFunction tf1 = t1n.isTypeFunction();
3487 TypeFunction tf2 = t2n.isTypeFunction();
3488 tf1.purityLevel();
3489 tf2.purityLevel();
3490
3491 TypeFunction d = tf1.syntaxCopy();
3492
3493 if (tf1.purity != tf2.purity)
3494 d.purity = PURE.impure;
3495 assert(d.purity != PURE.fwdref);
3496
3497 d.isNothrow = (tf1.isNothrow && tf2.isNothrow);
3498 d.isNogc = (tf1.isNogc && tf2.isNogc);
3499
3500 if (tf1.trust == tf2.trust)
3501 d.trust = tf1.trust;
3502 else if (tf1.trust <= TRUST.system || tf2.trust <= TRUST.system)
3503 d.trust = TRUST.system;
3504 else
3505 d.trust = TRUST.trusted;
3506
3507 Type tx = (t1.ty == Tdelegate) ? new TypeDelegate(d) : d.pointerTo();
3508 tx = tx.typeSemantic(e1.loc, sc);
3509
3510 if (t1.implicitConvTo(tx) && t2.implicitConvTo(tx))
3511 return coerce(tx);
3512 return null;
3513 }
3514
3515 if (t1n.mod != t2n.mod)
3516 {
3517 if (!t1n.isImmutable() && !t2n.isImmutable() && t1n.isShared() != t2n.isShared())
3518 return null;
3519 ubyte mod = MODmerge(t1n.mod, t2n.mod);
3520 t1 = t1n.castMod(mod).pointerTo();
3521 t2 = t2n.castMod(mod).pointerTo();
3522 t = t1;
3523 goto Lagain;
3524 }
3525
3526 if (t1n.ty == Tclass && t2n.ty == Tclass)
3527 {
3528 ClassDeclaration cd1 = t1n.isClassHandle();
3529 ClassDeclaration cd2 = t2n.isClassHandle();
3530 int offset;
3531 if (cd1.isBaseOf(cd2, &offset))
3532 {
3533 if (offset)
3534 e2 = e2.castTo(sc, t);
3535 return Lret(t);
3536 }
3537
3538 if (cd2.isBaseOf(cd1, &offset))
3539 {
3540 if (offset)
3541 e1 = e1.castTo(sc, t2);
3542 return Lret(t2);
3543 }
3544
3545 return null;
3546 }
3547
3548 t1 = t1n.constOf().pointerTo();
3549 t2 = t2n.constOf().pointerTo();
3550 if (t1.implicitConvTo(t2))
3551 return convert(e1, t2);
3552 if (t2.implicitConvTo(t1))
3553 return convert(e2, t1);
3554 return null;
3555 }
3556
3557 if (t1.isStaticOrDynamicArray() && (e2.op == EXP.null_ && t2.ty == Tpointer && t2.nextOf().ty == Tvoid || e2.op == EXP.arrayLiteral && t2.ty == Tsarray && t2.nextOf().ty == Tvoid && t2.isTypeSArray().dim.toInteger() == 0 || isVoidArrayLiteral(e2, t1)))
3558 {
3559 /* (T[n] op void*) => T[]
3560 * (T[] op void*) => T[]
3561 * (T[n] op void[0]) => T[]
3562 * (T[] op void[0]) => T[]
3563 * (T[n] op void[]) => T[]
3564 * (T[] op void[]) => T[]
3565 */
3566 return coerce(t1.nextOf().arrayOf());
3567 }
3568
3569 if (t2.isStaticOrDynamicArray() &&
3570 (e1.op == EXP.null_ && t1.ty == Tpointer && t1.nextOf().ty == Tvoid || e1.op == EXP.arrayLiteral
3571 && t1.ty == Tsarray && t1.nextOf().ty == Tvoid && t1.isTypeSArray().dim.toInteger() == 0 || isVoidArrayLiteral(e1, t2)))
3572 {
3573 /* (void* op T[n]) => T[]
3574 * (void* op T[]) => T[]
3575 * (void[0] op T[n]) => T[]
3576 * (void[0] op T[]) => T[]
3577 * (void[] op T[n]) => T[]
3578 * (void[] op T[]) => T[]
3579 */
3580 return coerce(t2.nextOf().arrayOf());
3581 }
3582
3583 if (t1.isStaticOrDynamicArray() && (m = t1.implicitConvTo(t2)) != MATCH.nomatch)
3584 {
3585 // https://issues.dlang.org/show_bug.cgi?id=7285
3586 // Tsarray op [x, y, ...] should to be Tsarray
3587 // https://issues.dlang.org/show_bug.cgi?id=14737
3588 // Tsarray ~ [x, y, ...] should to be Tarray
3589 if (t1.ty == Tsarray && e2.op == EXP.arrayLiteral && op != EXP.concatenate)
3590 return convert(e2, t1);
3591 if (m == MATCH.constant && (op == EXP.addAssign || op == EXP.minAssign || op == EXP.mulAssign || op == EXP.divAssign || op == EXP.modAssign || op == EXP.powAssign || op == EXP.andAssign || op == EXP.orAssign || op == EXP.xorAssign))
3592 {
3593 // Don't make the lvalue const
3594 return Lret(t2);
3595 }
3596 return convert(e1, t2);
3597 }
3598
3599 if (t2.isStaticOrDynamicArray() && t2.implicitConvTo(t1))
3600 {
3601 // https://issues.dlang.org/show_bug.cgi?id=7285
3602 // https://issues.dlang.org/show_bug.cgi?id=14737
3603 if (t2.ty == Tsarray && e1.op == EXP.arrayLiteral && op != EXP.concatenate)
3604 return convert(e1, t2);
3605 return convert(e2, t1);
3606 }
3607
3608 if ((t1.isStaticOrDynamicArray() || t1.ty == Tpointer) && (t2.isStaticOrDynamicArray() || t2.ty == Tpointer)
3609 && t1.nextOf().mod != t2.nextOf().mod)
3610 {
3611 /* If one is mutable and the other immutable, then retry
3612 * with both of them as const
3613 */
3614 Type t1n = t1.nextOf();
3615 Type t2n = t2.nextOf();
3616 ubyte mod;
3617 if (e1.op == EXP.null_ && e2.op != EXP.null_)
3618 mod = t2n.mod;
3619 else if (e1.op != EXP.null_ && e2.op == EXP.null_)
3620 mod = t1n.mod;
3621 else if (!t1n.isImmutable() && !t2n.isImmutable() && t1n.isShared() != t2n.isShared())
3622 return null;
3623 else
3624 mod = MODmerge(t1n.mod, t2n.mod);
3625
3626 if (t1.ty == Tpointer)
3627 t1 = t1n.castMod(mod).pointerTo();
3628 else
3629 t1 = t1n.castMod(mod).arrayOf();
3630
3631 if (t2.ty == Tpointer)
3632 t2 = t2n.castMod(mod).pointerTo();
3633 else
3634 t2 = t2n.castMod(mod).arrayOf();
3635 t = t1;
3636 goto Lagain;
3637 }
3638
3639 LmergeClassTypes:
3640 /* Merge different type modifiers on classes
3641 */
3642 if (t1.ty == Tclass && t2.ty == Tclass)
3643 {
3644 if (t1.mod != t2.mod)
3645 {
3646 ubyte mod;
3647 if (e1.op == EXP.null_ && e2.op != EXP.null_)
3648 mod = t2.mod;
3649 else if (e1.op != EXP.null_ && e2.op == EXP.null_)
3650 mod = t1.mod;
3651 else if (!t1.isImmutable() && !t2.isImmutable() && t1.isShared() != t2.isShared())
3652 return null;
3653 else
3654 mod = MODmerge(t1.mod, t2.mod);
3655 t1 = t1.castMod(mod);
3656 t2 = t2.castMod(mod);
3657 t = t1;
3658 goto Lagain;
3659 }
3660 goto Lcc;
3661 }
3662
3663 if (t1.ty == Tclass || t2.ty == Tclass)
3664 {
3665 Lcc:
3666 while (1)
3667 {
3668 MATCH i1woat = MATCH.exact;
3669 MATCH i2woat = MATCH.exact;
3670
3671 if (auto t2c = t2.isTypeClass())
3672 i1woat = t2c.implicitConvToWithoutAliasThis(t1);
3673 if (auto t1c = t1.isTypeClass())
3674 i2woat = t1c.implicitConvToWithoutAliasThis(t2);
3675
3676 MATCH i1 = e2.implicitConvTo(t1);
3677 MATCH i2 = e1.implicitConvTo(t2);
3678
3679 if (i1 && i2)
3680 {
3681 // We have the case of class vs. void*, so pick class
3682 if (t1.ty == Tpointer)
3683 i1 = MATCH.nomatch;
3684 else if (t2.ty == Tpointer)
3685 i2 = MATCH.nomatch;
3686 }
3687
3688 // Match but without 'alias this' on classes
3689 if (i2 && i2woat)
3690 return coerce(t2);
3691 if (i1 && i1woat)
3692 return coerce(t1);
3693
3694 // Here use implicitCastTo() instead of castTo() to try 'alias this' on classes
3695 Type coerceImplicit(Type towards)
3696 {
3697 e1 = e1.implicitCastTo(sc, towards);
3698 e2 = e2.implicitCastTo(sc, towards);
3699 return Lret(towards);
3700 }
3701
3702 // Implicit conversion with 'alias this'
3703 if (i2)
3704 return coerceImplicit(t2);
3705 if (i1)
3706 return coerceImplicit(t1);
3707
3708 if (t1.ty == Tclass && t2.ty == Tclass)
3709 {
3710 /* t1 cannot be converted to t2, and vice versa
3711 */
3712 TypeClass tc1 = t1.isTypeClass();
3713 TypeClass tc2 = t2.isTypeClass();
3714
3715 //if (tc1.sym.interfaces.length || tc2.sym.interfaces.length)
3716 if (tc1.sym.isInterfaceDeclaration() ||
3717 tc2.sym.isInterfaceDeclaration())
3718 {
3719 ClassDeclaration cd = findClassCommonRoot(tc1.sym, tc2.sym);
3720 if (!cd)
3721 return null; // no common root
3722 t1 = cd.type.castMod(t1.mod);
3723 t2 = cd.type.castMod(t2.mod);
3724 goto LmergeClassTypes; // deal with mod differences
3725 }
3726
3727 /* Pick 'tightest' type
3728 */
3729 ClassDeclaration cd1 = tc1.sym.baseClass;
3730 ClassDeclaration cd2 = tc2.sym.baseClass;
3731 if (cd1 && cd2)
3732 {
3733 t1 = cd1.type.castMod(t1.mod);
3734 t2 = cd2.type.castMod(t2.mod);
3735 }
3736 else if (cd1)
3737 t1 = cd1.type;
3738 else if (cd2)
3739 t2 = cd2.type;
3740 else
3741 return null;
3742 goto LmergeClassTypes;
3743 }
3744 else if (t1.ty == Tstruct && t1.isTypeStruct().sym.aliasthis)
3745 {
3746 if (isRecursiveAliasThis(att1, e1.type))
3747 return null;
3748 //printf("att tmerge(c || c) e1 = %s\n", e1.type.toChars());
3749 e1 = resolveAliasThis(sc, e1);
3750 t1 = e1.type;
3751 continue;
3752 }
3753 else if (t2.ty == Tstruct && t2.isTypeStruct().sym.aliasthis)
3754 {
3755 if (isRecursiveAliasThis(att2, e2.type))
3756 return null;
3757 //printf("att tmerge(c || c) e2 = %s\n", e2.type.toChars());
3758 e2 = resolveAliasThis(sc, e2);
3759 t2 = e2.type;
3760 continue;
3761 }
3762 else
3763 return null;
3764 }
3765 }
3766
3767 if (t1.ty == Tstruct && t2.ty == Tstruct)
3768 {
3769 if (t1.mod != t2.mod)
3770 {
3771 if (!t1.isImmutable() && !t2.isImmutable() && t1.isShared() != t2.isShared())
3772 return null;
3773 ubyte mod = MODmerge(t1.mod, t2.mod);
3774 t1 = t1.castMod(mod);
3775 t2 = t2.castMod(mod);
3776 t = t1;
3777 goto Lagain;
3778 }
3779
3780 TypeStruct ts1 = t1.isTypeStruct();
3781 TypeStruct ts2 = t2.isTypeStruct();
3782 if (ts1.sym != ts2.sym)
3783 {
3784 if (!ts1.sym.aliasthis && !ts2.sym.aliasthis)
3785 return null;
3786
3787 MATCH i1 = MATCH.nomatch;
3788 MATCH i2 = MATCH.nomatch;
3789
3790 Expression e1b = null;
3791 Expression e2b = null;
3792 if (ts2.sym.aliasthis)
3793 {
3794 if (isRecursiveAliasThis(att2, e2.type))
3795 return null;
3796 //printf("att tmerge(s && s) e2 = %s\n", e2.type.toChars());
3797 e2b = resolveAliasThis(sc, e2);
3798 i1 = e2b.implicitConvTo(t1);
3799 }
3800 if (ts1.sym.aliasthis)
3801 {
3802 if (isRecursiveAliasThis(att1, e1.type))
3803 return null;
3804 //printf("att tmerge(s && s) e1 = %s\n", e1.type.toChars());
3805 e1b = resolveAliasThis(sc, e1);
3806 i2 = e1b.implicitConvTo(t2);
3807 }
3808 if (i1 && i2)
3809 return null;
3810
3811 if (i1)
3812 return convert(e2, t1);
3813 if (i2)
3814 return convert(e1, t2);
3815
3816 if (e1b)
3817 {
3818 e1 = e1b;
3819 t1 = e1b.type.toBasetype();
3820 }
3821 if (e2b)
3822 {
3823 e2 = e2b;
3824 t2 = e2b.type.toBasetype();
3825 }
3826 t = t1;
3827 goto Lagain;
3828 }
3829 }
3830
3831 if (t1.ty == Tstruct && t1.isTypeStruct().sym.aliasthis)
3832 {
3833 if (isRecursiveAliasThis(att1, e1.type))
3834 return null;
3835 //printf("att tmerge(s || s) e1 = %s\n", e1.type.toChars());
3836 e1 = resolveAliasThis(sc, e1);
3837 t1 = e1.type;
3838 t = t1;
3839 goto Lagain;
3840 }
3841
3842 if (t2.ty == Tstruct && t2.isTypeStruct().sym.aliasthis)
3843 {
3844 if (isRecursiveAliasThis(att2, e2.type))
3845 return null;
3846 //printf("att tmerge(s || s) e2 = %s\n", e2.type.toChars());
3847 e2 = resolveAliasThis(sc, e2);
3848 t2 = e2.type;
3849 t = t2;
3850 goto Lagain;
3851 }
3852
3853 if ((e1.op == EXP.string_ || e1.op == EXP.null_) && e1.implicitConvTo(t2))
3854 return convert(e1, t2);
3855 if ((e2.op == EXP.string_ || e2.op == EXP.null_) && e2.implicitConvTo(t1))
3856 return convert(e2, t1);
3857 if (t1.ty == Tsarray && t2.ty == Tsarray && e2.implicitConvTo(t1.nextOf().arrayOf()))
3858 return coerce(t1.nextOf().arrayOf());
3859 if (t1.ty == Tsarray && t2.ty == Tsarray && e1.implicitConvTo(t2.nextOf().arrayOf()))
3860 return coerce(t2.nextOf().arrayOf());
3861
3862 if (t1.ty == Tvector && t2.ty == Tvector)
3863 {
3864 // https://issues.dlang.org/show_bug.cgi?id=13841
3865 // all vector types should have no common types between
3866 // different vectors, even though their sizes are same.
3867 auto tv1 = t1.isTypeVector();
3868 auto tv2 = t2.isTypeVector();
3869 if (!tv1.basetype.equals(tv2.basetype))
3870 return null;
3871
3872 goto LmodCompare;
3873 }
3874
3875 if (t1.ty == Tvector && t2.ty != Tvector && e2.implicitConvTo(t1))
3876 {
3877 e2 = e2.castTo(sc, t1);
3878 t2 = t1;
3879 t = t1;
3880 goto Lagain;
3881 }
3882
3883 if (t2.ty == Tvector && t1.ty != Tvector && e1.implicitConvTo(t2))
3884 {
3885 e1 = e1.castTo(sc, t2);
3886 t1 = t2;
3887 t = t1;
3888 goto Lagain;
3889 }
3890
3891 if (t1.isIntegral() && t2.isIntegral())
3892 {
3893 if (t1.ty != t2.ty)
3894 {
3895 if (t1.ty == Tvector || t2.ty == Tvector)
3896 return null;
3897 e1 = integralPromotions(e1, sc);
3898 e2 = integralPromotions(e2, sc);
3899 t1 = e1.type;
3900 t2 = e2.type;
3901 goto Lagain;
3902 }
3903 assert(t1.ty == t2.ty);
3904 LmodCompare:
3905 if (!t1.isImmutable() && !t2.isImmutable() && t1.isShared() != t2.isShared())
3906 return null;
3907 ubyte mod = MODmerge(t1.mod, t2.mod);
3908
3909 t1 = t1.castMod(mod);
3910 t2 = t2.castMod(mod);
3911 t = t1;
3912 e1 = e1.castTo(sc, t);
3913 e2 = e2.castTo(sc, t);
3914 goto Lagain;
3915 }
3916
3917 if (t1.ty == Tnull && t2.ty == Tnull)
3918 {
3919 ubyte mod = MODmerge(t1.mod, t2.mod);
3920 return coerce(t1.castMod(mod));
3921 }
3922
3923 if (t2.ty == Tnull && (t1.ty == Tpointer || t1.ty == Taarray || t1.ty == Tarray))
3924 return convert(e2, t1);
3925 if (t1.ty == Tnull && (t2.ty == Tpointer || t2.ty == Taarray || t2.ty == Tarray))
3926 return convert(e1, t2);
3927
3928 /// Covers array operations for user-defined types
3929 Type checkArrayOpType(Expression e1, Expression e2, EXP op, Scope* sc)
3930 {
3931 // scalar op scalar - we shouldn't be here
3932 if (e1.type.ty != Tarray && e1.type.ty != Tsarray && e2.type.ty != Tarray && e2.type.ty != Tsarray)
3933 return null;
3934
3935 // only supporting slices and array literals
3936 if (!e1.isSliceExp() && !e1.isArrayLiteralExp() && !e2.isSliceExp() && !e2.isArrayLiteralExp())
3937 return null;
3938
3939 // start with e1 op e2 and if either one of e1 or e2 is a slice or array literal,
3940 // replace it with the first element of the array
3941 Expression lhs = e1;
3942 Expression rhs = e2;
3943
3944 // T[x .. y] op ?
3945 if (auto se1 = e1.isSliceExp())
3946 lhs = new IndexExp(Loc.initial, se1.e1, IntegerExp.literal!0);
3947
3948 // [t1, t2, .. t3] op ?
3949 if (auto ale1 = e1.isArrayLiteralExp())
3950 lhs = ale1.opIndex(0);
3951
3952 // ? op U[z .. t]
3953 if (auto se2 = e2.isSliceExp())
3954 rhs = new IndexExp(Loc.initial, se2.e1, IntegerExp.literal!0);
3955
3956 // ? op [u1, u2, .. u3]
3957 if (auto ale2 = e2.isArrayLiteralExp())
3958 rhs = ale2.opIndex(0);
3959
3960 // create a new binary expression with the new lhs and rhs (at this stage, at least
3961 // one of lhs/rhs has been replaced with the 0'th element of the array it was before)
3962 Expression exp;
3963 switch (op)
3964 {
3965 case EXP.add:
3966 exp = new AddExp(Loc.initial, lhs, rhs); break;
3967 case EXP.min:
3968 exp = new MinExp(Loc.initial, lhs, rhs); break;
3969 case EXP.mul:
3970 exp = new MulExp(Loc.initial, lhs, rhs); break;
3971 case EXP.div:
3972 exp = new DivExp(Loc.initial, lhs, rhs); break;
3973 case EXP.pow:
3974 exp = new PowExp(Loc.initial, lhs, rhs); break;
3975 default:
3976 exp = null;
3977 }
3978
3979 if (exp)
3980 {
3981 // if T op U is valid and has type V
3982 // then T[] op U and T op U[] should be valid and have type V[]
3983 Expression e = exp.trySemantic(sc);
3984 if (e && e.type)
3985 return e.type.arrayOf;
3986 }
3987
3988 return null;
3989 }
3990
3991 if (t1.ty == Tarray && isBinArrayOp(op) && isArrayOpOperand(e1))
3992 {
3993 if (e2.implicitConvTo(t1.nextOf()))
3994 {
3995 // T[] op T
3996 // T[] op cast(T)U
3997 e2 = e2.castTo(sc, t1.nextOf());
3998 return Lret(t1.nextOf().arrayOf());
3999 }
4000 if (t1.nextOf().implicitConvTo(e2.type))
4001 {
4002 // (cast(T)U)[] op T (https://issues.dlang.org/show_bug.cgi?id=12780)
4003 // e1 is left as U[], it will be handled in arrayOp() later.
4004 return Lret(e2.type.arrayOf());
4005 }
4006 if (t2.ty == Tarray && isArrayOpOperand(e2))
4007 {
4008 if (t1.nextOf().implicitConvTo(t2.nextOf()))
4009 {
4010 // (cast(T)U)[] op T[] (https://issues.dlang.org/show_bug.cgi?id=12780)
4011 t = t2.nextOf().arrayOf();
4012 // if cast won't be handled in arrayOp() later
4013 if (!isArrayOpImplicitCast(t1.isTypeDArray(), t2.isTypeDArray()))
4014 e1 = e1.castTo(sc, t);
4015 return Lret(t);
4016 }
4017 if (t2.nextOf().implicitConvTo(t1.nextOf()))
4018 {
4019 // T[] op (cast(T)U)[] (https://issues.dlang.org/show_bug.cgi?id=12780)
4020 // e2 is left as U[], it will be handled in arrayOp() later.
4021 t = t1.nextOf().arrayOf();
4022 // if cast won't be handled in arrayOp() later
4023 if (!isArrayOpImplicitCast(t2.isTypeDArray(), t1.isTypeDArray()))
4024 e2 = e2.castTo(sc, t);
4025 return Lret(t);
4026 }
4027 }
4028
4029 t = checkArrayOpType(e1, e2, op, sc);
4030 if (t !is null)
4031 return Lret(t);
4032
4033 return null;
4034 }
4035 else if (t2.ty == Tarray && isBinArrayOp(op) && isArrayOpOperand(e2))
4036 {
4037 if (e1.implicitConvTo(t2.nextOf()))
4038 {
4039 // T op T[]
4040 // cast(T)U op T[]
4041 e1 = e1.castTo(sc, t2.nextOf());
4042 t = t2.nextOf().arrayOf();
4043 }
4044 else if (t2.nextOf().implicitConvTo(e1.type))
4045 {
4046 // T op (cast(T)U)[] (https://issues.dlang.org/show_bug.cgi?id=12780)
4047 // e2 is left as U[], it will be handled in arrayOp() later.
4048 t = e1.type.arrayOf();
4049 }
4050 else
4051 {
4052 t = checkArrayOpType(e1, e2, op, sc);
4053 if (t is null)
4054 return null;
4055 }
4056
4057 //printf("test %s\n", EXPtoString(op).ptr);
4058 e1 = e1.optimize(WANTvalue);
4059 if (isCommutative(op) && e1.isConst())
4060 {
4061 /* Swap operands to minimize number of functions generated
4062 */
4063 //printf("swap %s\n", EXPtoString(op).ptr);
4064 Expression tmp = e1;
4065 e1 = e2;
4066 e2 = tmp;
4067 }
4068 return Lret(t);
4069 }
4070
4071 return null;
4072 }
4073
4074 /**********************************
4075 * Find common root that both cd1 and cd2 can be implicitly converted to.
4076 * Params:
4077 * cd1 = first class
4078 * cd2 = second class
4079 * Returns:
4080 * common base that both can implicitly convert to, null if none or
4081 * multiple matches
4082 */
4083 private
4084 ClassDeclaration findClassCommonRoot(ClassDeclaration cd1, ClassDeclaration cd2)
4085 {
4086 enum log = false;
4087 if (log) printf("findClassCommonRoot(%s, %s)\n", cd1.toChars(), cd2.toChars());
4088 /* accumulate results in this */
4089 static struct Root
4090 {
4091 ClassDeclaration cd;
4092 bool error;
4093
4094 /* merge cd into results */
4095 void accumulate(ClassDeclaration cd)
4096 {
4097 if (log) printf(" accumulate(r.cd: %s r.error: %d cd: %s)\n", this.cd ? this.cd.toChars() : "null", error, cd ? cd.toChars() : null);
4098 if (this.cd is cd)
4099 {
4100 }
4101 else if (!this.cd)
4102 this.cd = cd;
4103 else
4104 error = true;
4105 }
4106 }
4107
4108 /* Find common root of cd1 and cd2. Accumulate results in r. depth is nesting level */
4109 void findCommonRoot(ClassDeclaration cd1, ClassDeclaration cd2, ref Root r)
4110 {
4111 if (log) printf("findCommonRoot(cd1: %s cd2: %s)\n", cd1.toChars(), cd2.toChars());
4112 /* Warning: quadratic time function
4113 */
4114 if (cd1 is cd2)
4115 {
4116 r.accumulate(cd1);
4117 return;
4118 }
4119
4120 foreach (b1; (*cd1.baseclasses)[])
4121 {
4122 if (b1.sym != r.cd)
4123 findCommonRoot(cd2, b1.sym, r);
4124 }
4125 foreach (b2; (*cd2.baseclasses)[])
4126 {
4127 if (b2.sym != r.cd)
4128 findCommonRoot(cd1, b2.sym, r);
4129 }
4130 }
4131
4132 Root r;
4133 findCommonRoot(cd1, cd2, r);
4134 if (!r.cd || r.error)
4135 return null; // no common root
4136 return r.cd;
4137 }
4138
4139 /************************************
4140 * Bring leaves to common type.
4141 * Returns:
4142 * null on success, ErrorExp if error occurs
4143 */
4144 Expression typeCombine(BinExp be, Scope* sc)
4145 {
4146 Expression errorReturn()
4147 {
4148 Expression ex = be.incompatibleTypes(sc);
4149 if (ex.op == EXP.error)
4150 return ex;
4151 return ErrorExp.get();
4152 }
4153
4154 if (auto result = typeMerge(sc, be.op, be.e1, be.e2))
4155 {
4156 if (be.type is null)
4157 be.type = result;
4158 }
4159 else
4160 return errorReturn();
4161
4162 // If the types have no value, return an error
4163 if (be.e1.op == EXP.error)
4164 return be.e1;
4165 if (be.e2.op == EXP.error)
4166 return be.e2;
4167 return null;
4168 }
4169
4170 /***********************************
4171 * Do integral promotions (convertchk).
4172 * Don't convert <array of> to <pointer to>
4173 */
4174 Expression integralPromotions(Expression e, Scope* sc)
4175 {
4176 //printf("integralPromotions %s %s\n", e.toChars(), e.type.toChars());
4177 switch (e.type.toBasetype().ty)
4178 {
4179 case Tvoid:
4180 error(e.loc, "void has no value");
4181 return ErrorExp.get();
4182
4183 case Tint8:
4184 case Tuns8:
4185 case Tint16:
4186 case Tuns16:
4187 case Tbool:
4188 case Tchar:
4189 case Twchar:
4190 e = e.castTo(sc, Type.tint32);
4191 break;
4192
4193 case Tdchar:
4194 e = e.castTo(sc, Type.tuns32);
4195 break;
4196
4197 default:
4198 break;
4199 }
4200 return e;
4201 }
4202
4203 /******************************************************
4204 * This provides a transition from the non-promoting behavior
4205 * of unary + - ~ to the C-like integral promotion behavior.
4206 * Params:
4207 * sc = context
4208 * ue = NegExp, UAddExp, or ComExp which is revised per rules
4209 * References:
4210 * https://issues.dlang.org/show_bug.cgi?id=16997
4211 */
4212
4213 void fix16997(Scope* sc, UnaExp ue)
4214 {
4215 if (global.params.fix16997 || sc.inCfile)
4216 ue.e1 = integralPromotions(ue.e1, sc); // desired C-like behavor
4217 else
4218 {
4219 switch (ue.e1.type.toBasetype.ty)
4220 {
4221 case Tint8:
4222 case Tuns8:
4223 case Tint16:
4224 case Tuns16:
4225 //case Tbool: // these operations aren't allowed on bool anyway
4226 case Tchar:
4227 case Twchar:
4228 case Tdchar:
4229 deprecation(ue.loc, "integral promotion not done for `%s`, remove '-revert=intpromote' switch or `%scast(int)(%s)`",
4230 ue.toChars(), EXPtoString(ue.op).ptr, ue.e1.toChars());
4231 break;
4232
4233 default:
4234 break;
4235 }
4236 }
4237 }
4238
4239 /***********************************
4240 * See if both types are arrays that can be compared
4241 * for equality without any casting. Return true if so.
4242 * This is to enable comparing things like an immutable
4243 * array with a mutable one.
4244 */
4245 extern (D) bool arrayTypeCompatibleWithoutCasting(Type t1, Type t2)
4246 {
4247 t1 = t1.toBasetype();
4248 t2 = t2.toBasetype();
4249
4250 if ((t1.isStaticOrDynamicArray() || t1.ty == Tpointer) && t2.ty == t1.ty)
4251 {
4252 if (t1.nextOf().implicitConvTo(t2.nextOf()) >= MATCH.constant || t2.nextOf().implicitConvTo(t1.nextOf()) >= MATCH.constant)
4253 return true;
4254 }
4255 return false;
4256 }
4257
4258 /******************************************************************/
4259 /* Determine the integral ranges of an expression.
4260 * This is used to determine if implicit narrowing conversions will
4261 * be allowed.
4262 */
4263 @trusted
4264 IntRange getIntRange(Expression e)
4265 {
4266 IntRange visit(Expression e)
4267 {
4268 return IntRange.fromType(e.type);
4269 }
4270
4271 IntRange visitInteger(IntegerExp e)
4272 {
4273 return IntRange(SignExtendedNumber(e.getInteger()))._cast(e.type);
4274 }
4275
4276 IntRange visitCast(CastExp e)
4277 {
4278 return getIntRange(e.e1)._cast(e.type);
4279 }
4280
4281 IntRange visitAdd(AddExp e)
4282 {
4283 IntRange ir1 = getIntRange(e.e1);
4284 IntRange ir2 = getIntRange(e.e2);
4285 return (ir1 + ir2)._cast(e.type);
4286 }
4287
4288 IntRange visitMin(MinExp e)
4289 {
4290 IntRange ir1 = getIntRange(e.e1);
4291 IntRange ir2 = getIntRange(e.e2);
4292 return (ir1 - ir2)._cast(e.type);
4293 }
4294
4295 IntRange visitDiv(DivExp e)
4296 {
4297 IntRange ir1 = getIntRange(e.e1);
4298 IntRange ir2 = getIntRange(e.e2);
4299
4300 return (ir1 / ir2)._cast(e.type);
4301 }
4302
4303 IntRange visitMul(MulExp e)
4304 {
4305 IntRange ir1 = getIntRange(e.e1);
4306 IntRange ir2 = getIntRange(e.e2);
4307
4308 return (ir1 * ir2)._cast(e.type);
4309 }
4310
4311 IntRange visitMod(ModExp e)
4312 {
4313 IntRange ir1 = getIntRange(e.e1);
4314 IntRange ir2 = getIntRange(e.e2);
4315
4316 // Modding on 0 is invalid anyway.
4317 if (!ir2.absNeg().imin.negative)
4318 {
4319 return visit(e);
4320 }
4321 return (ir1 % ir2)._cast(e.type);
4322 }
4323
4324 IntRange visitAnd(AndExp e)
4325 {
4326 IntRange result;
4327 bool hasResult = false;
4328 result.unionOrAssign(getIntRange(e.e1) & getIntRange(e.e2), hasResult);
4329
4330 assert(hasResult);
4331 return result._cast(e.type);
4332 }
4333
4334 IntRange visitOr(OrExp e)
4335 {
4336 IntRange result;
4337 bool hasResult = false;
4338 result.unionOrAssign(getIntRange(e.e1) | getIntRange(e.e2), hasResult);
4339
4340 assert(hasResult);
4341 return result._cast(e.type);
4342 }
4343
4344 IntRange visitXor(XorExp e)
4345 {
4346 IntRange result;
4347 bool hasResult = false;
4348 result.unionOrAssign(getIntRange(e.e1) ^ getIntRange(e.e2), hasResult);
4349
4350 assert(hasResult);
4351 return result._cast(e.type);
4352 }
4353
4354 IntRange visitShl(ShlExp e)
4355 {
4356 IntRange ir1 = getIntRange(e.e1);
4357 IntRange ir2 = getIntRange(e.e2);
4358
4359 return (ir1 << ir2)._cast(e.type);
4360 }
4361
4362 IntRange visitShr(ShrExp e)
4363 {
4364 IntRange ir1 = getIntRange(e.e1);
4365 IntRange ir2 = getIntRange(e.e2);
4366
4367 return (ir1 >> ir2)._cast(e.type);
4368 }
4369
4370 IntRange visitUshr(UshrExp e)
4371 {
4372 IntRange ir1 = getIntRange(e.e1).castUnsigned(e.e1.type);
4373 IntRange ir2 = getIntRange(e.e2);
4374
4375 return (ir1 >>> ir2)._cast(e.type);
4376 }
4377
4378 IntRange visitAssign(AssignExp e)
4379 {
4380 return getIntRange(e.e2)._cast(e.type);
4381 }
4382
4383 IntRange visitCond(CondExp e)
4384 {
4385 // No need to check e.econd; assume caller has called optimize()
4386 IntRange ir1 = getIntRange(e.e1);
4387 IntRange ir2 = getIntRange(e.e2);
4388 return ir1.unionWith(ir2)._cast(e.type);
4389 }
4390
4391 IntRange visitVar(VarExp e)
4392 {
4393 Expression ie;
4394 VarDeclaration vd = e.var.isVarDeclaration();
4395 if (vd && vd.range)
4396 return vd.range._cast(e.type);
4397 if (vd && vd._init && !vd.type.isMutable() && (ie = vd.getConstInitializer()) !is null)
4398 return getIntRange(ie);
4399 return visit(e);
4400 }
4401
4402 IntRange visitComma(CommaExp e)
4403 {
4404 return getIntRange(e.e2);
4405 }
4406
4407 IntRange visitCom(ComExp e)
4408 {
4409 IntRange ir = getIntRange(e.e1);
4410 return IntRange(SignExtendedNumber(~ir.imax.value, !ir.imax.negative), SignExtendedNumber(~ir.imin.value, !ir.imin.negative))._cast(e.type);
4411 }
4412
4413 IntRange visitNeg(NegExp e)
4414 {
4415 IntRange ir = getIntRange(e.e1);
4416 return (-ir)._cast(e.type);
4417 }
4418
4419 switch (e.op)
4420 {
4421 default : return visit(e);
4422 case EXP.int64 : return visitInteger(e.isIntegerExp());
4423 case EXP.cast_ : return visitCast(e.isCastExp());
4424 case EXP.add : return visitAdd(e.isAddExp());
4425 case EXP.min : return visitMin(e.isMinExp());
4426 case EXP.div : return visitDiv(e.isDivExp());
4427 case EXP.mul : return visitMul(e.isMulExp());
4428 case EXP.mod : return visitMod(e.isModExp());
4429 case EXP.and : return visitAnd(e.isAndExp());
4430 case EXP.or : return visitOr(e.isOrExp());
4431 case EXP.xor : return visitXor(e.isXorExp());
4432 case EXP.leftShift : return visitShl(e.isShlExp());
4433 case EXP.rightShift : return visitShr(e.isShrExp());
4434 case EXP.unsignedRightShift : return visitUshr(e.isUshrExp());
4435 case EXP.blit : return visitAssign(e.isBlitExp());
4436 case EXP.construct : return visitAssign(e.isConstructExp());
4437 case EXP.assign : return visitAssign(e.isAssignExp());
4438 case EXP.question : return visitCond(e.isCondExp());
4439 case EXP.variable : return visitVar(e.isVarExp());
4440 case EXP.comma : return visitComma(e.isCommaExp());
4441 case EXP.tilde : return visitCom(e.isComExp());
4442 case EXP.negate : return visitNeg(e.isNegExp());
4443 }
4444 }
4445 /**
4446 * A helper function to "cast" from expressions of type noreturn to
4447 * any other type - noreturn is implicitly convertible to any other type.
4448 * However, the dmd backend does not like a naive cast from a noreturn expression
4449 * (particularly an `assert(0)`) so this function generates:
4450 *
4451 * `(assert(0), value)` instead of `cast(to)(assert(0))`.
4452 *
4453 * `value` is currently `to.init` however it cannot be read so could be made simpler.
4454 * Params:
4455 * toBeCasted = Expression of type noreturn to cast
4456 * to = Type to cast the expression to.
4457 * Returns: A CommaExp, upon any failure ErrorExp will be returned.
4458 */
4459 Expression specialNoreturnCast(Expression toBeCasted, Type to)
4460 {
4461 return Expression.combine(toBeCasted, to.defaultInitLiteral(toBeCasted.loc));
4462 }