Debian Codegraph @

gcc/d/dmd/mtype.d

raw
1 /**
2 * Defines a D type.
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/mtype.d, _mtype.d)
8 * Documentation: https://dlang.org/phobos/dmd_mtype.html
9 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/mtype.d
10 */
11
12 module dmd.mtype;
13
14 import core.checkedint;
15 import core.stdc.stdarg;
16 import core.stdc.stdio;
17 import core.stdc.stdlib;
18 import core.stdc.string;
19
20 import dmd.aggregate;
21 import dmd.arraytypes;
22 import dmd.astenums;
23 import dmd.ast_node;
24 import dmd.dclass;
25 import dmd.declaration;
26 import dmd.denum;
27 import dmd.dstruct;
28 import dmd.dsymbol;
29 import dmd.dtemplate;
30 import dmd.enumsem;
31 import dmd.errors;
32 import dmd.expression;
33 import dmd.dsymbolsem : determineSize;
34 import dmd.globals;
35 import dmd.hdrgen;
36 import dmd.id;
37 import dmd.identifier;
38 import dmd.location;
39 import dmd.root.ctfloat;
40 import dmd.common.outbuffer;
41 import dmd.root.rmem;
42 import dmd.rootobject;
43 import dmd.root.stringtable;
44 import dmd.target;
45 import dmd.tokens;
46 import dmd.typesem;
47 import dmd.visitor;
48
49 enum LOGDOTEXP = 0; // log ::dotExp()
50 enum LOGDEFAULTINIT = 0; // log ::defaultInit()
51
52 enum SIZE_INVALID = (~cast(uinteger_t)0); // error return from size() functions
53
54 static if (__VERSION__ < 2095)
55 {
56 // Fix linker errors when building with older compilers.
57 // See: https://issues.dlang.org/show_bug.cgi?id=21299
58 private alias StringValueType = StringValue!Type;
59 }
60
61 private auto X(T, U)(T m, U n)
62 {
63 return (m << 4) | n;
64 }
65
66 /***************************
67 * Return !=0 if modfrom can be implicitly converted to modto
68 */
69 bool MODimplicitConv(MOD modfrom, MOD modto) pure nothrow @nogc @safe
70 {
71 if (modfrom == modto)
72 return true;
73
74 //printf("MODimplicitConv(from = %x, to = %x)\n", modfrom, modto);
75
76 switch (X(modfrom & ~MODFlags.shared_, modto & ~MODFlags.shared_))
77 {
78 case X(0, MODFlags.const_):
79 case X(MODFlags.wild, MODFlags.const_):
80 case X(MODFlags.wild, MODFlags.wildconst):
81 case X(MODFlags.wildconst, MODFlags.const_):
82 return (modfrom & MODFlags.shared_) == (modto & MODFlags.shared_);
83
84 case X(MODFlags.immutable_, MODFlags.const_):
85 case X(MODFlags.immutable_, MODFlags.wildconst):
86 return true;
87 default:
88 return false;
89 }
90 }
91
92 /***************************
93 * Return MATCH.exact or MATCH.constant if a method of type '() modfrom' can call a method of type '() modto'.
94 */
95 MATCH MODmethodConv(MOD modfrom, MOD modto) pure nothrow @nogc @safe
96 {
97 if (modfrom == modto)
98 return MATCH.exact;
99 if (MODimplicitConv(modfrom, modto))
100 return MATCH.constant;
101
102 switch (X(modfrom, modto))
103 {
104 case X(0, MODFlags.wild):
105 case X(MODFlags.immutable_, MODFlags.wild):
106 case X(MODFlags.const_, MODFlags.wild):
107 case X(MODFlags.wildconst, MODFlags.wild):
108 case X(MODFlags.shared_, MODFlags.shared_ | MODFlags.wild):
109 case X(MODFlags.shared_ | MODFlags.immutable_, MODFlags.shared_ | MODFlags.wild):
110 case X(MODFlags.shared_ | MODFlags.const_, MODFlags.shared_ | MODFlags.wild):
111 case X(MODFlags.shared_ | MODFlags.wildconst, MODFlags.shared_ | MODFlags.wild):
112 return MATCH.constant;
113
114 default:
115 return MATCH.nomatch;
116 }
117 }
118
119 /***************************
120 * Merge mod bits to form common mod.
121 */
122 MOD MODmerge(MOD mod1, MOD mod2) pure nothrow @nogc @safe
123 {
124 if (mod1 == mod2)
125 return mod1;
126
127 //printf("MODmerge(1 = %x, 2 = %x)\n", mod1, mod2);
128 MOD result = 0;
129 if ((mod1 | mod2) & MODFlags.shared_)
130 {
131 // If either type is shared, the result will be shared
132 result |= MODFlags.shared_;
133 mod1 &= ~MODFlags.shared_;
134 mod2 &= ~MODFlags.shared_;
135 }
136 if (mod1 == 0 || mod1 == MODFlags.mutable || mod1 == MODFlags.const_ || mod2 == 0 || mod2 == MODFlags.mutable || mod2 == MODFlags.const_)
137 {
138 // If either type is mutable or const, the result will be const.
139 result |= MODFlags.const_;
140 }
141 else
142 {
143 // MODFlags.immutable_ vs MODFlags.wild
144 // MODFlags.immutable_ vs MODFlags.wildconst
145 // MODFlags.wild vs MODFlags.wildconst
146 assert(mod1 & MODFlags.wild || mod2 & MODFlags.wild);
147 result |= MODFlags.wildconst;
148 }
149 return result;
150 }
151
152 /*********************************
153 * Store modifier name into buf.
154 */
155 void MODtoBuffer(ref OutBuffer buf, MOD mod) nothrow @safe
156 {
157 buf.writestring(MODtoString(mod));
158 }
159
160 /*********************************
161 * Returns:
162 * a human readable representation of `mod`,
163 * which is the token `mod` corresponds to
164 */
165 const(char)* MODtoChars(MOD mod) nothrow pure
166 {
167 /// Works because we return a literal
168 return MODtoString(mod).ptr;
169 }
170
171 /// Ditto
172 string MODtoString(MOD mod) nothrow pure @safe
173 {
174 final switch (mod)
175 {
176 case 0:
177 return "";
178
179 case MODFlags.immutable_:
180 return "immutable";
181
182 case MODFlags.shared_:
183 return "shared";
184
185 case MODFlags.shared_ | MODFlags.const_:
186 return "shared const";
187
188 case MODFlags.const_:
189 return "const";
190
191 case MODFlags.shared_ | MODFlags.wild:
192 return "shared inout";
193
194 case MODFlags.wild:
195 return "inout";
196
197 case MODFlags.shared_ | MODFlags.wildconst:
198 return "shared inout const";
199
200 case MODFlags.wildconst:
201 return "inout const";
202 }
203 }
204
205 /*************************************************
206 * Pick off one of the trust flags from trust,
207 * and return a string representation of it.
208 */
209 string trustToString(TRUST trust) pure nothrow @nogc @safe
210 {
211 final switch (trust)
212 {
213 case TRUST.default_:
214 return null;
215 case TRUST.system:
216 return "@system";
217 case TRUST.trusted:
218 return "@trusted";
219 case TRUST.safe:
220 return "@safe";
221 }
222 }
223
224 unittest
225 {
226 assert(trustToString(TRUST.default_) == "");
227 assert(trustToString(TRUST.system) == "@system");
228 assert(trustToString(TRUST.trusted) == "@trusted");
229 assert(trustToString(TRUST.safe) == "@safe");
230 }
231
232 /************************************
233 * Convert MODxxxx to STCxxx
234 */
235 STC ModToStc(uint mod) pure nothrow @nogc @safe
236 {
237 STC stc = STC.none;
238 if (mod & MODFlags.immutable_)
239 stc |= STC.immutable_;
240 if (mod & MODFlags.const_)
241 stc |= STC.const_;
242 if (mod & MODFlags.wild)
243 stc |= STC.wild;
244 if (mod & MODFlags.shared_)
245 stc |= STC.shared_;
246 return stc;
247 }
248
249 ///Returns true if ty is char, wchar, or dchar
250 bool isSomeChar(TY ty) pure nothrow @nogc @safe
251 {
252 return ty == Tchar || ty == Twchar || ty == Tdchar;
253 }
254
255 /****************
256 * dotExp() bit flags
257 */
258 enum DotExpFlag
259 {
260 none = 0,
261 gag = 1, // don't report "not a property" error and just return null
262 noDeref = 2, // the use of the expression will not attempt a dereference
263 noAliasThis = 4, // don't do 'alias this' resolution
264 }
265
266 /// Result of a check whether two types are covariant
267 enum Covariant
268 {
269 distinct = 0, /// types are distinct
270 yes = 1, /// types are covariant
271 no = 2, /// arguments match as far as overloading goes, but types are not covariant
272 fwdref = 3, /// cannot determine covariance because of forward references
273 }
274
275 /***********************************************************
276 */
277 extern (C++) abstract class Type : ASTNode
278 {
279 TY ty;
280 MOD mod; // modifiers MODxxxx
281 char* deco;
282
283 static struct Mcache
284 {
285 /* These are cached values that are lazily evaluated by constOf(), immutableOf(), etc.
286 * They should not be referenced by anybody but mtype.d.
287 * They can be null if not lazily evaluated yet.
288 * Note that there is no "shared immutable", because that is just immutable
289 * The point of this is to reduce the size of each Type instance as
290 * we bank on the idea that usually only one of variants exist.
291 * It will also speed up code because these are rarely referenced and
292 * so need not be in the cache.
293 */
294 Type cto; // MODFlags.const_
295 Type ito; // MODFlags.immutable_
296 Type sto; // MODFlags.shared_
297 Type scto; // MODFlags.shared_ | MODFlags.const_
298 Type wto; // MODFlags.wild
299 Type wcto; // MODFlags.wildconst
300 Type swto; // MODFlags.shared_ | MODFlags.wild
301 Type swcto; // MODFlags.shared_ | MODFlags.wildconst
302 Type pto; // merged pointer to this type
303 Type rto; // reference to this type
304 Type arrayof; // array of this type
305
306 // ImportC: store the name of the typedef resolving to this type
307 // So `uint8_t x;` will be printed as `uint8_t x;` and not as the resolved `ubyte x;`
308 Identifier typedefIdent;
309 }
310 Mcache* mcache;
311
312 TypeInfoDeclaration vtinfo; // TypeInfo object for this Type
313
314 void* ctype; // for back end
315
316 extern (C++) __gshared Type tvoid;
317 extern (C++) __gshared Type tint8;
318 extern (C++) __gshared Type tuns8;
319 extern (C++) __gshared Type tint16;
320 extern (C++) __gshared Type tuns16;
321 extern (C++) __gshared Type tint32;
322 extern (C++) __gshared Type tuns32;
323 extern (C++) __gshared Type tint64;
324 extern (C++) __gshared Type tuns64;
325 extern (C++) __gshared Type tint128;
326 extern (C++) __gshared Type tuns128;
327 extern (C++) __gshared Type tfloat32;
328 extern (C++) __gshared Type tfloat64;
329 extern (C++) __gshared Type tfloat80;
330 extern (C++) __gshared Type timaginary32;
331 extern (C++) __gshared Type timaginary64;
332 extern (C++) __gshared Type timaginary80;
333 extern (C++) __gshared Type tcomplex32;
334 extern (C++) __gshared Type tcomplex64;
335 extern (C++) __gshared Type tcomplex80;
336 extern (C++) __gshared Type tbool;
337 extern (C++) __gshared Type tchar;
338 extern (C++) __gshared Type twchar;
339 extern (C++) __gshared Type tdchar;
340
341 // Some special types
342 extern (C++) __gshared Type tshiftcnt;
343 extern (C++) __gshared Type tvoidptr; // void*
344 extern (C++) __gshared Type tstring; // immutable(char)[]
345 extern (C++) __gshared Type twstring; // immutable(wchar)[]
346 extern (C++) __gshared Type tdstring; // immutable(dchar)[]
347 extern (C++) __gshared Type terror; // for error recovery
348 extern (C++) __gshared Type tnull; // for null type
349 extern (C++) __gshared Type tnoreturn; // for bottom type typeof(*null)
350
351 extern (C++) __gshared Type tsize_t; // matches size_t alias
352 extern (C++) __gshared Type tptrdiff_t; // matches ptrdiff_t alias
353 extern (C++) __gshared Type thash_t; // matches hash_t alias
354
355 extern (C++) __gshared ClassDeclaration dtypeinfo;
356 extern (C++) __gshared ClassDeclaration typeinfoclass;
357 extern (C++) __gshared ClassDeclaration typeinfointerface;
358 extern (C++) __gshared ClassDeclaration typeinfostruct;
359 extern (C++) __gshared ClassDeclaration typeinfopointer;
360 extern (C++) __gshared ClassDeclaration typeinfoarray;
361 extern (C++) __gshared ClassDeclaration typeinfostaticarray;
362 extern (C++) __gshared ClassDeclaration typeinfoassociativearray;
363 extern (C++) __gshared ClassDeclaration typeinfovector;
364 extern (C++) __gshared ClassDeclaration typeinfoenum;
365 extern (C++) __gshared ClassDeclaration typeinfofunction;
366 extern (C++) __gshared ClassDeclaration typeinfodelegate;
367 extern (C++) __gshared ClassDeclaration typeinfotypelist;
368 extern (C++) __gshared ClassDeclaration typeinfoconst;
369 extern (C++) __gshared ClassDeclaration typeinfoinvariant;
370 extern (C++) __gshared ClassDeclaration typeinfoshared;
371 extern (C++) __gshared ClassDeclaration typeinfowild;
372
373 extern (C++) __gshared TemplateDeclaration rtinfo;
374
375 extern (C++) __gshared Type[TMAX] basic;
376
377 extern (D) __gshared StringTable!Type stringtable;
378 extern (D) private static immutable ubyte[TMAX] sizeTy = ()
379 {
380 ubyte[TMAX] sizeTy = __traits(classInstanceSize, TypeBasic);
381 sizeTy[Tsarray] = __traits(classInstanceSize, TypeSArray);
382 sizeTy[Tarray] = __traits(classInstanceSize, TypeDArray);
383 sizeTy[Taarray] = __traits(classInstanceSize, TypeAArray);
384 sizeTy[Tpointer] = __traits(classInstanceSize, TypePointer);
385 sizeTy[Treference] = __traits(classInstanceSize, TypeReference);
386 sizeTy[Tfunction] = __traits(classInstanceSize, TypeFunction);
387 sizeTy[Tdelegate] = __traits(classInstanceSize, TypeDelegate);
388 sizeTy[Tident] = __traits(classInstanceSize, TypeIdentifier);
389 sizeTy[Tinstance] = __traits(classInstanceSize, TypeInstance);
390 sizeTy[Ttypeof] = __traits(classInstanceSize, TypeTypeof);
391 sizeTy[Tenum] = __traits(classInstanceSize, TypeEnum);
392 sizeTy[Tstruct] = __traits(classInstanceSize, TypeStruct);
393 sizeTy[Tclass] = __traits(classInstanceSize, TypeClass);
394 sizeTy[Ttuple] = __traits(classInstanceSize, TypeTuple);
395 sizeTy[Tslice] = __traits(classInstanceSize, TypeSlice);
396 sizeTy[Treturn] = __traits(classInstanceSize, TypeReturn);
397 sizeTy[Terror] = __traits(classInstanceSize, TypeError);
398 sizeTy[Tnull] = __traits(classInstanceSize, TypeNull);
399 sizeTy[Tvector] = __traits(classInstanceSize, TypeVector);
400 sizeTy[Ttraits] = __traits(classInstanceSize, TypeTraits);
401 sizeTy[Tmixin] = __traits(classInstanceSize, TypeMixin);
402 sizeTy[Tnoreturn] = __traits(classInstanceSize, TypeNoreturn);
403 sizeTy[Ttag] = __traits(classInstanceSize, TypeTag);
404 return sizeTy;
405 }();
406
407 final extern (D) this(TY ty) scope @safe
408 {
409 this.ty = ty;
410 }
411
412 const(char)* kind() const nothrow pure @nogc @safe
413 {
414 assert(false); // should be overridden
415 }
416
417 final Type copy() nothrow const
418 {
419 Type t = cast(Type)mem.xmalloc(sizeTy[ty]);
420 memcpy(cast(void*)t, cast(void*)this, sizeTy[ty]);
421 return t;
422 }
423
424 Type syntaxCopy()
425 {
426 fprintf(stderr, "this = %s, ty = %d\n", toChars(), ty);
427 assert(0);
428 }
429
430 override bool equals(const RootObject o) const
431 {
432 Type t = cast(Type)o;
433 //printf("Type::equals(%s, %s)\n", toChars(), t.toChars());
434 // deco strings are unique
435 // and semantic() has been run
436 if (this == o || ((t && deco == t.deco) && deco !is null))
437 {
438 //printf("deco = '%s', t.deco = '%s'\n", deco, t.deco);
439 return true;
440 }
441 //if (deco && t && t.deco) printf("deco = '%s', t.deco = '%s'\n", deco, t.deco);
442 return false;
443 }
444
445 // kludge for template.isType()
446 override final DYNCAST dyncast() const
447 {
448 return DYNCAST.type;
449 }
450
451 /// Returns a non-zero unique ID for this Type, or returns 0 if the Type does not (yet) have a unique ID.
452 /// If `semantic()` has not been run, 0 is returned.
453 final size_t getUniqueID() const
454 {
455 return cast(size_t) deco;
456 }
457
458 extern (D)
459 final Mcache* getMcache()
460 {
461 if (!mcache)
462 mcache = cast(Mcache*) mem.xcalloc(Mcache.sizeof, 1);
463 return mcache;
464 }
465
466 /********************************
467 * For pretty-printing a type.
468 */
469 final override const(char)* toChars() const
470 {
471 return dmd.hdrgen.toChars(this);
472 }
473
474 /// ditto
475 final char* toPrettyChars(bool QualifyTypes = false)
476 {
477 OutBuffer buf;
478 buf.reserve(16);
479 HdrGenState hgs;
480 hgs.fullQual = QualifyTypes;
481
482 toCBuffer(this, buf, null, hgs);
483 return buf.extractChars();
484 }
485
486 static void _init()
487 {
488 stringtable._init(14_000);
489
490 // Set basic types
491 __gshared TY* basetab =
492 [
493 Tvoid,
494 Tint8,
495 Tuns8,
496 Tint16,
497 Tuns16,
498 Tint32,
499 Tuns32,
500 Tint64,
501 Tuns64,
502 Tint128,
503 Tuns128,
504 Tfloat32,
505 Tfloat64,
506 Tfloat80,
507 Timaginary32,
508 Timaginary64,
509 Timaginary80,
510 Tcomplex32,
511 Tcomplex64,
512 Tcomplex80,
513 Tbool,
514 Tchar,
515 Twchar,
516 Tdchar,
517 Terror
518 ];
519
520 static Type merge(Type t)
521 {
522 import dmd.mangle.basic : tyToDecoBuffer;
523
524 OutBuffer buf;
525 buf.reserve(3);
526
527 if (t.ty == Tnoreturn)
528 buf.writestring("Nn");
529 else
530 tyToDecoBuffer(buf, t.ty);
531
532 auto sv = t.stringtable.update(buf[]);
533 if (sv.value)
534 return sv.value;
535 t.deco = cast(char*)sv.toDchars();
536 sv.value = t;
537 return t;
538 }
539
540 for (size_t i = 0; basetab[i] != Terror; i++)
541 {
542 Type t = new TypeBasic(basetab[i]);
543 t = merge(t);
544 basic[basetab[i]] = t;
545 }
546 basic[Terror] = new TypeError();
547
548 tnoreturn = new TypeNoreturn();
549 tnoreturn.deco = merge(tnoreturn).deco;
550 basic[Tnoreturn] = tnoreturn;
551
552 tvoid = basic[Tvoid];
553 tint8 = basic[Tint8];
554 tuns8 = basic[Tuns8];
555 tint16 = basic[Tint16];
556 tuns16 = basic[Tuns16];
557 tint32 = basic[Tint32];
558 tuns32 = basic[Tuns32];
559 tint64 = basic[Tint64];
560 tuns64 = basic[Tuns64];
561 tint128 = basic[Tint128];
562 tuns128 = basic[Tuns128];
563 tfloat32 = basic[Tfloat32];
564 tfloat64 = basic[Tfloat64];
565 tfloat80 = basic[Tfloat80];
566
567 timaginary32 = basic[Timaginary32];
568 timaginary64 = basic[Timaginary64];
569 timaginary80 = basic[Timaginary80];
570
571 tcomplex32 = basic[Tcomplex32];
572 tcomplex64 = basic[Tcomplex64];
573 tcomplex80 = basic[Tcomplex80];
574
575 tbool = basic[Tbool];
576 tchar = basic[Tchar];
577 twchar = basic[Twchar];
578 tdchar = basic[Tdchar];
579
580 tshiftcnt = tint32;
581 terror = basic[Terror];
582 tnoreturn = basic[Tnoreturn];
583 tnull = new TypeNull();
584 tnull.deco = merge(tnull).deco;
585
586 tvoidptr = tvoid.pointerTo();
587 tstring = tchar.immutableOf().arrayOf();
588 twstring = twchar.immutableOf().arrayOf();
589 tdstring = tdchar.immutableOf().arrayOf();
590
591 const isLP64 = target.isLP64;
592
593 tsize_t = basic[isLP64 ? Tuns64 : Tuns32];
594 tptrdiff_t = basic[isLP64 ? Tint64 : Tint32];
595 thash_t = tsize_t;
596
597 static if (__VERSION__ == 2081)
598 {
599 // Related issue: https://issues.dlang.org/show_bug.cgi?id=19134
600 // D 2.081.x regressed initializing class objects at compile time.
601 // As a workaround initialize this global at run-time instead.
602 TypeTuple.empty = new TypeTuple();
603 }
604 }
605
606 /**
607 * Deinitializes the global state of the compiler.
608 *
609 * This can be used to restore the state set by `_init` to its original
610 * state.
611 */
612 static void deinitialize()
613 {
614 stringtable = stringtable.init;
615 }
616
617 uint alignsize()
618 {
619 return cast(uint)size(this, Loc.initial);
620 }
621
622 /*********************************
623 * Store this type's modifier name into buf.
624 */
625 final void modToBuffer(ref OutBuffer buf) nothrow const
626 {
627 if (mod)
628 {
629 buf.writeByte(' ');
630 MODtoBuffer(buf, mod);
631 }
632 }
633
634 /*********************************
635 * Return this type's modifier name.
636 */
637 final char* modToChars() nothrow const
638 {
639 OutBuffer buf;
640 buf.reserve(16);
641 modToBuffer(buf);
642 return buf.extractChars();
643 }
644
645 bool isIntegral()
646 {
647 return false;
648 }
649
650 // real, imaginary, or complex
651 bool isFloating()
652 {
653 return false;
654 }
655
656 bool isReal()
657 {
658 return false;
659 }
660
661 bool isImaginary()
662 {
663 return false;
664 }
665
666 bool isComplex()
667 {
668 return false;
669 }
670
671 bool isScalar()
672 {
673 return false;
674 }
675
676 bool isUnsigned()
677 {
678 return false;
679 }
680
681 bool isScopeClass()
682 {
683 return false;
684 }
685
686 bool isString()
687 {
688 return false;
689 }
690
691 /**************************
692 * When T is mutable,
693 * Given:
694 * T a, b;
695 * Can we bitwise assign:
696 * a = b;
697 * ?
698 */
699 bool isAssignable()
700 {
701 return true;
702 }
703
704 /**************************
705 * Returns true if T can be converted to boolean value.
706 */
707 bool isBoolean()
708 {
709 return isScalar();
710 }
711
712 final bool isConst() const nothrow pure @nogc @safe
713 {
714 return (mod & MODFlags.const_) != 0;
715 }
716
717 final bool isImmutable() const nothrow pure @nogc @safe
718 {
719 return (mod & MODFlags.immutable_) != 0;
720 }
721
722 final bool isMutable() const nothrow pure @nogc @safe
723 {
724 return (mod & (MODFlags.const_ | MODFlags.immutable_ | MODFlags.wild)) == 0;
725 }
726
727 final bool isShared() const nothrow pure @nogc @safe
728 {
729 return (mod & MODFlags.shared_) != 0;
730 }
731
732 final bool isSharedConst() const nothrow pure @nogc @safe
733 {
734 return (mod & (MODFlags.shared_ | MODFlags.const_)) == (MODFlags.shared_ | MODFlags.const_);
735 }
736
737 final bool isWild() const nothrow pure @nogc @safe
738 {
739 return (mod & MODFlags.wild) != 0;
740 }
741
742 final bool isWildConst() const nothrow pure @nogc @safe
743 {
744 return (mod & MODFlags.wildconst) == MODFlags.wildconst;
745 }
746
747 final bool isSharedWild() const nothrow pure @nogc @safe
748 {
749 return (mod & (MODFlags.shared_ | MODFlags.wild)) == (MODFlags.shared_ | MODFlags.wild);
750 }
751
752 final bool isNaked() const nothrow pure @nogc @safe
753 {
754 return mod == 0;
755 }
756
757 /********************************
758 * Return a copy of this type with all attributes null-initialized.
759 * Useful for creating a type with different modifiers.
760 */
761 final Type nullAttributes() nothrow const
762 {
763 uint sz = sizeTy[ty];
764 Type t = cast(Type)mem.xmalloc(sz);
765 memcpy(cast(void*)t, cast(void*)this, sz);
766 // t.mod = NULL; // leave mod unchanged
767 t.deco = null;
768 t.vtinfo = null;
769 t.ctype = null;
770 t.mcache = null;
771 if (t.ty == Tstruct)
772 (cast(TypeStruct)t).att = AliasThisRec.fwdref;
773 if (t.ty == Tclass)
774 (cast(TypeClass)t).att = AliasThisRec.fwdref;
775 return t;
776 }
777
778 /**********************************
779 * For our new type 'this', which is type-constructed from t,
780 * fill in the cto, ito, sto, scto, wto shortcuts.
781 */
782 extern (D) final void fixTo(Type t)
783 {
784 // If fixing this: immutable(T*) by t: immutable(T)*,
785 // cache t to this.xto won't break transitivity.
786 Type mto = null;
787 Type tn = nextOf();
788 if (!tn || ty != Tsarray && tn.mod == t.nextOf().mod)
789 {
790 switch (t.mod)
791 {
792 case 0:
793 mto = t;
794 break;
795
796 case MODFlags.const_:
797 getMcache();
798 mcache.cto = t;
799 break;
800
801 case MODFlags.wild:
802 getMcache();
803 mcache.wto = t;
804 break;
805
806 case MODFlags.wildconst:
807 getMcache();
808 mcache.wcto = t;
809 break;
810
811 case MODFlags.shared_:
812 getMcache();
813 mcache.sto = t;
814 break;
815
816 case MODFlags.shared_ | MODFlags.const_:
817 getMcache();
818 mcache.scto = t;
819 break;
820
821 case MODFlags.shared_ | MODFlags.wild:
822 getMcache();
823 mcache.swto = t;
824 break;
825
826 case MODFlags.shared_ | MODFlags.wildconst:
827 getMcache();
828 mcache.swcto = t;
829 break;
830
831 case MODFlags.immutable_:
832 getMcache();
833 mcache.ito = t;
834 break;
835
836 default:
837 break;
838 }
839 }
840 assert(mod != t.mod);
841
842 if (mod)
843 {
844 getMcache();
845 t.getMcache();
846 }
847 switch (mod)
848 {
849 case 0:
850 break;
851
852 case MODFlags.const_:
853 mcache.cto = mto;
854 t.mcache.cto = this;
855 break;
856
857 case MODFlags.wild:
858 mcache.wto = mto;
859 t.mcache.wto = this;
860 break;
861
862 case MODFlags.wildconst:
863 mcache.wcto = mto;
864 t.mcache.wcto = this;
865 break;
866
867 case MODFlags.shared_:
868 mcache.sto = mto;
869 t.mcache.sto = this;
870 break;
871
872 case MODFlags.shared_ | MODFlags.const_:
873 mcache.scto = mto;
874 t.mcache.scto = this;
875 break;
876
877 case MODFlags.shared_ | MODFlags.wild:
878 mcache.swto = mto;
879 t.mcache.swto = this;
880 break;
881
882 case MODFlags.shared_ | MODFlags.wildconst:
883 mcache.swcto = mto;
884 t.mcache.swcto = this;
885 break;
886
887 case MODFlags.immutable_:
888 t.mcache.ito = this;
889 if (t.mcache.cto)
890 t.mcache.cto.getMcache().ito = this;
891 if (t.mcache.sto)
892 t.mcache.sto.getMcache().ito = this;
893 if (t.mcache.scto)
894 t.mcache.scto.getMcache().ito = this;
895 if (t.mcache.wto)
896 t.mcache.wto.getMcache().ito = this;
897 if (t.mcache.wcto)
898 t.mcache.wcto.getMcache().ito = this;
899 if (t.mcache.swto)
900 t.mcache.swto.getMcache().ito = this;
901 if (t.mcache.swcto)
902 t.mcache.swcto.getMcache().ito = this;
903 break;
904
905 default:
906 assert(0);
907 }
908
909 check();
910 t.check();
911 //printf("fixTo: %s, %s\n", toChars(), t.toChars());
912 }
913
914 /***************************
915 * Look for bugs in constructing types.
916 */
917 extern (D) final void check()
918 {
919 if (mcache)
920 with (mcache)
921 switch (mod)
922 {
923 case 0:
924 if (cto)
925 assert(cto.mod == MODFlags.const_);
926 if (ito)
927 assert(ito.mod == MODFlags.immutable_);
928 if (sto)
929 assert(sto.mod == MODFlags.shared_);
930 if (scto)
931 assert(scto.mod == (MODFlags.shared_ | MODFlags.const_));
932 if (wto)
933 assert(wto.mod == MODFlags.wild);
934 if (wcto)
935 assert(wcto.mod == MODFlags.wildconst);
936 if (swto)
937 assert(swto.mod == (MODFlags.shared_ | MODFlags.wild));
938 if (swcto)
939 assert(swcto.mod == (MODFlags.shared_ | MODFlags.wildconst));
940 break;
941
942 case MODFlags.const_:
943 if (cto)
944 assert(cto.mod == 0);
945 if (ito)
946 assert(ito.mod == MODFlags.immutable_);
947 if (sto)
948 assert(sto.mod == MODFlags.shared_);
949 if (scto)
950 assert(scto.mod == (MODFlags.shared_ | MODFlags.const_));
951 if (wto)
952 assert(wto.mod == MODFlags.wild);
953 if (wcto)
954 assert(wcto.mod == MODFlags.wildconst);
955 if (swto)
956 assert(swto.mod == (MODFlags.shared_ | MODFlags.wild));
957 if (swcto)
958 assert(swcto.mod == (MODFlags.shared_ | MODFlags.wildconst));
959 break;
960
961 case MODFlags.wild:
962 if (cto)
963 assert(cto.mod == MODFlags.const_);
964 if (ito)
965 assert(ito.mod == MODFlags.immutable_);
966 if (sto)
967 assert(sto.mod == MODFlags.shared_);
968 if (scto)
969 assert(scto.mod == (MODFlags.shared_ | MODFlags.const_));
970 if (wto)
971 assert(wto.mod == 0);
972 if (wcto)
973 assert(wcto.mod == MODFlags.wildconst);
974 if (swto)
975 assert(swto.mod == (MODFlags.shared_ | MODFlags.wild));
976 if (swcto)
977 assert(swcto.mod == (MODFlags.shared_ | MODFlags.wildconst));
978 break;
979
980 case MODFlags.wildconst:
981 assert(!cto || cto.mod == MODFlags.const_);
982 assert(!ito || ito.mod == MODFlags.immutable_);
983 assert(!sto || sto.mod == MODFlags.shared_);
984 assert(!scto || scto.mod == (MODFlags.shared_ | MODFlags.const_));
985 assert(!wto || wto.mod == MODFlags.wild);
986 assert(!wcto || wcto.mod == 0);
987 assert(!swto || swto.mod == (MODFlags.shared_ | MODFlags.wild));
988 assert(!swcto || swcto.mod == (MODFlags.shared_ | MODFlags.wildconst));
989 break;
990
991 case MODFlags.shared_:
992 if (cto)
993 assert(cto.mod == MODFlags.const_);
994 if (ito)
995 assert(ito.mod == MODFlags.immutable_);
996 if (sto)
997 assert(sto.mod == 0);
998 if (scto)
999 assert(scto.mod == (MODFlags.shared_ | MODFlags.const_));
1000 if (wto)
1001 assert(wto.mod == MODFlags.wild);
1002 if (wcto)
1003 assert(wcto.mod == MODFlags.wildconst);
1004 if (swto)
1005 assert(swto.mod == (MODFlags.shared_ | MODFlags.wild));
1006 if (swcto)
1007 assert(swcto.mod == (MODFlags.shared_ | MODFlags.wildconst));
1008 break;
1009
1010 case MODFlags.shared_ | MODFlags.const_:
1011 if (cto)
1012 assert(cto.mod == MODFlags.const_);
1013 if (ito)
1014 assert(ito.mod == MODFlags.immutable_);
1015 if (sto)
1016 assert(sto.mod == MODFlags.shared_);
1017 if (scto)
1018 assert(scto.mod == 0);
1019 if (wto)
1020 assert(wto.mod == MODFlags.wild);
1021 if (wcto)
1022 assert(wcto.mod == MODFlags.wildconst);
1023 if (swto)
1024 assert(swto.mod == (MODFlags.shared_ | MODFlags.wild));
1025 if (swcto)
1026 assert(swcto.mod == (MODFlags.shared_ | MODFlags.wildconst));
1027 break;
1028
1029 case MODFlags.shared_ | MODFlags.wild:
1030 if (cto)
1031 assert(cto.mod == MODFlags.const_);
1032 if (ito)
1033 assert(ito.mod == MODFlags.immutable_);
1034 if (sto)
1035 assert(sto.mod == MODFlags.shared_);
1036 if (scto)
1037 assert(scto.mod == (MODFlags.shared_ | MODFlags.const_));
1038 if (wto)
1039 assert(wto.mod == MODFlags.wild);
1040 if (wcto)
1041 assert(wcto.mod == MODFlags.wildconst);
1042 if (swto)
1043 assert(swto.mod == 0);
1044 if (swcto)
1045 assert(swcto.mod == (MODFlags.shared_ | MODFlags.wildconst));
1046 break;
1047
1048 case MODFlags.shared_ | MODFlags.wildconst:
1049 assert(!cto || cto.mod == MODFlags.const_);
1050 assert(!ito || ito.mod == MODFlags.immutable_);
1051 assert(!sto || sto.mod == MODFlags.shared_);
1052 assert(!scto || scto.mod == (MODFlags.shared_ | MODFlags.const_));
1053 assert(!wto || wto.mod == MODFlags.wild);
1054 assert(!wcto || wcto.mod == MODFlags.wildconst);
1055 assert(!swto || swto.mod == (MODFlags.shared_ | MODFlags.wild));
1056 assert(!swcto || swcto.mod == 0);
1057 break;
1058
1059 case MODFlags.immutable_:
1060 if (cto)
1061 assert(cto.mod == MODFlags.const_);
1062 if (ito)
1063 assert(ito.mod == 0);
1064 if (sto)
1065 assert(sto.mod == MODFlags.shared_);
1066 if (scto)
1067 assert(scto.mod == (MODFlags.shared_ | MODFlags.const_));
1068 if (wto)
1069 assert(wto.mod == MODFlags.wild);
1070 if (wcto)
1071 assert(wcto.mod == MODFlags.wildconst);
1072 if (swto)
1073 assert(swto.mod == (MODFlags.shared_ | MODFlags.wild));
1074 if (swcto)
1075 assert(swcto.mod == (MODFlags.shared_ | MODFlags.wildconst));
1076 break;
1077
1078 default:
1079 assert(0);
1080 }
1081
1082 Type tn = nextOf();
1083 if (tn && ty != Tfunction && tn.ty != Tfunction && ty != Tenum)
1084 {
1085 // Verify transitivity
1086 switch (mod)
1087 {
1088 case 0:
1089 case MODFlags.const_:
1090 case MODFlags.wild:
1091 case MODFlags.wildconst:
1092 case MODFlags.shared_:
1093 case MODFlags.shared_ | MODFlags.const_:
1094 case MODFlags.shared_ | MODFlags.wild:
1095 case MODFlags.shared_ | MODFlags.wildconst:
1096 case MODFlags.immutable_:
1097 assert(tn.mod == MODFlags.immutable_ || (tn.mod & mod) == mod);
1098 break;
1099
1100 default:
1101 assert(0);
1102 }
1103 tn.check();
1104 }
1105 }
1106
1107 /*************************************
1108 * Apply STCxxxx bits to existing type.
1109 * Use *before* semantic analysis is run.
1110 */
1111 extern (D) final Type addSTC(STC stc)
1112 {
1113 Type t = this;
1114 if (t.isImmutable())
1115 {
1116 return t;
1117 }
1118 else if (stc & STC.immutable_)
1119 {
1120 t = t.makeImmutable();
1121 return t;
1122 }
1123
1124 if ((stc & STC.shared_) && !t.isShared())
1125 {
1126 if (t.isWild())
1127 {
1128 if (t.isConst())
1129 t = t.makeSharedWildConst();
1130 else
1131 t = t.makeSharedWild();
1132 }
1133 else
1134 {
1135 if (t.isConst())
1136 t = t.makeSharedConst();
1137 else
1138 t = t.makeShared();
1139 }
1140 }
1141 if ((stc & STC.const_) && !t.isConst())
1142 {
1143 if (t.isShared())
1144 {
1145 if (t.isWild())
1146 t = t.makeSharedWildConst();
1147 else
1148 t = t.makeSharedConst();
1149 }
1150 else
1151 {
1152 if (t.isWild())
1153 t = t.makeWildConst();
1154 else
1155 t = t.makeConst();
1156 }
1157 }
1158 if ((stc & STC.wild) && !t.isWild())
1159 {
1160 if (t.isShared())
1161 {
1162 if (t.isConst())
1163 t = t.makeSharedWildConst();
1164 else
1165 t = t.makeSharedWild();
1166 }
1167 else
1168 {
1169 if (t.isConst())
1170 t = t.makeWildConst();
1171 else
1172 t = t.makeWild();
1173 }
1174 }
1175
1176 return t;
1177 }
1178
1179 final bool hasDeprecatedAliasThis()
1180 {
1181 auto ad = isAggregate(this);
1182 return ad && ad.aliasthis && (ad.aliasthis.isDeprecated || ad.aliasthis.sym.isDeprecated);
1183 }
1184
1185 Type makeConst()
1186 {
1187 //printf("Type::makeConst() %p, %s\n", this, toChars());
1188 if (mcache && mcache.cto)
1189 return mcache.cto;
1190 Type t = this.nullAttributes();
1191 t.mod = MODFlags.const_;
1192 //printf("-Type::makeConst() %p, %s\n", t, toChars());
1193 return t;
1194 }
1195
1196 Type makeImmutable()
1197 {
1198 if (mcache && mcache.ito)
1199 return mcache.ito;
1200 Type t = this.nullAttributes();
1201 t.mod = MODFlags.immutable_;
1202 return t;
1203 }
1204
1205 Type makeShared()
1206 {
1207 if (mcache && mcache.sto)
1208 return mcache.sto;
1209 Type t = this.nullAttributes();
1210 t.mod = MODFlags.shared_;
1211 return t;
1212 }
1213
1214 Type makeSharedConst()
1215 {
1216 if (mcache && mcache.scto)
1217 return mcache.scto;
1218 Type t = this.nullAttributes();
1219 t.mod = MODFlags.shared_ | MODFlags.const_;
1220 return t;
1221 }
1222
1223 Type makeWild()
1224 {
1225 if (mcache && mcache.wto)
1226 return mcache.wto;
1227 Type t = this.nullAttributes();
1228 t.mod = MODFlags.wild;
1229 return t;
1230 }
1231
1232 Type makeWildConst()
1233 {
1234 if (mcache && mcache.wcto)
1235 return mcache.wcto;
1236 Type t = this.nullAttributes();
1237 t.mod = MODFlags.wildconst;
1238 return t;
1239 }
1240
1241 Type makeSharedWild()
1242 {
1243 if (mcache && mcache.swto)
1244 return mcache.swto;
1245 Type t = this.nullAttributes();
1246 t.mod = MODFlags.shared_ | MODFlags.wild;
1247 return t;
1248 }
1249
1250 Type makeSharedWildConst()
1251 {
1252 if (mcache && mcache.swcto)
1253 return mcache.swcto;
1254 Type t = this.nullAttributes();
1255 t.mod = MODFlags.shared_ | MODFlags.wildconst;
1256 return t;
1257 }
1258
1259 Type makeMutable()
1260 {
1261 Type t = this.nullAttributes();
1262 t.mod = mod & MODFlags.shared_;
1263 return t;
1264 }
1265
1266 /*******************************
1267 * If this is a shell around another type,
1268 * get that other type.
1269 */
1270 final Type toBasetype()
1271 {
1272 /* This function is used heavily.
1273 * De-virtualize it so it can be easily inlined.
1274 */
1275 TypeEnum te;
1276 return ((te = isTypeEnum()) !is null) ? te.toBasetype2() : this;
1277 }
1278
1279 /***************************************
1280 * Compute MOD bits matching `this` argument type to wild parameter type.
1281 * Params:
1282 * t = corresponding parameter type
1283 * isRef = parameter is `ref` or `out`
1284 * Returns:
1285 * MOD bits
1286 */
1287 MOD deduceWild(Type t, bool isRef)
1288 {
1289 //printf("Type::deduceWild this = '%s', tprm = '%s'\n", toChars(), tprm.toChars());
1290 if (t.isWild())
1291 {
1292 if (isImmutable())
1293 return MODFlags.immutable_;
1294 if (isWildConst())
1295 {
1296 if (t.isWildConst())
1297 return MODFlags.wild;
1298 return MODFlags.wildconst;
1299 }
1300 if (isWild())
1301 return MODFlags.wild;
1302 if (isConst())
1303 return MODFlags.const_;
1304 if (isMutable())
1305 return MODFlags.mutable;
1306 assert(0);
1307 }
1308 return 0;
1309 }
1310
1311 inout(ClassDeclaration) isClassHandle() inout
1312 {
1313 return null;
1314 }
1315
1316 /************************************
1317 * Return alignment to use for this type.
1318 */
1319 structalign_t alignment()
1320 {
1321 structalign_t s;
1322 s.setDefault();
1323 return s;
1324 }
1325
1326 /***************************************
1327 * Use when we prefer the default initializer to be a literal,
1328 * rather than a global immutable variable.
1329 */
1330 Expression defaultInitLiteral(Loc loc)
1331 {
1332 static if (LOGDEFAULTINIT)
1333 {
1334 printf("Type::defaultInitLiteral() '%s'\n", toChars());
1335 }
1336 return defaultInit(this, loc);
1337 }
1338
1339 /***************************************
1340 * Return !=0 if the type or any of its subtypes is wild.
1341 */
1342 int hasWild() const
1343 {
1344 return mod & MODFlags.wild;
1345 }
1346
1347 /*************************************
1348 * Detect if type has pointer fields that are initialized to void.
1349 * Local stack variables with such void fields can remain uninitialized,
1350 * leading to pointer bugs.
1351 * Returns:
1352 * true if so
1353 */
1354 bool hasVoidInitPointers()
1355 {
1356 return false;
1357 }
1358
1359 /*************************************
1360 * Detect if this is an unsafe type because of the presence of `@system` members
1361 * Returns:
1362 * true if so
1363 */
1364 bool hasUnsafeBitpatterns()
1365 {
1366 return false;
1367 }
1368
1369 /***************************************
1370 * Returns: true if type has any invariants
1371 */
1372 bool hasInvariant()
1373 {
1374 //printf("Type::hasInvariant() %s, %d\n", toChars(), ty);
1375 return false;
1376 }
1377
1378 /*************************************
1379 * If this is a type of something, return that something.
1380 */
1381 Type nextOf()
1382 {
1383 return null;
1384 }
1385
1386 /*************************************
1387 * If this is a type of static array, return its base element type.
1388 */
1389 final Type baseElemOf()
1390 {
1391 Type t = toBasetype();
1392 TypeSArray tsa;
1393 while ((tsa = t.isTypeSArray()) !is null)
1394 t = tsa.next.toBasetype();
1395 return t;
1396 }
1397
1398 /****************************************
1399 * Return the mask that an integral type will
1400 * fit into.
1401 */
1402 extern (D) final uinteger_t sizemask()
1403 {
1404 uinteger_t m;
1405 switch (toBasetype().ty)
1406 {
1407 case Tbool:
1408 m = 1;
1409 break;
1410 case Tchar:
1411 case Tint8:
1412 case Tuns8:
1413 m = 0xFF;
1414 break;
1415 case Twchar:
1416 case Tint16:
1417 case Tuns16:
1418 m = 0xFFFFU;
1419 break;
1420 case Tdchar:
1421 case Tint32:
1422 case Tuns32:
1423 m = 0xFFFFFFFFU;
1424 break;
1425 case Tint64:
1426 case Tuns64:
1427 m = 0xFFFFFFFFFFFFFFFFUL;
1428 break;
1429 default:
1430 assert(0);
1431 }
1432 return m;
1433 }
1434
1435 /********************************
1436 * true if when type goes out of scope, it needs a destructor applied.
1437 * Only applies to value types, not ref types.
1438 */
1439 bool needsDestruction()
1440 {
1441 return false;
1442 }
1443
1444 /********************************
1445 * true if when type is copied, it needs a copy constructor or postblit
1446 * applied. Only applies to value types, not ref types.
1447 */
1448 bool needsCopyOrPostblit()
1449 {
1450 return false;
1451 }
1452
1453 /*********************************
1454 *
1455 */
1456 bool needsNested()
1457 {
1458 return false;
1459 }
1460
1461 // For eliminating dynamic_cast
1462 TypeBasic isTypeBasic()
1463 {
1464 return null;
1465 }
1466
1467 final pure inout nothrow @nogc
1468 {
1469 /****************
1470 * Is this type a pointer to a function?
1471 * Returns:
1472 * the function type if it is
1473 */
1474 inout(TypeFunction) isPtrToFunction()
1475 {
1476 return (ty == Tpointer && (cast(TypePointer)this).next.ty == Tfunction)
1477 ? cast(typeof(return))(cast(TypePointer)this).next
1478 : null;
1479 }
1480
1481 /*****************
1482 * Is this type a function, delegate, or pointer to a function?
1483 * Returns:
1484 * the function type if it is
1485 */
1486 inout(TypeFunction) isFunction_Delegate_PtrToFunction()
1487 {
1488 return ty == Tfunction ? cast(typeof(return))this :
1489
1490 ty == Tdelegate ? cast(typeof(return))(cast(TypePointer)this).next :
1491
1492 ty == Tpointer && (cast(TypePointer)this).next.ty == Tfunction ?
1493 cast(typeof(return))(cast(TypePointer)this).next :
1494
1495 null;
1496 }
1497 }
1498
1499 final pure inout nothrow @nogc @trusted
1500 {
1501 inout(TypeError) isTypeError() { return ty == Terror ? cast(typeof(return))this : null; }
1502 inout(TypeVector) isTypeVector() { return ty == Tvector ? cast(typeof(return))this : null; }
1503 inout(TypeSArray) isTypeSArray() { return ty == Tsarray ? cast(typeof(return))this : null; }
1504 inout(TypeDArray) isTypeDArray() { return ty == Tarray ? cast(typeof(return))this : null; }
1505 inout(TypeAArray) isTypeAArray() { return ty == Taarray ? cast(typeof(return))this : null; }
1506 inout(TypePointer) isTypePointer() { return ty == Tpointer ? cast(typeof(return))this : null; }
1507 inout(TypeReference) isTypeReference() { return ty == Treference ? cast(typeof(return))this : null; }
1508 inout(TypeFunction) isTypeFunction() { return ty == Tfunction ? cast(typeof(return))this : null; }
1509 inout(TypeDelegate) isTypeDelegate() { return ty == Tdelegate ? cast(typeof(return))this : null; }
1510 inout(TypeIdentifier) isTypeIdentifier() { return ty == Tident ? cast(typeof(return))this : null; }
1511 inout(TypeInstance) isTypeInstance() { return ty == Tinstance ? cast(typeof(return))this : null; }
1512 inout(TypeTypeof) isTypeTypeof() { return ty == Ttypeof ? cast(typeof(return))this : null; }
1513 inout(TypeReturn) isTypeReturn() { return ty == Treturn ? cast(typeof(return))this : null; }
1514 inout(TypeStruct) isTypeStruct() { return ty == Tstruct ? cast(typeof(return))this : null; }
1515 inout(TypeEnum) isTypeEnum() { return ty == Tenum ? cast(typeof(return))this : null; }
1516 inout(TypeClass) isTypeClass() { return ty == Tclass ? cast(typeof(return))this : null; }
1517 inout(TypeTuple) isTypeTuple() { return ty == Ttuple ? cast(typeof(return))this : null; }
1518 inout(TypeSlice) isTypeSlice() { return ty == Tslice ? cast(typeof(return))this : null; }
1519 inout(TypeNull) isTypeNull() { return ty == Tnull ? cast(typeof(return))this : null; }
1520 inout(TypeMixin) isTypeMixin() { return ty == Tmixin ? cast(typeof(return))this : null; }
1521 inout(TypeTraits) isTypeTraits() { return ty == Ttraits ? cast(typeof(return))this : null; }
1522 inout(TypeNoreturn) isTypeNoreturn() { return ty == Tnoreturn ? cast(typeof(return))this : null; }
1523 inout(TypeTag) isTypeTag() { return ty == Ttag ? cast(typeof(return))this : null; }
1524
1525 extern (D) bool isStaticOrDynamicArray() const { return ty == Tarray || ty == Tsarray; }
1526 }
1527
1528 override void accept(Visitor v)
1529 {
1530 v.visit(this);
1531 }
1532
1533 final TypeFunction toTypeFunction()
1534 {
1535 if (ty != Tfunction)
1536 assert(0);
1537 return cast(TypeFunction)this;
1538 }
1539
1540 extern (D) static Types* arraySyntaxCopy(Types* types)
1541 {
1542 Types* a = null;
1543 if (types)
1544 {
1545 a = new Types(types.length);
1546 foreach (i, t; *types)
1547 {
1548 (*a)[i] = t ? t.syntaxCopy() : null;
1549 }
1550 }
1551 return a;
1552 }
1553 }
1554
1555 /***********************************************************
1556 */
1557 extern (C++) final class TypeError : Type
1558 {
1559 extern (D) this() @safe
1560 {
1561 super(Terror);
1562 }
1563
1564 override const(char)* kind() const
1565 {
1566 return "error";
1567 }
1568
1569 override TypeError syntaxCopy()
1570 {
1571 // No semantic analysis done, no need to copy
1572 return this;
1573 }
1574
1575 override Expression defaultInitLiteral(Loc loc)
1576 {
1577 return ErrorExp.get();
1578 }
1579
1580 override void accept(Visitor v)
1581 {
1582 v.visit(this);
1583 }
1584 }
1585
1586 /***********************************************************
1587 */
1588 extern (C++) abstract class TypeNext : Type
1589 {
1590 Type next;
1591
1592 final extern (D) this(TY ty, Type next) @safe
1593 {
1594 super(ty);
1595 this.next = next;
1596 }
1597
1598 override final int hasWild() const
1599 {
1600 if (ty == Tfunction)
1601 return 0;
1602 if (ty == Tdelegate)
1603 return Type.hasWild();
1604 return mod & MODFlags.wild || (next && next.hasWild());
1605 }
1606
1607 /*******************************
1608 * For TypeFunction, nextOf() can return NULL if the function return
1609 * type is meant to be inferred, and semantic() hasn't yet been run
1610 * on the function. After semantic(), it must no longer be NULL.
1611 */
1612 override final Type nextOf() @safe
1613 {
1614 return next;
1615 }
1616
1617 override final Type makeConst()
1618 {
1619 //printf("TypeNext::makeConst() %p, %s\n", this, toChars());
1620 if (mcache && mcache.cto)
1621 {
1622 assert(mcache.cto.mod == MODFlags.const_);
1623 return mcache.cto;
1624 }
1625 TypeNext t = cast(TypeNext)Type.makeConst();
1626 if (ty != Tfunction && next.ty != Tfunction && !next.isImmutable())
1627 {
1628 if (next.isShared())
1629 {
1630 if (next.isWild())
1631 t.next = next.sharedWildConstOf();
1632 else
1633 t.next = next.sharedConstOf();
1634 }
1635 else
1636 {
1637 if (next.isWild())
1638 t.next = next.wildConstOf();
1639 else
1640 t.next = next.constOf();
1641 }
1642 }
1643 //printf("TypeNext::makeConst() returns %p, %s\n", t, t.toChars());
1644 return t;
1645 }
1646
1647 override final Type makeImmutable()
1648 {
1649 //printf("TypeNext::makeImmutable() %s\n", toChars());
1650 if (mcache && mcache.ito)
1651 {
1652 assert(mcache.ito.isImmutable());
1653 return mcache.ito;
1654 }
1655 TypeNext t = cast(TypeNext)Type.makeImmutable();
1656 if (ty != Tfunction && next.ty != Tfunction && !next.isImmutable())
1657 {
1658 t.next = next.immutableOf();
1659 }
1660 return t;
1661 }
1662
1663 override final Type makeShared()
1664 {
1665 //printf("TypeNext::makeShared() %s\n", toChars());
1666 if (mcache && mcache.sto)
1667 {
1668 assert(mcache.sto.mod == MODFlags.shared_);
1669 return mcache.sto;
1670 }
1671 TypeNext t = cast(TypeNext)Type.makeShared();
1672 if (ty != Tfunction && next.ty != Tfunction && !next.isImmutable())
1673 {
1674 if (next.isWild())
1675 {
1676 if (next.isConst())
1677 t.next = next.sharedWildConstOf();
1678 else
1679 t.next = next.sharedWildOf();
1680 }
1681 else
1682 {
1683 if (next.isConst())
1684 t.next = next.sharedConstOf();
1685 else
1686 t.next = next.sharedOf();
1687 }
1688 }
1689 //printf("TypeNext::makeShared() returns %p, %s\n", t, t.toChars());
1690 return t;
1691 }
1692
1693 override final Type makeSharedConst()
1694 {
1695 //printf("TypeNext::makeSharedConst() %s\n", toChars());
1696 if (mcache && mcache.scto)
1697 {
1698 assert(mcache.scto.mod == (MODFlags.shared_ | MODFlags.const_));
1699 return mcache.scto;
1700 }
1701 TypeNext t = cast(TypeNext)Type.makeSharedConst();
1702 if (ty != Tfunction && next.ty != Tfunction && !next.isImmutable())
1703 {
1704 if (next.isWild())
1705 t.next = next.sharedWildConstOf();
1706 else
1707 t.next = next.sharedConstOf();
1708 }
1709 //printf("TypeNext::makeSharedConst() returns %p, %s\n", t, t.toChars());
1710 return t;
1711 }
1712
1713 override final Type makeWild()
1714 {
1715 //printf("TypeNext::makeWild() %s\n", toChars());
1716 if (mcache && mcache.wto)
1717 {
1718 assert(mcache.wto.mod == MODFlags.wild);
1719 return mcache.wto;
1720 }
1721 TypeNext t = cast(TypeNext)Type.makeWild();
1722 if (ty != Tfunction && next.ty != Tfunction && !next.isImmutable())
1723 {
1724 if (next.isShared())
1725 {
1726 if (next.isConst())
1727 t.next = next.sharedWildConstOf();
1728 else
1729 t.next = next.sharedWildOf();
1730 }
1731 else
1732 {
1733 if (next.isConst())
1734 t.next = next.wildConstOf();
1735 else
1736 t.next = next.wildOf();
1737 }
1738 }
1739 //printf("TypeNext::makeWild() returns %p, %s\n", t, t.toChars());
1740 return t;
1741 }
1742
1743 override final Type makeWildConst()
1744 {
1745 //printf("TypeNext::makeWildConst() %s\n", toChars());
1746 if (mcache && mcache.wcto)
1747 {
1748 assert(mcache.wcto.mod == MODFlags.wildconst);
1749 return mcache.wcto;
1750 }
1751 TypeNext t = cast(TypeNext)Type.makeWildConst();
1752 if (ty != Tfunction && next.ty != Tfunction && !next.isImmutable())
1753 {
1754 if (next.isShared())
1755 t.next = next.sharedWildConstOf();
1756 else
1757 t.next = next.wildConstOf();
1758 }
1759 //printf("TypeNext::makeWildConst() returns %p, %s\n", t, t.toChars());
1760 return t;
1761 }
1762
1763 override final Type makeSharedWild()
1764 {
1765 //printf("TypeNext::makeSharedWild() %s\n", toChars());
1766 if (mcache && mcache.swto)
1767 {
1768 assert(mcache.swto.isSharedWild());
1769 return mcache.swto;
1770 }
1771 TypeNext t = cast(TypeNext)Type.makeSharedWild();
1772 if (ty != Tfunction && next.ty != Tfunction && !next.isImmutable())
1773 {
1774 if (next.isConst())
1775 t.next = next.sharedWildConstOf();
1776 else
1777 t.next = next.sharedWildOf();
1778 }
1779 //printf("TypeNext::makeSharedWild() returns %p, %s\n", t, t.toChars());
1780 return t;
1781 }
1782
1783 override final Type makeSharedWildConst()
1784 {
1785 //printf("TypeNext::makeSharedWildConst() %s\n", toChars());
1786 if (mcache && mcache.swcto)
1787 {
1788 assert(mcache.swcto.mod == (MODFlags.shared_ | MODFlags.wildconst));
1789 return mcache.swcto;
1790 }
1791 TypeNext t = cast(TypeNext)Type.makeSharedWildConst();
1792 if (ty != Tfunction && next.ty != Tfunction && !next.isImmutable())
1793 {
1794 t.next = next.sharedWildConstOf();
1795 }
1796 //printf("TypeNext::makeSharedWildConst() returns %p, %s\n", t, t.toChars());
1797 return t;
1798 }
1799
1800 override final Type makeMutable()
1801 {
1802 //printf("TypeNext::makeMutable() %p, %s\n", this, toChars());
1803 TypeNext t = cast(TypeNext)Type.makeMutable();
1804 if (ty == Tsarray)
1805 {
1806 t.next = next.mutableOf();
1807 }
1808 //printf("TypeNext::makeMutable() returns %p, %s\n", t, t.toChars());
1809 return t;
1810 }
1811
1812 override final MOD deduceWild(Type t, bool isRef)
1813 {
1814 if (ty == Tfunction)
1815 return 0;
1816
1817 ubyte wm;
1818
1819 Type tn = t.nextOf();
1820 if (!isRef && (ty == Tarray || ty == Tpointer) && tn)
1821 {
1822 wm = next.deduceWild(tn, true);
1823 if (!wm)
1824 wm = Type.deduceWild(t, true);
1825 }
1826 else
1827 {
1828 wm = Type.deduceWild(t, isRef);
1829 if (!wm && tn)
1830 wm = next.deduceWild(tn, true);
1831 }
1832
1833 return wm;
1834 }
1835
1836 final void transitive()
1837 {
1838 /* Invoke transitivity of type attributes
1839 */
1840 next = next.addMod(mod);
1841 }
1842
1843 override void accept(Visitor v)
1844 {
1845 v.visit(this);
1846 }
1847 }
1848
1849 /***********************************************************
1850 */
1851 extern (C++) final class TypeBasic : Type
1852 {
1853 const(char)* dstring;
1854 uint flags;
1855
1856 extern (D) this(TY ty) scope
1857 {
1858 super(ty);
1859 const(char)* d;
1860 uint flags = 0;
1861 switch (ty)
1862 {
1863 case Tvoid:
1864 d = Token.toChars(TOK.void_);
1865 break;
1866
1867 case Tint8:
1868 d = Token.toChars(TOK.int8);
1869 flags |= TFlags.integral;
1870 break;
1871
1872 case Tuns8:
1873 d = Token.toChars(TOK.uns8);
1874 flags |= TFlags.integral | TFlags.unsigned;
1875 break;
1876
1877 case Tint16:
1878 d = Token.toChars(TOK.int16);
1879 flags |= TFlags.integral;
1880 break;
1881
1882 case Tuns16:
1883 d = Token.toChars(TOK.uns16);
1884 flags |= TFlags.integral | TFlags.unsigned;
1885 break;
1886
1887 case Tint32:
1888 d = Token.toChars(TOK.int32);
1889 flags |= TFlags.integral;
1890 break;
1891
1892 case Tuns32:
1893 d = Token.toChars(TOK.uns32);
1894 flags |= TFlags.integral | TFlags.unsigned;
1895 break;
1896
1897 case Tfloat32:
1898 d = Token.toChars(TOK.float32);
1899 flags |= TFlags.floating | TFlags.real_;
1900 break;
1901
1902 case Tint64:
1903 d = Token.toChars(TOK.int64);
1904 flags |= TFlags.integral;
1905 break;
1906
1907 case Tuns64:
1908 d = Token.toChars(TOK.uns64);
1909 flags |= TFlags.integral | TFlags.unsigned;
1910 break;
1911
1912 case Tint128:
1913 d = Token.toChars(TOK.int128);
1914 flags |= TFlags.integral;
1915 break;
1916
1917 case Tuns128:
1918 d = Token.toChars(TOK.uns128);
1919 flags |= TFlags.integral | TFlags.unsigned;
1920 break;
1921
1922 case Tfloat64:
1923 d = Token.toChars(TOK.float64);
1924 flags |= TFlags.floating | TFlags.real_;
1925 break;
1926
1927 case Tfloat80:
1928 d = Token.toChars(TOK.float80);
1929 flags |= TFlags.floating | TFlags.real_;
1930 break;
1931
1932 case Timaginary32:
1933 d = Token.toChars(TOK.imaginary32);
1934 flags |= TFlags.floating | TFlags.imaginary;
1935 break;
1936
1937 case Timaginary64:
1938 d = Token.toChars(TOK.imaginary64);
1939 flags |= TFlags.floating | TFlags.imaginary;
1940 break;
1941
1942 case Timaginary80:
1943 d = Token.toChars(TOK.imaginary80);
1944 flags |= TFlags.floating | TFlags.imaginary;
1945 break;
1946
1947 case Tcomplex32:
1948 d = Token.toChars(TOK.complex32);
1949 flags |= TFlags.floating | TFlags.complex;
1950 break;
1951
1952 case Tcomplex64:
1953 d = Token.toChars(TOK.complex64);
1954 flags |= TFlags.floating | TFlags.complex;
1955 break;
1956
1957 case Tcomplex80:
1958 d = Token.toChars(TOK.complex80);
1959 flags |= TFlags.floating | TFlags.complex;
1960 break;
1961
1962 case Tbool:
1963 d = "bool";
1964 flags |= TFlags.integral | TFlags.unsigned;
1965 break;
1966
1967 case Tchar:
1968 d = Token.toChars(TOK.char_);
1969 flags |= TFlags.integral | TFlags.unsigned;
1970 break;
1971
1972 case Twchar:
1973 d = Token.toChars(TOK.wchar_);
1974 flags |= TFlags.integral | TFlags.unsigned;
1975 break;
1976
1977 case Tdchar:
1978 d = Token.toChars(TOK.dchar_);
1979 flags |= TFlags.integral | TFlags.unsigned;
1980 break;
1981
1982 default:
1983 assert(0);
1984 }
1985 this.dstring = d;
1986 this.flags = flags;
1987 merge(this);
1988 }
1989
1990 override const(char)* kind() const
1991 {
1992 return dstring;
1993 }
1994
1995 override TypeBasic syntaxCopy()
1996 {
1997 // No semantic analysis done on basic types, no need to copy
1998 return this;
1999 }
2000
2001 override uint alignsize()
2002 {
2003 return target.alignsize(this);
2004 }
2005
2006 override bool isIntegral()
2007 {
2008 //printf("TypeBasic::isIntegral('%s') x%x\n", toChars(), flags);
2009 return (flags & TFlags.integral) != 0;
2010 }
2011
2012 override bool isFloating()
2013 {
2014 return (flags & TFlags.floating) != 0;
2015 }
2016
2017 override bool isReal()
2018 {
2019 return (flags & TFlags.real_) != 0;
2020 }
2021
2022 override bool isImaginary()
2023 {
2024 return (flags & TFlags.imaginary) != 0;
2025 }
2026
2027 override bool isComplex()
2028 {
2029 return (flags & TFlags.complex) != 0;
2030 }
2031
2032 override bool isScalar()
2033 {
2034 return (flags & (TFlags.integral | TFlags.floating)) != 0;
2035 }
2036
2037 override bool isUnsigned()
2038 {
2039 return (flags & TFlags.unsigned) != 0;
2040 }
2041
2042 override bool hasUnsafeBitpatterns()
2043 {
2044 return ty == Tbool;
2045 }
2046
2047 // For eliminating dynamic_cast
2048 override TypeBasic isTypeBasic()
2049 {
2050 return this;
2051 }
2052
2053 override void accept(Visitor v)
2054 {
2055 v.visit(this);
2056 }
2057 }
2058
2059 /***********************************************************
2060 * The basetype must be one of:
2061 * byte[16],ubyte[16],short[8],ushort[8],int[4],uint[4],long[2],ulong[2],float[4],double[2]
2062 * For AVX:
2063 * byte[32],ubyte[32],short[16],ushort[16],int[8],uint[8],long[4],ulong[4],float[8],double[4]
2064 */
2065 extern (C++) final class TypeVector : Type
2066 {
2067 Type basetype;
2068
2069 extern (D) this(Type basetype) @safe
2070 {
2071 super(Tvector);
2072 this.basetype = basetype;
2073 }
2074
2075 static TypeVector create(Type basetype) @safe
2076 {
2077 return new TypeVector(basetype);
2078 }
2079
2080 override const(char)* kind() const
2081 {
2082 return "vector";
2083 }
2084
2085 override TypeVector syntaxCopy()
2086 {
2087 return new TypeVector(basetype.syntaxCopy());
2088 }
2089
2090 override uint alignsize()
2091 {
2092 return cast(uint)basetype.size();
2093 }
2094
2095 override bool isIntegral()
2096 {
2097 //printf("TypeVector::isIntegral('%s') x%x\n", toChars(), flags);
2098 return basetype.nextOf().isIntegral();
2099 }
2100
2101 override bool isFloating()
2102 {
2103 return basetype.nextOf().isFloating();
2104 }
2105
2106 override bool isScalar()
2107 {
2108 return basetype.nextOf().isScalar();
2109 }
2110
2111 override bool isUnsigned()
2112 {
2113 return basetype.nextOf().isUnsigned();
2114 }
2115
2116 override bool isBoolean()
2117 {
2118 return false;
2119 }
2120
2121 override Expression defaultInitLiteral(Loc loc)
2122 {
2123 //printf("TypeVector::defaultInitLiteral()\n");
2124 assert(basetype.ty == Tsarray);
2125 Expression e = basetype.defaultInitLiteral(loc);
2126 auto ve = new VectorExp(loc, e, this);
2127 ve.type = this;
2128 ve.dim = cast(int)(basetype.size(loc) / elementType().size(loc));
2129 return ve;
2130 }
2131
2132 TypeBasic elementType()
2133 {
2134 assert(basetype.ty == Tsarray);
2135 TypeSArray t = cast(TypeSArray)basetype;
2136 TypeBasic tb = t.nextOf().isTypeBasic();
2137 assert(tb);
2138 return tb;
2139 }
2140
2141 override void accept(Visitor v)
2142 {
2143 v.visit(this);
2144 }
2145 }
2146
2147 /***********************************************************
2148 */
2149 extern (C++) abstract class TypeArray : TypeNext
2150 {
2151 final extern (D) this(TY ty, Type next) @safe
2152 {
2153 super(ty, next);
2154 }
2155
2156 override void accept(Visitor v)
2157 {
2158 v.visit(this);
2159 }
2160 }
2161
2162 /***********************************************************
2163 * Static array, one with a fixed dimension
2164 */
2165 extern (C++) final class TypeSArray : TypeArray
2166 {
2167 Expression dim;
2168
2169 extern (D) this(Type t, Expression dim) @safe
2170 {
2171 super(Tsarray, t);
2172 //printf("TypeSArray(%s)\n", dim.toChars());
2173 this.dim = dim;
2174 }
2175
2176 extern (D) this(Type t) // for incomplete type
2177 {
2178 super(Tsarray, t);
2179 //printf("TypeSArray()\n");
2180 this.dim = new IntegerExp(0);
2181 }
2182
2183 override const(char)* kind() const
2184 {
2185 return "sarray";
2186 }
2187
2188 override TypeSArray syntaxCopy()
2189 {
2190 Type t = next.syntaxCopy();
2191 Expression e = dim.syntaxCopy();
2192 auto result = new TypeSArray(t, e);
2193 result.mod = mod;
2194 return result;
2195 }
2196
2197 /***
2198 * C11 6.7.6.2-4 incomplete array type
2199 * Returns: true if incomplete type
2200 */
2201 bool isIncomplete()
2202 {
2203 return dim.isIntegerExp() && dim.isIntegerExp().getInteger() == 0;
2204 }
2205
2206 override uint alignsize()
2207 {
2208 return next.alignsize();
2209 }
2210
2211 override bool isString()
2212 {
2213 TY nty = next.toBasetype().ty;
2214 return nty.isSomeChar;
2215 }
2216
2217 override structalign_t alignment()
2218 {
2219 return next.alignment();
2220 }
2221
2222 override Expression defaultInitLiteral(Loc loc)
2223 {
2224 static if (LOGDEFAULTINIT)
2225 {
2226 printf("TypeSArray::defaultInitLiteral() '%s'\n", toChars());
2227 }
2228 size_t d = cast(size_t)dim.toInteger();
2229 Expression elementinit;
2230 if (next.ty == Tvoid)
2231 elementinit = tuns8.defaultInitLiteral(loc);
2232 else
2233 elementinit = next.defaultInitLiteral(loc);
2234 auto elements = new Expressions(d);
2235 foreach (ref e; *elements)
2236 e = null;
2237 auto ae = new ArrayLiteralExp(Loc.initial, this, elementinit, elements);
2238 return ae;
2239 }
2240
2241 override bool hasUnsafeBitpatterns()
2242 {
2243 return next.hasUnsafeBitpatterns();
2244 }
2245
2246 override bool hasVoidInitPointers()
2247 {
2248 return next.hasVoidInitPointers();
2249 }
2250
2251 override bool hasInvariant()
2252 {
2253 return next.hasInvariant();
2254 }
2255
2256 override bool needsDestruction()
2257 {
2258 return next.needsDestruction();
2259 }
2260
2261 override bool needsCopyOrPostblit()
2262 {
2263 return next.needsCopyOrPostblit();
2264 }
2265
2266 /*********************************
2267 *
2268 */
2269 override bool needsNested()
2270 {
2271 return next.needsNested();
2272 }
2273
2274 override void accept(Visitor v)
2275 {
2276 v.visit(this);
2277 }
2278 }
2279
2280 /***********************************************************
2281 * Dynamic array, no dimension
2282 */
2283 extern (C++) final class TypeDArray : TypeArray
2284 {
2285 extern (D) this(Type t) @safe
2286 {
2287 super(Tarray, t);
2288 //printf("TypeDArray(t = %p)\n", t);
2289 }
2290
2291 override const(char)* kind() const
2292 {
2293 return "darray";
2294 }
2295
2296 override TypeDArray syntaxCopy()
2297 {
2298 Type t = next.syntaxCopy();
2299 if (t == next)
2300 return this;
2301
2302 auto result = new TypeDArray(t);
2303 result.mod = mod;
2304 return result;
2305 }
2306
2307 override uint alignsize()
2308 {
2309 // A DArray consists of two ptr-sized values, so align it on pointer size
2310 // boundary
2311 return target.ptrsize;
2312 }
2313
2314 override bool isString()
2315 {
2316 TY nty = next.toBasetype().ty;
2317 return nty.isSomeChar;
2318 }
2319
2320 override bool isBoolean()
2321 {
2322 return true;
2323 }
2324
2325 override void accept(Visitor v)
2326 {
2327 v.visit(this);
2328 }
2329 }
2330
2331 /***********************************************************
2332 */
2333 extern (C++) final class TypeAArray : TypeArray
2334 {
2335 Type index; // key type
2336 Loc loc;
2337
2338 extern (D) this(Type t, Type index) @safe
2339 {
2340 super(Taarray, t);
2341 this.index = index;
2342 }
2343
2344 static TypeAArray create(Type t, Type index) @safe
2345 {
2346 return new TypeAArray(t, index);
2347 }
2348
2349 override const(char)* kind() const
2350 {
2351 return "aarray";
2352 }
2353
2354 override TypeAArray syntaxCopy()
2355 {
2356 Type t = next.syntaxCopy();
2357 Type ti = index.syntaxCopy();
2358 if (t == next && ti == index)
2359 return this;
2360
2361 auto result = new TypeAArray(t, ti);
2362 result.mod = mod;
2363 return result;
2364 }
2365
2366 override bool isBoolean()
2367 {
2368 return true;
2369 }
2370
2371 override void accept(Visitor v)
2372 {
2373 v.visit(this);
2374 }
2375 }
2376
2377 /***********************************************************
2378 */
2379 extern (C++) final class TypePointer : TypeNext
2380 {
2381 extern (D) this(Type t) @safe
2382 {
2383 super(Tpointer, t);
2384 }
2385
2386 static TypePointer create(Type t) @safe
2387 {
2388 return new TypePointer(t);
2389 }
2390
2391 override const(char)* kind() const
2392 {
2393 return "pointer";
2394 }
2395
2396 override TypePointer syntaxCopy()
2397 {
2398 Type t = next.syntaxCopy();
2399 if (t == next)
2400 return this;
2401
2402 auto result = new TypePointer(t);
2403 result.mod = mod;
2404 return result;
2405 }
2406
2407 override bool isScalar()
2408 {
2409 return true;
2410 }
2411
2412 override void accept(Visitor v)
2413 {
2414 v.visit(this);
2415 }
2416 }
2417
2418 /***********************************************************
2419 */
2420 extern (C++) final class TypeReference : TypeNext
2421 {
2422 extern (D) this(Type t) @safe
2423 {
2424 super(Treference, t);
2425 // BUG: what about references to static arrays?
2426 }
2427
2428 override const(char)* kind() const
2429 {
2430 return "reference";
2431 }
2432
2433 override TypeReference syntaxCopy()
2434 {
2435 Type t = next.syntaxCopy();
2436 if (t == next)
2437 return this;
2438
2439 auto result = new TypeReference(t);
2440 result.mod = mod;
2441 return result;
2442 }
2443
2444 override void accept(Visitor v)
2445 {
2446 v.visit(this);
2447 }
2448 }
2449
2450 enum RET : int
2451 {
2452 regs = 1, // returned in registers
2453 stack = 2, // returned on stack
2454 }
2455
2456 enum TRUSTformat : int
2457 {
2458 TRUSTformatDefault, // do not emit @system when trust == TRUST.default_
2459 TRUSTformatSystem, // emit @system when trust == TRUST.default_
2460 }
2461
2462 alias TRUSTformatDefault = TRUSTformat.TRUSTformatDefault;
2463 alias TRUSTformatSystem = TRUSTformat.TRUSTformatSystem;
2464
2465 /***********************************************************
2466 */
2467 extern (C++) final class TypeFunction : TypeNext
2468 {
2469 // .next is the return type
2470
2471 ParameterList parameterList; // function parameters
2472
2473 // These flags can be accessed like `bool` properties,
2474 // getters and setters are generated for them
2475 private extern (D) static struct BitFields
2476 {
2477 bool isNothrow; /// nothrow
2478 bool isNogc; /// is @nogc
2479 bool isProperty; /// can be called without parentheses
2480 bool isRef; /// returns a reference
2481 bool isReturn; /// 'this' is returned by ref
2482 bool isScopeQual; /// 'this' is scope
2483 bool isReturnInferred; /// 'this' is return from inference
2484 bool isScopeInferred; /// 'this' is scope from inference
2485 bool isLive; /// is @live
2486 bool incomplete; /// return type or default arguments removed
2487 bool isInOutParam; /// inout on the parameters
2488 bool isInOutQual; /// inout on the qualifier
2489 bool isCtor; /// the function is a constructor
2490 bool isReturnScope; /// `this` is returned by value
2491 bool isRvalue; /// returned reference should be treated as rvalue
2492 }
2493
2494 import dmd.common.bitfields : generateBitFields;
2495 mixin(generateBitFields!(BitFields, ushort));
2496
2497 LINK linkage; // calling convention
2498 TRUST trust; // level of trust
2499 PURE purity = PURE.impure;
2500 byte inuse;
2501 ArgumentList inferenceArguments; // function arguments to determine `auto ref` in type semantic
2502
2503 extern (D) this(ParameterList pl, Type treturn, LINK linkage, STC stc = STC.none) @safe
2504 {
2505 super(Tfunction, treturn);
2506 //if (!treturn) *(char*)0=0;
2507 // assert(treturn);
2508 assert(VarArg.none <= pl.varargs && pl.varargs <= VarArg.max);
2509 this.parameterList = pl;
2510 this.linkage = linkage;
2511
2512 if (stc & STC.pure_)
2513 this.purity = PURE.fwdref;
2514 if (stc & STC.nothrow_)
2515 this.isNothrow = true;
2516 if (stc & STC.nogc)
2517 this.isNogc = true;
2518 if (stc & STC.property)
2519 this.isProperty = true;
2520 if (stc & STC.live)
2521 this.isLive = true;
2522
2523 if (stc & STC.ref_)
2524 this.isRef = true;
2525 if (stc & STC.return_)
2526 this.isReturn = true;
2527 if (stc & STC.returnScope)
2528 this.isReturnScope = true;
2529 if (stc & STC.returninferred)
2530 this.isReturnInferred = true;
2531 if (stc & STC.scope_)
2532 this.isScopeQual = true;
2533 if (stc & STC.scopeinferred)
2534 this.isScopeInferred = true;
2535 if (stc & STC.rvalue)
2536 this.isRvalue = true;
2537
2538 this.trust = TRUST.default_;
2539 if (stc & STC.safe)
2540 this.trust = TRUST.safe;
2541 else if (stc & STC.system)
2542 this.trust = TRUST.system;
2543 else if (stc & STC.trusted)
2544 this.trust = TRUST.trusted;
2545 }
2546
2547 static TypeFunction create(Parameters* parameters, Type treturn, ubyte varargs, LINK linkage, StorageClass stc = STC.none) @safe
2548 {
2549 return new TypeFunction(ParameterList(parameters, cast(VarArg)varargs), treturn, linkage, cast(STC) stc);
2550 }
2551
2552 override const(char)* kind() const
2553 {
2554 return "function";
2555 }
2556
2557 override TypeFunction syntaxCopy()
2558 {
2559 Type treturn = next ? next.syntaxCopy() : null;
2560 auto t = new TypeFunction(parameterList.syntaxCopy(), treturn, linkage);
2561 t.mod = mod;
2562 t.isNothrow = isNothrow;
2563 t.isNogc = isNogc;
2564 t.isLive = isLive;
2565 t.purity = purity;
2566 t.isProperty = isProperty;
2567 t.isRef = isRef;
2568 t.isReturn = isReturn;
2569 t.isReturnScope = isReturnScope;
2570 t.isScopeQual = isScopeQual;
2571 t.isReturnInferred = isReturnInferred;
2572 t.isScopeInferred = isScopeInferred;
2573 t.isRvalue = isRvalue;
2574 t.isInOutParam = isInOutParam;
2575 t.isInOutQual = isInOutQual;
2576 t.trust = trust;
2577 t.inferenceArguments = inferenceArguments;
2578 t.isCtor = isCtor;
2579 return t;
2580 }
2581
2582 /********************************************
2583 * Return true if there are lazy parameters.
2584 */
2585 bool hasLazyParameters()
2586 {
2587 foreach (i, fparam; parameterList)
2588 {
2589 if (fparam.isLazy())
2590 return true;
2591 }
2592 return false;
2593 }
2594
2595 /*******************************
2596 * Check for `extern (D) U func(T t, ...)` variadic function type,
2597 * which has `_arguments[]` added as the first argument.
2598 * Returns:
2599 * true if D-style variadic
2600 */
2601 bool isDstyleVariadic() const pure nothrow @safe
2602 {
2603 return linkage == LINK.d && parameterList.varargs == VarArg.variadic;
2604 }
2605
2606 /*********************************
2607 * Append error message to buf.
2608 * Input:
2609 * buf = message sink
2610 * format = printf format
2611 */
2612 extern(C) static void getMatchError(ref OutBuffer buf, const(char)* format, ...)
2613 {
2614 if (global.gag && !global.params.v.showGaggedErrors)
2615 return;
2616 va_list ap;
2617 va_start(ap, format);
2618 buf.vprintf(format, ap);
2619 va_end(ap);
2620 }
2621
2622 /********************************
2623 * Convert an `argumentList`, which may contain named arguments, into
2624 * a list of arguments in the order of the parameter list.
2625 *
2626 * Params:
2627 * argumentList = array of function arguments
2628 * buf = if not null, append error message to it
2629 * Returns: re-ordered argument list, or `null` on error
2630 */
2631 extern(D) Expressions* resolveNamedArgs(ArgumentList argumentList, OutBuffer* buf)
2632 {
2633 Expression[] args = argumentList.arguments ? (*argumentList.arguments)[] : null;
2634 Identifier[] names = argumentList.names ? (*argumentList.names)[] : null;
2635 const nParams = parameterList.length(); // cached because O(n)
2636 auto newArgs = new Expressions(nParams);
2637 newArgs.zero();
2638 size_t ci = 0;
2639 bool hasNamedArgs = false;
2640 const bool isVariadic = parameterList.varargs != VarArg.none;
2641 foreach (i, arg; args)
2642 {
2643 if (!arg)
2644 {
2645 ci++;
2646 continue;
2647 }
2648 auto name = i < names.length ? names[i] : null;
2649 if (name)
2650 {
2651 hasNamedArgs = true;
2652 const pi = findParameterIndex(name);
2653 if (pi == -1)
2654 {
2655 if (buf)
2656 getMatchError(*buf, "no parameter named `%s`", name.toChars());
2657 return null;
2658 }
2659 ci = pi;
2660 }
2661 if (ci >= newArgs.length)
2662 {
2663 if (!isVariadic)
2664 {
2665 // Without named args, let the caller diagnose argument overflow
2666 if (hasNamedArgs && buf)
2667 getMatchError(*buf, "argument `%s` goes past end of parameter list", arg.toChars());
2668 return null;
2669 }
2670 while (ci >= newArgs.length)
2671 newArgs.push(null);
2672 }
2673
2674 if ((*newArgs)[ci])
2675 {
2676 if (buf)
2677 getMatchError(*buf, "parameter `%s` assigned twice", parameterList[ci].toChars());
2678 return null;
2679 }
2680 (*newArgs)[ci++] = arg;
2681 }
2682 foreach (i, arg; (*newArgs)[])
2683 {
2684 if (arg || parameterList[i].defaultArg)
2685 continue;
2686
2687 if (isVariadic && i + 1 == newArgs.length)
2688 continue;
2689
2690 // dtemplate sets `defaultArg=null` to avoid semantic on default arguments,
2691 // don't complain about missing arguments in that case
2692 if (this.incomplete)
2693 continue;
2694
2695 if (buf)
2696 getMatchError(*buf, "missing argument for parameter #%d: `%s`",
2697 i + 1, parameterToChars(parameterList[i], this, false));
2698 return null;
2699 }
2700 // strip trailing nulls from default arguments
2701 size_t e = newArgs.length;
2702 while (e > 0 && (*newArgs)[e - 1] is null)
2703 {
2704 --e;
2705 }
2706 newArgs.setDim(e);
2707 return newArgs;
2708 }
2709
2710 /// Returns: `true` the function is `isInOutQual` or `isInOutParam` ,`false` otherwise.
2711 bool iswild() const pure nothrow @safe @nogc
2712 {
2713 return isInOutParam || isInOutQual;
2714 }
2715
2716 /// Returns: whether `this` function type has the same attributes (`@safe`,...) as `other`
2717 extern (D) bool attributesEqual(const scope TypeFunction other, bool trustSystemEqualsDefault = true) const pure nothrow @safe @nogc
2718 {
2719 // @@@DEPRECATED_2.112@@@
2720 // See semantic2.d Semantic2Visitor.visit(FuncDeclaration):
2721 // Two overloads that are identical except for one having an explicit `@system`
2722 // attribute is currently in deprecation, and will become an error in 2.104 for
2723 // `extern(C)`, and 2.112 for `extern(D)` code respectively. Once the deprecation
2724 // period has passed, the trustSystemEqualsDefault=true behaviour should be made
2725 // the default, then we can remove the `cannot overload extern(...) function`
2726 // errors as they will become dead code as a result.
2727 return (this.trust == other.trust ||
2728 (trustSystemEqualsDefault && this.trust <= TRUST.system && other.trust <= TRUST.system)) &&
2729 this.purity == other.purity &&
2730 this.isNothrow == other.isNothrow &&
2731 this.isNogc == other.isNogc &&
2732 this.isLive == other.isLive;
2733 }
2734
2735 override void accept(Visitor v)
2736 {
2737 v.visit(this);
2738 }
2739
2740 /**
2741 * Look for the index of parameter `ident` in the parameter list
2742 *
2743 * Params:
2744 * ident = identifier of parameter to search for
2745 * Returns: index of parameter with name `ident` or -1 if not found
2746 */
2747 private extern(D) ptrdiff_t findParameterIndex(Identifier ident)
2748 {
2749 foreach (i, p; this.parameterList)
2750 {
2751 if (p.ident == ident)
2752 return i;
2753 }
2754 return -1;
2755 }
2756 }
2757
2758 /***********************************************************
2759 */
2760 extern (C++) final class TypeDelegate : TypeNext
2761 {
2762 // .next is a TypeFunction
2763
2764 extern (D) this(TypeFunction t) @safe
2765 {
2766 super(Tfunction, t);
2767 ty = Tdelegate;
2768 }
2769
2770 static TypeDelegate create(TypeFunction t) @safe
2771 {
2772 return new TypeDelegate(t);
2773 }
2774
2775 override const(char)* kind() const
2776 {
2777 return "delegate";
2778 }
2779
2780 override TypeDelegate syntaxCopy()
2781 {
2782 auto tf = next.syntaxCopy().isTypeFunction();
2783 if (tf == next)
2784 return this;
2785
2786 auto result = new TypeDelegate(tf);
2787 result.mod = mod;
2788 return result;
2789 }
2790
2791 override uint alignsize()
2792 {
2793 return target.ptrsize;
2794 }
2795
2796 override bool isBoolean()
2797 {
2798 return true;
2799 }
2800
2801 override void accept(Visitor v)
2802 {
2803 v.visit(this);
2804 }
2805 }
2806
2807 /**
2808 * This is a shell containing a TraitsExp that can be
2809 * either resolved to a type or to a symbol.
2810 *
2811 * The point is to allow AliasDeclarationY to use `__traits()`, see $(LINK https://issues.dlang.org/show_bug.cgi?id=7804).
2812 */
2813 extern (C++) final class TypeTraits : Type
2814 {
2815 Loc loc;
2816 /// The expression to resolve as type or symbol.
2817 TraitsExp exp;
2818 /// Cached type/symbol after semantic analysis.
2819 RootObject obj;
2820
2821 final extern (D) this(Loc loc, TraitsExp exp) @safe
2822 {
2823 super(Ttraits);
2824 this.loc = loc;
2825 this.exp = exp;
2826 }
2827
2828 override const(char)* kind() const
2829 {
2830 return "traits";
2831 }
2832
2833 override TypeTraits syntaxCopy()
2834 {
2835 TraitsExp te = exp.syntaxCopy();
2836 TypeTraits tt = new TypeTraits(loc, te);
2837 tt.mod = mod;
2838 return tt;
2839 }
2840
2841 override void accept(Visitor v)
2842 {
2843 v.visit(this);
2844 }
2845 }
2846
2847 /******
2848 * Implements mixin types.
2849 *
2850 * Semantic analysis will convert it to a real type.
2851 */
2852 extern (C++) final class TypeMixin : Type
2853 {
2854 Loc loc;
2855 Expressions* exps;
2856 RootObject obj; // cached result of semantic analysis.
2857
2858 extern (D) this(Loc loc, Expressions* exps) @safe
2859 {
2860 super(Tmixin);
2861 this.loc = loc;
2862 this.exps = exps;
2863 }
2864
2865 override const(char)* kind() const
2866 {
2867 return "mixin";
2868 }
2869
2870 override TypeMixin syntaxCopy()
2871 {
2872 return new TypeMixin(loc, Expression.arraySyntaxCopy(exps));
2873 }
2874
2875 override void accept(Visitor v)
2876 {
2877 v.visit(this);
2878 }
2879 }
2880
2881 /***********************************************************
2882 */
2883 extern (C++) abstract class TypeQualified : Type
2884 {
2885 Loc loc;
2886
2887 // array of Identifier and TypeInstance,
2888 // representing ident.ident!tiargs.ident. ... etc.
2889 Objects idents;
2890
2891 final extern (D) this(TY ty, Loc loc)
2892 {
2893 super(ty);
2894 this.loc = loc;
2895 }
2896
2897 // abstract override so that using `TypeQualified.syntaxCopy` gets
2898 // us a `TypeQualified`
2899 abstract override TypeQualified syntaxCopy();
2900
2901 extern (D) final void syntaxCopyHelper(TypeQualified t)
2902 {
2903 //printf("TypeQualified::syntaxCopyHelper(%s) %s\n", t.toChars(), toChars());
2904 idents.setDim(t.idents.length);
2905 for (size_t i = 0; i < idents.length; i++)
2906 {
2907 RootObject id = t.idents[i];
2908 with (DYNCAST) final switch (id.dyncast())
2909 {
2910 case object:
2911 break;
2912 case expression:
2913 Expression e = cast(Expression)id;
2914 e = e.syntaxCopy();
2915 id = e;
2916 break;
2917 case dsymbol:
2918 TemplateInstance ti = cast(TemplateInstance)id;
2919 ti = ti.syntaxCopy(null);
2920 id = ti;
2921 break;
2922 case type:
2923 Type tx = cast(Type)id;
2924 tx = tx.syntaxCopy();
2925 id = tx;
2926 break;
2927 case identifier:
2928 case tuple:
2929 case parameter:
2930 case statement:
2931 case condition:
2932 case templateparameter:
2933 case initializer:
2934 }
2935 idents[i] = id;
2936 }
2937 }
2938
2939 extern (D) final void addIdent(Identifier ident)
2940 {
2941 idents.push(ident);
2942 }
2943
2944 extern (D) final void addInst(TemplateInstance inst)
2945 {
2946 idents.push(inst);
2947 }
2948
2949 extern (D) final void addIndex(RootObject e)
2950 {
2951 idents.push(e);
2952 }
2953
2954 override void accept(Visitor v)
2955 {
2956 v.visit(this);
2957 }
2958 }
2959
2960 /***********************************************************
2961 */
2962 extern (C++) final class TypeIdentifier : TypeQualified
2963 {
2964 Identifier ident;
2965
2966 extern (D) this(Loc loc, Identifier ident)
2967 {
2968 super(Tident, loc);
2969 this.ident = ident;
2970 }
2971
2972 static TypeIdentifier create(Loc loc, Identifier ident)
2973 {
2974 return new TypeIdentifier(loc, ident);
2975 }
2976
2977 override const(char)* kind() const
2978 {
2979 return "identifier";
2980 }
2981
2982 override TypeIdentifier syntaxCopy()
2983 {
2984 auto t = new TypeIdentifier(loc, ident);
2985 t.syntaxCopyHelper(this);
2986 t.mod = mod;
2987 return t;
2988 }
2989
2990 override void accept(Visitor v)
2991 {
2992 v.visit(this);
2993 }
2994 }
2995
2996 /***********************************************************
2997 * Similar to TypeIdentifier, but with a TemplateInstance as the root
2998 */
2999 extern (C++) final class TypeInstance : TypeQualified
3000 {
3001 TemplateInstance tempinst;
3002
3003 extern (D) this(Loc loc, TemplateInstance tempinst)
3004 {
3005 super(Tinstance, loc);
3006 this.tempinst = tempinst;
3007 }
3008
3009 override const(char)* kind() const
3010 {
3011 return "instance";
3012 }
3013
3014 override TypeInstance syntaxCopy()
3015 {
3016 //printf("TypeInstance::syntaxCopy() %s, %d\n", toChars(), idents.length);
3017 auto t = new TypeInstance(loc, tempinst.syntaxCopy(null));
3018 t.syntaxCopyHelper(this);
3019 t.mod = mod;
3020 return t;
3021 }
3022
3023 override void accept(Visitor v)
3024 {
3025 v.visit(this);
3026 }
3027 }
3028
3029 /***********************************************************
3030 */
3031 extern (C++) final class TypeTypeof : TypeQualified
3032 {
3033 Expression exp;
3034 int inuse;
3035
3036 extern (D) this(Loc loc, Expression exp)
3037 {
3038 super(Ttypeof, loc);
3039 this.exp = exp;
3040 }
3041
3042 override const(char)* kind() const
3043 {
3044 return "typeof";
3045 }
3046
3047 override TypeTypeof syntaxCopy()
3048 {
3049 //printf("TypeTypeof::syntaxCopy() %s\n", toChars());
3050 auto t = new TypeTypeof(loc, exp.syntaxCopy());
3051 t.syntaxCopyHelper(this);
3052 t.mod = mod;
3053 return t;
3054 }
3055
3056 override void accept(Visitor v)
3057 {
3058 v.visit(this);
3059 }
3060 }
3061
3062 /***********************************************************
3063 */
3064 extern (C++) final class TypeReturn : TypeQualified
3065 {
3066 extern (D) this(Loc loc)
3067 {
3068 super(Treturn, loc);
3069 }
3070
3071 override const(char)* kind() const
3072 {
3073 return "return";
3074 }
3075
3076 override TypeReturn syntaxCopy()
3077 {
3078 auto t = new TypeReturn(loc);
3079 t.syntaxCopyHelper(this);
3080 t.mod = mod;
3081 return t;
3082 }
3083
3084 override void accept(Visitor v)
3085 {
3086 v.visit(this);
3087 }
3088 }
3089
3090 /***********************************************************
3091 */
3092 extern (C++) final class TypeStruct : Type
3093 {
3094 StructDeclaration sym;
3095 AliasThisRec att = AliasThisRec.fwdref;
3096 bool inuse = false; // struct currently subject of recursive method call
3097
3098 extern (D) this(StructDeclaration sym) @safe
3099 {
3100 super(Tstruct);
3101 this.sym = sym;
3102 }
3103
3104 static TypeStruct create(StructDeclaration sym) @safe
3105 {
3106 return new TypeStruct(sym);
3107 }
3108
3109 override const(char)* kind() const
3110 {
3111 return "struct";
3112 }
3113
3114 override uint alignsize()
3115 {
3116 sym.size(Loc.initial); // give error for forward references
3117 return sym.alignsize;
3118 }
3119
3120 override TypeStruct syntaxCopy()
3121 {
3122 return this;
3123 }
3124
3125 override structalign_t alignment()
3126 {
3127 if (sym.alignment.isUnknown())
3128 sym.size(sym.loc);
3129 return sym.alignment;
3130 }
3131
3132 /***************************************
3133 * Use when we prefer the default initializer to be a literal,
3134 * rather than a global immutable variable.
3135 */
3136 override Expression defaultInitLiteral(Loc loc)
3137 {
3138 static if (LOGDEFAULTINIT)
3139 {
3140 printf("TypeStruct::defaultInitLiteral() '%s'\n", toChars());
3141 }
3142 sym.size(loc);
3143 if (sym.sizeok != Sizeok.done)
3144 return ErrorExp.get();
3145
3146 auto structelems = new Expressions(sym.nonHiddenFields());
3147 uint offset = 0;
3148 foreach (j; 0 .. structelems.length)
3149 {
3150 VarDeclaration vd = sym.fields[j];
3151 Expression e;
3152 if (vd.inuse)
3153 {
3154 error(loc, "circular reference to `%s`", vd.toPrettyChars());
3155 return ErrorExp.get();
3156 }
3157 if (vd.offset < offset || vd.type.size() == 0)
3158 e = null;
3159 else if (vd._init)
3160 {
3161 if (vd._init.isVoidInitializer())
3162 e = null;
3163 else
3164 e = vd.getConstInitializer(false);
3165 }
3166 else
3167 e = vd.type.defaultInitLiteral(loc);
3168 if (e && e.op == EXP.error)
3169 return e;
3170 if (e)
3171 offset = vd.offset + cast(uint)vd.type.size();
3172 (*structelems)[j] = e;
3173 }
3174 auto structinit = new StructLiteralExp(loc, sym, structelems);
3175
3176 /* Copy from the initializer symbol for larger symbols,
3177 * otherwise the literals expressed as code get excessively large.
3178 */
3179 if (size(this, loc) > target.ptrsize * 4 && !needsNested())
3180 structinit.useStaticInit = true;
3181
3182 structinit.type = this;
3183 return structinit;
3184 }
3185
3186 override bool isAssignable()
3187 {
3188 bool assignable = true;
3189 uint offset = ~0; // dead-store initialize to prevent spurious warning
3190
3191 sym.determineSize(sym.loc);
3192
3193 /* If any of the fields are const or immutable,
3194 * then one cannot assign this struct.
3195 */
3196 for (size_t i = 0; i < sym.fields.length; i++)
3197 {
3198 VarDeclaration v = sym.fields[i];
3199 //printf("%s [%d] v = (%s) %s, v.offset = %d, v.parent = %s\n", sym.toChars(), i, v.kind(), v.toChars(), v.offset, v.parent.kind());
3200 if (i == 0)
3201 {
3202 }
3203 else if (v.offset == offset)
3204 {
3205 /* If any fields of anonymous union are assignable,
3206 * then regard union as assignable.
3207 * This is to support unsafe things like Rebindable templates.
3208 */
3209 if (assignable)
3210 continue;
3211 }
3212 else
3213 {
3214 if (!assignable)
3215 return false;
3216 }
3217 assignable = v.type.isMutable() && v.type.isAssignable();
3218 offset = v.offset;
3219 //printf(" -> assignable = %d\n", assignable);
3220 }
3221
3222 return assignable;
3223 }
3224
3225 override bool isBoolean()
3226 {
3227 return false;
3228 }
3229
3230 override bool needsDestruction()
3231 {
3232 return sym.dtor !is null;
3233 }
3234
3235 override bool needsCopyOrPostblit()
3236 {
3237 return sym.hasCopyCtor || sym.postblit;
3238 }
3239
3240 override bool needsNested()
3241 {
3242 if (inuse) return false; // circular type, error instead of crashing
3243
3244 inuse = true;
3245 scope(exit) inuse = false;
3246
3247 if (sym.isNested())
3248 return true;
3249
3250 for (size_t i = 0; i < sym.fields.length; i++)
3251 {
3252 VarDeclaration v = sym.fields[i];
3253 if (!v.isDataseg() && v.type.needsNested())
3254 return true;
3255 }
3256 return false;
3257 }
3258
3259 override bool hasVoidInitPointers()
3260 {
3261 sym.size(Loc.initial); // give error for forward references
3262 sym.determineTypeProperties();
3263 return sym.hasVoidInitPointers;
3264 }
3265
3266 override bool hasUnsafeBitpatterns()
3267 {
3268 sym.size(Loc.initial); // give error for forward references
3269 sym.determineTypeProperties();
3270 return sym.hasUnsafeBitpatterns;
3271 }
3272
3273 override bool hasInvariant()
3274 {
3275 sym.size(Loc.initial); // give error for forward references
3276 sym.determineTypeProperties();
3277 return sym.hasInvariant() || sym.hasFieldWithInvariant;
3278 }
3279
3280 override MOD deduceWild(Type t, bool isRef)
3281 {
3282 if (ty == t.ty && sym == (cast(TypeStruct)t).sym)
3283 return Type.deduceWild(t, isRef);
3284
3285 ubyte wm = 0;
3286
3287 if (t.hasWild() && sym.aliasthis && !(att & AliasThisRec.tracing))
3288 {
3289 if (auto ato = aliasthisOf(this))
3290 {
3291 att = cast(AliasThisRec)(att | AliasThisRec.tracing);
3292 wm = ato.deduceWild(t, isRef);
3293 att = cast(AliasThisRec)(att & ~AliasThisRec.tracing);
3294 }
3295 }
3296
3297 return wm;
3298 }
3299
3300 override void accept(Visitor v)
3301 {
3302 v.visit(this);
3303 }
3304 }
3305
3306 /***********************************************************
3307 */
3308 extern (C++) final class TypeEnum : Type
3309 {
3310 EnumDeclaration sym;
3311
3312 extern (D) this(EnumDeclaration sym) @safe
3313 {
3314 super(Tenum);
3315 this.sym = sym;
3316 }
3317
3318 override const(char)* kind() const
3319 {
3320 return "enum";
3321 }
3322
3323 override TypeEnum syntaxCopy()
3324 {
3325 return this;
3326 }
3327
3328 Type memType()
3329 {
3330 return sym.getMemtype(Loc.initial);
3331 }
3332
3333 override uint alignsize()
3334 {
3335 Type t = memType();
3336 if (t.ty == Terror)
3337 return 4;
3338 return t.alignsize();
3339 }
3340
3341 override bool isIntegral()
3342 {
3343 return memType().isIntegral();
3344 }
3345
3346 override bool isFloating()
3347 {
3348 return memType().isFloating();
3349 }
3350
3351 override bool isReal()
3352 {
3353 return memType().isReal();
3354 }
3355
3356 override bool isImaginary()
3357 {
3358 return memType().isImaginary();
3359 }
3360
3361 override bool isComplex()
3362 {
3363 return memType().isComplex();
3364 }
3365
3366 override bool isScalar()
3367 {
3368 return memType().isScalar();
3369 }
3370
3371 override bool isUnsigned()
3372 {
3373 return memType().isUnsigned();
3374 }
3375
3376 override bool isBoolean()
3377 {
3378 return memType().isBoolean();
3379 }
3380
3381 override bool isString()
3382 {
3383 return memType().isString();
3384 }
3385
3386 override bool isAssignable()
3387 {
3388 return memType().isAssignable();
3389 }
3390
3391 override bool needsDestruction()
3392 {
3393 return memType().needsDestruction();
3394 }
3395
3396 override bool needsCopyOrPostblit()
3397 {
3398 return memType().needsCopyOrPostblit();
3399 }
3400
3401 override bool needsNested()
3402 {
3403 return memType().needsNested();
3404 }
3405
3406 extern (D) Type toBasetype2()
3407 {
3408 if (!sym.members && !sym.memtype)
3409 return this;
3410 auto tb = sym.getMemtype(Loc.initial).toBasetype();
3411 return tb.castMod(mod); // retain modifier bits from 'this'
3412 }
3413
3414 override bool hasVoidInitPointers()
3415 {
3416 return memType().hasVoidInitPointers();
3417 }
3418
3419 override bool hasUnsafeBitpatterns()
3420 {
3421 return memType().hasUnsafeBitpatterns();
3422 }
3423
3424 override bool hasInvariant()
3425 {
3426 return memType().hasInvariant();
3427 }
3428
3429 override Type nextOf()
3430 {
3431 return memType().nextOf();
3432 }
3433
3434 override void accept(Visitor v)
3435 {
3436 v.visit(this);
3437 }
3438 }
3439
3440 /***********************************************************
3441 */
3442 extern (C++) final class TypeClass : Type
3443 {
3444 ClassDeclaration sym;
3445 AliasThisRec att = AliasThisRec.fwdref;
3446 CPPMANGLE cppmangle = CPPMANGLE.def;
3447
3448 extern (D) this(ClassDeclaration sym) @safe
3449 {
3450 super(Tclass);
3451 this.sym = sym;
3452 }
3453
3454 override const(char)* kind() const
3455 {
3456 return "class";
3457 }
3458
3459 override TypeClass syntaxCopy()
3460 {
3461 return this;
3462 }
3463
3464 override inout(ClassDeclaration) isClassHandle() inout
3465 {
3466 return sym;
3467 }
3468
3469 override MOD deduceWild(Type t, bool isRef)
3470 {
3471 ClassDeclaration cd = t.isClassHandle();
3472 if (cd && (sym == cd || cd.isBaseOf(sym, null)))
3473 return Type.deduceWild(t, isRef);
3474
3475 ubyte wm = 0;
3476
3477 if (t.hasWild() && sym.aliasthis && !(att & AliasThisRec.tracing))
3478 {
3479 if (auto ato = aliasthisOf(this))
3480 {
3481 att = cast(AliasThisRec)(att | AliasThisRec.tracing);
3482 wm = ato.deduceWild(t, isRef);
3483 att = cast(AliasThisRec)(att & ~AliasThisRec.tracing);
3484 }
3485 }
3486
3487 return wm;
3488 }
3489
3490 override bool isScopeClass()
3491 {
3492 return sym.stack;
3493 }
3494
3495 override bool isBoolean()
3496 {
3497 return true;
3498 }
3499
3500 override void accept(Visitor v)
3501 {
3502 v.visit(this);
3503 }
3504 }
3505
3506 /***********************************************************
3507 */
3508 extern (C++) final class TypeTuple : Type
3509 {
3510 // 'logically immutable' cached global - don't modify!
3511 static if (__VERSION__ == 2081)
3512 __gshared TypeTuple empty; // See comment in Type._init
3513 else
3514 __gshared TypeTuple empty = new TypeTuple();
3515
3516 Parameters* arguments; // types making up the tuple
3517
3518 extern (D) this(Parameters* arguments) @safe
3519 {
3520 super(Ttuple);
3521 //printf("TypeTuple(this = %p)\n", this);
3522 this.arguments = arguments;
3523 //printf("TypeTuple() %p, %s\n", this, toChars());
3524 debug
3525 {
3526 if (arguments)
3527 {
3528 for (size_t i = 0; i < arguments.length; i++)
3529 {
3530 Parameter arg = (*arguments)[i];
3531 assert(arg && arg.type);
3532 }
3533 }
3534 }
3535 }
3536
3537 /****************
3538 * Form TypeTuple from the types of the expressions.
3539 * Assume exps[] is already tuple expanded.
3540 */
3541 extern (D) this(Expressions* exps)
3542 {
3543 super(Ttuple);
3544 if (!exps)
3545 {
3546 this.arguments = new Parameters(0);
3547 return;
3548 }
3549 auto arguments = new Parameters(exps.length);
3550
3551 for (size_t i = 0; i < exps.length; i++)
3552 {
3553 Expression e = (*exps)[i];
3554 assert(e.type.ty != Ttuple);
3555 auto arg = new Parameter(e.loc, STC.none, e.type, null, null, null);
3556 (*arguments)[i] = arg;
3557 }
3558 this.arguments = arguments;
3559 //printf("TypeTuple() %p, %s\n", this, toChars());
3560 }
3561
3562 static TypeTuple create(Parameters* arguments) @safe
3563 {
3564 return new TypeTuple(arguments);
3565 }
3566
3567 /*******************************************
3568 * Type tuple with 0, 1 or 2 types in it.
3569 */
3570 extern (D) this() @safe
3571 {
3572 super(Ttuple);
3573 arguments = new Parameters();
3574 }
3575
3576 extern (D) this(Type t1)
3577 {
3578 super(Ttuple);
3579 arguments = new Parameters();
3580 arguments.push(new Parameter(Loc.initial, STC.none, t1, null, null, null));
3581 }
3582
3583 extern (D) this(Type t1, Type t2)
3584 {
3585 super(Ttuple);
3586 arguments = new Parameters();
3587 arguments.push(new Parameter(Loc.initial, STC.none, t1, null, null, null));
3588 arguments.push(new Parameter(Loc.initial, STC.none, t2, null, null, null));
3589 }
3590
3591 static TypeTuple create() @safe
3592 {
3593 return new TypeTuple();
3594 }
3595
3596 static TypeTuple create(Type t1)
3597 {
3598 return new TypeTuple(t1);
3599 }
3600
3601 static TypeTuple create(Type t1, Type t2)
3602 {
3603 return new TypeTuple(t1, t2);
3604 }
3605
3606 override const(char)* kind() const
3607 {
3608 return "sequence";
3609 }
3610
3611 override TypeTuple syntaxCopy()
3612 {
3613 Parameters* args = Parameter.arraySyntaxCopy(arguments);
3614 auto t = new TypeTuple(args);
3615 t.mod = mod;
3616 return t;
3617 }
3618
3619 override bool equals(const RootObject o) const
3620 {
3621 Type t = cast(Type)o;
3622 //printf("TypeTuple::equals(%s, %s)\n", toChars(), t.toChars());
3623 if (this == t)
3624 return true;
3625 if (auto tt = t.isTypeTuple())
3626 {
3627 if (arguments.length == tt.arguments.length)
3628 {
3629 for (size_t i = 0; i < tt.arguments.length; i++)
3630 {
3631 const Parameter arg1 = (*arguments)[i];
3632 Parameter arg2 = (*tt.arguments)[i];
3633 if (!arg1.type.equals(arg2.type))
3634 return false;
3635 }
3636 return true;
3637 }
3638 }
3639 return false;
3640 }
3641
3642 override void accept(Visitor v)
3643 {
3644 v.visit(this);
3645 }
3646 }
3647
3648 /***********************************************************
3649 * This is so we can slice a TypeTuple
3650 */
3651 extern (C++) final class TypeSlice : TypeNext
3652 {
3653 Expression lwr;
3654 Expression upr;
3655
3656 extern (D) this(Type next, Expression lwr, Expression upr) @safe
3657 {
3658 super(Tslice, next);
3659 //printf("TypeSlice[%s .. %s]\n", lwr.toChars(), upr.toChars());
3660 this.lwr = lwr;
3661 this.upr = upr;
3662 }
3663
3664 override const(char)* kind() const
3665 {
3666 return "slice";
3667 }
3668
3669 override TypeSlice syntaxCopy()
3670 {
3671 auto t = new TypeSlice(next.syntaxCopy(), lwr.syntaxCopy(), upr.syntaxCopy());
3672 t.mod = mod;
3673 return t;
3674 }
3675
3676 override void accept(Visitor v)
3677 {
3678 v.visit(this);
3679 }
3680 }
3681
3682 /***********************************************************
3683 */
3684 extern (C++) final class TypeNull : Type
3685 {
3686 extern (D) this() @safe
3687 {
3688 //printf("TypeNull %p\n", this);
3689 super(Tnull);
3690 }
3691
3692 override const(char)* kind() const
3693 {
3694 return "null";
3695 }
3696
3697 override TypeNull syntaxCopy()
3698 {
3699 // No semantic analysis done, no need to copy
3700 return this;
3701 }
3702
3703 override bool isBoolean()
3704 {
3705 return true;
3706 }
3707
3708 override void accept(Visitor v)
3709 {
3710 v.visit(this);
3711 }
3712 }
3713
3714 /***********************************************************
3715 */
3716 extern (C++) final class TypeNoreturn : Type
3717 {
3718 extern (D) this() @safe
3719 {
3720 //printf("TypeNoreturn %p\n", this);
3721 super(Tnoreturn);
3722 }
3723
3724 override const(char)* kind() const
3725 {
3726 return "noreturn";
3727 }
3728
3729 override TypeNoreturn syntaxCopy()
3730 {
3731 // No semantic analysis done, no need to copy
3732 return this;
3733 }
3734
3735 override bool isBoolean()
3736 {
3737 return true; // bottom type can be implicitly converted to any other type
3738 }
3739
3740 override uint alignsize()
3741 {
3742 return 0;
3743 }
3744
3745 override void accept(Visitor v)
3746 {
3747 v.visit(this);
3748 }
3749 }
3750
3751 /***********************************************************
3752 * Unlike D, C can declare/define struct/union/enum tag names
3753 * inside Declarators, instead of separately as in D.
3754 * The order these appear in the symbol table must be in lexical
3755 * order. There isn't enough info at the parsing stage to determine if
3756 * it's a declaration or a reference to an existing name, so this Type
3757 * collects the necessary info and defers it to semantic().
3758 */
3759 extern (C++) final class TypeTag : Type
3760 {
3761 Loc loc; /// location of declaration
3762 TOK tok; /// TOK.struct_, TOK.union_, TOK.enum_
3763 structalign_t packalign; /// alignment of struct/union fields
3764 Identifier id; /// tag name identifier
3765 Type base; /// base type for enums otherwise null
3766 Dsymbols* members; /// members of struct, null if none
3767
3768 Type resolved; /// type after semantic() in case there are more others
3769 /// pointing to this instance, which can happen with
3770 /// struct S { int a; } s1, *s2;
3771 MOD mod; /// modifiers to apply after type is resolved (only MODFlags.const_ at the moment)
3772
3773 extern (D) this(Loc loc, TOK tok, Identifier id, structalign_t packalign, Type base, Dsymbols* members) @safe
3774 {
3775 //printf("TypeTag ctor %s %p\n", id ? id.toChars() : "null".ptr, this);
3776 super(Ttag);
3777 this.loc = loc;
3778 this.tok = tok;
3779 this.id = id;
3780 this.packalign = packalign;
3781 this.base = base;
3782 this.members = members;
3783 this.mod = 0;
3784 }
3785
3786 override const(char)* kind() const
3787 {
3788 return "tag";
3789 }
3790
3791 override TypeTag syntaxCopy()
3792 {
3793 //printf("TypeTag syntaxCopy()\n");
3794 // No semantic analysis done, no need to copy
3795 return this;
3796 }
3797
3798 override void accept(Visitor v)
3799 {
3800 v.visit(this);
3801 }
3802 }
3803
3804 /***********************************************************
3805 * Represents a function's formal parameters + variadics info.
3806 * Length, indexing and iteration are based on a depth-first tuple expansion.
3807 * https://dlang.org/spec/function.html#ParameterList
3808 */
3809 extern (C++) struct ParameterList
3810 {
3811 /// The raw (unexpanded) formal parameters, possibly containing tuples.
3812 Parameters* parameters;
3813 STC stc; // storage class of ...
3814 VarArg varargs = VarArg.none;
3815 bool hasIdentifierList; // true if C identifier-list style
3816
3817 this(Parameters* parameters, VarArg varargs = VarArg.none, STC stc = STC.none) @safe
3818 {
3819 this.parameters = parameters;
3820 this.varargs = varargs;
3821 this.stc = stc;
3822 }
3823
3824 /// Returns the number of expanded parameters. Complexity: O(N).
3825 size_t length()
3826 {
3827 return Parameter.dim(parameters);
3828 }
3829
3830 /// Returns the expanded parameter at the given index, or null if out of
3831 /// bounds. Complexity: O(i).
3832 Parameter opIndex(size_t i)
3833 {
3834 return Parameter.getNth(parameters, i);
3835 }
3836
3837 /// Iterates over the expanded parameters. Complexity: O(N).
3838 /// Prefer this to avoid the O(N + N^2/2) complexity of calculating length
3839 /// and calling N times opIndex.
3840 extern (D) int opApply(scope Parameter.ForeachDg dg)
3841 {
3842 return Parameter._foreach(parameters, dg);
3843 }
3844
3845 /// Iterates over the expanded parameters, matching them with the unexpanded
3846 /// ones, for semantic processing
3847 extern (D) int opApply(scope Parameter.SemanticForeachDg dg)
3848 {
3849 return Parameter._foreach(this.parameters, dg);
3850 }
3851
3852 extern (D) ParameterList syntaxCopy()
3853 {
3854 return ParameterList(Parameter.arraySyntaxCopy(parameters), varargs);
3855 }
3856
3857 /// Compares this to another ParameterList (and expands tuples if necessary)
3858 extern (D) bool opEquals(scope ref ParameterList other) const
3859 {
3860 if (stc != other.stc || varargs != other.varargs || (!parameters != !other.parameters))
3861 return false;
3862
3863 if (this.parameters is other.parameters)
3864 return true;
3865
3866 size_t idx;
3867 bool diff;
3868
3869 // Pairwise compare each parameter
3870 // Can this avoid the O(n) indexing for the second list?
3871 foreach (_, p1; cast() this)
3872 {
3873 auto p2 = other[idx++];
3874 if (!p2 || p1 != p2)
3875 {
3876 diff = true;
3877 break;
3878 }
3879 }
3880
3881 // Ensure no remaining parameters in `other`
3882 return !diff && other[idx] is null;
3883 }
3884
3885 /// Returns: `true` if any parameter has a default argument
3886 extern(D) bool hasDefaultArgs()
3887 {
3888 foreach (oidx, oparam, eidx, eparam; this)
3889 {
3890 if (eparam.defaultArg)
3891 return true;
3892 }
3893 return false;
3894 }
3895
3896 // Returns: `true` if any parameter doesn't have a default argument
3897 extern(D) bool hasArgsWithoutDefault()
3898 {
3899 foreach (oidx, oparam, eidx, eparam; this)
3900 {
3901 if (!eparam.defaultArg)
3902 return true;
3903 }
3904 return false;
3905 }
3906 }
3907
3908
3909 /***********************************************************
3910 */
3911 extern (C++) final class Parameter : ASTNode
3912 {
3913 import dmd.attrib : UserAttributeDeclaration;
3914
3915 Loc loc;
3916 STC storageClass;
3917 Type type;
3918 Identifier ident;
3919 Expression defaultArg;
3920 UserAttributeDeclaration userAttribDecl; // user defined attributes
3921
3922 extern (D) this(Loc loc, STC storageClass, Type type, Identifier ident, Expression defaultArg, UserAttributeDeclaration userAttribDecl) @safe
3923 {
3924 this.loc = loc;
3925 this.type = type;
3926 this.ident = ident;
3927 this.storageClass = storageClass;
3928 this.defaultArg = defaultArg;
3929 this.userAttribDecl = userAttribDecl;
3930 }
3931
3932 static Parameter create(Loc loc, StorageClass storageClass, Type type, Identifier ident, Expression defaultArg, UserAttributeDeclaration userAttribDecl) @safe
3933 {
3934 return new Parameter(loc, cast(STC) storageClass, type, ident, defaultArg, userAttribDecl);
3935 }
3936
3937 Parameter syntaxCopy()
3938 {
3939 return new Parameter(loc, storageClass, type ? type.syntaxCopy() : null, ident, defaultArg ? defaultArg.syntaxCopy() : null, userAttribDecl ? userAttribDecl.syntaxCopy(null) : null);
3940 }
3941
3942 /****************************************************
3943 * Determine if parameter is a lazy array of delegates.
3944 * If so, return the return type of those delegates.
3945 * If not, return NULL.
3946 *
3947 * Returns T if the type is one of the following forms:
3948 * T delegate()[]
3949 * T delegate()[dim]
3950 */
3951 Type isLazyArray()
3952 {
3953 Type tb = type.toBasetype();
3954 if (tb.isStaticOrDynamicArray())
3955 {
3956 Type tel = (cast(TypeArray)tb).next.toBasetype();
3957 if (auto td = tel.isTypeDelegate())
3958 {
3959 TypeFunction tf = td.next.toTypeFunction();
3960 if (tf.parameterList.varargs == VarArg.none && tf.parameterList.length == 0)
3961 {
3962 return tf.next; // return type of delegate
3963 }
3964 }
3965 }
3966 return null;
3967 }
3968
3969 /// Returns: Whether the function parameter is lazy
3970 bool isLazy() const @safe pure nothrow @nogc
3971 {
3972 return (this.storageClass & (STC.lazy_)) != 0;
3973 }
3974
3975 /// Returns: Whether the function parameter is a reference (out / ref)
3976 bool isReference() const @safe pure nothrow @nogc
3977 {
3978 return (this.storageClass & (STC.ref_ | STC.out_)) != 0;
3979 }
3980
3981 // kludge for template.isType()
3982 override DYNCAST dyncast() const
3983 {
3984 return DYNCAST.parameter;
3985 }
3986
3987 override void accept(Visitor v)
3988 {
3989 v.visit(this);
3990 }
3991
3992 extern (D) static Parameters* arraySyntaxCopy(Parameters* parameters)
3993 {
3994 Parameters* params = null;
3995 if (parameters)
3996 {
3997 params = new Parameters(parameters.length);
3998 for (size_t i = 0; i < params.length; i++)
3999 (*params)[i] = (*parameters)[i].syntaxCopy();
4000 }
4001 return params;
4002 }
4003
4004 /***************************************
4005 * Determine number of arguments, folding in tuples.
4006 */
4007 static size_t dim(Parameters* parameters)
4008 {
4009 size_t nargs = 0;
4010
4011 int dimDg(size_t n, Parameter p)
4012 {
4013 ++nargs;
4014 return 0;
4015 }
4016
4017 _foreach(parameters, &dimDg);
4018 return nargs;
4019 }
4020
4021 /**
4022 * Get nth `Parameter`, folding in tuples.
4023 *
4024 * Since `parameters` can include tuples, which would increase its
4025 * length, this function allows to get the `nth` parameter as if
4026 * all tuples transitively contained in `parameters` were flattened.
4027 *
4028 * Params:
4029 * parameters = Array of `Parameter` to iterate over
4030 * nth = Index of the desired parameter.
4031 *
4032 * Returns:
4033 * The parameter at index `nth` (taking tuples into account),
4034 * or `null` if out of bound.
4035 */
4036 static Parameter getNth(Parameters* parameters, size_t nth)
4037 {
4038 Parameter param;
4039
4040 int getNthParamDg(size_t n, Parameter p)
4041 {
4042 if (n == nth)
4043 {
4044 param = p;
4045 return 1;
4046 }
4047 return 0;
4048 }
4049
4050 int res = _foreach(parameters, &getNthParamDg);
4051 return res ? param : null;
4052 }
4053
4054 /// Type of delegate when iterating solely on the parameters
4055 alias ForeachDg = extern (D) int delegate(size_t paramidx, Parameter param);
4056 /// Type of delegate when iterating on both the original set of parameters,
4057 /// and the type tuple. Useful for semantic analysis.
4058 /// 'o' stands for 'original' and 'e' stands for 'expanded'.
4059 alias SemanticForeachDg = extern (D) int delegate(
4060 size_t oidx, Parameter oparam, size_t eidx, Parameter eparam);
4061
4062 /***************************************
4063 * Expands tuples in args in depth first order. Calls
4064 * dg(void* ctx, size_t argidx, Parameter* arg) for each Parameter.
4065 * If dg returns !=0, stops and returns that value else returns 0.
4066 * Use this function to avoid the O(N + N^2/2) complexity of
4067 * calculating dim and calling N times getNth.
4068 */
4069 extern (D) static int _foreach(Parameters* parameters, scope ForeachDg dg)
4070 {
4071 assert(dg !is null);
4072 return _foreach(parameters, (_oidx, _oparam, idx, param) => dg(idx, param));
4073 }
4074
4075 /// Ditto
4076 extern (D) static int _foreach(
4077 Parameters* parameters, scope SemanticForeachDg dg)
4078 {
4079 assert(dg !is null);
4080 if (parameters is null)
4081 return 0;
4082
4083 size_t eidx;
4084 foreach (oidx; 0 .. parameters.length)
4085 {
4086 Parameter oparam = (*parameters)[oidx];
4087 if (auto r = _foreachImpl(dg, oidx, oparam, eidx, /* eparam */ oparam))
4088 return r;
4089 }
4090 return 0;
4091 }
4092
4093 /// Implementation of the iteration process, which recurses in itself
4094 /// and just forwards `oidx` and `oparam`.
4095 extern (D) private static int _foreachImpl(scope SemanticForeachDg dg,
4096 size_t oidx, Parameter oparam, ref size_t eidx, Parameter eparam)
4097 {
4098 if (eparam is null)
4099 return 0;
4100
4101 Type t = eparam.type.toBasetype();
4102 if (auto tu = t.isTypeTuple())
4103 {
4104 // Check for empty tuples
4105 if (tu.arguments is null)
4106 return 0;
4107
4108 foreach (nidx; 0 .. tu.arguments.length)
4109 {
4110 Parameter nextep = (*tu.arguments)[nidx];
4111 if (auto r = _foreachImpl(dg, oidx, oparam, eidx, nextep))
4112 return r;
4113 }
4114 }
4115 else
4116 {
4117 if (auto r = dg(oidx, oparam, eidx, eparam))
4118 return r;
4119 // The only place where we should increment eidx is here,
4120 // as a TypeTuple doesn't count as a parameter (for arity)
4121 // it it is empty.
4122 eidx++;
4123 }
4124 return 0;
4125 }
4126
4127 override const(char)* toChars() const
4128 {
4129 return ident ? ident.toChars() : "__anonymous_param";
4130 }
4131
4132 /*********************************
4133 * Compute covariance of parameters `this` and `p`
4134 * as determined by the storage classes of both.
4135 *
4136 * Params:
4137 * returnByRef = true if the function returns by ref
4138 * p = Parameter to compare with
4139 * Returns:
4140 * true = `this` can be used in place of `p`
4141 * false = nope
4142 */
4143 bool isCovariant(bool returnByRef, const Parameter p)
4144 const pure nothrow @nogc @safe
4145 {
4146 STC thisSTC = this.storageClass;
4147 STC otherSTC = p.storageClass;
4148
4149 if (thisSTC & STC.constscoperef)
4150 thisSTC |= STC.scope_;
4151 if (otherSTC & STC.constscoperef)
4152 otherSTC |= STC.scope_;
4153
4154 const mask = STC.ref_ | STC.out_ | STC.lazy_ | (((thisSTC | otherSTC) & STC.constscoperef) ? STC.in_ : STC.none);
4155 if ((thisSTC & mask) != (otherSTC & mask))
4156 return false;
4157 return isCovariantScope(returnByRef, thisSTC, otherSTC);
4158 }
4159
4160 extern (D) static bool isCovariantScope(bool returnByRef, STC from, STC to) pure nothrow @nogc @safe
4161 {
4162 // Workaround for failing covariance when finding a common type of delegates,
4163 // some of which have parameters with inferred scope
4164 // https://issues.dlang.org/show_bug.cgi?id=21285
4165 // The root cause is that scopeinferred is not part of the mangle, and mangle
4166 // is used for type equality checks
4167 if (to & STC.returninferred)
4168 to &= ~STC.return_;
4169 // note: f(return int* x) currently 'infers' scope without inferring `return`, in that case keep STC.scope
4170 if (to & STC.scopeinferred && !(to & STC.return_))
4171 to &= ~STC.scope_;
4172
4173 if (from == to)
4174 return true;
4175
4176 /* result is true if the 'from' can be used as a 'to'
4177 */
4178
4179 if ((from ^ to) & STC.ref_) // differing in 'ref' means no covariance
4180 return false;
4181
4182 /* workaround until we get STC.returnScope reliably set correctly
4183 */
4184 if (returnByRef)
4185 {
4186 from &= ~STC.returnScope;
4187 to &= ~STC.returnScope;
4188 }
4189 else
4190 {
4191 from |= STC.returnScope;
4192 to |= STC.returnScope;
4193 }
4194 return covariant[buildScopeRef(from)][buildScopeRef(to)];
4195 }
4196
4197 extern (D) private static bool[ScopeRef.max + 1][ScopeRef.max + 1] covariantInit() pure nothrow @nogc @safe
4198 {
4199 /* Initialize covariant[][] with this:
4200
4201 From\To n rs s
4202 None X
4203 ReturnScope X X
4204 Scope X X X
4205
4206 From\To r rr rs rr-s r-rs
4207 Ref X X
4208 ReturnRef X
4209 RefScope X X X X X
4210 ReturnRef-Scope X X
4211 Ref-ReturnScope X X X
4212 */
4213 bool[ScopeRef.max + 1][ScopeRef.max + 1] covariant;
4214
4215 foreach (i; 0 .. ScopeRef.max + 1)
4216 {
4217 covariant[i][i] = true;
4218 covariant[ScopeRef.RefScope][i] = true;
4219 }
4220 covariant[ScopeRef.ReturnScope][ScopeRef.None] = true;
4221 covariant[ScopeRef.Scope ][ScopeRef.None] = true;
4222 covariant[ScopeRef.Scope ][ScopeRef.ReturnScope] = true;
4223
4224 covariant[ScopeRef.Ref ][ScopeRef.ReturnRef] = true;
4225 covariant[ScopeRef.ReturnRef_Scope][ScopeRef.ReturnRef] = true;
4226 covariant[ScopeRef.Ref_ReturnScope][ScopeRef.Ref ] = true;
4227 covariant[ScopeRef.Ref_ReturnScope][ScopeRef.ReturnRef] = true;
4228
4229 return covariant;
4230 }
4231
4232 extern (D) private static immutable bool[ScopeRef.max + 1][ScopeRef.max + 1] covariant = covariantInit();
4233
4234 extern (D) bool opEquals(const Parameter other) const
4235 {
4236 return this.storageClass == other.storageClass
4237 && this.type == other.type;
4238 }
4239 }
4240
4241 /*************************************************************
4242 * For printing two types with qualification when necessary.
4243 * Params:
4244 * t1 = The first type to receive the type name for
4245 * t2 = The second type to receive the type name for
4246 * Returns:
4247 * The fully-qualified names of both types if the two type names are not the same,
4248 * or the unqualified names of both types if the two type names are the same.
4249 */
4250 const(char*)[2] toAutoQualChars(Type t1, Type t2)
4251 {
4252 auto s1 = t1.toChars();
4253 auto s2 = t2.toChars();
4254 // show qualification only if it's different
4255 if (!t1.equals(t2) && strcmp(s1, s2) == 0)
4256 {
4257 s1 = t1.toPrettyChars(true);
4258 s2 = t2.toPrettyChars(true);
4259 }
4260 return [s1, s2];
4261 }
4262
4263
4264 /**
4265 * For each active modifier (MODFlags.const_, MODFlags.immutable_, etc) call `fp` with a
4266 * void* for the work param and a string representation of the attribute.
4267 */
4268 void modifiersApply(const TypeFunction tf, void delegate(string) dg)
4269 {
4270 immutable ubyte[4] modsArr = [MODFlags.const_, MODFlags.immutable_, MODFlags.wild, MODFlags.shared_];
4271
4272 foreach (modsarr; modsArr)
4273 {
4274 if (tf.mod & modsarr)
4275 {
4276 dg(MODtoString(modsarr));
4277 }
4278 }
4279 }
4280
4281 /**
4282 * For each active attribute (ref/const/nogc/etc) call `fp` with a void* for the
4283 * work param and a string representation of the attribute.
4284 */
4285 void attributesApply(const TypeFunction tf, void delegate(string) dg, TRUSTformat trustFormat = TRUSTformatDefault)
4286 {
4287 if (tf.purity)
4288 dg("pure");
4289 if (tf.isNothrow)
4290 dg("nothrow");
4291 if (tf.isNogc)
4292 dg("@nogc");
4293 if (tf.isProperty)
4294 dg("@property");
4295 if (tf.isRef)
4296 dg("ref");
4297 if (tf.isReturn && !tf.isReturnInferred)
4298 dg("return");
4299 if (tf.isScopeQual && !tf.isScopeInferred)
4300 dg("scope");
4301 if (tf.isLive)
4302 dg("@live");
4303
4304 TRUST trustAttrib = tf.trust;
4305
4306 if (trustAttrib == TRUST.default_)
4307 {
4308 if (trustFormat != TRUSTformatSystem)
4309 return;
4310 trustAttrib = TRUST.system; // avoid calling with an empty string
4311 }
4312
4313 dg(trustToString(trustAttrib));
4314 }
4315
4316 /**
4317 * If the type is a class or struct, returns the symbol for it,
4318 * else null.
4319 */
4320 AggregateDeclaration isAggregate(Type t)
4321 {
4322 t = t.toBasetype();
4323 if (auto tc = t.isTypeClass())
4324 return tc.sym;
4325 if (auto ts = t.isTypeStruct())
4326 return ts.sym;
4327 return null;
4328 }
4329
4330 /***************************************************
4331 * Determine if type t can be indexed or sliced given that it is not an
4332 * aggregate with operator overloads.
4333 * Params:
4334 * t = type to check
4335 * Returns:
4336 * true if an expression of type t can be e1 in an array expression
4337 */
4338 bool isIndexableNonAggregate(Type t)
4339 {
4340 t = t.toBasetype();
4341 return (t.ty == Tpointer || t.isStaticOrDynamicArray() || t.ty == Taarray ||
4342 t.ty == Ttuple || t.ty == Tvector);
4343 }
4344
4345 /***************************************
4346 * Computes how a parameter may be returned.
4347 * Shrinking the representation is necessary because STC is so wide
4348 * Params:
4349 * stc = storage class of parameter
4350 * Returns:
4351 * value from enum ScopeRef
4352 */
4353 ScopeRef buildScopeRef(STC stc) pure nothrow @nogc @safe
4354 {
4355 if (stc & STC.out_)
4356 stc |= STC.ref_; // treat `out` and `ref` the same
4357
4358 ScopeRef result;
4359 switch (stc & (STC.ref_ | STC.scope_ | STC.return_))
4360 {
4361 case STC.none: result = ScopeRef.None; break;
4362
4363 /* can occur in case test/compilable/testsctreturn.d
4364 * related to https://issues.dlang.org/show_bug.cgi?id=20149
4365 * where inout adds `return` without `scope` or `ref`
4366 */
4367 case STC.return_: result = ScopeRef.Return; break;
4368
4369 case STC.ref_: result = ScopeRef.Ref; break;
4370 case STC.scope_: result = ScopeRef.Scope; break;
4371 case STC.return_ | STC.ref_: result = ScopeRef.ReturnRef; break;
4372 case STC.return_ | STC.scope_: result = ScopeRef.ReturnScope; break;
4373 case STC.ref_ | STC.scope_: result = ScopeRef.RefScope; break;
4374
4375 case STC.return_ | STC.ref_ | STC.scope_:
4376 result = stc & STC.returnScope ? ScopeRef.Ref_ReturnScope
4377 : ScopeRef.ReturnRef_Scope;
4378 break;
4379 default:
4380 assert(0);
4381 }
4382 return result;
4383 }
4384
4385 /**
4386 * Classification of 'scope-return-ref' possibilities
4387 */
4388 enum ScopeRef
4389 {
4390 None,
4391 Scope,
4392 ReturnScope,
4393 Ref,
4394 ReturnRef,
4395 RefScope,
4396 ReturnRef_Scope,
4397 Ref_ReturnScope,
4398 Return,
4399 }
4400
4401 /*********************************
4402 * Give us a nice string for debugging purposes.
4403 * Params:
4404 * sr = value
4405 * Returns:
4406 * corresponding string
4407 */
4408 const(char)* ScopeRefToChars(ScopeRef sr) pure nothrow @nogc @safe
4409 {
4410 with (ScopeRef)
4411 {
4412 static immutable char*[ScopeRef.max + 1] names =
4413 [
4414 None: "None",
4415 Scope: "Scope",
4416 ReturnScope: "ReturnScope",
4417 Ref: "Ref",
4418 ReturnRef: "ReturnRef",
4419 RefScope: "RefScope",
4420 ReturnRef_Scope: "ReturnRef_Scope",
4421 Ref_ReturnScope: "Ref_ReturnScope",
4422 Return: "Return",
4423 ];
4424 return names[sr];
4425 }
4426 }
4427
4428 /**
4429 * Creates an appropriate vector type for `tv` that will hold one boolean
4430 * result for each element of the vector type. The result of vector comparisons
4431 * is a single or doubleword mask of all 1s (comparison true) or all 0s
4432 * (comparison false). This SIMD mask type does not have an equivalent D type,
4433 * however its closest equivalent would be an integer vector of the same unit
4434 * size and length.
4435 *
4436 * Params:
4437 * tv = The `TypeVector` to build a vector from.
4438 * Returns:
4439 * A vector type suitable for the result of a vector comparison operation.
4440 */
4441 TypeVector toBooleanVector(TypeVector tv)
4442 {
4443 Type telem = tv.elementType();
4444 switch (telem.ty)
4445 {
4446 case Tvoid:
4447 case Tint8:
4448 case Tuns8:
4449 case Tint16:
4450 case Tuns16:
4451 case Tint32:
4452 case Tuns32:
4453 case Tint64:
4454 case Tuns64:
4455 // No need to build an equivalent mask type.
4456 return tv;
4457
4458 case Tfloat32:
4459 telem = Type.tuns32;
4460 break;
4461
4462 case Tfloat64:
4463 telem = Type.tuns64;
4464 break;
4465
4466 default:
4467 assert(0);
4468 }
4469
4470 TypeSArray tsa = tv.basetype.isTypeSArray();
4471 assert(tsa !is null);
4472
4473 return new TypeVector(new TypeSArray(telem, tsa.dim));
4474 }
4475
4476 /*************************************************
4477 * Dispatch to function based on static type of Type.
4478 */
4479 mixin template VisitType(Result)
4480 {
4481 Result VisitType(Type t)
4482 {
4483 final switch (t.ty)
4484 {
4485 case TY.Tvoid:
4486 case TY.Tint8:
4487 case TY.Tuns8:
4488 case TY.Tint16:
4489 case TY.Tuns16:
4490 case TY.Tint32:
4491 case TY.Tuns32:
4492 case TY.Tint64:
4493 case TY.Tuns64:
4494 case TY.Tfloat32:
4495 case TY.Tfloat64:
4496 case TY.Tfloat80:
4497 case TY.Timaginary32:
4498 case TY.Timaginary64:
4499 case TY.Timaginary80:
4500 case TY.Tcomplex32:
4501 case TY.Tcomplex64:
4502 case TY.Tcomplex80:
4503 case TY.Tbool:
4504 case TY.Tchar:
4505 case TY.Twchar:
4506 case TY.Tdchar:
4507 case TY.Tint128:
4508 case TY.Tuns128: mixin(visitTYCase("Basic"));
4509 case TY.Tarray: mixin(visitTYCase("DArray"));
4510 case TY.Tsarray: mixin(visitTYCase("SArray"));
4511 case TY.Taarray: mixin(visitTYCase("AArray"));
4512 case TY.Tpointer: mixin(visitTYCase("Pointer"));
4513 case TY.Treference: mixin(visitTYCase("Reference"));
4514 case TY.Tfunction: mixin(visitTYCase("Function"));
4515 case TY.Tident: mixin(visitTYCase("Identifier"));
4516 case TY.Tclass: mixin(visitTYCase("Class"));
4517 case TY.Tstruct: mixin(visitTYCase("Struct"));
4518 case TY.Tenum: mixin(visitTYCase("Enum"));
4519 case TY.Tdelegate: mixin(visitTYCase("Delegate"));
4520 case TY.Terror: mixin(visitTYCase("Error"));
4521 case TY.Tinstance: mixin(visitTYCase("Instance"));
4522 case TY.Ttypeof: mixin(visitTYCase("Typeof"));
4523 case TY.Ttuple: mixin(visitTYCase("Tuple"));
4524 case TY.Tslice: mixin(visitTYCase("Slice"));
4525 case TY.Treturn: mixin(visitTYCase("Return"));
4526 case TY.Tnull: mixin(visitTYCase("Null"));
4527 case TY.Tvector: mixin(visitTYCase("Vector"));
4528 case TY.Ttraits: mixin(visitTYCase("Traits"));
4529 case TY.Tmixin: mixin(visitTYCase("Mixin"));
4530 case TY.Tnoreturn: mixin(visitTYCase("Noreturn"));
4531 case TY.Ttag: mixin(visitTYCase("Tag"));
4532 case TY.Tnone: assert(0);
4533 }
4534 }
4535 }
4536
4537 /****************************************
4538 * CTFE-only helper function for VisitInitializer.
4539 * Params:
4540 * handler = string for the name of the visit handler
4541 * Returns: boilerplate code for a case
4542 */
4543 pure string visitTYCase(string handler) @safe
4544 {
4545 if (__ctfe)
4546 {
4547 return
4548 "
4549 enum isVoid = is(Result == void);
4550 auto tx = t.isType"~handler~"();
4551 static if (__traits(compiles, visit"~handler~"(tx)))
4552 {
4553 static if (isVoid)
4554 {
4555 visit"~handler~"(tx);
4556 return;
4557 }
4558 else
4559 {
4560 if (Result r = visit"~handler~"(tx))
4561 return r;
4562 return Result.init;
4563 }
4564 }
4565 else static if (__traits(compiles, visitDefaultCase(t)))
4566 {
4567 static if (isVoid)
4568 {
4569 visitDefaultCase(tx);
4570 return;
4571 }
4572 else
4573 {
4574 if (Result r = visitDefaultCase(t))
4575 return r;
4576 return Result.init;
4577 }
4578 }
4579 else
4580 static assert(0, "~handler~");
4581 ";
4582 }
4583 assert(0);
4584 }
4585
4586
4587 /**
4588 * Returns:
4589 * `TypeIdentifier` corresponding to `object.Throwable`
4590 */
4591 TypeIdentifier getThrowable()
4592 {
4593 auto tid = new TypeIdentifier(Loc.initial, Id.empty);
4594 tid.addIdent(Id.object);
4595 tid.addIdent(Id.Throwable);
4596 return tid;
4597 }
4598
4599 /**
4600 * Returns:
4601 * TypeIdentifier corresponding to `object.Exception`
4602 */
4603 TypeIdentifier getException()
4604 {
4605 auto tid = new TypeIdentifier(Loc.initial, Id.empty);
4606 tid.addIdent(Id.object);
4607 tid.addIdent(Id.Exception);
4608 return tid;
4609 }