Debian Codegraph @

gcc/d/dmd/typesem.d

raw
1 /**
2 * Semantic analysis for D types.
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/typesem.d, _typesem.d)
8 * Documentation: https://dlang.org/phobos/dmd_typesem.html
9 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/typesem.d
10 */
11
12 module dmd.typesem;
13
14 import core.checkedint;
15 import core.stdc.string;
16 import core.stdc.stdio;
17
18 import dmd.access;
19 import dmd.aggregate;
20 import dmd.aliasthis;
21 import dmd.arrayop;
22 import dmd.arraytypes;
23 import dmd.astcodegen;
24 import dmd.astenums;
25 import dmd.dcast;
26 import dmd.dclass;
27 import dmd.declaration;
28 import dmd.denum;
29 import dmd.dimport;
30 import dmd.dinterpret;
31 import dmd.dmodule;
32 import dmd.dscope;
33 import dmd.dstruct;
34 import dmd.dsymbol;
35 import dmd.dsymbolsem;
36 import dmd.dtemplate;
37 import dmd.enumsem;
38 import dmd.errors;
39 import dmd.errorsink;
40 import dmd.expression;
41 import dmd.expressionsem;
42 import dmd.func;
43 import dmd.funcsem;
44 import dmd.globals;
45 import dmd.hdrgen;
46 import dmd.id;
47 import dmd.identifier;
48 import dmd.imphint;
49 import dmd.importc;
50 import dmd.init;
51 import dmd.initsem;
52 import dmd.location;
53 import dmd.visitor;
54 import dmd.mtype;
55 import dmd.mangle;
56 import dmd.nogc;
57 import dmd.objc;
58 import dmd.opover;
59 import dmd.optimize;
60 import dmd.parse;
61 import dmd.root.complex;
62 import dmd.root.ctfloat;
63 import dmd.root.rmem;
64 import dmd.common.outbuffer;
65 import dmd.rootobject;
66 import dmd.root.string;
67 import dmd.root.stringtable;
68 import dmd.safe;
69 import dmd.semantic3;
70 import dmd.sideeffect;
71 import dmd.target;
72 import dmd.tokens;
73
74 /*************************************
75 * Resolve a tuple index, `s[oindex]`, by figuring out what `s[oindex]` represents.
76 * Setting one of pe/pt/ps.
77 * Params:
78 * loc = location for error messages
79 * sc = context
80 * s = symbol being indexed - could be a tuple, could be an expression
81 * pe = set if s[oindex] is an Expression, otherwise null
82 * pt = set if s[oindex] is a Type, otherwise null
83 * ps = set if s[oindex] is a Dsymbol, otherwise null
84 * oindex = index into s
85 */
86 private void resolveTupleIndex(Loc loc, Scope* sc, Dsymbol s, out Expression pe, out Type pt, out Dsymbol ps, RootObject oindex)
87 {
88 auto tup = s.isTupleDeclaration();
89
90 auto eindex = isExpression(oindex);
91 auto tindex = isType(oindex);
92 auto sindex = isDsymbol(oindex);
93
94 if (!tup)
95 {
96 // It's really an index expression
97 if (tindex)
98 eindex = new TypeExp(loc, tindex);
99 else if (sindex)
100 eindex = symbolToExp(sindex, loc, sc, false);
101 Expression e = new IndexExp(loc, symbolToExp(s, loc, sc, false), eindex);
102 e = e.expressionSemantic(sc);
103 resolveExp(e, pt, pe, ps);
104 return;
105 }
106
107 // Convert oindex to Expression, then try to resolve to constant.
108 if (tindex)
109 tindex.resolve(loc, sc, eindex, tindex, sindex);
110 if (sindex)
111 eindex = symbolToExp(sindex, loc, sc, false);
112 if (!eindex)
113 {
114 .error(loc, "index `%s` is not an expression", oindex.toChars());
115 pt = Type.terror;
116 return;
117 }
118
119 eindex = semanticLength(sc, tup, eindex);
120 eindex = eindex.ctfeInterpret();
121 if (eindex.op == EXP.error)
122 {
123 pt = Type.terror;
124 return;
125 }
126 const(uinteger_t) d = eindex.toUInteger();
127 if (d >= tup.objects.length)
128 {
129 .error(loc, "sequence index `%llu` out of bounds `[0 .. %llu]`", d, cast(ulong)tup.objects.length);
130 pt = Type.terror;
131 return;
132 }
133
134 RootObject o = (*tup.objects)[cast(size_t)d];
135 ps = isDsymbol(o);
136 if (auto t = isType(o))
137 pt = t.typeSemantic(loc, sc);
138 if (auto e = isExpression(o))
139 resolveExp(e, pt, pe, ps);
140 }
141
142 /*************************************
143 * Takes an array of Identifiers and figures out if
144 * it represents a Type, Expression, or Dsymbol.
145 * Params:
146 * mt = array of identifiers
147 * loc = location for error messages
148 * sc = context
149 * s = symbol to start search at
150 * scopesym = unused
151 * pe = set if expression otherwise null
152 * pt = set if type otherwise null
153 * ps = set if symbol otherwise null
154 * typeid = set if in TypeidExpression https://dlang.org/spec/expression.html#TypeidExpression
155 */
156 private void resolveHelper(TypeQualified mt, Loc loc, Scope* sc, Dsymbol s, Dsymbol scopesym,
157 out Expression pe, out Type pt, out Dsymbol ps, bool intypeid = false)
158 {
159 version (none)
160 {
161 printf("TypeQualified::resolveHelper(sc = %p, idents = '%s')\n", sc, mt.toChars());
162 if (scopesym)
163 printf("\tscopesym = '%s'\n", scopesym.toChars());
164 }
165
166 if (!s)
167 {
168 /* Look for what user might have intended
169 */
170 const p = mt.mutableOf().unSharedOf().toChars();
171 auto id = Identifier.idPool(p[0 .. strlen(p)]);
172 if (const n = importHint(id.toString()))
173 error(loc, "`%s` is not defined, perhaps `import %.*s;` ?", p, cast(int)n.length, n.ptr);
174 else if (auto s2 = sc.search_correct(id))
175 error(loc, "undefined identifier `%s`, did you mean %s `%s`?", p, s2.kind(), s2.toChars());
176 else if (const q = Scope.search_correct_C(id))
177 error(loc, "undefined identifier `%s`, did you mean `%s`?", p, q);
178 else if ((id == Id.This && sc.getStructClassScope()) ||
179 (id == Id._super && sc.getClassScope()))
180 error(loc, "undefined identifier `%s`, did you mean `typeof(%s)`?", p, p);
181 else
182 error(loc, "undefined identifier `%s`", p);
183
184 pt = Type.terror;
185 return;
186 }
187
188 //printf("\t1: s = '%s' %p, kind = '%s'\n",s.toChars(), s, s.kind());
189 Declaration d = s.isDeclaration();
190 if (d && (d.storage_class & STC.templateparameter))
191 s = s.toAlias();
192 else
193 {
194 // check for deprecated or disabled aliases
195 // functions are checked after overloading
196 // templates are checked after matching constraints
197 if (!s.isFuncDeclaration() && !s.isTemplateDeclaration())
198 s.checkDeprecated(loc, sc);
199 if (d)
200 d.checkDisabled(loc, sc, true);
201 }
202 s = s.toAlias();
203 //printf("\t2: s = '%s' %p, kind = '%s'\n",s.toChars(), s, s.kind());
204 for (size_t i = 0; i < mt.idents.length; i++)
205 {
206 RootObject id = mt.idents[i];
207 switch (id.dyncast()) with (DYNCAST)
208 {
209 case expression:
210 case type:
211 Type tx;
212 Expression ex;
213 Dsymbol sx;
214 resolveTupleIndex(loc, sc, s, ex, tx, sx, id);
215 if (sx)
216 {
217 s = sx.toAlias();
218 continue;
219 }
220 if (tx)
221 ex = new TypeExp(loc, tx);
222 assert(ex);
223
224 ex = typeToExpressionHelper(mt, ex, i + 1);
225 ex = ex.expressionSemantic(sc);
226 resolveExp(ex, pt, pe, ps);
227 return;
228 default:
229 break;
230 }
231
232 Type t = s.getType(); // type symbol, type alias, or type tuple?
233 const errorsave = global.errors;
234 SearchOptFlags flags = t is null ? SearchOpt.localsOnly : SearchOpt.ignorePrivateImports;
235
236 Dsymbol sm = s.searchX(loc, sc, id, flags);
237 if (sm)
238 {
239 if (!sc.ignoresymbolvisibility && !symbolIsVisible(sc, sm))
240 {
241 .error(loc, "`%s` is not visible from module `%s`", sm.toPrettyChars(), sc._module.toChars());
242 sm = null;
243 }
244 // Same check as in dotIdSemanticProp(DotIdExp)
245 else if (sm.isPackage() && checkAccess(sc, sm.isPackage()))
246 {
247 // @@@DEPRECATED_2.106@@@
248 // Should be an error in 2.106. Just remove the deprecation call
249 // and uncomment the null assignment
250 deprecation(loc, "%s %s is not accessible here, perhaps add 'static import %s;'", sm.kind(), sm.toPrettyChars(), sm.toPrettyChars());
251 //sm = null;
252 }
253 }
254 if (global.errors != errorsave)
255 {
256 pt = Type.terror;
257 return;
258 }
259
260 void helper3()
261 {
262 Expression e;
263 VarDeclaration v = s.isVarDeclaration();
264 FuncDeclaration f = s.isFuncDeclaration();
265 if (intypeid || !v && !f)
266 e = symbolToExp(s, loc, sc, true);
267 else
268 e = new VarExp(loc, s.isDeclaration(), true);
269
270 e = typeToExpressionHelper(mt, e, i);
271 e = e.expressionSemantic(sc);
272 resolveExp(e, pt, pe, ps);
273 }
274
275 //printf("\t3: s = %p %s %s, sm = %p\n", s, s.kind(), s.toChars(), sm);
276 if (intypeid && !t && sm && sm.needThis())
277 return helper3();
278
279 if (VarDeclaration v = s.isVarDeclaration())
280 {
281 // https://issues.dlang.org/show_bug.cgi?id=19913
282 // v.type would be null if it is a forward referenced member.
283 if (v.type is null)
284 v.dsymbolSemantic(sc);
285 if (v.storage_class & (STC.const_ | STC.immutable_ | STC.manifest) ||
286 v.type.isConst() || v.type.isImmutable())
287 {
288 // https://issues.dlang.org/show_bug.cgi?id=13087
289 // this.field is not constant always
290 if (!v.isThisDeclaration())
291 return helper3();
292 }
293 }
294
295 if (!sm)
296 return helper3();
297
298 if (sm.isAliasDeclaration)
299 sm.checkDeprecated(loc, sc);
300 s = sm.toAlias();
301 }
302
303 if (auto em = s.isEnumMember())
304 {
305 // It's not a type, it's an expression
306 pe = em.getVarExp(loc, sc);
307 return;
308 }
309 if (auto v = s.isVarDeclaration())
310 {
311 /* This is mostly same with DsymbolExp::semantic(), but we cannot use it
312 * because some variables used in type context need to prevent lowering
313 * to a literal or contextful expression. For example:
314 *
315 * enum a = 1; alias b = a;
316 * template X(alias e){ alias v = e; } alias x = X!(1);
317 * struct S { int v; alias w = v; }
318 * // TypeIdentifier 'a', 'e', and 'v' should be EXP.variable,
319 * // because getDsymbol() need to work in AliasDeclaration::semantic().
320 */
321 if (!v.type ||
322 !v.type.deco && v.inuse)
323 {
324 if (v.inuse) // https://issues.dlang.org/show_bug.cgi?id=9494
325 error(loc, "circular reference to %s `%s`", v.kind(), v.toPrettyChars());
326 else
327 error(loc, "forward reference to %s `%s`", v.kind(), v.toPrettyChars());
328 pt = Type.terror;
329 return;
330 }
331 if (v.type.ty == Terror)
332 pt = Type.terror;
333 else
334 pe = new VarExp(loc, v);
335 return;
336 }
337 if (auto fld = s.isFuncLiteralDeclaration())
338 {
339 //printf("'%s' is a function literal\n", fld.toChars());
340 auto e = new FuncExp(loc, fld);
341 pe = e.expressionSemantic(sc);
342 return;
343 }
344 version (none)
345 {
346 if (FuncDeclaration fd = s.isFuncDeclaration())
347 {
348 pe = new DsymbolExp(loc, fd);
349 return;
350 }
351 }
352
353 Type t;
354 while (1)
355 {
356 t = s.getType();
357 if (t)
358 break;
359 ps = s;
360 return;
361 }
362
363 if (auto ti = t.isTypeInstance())
364 if (ti != mt && !ti.deco)
365 {
366 if (!ti.tempinst.errors)
367 error(loc, "forward reference to `%s`", ti.toChars());
368 pt = Type.terror;
369 return;
370 }
371
372 if (t.ty == Ttuple)
373 pt = t;
374 else
375 pt = t.merge();
376 }
377
378 /***************************************
379 * Search for identifier id as a member of `this`.
380 * `id` may be a template instance.
381 *
382 * Params:
383 * loc = location to print the error messages
384 * sc = the scope where the symbol is located
385 * id = the id of the symbol
386 * flags = the search flags which can be `SearchLocalsOnly` or `SearchOpt.ignorePrivateImports`
387 *
388 * Returns:
389 * symbol found, NULL if not
390 */
391 private Dsymbol searchX(Dsymbol dsym, Loc loc, Scope* sc, RootObject id, SearchOptFlags flags)
392 {
393 //printf("Dsymbol::searchX(this=%p,%s, ident='%s')\n", this, toChars(), ident.toChars());
394 Dsymbol s = dsym.toAlias();
395 Dsymbol sm;
396 if (Declaration d = s.isDeclaration())
397 {
398 if (d.inuse)
399 {
400 .error(loc, "circular reference to `%s`", d.toPrettyChars());
401 return null;
402 }
403 }
404 switch (id.dyncast())
405 {
406 case DYNCAST.identifier:
407 sm = s.search(loc, cast(Identifier)id, flags);
408 break;
409 case DYNCAST.dsymbol:
410 {
411 // It's a template instance
412 //printf("\ttemplate instance id\n");
413 Dsymbol st = cast(Dsymbol)id;
414 TemplateInstance ti = st.isTemplateInstance();
415 sm = s.search(loc, ti.name);
416 if (!sm)
417 return null;
418 sm = sm.toAlias();
419 TemplateDeclaration td = sm.isTemplateDeclaration();
420 if (!td)
421 return null; // error but handled later
422 ti.tempdecl = td;
423 if (!ti.semanticRun)
424 ti.dsymbolSemantic(sc);
425 sm = ti.toAlias();
426 break;
427 }
428 case DYNCAST.type:
429 case DYNCAST.expression:
430 default:
431 assert(0);
432 }
433 return sm;
434 }
435
436 /***************************************************
437 * Determine if type t is copyable.
438 * Params:
439 * t = type to check
440 * Returns:
441 * true if we can copy it
442 */
443 bool isCopyable(Type t)
444 {
445 //printf("isCopyable() %s\n", t.toChars());
446 if (auto ts = t.isTypeStruct())
447 {
448 if (ts.sym.postblit &&
449 ts.sym.postblit.storage_class & STC.disable)
450 return false;
451 if (ts.sym.hasCopyCtor)
452 {
453 // check if there is a matching overload of the copy constructor and whether it is disabled or not
454 // `assert(ctor)` fails on Win32 and Win_32_64. See: https://auto-tester.puremagic.com/pull-history.ghtml?projectid=1&repoid=1&pullid=10575
455 Dsymbol ctor = search_function(ts.sym, Id.ctor);
456 assert(ctor);
457 scope el = new IdentifierExp(Loc.initial, Id.p); // dummy lvalue
458 el.type = cast() ts;
459 Expressions* args = new Expressions();
460 args.push(el);
461 FuncDeclaration f = resolveFuncCall(Loc.initial, null, ctor, null, cast()ts, ArgumentList(args), FuncResolveFlag.quiet);
462 if (!f || f.storage_class & STC.disable)
463 return false;
464 }
465 }
466 return true;
467 }
468
469 /************************************
470 * Determine mutability of indirections in (ref) t.
471 *
472 * Returns: When the type has any mutable indirections, returns 0.
473 * When all indirections are immutable, returns 2.
474 * Otherwise, when the type has const/inout indirections, returns 1.
475 *
476 * Params:
477 * isRef = if true, check `ref t`; otherwise, check just `t`
478 * t = the type that is being checked
479 */
480 int mutabilityOfType(bool isRef, Type t)
481 {
482 if (isRef)
483 {
484 if (t.mod & MODFlags.immutable_)
485 return 2;
486 if (t.mod & (MODFlags.const_ | MODFlags.wild))
487 return 1;
488 return 0;
489 }
490
491 t = t.baseElemOf();
492
493 if (!t.hasPointers() || t.mod & MODFlags.immutable_)
494 return 2;
495
496 /* Accept immutable(T)[] and immutable(T)* as being strongly pure
497 */
498 if (t.ty == Tarray || t.ty == Tpointer)
499 {
500 Type tn = t.nextOf().toBasetype();
501 if (tn.mod & MODFlags.immutable_)
502 return 2;
503 if (tn.mod & (MODFlags.const_ | MODFlags.wild))
504 return 1;
505 }
506
507 /* The rest of this is too strict; fix later.
508 * For example, the only pointer members of a struct may be immutable,
509 * which would maintain strong purity.
510 * (Just like for dynamic arrays and pointers above.)
511 */
512 if (t.mod & (MODFlags.const_ | MODFlags.wild))
513 return 1;
514
515 /* Should catch delegates and function pointers, and fold in their purity
516 */
517 return 0;
518 }
519
520 /********************************************
521 * Set 'purity' field of 'typeFunction'.
522 * Do this lazily, as the parameter types might be forward referenced.
523 */
524 void purityLevel(TypeFunction typeFunction)
525 {
526 TypeFunction tf = typeFunction;
527 if (tf.purity != PURE.fwdref)
528 return;
529
530 typeFunction.purity = PURE.const_; // assume strong until something weakens it
531
532 /* Evaluate what kind of purity based on the modifiers for the parameters
533 */
534 foreach (i, fparam; tf.parameterList)
535 {
536 Type t = fparam.type;
537 if (!t)
538 continue;
539
540 if (fparam.storageClass & (STC.lazy_ | STC.out_))
541 {
542 typeFunction.purity = PURE.weak;
543 break;
544 }
545 const pref = (fparam.storageClass & STC.ref_) != 0;
546 if (mutabilityOfType(pref, t) == 0)
547 typeFunction.purity = PURE.weak;
548 }
549
550 tf.purity = typeFunction.purity;
551 }
552
553 /******************************************
554 * We've mistakenly parsed `t` as a type.
555 * Redo `t` as an Expression only if there are no type modifiers.
556 * Params:
557 * t = mistaken type
558 * Returns:
559 * t redone as Expression, null if cannot
560 */
561 Expression typeToExpression(Type t)
562 {
563 static Expression visitSArray(TypeSArray t)
564 {
565 if (auto e = t.next.typeToExpression())
566 return new ArrayExp(t.dim.loc, e, t.dim);
567 return null;
568 }
569
570 static Expression visitAArray(TypeAArray t)
571 {
572 if (auto e = t.next.typeToExpression())
573 {
574 if (auto ei = t.index.typeToExpression())
575 return new ArrayExp(t.loc, e, ei);
576 }
577 return null;
578 }
579
580 static Expression visitIdentifier(TypeIdentifier t)
581 {
582 return typeToExpressionHelper(t, new IdentifierExp(t.loc, t.ident));
583 }
584
585 static Expression visitInstance(TypeInstance t)
586 {
587 return typeToExpressionHelper(t, new ScopeExp(t.loc, t.tempinst));
588 }
589
590 // easy way to enable 'auto v = new int[mixin("exp")];' in 2.088+
591 static Expression visitMixin(TypeMixin t)
592 {
593 return new TypeExp(t.loc, t);
594 }
595
596 if (t.mod)
597 return null;
598 switch (t.ty)
599 {
600 case Tsarray: return visitSArray(t.isTypeSArray());
601 case Taarray: return visitAArray(t.isTypeAArray());
602 case Tident: return visitIdentifier(t.isTypeIdentifier());
603 case Tinstance: return visitInstance(t.isTypeInstance());
604 case Tmixin: return visitMixin(t.isTypeMixin());
605 default: return null;
606 }
607 }
608
609 /*************************************
610 * https://issues.dlang.org/show_bug.cgi?id=14488
611 * Check if the inner most base type is complex or imaginary.
612 * Should only give alerts when set to emit transitional messages.
613 * Params:
614 * type = type to check
615 * loc = The source location.
616 * sc = scope of the type
617 */
618 extern (D) bool checkComplexTransition(Type type, Loc loc, Scope* sc)
619 {
620 if (sc.isDeprecated())
621 return false;
622 // Don't complain if we're inside a template constraint
623 // https://issues.dlang.org/show_bug.cgi?id=21831
624 if (sc.inTemplateConstraint)
625 return false;
626
627 Type t = type.baseElemOf();
628 while (t.ty == Tpointer || t.ty == Tarray)
629 t = t.nextOf().baseElemOf();
630
631 // Basetype is an opaque enum, nothing to check.
632 if (t.ty == Tenum && !(cast(TypeEnum)t).sym.memtype)
633 return false;
634
635 if (t.isImaginary() || t.isComplex())
636 {
637 if (sc.inCfile)
638 return true; // complex/imaginary not deprecated in C code
639 Type rt;
640 switch (t.ty)
641 {
642 case Tcomplex32:
643 case Timaginary32:
644 rt = Type.tfloat32;
645 break;
646
647 case Tcomplex64:
648 case Timaginary64:
649 rt = Type.tfloat64;
650 break;
651
652 case Tcomplex80:
653 case Timaginary80:
654 rt = Type.tfloat80;
655 break;
656
657 default:
658 assert(0);
659 }
660 // @@@DEPRECATED_2.117@@@
661 // Deprecated in 2.097 - Can be made an error from 2.117.
662 // The deprecation period is longer than usual as `cfloat`,
663 // `cdouble`, and `creal` were quite widely used.
664 if (t.isComplex())
665 {
666 deprecation(loc, "use of complex type `%s` is deprecated, use `std.complex.Complex!(%s)` instead",
667 type.toChars(), rt.toChars());
668 return true;
669 }
670 else
671 {
672 deprecation(loc, "use of imaginary type `%s` is deprecated, use `%s` instead",
673 type.toChars(), rt.toChars());
674 return true;
675 }
676 }
677 return false;
678 }
679
680 /********************************
681 * 'args' are being matched to function type 'tf'
682 * Determine match level.
683 * Params:
684 * fd = function being called, if a symbol
685 * tf = function type
686 * tthis = type of `this` pointer, null if not member function
687 * argumentList = arguments to function call
688 * flag = 1: performing a partial ordering match
689 * errorHelper = delegate to call for error messages
690 * sc = context
691 * Returns:
692 * MATCHxxxx
693 */
694 extern (D) MATCH callMatch(FuncDeclaration fd, TypeFunction tf, Type tthis, ArgumentList argumentList,
695 int flag = 0, void delegate(const(char)*) scope errorHelper = null, Scope* sc = null)
696 {
697 //printf("callMatch() fd: %s, tf: %s\n", fd ? fd.ident.toChars() : "null", toChars(tf));
698 MATCH match = MATCH.exact; // assume exact match
699 ubyte wildmatch = 0;
700
701 if (tthis)
702 {
703 Type t = tthis;
704 if (t.toBasetype().ty == Tpointer)
705 t = t.toBasetype().nextOf(); // change struct* to struct
706 if (t.mod != tf.mod)
707 {
708 if (MODimplicitConv(t.mod, tf.mod))
709 match = MATCH.constant;
710 else if ((tf.mod & MODFlags.wild) && MODimplicitConv(t.mod, (tf.mod & ~MODFlags.wild) | MODFlags.const_))
711 {
712 match = MATCH.constant;
713 }
714 else
715 return MATCH.nomatch;
716 }
717 if (tf.isWild())
718 {
719 if (t.isWild())
720 wildmatch |= MODFlags.wild;
721 else if (t.isConst())
722 wildmatch |= MODFlags.const_;
723 else if (t.isImmutable())
724 wildmatch |= MODFlags.immutable_;
725 else
726 wildmatch |= MODFlags.mutable;
727 }
728 }
729
730 ParameterList* parameterList = &tf.parameterList;
731 const nparams = parameterList.length;
732 if (argumentList.length > nparams)
733 {
734 if (parameterList.varargs == VarArg.none)
735 {
736 // suppress early exit if an error message is wanted,
737 // so we can check any matching args are valid
738 if (!errorHelper)
739 return MATCH.nomatch;
740 }
741 // too many args; no match
742 match = MATCH.convert; // match ... with a "conversion" match level
743 }
744
745 // https://issues.dlang.org/show_bug.cgi?id=22997
746 if (parameterList.varargs == VarArg.none && nparams > argumentList.length && !parameterList.hasDefaultArgs)
747 {
748 if (errorHelper)
749 {
750 OutBuffer buf;
751 buf.printf("too few arguments, expected %d, got %d", cast(int)nparams, cast(int)argumentList.length);
752 errorHelper(buf.peekChars());
753 }
754 return MATCH.nomatch;
755 }
756 const(char)* failMessage;
757 const(char)** pMessage = errorHelper ? &failMessage : null;
758 OutBuffer buf;
759 auto resolvedArgs = tf.resolveNamedArgs(argumentList, errorHelper ? &buf : null);
760 Expression[] args;
761 if (!resolvedArgs)
762 {
763 if (buf.length)
764 {
765 errorHelper(buf.peekChars());
766 return MATCH.nomatch;
767 }
768
769 // if no message was provided, it was because of overflow which will be diagnosed below
770 match = MATCH.nomatch;
771 args = argumentList.arguments ? (*argumentList.arguments)[] : null;
772 }
773 else
774 {
775 args = (*resolvedArgs)[];
776 }
777
778 foreach (u, p; *parameterList)
779 {
780 if (u >= args.length)
781 break;
782
783 Expression arg = args[u];
784 if (!arg)
785 continue; // default argument
786
787 Type tprm = p.type;
788 Type targ = arg.type;
789
790 if (!(p.isLazy() && tprm.ty == Tvoid && targ.ty != Tvoid))
791 {
792 const isRef = p.isReference();
793 wildmatch |= targ.deduceWild(tprm, isRef);
794 }
795 }
796 if (wildmatch)
797 {
798 /* Calculate wild matching modifier
799 */
800 if (wildmatch & MODFlags.const_ || wildmatch & (wildmatch - 1))
801 wildmatch = MODFlags.const_;
802 else if (wildmatch & MODFlags.immutable_)
803 wildmatch = MODFlags.immutable_;
804 else if (wildmatch & MODFlags.wild)
805 wildmatch = MODFlags.wild;
806 else
807 {
808 assert(wildmatch & MODFlags.mutable);
809 wildmatch = MODFlags.mutable;
810 }
811 }
812
813 foreach (u, p; *parameterList)
814 {
815 MATCH m;
816
817 assert(p);
818
819 // One or more arguments remain
820 if (u < args.length)
821 {
822 Expression arg = args[u];
823 if (!arg)
824 continue; // default argument
825 m = argumentMatchParameter(fd, tf, p, arg, wildmatch, flag, sc, pMessage);
826 if (failMessage)
827 {
828 buf.reset();
829 buf.writestring(failMessage);
830 }
831 }
832 else if (p.defaultArg)
833 continue;
834
835 /* prefer matching the element type rather than the array
836 * type when more arguments are present with T[]...
837 */
838 if (parameterList.varargs == VarArg.typesafe && u + 1 == nparams && args.length > nparams)
839 goto L1;
840
841 //printf("\tm = %d\n", m);
842 if (m == MATCH.nomatch) // if no match
843 {
844 L1:
845 if (parameterList.varargs == VarArg.typesafe && u + 1 == nparams) // if last varargs param
846 {
847 Expression[] trailingArgs;
848 if (args.length >= u)
849 trailingArgs = args[u .. $];
850 if (auto vmatch = matchTypeSafeVarArgs(tf, p, trailingArgs, pMessage))
851 return vmatch < match ? vmatch : match;
852 // Error message was already generated in `matchTypeSafeVarArgs`
853 if (failMessage)
854 errorHelper(failMessage);
855 return MATCH.nomatch;
856 }
857 if (errorHelper)
858 {
859 if (u >= args.length)
860 TypeFunction.getMatchError(buf, "missing argument for parameter #%d: `%s`",
861 u + 1, parameterToChars(p, tf, false));
862 // If an error happened previously, `pMessage` was already filled
863 else if (buf.length == 0)
864 buf.writestring(tf.getParamError(args[u], p));
865
866 errorHelper(buf.peekChars());
867 }
868 return MATCH.nomatch;
869 }
870 if (m < match)
871 match = m; // pick worst match
872 }
873
874 if (errorHelper && !parameterList.varargs && args.length > nparams)
875 {
876 // all parameters had a match, but there are surplus args
877 OutBuffer buf2;
878 TypeFunction.getMatchError(buf2, "expected %d argument(s), not %d", nparams, args.length);
879 errorHelper(buf2.extractChars());
880 return MATCH.nomatch;
881 }
882 //printf("match = %d\n", match);
883 return match;
884 }
885
886 /**
887 * Used by `callMatch` to check if the copy constructor may be called to
888 * copy the argument
889 *
890 * This is done by seeing if a call to the copy constructor can be made:
891 * ```
892 * typeof(tprm) __copytemp;
893 * copytemp.__copyCtor(arg);
894 * ```
895 */
896 private extern(D) bool isCopyConstructorCallable (StructDeclaration argStruct,
897 Expression arg, Type tprm, Scope* sc, const(char)** pMessage)
898 {
899 //printf("isCopyConstructorCallable() argStruct: %s arg: %s tprm: %s\n", argStruct.toChars(), toChars(arg), toChars(tprm));
900 auto tmp = new VarDeclaration(arg.loc, tprm, Identifier.generateId("__copytemp"), null);
901 tmp.storage_class = STC.rvalue | STC.temp | STC.ctfe;
902 tmp.dsymbolSemantic(sc);
903 Expression ve = new VarExp(arg.loc, tmp);
904 Expression e = new DotIdExp(arg.loc, ve, Id.ctor);
905 e = new CallExp(arg.loc, e, arg);
906 //printf("e = %s\n", e.toChars());
907 if (dmd.expressionsem.trySemantic(e, sc))
908 return true;
909
910 if (!pMessage)
911 return false;
912
913 /* https://issues.dlang.org/show_bug.cgi?id=22202
914 *
915 * If a function was deduced by semantic on the CallExp,
916 * it means that resolveFuncCall completed succesfully.
917 * Therefore, there exists a callable copy constructor,
918 * however, it cannot be called because scope constraints
919 * such as purity, safety or nogc.
920 */
921 OutBuffer buf;
922 auto callExp = e.isCallExp();
923
924 bool nocpctor()
925 {
926 buf.printf("`struct %s` does not define a copy constructor for `%s` to `%s` copies",
927 argStruct.toChars(), arg.type.toChars(), tprm.toChars());
928 *pMessage = buf.extractChars();
929 return false;
930 }
931
932 auto f = callExp.f;
933 if (!f)
934 return nocpctor();
935
936 if (f.isDisabled() && !f.isGenerated())
937 {
938 /* https://issues.dlang.org/show_bug.cgi?id=24301
939 * Copy constructor is explicitly disabled
940 */
941 buf.printf("`%s` copy constructor cannot be used because it is annotated with `@disable`",
942 f.type.toChars());
943 *pMessage = buf.extractChars();
944 return false;
945 }
946
947 bool bpure = !f.isPure && sc.func.setImpure(arg.loc, null);
948 bool bsafe = !f.isSafe() && !f.isTrusted() && sc.setUnsafe(false, arg.loc, null);
949 bool bnogc = !f.isNogc && sc.func.setGC(arg.loc, null);
950 if (bpure | bsafe | bnogc)
951 {
952 const nullptr = "".ptr;
953 buf.printf("`%s` copy constructor cannot be called from a `%s%s%s` context",
954 f.type.toChars(),
955 bpure ? "pure " .ptr : nullptr,
956 bsafe ? "@safe ".ptr : nullptr,
957 bnogc ? "nogc" .ptr : nullptr);
958 }
959 else if (f.isGenerated() && f.isDisabled())
960 {
961 /* https://issues.dlang.org/show_bug.cgi?id=23097
962 * Compiler generated copy constructor failed.
963 */
964 buf.printf("generating a copy constructor for `struct %s` failed, therefore instances of it are uncopyable",
965 argStruct.toChars());
966 }
967 else
968 {
969 /* Although a copy constructor may exist, no suitable match was found.
970 * i.e: `inout` constructor creates `const` object, not mutable.
971 * Fallback to using the original generic error before https://issues.dlang.org/show_bug.cgi?id=22202.
972 */
973 return nocpctor();
974 }
975
976 *pMessage = buf.extractChars();
977
978 return false;
979 }
980
981 /**
982 * Match a single parameter to an argument.
983 *
984 * This function is called by `TypeFunction.callMatch` while iterating over
985 * the list of parameter. Here we check if `arg` is a match for `p`,
986 * which is mostly about checking if `arg.type` converts to type of `p`
987 * and some check about value reference.
988 *
989 * Params:
990 * fd = the function being called if symbol, null if not
991 * tf = The `TypeFunction`, only used for error reporting
992 * p = The parameter of `tf` being matched
993 * arg = Argument being passed (bound) to `p`
994 * wildmatch = Wild (`inout`) matching level, derived from the full argument list
995 * flag = A non-zero value means we are doing a partial ordering check
996 * (no value semantic check)
997 * sc = Scope we are in
998 * pMessage = A buffer to write the error in, or `null`
999 *
1000 * Returns: Whether `trailingArgs` match `p`.
1001 */
1002 private extern(D) MATCH argumentMatchParameter (FuncDeclaration fd, TypeFunction tf, Parameter p,
1003 Expression arg, ubyte wildmatch, int flag, Scope* sc, const(char)** pMessage)
1004 {
1005 static if (0)
1006 printf("argumentMatchParameter() sc: %p, fd: %s, tf: %s, p: %s, arg: %s, arg.type: %s\n",
1007 sc, fd ? fd.ident.toChars() : "null", tf.toChars(), parameterToChars(p, tf, false), arg.toChars(), arg.type.toChars());
1008 MATCH m;
1009 Type targ = arg.type;
1010 Type tprm = wildmatch ? p.type.substWildTo(wildmatch) : p.type;
1011
1012 if (p.isLazy() && tprm.ty == Tvoid && targ.ty != Tvoid)
1013 m = MATCH.convert;
1014 else if (flag)
1015 {
1016 // for partial ordering, value is an irrelevant mockup, just look at the type
1017 m = targ.implicitConvTo(tprm);
1018 }
1019 else
1020 {
1021 const isRef = p.isReference();
1022
1023 StructDeclaration argStruct, prmStruct;
1024 if (targ.ty == Tstruct && tprm.ty == Tstruct)
1025 {
1026 // if the argument and the parameter are of the same unqualified struct type
1027 argStruct = (cast(TypeStruct)targ).sym;
1028 prmStruct = (cast(TypeStruct)tprm).sym;
1029
1030 /* if both a copy constructor and move constructor exist, then match
1031 * the lvalue to the copy constructor only and the rvalue to the move constructor
1032 * only
1033 */
1034 if (argStruct == prmStruct && fd)
1035 {
1036 if (auto cfd = fd.isCtorDeclaration())
1037 {
1038 /* Get struct that constructor is making
1039 */
1040
1041 auto t1 = cfd.type.toBasetype();
1042 auto t2 = t1.nextOf();
1043 auto t3 = t2.isTypeStruct();
1044 if (t3)
1045 {
1046 auto ctorStruct = t3.sym;
1047 // StructDeclaration ctorStruct = cfd.type.toBasetype().nextOf().isTypeStruct().sym;
1048
1049 if (prmStruct == ctorStruct && ctorStruct.hasCopyCtor && ctorStruct.hasMoveCtor)
1050 {
1051 if (cfd.isCpCtor && !arg.isLvalue())
1052 return MATCH.nomatch; // copy constructor is only for lvalues
1053 if (cfd.isMoveCtor && arg.isLvalue())
1054 return MATCH.nomatch; // move constructor is only for rvalues
1055 }
1056 }
1057 }
1058 }
1059 }
1060
1061 // check if the copy constructor may be called to copy the argument
1062 if (arg.isLvalue() && !isRef && argStruct && argStruct == prmStruct && argStruct.hasCopyCtor)
1063 {
1064 if (!isCopyConstructorCallable(argStruct, arg, tprm, sc, pMessage))
1065 return MATCH.nomatch;
1066 m = MATCH.exact;
1067 }
1068 else
1069 {
1070 import dmd.dcast : cimplicitConvTo;
1071 m = (sc && sc.inCfile) ? arg.cimplicitConvTo(tprm) : arg.implicitConvTo(tprm);
1072 }
1073 }
1074
1075 // Non-lvalues do not match ref or out parameters
1076 if (!p.isReference())
1077 return m;
1078
1079 // https://issues.dlang.org/show_bug.cgi?id=13783
1080 // Don't use toBasetype() to handle enum types.
1081 Type ta = targ;
1082 Type tp = tprm;
1083 //printf("fparam[%d] ta = %s, tp = %s\n", u, ta.toChars(), tp.toChars());
1084
1085 if (m && !arg.isLvalue())
1086 {
1087 if (p.storageClass & STC.out_)
1088 {
1089 if (pMessage) *pMessage = tf.getParamError(arg, p);
1090 return MATCH.nomatch;
1091 }
1092
1093 if (arg.op == EXP.string_ && tp.ty == Tsarray)
1094 {
1095 if (ta.ty != Tsarray)
1096 {
1097 Type tn = tp.nextOf().castMod(ta.nextOf().mod);
1098 dinteger_t dim = (cast(StringExp)arg).len;
1099 ta = tn.sarrayOf(dim);
1100 }
1101 }
1102 else if (arg.op == EXP.slice && tp.ty == Tsarray)
1103 {
1104 // Allow conversion from T[lwr .. upr] to ref T[upr-lwr]
1105 if (ta.ty != Tsarray)
1106 {
1107 Type tn = ta.nextOf();
1108 dinteger_t dim = (cast(TypeSArray)tp).dim.toUInteger();
1109 ta = tn.sarrayOf(dim);
1110 }
1111 }
1112 else if (p.storageClass & STC.constscoperef)
1113 {
1114 // Allow converting a literal to an `in` which is `ref`
1115 if (arg.op == EXP.arrayLiteral && tp.ty == Tsarray)
1116 {
1117 Type tn = tp.nextOf();
1118 dinteger_t dim = (cast(TypeSArray)tp).dim.toUInteger();
1119 ta = tn.sarrayOf(dim);
1120 }
1121
1122 // Need to make this a rvalue through a temporary
1123 m = MATCH.convert;
1124 }
1125 else if (!(sc && sc.previews.rvalueRefParam) ||
1126 p.storageClass & STC.out_ ||
1127 !arg.type.isCopyable()) // can't copy to temp for ref parameter
1128 {
1129 if (pMessage) *pMessage = tf.getParamError(arg, p);
1130 return MATCH.nomatch;
1131 }
1132 else
1133 {
1134 /* in functionParameters() we'll convert this
1135 * rvalue into a temporary
1136 */
1137 m = MATCH.convert;
1138 }
1139 }
1140
1141 /* If the match is not already perfect or if the arg
1142 is not a lvalue then try the `alias this` chain
1143 see https://issues.dlang.org/show_bug.cgi?id=15674
1144 and https://issues.dlang.org/show_bug.cgi?id=21905
1145 */
1146 if (ta != tp || !arg.isLvalue())
1147 {
1148 Type firsttab = ta.toBasetype();
1149 while (1)
1150 {
1151 Type tab = ta.toBasetype();
1152 Type tat = tab.aliasthisOf();
1153 if (!tat || !tat.implicitConvTo(tprm))
1154 break;
1155 if (tat == tab || tat == firsttab)
1156 break;
1157 ta = tat;
1158 }
1159 }
1160
1161 /* A ref variable should work like a head-const reference.
1162 * e.g. disallows:
1163 * ref T <- an lvalue of const(T) argument
1164 * ref T[dim] <- an lvalue of const(T[dim]) argument
1165 */
1166 if (!ta.constConv(tp))
1167 {
1168 if (pMessage) *pMessage = tf.getParamError(arg, p);
1169 return MATCH.nomatch;
1170 }
1171
1172 return m;
1173 }
1174
1175 // arguments get specially formatted
1176 private const(char)* getParamError(TypeFunction tf, Expression arg, Parameter par)
1177 {
1178 if (global.gag && !global.params.v.showGaggedErrors)
1179 return null;
1180 // show qualification when toChars() is the same but types are different
1181 // https://issues.dlang.org/show_bug.cgi?id=19948
1182 // when comparing the type with strcmp, we need to drop the qualifier
1183 bool qual = !arg.type.mutableOf().equals(par.type.mutableOf()) &&
1184 strcmp(arg.type.mutableOf().toChars(), par.type.mutableOf().toChars()) == 0;
1185 auto at = qual ? arg.type.toPrettyChars(true) : arg.type.toChars();
1186 OutBuffer buf;
1187 // only mention rvalue if it's relevant
1188 const rv = !arg.isLvalue() && par.isReference();
1189 buf.printf("cannot pass %sargument `%s` of type `%s` to parameter `%s`",
1190 rv ? "rvalue ".ptr : "".ptr, arg.toErrMsg(), at,
1191 parameterToChars(par, tf, qual));
1192 return buf.extractChars();
1193 }
1194
1195 /**
1196 * Match the remaining arguments `trailingArgs` with parameter `p`.
1197 *
1198 * Assume we already checked that `p` is the last parameter of `tf`,
1199 * and we want to know whether the arguments would match `p`.
1200 *
1201 * Params:
1202 * tf = The `TypeFunction`, only used for error reporting
1203 * p = The last parameter of `tf` which is variadic
1204 * trailingArgs = The remaining arguments that should match `p`
1205 * pMessage = A buffer to write the error in, or `null`
1206 *
1207 * Returns: Whether `trailingArgs` match `p`.
1208 */
1209 private extern(D) MATCH matchTypeSafeVarArgs(TypeFunction tf, Parameter p,
1210 Expression[] trailingArgs, const(char)** pMessage)
1211 {
1212 Type tb = p.type.toBasetype();
1213
1214 switch (tb.ty)
1215 {
1216 case Tsarray:
1217 TypeSArray tsa = cast(TypeSArray)tb;
1218 dinteger_t sz = tsa.dim.toInteger();
1219 if (sz != trailingArgs.length)
1220 {
1221 if (pMessage)
1222 {
1223 OutBuffer buf;
1224 TypeFunction.getMatchError(buf, "expected %llu variadic argument(s), not %zu",
1225 sz, trailingArgs.length);
1226 *pMessage = buf.extractChars();
1227 }
1228 return MATCH.nomatch;
1229 }
1230 goto case Tarray;
1231 case Tarray:
1232 {
1233 MATCH match = MATCH.exact;
1234 TypeArray ta = cast(TypeArray)tb;
1235 foreach (arg; trailingArgs)
1236 {
1237 MATCH m;
1238 assert(arg);
1239
1240 /* If lazy array of delegates,
1241 * convert arg(s) to delegate(s)
1242 */
1243 Type tret = p.isLazyArray();
1244 if (tret)
1245 {
1246 if (ta.next.equals(arg.type))
1247 m = MATCH.exact;
1248 else if (tret.toBasetype().ty == Tvoid)
1249 m = MATCH.convert;
1250 else
1251 {
1252 m = arg.implicitConvTo(tret);
1253 if (m == MATCH.nomatch)
1254 m = arg.implicitConvTo(ta.next);
1255 }
1256 }
1257 else
1258 m = arg.implicitConvTo(ta.next);
1259
1260 if (m == MATCH.nomatch)
1261 {
1262 if (pMessage) *pMessage = tf.getParamError(arg, p);
1263 return MATCH.nomatch;
1264 }
1265 if (m < match)
1266 match = m;
1267 }
1268 return match;
1269 }
1270 case Tclass:
1271 // We leave it up to the actual constructor call to do the matching.
1272 return MATCH.exact;
1273
1274 default:
1275 // We can have things as `foo(int[int] wat...)` but they only match
1276 // with an associative array proper.
1277 if (pMessage && trailingArgs.length) *pMessage = tf.getParamError(trailingArgs[0], p);
1278 return MATCH.nomatch;
1279 }
1280 }
1281
1282 /***************************************
1283 * Return !=0 if type has pointers that need to
1284 * be scanned by the GC during a collection cycle.
1285 */
1286 bool hasPointers(Type t)
1287 {
1288 bool visitType(Type _) { return false; }
1289 bool visitDArray(TypeDArray _) { return true; }
1290 bool visitAArray(TypeAArray _) { return true; }
1291 bool visitPointer(TypePointer _) { return true; }
1292 bool visitDelegate(TypeDelegate _) { return true; }
1293 bool visitClass(TypeClass _) { return true; }
1294 bool visitEnum(TypeEnum t) { return t.memType().hasPointers(); }
1295
1296 /* Although null isn't dereferencable, treat it as a pointer type for
1297 * attribute inference, generic code, etc.
1298 */
1299 bool visitNull(TypeNull _) { return true; }
1300
1301 bool visitSArray(TypeSArray t)
1302 {
1303 /* Don't want to do this, because:
1304 * struct S { T* array[0]; }
1305 * may be a variable length struct.
1306 */
1307 //if (dim.toInteger() == 0)
1308 // return false;
1309
1310 if (t.next.ty == Tvoid)
1311 {
1312 // Arrays of void contain arbitrary data, which may include pointers
1313 return true;
1314 }
1315 else
1316 return t.next.hasPointers();
1317 }
1318
1319 bool visitStruct(TypeStruct t)
1320 {
1321 StructDeclaration sym = t.sym;
1322
1323 if (sym.members && !sym.determineFields() && sym.type != Type.terror)
1324 error(sym.loc, "no size because of forward references");
1325
1326 sym.determineTypeProperties();
1327 return sym.hasPointerField;
1328 }
1329
1330
1331 switch(t.ty)
1332 {
1333 default: return visitType(t);
1334 case Tsarray: return visitSArray(t.isTypeSArray());
1335 case Tarray: return visitDArray(t.isTypeDArray());
1336 case Taarray: return visitAArray(t.isTypeAArray());
1337 case Tpointer: return visitPointer(t.isTypePointer());
1338 case Tdelegate: return visitDelegate(t.isTypeDelegate());
1339 case Tstruct: return visitStruct(t.isTypeStruct());
1340 case Tenum: return visitEnum(t.isTypeEnum());
1341 case Tclass: return visitClass(t.isTypeClass());
1342 case Tnull: return visitNull(t.isTypeNull());
1343 }
1344 }
1345
1346 /**************************************
1347 * Returns an indirect type one step from t.
1348 */
1349 Type getIndirection(Type t)
1350 {
1351 t = t.baseElemOf();
1352 if (t.ty == Tarray || t.ty == Tpointer)
1353 return t.nextOf().toBasetype();
1354 if (t.ty == Taarray || t.ty == Tclass)
1355 return t;
1356 if (t.ty == Tstruct)
1357 return t.hasPointers() ? t : null; // TODO
1358
1359 // should consider TypeDelegate?
1360 return null;
1361 }
1362
1363 uinteger_t size(Type t)
1364 {
1365 return size(t, Loc.initial);
1366 }
1367
1368 uinteger_t size(Type t, Loc loc)
1369 {
1370
1371 uinteger_t visitType(Type t)
1372 {
1373 error(loc, "no size for type `%s`", t.toChars());
1374 return SIZE_INVALID;
1375 }
1376
1377 uinteger_t visitBasic(TypeBasic t)
1378 {
1379 uint size;
1380 //printf("TypeBasic::size()\n");
1381 switch (t.ty)
1382 {
1383 case Tint8:
1384 case Tuns8:
1385 size = 1;
1386 break;
1387
1388 case Tint16:
1389 case Tuns16:
1390 size = 2;
1391 break;
1392
1393 case Tint32:
1394 case Tuns32:
1395 case Tfloat32:
1396 case Timaginary32:
1397 size = 4;
1398 break;
1399
1400 case Tint64:
1401 case Tuns64:
1402 case Tfloat64:
1403 case Timaginary64:
1404 size = 8;
1405 break;
1406
1407 case Tfloat80:
1408 case Timaginary80:
1409 size = target.realsize;
1410 break;
1411
1412 case Tcomplex32:
1413 size = 8;
1414 break;
1415
1416 case Tcomplex64:
1417 case Tint128:
1418 case Tuns128:
1419 size = 16;
1420 break;
1421
1422 case Tcomplex80:
1423 size = target.realsize * 2;
1424 break;
1425
1426 case Tvoid:
1427 //size = Type::size(); // error message
1428 size = 1;
1429 break;
1430
1431 case Tbool:
1432 size = 1;
1433 break;
1434
1435 case Tchar:
1436 size = 1;
1437 break;
1438
1439 case Twchar:
1440 size = 2;
1441 break;
1442
1443 case Tdchar:
1444 size = 4;
1445 break;
1446
1447 default:
1448 assert(0);
1449 }
1450
1451 //printf("TypeBasic::size() = %d\n", size);
1452 return size;
1453 }
1454
1455 uinteger_t visitSArray(TypeSArray t)
1456 {
1457 //printf("TypeSArray::size()\n");
1458 const n = t.numberOfElems(loc);
1459 const elemsize = t.baseElemOf().size(loc);
1460 bool overflow = false;
1461 const sz = mulu(n, elemsize, overflow);
1462 if (overflow || sz >= uint.max)
1463 {
1464 if (elemsize != SIZE_INVALID && n != uint.max)
1465 error(loc, "static array `%s` size overflowed to %lld", t.toChars(), cast(long)sz);
1466 return SIZE_INVALID;
1467 }
1468 return sz;
1469
1470 }
1471
1472 uinteger_t visitTypeQualified(TypeQualified t)
1473 {
1474 if (t.ty == Ttypeof)
1475 {
1476 auto type = (cast(TypeTypeof)t).exp.type;
1477 if (type)
1478 return type.size(loc);
1479 }
1480
1481 error(t.loc, "size of type `%s` is not known", t.toChars());
1482 return SIZE_INVALID;
1483 }
1484
1485 switch(t.ty)
1486 {
1487 default: return t.isTypeBasic() ? visitBasic(t.isTypeBasic()) : visitType(t);
1488 case Ttraits:
1489 case Terror: return SIZE_INVALID;
1490 case Tvector: return t.isTypeVector().basetype.size();
1491 case Tsarray: return visitSArray(t.isTypeSArray());
1492 case Tdelegate:
1493 case Tarray: return target.ptrsize * 2;
1494 case Tpointer:
1495 case Treference:
1496 case Tclass:
1497 case Taarray: return target.ptrsize;
1498 case Tident:
1499 case Tinstance:
1500 case Ttypeof:
1501 case Treturn: return visitTypeQualified(cast(TypeQualified)t);
1502 case Tstruct: return t.isTypeStruct().sym.size(loc);
1503 case Tenum: return t.isTypeEnum().sym.getMemtype(loc).size(loc);
1504 case Tnull: return t.tvoidptr.size(loc);
1505 case Tnoreturn: return 0;
1506 }
1507 }
1508
1509 /*******************************
1510 * Determine if converting 'this' to 'to' is an identity operation,
1511 * a conversion to const operation, or the types aren't the same.
1512 * Returns:
1513 * MATCH.exact 'this' == 'to'
1514 * MATCH.constant 'to' is const
1515 * MATCH.nomatch conversion to mutable or invariant
1516 */
1517 MATCH constConv(Type from, Type to)
1518 {
1519 MATCH visitType(Type from)
1520 {
1521 //printf("Type::constConv(this = %s, to = %s)\n", from.toChars(), to.toChars());
1522 if (from.equals(to))
1523 return MATCH.exact;
1524 if (from.ty == to.ty && MODimplicitConv(from.mod, to.mod))
1525 return MATCH.constant;
1526 return MATCH.nomatch;
1527 }
1528
1529 MATCH visitNext(TypeNext from)
1530 {
1531 //printf("TypeNext::constConv from = %s, to = %s\n", from.toChars(), to.toChars());
1532 if (from.equals(to))
1533 return MATCH.exact;
1534
1535 if (!(from.ty == to.ty && MODimplicitConv(from.mod, to.mod)))
1536 return MATCH.nomatch;
1537
1538 Type tn = to.nextOf();
1539 if (!(tn && from.next.ty == tn.ty))
1540 return MATCH.nomatch;
1541
1542 MATCH m;
1543 if (to.isConst()) // whole tail const conversion
1544 {
1545 // Recursive shared level check
1546 m = from.next.constConv(tn);
1547 if (m == MATCH.exact)
1548 m = MATCH.constant;
1549 }
1550 else
1551 {
1552 //printf("\tnext => %s, to.next => %s\n", from.next.toChars(), tn.toChars());
1553 m = from.next.equals(tn) ? MATCH.constant : MATCH.nomatch;
1554 }
1555 return m;
1556 }
1557
1558 MATCH visitSArray(TypeSArray from)
1559 {
1560 if (auto tsa = to.isTypeSArray())
1561 {
1562 if (!from.dim.equals(tsa.dim))
1563 return MATCH.nomatch;
1564 }
1565 return visitNext(from);
1566 }
1567
1568 MATCH visitAArray(TypeAArray from)
1569 {
1570 if (auto taa = to.isTypeAArray())
1571 {
1572 MATCH mindex = from.index.constConv(taa.index);
1573 MATCH mkey = from.next.constConv(taa.next);
1574 // Pick the worst match
1575 return mkey < mindex ? mkey : mindex;
1576 }
1577 return visitType(from);
1578 }
1579
1580 MATCH visitPointer(TypePointer from)
1581 {
1582 if (from.next.ty == Tfunction)
1583 {
1584 if (to.nextOf() && from.next.equals((cast(TypeNext)to).next))
1585 return visitType(from);
1586 else
1587 return MATCH.nomatch;
1588 }
1589 return visitNext(from);
1590 }
1591
1592 MATCH visitFunction(TypeFunction from)
1593 {
1594 // Attributes need to match exactly, otherwise it's an implicit conversion
1595 if (from.ty != to.ty || !from.attributesEqual(cast(TypeFunction) to))
1596 return MATCH.nomatch;
1597
1598 return visitNext(from);
1599 }
1600
1601 MATCH visitStruct(TypeStruct from)
1602 {
1603 if (from.equals(to))
1604 return MATCH.exact;
1605 if (from.ty == to.ty && from.sym == (cast(TypeStruct)to).sym && MODimplicitConv(from.mod, to.mod))
1606 return MATCH.constant;
1607 return MATCH.nomatch;
1608 }
1609
1610 MATCH visitEnum(TypeEnum from)
1611 {
1612 if (from.equals(to))
1613 return MATCH.exact;
1614 if (from.ty == to.ty && from.sym == (cast(TypeEnum)to).sym && MODimplicitConv(from.mod, to.mod))
1615 return MATCH.constant;
1616 return MATCH.nomatch;
1617 }
1618
1619 MATCH visitClass(TypeClass from)
1620 {
1621 if (from.equals(to))
1622 return MATCH.exact;
1623 if (from.ty == to.ty && from.sym == (cast(TypeClass)to).sym && MODimplicitConv(from.mod, to.mod))
1624 return MATCH.constant;
1625
1626 /* Conversion derived to const(base)
1627 */
1628 int offset = 0;
1629 if (to.isBaseOf(from, &offset) && offset == 0 && MODimplicitConv(from.mod, to.mod))
1630 {
1631 // Disallow:
1632 // derived to base
1633 // inout(derived) to inout(base)
1634 if (!to.isMutable() && !to.isWild())
1635 return MATCH.convert;
1636 }
1637
1638 return MATCH.nomatch;
1639 }
1640
1641 MATCH visitNoreturn(TypeNoreturn from)
1642 {
1643 // Either another noreturn or conversion to any type
1644 return from.implicitConvTo(to);
1645 }
1646
1647 switch(from.ty)
1648 {
1649 default: return visitType(from);
1650 case Tsarray: return visitSArray(from.isTypeSArray());
1651 case Taarray: return visitAArray(from.isTypeAArray());
1652 case Treference:
1653 case Tdelegate:
1654 case Tslice:
1655 case Tarray: return visitNext(cast(TypeNext)from);
1656 case Tpointer: return visitPointer(from.isTypePointer());
1657 case Tfunction: return visitFunction(from.isTypeFunction());
1658 case Tstruct: return visitStruct(from.isTypeStruct());
1659 case Tenum: return visitEnum(from.isTypeEnum());
1660 case Tclass: return visitClass(from.isTypeClass());
1661 case Tnoreturn: return visitNoreturn(from.isTypeNoreturn());
1662 }
1663 }
1664
1665
1666 /******************************************
1667 * Perform semantic analysis on a type.
1668 * Params:
1669 * type = Type AST node
1670 * loc = the location of the type
1671 * sc = context
1672 * Returns:
1673 * `Type` with completed semantic analysis, `Terror` if errors
1674 * were encountered
1675 */
1676 Type typeSemantic(Type type, Loc loc, Scope* sc)
1677 {
1678 static Type error()
1679 {
1680 return Type.terror;
1681 }
1682
1683 Type visitType(Type t)
1684 {
1685 // @@@DEPRECATED_2.110@@@
1686 // Use of `cent` and `ucent` has always been an error.
1687 // Starting from 2.100, recommend core.int128 as a replace for the
1688 // lack of compiler support.
1689 if (t.ty == Tint128 || t.ty == Tuns128)
1690 {
1691 .error(loc, "`cent` and `ucent` types are obsolete, use `core.int128.Cent` instead");
1692 return error();
1693 }
1694
1695 return t.merge();
1696 }
1697
1698 Type visitComplex(TypeBasic t)
1699 {
1700 if (!sc.inCfile)
1701 return visitType(t);
1702
1703 auto tc = getComplexLibraryType(loc, sc, t.ty);
1704 if (tc.ty == Terror)
1705 return tc;
1706 return tc.addMod(t.mod).merge();
1707 }
1708
1709 Type visitVector(TypeVector mtype)
1710 {
1711 const errors = global.errors;
1712 mtype.basetype = mtype.basetype.typeSemantic(loc, sc);
1713 if (errors != global.errors)
1714 return error();
1715 mtype.basetype = mtype.basetype.toBasetype().mutableOf();
1716 if (mtype.basetype.ty != Tsarray)
1717 {
1718 .error(loc, "T in __vector(T) must be a static array, not `%s`", mtype.basetype.toChars());
1719 return error();
1720 }
1721 TypeSArray t = mtype.basetype.isTypeSArray();
1722 const sz = cast(int)t.size(loc);
1723 final switch (target.isVectorTypeSupported(sz, t.nextOf()))
1724 {
1725 case 0:
1726 // valid
1727 break;
1728
1729 case 1:
1730 // no support at all
1731 .error(loc, "SIMD vector types not supported on this platform");
1732 return error();
1733
1734 case 2:
1735 // invalid base type
1736 .error(loc, "vector type `%s` is not supported on this platform", mtype.toChars());
1737 return error();
1738
1739 case 3:
1740 // invalid size
1741 .error(loc, "%d byte vector type `%s` is not supported on this platform", sz, mtype.toChars());
1742 return error();
1743 }
1744 return merge(mtype);
1745 }
1746
1747 Type visitSArray(TypeSArray mtype)
1748 {
1749 //printf("TypeSArray::semantic() %s\n", toChars());
1750 Type t;
1751 Expression e;
1752 Dsymbol s;
1753 mtype.next.resolve(loc, sc, e, t, s);
1754
1755 if (auto tup = s ? s.isTupleDeclaration() : null)
1756 {
1757 mtype.dim = semanticLength(sc, tup, mtype.dim);
1758 mtype.dim = mtype.dim.ctfeInterpret();
1759 if (mtype.dim.op == EXP.error)
1760 return error();
1761
1762 uinteger_t d = mtype.dim.toUInteger();
1763 if (d >= tup.objects.length)
1764 {
1765 .error(loc, "sequence index `%llu` out of bounds `[0 .. %llu]`", cast(ulong)d, cast(ulong)tup.objects.length);
1766 return error();
1767 }
1768
1769 RootObject o = (*tup.objects)[cast(size_t)d];
1770 if (auto tt = o.isType())
1771 return tt.addMod(mtype.mod);
1772 .error(loc, "`%s` is not a type", mtype.toChars());
1773 return error();
1774 }
1775
1776 if (t && t.ty == Terror)
1777 return error();
1778
1779 Type tn = mtype.next.typeSemantic(loc, sc);
1780 if (tn.ty == Terror)
1781 return error();
1782
1783 Type tbn = tn.toBasetype();
1784 if (mtype.dim)
1785 {
1786 auto errors = global.errors;
1787 mtype.dim = semanticLength(sc, tbn, mtype.dim);
1788 mtype.dim = mtype.dim.implicitCastTo(sc, Type.tsize_t);
1789 if (errors != global.errors)
1790 return error();
1791
1792 mtype.dim = mtype.dim.optimize(WANTvalue);
1793 mtype.dim = mtype.dim.ctfeInterpret();
1794 if (mtype.dim.op == EXP.error)
1795 return error();
1796
1797 errors = global.errors;
1798 dinteger_t d1 = mtype.dim.toInteger();
1799 if (errors != global.errors)
1800 return error();
1801
1802 mtype.dim = mtype.dim.implicitCastTo(sc, Type.tsize_t);
1803 mtype.dim = mtype.dim.optimize(WANTvalue);
1804 if (mtype.dim.op == EXP.error)
1805 return error();
1806
1807 errors = global.errors;
1808 dinteger_t d2 = mtype.dim.toInteger();
1809 if (errors != global.errors)
1810 return error();
1811
1812 if (mtype.dim.op == EXP.error)
1813 return error();
1814
1815 Type overflowError()
1816 {
1817 .error(loc, "`%s` size %llu * %llu exceeds 0x%llx size limit for static array",
1818 mtype.toChars(), cast(ulong)tbn.size(loc), cast(ulong)d1, target.maxStaticDataSize);
1819 return error();
1820 }
1821
1822 if (d1 != d2)
1823 return overflowError();
1824
1825 Type tbx = tbn.baseElemOf();
1826 if (tbx.ty == Tstruct && !tbx.isTypeStruct().sym.members ||
1827 tbx.ty == Tenum && !tbx.isTypeEnum().sym.members)
1828 {
1829 /* To avoid meaningless error message, skip the total size limit check
1830 * when the bottom of element type is opaque.
1831 */
1832 }
1833 else if (tbn.isTypeBasic() ||
1834 tbn.ty == Tpointer ||
1835 tbn.ty == Tarray ||
1836 tbn.ty == Tsarray ||
1837 tbn.ty == Taarray ||
1838 (tbn.ty == Tstruct && tbn.isTypeStruct().sym.sizeok == Sizeok.done) ||
1839 tbn.ty == Tclass)
1840 {
1841 /* Only do this for types that don't need to have semantic()
1842 * run on them for the size, since they may be forward referenced.
1843 */
1844 bool overflow = false;
1845 if (mulu(tbn.size(loc), d2, overflow) > target.maxStaticDataSize || overflow)
1846 return overflowError();
1847 }
1848 }
1849 switch (tbn.ty)
1850 {
1851 case Ttuple:
1852 {
1853 // Index the tuple to get the type
1854 assert(mtype.dim);
1855 TypeTuple tt = tbn.isTypeTuple();
1856 uinteger_t d = mtype.dim.toUInteger();
1857 if (d >= tt.arguments.length)
1858 {
1859 .error(loc, "sequence index `%llu` out of bounds `[0 .. %llu]`", cast(ulong)d, cast(ulong)tt.arguments.length);
1860 return error();
1861 }
1862 Type telem = (*tt.arguments)[cast(size_t)d].type;
1863 return telem.addMod(mtype.mod);
1864 }
1865
1866 case Tfunction:
1867 case Tnone:
1868 .error(loc, "cannot have array of `%s`", tbn.toChars());
1869 return error();
1870
1871 default:
1872 break;
1873 }
1874 if (tbn.isScopeClass())
1875 {
1876 .error(loc, "cannot have array of scope `%s`", tbn.toChars());
1877 return error();
1878 }
1879
1880 /* Ensure things like const(immutable(T)[3]) become immutable(T[3])
1881 * and const(T)[3] become const(T[3])
1882 */
1883 mtype.next = tn;
1884 mtype.transitive();
1885 return mtype.addMod(tn.mod).merge();
1886 }
1887
1888 Type visitDArray(TypeDArray mtype)
1889 {
1890 Type tn = mtype.next.typeSemantic(loc, sc);
1891 Type tbn = tn.toBasetype();
1892 switch (tbn.ty)
1893 {
1894 case Ttuple:
1895 return tbn;
1896
1897 case Tfunction:
1898 case Tnone:
1899 .error(loc, "cannot have array of `%s`", tbn.toChars());
1900 return error();
1901
1902 case Terror:
1903 return error();
1904
1905 default:
1906 break;
1907 }
1908 if (tn.isScopeClass())
1909 {
1910 .error(loc, "cannot have array of scope `%s`", tn.toChars());
1911 return error();
1912 }
1913 mtype.next = tn;
1914 mtype.transitive();
1915 return merge(mtype);
1916 }
1917
1918 Type visitAArray(TypeAArray mtype)
1919 {
1920 //printf("TypeAArray::semantic() %s index.ty = %d\n", mtype.toChars(), mtype.index.ty);
1921 if (mtype.deco)
1922 {
1923 return mtype;
1924 }
1925
1926 mtype.loc = loc;
1927 if (sc)
1928 sc.setNoFree();
1929
1930 // Deal with the case where we thought the index was a type, but
1931 // in reality it was an expression.
1932 if (mtype.index.ty == Tident || mtype.index.ty == Tinstance || mtype.index.ty == Tsarray || mtype.index.ty == Ttypeof || mtype.index.ty == Treturn || mtype.index.ty == Tmixin)
1933 {
1934 Expression e;
1935 Type t;
1936 Dsymbol s;
1937 mtype.index.resolve(loc, sc, e, t, s);
1938
1939 // https://issues.dlang.org/show_bug.cgi?id=15478
1940 if (s)
1941 e = symbolToExp(s, loc, sc, false);
1942
1943 if (e)
1944 {
1945 // It was an expression -
1946 // Rewrite as a static array
1947 auto tsa = new TypeSArray(mtype.next, e);
1948 return tsa.typeSemantic(loc, sc);
1949 }
1950 else if (t)
1951 mtype.index = t.typeSemantic(loc, sc);
1952 else
1953 {
1954 .error(loc, "index is not a type or an expression");
1955 return error();
1956 }
1957 }
1958 else
1959 mtype.index = mtype.index.typeSemantic(loc, sc);
1960 mtype.index = mtype.index.merge2();
1961
1962 if (mtype.index.nextOf() && !mtype.index.nextOf().isImmutable())
1963 {
1964 mtype.index = mtype.index.constOf().mutableOf();
1965 version (none)
1966 {
1967 printf("index is %p %s\n", mtype.index, mtype.index.toChars());
1968 mtype.index.check();
1969 printf("index.mod = x%x\n", mtype.index.mod);
1970 printf("index.ito = x%p\n", mtype.index.getMcache().ito);
1971 if (mtype.index.getMcache().ito)
1972 {
1973 printf("index.ito.mod = x%x\n", mtype.index.getMcache().ito.mod);
1974 printf("index.ito.ito = x%p\n", mtype.index.getMcache().ito.getMcache().ito);
1975 }
1976 }
1977 }
1978
1979 switch (mtype.index.toBasetype().ty)
1980 {
1981 case Tfunction:
1982 case Tvoid:
1983 case Tnone:
1984 case Ttuple:
1985 .error(loc, "cannot have associative array key of `%s`", mtype.index.toBasetype().toChars());
1986 goto case Terror;
1987 case Terror:
1988 return error();
1989
1990 default:
1991 break;
1992 }
1993 Type tbase = mtype.index.baseElemOf();
1994 while (tbase.ty == Tarray)
1995 tbase = tbase.nextOf().baseElemOf();
1996 if (auto ts = tbase.isTypeStruct())
1997 {
1998 /* AA's need typeid(index).equals() and getHash(). Issue error if not correctly set up.
1999 */
2000 StructDeclaration sd = ts.sym;
2001 if (sd.semanticRun < PASS.semanticdone)
2002 sd.dsymbolSemantic(null);
2003
2004 // duplicate a part of StructDeclaration::semanticTypeInfoMembers
2005 //printf("AA = %s, key: xeq = %p, xerreq = %p xhash = %p\n", toChars(), sd.xeq, sd.xerreq, sd.xhash);
2006
2007 if (sd.xeq && sd.xeq.isGenerated() && sd.xeq._scope && sd.xeq.semanticRun < PASS.semantic3done)
2008 {
2009 uint errors = global.startGagging();
2010 sd.xeq.semantic3(sd.xeq._scope);
2011 if (global.endGagging(errors))
2012 sd.xeq = sd.xerreq;
2013 }
2014
2015
2016 //printf("AA = %s, key: xeq = %p, xhash = %p\n", toChars(), sd.xeq, sd.xhash);
2017 const(char)* s = (mtype.index.toBasetype().ty != Tstruct) ? "bottom of " : "";
2018 if (!sd.xeq)
2019 {
2020 // If sd.xhash != NULL:
2021 // sd or its fields have user-defined toHash.
2022 // AA assumes that its result is consistent with bitwise equality.
2023 // else:
2024 // bitwise equality & hashing
2025 }
2026 else if (sd.xeq == sd.xerreq)
2027 {
2028 if (search_function(sd, Id.opEquals))
2029 {
2030 .error(loc, "%sAA key type `%s` does not have `bool opEquals(ref const %s) const`", s, sd.toChars(), sd.toChars());
2031 }
2032 else
2033 {
2034 .error(loc, "%sAA key type `%s` does not support const equality", s, sd.toChars());
2035 }
2036 return error();
2037 }
2038 else if (!sd.xhash)
2039 {
2040 if (search_function(sd, Id.opEquals))
2041 {
2042 .error(loc, "%sAA key type `%s` should have `extern (D) size_t toHash() const nothrow @safe` if `opEquals` defined", s, sd.toChars());
2043 }
2044 else
2045 {
2046 .error(loc, "%sAA key type `%s` supports const equality but doesn't support const hashing", s, sd.toChars());
2047 }
2048 return error();
2049 }
2050 else
2051 {
2052 // defined equality & hashing
2053 assert(sd.xeq && sd.xhash);
2054
2055 /* xeq and xhash may be implicitly defined by compiler. For example:
2056 * struct S { int[] arr; }
2057 * With 'arr' field equality and hashing, compiler will implicitly
2058 * generate functions for xopEquals and xtoHash in TypeInfo_Struct.
2059 */
2060 }
2061 }
2062 else if (tbase.ty == Tclass && !tbase.isTypeClass().sym.isInterfaceDeclaration())
2063 {
2064 ClassDeclaration cd = tbase.isTypeClass().sym;
2065 if (cd.semanticRun < PASS.semanticdone)
2066 cd.dsymbolSemantic(null);
2067
2068 if (!ClassDeclaration.object)
2069 {
2070 ObjectNotFound(Loc.initial, cd.ident);
2071 return error();
2072 }
2073
2074 __gshared FuncDeclaration feq = null;
2075 __gshared FuncDeclaration fcmp = null;
2076 __gshared FuncDeclaration fhash = null;
2077 if (!feq)
2078 feq = search_function(ClassDeclaration.object, Id.opEquals).isFuncDeclaration();
2079 if (!fcmp)
2080 fcmp = search_function(ClassDeclaration.object, Id.opCmp).isFuncDeclaration();
2081 if (!fhash)
2082 fhash = search_function(ClassDeclaration.object, Id.tohash).isFuncDeclaration();
2083 assert(fcmp && feq && fhash);
2084
2085 if (feq.vtblIndex < cd.vtbl.length && cd.vtbl[feq.vtblIndex] == feq)
2086 {
2087 version (all)
2088 {
2089 if (fcmp.vtblIndex < cd.vtbl.length && cd.vtbl[fcmp.vtblIndex] != fcmp)
2090 {
2091 const(char)* s = (mtype.index.toBasetype().ty != Tclass) ? "bottom of " : "";
2092 .error(loc, "%sAA key type `%s` now requires equality rather than comparison", s, cd.toChars());
2093 errorSupplemental(loc, "Please override `Object.opEquals` and `Object.toHash`.");
2094 }
2095 }
2096 }
2097 }
2098 mtype.next = mtype.next.typeSemantic(loc, sc).merge2();
2099 mtype.transitive();
2100
2101 switch (mtype.next.toBasetype().ty)
2102 {
2103 case Tfunction:
2104 case Tvoid:
2105 case Tnone:
2106 case Ttuple:
2107 .error(loc, "cannot have associative array of `%s`", mtype.next.toChars());
2108 goto case Terror;
2109 case Terror:
2110 return error();
2111 default:
2112 break;
2113 }
2114 if (mtype.next.isScopeClass())
2115 {
2116 .error(loc, "cannot have array of scope `%s`", mtype.next.toChars());
2117 return error();
2118 }
2119 return merge(mtype);
2120 }
2121
2122 Type visitPointer(TypePointer mtype)
2123 {
2124 //printf("TypePointer::semantic() %s\n", toChars());
2125 if (mtype.deco)
2126 {
2127 return mtype;
2128 }
2129 Type n = mtype.next.typeSemantic(loc, sc);
2130 switch (n.toBasetype().ty)
2131 {
2132 case Ttuple:
2133 .error(loc, "cannot have pointer to `%s`", n.toChars());
2134 goto case Terror;
2135 case Terror:
2136 return error();
2137 default:
2138 break;
2139 }
2140 if (n != mtype.next)
2141 {
2142 mtype.deco = null;
2143 }
2144 mtype.next = n;
2145 if (mtype.next.ty != Tfunction)
2146 {
2147 mtype.transitive();
2148 return merge(mtype);
2149 }
2150 version (none)
2151 {
2152 return merge(mtype);
2153 }
2154 else
2155 {
2156 mtype.deco = merge(mtype).deco;
2157 /* Don't return merge(), because arg identifiers and default args
2158 * can be different
2159 * even though the types match
2160 */
2161 return mtype;
2162 }
2163 }
2164
2165 Type visitReference(TypeReference mtype)
2166 {
2167 //printf("TypeReference::semantic()\n");
2168 Type n = mtype.next.typeSemantic(loc, sc);
2169 if (n != mtype.next)
2170 mtype.deco = null;
2171 mtype.next = n;
2172 mtype.transitive();
2173 return merge(mtype);
2174 }
2175
2176 Type visitFunction(TypeFunction mtype)
2177 {
2178 if (mtype.deco) // if semantic() already run
2179 {
2180 //printf("already done\n");
2181 return mtype;
2182 }
2183 //printf("TypeFunction::semantic() this = %p\n", mtype);
2184 //printf("TypeFunction::semantic() %s, sc.stc = %llx\n", mtype.toChars(), sc.stc);
2185
2186 bool errors = false;
2187
2188 if (mtype.inuse > global.recursionLimit)
2189 {
2190 mtype.inuse = 0;
2191 .error(loc, "recursive type");
2192 return error();
2193 }
2194
2195 /* Copy in order to not mess up original.
2196 * This can produce redundant copies if inferring return type,
2197 * as semantic() will get called again on this.
2198 */
2199 TypeFunction tf = mtype.copy().toTypeFunction();
2200 if (mtype.parameterList.parameters)
2201 {
2202 tf.parameterList.parameters = mtype.parameterList.parameters.copy();
2203 for (size_t i = 0; i < mtype.parameterList.parameters.length; i++)
2204 {
2205 Parameter p = cast(Parameter)mem.xmalloc(__traits(classInstanceSize, Parameter));
2206 memcpy(cast(void*)p, cast(void*)(*mtype.parameterList.parameters)[i], __traits(classInstanceSize, Parameter));
2207 (*tf.parameterList.parameters)[i] = p;
2208 }
2209 }
2210
2211 if (sc.stc & STC.pure_)
2212 tf.purity = PURE.fwdref;
2213 if (sc.stc & STC.nothrow_)
2214 tf.isNothrow = true;
2215 if (sc.stc & STC.nogc)
2216 tf.isNogc = true;
2217 if (sc.stc & STC.ref_)
2218 tf.isRef = true;
2219 if (sc.stc & STC.return_)
2220 tf.isReturn = true;
2221 if (sc.stc & STC.returnScope)
2222 tf.isReturnScope = true;
2223 if (sc.stc & STC.returninferred)
2224 tf.isReturnInferred = true;
2225 if (sc.stc & STC.scope_)
2226 tf.isScopeQual = true;
2227 if (sc.stc & STC.scopeinferred)
2228 tf.isScopeInferred = true;
2229
2230 // if (tf.isReturn && !tf.isRef)
2231 // tf.isScopeQual = true; // return by itself means 'return scope'
2232
2233 if (tf.trust == TRUST.default_)
2234 {
2235 if (sc.stc & STC.safe)
2236 tf.trust = TRUST.safe;
2237 else if (sc.stc & STC.system)
2238 tf.trust = TRUST.system;
2239 else if (sc.stc & STC.trusted)
2240 tf.trust = TRUST.trusted;
2241 }
2242
2243 if (sc.stc & STC.property)
2244 tf.isProperty = true;
2245 if (sc.stc & STC.live)
2246 tf.isLive = true;
2247
2248 tf.linkage = sc.linkage;
2249 if (tf.linkage == LINK.system)
2250 tf.linkage = target.systemLinkage();
2251
2252 version (none)
2253 {
2254 /* If the parent is @safe, then this function defaults to safe
2255 * too.
2256 * If the parent's @safe-ty is inferred, then this function's @safe-ty needs
2257 * to be inferred first.
2258 */
2259 if (tf.trust == TRUST.default_)
2260 for (Dsymbol p = sc.func; p; p = p.toParent2())
2261 {
2262 FuncDeclaration fd = p.isFuncDeclaration();
2263 if (fd)
2264 {
2265 if (fd.isSafeBypassingInference())
2266 tf.trust = TRUST.safe; // default to @safe
2267 break;
2268 }
2269 }
2270 }
2271
2272 bool wildreturn = false;
2273 if (tf.next)
2274 {
2275 sc = sc.push();
2276 sc.stc &= ~(STC.TYPECTOR | STC.FUNCATTR);
2277 tf.next = tf.next.typeSemantic(loc, sc);
2278 sc = sc.pop();
2279 errors |= tf.checkRetType(loc);
2280 if (tf.next.isScopeClass() && !tf.isCtor)
2281 {
2282 .error(loc, "functions cannot return `scope %s`", tf.next.toChars());
2283 errors = true;
2284 }
2285 if (tf.next.hasWild())
2286 wildreturn = true;
2287
2288 if (tf.isReturn && !tf.isRef && !tf.next.hasPointers())
2289 {
2290 tf.isReturn = false;
2291 }
2292 }
2293
2294 /// Perform semantic on the default argument to a parameter
2295 /// Modify the `defaultArg` field of `fparam`, which must not be `null`
2296 /// Returns `false` whether an error was encountered.
2297 static bool defaultArgSemantic (ref Parameter fparam, Scope* sc)
2298 {
2299 Expression e = fparam.defaultArg;
2300 const isRefOrOut = fparam.isReference();
2301 const isAuto = fparam.storageClass & (STC.auto_ | STC.autoref);
2302 if (isRefOrOut && !isAuto)
2303 {
2304 e = e.expressionSemantic(sc);
2305 e = resolveProperties(sc, e);
2306 }
2307 else
2308 {
2309 e = inferType(e, fparam.type);
2310 Scope* sc2 = sc.push();
2311 sc2.inDefaultArg = true;
2312 Initializer iz = new ExpInitializer(e.loc, e);
2313 iz = iz.initializerSemantic(sc2, fparam.type, INITnointerpret);
2314 e = iz.initializerToExpression();
2315 sc2.pop();
2316 }
2317 if (e.op == EXP.function_) // https://issues.dlang.org/show_bug.cgi?id=4820
2318 {
2319 FuncExp fe = e.isFuncExp();
2320 // Replace function literal with a function symbol,
2321 // since default arg expression must be copied when used
2322 // and copying the literal itself is wrong.
2323 e = new VarExp(e.loc, fe.fd, false);
2324 e = new AddrExp(e.loc, e);
2325 e = e.expressionSemantic(sc);
2326 }
2327 if (isRefOrOut && (!isAuto || e.isLvalue())
2328 && !MODimplicitConv(e.type.mod, fparam.type.mod))
2329 {
2330 const(char)* errTxt = fparam.storageClass & STC.ref_ ? "ref" : "out";
2331 .error(e.loc, "expression `%s` of type `%s` is not implicitly convertible to type `%s %s` of parameter `%s`",
2332 e.toErrMsg(), e.type.toChars(), errTxt, fparam.type.toChars(), fparam.toChars());
2333 }
2334 e = e.implicitCastTo(sc, fparam.type);
2335
2336 // default arg must be an lvalue
2337 if (isRefOrOut && !isAuto &&
2338 !(fparam.storageClass & STC.constscoperef) && !sc.previews.rvalueRefParam)
2339 e = e.toLvalue(sc, "create default argument for `ref` / `out` parameter from");
2340
2341 fparam.defaultArg = e;
2342 return (e.op != EXP.error);
2343 }
2344
2345 ubyte wildparams = 0;
2346 if (tf.parameterList.parameters)
2347 {
2348 /* Create a scope for evaluating the default arguments for the parameters
2349 */
2350 Scope* argsc = sc.push();
2351 argsc.stc = STC.none; // don't inherit storage class
2352 argsc.visibility = Visibility(Visibility.Kind.public_);
2353 argsc.func = null;
2354
2355 size_t dim = tf.parameterList.length;
2356 for (size_t i = 0; i < dim; i++)
2357 {
2358 Parameter fparam = tf.parameterList[i];
2359 fparam.storageClass |= STC.parameter;
2360 mtype.inuse++;
2361 fparam.type = fparam.type.typeSemantic(loc, argsc);
2362 mtype.inuse--;
2363
2364 if (fparam.type.ty == Terror)
2365 {
2366 errors = true;
2367 continue;
2368 }
2369
2370 fparam.type = fparam.type.addStorageClass(fparam.storageClass);
2371
2372 if (fparam.storageClass & (STC.auto_ | STC.alias_ | STC.static_))
2373 {
2374 if (!fparam.type)
2375 continue;
2376 }
2377
2378 fparam.type = fparam.type.cAdjustParamType(sc); // adjust C array and function parameter types
2379
2380 Type t = fparam.type.toBasetype();
2381
2382 /* If fparam after semantic() turns out to be a tuple, the number of parameters may
2383 * change.
2384 */
2385 if (auto tt = t.isTypeTuple())
2386 {
2387 /* TypeFunction::parameter also is used as the storage of
2388 * Parameter objects for FuncDeclaration. So we should copy
2389 * the elements of TypeTuple::arguments to avoid unintended
2390 * sharing of Parameter object among other functions.
2391 */
2392 if (tt.arguments && tt.arguments.length)
2393 {
2394 /* Propagate additional storage class from tuple parameters to their
2395 * element-parameters.
2396 * Make a copy, as original may be referenced elsewhere.
2397 */
2398 size_t tdim = tt.arguments.length;
2399 auto newparams = new Parameters(tdim);
2400 for (size_t j = 0; j < tdim; j++)
2401 {
2402 Parameter narg = (*tt.arguments)[j];
2403
2404 // https://issues.dlang.org/show_bug.cgi?id=12744
2405 // If the storage classes of narg
2406 // conflict with the ones in fparam, it's ignored.
2407 STC stc = fparam.storageClass | narg.storageClass;
2408 STC stc1 = fparam.storageClass & (STC.ref_ | STC.out_ | STC.lazy_);
2409 STC stc2 = narg.storageClass & (STC.ref_ | STC.out_ | STC.lazy_);
2410 if (stc1 && stc2 && stc1 != stc2)
2411 {
2412 OutBuffer buf1; stcToBuffer(buf1, stc1 | ((stc1 & STC.ref_) ? (fparam.storageClass & STC.auto_) : STC.none));
2413 OutBuffer buf2; stcToBuffer(buf2, stc2);
2414
2415 .error(loc, "incompatible parameter storage classes `%s` and `%s`",
2416 buf1.peekChars(), buf2.peekChars());
2417 errors = true;
2418 stc = stc1 | (stc & ~(STC.ref_ | STC.out_ | STC.lazy_));
2419 }
2420 (*newparams)[j] = new Parameter(
2421 loc, stc, narg.type, narg.ident, narg.defaultArg, narg.userAttribDecl);
2422 }
2423 fparam.type = new TypeTuple(newparams);
2424 fparam.type = fparam.type.typeSemantic(loc, argsc);
2425 }
2426 fparam.storageClass = STC.parameter;
2427
2428 /* Reset number of parameters, and back up one to do this fparam again,
2429 * now that it is a tuple
2430 */
2431 dim = tf.parameterList.length;
2432 i--;
2433 continue;
2434 }
2435
2436 // -preview=in: Always add `ref` when used with `extern(C++)` functions
2437 // Done here to allow passing opaque types with `in`
2438 if ((fparam.storageClass & (STC.in_ | STC.ref_)) == STC.in_)
2439 {
2440 switch (tf.linkage)
2441 {
2442 case LINK.cpp:
2443 if (fparam.storageClass & STC.constscoperef)
2444 fparam.storageClass |= STC.ref_;
2445 break;
2446 case LINK.default_, LINK.d:
2447 break;
2448 default:
2449 if (fparam.storageClass & STC.constscoperef)
2450 {
2451 .error(loc, "cannot use `in` parameters with `extern(%s)` functions",
2452 linkageToChars(tf.linkage));
2453 .errorSupplemental(loc, "parameter `%s` declared as `in` here", fparam.toChars());
2454 }
2455 else
2456 {
2457 // Note that this deprecation will not trigger on `in ref` / `ref in`
2458 // parameters, however the parser will trigger a deprecation on them.
2459 .deprecation(loc, "using `in` parameters with `extern(%s)` functions is deprecated",
2460 linkageToChars(tf.linkage));
2461 .deprecationSupplemental(loc, "parameter `%s` declared as `in` here", fparam.toChars());
2462 }
2463 break;
2464 }
2465 }
2466
2467 if (t.ty == Tfunction)
2468 {
2469 .error(loc, "cannot have parameter of function type `%s`", fparam.type.toChars());
2470 errors = true;
2471 }
2472 else if (!fparam.isReference() &&
2473 (t.ty == Tstruct || t.ty == Tsarray || t.ty == Tenum))
2474 {
2475 Type tb2 = t.baseElemOf();
2476 if (tb2.ty == Tstruct && !tb2.isTypeStruct().sym.members ||
2477 tb2.ty == Tenum && !tb2.isTypeEnum().sym.memtype)
2478 {
2479 if (fparam.storageClass & STC.constscoperef)
2480 {
2481 .error(loc, "cannot infer `ref` for `in` parameter `%s` of opaque type `%s`",
2482 fparam.toChars(), fparam.type.toChars());
2483 }
2484 else
2485 .error(loc, "cannot have parameter of opaque type `%s` by value",
2486 fparam.type.toChars());
2487 errors = true;
2488 }
2489 }
2490 else if (!fparam.isLazy() && t.ty == Tvoid)
2491 {
2492 .error(loc, "cannot have parameter of type `%s`", fparam.type.toChars());
2493 errors = true;
2494 }
2495
2496 const bool isTypesafeVariadic = i + 1 == dim && tf.parameterList.varargs == VarArg.typesafe;
2497 const bool isStackAllocatedVariadic = isTypesafeVariadic && (t.isTypeDArray() || t.isTypeClass());
2498
2499 if (isTypesafeVariadic && t.isTypeClass())
2500 {
2501 // Deprecated in 2.111, kept as a legacy feature for compatibility (currently no plan to turn it into an error)
2502 .deprecation(loc, "typesafe variadic parameters with a `class` type (`%s %s...`) are deprecated",
2503 t.isTypeClass().sym.ident.toChars(), fparam.toChars());
2504 }
2505
2506 if (isStackAllocatedVariadic)
2507 {
2508 /* typesafe variadic arguments are constructed on the stack, so must be `scope`
2509 */
2510 fparam.storageClass |= STC.scope_ | STC.scopeinferred;
2511 }
2512
2513 if (fparam.storageClass & STC.return_)
2514 {
2515 if (!fparam.isReference())
2516 {
2517 if (!(fparam.storageClass & STC.scope_))
2518 fparam.storageClass |= STC.scope_ | STC.scopeinferred; // 'return' implies 'scope'
2519 if (tf.isRef)
2520 {
2521 }
2522 else if (tf.next && !tf.next.hasPointers() && tf.next.toBasetype().ty != Tvoid)
2523 {
2524 fparam.storageClass &= ~STC.return_; // https://issues.dlang.org/show_bug.cgi?id=18963
2525 }
2526 }
2527
2528 if (isStackAllocatedVariadic)
2529 {
2530 /* This is because they can be constructed on the stack
2531 * https://dlang.org/spec/function.html#typesafe_variadic_functions
2532 */
2533 .error(loc, "typesafe variadic function parameter `%s` of type `%s` cannot be marked `return`",
2534 fparam.ident ? fparam.ident.toChars() : "", t.toChars());
2535 errors = true;
2536 }
2537 }
2538
2539 if (fparam.storageClass & STC.out_)
2540 {
2541 if (ubyte m = fparam.type.mod & (MODFlags.immutable_ | MODFlags.const_ | MODFlags.wild))
2542 {
2543 .error(loc, "cannot have `%s out` parameter of type `%s`", MODtoChars(m), t.toChars());
2544 errors = true;
2545 }
2546 else
2547 {
2548 Type tv = t.baseElemOf();
2549 if (tv.ty == Tstruct && tv.isTypeStruct().sym.noDefaultCtor)
2550 {
2551 .error(loc, "cannot have `out` parameter of type `%s` because the default construction is disabled", fparam.type.toChars());
2552 errors = true;
2553 }
2554 }
2555 }
2556
2557 if (t.hasWild())
2558 {
2559 wildparams |= 1;
2560 //if (tf.next && !wildreturn)
2561 // error(loc, "inout on parameter means inout must be on return type as well (if from D1 code, replace with `ref`)");
2562 }
2563
2564 // Remove redundant storage classes for type, they are already applied
2565 fparam.storageClass &= ~(STC.TYPECTOR);
2566
2567 // -preview=in: add `ref` storage class to suited `in` params
2568 if ((fparam.storageClass & (STC.constscoperef | STC.ref_)) == STC.constscoperef)
2569 {
2570 auto ts = t.baseElemOf().isTypeStruct();
2571 const isPOD = !ts || ts.sym.isPOD();
2572 if (!isPOD || target.preferPassByRef(t))
2573 fparam.storageClass |= STC.ref_;
2574 }
2575 }
2576
2577 Expressions* fargs = mtype.inferenceArguments.arguments;
2578
2579 // mtype.argumentList only provided for Implicit Function Template Instantiation
2580 if (mtype.inferenceArguments.length > 0)
2581 fargs = tf.resolveNamedArgs(mtype.inferenceArguments, null);
2582
2583 // Now that we completed semantic for the argument types,
2584 // run semantic on their default values,
2585 // bearing in mind tuples have been expanded.
2586 // We need to keep a pair of [oidx, eidx] (original index,
2587 // extended index), as we need to run semantic when `oidx` changes.
2588 size_t tupleOrigIdx = size_t.max;
2589 size_t tupleExtIdx = size_t.max;
2590 foreach (oidx, oparam, eidx, eparam; tf.parameterList)
2591 {
2592 // oparam (original param) will always have the default arg
2593 // if there's one, but `eparam` will not if it's an expanded
2594 // tuple. When we see an expanded tuple, we need to save its
2595 // position to get the offset in it later on.
2596 if (oparam.defaultArg)
2597 {
2598 // Get the obvious case out of the way
2599 if (oparam is eparam)
2600 errors |= !defaultArgSemantic(eparam, argsc);
2601 // We're seeing a new tuple
2602 else if (tupleOrigIdx == size_t.max || tupleOrigIdx < oidx)
2603 {
2604 /* https://issues.dlang.org/show_bug.cgi?id=18572
2605 *
2606 * If a tuple parameter has a default argument, when expanding the parameter
2607 * tuple the default argument tuple must also be expanded.
2608 */
2609 tupleOrigIdx = oidx;
2610 tupleExtIdx = eidx;
2611 errors |= !defaultArgSemantic(oparam, argsc);
2612 TupleExp te = oparam.defaultArg.isTupleExp();
2613 if (te && te.exps && te.exps.length)
2614 eparam.defaultArg = (*te.exps)[0];
2615 }
2616 // Processing an already-seen tuple
2617 else
2618 {
2619 TupleExp te = oparam.defaultArg.isTupleExp();
2620 if (te && te.exps && te.exps.length)
2621 eparam.defaultArg = (*te.exps)[eidx - tupleExtIdx];
2622 }
2623 }
2624
2625 // We need to know the default argument to resolve `auto ref`,
2626 // hence why this has to take place as the very last step.
2627 /* Resolve "auto ref" storage class to be either ref or value,
2628 * based on the argument matching the parameter
2629 */
2630 if (eparam.storageClass & STC.auto_)
2631 {
2632 Expression farg = (fargs && eidx < fargs.length) ? (*fargs)[eidx] : null;
2633 if (!farg)
2634 farg = eparam.defaultArg;
2635
2636 if (farg && (eparam.storageClass & STC.ref_))
2637 {
2638 if (!farg.isLvalue())
2639 eparam.storageClass &= ~STC.ref_; // value parameter
2640 eparam.storageClass &= ~STC.auto_; // https://issues.dlang.org/show_bug.cgi?id=14656
2641 eparam.storageClass |= STC.autoref;
2642 }
2643 else if (mtype.incomplete && (eparam.storageClass & STC.ref_))
2644 {
2645 // the default argument may have been temporarily removed,
2646 // see usage of `TypeFunction.incomplete`.
2647 // https://issues.dlang.org/show_bug.cgi?id=19891
2648 eparam.storageClass &= ~STC.auto_;
2649 eparam.storageClass |= STC.autoref;
2650 }
2651 else if (eparam.storageClass & STC.ref_)
2652 {
2653 .error(loc, "cannot explicitly instantiate template function with `auto ref` parameter");
2654 errors = true;
2655 }
2656 else
2657 {
2658 .error(loc, "`auto` can only be used as part of `auto ref` for template function parameters");
2659 errors = true;
2660 }
2661 }
2662 }
2663
2664 argsc.pop();
2665 }
2666 if (tf.isWild())
2667 wildparams |= 2;
2668
2669 if (wildreturn && !wildparams)
2670 {
2671 .error(loc, "`inout` on `return` means `inout` must be on a parameter as well for `%s`", mtype.toChars());
2672 errors = true;
2673 }
2674 tf.isInOutParam = (wildparams & 1) != 0;
2675 tf.isInOutQual = (wildparams & 2) != 0;
2676
2677 if (tf.isProperty && (tf.parameterList.varargs != VarArg.none || tf.parameterList.length > 2))
2678 {
2679 .error(loc, "properties can only have zero, one, or two parameter");
2680 errors = true;
2681 }
2682
2683 if (tf.parameterList.varargs == VarArg.variadic && tf.linkage != LINK.d && tf.parameterList.length == 0 &&
2684 !sc.inCfile)
2685 {
2686 .error(loc, "variadic functions with non-D linkage must have at least one parameter");
2687 errors = true;
2688 }
2689
2690 if (errors)
2691 return error();
2692
2693 if (tf.next)
2694 tf.deco = tf.merge().deco;
2695
2696 /* Don't return merge(), because arg identifiers and default args
2697 * can be different
2698 * even though the types match
2699 */
2700 return tf;
2701 }
2702
2703 Type visitDelegate(TypeDelegate mtype)
2704 {
2705 //printf("TypeDelegate::semantic() %s\n", mtype.toChars());
2706 if (mtype.deco) // if semantic() already run
2707 {
2708 //printf("already done\n");
2709 return mtype;
2710 }
2711 mtype.next = mtype.next.typeSemantic(loc, sc);
2712 if (mtype.next.ty != Tfunction)
2713 return error();
2714
2715 /* In order to deal with https://issues.dlang.org/show_bug.cgi?id=4028
2716 * perhaps default arguments should
2717 * be removed from next before the merge.
2718 */
2719 version (none)
2720 {
2721 return mtype.merge();
2722 }
2723 else
2724 {
2725 /* Don't return merge(), because arg identifiers and default args
2726 * can be different
2727 * even though the types match
2728 */
2729 mtype.deco = mtype.merge().deco;
2730 return mtype;
2731 }
2732 }
2733
2734 Type visitIdentifier(TypeIdentifier mtype)
2735 {
2736 Type t;
2737 Expression e;
2738 Dsymbol s;
2739 //printf("TypeIdentifier::semantic(%s)\n", mtype.toChars());
2740 mtype.resolve(loc, sc, e, t, s);
2741 if (t)
2742 {
2743 //printf("\tit's a type %d, %s, %s\n", t.ty, t.toChars(), t.deco);
2744 return t.addMod(mtype.mod);
2745 }
2746
2747 if (s)
2748 {
2749 auto td = s.isTemplateDeclaration;
2750 if (td && td.onemember && td.onemember.isAggregateDeclaration)
2751 .error(loc, "template %s `%s` is used as a type without instantiation"
2752 ~ "; to instantiate it use `%s!(arguments)`",
2753 s.kind, s.toPrettyChars, s.ident.toChars);
2754 else
2755 .error(loc, "%s `%s` is used as a type", s.kind, s.toPrettyChars);
2756 //assert(0);
2757 }
2758 else if (e.op == EXP.variable) // special case: variable is used as a type
2759 {
2760 /*
2761 N.B. This branch currently triggers for the following code
2762 template test(x* x)
2763 {
2764
2765 }
2766 i.e. the compiler prints "variable x is used as a type"
2767 which isn't a particularly good error message (x is a variable?).
2768 */
2769 Dsymbol varDecl = mtype.toDsymbol(sc);
2770 Module varDeclModule = varDecl.getModule(); //This can be null
2771
2772 .error(loc, "variable `%s` is used as a type", mtype.toChars());
2773 //Check for null to avoid https://issues.dlang.org/show_bug.cgi?id=22574
2774 if ((varDeclModule !is null) && varDeclModule != sc._module) // variable is imported
2775 {
2776 .errorSupplemental(
2777 varDeclModule.loc,
2778 "variable `%s` is imported here from: `%s`",
2779 varDecl.toChars,
2780 varDeclModule.toPrettyChars,
2781 );
2782 }
2783
2784 .errorSupplemental(varDecl.loc, "variable `%s` is declared here", varDecl.toChars);
2785 }
2786 else
2787 .error(loc, "`%s` is used as a type", mtype.toChars());
2788 return error();
2789 }
2790
2791 Type visitInstance(TypeInstance mtype)
2792 {
2793 Type t;
2794 Expression e;
2795 Dsymbol s;
2796
2797 //printf("TypeInstance::semantic(%p, %s)\n", this, toChars());
2798 {
2799 const errors = global.errors;
2800 mtype.resolve(loc, sc, e, t, s);
2801 // if we had an error evaluating the symbol, suppress further errors
2802 if (!t && errors != global.errors)
2803 return error();
2804 }
2805
2806 if (!t)
2807 {
2808 if (!e && s && s.errors)
2809 {
2810 // if there was an error evaluating the symbol, it might actually
2811 // be a type. Avoid misleading error messages.
2812 .error(loc, "`%s` had previous errors", mtype.toChars());
2813 }
2814 else
2815 .error(loc, "`%s` is used as a type", mtype.toChars());
2816 return error();
2817 }
2818 return t;
2819 }
2820
2821 Type visitTypeof(TypeTypeof mtype)
2822 {
2823 //printf("TypeTypeof::semantic() %s\n", mtype.toChars());
2824 Expression e;
2825 Type t;
2826 Dsymbol s;
2827 mtype.resolve(loc, sc, e, t, s);
2828 if (s && (t = s.getType()) !is null)
2829 t = t.addMod(mtype.mod);
2830 if (!t)
2831 {
2832 .error(loc, "`%s` is used as a type", mtype.toChars());
2833 return error();
2834 }
2835 return t;
2836 }
2837
2838 Type visitTraits(TypeTraits mtype)
2839 {
2840 Expression e;
2841 Type t;
2842 Dsymbol s;
2843 mtype.resolve(loc, sc, e, t, s);
2844
2845 if (!t)
2846 {
2847 if (!global.errors)
2848 .error(mtype.loc, "`%s` does not give a valid type", mtype.toChars);
2849 return error();
2850 }
2851 return t;
2852 }
2853
2854 Type visitReturn(TypeReturn mtype)
2855 {
2856 //printf("TypeReturn::semantic() %s\n", toChars());
2857 Expression e;
2858 Type t;
2859 Dsymbol s;
2860 mtype.resolve(loc, sc, e, t, s);
2861 if (s && (t = s.getType()) !is null)
2862 t = t.addMod(mtype.mod);
2863 if (!t)
2864 {
2865 .error(loc, "`%s` is used as a type", mtype.toChars());
2866 return error();
2867 }
2868 return t;
2869 }
2870
2871 Type visitStruct(TypeStruct mtype)
2872 {
2873 //printf("TypeStruct::semantic('%s')\n", mtype.toChars());
2874 if (mtype.deco)
2875 return mtype;
2876
2877 /* Don't semantic for sym because it should be deferred until
2878 * sizeof needed or its members accessed.
2879 */
2880 // instead, parent should be set correctly
2881 assert(mtype.sym.parent);
2882
2883 if (mtype.sym.type.ty == Terror)
2884 return error();
2885
2886 return merge(mtype);
2887 }
2888
2889 Type visitEnum(TypeEnum mtype)
2890 {
2891 //printf("TypeEnum::semantic() %s\n", toChars());
2892 return mtype.deco ? mtype : merge(mtype);
2893 }
2894
2895 Type visitClass(TypeClass mtype)
2896 {
2897 //printf("TypeClass::semantic(%s)\n", mtype.toChars());
2898 if (mtype.deco)
2899 return mtype;
2900
2901 /* Don't semantic for sym because it should be deferred until
2902 * sizeof needed or its members accessed.
2903 */
2904 // instead, parent should be set correctly
2905 assert(mtype.sym.parent);
2906
2907 if (mtype.sym.type.ty == Terror)
2908 return error();
2909
2910 return merge(mtype);
2911 }
2912
2913 Type visitTuple(TypeTuple mtype)
2914 {
2915 //printf("TypeTuple::semantic(this = %p)\n", this);
2916 //printf("TypeTuple::semantic() %p, %s\n", this, toChars());
2917 if (!mtype.deco)
2918 mtype.deco = merge(mtype).deco;
2919
2920 /* Don't return merge(), because a tuple with one type has the
2921 * same deco as that type.
2922 */
2923 return mtype;
2924 }
2925
2926 Type visitSlice(TypeSlice mtype)
2927 {
2928 //printf("TypeSlice::semantic() %s\n", toChars());
2929 Type tn = mtype.next.typeSemantic(loc, sc);
2930 //printf("next: %s\n", tn.toChars());
2931
2932 Type tbn = tn.toBasetype();
2933 if (tbn.ty != Ttuple)
2934 {
2935 .error(loc, "can only slice type sequences, not `%s`", tbn.toChars());
2936 return error();
2937 }
2938 TypeTuple tt = cast(TypeTuple)tbn;
2939
2940 mtype.lwr = semanticLength(sc, tbn, mtype.lwr);
2941 mtype.upr = semanticLength(sc, tbn, mtype.upr);
2942 mtype.lwr = mtype.lwr.ctfeInterpret();
2943 mtype.upr = mtype.upr.ctfeInterpret();
2944 if (mtype.lwr.op == EXP.error || mtype.upr.op == EXP.error)
2945 return error();
2946
2947 uinteger_t i1 = mtype.lwr.toUInteger();
2948 uinteger_t i2 = mtype.upr.toUInteger();
2949 if (!(i1 <= i2 && i2 <= tt.arguments.length))
2950 {
2951 .error(loc, "slice `[%llu..%llu]` is out of range of `[0..%llu]`",
2952 cast(ulong)i1, cast(ulong)i2, cast(ulong)tt.arguments.length);
2953 return error();
2954 }
2955
2956 mtype.next = tn;
2957 mtype.transitive();
2958
2959 auto args = new Parameters();
2960 args.reserve(cast(size_t)(i2 - i1));
2961 foreach (arg; (*tt.arguments)[cast(size_t)i1 .. cast(size_t)i2])
2962 {
2963 args.push(arg);
2964 }
2965 Type t = new TypeTuple(args);
2966 return t.typeSemantic(loc, sc);
2967 }
2968
2969 Type visitMixin(TypeMixin mtype)
2970 {
2971 //printf("TypeMixin::semantic() %s\n", toChars());
2972
2973 Expression e;
2974 Type t;
2975 Dsymbol s;
2976 mtype.resolve(loc, sc, e, t, s);
2977
2978 if (t && t.ty != Terror)
2979 return t;
2980
2981 .error(mtype.loc, "`mixin(%s)` does not give a valid type", mtype.obj.toChars);
2982 return error();
2983 }
2984
2985 Type visitTag(TypeTag mtype)
2986 {
2987 //printf("TypeTag.semantic() %s\n", mtype.toChars());
2988 Type returnType(TypeTag tt)
2989 {
2990 Type t = tt.resolved;
2991 // To make const checking work, the const STC needs to be added:
2992 // t = t.resolved.addSTC(mtype.mod.ModToStc);
2993 // However, this currently fails compilable/test22875.i
2994 // Apparently there's some aliasing going on, where mutable
2995 // versions of the type also get const applied to them.
2996 return t.deco ? t : t.merge();
2997 }
2998
2999 if (mtype.resolved)
3000 {
3001 /* struct S s, *p;
3002 */
3003 return returnType(mtype);
3004 }
3005
3006 /* Find the current scope by skipping tag scopes.
3007 * In C, tag scopes aren't considered scopes.
3008 */
3009 Scope* sc2 = sc;
3010 while (1)
3011 {
3012 sc2 = sc2.inner();
3013 auto scopesym = sc2.scopesym;
3014 if (scopesym.isStructDeclaration())
3015 {
3016 sc2 = sc2.enclosing;
3017 continue;
3018 }
3019 break;
3020 }
3021
3022 /* Declare mtype as a struct/union/enum declaration
3023 */
3024 void declareTag()
3025 {
3026 void declare(ScopeDsymbol sd)
3027 {
3028 sd.members = mtype.members;
3029 auto scopesym = sc2.inner().scopesym;
3030 if (scopesym.members)
3031 scopesym.members.push(sd);
3032 if (scopesym.symtab && !scopesym.symtabInsert(sd))
3033 {
3034 Dsymbol s2 = scopesym.symtabLookup(sd, mtype.id);
3035 handleTagSymbols(*sc2, sd, s2, scopesym);
3036 }
3037 sd.parent = sc2.parent;
3038 sd.dsymbolSemantic(sc2);
3039 }
3040
3041 switch (mtype.tok)
3042 {
3043 case TOK.enum_:
3044 auto ed = new EnumDeclaration(mtype.loc, mtype.id, mtype.base);
3045 declare(ed);
3046 mtype.resolved = visitEnum(new TypeEnum(ed));
3047 break;
3048
3049 case TOK.struct_:
3050 auto sd = new StructDeclaration(mtype.loc, mtype.id, false);
3051 sd.alignment = mtype.packalign;
3052 declare(sd);
3053 mtype.resolved = visitStruct(new TypeStruct(sd));
3054 break;
3055
3056 case TOK.union_:
3057 auto ud = new UnionDeclaration(mtype.loc, mtype.id);
3058 ud.alignment = mtype.packalign;
3059 declare(ud);
3060 mtype.resolved = visitStruct(new TypeStruct(ud));
3061 break;
3062
3063 default:
3064 assert(0);
3065 }
3066 }
3067
3068 /* If it doesn't have a tag by now, supply one.
3069 * It'll be unique, and therefore introducing.
3070 * Declare it, and done.
3071 */
3072 if (!mtype.id)
3073 {
3074 mtype.id = Identifier.generateId("__tag"[]);
3075 declareTag();
3076 return returnType(mtype);
3077 }
3078
3079 /* look for pre-existing declaration
3080 */
3081 Dsymbol scopesym;
3082 auto s = sc2.search(mtype.loc, mtype.id, scopesym, SearchOpt.ignoreErrors | SearchOpt.tagNameSpace);
3083 if (!s || s.isModule())
3084 {
3085 // no pre-existing declaration, so declare it
3086 if (mtype.tok == TOK.enum_ && !mtype.members)
3087 .error(mtype.loc, "`enum %s` is incomplete without members", mtype.id.toChars()); // C11 6.7.2.3-3
3088 declareTag();
3089 return returnType(mtype);
3090 }
3091
3092 /* A redeclaration only happens if both declarations are in
3093 * the same scope
3094 */
3095 const bool redeclar = (scopesym == sc2.inner().scopesym);
3096
3097 if (redeclar)
3098 {
3099 if (mtype.tok == TOK.enum_ && s.isEnumDeclaration())
3100 {
3101 auto ed = s.isEnumDeclaration();
3102 if (mtype.members && ed.members)
3103 .error(mtype.loc, "`%s` already has members", mtype.id.toChars());
3104 else if (!ed.members)
3105 {
3106 ed.members = mtype.members;
3107 }
3108 else
3109 {
3110 }
3111 mtype.resolved = ed.type;
3112 }
3113 else if (mtype.tok == TOK.union_ && s.isUnionDeclaration() ||
3114 mtype.tok == TOK.struct_ && s.isStructDeclaration())
3115 {
3116 // Add members to original declaration
3117 auto sd = s.isStructDeclaration();
3118 if (mtype.members && sd.members)
3119 {
3120 /* struct S { int b; };
3121 * struct S { int a; } *s;
3122 */
3123 .error(mtype.loc, "`%s` already has members", mtype.id.toChars());
3124 }
3125 else if (!sd.members)
3126 {
3127 /* struct S;
3128 * struct S { int a; } *s;
3129 */
3130 sd.members = mtype.members;
3131 if (sd.semanticRun == PASS.semanticdone)
3132 {
3133 /* The first semantic pass marked `sd` as an opaque struct.
3134 * Re-run semantic so that all newly assigned members are
3135 * picked up and added to the symtab.
3136 */
3137 sd.semanticRun = PASS.semantic;
3138 sd.dsymbolSemantic(sc2);
3139 }
3140 }
3141 else
3142 {
3143 /* struct S { int a; };
3144 * struct S* s;
3145 */
3146 }
3147 mtype.resolved = sd.type;
3148 }
3149 else
3150 {
3151 /* int S;
3152 * struct S { int a; } *s;
3153 */
3154 .error(mtype.loc, "redeclaration of `%s`", mtype.id.toChars());
3155 mtype.resolved = error();
3156 }
3157 }
3158 else if (mtype.members)
3159 {
3160 /* struct S;
3161 * { struct S { int a; } *s; }
3162 */
3163 declareTag();
3164 }
3165 else
3166 {
3167 if (mtype.tok == TOK.enum_ && s.isEnumDeclaration())
3168 {
3169 mtype.resolved = s.isEnumDeclaration().type;
3170 }
3171 else if (mtype.tok == TOK.union_ && s.isUnionDeclaration() ||
3172 mtype.tok == TOK.struct_ && s.isStructDeclaration())
3173 {
3174 /* struct S;
3175 * { struct S* s; }
3176 */
3177 mtype.resolved = s.isStructDeclaration().type;
3178 }
3179 else
3180 {
3181 /* union S;
3182 * { struct S* s; }
3183 */
3184 .error(mtype.loc, "redeclaring `%s %s` as `%s %s`",
3185 s.kind(), s.toChars(), Token.toChars(mtype.tok), mtype.id.toChars());
3186 declareTag();
3187 }
3188 }
3189 return returnType(mtype);
3190 }
3191
3192 switch (type.ty)
3193 {
3194 default: return visitType(type);
3195 case Tcomplex32:
3196 case Tcomplex64:
3197 case Tcomplex80: return visitComplex(type.isTypeBasic());
3198 case Tvector: return visitVector(type.isTypeVector());
3199 case Tsarray: return visitSArray(type.isTypeSArray());
3200 case Tarray: return visitDArray(type.isTypeDArray());
3201 case Taarray: return visitAArray(type.isTypeAArray());
3202 case Tpointer: return visitPointer(type.isTypePointer());
3203 case Treference: return visitReference(type.isTypeReference());
3204 case Tfunction: return visitFunction(type.isTypeFunction());
3205 case Tdelegate: return visitDelegate(type.isTypeDelegate());
3206 case Tident: return visitIdentifier(type.isTypeIdentifier());
3207 case Tinstance: return visitInstance(type.isTypeInstance());
3208 case Ttypeof: return visitTypeof(type.isTypeTypeof());
3209 case Ttraits: return visitTraits(type.isTypeTraits());
3210 case Treturn: return visitReturn(type.isTypeReturn());
3211 case Tstruct: return visitStruct(type.isTypeStruct());
3212 case Tenum: return visitEnum(type.isTypeEnum());
3213 case Tclass: return visitClass(type.isTypeClass());
3214 case Ttuple: return visitTuple(type.isTypeTuple());
3215 case Tslice: return visitSlice(type.isTypeSlice());
3216 case Tmixin: return visitMixin(type.isTypeMixin());
3217 case Ttag: return visitTag(type.isTypeTag());
3218 }
3219 }
3220
3221 Type trySemantic(Type type, Loc loc, Scope* sc)
3222 {
3223 //printf("+trySemantic(%s) %d\n", toChars(), global.errors);
3224
3225 // Needed to display any deprecations that were gagged
3226 auto tcopy = type.syntaxCopy();
3227
3228 const errors = global.startGagging();
3229 Type t = typeSemantic(type, loc, sc);
3230 if (global.endGagging(errors) || t.ty == Terror) // if any errors happened
3231 {
3232 t = null;
3233 }
3234 else
3235 {
3236 // If `typeSemantic` succeeded, there may have been deprecations that
3237 // were gagged due the `startGagging` above. Run again to display
3238 // those deprecations. https://issues.dlang.org/show_bug.cgi?id=19107
3239 if (global.gaggedWarnings > 0)
3240 typeSemantic(tcopy, loc, sc);
3241 }
3242 //printf("-trySemantic(%s) %d\n", toChars(), global.errors);
3243 return t;
3244 }
3245
3246 /************************************
3247 * If an identical type to `type` is in `type.stringtable`, return
3248 * the latter one. Otherwise, add it to `type.stringtable`.
3249 * Some types don't get merged and are returned as-is.
3250 * Params:
3251 * type = Type to check against existing types
3252 * Returns:
3253 * the type that was merged
3254 */
3255 Type merge(Type type)
3256 {
3257 switch (type.ty)
3258 {
3259 case Terror:
3260 case Ttypeof:
3261 case Tident:
3262 case Tinstance:
3263 case Tmixin:
3264 case Ttag:
3265 return type; // don't merge placeholder types
3266
3267 case Tsarray:
3268 // prevents generating the mangle if the array dim is not yet known
3269 if (auto ie = type.isTypeSArray().dim.isIntegerExp())
3270 {
3271 // After TypeSemantic, the length is always converted to size_t, but the parser
3272 // usually generates regular integer types (e.g. in cast(const ubyte[2])) which
3273 // it may try to merge, which then leads to failing implicit conversions as 2LU != 2
3274 // according to Expression.equals. Only merge array types with size_t lengths for now.
3275 // https://github.com/dlang/dmd/issues/21179
3276 if (ie.type != Type.tsize_t)
3277 return type;
3278
3279 goto default;
3280 }
3281 return type;
3282
3283 case Tenum:
3284 break;
3285
3286 case Taarray:
3287 if (!type.isTypeAArray().index.merge().deco)
3288 return type;
3289 goto default;
3290
3291 default:
3292 if (type.nextOf() && !type.nextOf().deco)
3293 return type;
3294 break;
3295 }
3296
3297 //printf("merge(%s)\n", toChars());
3298 if (type.deco)
3299 return type;
3300
3301 OutBuffer buf;
3302 buf.reserve(32);
3303
3304 mangleToBuffer(type, buf);
3305
3306 auto sv = type.stringtable.update(buf[]);
3307 if (sv.value)
3308 {
3309 Type t = sv.value;
3310 debug
3311 {
3312 import core.stdc.stdio;
3313 if (!t.deco)
3314 printf("t = %s\n", t.toChars());
3315 }
3316 assert(t.deco);
3317 //printf("old value, deco = '%s' %p\n", t.deco, t.deco);
3318 return t;
3319 }
3320 else
3321 {
3322 Type t = stripDefaultArgs(type);
3323 sv.value = t;
3324 type.deco = t.deco = cast(char*)sv.toDchars();
3325 //printf("new value, deco = '%s' %p\n", t.deco, t.deco);
3326 return t;
3327 }
3328 }
3329
3330 /*************************************
3331 * This version does a merge even if the deco is already computed.
3332 * Necessary for types that have a deco, but are not merged.
3333 */
3334 Type merge2(Type type)
3335 {
3336 //printf("merge2(%s)\n", toChars());
3337 Type t = type;
3338 assert(t);
3339 if (!t.deco)
3340 return t.merge();
3341
3342 auto sv = Type.stringtable.lookup(t.deco, strlen(t.deco));
3343 if (sv && sv.value)
3344 {
3345 t = sv.value;
3346 assert(t.deco);
3347 }
3348 else
3349 assert(0);
3350 return t;
3351 }
3352
3353 /***************************************
3354 * Calculate built-in properties which just the type is necessary.
3355 *
3356 * Params:
3357 * t = the type for which the property is calculated
3358 * scope_ = the scope from which the property is being accessed. Used for visibility checks only.
3359 * loc = the location where the property is encountered
3360 * ident = the identifier of the property
3361 * flag = if flag & 1, don't report "not a property" error and just return NULL.
3362 * src = expression for type `t` or null.
3363 * Returns:
3364 * expression representing the property, or null if not a property and (flag & 1)
3365 */
3366 Expression getProperty(Type t, Scope* scope_, Loc loc, Identifier ident, int flag,
3367 Expression src = null)
3368 {
3369 Expression visitType(Type mt)
3370 {
3371 Expression e;
3372 static if (LOGDOTEXP)
3373 {
3374 printf("Type::getProperty(type = '%s', ident = '%s')\n", mt.toChars(), ident.toChars());
3375 }
3376 if (ident == Id.__sizeof)
3377 {
3378 const sz = mt.size(loc);
3379 if (sz == SIZE_INVALID)
3380 return ErrorExp.get();
3381 return new IntegerExp(loc, sz, Type.tsize_t);
3382 }
3383 else if (ident == Id.__xalignof)
3384 {
3385 const explicitAlignment = mt.alignment();
3386 const naturalAlignment = mt.alignsize();
3387 const actualAlignment = (explicitAlignment.isDefault() ? naturalAlignment : explicitAlignment.get());
3388 return new IntegerExp(loc, actualAlignment, Type.tsize_t);
3389 }
3390 else if (ident == Id._init)
3391 {
3392 Type tb = mt.toBasetype();
3393 e = mt.defaultInitLiteral(loc);
3394 if (tb.ty == Tstruct && tb.needsNested())
3395 {
3396 e.isStructLiteralExp().useStaticInit = true;
3397 }
3398 return e;
3399 }
3400 else if (ident == Id._mangleof)
3401 {
3402 if (!mt.deco)
3403 {
3404 error(loc, "forward reference of type `%s.mangleof`", mt.toChars());
3405 return ErrorExp.get();
3406 }
3407 else
3408 {
3409 e = new StringExp(loc, mt.deco.toDString());
3410 Scope sc;
3411 sc.eSink = global.errorSink;
3412 e = e.expressionSemantic(&sc);
3413 }
3414 return e;
3415 }
3416 else if (ident == Id.stringof)
3417 {
3418 const s = mt.toChars();
3419 e = new StringExp(loc, s.toDString());
3420 Scope sc;
3421 sc.eSink = global.errorSink;
3422 e = e.expressionSemantic(&sc);
3423 return e;
3424 }
3425 else if (flag && mt != Type.terror)
3426 {
3427 return null;
3428 }
3429
3430 Dsymbol s = null;
3431 if (mt.ty == Tstruct || mt.ty == Tclass || mt.ty == Tenum)
3432 s = mt.toDsymbol(null);
3433 if (s)
3434 s = s.search_correct(ident);
3435 if (s && !symbolIsVisible(scope_, s))
3436 s = null;
3437
3438 if (mt == Type.terror)
3439 return ErrorExp.get();
3440
3441 if (s)
3442 error(loc, "no property `%s` for type `%s`, did you mean `%s`?", ident.toChars(), mt.toChars(), s.toPrettyChars());
3443 else if (ident == Id.opCall && mt.ty == Tclass)
3444 error(loc, "no property `%s` for type `%s`, did you mean `new %s`?", ident.toChars(), mt.toChars(), mt.toPrettyChars());
3445
3446 else if (const n = importHint(ident.toString()))
3447 error(loc, "no property `%s` for type `%s`, perhaps `import %.*s;` is needed?", ident.toChars(), mt.toChars(), cast(int)n.length, n.ptr);
3448 else
3449 {
3450 if (src)
3451 {
3452 error(loc, "no property `%s` for `%s` of type `%s`",
3453 ident.toChars(), src.toChars(), mt.toPrettyChars(true));
3454 auto s2 = scope_.search_correct(ident);
3455 // UFCS
3456 if (s2 && s2.isFuncDeclaration)
3457 {
3458 if (s2.ident == ident)
3459 {
3460 errorSupplemental(s2.loc, "cannot call %s `%s` with UFCS because it is not declared at module scope",
3461 s2.kind(), s2.toChars());
3462 }
3463 else
3464 errorSupplemental(s2.loc, "did you mean %s `%s`?",
3465 s2.kind(), s2.toChars());
3466 }
3467 else if (src.type.ty == Tpointer)
3468 {
3469 // structPtr.field
3470 auto tn = (cast(TypeNext) src.type).nextOf();
3471 if (auto as = tn.isAggregate())
3472 {
3473 if (auto s3 = as.search_correct(ident))
3474 {
3475 errorSupplemental(s3.loc, "did you mean %s `%s`?",
3476 s3.kind(), s3.toChars());
3477 }
3478 }
3479 }
3480 }
3481 else
3482 error(loc, "no property `%s` for type `%s`", ident.toChars(), mt.toPrettyChars(true));
3483
3484 if (auto dsym = mt.toDsymbol(scope_))
3485 {
3486 if (auto sym = dsym.isAggregateDeclaration())
3487 {
3488 if (!sym.members)
3489 {
3490 errorSupplemental(sym.loc, "`%s %s` is opaque and has no members.", sym.kind, mt.toPrettyChars(true));
3491 return ErrorExp.get();
3492 }
3493
3494 if (auto fd = search_function(sym, Id.opDispatch))
3495 {
3496 if (auto td = fd.isTemplateDeclaration())
3497 {
3498 e = mt.defaultInitLiteral(loc);
3499 auto se = new StringExp(e.loc, ident.toString());
3500 auto tiargs = new Objects();
3501 tiargs.push(se);
3502 auto dti = new DotTemplateInstanceExp(e.loc, e, Id.opDispatch, tiargs);
3503 dti.ti.tempdecl = td;
3504 dti.dotTemplateSemanticProp(scope_, DotExpFlag.none);
3505 return ErrorExp.get();
3506 }
3507 }
3508 }
3509 errorSupplemental(dsym.loc, "%s `%s` defined here",
3510 dsym.kind, dsym.toChars());
3511 }
3512 }
3513
3514 return ErrorExp.get();
3515 }
3516
3517 Expression visitError(TypeError)
3518 {
3519 return ErrorExp.get();
3520 }
3521
3522 Expression visitBasic(TypeBasic mt)
3523 {
3524 Expression integerValue(dinteger_t i)
3525 {
3526 return new IntegerExp(loc, i, mt);
3527 }
3528
3529 Expression intValue(dinteger_t i)
3530 {
3531 return new IntegerExp(loc, i, Type.tint32);
3532 }
3533
3534 Expression floatValue(real_t r)
3535 {
3536 if (mt.isReal() || mt.isImaginary())
3537 return new RealExp(loc, r, mt);
3538 else
3539 {
3540 return new ComplexExp(loc, complex_t(r, r), mt);
3541 }
3542 }
3543
3544 //printf("TypeBasic::getProperty('%s')\n", ident.toChars());
3545 if (ident == Id.max)
3546 {
3547 switch (mt.ty)
3548 {
3549 case Tint8: return integerValue(byte.max);
3550 case Tuns8: return integerValue(ubyte.max);
3551 case Tint16: return integerValue(short.max);
3552 case Tuns16: return integerValue(ushort.max);
3553 case Tint32: return integerValue(int.max);
3554 case Tuns32: return integerValue(uint.max);
3555 case Tint64: return integerValue(long.max);
3556 case Tuns64: return integerValue(ulong.max);
3557 case Tbool: return integerValue(bool.max);
3558 case Tchar: return integerValue(char.max);
3559 case Twchar: return integerValue(wchar.max);
3560 case Tdchar: return integerValue(dchar.max);
3561 case Tcomplex32:
3562 case Timaginary32:
3563 case Tfloat32: return floatValue(target.FloatProperties.max);
3564 case Tcomplex64:
3565 case Timaginary64:
3566 case Tfloat64: return floatValue(target.DoubleProperties.max);
3567 case Tcomplex80:
3568 case Timaginary80:
3569 case Tfloat80: return floatValue(target.RealProperties.max);
3570 default: break;
3571 }
3572 }
3573 else if (ident == Id.min)
3574 {
3575 switch (mt.ty)
3576 {
3577 case Tint8: return integerValue(byte.min);
3578 case Tuns8:
3579 case Tuns16:
3580 case Tuns32:
3581 case Tuns64:
3582 case Tbool:
3583 case Tchar:
3584 case Twchar:
3585 case Tdchar: return integerValue(0);
3586 case Tint16: return integerValue(short.min);
3587 case Tint32: return integerValue(int.min);
3588 case Tint64: return integerValue(long.min);
3589 default: break;
3590 }
3591 }
3592 else if (ident == Id.min_normal)
3593 {
3594 switch (mt.ty)
3595 {
3596 case Tcomplex32:
3597 case Timaginary32:
3598 case Tfloat32: return floatValue(target.FloatProperties.min_normal);
3599 case Tcomplex64:
3600 case Timaginary64:
3601 case Tfloat64: return floatValue(target.DoubleProperties.min_normal);
3602 case Tcomplex80:
3603 case Timaginary80:
3604 case Tfloat80: return floatValue(target.RealProperties.min_normal);
3605 default: break;
3606 }
3607 }
3608 else if (ident == Id.nan)
3609 {
3610 switch (mt.ty)
3611 {
3612 case Tcomplex32:
3613 case Tcomplex64:
3614 case Tcomplex80:
3615 case Timaginary32:
3616 case Timaginary64:
3617 case Timaginary80:
3618 case Tfloat32:
3619 case Tfloat64:
3620 case Tfloat80: return floatValue(target.RealProperties.nan);
3621 default: break;
3622 }
3623 }
3624 else if (ident == Id.infinity)
3625 {
3626 switch (mt.ty)
3627 {
3628 case Tcomplex32:
3629 case Tcomplex64:
3630 case Tcomplex80:
3631 case Timaginary32:
3632 case Timaginary64:
3633 case Timaginary80:
3634 case Tfloat32:
3635 case Tfloat64:
3636 case Tfloat80: return floatValue(target.RealProperties.infinity);
3637 default: break;
3638 }
3639 }
3640 else if (ident == Id.dig)
3641 {
3642 switch (mt.ty)
3643 {
3644 case Tcomplex32:
3645 case Timaginary32:
3646 case Tfloat32: return intValue(target.FloatProperties.dig);
3647 case Tcomplex64:
3648 case Timaginary64:
3649 case Tfloat64: return intValue(target.DoubleProperties.dig);
3650 case Tcomplex80:
3651 case Timaginary80:
3652 case Tfloat80: return intValue(target.RealProperties.dig);
3653 default: break;
3654 }
3655 }
3656 else if (ident == Id.epsilon)
3657 {
3658 switch (mt.ty)
3659 {
3660 case Tcomplex32:
3661 case Timaginary32:
3662 case Tfloat32: return floatValue(target.FloatProperties.epsilon);
3663 case Tcomplex64:
3664 case Timaginary64:
3665 case Tfloat64: return floatValue(target.DoubleProperties.epsilon);
3666 case Tcomplex80:
3667 case Timaginary80:
3668 case Tfloat80: return floatValue(target.RealProperties.epsilon);
3669 default: break;
3670 }
3671 }
3672 else if (ident == Id.mant_dig)
3673 {
3674 switch (mt.ty)
3675 {
3676 case Tcomplex32:
3677 case Timaginary32:
3678 case Tfloat32: return intValue(target.FloatProperties.mant_dig);
3679 case Tcomplex64:
3680 case Timaginary64:
3681 case Tfloat64: return intValue(target.DoubleProperties.mant_dig);
3682 case Tcomplex80:
3683 case Timaginary80:
3684 case Tfloat80: return intValue(target.RealProperties.mant_dig);
3685 default: break;
3686 }
3687 }
3688 else if (ident == Id.max_10_exp)
3689 {
3690 switch (mt.ty)
3691 {
3692 case Tcomplex32:
3693 case Timaginary32:
3694 case Tfloat32: return intValue(target.FloatProperties.max_10_exp);
3695 case Tcomplex64:
3696 case Timaginary64:
3697 case Tfloat64: return intValue(target.DoubleProperties.max_10_exp);
3698 case Tcomplex80:
3699 case Timaginary80:
3700 case Tfloat80: return intValue(target.RealProperties.max_10_exp);
3701 default: break;
3702 }
3703 }
3704 else if (ident == Id.max_exp)
3705 {
3706 switch (mt.ty)
3707 {
3708 case Tcomplex32:
3709 case Timaginary32:
3710 case Tfloat32: return intValue(target.FloatProperties.max_exp);
3711 case Tcomplex64:
3712 case Timaginary64:
3713 case Tfloat64: return intValue(target.DoubleProperties.max_exp);
3714 case Tcomplex80:
3715 case Timaginary80:
3716 case Tfloat80: return intValue(target.RealProperties.max_exp);
3717 default: break;
3718 }
3719 }
3720 else if (ident == Id.min_10_exp)
3721 {
3722 switch (mt.ty)
3723 {
3724 case Tcomplex32:
3725 case Timaginary32:
3726 case Tfloat32: return intValue(target.FloatProperties.min_10_exp);
3727 case Tcomplex64:
3728 case Timaginary64:
3729 case Tfloat64: return intValue(target.DoubleProperties.min_10_exp);
3730 case Tcomplex80:
3731 case Timaginary80:
3732 case Tfloat80: return intValue(target.RealProperties.min_10_exp);
3733 default: break;
3734 }
3735 }
3736 else if (ident == Id.min_exp)
3737 {
3738 switch (mt.ty)
3739 {
3740 case Tcomplex32:
3741 case Timaginary32:
3742 case Tfloat32: return intValue(target.FloatProperties.min_exp);
3743 case Tcomplex64:
3744 case Timaginary64:
3745 case Tfloat64: return intValue(target.DoubleProperties.min_exp);
3746 case Tcomplex80:
3747 case Timaginary80:
3748 case Tfloat80: return intValue(target.RealProperties.min_exp);
3749 default: break;
3750 }
3751 }
3752 return visitType(mt);
3753 }
3754
3755 Expression visitVector(TypeVector mt)
3756 {
3757 return visitType(mt);
3758 }
3759
3760 Expression visitEnum(TypeEnum mt)
3761 {
3762 Expression e;
3763 if (ident == Id.max || ident == Id.min)
3764 {
3765 return mt.sym.getMaxMinValue(loc, ident);
3766 }
3767 else if (ident == Id._init)
3768 {
3769 e = mt.defaultInitLiteral(loc);
3770 }
3771 else if (ident == Id.stringof)
3772 {
3773 e = new StringExp(loc, mt.toString());
3774 Scope sc;
3775 e = e.expressionSemantic(&sc);
3776 }
3777 else if (ident == Id._mangleof)
3778 {
3779 e = visitType(mt);
3780 }
3781 else
3782 {
3783 e = mt.toBasetype().getProperty(scope_, loc, ident, flag);
3784 }
3785 return e;
3786 }
3787
3788 Expression visitTuple(TypeTuple mt)
3789 {
3790 Expression e;
3791 static if (LOGDOTEXP)
3792 {
3793 printf("TypeTuple::getProperty(type = '%s', ident = '%s')\n", mt.toChars(), ident.toChars());
3794 }
3795 if (ident == Id.length)
3796 {
3797 e = new IntegerExp(loc, mt.arguments.length, Type.tsize_t);
3798 }
3799 else if (ident == Id._init)
3800 {
3801 e = mt.defaultInitLiteral(loc);
3802 }
3803 else if (flag)
3804 {
3805 e = null;
3806 }
3807 else
3808 {
3809 error(loc, "no property `%s` for sequence `%s`", ident.toChars(), mt.toChars());
3810 e = ErrorExp.get();
3811 }
3812 return e;
3813 }
3814
3815 switch (t.ty)
3816 {
3817 default: return t.isTypeBasic() ?
3818 visitBasic(cast(TypeBasic)t) :
3819 visitType(t);
3820
3821 case Terror: return visitError (t.isTypeError());
3822 case Tvector: return visitVector(t.isTypeVector());
3823 case Tenum: return visitEnum (t.isTypeEnum());
3824 case Ttuple: return visitTuple (t.isTypeTuple());
3825 }
3826 }
3827
3828 /***************************************
3829 * Determine if Expression `exp` should instead be a Type, a Dsymbol, or remain an Expression.
3830 * Params:
3831 * exp = Expression to look at
3832 * t = if exp should be a Type, set t to that Type else null
3833 * s = if exp should be a Dsymbol, set s to that Dsymbol else null
3834 * e = if exp should remain an Expression, set e to that Expression else null
3835 *
3836 */
3837 private void resolveExp(Expression exp, out Type t, out Expression e, out Dsymbol s)
3838 {
3839 if (exp.isTypeExp())
3840 t = exp.type;
3841 else if (auto ve = exp.isVarExp())
3842 {
3843 if (auto v = ve.var.isVarDeclaration())
3844 e = exp;
3845 else
3846 s = ve.var;
3847 }
3848 else if (auto te = exp.isTemplateExp())
3849 s = te.td;
3850 else if (auto se = exp.isScopeExp())
3851 s = se.sds;
3852 else if (exp.isFuncExp())
3853 s = getDsymbol(exp);
3854 else if (auto dte = exp.isDotTemplateExp())
3855 s = dte.td;
3856 else if (exp.isErrorExp())
3857 t = Type.terror;
3858 else
3859 e = exp;
3860 }
3861
3862 /************************************
3863 * Resolve type 'mt' to either type, symbol, or expression.
3864 * If errors happened, resolved to Type.terror.
3865 *
3866 * Params:
3867 * mt = type to be resolved
3868 * loc = the location where the type is encountered
3869 * sc = the scope of the type
3870 * pe = is set if t is an expression
3871 * pt = is set if t is a type
3872 * ps = is set if t is a symbol
3873 * intypeid = true if in type id
3874 */
3875 void resolve(Type mt, Loc loc, Scope* sc, out Expression pe, out Type pt, out Dsymbol ps, bool intypeid = false)
3876 {
3877 void returnExp(Expression e)
3878 {
3879 pe = e;
3880 pt = null;
3881 ps = null;
3882 }
3883
3884 void returnType(Type t)
3885 {
3886 pe = null;
3887 pt = t;
3888 ps = null;
3889 }
3890
3891 void returnSymbol(Dsymbol s)
3892 {
3893 pe = null;
3894 pt = null;
3895 ps = s;
3896 }
3897
3898 void returnError()
3899 {
3900 returnType(Type.terror);
3901 }
3902
3903 void visitType(Type mt)
3904 {
3905 //printf("Type::resolve() %s, %d\n", mt.toChars(), mt.ty);
3906 Type t = typeSemantic(mt, loc, sc);
3907 assert(t);
3908 returnType(t);
3909 }
3910
3911 void visitSArray(TypeSArray mt)
3912 {
3913 //printf("TypeSArray::resolve() %s\n", mt.toChars());
3914 mt.next.resolve(loc, sc, pe, pt, ps, intypeid);
3915 //printf("s = %p, e = %p, t = %p\n", ps, pe, pt);
3916 if (pe)
3917 {
3918 // It's really an index expression
3919 if (Dsymbol s = getDsymbol(pe))
3920 pe = new DsymbolExp(loc, s);
3921 returnExp(new ArrayExp(loc, pe, mt.dim));
3922 }
3923 else if (ps)
3924 {
3925 Dsymbol s = ps;
3926 if (auto tup = s.isTupleDeclaration())
3927 {
3928 mt.dim = semanticLength(sc, tup, mt.dim);
3929 mt.dim = mt.dim.ctfeInterpret();
3930 if (mt.dim.op == EXP.error)
3931 return returnError();
3932
3933 const d = mt.dim.toUInteger();
3934 if (d >= tup.objects.length)
3935 {
3936 error(loc, "sequence index `%llu` out of bounds `[0 .. %llu]`", d, cast(ulong) tup.objects.length);
3937 return returnError();
3938 }
3939
3940 RootObject o = (*tup.objects)[cast(size_t)d];
3941 switch (o.dyncast()) with (DYNCAST)
3942 {
3943 case dsymbol:
3944 return returnSymbol(cast(Dsymbol)o);
3945 case expression:
3946 Expression e = cast(Expression)o;
3947 if (e.op == EXP.dSymbol)
3948 return returnSymbol(e.isDsymbolExp().s);
3949 else
3950 return returnExp(e);
3951 case type:
3952 return returnType((cast(Type)o).addMod(mt.mod));
3953 default:
3954 break;
3955 }
3956
3957 /* Create a new TupleDeclaration which
3958 * is a slice [d..d+1] out of the old one.
3959 * Do it this way because TemplateInstance::semanticTiargs()
3960 * can handle unresolved Objects this way.
3961 */
3962 auto objects = new Objects(1);
3963 (*objects)[0] = o;
3964 return returnSymbol(new TupleDeclaration(loc, tup.ident, objects));
3965 }
3966 else
3967 return visitType(mt);
3968 }
3969 else
3970 {
3971 if (pt.ty != Terror)
3972 mt.next = pt; // prevent re-running semantic() on 'next'
3973 visitType(mt);
3974 }
3975
3976 }
3977
3978 void visitDArray(TypeDArray mt)
3979 {
3980 //printf("TypeDArray::resolve() %s\n", mt.toChars());
3981 mt.next.resolve(loc, sc, pe, pt, ps, intypeid);
3982 //printf("s = %p, e = %p, t = %p\n", ps, pe, pt);
3983 if (pe)
3984 {
3985 // It's really a slice expression
3986 if (Dsymbol s = getDsymbol(pe))
3987 pe = new DsymbolExp(loc, s);
3988 returnExp(new ArrayExp(loc, pe));
3989 }
3990 else if (ps)
3991 {
3992 if (auto tup = ps.isTupleDeclaration())
3993 {
3994 // keep ps
3995 }
3996 else
3997 visitType(mt);
3998 }
3999 else
4000 {
4001 if (pt.ty != Terror)
4002 mt.next = pt; // prevent re-running semantic() on 'next'
4003 visitType(mt);
4004 }
4005 }
4006
4007 void visitAArray(TypeAArray mt)
4008 {
4009 //printf("TypeAArray::resolve() %s\n", mt.toChars());
4010 // Deal with the case where we thought the index was a type, but
4011 // in reality it was an expression.
4012 if (mt.index.ty == Tident || mt.index.ty == Tinstance || mt.index.ty == Tsarray)
4013 {
4014 Expression e;
4015 Type t;
4016 Dsymbol s;
4017 mt.index.resolve(loc, sc, e, t, s, intypeid);
4018 if (e)
4019 {
4020 // It was an expression -
4021 // Rewrite as a static array
4022 auto tsa = new TypeSArray(mt.next, e);
4023 tsa.mod = mt.mod; // just copy mod field so tsa's semantic is not yet done
4024 return tsa.resolve(loc, sc, pe, pt, ps, intypeid);
4025 }
4026 else if (t)
4027 mt.index = t;
4028 else
4029 .error(loc, "index is not a type or an expression");
4030 }
4031 visitType(mt);
4032 }
4033
4034 /*************************************
4035 * Takes an array of Identifiers and figures out if
4036 * it represents a Type or an Expression.
4037 * Output:
4038 * if expression, pe is set
4039 * if type, pt is set
4040 */
4041 void visitIdentifier(TypeIdentifier mt)
4042 {
4043 //printf("TypeIdentifier::resolve(sc = %p, idents = '%s')\n", sc, mt.toChars());
4044 if (mt.ident == Id.ctfe)
4045 {
4046 error(loc, "variable `__ctfe` cannot be read at compile time");
4047 return returnError();
4048 }
4049 if (mt.ident == Id.builtin_va_list) // gcc has __builtin_va_xxxx for stdarg.h
4050 {
4051 /* Since we don't support __builtin_va_start, -arg, -end, we don't
4052 * have to actually care what -list is. A void* will do.
4053 * If we ever do care, import core.stdc.stdarg and pull
4054 * the definition out of that, similarly to how std.math is handled for PowExp
4055 */
4056 pt = target.va_listType(loc, sc);
4057 return;
4058 }
4059
4060 Dsymbol scopesym;
4061 Dsymbol s = sc.search(loc, mt.ident, scopesym);
4062 /*
4063 * https://issues.dlang.org/show_bug.cgi?id=1170
4064 * https://issues.dlang.org/show_bug.cgi?id=10739
4065 *
4066 * If a symbol is not found, it might be declared in
4067 * a mixin-ed string or a mixin-ed template, so before
4068 * issuing an error semantically analyze all string/template
4069 * mixins that are members of the current ScopeDsymbol.
4070 */
4071 if (!s && sc.enclosing)
4072 {
4073 ScopeDsymbol sds = sc.enclosing.scopesym;
4074 if (sds && sds.members)
4075 {
4076 void semanticOnMixin(Dsymbol member)
4077 {
4078 if (auto compileDecl = member.isMixinDeclaration())
4079 compileDecl.dsymbolSemantic(sc);
4080 else if (auto mixinTempl = member.isTemplateMixin())
4081 mixinTempl.dsymbolSemantic(sc);
4082 }
4083 sds.members.foreachDsymbol( s => semanticOnMixin(s) );
4084 s = sc.search(loc, mt.ident, scopesym);
4085 }
4086 }
4087
4088 if (s)
4089 {
4090 // https://issues.dlang.org/show_bug.cgi?id=16042
4091 // If `f` is really a function template, then replace `f`
4092 // with the function template declaration.
4093 if (auto f = s.isFuncDeclaration())
4094 {
4095 if (auto td = getFuncTemplateDecl(f))
4096 {
4097 // If not at the beginning of the overloaded list of
4098 // `TemplateDeclaration`s, then get the beginning
4099 if (td.overroot)
4100 td = td.overroot;
4101 s = td;
4102 }
4103 }
4104 }
4105
4106 mt.resolveHelper(loc, sc, s, scopesym, pe, pt, ps, intypeid);
4107 if (pt)
4108 pt = pt.addMod(mt.mod);
4109 }
4110
4111 void visitInstance(TypeInstance mt)
4112 {
4113 // Note close similarity to TypeIdentifier::resolve()
4114
4115 //printf("TypeInstance::resolve(sc = %p, tempinst = '%s')\n", sc, mt.tempinst.toChars());
4116 mt.tempinst.dsymbolSemantic(sc);
4117 if (!global.gag && mt.tempinst.errors)
4118 return returnError();
4119
4120 mt.resolveHelper(loc, sc, mt.tempinst, null, pe, pt, ps, intypeid);
4121 if (pt)
4122 pt = pt.addMod(mt.mod);
4123 //if (pt) printf("pt = %d '%s'\n", pt.ty, pt.toChars());
4124 }
4125
4126 void visitTypeof(TypeTypeof mt)
4127 {
4128 //printf("TypeTypeof::resolve(this = %p, sc = %p, idents = '%s')\n", mt, sc, mt.toChars());
4129 //static int nest; if (++nest == 50) *(char*)0=0;
4130 if (sc is null)
4131 {
4132 error(loc, "invalid scope");
4133 return returnError();
4134 }
4135 if (mt.inuse)
4136 {
4137 mt.inuse = 2;
4138 error(loc, "circular `typeof` definition");
4139 Lerr:
4140 mt.inuse--;
4141 return returnError();
4142 }
4143 mt.inuse++;
4144
4145 /* Currently we cannot evaluate 'exp' in speculative context, because
4146 * the type implementation may leak to the final execution. Consider:
4147 *
4148 * struct S(T) {
4149 * string toString() const { return "x"; }
4150 * }
4151 * void main() {
4152 * alias X = typeof(S!int());
4153 * assert(typeid(X).toString() == "x");
4154 * }
4155 */
4156 Scope* sc2 = sc.push();
4157
4158 if (!mt.exp.isTypeidExp())
4159 /* Treat typeof(typeid(exp)) as needing
4160 * the full semantic analysis of the typeid.
4161 * https://issues.dlang.org/show_bug.cgi?id=20958
4162 */
4163 sc2.intypeof = 1;
4164
4165 auto exp2 = mt.exp.expressionSemantic(sc2);
4166 exp2 = resolvePropertiesOnly(sc2, exp2);
4167 sc2.pop();
4168
4169 if (exp2.op == EXP.error)
4170 {
4171 if (!global.gag)
4172 mt.exp = exp2;
4173 goto Lerr;
4174 }
4175 mt.exp = exp2;
4176
4177 if ((mt.exp.op == EXP.type || mt.exp.op == EXP.scope_) &&
4178 // https://issues.dlang.org/show_bug.cgi?id=23863
4179 // compile time sequences are valid types
4180 !mt.exp.type.isTypeTuple())
4181 {
4182 if (!sc.inCfile && // in (extended) C typeof may be used on types as with sizeof
4183 mt.exp.checkType())
4184 goto Lerr;
4185
4186 /* Today, 'typeof(func)' returns void if func is a
4187 * function template (TemplateExp), or
4188 * template lambda (FuncExp).
4189 * It's actually used in Phobos as an idiom, to branch code for
4190 * template functions.
4191 */
4192 }
4193 if (auto f = mt.exp.op == EXP.variable ? mt.exp.isVarExp().var.isFuncDeclaration()
4194 : mt.exp.op == EXP.dotVariable ? mt.exp.isDotVarExp().var.isFuncDeclaration() : null)
4195 {
4196 // f might be a unittest declaration which is incomplete when compiled
4197 // without -unittest. That causes a segfault in checkForwardRef, see
4198 // https://issues.dlang.org/show_bug.cgi?id=20626
4199 if ((!f.isUnitTestDeclaration() || global.params.useUnitTests) && checkForwardRef(f, loc))
4200 goto Lerr;
4201 }
4202 if (auto f = isFuncAddress(mt.exp))
4203 {
4204 if (checkForwardRef(f, loc))
4205 goto Lerr;
4206 }
4207
4208 Type t = mt.exp.type;
4209 if (!t)
4210 {
4211 error(loc, "expression `%s` has no type", mt.exp.toChars());
4212 goto Lerr;
4213 }
4214 if (t.ty == Ttypeof)
4215 {
4216 error(loc, "forward reference to `%s`", mt.toChars());
4217 goto Lerr;
4218 }
4219 if (mt.idents.length == 0)
4220 {
4221 returnType(t.addMod(mt.mod));
4222 }
4223 else
4224 {
4225 if (Dsymbol s = t.toDsymbol(sc))
4226 mt.resolveHelper(loc, sc, s, null, pe, pt, ps, intypeid);
4227 else
4228 {
4229 auto e = typeToExpressionHelper(mt, new TypeExp(loc, t));
4230 e = e.expressionSemantic(sc);
4231 resolveExp(e, pt, pe, ps);
4232 }
4233 if (pt)
4234 pt = pt.addMod(mt.mod);
4235 }
4236 mt.inuse--;
4237 }
4238
4239 void visitReturn(TypeReturn mt)
4240 {
4241 //printf("TypeReturn::resolve(sc = %p, idents = '%s')\n", sc, mt.toChars());
4242 Type t;
4243 {
4244 FuncDeclaration func = sc.func;
4245 if (!func)
4246 {
4247 error(loc, "`typeof(return)` must be inside function");
4248 return returnError();
4249 }
4250 if (func.fes)
4251 func = func.fes.func;
4252 t = func.type.nextOf();
4253 if (!t)
4254 {
4255 error(loc, "cannot use `typeof(return)` inside function `%s` with inferred return type", sc.func.toChars());
4256 return returnError();
4257 }
4258 }
4259 if (mt.idents.length == 0)
4260 {
4261 return returnType(t.addMod(mt.mod));
4262 }
4263 else
4264 {
4265 if (Dsymbol s = t.toDsymbol(sc))
4266 mt.resolveHelper(loc, sc, s, null, pe, pt, ps, intypeid);
4267 else
4268 {
4269 auto e = typeToExpressionHelper(mt, new TypeExp(loc, t));
4270 e = e.expressionSemantic(sc);
4271 resolveExp(e, pt, pe, ps);
4272 }
4273 if (pt)
4274 pt = pt.addMod(mt.mod);
4275 }
4276 }
4277
4278 void visitSlice(TypeSlice mt)
4279 {
4280 mt.next.resolve(loc, sc, pe, pt, ps, intypeid);
4281 if (pe)
4282 {
4283 // It's really a slice expression
4284 if (Dsymbol s = getDsymbol(pe))
4285 pe = new DsymbolExp(loc, s);
4286 return returnExp(new ArrayExp(loc, pe, new IntervalExp(loc, mt.lwr, mt.upr)));
4287 }
4288 else if (ps)
4289 {
4290 Dsymbol s = ps;
4291 TupleDeclaration td = s.isTupleDeclaration();
4292 if (td)
4293 {
4294 /* It's a slice of a TupleDeclaration
4295 */
4296 ScopeDsymbol sym = new ArrayScopeSymbol(sc, td);
4297 sym.parent = sc.scopesym;
4298 sc = sc.push(sym);
4299 sc = sc.startCTFE();
4300 mt.lwr = mt.lwr.expressionSemantic(sc);
4301 mt.upr = mt.upr.expressionSemantic(sc);
4302 sc = sc.endCTFE();
4303 sc = sc.pop();
4304
4305 mt.lwr = mt.lwr.ctfeInterpret();
4306 mt.upr = mt.upr.ctfeInterpret();
4307 const i1 = mt.lwr.toUInteger();
4308 const i2 = mt.upr.toUInteger();
4309 if (!(i1 <= i2 && i2 <= td.objects.length))
4310 {
4311 error(loc, "slice `[%llu..%llu]` is out of range of [0..%llu]", i1, i2, cast(ulong) td.objects.length);
4312 return returnError();
4313 }
4314
4315 if (i1 == 0 && i2 == td.objects.length)
4316 {
4317 return returnSymbol(td);
4318 }
4319
4320 /* Create a new TupleDeclaration which
4321 * is a slice [i1..i2] out of the old one.
4322 */
4323 auto objects = new Objects(cast(size_t)(i2 - i1));
4324 for (size_t i = 0; i < objects.length; i++)
4325 {
4326 (*objects)[i] = (*td.objects)[cast(size_t)i1 + i];
4327 }
4328
4329 return returnSymbol(new TupleDeclaration(loc, td.ident, objects));
4330 }
4331 else
4332 visitType(mt);
4333 }
4334 else
4335 {
4336 if (pt.ty != Terror)
4337 mt.next = pt; // prevent re-running semantic() on 'next'
4338 visitType(mt);
4339 }
4340 }
4341
4342 void visitMixin(TypeMixin mt)
4343 {
4344 RootObject o = mt.obj;
4345
4346 // if already resolved just set pe/pt/ps and return.
4347 if (o)
4348 {
4349 pe = o.isExpression();
4350 pt = o.isType();
4351 ps = o.isDsymbol();
4352 return;
4353 }
4354
4355 o = mt.compileTypeMixin(loc, sc);
4356 if (auto t = o.isType())
4357 {
4358 resolve(t, loc, sc, pe, pt, ps, intypeid);
4359 if (pt)
4360 pt = pt.addMod(mt.mod);
4361 }
4362 else if (auto e = o.isExpression())
4363 {
4364 e = e.expressionSemantic(sc);
4365 if (auto et = e.isTypeExp())
4366 returnType(et.type.addMod(mt.mod));
4367 else
4368 returnExp(e);
4369 }
4370 else
4371 returnError();
4372
4373 // save the result
4374 mt.obj = pe ? pe : (pt ? pt : ps);
4375 }
4376
4377 void visitTraits(TypeTraits mt)
4378 {
4379 // if already resolved just return the cached object.
4380 if (mt.obj)
4381 {
4382 pt = mt.obj.isType();
4383 ps = mt.obj.isDsymbol();
4384 pe = mt.obj.isExpression();
4385 return;
4386 }
4387
4388 import dmd.traits : semanticTraits;
4389
4390 if (Expression e = semanticTraits(mt.exp, sc))
4391 {
4392 switch (e.op)
4393 {
4394 case EXP.dotVariable:
4395 mt.obj = e.isDotVarExp().var;
4396 break;
4397 case EXP.variable:
4398 mt.obj = e.isVarExp().var;
4399 break;
4400 case EXP.function_:
4401 auto fe = e.isFuncExp();
4402 mt.obj = fe.td ? fe.td : fe.fd;
4403 break;
4404 case EXP.dotTemplateDeclaration:
4405 mt.obj = e.isDotTemplateExp().td;
4406 break;
4407 case EXP.dSymbol:
4408 mt.obj = e.isDsymbolExp().s;
4409 break;
4410 case EXP.template_:
4411 mt.obj = e.isTemplateExp().td;
4412 break;
4413 case EXP.scope_:
4414 mt.obj = e.isScopeExp().sds;
4415 break;
4416 case EXP.tuple:
4417 TupleExp te = e.isTupleExp();
4418 Objects* elems = new Objects(te.exps.length);
4419 foreach (i; 0 .. elems.length)
4420 {
4421 auto src = (*te.exps)[i];
4422 switch (src.op)
4423 {
4424 case EXP.type:
4425 (*elems)[i] = src.isTypeExp().type;
4426 break;
4427 case EXP.dotType:
4428 (*elems)[i] = src.isDotTypeExp().sym.isType();
4429 break;
4430 case EXP.overloadSet:
4431 (*elems)[i] = src.isOverExp().type;
4432 break;
4433 default:
4434 if (auto sym = isDsymbol(src))
4435 (*elems)[i] = sym;
4436 else
4437 (*elems)[i] = src;
4438 }
4439 }
4440 TupleDeclaration td = new TupleDeclaration(e.loc, Identifier.generateId("__aliastup"), elems);
4441 mt.obj = td;
4442 break;
4443 case EXP.dotType:
4444 mt.obj = e.isDotTypeExp().sym.isType();
4445 break;
4446 case EXP.type:
4447 mt.obj = e.isTypeExp().type;
4448 break;
4449 case EXP.overloadSet:
4450 mt.obj = e.isOverExp().type;
4451 break;
4452 case EXP.error:
4453 break;
4454 default:
4455 mt.obj = e;
4456 break;
4457 }
4458 }
4459
4460 if (mt.obj)
4461 {
4462 if (auto t = mt.obj.isType())
4463 {
4464 t = t.addMod(mt.mod);
4465 mt.obj = t;
4466 returnType(t);
4467 }
4468 else if (auto s = mt.obj.isDsymbol())
4469 returnSymbol(s);
4470 else if (auto e = mt.obj.isExpression())
4471 returnExp(e);
4472 }
4473 else
4474 {
4475 assert(global.errors);
4476 mt.obj = Type.terror;
4477 return returnError();
4478 }
4479 }
4480
4481 switch (mt.ty)
4482 {
4483 default: visitType (mt); break;
4484 case Tsarray: visitSArray (mt.isTypeSArray()); break;
4485 case Tarray: visitDArray (mt.isTypeDArray()); break;
4486 case Taarray: visitAArray (mt.isTypeAArray()); break;
4487 case Tident: visitIdentifier(mt.isTypeIdentifier()); break;
4488 case Tinstance: visitInstance (mt.isTypeInstance()); break;
4489 case Ttypeof: visitTypeof (mt.isTypeTypeof()); break;
4490 case Treturn: visitReturn (mt.isTypeReturn()); break;
4491 case Tslice: visitSlice (mt.isTypeSlice()); break;
4492 case Tmixin: visitMixin (mt.isTypeMixin()); break;
4493 case Ttraits: visitTraits (mt.isTypeTraits()); break;
4494 }
4495 }
4496
4497 /************************
4498 * Access the members of the object e. This type is same as e.type.
4499 * Params:
4500 * mt = type for which the dot expression is used
4501 * sc = instantiating scope
4502 * e = expression to convert
4503 * ident = identifier being used
4504 * flag = DotExpFlag bit flags
4505 *
4506 * Returns:
4507 * resulting expression with e.ident resolved
4508 */
4509 Expression dotExp(Type mt, Scope* sc, Expression e, Identifier ident, DotExpFlag flag)
4510 {
4511 enum LOGDOTEXP = false;
4512 if (LOGDOTEXP)
4513 printf("dotExp()\n");
4514
4515 Expression visitType(Type mt)
4516 {
4517 VarDeclaration v = null;
4518 static if (LOGDOTEXP)
4519 {
4520 printf("Type::dotExp(e = '%s', ident = '%s')\n", e.toChars(), ident.toChars());
4521 }
4522 Expression ex = e.lastComma();
4523 if (ex.op == EXP.dotVariable)
4524 {
4525 DotVarExp dv = cast(DotVarExp)ex;
4526 v = dv.var.isVarDeclaration();
4527 }
4528 else if (ex.op == EXP.variable)
4529 {
4530 VarExp ve = cast(VarExp)ex;
4531 v = ve.var.isVarDeclaration();
4532 }
4533 if (v)
4534 {
4535 if (ident == Id.offsetof ||
4536 ident == Id.bitoffsetof ||
4537 ident == Id.bitwidth)
4538 {
4539 v.dsymbolSemantic(null);
4540 if (v.isField())
4541 {
4542 auto ad = v.isMember();
4543 objc.checkOffsetof(e, ad);
4544 ad.size(e.loc);
4545 if (ad.sizeok != Sizeok.done)
4546 return ErrorExp.get();
4547 uint value;
4548 if (ident == Id.offsetof)
4549 value = v.offset;
4550 else // Id.bitoffsetof || Id.bitwidth
4551 {
4552 auto bf = v.isBitFieldDeclaration();
4553 if (bf)
4554 {
4555 value = ident == Id.bitoffsetof ? bf.bitOffset : bf.fieldWidth;
4556 }
4557 else
4558 error(v.loc, "`%s` is not a bitfield, cannot apply `%s`", v.toChars(), ident.toChars());
4559 }
4560 return new IntegerExp(e.loc, value, Type.tsize_t);
4561 }
4562 }
4563 else if (ident == Id._init)
4564 {
4565 Type tb = mt.toBasetype();
4566 e = mt.defaultInitLiteral(e.loc);
4567 if (tb.ty == Tstruct && tb.needsNested())
4568 {
4569 e.isStructLiteralExp().useStaticInit = true;
4570 }
4571 goto Lreturn;
4572 }
4573 }
4574 if (ident == Id.stringof)
4575 {
4576 /* https://issues.dlang.org/show_bug.cgi?id=3796
4577 * this should demangle e.type.deco rather than
4578 * pretty-printing the type.
4579 */
4580 e = new StringExp(e.loc, e.toString());
4581 }
4582 else
4583 e = mt.getProperty(sc, e.loc, ident, flag & DotExpFlag.gag);
4584
4585 Lreturn:
4586 if (e)
4587 e = e.expressionSemantic(sc);
4588 return e;
4589 }
4590
4591 Expression visitError(TypeError)
4592 {
4593 return ErrorExp.get();
4594 }
4595
4596 Expression visitBasic(TypeBasic mt)
4597 {
4598 static if (LOGDOTEXP)
4599 {
4600 printf("TypeBasic::dotExp(e = '%s', ident = '%s')\n", e.toChars(), ident.toChars());
4601 }
4602 Type t;
4603 if (ident == Id.re)
4604 {
4605 switch (mt.ty)
4606 {
4607 case Tcomplex32:
4608 t = mt.tfloat32;
4609 goto L1;
4610
4611 case Tcomplex64:
4612 t = mt.tfloat64;
4613 goto L1;
4614
4615 case Tcomplex80:
4616 t = mt.tfloat80;
4617 goto L1;
4618 L1:
4619 e = e.castTo(sc, t);
4620 break;
4621
4622 case Tfloat32:
4623 case Tfloat64:
4624 case Tfloat80:
4625 break;
4626
4627 case Timaginary32:
4628 t = mt.tfloat32;
4629 goto L2;
4630
4631 case Timaginary64:
4632 t = mt.tfloat64;
4633 goto L2;
4634
4635 case Timaginary80:
4636 t = mt.tfloat80;
4637 goto L2;
4638 L2:
4639 e = new RealExp(e.loc, CTFloat.zero, t);
4640 break;
4641
4642 default:
4643 e = mt.Type.getProperty(sc, e.loc, ident, flag);
4644 break;
4645 }
4646 }
4647 else if (ident == Id.im)
4648 {
4649 Type t2;
4650 switch (mt.ty)
4651 {
4652 case Tcomplex32:
4653 t = mt.timaginary32;
4654 t2 = mt.tfloat32;
4655 goto L3;
4656
4657 case Tcomplex64:
4658 t = mt.timaginary64;
4659 t2 = mt.tfloat64;
4660 goto L3;
4661
4662 case Tcomplex80:
4663 t = mt.timaginary80;
4664 t2 = mt.tfloat80;
4665 goto L3;
4666 L3:
4667 e = e.castTo(sc, t);
4668 e.type = t2;
4669 break;
4670
4671 case Timaginary32:
4672 t = mt.tfloat32;
4673 goto L4;
4674
4675 case Timaginary64:
4676 t = mt.tfloat64;
4677 goto L4;
4678
4679 case Timaginary80:
4680 t = mt.tfloat80;
4681 goto L4;
4682 L4:
4683 e = e.copy();
4684 e.type = t;
4685 break;
4686
4687 case Tfloat32:
4688 case Tfloat64:
4689 case Tfloat80:
4690 e = new RealExp(e.loc, CTFloat.zero, mt);
4691 break;
4692
4693 default:
4694 e = mt.Type.getProperty(sc, e.loc, ident, flag);
4695 break;
4696 }
4697 }
4698 else
4699 {
4700 return visitType(mt);
4701 }
4702 if (!(flag & 1) || e)
4703 e = e.expressionSemantic(sc);
4704 return e;
4705 }
4706
4707 Expression visitVector(TypeVector mt)
4708 {
4709 static if (LOGDOTEXP)
4710 {
4711 printf("TypeVector::dotExp(e = '%s', ident = '%s')\n", e.toChars(), ident.toChars());
4712 }
4713 if (ident == Id.ptr && e.op == EXP.call)
4714 {
4715 /* The trouble with EXP.call is the return ABI for float[4] is different from
4716 * __vector(float[4]), and a type paint won't do.
4717 */
4718 e = new AddrExp(e.loc, e);
4719 e = e.expressionSemantic(sc);
4720 return e.castTo(sc, mt.basetype.nextOf().pointerTo());
4721 }
4722 if (ident == Id.array)
4723 {
4724 //e = e.castTo(sc, basetype);
4725 // Keep lvalue-ness
4726 e = new VectorArrayExp(e.loc, e);
4727 e = e.expressionSemantic(sc);
4728 return e;
4729 }
4730 if (ident == Id._init || ident == Id.offsetof || ident == Id.stringof || ident == Id.__xalignof)
4731 {
4732 // init should return a new VectorExp
4733 // https://issues.dlang.org/show_bug.cgi?id=12776
4734 // offsetof does not work on a cast expression, so use e directly
4735 // stringof should not add a cast to the output
4736 return visitType(mt);
4737 }
4738
4739 // Properties based on the vector element type and are values of the element type
4740 if (ident == Id.max || ident == Id.min || ident == Id.min_normal ||
4741 ident == Id.nan || ident == Id.infinity || ident == Id.epsilon)
4742 {
4743 auto vet = mt.basetype.isTypeSArray().next; // vector element type
4744 if (auto ev = getProperty(vet, sc, e.loc, ident, DotExpFlag.gag))
4745 return ev.castTo(sc, mt); // 'broadcast' ev to the vector elements
4746 }
4747
4748 return mt.basetype.dotExp(sc, e.castTo(sc, mt.basetype), ident, flag);
4749 }
4750
4751 Expression visitArray(TypeArray mt)
4752 {
4753 static if (LOGDOTEXP)
4754 {
4755 printf("TypeArray::dotExp(e = '%s', ident = '%s')\n", e.toChars(), ident.toChars());
4756 }
4757
4758 e = visitType(mt);
4759
4760 if (!(flag & 1) || e)
4761 e = e.expressionSemantic(sc);
4762 return e;
4763 }
4764
4765 Expression visitSArray(TypeSArray mt)
4766 {
4767 static if (LOGDOTEXP)
4768 {
4769 printf("TypeSArray::dotExp(e = '%s', ident = '%s')\n", e.toChars(), ident.toChars());
4770 }
4771 if (ident == Id.length)
4772 {
4773 Loc oldLoc = e.loc;
4774 e = mt.dim.copy();
4775 e.loc = oldLoc;
4776 }
4777 else if (ident == Id.ptr)
4778 {
4779 if (e.op == EXP.type)
4780 {
4781 error(e.loc, "`%s` is not an expression", e.toErrMsg());
4782 return ErrorExp.get();
4783 }
4784 else if (mt.dim.toUInteger() < 1 && checkUnsafeDotExp(sc, e, ident, flag))
4785 {
4786 // .ptr on static array is @safe unless size is 0
4787 // https://issues.dlang.org/show_bug.cgi?id=20853
4788 return ErrorExp.get();
4789 }
4790 e = e.castTo(sc, e.type.nextOf().pointerTo());
4791 }
4792 else if (ident == Id._tupleof)
4793 {
4794 if (e.isTypeExp())
4795 {
4796 error(e.loc, "`.tupleof` cannot be used on type `%s`", mt.toChars);
4797 return ErrorExp.get();
4798 }
4799 else
4800 {
4801 Expression e0;
4802 Expression ev = e;
4803 ev = extractSideEffect(sc, "__tup", e0, ev);
4804
4805 const length = cast(size_t)mt.dim.toUInteger();
4806 auto exps = new Expressions();
4807 exps.reserve(length);
4808 foreach (i; 0 .. length)
4809 exps.push(new IndexExp(e.loc, ev, new IntegerExp(e.loc, i, Type.tsize_t)));
4810 e = new TupleExp(e.loc, e0, exps);
4811 }
4812 }
4813 else
4814 {
4815 e = visitArray(mt);
4816 }
4817 if (!(flag & 1) || e)
4818 e = e.expressionSemantic(sc);
4819 return e;
4820 }
4821
4822 Expression visitDArray(TypeDArray mt)
4823 {
4824 static if (LOGDOTEXP)
4825 {
4826 printf("TypeDArray::dotExp(e = '%s', ident = '%s')\n", e.toChars(), ident.toChars());
4827 }
4828 if (e.op == EXP.type && (ident == Id.length || ident == Id.ptr))
4829 {
4830 error(e.loc, "`%s` is not an expression", e.toErrMsg());
4831 return ErrorExp.get();
4832 }
4833 if (ident == Id.length)
4834 {
4835 if (e.op == EXP.string_)
4836 {
4837 StringExp se = cast(StringExp)e;
4838 return new IntegerExp(se.loc, se.len, Type.tsize_t);
4839 }
4840 if (e.op == EXP.null_)
4841 {
4842 return new IntegerExp(e.loc, 0, Type.tsize_t);
4843 }
4844 if (checkNonAssignmentArrayOp(e))
4845 {
4846 return ErrorExp.get();
4847 }
4848 e = new ArrayLengthExp(e.loc, e);
4849 e.type = Type.tsize_t;
4850 return e;
4851 }
4852 else if (ident == Id.ptr)
4853 {
4854 if (checkUnsafeDotExp(sc, e, ident, flag))
4855 return ErrorExp.get();
4856 return e.castTo(sc, mt.next.pointerTo());
4857 }
4858 else
4859 {
4860 return visitArray(mt);
4861 }
4862 }
4863
4864 Expression visitAArray(TypeAArray mt)
4865 {
4866 static if (LOGDOTEXP)
4867 {
4868 printf("TypeAArray::dotExp(e = '%s', ident = '%s')\n", e.toChars(), ident.toChars());
4869 }
4870 if (ident == Id.length)
4871 {
4872 __gshared FuncDeclaration fd_aaLen = null;
4873 if (fd_aaLen is null)
4874 {
4875 auto fparams = new Parameters();
4876 fparams.push(new Parameter(Loc.initial, STC.const_ | STC.scope_, mt, null, null, null));
4877 fd_aaLen = FuncDeclaration.genCfunc(fparams, Type.tsize_t, Id.aaLen);
4878 TypeFunction tf = fd_aaLen.type.toTypeFunction();
4879 tf.purity = PURE.const_;
4880 tf.isNothrow = true;
4881 tf.isNogc = false;
4882 }
4883 Expression ev = new VarExp(e.loc, fd_aaLen, false);
4884 e = new CallExp(e.loc, ev, e);
4885 e.type = fd_aaLen.type.toTypeFunction().next;
4886 return e;
4887 }
4888 else
4889 {
4890 return visitType(mt);
4891 }
4892 }
4893
4894 Expression visitReference(TypeReference mt)
4895 {
4896 static if (LOGDOTEXP)
4897 {
4898 printf("TypeReference::dotExp(e = '%s', ident = '%s')\n", e.toChars(), ident.toChars());
4899 }
4900 // References just forward things along
4901 return mt.next.dotExp(sc, e, ident, flag);
4902 }
4903
4904 Expression visitDelegate(TypeDelegate mt)
4905 {
4906 static if (LOGDOTEXP)
4907 {
4908 printf("TypeDelegate::dotExp(e = '%s', ident = '%s')\n", e.toChars(), ident.toChars());
4909 }
4910 if (ident == Id.ptr)
4911 {
4912 e = new DelegatePtrExp(e.loc, e);
4913 e = e.expressionSemantic(sc);
4914 }
4915 else if (ident == Id.funcptr)
4916 {
4917 if (checkUnsafeDotExp(sc, e, ident, flag))
4918 {
4919 return ErrorExp.get();
4920 }
4921 e = new DelegateFuncptrExp(e.loc, e);
4922 e = e.expressionSemantic(sc);
4923 }
4924 else
4925 {
4926 return visitType(mt);
4927 }
4928 return e;
4929 }
4930
4931 /***************************************
4932 * `ident` was not found as a member of `mt`.
4933 * Attempt to use overloaded opDispatch() or `alias this`.
4934 * If that fails, forward to visitType().
4935 * Params:
4936 * mt = class or struct
4937 * sc = context
4938 * e = `this` for `ident`
4939 * ident = name of member
4940 * flag = flag & 1, don't report "not a property" error and just return NULL.
4941 * flag & DotExpFlag.noAliasThis, don't do 'alias this' resolution.
4942 * Returns:
4943 * resolved expression if found, otherwise null
4944 */
4945 Expression noMember(Type mt, Scope* sc, Expression e, Identifier ident, int flag)
4946 {
4947 //printf("Type.noMember(e: %s ident: %s flag: %d)\n", e.toChars(), ident.toChars(), flag);
4948
4949 bool gagError = flag & 1;
4950
4951 __gshared int nest; // https://issues.dlang.org/show_bug.cgi?id=17380
4952
4953 static Expression returnExp(Expression e)
4954 {
4955 --nest;
4956 return e;
4957 }
4958
4959 if (++nest > global.recursionLimit)
4960 {
4961 .error(e.loc, "cannot resolve identifier `%s`", ident.toChars());
4962 return returnExp(gagError ? null : ErrorExp.get());
4963 }
4964
4965
4966 assert(mt.ty == Tstruct || mt.ty == Tclass);
4967 auto sym = mt.toDsymbol(sc).isAggregateDeclaration();
4968 assert(sym);
4969 if (// https://issues.dlang.org/show_bug.cgi?id=22054
4970 // if a class or struct does not have a body
4971 // there is no point in searching for its members
4972 sym.members &&
4973 ident != Id.__sizeof &&
4974 ident != Id.__xalignof &&
4975 ident != Id._init &&
4976 ident != Id._mangleof &&
4977 ident != Id.stringof &&
4978 ident != Id.offsetof &&
4979 ident != Id.bitoffsetof &&
4980 ident != Id.bitwidth &&
4981 // https://issues.dlang.org/show_bug.cgi?id=15045
4982 // Don't forward special built-in member functions.
4983 ident != Id.ctor &&
4984 ident != Id.dtor &&
4985 ident != Id.__xdtor &&
4986 ident != Id.postblit &&
4987 ident != Id.__xpostblit)
4988 {
4989 /* Look for overloaded opDispatch to see if we should forward request
4990 * to it.
4991 */
4992 if (auto fd = search_function(sym, Id.opDispatch))
4993 {
4994 /* Rewrite e.ident as:
4995 * e.opDispatch!("ident")
4996 */
4997 TemplateDeclaration td = fd.isTemplateDeclaration();
4998 if (!td)
4999 {
5000 .error(fd.loc, "%s `%s` must be a template `opDispatch(string s)`, not a %s", fd.kind, fd.toPrettyChars, fd.kind());
5001 return returnExp(ErrorExp.get());
5002 }
5003 auto se = new StringExp(e.loc, ident.toString());
5004 auto tiargs = new Objects();
5005 tiargs.push(se);
5006 auto dti = new DotTemplateInstanceExp(e.loc, e, Id.opDispatch, tiargs);
5007 dti.ti.tempdecl = td;
5008 /* opDispatch, which doesn't need IFTI, may occur instantiate error.
5009 * e.g.
5010 * template opDispatch(name) if (isValid!name) { ... }
5011 */
5012 const errors = gagError ? global.startGagging() : 0;
5013 e = dti.dotTemplateSemanticProp(sc, DotExpFlag.none);
5014 if (gagError && global.endGagging(errors))
5015 e = null;
5016 return returnExp(e);
5017 }
5018
5019 /* See if we should forward to the alias this.
5020 */
5021 auto alias_e = flag & DotExpFlag.noAliasThis ? null
5022 : resolveAliasThis(sc, e, gagError);
5023 if (alias_e && alias_e != e)
5024 {
5025 /* Rewrite e.ident as:
5026 * e.aliasthis.ident
5027 */
5028 auto die = new DotIdExp(e.loc, alias_e, ident);
5029
5030 const errors = gagError ? 0 : global.startGagging();
5031 auto exp = die.dotIdSemanticProp(sc, gagError);
5032 if (!gagError)
5033 {
5034 global.endGagging(errors);
5035 if (exp && exp.op == EXP.error)
5036 exp = null;
5037 }
5038
5039 if (exp && gagError)
5040 // now that we know that the alias this leads somewhere useful,
5041 // go back and print deprecations/warnings that we skipped earlier due to the gag
5042 resolveAliasThis(sc, e, false);
5043
5044 return returnExp(exp);
5045 }
5046 }
5047 return returnExp(visitType(mt));
5048 }
5049
5050 Expression visitStruct(TypeStruct mt)
5051 {
5052 Dsymbol s;
5053 static if (LOGDOTEXP)
5054 {
5055 printf("TypeStruct::dotExp(e = '%s', ident = '%s')\n", e.toChars(), ident.toChars());
5056 }
5057 assert(e.op != EXP.dot);
5058
5059 // https://issues.dlang.org/show_bug.cgi?id=14010
5060 if (!sc.inCfile && ident == Id._mangleof)
5061 {
5062 return mt.getProperty(sc, e.loc, ident, flag & 1);
5063 }
5064
5065 /* If e.tupleof
5066 */
5067 if (ident == Id._tupleof)
5068 {
5069 /* Create a TupleExp out of the fields of the struct e:
5070 * (e.field0, e.field1, e.field2, ...)
5071 */
5072 e = e.expressionSemantic(sc); // do this before turning on noAccessCheck
5073
5074 if (!mt.sym.determineFields())
5075 {
5076 error(e.loc, "unable to determine fields of `%s` because of forward references", mt.toChars());
5077 }
5078
5079 Expression e0;
5080 Expression ev = e.op == EXP.type ? null : e;
5081 if (ev)
5082 ev = extractSideEffect(sc, "__tup", e0, ev);
5083
5084 auto exps = new Expressions();
5085 exps.reserve(mt.sym.fields.length);
5086 for (size_t i = 0; i < mt.sym.fields.length; i++)
5087 {
5088 VarDeclaration v = mt.sym.fields[i];
5089 Expression ex;
5090 if (ev)
5091 ex = new DotVarExp(e.loc, ev, v);
5092 else
5093 {
5094 ex = new VarExp(e.loc, v);
5095 ex.type = ex.type.addMod(e.type.mod);
5096 }
5097 exps.push(ex);
5098 }
5099
5100 e = new TupleExp(e.loc, e0, exps);
5101 Scope* sc2 = sc.push();
5102 sc2.noAccessCheck = true;
5103 e = e.expressionSemantic(sc2);
5104 sc2.pop();
5105 return e;
5106 }
5107
5108 immutable flags = sc.ignoresymbolvisibility ? SearchOpt.ignoreVisibility : 0;
5109 s = mt.sym.search(e.loc, ident, flags | SearchOpt.ignorePrivateImports);
5110 L1:
5111 if (!s)
5112 {
5113 return noMember(mt, sc, e, ident, flag);
5114 }
5115 if (!sc.ignoresymbolvisibility && !symbolIsVisible(sc, s))
5116 {
5117 return noMember(mt, sc, e, ident, flag);
5118 }
5119 // check before alias resolution; the alias itself might be deprecated!
5120 if (auto ad = s.isAliasDeclaration)
5121 {
5122 s.checkDeprecated(e.loc, sc);
5123
5124 // Fix for https://github.com/dlang/dmd/issues/20610
5125 if (ad.originalType)
5126 {
5127 if (auto tid = ad.originalType.isTypeIdentifier())
5128 {
5129 if (tid.idents.length)
5130 {
5131 static if (0)
5132 {
5133 printf("TypeStruct::dotExp(e = '%s', ident = '%s')\n", e.toChars(), ident.toChars());
5134 printf("AliasDeclaration: %s\n", ad.toChars());
5135 if (ad.aliassym)
5136 printf("aliassym: %s\n", ad.aliassym.toChars());
5137 printf("tid type: %s\n", toChars(tid));
5138 }
5139 /* Rewrite e.s as e.(tid.ident).(tid.idents)
5140 */
5141 Expression die = new DotIdExp(e.loc, e, tid.ident);
5142 foreach (id; tid.idents) // maybe use typeToExpressionHelper()
5143 die = new DotIdExp(e.loc, die, cast(Identifier)id);
5144 /* Ambiguous syntax, only way to disambiguate it to try it
5145 */
5146 die = dmd.expressionsem.trySemantic(die, sc);
5147 if (die && die.isDotVarExp()) // shrink wrap around DotVarExp()
5148 {
5149 return die;
5150 }
5151 }
5152 }
5153 }
5154 }
5155 s = s.toAlias();
5156
5157 if (auto em = s.isEnumMember())
5158 {
5159 return em.getVarExp(e.loc, sc);
5160 }
5161 if (auto v = s.isVarDeclaration())
5162 {
5163 v.checkDeprecated(e.loc, sc);
5164 v.checkDisabled(e.loc, sc);
5165 if (!v.type ||
5166 !v.type.deco && v.inuse)
5167 {
5168 if (v.inuse) // https://issues.dlang.org/show_bug.cgi?id=9494
5169 error(e.loc, "circular reference to %s `%s`", v.kind(), v.toPrettyChars());
5170 else
5171 error(e.loc, "forward reference to %s `%s`", v.kind(), v.toPrettyChars());
5172 return ErrorExp.get();
5173 }
5174 if (v.type.ty == Terror)
5175 {
5176 return ErrorExp.get();
5177 }
5178
5179 if ((v.storage_class & STC.manifest) && v._init)
5180 {
5181 if (v.inuse)
5182 {
5183 error(e.loc, "circular initialization of %s `%s`", v.kind(), v.toPrettyChars());
5184 return ErrorExp.get();
5185 }
5186 checkAccess(e.loc, sc, null, v);
5187 Expression ve = new VarExp(e.loc, v);
5188 if (!isTrivialExp(e))
5189 {
5190 ve = new CommaExp(e.loc, e, ve);
5191 }
5192 return ve.expressionSemantic(sc);
5193 }
5194 }
5195
5196 if (auto t = s.getType())
5197 {
5198 return (new TypeExp(e.loc, t)).expressionSemantic(sc);
5199 }
5200
5201 TemplateMixin tm = s.isTemplateMixin();
5202 if (tm)
5203 {
5204 return new DotExp(e.loc, e, new ScopeExp(e.loc, tm)).expressionSemantic(sc);
5205 }
5206
5207 TemplateDeclaration td = s.isTemplateDeclaration();
5208 if (td)
5209 {
5210 if (e.op == EXP.type)
5211 e = new TemplateExp(e.loc, td);
5212 else
5213 e = new DotTemplateExp(e.loc, e, td);
5214 return e.expressionSemantic(sc);
5215 }
5216
5217 TemplateInstance ti = s.isTemplateInstance();
5218 if (ti)
5219 {
5220 if (!ti.semanticRun)
5221 {
5222 ti.dsymbolSemantic(sc);
5223 if (!ti.inst || ti.errors) // if template failed to expand
5224 {
5225 return ErrorExp.get();
5226 }
5227 }
5228 s = ti.inst.toAlias();
5229 if (!s.isTemplateInstance())
5230 goto L1;
5231 if (e.op == EXP.type)
5232 e = new ScopeExp(e.loc, ti);
5233 else
5234 e = new DotExp(e.loc, e, new ScopeExp(e.loc, ti));
5235 return e.expressionSemantic(sc);
5236 }
5237
5238 if (s.isImport() || s.isModule() || s.isPackage())
5239 {
5240 return symbolToExp(s, e.loc, sc, false);
5241 }
5242
5243 OverloadSet o = s.isOverloadSet();
5244 if (o)
5245 {
5246 auto oe = new OverExp(e.loc, o);
5247 if (e.op == EXP.type)
5248 {
5249 return oe;
5250 }
5251 return new DotExp(e.loc, e, oe);
5252 }
5253
5254 Declaration d = s.isDeclaration();
5255 if (!d)
5256 {
5257 error(e.loc, "`%s.%s` is not a declaration", e.toErrMsg(), ident.toChars());
5258 return ErrorExp.get();
5259 }
5260
5261 if (e.op == EXP.type)
5262 {
5263 /* It's:
5264 * Struct.d
5265 */
5266 if (TupleDeclaration tup = d.isTupleDeclaration())
5267 {
5268 e = new TupleExp(e.loc, tup);
5269 return e.expressionSemantic(sc);
5270 }
5271 if (d.needThis() && sc.intypeof != 1)
5272 {
5273 /* Rewrite as:
5274 * this.d
5275 *
5276 * only if the scope in which we are
5277 * has a `this` that matches the type
5278 * of the lhs of the dot expression.
5279 *
5280 * https://issues.dlang.org/show_bug.cgi?id=23617
5281 */
5282 auto fd = hasThis(sc);
5283 if (fd && fd.isThis() == mt.sym)
5284 {
5285 e = new DotVarExp(e.loc, new ThisExp(e.loc), d);
5286 return e.expressionSemantic(sc);
5287 }
5288 }
5289 if (d.semanticRun == PASS.initial)
5290 d.dsymbolSemantic(null);
5291 checkAccess(e.loc, sc, e, d);
5292 auto ve = new VarExp(e.loc, d);
5293 if (d.isVarDeclaration() && d.needThis())
5294 ve.type = d.type.addMod(e.type.mod);
5295 return ve;
5296 }
5297
5298 bool unreal = e.op == EXP.variable && (cast(VarExp)e).var.isField();
5299 if (d.isDataseg() || unreal && d.isField())
5300 {
5301 // (e, d)
5302 checkAccess(e.loc, sc, e, d);
5303 Expression ve = new VarExp(e.loc, d);
5304 e = unreal ? ve : new CommaExp(e.loc, e, ve);
5305 return e.expressionSemantic(sc);
5306 }
5307
5308 e = new DotVarExp(e.loc, e, d);
5309 return e.expressionSemantic(sc);
5310 }
5311
5312 Expression visitEnum(TypeEnum mt)
5313 {
5314 static if (LOGDOTEXP)
5315 {
5316 printf("TypeEnum::dotExp(e = '%s', ident = '%s') '%s'\n", e.toChars(), ident.toChars(), mt.toChars());
5317 }
5318 // https://issues.dlang.org/show_bug.cgi?id=14010
5319 if (ident == Id._mangleof)
5320 {
5321 return mt.getProperty(sc, e.loc, ident, flag & 1);
5322 }
5323
5324 if (mt.sym.semanticRun < PASS.semanticdone)
5325 mt.sym.dsymbolSemantic(null);
5326
5327 Dsymbol s = mt.sym.search(e.loc, ident);
5328 if (!s)
5329 {
5330 if (ident == Id._init)
5331 {
5332 return mt.getProperty(sc, e.loc, ident, flag & 1);
5333 }
5334
5335 /* Allow special enums to not need a member list
5336 */
5337 if ((ident == Id.max || ident == Id.min) && (mt.sym.members || !mt.sym.isSpecial()))
5338 {
5339 return mt.getProperty(sc, e.loc, ident, flag & 1);
5340 }
5341
5342 Expression res = mt.sym.getMemtype(Loc.initial).dotExp(sc, e, ident, DotExpFlag.gag);
5343 if (!(flag & 1) && !res)
5344 {
5345 if (auto ns = mt.sym.search_correct(ident))
5346 error(e.loc, "no property `%s` for type `%s`. Did you mean `%s.%s` ?", ident.toChars(), mt.toChars(), mt.toChars(),
5347 ns.toChars());
5348 else
5349 error(e.loc, "no property `%s` for type `%s`", ident.toChars(),
5350 mt.toChars());
5351
5352 errorSupplemental(mt.sym.loc, "%s `%s` defined here",
5353 mt.sym.kind, mt.toChars());
5354 return ErrorExp.get();
5355 }
5356 return res;
5357 }
5358 EnumMember m = s.isEnumMember();
5359 return m.getVarExp(e.loc, sc);
5360 }
5361
5362 Expression visitClass(TypeClass mt)
5363 {
5364 Dsymbol s;
5365 static if (LOGDOTEXP)
5366 {
5367 printf("TypeClass::dotExp(e = '%s', ident = '%s')\n", e.toChars(), ident.toChars());
5368 }
5369 assert(e.op != EXP.dot);
5370
5371 // https://issues.dlang.org/show_bug.cgi?id=12543
5372 if (ident == Id.__sizeof || ident == Id.__xalignof || ident == Id._mangleof)
5373 {
5374 return mt.Type.getProperty(sc, e.loc, ident, 0);
5375 }
5376
5377 /* If e.tupleof
5378 */
5379 if (ident == Id._tupleof)
5380 {
5381 objc.checkTupleof(e, mt);
5382
5383 /* Create a TupleExp
5384 */
5385 e = e.expressionSemantic(sc); // do this before turning on noAccessCheck
5386
5387 mt.sym.size(e.loc); // do semantic of type
5388
5389 Expression e0;
5390 Expression ev = e.op == EXP.type ? null : e;
5391 if (ev)
5392 ev = extractSideEffect(sc, "__tup", e0, ev);
5393
5394 auto exps = new Expressions();
5395 exps.reserve(mt.sym.fields.length);
5396 for (size_t i = 0; i < mt.sym.fields.length; i++)
5397 {
5398 VarDeclaration v = mt.sym.fields[i];
5399 // Don't include hidden 'this' pointer
5400 if (v.isThisDeclaration())
5401 continue;
5402 Expression ex;
5403 if (ev)
5404 ex = new DotVarExp(e.loc, ev, v);
5405 else
5406 {
5407 ex = new VarExp(e.loc, v);
5408 ex.type = ex.type.addMod(e.type.mod);
5409 }
5410 exps.push(ex);
5411 }
5412
5413 e = new TupleExp(e.loc, e0, exps);
5414 Scope* sc2 = sc.push();
5415 sc2.noAccessCheck = true;
5416 e = e.expressionSemantic(sc2);
5417 sc2.pop();
5418 return e;
5419 }
5420
5421 SearchOptFlags flags = sc.ignoresymbolvisibility ? SearchOpt.ignoreVisibility : SearchOpt.all;
5422 s = mt.sym.search(e.loc, ident, flags | SearchOpt.ignorePrivateImports);
5423
5424 L1:
5425 if (!s)
5426 {
5427 // See if it's a 'this' class or a base class
5428 if (mt.sym.ident == ident)
5429 {
5430 if (e.op == EXP.type)
5431 {
5432 return mt.Type.getProperty(sc, e.loc, ident, 0);
5433 }
5434 e = new DotTypeExp(e.loc, e, mt.sym);
5435 e = e.expressionSemantic(sc);
5436 return e;
5437 }
5438 if (auto cbase = mt.sym.searchBase(ident))
5439 {
5440 if (e.op == EXP.type)
5441 {
5442 return mt.Type.getProperty(sc, e.loc, ident, 0);
5443 }
5444 if (auto ifbase = cbase.isInterfaceDeclaration())
5445 e = new CastExp(e.loc, e, ifbase.type);
5446 else
5447 e = new DotTypeExp(e.loc, e, cbase);
5448 e = e.expressionSemantic(sc);
5449 return e;
5450 }
5451
5452 if (ident == Id.classinfo)
5453 {
5454 if (!Type.typeinfoclass)
5455 {
5456 error(e.loc, "`object.TypeInfo_Class` could not be found, but is implicitly used");
5457 return ErrorExp.get();
5458 }
5459
5460 Type t = Type.typeinfoclass.type;
5461 if (e.op == EXP.type || e.op == EXP.dotType)
5462 {
5463 /* For type.classinfo, we know the classinfo
5464 * at compile time.
5465 */
5466 if (!mt.sym.vclassinfo)
5467 mt.sym.vclassinfo = new TypeInfoClassDeclaration(mt.sym.type);
5468 e = new VarExp(e.loc, mt.sym.vclassinfo);
5469 e = e.addressOf();
5470 e.type = t; // do this so we don't get redundant dereference
5471 }
5472 else
5473 {
5474 /* For class objects, the classinfo reference is the first
5475 * entry in the vtbl[]
5476 */
5477 e = new PtrExp(e.loc, e);
5478 e.type = t.pointerTo();
5479 if (mt.sym.isInterfaceDeclaration())
5480 {
5481 if (mt.sym.isCPPinterface())
5482 {
5483 /* C++ interface vtbl[]s are different in that the
5484 * first entry is always pointer to the first virtual
5485 * function, not classinfo.
5486 * We can't get a .classinfo for it.
5487 */
5488 error(e.loc, "no `.classinfo` for C++ interface objects");
5489 }
5490 /* For an interface, the first entry in the vtbl[]
5491 * is actually a pointer to an instance of struct Interface.
5492 * The first member of Interface is the .classinfo,
5493 * so add an extra pointer indirection.
5494 */
5495 e.type = e.type.pointerTo();
5496 e = new PtrExp(e.loc, e);
5497 e.type = t.pointerTo();
5498 }
5499 e = new PtrExp(e.loc, e, t);
5500 }
5501 return e;
5502 }
5503
5504 if (ident == Id.__vptr)
5505 {
5506 /* The pointer to the vtbl[]
5507 * *cast(immutable(void*)**)e
5508 */
5509 e = e.castTo(sc, mt.tvoidptr.immutableOf().pointerTo().pointerTo());
5510 e = new PtrExp(e.loc, e);
5511 e = e.expressionSemantic(sc);
5512 return e;
5513 }
5514
5515 if (ident == Id.__monitor && mt.sym.hasMonitor())
5516 {
5517 /* The handle to the monitor (call it a void*)
5518 * *(cast(void**)e + 1)
5519 */
5520 e = e.castTo(sc, mt.tvoidptr.pointerTo());
5521 e = new AddExp(e.loc, e, IntegerExp.literal!1);
5522 e = new PtrExp(e.loc, e);
5523 e = e.expressionSemantic(sc);
5524 return e;
5525 }
5526
5527 if (ident == Id.outer && mt.sym.vthis)
5528 {
5529 if (mt.sym.vthis.semanticRun == PASS.initial)
5530 mt.sym.vthis.dsymbolSemantic(null);
5531
5532 if (auto cdp = mt.sym.toParentLocal().isClassDeclaration())
5533 {
5534 auto dve = new DotVarExp(e.loc, e, mt.sym.vthis);
5535 dve.type = cdp.type.addMod(e.type.mod);
5536 return dve;
5537 }
5538
5539 /* https://issues.dlang.org/show_bug.cgi?id=15839
5540 * Find closest parent class through nested functions.
5541 */
5542 for (auto p = mt.sym.toParentLocal(); p; p = p.toParentLocal())
5543 {
5544 auto fd = p.isFuncDeclaration();
5545 if (!fd)
5546 break;
5547 auto ad = fd.isThis();
5548 if (!ad && fd.isNested())
5549 continue;
5550 if (!ad)
5551 break;
5552 if (auto cdp = ad.isClassDeclaration())
5553 {
5554 auto ve = new ThisExp(e.loc);
5555
5556 ve.var = fd.vthis;
5557 const nestedError = fd.vthis.checkNestedReference(sc, e.loc);
5558 assert(!nestedError);
5559
5560 ve.type = cdp.type.addMod(fd.vthis.type.mod).addMod(e.type.mod);
5561 return ve;
5562 }
5563 break;
5564 }
5565
5566 // Continue to show enclosing function's frame (stack or closure).
5567 auto dve = new DotVarExp(e.loc, e, mt.sym.vthis);
5568 dve.type = mt.sym.vthis.type.addMod(e.type.mod);
5569 return dve;
5570 }
5571
5572 return noMember(mt, sc, e, ident, flag & 1);
5573 }
5574 if (!sc.ignoresymbolvisibility && !symbolIsVisible(sc, s))
5575 {
5576 return noMember(mt, sc, e, ident, flag);
5577 }
5578 if (!s.isFuncDeclaration()) // because of overloading
5579 {
5580 s.checkDeprecated(e.loc, sc);
5581 if (auto d = s.isDeclaration())
5582 d.checkDisabled(e.loc, sc);
5583 }
5584 s = s.toAlias();
5585
5586 if (auto em = s.isEnumMember())
5587 {
5588 return em.getVarExp(e.loc, sc);
5589 }
5590 if (auto v = s.isVarDeclaration())
5591 {
5592 if (!v.type ||
5593 !v.type.deco && v.inuse)
5594 {
5595 if (v.inuse) // https://issues.dlang.org/show_bug.cgi?id=9494
5596 error(e.loc, "circular reference to %s `%s`", v.kind(), v.toPrettyChars());
5597 else
5598 error(e.loc, "forward reference to %s `%s`", v.kind(), v.toPrettyChars());
5599 return ErrorExp.get();
5600 }
5601 if (v.type.ty == Terror)
5602 {
5603 error(e.loc, "type of variable `%s` has errors", v.toPrettyChars);
5604 return ErrorExp.get();
5605 }
5606
5607 if ((v.storage_class & STC.manifest) && v._init)
5608 {
5609 if (v.inuse)
5610 {
5611 error(e.loc, "circular initialization of %s `%s`", v.kind(), v.toPrettyChars());
5612 return ErrorExp.get();
5613 }
5614 checkAccess(e.loc, sc, null, v);
5615 Expression ve = new VarExp(e.loc, v);
5616 ve = ve.expressionSemantic(sc);
5617 return ve;
5618 }
5619 }
5620
5621 if (auto t = s.getType())
5622 {
5623 return (new TypeExp(e.loc, t)).expressionSemantic(sc);
5624 }
5625
5626 TemplateMixin tm = s.isTemplateMixin();
5627 if (tm)
5628 {
5629 return new DotExp(e.loc, e, new ScopeExp(e.loc, tm)).expressionSemantic(sc);
5630 }
5631
5632 TemplateDeclaration td = s.isTemplateDeclaration();
5633
5634 Expression toTemplateExp(TemplateDeclaration td)
5635 {
5636 if (e.op == EXP.type)
5637 e = new TemplateExp(e.loc, td);
5638 else
5639 e = new DotTemplateExp(e.loc, e, td);
5640 e = e.expressionSemantic(sc);
5641 return e;
5642 }
5643
5644 if (td)
5645 {
5646 return toTemplateExp(td);
5647 }
5648
5649 TemplateInstance ti = s.isTemplateInstance();
5650 if (ti)
5651 {
5652 if (!ti.semanticRun)
5653 {
5654 ti.dsymbolSemantic(sc);
5655 if (!ti.inst || ti.errors) // if template failed to expand
5656 {
5657 return ErrorExp.get();
5658 }
5659 }
5660 s = ti.inst.toAlias();
5661 if (!s.isTemplateInstance())
5662 goto L1;
5663 if (e.op == EXP.type)
5664 e = new ScopeExp(e.loc, ti);
5665 else
5666 e = new DotExp(e.loc, e, new ScopeExp(e.loc, ti));
5667 return e.expressionSemantic(sc);
5668 }
5669
5670 if (s.isImport() || s.isModule() || s.isPackage())
5671 {
5672 e = symbolToExp(s, e.loc, sc, false);
5673 return e;
5674 }
5675
5676 OverloadSet o = s.isOverloadSet();
5677 if (o)
5678 {
5679 auto oe = new OverExp(e.loc, o);
5680 if (e.op == EXP.type)
5681 {
5682 return oe;
5683 }
5684 return new DotExp(e.loc, e, oe);
5685 }
5686
5687 Declaration d = s.isDeclaration();
5688 if (!d)
5689 {
5690 error(e.loc, "`%s.%s` is not a declaration", e.toErrMsg(), ident.toChars());
5691 return ErrorExp.get();
5692 }
5693
5694 if (e.op == EXP.type)
5695 {
5696 /* It's:
5697 * Class.d
5698 */
5699 if (TupleDeclaration tup = d.isTupleDeclaration())
5700 {
5701 e = new TupleExp(e.loc, tup);
5702 e = e.expressionSemantic(sc);
5703 return e;
5704 }
5705
5706 if (mt.sym.classKind == ClassKind.objc
5707 && d.isFuncDeclaration()
5708 && d.isFuncDeclaration().isStatic
5709 && d.isFuncDeclaration().objc.selector)
5710 {
5711 auto classRef = new ObjcClassReferenceExp(e.loc, mt.sym);
5712 classRef.type = objc.getRuntimeMetaclass(mt.sym).getType();
5713 return new DotVarExp(e.loc, classRef, d).expressionSemantic(sc);
5714 }
5715 else if (d.needThis() && sc.intypeof != 1)
5716 {
5717 /* Rewrite as:
5718 * this.d
5719 */
5720 AggregateDeclaration ad = d.isMemberLocal();
5721 if (auto f = hasThis(sc))
5722 {
5723 // This is almost same as getRightThis() in expressionsem.d
5724 Expression e1;
5725 Type t;
5726 /* returns: true to continue, false to return */
5727 if (f.hasDualContext())
5728 {
5729 if (f.followInstantiationContext(ad))
5730 {
5731 e1 = new VarExp(e.loc, f.vthis);
5732 e1 = new PtrExp(e1.loc, e1);
5733 e1 = new IndexExp(e1.loc, e1, IntegerExp.literal!1);
5734 auto pd = f.toParent2().isDeclaration();
5735 assert(pd);
5736 t = pd.type.toBasetype();
5737 e1 = getThisSkipNestedFuncs(e1.loc, sc, f.toParent2(), ad, e1, t, d, true);
5738 if (!e1)
5739 {
5740 e = new VarExp(e.loc, d);
5741 return e;
5742 }
5743 goto L2;
5744 }
5745 }
5746 e1 = new ThisExp(e.loc);
5747 e1 = e1.expressionSemantic(sc);
5748 L2:
5749 t = e1.type.toBasetype();
5750 ClassDeclaration cd = e.type.isClassHandle();
5751 ClassDeclaration tcd = t.isClassHandle();
5752 if (cd && tcd && (tcd == cd || cd.isBaseOf(tcd, null)))
5753 {
5754 e = new DotTypeExp(e1.loc, e1, cd);
5755 e = new DotVarExp(e.loc, e, d);
5756 e = e.expressionSemantic(sc);
5757 return e;
5758 }
5759 if (tcd && tcd.isNested())
5760 {
5761 /* e1 is the 'this' pointer for an inner class: tcd.
5762 * Rewrite it as the 'this' pointer for the outer class.
5763 */
5764 auto vthis = tcd.followInstantiationContext(ad) ? tcd.vthis2 : tcd.vthis;
5765 e1 = new DotVarExp(e.loc, e1, vthis);
5766 e1.type = vthis.type;
5767 e1.type = e1.type.addMod(t.mod);
5768 // Do not call ensureStaticLinkTo()
5769 //e1 = e1.expressionSemantic(sc);
5770
5771 // Skip up over nested functions, and get the enclosing
5772 // class type.
5773 e1 = getThisSkipNestedFuncs(e1.loc, sc, tcd.toParentP(ad), ad, e1, t, d, true);
5774 if (!e1)
5775 {
5776 e = new VarExp(e.loc, d);
5777 return e;
5778 }
5779 goto L2;
5780 }
5781 }
5782 }
5783 //printf("e = %s, d = %s\n", e.toChars(), d.toChars());
5784 if (d.semanticRun == PASS.initial)
5785 d.dsymbolSemantic(null);
5786
5787 // If static function, get the most visible overload.
5788 // Later on the call is checked for correctness.
5789 // https://issues.dlang.org/show_bug.cgi?id=12511
5790 Dsymbol d2 = d;
5791 if (auto fd = d.isFuncDeclaration())
5792 {
5793 import dmd.access : mostVisibleOverload;
5794 d2 = mostVisibleOverload(fd, sc._module);
5795 }
5796
5797 checkAccess(e.loc, sc, e, d2);
5798 if (d2.isDeclaration())
5799 {
5800 d = cast(Declaration)d2;
5801 auto ve = new VarExp(e.loc, d);
5802 if (d.isVarDeclaration() && d.needThis())
5803 ve.type = d.type.addMod(e.type.mod);
5804 return ve;
5805 }
5806 else if (d2.isTemplateDeclaration())
5807 {
5808 return toTemplateExp(cast(TemplateDeclaration)d2);
5809 }
5810 else
5811 assert(0);
5812 }
5813
5814 bool unreal = e.op == EXP.variable && (cast(VarExp)e).var.isField();
5815 if (d.isDataseg() || unreal && d.isField())
5816 {
5817 // (e, d)
5818 checkAccess(e.loc, sc, e, d);
5819 Expression ve = new VarExp(e.loc, d);
5820 e = unreal ? ve : new CommaExp(e.loc, e, ve);
5821 e = e.expressionSemantic(sc);
5822 return e;
5823 }
5824
5825 e = new DotVarExp(e.loc, e, d);
5826 e = e.expressionSemantic(sc);
5827 return e;
5828 }
5829
5830 switch (mt.ty)
5831 {
5832 case Tvector: return visitVector (mt.isTypeVector());
5833 case Tsarray: return visitSArray (mt.isTypeSArray());
5834 case Tstruct: return visitStruct (mt.isTypeStruct());
5835 case Tenum: return visitEnum (mt.isTypeEnum());
5836 case Terror: return visitError (mt.isTypeError());
5837 case Tarray: return visitDArray (mt.isTypeDArray());
5838 case Taarray: return visitAArray (mt.isTypeAArray());
5839 case Treference: return visitReference(mt.isTypeReference());
5840 case Tdelegate: return visitDelegate (mt.isTypeDelegate());
5841 case Tclass: return visitClass (mt.isTypeClass());
5842
5843 default: return mt.isTypeBasic()
5844 ? visitBasic(cast(TypeBasic)mt)
5845 : visitType(mt);
5846 }
5847 }
5848
5849 // if initializer is 0
5850 bool isZeroInit(Type t, Loc loc)
5851 {
5852 bool visitType(Type _)
5853 {
5854 return false; // assume not
5855 }
5856
5857 bool visitBasic(TypeBasic t)
5858 {
5859 switch (t.ty)
5860 {
5861 case Tchar:
5862 case Twchar:
5863 case Tdchar:
5864 case Timaginary32:
5865 case Timaginary64:
5866 case Timaginary80:
5867 case Tfloat32:
5868 case Tfloat64:
5869 case Tfloat80:
5870 case Tcomplex32:
5871 case Tcomplex64:
5872 case Tcomplex80:
5873 return false; // no
5874 default:
5875 return true; // yes
5876 }
5877 }
5878
5879 bool visitVector(TypeVector t)
5880 {
5881 return t.basetype.isZeroInit(loc);
5882 }
5883
5884 bool visitSArray(TypeSArray t)
5885 {
5886 return t.next.isZeroInit(loc);
5887 }
5888
5889 bool visitStruct(TypeStruct t)
5890 {
5891 // Determine zeroInit here, as this can be called before semantic2
5892 t.sym.determineSize(t.sym.loc);
5893 return t.sym.zeroInit;
5894 }
5895
5896 bool visitEnum(TypeEnum t)
5897 {
5898 return t.sym.getDefaultValue(loc).toBool().hasValue(false);
5899 }
5900
5901 switch(t.ty)
5902 {
5903 default: return t.isTypeBasic() ? visitBasic(cast(TypeBasic)t) : visitType(t);
5904 case Tvector: return visitVector(t.isTypeVector());
5905 case Tsarray: return visitSArray(t.isTypeSArray());
5906 case Taarray:
5907 case Tarray:
5908 case Treference:
5909 case Tdelegate:
5910 case Tclass:
5911 case Tpointer: return true;
5912 case Tstruct: return visitStruct(t.isTypeStruct());
5913 case Tenum: return visitEnum(t.isTypeEnum());
5914 }
5915 }
5916
5917
5918 /************************
5919 * Get the default initialization expression for a type.
5920 * Params:
5921 * mt = the type for which the init expression is returned
5922 * loc = the location where the expression needs to be evaluated
5923 * isCfile = default initializers are different with C
5924 *
5925 * Returns:
5926 * The initialization expression for the type.
5927 */
5928 Expression defaultInit(Type mt, Loc loc, const bool isCfile = false)
5929 {
5930 Expression visitBasic(TypeBasic mt)
5931 {
5932 static if (LOGDEFAULTINIT)
5933 {
5934 printf("TypeBasic::defaultInit() '%s' isCfile: %d\n", mt.toChars(), isCfile);
5935 }
5936 dinteger_t value = 0;
5937
5938 switch (mt.ty)
5939 {
5940 case Tchar:
5941 value = isCfile ? 0 : 0xFF;
5942 break;
5943
5944 case Twchar:
5945 case Tdchar:
5946 value = isCfile ? 0 : 0xFFFF;
5947 break;
5948
5949 case Timaginary32:
5950 case Timaginary64:
5951 case Timaginary80:
5952 case Tfloat32:
5953 case Tfloat64:
5954 case Tfloat80:
5955 return new RealExp(loc, isCfile ? CTFloat.zero : target.RealProperties.nan, mt);
5956
5957 case Tcomplex32:
5958 case Tcomplex64:
5959 case Tcomplex80:
5960 {
5961 // Can't use fvalue + I*fvalue (the im part becomes a quiet NaN).
5962 const cvalue = isCfile ? complex_t(CTFloat.zero, CTFloat.zero)
5963 : complex_t(target.RealProperties.nan, target.RealProperties.nan);
5964 return new ComplexExp(loc, cvalue, mt);
5965 }
5966
5967 case Tvoid:
5968 error(loc, "`void` does not have a default initializer");
5969 return ErrorExp.get();
5970
5971 default:
5972 break;
5973 }
5974 return new IntegerExp(loc, value, mt);
5975 }
5976
5977 Expression visitVector(TypeVector mt)
5978 {
5979 //printf("TypeVector::defaultInit()\n");
5980 assert(mt.basetype.ty == Tsarray);
5981 Expression e = mt.basetype.defaultInit(loc, isCfile);
5982 auto ve = new VectorExp(loc, e, mt);
5983 ve.type = mt;
5984 ve.dim = cast(int)(mt.basetype.size(loc) / mt.elementType().size(loc));
5985 return ve;
5986 }
5987
5988 Expression visitSArray(TypeSArray mt)
5989 {
5990 static if (LOGDEFAULTINIT)
5991 {
5992 printf("TypeSArray::defaultInit() '%s' isCfile %d\n", mt.toChars(), isCfile);
5993 }
5994 if (mt.next.ty == Tvoid)
5995 return mt.tuns8.defaultInit(loc, isCfile);
5996 else
5997 return mt.next.defaultInit(loc, isCfile);
5998 }
5999
6000 Expression visitFunction(TypeFunction mt)
6001 {
6002 error(loc, "`function` does not have a default initializer");
6003 return ErrorExp.get();
6004 }
6005
6006 Expression visitStruct(TypeStruct mt)
6007 {
6008 static if (LOGDEFAULTINIT)
6009 {
6010 printf("TypeStruct::defaultInit() '%s'\n", mt.toChars());
6011 }
6012 Declaration d = new SymbolDeclaration(mt.sym.loc, mt.sym);
6013 assert(d);
6014 d.type = mt;
6015 d.storage_class |= STC.rvalue; // https://issues.dlang.org/show_bug.cgi?id=14398
6016 return new VarExp(mt.sym.loc, d);
6017 }
6018
6019 Expression visitEnum(TypeEnum mt)
6020 {
6021 static if (LOGDEFAULTINIT)
6022 {
6023 printf("TypeEnum::defaultInit() '%s'\n", mt.toChars());
6024 }
6025 // Initialize to first member of enum
6026 Expression e = mt.sym.getDefaultValue(loc);
6027 e = e.copy();
6028 e.loc = loc;
6029 e.type = mt; // to deal with const, immutable, etc., variants
6030 return e;
6031 }
6032
6033 Expression visitTuple(TypeTuple mt)
6034 {
6035 static if (LOGDEFAULTINIT)
6036 {
6037 printf("TypeTuple::defaultInit() '%s'\n", mt.toChars());
6038 }
6039 auto exps = new Expressions(mt.arguments.length);
6040 for (size_t i = 0; i < mt.arguments.length; i++)
6041 {
6042 Parameter p = (*mt.arguments)[i];
6043 assert(p.type);
6044 Expression e = p.type.defaultInitLiteral(loc);
6045 if (e.op == EXP.error)
6046 {
6047 return e;
6048 }
6049 (*exps)[i] = e;
6050 }
6051 return new TupleExp(loc, exps);
6052 }
6053
6054 Expression visitNoreturn(TypeNoreturn mt)
6055 {
6056 static if (LOGDEFAULTINIT)
6057 {
6058 printf("TypeNoreturn::defaultInit() '%s'\n", mt.toChars());
6059 }
6060 auto cond = IntegerExp.createBool(false);
6061 auto msg = new StringExp(loc, "Accessed expression of type `noreturn`");
6062 msg.type = Type.tstring;
6063 auto ae = new AssertExp(loc, cond, msg);
6064 ae.type = mt;
6065 return ae;
6066 }
6067
6068 switch (mt.ty)
6069 {
6070 case Tvector: return visitVector (mt.isTypeVector());
6071 case Tsarray: return visitSArray (mt.isTypeSArray());
6072 case Tfunction: return visitFunction(mt.isTypeFunction());
6073 case Tstruct: return visitStruct (mt.isTypeStruct());
6074 case Tenum: return visitEnum (mt.isTypeEnum());
6075 case Ttuple: return visitTuple (mt.isTypeTuple());
6076
6077 case Tnull: return new NullExp(Loc.initial, Type.tnull);
6078
6079 case Terror: return ErrorExp.get();
6080
6081 case Tarray:
6082 case Taarray:
6083 case Tpointer:
6084 case Treference:
6085 case Tdelegate:
6086 case Tclass: return new NullExp(loc, mt);
6087 case Tnoreturn: return visitNoreturn(mt.isTypeNoreturn());
6088
6089 default: return mt.isTypeBasic() ?
6090 visitBasic(cast(TypeBasic)mt) :
6091 null;
6092 }
6093 }
6094
6095 /*
6096 If `type` resolves to a dsymbol, then that
6097 dsymbol is returned.
6098
6099 Params:
6100 type = the type that is checked
6101 sc = the scope where the type is used
6102
6103 Returns:
6104 The dsymbol to which the type resolve or `null`
6105 if the type does resolve to any symbol (for example,
6106 in the case of basic types).
6107 */
6108 Dsymbol toDsymbol(Type type, Scope* sc)
6109 {
6110 Dsymbol visitType(Type _) { return null; }
6111 Dsymbol visitStruct(TypeStruct type) { return type.sym; }
6112 Dsymbol visitEnum(TypeEnum type) { return type.sym; }
6113 Dsymbol visitClass(TypeClass type) { return type.sym; }
6114
6115 Dsymbol visitTraits(TypeTraits type)
6116 {
6117 Type t;
6118 Expression e;
6119 Dsymbol s;
6120 resolve(type, type.loc, sc, e, t, s);
6121 if (t && t.ty != Terror)
6122 s = t.toDsymbol(sc);
6123 else if (e)
6124 s = getDsymbol(e);
6125
6126 return s;
6127 }
6128
6129 Dsymbol visitMixin(TypeMixin type)
6130 {
6131 Type t;
6132 Expression e;
6133 Dsymbol s;
6134 resolve(type, type.loc, sc, e, t, s);
6135 if (t)
6136 s = t.toDsymbol(sc);
6137 else if (e)
6138 s = getDsymbol(e);
6139
6140 return s;
6141 }
6142
6143 Dsymbol visitIdentifier(TypeIdentifier type)
6144 {
6145 //printf("TypeIdentifier::toDsymbol('%s')\n", toChars(type));
6146 if (!sc)
6147 return null;
6148
6149 Type t;
6150 Expression e;
6151 Dsymbol s;
6152 resolve(type, type.loc, sc, e, t, s);
6153 if (t && t.ty != Tident)
6154 s = t.toDsymbol(sc);
6155 if (e)
6156 s = getDsymbol(e);
6157 return s;
6158 }
6159
6160 Dsymbol visitInstance(TypeInstance type)
6161 {
6162 Type t;
6163 Expression e;
6164 Dsymbol s;
6165 //printf("TypeInstance::semantic(%s)\n", toChars());
6166 resolve(type, type.loc, sc, e, t, s);
6167 if (t && t.ty != Tinstance)
6168 s = t.toDsymbol(sc);
6169 return s;
6170 }
6171
6172 Dsymbol visitTypeof(TypeTypeof type)
6173 {
6174 //printf("TypeTypeof::toDsymbol('%s')\n", toChars());
6175 Expression e;
6176 Type t;
6177 Dsymbol s;
6178 resolve(type, type.loc, sc, e, t, s);
6179 return s;
6180 }
6181
6182 Dsymbol visitReturn(TypeReturn type)
6183 {
6184 Expression e;
6185 Type t;
6186 Dsymbol s;
6187 resolve(type, type.loc, sc, e, t, s);
6188 return s;
6189 }
6190
6191 switch(type.ty)
6192 {
6193 default: return visitType(type);
6194 case Ttraits: return visitTraits(type.isTypeTraits());
6195 case Tmixin: return visitMixin(type.isTypeMixin());
6196 case Tident: return visitIdentifier(type.isTypeIdentifier());
6197 case Tinstance: return visitInstance(type.isTypeInstance());
6198 case Ttypeof: return visitTypeof(type.isTypeTypeof());
6199 case Treturn: return visitReturn(type.isTypeReturn());
6200 case Tstruct: return visitStruct(type.isTypeStruct());
6201 case Tenum: return visitEnum(type.isTypeEnum());
6202 case Tclass: return visitClass(type.isTypeClass());
6203 }
6204 }
6205
6206 /************************************
6207 * Add storage class modifiers to type.
6208 */
6209 Type addStorageClass(Type type, STC stc)
6210 {
6211 Type visitType(Type t)
6212 {
6213 /* Just translate to MOD bits and let addMod() do the work
6214 */
6215 MOD mod = 0;
6216 if (stc & STC.immutable_)
6217 mod = MODFlags.immutable_;
6218 else
6219 {
6220 if (stc & (STC.const_ | STC.in_))
6221 mod |= MODFlags.const_;
6222 if (stc & STC.wild)
6223 mod |= MODFlags.wild;
6224 if (stc & STC.shared_)
6225 mod |= MODFlags.shared_;
6226 }
6227 return t.addMod(mod);
6228 }
6229
6230 Type visitFunction(TypeFunction tf_src)
6231 {
6232 //printf("addStorageClass(%llx) %d\n", stc, (stc & STC.scope_) != 0);
6233 TypeFunction t = visitType(tf_src).toTypeFunction();
6234 if ((stc & STC.pure_ && !t.purity) ||
6235 (stc & STC.nothrow_ && !t.isNothrow) ||
6236 (stc & STC.nogc && !t.isNogc) ||
6237 (stc & STC.scope_ && !t.isScopeQual) ||
6238 (stc & STC.safe && t.trust < TRUST.trusted))
6239 {
6240 // Klunky to change these
6241 auto tf = new TypeFunction(t.parameterList, t.next, t.linkage, STC.none);
6242 tf.mod = t.mod;
6243 tf.inferenceArguments = tf_src.inferenceArguments;
6244 tf.purity = t.purity;
6245 tf.isNothrow = t.isNothrow;
6246 tf.isNogc = t.isNogc;
6247 tf.isProperty = t.isProperty;
6248 tf.isRef = t.isRef;
6249 tf.isReturn = t.isReturn;
6250 tf.isReturnScope = t.isReturnScope;
6251 tf.isScopeQual = t.isScopeQual;
6252 tf.isReturnInferred = t.isReturnInferred;
6253 tf.isScopeInferred = t.isScopeInferred;
6254 tf.trust = t.trust;
6255 tf.isInOutParam = t.isInOutParam;
6256 tf.isInOutQual = t.isInOutQual;
6257 tf.isCtor = t.isCtor;
6258
6259 if (stc & STC.pure_)
6260 tf.purity = PURE.fwdref;
6261 if (stc & STC.nothrow_)
6262 tf.isNothrow = true;
6263 if (stc & STC.nogc)
6264 tf.isNogc = true;
6265 if (stc & STC.safe)
6266 tf.trust = TRUST.safe;
6267 if (stc & STC.scope_)
6268 {
6269 tf.isScopeQual = true;
6270 if (stc & STC.scopeinferred)
6271 tf.isScopeInferred = true;
6272 }
6273
6274 tf.deco = tf.merge().deco;
6275 t = tf;
6276 }
6277 return t;
6278 }
6279
6280 Type visitDelegate(TypeDelegate tdg)
6281 {
6282 TypeDelegate t = visitType(tdg).isTypeDelegate();
6283 return t;
6284 }
6285
6286 switch(type.ty)
6287 {
6288 default: return visitType(type);
6289 case Tfunction: return visitFunction(type.isTypeFunction());
6290 case Tdelegate: return visitDelegate(type.isTypeDelegate());
6291 }
6292 }
6293
6294 /**********************************************
6295 * Extract complex type from core.stdc.config
6296 * Params:
6297 * loc = for error messages
6298 * sc = context
6299 * ty = a complex or imaginary type
6300 * Returns:
6301 * Complex!float, Complex!double, Complex!real or null for error
6302 */
6303
6304 Type getComplexLibraryType(Loc loc, Scope* sc, TY ty)
6305 {
6306 // singleton
6307 __gshared Type complex_float;
6308 __gshared Type complex_double;
6309 __gshared Type complex_real;
6310
6311 Type* pt;
6312 Identifier id;
6313 switch (ty)
6314 {
6315 case Timaginary32:
6316 case Tcomplex32: id = Id.c_complex_float; pt = &complex_float; break;
6317 case Timaginary64:
6318 case Tcomplex64: id = Id.c_complex_double; pt = &complex_double; break;
6319 case Timaginary80:
6320 case Tcomplex80: id = Id.c_complex_real; pt = &complex_real; break;
6321 default:
6322 return Type.terror;
6323 }
6324
6325 if (*pt)
6326 return *pt;
6327 *pt = Type.terror;
6328
6329 Module mConfig = Module.loadCoreStdcConfig();
6330 if (!mConfig)
6331 {
6332 error(loc, "`core.stdc.config` is required for complex numbers");
6333 return *pt;
6334 }
6335
6336 Dsymbol s = mConfig.searchX(Loc.initial, sc, id, SearchOpt.ignorePrivateImports);
6337 if (!s)
6338 {
6339 error(loc, "`%s` not found in core.stdc.config", id.toChars());
6340 return *pt;
6341 }
6342 s = s.toAlias();
6343 if (auto t = s.getType())
6344 {
6345 if (auto ts = t.toBasetype().isTypeStruct())
6346 {
6347 *pt = ts;
6348 return ts;
6349 }
6350 }
6351 if (auto sd = s.isStructDeclaration())
6352 {
6353 *pt = sd.type;
6354 return sd.type;
6355 }
6356
6357 error(loc, "`%s` must be an alias for a complex struct", s.toChars());
6358 return *pt;
6359 }
6360
6361 /*******************************
6362 * Covariant means that 'src' can substitute for 't',
6363 * i.e. a pure function is a match for an impure type.
6364 * Params:
6365 * src = source type
6366 * t = type 'src' is covariant with
6367 * pstc = if not null, store STCxxxx which would make it covariant
6368 * cppCovariant = true if extern(C++) function types should follow C++ covariant rules
6369 * Returns:
6370 * An enum value of either `Covariant.yes` or a reason it's not covariant.
6371 */
6372 Covariant covariant(Type src, Type t, STC* pstc = null, bool cppCovariant = false)
6373 {
6374 version (none)
6375 {
6376 printf("Type::covariant(t = %s) %s\n", t.toChars(), src.toChars());
6377 printf("deco = %p, %p\n", src.deco, t.deco);
6378 // printf("ty = %d\n", next.ty);
6379 printf("mod = %x, %x\n", src.mod, t.mod);
6380 }
6381 if (pstc)
6382 *pstc = STC.none;
6383 STC stc = STC.none;
6384
6385 bool notcovariant = false;
6386
6387 if (src.equals(t))
6388 return Covariant.yes;
6389
6390 TypeFunction t1 = src.isTypeFunction();
6391 TypeFunction t2 = t.isTypeFunction();
6392
6393 if (!t1 || !t2)
6394 goto Ldistinct;
6395
6396 if (t1.parameterList.varargs != t2.parameterList.varargs)
6397 goto Ldistinct;
6398
6399 if (t1.parameterList.parameters && t2.parameterList.parameters)
6400 {
6401 if (t1.parameterList.length != t2.parameterList.length)
6402 goto Ldistinct;
6403
6404 foreach (i, fparam1; t1.parameterList)
6405 {
6406 Parameter fparam2 = t2.parameterList[i];
6407 Type tp1 = fparam1.type;
6408 Type tp2 = fparam2.type;
6409
6410 if (!tp1.equals(tp2))
6411 {
6412 if (tp1.ty == tp2.ty)
6413 {
6414 if (auto tc1 = tp1.isTypeClass())
6415 {
6416 if (tc1.sym == (cast(TypeClass)tp2).sym && MODimplicitConv(tp2.mod, tp1.mod))
6417 goto Lcov;
6418 }
6419 else if (auto ts1 = tp1.isTypeStruct())
6420 {
6421 if (ts1.sym == (cast(TypeStruct)tp2).sym && MODimplicitConv(tp2.mod, tp1.mod))
6422 goto Lcov;
6423 }
6424 else if (tp1.ty == Tpointer)
6425 {
6426 if (tp2.implicitConvTo(tp1))
6427 goto Lcov;
6428 }
6429 else if (tp1.ty == Tarray)
6430 {
6431 if (tp2.implicitConvTo(tp1))
6432 goto Lcov;
6433 }
6434 else if (tp1.ty == Tdelegate)
6435 {
6436 if (tp2.implicitConvTo(tp1))
6437 goto Lcov;
6438 }
6439 }
6440 goto Ldistinct;
6441 }
6442 Lcov:
6443 notcovariant |= !fparam1.isCovariant(t1.isRef, fparam2);
6444
6445 /* https://issues.dlang.org/show_bug.cgi?id=23135
6446 * extern(C++) mutable parameters are not covariant with const.
6447 */
6448 if (t1.linkage == LINK.cpp && cppCovariant)
6449 {
6450 notcovariant |= tp1.isNaked() != tp2.isNaked();
6451 if (auto tpn1 = tp1.nextOf())
6452 notcovariant |= tpn1.isNaked() != tp2.nextOf().isNaked();
6453 }
6454 }
6455 }
6456 else if (t1.parameterList.parameters != t2.parameterList.parameters)
6457 {
6458 if (t1.parameterList.length || t2.parameterList.length)
6459 goto Ldistinct;
6460 }
6461
6462 // The argument lists match
6463 if (notcovariant)
6464 goto Lnotcovariant;
6465 if (t1.linkage != t2.linkage)
6466 goto Lnotcovariant;
6467
6468 {
6469 // Return types
6470 Type t1n = t1.next;
6471 Type t2n = t2.next;
6472
6473 if (!t1n || !t2n) // happens with return type inference
6474 goto Lnotcovariant;
6475
6476 if (t1n.equals(t2n))
6477 goto Lcovariant;
6478 if (t1n.ty == Tclass && t2n.ty == Tclass)
6479 {
6480 /* If same class type, but t2n is const, then it's
6481 * covariant. Do this test first because it can work on
6482 * forward references.
6483 */
6484 if ((cast(TypeClass)t1n).sym == (cast(TypeClass)t2n).sym && MODimplicitConv(t1n.mod, t2n.mod))
6485 goto Lcovariant;
6486
6487 // If t1n is forward referenced:
6488 ClassDeclaration cd = (cast(TypeClass)t1n).sym;
6489 if (cd.semanticRun < PASS.semanticdone && !cd.isBaseInfoComplete())
6490 cd.dsymbolSemantic(null);
6491 if (!cd.isBaseInfoComplete())
6492 {
6493 return Covariant.fwdref;
6494 }
6495 }
6496 if (t1n.ty == Tstruct && t2n.ty == Tstruct)
6497 {
6498 if ((cast(TypeStruct)t1n).sym == (cast(TypeStruct)t2n).sym && MODimplicitConv(t1n.mod, t2n.mod))
6499 goto Lcovariant;
6500 }
6501 else if (t1n.ty == t2n.ty && t1n.implicitConvTo(t2n))
6502 {
6503 if (t1.isRef && t2.isRef)
6504 {
6505 // Treat like pointers to t1n and t2n
6506 if (t1n.constConv(t2n) < MATCH.constant)
6507 goto Lnotcovariant;
6508 }
6509 goto Lcovariant;
6510 }
6511 else if (t1n.ty == Tnull)
6512 {
6513 // NULL is covariant with any pointer type, but not with any
6514 // dynamic arrays, associative arrays or delegates.
6515 // https://issues.dlang.org/show_bug.cgi?id=8589
6516 // https://issues.dlang.org/show_bug.cgi?id=19618
6517 Type t2bn = t2n.toBasetype();
6518 if (t2bn.ty == Tnull || t2bn.ty == Tpointer || t2bn.ty == Tclass)
6519 goto Lcovariant;
6520 }
6521 // bottom type is covariant to any type
6522 else if (t1n.ty == Tnoreturn)
6523 goto Lcovariant;
6524 }
6525 goto Lnotcovariant;
6526
6527 Lcovariant:
6528 if (t1.isRef != t2.isRef)
6529 goto Lnotcovariant;
6530
6531 if (!t1.isRef && (t1.isScopeQual || t2.isScopeQual))
6532 {
6533 STC stc1 = t1.isScopeQual ? STC.scope_ : STC.none;
6534 STC stc2 = t2.isScopeQual ? STC.scope_ : STC.none;
6535 if (t1.isReturn)
6536 {
6537 stc1 |= STC.return_;
6538 if (!t1.isScopeQual)
6539 stc1 |= STC.ref_;
6540 }
6541 if (t2.isReturn)
6542 {
6543 stc2 |= STC.return_;
6544 if (!t2.isScopeQual)
6545 stc2 |= STC.ref_;
6546 }
6547 if (!Parameter.isCovariantScope(t1.isRef, stc1, stc2))
6548 goto Lnotcovariant;
6549 }
6550
6551 // We can subtract 'return ref' from 'this', but cannot add it
6552 else if (t1.isReturn && !t2.isReturn)
6553 goto Lnotcovariant;
6554
6555 /* https://issues.dlang.org/show_bug.cgi?id=23135
6556 * extern(C++) mutable member functions are not covariant with const.
6557 */
6558 if (t1.linkage == LINK.cpp && cppCovariant && t1.isNaked() != t2.isNaked())
6559 goto Lnotcovariant;
6560
6561 /* Can convert mutable to const
6562 */
6563 if (!MODimplicitConv(t2.mod, t1.mod))
6564 {
6565 version (none)
6566 {
6567 //stop attribute inference with const
6568 // If adding 'const' will make it covariant
6569 if (MODimplicitConv(t2.mod, MODmerge(t1.mod, MODFlags.const_)))
6570 stc |= STC.const_;
6571 else
6572 goto Lnotcovariant;
6573 }
6574 else
6575 {
6576 goto Ldistinct;
6577 }
6578 }
6579
6580 /* Can convert pure to impure, nothrow to throw, and nogc to gc
6581 */
6582 if (!t1.purity && t2.purity)
6583 stc |= STC.pure_;
6584
6585 if (!t1.isNothrow && t2.isNothrow)
6586 stc |= STC.nothrow_;
6587
6588 if (!t1.isNogc && t2.isNogc)
6589 stc |= STC.nogc;
6590
6591 /* Can convert safe/trusted to system
6592 */
6593 if (t1.trust <= TRUST.system && t2.trust >= TRUST.trusted)
6594 {
6595 // Should we infer trusted or safe? Go with safe.
6596 stc |= STC.safe;
6597 }
6598
6599 if (stc)
6600 {
6601 if (pstc)
6602 *pstc = stc;
6603 goto Lnotcovariant;
6604 }
6605
6606 //printf("\tcovaraint: 1\n");
6607 return Covariant.yes;
6608
6609 Ldistinct:
6610 //printf("\tcovaraint: 0\n");
6611 return Covariant.distinct;
6612
6613 Lnotcovariant:
6614 //printf("\tcovaraint: 2\n");
6615 return Covariant.no;
6616 }
6617
6618 /************************************
6619 * Take the specified storage class for p,
6620 * and use the function signature to infer whether
6621 * STC.scope_ and STC.return_ should be OR'd in.
6622 * (This will not affect the name mangling.)
6623 * Params:
6624 * tf = TypeFunction to use to get the signature from
6625 * tthis = type of `this` parameter, null if none
6626 * p = parameter to this function
6627 * outerVars = context variables p could escape into, if any
6628 * indirect = is this for an indirect or virtual function call?
6629 * Returns:
6630 * storage class with STC.scope_ or STC.return_ OR'd in
6631 */
6632 STC parameterStorageClass(TypeFunction tf, Type tthis, Parameter p, VarDeclarations* outerVars = null,
6633 bool indirect = false)
6634 {
6635 //printf("parameterStorageClass(p: %s)\n", p.toChars());
6636 auto stc = p.storageClass;
6637
6638 // When the preview switch is enable, `in` parameters are `scope`
6639 if (stc & STC.constscoperef)
6640 return stc | STC.scope_;
6641
6642 if (stc & (STC.scope_ | STC.return_ | STC.lazy_) || tf.purity == PURE.impure)
6643 return stc;
6644
6645 /* If haven't inferred the return type yet, can't infer storage classes
6646 */
6647 if (!tf.nextOf() || !tf.isNothrow())
6648 return stc;
6649
6650 tf.purityLevel();
6651
6652 static bool mayHavePointers(Type t)
6653 {
6654 if (auto ts = t.isTypeStruct())
6655 {
6656 auto sym = ts.sym;
6657 if (sym.members && !sym.determineFields() && sym.type != Type.terror)
6658 // struct is forward referenced, so "may have" pointers
6659 return true;
6660 }
6661 return t.hasPointers();
6662 }
6663
6664 // See if p can escape via any of the other parameters
6665 if (tf.purity == PURE.weak)
6666 {
6667 /*
6668 * Indirect calls may escape p through a nested context
6669 * See:
6670 * https://issues.dlang.org/show_bug.cgi?id=24212
6671 * https://issues.dlang.org/show_bug.cgi?id=24213
6672 */
6673 if (indirect)
6674 return stc;
6675
6676 // Check escaping through parameters
6677 foreach (i, fparam; tf.parameterList)
6678 {
6679 Type t = fparam.type;
6680 if (!t)
6681 continue;
6682 t = t.baseElemOf(); // punch thru static arrays
6683 if (t.isMutable() && t.hasPointers())
6684 {
6685 if (fparam.isReference() && fparam != p)
6686 return stc;
6687
6688 if (t.ty == Tdelegate)
6689 return stc; // could escape thru delegate
6690
6691 if (t.ty == Tclass)
6692 return stc;
6693
6694 /* if t is a pointer to mutable pointer
6695 */
6696 if (auto tn = t.nextOf())
6697 {
6698 if (tn.isMutable() && mayHavePointers(tn))
6699 return stc; // escape through pointers
6700 }
6701 }
6702 }
6703
6704 // Check escaping through `this`
6705 if (tthis && tthis.isMutable())
6706 {
6707 foreach (VarDeclaration v; isAggregate(tthis).fields)
6708 {
6709 if (v.hasPointers())
6710 return stc;
6711 }
6712 }
6713
6714 // Check escaping through nested context
6715 if (outerVars && tf.isMutable())
6716 {
6717 foreach (VarDeclaration v; *outerVars)
6718 {
6719 if (v.hasPointers())
6720 return stc;
6721 }
6722 }
6723 }
6724
6725 // Check escaping through return value
6726 Type tret = tf.nextOf().toBasetype();
6727 if (tf.isRef || tret.hasPointers())
6728 {
6729 return stc | STC.scope_ | STC.return_ | STC.returnScope;
6730 }
6731 else
6732 return stc | STC.scope_;
6733 }
6734
6735 bool isBaseOf(Type tthis, Type t, int* poffset)
6736 {
6737 auto tc = tthis.isTypeClass();
6738 if (!tc)
6739 return false;
6740
6741 if (!t || t.ty != Tclass)
6742 return false;
6743
6744 ClassDeclaration cd = t.isTypeClass().sym;
6745 if (cd.semanticRun < PASS.semanticdone && !cd.isBaseInfoComplete())
6746 cd.dsymbolSemantic(null);
6747 if (tc.sym.semanticRun < PASS.semanticdone && !tc.sym.isBaseInfoComplete())
6748 tc.sym.dsymbolSemantic(null);
6749
6750 if (tc.sym.isBaseOf(cd, poffset))
6751 return true;
6752
6753 return false;
6754 }
6755
6756 bool equivalent(Type src, Type t)
6757 {
6758 return immutableOf(src).equals(t.immutableOf());
6759 }
6760
6761 Type pointerTo(Type type)
6762 {
6763 if (type.ty == Terror)
6764 return type;
6765 auto mcache = type.getMcache();
6766 if (!mcache.pto)
6767 {
6768 Type t = new TypePointer(type);
6769 if (type.ty == Tfunction)
6770 {
6771 t.deco = t.merge().deco;
6772 mcache.pto = t;
6773 }
6774 else
6775 mcache.pto = t.merge();
6776 }
6777 return mcache.pto;
6778 }
6779
6780 Type referenceTo(Type type)
6781 {
6782 if (type.ty == Terror)
6783 return type;
6784 auto mcache = type.getMcache();
6785 if (!mcache.rto)
6786 {
6787 Type t = new TypeReference(type);
6788 mcache.rto = t.merge();
6789 }
6790 return mcache.rto;
6791 }
6792
6793 // Make corresponding static array type without semantic
6794 Type sarrayOf(Type type, dinteger_t dim)
6795 {
6796 assert(type.deco);
6797 Type t = new TypeSArray(type, new IntegerExp(Loc.initial, dim, Type.tsize_t));
6798 // according to TypeSArray.semantic()
6799 t = t.addMod(type.mod);
6800 t = t.merge();
6801 return t;
6802 }
6803
6804 Type arrayOf(Type type)
6805 {
6806 if (type.ty == Terror)
6807 return type;
6808 auto mcache = type.getMcache();
6809 if (!mcache.arrayof)
6810 {
6811 Type t = new TypeDArray(type);
6812 mcache.arrayof = t.merge();
6813 }
6814 return mcache.arrayof;
6815 }
6816
6817 /********************************
6818 * Convert to 'const'.
6819 */
6820 Type constOf(Type type)
6821 {
6822 //printf("Type::constOf() %p %s\n", type, type.toChars());
6823 if (type.mod == MODFlags.const_)
6824 return type;
6825 if (type.mcache && type.mcache.cto)
6826 {
6827 assert(type.mcache.cto.mod == MODFlags.const_);
6828 return type.mcache.cto;
6829 }
6830 Type t = type.makeConst();
6831 t = t.merge();
6832 t.fixTo(type);
6833 //printf("-Type::constOf() %p %s\n", t, t.toChars());
6834 return t;
6835 }
6836
6837 /********************************
6838 * Convert to 'immutable'.
6839 */
6840 Type immutableOf(Type type)
6841 {
6842 //printf("Type::immutableOf() %p %s\n", this, toChars());
6843 if (type.isImmutable())
6844 return type;
6845 if (type.mcache && type.mcache.ito)
6846 {
6847 assert(type.mcache.ito.isImmutable());
6848 return type.mcache.ito;
6849 }
6850 Type t = type.makeImmutable();
6851 t = t.merge();
6852 t.fixTo(type);
6853 //printf("\t%p\n", t);
6854 return t;
6855 }
6856
6857 /********************************
6858 * Make type mutable.
6859 */
6860 Type mutableOf(Type type)
6861 {
6862 //printf("Type::mutableOf() %p, %s\n", type, type.toChars());
6863 Type t = type;
6864 if (type.isImmutable())
6865 {
6866 type.getMcache();
6867 t = type.mcache.ito; // immutable => naked
6868 assert(!t || (t.isMutable() && !t.isShared()));
6869 }
6870 else if (type.isConst())
6871 {
6872 type.getMcache();
6873 if (type.isShared())
6874 {
6875 if (type.isWild())
6876 t = type.mcache.swcto; // shared wild const -> shared
6877 else
6878 t = type.mcache.sto; // shared const => shared
6879 }
6880 else
6881 {
6882 if (type.isWild())
6883 t = type.mcache.wcto; // wild const -> naked
6884 else
6885 t = type.mcache.cto; // const => naked
6886 }
6887 assert(!t || t.isMutable());
6888 }
6889 else if (type.isWild())
6890 {
6891 type.getMcache();
6892 if (type.isShared())
6893 t = type.mcache.sto; // shared wild => shared
6894 else
6895 t = type.mcache.wto; // wild => naked
6896 assert(!t || t.isMutable());
6897 }
6898 if (!t)
6899 {
6900 t = type.makeMutable();
6901 t = t.merge();
6902 t.fixTo(type);
6903 }
6904 else
6905 t = t.merge();
6906 assert(t.isMutable());
6907 return t;
6908 }
6909
6910 Type sharedOf(Type type)
6911 {
6912 //printf("Type::sharedOf() %p, %s\n", type, type.toChars());
6913 if (type.mod == MODFlags.shared_)
6914 return type;
6915 if (type.mcache && type.mcache.sto)
6916 {
6917 assert(type.mcache.sto.mod == MODFlags.shared_);
6918 return type.mcache.sto;
6919 }
6920 Type t = type.makeShared();
6921 t = t.merge();
6922 t.fixTo(type);
6923 //printf("\t%p\n", t);
6924 return t;
6925 }
6926
6927 Type sharedConstOf(Type type)
6928 {
6929 //printf("Type::sharedConstOf() %p, %s\n", type, type.toChars());
6930 if (type.mod == (MODFlags.shared_ | MODFlags.const_))
6931 return type;
6932 if (type.mcache && type.mcache.scto)
6933 {
6934 assert(type.mcache.scto.mod == (MODFlags.shared_ | MODFlags.const_));
6935 return type.mcache.scto;
6936 }
6937 Type t = type.makeSharedConst();
6938 t = t.merge();
6939 t.fixTo(type);
6940 //printf("\t%p\n", t);
6941 return t;
6942 }
6943
6944 /********************************
6945 * Make type unshared.
6946 * 0 => 0
6947 * const => const
6948 * immutable => immutable
6949 * shared => 0
6950 * shared const => const
6951 * wild => wild
6952 * wild const => wild const
6953 * shared wild => wild
6954 * shared wild const => wild const
6955 */
6956 Type unSharedOf(Type type)
6957 {
6958 //printf("Type::unSharedOf() %p, %s\n", type, type.toChars());
6959 Type t = type;
6960
6961 if (type.isShared())
6962 {
6963 type.getMcache();
6964 if (type.isWild())
6965 {
6966 if (type.isConst())
6967 t = type.mcache.wcto; // shared wild const => wild const
6968 else
6969 t = type.mcache.wto; // shared wild => wild
6970 }
6971 else
6972 {
6973 if (type.isConst())
6974 t = type.mcache.cto; // shared const => const
6975 else
6976 t = type.mcache.sto; // shared => naked
6977 }
6978 assert(!t || !t.isShared());
6979 }
6980
6981 if (!t)
6982 {
6983 t = type.nullAttributes();
6984 t.mod = type.mod & ~MODFlags.shared_;
6985 t.ctype = type.ctype;
6986 t = t.merge();
6987 t.fixTo(type);
6988 }
6989 else
6990 t = t.merge();
6991 assert(!t.isShared());
6992 return t;
6993 }
6994
6995 /********************************
6996 * Convert to 'wild'.
6997 */
6998 Type wildOf(Type type)
6999 {
7000 //printf("Type::wildOf() %p %s\n", type, type.toChars());
7001 if (type.mod == MODFlags.wild)
7002 return type;
7003 if (type.mcache && type.mcache.wto)
7004 {
7005 assert(type.mcache.wto.mod == MODFlags.wild);
7006 return type.mcache.wto;
7007 }
7008 Type t = type.makeWild();
7009 t = t.merge();
7010 t.fixTo(type);
7011 //printf("\t%p %s\n", t, t.toChars());
7012 return t;
7013 }
7014
7015 Type wildConstOf(Type type)
7016 {
7017 //printf("Type::wildConstOf() %p %s\n", type, type.toChars());
7018 if (type.mod == MODFlags.wildconst)
7019 return type;
7020 if (type.mcache && type.mcache.wcto)
7021 {
7022 assert(type.mcache.wcto.mod == MODFlags.wildconst);
7023 return type.mcache.wcto;
7024 }
7025 Type t = type.makeWildConst();
7026 t = t.merge();
7027 t.fixTo(type);
7028 //printf("\t%p %s\n", t, t.toChars());
7029 return t;
7030 }
7031
7032 Type sharedWildOf(Type type)
7033 {
7034 //printf("Type::sharedWildOf() %p, %s\n", type, type.toChars());
7035 if (type.mod == (MODFlags.shared_ | MODFlags.wild))
7036 return type;
7037 if (type.mcache && type.mcache.swto)
7038 {
7039 assert(type.mcache.swto.mod == (MODFlags.shared_ | MODFlags.wild));
7040 return type.mcache.swto;
7041 }
7042 Type t = type.makeSharedWild();
7043 t = t.merge();
7044 t.fixTo(type);
7045 //printf("\t%p %s\n", t, t.toChars());
7046 return t;
7047 }
7048
7049 Type sharedWildConstOf(Type type)
7050 {
7051 //printf("Type::sharedWildConstOf() %p, %s\n", type, type.toChars());
7052 if (type.mod == (MODFlags.shared_ | MODFlags.wildconst))
7053 return type;
7054 if (type.mcache && type.mcache.swcto)
7055 {
7056 assert(type.mcache.swcto.mod == (MODFlags.shared_ | MODFlags.wildconst));
7057 return type.mcache.swcto;
7058 }
7059 Type t = type.makeSharedWildConst();
7060 t = t.merge();
7061 t.fixTo(type);
7062 //printf("\t%p %s\n", t, t.toChars());
7063 return t;
7064 }
7065
7066 Type nakedOf(Type type)
7067 {
7068 //printf("Type::nakedOf() %p, %s\n", type, type.toChars());
7069 if (type.mod == 0)
7070 return type;
7071 if (type.mcache) with(type.mcache)
7072 {
7073 // the cache has the naked type at the "identity" position, try to find it
7074 if (cto && cto.mod == 0)
7075 return cto;
7076 if (ito && ito.mod == 0)
7077 return ito;
7078 if (sto && sto.mod == 0)
7079 return sto;
7080 if (scto && scto.mod == 0)
7081 return scto;
7082 if (wto && wto.mod == 0)
7083 return wto;
7084 if (wcto && wcto.mod == 0)
7085 return wcto;
7086 if (swto && swto.mod == 0)
7087 return swto;
7088 if (swcto && swcto.mod == 0)
7089 return swcto;
7090 }
7091 Type t = type.nullAttributes();
7092 t.mod = 0;
7093 t = t.merge();
7094 t.fixTo(type);
7095 //printf("\t%p %s\n", t, t.toChars());
7096 return t;
7097 }
7098
7099 Type unqualify(Type type, uint m)
7100 {
7101 Type t = type.mutableOf().unSharedOf();
7102
7103 Type tn = type.ty == Tenum ? null : type.nextOf();
7104 if (tn && tn.ty != Tfunction)
7105 {
7106 Type utn = tn.unqualify(m);
7107 if (utn != tn)
7108 {
7109 if (type.ty == Tpointer)
7110 t = utn.pointerTo();
7111 else if (type.ty == Tarray)
7112 t = utn.arrayOf();
7113 else if (type.ty == Tsarray)
7114 t = new TypeSArray(utn, (cast(TypeSArray)type).dim);
7115 else if (type.ty == Taarray)
7116 {
7117 t = new TypeAArray(utn, (cast(TypeAArray)type).index);
7118 }
7119 else
7120 assert(0);
7121
7122 t = t.merge();
7123 }
7124 }
7125 t = t.addMod(type.mod & ~m);
7126 return t;
7127 }
7128
7129 /**************************
7130 * Return type with the top level of it being mutable.
7131 *
7132 * Params:
7133 * t = type for which the top level mutable version is being returned
7134 *
7135 * Returns:
7136 * type version with mutable top level
7137 */
7138 Type toHeadMutable(const Type t)
7139 {
7140 Type unqualType = cast(Type) t;
7141 if (t.isTypeStruct() || t.isTypeClass())
7142 return unqualType;
7143
7144 if (!t.mod)
7145 return unqualType;
7146 return unqualType.mutableOf();
7147 }
7148
7149 Type aliasthisOf(Type type)
7150 {
7151 auto ad = isAggregate(type);
7152 if (!ad || !ad.aliasthis)
7153 return null;
7154
7155 auto s = ad.aliasthis.sym;
7156 if (s.isAliasDeclaration())
7157 s = s.toAlias();
7158
7159 if (s.isTupleDeclaration())
7160 return null;
7161
7162 if (auto vd = s.isVarDeclaration())
7163 {
7164 auto t = vd.type;
7165 if (vd.needThis())
7166 t = t.addMod(type.mod);
7167 return t;
7168 }
7169 Dsymbol callable = s.isFuncDeclaration();
7170 callable = callable ? callable : s.isTemplateDeclaration();
7171 if (callable)
7172 {
7173 auto fd = resolveFuncCall(Loc.initial, null, callable, null, type, ArgumentList(), FuncResolveFlag.quiet);
7174 if (!fd || fd.errors || !functionSemantic(fd))
7175 return Type.terror;
7176
7177 auto t = fd.type.nextOf();
7178 if (!t) // https://issues.dlang.org/show_bug.cgi?id=14185
7179 return Type.terror;
7180 t = t.substWildTo(type.mod == 0 ? MODFlags.mutable : type.mod);
7181 return t;
7182 }
7183 if (auto d = s.isDeclaration())
7184 {
7185 assert(d.type);
7186 return d.type;
7187 }
7188 if (auto ed = s.isEnumDeclaration())
7189 {
7190 return ed.type;
7191 }
7192
7193 //printf("%s\n", s.kind());
7194 return null;
7195 }
7196
7197 /************************************
7198 * Apply MODxxxx bits to existing type.
7199 */
7200 Type castMod(Type type, MOD mod)
7201 {
7202 Type t;
7203 switch (mod)
7204 {
7205 case 0:
7206 t = type.unSharedOf().mutableOf();
7207 break;
7208
7209 case MODFlags.const_:
7210 t = type.unSharedOf().constOf();
7211 break;
7212
7213 case MODFlags.wild:
7214 t = type.unSharedOf().wildOf();
7215 break;
7216
7217 case MODFlags.wildconst:
7218 t = type.unSharedOf().wildConstOf();
7219 break;
7220
7221 case MODFlags.shared_:
7222 t = type.mutableOf().sharedOf();
7223 break;
7224
7225 case MODFlags.shared_ | MODFlags.const_:
7226 t = type.sharedConstOf();
7227 break;
7228
7229 case MODFlags.shared_ | MODFlags.wild:
7230 t = type.sharedWildOf();
7231 break;
7232
7233 case MODFlags.shared_ | MODFlags.wildconst:
7234 t = type.sharedWildConstOf();
7235 break;
7236
7237 case MODFlags.immutable_:
7238 t = type.immutableOf();
7239 break;
7240
7241 default:
7242 assert(0);
7243 }
7244 return t;
7245 }
7246
7247 Type substWildTo(Type type, uint mod)
7248 {
7249 auto tf = type.isTypeFunction();
7250 if (!tf)
7251 {
7252 //printf("+Type.substWildTo this = %s, mod = x%x\n", toChars(), mod);
7253 Type t;
7254
7255 if (Type tn = type.nextOf())
7256 {
7257 // substitution has no effect on function pointer type.
7258 if (type.ty == Tpointer && tn.ty == Tfunction)
7259 {
7260 t = type;
7261 goto L1;
7262 }
7263
7264 t = tn.substWildTo(mod);
7265 if (t == tn)
7266 t = type;
7267 else
7268 {
7269 if (type.ty == Tpointer)
7270 t = t.pointerTo();
7271 else if (type.ty == Tarray)
7272 t = t.arrayOf();
7273 else if (type.ty == Tsarray)
7274 t = new TypeSArray(t, (cast(TypeSArray)type).dim.syntaxCopy());
7275 else if (type.ty == Taarray)
7276 {
7277 t = new TypeAArray(t, (cast(TypeAArray)type).index.substWildTo(mod));
7278 }
7279 else if (type.ty == Tdelegate)
7280 {
7281 t = new TypeDelegate(t.isTypeFunction());
7282 }
7283 else
7284 assert(0);
7285
7286 t = t.merge();
7287 }
7288 }
7289 else
7290 t = type;
7291
7292 L1:
7293 if (type.isWild())
7294 {
7295 if (mod == MODFlags.immutable_)
7296 {
7297 t = t.immutableOf();
7298 }
7299 else if (mod == MODFlags.wildconst)
7300 {
7301 t = t.wildConstOf();
7302 }
7303 else if (mod == MODFlags.wild)
7304 {
7305 if (type.isWildConst())
7306 t = t.wildConstOf();
7307 else
7308 t = t.wildOf();
7309 }
7310 else if (mod == MODFlags.const_)
7311 {
7312 t = t.constOf();
7313 }
7314 else
7315 {
7316 if (type.isWildConst())
7317 t = t.constOf();
7318 else
7319 t = t.mutableOf();
7320 }
7321 }
7322 if (type.isConst())
7323 t = t.addMod(MODFlags.const_);
7324 if (type.isShared())
7325 t = t.addMod(MODFlags.shared_);
7326
7327 //printf("-Type.substWildTo t = %s\n", t.toChars());
7328 return t;
7329 }
7330
7331 if (!tf.iswild && !(tf.mod & MODFlags.wild))
7332 return tf;
7333
7334 // Substitude inout qualifier of function type to mutable or immutable
7335 // would break type system. Instead substitude inout to the most weak
7336 // qualifer - const.
7337 uint m = MODFlags.const_;
7338
7339 assert(tf.next);
7340 Type tret = tf.next.substWildTo(m);
7341 Parameters* params = tf.parameterList.parameters;
7342 if (tf.mod & MODFlags.wild)
7343 params = tf.parameterList.parameters.copy();
7344 for (size_t i = 0; i < params.length; i++)
7345 {
7346 Parameter p = (*params)[i];
7347 Type t = p.type.substWildTo(m);
7348 if (t == p.type)
7349 continue;
7350 if (params == tf.parameterList.parameters)
7351 params = tf.parameterList.parameters.copy();
7352 (*params)[i] = new Parameter(p.loc, p.storageClass, t, null, null, null);
7353 }
7354 if (tf.next == tret && params == tf.parameterList.parameters)
7355 return tf;
7356
7357 // Similar to TypeFunction.syntaxCopy;
7358 auto t = new TypeFunction(ParameterList(params, tf.parameterList.varargs), tret, tf.linkage);
7359 t.mod = ((tf.mod & MODFlags.wild) ? (tf.mod & ~MODFlags.wild) | MODFlags.const_ : tf.mod);
7360 t.isNothrow = tf.isNothrow;
7361 t.isNogc = tf.isNogc;
7362 t.purity = tf.purity;
7363 t.isProperty = tf.isProperty;
7364 t.isRef = tf.isRef;
7365 t.isReturn = tf.isReturn;
7366 t.isReturnScope = tf.isReturnScope;
7367 t.isScopeQual = tf.isScopeQual;
7368 t.isReturnInferred = tf.isReturnInferred;
7369 t.isScopeInferred = tf.isScopeInferred;
7370 t.isInOutParam = false;
7371 t.isInOutQual = false;
7372 t.trust = tf.trust;
7373 t.inferenceArguments = tf.inferenceArguments;
7374 t.isCtor = tf.isCtor;
7375 return t.merge();
7376 }
7377
7378 /************************************
7379 * Add MODxxxx bits to existing type.
7380 * We're adding, not replacing, so adding const to
7381 * a shared type => "shared const"
7382 */
7383 Type addMod(Type type, MOD mod)
7384 {
7385 /* Add anything to immutable, and it remains immutable
7386 */
7387 Type t = type;
7388 if (!t.isImmutable())
7389 {
7390 //printf("addMod(%x) %s\n", mod, toChars());
7391 switch (mod)
7392 {
7393 case 0:
7394 break;
7395
7396 case MODFlags.const_:
7397 if (type.isShared())
7398 {
7399 if (type.isWild())
7400 t = type.sharedWildConstOf();
7401 else
7402 t = type.sharedConstOf();
7403 }
7404 else
7405 {
7406 if (type.isWild())
7407 t = type.wildConstOf();
7408 else
7409 t = t.constOf();
7410 }
7411 break;
7412
7413 case MODFlags.wild:
7414 if (type.isShared())
7415 {
7416 if (type.isConst())
7417 t = type.sharedWildConstOf();
7418 else
7419 t = type.sharedWildOf();
7420 }
7421 else
7422 {
7423 if (type.isConst())
7424 t = type.wildConstOf();
7425 else
7426 t = type.wildOf();
7427 }
7428 break;
7429
7430 case MODFlags.wildconst:
7431 if (type.isShared())
7432 t = type.sharedWildConstOf();
7433 else
7434 t = type.wildConstOf();
7435 break;
7436
7437 case MODFlags.shared_:
7438 if (type.isWild())
7439 {
7440 if (type.isConst())
7441 t = type.sharedWildConstOf();
7442 else
7443 t = type.sharedWildOf();
7444 }
7445 else
7446 {
7447 if (type.isConst())
7448 t = type.sharedConstOf();
7449 else
7450 t = type.sharedOf();
7451 }
7452 break;
7453
7454 case MODFlags.shared_ | MODFlags.const_:
7455 if (type.isWild())
7456 t = type.sharedWildConstOf();
7457 else
7458 t = type.sharedConstOf();
7459 break;
7460
7461 case MODFlags.shared_ | MODFlags.wild:
7462 if (type.isConst())
7463 t = type.sharedWildConstOf();
7464 else
7465 t = type.sharedWildOf();
7466 break;
7467
7468 case MODFlags.shared_ | MODFlags.wildconst:
7469 t = type.sharedWildConstOf();
7470 break;
7471
7472 case MODFlags.immutable_:
7473 t = type.immutableOf();
7474 break;
7475
7476 default:
7477 assert(0);
7478 }
7479 }
7480 return t;
7481 }
7482
7483 /**
7484 * Check whether this type has endless `alias this` recursion.
7485 *
7486 * Params:
7487 * t = type to check whether it has a recursive alias this
7488 * Returns:
7489 * `true` if `t` has an `alias this` that can be implicitly
7490 * converted back to `t` itself.
7491 */
7492 private bool checkAliasThisRec(Type t)
7493 {
7494 Type tb = t.toBasetype();
7495 AliasThisRec* pflag;
7496 if (tb.ty == Tstruct)
7497 pflag = &(cast(TypeStruct)tb).att;
7498 else if (tb.ty == Tclass)
7499 pflag = &(cast(TypeClass)tb).att;
7500 else
7501 return false;
7502
7503 AliasThisRec flag = cast(AliasThisRec)(*pflag & AliasThisRec.typeMask);
7504 if (flag == AliasThisRec.fwdref)
7505 {
7506 Type att = aliasthisOf(t);
7507 flag = att && att.implicitConvTo(t) ? AliasThisRec.yes : AliasThisRec.no;
7508 }
7509 *pflag = cast(AliasThisRec)(flag | (*pflag & ~AliasThisRec.typeMask));
7510 return flag == AliasThisRec.yes;
7511 }
7512
7513 /**************************************
7514 * Check and set 'att' if 't' is a recursive 'alias this' type
7515 *
7516 * The goal is to prevent endless loops when there is a cycle in the alias this chain.
7517 * Since there is no multiple `alias this`, the chain either ends in a leaf,
7518 * or it loops back on itself as some point.
7519 *
7520 * Example: S0 -> (S1 -> S2 -> S3 -> S1)
7521 *
7522 * `S0` is not a recursive alias this, so this returns `false`, and a rewrite to `S1` can be tried.
7523 * `S1` is a recursive alias this type, but since `att` is initialized to `null`,
7524 * this still returns `false`, but `att1` is set to `S1`.
7525 * A rewrite to `S2` and `S3` can be tried, but when we want to try a rewrite to `S1` again,
7526 * we notice `att == t`, so we're back at the start of the loop, and this returns `true`.
7527 *
7528 * Params:
7529 * att = type reference used to detect recursion. Should be initialized to `null`.
7530 * t = type of 'alias this' rewrite to attempt
7531 *
7532 * Returns:
7533 * `false` if the rewrite is safe, `true` if it would loop back around
7534 */
7535 bool isRecursiveAliasThis(ref Type att, Type t)
7536 {
7537 //printf("+isRecursiveAliasThis(att = %s, t = %s)\n", att ? att.toChars() : "null", t.toChars());
7538 auto tb = t.toBasetype();
7539 if (att && tb.equivalent(att))
7540 return true;
7541 if (!att && tb.checkAliasThisRec())
7542 att = tb;
7543 return false;
7544 }
7545
7546 MATCH implicitConvToWithoutAliasThis(TypeStruct from, Type to)
7547 {
7548 //printf("TypeStruct::implicitConvToWithoutAliasThis(%s => %s)\n", toChars(), to.toChars());
7549
7550 auto tos = to.isTypeStruct();
7551 if (!(tos && from.sym == tos.sym))
7552 return MATCH.nomatch;
7553
7554 if (from.mod == to.mod)
7555 return MATCH.exact;
7556
7557 if (MODimplicitConv(from.mod, to.mod))
7558 return MATCH.constant;
7559
7560 /* Check all the fields. If they can all be converted,
7561 * allow the conversion.
7562 */
7563 MATCH m = MATCH.constant;
7564 uint offset = ~0; // must never match a field offset
7565 foreach (v; from.sym.fields[])
7566 {
7567 /* Why are we only looking at the first member of a union?
7568 * The check should check for overlap of v with the previous field,
7569 * not just starting at the same point
7570 */
7571 if (!global.params.fixImmutableConv && v.offset == offset) // v is at same offset as previous field
7572 continue; // ignore
7573
7574 Type tvf = v.type.addMod(from.mod); // from type
7575 Type tvt = v.type.addMod(to.mod); // to type
7576
7577 // field match
7578 MATCH mf = tvf.implicitConvTo(tvt);
7579 //printf("\t%s => %s, match = %d\n", v.type.toChars(), tvt.toChars(), mf);
7580
7581 if (mf == MATCH.nomatch)
7582 return MATCH.nomatch;
7583 if (mf < m) // if field match is worse
7584 m = mf;
7585 offset = v.offset;
7586 }
7587 return m;
7588 }
7589
7590 MATCH implicitConvToWithoutAliasThis(TypeClass from, Type to)
7591 {
7592 ClassDeclaration cdto = to.isClassHandle();
7593 MATCH m = constConv(from, to);
7594 if (m > MATCH.nomatch)
7595 return m;
7596
7597 if (cdto && cdto.isBaseOf(from.sym, null) && MODimplicitConv(from.mod, to.mod))
7598 {
7599 //printf("'to' is base\n");
7600 return MATCH.convert;
7601 }
7602 return MATCH.nomatch;
7603 }
7604
7605 MATCH implicitConvToThroughAliasThis(TypeClass from, Type to)
7606 {
7607 MATCH m;
7608 if (from.sym.aliasthis && !(from.att & AliasThisRec.tracing))
7609 {
7610 if (auto ato = aliasthisOf(from))
7611 {
7612 from.att = cast(AliasThisRec)(from.att | AliasThisRec.tracing);
7613 m = ato.implicitConvTo(to);
7614 from.att = cast(AliasThisRec)(from.att & ~AliasThisRec.tracing);
7615 }
7616 }
7617 return m;
7618 }
7619
7620 MATCH implicitConvToThroughAliasThis(TypeStruct from, Type to)
7621 {
7622 auto tos = to.isTypeStruct();
7623 if (!(tos && from.sym == tos.sym) &&
7624 from.sym.aliasthis &&
7625 !(from.att & AliasThisRec.tracing))
7626 {
7627 if (auto ato = aliasthisOf(from))
7628 {
7629 from.att = cast(AliasThisRec)(from.att | AliasThisRec.tracing);
7630 MATCH m = ato.implicitConvTo(to);
7631 from.att = cast(AliasThisRec)(from.att & ~AliasThisRec.tracing);
7632 return m;
7633 }
7634 }
7635 return MATCH.nomatch;
7636 }
7637
7638 /*******************************************
7639 * Compute number of elements for a (possibly multidimensional) static array,
7640 * or 1 for other types.
7641 * Params:
7642 * t = static array type
7643 * loc = for error message
7644 * Returns:
7645 * number of elements, uint.max on overflow
7646 */
7647 uint numberOfElems(Type t, Loc loc)
7648 {
7649 //printf("Type::numberOfElems()\n");
7650 uinteger_t n = 1;
7651 Type tb = t;
7652 while ((tb = tb.toBasetype()).ty == Tsarray)
7653 {
7654 bool overflow = false;
7655 n = mulu(n, (cast(TypeSArray)tb).dim.toUInteger(), overflow);
7656 if (overflow || n >= uint.max)
7657 {
7658 error(loc, "static array `%s` size overflowed to %llu", t.toChars(), cast(ulong)n);
7659 return uint.max;
7660 }
7661 tb = (cast(TypeSArray)tb).next;
7662 }
7663 return cast(uint)n;
7664 }
7665
7666 bool checkRetType(TypeFunction tf, Loc loc)
7667 {
7668 Type tb = tf.next.toBasetype();
7669 if (tb.ty == Tfunction)
7670 {
7671 error(loc, "functions cannot return a function");
7672 tf.next = Type.terror;
7673 }
7674 if (tb.ty == Ttuple)
7675 {
7676 error(loc, "functions cannot return a sequence (use `std.typecons.Tuple`)");
7677 tf.next = Type.terror;
7678 }
7679 if (!tf.isRef && (tb.ty == Tstruct || tb.ty == Tsarray))
7680 {
7681 if (auto ts = tb.baseElemOf().isTypeStruct())
7682 {
7683 if (!ts.sym.members)
7684 {
7685 error(loc, "functions cannot return opaque type `%s` by value", tb.toChars());
7686 tf.next = Type.terror;
7687 }
7688 }
7689 }
7690 if (tb.ty == Terror)
7691 return true;
7692 return false;
7693 }
7694
7695 /// Returns: whether `t` is a struct/class/enum without a body
7696 bool isOpaqueType(Type t)
7697 {
7698 if (auto te = t.isTypeEnum())
7699 return te.sym.members is null;
7700 if (auto ts = t.isTypeStruct())
7701 return ts.sym.members is null;
7702 if (auto tc = t.isTypeClass())
7703 return tc.sym.members is null;
7704 return false;
7705 }
7706
7707
7708 /******************************* Private *****************************************/
7709
7710 private:
7711
7712 /* Helper function for `typeToExpression`. Contains common code
7713 * for TypeQualified derived classes.
7714 */
7715 Expression typeToExpressionHelper(TypeQualified t, Expression e, size_t i = 0)
7716 {
7717 //printf("toExpressionHelper(e = %s %s)\n", EXPtoString(e.op).ptr, e.toChars());
7718 foreach (id; t.idents[i .. t.idents.length])
7719 {
7720 //printf("\t[%d] e: '%s', id: '%s'\n", i, e.toChars(), id.toChars());
7721
7722 final switch (id.dyncast())
7723 {
7724 // ... '. ident'
7725 case DYNCAST.identifier:
7726 e = new DotIdExp(e.loc, e, cast(Identifier)id);
7727 break;
7728
7729 // ... '. name!(tiargs)'
7730 case DYNCAST.dsymbol:
7731 auto ti = (cast(Dsymbol)id).isTemplateInstance();
7732 assert(ti);
7733 e = new DotTemplateInstanceExp(e.loc, e, ti.name, ti.tiargs);
7734 break;
7735
7736 // ... '[type]'
7737 case DYNCAST.type: // https://issues.dlang.org/show_bug.cgi?id=1215
7738 e = new ArrayExp(t.loc, e, new TypeExp(t.loc, cast(Type)id));
7739 break;
7740
7741 // ... '[expr]'
7742 case DYNCAST.expression: // https://issues.dlang.org/show_bug.cgi?id=1215
7743 e = new ArrayExp(t.loc, e, cast(Expression)id);
7744 break;
7745
7746 case DYNCAST.object:
7747 case DYNCAST.tuple:
7748 case DYNCAST.parameter:
7749 case DYNCAST.statement:
7750 case DYNCAST.condition:
7751 case DYNCAST.templateparameter:
7752 case DYNCAST.initializer:
7753 assert(0);
7754 }
7755 }
7756 return e;
7757 }
7758
7759 /**************************
7760 * This evaluates exp while setting length to be the number
7761 * of elements in the tuple t.
7762 */
7763 Expression semanticLength(Scope* sc, Type t, Expression exp)
7764 {
7765 if (auto tt = t.isTypeTuple())
7766 {
7767 ScopeDsymbol sym = new ArrayScopeSymbol(sc, tt);
7768 sym.parent = sc.scopesym;
7769 sc = sc.push(sym);
7770 sc = sc.startCTFE();
7771 exp = exp.expressionSemantic(sc);
7772 exp = resolveProperties(sc, exp);
7773 sc = sc.endCTFE();
7774 sc.pop();
7775 }
7776 else
7777 {
7778 sc = sc.startCTFE();
7779 exp = exp.expressionSemantic(sc);
7780 exp = resolveProperties(sc, exp);
7781 sc = sc.endCTFE();
7782 }
7783 return exp;
7784 }
7785
7786 Expression semanticLength(Scope* sc, TupleDeclaration tup, Expression exp)
7787 {
7788 ScopeDsymbol sym = new ArrayScopeSymbol(sc, tup);
7789 sym.parent = sc.scopesym;
7790
7791 sc = sc.push(sym);
7792 sc = sc.startCTFE();
7793 exp = exp.expressionSemantic(sc);
7794 exp = resolveProperties(sc, exp);
7795 sc = sc.endCTFE();
7796 sc.pop();
7797
7798 return exp;
7799 }
7800
7801 /************************************
7802 * Transitively search a type for all function types.
7803 * If any function types with parameters are found that have parameter identifiers
7804 * or default arguments, remove those and create a new type stripped of those.
7805 * This is used to determine the "canonical" version of a type which is useful for
7806 * comparisons.
7807 * Params:
7808 * t = type to scan
7809 * Returns:
7810 * `t` if no parameter identifiers or default arguments found, otherwise a new type that is
7811 * the same as t but with no parameter identifiers or default arguments.
7812 */
7813 Type stripDefaultArgs(Type t)
7814 {
7815 static Parameters* stripParams(Parameters* parameters)
7816 {
7817 static Parameter stripParameter(Parameter p)
7818 {
7819 Type t = stripDefaultArgs(p.type);
7820 return (t != p.type || p.defaultArg || p.ident || p.userAttribDecl)
7821 ? new Parameter(p.loc, p.storageClass, t, null, null, null)
7822 : null;
7823 }
7824
7825 if (parameters)
7826 {
7827 foreach (i, p; *parameters)
7828 {
7829 if (Parameter ps = stripParameter(p))
7830 {
7831 // Replace params with a copy we can modify
7832 Parameters* nparams = new Parameters(parameters.length);
7833
7834 foreach (j, ref np; *nparams)
7835 {
7836 Parameter pj = (*parameters)[j];
7837 if (j < i)
7838 np = pj;
7839 else if (j == i)
7840 np = ps;
7841 else
7842 {
7843 Parameter nps = stripParameter(pj);
7844 np = nps ? nps : pj;
7845 }
7846 }
7847 return nparams;
7848 }
7849 }
7850 }
7851 return parameters;
7852 }
7853
7854 if (t is null)
7855 return t;
7856
7857 if (auto tf = t.isTypeFunction())
7858 {
7859 Type tret = stripDefaultArgs(tf.next);
7860 Parameters* params = stripParams(tf.parameterList.parameters);
7861 if (tret == tf.next && params == tf.parameterList.parameters)
7862 return t;
7863 TypeFunction tr = tf.copy().isTypeFunction();
7864 tr.parameterList.parameters = params;
7865 tr.next = tret;
7866 //printf("strip %s\n <- %s\n", tr.toChars(), t.toChars());
7867 return tr;
7868 }
7869 else if (auto tt = t.isTypeTuple())
7870 {
7871 Parameters* args = stripParams(tt.arguments);
7872 if (args == tt.arguments)
7873 return t;
7874 TypeTuple tr = t.copy().isTypeTuple();
7875 tr.arguments = args;
7876 return tr;
7877 }
7878 else if (t.ty == Tenum)
7879 {
7880 // TypeEnum::nextOf() may be != NULL, but it's not necessary here.
7881 return t;
7882 }
7883 else
7884 {
7885 Type tn = t.nextOf();
7886 Type n = stripDefaultArgs(tn);
7887 if (n == tn)
7888 return t;
7889 TypeNext tr = cast(TypeNext)t.copy();
7890 tr.next = n;
7891 return tr;
7892 }
7893 }
7894
7895 /******************************
7896 * Get the value of the .max/.min property of `ed` as an Expression.
7897 * Lazily computes the value and caches it in maxval/minval.
7898 * Reports any errors.
7899 * Params:
7900 * ed = the EnumDeclaration being examined
7901 * loc = location to use for error messages
7902 * id = Id::max or Id::min
7903 * Returns:
7904 * corresponding value of .max/.min
7905 */
7906 Expression getMaxMinValue(EnumDeclaration ed, Loc loc, Identifier id)
7907 {
7908 //printf("EnumDeclaration::getMaxValue()\n");
7909
7910 static Expression pvalToResult(Expression e, Loc loc)
7911 {
7912 if (e.op != EXP.error)
7913 {
7914 e = e.copy();
7915 e.loc = loc;
7916 }
7917 return e;
7918 }
7919
7920 Expression* pval = (id == Id.max) ? &ed.maxval : &ed.minval;
7921
7922 Expression errorReturn()
7923 {
7924 *pval = ErrorExp.get();
7925 return *pval;
7926 }
7927
7928 if (ed.inuse)
7929 {
7930 .error(loc, "%s `%s` recursive definition of `.%s` property", ed.kind, ed.toPrettyChars, id.toChars());
7931 return errorReturn();
7932 }
7933 if (*pval)
7934 return pvalToResult(*pval, loc);
7935
7936 if (ed._scope)
7937 dsymbolSemantic(ed, ed._scope);
7938 if (ed.errors)
7939 return errorReturn();
7940 if (!ed.members)
7941 {
7942 .error(loc, "%s `%s` is opaque and has no `.%s`", ed.kind, ed.toPrettyChars, id.toChars(), id.toChars());
7943 return errorReturn();
7944 }
7945 if (!(ed.memtype && ed.memtype.isIntegral()))
7946 {
7947 .error(loc, "%s `%s` has no `.%s` property because base type `%s` is not an integral type", ed.kind, ed.toPrettyChars, id.toChars(),
7948 id.toChars(), ed.memtype ? ed.memtype.toChars() : "");
7949 return errorReturn();
7950 }
7951
7952 bool first = true;
7953 for (size_t i = 0; i < ed.members.length; i++)
7954 {
7955 EnumMember em = (*ed.members)[i].isEnumMember();
7956 if (!em)
7957 continue;
7958 if (em.errors)
7959 {
7960 ed.errors = true;
7961 continue;
7962 }
7963
7964 if (em.semanticRun < PASS.semanticdone)
7965 {
7966 .error(em.loc, "%s `%s` is forward referenced looking for `.%s`", em.kind, em.toPrettyChars, id.toChars());
7967 ed.errors = true;
7968 continue;
7969 }
7970
7971 if (first)
7972 {
7973 *pval = em.value;
7974 first = false;
7975 }
7976 else
7977 {
7978 /* In order to work successfully with UDTs,
7979 * build expressions to do the comparisons,
7980 * and let the semantic analyzer and constant
7981 * folder give us the result.
7982 */
7983
7984 /* Compute:
7985 * if (e > maxval)
7986 * maxval = e;
7987 */
7988 Expression e = em.value;
7989 Expression ec = new CmpExp(id == Id.max ? EXP.greaterThan : EXP.lessThan, em.loc, e, *pval);
7990 ed.inuse = true;
7991 ec = ec.expressionSemantic(em._scope);
7992 ed.inuse = false;
7993 ec = ec.ctfeInterpret();
7994 if (ec.op == EXP.error)
7995 {
7996 ed.errors = true;
7997 continue;
7998 }
7999 if (ec.toInteger())
8000 *pval = e;
8001 }
8002 }
8003 return ed.errors ? errorReturn() : pvalToResult(*pval, loc);
8004 }
8005
8006 /******************************************
8007 * Compile the MixinType, returning the type or expression AST.
8008 *
8009 * Doesn't run semantic() on the returned object.
8010 * Params:
8011 * tm = mixin to compile as a type or expression
8012 * loc = location for error messages
8013 * sc = context
8014 * Return:
8015 * null if error, else RootObject AST as parsed
8016 */
8017 RootObject compileTypeMixin(TypeMixin tm, Loc loc, Scope* sc)
8018 {
8019 OutBuffer buf;
8020 if (expressionsToString(buf, sc, tm.exps, tm.loc, null, true))
8021 return null;
8022
8023 const errors = global.errors;
8024 const len = buf.length;
8025 buf.writeByte(0);
8026 const str = buf.extractSlice()[0 .. len];
8027 const bool doUnittests = global.params.parsingUnittestsRequired();
8028 scope p = new Parser!ASTCodegen(sc._module, str, false, global.errorSink, &global.compileEnv, doUnittests);
8029 adjustLocForMixin(str, loc, *p.baseLoc, global.params.mixinOut);
8030 p.linnum = p.baseLoc.startLine;
8031 p.nextToken();
8032 //printf("p.loc.linnum = %d\n", p.loc.linnum);
8033
8034 auto o = p.parseTypeOrAssignExp(TOK.endOfFile);
8035 if (errors != global.errors)
8036 {
8037 assert(global.errors != errors); // should have caught all these cases
8038 return null;
8039 }
8040 if (p.token.value != TOK.endOfFile)
8041 {
8042 .error(loc, "unexpected token `%s` after type `%s`",
8043 p.token.toChars(), o.toChars());
8044 .errorSupplemental(loc, "while parsing string mixin type `%s`",
8045 str.ptr);
8046 return null;
8047 }
8048
8049 return o;
8050 }