2 /* Compiler implementation of the D programming language
3 * Copyright (C) 1999-2018 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
10 #include "root/checkedint.h"
13 #include "expression.h"
14 #include "statement.h"
15 #include "declaration.h"
16 #include "aggregate.h"
22 FuncDeclaration
*isFuncAddress(Expression
*e
, bool *hasOverloads
= NULL
);
23 Expression
*semantic(Expression
*e
, Scope
*sc
);
24 Initializer
*inferType(Initializer
*init
, Scope
*sc
);
25 Initializer
*semantic(Initializer
*init
, Scope
*sc
, Type
*t
, NeedInterpret needInterpret
);
26 bool hasNonConstPointers(Expression
*e
);
28 class InitializerSemanticVisitor
: public Visitor
34 NeedInterpret needInterpret
;
36 InitializerSemanticVisitor(Scope
*sc
, Type
*t
, NeedInterpret needInterpret
)
41 this->needInterpret
= needInterpret
;
44 void visit(ErrorInitializer
*i
)
46 //printf("ErrorInitializer::semantic(t = %p)\n", t);
50 void visit(VoidInitializer
*i
)
52 //printf("VoidInitializer::semantic(t = %p)\n", t);
57 void visit(StructInitializer
*i
)
59 //printf("StructInitializer::semantic(t = %s) %s\n", t->toChars(), toChars());
61 if (t
->ty
== Tsarray
&& t
->nextOf()->toBasetype()->ty
== Tstruct
)
62 t
= t
->nextOf()->toBasetype();
65 StructDeclaration
*sd
= ((TypeStruct
*)t
)->sym
;
68 error(i
->loc
, "%s %s has constructors, cannot use { initializers }, use %s( initializers ) instead",
69 sd
->kind(), sd
->toChars(), sd
->toChars());
70 result
= new ErrorInitializer();
74 if (sd
->sizeok
!= SIZEOKdone
)
76 result
= new ErrorInitializer();
79 size_t nfields
= sd
->fields
.dim
- sd
->isNested();
81 //expandTuples for non-identity arguments?
83 Expressions
*elements
= new Expressions();
84 elements
->setDim(nfields
);
85 for (size_t j
= 0; j
< elements
->dim
; j
++)
86 (*elements
)[j
] = NULL
;
88 // Run semantic for explicitly given initializers
89 // TODO: this part is slightly different from StructLiteralExp::semantic.
91 for (size_t fieldi
= 0, j
= 0; j
< i
->field
.dim
; j
++)
93 if (Identifier
*id
= i
->field
[j
])
95 Dsymbol
*s
= sd
->search(i
->loc
, id
);
98 s
= sd
->search_correct(id
);
100 error(i
->loc
, "'%s' is not a member of '%s', did you mean %s '%s'?",
101 id
->toChars(), sd
->toChars(), s
->kind(), s
->toChars());
103 error(i
->loc
, "'%s' is not a member of '%s'", id
->toChars(), sd
->toChars());
104 result
= new ErrorInitializer();
109 // Find out which field index it is
110 for (fieldi
= 0; 1; fieldi
++)
112 if (fieldi
>= nfields
)
114 error(i
->loc
, "%s.%s is not a per-instance initializable field",
115 sd
->toChars(), s
->toChars());
116 result
= new ErrorInitializer();
119 if (s
== sd
->fields
[fieldi
])
123 else if (fieldi
>= nfields
)
125 error(i
->loc
, "too many initializers for %s", sd
->toChars());
126 result
= new ErrorInitializer();
130 VarDeclaration
*vd
= sd
->fields
[fieldi
];
131 if ((*elements
)[fieldi
])
133 error(i
->loc
, "duplicate initializer for field '%s'", vd
->toChars());
137 for (size_t k
= 0; k
< nfields
; k
++)
139 VarDeclaration
*v2
= sd
->fields
[k
];
140 if (vd
->isOverlappedWith(v2
) && (*elements
)[k
])
142 error(i
->loc
, "overlapping initialization for field %s and %s",
143 v2
->toChars(), vd
->toChars());
150 Initializer
*iz
= i
->value
[j
];
151 iz
= ::semantic(iz
, sc
, vd
->type
->addMod(t
->mod
), needInterpret
);
152 Expression
*ex
= initializerToExpression(iz
);
153 if (ex
->op
== TOKerror
)
159 (*elements
)[fieldi
] = doCopyOrMove(sc
, ex
);
164 result
= new ErrorInitializer();
168 StructLiteralExp
*sle
= new StructLiteralExp(i
->loc
, sd
, elements
, t
);
169 if (!sd
->fill(i
->loc
, elements
, false))
171 result
= new ErrorInitializer();
176 ExpInitializer
*ie
= new ExpInitializer(i
->loc
, sle
);
177 result
= ::semantic(ie
, sc
, t
, needInterpret
);
180 else if ((t
->ty
== Tdelegate
|| (t
->ty
== Tpointer
&& t
->nextOf()->ty
== Tfunction
)) && i
->value
.dim
== 0)
182 TOK tok
= (t
->ty
== Tdelegate
) ? TOKdelegate
: TOKfunction
;
183 /* Rewrite as empty delegate literal { }
185 Parameters
*parameters
= new Parameters
;
186 Type
*tf
= new TypeFunction(parameters
, NULL
, 0, LINKd
);
187 FuncLiteralDeclaration
*fd
= new FuncLiteralDeclaration(i
->loc
, Loc(), tf
, tok
, NULL
);
188 fd
->fbody
= new CompoundStatement(i
->loc
, new Statements());
190 Expression
*e
= new FuncExp(i
->loc
, fd
);
191 ExpInitializer
*ie
= new ExpInitializer(i
->loc
, e
);
192 result
= ::semantic(ie
, sc
, t
, needInterpret
);
196 error(i
->loc
, "a struct is not a valid initializer for a %s", t
->toChars());
197 result
= new ErrorInitializer();
200 void visit(ArrayInitializer
*i
)
203 const unsigned amax
= 0x80000000;
206 //printf("ArrayInitializer::semantic(%s)\n", t->toChars());
207 if (i
->sem
) // if semantic() already run
221 t
= ((TypeVector
*)t
)->basetype
;
225 case Tstruct
: // consider implicit constructor call
228 // note: MyStruct foo = [1:2, 3:4] is correct code if MyStruct has a this(int[int])
229 if (t
->ty
== Taarray
|| i
->isAssociativeArray())
230 e
= i
->toAssocArrayLiteral();
232 e
= initializerToExpression(i
);
233 if (!e
) // Bugzilla 13987
235 error(i
->loc
, "cannot use array to initialize %s", t
->toChars());
238 ExpInitializer
*ei
= new ExpInitializer(e
->loc
, e
);
239 result
= ::semantic(ei
, sc
, t
, needInterpret
);
243 if (t
->nextOf()->ty
!= Tfunction
)
248 error(i
->loc
, "cannot use array to initialize %s", t
->toChars());
255 for (size_t j
= 0; j
< i
->index
.dim
; j
++)
257 Expression
*idx
= i
->index
[j
];
260 sc
= sc
->startCTFE();
261 idx
= ::semantic(idx
, sc
);
263 idx
= idx
->ctfeInterpret();
265 const uinteger_t idxvalue
= idx
->toInteger();
266 if (idxvalue
>= amax
)
268 error(i
->loc
, "array index %llu overflow", (ulonglong
)idxvalue
);
271 length
= (unsigned)idx
->toInteger();
272 if (idx
->op
== TOKerror
)
276 Initializer
*val
= i
->value
[j
];
277 ExpInitializer
*ei
= val
->isExpInitializer();
279 ei
->expandTuples
= true;
280 val
= ::semantic(val
, sc
, t
->nextOf(), needInterpret
);
281 if (val
->isErrorInitializer())
284 ei
= val
->isExpInitializer();
285 // found a tuple, expand it
286 if (ei
&& ei
->exp
->op
== TOKtuple
)
288 TupleExp
*te
= (TupleExp
*)ei
->exp
;
292 for (size_t k
= 0; k
< te
->exps
->dim
; ++k
)
294 Expression
*e
= (*te
->exps
)[k
];
295 i
->index
.insert(j
+ k
, (Expression
*)NULL
);
296 i
->value
.insert(j
+ k
, new ExpInitializer(e
->loc
, e
));
309 error(i
->loc
, "array dimension overflow");
315 if (t
->ty
== Tsarray
)
317 uinteger_t edim
= ((TypeSArray
*)t
)->dim
->toInteger();
320 error(i
->loc
, "array initializer has %u elements, but array length is %llu", i
->dim
, (ulonglong
)edim
);
328 d_uns64 sz
= t
->nextOf()->size();
329 bool overflow
= false;
330 const d_uns64 max
= mulu((d_uns64
)i
->dim
, sz
, overflow
);
331 if (overflow
|| max
> amax
)
333 error(i
->loc
, "array dimension %llu exceeds max of %llu", (ulonglong
)i
->dim
, (ulonglong
)(amax
/ sz
));
341 result
= new ErrorInitializer();
344 void visit(ExpInitializer
*i
)
346 //printf("ExpInitializer::semantic(%s), type = %s\n", i->exp->toChars(), t->toChars());
347 if (needInterpret
) sc
= sc
->startCTFE();
348 i
->exp
= ::semantic(i
->exp
, sc
);
349 i
->exp
= resolveProperties(sc
, i
->exp
);
350 if (needInterpret
) sc
= sc
->endCTFE();
351 if (i
->exp
->op
== TOKerror
)
353 result
= new ErrorInitializer();
357 unsigned int olderrors
= global
.errors
;
360 // If the result will be implicitly cast, move the cast into CTFE
361 // to avoid premature truncation of polysemous types.
362 // eg real [] x = [1.1, 2.2]; should use real precision.
363 if (i
->exp
->implicitConvTo(t
))
365 i
->exp
= i
->exp
->implicitCastTo(sc
, t
);
367 if (!global
.gag
&& olderrors
!= global
.errors
)
372 i
->exp
= i
->exp
->ctfeInterpret();
376 i
->exp
= i
->exp
->optimize(WANTvalue
);
378 if (!global
.gag
&& olderrors
!= global
.errors
)
380 result
= i
; // Failed, suppress duplicate error messages
384 if (i
->exp
->type
->ty
== Ttuple
&& ((TypeTuple
*)i
->exp
->type
)->arguments
->dim
== 0)
386 Type
*et
= i
->exp
->type
;
387 i
->exp
= new TupleExp(i
->exp
->loc
, new Expressions());
390 if (i
->exp
->op
== TOKtype
)
392 i
->exp
->error("initializer must be an expression, not '%s'", i
->exp
->toChars());
393 result
= new ErrorInitializer();
397 // Make sure all pointers are constants
398 if (needInterpret
&& hasNonConstPointers(i
->exp
))
400 i
->exp
->error("cannot use non-constant CTFE pointer in an initializer '%s'", i
->exp
->toChars());
401 result
= new ErrorInitializer();
405 Type
*tb
= t
->toBasetype();
406 Type
*ti
= i
->exp
->type
->toBasetype();
408 if (i
->exp
->op
== TOKtuple
&& i
->expandTuples
&& !i
->exp
->implicitConvTo(t
))
410 result
= new ExpInitializer(i
->loc
, i
->exp
);
414 /* Look for case of initializing a static array with a too-short
415 * string literal, such as:
416 * char[5] foo = "abc";
417 * Allow this by doing an explicit cast, which will lengthen the string
420 if (i
->exp
->op
== TOKstring
&& tb
->ty
== Tsarray
)
422 StringExp
*se
= (StringExp
*)i
->exp
;
423 Type
*typeb
= se
->type
->toBasetype();
424 TY tynto
= tb
->nextOf()->ty
;
425 if (!se
->committed
&&
426 (typeb
->ty
== Tarray
|| typeb
->ty
== Tsarray
) &&
427 (tynto
== Tchar
|| tynto
== Twchar
|| tynto
== Tdchar
) &&
428 se
->numberOfCodeUnits(tynto
) < ((TypeSArray
*)tb
)->dim
->toInteger())
430 i
->exp
= se
->castTo(sc
, t
);
435 // Look for implicit constructor call
436 if (tb
->ty
== Tstruct
&&
437 !(ti
->ty
== Tstruct
&& tb
->toDsymbol(sc
) == ti
->toDsymbol(sc
)) &&
438 !i
->exp
->implicitConvTo(t
))
440 StructDeclaration
*sd
= ((TypeStruct
*)tb
)->sym
;
443 // Rewrite as S().ctor(exp)
445 e
= new StructLiteralExp(i
->loc
, sd
, NULL
);
446 e
= new DotIdExp(i
->loc
, e
, Id::ctor
);
447 e
= new CallExp(i
->loc
, e
, i
->exp
);
448 e
= ::semantic(e
, sc
);
450 i
->exp
= e
->ctfeInterpret();
452 i
->exp
= e
->optimize(WANTvalue
);
456 // Look for the case of statically initializing an array
457 // with a single member.
458 if (tb
->ty
== Tsarray
&&
459 !tb
->nextOf()->equals(ti
->toBasetype()->nextOf()) &&
460 i
->exp
->implicitConvTo(tb
->nextOf())
463 /* If the variable is not actually used in compile time, array creation is
464 * redundant. So delay it until invocation of toExpression() or toDt().
469 if (i
->exp
->implicitConvTo(t
))
471 i
->exp
= i
->exp
->implicitCastTo(sc
, t
);
475 // Look for mismatch of compile-time known length to emit
476 // better diagnostic message, as same as AssignExp::semantic.
477 if (tb
->ty
== Tsarray
&&
478 i
->exp
->implicitConvTo(tb
->nextOf()->arrayOf()) > MATCHnomatch
)
480 uinteger_t dim1
= ((TypeSArray
*)tb
)->dim
->toInteger();
481 uinteger_t dim2
= dim1
;
482 if (i
->exp
->op
== TOKarrayliteral
)
484 ArrayLiteralExp
*ale
= (ArrayLiteralExp
*)i
->exp
;
485 dim2
= ale
->elements
? ale
->elements
->dim
: 0;
487 else if (i
->exp
->op
== TOKslice
)
489 Type
*tx
= toStaticArrayType((SliceExp
*)i
->exp
);
491 dim2
= ((TypeSArray
*)tx
)->dim
->toInteger();
495 i
->exp
->error("mismatched array lengths, %d and %d", (int)dim1
, (int)dim2
);
496 i
->exp
= new ErrorExp();
499 i
->exp
= i
->exp
->implicitCastTo(sc
, t
);
502 if (i
->exp
->op
== TOKerror
)
508 i
->exp
= i
->exp
->ctfeInterpret();
510 i
->exp
= i
->exp
->optimize(WANTvalue
);
511 //printf("-ExpInitializer::semantic(): "); i->exp->print();
516 // Performs semantic analisys on Initializer AST nodes
517 Initializer
*semantic(Initializer
*init
, Scope
*sc
, Type
*t
, NeedInterpret needInterpret
)
519 InitializerSemanticVisitor v
= InitializerSemanticVisitor(sc
, t
, needInterpret
);
524 class InferTypeVisitor
: public Visitor
530 InferTypeVisitor(Scope
*sc
)
536 void visit(ErrorInitializer
*i
)
541 void visit(VoidInitializer
*i
)
543 error(i
->loc
, "cannot infer type from void initializer");
544 result
= new ErrorInitializer();
547 void visit(StructInitializer
*i
)
549 error(i
->loc
, "cannot infer type from struct initializer");
550 result
= new ErrorInitializer();
553 void visit(ArrayInitializer
*init
)
555 //printf("ArrayInitializer::inferType() %s\n", init->toChars());
556 Expressions
*keys
= NULL
;
558 if (init
->isAssociativeArray())
560 keys
= new Expressions();
561 keys
->setDim(init
->value
.dim
);
562 values
= new Expressions();
563 values
->setDim(init
->value
.dim
);
565 for (size_t i
= 0; i
< init
->value
.dim
; i
++)
567 Expression
*e
= init
->index
[i
];
572 Initializer
*iz
= init
->value
[i
];
575 iz
= inferType(iz
, sc
);
576 if (iz
->isErrorInitializer())
581 assert(iz
->isExpInitializer());
582 (*values
)[i
] = ((ExpInitializer
*)iz
)->exp
;
583 assert((*values
)[i
]->op
!= TOKerror
);
586 Expression
*e
= new AssocArrayLiteralExp(init
->loc
, keys
, values
);
587 ExpInitializer
*ei
= new ExpInitializer(init
->loc
, e
);
588 result
= inferType(ei
, sc
);
593 Expressions
*elements
= new Expressions();
594 elements
->setDim(init
->value
.dim
);
597 for (size_t i
= 0; i
< init
->value
.dim
; i
++)
599 assert(!init
->index
[i
]); // already asserted by isAssociativeArray()
601 Initializer
*iz
= init
->value
[i
];
604 iz
= inferType(iz
, sc
);
605 if (iz
->isErrorInitializer())
610 assert(iz
->isExpInitializer());
611 (*elements
)[i
] = ((ExpInitializer
*)iz
)->exp
;
612 assert((*elements
)[i
]->op
!= TOKerror
);
615 Expression
*e
= new ArrayLiteralExp(init
->loc
, elements
);
616 ExpInitializer
*ei
= new ExpInitializer(init
->loc
, e
);
617 result
= inferType(ei
, sc
);
625 error(init
->loc
, "not an associative array initializer");
629 error(init
->loc
, "cannot infer type from array initializer");
631 result
= new ErrorInitializer();
634 void visit(ExpInitializer
*init
)
636 //printf("ExpInitializer::inferType() %s\n", init->toChars());
637 init
->exp
= ::semantic(init
->exp
, sc
);
638 init
->exp
= resolveProperties(sc
, init
->exp
);
640 if (init
->exp
->op
== TOKscope
)
642 ScopeExp
*se
= (ScopeExp
*)init
->exp
;
643 TemplateInstance
*ti
= se
->sds
->isTemplateInstance();
644 if (ti
&& ti
->semanticRun
== PASSsemantic
&& !ti
->aliasdecl
)
645 se
->error("cannot infer type from %s %s, possible circular dependency", se
->sds
->kind(), se
->toChars());
647 se
->error("cannot infer type from %s %s", se
->sds
->kind(), se
->toChars());
648 result
= new ErrorInitializer();
652 // Give error for overloaded function addresses
653 bool hasOverloads
= false;
654 if (FuncDeclaration
*f
= isFuncAddress(init
->exp
, &hasOverloads
))
656 if (f
->checkForwardRef(init
->loc
))
658 result
= new ErrorInitializer();
662 if (hasOverloads
&& !f
->isUnique())
664 init
->exp
->error("cannot infer type from overloaded function symbol %s", init
->exp
->toChars());
665 result
= new ErrorInitializer();
669 if (init
->exp
->op
== TOKaddress
)
671 AddrExp
*ae
= (AddrExp
*)init
->exp
;
672 if (ae
->e1
->op
== TOKoverloadset
)
674 init
->exp
->error("cannot infer type from overloaded function symbol %s", init
->exp
->toChars());
675 result
= new ErrorInitializer();
680 if (init
->exp
->op
== TOKerror
)
682 result
= new ErrorInitializer();
685 if (!init
->exp
->type
)
687 result
= new ErrorInitializer();
694 /* Translates to an expression to infer type.
695 * Returns ExpInitializer or ErrorInitializer.
697 Initializer
*inferType(Initializer
*init
, Scope
*sc
)
699 InferTypeVisitor v
= InferTypeVisitor(sc
);
704 class InitToExpressionVisitor
: public Visitor
710 InitToExpressionVisitor(Type
*itype
)
716 void visit(ErrorInitializer
*)
718 result
= new ErrorExp();
721 void visit(VoidInitializer
*)
726 /***************************************
727 * This works by transforming a struct initializer into
728 * a struct literal. In the future, the two should be the
731 void visit(StructInitializer
*)
733 // cannot convert to an expression without target 'ad'
737 /********************************
738 * If possible, convert array initializer to array literal.
739 * Otherwise return NULL.
742 void visit(ArrayInitializer
*init
)
744 //printf("ArrayInitializer::toExpression(), dim = %d\n", init->dim);
745 //static int i; if (++i == 2) halt();
747 Expressions
*elements
;
749 const unsigned amax
= 0x80000000;
753 if (init
->type
== Type::terror
)
755 result
= new ErrorExp();
759 t
= init
->type
->toBasetype();
763 t
= ((TypeVector
*)t
)->basetype
;
768 uinteger_t adim
= ((TypeSArray
*)t
)->dim
->toInteger();
771 edim
= (unsigned)adim
;
786 edim
= (unsigned)init
->value
.dim
;
787 for (size_t i
= 0, j
= 0; i
< init
->value
.dim
; i
++, j
++)
791 if (init
->index
[i
]->op
== TOKint64
)
793 const uinteger_t idxval
= init
->index
[i
]->toInteger();
802 edim
= (unsigned)(j
+ 1);
806 elements
= new Expressions();
807 elements
->setDim(edim
);
809 for (size_t i
= 0, j
= 0; i
< init
->value
.dim
; i
++, j
++)
812 j
= (size_t)(init
->index
[i
])->toInteger();
814 Initializer
*iz
= init
->value
[i
];
817 Expression
*ex
= initializerToExpression(iz
);
825 /* Fill in any missing elements with the default initializer
828 Expression
*_init
= NULL
;
829 for (size_t i
= 0; i
< edim
; i
++)
836 _init
= ((TypeNext
*)t
)->next
->defaultInit();
837 (*elements
)[i
] = _init
;
841 /* Expand any static array initializers that are a single expression
842 * into an array of them
846 Type
*tn
= t
->nextOf()->toBasetype();
847 if (tn
->ty
== Tsarray
)
849 size_t dim
= ((TypeSArray
*)tn
)->dim
->toInteger();
850 Type
*te
= tn
->nextOf()->toBasetype();
851 for (size_t i
= 0; i
< elements
->dim
; i
++)
853 Expression
*e
= (*elements
)[i
];
854 if (te
->equals(e
->type
))
856 Expressions
*elements2
= new Expressions();
857 elements2
->setDim(dim
);
858 for (size_t j
= 0; j
< dim
; j
++)
860 e
= new ArrayLiteralExp(e
->loc
, elements2
);
868 /* If any elements are errors, then the whole thing is an error
870 for (size_t i
= 0; i
< edim
; i
++)
872 Expression
*e
= (*elements
)[i
];
873 if (e
->op
== TOKerror
)
880 Expression
*e
= new ArrayLiteralExp(init
->loc
, elements
);
881 e
->type
= init
->type
;
890 void visit(ExpInitializer
*i
)
894 //printf("ExpInitializer::toExpression(t = %s) exp = %s\n", itype->toChars(), i->exp->toChars());
895 Type
*tb
= itype
->toBasetype();
896 Expression
*e
= (i
->exp
->op
== TOKconstruct
|| i
->exp
->op
== TOKblit
) ? ((AssignExp
*)i
->exp
)->e2
: i
->exp
;
897 if (tb
->ty
== Tsarray
&& e
->implicitConvTo(tb
->nextOf()))
899 TypeSArray
*tsa
= (TypeSArray
*)tb
;
900 size_t d
= (size_t)tsa
->dim
->toInteger();
901 Expressions
*elements
= new Expressions();
903 for (size_t i
= 0; i
< d
; i
++)
905 ArrayLiteralExp
*ae
= new ArrayLiteralExp(e
->loc
, elements
);
915 Expression
*initializerToExpression(Initializer
*i
, Type
*t
)
917 InitToExpressionVisitor v
= InitToExpressionVisitor(t
);