blob: 041e994bca8faae10636c530846808e3356d7ff7 [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"
Chris Lattner52a425b2009-01-27 18:30:58 +000018#include "clang/Basic/DiagnosticSema.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()) {
Douglas Gregor5a203a62009-01-23 16:54:12 +0000145 llvm::APSInt Zero(
146 SemaRef->Context.getTypeSize(SemaRef->Context.getSizeType()),
147 false);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000148 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index);
149 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000150 else
151 assert(0 && "Aggregate that isn't a function or array?!");
Steve Naroffff5b3a82008-08-10 16:05:48 +0000152 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
153 // This type is invalid, issue a diagnostic.
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000154 Index++;
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000155 SemaRef->Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000156 << DeclType;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000157 hadError = true;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000158 } else {
159 // In C, all types are either scalars or aggregates, but
160 // additional handling is needed here for C++ (and possibly others?).
161 assert(0 && "Unsupported initializer type");
162 }
163}
164
Eli Friedman683cedf2008-05-19 19:16:24 +0000165void InitListChecker::CheckSubElementType(InitListExpr *IList,
166 QualType ElemType,
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000167 Expr *expr,
Eli Friedman683cedf2008-05-19 19:16:24 +0000168 unsigned &Index) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000169 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
170 unsigned newIndex = 0;
171 CheckExplicitInitList(SubInitList, ElemType, newIndex);
172 Index++;
Eli Friedman683cedf2008-05-19 19:16:24 +0000173 } else if (StringLiteral *lit =
174 SemaRef->IsStringLiteralInit(expr, ElemType)) {
175 SemaRef->CheckStringLiteralInit(lit, ElemType);
176 Index++;
Eli Friedmand8535af2008-05-19 20:00:43 +0000177 } else if (ElemType->isScalarType()) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000178 CheckScalarType(IList, ElemType, expr, Index);
Eli Friedman683cedf2008-05-19 19:16:24 +0000179 } else if (expr->getType()->getAsRecordType() &&
Eli Friedman2ccfb512008-06-09 03:52:40 +0000180 SemaRef->Context.typesAreCompatible(
181 expr->getType().getUnqualifiedType(),
182 ElemType.getUnqualifiedType())) {
Eli Friedman683cedf2008-05-19 19:16:24 +0000183 Index++;
184 // FIXME: Add checking
185 } else {
186 CheckImplicitInitList(IList, ElemType, Index);
187 Index++;
188 }
189}
190
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000191void InitListChecker::CheckScalarType(InitListExpr *IList, QualType &DeclType,
192 Expr *expr, unsigned &Index) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000193 if (Index < IList->getNumInits()) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000194 if (!expr)
195 expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000196 if (isa<InitListExpr>(expr)) {
Eli Friedman71de9eb2008-05-19 20:12:18 +0000197 SemaRef->Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000198 diag::err_many_braces_around_scalar_init)
199 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000200 hadError = true;
201 ++Index;
202 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000203 } else if (isa<DesignatedInitExpr>(expr)) {
204 SemaRef->Diag(expr->getSourceRange().getBegin(),
205 diag::err_designator_for_scalar_init)
206 << DeclType << expr->getSourceRange();
207 hadError = true;
208 ++Index;
209 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000210 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000211
Eli Friedmand8535af2008-05-19 20:00:43 +0000212 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000213 if (SemaRef->CheckSingleInitializer(expr, DeclType, false))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000214 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000215 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000216 // The type was promoted, update initializer list.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000217 if (DesignatedInitExpr *DIE
218 = dyn_cast<DesignatedInitExpr>(IList->getInit(Index)))
219 DIE->setInit(expr);
220 else
221 IList->setInit(Index, expr);
222 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000223 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000224 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000225 SemaRef->Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
226 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000227 hadError = true;
228 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000229 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000230}
231
232void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
233 unsigned &Index) {
234 if (Index < IList->getNumInits()) {
235 const VectorType *VT = DeclType->getAsVectorType();
236 int maxElements = VT->getNumElements();
237 QualType elementType = VT->getElementType();
238
239 for (int i = 0; i < maxElements; ++i) {
240 // Don't attempt to go past the end of the init list
241 if (Index >= IList->getNumInits())
242 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000243 CheckSubElementType(IList, elementType, IList->getInit(Index), Index);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000244 }
245 }
246}
247
248void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000249 llvm::APSInt elementIndex,
250 bool SubobjectIsDesignatorContext,
Steve Naroffc4d4a482008-05-01 22:18:59 +0000251 unsigned &Index) {
252 // Check for the special-case of initializing an array with a string.
253 if (Index < IList->getNumInits()) {
254 if (StringLiteral *lit =
255 SemaRef->IsStringLiteralInit(IList->getInit(Index), DeclType)) {
256 SemaRef->CheckStringLiteralInit(lit, DeclType);
257 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000258 return;
259 }
260 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000261 if (const VariableArrayType *VAT =
262 SemaRef->Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000263 // Check for VLAs; in standard C it would be possible to check this
264 // earlier, but I don't know where clang accepts VLAs (gcc accepts
265 // them in all sorts of strange places).
266 SemaRef->Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000267 diag::err_variable_object_no_init)
268 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000269 hadError = true;
270 return;
271 }
272
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000273 // We might know the maximum number of elements in advance.
Douglas Gregor69722702009-01-23 18:58:42 +0000274 llvm::APSInt maxElements(elementIndex.getBitWidth(), elementIndex.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000275 bool maxElementsKnown = false;
276 if (const ConstantArrayType *CAT =
277 SemaRef->Context.getAsConstantArrayType(DeclType)) {
278 maxElements = CAT->getSize();
Douglas Gregor5a203a62009-01-23 16:54:12 +0000279 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000280 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000281 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
Douglas Gregor5a203a62009-01-23 16:54:12 +0000303 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
304 maxElements.extend(elementIndex.getBitWidth());
305 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
306 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000307 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor5a203a62009-01-23 16:54:12 +0000308
Douglas Gregor710f6d42009-01-22 23:26:18 +0000309 // If the array is of incomplete type, keep track of the number of
310 // elements in the initializer.
311 if (!maxElementsKnown && elementIndex > maxElements)
312 maxElements = elementIndex;
313
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000314 continue;
315 }
316
317 // If we know the maximum number of elements, and we've already
318 // hit it, stop consuming elements in the initializer list.
319 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000320 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000321
322 // Check this element.
323 CheckSubElementType(IList, elementType, IList->getInit(Index), Index);
324 ++elementIndex;
325
326 // If the array is of incomplete type, keep track of the number of
327 // elements in the initializer.
328 if (!maxElementsKnown && elementIndex > maxElements)
329 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000330 }
331 if (DeclType->isIncompleteArrayType()) {
332 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000333 // be calculated here.
Douglas Gregor69722702009-01-23 18:58:42 +0000334 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000335 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000336 // Sizing an array implicitly to zero is not allowed by ISO C,
337 // but is supported by GNU.
Steve Naroffc4d4a482008-05-01 22:18:59 +0000338 SemaRef->Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000339 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000340 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000341
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000342 DeclType = SemaRef->Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000343 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000344 }
345}
346
347void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
348 QualType DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000349 RecordDecl::field_iterator Field,
350 bool SubobjectIsDesignatorContext,
Eli Friedman683cedf2008-05-19 19:16:24 +0000351 unsigned &Index) {
352 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000353
Eli Friedman683cedf2008-05-19 19:16:24 +0000354 // If the record is invalid, some of it's members are invalid. To avoid
355 // confusion, we forgo checking the intializer for the entire record.
356 if (structDecl->isInvalidDecl()) {
357 hadError = true;
358 return;
359 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000360 // If structDecl is a forward declaration, this loop won't do
361 // anything except look at designated initializers; That's okay,
362 // because an error should get printed out elsewhere. It might be
363 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000364 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor710f6d42009-01-22 23:26:18 +0000365 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000366 while (Index < IList->getNumInits()) {
367 Expr *Init = IList->getInit(Index);
368
369 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000370 // If we're not the subobject that matches up with the '{' for
371 // the designator, we shouldn't be handling the
372 // designator. Return immediately.
373 if (!SubobjectIsDesignatorContext)
374 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000375
Douglas Gregor710f6d42009-01-22 23:26:18 +0000376 // Handle this designated initializer. Field will be updated to
377 // the next field that we'll be initializing.
378 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
379 DeclType, &Field, 0, Index))
380 hadError = true;
381
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000382 continue;
383 }
384
385 if (Field == FieldEnd) {
386 // We've run out of fields. We're done.
387 break;
388 }
389
Douglas Gregor8acb7272008-12-11 16:49:14 +0000390 // If we've hit the flexible array member at the end, we're done.
391 if (Field->getType()->isIncompleteArrayType())
392 break;
393
Douglas Gregor8acb7272008-12-11 16:49:14 +0000394 if (!Field->getIdentifier()) {
Eli Friedman683cedf2008-05-19 19:16:24 +0000395 // Don't initialize unnamed fields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000396 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +0000397 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000398 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000399
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000400 CheckSubElementType(IList, Field->getType(), IList->getInit(Index), Index);
401 if (DeclType->isUnionType()) // FIXME: designated initializers?
Eli Friedman683cedf2008-05-19 19:16:24 +0000402 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000403
404 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000405 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000406
Eli Friedman683cedf2008-05-19 19:16:24 +0000407 // FIXME: Implement flexible array initialization GCC extension (it's a
408 // really messy extension to implement, unfortunately...the necessary
409 // information isn't actually even here!)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000410}
Steve Naroffc4d4a482008-05-01 22:18:59 +0000411
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000412/// @brief Check the well-formedness of a C99 designated initializer.
413///
414/// Determines whether the designated initializer @p DIE, which
415/// resides at the given @p Index within the initializer list @p
416/// IList, is well-formed for a current object of type @p DeclType
417/// (C99 6.7.8). The actual subobject that this designator refers to
418/// within the current subobject is returned in either
419/// @p DesignatedField or @p DesignatedIndex (whichever is
420/// appropriate).
421///
422/// @param IList The initializer list in which this designated
423/// initializer occurs.
424///
425/// @param DIE The designated initializer and its initialization
426/// expression.
427///
428/// @param DeclType The type of the "current object" (C99 6.7.8p17),
429/// into which the designation in @p DIE should refer.
430///
Douglas Gregor710f6d42009-01-22 23:26:18 +0000431/// @param NextField If non-NULL and the first designator in @p DIE is
432/// a field, this will be set to the field declaration corresponding
433/// to the field named by the designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000434///
Douglas Gregor710f6d42009-01-22 23:26:18 +0000435/// @param NextElementIndex If non-NULL and the first designator in @p
436/// DIE is an array designator or GNU array-range designator, this
437/// will be set to the last index initialized by this designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000438///
439/// @param Index Index into @p IList where the designated initializer
440/// @p DIE occurs.
441///
442/// @returns true if there was an error, false otherwise.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000443bool
444InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
445 DesignatedInitExpr *DIE,
446 DesignatedInitExpr::designators_iterator D,
447 QualType &CurrentObjectType,
448 RecordDecl::field_iterator *NextField,
449 llvm::APSInt *NextElementIndex,
450 unsigned &Index) {
451 bool IsFirstDesignator = (D == DIE->designators_begin());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000452
Douglas Gregor710f6d42009-01-22 23:26:18 +0000453 if (D == DIE->designators_end()) {
454 // Check the actual initialization for the designated object type.
455 bool prevHadError = hadError;
456 CheckSubElementType(IList, CurrentObjectType, DIE->getInit(), Index);
457 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000458 }
459
Douglas Gregor710f6d42009-01-22 23:26:18 +0000460 if (D->isFieldDesignator()) {
461 // C99 6.7.8p7:
462 //
463 // If a designator has the form
464 //
465 // . identifier
466 //
467 // then the current object (defined below) shall have
468 // structure or union type and the identifier shall be the
469 // name of a member of that type.
470 const RecordType *RT = CurrentObjectType->getAsRecordType();
471 if (!RT) {
472 SourceLocation Loc = D->getDotLoc();
473 if (Loc.isInvalid())
474 Loc = D->getFieldLoc();
475 SemaRef->Diag(Loc, diag::err_field_designator_non_aggr)
476 << SemaRef->getLangOptions().CPlusPlus << CurrentObjectType;
477 ++Index;
478 return true;
479 }
480
481 IdentifierInfo *FieldName = D->getFieldName();
482 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
483 FieldDecl *DesignatedField = 0;
484 if (Lookup.first == Lookup.second) {
485 // Lookup did not find anything with this name.
486 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
487 << FieldName << CurrentObjectType;
488 } else if (isa<FieldDecl>(*Lookup.first)) {
489 // Name lookup found a field.
490 DesignatedField = cast<FieldDecl>(*Lookup.first);
491 // FIXME: Make sure this isn't a field in an anonymous
492 // struct/union.
493 } else {
494 // Name lookup found something, but it wasn't a field.
495 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
496 << FieldName;
497 SemaRef->Diag((*Lookup.first)->getLocation(),
498 diag::note_field_designator_found);
499 }
500
501 if (!DesignatedField) {
502 ++Index;
503 return true;
504 }
505
506 // Update the designator with the field declaration.
507 D->setField(DesignatedField);
508
509 // Recurse to check later designated subobjects.
510 QualType FieldType = DesignatedField->getType();
511 if (CheckDesignatedInitializer(IList, DIE, ++D, FieldType, 0, 0, Index))
512 return true;
513
514 // Find the position of the next field to be initialized in this
515 // subobject.
516 RecordDecl::field_iterator Field(DeclContext::decl_iterator(DesignatedField),
517 RT->getDecl()->decls_end());
518 ++Field;
519
520 // If this the first designator, our caller will continue checking
521 // the rest of this struct/class/union subobject.
522 if (IsFirstDesignator) {
523 if (NextField)
524 *NextField = Field;
525 return false;
526 }
527
528 // Check the remaining fields within this class/struct/union subobject.
529 bool prevHadError = hadError;
530 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index);
531 return hadError && !prevHadError;
532 }
533
534 // C99 6.7.8p6:
535 //
536 // If a designator has the form
537 //
538 // [ constant-expression ]
539 //
540 // then the current object (defined below) shall have array
541 // type and the expression shall be an integer constant
542 // expression. If the array is of unknown size, any
543 // nonnegative value is valid.
544 //
545 // Additionally, cope with the GNU extension that permits
546 // designators of the form
547 //
548 // [ constant-expression ... constant-expression ]
549 const ArrayType *AT = SemaRef->Context.getAsArrayType(CurrentObjectType);
550 if (!AT) {
551 SemaRef->Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
552 << CurrentObjectType;
553 ++Index;
554 return true;
555 }
556
557 Expr *IndexExpr = 0;
558 llvm::APSInt DesignatedIndex;
559 if (D->isArrayDesignator())
560 IndexExpr = DIE->getArrayIndex(*D);
561 else {
562 assert(D->isArrayRangeDesignator() && "Need array-range designator");
563 IndexExpr = DIE->getArrayRangeEnd(*D);
564 }
565
566 bool ConstExpr
567 = IndexExpr->isIntegerConstantExpr(DesignatedIndex, SemaRef->Context);
568 assert(ConstExpr && "Expression must be constant"); (void)ConstExpr;
569
570 if (isa<ConstantArrayType>(AT)) {
571 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor5a203a62009-01-23 16:54:12 +0000572 DesignatedIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000573 DesignatedIndex.setIsUnsigned(MaxElements.isUnsigned());
Douglas Gregor710f6d42009-01-22 23:26:18 +0000574 if (DesignatedIndex >= MaxElements) {
575 SemaRef->Diag(IndexExpr->getSourceRange().getBegin(),
576 diag::err_array_designator_too_large)
577 << DesignatedIndex.toString(10) << MaxElements.toString(10)
578 << IndexExpr->getSourceRange();
579 ++Index;
580 return true;
581 }
582 }
583
584 // Recurse to check later designated subobjects.
585 QualType ElementType = AT->getElementType();
586 if (CheckDesignatedInitializer(IList, DIE, ++D, ElementType, 0, 0, Index))
587 return true;
588
589 // Move to the next index in the array that we'll be initializing.
590 ++DesignatedIndex;
591
592 // If this the first designator, our caller will continue checking
593 // the rest of this array subobject.
594 if (IsFirstDesignator) {
595 if (NextElementIndex)
596 *NextElementIndex = DesignatedIndex;
597 return false;
598 }
599
600 // Check the remaining elements within this array subobject.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000601 bool prevHadError = hadError;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000602 CheckArrayType(IList, CurrentObjectType, DesignatedIndex, true, Index);
603 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000604}
605
606/// Check that the given Index expression is a valid array designator
607/// value. This is essentailly just a wrapper around
608/// Expr::isIntegerConstantExpr that also checks for negative values
609/// and produces a reasonable diagnostic if there is a
610/// failure. Returns true if there was an error, false otherwise. If
611/// everything went okay, Value will receive the value of the constant
612/// expression.
613static bool
614CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) {
615 SourceLocation Loc = Index->getSourceRange().getBegin();
616
617 // Make sure this is an integer constant expression.
618 if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc))
619 return Self.Diag(Loc, diag::err_array_designator_nonconstant)
620 << Index->getSourceRange();
621
622 // Make sure this constant expression is non-negative.
Douglas Gregor69722702009-01-23 18:58:42 +0000623 llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()),
624 Value.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000625 if (Value < Zero)
626 return Self.Diag(Loc, diag::err_array_designator_negative)
627 << Value.toString(10) << Index->getSourceRange();
628
Douglas Gregore498e372009-01-23 21:04:18 +0000629 Value.setIsUnsigned(true);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000630 return false;
631}
632
633Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
634 SourceLocation Loc,
635 bool UsedColonSyntax,
636 OwningExprResult Init) {
637 typedef DesignatedInitExpr::Designator ASTDesignator;
638
639 bool Invalid = false;
640 llvm::SmallVector<ASTDesignator, 32> Designators;
641 llvm::SmallVector<Expr *, 32> InitExpressions;
642
643 // Build designators and check array designator expressions.
644 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
645 const Designator &D = Desig.getDesignator(Idx);
646 switch (D.getKind()) {
647 case Designator::FieldDesignator:
648 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
649 D.getFieldLoc()));
650 break;
651
652 case Designator::ArrayDesignator: {
653 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
654 llvm::APSInt IndexValue;
655 if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
656 Invalid = true;
657 else {
658 Designators.push_back(ASTDesignator(InitExpressions.size(),
659 D.getLBracketLoc(),
660 D.getRBracketLoc()));
661 InitExpressions.push_back(Index);
662 }
663 break;
664 }
665
666 case Designator::ArrayRangeDesignator: {
667 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
668 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
669 llvm::APSInt StartValue;
670 llvm::APSInt EndValue;
671 if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
672 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
673 Invalid = true;
Douglas Gregorea0528d2009-01-23 22:22:29 +0000674 else {
675 // Make sure we're comparing values with the same bit width.
676 if (StartValue.getBitWidth() > EndValue.getBitWidth())
677 EndValue.extend(StartValue.getBitWidth());
678 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
679 StartValue.extend(EndValue.getBitWidth());
680
681 if (EndValue < StartValue) {
682 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
683 << StartValue.toString(10) << EndValue.toString(10)
684 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
685 Invalid = true;
686 } else {
687 Designators.push_back(ASTDesignator(InitExpressions.size(),
688 D.getLBracketLoc(),
689 D.getEllipsisLoc(),
690 D.getRBracketLoc()));
691 InitExpressions.push_back(StartIndex);
692 InitExpressions.push_back(EndIndex);
693 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000694 }
695 break;
696 }
697 }
698 }
699
700 if (Invalid || Init.isInvalid())
701 return ExprError();
702
703 // Clear out the expressions within the designation.
704 Desig.ClearExprs(*this);
705
706 DesignatedInitExpr *DIE
707 = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
708 &InitExpressions[0], InitExpressions.size(),
709 Loc, UsedColonSyntax,
710 static_cast<Expr *>(Init.release()));
711 return Owned(DIE);
712}