blob: e855840ea5dffd1a955d09f76252e8c5ad5dbadb [file] [log] [blame]
Steve Naroffc4d4a482008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for initializers.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +000015#include "clang/Parse/Designator.h"
Steve Naroffc4d4a482008-05-01 22:18:59 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/Expr.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000018#include "clang/Basic/Diagnostic.h"
Douglas Gregor8acb7272008-12-11 16:49:14 +000019#include <algorithm> // for std::count_if
20#include <functional> // for std::mem_fun
Steve Naroffc4d4a482008-05-01 22:18:59 +000021
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +000022using namespace clang;
Steve Naroffc4d4a482008-05-01 22:18:59 +000023
24InitListChecker::InitListChecker(Sema *S, InitListExpr *IL, QualType &T) {
25 hadError = false;
26 SemaRef = S;
Eli Friedmand8535af2008-05-19 20:00:43 +000027
Eli Friedman683cedf2008-05-19 19:16:24 +000028 unsigned newIndex = 0;
Eli Friedmand8535af2008-05-19 20:00:43 +000029
Eli Friedman683cedf2008-05-19 19:16:24 +000030 CheckExplicitInitList(IL, T, newIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +000031}
32
33int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman46f81662008-05-25 13:22:35 +000034 // FIXME: use a proper constant
35 int maxElements = 0x7FFFFFFF;
Chris Lattnera1923f62008-08-04 07:31:14 +000036 if (const ConstantArrayType *CAT =
37 SemaRef->Context.getAsConstantArrayType(DeclType)) {
Steve Naroffc4d4a482008-05-01 22:18:59 +000038 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
39 }
40 return maxElements;
41}
42
43int InitListChecker::numStructUnionElements(QualType DeclType) {
44 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregor39677622008-12-11 20:41:00 +000045 const int InitializableMembers
Douglas Gregor8acb7272008-12-11 16:49:14 +000046 = std::count_if(structDecl->field_begin(), structDecl->field_end(),
47 std::mem_fun(&FieldDecl::getDeclName));
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +000048 if (structDecl->isUnion())
Eli Friedman9f5250b2008-05-25 14:03:31 +000049 return std::min(InitializableMembers, 1);
50 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroffc4d4a482008-05-01 22:18:59 +000051}
52
53void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
54 QualType T, unsigned &Index) {
55 llvm::SmallVector<Expr*, 4> InitExprs;
56 int maxElements = 0;
57
58 if (T->isArrayType())
59 maxElements = numArrayElements(T);
60 else if (T->isStructureType() || T->isUnionType())
61 maxElements = numStructUnionElements(T);
Eli Friedman683cedf2008-05-19 19:16:24 +000062 else if (T->isVectorType())
63 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroffc4d4a482008-05-01 22:18:59 +000064 else
65 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman683cedf2008-05-19 19:16:24 +000066
Eli Friedmanf8df28c2008-05-25 13:49:22 +000067 if (maxElements == 0) {
68 SemaRef->Diag(ParentIList->getInit(Index)->getLocStart(),
69 diag::err_implicit_empty_initializer);
70 hadError = true;
71 return;
72 }
73
Eli Friedman683cedf2008-05-19 19:16:24 +000074 // Check the element types *before* we create the implicit init list;
75 // otherwise, we might end up taking the wrong number of elements
76 unsigned NewIndex = Index;
Douglas Gregor710f6d42009-01-22 23:26:18 +000077 CheckListElementTypes(ParentIList, T, false, NewIndex);
Eli Friedman683cedf2008-05-19 19:16:24 +000078
Steve Naroffc4d4a482008-05-01 22:18:59 +000079 for (int i = 0; i < maxElements; ++i) {
80 // Don't attempt to go past the end of the init list
81 if (Index >= ParentIList->getNumInits())
82 break;
83 Expr* expr = ParentIList->getInit(Index);
84
85 // Add the expr to the new implicit init list and remove if from the old.
86 InitExprs.push_back(expr);
87 ParentIList->removeInit(Index);
88 }
89 // Synthesize an "implicit" InitListExpr (marked by the invalid source locs).
90 InitListExpr *ILE = new InitListExpr(SourceLocation(),
91 &InitExprs[0], InitExprs.size(),
Chris Lattner71ca8c82008-10-26 23:43:26 +000092 SourceLocation(),
93 ParentIList->hadDesignators());
Steve Naroffc4d4a482008-05-01 22:18:59 +000094 ILE->setType(T);
Eli Friedmand8535af2008-05-19 20:00:43 +000095
Steve Naroffc4d4a482008-05-01 22:18:59 +000096 // Modify the parent InitListExpr to point to the implicit InitListExpr.
97 ParentIList->addInit(Index, ILE);
Steve Naroffc4d4a482008-05-01 22:18:59 +000098}
99
Steve Naroff56099522008-05-06 00:23:44 +0000100void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Steve Naroffc4d4a482008-05-01 22:18:59 +0000101 unsigned &Index) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000102 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Eli Friedmand8535af2008-05-19 20:00:43 +0000103
Douglas Gregor710f6d42009-01-22 23:26:18 +0000104 CheckListElementTypes(IList, T, true, Index);
Steve Naroff56099522008-05-06 00:23:44 +0000105 IList->setType(T);
Eli Friedman46f81662008-05-25 13:22:35 +0000106 if (hadError)
107 return;
Eli Friedmand8535af2008-05-19 20:00:43 +0000108
Eli Friedman46f81662008-05-25 13:22:35 +0000109 if (Index < IList->getNumInits()) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000110 // We have leftover initializers
111 if (IList->getNumInits() > 0 &&
112 SemaRef->IsStringLiteralInit(IList->getInit(Index), T)) {
Eli Friedman71de9eb2008-05-19 20:12:18 +0000113 // Special-case
Eli Friedmand8535af2008-05-19 20:00:43 +0000114 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000115 diag::err_excess_initializers_in_char_array_initializer)
116 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000117 hadError = true;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000118 } else if (!T->isIncompleteType()) {
119 // Don't warn for incomplete types, since we'll get an error elsewhere
Eli Friedmand8535af2008-05-19 20:00:43 +0000120 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000121 diag::warn_excess_initializers)
122 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000123 }
124 }
Eli Friedman455f7622008-05-19 20:20:43 +0000125
Eli Friedman46f81662008-05-25 13:22:35 +0000126 if (T->isScalarType())
Chris Lattner9d2cf082008-11-19 05:27:50 +0000127 SemaRef->Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
128 << IList->getSourceRange();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000129}
130
Eli Friedman683cedf2008-05-19 19:16:24 +0000131void InitListChecker::CheckListElementTypes(InitListExpr *IList,
132 QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000133 bool SubobjectIsDesignatorContext,
Eli Friedman683cedf2008-05-19 19:16:24 +0000134 unsigned &Index) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000135 if (DeclType->isScalarType()) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000136 CheckScalarType(IList, DeclType, 0, Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000137 } else if (DeclType->isVectorType()) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000138 CheckVectorType(IList, DeclType, Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000139 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000140 if (DeclType->isStructureType() || DeclType->isUnionType()) {
141 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
142 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
143 SubobjectIsDesignatorContext, Index);
144 } else if (DeclType->isArrayType()) {
145 // FIXME: Is 32 always large enough for array indices?
146 llvm::APSInt Zero(32, false);
147 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index);
148 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000149 else
150 assert(0 && "Aggregate that isn't a function or array?!");
Steve Naroffff5b3a82008-08-10 16:05:48 +0000151 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
152 // This type is invalid, issue a diagnostic.
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000153 Index++;
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000154 SemaRef->Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000155 << DeclType;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000156 hadError = true;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000157 } else {
158 // In C, all types are either scalars or aggregates, but
159 // additional handling is needed here for C++ (and possibly others?).
160 assert(0 && "Unsupported initializer type");
161 }
162}
163
Eli Friedman683cedf2008-05-19 19:16:24 +0000164void InitListChecker::CheckSubElementType(InitListExpr *IList,
165 QualType ElemType,
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000166 Expr *expr,
Eli Friedman683cedf2008-05-19 19:16:24 +0000167 unsigned &Index) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000168 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
169 unsigned newIndex = 0;
170 CheckExplicitInitList(SubInitList, ElemType, newIndex);
171 Index++;
Eli Friedman683cedf2008-05-19 19:16:24 +0000172 } else if (StringLiteral *lit =
173 SemaRef->IsStringLiteralInit(expr, ElemType)) {
174 SemaRef->CheckStringLiteralInit(lit, ElemType);
175 Index++;
Eli Friedmand8535af2008-05-19 20:00:43 +0000176 } else if (ElemType->isScalarType()) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000177 CheckScalarType(IList, ElemType, expr, Index);
Eli Friedman683cedf2008-05-19 19:16:24 +0000178 } else if (expr->getType()->getAsRecordType() &&
Eli Friedman2ccfb512008-06-09 03:52:40 +0000179 SemaRef->Context.typesAreCompatible(
180 expr->getType().getUnqualifiedType(),
181 ElemType.getUnqualifiedType())) {
Eli Friedman683cedf2008-05-19 19:16:24 +0000182 Index++;
183 // FIXME: Add checking
184 } else {
185 CheckImplicitInitList(IList, ElemType, Index);
186 Index++;
187 }
188}
189
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000190void InitListChecker::CheckScalarType(InitListExpr *IList, QualType &DeclType,
191 Expr *expr, unsigned &Index) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000192 if (Index < IList->getNumInits()) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000193 if (!expr)
194 expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000195 if (isa<InitListExpr>(expr)) {
Eli Friedman71de9eb2008-05-19 20:12:18 +0000196 SemaRef->Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000197 diag::err_many_braces_around_scalar_init)
198 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000199 hadError = true;
200 ++Index;
201 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000202 } else if (isa<DesignatedInitExpr>(expr)) {
203 SemaRef->Diag(expr->getSourceRange().getBegin(),
204 diag::err_designator_for_scalar_init)
205 << DeclType << expr->getSourceRange();
206 hadError = true;
207 ++Index;
208 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000209 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000210
Eli Friedmand8535af2008-05-19 20:00:43 +0000211 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000212 if (SemaRef->CheckSingleInitializer(expr, DeclType, false))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000213 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000214 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000215 // The type was promoted, update initializer list.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000216 if (DesignatedInitExpr *DIE
217 = dyn_cast<DesignatedInitExpr>(IList->getInit(Index)))
218 DIE->setInit(expr);
219 else
220 IList->setInit(Index, expr);
221 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000222 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000223 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000224 SemaRef->Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
225 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000226 hadError = true;
227 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000228 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000229}
230
231void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
232 unsigned &Index) {
233 if (Index < IList->getNumInits()) {
234 const VectorType *VT = DeclType->getAsVectorType();
235 int maxElements = VT->getNumElements();
236 QualType elementType = VT->getElementType();
237
238 for (int i = 0; i < maxElements; ++i) {
239 // Don't attempt to go past the end of the init list
240 if (Index >= IList->getNumInits())
241 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000242 CheckSubElementType(IList, elementType, IList->getInit(Index), Index);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000243 }
244 }
245}
246
247void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000248 llvm::APSInt elementIndex,
249 bool SubobjectIsDesignatorContext,
Steve Naroffc4d4a482008-05-01 22:18:59 +0000250 unsigned &Index) {
251 // Check for the special-case of initializing an array with a string.
252 if (Index < IList->getNumInits()) {
253 if (StringLiteral *lit =
254 SemaRef->IsStringLiteralInit(IList->getInit(Index), DeclType)) {
255 SemaRef->CheckStringLiteralInit(lit, DeclType);
256 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000257 return;
258 }
259 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000260 if (const VariableArrayType *VAT =
261 SemaRef->Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000262 // Check for VLAs; in standard C it would be possible to check this
263 // earlier, but I don't know where clang accepts VLAs (gcc accepts
264 // them in all sorts of strange places).
265 SemaRef->Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000266 diag::err_variable_object_no_init)
267 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000268 hadError = true;
269 return;
270 }
271
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000272 // FIXME: Will 32 bits always be enough? I hope so.
273 const unsigned ArraySizeBits = 32;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000274
275 // We might know the maximum number of elements in advance.
276 llvm::APSInt maxElements(ArraySizeBits, 0);
277 bool maxElementsKnown = false;
278 if (const ConstantArrayType *CAT =
279 SemaRef->Context.getAsConstantArrayType(DeclType)) {
280 maxElements = CAT->getSize();
281 maxElementsKnown = true;
282 }
283
Chris Lattnera1923f62008-08-04 07:31:14 +0000284 QualType elementType = SemaRef->Context.getAsArrayType(DeclType)
285 ->getElementType();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000286 while (Index < IList->getNumInits()) {
287 Expr *Init = IList->getInit(Index);
288 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000289 // If we're not the subobject that matches up with the '{' for
290 // the designator, we shouldn't be handling the
291 // designator. Return immediately.
292 if (!SubobjectIsDesignatorContext)
293 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000294
Douglas Gregor710f6d42009-01-22 23:26:18 +0000295 // Handle this designated initializer. elementIndex will be
296 // updated to be the next array element we'll initialize.
297 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
298 DeclType, 0, &elementIndex, Index)) {
299 hadError = true;
300 continue;
301 }
302
303 // If the array is of incomplete type, keep track of the number of
304 // elements in the initializer.
305 if (!maxElementsKnown && elementIndex > maxElements)
306 maxElements = elementIndex;
307
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000308 continue;
309 }
310
311 // If we know the maximum number of elements, and we've already
312 // hit it, stop consuming elements in the initializer list.
313 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000314 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000315
316 // Check this element.
317 CheckSubElementType(IList, elementType, IList->getInit(Index), Index);
318 ++elementIndex;
319
320 // If the array is of incomplete type, keep track of the number of
321 // elements in the initializer.
322 if (!maxElementsKnown && elementIndex > maxElements)
323 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000324 }
325 if (DeclType->isIncompleteArrayType()) {
326 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000327 // be calculated here.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000328 llvm::APInt Zero(ArraySizeBits, 0);
329 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000330 // Sizing an array implicitly to zero is not allowed by ISO C,
331 // but is supported by GNU.
Steve Naroffc4d4a482008-05-01 22:18:59 +0000332 SemaRef->Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000333 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000334 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000335
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000336 DeclType = SemaRef->Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000337 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000338 }
339}
340
341void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
342 QualType DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000343 RecordDecl::field_iterator Field,
344 bool SubobjectIsDesignatorContext,
Eli Friedman683cedf2008-05-19 19:16:24 +0000345 unsigned &Index) {
346 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000347
Eli Friedman683cedf2008-05-19 19:16:24 +0000348 // If the record is invalid, some of it's members are invalid. To avoid
349 // confusion, we forgo checking the intializer for the entire record.
350 if (structDecl->isInvalidDecl()) {
351 hadError = true;
352 return;
353 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000354 // If structDecl is a forward declaration, this loop won't do
355 // anything except look at designated initializers; That's okay,
356 // because an error should get printed out elsewhere. It might be
357 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000358 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor710f6d42009-01-22 23:26:18 +0000359 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000360 while (Index < IList->getNumInits()) {
361 Expr *Init = IList->getInit(Index);
362
363 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000364 // If we're not the subobject that matches up with the '{' for
365 // the designator, we shouldn't be handling the
366 // designator. Return immediately.
367 if (!SubobjectIsDesignatorContext)
368 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000369
Douglas Gregor710f6d42009-01-22 23:26:18 +0000370 // Handle this designated initializer. Field will be updated to
371 // the next field that we'll be initializing.
372 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
373 DeclType, &Field, 0, Index))
374 hadError = true;
375
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000376 continue;
377 }
378
379 if (Field == FieldEnd) {
380 // We've run out of fields. We're done.
381 break;
382 }
383
Douglas Gregor8acb7272008-12-11 16:49:14 +0000384 // If we've hit the flexible array member at the end, we're done.
385 if (Field->getType()->isIncompleteArrayType())
386 break;
387
Douglas Gregor8acb7272008-12-11 16:49:14 +0000388 if (!Field->getIdentifier()) {
Eli Friedman683cedf2008-05-19 19:16:24 +0000389 // Don't initialize unnamed fields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000390 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +0000391 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000392 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000393
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000394 CheckSubElementType(IList, Field->getType(), IList->getInit(Index), Index);
395 if (DeclType->isUnionType()) // FIXME: designated initializers?
Eli Friedman683cedf2008-05-19 19:16:24 +0000396 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000397
398 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000399 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000400
Eli Friedman683cedf2008-05-19 19:16:24 +0000401 // FIXME: Implement flexible array initialization GCC extension (it's a
402 // really messy extension to implement, unfortunately...the necessary
403 // information isn't actually even here!)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000404}
Steve Naroffc4d4a482008-05-01 22:18:59 +0000405
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000406/// @brief Check the well-formedness of a C99 designated initializer.
407///
408/// Determines whether the designated initializer @p DIE, which
409/// resides at the given @p Index within the initializer list @p
410/// IList, is well-formed for a current object of type @p DeclType
411/// (C99 6.7.8). The actual subobject that this designator refers to
412/// within the current subobject is returned in either
413/// @p DesignatedField or @p DesignatedIndex (whichever is
414/// appropriate).
415///
416/// @param IList The initializer list in which this designated
417/// initializer occurs.
418///
419/// @param DIE The designated initializer and its initialization
420/// expression.
421///
422/// @param DeclType The type of the "current object" (C99 6.7.8p17),
423/// into which the designation in @p DIE should refer.
424///
Douglas Gregor710f6d42009-01-22 23:26:18 +0000425/// @param NextField If non-NULL and the first designator in @p DIE is
426/// a field, this will be set to the field declaration corresponding
427/// to the field named by the designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000428///
Douglas Gregor710f6d42009-01-22 23:26:18 +0000429/// @param NextElementIndex If non-NULL and the first designator in @p
430/// DIE is an array designator or GNU array-range designator, this
431/// will be set to the last index initialized by this designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000432///
433/// @param Index Index into @p IList where the designated initializer
434/// @p DIE occurs.
435///
436/// @returns true if there was an error, false otherwise.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000437bool
438InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
439 DesignatedInitExpr *DIE,
440 DesignatedInitExpr::designators_iterator D,
441 QualType &CurrentObjectType,
442 RecordDecl::field_iterator *NextField,
443 llvm::APSInt *NextElementIndex,
444 unsigned &Index) {
445 bool IsFirstDesignator = (D == DIE->designators_begin());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000446
Douglas Gregor710f6d42009-01-22 23:26:18 +0000447 if (D == DIE->designators_end()) {
448 // Check the actual initialization for the designated object type.
449 bool prevHadError = hadError;
450 CheckSubElementType(IList, CurrentObjectType, DIE->getInit(), Index);
451 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000452 }
453
Douglas Gregor710f6d42009-01-22 23:26:18 +0000454 if (D->isFieldDesignator()) {
455 // C99 6.7.8p7:
456 //
457 // If a designator has the form
458 //
459 // . identifier
460 //
461 // then the current object (defined below) shall have
462 // structure or union type and the identifier shall be the
463 // name of a member of that type.
464 const RecordType *RT = CurrentObjectType->getAsRecordType();
465 if (!RT) {
466 SourceLocation Loc = D->getDotLoc();
467 if (Loc.isInvalid())
468 Loc = D->getFieldLoc();
469 SemaRef->Diag(Loc, diag::err_field_designator_non_aggr)
470 << SemaRef->getLangOptions().CPlusPlus << CurrentObjectType;
471 ++Index;
472 return true;
473 }
474
475 IdentifierInfo *FieldName = D->getFieldName();
476 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
477 FieldDecl *DesignatedField = 0;
478 if (Lookup.first == Lookup.second) {
479 // Lookup did not find anything with this name.
480 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
481 << FieldName << CurrentObjectType;
482 } else if (isa<FieldDecl>(*Lookup.first)) {
483 // Name lookup found a field.
484 DesignatedField = cast<FieldDecl>(*Lookup.first);
485 // FIXME: Make sure this isn't a field in an anonymous
486 // struct/union.
487 } else {
488 // Name lookup found something, but it wasn't a field.
489 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
490 << FieldName;
491 SemaRef->Diag((*Lookup.first)->getLocation(),
492 diag::note_field_designator_found);
493 }
494
495 if (!DesignatedField) {
496 ++Index;
497 return true;
498 }
499
500 // Update the designator with the field declaration.
501 D->setField(DesignatedField);
502
503 // Recurse to check later designated subobjects.
504 QualType FieldType = DesignatedField->getType();
505 if (CheckDesignatedInitializer(IList, DIE, ++D, FieldType, 0, 0, Index))
506 return true;
507
508 // Find the position of the next field to be initialized in this
509 // subobject.
510 RecordDecl::field_iterator Field(DeclContext::decl_iterator(DesignatedField),
511 RT->getDecl()->decls_end());
512 ++Field;
513
514 // If this the first designator, our caller will continue checking
515 // the rest of this struct/class/union subobject.
516 if (IsFirstDesignator) {
517 if (NextField)
518 *NextField = Field;
519 return false;
520 }
521
522 // Check the remaining fields within this class/struct/union subobject.
523 bool prevHadError = hadError;
524 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index);
525 return hadError && !prevHadError;
526 }
527
528 // C99 6.7.8p6:
529 //
530 // If a designator has the form
531 //
532 // [ constant-expression ]
533 //
534 // then the current object (defined below) shall have array
535 // type and the expression shall be an integer constant
536 // expression. If the array is of unknown size, any
537 // nonnegative value is valid.
538 //
539 // Additionally, cope with the GNU extension that permits
540 // designators of the form
541 //
542 // [ constant-expression ... constant-expression ]
543 const ArrayType *AT = SemaRef->Context.getAsArrayType(CurrentObjectType);
544 if (!AT) {
545 SemaRef->Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
546 << CurrentObjectType;
547 ++Index;
548 return true;
549 }
550
551 Expr *IndexExpr = 0;
552 llvm::APSInt DesignatedIndex;
553 if (D->isArrayDesignator())
554 IndexExpr = DIE->getArrayIndex(*D);
555 else {
556 assert(D->isArrayRangeDesignator() && "Need array-range designator");
557 IndexExpr = DIE->getArrayRangeEnd(*D);
558 }
559
560 bool ConstExpr
561 = IndexExpr->isIntegerConstantExpr(DesignatedIndex, SemaRef->Context);
562 assert(ConstExpr && "Expression must be constant"); (void)ConstExpr;
563
564 if (isa<ConstantArrayType>(AT)) {
565 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
566 if (DesignatedIndex >= MaxElements) {
567 SemaRef->Diag(IndexExpr->getSourceRange().getBegin(),
568 diag::err_array_designator_too_large)
569 << DesignatedIndex.toString(10) << MaxElements.toString(10)
570 << IndexExpr->getSourceRange();
571 ++Index;
572 return true;
573 }
574 }
575
576 // Recurse to check later designated subobjects.
577 QualType ElementType = AT->getElementType();
578 if (CheckDesignatedInitializer(IList, DIE, ++D, ElementType, 0, 0, Index))
579 return true;
580
581 // Move to the next index in the array that we'll be initializing.
582 ++DesignatedIndex;
583
584 // If this the first designator, our caller will continue checking
585 // the rest of this array subobject.
586 if (IsFirstDesignator) {
587 if (NextElementIndex)
588 *NextElementIndex = DesignatedIndex;
589 return false;
590 }
591
592 // Check the remaining elements within this array subobject.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000593 bool prevHadError = hadError;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000594 CheckArrayType(IList, CurrentObjectType, DesignatedIndex, true, Index);
595 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000596}
597
598/// Check that the given Index expression is a valid array designator
599/// value. This is essentailly just a wrapper around
600/// Expr::isIntegerConstantExpr that also checks for negative values
601/// and produces a reasonable diagnostic if there is a
602/// failure. Returns true if there was an error, false otherwise. If
603/// everything went okay, Value will receive the value of the constant
604/// expression.
605static bool
606CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) {
607 SourceLocation Loc = Index->getSourceRange().getBegin();
608
609 // Make sure this is an integer constant expression.
610 if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc))
611 return Self.Diag(Loc, diag::err_array_designator_nonconstant)
612 << Index->getSourceRange();
613
614 // Make sure this constant expression is non-negative.
615 llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()), false);
616 if (Value < Zero)
617 return Self.Diag(Loc, diag::err_array_designator_negative)
618 << Value.toString(10) << Index->getSourceRange();
619
620 return false;
621}
622
623Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
624 SourceLocation Loc,
625 bool UsedColonSyntax,
626 OwningExprResult Init) {
627 typedef DesignatedInitExpr::Designator ASTDesignator;
628
629 bool Invalid = false;
630 llvm::SmallVector<ASTDesignator, 32> Designators;
631 llvm::SmallVector<Expr *, 32> InitExpressions;
632
633 // Build designators and check array designator expressions.
634 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
635 const Designator &D = Desig.getDesignator(Idx);
636 switch (D.getKind()) {
637 case Designator::FieldDesignator:
638 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
639 D.getFieldLoc()));
640 break;
641
642 case Designator::ArrayDesignator: {
643 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
644 llvm::APSInt IndexValue;
645 if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
646 Invalid = true;
647 else {
648 Designators.push_back(ASTDesignator(InitExpressions.size(),
649 D.getLBracketLoc(),
650 D.getRBracketLoc()));
651 InitExpressions.push_back(Index);
652 }
653 break;
654 }
655
656 case Designator::ArrayRangeDesignator: {
657 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
658 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
659 llvm::APSInt StartValue;
660 llvm::APSInt EndValue;
661 if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
662 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
663 Invalid = true;
664 else if (EndValue < StartValue) {
665 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
666 << StartValue.toString(10) << EndValue.toString(10)
667 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
668 Invalid = true;
669 } else {
670 Designators.push_back(ASTDesignator(InitExpressions.size(),
671 D.getLBracketLoc(),
672 D.getEllipsisLoc(),
673 D.getRBracketLoc()));
674 InitExpressions.push_back(StartIndex);
675 InitExpressions.push_back(EndIndex);
676 }
677 break;
678 }
679 }
680 }
681
682 if (Invalid || Init.isInvalid())
683 return ExprError();
684
685 // Clear out the expressions within the designation.
686 Desig.ClearExprs(*this);
687
688 DesignatedInitExpr *DIE
689 = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
690 &InitExpressions[0], InitExpressions.size(),
691 Loc, UsedColonSyntax,
692 static_cast<Expr *>(Init.release()));
693 return Owned(DIE);
694}