blob: 163dac94b92bd486bf1e3f3d5c21b11bc0959a34 [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;
77 CheckListElementTypes(ParentIList, T, NewIndex);
78
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
Eli Friedman683cedf2008-05-19 19:16:24 +0000104 CheckListElementTypes(IList, T, 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,
133 unsigned &Index) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000134 if (DeclType->isScalarType()) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000135 CheckScalarType(IList, DeclType, 0, Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000136 } else if (DeclType->isVectorType()) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000137 CheckVectorType(IList, DeclType, Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000138 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000139 if (DeclType->isStructureType() || DeclType->isUnionType())
140 CheckStructUnionTypes(IList, DeclType, Index);
141 else if (DeclType->isArrayType())
142 CheckArrayType(IList, DeclType, Index);
143 else
144 assert(0 && "Aggregate that isn't a function or array?!");
Steve Naroffff5b3a82008-08-10 16:05:48 +0000145 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
146 // This type is invalid, issue a diagnostic.
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000147 Index++;
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000148 SemaRef->Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000149 << DeclType;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000150 hadError = true;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000151 } else {
152 // In C, all types are either scalars or aggregates, but
153 // additional handling is needed here for C++ (and possibly others?).
154 assert(0 && "Unsupported initializer type");
155 }
156}
157
Eli Friedman683cedf2008-05-19 19:16:24 +0000158void InitListChecker::CheckSubElementType(InitListExpr *IList,
159 QualType ElemType,
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000160 Expr *expr,
Eli Friedman683cedf2008-05-19 19:16:24 +0000161 unsigned &Index) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000162 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
163 unsigned newIndex = 0;
164 CheckExplicitInitList(SubInitList, ElemType, newIndex);
165 Index++;
Eli Friedman683cedf2008-05-19 19:16:24 +0000166 } else if (StringLiteral *lit =
167 SemaRef->IsStringLiteralInit(expr, ElemType)) {
168 SemaRef->CheckStringLiteralInit(lit, ElemType);
169 Index++;
Eli Friedmand8535af2008-05-19 20:00:43 +0000170 } else if (ElemType->isScalarType()) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000171 CheckScalarType(IList, ElemType, expr, Index);
Eli Friedman683cedf2008-05-19 19:16:24 +0000172 } else if (expr->getType()->getAsRecordType() &&
Eli Friedman2ccfb512008-06-09 03:52:40 +0000173 SemaRef->Context.typesAreCompatible(
174 expr->getType().getUnqualifiedType(),
175 ElemType.getUnqualifiedType())) {
Eli Friedman683cedf2008-05-19 19:16:24 +0000176 Index++;
177 // FIXME: Add checking
178 } else {
179 CheckImplicitInitList(IList, ElemType, Index);
180 Index++;
181 }
182}
183
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000184void InitListChecker::CheckScalarType(InitListExpr *IList, QualType &DeclType,
185 Expr *expr, unsigned &Index) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000186 if (Index < IList->getNumInits()) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000187 if (!expr)
188 expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000189 if (isa<InitListExpr>(expr)) {
Eli Friedman71de9eb2008-05-19 20:12:18 +0000190 SemaRef->Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000191 diag::err_many_braces_around_scalar_init)
192 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000193 hadError = true;
194 ++Index;
195 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000196 } else if (isa<DesignatedInitExpr>(expr)) {
197 SemaRef->Diag(expr->getSourceRange().getBegin(),
198 diag::err_designator_for_scalar_init)
199 << DeclType << expr->getSourceRange();
200 hadError = true;
201 ++Index;
202 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000203 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000204
Eli Friedmand8535af2008-05-19 20:00:43 +0000205 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000206 if (SemaRef->CheckSingleInitializer(expr, DeclType, false))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000207 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000208 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000209 // The type was promoted, update initializer list.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000210 if (DesignatedInitExpr *DIE
211 = dyn_cast<DesignatedInitExpr>(IList->getInit(Index)))
212 DIE->setInit(expr);
213 else
214 IList->setInit(Index, expr);
215 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000216 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000217 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000218 SemaRef->Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
219 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000220 hadError = true;
221 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000222 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000223}
224
225void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
226 unsigned &Index) {
227 if (Index < IList->getNumInits()) {
228 const VectorType *VT = DeclType->getAsVectorType();
229 int maxElements = VT->getNumElements();
230 QualType elementType = VT->getElementType();
231
232 for (int i = 0; i < maxElements; ++i) {
233 // Don't attempt to go past the end of the init list
234 if (Index >= IList->getNumInits())
235 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000236 CheckSubElementType(IList, elementType, IList->getInit(Index), Index);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000237 }
238 }
239}
240
241void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
242 unsigned &Index) {
243 // Check for the special-case of initializing an array with a string.
244 if (Index < IList->getNumInits()) {
245 if (StringLiteral *lit =
246 SemaRef->IsStringLiteralInit(IList->getInit(Index), DeclType)) {
247 SemaRef->CheckStringLiteralInit(lit, DeclType);
248 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000249 return;
250 }
251 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000252 if (const VariableArrayType *VAT =
253 SemaRef->Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000254 // Check for VLAs; in standard C it would be possible to check this
255 // earlier, but I don't know where clang accepts VLAs (gcc accepts
256 // them in all sorts of strange places).
257 SemaRef->Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000258 diag::err_variable_object_no_init)
259 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000260 hadError = true;
261 return;
262 }
263
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000264 // FIXME: Will 32 bits always be enough? I hope so.
265 const unsigned ArraySizeBits = 32;
266 llvm::APSInt elementIndex(ArraySizeBits, 0);
267
268 // We might know the maximum number of elements in advance.
269 llvm::APSInt maxElements(ArraySizeBits, 0);
270 bool maxElementsKnown = false;
271 if (const ConstantArrayType *CAT =
272 SemaRef->Context.getAsConstantArrayType(DeclType)) {
273 maxElements = CAT->getSize();
274 maxElementsKnown = true;
275 }
276
Chris Lattnera1923f62008-08-04 07:31:14 +0000277 QualType elementType = SemaRef->Context.getAsArrayType(DeclType)
278 ->getElementType();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000279 while (Index < IList->getNumInits()) {
280 Expr *Init = IList->getInit(Index);
281 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
282 // C99 6.7.8p17:
283 // [...] In contrast, a designation causes the following
284 // initializer to begin initialization of the subobject
285 // described by the designator.
286 FieldDecl *DesignatedField = 0;
287 if (CheckDesignatedInitializer(IList, DIE, DeclType, DesignatedField,
288 elementIndex, Index))
289 hadError = true;
290
291 ++elementIndex;
292 continue;
293 }
294
295 // If we know the maximum number of elements, and we've already
296 // hit it, stop consuming elements in the initializer list.
297 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000298 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000299
300 // Check this element.
301 CheckSubElementType(IList, elementType, IList->getInit(Index), Index);
302 ++elementIndex;
303
304 // If the array is of incomplete type, keep track of the number of
305 // elements in the initializer.
306 if (!maxElementsKnown && elementIndex > maxElements)
307 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000308 }
309 if (DeclType->isIncompleteArrayType()) {
310 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000311 // be calculated here.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000312 llvm::APInt Zero(ArraySizeBits, 0);
313 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000314 // Sizing an array implicitly to zero is not allowed by ISO C,
315 // but is supported by GNU.
Steve Naroffc4d4a482008-05-01 22:18:59 +0000316 SemaRef->Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000317 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000318 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000319
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000320 DeclType = SemaRef->Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000321 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000322 }
323}
324
325void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
326 QualType DeclType,
Eli Friedman683cedf2008-05-19 19:16:24 +0000327 unsigned &Index) {
328 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000329
Eli Friedman683cedf2008-05-19 19:16:24 +0000330 // If the record is invalid, some of it's members are invalid. To avoid
331 // confusion, we forgo checking the intializer for the entire record.
332 if (structDecl->isInvalidDecl()) {
333 hadError = true;
334 return;
335 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000336 // If structDecl is a forward declaration, this loop won't do
337 // anything except look at designated initializers; That's okay,
338 // because an error should get printed out elsewhere. It might be
339 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000340 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000341 RecordDecl::field_iterator Field = RD->field_begin(),
342 FieldEnd = RD->field_end();
343 while (Index < IList->getNumInits()) {
344 Expr *Init = IList->getInit(Index);
345
346 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
347 // C99 6.7.8p17:
348 // [...] In contrast, a designation causes the following
349 // initializer to begin initialization of the subobject
350 // described by the designator. Initialization then continues
351 // forward in order, beginning with the next subobject after
352 // that described by the designator.
353 FieldDecl *DesignatedField = 0;
354 llvm::APSInt LastElement;
355 if (CheckDesignatedInitializer(IList, DIE, DeclType, DesignatedField,
356 LastElement, Index)) {
357 hadError = true;
358 continue;
359 }
360
361 Field = RecordDecl::field_iterator(
362 DeclContext::decl_iterator(DesignatedField),
363 DeclType->getAsRecordType()->getDecl()->decls_end());
364 ++Field;
365 continue;
366 }
367
368 if (Field == FieldEnd) {
369 // We've run out of fields. We're done.
370 break;
371 }
372
Douglas Gregor8acb7272008-12-11 16:49:14 +0000373 // If we've hit the flexible array member at the end, we're done.
374 if (Field->getType()->isIncompleteArrayType())
375 break;
376
Douglas Gregor8acb7272008-12-11 16:49:14 +0000377 if (!Field->getIdentifier()) {
Eli Friedman683cedf2008-05-19 19:16:24 +0000378 // Don't initialize unnamed fields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000379 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +0000380 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000381 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000382
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000383 CheckSubElementType(IList, Field->getType(), IList->getInit(Index), Index);
384 if (DeclType->isUnionType()) // FIXME: designated initializers?
Eli Friedman683cedf2008-05-19 19:16:24 +0000385 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000386
387 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000388 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000389
Eli Friedman683cedf2008-05-19 19:16:24 +0000390 // FIXME: Implement flexible array initialization GCC extension (it's a
391 // really messy extension to implement, unfortunately...the necessary
392 // information isn't actually even here!)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000393}
Steve Naroffc4d4a482008-05-01 22:18:59 +0000394
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000395/// @brief Check the well-formedness of a C99 designated initializer.
396///
397/// Determines whether the designated initializer @p DIE, which
398/// resides at the given @p Index within the initializer list @p
399/// IList, is well-formed for a current object of type @p DeclType
400/// (C99 6.7.8). The actual subobject that this designator refers to
401/// within the current subobject is returned in either
402/// @p DesignatedField or @p DesignatedIndex (whichever is
403/// appropriate).
404///
405/// @param IList The initializer list in which this designated
406/// initializer occurs.
407///
408/// @param DIE The designated initializer and its initialization
409/// expression.
410///
411/// @param DeclType The type of the "current object" (C99 6.7.8p17),
412/// into which the designation in @p DIE should refer.
413///
414/// @param DesignatedField If the first designator in @p DIE is a field,
415/// this will be set to the field declaration corresponding to the
416/// field named by the designator.
417///
418/// @param DesignatedIndex If the first designator in @p DIE is an
419/// array designator or GNU array-range designator, this will be set
420/// to the last index initialized by this designator.
421///
422/// @param Index Index into @p IList where the designated initializer
423/// @p DIE occurs.
424///
425/// @returns true if there was an error, false otherwise.
426bool InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
427 DesignatedInitExpr *DIE,
428 QualType DeclType,
429 FieldDecl *&DesignatedField,
430 llvm::APSInt &DesignatedIndex,
431 unsigned &Index) {
432 // DeclType is always the type of the "current object" (C99 6.7.8p17).
433
434 for (DesignatedInitExpr::designators_iterator D = DIE->designators_begin(),
435 DEnd = DIE->designators_end();
436 D != DEnd; ++D) {
437 if (D->isFieldDesignator()) {
438 // C99 6.7.8p7:
439 //
440 // If a designator has the form
441 //
442 // . identifier
443 //
444 // then the current object (defined below) shall have
445 // structure or union type and the identifier shall be the
446 // name of a member of that type.
447 const RecordType *RT = DeclType->getAsRecordType();
448 if (!RT) {
449 SemaRef->Diag(DIE->getSourceRange().getBegin(),
450 diag::err_field_designator_non_aggr)
451 << SemaRef->getLangOptions().CPlusPlus << DeclType;
452 ++Index;
453 return true;
454 }
455
456 IdentifierInfo *FieldName = D->getFieldName();
457 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
458 FieldDecl *ThisField = 0;
459 if (Lookup.first == Lookup.second) {
460 // Lookup did not find anything with this name.
461 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
462 << FieldName << DeclType;
463 } else if (isa<FieldDecl>(*Lookup.first)) {
464 // Name lookup found a field.
465 ThisField = cast<FieldDecl>(*Lookup.first);
466 // FIXME: Make sure this isn't a field in an anonymous
467 // struct/union.
468 } else {
469 // Name lookup found something, but it wasn't a field.
470 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
471 << FieldName;
472 SemaRef->Diag((*Lookup.first)->getLocation(),
473 diag::note_field_designator_found);
474 }
475
476 if (!ThisField) {
477 ++Index;
478 return true;
479 }
480
481 // Update the designator with the field declaration.
482 D->setField(ThisField);
483
484 if (D == DIE->designators_begin())
485 DesignatedField = ThisField;
486
487 // The current object is now the type of this field.
488 DeclType = ThisField->getType();
489 } else {
490 // C99 6.7.8p6:
491 //
492 // If a designator has the form
493 //
494 // [ constant-expression ]
495 //
496 // then the current object (defined below) shall have array
497 // type and the expression shall be an integer constant
498 // expression. If the array is of unknown size, any
499 // nonnegative value is valid.
500 const ArrayType *AT = SemaRef->Context.getAsArrayType(DeclType);
501 if (!AT) {
502 SemaRef->Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
503 << DeclType;
504 ++Index;
505 return true;
506 }
507
508 Expr *IndexExpr = 0;
509 llvm::APSInt ThisIndex;
510 if (D->isArrayDesignator())
511 IndexExpr = DIE->getArrayIndex(*D);
512 else {
513 assert(D->isArrayRangeDesignator() && "Need array-range designator");
514 IndexExpr = DIE->getArrayRangeEnd(*D);
515 }
516
517 bool ConstExpr
518 = IndexExpr->isIntegerConstantExpr(ThisIndex, SemaRef->Context);
519 assert(ConstExpr && "Expression must be constant"); (void)ConstExpr;
520
521 if (isa<ConstantArrayType>(AT)) {
522 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
523 if (ThisIndex >= MaxElements) {
524 SemaRef->Diag(IndexExpr->getSourceRange().getBegin(),
525 diag::err_array_designator_too_large)
526 << ThisIndex.toString(10) << MaxElements.toString(10);
527 ++Index;
528 return true;
529 }
530 }
531
532 if (D == DIE->designators_begin())
533 DesignatedIndex = ThisIndex;
534
535 // The current object is now the element type of this array.
536 DeclType = AT->getElementType();
537 }
538 }
539
540 // Check the actual initialization for the designated object type.
541 bool prevHadError = hadError;
542 CheckSubElementType(IList, DeclType, DIE->getInit(), Index);
543 return hadError && !prevHadError;
544}
545
546/// Check that the given Index expression is a valid array designator
547/// value. This is essentailly just a wrapper around
548/// Expr::isIntegerConstantExpr that also checks for negative values
549/// and produces a reasonable diagnostic if there is a
550/// failure. Returns true if there was an error, false otherwise. If
551/// everything went okay, Value will receive the value of the constant
552/// expression.
553static bool
554CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) {
555 SourceLocation Loc = Index->getSourceRange().getBegin();
556
557 // Make sure this is an integer constant expression.
558 if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc))
559 return Self.Diag(Loc, diag::err_array_designator_nonconstant)
560 << Index->getSourceRange();
561
562 // Make sure this constant expression is non-negative.
563 llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()), false);
564 if (Value < Zero)
565 return Self.Diag(Loc, diag::err_array_designator_negative)
566 << Value.toString(10) << Index->getSourceRange();
567
568 return false;
569}
570
571Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
572 SourceLocation Loc,
573 bool UsedColonSyntax,
574 OwningExprResult Init) {
575 typedef DesignatedInitExpr::Designator ASTDesignator;
576
577 bool Invalid = false;
578 llvm::SmallVector<ASTDesignator, 32> Designators;
579 llvm::SmallVector<Expr *, 32> InitExpressions;
580
581 // Build designators and check array designator expressions.
582 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
583 const Designator &D = Desig.getDesignator(Idx);
584 switch (D.getKind()) {
585 case Designator::FieldDesignator:
586 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
587 D.getFieldLoc()));
588 break;
589
590 case Designator::ArrayDesignator: {
591 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
592 llvm::APSInt IndexValue;
593 if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
594 Invalid = true;
595 else {
596 Designators.push_back(ASTDesignator(InitExpressions.size(),
597 D.getLBracketLoc(),
598 D.getRBracketLoc()));
599 InitExpressions.push_back(Index);
600 }
601 break;
602 }
603
604 case Designator::ArrayRangeDesignator: {
605 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
606 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
607 llvm::APSInt StartValue;
608 llvm::APSInt EndValue;
609 if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
610 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
611 Invalid = true;
612 else if (EndValue < StartValue) {
613 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
614 << StartValue.toString(10) << EndValue.toString(10)
615 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
616 Invalid = true;
617 } else {
618 Designators.push_back(ASTDesignator(InitExpressions.size(),
619 D.getLBracketLoc(),
620 D.getEllipsisLoc(),
621 D.getRBracketLoc()));
622 InitExpressions.push_back(StartIndex);
623 InitExpressions.push_back(EndIndex);
624 }
625 break;
626 }
627 }
628 }
629
630 if (Invalid || Init.isInvalid())
631 return ExprError();
632
633 // Clear out the expressions within the designation.
634 Desig.ClearExprs(*this);
635
636 DesignatedInitExpr *DIE
637 = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
638 &InitExpressions[0], InitExpressions.size(),
639 Loc, UsedColonSyntax,
640 static_cast<Expr *>(Init.release()));
641 return Owned(DIE);
642}