1 //===--- ParseInit.cpp - Initializer Parsing ------------------------------===// 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 initializer parsing as specified by C99 6.7.8. 11 // 12 //===----------------------------------------------------------------------===// 13 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; 22 23 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, 26 /// return false. 27 bool Parser::MayBeDesignationStart() { 28 switch (Tok.getKind()) { 29 default: 30 return false; 31 32 case tok::period: // designator: '.' identifier 33 return true; 34 35 case tok::l_square: { // designator: array-designator 36 if (!PP.getLangOpts().CPlusPlus11) 37 return true; 38 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()) { 43 case tok::equal: 44 case tok::r_square: 45 // Definitely starts a lambda expression. 46 return false; 47 48 case tok::amp: 49 case tok::kw_this: 50 case tok::identifier: 51 // We have to do additional analysis, because these could be the 52 // start of a constant expression or a lambda capture list. 53 break; 54 55 default: 56 // Anything not mentioned above cannot occur following a '[' in a 57 // lambda expression. 58 return true; 59 } 60 61 // Handle the complicated case below. 62 break; 63 } 64 case tok::identifier: // designation: identifier ':' 65 return PP.LookAhead(0).is(tok::colon); 66 } 67 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); 71 ConsumeBracket(); 72 while (true) { 73 switch (Tok.getKind()) { 74 case tok::equal: 75 case tok::amp: 76 case tok::identifier: 77 case tok::kw_this: 78 // These tokens can occur in a capture list or a constant-expression. 79 // Keep looking. 80 ConsumeToken(); 81 continue; 82 83 case tok::comma: 84 // Since a comma cannot occur in a constant-expression, this must 85 // be a lambda. 86 Tentative.Revert(); 87 return false; 88 89 case tok::r_square: { 90 // Once we hit the closing square bracket, we look at the next 91 // token. If it's an '=', this is a designator. Otherwise, it's a 92 // lambda expression. This decision favors lambdas over the older 93 // GNU designator syntax, which allows one to omit the '=', but is 94 // consistent with GCC. 95 ConsumeBracket(); 96 tok::TokenKind Kind = Tok.getKind(); 97 Tentative.Revert(); 98 return Kind == tok::equal; 99 } 100 101 default: 102 // Anything else cannot occur in a lambda capture list, so it 103 // must be a designator. 104 Tentative.Revert(); 105 return true; 106 } 107 } 108 } 109 110 static void CheckArrayDesignatorSyntax(Parser &P, SourceLocation Loc, 111 Designation &Desig) { 112 // If we have exactly one array designator, this used the GNU 113 // 'designation: array-designator' extension, otherwise there should be no 114 // designators at all! 115 if (Desig.getNumDesignators() == 1 && 116 (Desig.getDesignator(0).isArrayDesignator() || 117 Desig.getDesignator(0).isArrayRangeDesignator())) 118 P.Diag(Loc, diag::ext_gnu_missing_equal_designator); 119 else if (Desig.getNumDesignators() > 0) 120 P.Diag(Loc, diag::err_expected_equal_designator); 121 } 122 123 /// ParseInitializerWithPotentialDesignator - Parse the 'initializer' production 124 /// checking to see if the token stream starts with a designator. 125 /// 126 /// designation: 127 /// designator-list '=' 128 /// [GNU] array-designator 129 /// [GNU] identifier ':' 130 /// 131 /// designator-list: 132 /// designator 133 /// designator-list designator 134 /// 135 /// designator: 136 /// array-designator 137 /// '.' identifier 138 /// 139 /// array-designator: 140 /// '[' constant-expression ']' 141 /// [GNU] '[' constant-expression '...' constant-expression ']' 142 /// 143 /// NOTE: [OBC] allows '[ objc-receiver objc-message-args ]' as an 144 /// initializer (because it is an expression). We need to consider this case 145 /// when parsing array designators. 146 /// 147 ExprResult Parser::ParseInitializerWithPotentialDesignator() { 148 149 // If this is the old-style GNU extension: 150 // designation ::= identifier ':' 151 // Handle it as a field designator. Otherwise, this must be the start of a 152 // normal expression. 153 if (Tok.is(tok::identifier)) { 154 const IdentifierInfo *FieldName = Tok.getIdentifierInfo(); 155 156 SmallString<256> NewSyntax; 157 llvm::raw_svector_ostream(NewSyntax) << '.' << FieldName->getName() 158 << " = "; 159 160 SourceLocation NameLoc = ConsumeToken(); // Eat the identifier. 161 162 assert(Tok.is(tok::colon) && "MayBeDesignationStart not working properly!"); 163 SourceLocation ColonLoc = ConsumeToken(); 164 165 Diag(NameLoc, diag::ext_gnu_old_style_field_designator) 166 << FixItHint::CreateReplacement(SourceRange(NameLoc, ColonLoc), 167 NewSyntax.str()); 168 169 Designation D; 170 D.AddDesignator(Designator::getField(FieldName, SourceLocation(), NameLoc)); 171 return Actions.ActOnDesignatedInitializer(D, ColonLoc, true, 172 ParseInitializer()); 173 } 174 175 // Desig - This is initialized when we see our first designator. We may have 176 // an objc message send with no designator, so we don't want to create this 177 // eagerly. 178 Designation Desig; 179 180 // Parse each designator in the designator list until we find an initializer. 181 while (Tok.is(tok::period) || Tok.is(tok::l_square)) { 182 if (Tok.is(tok::period)) { 183 // designator: '.' identifier 184 SourceLocation DotLoc = ConsumeToken(); 185 186 if (Tok.isNot(tok::identifier)) { 187 Diag(Tok.getLocation(), diag::err_expected_field_designator); 188 return ExprError(); 189 } 190 191 Desig.AddDesignator(Designator::getField(Tok.getIdentifierInfo(), DotLoc, 192 Tok.getLocation())); 193 ConsumeToken(); // Eat the identifier. 194 continue; 195 } 196 197 // We must have either an array designator now or an objc message send. 198 assert(Tok.is(tok::l_square) && "Unexpected token!"); 199 200 // Handle the two forms of array designator: 201 // array-designator: '[' constant-expression ']' 202 // array-designator: '[' constant-expression '...' constant-expression ']' 203 // 204 // Also, we have to handle the case where the expression after the 205 // designator an an objc message send: '[' objc-message-expr ']'. 206 // Interesting cases are: 207 // [foo bar] -> objc message send 208 // [foo] -> array designator 209 // [foo ... bar] -> array designator 210 // [4][foo bar] -> obsolete GNU designation with objc message send. 211 // 212 // We do not need to check for an expression starting with [[ here. If it 213 // contains an Objective-C message send, then it is not an ill-formed 214 // attribute. If it is a lambda-expression within an array-designator, then 215 // it will be rejected because a constant-expression cannot begin with a 216 // lambda-expression. 217 InMessageExpressionRAIIObject InMessage(*this, true); 218 219 BalancedDelimiterTracker T(*this, tok::l_square); 220 T.consumeOpen(); 221 SourceLocation StartLoc = T.getOpenLocation(); 222 223 ExprResult Idx; 224 225 // If Objective-C is enabled and this is a typename (class message 226 // send) or send to 'super', parse this as a message send 227 // expression. We handle C++ and C separately, since C++ requires 228 // much more complicated parsing. 229 if (getLangOpts().ObjC1 && getLangOpts().CPlusPlus) { 230 // Send to 'super'. 231 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super && 232 NextToken().isNot(tok::period) && 233 getCurScope()->isInObjcMethodScope()) { 234 CheckArrayDesignatorSyntax(*this, StartLoc, Desig); 235 return ParseAssignmentExprWithObjCMessageExprStart(StartLoc, 236 ConsumeToken(), 237 ParsedType(), 238 0); 239 } 240 241 // Parse the receiver, which is either a type or an expression. 242 bool IsExpr; 243 void *TypeOrExpr; 244 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) { 245 SkipUntil(tok::r_square, StopAtSemi); 246 return ExprError(); 247 } 248 249 // If the receiver was a type, we have a class message; parse 250 // the rest of it. 251 if (!IsExpr) { 252 CheckArrayDesignatorSyntax(*this, StartLoc, Desig); 253 return ParseAssignmentExprWithObjCMessageExprStart(StartLoc, 254 SourceLocation(), 255 ParsedType::getFromOpaquePtr(TypeOrExpr), 256 0); 257 } 258 259 // If the receiver was an expression, we still don't know 260 // whether we have a message send or an array designator; just 261 // adopt the expression for further analysis below. 262 // FIXME: potentially-potentially evaluated expression above? 263 Idx = ExprResult(static_cast<Expr*>(TypeOrExpr)); 264 } else if (getLangOpts().ObjC1 && Tok.is(tok::identifier)) { 265 IdentifierInfo *II = Tok.getIdentifierInfo(); 266 SourceLocation IILoc = Tok.getLocation(); 267 ParsedType ReceiverType; 268 // Three cases. This is a message send to a type: [type foo] 269 // This is a message send to super: [super foo] 270 // This is a message sent to an expr: [super.bar foo] 271 switch (Sema::ObjCMessageKind Kind 272 = Actions.getObjCMessageKind(getCurScope(), II, IILoc, 273 II == Ident_super, 274 NextToken().is(tok::period), 275 ReceiverType)) { 276 case Sema::ObjCSuperMessage: 277 case Sema::ObjCClassMessage: 278 CheckArrayDesignatorSyntax(*this, StartLoc, Desig); 279 if (Kind == Sema::ObjCSuperMessage) 280 return ParseAssignmentExprWithObjCMessageExprStart(StartLoc, 281 ConsumeToken(), 282 ParsedType(), 283 0); 284 ConsumeToken(); // the identifier 285 if (!ReceiverType) { 286 SkipUntil(tok::r_square, StopAtSemi); 287 return ExprError(); 288 } 289 290 return ParseAssignmentExprWithObjCMessageExprStart(StartLoc, 291 SourceLocation(), 292 ReceiverType, 293 0); 294 295 case Sema::ObjCInstanceMessage: 296 // Fall through; we'll just parse the expression and 297 // (possibly) treat this like an Objective-C message send 298 // later. 299 break; 300 } 301 } 302 303 // Parse the index expression, if we haven't already gotten one 304 // above (which can only happen in Objective-C++). 305 // Note that we parse this as an assignment expression, not a constant 306 // expression (allowing *=, =, etc) to handle the objc case. Sema needs 307 // to validate that the expression is a constant. 308 // FIXME: We also need to tell Sema that we're in a 309 // potentially-potentially evaluated context. 310 if (!Idx.get()) { 311 Idx = ParseAssignmentExpression(); 312 if (Idx.isInvalid()) { 313 SkipUntil(tok::r_square, StopAtSemi); 314 return Idx; 315 } 316 } 317 318 // Given an expression, we could either have a designator (if the next 319 // tokens are '...' or ']' or an objc message send. If this is an objc 320 // message send, handle it now. An objc-message send is the start of 321 // an assignment-expression production. 322 if (getLangOpts().ObjC1 && Tok.isNot(tok::ellipsis) && 323 Tok.isNot(tok::r_square)) { 324 CheckArrayDesignatorSyntax(*this, Tok.getLocation(), Desig); 325 return ParseAssignmentExprWithObjCMessageExprStart(StartLoc, 326 SourceLocation(), 327 ParsedType(), 328 Idx.take()); 329 } 330 331 // If this is a normal array designator, remember it. 332 if (Tok.isNot(tok::ellipsis)) { 333 Desig.AddDesignator(Designator::getArray(Idx.release(), StartLoc)); 334 } else { 335 // Handle the gnu array range extension. 336 Diag(Tok, diag::ext_gnu_array_range); 337 SourceLocation EllipsisLoc = ConsumeToken(); 338 339 ExprResult RHS(ParseConstantExpression()); 340 if (RHS.isInvalid()) { 341 SkipUntil(tok::r_square, StopAtSemi); 342 return RHS; 343 } 344 Desig.AddDesignator(Designator::getArrayRange(Idx.release(), 345 RHS.release(), 346 StartLoc, EllipsisLoc)); 347 } 348 349 T.consumeClose(); 350 Desig.getDesignator(Desig.getNumDesignators() - 1).setRBracketLoc( 351 T.getCloseLocation()); 352 } 353 354 // Okay, we're done with the designator sequence. We know that there must be 355 // at least one designator, because the only case we can get into this method 356 // without a designator is when we have an objc message send. That case is 357 // handled and returned from above. 358 assert(!Desig.empty() && "Designator is empty?"); 359 360 // Handle a normal designator sequence end, which is an equal. 361 if (Tok.is(tok::equal)) { 362 SourceLocation EqualLoc = ConsumeToken(); 363 return Actions.ActOnDesignatedInitializer(Desig, EqualLoc, false, 364 ParseInitializer()); 365 } 366 367 // We read some number of designators and found something that isn't an = or 368 // an initializer. If we have exactly one array designator, this 369 // is the GNU 'designation: array-designator' extension. Otherwise, it is a 370 // parse error. 371 if (Desig.getNumDesignators() == 1 && 372 (Desig.getDesignator(0).isArrayDesignator() || 373 Desig.getDesignator(0).isArrayRangeDesignator())) { 374 Diag(Tok, diag::ext_gnu_missing_equal_designator) 375 << FixItHint::CreateInsertion(Tok.getLocation(), "= "); 376 return Actions.ActOnDesignatedInitializer(Desig, Tok.getLocation(), 377 true, ParseInitializer()); 378 } 379 380 Diag(Tok, diag::err_expected_equal_designator); 381 return ExprError(); 382 } 383 384 385 /// ParseBraceInitializer - Called when parsing an initializer that has a 386 /// leading open brace. 387 /// 388 /// initializer: [C99 6.7.8] 389 /// '{' initializer-list '}' 390 /// '{' initializer-list ',' '}' 391 /// [GNU] '{' '}' 392 /// 393 /// initializer-list: 394 /// designation[opt] initializer ...[opt] 395 /// initializer-list ',' designation[opt] initializer ...[opt] 396 /// 397 ExprResult Parser::ParseBraceInitializer() { 398 InMessageExpressionRAIIObject InMessage(*this, false); 399 400 BalancedDelimiterTracker T(*this, tok::l_brace); 401 T.consumeOpen(); 402 SourceLocation LBraceLoc = T.getOpenLocation(); 403 404 /// InitExprs - This is the actual list of expressions contained in the 405 /// initializer. 406 ExprVector InitExprs; 407 408 if (Tok.is(tok::r_brace)) { 409 // Empty initializers are a C++ feature and a GNU extension to C. 410 if (!getLangOpts().CPlusPlus) 411 Diag(LBraceLoc, diag::ext_gnu_empty_initializer); 412 // Match the '}'. 413 return Actions.ActOnInitList(LBraceLoc, None, ConsumeBrace()); 414 } 415 416 bool InitExprsOk = true; 417 418 while (1) { 419 // Handle Microsoft __if_exists/if_not_exists if necessary. 420 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) || 421 Tok.is(tok::kw___if_not_exists))) { 422 if (ParseMicrosoftIfExistsBraceInitializer(InitExprs, InitExprsOk)) { 423 if (Tok.isNot(tok::comma)) break; 424 ConsumeToken(); 425 } 426 if (Tok.is(tok::r_brace)) break; 427 continue; 428 } 429 430 // Parse: designation[opt] initializer 431 432 // If we know that this cannot be a designation, just parse the nested 433 // initializer directly. 434 ExprResult SubElt; 435 if (MayBeDesignationStart()) 436 SubElt = ParseInitializerWithPotentialDesignator(); 437 else 438 SubElt = ParseInitializer(); 439 440 if (Tok.is(tok::ellipsis)) 441 SubElt = Actions.ActOnPackExpansion(SubElt.get(), ConsumeToken()); 442 443 // If we couldn't parse the subelement, bail out. 444 if (!SubElt.isInvalid()) { 445 InitExprs.push_back(SubElt.release()); 446 } else { 447 InitExprsOk = false; 448 449 // We have two ways to try to recover from this error: if the code looks 450 // grammatically ok (i.e. we have a comma coming up) try to continue 451 // parsing the rest of the initializer. This allows us to emit 452 // diagnostics for later elements that we find. If we don't see a comma, 453 // assume there is a parse error, and just skip to recover. 454 // FIXME: This comment doesn't sound right. If there is a r_brace 455 // immediately, it can't be an error, since there is no other way of 456 // leaving this loop except through this if. 457 if (Tok.isNot(tok::comma)) { 458 SkipUntil(tok::r_brace, StopBeforeMatch); 459 break; 460 } 461 } 462 463 // If we don't have a comma continued list, we're done. 464 if (Tok.isNot(tok::comma)) break; 465 466 // TODO: save comma locations if some client cares. 467 ConsumeToken(); 468 469 // Handle trailing comma. 470 if (Tok.is(tok::r_brace)) break; 471 } 472 473 bool closed = !T.consumeClose(); 474 475 if (InitExprsOk && closed) 476 return Actions.ActOnInitList(LBraceLoc, InitExprs, 477 T.getCloseLocation()); 478 479 return ExprError(); // an error occurred. 480 } 481 482 483 // Return true if a comma (or closing brace) is necessary after the 484 // __if_exists/if_not_exists statement. 485 bool Parser::ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs, 486 bool &InitExprsOk) { 487 bool trailingComma = false; 488 IfExistsCondition Result; 489 if (ParseMicrosoftIfExistsCondition(Result)) 490 return false; 491 492 BalancedDelimiterTracker Braces(*this, tok::l_brace); 493 if (Braces.consumeOpen()) { 494 Diag(Tok, diag::err_expected) << tok::l_brace; 495 return false; 496 } 497 498 switch (Result.Behavior) { 499 case IEB_Parse: 500 // Parse the declarations below. 501 break; 502 503 case IEB_Dependent: 504 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists) 505 << Result.IsIfExists; 506 // Fall through to skip. 507 508 case IEB_Skip: 509 Braces.skipToEnd(); 510 return false; 511 } 512 513 while (!isEofOrEom()) { 514 trailingComma = false; 515 // If we know that this cannot be a designation, just parse the nested 516 // initializer directly. 517 ExprResult SubElt; 518 if (MayBeDesignationStart()) 519 SubElt = ParseInitializerWithPotentialDesignator(); 520 else 521 SubElt = ParseInitializer(); 522 523 if (Tok.is(tok::ellipsis)) 524 SubElt = Actions.ActOnPackExpansion(SubElt.get(), ConsumeToken()); 525 526 // If we couldn't parse the subelement, bail out. 527 if (!SubElt.isInvalid()) 528 InitExprs.push_back(SubElt.release()); 529 else 530 InitExprsOk = false; 531 532 if (Tok.is(tok::comma)) { 533 ConsumeToken(); 534 trailingComma = true; 535 } 536 537 if (Tok.is(tok::r_brace)) 538 break; 539 } 540 541 Braces.consumeClose(); 542 543 return !trailingComma; 544 } 545