1 //===--- ParseInit.cpp - Initializer Parsing ------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements initializer parsing as specified by C99 6.7.8. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/Parse/ParseDiagnostic.h" 14 #include "clang/Parse/Parser.h" 15 #include "clang/Parse/RAIIObjectsForParser.h" 16 #include "clang/Sema/Designator.h" 17 #include "clang/Sema/Scope.h" 18 #include "llvm/ADT/SmallString.h" 19 using namespace clang; 20 21 22 /// MayBeDesignationStart - Return true if the current token might be the start 23 /// of a designator. If we can tell it is impossible that it is a designator, 24 /// return false. 25 bool Parser::MayBeDesignationStart() { 26 switch (Tok.getKind()) { 27 default: 28 return false; 29 30 case tok::period: // designator: '.' identifier 31 return true; 32 33 case tok::l_square: { // designator: array-designator 34 if (!PP.getLangOpts().CPlusPlus11) 35 return true; 36 37 // C++11 lambda expressions and C99 designators can be ambiguous all the 38 // way through the closing ']' and to the next character. Handle the easy 39 // cases here, and fall back to tentative parsing if those fail. 40 switch (PP.LookAhead(0).getKind()) { 41 case tok::equal: 42 case tok::r_square: 43 // Definitely starts a lambda expression. 44 return false; 45 46 case tok::amp: 47 case tok::kw_this: 48 case tok::star: 49 case tok::identifier: 50 // We have to do additional analysis, because these could be the 51 // start of a constant expression or a lambda capture list. 52 break; 53 54 default: 55 // Anything not mentioned above cannot occur following a '[' in a 56 // lambda expression. 57 return true; 58 } 59 60 // Handle the complicated case below. 61 break; 62 } 63 case tok::identifier: // designation: identifier ':' 64 return PP.LookAhead(0).is(tok::colon); 65 } 66 67 // Parse up to (at most) the token after the closing ']' to determine 68 // whether this is a C99 designator or a lambda. 69 RevertingTentativeParsingAction Tentative(*this); 70 71 LambdaIntroducer Intro; 72 LambdaIntroducerTentativeParse ParseResult; 73 if (ParseLambdaIntroducer(Intro, &ParseResult)) { 74 // Hit and diagnosed an error in a lambda. 75 // FIXME: Tell the caller this happened so they can recover. 76 return true; 77 } 78 79 switch (ParseResult) { 80 case LambdaIntroducerTentativeParse::Success: 81 case LambdaIntroducerTentativeParse::Incomplete: 82 // Might be a lambda-expression. Keep looking. 83 // FIXME: If our tentative parse was not incomplete, parse the lambda from 84 // here rather than throwing away then reparsing the LambdaIntroducer. 85 break; 86 87 case LambdaIntroducerTentativeParse::MessageSend: 88 case LambdaIntroducerTentativeParse::Invalid: 89 // Can't be a lambda-expression. Treat it as a designator. 90 // FIXME: Should we disambiguate against a message-send? 91 return true; 92 } 93 94 // Once we hit the closing square bracket, we look at the next 95 // token. If it's an '=', this is a designator. Otherwise, it's a 96 // lambda expression. This decision favors lambdas over the older 97 // GNU designator syntax, which allows one to omit the '=', but is 98 // consistent with GCC. 99 return Tok.is(tok::equal); 100 } 101 102 static void CheckArrayDesignatorSyntax(Parser &P, SourceLocation Loc, 103 Designation &Desig) { 104 // If we have exactly one array designator, this used the GNU 105 // 'designation: array-designator' extension, otherwise there should be no 106 // designators at all! 107 if (Desig.getNumDesignators() == 1 && 108 (Desig.getDesignator(0).isArrayDesignator() || 109 Desig.getDesignator(0).isArrayRangeDesignator())) 110 P.Diag(Loc, diag::ext_gnu_missing_equal_designator); 111 else if (Desig.getNumDesignators() > 0) 112 P.Diag(Loc, diag::err_expected_equal_designator); 113 } 114 115 /// ParseInitializerWithPotentialDesignator - Parse the 'initializer' production 116 /// checking to see if the token stream starts with a designator. 117 /// 118 /// designation: 119 /// designator-list '=' 120 /// [GNU] array-designator 121 /// [GNU] identifier ':' 122 /// 123 /// designator-list: 124 /// designator 125 /// designator-list designator 126 /// 127 /// designator: 128 /// array-designator 129 /// '.' identifier 130 /// 131 /// array-designator: 132 /// '[' constant-expression ']' 133 /// [GNU] '[' constant-expression '...' constant-expression ']' 134 /// 135 /// NOTE: [OBC] allows '[ objc-receiver objc-message-args ]' as an 136 /// initializer (because it is an expression). We need to consider this case 137 /// when parsing array designators. 138 /// 139 ExprResult Parser::ParseInitializerWithPotentialDesignator() { 140 141 // If this is the old-style GNU extension: 142 // designation ::= identifier ':' 143 // Handle it as a field designator. Otherwise, this must be the start of a 144 // normal expression. 145 if (Tok.is(tok::identifier)) { 146 const IdentifierInfo *FieldName = Tok.getIdentifierInfo(); 147 148 SmallString<256> NewSyntax; 149 llvm::raw_svector_ostream(NewSyntax) << '.' << FieldName->getName() 150 << " = "; 151 152 SourceLocation NameLoc = ConsumeToken(); // Eat the identifier. 153 154 assert(Tok.is(tok::colon) && "MayBeDesignationStart not working properly!"); 155 SourceLocation ColonLoc = ConsumeToken(); 156 157 Diag(NameLoc, diag::ext_gnu_old_style_field_designator) 158 << FixItHint::CreateReplacement(SourceRange(NameLoc, ColonLoc), 159 NewSyntax); 160 161 Designation D; 162 D.AddDesignator(Designator::getField(FieldName, SourceLocation(), NameLoc)); 163 return Actions.ActOnDesignatedInitializer(D, ColonLoc, true, 164 ParseInitializer()); 165 } 166 167 // Desig - This is initialized when we see our first designator. We may have 168 // an objc message send with no designator, so we don't want to create this 169 // eagerly. 170 Designation Desig; 171 172 // Parse each designator in the designator list until we find an initializer. 173 while (Tok.is(tok::period) || Tok.is(tok::l_square)) { 174 if (Tok.is(tok::period)) { 175 // designator: '.' identifier 176 SourceLocation DotLoc = ConsumeToken(); 177 178 if (Tok.isNot(tok::identifier)) { 179 Diag(Tok.getLocation(), diag::err_expected_field_designator); 180 return ExprError(); 181 } 182 183 Desig.AddDesignator(Designator::getField(Tok.getIdentifierInfo(), DotLoc, 184 Tok.getLocation())); 185 ConsumeToken(); // Eat the identifier. 186 continue; 187 } 188 189 // We must have either an array designator now or an objc message send. 190 assert(Tok.is(tok::l_square) && "Unexpected token!"); 191 192 // Handle the two forms of array designator: 193 // array-designator: '[' constant-expression ']' 194 // array-designator: '[' constant-expression '...' constant-expression ']' 195 // 196 // Also, we have to handle the case where the expression after the 197 // designator an an objc message send: '[' objc-message-expr ']'. 198 // Interesting cases are: 199 // [foo bar] -> objc message send 200 // [foo] -> array designator 201 // [foo ... bar] -> array designator 202 // [4][foo bar] -> obsolete GNU designation with objc message send. 203 // 204 // We do not need to check for an expression starting with [[ here. If it 205 // contains an Objective-C message send, then it is not an ill-formed 206 // attribute. If it is a lambda-expression within an array-designator, then 207 // it will be rejected because a constant-expression cannot begin with a 208 // lambda-expression. 209 InMessageExpressionRAIIObject InMessage(*this, true); 210 211 BalancedDelimiterTracker T(*this, tok::l_square); 212 T.consumeOpen(); 213 SourceLocation StartLoc = T.getOpenLocation(); 214 215 ExprResult Idx; 216 217 // If Objective-C is enabled and this is a typename (class message 218 // send) or send to 'super', parse this as a message send 219 // expression. We handle C++ and C separately, since C++ requires 220 // much more complicated parsing. 221 if (getLangOpts().ObjC && getLangOpts().CPlusPlus) { 222 // Send to 'super'. 223 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super && 224 NextToken().isNot(tok::period) && 225 getCurScope()->isInObjcMethodScope()) { 226 CheckArrayDesignatorSyntax(*this, StartLoc, Desig); 227 return ParseAssignmentExprWithObjCMessageExprStart( 228 StartLoc, ConsumeToken(), nullptr, nullptr); 229 } 230 231 // Parse the receiver, which is either a type or an expression. 232 bool IsExpr; 233 void *TypeOrExpr; 234 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) { 235 SkipUntil(tok::r_square, StopAtSemi); 236 return ExprError(); 237 } 238 239 // If the receiver was a type, we have a class message; parse 240 // the rest of it. 241 if (!IsExpr) { 242 CheckArrayDesignatorSyntax(*this, StartLoc, Desig); 243 return ParseAssignmentExprWithObjCMessageExprStart(StartLoc, 244 SourceLocation(), 245 ParsedType::getFromOpaquePtr(TypeOrExpr), 246 nullptr); 247 } 248 249 // If the receiver was an expression, we still don't know 250 // whether we have a message send or an array designator; just 251 // adopt the expression for further analysis below. 252 // FIXME: potentially-potentially evaluated expression above? 253 Idx = ExprResult(static_cast<Expr*>(TypeOrExpr)); 254 } else if (getLangOpts().ObjC && Tok.is(tok::identifier)) { 255 IdentifierInfo *II = Tok.getIdentifierInfo(); 256 SourceLocation IILoc = Tok.getLocation(); 257 ParsedType ReceiverType; 258 // Three cases. This is a message send to a type: [type foo] 259 // This is a message send to super: [super foo] 260 // This is a message sent to an expr: [super.bar foo] 261 switch (Actions.getObjCMessageKind( 262 getCurScope(), II, IILoc, II == Ident_super, 263 NextToken().is(tok::period), ReceiverType)) { 264 case Sema::ObjCSuperMessage: 265 CheckArrayDesignatorSyntax(*this, StartLoc, Desig); 266 return ParseAssignmentExprWithObjCMessageExprStart( 267 StartLoc, ConsumeToken(), nullptr, nullptr); 268 269 case Sema::ObjCClassMessage: 270 CheckArrayDesignatorSyntax(*this, StartLoc, Desig); 271 ConsumeToken(); // the identifier 272 if (!ReceiverType) { 273 SkipUntil(tok::r_square, StopAtSemi); 274 return ExprError(); 275 } 276 277 // Parse type arguments and protocol qualifiers. 278 if (Tok.is(tok::less)) { 279 SourceLocation NewEndLoc; 280 TypeResult NewReceiverType 281 = parseObjCTypeArgsAndProtocolQualifiers(IILoc, ReceiverType, 282 /*consumeLastToken=*/true, 283 NewEndLoc); 284 if (!NewReceiverType.isUsable()) { 285 SkipUntil(tok::r_square, StopAtSemi); 286 return ExprError(); 287 } 288 289 ReceiverType = NewReceiverType.get(); 290 } 291 292 return ParseAssignmentExprWithObjCMessageExprStart(StartLoc, 293 SourceLocation(), 294 ReceiverType, 295 nullptr); 296 297 case Sema::ObjCInstanceMessage: 298 // Fall through; we'll just parse the expression and 299 // (possibly) treat this like an Objective-C message send 300 // later. 301 break; 302 } 303 } 304 305 // Parse the index expression, if we haven't already gotten one 306 // above (which can only happen in Objective-C++). 307 // Note that we parse this as an assignment expression, not a constant 308 // expression (allowing *=, =, etc) to handle the objc case. Sema needs 309 // to validate that the expression is a constant. 310 // FIXME: We also need to tell Sema that we're in a 311 // potentially-potentially evaluated context. 312 if (!Idx.get()) { 313 Idx = ParseAssignmentExpression(); 314 if (Idx.isInvalid()) { 315 SkipUntil(tok::r_square, StopAtSemi); 316 return Idx; 317 } 318 } 319 320 // Given an expression, we could either have a designator (if the next 321 // tokens are '...' or ']' or an objc message send. If this is an objc 322 // message send, handle it now. An objc-message send is the start of 323 // an assignment-expression production. 324 if (getLangOpts().ObjC && Tok.isNot(tok::ellipsis) && 325 Tok.isNot(tok::r_square)) { 326 CheckArrayDesignatorSyntax(*this, Tok.getLocation(), Desig); 327 return ParseAssignmentExprWithObjCMessageExprStart( 328 StartLoc, SourceLocation(), nullptr, Idx.get()); 329 } 330 331 // If this is a normal array designator, remember it. 332 if (Tok.isNot(tok::ellipsis)) { 333 Desig.AddDesignator(Designator::getArray(Idx.get(), 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.get(), 345 RHS.get(), 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 // Enter an appropriate expression evaluation context for an initializer list. 417 EnterExpressionEvaluationContext EnterContext( 418 Actions, EnterExpressionEvaluationContext::InitList); 419 420 bool InitExprsOk = true; 421 422 while (1) { 423 // Handle Microsoft __if_exists/if_not_exists if necessary. 424 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) || 425 Tok.is(tok::kw___if_not_exists))) { 426 if (ParseMicrosoftIfExistsBraceInitializer(InitExprs, InitExprsOk)) { 427 if (Tok.isNot(tok::comma)) break; 428 ConsumeToken(); 429 } 430 if (Tok.is(tok::r_brace)) break; 431 continue; 432 } 433 434 // Parse: designation[opt] initializer 435 436 // If we know that this cannot be a designation, just parse the nested 437 // initializer directly. 438 ExprResult SubElt; 439 if (MayBeDesignationStart()) 440 SubElt = ParseInitializerWithPotentialDesignator(); 441 else 442 SubElt = ParseInitializer(); 443 444 if (Tok.is(tok::ellipsis)) 445 SubElt = Actions.ActOnPackExpansion(SubElt.get(), ConsumeToken()); 446 447 SubElt = Actions.CorrectDelayedTyposInExpr(SubElt.get()); 448 449 // If we couldn't parse the subelement, bail out. 450 if (SubElt.isUsable()) { 451 InitExprs.push_back(SubElt.get()); 452 } else { 453 InitExprsOk = false; 454 455 // We have two ways to try to recover from this error: if the code looks 456 // grammatically ok (i.e. we have a comma coming up) try to continue 457 // parsing the rest of the initializer. This allows us to emit 458 // diagnostics for later elements that we find. If we don't see a comma, 459 // assume there is a parse error, and just skip to recover. 460 // FIXME: This comment doesn't sound right. If there is a r_brace 461 // immediately, it can't be an error, since there is no other way of 462 // leaving this loop except through this if. 463 if (Tok.isNot(tok::comma)) { 464 SkipUntil(tok::r_brace, StopBeforeMatch); 465 break; 466 } 467 } 468 469 // If we don't have a comma continued list, we're done. 470 if (Tok.isNot(tok::comma)) break; 471 472 // TODO: save comma locations if some client cares. 473 ConsumeToken(); 474 475 // Handle trailing comma. 476 if (Tok.is(tok::r_brace)) break; 477 } 478 479 bool closed = !T.consumeClose(); 480 481 if (InitExprsOk && closed) 482 return Actions.ActOnInitList(LBraceLoc, InitExprs, 483 T.getCloseLocation()); 484 485 return ExprError(); // an error occurred. 486 } 487 488 489 // Return true if a comma (or closing brace) is necessary after the 490 // __if_exists/if_not_exists statement. 491 bool Parser::ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs, 492 bool &InitExprsOk) { 493 bool trailingComma = false; 494 IfExistsCondition Result; 495 if (ParseMicrosoftIfExistsCondition(Result)) 496 return false; 497 498 BalancedDelimiterTracker Braces(*this, tok::l_brace); 499 if (Braces.consumeOpen()) { 500 Diag(Tok, diag::err_expected) << tok::l_brace; 501 return false; 502 } 503 504 switch (Result.Behavior) { 505 case IEB_Parse: 506 // Parse the declarations below. 507 break; 508 509 case IEB_Dependent: 510 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists) 511 << Result.IsIfExists; 512 // Fall through to skip. 513 LLVM_FALLTHROUGH; 514 515 case IEB_Skip: 516 Braces.skipToEnd(); 517 return false; 518 } 519 520 while (!isEofOrEom()) { 521 trailingComma = false; 522 // If we know that this cannot be a designation, just parse the nested 523 // initializer directly. 524 ExprResult SubElt; 525 if (MayBeDesignationStart()) 526 SubElt = ParseInitializerWithPotentialDesignator(); 527 else 528 SubElt = ParseInitializer(); 529 530 if (Tok.is(tok::ellipsis)) 531 SubElt = Actions.ActOnPackExpansion(SubElt.get(), ConsumeToken()); 532 533 // If we couldn't parse the subelement, bail out. 534 if (!SubElt.isInvalid()) 535 InitExprs.push_back(SubElt.get()); 536 else 537 InitExprsOk = false; 538 539 if (Tok.is(tok::comma)) { 540 ConsumeToken(); 541 trailingComma = true; 542 } 543 544 if (Tok.is(tok::r_brace)) 545 break; 546 } 547 548 Braces.consumeClose(); 549 550 return !trailingComma; 551 } 552