1
2 /* Compiler implementation of the D programming language
3 * Copyright (C) 1999-2021 by The D Language Foundation, All Rights Reserved
4 * written by Walter Bright
5 * http://www.digitalmars.com
6 * Distributed under the Boost Software License, Version 1.0.
7 * http://www.boost.org/LICENSE_1_0.txt
8 */
9
10 #include "root/dsystem.h"
11 #include "root/checkedint.h"
12
13 #include "mtype.h"
14 #include "aggregate.h"
15 #include "enum.h"
16 #include "errors.h"
17 #include "expression.h"
18 #include "hdrgen.h"
19 #include "id.h"
20 #include "init.h"
21 #include "parse.h"
22 #include "scope.h"
23 #include "target.h"
24 #include "template.h"
25 #include "visitor.h"
26
27 Expression *typeToExpression(Type *t);
28 Expression *typeToExpressionHelper(TypeQualified *t, Expression *e, size_t i = 0);
29 bool expressionsToString(OutBuffer &buf, Scope *sc, Expressions *exps);
30 char *MODtoChars(MOD mod);
31
32 class TypeToExpressionVisitor : public Visitor
33 {
34 public:
35 Expression *result;
36 Type *itype;
37
TypeToExpressionVisitor(Type * itype)38 TypeToExpressionVisitor(Type *itype)
39 {
40 this->result = NULL;
41 this->itype = itype;
42 }
43
visit(Type *)44 void visit(Type *)
45 {
46 result = NULL;
47 }
48
visit(TypeSArray * t)49 void visit(TypeSArray *t)
50 {
51 Expression *e = typeToExpression(t->next);
52 if (e)
53 e = new ArrayExp(t->dim->loc, e, t->dim);
54 result = e;
55 }
56
visit(TypeAArray * t)57 void visit(TypeAArray *t)
58 {
59 Expression *e = typeToExpression(t->next);
60 if (e)
61 {
62 Expression *ei = typeToExpression(t->index);
63 if (ei)
64 {
65 result = new ArrayExp(t->loc, e, ei);
66 return;
67 }
68 }
69 result = NULL;
70 }
71
visit(TypeIdentifier * t)72 void visit(TypeIdentifier *t)
73 {
74 result = typeToExpressionHelper(t, new IdentifierExp(t->loc, t->ident));
75 }
76
visit(TypeInstance * t)77 void visit(TypeInstance *t)
78 {
79 result = typeToExpressionHelper(t, new ScopeExp(t->loc, t->tempinst));
80 }
81
visit(TypeMixin * t)82 void visit(TypeMixin *t)
83 {
84 result = new TypeExp(t->loc, t);
85 }
86 };
87
88 /* We've mistakenly parsed this as a type.
89 * Redo it as an Expression.
90 * NULL if cannot.
91 */
typeToExpression(Type * t)92 Expression *typeToExpression(Type *t)
93 {
94 if (t->mod)
95 return NULL;
96 TypeToExpressionVisitor v = TypeToExpressionVisitor(t);
97 t->accept(&v);
98 return v.result;
99 }
100
101 /* Helper function for `typeToExpression`. Contains common code
102 * for TypeQualified derived classes.
103 */
typeToExpressionHelper(TypeQualified * t,Expression * e,size_t i)104 Expression *typeToExpressionHelper(TypeQualified *t, Expression *e, size_t i)
105 {
106 //printf("toExpressionHelper(e = %s %s)\n", Token::toChars(e->op), e->toChars());
107 for (; i < t->idents.length; i++)
108 {
109 RootObject *id = t->idents[i];
110 //printf("\t[%d] e: '%s', id: '%s'\n", i, e->toChars(), id->toChars());
111
112 switch (id->dyncast())
113 {
114 case DYNCAST_IDENTIFIER:
115 {
116 // ... '. ident'
117 e = new DotIdExp(e->loc, e, (Identifier *)id);
118 break;
119 }
120 case DYNCAST_DSYMBOL:
121 {
122 // ... '. name!(tiargs)'
123 TemplateInstance *ti = ((Dsymbol *)id)->isTemplateInstance();
124 assert(ti);
125 e = new DotTemplateInstanceExp(e->loc, e, ti->name, ti->tiargs);
126 break;
127 }
128 case DYNCAST_TYPE: // Bugzilla 1215
129 {
130 // ... '[type]'
131 e = new ArrayExp(t->loc, e, new TypeExp(t->loc, (Type *)id));
132 break;
133 }
134 case DYNCAST_EXPRESSION: // Bugzilla 1215
135 {
136 // ... '[expr]'
137 e = new ArrayExp(t->loc, e, (Expression *)id);
138 break;
139 }
140 default:
141 assert(0);
142 }
143 }
144 return e;
145 }
146
147 /**************************
148 * This evaluates exp while setting length to be the number
149 * of elements in the tuple t.
150 */
semanticLength(Scope * sc,Type * t,Expression * exp)151 static Expression *semanticLength(Scope *sc, Type *t, Expression *exp)
152 {
153 if (t->ty == Ttuple)
154 {
155 ScopeDsymbol *sym = new ArrayScopeSymbol(sc, (TypeTuple *)t);
156 sym->parent = sc->scopesym;
157 sc = sc->push(sym);
158
159 sc = sc->startCTFE();
160 exp = expressionSemantic(exp, sc);
161 sc = sc->endCTFE();
162
163 sc->pop();
164 }
165 else
166 {
167 sc = sc->startCTFE();
168 exp = expressionSemantic(exp, sc);
169 sc = sc->endCTFE();
170 }
171
172 return exp;
173 }
174
semanticLength(Scope * sc,TupleDeclaration * s,Expression * exp)175 static Expression *semanticLength(Scope *sc, TupleDeclaration *s, Expression *exp)
176 {
177 ScopeDsymbol *sym = new ArrayScopeSymbol(sc, s);
178 sym->parent = sc->scopesym;
179 sc = sc->push(sym);
180
181 sc = sc->startCTFE();
182 exp = expressionSemantic(exp, sc);
183 sc = sc->endCTFE();
184
185 sc->pop();
186 return exp;
187 }
188
189 /******************************************
190 * Compile the MixinType, returning the type or expression AST.
191 *
192 * Doesn't run semantic() on the returned object.
193 * Params:
194 * tm = mixin to compile as a type or expression
195 * loc = location for error messages
196 * sc = context
197 * Return:
198 * null if error, else RootObject AST as parsed
199 */
compileTypeMixin(TypeMixin * tm,Loc loc,Scope * sc)200 RootObject *compileTypeMixin(TypeMixin *tm, Loc loc, Scope *sc)
201 {
202 OutBuffer buf;
203 if (expressionsToString(buf, sc, tm->exps))
204 return NULL;
205
206 const unsigned errors = global.errors;
207 const size_t len = buf.length();
208 const char *str = buf.extractChars();
209 Parser p(loc, sc->_module, (const utf8_t *)str, len, false);
210 p.nextToken();
211 //printf("p.loc.linnum = %d\n", p.loc.linnum);
212
213 RootObject *o = p.parseTypeOrAssignExp(TOKeof);
214 if (errors != global.errors)
215 {
216 assert(global.errors != errors); // should have caught all these cases
217 return NULL;
218 }
219 if (p.token.value != TOKeof)
220 {
221 ::error(loc, "incomplete mixin type `%s`", str);
222 return NULL;
223 }
224
225 Type *t = isType(o);
226 Expression *e = t ? typeToExpression(t) : isExpression(o);
227
228 return (!e && t) ? (RootObject *)t : (RootObject *)e;
229 }
230
231 /******************************************
232 * Perform semantic analysis on a type.
233 * Params:
234 * type = Type AST node
235 * loc = the location of the type
236 * sc = context
237 * Returns:
238 * `Type` with completed semantic analysis, `Terror` if errors
239 * were encountered
240 */
typeSemantic(Type * type,const Loc & loc,Scope * sc)241 Type *typeSemantic(Type *type, const Loc &loc, Scope *sc)
242 {
243 class TypeSemanticVisitor : public Visitor
244 {
245 public:
246 Loc loc;
247 Scope *sc;
248 Type *result;
249
250 TypeSemanticVisitor(const Loc &loc, Scope *sc)
251 {
252 this->loc = loc;
253 this->sc = sc;
254 this->result = NULL;
255 }
256
257 private:
258 void error()
259 {
260 result = Type::terror;
261 }
262
263 public:
264 void visit(Type *t)
265 {
266 if (t->ty == Tint128 || t->ty == Tuns128)
267 {
268 ::error(loc, "cent and ucent types not implemented");
269 return error();
270 }
271
272 result = t->merge();
273 }
274
275 void visit(TypeVector *mtype)
276 {
277 unsigned int errors = global.errors;
278 mtype->basetype = typeSemantic(mtype->basetype, loc, sc);
279 if (errors != global.errors)
280 return error();
281 mtype->basetype = mtype->basetype->toBasetype()->mutableOf();
282 if (mtype->basetype->ty != Tsarray)
283 {
284 ::error(loc, "T in __vector(T) must be a static array, not %s", mtype->basetype->toChars());
285 return error();
286 }
287 TypeSArray *t = (TypeSArray *)mtype->basetype;
288 int sz = (int)t->size(loc);
289 switch (target.isVectorTypeSupported(sz, t->nextOf()))
290 {
291 case 0: // valid
292 break;
293 case 1: // no support at all
294 ::error(loc, "SIMD vector types not supported on this platform");
295 return error();
296 case 2: // invalid base type
297 ::error(loc, "vector type %s is not supported on this platform", mtype->toChars());
298 return error();
299 case 3: // invalid size
300 ::error(loc, "%d byte vector type %s is not supported on this platform", sz, mtype->toChars());
301 return error();
302 default:
303 assert(0);
304 }
305 result = mtype->merge();
306 }
307
308 void visit(TypeSArray *mtype)
309 {
310 //printf("TypeSArray::semantic() %s\n", mtype->toChars());
311
312 Type *t;
313 Expression *e;
314 Dsymbol *s;
315 mtype->next->resolve(loc, sc, &e, &t, &s);
316
317 if (mtype->dim && s && s->isTupleDeclaration())
318 {
319 TupleDeclaration *sd = s->isTupleDeclaration();
320
321 mtype->dim = semanticLength(sc, sd, mtype->dim);
322 mtype->dim = mtype->dim->ctfeInterpret();
323 if(mtype->dim->op == TOKerror)
324 return error();
325
326 uinteger_t d = mtype->dim->toUInteger();
327 if (d >= sd->objects->length)
328 {
329 ::error(loc, "tuple index %llu exceeds %llu", (unsigned long long)d, (unsigned long long)sd->objects->length);
330 return error();
331 }
332
333 RootObject *o = (*sd->objects)[(size_t)d];
334 if (o->dyncast() != DYNCAST_TYPE)
335 {
336 ::error(loc, "%s is not a type", mtype->toChars());
337 return error();
338 }
339 result = ((Type *)o)->addMod(mtype->mod);
340 return;
341 }
342
343 if (t && t->ty == Terror)
344 return error();
345
346 Type *tn = typeSemantic(mtype->next, loc, sc);
347 if (tn->ty == Terror)
348 return error();
349
350 Type *tbn = tn->toBasetype();
351 if (mtype->dim)
352 {
353 unsigned int errors = global.errors;
354 mtype->dim = semanticLength(sc, tbn, mtype->dim);
355 if (errors != global.errors)
356 return error();
357
358 mtype->dim = mtype->dim->optimize(WANTvalue);
359 mtype->dim = mtype->dim->ctfeInterpret();
360 if (mtype->dim->op == TOKerror)
361 return error();
362 errors = global.errors;
363 dinteger_t d1 = mtype->dim->toInteger();
364 if (errors != global.errors)
365 return error();
366
367 mtype->dim = mtype->dim->implicitCastTo(sc, Type::tsize_t);
368 mtype->dim = mtype->dim->optimize(WANTvalue);
369 if (mtype->dim->op == TOKerror)
370 return error();
371 errors = global.errors;
372 dinteger_t d2 = mtype->dim->toInteger();
373 if (errors != global.errors)
374 return error();
375
376 if (mtype->dim->op == TOKerror)
377 return error();
378
379 if (d1 != d2)
380 {
381 Loverflow:
382 ::error(loc, "%s size %llu * %llu exceeds 0x%llx size limit for static array",
383 mtype->toChars(), (unsigned long long)tbn->size(loc), (unsigned long long)d1, target.maxStaticDataSize);
384 return error();
385 }
386
387 Type *tbx = tbn->baseElemOf();
388 if ((tbx->ty == Tstruct && !((TypeStruct *)tbx)->sym->members) ||
389 (tbx->ty == Tenum && !((TypeEnum *)tbx)->sym->members))
390 {
391 /* To avoid meaningless error message, skip the total size limit check
392 * when the bottom of element type is opaque.
393 */
394 }
395 else if (tbn->isTypeBasic() ||
396 tbn->ty == Tpointer ||
397 tbn->ty == Tarray ||
398 tbn->ty == Tsarray ||
399 tbn->ty == Taarray ||
400 (tbn->ty == Tstruct && (((TypeStruct *)tbn)->sym->sizeok == SIZEOKdone)) ||
401 tbn->ty == Tclass)
402 {
403 /* Only do this for types that don't need to have semantic()
404 * run on them for the size, since they may be forward referenced.
405 */
406 bool overflow = false;
407 if (mulu(tbn->size(loc), d2, overflow) >= target.maxStaticDataSize || overflow)
408 goto Loverflow;
409 }
410 }
411 switch (tbn->ty)
412 {
413 case Ttuple:
414 {
415 // Index the tuple to get the type
416 assert(mtype->dim);
417 TypeTuple *tt = (TypeTuple *)tbn;
418 uinteger_t d = mtype->dim->toUInteger();
419 if (d >= tt->arguments->length)
420 {
421 ::error(loc, "tuple index %llu exceeds %llu", (unsigned long long)d, (unsigned long long)tt->arguments->length);
422 return error();
423 }
424 Type *telem = (*tt->arguments)[(size_t)d]->type;
425 result = telem->addMod(mtype->mod);
426 return;
427 }
428 case Tfunction:
429 case Tnone:
430 ::error(loc, "cannot have array of %s", tbn->toChars());
431 return error();
432 default:
433 break;
434 }
435 if (tbn->isscope())
436 {
437 ::error(loc, "cannot have array of scope %s", tbn->toChars());
438 return error();
439 }
440
441 /* Ensure things like const(immutable(T)[3]) become immutable(T[3])
442 * and const(T)[3] become const(T[3])
443 */
444 mtype->next = tn;
445 mtype->transitive();
446 result = mtype->addMod(tn->mod)->merge();
447 }
448
449 void visit(TypeDArray *mtype)
450 {
451 Type *tn = typeSemantic(mtype->next, loc,sc);
452 Type *tbn = tn->toBasetype();
453 switch (tbn->ty)
454 {
455 case Ttuple:
456 result = tbn;
457 return;
458 case Tfunction:
459 case Tnone:
460 ::error(loc, "cannot have array of %s", tbn->toChars());
461 return error();
462 case Terror:
463 return error();
464 default:
465 break;
466 }
467 if (tn->isscope())
468 {
469 ::error(loc, "cannot have array of scope %s", tn->toChars());
470 return error();
471 }
472 mtype->next = tn;
473 mtype->transitive();
474 result = mtype->merge();
475 }
476
477 void visit(TypeAArray *mtype)
478 {
479 //printf("TypeAArray::semantic() %s index->ty = %d\n", mtype->toChars(), mtype->index->ty);
480 if (mtype->deco)
481 {
482 result = mtype;
483 return;
484 }
485
486 mtype->loc = loc;
487 mtype->sc = sc;
488 if (sc)
489 sc->setNoFree();
490
491 // Deal with the case where we thought the index was a type, but
492 // in reality it was an expression.
493 if (mtype->index->ty == Tident || mtype->index->ty == Tinstance || mtype->index->ty == Tsarray ||
494 mtype->index->ty == Ttypeof || mtype->index->ty == Treturn || mtype->index->ty == Tmixin)
495 {
496 Expression *e;
497 Type *t;
498 Dsymbol *s;
499
500 mtype->index->resolve(loc, sc, &e, &t, &s);
501 if (e)
502 {
503 // It was an expression -
504 // Rewrite as a static array
505 TypeSArray *tsa = new TypeSArray(mtype->next, e);
506 result = typeSemantic(tsa, loc, sc);
507 return;
508 }
509 else if (t)
510 mtype->index = typeSemantic(t, loc, sc);
511 else
512 {
513 mtype->index->error(loc, "index is not a type or an expression");
514 return error();
515 }
516 }
517 else
518 mtype->index = typeSemantic(mtype->index, loc,sc);
519 mtype->index = mtype->index->merge2();
520
521 if (mtype->index->nextOf() && !mtype->index->nextOf()->isImmutable())
522 {
523 mtype->index = mtype->index->constOf()->mutableOf();
524 }
525
526 switch (mtype->index->toBasetype()->ty)
527 {
528 case Tfunction:
529 case Tvoid:
530 case Tnone:
531 case Ttuple:
532 ::error(loc, "cannot have associative array key of %s", mtype->index->toBasetype()->toChars());
533 /* fall through */
534 case Terror:
535 return error();
536 default:
537 break;
538 }
539 Type *tbase = mtype->index->baseElemOf();
540 while (tbase->ty == Tarray)
541 tbase = tbase->nextOf()->baseElemOf();
542 if (tbase->ty == Tstruct)
543 {
544 /* AA's need typeid(index).equals() and getHash(). Issue error if not correctly set up.
545 */
546 StructDeclaration *sd = ((TypeStruct *)tbase)->sym;
547 if (sd->semanticRun < PASSsemanticdone)
548 dsymbolSemantic(sd, NULL);
549
550 // duplicate a part of StructDeclaration::semanticTypeInfoMembers
551 //printf("AA = %s, key: xeq = %p, xerreq = %p xhash = %p\n", mtype->toChars(), sd->xeq, sd->xerreq, sd->xhash);
552 if (sd->xeq &&
553 sd->xeq->_scope &&
554 sd->xeq->semanticRun < PASSsemantic3done)
555 {
556 unsigned errors = global.startGagging();
557 semantic3(sd->xeq, sd->xeq->_scope);
558 if (global.endGagging(errors))
559 sd->xeq = sd->xerreq;
560 }
561
562 const char *s = (mtype->index->toBasetype()->ty != Tstruct) ? "bottom of " : "";
563 if (!sd->xeq)
564 {
565 // If sd->xhash != NULL:
566 // sd or its fields have user-defined toHash.
567 // AA assumes that its result is consistent with bitwise equality.
568 // else:
569 // bitwise equality & hashing
570 }
571 else if (sd->xeq == sd->xerreq)
572 {
573 if (search_function(sd, Id::eq))
574 {
575 ::error(loc, "%sAA key type %s does not have `bool opEquals(ref const %s) const`",
576 s, sd->toChars(), sd->toChars());
577 }
578 else
579 {
580 ::error(loc, "%sAA key type %s does not support const equality",
581 s, sd->toChars());
582 }
583 return error();
584 }
585 else if (!sd->xhash)
586 {
587 if (search_function(sd, Id::eq))
588 {
589 ::error(loc, "%sAA key type %s should have `size_t toHash() const nothrow @safe` if opEquals defined",
590 s, sd->toChars());
591 }
592 else
593 {
594 ::error(loc, "%sAA key type %s supports const equality but doesn't support const hashing",
595 s, sd->toChars());
596 }
597 return error();
598 }
599 else
600 {
601 // defined equality & hashing
602 assert(sd->xeq && sd->xhash);
603
604 /* xeq and xhash may be implicitly defined by compiler. For example:
605 * struct S { int[] arr; }
606 * With 'arr' field equality and hashing, compiler will implicitly
607 * generate functions for xopEquals and xtoHash in TypeInfo_Struct.
608 */
609 }
610 }
611 else if (tbase->ty == Tclass && !((TypeClass *)tbase)->sym->isInterfaceDeclaration())
612 {
613 ClassDeclaration *cd = ((TypeClass *)tbase)->sym;
614 if (cd->semanticRun < PASSsemanticdone)
615 dsymbolSemantic(cd, NULL);
616
617 if (!ClassDeclaration::object)
618 {
619 ::error(Loc(), "missing or corrupt object.d");
620 fatal();
621 }
622
623 static FuncDeclaration *feq = NULL;
624 static FuncDeclaration *fcmp = NULL;
625 static FuncDeclaration *fhash = NULL;
626 if (!feq) feq = search_function(ClassDeclaration::object, Id::eq)->isFuncDeclaration();
627 if (!fcmp) fcmp = search_function(ClassDeclaration::object, Id::cmp)->isFuncDeclaration();
628 if (!fhash) fhash = search_function(ClassDeclaration::object, Id::tohash)->isFuncDeclaration();
629 assert(fcmp && feq && fhash);
630
631 if (feq->vtblIndex < (int)cd->vtbl.length && cd->vtbl[feq ->vtblIndex] == feq)
632 {
633 if (fcmp->vtblIndex < (int)cd->vtbl.length && cd->vtbl[fcmp->vtblIndex] != fcmp)
634 {
635 const char *s = (mtype->index->toBasetype()->ty != Tclass) ? "bottom of " : "";
636 ::error(loc, "%sAA key type %s now requires equality rather than comparison",
637 s, cd->toChars());
638 errorSupplemental(loc, "Please override Object.opEquals and toHash.");
639 }
640 }
641 }
642 mtype->next = typeSemantic(mtype->next, loc,sc)->merge2();
643 mtype->transitive();
644
645 switch (mtype->next->toBasetype()->ty)
646 {
647 case Tfunction:
648 case Tvoid:
649 case Tnone:
650 case Ttuple:
651 ::error(loc, "cannot have associative array of %s", mtype->next->toChars());
652 /* fall through */
653 case Terror:
654 return error();
655 }
656 if (mtype->next->isscope())
657 {
658 ::error(loc, "cannot have array of scope %s", mtype->next->toChars());
659 return error();
660 }
661 result = mtype->merge();
662 }
663
664 void visit(TypePointer *mtype)
665 {
666 //printf("TypePointer::semantic() %s\n", mtype->toChars());
667 if (mtype->deco)
668 {
669 result = mtype;
670 return;
671 }
672 Type *n = typeSemantic(mtype->next, loc, sc);
673 switch (n->toBasetype()->ty)
674 {
675 case Ttuple:
676 ::error(loc, "cannot have pointer to %s", n->toChars());
677 /* fall through */
678 case Terror:
679 return error();
680 default:
681 break;
682 }
683 if (n != mtype->next)
684 {
685 mtype->deco = NULL;
686 }
687 mtype->next = n;
688 if (mtype->next->ty != Tfunction)
689 {
690 mtype->transitive();
691 result = mtype->merge();
692 return;
693 }
694 mtype->deco = mtype->merge()->deco;
695 /* Don't return merge(), because arg identifiers and default args
696 * can be different
697 * even though the types match
698 */
699 result = mtype;
700 }
701
702 void visit(TypeReference *mtype)
703 {
704 //printf("TypeReference::semantic()\n");
705 Type *n = typeSemantic(mtype->next, loc, sc);
706 if (n != mtype->next)
707 mtype->deco = NULL;
708 mtype->next = n;
709 mtype->transitive();
710 result = mtype->merge();
711 }
712
713
714 void visit(TypeFunction *mtype)
715 {
716 if (mtype->deco) // if semantic() already run
717 {
718 //printf("already done\n");
719 result = mtype;
720 return;
721 }
722 //printf("TypeFunction::semantic() this = %p\n", this);
723 //printf("TypeFunction::semantic() %s, sc->stc = %llx, fargs = %p\n", mtype->toChars(), sc->stc, mtype->fargs);
724
725 bool errors = false;
726
727 if (mtype->inuse > global.recursionLimit)
728 {
729 mtype->inuse = 0;
730 ::error(loc, "recursive type");
731 return error();
732 }
733
734 /* Copy in order to not mess up original.
735 * This can produce redundant copies if inferring return type,
736 * as semantic() will get called again on this.
737 */
738 TypeFunction *tf = mtype->copy()->toTypeFunction();
739 if (mtype->parameterList.parameters)
740 {
741 tf->parameterList.parameters = mtype->parameterList.parameters->copy();
742 for (size_t i = 0; i < mtype->parameterList.parameters->length; i++)
743 {
744 void *pp = mem.xmalloc(sizeof(Parameter));
745 Parameter *p = (Parameter *)memcpy(pp, (void *)(*mtype->parameterList.parameters)[i],
746 sizeof(Parameter));
747 (*tf->parameterList.parameters)[i] = p;
748 }
749 }
750
751 if (sc->stc & STCpure)
752 tf->purity = PUREfwdref;
753 if (sc->stc & STCnothrow)
754 tf->isnothrow = true;
755 if (sc->stc & STCnogc)
756 tf->isnogc = true;
757 if (sc->stc & STCref)
758 tf->isref = true;
759 if (sc->stc & STCreturn)
760 tf->isreturn = true;
761 if (sc->stc & STCscope)
762 tf->isscope = true;
763 if (sc->stc & STCscopeinferred)
764 tf->isscopeinferred = true;
765 //if ((sc->stc & (STCreturn | STCref)) == STCreturn)
766 // tf->isscope = true; // return by itself means 'return scope'
767
768 if (tf->trust == TRUSTdefault)
769 {
770 if (sc->stc & STCsafe)
771 tf->trust = TRUSTsafe;
772 if (sc->stc & STCsystem)
773 tf->trust = TRUSTsystem;
774 if (sc->stc & STCtrusted)
775 tf->trust = TRUSTtrusted;
776 }
777
778 if (sc->stc & STCproperty)
779 tf->isproperty = true;
780
781 tf->linkage = sc->linkage;
782 bool wildreturn = false;
783 if (tf->next)
784 {
785 sc = sc->push();
786 sc->stc &= ~(STC_TYPECTOR | STC_FUNCATTR);
787 tf->next = typeSemantic(tf->next, loc, sc);
788 sc = sc->pop();
789 errors |= tf->checkRetType(loc);
790 if (tf->next->isscope() && !(sc->flags & SCOPEctor))
791 {
792 ::error(loc, "functions cannot return scope %s", tf->next->toChars());
793 errors = true;
794 }
795 if (tf->next->hasWild())
796 wildreturn = true;
797
798 if (tf->isreturn && !tf->isref && !tf->next->hasPointers())
799 {
800 tf->isreturn = false;
801 }
802 }
803
804 unsigned char wildparams = 0;
805 if (tf->parameterList.parameters)
806 {
807 /* Create a scope for evaluating the default arguments for the parameters
808 */
809 Scope *argsc = sc->push();
810 argsc->stc = 0; // don't inherit storage class
811 argsc->protection = Prot(Prot::public_);
812 argsc->func = NULL;
813
814 size_t dim = tf->parameterList.length();
815 for (size_t i = 0; i < dim; i++)
816 {
817 Parameter *fparam = tf->parameterList[i];
818 mtype->inuse++;
819 fparam->type = typeSemantic(fparam->type, loc, argsc);
820 mtype->inuse--;
821
822 if (fparam->type->ty == Terror)
823 {
824 errors = true;
825 continue;
826 }
827
828 fparam->type = fparam->type->addStorageClass(fparam->storageClass);
829
830 if (fparam->storageClass & (STCauto | STCalias | STCstatic))
831 {
832 if (!fparam->type)
833 continue;
834 }
835
836 Type *t = fparam->type->toBasetype();
837
838 if (t->ty == Tfunction)
839 {
840 ::error(loc, "cannot have parameter of function type %s", fparam->type->toChars());
841 errors = true;
842 }
843 else if (!(fparam->storageClass & (STCref | STCout)) &&
844 (t->ty == Tstruct || t->ty == Tsarray || t->ty == Tenum))
845 {
846 Type *tb2 = t->baseElemOf();
847 if ((tb2->ty == Tstruct && !((TypeStruct *)tb2)->sym->members) ||
848 (tb2->ty == Tenum && !((TypeEnum *)tb2)->sym->memtype))
849 {
850 ::error(loc, "cannot have parameter of opaque type %s by value", fparam->type->toChars());
851 errors = true;
852 }
853 }
854 else if (!(fparam->storageClass & STClazy) && t->ty == Tvoid)
855 {
856 ::error(loc, "cannot have parameter of type %s", fparam->type->toChars());
857 errors = true;
858 }
859
860 if ((fparam->storageClass & (STCref | STCwild)) == (STCref | STCwild))
861 {
862 // 'ref inout' implies 'return'
863 fparam->storageClass |= STCreturn;
864 }
865
866 if (fparam->storageClass & STCreturn)
867 {
868 if (fparam->storageClass & (STCref | STCout))
869 {
870 // Disabled for the moment awaiting improvement to allow return by ref
871 // to be transformed into return by scope.
872 if (0 && !tf->isref)
873 {
874 StorageClass stc = fparam->storageClass & (STCref | STCout);
875 ::error(loc, "parameter `%s` is `return %s` but function does not return by `ref`",
876 fparam->ident ? fparam->ident->toChars() : "",
877 stcToChars(stc));
878 errors = true;
879 }
880 }
881 else
882 {
883 fparam->storageClass |= STCscope; // 'return' implies 'scope'
884 if (tf->isref)
885 {
886 }
887 else if (!tf->isref && tf->next && !tf->next->hasPointers())
888 {
889 fparam->storageClass &= STCreturn; // https://issues.dlang.org/show_bug.cgi?id=18963
890 }
891 }
892 }
893
894 if (fparam->storageClass & (STCref | STClazy))
895 {
896 }
897 else if (fparam->storageClass & STCout)
898 {
899 if (unsigned char m = fparam->type->mod & (MODimmutable | MODconst | MODwild))
900 {
901 ::error(loc, "cannot have %s out parameter of type %s", MODtoChars(m), t->toChars());
902 errors = true;
903 }
904 else
905 {
906 Type *tv = t;
907 while (tv->ty == Tsarray)
908 tv = tv->nextOf()->toBasetype();
909 if (tv->ty == Tstruct && ((TypeStruct *)tv)->sym->noDefaultCtor)
910 {
911 ::error(loc, "cannot have out parameter of type %s because the default construction is disabled",
912 fparam->type->toChars());
913 errors = true;
914 }
915 }
916 }
917
918 if (fparam->storageClass & STCscope && !fparam->type->hasPointers() && fparam->type->ty != Ttuple)
919 {
920 fparam->storageClass &= ~STCscope;
921 if (!(fparam->storageClass & STCref))
922 fparam->storageClass &= ~STCreturn;
923 }
924
925 if (t->hasWild())
926 {
927 wildparams |= 1;
928 //if (tf->next && !wildreturn)
929 // ::error(loc, "inout on parameter means inout must be on return type as well (if from D1 code, replace with `ref`)");
930 }
931
932 if (fparam->defaultArg)
933 {
934 Expression *e = fparam->defaultArg;
935 if (fparam->storageClass & (STCref | STCout))
936 {
937 e = expressionSemantic(e, argsc);
938 e = resolveProperties(argsc, e);
939 }
940 else
941 {
942 e = inferType(e, fparam->type);
943 Initializer *iz = new ExpInitializer(e->loc, e);
944 iz = initializerSemantic(iz, argsc, fparam->type, INITnointerpret);
945 e = initializerToExpression(iz);
946 }
947 if (e->op == TOKfunction) // see Bugzilla 4820
948 {
949 FuncExp *fe = (FuncExp *)e;
950 // Replace function literal with a function symbol,
951 // since default arg expression must be copied when used
952 // and copying the literal itself is wrong.
953 e = new VarExp(e->loc, fe->fd, false);
954 e = new AddrExp(e->loc, e);
955 e = expressionSemantic(e, argsc);
956 }
957 e = e->implicitCastTo(argsc, fparam->type);
958
959 // default arg must be an lvalue
960 if (fparam->storageClass & (STCout | STCref))
961 e = e->toLvalue(argsc, e);
962
963 fparam->defaultArg = e;
964 if (e->op == TOKerror)
965 errors = true;
966 }
967
968 /* If fparam after semantic() turns out to be a tuple, the number of parameters may
969 * change.
970 */
971 if (t->ty == Ttuple)
972 {
973 /* TypeFunction::parameter also is used as the storage of
974 * Parameter objects for FuncDeclaration. So we should copy
975 * the elements of TypeTuple::arguments to avoid unintended
976 * sharing of Parameter object among other functions.
977 */
978 TypeTuple *tt = (TypeTuple *)t;
979 if (tt->arguments && tt->arguments->length)
980 {
981 /* Propagate additional storage class from tuple parameters to their
982 * element-parameters.
983 * Make a copy, as original may be referenced elsewhere.
984 */
985 size_t tdim = tt->arguments->length;
986 Parameters *newparams = new Parameters();
987 newparams->setDim(tdim);
988 for (size_t j = 0; j < tdim; j++)
989 {
990 Parameter *narg = (*tt->arguments)[j];
991
992 // Bugzilla 12744: If the storage classes of narg
993 // conflict with the ones in fparam, it's ignored.
994 StorageClass stc = fparam->storageClass | narg->storageClass;
995 StorageClass stc1 = fparam->storageClass & (STCref | STCout | STClazy);
996 StorageClass stc2 = narg->storageClass & (STCref | STCout | STClazy);
997 if (stc1 && stc2 && stc1 != stc2)
998 {
999 OutBuffer buf1; stcToBuffer(&buf1, stc1 | ((stc1 & STCref) ? (fparam->storageClass & STCauto) : 0));
1000 OutBuffer buf2; stcToBuffer(&buf2, stc2);
1001
1002 ::error(loc, "incompatible parameter storage classes `%s` and `%s`",
1003 buf1.peekChars(), buf2.peekChars());
1004 errors = true;
1005 stc = stc1 | (stc & ~(STCref | STCout | STClazy));
1006 }
1007
1008 (*newparams)[j] = new Parameter(
1009 stc, narg->type, narg->ident, narg->defaultArg, narg->userAttribDecl);
1010 }
1011 fparam->type = new TypeTuple(newparams);
1012 }
1013 fparam->storageClass = 0;
1014
1015 /* Reset number of parameters, and back up one to do this fparam again,
1016 * now that it is a tuple
1017 */
1018 dim = tf->parameterList.length();
1019 i--;
1020 continue;
1021 }
1022
1023 /* Resolve "auto ref" storage class to be either ref or value,
1024 * based on the argument matching the parameter
1025 */
1026 if (fparam->storageClass & STCauto)
1027 {
1028 if (mtype->fargs && i < mtype->fargs->length && (fparam->storageClass & STCref))
1029 {
1030 Expression *farg = (*mtype->fargs)[i];
1031 if (farg->isLvalue())
1032 ; // ref parameter
1033 else
1034 fparam->storageClass &= ~STCref; // value parameter
1035 fparam->storageClass &= ~STCauto; // Bugzilla 14656
1036 fparam->storageClass |= STCautoref;
1037 }
1038 else
1039 {
1040 ::error(loc, "`auto` can only be used as part of `auto ref` for template function parameters");
1041 errors = true;
1042 }
1043 }
1044
1045 // Remove redundant storage classes for type, they are already applied
1046 fparam->storageClass &= ~(STC_TYPECTOR | STCin);
1047 }
1048 argsc->pop();
1049 }
1050 if (tf->isWild())
1051 wildparams |= 2;
1052
1053 if (wildreturn && !wildparams)
1054 {
1055 ::error(loc, "inout on return means inout must be on a parameter as well for %s", mtype->toChars());
1056 errors = true;
1057 }
1058 tf->iswild = wildparams;
1059
1060 if (tf->isproperty && (tf->parameterList.varargs != VARARGnone || tf->parameterList.length() > 2))
1061 {
1062 ::error(loc, "properties can only have zero, one, or two parameter");
1063 errors = true;
1064 }
1065
1066 if (tf->parameterList.varargs == VARARGvariadic && tf->linkage != LINKd && tf->parameterList.length() == 0)
1067 {
1068 ::error(loc, "variadic functions with non-D linkage must have at least one parameter");
1069 errors = true;
1070 }
1071
1072 if (errors)
1073 return error();
1074
1075 if (tf->next)
1076 tf->deco = tf->merge()->deco;
1077
1078 /* Don't return merge(), because arg identifiers and default args
1079 * can be different
1080 * even though the types match
1081 */
1082 result = tf;
1083 }
1084
1085 void visit(TypeDelegate *mtype)
1086 {
1087 //printf("TypeDelegate::semantic() %s\n", mtype->toChars());
1088 if (mtype->deco) // if semantic() already run
1089 {
1090 //printf("already done\n");
1091 result = mtype;
1092 return;
1093 }
1094 mtype->next = typeSemantic(mtype->next, loc,sc);
1095 if (mtype->next->ty != Tfunction)
1096 return error();
1097
1098 /* In order to deal with Bugzilla 4028, perhaps default arguments should
1099 * be removed from next before the merge.
1100 */
1101
1102 /* Don't return merge(), because arg identifiers and default args
1103 * can be different
1104 * even though the types match
1105 */
1106 mtype->deco = mtype->merge()->deco;
1107 result = mtype;
1108 }
1109
1110 void visit(TypeTraits *mtype)
1111 {
1112 if (mtype->ty == Terror)
1113 {
1114 result = mtype;
1115 return;
1116 }
1117
1118 const int inAlias = (sc->flags & SCOPEalias) != 0;
1119 if (mtype->exp->ident != Id::allMembers &&
1120 mtype->exp->ident != Id::derivedMembers &&
1121 mtype->exp->ident != Id::getMember &&
1122 mtype->exp->ident != Id::parent &&
1123 mtype->exp->ident != Id::child &&
1124 mtype->exp->ident != Id::toType &&
1125 mtype->exp->ident != Id::getOverloads &&
1126 mtype->exp->ident != Id::getVirtualFunctions &&
1127 mtype->exp->ident != Id::getVirtualMethods &&
1128 mtype->exp->ident != Id::getAttributes &&
1129 mtype->exp->ident != Id::getUnitTests &&
1130 mtype->exp->ident != Id::getAliasThis)
1131 {
1132 static const char *ctxt[2] = {"as type", "in alias"};
1133 ::error(loc, "trait `%s` is either invalid or not supported %s",
1134 mtype->exp->ident->toChars(), ctxt[inAlias]);
1135 mtype->ty = Terror;
1136 result = mtype;
1137 return;
1138 }
1139
1140 if (Expression *e = semanticTraits(mtype->exp, sc))
1141 {
1142 switch (e->op)
1143 {
1144 case TOKdotvar:
1145 mtype->sym = ((DotVarExp *)e)->var;
1146 break;
1147 case TOKvar:
1148 mtype->sym = ((VarExp *)e)->var;
1149 break;
1150 case TOKfunction:
1151 {
1152 FuncExp *fe = (FuncExp *)e;
1153 if (fe->td)
1154 mtype->sym = fe->td;
1155 else
1156 mtype->sym = fe->fd;
1157 break;
1158 }
1159 case TOKdottd:
1160 mtype->sym = ((DotTemplateExp*)e)->td;
1161 break;
1162 case TOKdsymbol:
1163 mtype->sym = ((DsymbolExp *)e)->s;
1164 break;
1165 case TOKtemplate:
1166 mtype->sym = ((TemplateExp *)e)->td;
1167 break;
1168 case TOKscope:
1169 mtype->sym = ((ScopeExp *)e)->sds;
1170 break;
1171 case TOKtuple:
1172 {
1173 TupleExp *te = e->toTupleExp();
1174 Objects *elems = new Objects;
1175 elems->setDim(te->exps->length);
1176 for (size_t i = 0; i < elems->length; i++)
1177 {
1178 Expression *src = (*te->exps)[i];
1179 switch (src->op)
1180 {
1181 case TOKtype:
1182 (*elems)[i] = ((TypeExp *)src)->type;
1183 break;
1184 case TOKdottype:
1185 (*elems)[i] = ((DotTypeExp *)src)->type;
1186 break;
1187 case TOKoverloadset:
1188 (*elems)[i] = ((OverExp *)src)->type;
1189 break;
1190 default:
1191 if (Dsymbol *sym = isDsymbol(src))
1192 (*elems)[i] = sym;
1193 else
1194 (*elems)[i] = src;
1195 }
1196 }
1197 TupleDeclaration *td = new TupleDeclaration(e->loc,
1198 Identifier::generateId("__aliastup"), elems);
1199 mtype->sym = td;
1200 break;
1201 }
1202 case TOKdottype:
1203 result = isType(((DotTypeExp *)e)->sym);
1204 break;
1205 case TOKtype:
1206 result = ((TypeExp *)e)->type;
1207 break;
1208 case TOKoverloadset:
1209 result = ((OverExp *)e)->type;
1210 break;
1211 default:
1212 break;
1213 }
1214 }
1215
1216 if (result)
1217 result = result->addMod(mtype->mod);
1218 if (!inAlias && !result)
1219 {
1220 if (!global.errors)
1221 ::error(loc, "`%s` does not give a valid type", mtype->toChars());
1222 return error();
1223 }
1224 }
1225
1226 void visit(TypeIdentifier *mtype)
1227 {
1228 Type *t;
1229 Expression *e;
1230 Dsymbol *s;
1231
1232 //printf("TypeIdentifier::semantic(%s)\n", mtype->toChars());
1233 mtype->resolve(loc, sc, &e, &t, &s);
1234 if (t)
1235 {
1236 //printf("\tit's a type %d, %s, %s\n", t->ty, t->toChars(), t->deco);
1237 t = t->addMod(mtype->mod);
1238 }
1239 else
1240 {
1241 if (s)
1242 {
1243 s->error(loc, "is used as a type");
1244 //halt();
1245 }
1246 else
1247 ::error(loc, "%s is used as a type", mtype->toChars());
1248 return error();
1249 }
1250 //t->print();
1251 result = t;
1252 }
1253
1254 void visit(TypeInstance *mtype)
1255 {
1256 Type *t;
1257 Expression *e;
1258 Dsymbol *s;
1259
1260 //printf("TypeInstance::semantic(%p, %s)\n", this, mtype->toChars());
1261 {
1262 unsigned errors = global.errors;
1263 mtype->resolve(loc, sc, &e, &t, &s);
1264 // if we had an error evaluating the symbol, suppress further errors
1265 if (!t && errors != global.errors)
1266 return error();
1267 }
1268
1269 if (!t)
1270 {
1271 if (!e && s && s->errors)
1272 {
1273 // if there was an error evaluating the symbol, it might actually
1274 // be a type. Avoid misleading error messages.
1275 ::error(loc, "%s had previous errors", mtype->toChars());
1276 }
1277 else
1278 ::error(loc, "%s is used as a type", mtype->toChars());
1279 return error();
1280 }
1281 result = t;
1282 }
1283
1284 void visit(TypeTypeof *mtype)
1285 {
1286 //printf("TypeTypeof::semantic() %s\n", mtype->toChars());
1287
1288 Expression *e;
1289 Type *t;
1290 Dsymbol *s;
1291 mtype->resolve(loc, sc, &e, &t, &s);
1292 if (s && (t = s->getType()) != NULL)
1293 t = t->addMod(mtype->mod);
1294 if (!t)
1295 {
1296 ::error(loc, "%s is used as a type", mtype->toChars());
1297 return error();
1298 }
1299 result = t;
1300 }
1301
1302 void visit(TypeReturn *mtype)
1303 {
1304 //printf("TypeReturn::semantic() %s\n", mtype->toChars());
1305
1306 Expression *e;
1307 Type *t;
1308 Dsymbol *s;
1309 mtype->resolve(loc, sc, &e, &t, &s);
1310 if (s && (t = s->getType()) != NULL)
1311 t = t->addMod(mtype->mod);
1312 if (!t)
1313 {
1314 ::error(loc, "%s is used as a type", mtype->toChars());
1315 return error();
1316 }
1317 result = t;
1318 }
1319
1320 void visit(TypeEnum *mtype)
1321 {
1322 //printf("TypeEnum::semantic() %s\n", mtype->toChars());
1323 result = mtype->deco ? mtype : mtype->merge();
1324 }
1325
1326 void visit(TypeStruct *mtype)
1327 {
1328 //printf("TypeStruct::semantic('%s')\n", mtype->toChars());
1329 if (mtype->deco)
1330 {
1331 if (sc && sc->cppmangle != CPPMANGLEdefault)
1332 {
1333 if (mtype->cppmangle == CPPMANGLEdefault)
1334 mtype->cppmangle = sc->cppmangle;
1335 else
1336 assert(mtype->cppmangle == sc->cppmangle);
1337 }
1338 result = mtype;
1339 return;
1340 }
1341
1342 /* Don't semantic for sym because it should be deferred until
1343 * sizeof needed or its members accessed.
1344 */
1345 // instead, parent should be set correctly
1346 assert(mtype->sym->parent);
1347
1348 if (mtype->sym->type->ty == Terror)
1349 return error();
1350 if (sc)
1351 mtype->cppmangle = sc->cppmangle;
1352 result = mtype->merge();
1353 }
1354
1355 void visit(TypeClass *mtype)
1356 {
1357 //printf("TypeClass::semantic(%s)\n", mtype->toChars());
1358 if (mtype->deco)
1359 {
1360 if (sc && sc->cppmangle != CPPMANGLEdefault)
1361 {
1362 if (mtype->cppmangle == CPPMANGLEdefault)
1363 mtype->cppmangle = sc->cppmangle;
1364 else
1365 assert(mtype->cppmangle == sc->cppmangle);
1366 }
1367 result = mtype;
1368 return;
1369 }
1370
1371 /* Don't semantic for sym because it should be deferred until
1372 * sizeof needed or its members accessed.
1373 */
1374 // instead, parent should be set correctly
1375 assert(mtype->sym->parent);
1376
1377 if (mtype->sym->type->ty == Terror)
1378 return error();
1379 if (sc)
1380 mtype->cppmangle = sc->cppmangle;
1381 result = mtype->merge();
1382 }
1383
1384 void visit(TypeTuple *mtype)
1385 {
1386 //printf("TypeTuple::semantic(this = %p)\n", this);
1387 //printf("TypeTuple::semantic() %p, %s\n", this, mtype->toChars());
1388 if (!mtype->deco)
1389 mtype->deco = mtype->merge()->deco;
1390
1391 /* Don't return merge(), because a tuple with one type has the
1392 * same deco as that type.
1393 */
1394 result = mtype;
1395 }
1396
1397 void visit(TypeSlice *mtype)
1398 {
1399 //printf("TypeSlice::semantic() %s\n", mtype->toChars());
1400 Type *tn = typeSemantic(mtype->next, loc, sc);
1401 //printf("next: %s\n", tn->toChars());
1402
1403 Type *tbn = tn->toBasetype();
1404 if (tbn->ty != Ttuple)
1405 {
1406 ::error(loc, "can only slice tuple types, not %s", tbn->toChars());
1407 return error();
1408 }
1409 TypeTuple *tt = (TypeTuple *)tbn;
1410
1411 mtype->lwr = semanticLength(sc, tbn, mtype->lwr);
1412 mtype->lwr = mtype->lwr->ctfeInterpret();
1413 uinteger_t i1 = mtype->lwr->toUInteger();
1414
1415 mtype->upr = semanticLength(sc, tbn, mtype->upr);
1416 mtype->upr = mtype->upr->ctfeInterpret();
1417 uinteger_t i2 = mtype->upr->toUInteger();
1418
1419 if (!(i1 <= i2 && i2 <= tt->arguments->length))
1420 {
1421 ::error(loc, "slice `[%llu..%llu]` is out of range of [0..%llu]",
1422 (unsigned long long)i1, (unsigned long long)i2, (unsigned long long)tt->arguments->length);
1423 return error();
1424 }
1425
1426 mtype->next = tn;
1427 mtype->transitive();
1428
1429 Parameters *args = new Parameters;
1430 args->reserve((size_t)(i2 - i1));
1431 for (size_t i = (size_t)i1; i < (size_t)i2; i++)
1432 {
1433 Parameter *arg = (*tt->arguments)[i];
1434 args->push(arg);
1435 }
1436 Type *t = new TypeTuple(args);
1437 result = typeSemantic(t, loc, sc);
1438 }
1439
1440 void visit(TypeMixin *mtype)
1441 {
1442 //printf("TypeMixin::semantic() %s\n", mtype->toChars());
1443
1444 Expression *e = NULL;
1445 Type *t = NULL;
1446 Dsymbol *s = NULL;
1447 mtype->resolve(loc, sc, &e, &t, &s);
1448
1449 if (t && t->ty != Terror)
1450 {
1451 result = t;
1452 return;
1453 }
1454
1455 ::error(mtype->loc, "`mixin(%s)` does not give a valid type", mtype->obj->toChars());
1456 return error();
1457 }
1458 };
1459 TypeSemanticVisitor v(loc, sc);
1460 type->accept(&v);
1461 return v.result;
1462 }
1463