1 //===--- ParseInit.cpp - Initializer Parsing ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements initializer parsing as specified by C99 6.7.8.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "RAIIObjectsForParser.h"
16 #include "clang/Parse/ParseDiagnostic.h"
17 #include "clang/Sema/Designator.h"
18 #include "clang/Sema/Scope.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/Support/raw_ostream.h"
21 using namespace clang;
24 /// MayBeDesignationStart - Return true if the current token might be the start
25 /// of a designator. If we can tell it is impossible that it is a designator,
27 bool Parser::MayBeDesignationStart() {
28 switch (Tok.getKind()) {
32 case tok::period: // designator: '.' identifier
35 case tok::l_square: { // designator: array-designator
36 if (!PP.getLangOpts().CPlusPlus11)
39 // C++11 lambda expressions and C99 designators can be ambiguous all the
40 // way through the closing ']' and to the next character. Handle the easy
41 // cases here, and fall back to tentative parsing if those fail.
42 switch (PP.LookAhead(0).getKind()) {
45 // Definitely starts a lambda expression.
51 // We have to do additional analysis, because these could be the
52 // start of a constant expression or a lambda capture list.
56 // Anything not mentioned above cannot occur following a '[' in a
61 // Handle the complicated case below.
64 case tok::identifier: // designation: identifier ':'
65 return PP.LookAhead(0).is(tok::colon);
68 // Parse up to (at most) the token after the closing ']' to determine
69 // whether this is a C99 designator or a lambda.
70 TentativeParsingAction Tentative(*this);
72 LambdaIntroducer Intro;
73 bool SkippedInits = false;
74 Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
77 // If this can't be a lambda capture list, it's a designator.
82 // Once we hit the closing square bracket, we look at the next
83 // token. If it's an '=', this is a designator. Otherwise, it's a
84 // lambda expression. This decision favors lambdas over the older
85 // GNU designator syntax, which allows one to omit the '=', but is
86 // consistent with GCC.
87 tok::TokenKind Kind = Tok.getKind();
88 // FIXME: If we didn't skip any inits, parse the lambda from here
89 // rather than throwing away then reparsing the LambdaIntroducer.
91 return Kind == tok::equal;
94 static void CheckArrayDesignatorSyntax(Parser &P, SourceLocation Loc,
96 // If we have exactly one array designator, this used the GNU
97 // 'designation: array-designator' extension, otherwise there should be no
98 // designators at all!
99 if (Desig.getNumDesignators() == 1 &&
100 (Desig.getDesignator(0).isArrayDesignator() ||
101 Desig.getDesignator(0).isArrayRangeDesignator()))
102 P.Diag(Loc, diag::ext_gnu_missing_equal_designator);
103 else if (Desig.getNumDesignators() > 0)
104 P.Diag(Loc, diag::err_expected_equal_designator);
107 /// ParseInitializerWithPotentialDesignator - Parse the 'initializer' production
108 /// checking to see if the token stream starts with a designator.
111 /// designator-list '='
112 /// [GNU] array-designator
113 /// [GNU] identifier ':'
117 /// designator-list designator
123 /// array-designator:
124 /// '[' constant-expression ']'
125 /// [GNU] '[' constant-expression '...' constant-expression ']'
127 /// NOTE: [OBC] allows '[ objc-receiver objc-message-args ]' as an
128 /// initializer (because it is an expression). We need to consider this case
129 /// when parsing array designators.
131 ExprResult Parser::ParseInitializerWithPotentialDesignator() {
133 // If this is the old-style GNU extension:
134 // designation ::= identifier ':'
135 // Handle it as a field designator. Otherwise, this must be the start of a
136 // normal expression.
137 if (Tok.is(tok::identifier)) {
138 const IdentifierInfo *FieldName = Tok.getIdentifierInfo();
140 SmallString<256> NewSyntax;
141 llvm::raw_svector_ostream(NewSyntax) << '.' << FieldName->getName()
144 SourceLocation NameLoc = ConsumeToken(); // Eat the identifier.
146 assert(Tok.is(tok::colon) && "MayBeDesignationStart not working properly!");
147 SourceLocation ColonLoc = ConsumeToken();
149 Diag(NameLoc, diag::ext_gnu_old_style_field_designator)
150 << FixItHint::CreateReplacement(SourceRange(NameLoc, ColonLoc),
154 D.AddDesignator(Designator::getField(FieldName, SourceLocation(), NameLoc));
155 return Actions.ActOnDesignatedInitializer(D, ColonLoc, true,
159 // Desig - This is initialized when we see our first designator. We may have
160 // an objc message send with no designator, so we don't want to create this
164 // Parse each designator in the designator list until we find an initializer.
165 while (Tok.is(tok::period) || Tok.is(tok::l_square)) {
166 if (Tok.is(tok::period)) {
167 // designator: '.' identifier
168 SourceLocation DotLoc = ConsumeToken();
170 if (Tok.isNot(tok::identifier)) {
171 Diag(Tok.getLocation(), diag::err_expected_field_designator);
175 Desig.AddDesignator(Designator::getField(Tok.getIdentifierInfo(), DotLoc,
177 ConsumeToken(); // Eat the identifier.
181 // We must have either an array designator now or an objc message send.
182 assert(Tok.is(tok::l_square) && "Unexpected token!");
184 // Handle the two forms of array designator:
185 // array-designator: '[' constant-expression ']'
186 // array-designator: '[' constant-expression '...' constant-expression ']'
188 // Also, we have to handle the case where the expression after the
189 // designator an an objc message send: '[' objc-message-expr ']'.
190 // Interesting cases are:
191 // [foo bar] -> objc message send
192 // [foo] -> array designator
193 // [foo ... bar] -> array designator
194 // [4][foo bar] -> obsolete GNU designation with objc message send.
196 // We do not need to check for an expression starting with [[ here. If it
197 // contains an Objective-C message send, then it is not an ill-formed
198 // attribute. If it is a lambda-expression within an array-designator, then
199 // it will be rejected because a constant-expression cannot begin with a
200 // lambda-expression.
201 InMessageExpressionRAIIObject InMessage(*this, true);
203 BalancedDelimiterTracker T(*this, tok::l_square);
205 SourceLocation StartLoc = T.getOpenLocation();
209 // If Objective-C is enabled and this is a typename (class message
210 // send) or send to 'super', parse this as a message send
211 // expression. We handle C++ and C separately, since C++ requires
212 // much more complicated parsing.
213 if (getLangOpts().ObjC1 && getLangOpts().CPlusPlus) {
215 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
216 NextToken().isNot(tok::period) &&
217 getCurScope()->isInObjcMethodScope()) {
218 CheckArrayDesignatorSyntax(*this, StartLoc, Desig);
219 return ParseAssignmentExprWithObjCMessageExprStart(
220 StartLoc, ConsumeToken(), nullptr, nullptr);
223 // Parse the receiver, which is either a type or an expression.
226 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
227 SkipUntil(tok::r_square, StopAtSemi);
231 // If the receiver was a type, we have a class message; parse
234 CheckArrayDesignatorSyntax(*this, StartLoc, Desig);
235 return ParseAssignmentExprWithObjCMessageExprStart(StartLoc,
237 ParsedType::getFromOpaquePtr(TypeOrExpr),
241 // If the receiver was an expression, we still don't know
242 // whether we have a message send or an array designator; just
243 // adopt the expression for further analysis below.
244 // FIXME: potentially-potentially evaluated expression above?
245 Idx = ExprResult(static_cast<Expr*>(TypeOrExpr));
246 } else if (getLangOpts().ObjC1 && Tok.is(tok::identifier)) {
247 IdentifierInfo *II = Tok.getIdentifierInfo();
248 SourceLocation IILoc = Tok.getLocation();
249 ParsedType ReceiverType;
250 // Three cases. This is a message send to a type: [type foo]
251 // This is a message send to super: [super foo]
252 // This is a message sent to an expr: [super.bar foo]
253 switch (Actions.getObjCMessageKind(
254 getCurScope(), II, IILoc, II == Ident_super,
255 NextToken().is(tok::period), ReceiverType)) {
256 case Sema::ObjCSuperMessage:
257 CheckArrayDesignatorSyntax(*this, StartLoc, Desig);
258 return ParseAssignmentExprWithObjCMessageExprStart(
259 StartLoc, ConsumeToken(), nullptr, nullptr);
261 case Sema::ObjCClassMessage:
262 CheckArrayDesignatorSyntax(*this, StartLoc, Desig);
263 ConsumeToken(); // the identifier
265 SkipUntil(tok::r_square, StopAtSemi);
269 // Parse type arguments and protocol qualifiers.
270 if (Tok.is(tok::less)) {
271 SourceLocation NewEndLoc;
272 TypeResult NewReceiverType
273 = parseObjCTypeArgsAndProtocolQualifiers(IILoc, ReceiverType,
274 /*consumeLastToken=*/true,
276 if (!NewReceiverType.isUsable()) {
277 SkipUntil(tok::r_square, StopAtSemi);
281 ReceiverType = NewReceiverType.get();
284 return ParseAssignmentExprWithObjCMessageExprStart(StartLoc,
289 case Sema::ObjCInstanceMessage:
290 // Fall through; we'll just parse the expression and
291 // (possibly) treat this like an Objective-C message send
297 // Parse the index expression, if we haven't already gotten one
298 // above (which can only happen in Objective-C++).
299 // Note that we parse this as an assignment expression, not a constant
300 // expression (allowing *=, =, etc) to handle the objc case. Sema needs
301 // to validate that the expression is a constant.
302 // FIXME: We also need to tell Sema that we're in a
303 // potentially-potentially evaluated context.
305 Idx = ParseAssignmentExpression();
306 if (Idx.isInvalid()) {
307 SkipUntil(tok::r_square, StopAtSemi);
312 // Given an expression, we could either have a designator (if the next
313 // tokens are '...' or ']' or an objc message send. If this is an objc
314 // message send, handle it now. An objc-message send is the start of
315 // an assignment-expression production.
316 if (getLangOpts().ObjC1 && Tok.isNot(tok::ellipsis) &&
317 Tok.isNot(tok::r_square)) {
318 CheckArrayDesignatorSyntax(*this, Tok.getLocation(), Desig);
319 return ParseAssignmentExprWithObjCMessageExprStart(
320 StartLoc, SourceLocation(), nullptr, Idx.get());
323 // If this is a normal array designator, remember it.
324 if (Tok.isNot(tok::ellipsis)) {
325 Desig.AddDesignator(Designator::getArray(Idx.get(), StartLoc));
327 // Handle the gnu array range extension.
328 Diag(Tok, diag::ext_gnu_array_range);
329 SourceLocation EllipsisLoc = ConsumeToken();
331 ExprResult RHS(ParseConstantExpression());
332 if (RHS.isInvalid()) {
333 SkipUntil(tok::r_square, StopAtSemi);
336 Desig.AddDesignator(Designator::getArrayRange(Idx.get(),
338 StartLoc, EllipsisLoc));
342 Desig.getDesignator(Desig.getNumDesignators() - 1).setRBracketLoc(
343 T.getCloseLocation());
346 // Okay, we're done with the designator sequence. We know that there must be
347 // at least one designator, because the only case we can get into this method
348 // without a designator is when we have an objc message send. That case is
349 // handled and returned from above.
350 assert(!Desig.empty() && "Designator is empty?");
352 // Handle a normal designator sequence end, which is an equal.
353 if (Tok.is(tok::equal)) {
354 SourceLocation EqualLoc = ConsumeToken();
355 return Actions.ActOnDesignatedInitializer(Desig, EqualLoc, false,
359 // We read some number of designators and found something that isn't an = or
360 // an initializer. If we have exactly one array designator, this
361 // is the GNU 'designation: array-designator' extension. Otherwise, it is a
363 if (Desig.getNumDesignators() == 1 &&
364 (Desig.getDesignator(0).isArrayDesignator() ||
365 Desig.getDesignator(0).isArrayRangeDesignator())) {
366 Diag(Tok, diag::ext_gnu_missing_equal_designator)
367 << FixItHint::CreateInsertion(Tok.getLocation(), "= ");
368 return Actions.ActOnDesignatedInitializer(Desig, Tok.getLocation(),
369 true, ParseInitializer());
372 Diag(Tok, diag::err_expected_equal_designator);
377 /// ParseBraceInitializer - Called when parsing an initializer that has a
378 /// leading open brace.
380 /// initializer: [C99 6.7.8]
381 /// '{' initializer-list '}'
382 /// '{' initializer-list ',' '}'
385 /// initializer-list:
386 /// designation[opt] initializer ...[opt]
387 /// initializer-list ',' designation[opt] initializer ...[opt]
389 ExprResult Parser::ParseBraceInitializer() {
390 InMessageExpressionRAIIObject InMessage(*this, false);
392 BalancedDelimiterTracker T(*this, tok::l_brace);
394 SourceLocation LBraceLoc = T.getOpenLocation();
396 /// InitExprs - This is the actual list of expressions contained in the
398 ExprVector InitExprs;
400 if (Tok.is(tok::r_brace)) {
401 // Empty initializers are a C++ feature and a GNU extension to C.
402 if (!getLangOpts().CPlusPlus)
403 Diag(LBraceLoc, diag::ext_gnu_empty_initializer);
405 return Actions.ActOnInitList(LBraceLoc, None, ConsumeBrace());
408 bool InitExprsOk = true;
411 // Handle Microsoft __if_exists/if_not_exists if necessary.
412 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
413 Tok.is(tok::kw___if_not_exists))) {
414 if (ParseMicrosoftIfExistsBraceInitializer(InitExprs, InitExprsOk)) {
415 if (Tok.isNot(tok::comma)) break;
418 if (Tok.is(tok::r_brace)) break;
422 // Parse: designation[opt] initializer
424 // If we know that this cannot be a designation, just parse the nested
425 // initializer directly.
427 if (MayBeDesignationStart())
428 SubElt = ParseInitializerWithPotentialDesignator();
430 SubElt = ParseInitializer();
432 if (Tok.is(tok::ellipsis))
433 SubElt = Actions.ActOnPackExpansion(SubElt.get(), ConsumeToken());
435 SubElt = Actions.CorrectDelayedTyposInExpr(SubElt.get());
437 // If we couldn't parse the subelement, bail out.
438 if (SubElt.isUsable()) {
439 InitExprs.push_back(SubElt.get());
443 // We have two ways to try to recover from this error: if the code looks
444 // grammatically ok (i.e. we have a comma coming up) try to continue
445 // parsing the rest of the initializer. This allows us to emit
446 // diagnostics for later elements that we find. If we don't see a comma,
447 // assume there is a parse error, and just skip to recover.
448 // FIXME: This comment doesn't sound right. If there is a r_brace
449 // immediately, it can't be an error, since there is no other way of
450 // leaving this loop except through this if.
451 if (Tok.isNot(tok::comma)) {
452 SkipUntil(tok::r_brace, StopBeforeMatch);
457 // If we don't have a comma continued list, we're done.
458 if (Tok.isNot(tok::comma)) break;
460 // TODO: save comma locations if some client cares.
463 // Handle trailing comma.
464 if (Tok.is(tok::r_brace)) break;
467 bool closed = !T.consumeClose();
469 if (InitExprsOk && closed)
470 return Actions.ActOnInitList(LBraceLoc, InitExprs,
471 T.getCloseLocation());
473 return ExprError(); // an error occurred.
477 // Return true if a comma (or closing brace) is necessary after the
478 // __if_exists/if_not_exists statement.
479 bool Parser::ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
481 bool trailingComma = false;
482 IfExistsCondition Result;
483 if (ParseMicrosoftIfExistsCondition(Result))
486 BalancedDelimiterTracker Braces(*this, tok::l_brace);
487 if (Braces.consumeOpen()) {
488 Diag(Tok, diag::err_expected) << tok::l_brace;
492 switch (Result.Behavior) {
494 // Parse the declarations below.
498 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
499 << Result.IsIfExists;
500 // Fall through to skip.
507 while (!isEofOrEom()) {
508 trailingComma = false;
509 // If we know that this cannot be a designation, just parse the nested
510 // initializer directly.
512 if (MayBeDesignationStart())
513 SubElt = ParseInitializerWithPotentialDesignator();
515 SubElt = ParseInitializer();
517 if (Tok.is(tok::ellipsis))
518 SubElt = Actions.ActOnPackExpansion(SubElt.get(), ConsumeToken());
520 // If we couldn't parse the subelement, bail out.
521 if (!SubElt.isInvalid())
522 InitExprs.push_back(SubElt.get());
526 if (Tok.is(tok::comma)) {
528 trailingComma = true;
531 if (Tok.is(tok::r_brace))
535 Braces.consumeClose();
537 return !trailingComma;