ParseDecl.cpp revision 239a53edc946f3756635b2d230f62ed43dbbbef7
1//===--- ParseDecl.cpp - Declaration 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 the Declaration portions of the Parser interfaces. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Parse/Parser.h" 15#include "clang/Parse/ParseDiagnostic.h" 16#include "clang/Parse/Scope.h" 17#include "ExtensionRAIIObject.h" 18#include "AstGuard.h" 19#include "llvm/ADT/SmallSet.h" 20using namespace clang; 21 22//===----------------------------------------------------------------------===// 23// C99 6.7: Declarations. 24//===----------------------------------------------------------------------===// 25 26/// ParseTypeName 27/// type-name: [C99 6.7.6] 28/// specifier-qualifier-list abstract-declarator[opt] 29/// 30/// Called type-id in C++. 31Action::TypeResult Parser::ParseTypeName() { 32 // Parse the common declaration-specifiers piece. 33 DeclSpec DS; 34 ParseSpecifierQualifierList(DS); 35 36 // Parse the abstract-declarator, if present. 37 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 38 ParseDeclarator(DeclaratorInfo); 39 40 if (DeclaratorInfo.getInvalidType()) 41 return true; 42 43 return Actions.ActOnTypeName(CurScope, DeclaratorInfo); 44} 45 46/// ParseAttributes - Parse a non-empty attributes list. 47/// 48/// [GNU] attributes: 49/// attribute 50/// attributes attribute 51/// 52/// [GNU] attribute: 53/// '__attribute__' '(' '(' attribute-list ')' ')' 54/// 55/// [GNU] attribute-list: 56/// attrib 57/// attribute_list ',' attrib 58/// 59/// [GNU] attrib: 60/// empty 61/// attrib-name 62/// attrib-name '(' identifier ')' 63/// attrib-name '(' identifier ',' nonempty-expr-list ')' 64/// attrib-name '(' argument-expression-list [C99 6.5.2] ')' 65/// 66/// [GNU] attrib-name: 67/// identifier 68/// typespec 69/// typequal 70/// storageclass 71/// 72/// FIXME: The GCC grammar/code for this construct implies we need two 73/// token lookahead. Comment from gcc: "If they start with an identifier 74/// which is followed by a comma or close parenthesis, then the arguments 75/// start with that identifier; otherwise they are an expression list." 76/// 77/// At the moment, I am not doing 2 token lookahead. I am also unaware of 78/// any attributes that don't work (based on my limited testing). Most 79/// attributes are very simple in practice. Until we find a bug, I don't see 80/// a pressing need to implement the 2 token lookahead. 81 82AttributeList *Parser::ParseAttributes(SourceLocation *EndLoc) { 83 assert(Tok.is(tok::kw___attribute) && "Not an attribute list!"); 84 85 AttributeList *CurrAttr = 0; 86 87 while (Tok.is(tok::kw___attribute)) { 88 ConsumeToken(); 89 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, 90 "attribute")) { 91 SkipUntil(tok::r_paren, true); // skip until ) or ; 92 return CurrAttr; 93 } 94 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) { 95 SkipUntil(tok::r_paren, true); // skip until ) or ; 96 return CurrAttr; 97 } 98 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") )) 99 while (Tok.is(tok::identifier) || isDeclarationSpecifier() || 100 Tok.is(tok::comma)) { 101 102 if (Tok.is(tok::comma)) { 103 // allows for empty/non-empty attributes. ((__vector_size__(16),,,,)) 104 ConsumeToken(); 105 continue; 106 } 107 // we have an identifier or declaration specifier (const, int, etc.) 108 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 109 SourceLocation AttrNameLoc = ConsumeToken(); 110 111 // check if we have a "paramterized" attribute 112 if (Tok.is(tok::l_paren)) { 113 ConsumeParen(); // ignore the left paren loc for now 114 115 if (Tok.is(tok::identifier)) { 116 IdentifierInfo *ParmName = Tok.getIdentifierInfo(); 117 SourceLocation ParmLoc = ConsumeToken(); 118 119 if (Tok.is(tok::r_paren)) { 120 // __attribute__(( mode(byte) )) 121 ConsumeParen(); // ignore the right paren loc for now 122 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 123 ParmName, ParmLoc, 0, 0, CurrAttr); 124 } else if (Tok.is(tok::comma)) { 125 ConsumeToken(); 126 // __attribute__(( format(printf, 1, 2) )) 127 ExprVector ArgExprs(Actions); 128 bool ArgExprsOk = true; 129 130 // now parse the non-empty comma separated list of expressions 131 while (1) { 132 OwningExprResult ArgExpr(ParseAssignmentExpression()); 133 if (ArgExpr.isInvalid()) { 134 ArgExprsOk = false; 135 SkipUntil(tok::r_paren); 136 break; 137 } else { 138 ArgExprs.push_back(ArgExpr.release()); 139 } 140 if (Tok.isNot(tok::comma)) 141 break; 142 ConsumeToken(); // Eat the comma, move to the next argument 143 } 144 if (ArgExprsOk && Tok.is(tok::r_paren)) { 145 ConsumeParen(); // ignore the right paren loc for now 146 CurrAttr = new AttributeList(AttrName, AttrNameLoc, ParmName, 147 ParmLoc, ArgExprs.take(), ArgExprs.size(), CurrAttr); 148 } 149 } 150 } else { // not an identifier 151 // parse a possibly empty comma separated list of expressions 152 if (Tok.is(tok::r_paren)) { 153 // __attribute__(( nonnull() )) 154 ConsumeParen(); // ignore the right paren loc for now 155 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 156 0, SourceLocation(), 0, 0, CurrAttr); 157 } else { 158 // __attribute__(( aligned(16) )) 159 ExprVector ArgExprs(Actions); 160 bool ArgExprsOk = true; 161 162 // now parse the list of expressions 163 while (1) { 164 OwningExprResult ArgExpr(ParseAssignmentExpression()); 165 if (ArgExpr.isInvalid()) { 166 ArgExprsOk = false; 167 SkipUntil(tok::r_paren); 168 break; 169 } else { 170 ArgExprs.push_back(ArgExpr.release()); 171 } 172 if (Tok.isNot(tok::comma)) 173 break; 174 ConsumeToken(); // Eat the comma, move to the next argument 175 } 176 // Match the ')'. 177 if (ArgExprsOk && Tok.is(tok::r_paren)) { 178 ConsumeParen(); // ignore the right paren loc for now 179 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, 180 SourceLocation(), ArgExprs.take(), ArgExprs.size(), 181 CurrAttr); 182 } 183 } 184 } 185 } else { 186 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 187 0, SourceLocation(), 0, 0, CurrAttr); 188 } 189 } 190 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) 191 SkipUntil(tok::r_paren, false); 192 SourceLocation Loc = Tok.getLocation();; 193 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) { 194 SkipUntil(tok::r_paren, false); 195 } 196 if (EndLoc) 197 *EndLoc = Loc; 198 } 199 return CurrAttr; 200} 201 202/// FuzzyParseMicrosoftDeclSpec. When -fms-extensions is enabled, this 203/// routine is called to skip/ignore tokens that comprise the MS declspec. 204void Parser::FuzzyParseMicrosoftDeclSpec() { 205 assert(Tok.is(tok::kw___declspec) && "Not a declspec!"); 206 ConsumeToken(); 207 if (Tok.is(tok::l_paren)) { 208 unsigned short savedParenCount = ParenCount; 209 do { 210 ConsumeAnyToken(); 211 } while (ParenCount > savedParenCount && Tok.isNot(tok::eof)); 212 } 213 return; 214} 215 216/// ParseDeclaration - Parse a full 'declaration', which consists of 217/// declaration-specifiers, some number of declarators, and a semicolon. 218/// 'Context' should be a Declarator::TheContext value. 219/// 220/// declaration: [C99 6.7] 221/// block-declaration -> 222/// simple-declaration 223/// others [FIXME] 224/// [C++] template-declaration 225/// [C++] namespace-definition 226/// [C++] using-directive 227/// [C++] using-declaration [TODO] 228/// [C++0x] static_assert-declaration 229/// others... [FIXME] 230/// 231Parser::DeclTy *Parser::ParseDeclaration(unsigned Context) { 232 switch (Tok.getKind()) { 233 case tok::kw_export: 234 case tok::kw_template: 235 return ParseTemplateDeclarationOrSpecialization(Context); 236 case tok::kw_namespace: 237 return ParseNamespace(Context); 238 case tok::kw_using: 239 return ParseUsingDirectiveOrDeclaration(Context); 240 case tok::kw_static_assert: 241 return ParseStaticAssertDeclaration(); 242 default: 243 return ParseSimpleDeclaration(Context); 244 } 245} 246 247/// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl] 248/// declaration-specifiers init-declarator-list[opt] ';' 249///[C90/C++]init-declarator-list ';' [TODO] 250/// [OMP] threadprivate-directive [TODO] 251Parser::DeclTy *Parser::ParseSimpleDeclaration(unsigned Context) { 252 // Parse the common declaration-specifiers piece. 253 DeclSpec DS; 254 ParseDeclarationSpecifiers(DS); 255 256 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };" 257 // declaration-specifiers init-declarator-list[opt] ';' 258 if (Tok.is(tok::semi)) { 259 ConsumeToken(); 260 return Actions.ParsedFreeStandingDeclSpec(CurScope, DS); 261 } 262 263 Declarator DeclaratorInfo(DS, (Declarator::TheContext)Context); 264 ParseDeclarator(DeclaratorInfo); 265 266 return ParseInitDeclaratorListAfterFirstDeclarator(DeclaratorInfo); 267} 268 269 270/// ParseInitDeclaratorListAfterFirstDeclarator - Parse 'declaration' after 271/// parsing 'declaration-specifiers declarator'. This method is split out this 272/// way to handle the ambiguity between top-level function-definitions and 273/// declarations. 274/// 275/// init-declarator-list: [C99 6.7] 276/// init-declarator 277/// init-declarator-list ',' init-declarator 278/// init-declarator: [C99 6.7] 279/// declarator 280/// declarator '=' initializer 281/// [GNU] declarator simple-asm-expr[opt] attributes[opt] 282/// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer 283/// [C++] declarator initializer[opt] 284/// 285/// [C++] initializer: 286/// [C++] '=' initializer-clause 287/// [C++] '(' expression-list ')' 288/// [C++0x] '=' 'default' [TODO] 289/// [C++0x] '=' 'delete' 290/// 291/// According to the standard grammar, =default and =delete are function 292/// definitions, but that definitely doesn't fit with the parser here. 293/// 294Parser::DeclTy *Parser:: 295ParseInitDeclaratorListAfterFirstDeclarator(Declarator &D) { 296 297 // Declarators may be grouped together ("int X, *Y, Z();"). Provide info so 298 // that they can be chained properly if the actions want this. 299 Parser::DeclTy *LastDeclInGroup = 0; 300 301 // At this point, we know that it is not a function definition. Parse the 302 // rest of the init-declarator-list. 303 while (1) { 304 // If a simple-asm-expr is present, parse it. 305 if (Tok.is(tok::kw_asm)) { 306 SourceLocation Loc; 307 OwningExprResult AsmLabel(ParseSimpleAsm(&Loc)); 308 if (AsmLabel.isInvalid()) { 309 SkipUntil(tok::semi); 310 return 0; 311 } 312 313 D.setAsmLabel(AsmLabel.release()); 314 D.SetRangeEnd(Loc); 315 } 316 317 // If attributes are present, parse them. 318 if (Tok.is(tok::kw___attribute)) { 319 SourceLocation Loc; 320 AttributeList *AttrList = ParseAttributes(&Loc); 321 D.AddAttributes(AttrList, Loc); 322 } 323 324 // Inform the current actions module that we just parsed this declarator. 325 LastDeclInGroup = Actions.ActOnDeclarator(CurScope, D, LastDeclInGroup); 326 327 // Parse declarator '=' initializer. 328 if (Tok.is(tok::equal)) { 329 ConsumeToken(); 330 if (getLang().CPlusPlus0x && Tok.is(tok::kw_delete)) { 331 SourceLocation DelLoc = ConsumeToken(); 332 Actions.SetDeclDeleted(LastDeclInGroup, DelLoc); 333 } else { 334 OwningExprResult Init(ParseInitializer()); 335 if (Init.isInvalid()) { 336 SkipUntil(tok::semi); 337 return 0; 338 } 339 Actions.AddInitializerToDecl(LastDeclInGroup, move(Init)); 340 } 341 } else if (Tok.is(tok::l_paren)) { 342 // Parse C++ direct initializer: '(' expression-list ')' 343 SourceLocation LParenLoc = ConsumeParen(); 344 ExprVector Exprs(Actions); 345 CommaLocsTy CommaLocs; 346 347 bool InvalidExpr = false; 348 if (ParseExpressionList(Exprs, CommaLocs)) { 349 SkipUntil(tok::r_paren); 350 InvalidExpr = true; 351 } 352 // Match the ')'. 353 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 354 355 if (!InvalidExpr) { 356 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() && 357 "Unexpected number of commas!"); 358 Actions.AddCXXDirectInitializerToDecl(LastDeclInGroup, LParenLoc, 359 move_arg(Exprs), 360 &CommaLocs[0], RParenLoc); 361 } 362 } else { 363 Actions.ActOnUninitializedDecl(LastDeclInGroup); 364 } 365 366 // If we don't have a comma, it is either the end of the list (a ';') or an 367 // error, bail out. 368 if (Tok.isNot(tok::comma)) 369 break; 370 371 // Consume the comma. 372 ConsumeToken(); 373 374 // Parse the next declarator. 375 D.clear(); 376 377 // Accept attributes in an init-declarator. In the first declarator in a 378 // declaration, these would be part of the declspec. In subsequent 379 // declarators, they become part of the declarator itself, so that they 380 // don't apply to declarators after *this* one. Examples: 381 // short __attribute__((common)) var; -> declspec 382 // short var __attribute__((common)); -> declarator 383 // short x, __attribute__((common)) var; -> declarator 384 if (Tok.is(tok::kw___attribute)) { 385 SourceLocation Loc; 386 AttributeList *AttrList = ParseAttributes(&Loc); 387 D.AddAttributes(AttrList, Loc); 388 } 389 390 ParseDeclarator(D); 391 } 392 393 if (Tok.is(tok::semi)) { 394 ConsumeToken(); 395 // for(is key; in keys) is error. 396 if (D.getContext() == Declarator::ForContext && isTokIdentifier_in()) { 397 Diag(Tok, diag::err_parse_error); 398 return 0; 399 } 400 return Actions.FinalizeDeclaratorGroup(CurScope, LastDeclInGroup); 401 } 402 403 // If this is an ObjC2 for-each loop, this is a successful declarator 404 // parse. The syntax for these looks like: 405 // 'for' '(' declaration 'in' expr ')' statement 406 if (D.getContext() == Declarator::ForContext && isTokIdentifier_in()) 407 return Actions.FinalizeDeclaratorGroup(CurScope, LastDeclInGroup); 408 409 Diag(Tok, diag::err_parse_error); 410 // Skip to end of block or statement 411 SkipUntil(tok::r_brace, true, true); 412 if (Tok.is(tok::semi)) 413 ConsumeToken(); 414 return 0; 415} 416 417/// ParseSpecifierQualifierList 418/// specifier-qualifier-list: 419/// type-specifier specifier-qualifier-list[opt] 420/// type-qualifier specifier-qualifier-list[opt] 421/// [GNU] attributes specifier-qualifier-list[opt] 422/// 423void Parser::ParseSpecifierQualifierList(DeclSpec &DS) { 424 /// specifier-qualifier-list is a subset of declaration-specifiers. Just 425 /// parse declaration-specifiers and complain about extra stuff. 426 ParseDeclarationSpecifiers(DS); 427 428 // Validate declspec for type-name. 429 unsigned Specs = DS.getParsedSpecifiers(); 430 if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers()) 431 Diag(Tok, diag::err_typename_requires_specqual); 432 433 // Issue diagnostic and remove storage class if present. 434 if (Specs & DeclSpec::PQ_StorageClassSpecifier) { 435 if (DS.getStorageClassSpecLoc().isValid()) 436 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass); 437 else 438 Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass); 439 DS.ClearStorageClassSpecs(); 440 } 441 442 // Issue diagnostic and remove function specfier if present. 443 if (Specs & DeclSpec::PQ_FunctionSpecifier) { 444 if (DS.isInlineSpecified()) 445 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec); 446 if (DS.isVirtualSpecified()) 447 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec); 448 if (DS.isExplicitSpecified()) 449 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec); 450 DS.ClearFunctionSpecs(); 451 } 452} 453 454/// ParseDeclarationSpecifiers 455/// declaration-specifiers: [C99 6.7] 456/// storage-class-specifier declaration-specifiers[opt] 457/// type-specifier declaration-specifiers[opt] 458/// [C99] function-specifier declaration-specifiers[opt] 459/// [GNU] attributes declaration-specifiers[opt] 460/// 461/// storage-class-specifier: [C99 6.7.1] 462/// 'typedef' 463/// 'extern' 464/// 'static' 465/// 'auto' 466/// 'register' 467/// [C++] 'mutable' 468/// [GNU] '__thread' 469/// function-specifier: [C99 6.7.4] 470/// [C99] 'inline' 471/// [C++] 'virtual' 472/// [C++] 'explicit' 473/// 474void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, 475 TemplateParameterLists *TemplateParams, 476 AccessSpecifier AS){ 477 DS.SetRangeStart(Tok.getLocation()); 478 while (1) { 479 int isInvalid = false; 480 const char *PrevSpec = 0; 481 SourceLocation Loc = Tok.getLocation(); 482 483 switch (Tok.getKind()) { 484 default: 485 DoneWithDeclSpec: 486 // If this is not a declaration specifier token, we're done reading decl 487 // specifiers. First verify that DeclSpec's are consistent. 488 DS.Finish(Diags, PP.getSourceManager(), getLang()); 489 return; 490 491 case tok::coloncolon: // ::foo::bar 492 // Annotate C++ scope specifiers. If we get one, loop. 493 if (TryAnnotateCXXScopeToken()) 494 continue; 495 goto DoneWithDeclSpec; 496 497 case tok::annot_cxxscope: { 498 if (DS.hasTypeSpecifier()) 499 goto DoneWithDeclSpec; 500 501 // We are looking for a qualified typename. 502 Token Next = NextToken(); 503 if (Next.is(tok::annot_template_id) && 504 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue()) 505 ->Kind == TNK_Class_template) { 506 // We have a qualified template-id, e.g., N::A<int> 507 CXXScopeSpec SS; 508 ParseOptionalCXXScopeSpecifier(SS); 509 assert(Tok.is(tok::annot_template_id) && 510 "ParseOptionalCXXScopeSpecifier not working"); 511 AnnotateTemplateIdTokenAsType(&SS); 512 continue; 513 } 514 515 if (Next.isNot(tok::identifier)) 516 goto DoneWithDeclSpec; 517 518 CXXScopeSpec SS; 519 SS.setScopeRep(Tok.getAnnotationValue()); 520 SS.setRange(Tok.getAnnotationRange()); 521 522 // If the next token is the name of the class type that the C++ scope 523 // denotes, followed by a '(', then this is a constructor declaration. 524 // We're done with the decl-specifiers. 525 if (Actions.isCurrentClassName(*NextToken().getIdentifierInfo(), 526 CurScope, &SS) && 527 GetLookAheadToken(2).is(tok::l_paren)) 528 goto DoneWithDeclSpec; 529 530 TypeTy *TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(), 531 Next.getLocation(), CurScope, &SS); 532 533 if (TypeRep == 0) 534 goto DoneWithDeclSpec; 535 536 ConsumeToken(); // The C++ scope. 537 538 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 539 TypeRep); 540 if (isInvalid) 541 break; 542 543 DS.SetRangeEnd(Tok.getLocation()); 544 ConsumeToken(); // The typename. 545 546 continue; 547 } 548 549 case tok::annot_typename: { 550 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 551 Tok.getAnnotationValue()); 552 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 553 ConsumeToken(); // The typename 554 555 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 556 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 557 // Objective-C interface. If we don't have Objective-C or a '<', this is 558 // just a normal reference to a typedef name. 559 if (!Tok.is(tok::less) || !getLang().ObjC1) 560 continue; 561 562 SourceLocation EndProtoLoc; 563 llvm::SmallVector<DeclTy *, 8> ProtocolDecl; 564 ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc); 565 DS.setProtocolQualifiers(&ProtocolDecl[0], ProtocolDecl.size()); 566 567 DS.SetRangeEnd(EndProtoLoc); 568 continue; 569 } 570 571 // typedef-name 572 case tok::identifier: { 573 // In C++, check to see if this is a scope specifier like foo::bar::, if 574 // so handle it as such. This is important for ctor parsing. 575 if (getLang().CPlusPlus && TryAnnotateCXXScopeToken()) 576 continue; 577 578 // This identifier can only be a typedef name if we haven't already seen 579 // a type-specifier. Without this check we misparse: 580 // typedef int X; struct Y { short X; }; as 'short int'. 581 if (DS.hasTypeSpecifier()) 582 goto DoneWithDeclSpec; 583 584 // It has to be available as a typedef too! 585 TypeTy *TypeRep = Actions.getTypeName(*Tok.getIdentifierInfo(), 586 Tok.getLocation(), CurScope); 587 588 if (TypeRep == 0) 589 goto DoneWithDeclSpec; 590 591 // C++: If the identifier is actually the name of the class type 592 // being defined and the next token is a '(', then this is a 593 // constructor declaration. We're done with the decl-specifiers 594 // and will treat this token as an identifier. 595 if (getLang().CPlusPlus && 596 CurScope->isClassScope() && 597 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), CurScope) && 598 NextToken().getKind() == tok::l_paren) 599 goto DoneWithDeclSpec; 600 601 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 602 TypeRep); 603 if (isInvalid) 604 break; 605 606 DS.SetRangeEnd(Tok.getLocation()); 607 ConsumeToken(); // The identifier 608 609 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 610 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 611 // Objective-C interface. If we don't have Objective-C or a '<', this is 612 // just a normal reference to a typedef name. 613 if (!Tok.is(tok::less) || !getLang().ObjC1) 614 continue; 615 616 SourceLocation EndProtoLoc; 617 llvm::SmallVector<DeclTy *, 8> ProtocolDecl; 618 ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc); 619 DS.setProtocolQualifiers(&ProtocolDecl[0], ProtocolDecl.size()); 620 621 DS.SetRangeEnd(EndProtoLoc); 622 623 // Need to support trailing type qualifiers (e.g. "id<p> const"). 624 // If a type specifier follows, it will be diagnosed elsewhere. 625 continue; 626 } 627 628 // type-name 629 case tok::annot_template_id: { 630 TemplateIdAnnotation *TemplateId 631 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 632 if (TemplateId->Kind != TNK_Class_template) { 633 // This template-id does not refer to a type name, so we're 634 // done with the type-specifiers. 635 goto DoneWithDeclSpec; 636 } 637 638 // Turn the template-id annotation token into a type annotation 639 // token, then try again to parse it as a type-specifier. 640 if (AnnotateTemplateIdTokenAsType()) 641 DS.SetTypeSpecError(); 642 643 continue; 644 } 645 646 // GNU attributes support. 647 case tok::kw___attribute: 648 DS.AddAttributes(ParseAttributes()); 649 continue; 650 651 // Microsoft declspec support. 652 case tok::kw___declspec: 653 if (!PP.getLangOptions().Microsoft) 654 goto DoneWithDeclSpec; 655 FuzzyParseMicrosoftDeclSpec(); 656 continue; 657 658 // Microsoft single token adornments. 659 case tok::kw___forceinline: 660 case tok::kw___w64: 661 case tok::kw___cdecl: 662 case tok::kw___stdcall: 663 case tok::kw___fastcall: 664 if (!PP.getLangOptions().Microsoft) 665 goto DoneWithDeclSpec; 666 // Just ignore it. 667 break; 668 669 // storage-class-specifier 670 case tok::kw_typedef: 671 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec); 672 break; 673 case tok::kw_extern: 674 if (DS.isThreadSpecified()) 675 Diag(Tok, diag::ext_thread_before) << "extern"; 676 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec); 677 break; 678 case tok::kw___private_extern__: 679 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc, 680 PrevSpec); 681 break; 682 case tok::kw_static: 683 if (DS.isThreadSpecified()) 684 Diag(Tok, diag::ext_thread_before) << "static"; 685 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec); 686 break; 687 case tok::kw_auto: 688 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec); 689 break; 690 case tok::kw_register: 691 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec); 692 break; 693 case tok::kw_mutable: 694 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_mutable, Loc, PrevSpec); 695 break; 696 case tok::kw___thread: 697 isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec)*2; 698 break; 699 700 continue; 701 702 // function-specifier 703 case tok::kw_inline: 704 isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec); 705 break; 706 case tok::kw_virtual: 707 isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec); 708 break; 709 case tok::kw_explicit: 710 isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec); 711 break; 712 713 // type-specifier 714 case tok::kw_short: 715 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec); 716 break; 717 case tok::kw_long: 718 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long) 719 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec); 720 else 721 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec); 722 break; 723 case tok::kw_signed: 724 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec); 725 break; 726 case tok::kw_unsigned: 727 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec); 728 break; 729 case tok::kw__Complex: 730 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec); 731 break; 732 case tok::kw__Imaginary: 733 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec); 734 break; 735 case tok::kw_void: 736 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec); 737 break; 738 case tok::kw_char: 739 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec); 740 break; 741 case tok::kw_int: 742 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec); 743 break; 744 case tok::kw_float: 745 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec); 746 break; 747 case tok::kw_double: 748 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec); 749 break; 750 case tok::kw_wchar_t: 751 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec); 752 break; 753 case tok::kw_bool: 754 case tok::kw__Bool: 755 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec); 756 break; 757 case tok::kw__Decimal32: 758 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec); 759 break; 760 case tok::kw__Decimal64: 761 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec); 762 break; 763 case tok::kw__Decimal128: 764 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec); 765 break; 766 767 // class-specifier: 768 case tok::kw_class: 769 case tok::kw_struct: 770 case tok::kw_union: 771 ParseClassSpecifier(DS, TemplateParams, AS); 772 continue; 773 774 // enum-specifier: 775 case tok::kw_enum: 776 ParseEnumSpecifier(DS, AS); 777 continue; 778 779 // cv-qualifier: 780 case tok::kw_const: 781 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec,getLang())*2; 782 break; 783 case tok::kw_volatile: 784 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, 785 getLang())*2; 786 break; 787 case tok::kw_restrict: 788 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, 789 getLang())*2; 790 break; 791 792 // C++ typename-specifier: 793 case tok::kw_typename: 794 if (TryAnnotateTypeOrScopeToken()) 795 continue; 796 break; 797 798 // GNU typeof support. 799 case tok::kw_typeof: 800 ParseTypeofSpecifier(DS); 801 continue; 802 803 case tok::less: 804 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for 805 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous, 806 // but we support it. 807 if (DS.hasTypeSpecifier() || !getLang().ObjC1) 808 goto DoneWithDeclSpec; 809 810 { 811 SourceLocation EndProtoLoc; 812 llvm::SmallVector<DeclTy *, 8> ProtocolDecl; 813 ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc); 814 DS.setProtocolQualifiers(&ProtocolDecl[0], ProtocolDecl.size()); 815 DS.SetRangeEnd(EndProtoLoc); 816 817 Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id) 818 << SourceRange(Loc, EndProtoLoc); 819 // Need to support trailing type qualifiers (e.g. "id<p> const"). 820 // If a type specifier follows, it will be diagnosed elsewhere. 821 continue; 822 } 823 } 824 // If the specifier combination wasn't legal, issue a diagnostic. 825 if (isInvalid) { 826 assert(PrevSpec && "Method did not return previous specifier!"); 827 // Pick between error or extwarn. 828 unsigned DiagID = isInvalid == 1 ? diag::err_invalid_decl_spec_combination 829 : diag::ext_duplicate_declspec; 830 Diag(Tok, DiagID) << PrevSpec; 831 } 832 DS.SetRangeEnd(Tok.getLocation()); 833 ConsumeToken(); 834 } 835} 836 837/// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We 838/// primarily follow the C++ grammar with additions for C99 and GNU, 839/// which together subsume the C grammar. Note that the C++ 840/// type-specifier also includes the C type-qualifier (for const, 841/// volatile, and C99 restrict). Returns true if a type-specifier was 842/// found (and parsed), false otherwise. 843/// 844/// type-specifier: [C++ 7.1.5] 845/// simple-type-specifier 846/// class-specifier 847/// enum-specifier 848/// elaborated-type-specifier [TODO] 849/// cv-qualifier 850/// 851/// cv-qualifier: [C++ 7.1.5.1] 852/// 'const' 853/// 'volatile' 854/// [C99] 'restrict' 855/// 856/// simple-type-specifier: [ C++ 7.1.5.2] 857/// '::'[opt] nested-name-specifier[opt] type-name [TODO] 858/// '::'[opt] nested-name-specifier 'template' template-id [TODO] 859/// 'char' 860/// 'wchar_t' 861/// 'bool' 862/// 'short' 863/// 'int' 864/// 'long' 865/// 'signed' 866/// 'unsigned' 867/// 'float' 868/// 'double' 869/// 'void' 870/// [C99] '_Bool' 871/// [C99] '_Complex' 872/// [C99] '_Imaginary' // Removed in TC2? 873/// [GNU] '_Decimal32' 874/// [GNU] '_Decimal64' 875/// [GNU] '_Decimal128' 876/// [GNU] typeof-specifier 877/// [OBJC] class-name objc-protocol-refs[opt] [TODO] 878/// [OBJC] typedef-name objc-protocol-refs[opt] [TODO] 879bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, int& isInvalid, 880 const char *&PrevSpec, 881 TemplateParameterLists *TemplateParams){ 882 SourceLocation Loc = Tok.getLocation(); 883 884 switch (Tok.getKind()) { 885 case tok::identifier: // foo::bar 886 case tok::kw_typename: // typename foo::bar 887 // Annotate typenames and C++ scope specifiers. If we get one, just 888 // recurse to handle whatever we get. 889 if (TryAnnotateTypeOrScopeToken()) 890 return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec,TemplateParams); 891 // Otherwise, not a type specifier. 892 return false; 893 case tok::coloncolon: // ::foo::bar 894 if (NextToken().is(tok::kw_new) || // ::new 895 NextToken().is(tok::kw_delete)) // ::delete 896 return false; 897 898 // Annotate typenames and C++ scope specifiers. If we get one, just 899 // recurse to handle whatever we get. 900 if (TryAnnotateTypeOrScopeToken()) 901 return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec,TemplateParams); 902 // Otherwise, not a type specifier. 903 return false; 904 905 // simple-type-specifier: 906 case tok::annot_typename: { 907 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 908 Tok.getAnnotationValue()); 909 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 910 ConsumeToken(); // The typename 911 912 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 913 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 914 // Objective-C interface. If we don't have Objective-C or a '<', this is 915 // just a normal reference to a typedef name. 916 if (!Tok.is(tok::less) || !getLang().ObjC1) 917 return true; 918 919 SourceLocation EndProtoLoc; 920 llvm::SmallVector<DeclTy *, 8> ProtocolDecl; 921 ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc); 922 DS.setProtocolQualifiers(&ProtocolDecl[0], ProtocolDecl.size()); 923 924 DS.SetRangeEnd(EndProtoLoc); 925 return true; 926 } 927 928 case tok::kw_short: 929 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec); 930 break; 931 case tok::kw_long: 932 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long) 933 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec); 934 else 935 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec); 936 break; 937 case tok::kw_signed: 938 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec); 939 break; 940 case tok::kw_unsigned: 941 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec); 942 break; 943 case tok::kw__Complex: 944 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec); 945 break; 946 case tok::kw__Imaginary: 947 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec); 948 break; 949 case tok::kw_void: 950 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec); 951 break; 952 case tok::kw_char: 953 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec); 954 break; 955 case tok::kw_int: 956 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec); 957 break; 958 case tok::kw_float: 959 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec); 960 break; 961 case tok::kw_double: 962 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec); 963 break; 964 case tok::kw_wchar_t: 965 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec); 966 break; 967 case tok::kw_bool: 968 case tok::kw__Bool: 969 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec); 970 break; 971 case tok::kw__Decimal32: 972 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec); 973 break; 974 case tok::kw__Decimal64: 975 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec); 976 break; 977 case tok::kw__Decimal128: 978 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec); 979 break; 980 981 // class-specifier: 982 case tok::kw_class: 983 case tok::kw_struct: 984 case tok::kw_union: 985 ParseClassSpecifier(DS, TemplateParams); 986 return true; 987 988 // enum-specifier: 989 case tok::kw_enum: 990 ParseEnumSpecifier(DS); 991 return true; 992 993 // cv-qualifier: 994 case tok::kw_const: 995 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, 996 getLang())*2; 997 break; 998 case tok::kw_volatile: 999 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, 1000 getLang())*2; 1001 break; 1002 case tok::kw_restrict: 1003 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, 1004 getLang())*2; 1005 break; 1006 1007 // GNU typeof support. 1008 case tok::kw_typeof: 1009 ParseTypeofSpecifier(DS); 1010 return true; 1011 1012 case tok::kw___cdecl: 1013 case tok::kw___stdcall: 1014 case tok::kw___fastcall: 1015 if (!PP.getLangOptions().Microsoft) return false; 1016 ConsumeToken(); 1017 return true; 1018 1019 default: 1020 // Not a type-specifier; do nothing. 1021 return false; 1022 } 1023 1024 // If the specifier combination wasn't legal, issue a diagnostic. 1025 if (isInvalid) { 1026 assert(PrevSpec && "Method did not return previous specifier!"); 1027 // Pick between error or extwarn. 1028 unsigned DiagID = isInvalid == 1 ? diag::err_invalid_decl_spec_combination 1029 : diag::ext_duplicate_declspec; 1030 Diag(Tok, DiagID) << PrevSpec; 1031 } 1032 DS.SetRangeEnd(Tok.getLocation()); 1033 ConsumeToken(); // whatever we parsed above. 1034 return true; 1035} 1036 1037/// ParseStructDeclaration - Parse a struct declaration without the terminating 1038/// semicolon. 1039/// 1040/// struct-declaration: 1041/// specifier-qualifier-list struct-declarator-list 1042/// [GNU] __extension__ struct-declaration 1043/// [GNU] specifier-qualifier-list 1044/// struct-declarator-list: 1045/// struct-declarator 1046/// struct-declarator-list ',' struct-declarator 1047/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator 1048/// struct-declarator: 1049/// declarator 1050/// [GNU] declarator attributes[opt] 1051/// declarator[opt] ':' constant-expression 1052/// [GNU] declarator[opt] ':' constant-expression attributes[opt] 1053/// 1054void Parser:: 1055ParseStructDeclaration(DeclSpec &DS, 1056 llvm::SmallVectorImpl<FieldDeclarator> &Fields) { 1057 if (Tok.is(tok::kw___extension__)) { 1058 // __extension__ silences extension warnings in the subexpression. 1059 ExtensionRAIIObject O(Diags); // Use RAII to do this. 1060 ConsumeToken(); 1061 return ParseStructDeclaration(DS, Fields); 1062 } 1063 1064 // Parse the common specifier-qualifiers-list piece. 1065 SourceLocation DSStart = Tok.getLocation(); 1066 ParseSpecifierQualifierList(DS); 1067 1068 // If there are no declarators, this is a free-standing declaration 1069 // specifier. Let the actions module cope with it. 1070 if (Tok.is(tok::semi)) { 1071 Actions.ParsedFreeStandingDeclSpec(CurScope, DS); 1072 return; 1073 } 1074 1075 // Read struct-declarators until we find the semicolon. 1076 Fields.push_back(FieldDeclarator(DS)); 1077 while (1) { 1078 FieldDeclarator &DeclaratorInfo = Fields.back(); 1079 1080 /// struct-declarator: declarator 1081 /// struct-declarator: declarator[opt] ':' constant-expression 1082 if (Tok.isNot(tok::colon)) 1083 ParseDeclarator(DeclaratorInfo.D); 1084 1085 if (Tok.is(tok::colon)) { 1086 ConsumeToken(); 1087 OwningExprResult Res(ParseConstantExpression()); 1088 if (Res.isInvalid()) 1089 SkipUntil(tok::semi, true, true); 1090 else 1091 DeclaratorInfo.BitfieldSize = Res.release(); 1092 } 1093 1094 // If attributes exist after the declarator, parse them. 1095 if (Tok.is(tok::kw___attribute)) { 1096 SourceLocation Loc; 1097 AttributeList *AttrList = ParseAttributes(&Loc); 1098 DeclaratorInfo.D.AddAttributes(AttrList, Loc); 1099 } 1100 1101 // If we don't have a comma, it is either the end of the list (a ';') 1102 // or an error, bail out. 1103 if (Tok.isNot(tok::comma)) 1104 return; 1105 1106 // Consume the comma. 1107 ConsumeToken(); 1108 1109 // Parse the next declarator. 1110 Fields.push_back(FieldDeclarator(DS)); 1111 1112 // Attributes are only allowed on the second declarator. 1113 if (Tok.is(tok::kw___attribute)) { 1114 SourceLocation Loc; 1115 AttributeList *AttrList = ParseAttributes(&Loc); 1116 Fields.back().D.AddAttributes(AttrList, Loc); 1117 } 1118 } 1119} 1120 1121/// ParseStructUnionBody 1122/// struct-contents: 1123/// struct-declaration-list 1124/// [EXT] empty 1125/// [GNU] "struct-declaration-list" without terminatoring ';' 1126/// struct-declaration-list: 1127/// struct-declaration 1128/// struct-declaration-list struct-declaration 1129/// [OBC] '@' 'defs' '(' class-name ')' 1130/// 1131void Parser::ParseStructUnionBody(SourceLocation RecordLoc, 1132 unsigned TagType, DeclTy *TagDecl) { 1133 PrettyStackTraceActionsDecl CrashInfo(TagDecl, RecordLoc, Actions, 1134 PP.getSourceManager(), 1135 "parsing struct/union body"); 1136 1137 SourceLocation LBraceLoc = ConsumeBrace(); 1138 1139 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope); 1140 Actions.ActOnTagStartDefinition(CurScope, TagDecl); 1141 1142 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in 1143 // C++. 1144 if (Tok.is(tok::r_brace) && !getLang().CPlusPlus) 1145 Diag(Tok, diag::ext_empty_struct_union_enum) 1146 << DeclSpec::getSpecifierName((DeclSpec::TST)TagType); 1147 1148 llvm::SmallVector<DeclTy*, 32> FieldDecls; 1149 llvm::SmallVector<FieldDeclarator, 8> FieldDeclarators; 1150 1151 // While we still have something to read, read the declarations in the struct. 1152 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 1153 // Each iteration of this loop reads one struct-declaration. 1154 1155 // Check for extraneous top-level semicolon. 1156 if (Tok.is(tok::semi)) { 1157 Diag(Tok, diag::ext_extra_struct_semi); 1158 ConsumeToken(); 1159 continue; 1160 } 1161 1162 // Parse all the comma separated declarators. 1163 DeclSpec DS; 1164 FieldDeclarators.clear(); 1165 if (!Tok.is(tok::at)) { 1166 ParseStructDeclaration(DS, FieldDeclarators); 1167 1168 // Convert them all to fields. 1169 for (unsigned i = 0, e = FieldDeclarators.size(); i != e; ++i) { 1170 FieldDeclarator &FD = FieldDeclarators[i]; 1171 // Install the declarator into the current TagDecl. 1172 DeclTy *Field = Actions.ActOnField(CurScope, TagDecl, 1173 DS.getSourceRange().getBegin(), 1174 FD.D, FD.BitfieldSize); 1175 FieldDecls.push_back(Field); 1176 } 1177 } else { // Handle @defs 1178 ConsumeToken(); 1179 if (!Tok.isObjCAtKeyword(tok::objc_defs)) { 1180 Diag(Tok, diag::err_unexpected_at); 1181 SkipUntil(tok::semi, true, true); 1182 continue; 1183 } 1184 ConsumeToken(); 1185 ExpectAndConsume(tok::l_paren, diag::err_expected_lparen); 1186 if (!Tok.is(tok::identifier)) { 1187 Diag(Tok, diag::err_expected_ident); 1188 SkipUntil(tok::semi, true, true); 1189 continue; 1190 } 1191 llvm::SmallVector<DeclTy*, 16> Fields; 1192 Actions.ActOnDefs(CurScope, TagDecl, Tok.getLocation(), 1193 Tok.getIdentifierInfo(), Fields); 1194 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end()); 1195 ConsumeToken(); 1196 ExpectAndConsume(tok::r_paren, diag::err_expected_rparen); 1197 } 1198 1199 if (Tok.is(tok::semi)) { 1200 ConsumeToken(); 1201 } else if (Tok.is(tok::r_brace)) { 1202 Diag(Tok, diag::ext_expected_semi_decl_list); 1203 break; 1204 } else { 1205 Diag(Tok, diag::err_expected_semi_decl_list); 1206 // Skip to end of block or statement 1207 SkipUntil(tok::r_brace, true, true); 1208 } 1209 } 1210 1211 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc); 1212 1213 AttributeList *AttrList = 0; 1214 // If attributes exist after struct contents, parse them. 1215 if (Tok.is(tok::kw___attribute)) 1216 AttrList = ParseAttributes(); 1217 1218 Actions.ActOnFields(CurScope, 1219 RecordLoc,TagDecl,&FieldDecls[0],FieldDecls.size(), 1220 LBraceLoc, RBraceLoc, 1221 AttrList); 1222 StructScope.Exit(); 1223 Actions.ActOnTagFinishDefinition(CurScope, TagDecl); 1224} 1225 1226 1227/// ParseEnumSpecifier 1228/// enum-specifier: [C99 6.7.2.2] 1229/// 'enum' identifier[opt] '{' enumerator-list '}' 1230///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}' 1231/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt] 1232/// '}' attributes[opt] 1233/// 'enum' identifier 1234/// [GNU] 'enum' attributes[opt] identifier 1235/// 1236/// [C++] elaborated-type-specifier: 1237/// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier 1238/// 1239void Parser::ParseEnumSpecifier(DeclSpec &DS, AccessSpecifier AS) { 1240 assert(Tok.is(tok::kw_enum) && "Not an enum specifier"); 1241 SourceLocation StartLoc = ConsumeToken(); 1242 1243 // Parse the tag portion of this. 1244 1245 AttributeList *Attr = 0; 1246 // If attributes exist after tag, parse them. 1247 if (Tok.is(tok::kw___attribute)) 1248 Attr = ParseAttributes(); 1249 1250 CXXScopeSpec SS; 1251 if (getLang().CPlusPlus && ParseOptionalCXXScopeSpecifier(SS)) { 1252 if (Tok.isNot(tok::identifier)) { 1253 Diag(Tok, diag::err_expected_ident); 1254 if (Tok.isNot(tok::l_brace)) { 1255 // Has no name and is not a definition. 1256 // Skip the rest of this declarator, up until the comma or semicolon. 1257 SkipUntil(tok::comma, true); 1258 return; 1259 } 1260 } 1261 } 1262 1263 // Must have either 'enum name' or 'enum {...}'. 1264 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace)) { 1265 Diag(Tok, diag::err_expected_ident_lbrace); 1266 1267 // Skip the rest of this declarator, up until the comma or semicolon. 1268 SkipUntil(tok::comma, true); 1269 return; 1270 } 1271 1272 // If an identifier is present, consume and remember it. 1273 IdentifierInfo *Name = 0; 1274 SourceLocation NameLoc; 1275 if (Tok.is(tok::identifier)) { 1276 Name = Tok.getIdentifierInfo(); 1277 NameLoc = ConsumeToken(); 1278 } 1279 1280 // There are three options here. If we have 'enum foo;', then this is a 1281 // forward declaration. If we have 'enum foo {...' then this is a 1282 // definition. Otherwise we have something like 'enum foo xyz', a reference. 1283 // 1284 // This is needed to handle stuff like this right (C99 6.7.2.3p11): 1285 // enum foo {..}; void bar() { enum foo; } <- new foo in bar. 1286 // enum foo {..}; void bar() { enum foo x; } <- use of old foo. 1287 // 1288 Action::TagKind TK; 1289 if (Tok.is(tok::l_brace)) 1290 TK = Action::TK_Definition; 1291 else if (Tok.is(tok::semi)) 1292 TK = Action::TK_Declaration; 1293 else 1294 TK = Action::TK_Reference; 1295 DeclTy *TagDecl = Actions.ActOnTag(CurScope, DeclSpec::TST_enum, TK, StartLoc, 1296 SS, Name, NameLoc, Attr, AS); 1297 1298 if (Tok.is(tok::l_brace)) 1299 ParseEnumBody(StartLoc, TagDecl); 1300 1301 // TODO: semantic analysis on the declspec for enums. 1302 const char *PrevSpec = 0; 1303 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, PrevSpec, TagDecl)) 1304 Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec; 1305} 1306 1307/// ParseEnumBody - Parse a {} enclosed enumerator-list. 1308/// enumerator-list: 1309/// enumerator 1310/// enumerator-list ',' enumerator 1311/// enumerator: 1312/// enumeration-constant 1313/// enumeration-constant '=' constant-expression 1314/// enumeration-constant: 1315/// identifier 1316/// 1317void Parser::ParseEnumBody(SourceLocation StartLoc, DeclTy *EnumDecl) { 1318 // Enter the scope of the enum body and start the definition. 1319 ParseScope EnumScope(this, Scope::DeclScope); 1320 Actions.ActOnTagStartDefinition(CurScope, EnumDecl); 1321 1322 SourceLocation LBraceLoc = ConsumeBrace(); 1323 1324 // C does not allow an empty enumerator-list, C++ does [dcl.enum]. 1325 if (Tok.is(tok::r_brace) && !getLang().CPlusPlus) 1326 Diag(Tok, diag::ext_empty_struct_union_enum) << "enum"; 1327 1328 llvm::SmallVector<DeclTy*, 32> EnumConstantDecls; 1329 1330 DeclTy *LastEnumConstDecl = 0; 1331 1332 // Parse the enumerator-list. 1333 while (Tok.is(tok::identifier)) { 1334 IdentifierInfo *Ident = Tok.getIdentifierInfo(); 1335 SourceLocation IdentLoc = ConsumeToken(); 1336 1337 SourceLocation EqualLoc; 1338 OwningExprResult AssignedVal(Actions); 1339 if (Tok.is(tok::equal)) { 1340 EqualLoc = ConsumeToken(); 1341 AssignedVal = ParseConstantExpression(); 1342 if (AssignedVal.isInvalid()) 1343 SkipUntil(tok::comma, tok::r_brace, true, true); 1344 } 1345 1346 // Install the enumerator constant into EnumDecl. 1347 DeclTy *EnumConstDecl = Actions.ActOnEnumConstant(CurScope, EnumDecl, 1348 LastEnumConstDecl, 1349 IdentLoc, Ident, 1350 EqualLoc, 1351 AssignedVal.release()); 1352 EnumConstantDecls.push_back(EnumConstDecl); 1353 LastEnumConstDecl = EnumConstDecl; 1354 1355 if (Tok.isNot(tok::comma)) 1356 break; 1357 SourceLocation CommaLoc = ConsumeToken(); 1358 1359 if (Tok.isNot(tok::identifier) && !getLang().C99) 1360 Diag(CommaLoc, diag::ext_c99_enumerator_list_comma); 1361 } 1362 1363 // Eat the }. 1364 MatchRHSPunctuation(tok::r_brace, LBraceLoc); 1365 1366 Actions.ActOnEnumBody(StartLoc, EnumDecl, &EnumConstantDecls[0], 1367 EnumConstantDecls.size()); 1368 1369 DeclTy *AttrList = 0; 1370 // If attributes exist after the identifier list, parse them. 1371 if (Tok.is(tok::kw___attribute)) 1372 AttrList = ParseAttributes(); // FIXME: where do they do? 1373 1374 EnumScope.Exit(); 1375 Actions.ActOnTagFinishDefinition(CurScope, EnumDecl); 1376} 1377 1378/// isTypeSpecifierQualifier - Return true if the current token could be the 1379/// start of a type-qualifier-list. 1380bool Parser::isTypeQualifier() const { 1381 switch (Tok.getKind()) { 1382 default: return false; 1383 // type-qualifier 1384 case tok::kw_const: 1385 case tok::kw_volatile: 1386 case tok::kw_restrict: 1387 return true; 1388 } 1389} 1390 1391/// isTypeSpecifierQualifier - Return true if the current token could be the 1392/// start of a specifier-qualifier-list. 1393bool Parser::isTypeSpecifierQualifier() { 1394 switch (Tok.getKind()) { 1395 default: return false; 1396 1397 case tok::identifier: // foo::bar 1398 case tok::kw_typename: // typename T::type 1399 // Annotate typenames and C++ scope specifiers. If we get one, just 1400 // recurse to handle whatever we get. 1401 if (TryAnnotateTypeOrScopeToken()) 1402 return isTypeSpecifierQualifier(); 1403 // Otherwise, not a type specifier. 1404 return false; 1405 1406 case tok::coloncolon: // ::foo::bar 1407 if (NextToken().is(tok::kw_new) || // ::new 1408 NextToken().is(tok::kw_delete)) // ::delete 1409 return false; 1410 1411 // Annotate typenames and C++ scope specifiers. If we get one, just 1412 // recurse to handle whatever we get. 1413 if (TryAnnotateTypeOrScopeToken()) 1414 return isTypeSpecifierQualifier(); 1415 // Otherwise, not a type specifier. 1416 return false; 1417 1418 // GNU attributes support. 1419 case tok::kw___attribute: 1420 // GNU typeof support. 1421 case tok::kw_typeof: 1422 1423 // type-specifiers 1424 case tok::kw_short: 1425 case tok::kw_long: 1426 case tok::kw_signed: 1427 case tok::kw_unsigned: 1428 case tok::kw__Complex: 1429 case tok::kw__Imaginary: 1430 case tok::kw_void: 1431 case tok::kw_char: 1432 case tok::kw_wchar_t: 1433 case tok::kw_int: 1434 case tok::kw_float: 1435 case tok::kw_double: 1436 case tok::kw_bool: 1437 case tok::kw__Bool: 1438 case tok::kw__Decimal32: 1439 case tok::kw__Decimal64: 1440 case tok::kw__Decimal128: 1441 1442 // struct-or-union-specifier (C99) or class-specifier (C++) 1443 case tok::kw_class: 1444 case tok::kw_struct: 1445 case tok::kw_union: 1446 // enum-specifier 1447 case tok::kw_enum: 1448 1449 // type-qualifier 1450 case tok::kw_const: 1451 case tok::kw_volatile: 1452 case tok::kw_restrict: 1453 1454 // typedef-name 1455 case tok::annot_typename: 1456 return true; 1457 1458 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 1459 case tok::less: 1460 return getLang().ObjC1; 1461 1462 case tok::kw___cdecl: 1463 case tok::kw___stdcall: 1464 case tok::kw___fastcall: 1465 return PP.getLangOptions().Microsoft; 1466 } 1467} 1468 1469/// isDeclarationSpecifier() - Return true if the current token is part of a 1470/// declaration specifier. 1471bool Parser::isDeclarationSpecifier() { 1472 switch (Tok.getKind()) { 1473 default: return false; 1474 1475 case tok::identifier: // foo::bar 1476 // Unfortunate hack to support "Class.factoryMethod" notation. 1477 if (getLang().ObjC1 && NextToken().is(tok::period)) 1478 return false; 1479 // Fall through 1480 1481 case tok::kw_typename: // typename T::type 1482 // Annotate typenames and C++ scope specifiers. If we get one, just 1483 // recurse to handle whatever we get. 1484 if (TryAnnotateTypeOrScopeToken()) 1485 return isDeclarationSpecifier(); 1486 // Otherwise, not a declaration specifier. 1487 return false; 1488 case tok::coloncolon: // ::foo::bar 1489 if (NextToken().is(tok::kw_new) || // ::new 1490 NextToken().is(tok::kw_delete)) // ::delete 1491 return false; 1492 1493 // Annotate typenames and C++ scope specifiers. If we get one, just 1494 // recurse to handle whatever we get. 1495 if (TryAnnotateTypeOrScopeToken()) 1496 return isDeclarationSpecifier(); 1497 // Otherwise, not a declaration specifier. 1498 return false; 1499 1500 // storage-class-specifier 1501 case tok::kw_typedef: 1502 case tok::kw_extern: 1503 case tok::kw___private_extern__: 1504 case tok::kw_static: 1505 case tok::kw_auto: 1506 case tok::kw_register: 1507 case tok::kw___thread: 1508 1509 // type-specifiers 1510 case tok::kw_short: 1511 case tok::kw_long: 1512 case tok::kw_signed: 1513 case tok::kw_unsigned: 1514 case tok::kw__Complex: 1515 case tok::kw__Imaginary: 1516 case tok::kw_void: 1517 case tok::kw_char: 1518 case tok::kw_wchar_t: 1519 case tok::kw_int: 1520 case tok::kw_float: 1521 case tok::kw_double: 1522 case tok::kw_bool: 1523 case tok::kw__Bool: 1524 case tok::kw__Decimal32: 1525 case tok::kw__Decimal64: 1526 case tok::kw__Decimal128: 1527 1528 // struct-or-union-specifier (C99) or class-specifier (C++) 1529 case tok::kw_class: 1530 case tok::kw_struct: 1531 case tok::kw_union: 1532 // enum-specifier 1533 case tok::kw_enum: 1534 1535 // type-qualifier 1536 case tok::kw_const: 1537 case tok::kw_volatile: 1538 case tok::kw_restrict: 1539 1540 // function-specifier 1541 case tok::kw_inline: 1542 case tok::kw_virtual: 1543 case tok::kw_explicit: 1544 1545 // typedef-name 1546 case tok::annot_typename: 1547 1548 // GNU typeof support. 1549 case tok::kw_typeof: 1550 1551 // GNU attributes. 1552 case tok::kw___attribute: 1553 return true; 1554 1555 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 1556 case tok::less: 1557 return getLang().ObjC1; 1558 1559 case tok::kw___declspec: 1560 case tok::kw___cdecl: 1561 case tok::kw___stdcall: 1562 case tok::kw___fastcall: 1563 return PP.getLangOptions().Microsoft; 1564 } 1565} 1566 1567 1568/// ParseTypeQualifierListOpt 1569/// type-qualifier-list: [C99 6.7.5] 1570/// type-qualifier 1571/// [GNU] attributes [ only if AttributesAllowed=true ] 1572/// type-qualifier-list type-qualifier 1573/// [GNU] type-qualifier-list attributes [ only if AttributesAllowed=true ] 1574/// 1575void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, bool AttributesAllowed) { 1576 while (1) { 1577 int isInvalid = false; 1578 const char *PrevSpec = 0; 1579 SourceLocation Loc = Tok.getLocation(); 1580 1581 switch (Tok.getKind()) { 1582 case tok::kw_const: 1583 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, 1584 getLang())*2; 1585 break; 1586 case tok::kw_volatile: 1587 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, 1588 getLang())*2; 1589 break; 1590 case tok::kw_restrict: 1591 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, 1592 getLang())*2; 1593 break; 1594 case tok::kw___ptr64: 1595 case tok::kw___cdecl: 1596 case tok::kw___stdcall: 1597 case tok::kw___fastcall: 1598 if (!PP.getLangOptions().Microsoft) 1599 goto DoneWithTypeQuals; 1600 // Just ignore it. 1601 break; 1602 case tok::kw___attribute: 1603 if (AttributesAllowed) { 1604 DS.AddAttributes(ParseAttributes()); 1605 continue; // do *not* consume the next token! 1606 } 1607 // otherwise, FALL THROUGH! 1608 default: 1609 DoneWithTypeQuals: 1610 // If this is not a type-qualifier token, we're done reading type 1611 // qualifiers. First verify that DeclSpec's are consistent. 1612 DS.Finish(Diags, PP.getSourceManager(), getLang()); 1613 return; 1614 } 1615 1616 // If the specifier combination wasn't legal, issue a diagnostic. 1617 if (isInvalid) { 1618 assert(PrevSpec && "Method did not return previous specifier!"); 1619 // Pick between error or extwarn. 1620 unsigned DiagID = isInvalid == 1 ? diag::err_invalid_decl_spec_combination 1621 : diag::ext_duplicate_declspec; 1622 Diag(Tok, DiagID) << PrevSpec; 1623 } 1624 ConsumeToken(); 1625 } 1626} 1627 1628 1629/// ParseDeclarator - Parse and verify a newly-initialized declarator. 1630/// 1631void Parser::ParseDeclarator(Declarator &D) { 1632 /// This implements the 'declarator' production in the C grammar, then checks 1633 /// for well-formedness and issues diagnostics. 1634 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 1635} 1636 1637/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator 1638/// is parsed by the function passed to it. Pass null, and the direct-declarator 1639/// isn't parsed at all, making this function effectively parse the C++ 1640/// ptr-operator production. 1641/// 1642/// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl] 1643/// [C] pointer[opt] direct-declarator 1644/// [C++] direct-declarator 1645/// [C++] ptr-operator declarator 1646/// 1647/// pointer: [C99 6.7.5] 1648/// '*' type-qualifier-list[opt] 1649/// '*' type-qualifier-list[opt] pointer 1650/// 1651/// ptr-operator: 1652/// '*' cv-qualifier-seq[opt] 1653/// '&' 1654/// [C++0x] '&&' 1655/// [GNU] '&' restrict[opt] attributes[opt] 1656/// [GNU?] '&&' restrict[opt] attributes[opt] 1657/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt] 1658void Parser::ParseDeclaratorInternal(Declarator &D, 1659 DirectDeclParseFunction DirectDeclParser) { 1660 1661 // C++ member pointers start with a '::' or a nested-name. 1662 // Member pointers get special handling, since there's no place for the 1663 // scope spec in the generic path below. 1664 if (getLang().CPlusPlus && 1665 (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) || 1666 Tok.is(tok::annot_cxxscope))) { 1667 CXXScopeSpec SS; 1668 if (ParseOptionalCXXScopeSpecifier(SS)) { 1669 if(Tok.isNot(tok::star)) { 1670 // The scope spec really belongs to the direct-declarator. 1671 D.getCXXScopeSpec() = SS; 1672 if (DirectDeclParser) 1673 (this->*DirectDeclParser)(D); 1674 return; 1675 } 1676 1677 SourceLocation Loc = ConsumeToken(); 1678 D.SetRangeEnd(Loc); 1679 DeclSpec DS; 1680 ParseTypeQualifierListOpt(DS); 1681 D.ExtendWithDeclSpec(DS); 1682 1683 // Recurse to parse whatever is left. 1684 ParseDeclaratorInternal(D, DirectDeclParser); 1685 1686 // Sema will have to catch (syntactically invalid) pointers into global 1687 // scope. It has to catch pointers into namespace scope anyway. 1688 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(), 1689 Loc, DS.TakeAttributes()), 1690 /* Don't replace range end. */SourceLocation()); 1691 return; 1692 } 1693 } 1694 1695 tok::TokenKind Kind = Tok.getKind(); 1696 // Not a pointer, C++ reference, or block. 1697 if (Kind != tok::star && Kind != tok::caret && 1698 (Kind != tok::amp || !getLang().CPlusPlus) && 1699 // We parse rvalue refs in C++03, because otherwise the errors are scary. 1700 (Kind != tok::ampamp || !getLang().CPlusPlus)) { 1701 if (DirectDeclParser) 1702 (this->*DirectDeclParser)(D); 1703 return; 1704 } 1705 1706 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference, 1707 // '&&' -> rvalue reference 1708 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&. 1709 D.SetRangeEnd(Loc); 1710 1711 if (Kind == tok::star || Kind == tok::caret) { 1712 // Is a pointer. 1713 DeclSpec DS; 1714 1715 ParseTypeQualifierListOpt(DS); 1716 D.ExtendWithDeclSpec(DS); 1717 1718 // Recursively parse the declarator. 1719 ParseDeclaratorInternal(D, DirectDeclParser); 1720 if (Kind == tok::star) 1721 // Remember that we parsed a pointer type, and remember the type-quals. 1722 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc, 1723 DS.TakeAttributes()), 1724 SourceLocation()); 1725 else 1726 // Remember that we parsed a Block type, and remember the type-quals. 1727 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), 1728 Loc), 1729 SourceLocation()); 1730 } else { 1731 // Is a reference 1732 DeclSpec DS; 1733 1734 // Complain about rvalue references in C++03, but then go on and build 1735 // the declarator. 1736 if (Kind == tok::ampamp && !getLang().CPlusPlus0x) 1737 Diag(Loc, diag::err_rvalue_reference); 1738 1739 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the 1740 // cv-qualifiers are introduced through the use of a typedef or of a 1741 // template type argument, in which case the cv-qualifiers are ignored. 1742 // 1743 // [GNU] Retricted references are allowed. 1744 // [GNU] Attributes on references are allowed. 1745 ParseTypeQualifierListOpt(DS); 1746 D.ExtendWithDeclSpec(DS); 1747 1748 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) { 1749 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 1750 Diag(DS.getConstSpecLoc(), 1751 diag::err_invalid_reference_qualifier_application) << "const"; 1752 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 1753 Diag(DS.getVolatileSpecLoc(), 1754 diag::err_invalid_reference_qualifier_application) << "volatile"; 1755 } 1756 1757 // Recursively parse the declarator. 1758 ParseDeclaratorInternal(D, DirectDeclParser); 1759 1760 if (D.getNumTypeObjects() > 0) { 1761 // C++ [dcl.ref]p4: There shall be no references to references. 1762 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1); 1763 if (InnerChunk.Kind == DeclaratorChunk::Reference) { 1764 if (const IdentifierInfo *II = D.getIdentifier()) 1765 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 1766 << II; 1767 else 1768 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 1769 << "type name"; 1770 1771 // Once we've complained about the reference-to-reference, we 1772 // can go ahead and build the (technically ill-formed) 1773 // declarator: reference collapsing will take care of it. 1774 } 1775 } 1776 1777 // Remember that we parsed a reference type. It doesn't have type-quals. 1778 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc, 1779 DS.TakeAttributes(), 1780 Kind == tok::amp), 1781 SourceLocation()); 1782 } 1783} 1784 1785/// ParseDirectDeclarator 1786/// direct-declarator: [C99 6.7.5] 1787/// [C99] identifier 1788/// '(' declarator ')' 1789/// [GNU] '(' attributes declarator ')' 1790/// [C90] direct-declarator '[' constant-expression[opt] ']' 1791/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 1792/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 1793/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 1794/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 1795/// direct-declarator '(' parameter-type-list ')' 1796/// direct-declarator '(' identifier-list[opt] ')' 1797/// [GNU] direct-declarator '(' parameter-forward-declarations 1798/// parameter-type-list[opt] ')' 1799/// [C++] direct-declarator '(' parameter-declaration-clause ')' 1800/// cv-qualifier-seq[opt] exception-specification[opt] 1801/// [C++] declarator-id 1802/// 1803/// declarator-id: [C++ 8] 1804/// id-expression 1805/// '::'[opt] nested-name-specifier[opt] type-name 1806/// 1807/// id-expression: [C++ 5.1] 1808/// unqualified-id 1809/// qualified-id [TODO] 1810/// 1811/// unqualified-id: [C++ 5.1] 1812/// identifier 1813/// operator-function-id 1814/// conversion-function-id [TODO] 1815/// '~' class-name 1816/// template-id 1817/// 1818void Parser::ParseDirectDeclarator(Declarator &D) { 1819 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec()); 1820 1821 if (getLang().CPlusPlus) { 1822 if (D.mayHaveIdentifier()) { 1823 // ParseDeclaratorInternal might already have parsed the scope. 1824 bool afterCXXScope = D.getCXXScopeSpec().isSet() || 1825 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec()); 1826 if (afterCXXScope) { 1827 // Change the declaration context for name lookup, until this function 1828 // is exited (and the declarator has been parsed). 1829 DeclScopeObj.EnterDeclaratorScope(); 1830 } 1831 1832 if (Tok.is(tok::identifier)) { 1833 assert(Tok.getIdentifierInfo() && "Not an identifier?"); 1834 1835 // If this identifier is the name of the current class, it's a 1836 // constructor name. 1837 if (Actions.isCurrentClassName(*Tok.getIdentifierInfo(),CurScope)){ 1838 D.setConstructor(Actions.getTypeName(*Tok.getIdentifierInfo(), 1839 Tok.getLocation(), CurScope), 1840 Tok.getLocation()); 1841 // This is a normal identifier. 1842 } else 1843 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 1844 ConsumeToken(); 1845 goto PastIdentifier; 1846 } else if (Tok.is(tok::annot_template_id)) { 1847 TemplateIdAnnotation *TemplateId 1848 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 1849 1850 // FIXME: Could this template-id name a constructor? 1851 1852 // FIXME: This is an egregious hack, where we silently ignore 1853 // the specialization (which should be a function template 1854 // specialization name) and use the name instead. This hack 1855 // will go away when we have support for function 1856 // specializations. 1857 D.SetIdentifier(TemplateId->Name, Tok.getLocation()); 1858 TemplateId->Destroy(); 1859 ConsumeToken(); 1860 goto PastIdentifier; 1861 } else if (Tok.is(tok::kw_operator)) { 1862 SourceLocation OperatorLoc = Tok.getLocation(); 1863 SourceLocation EndLoc; 1864 1865 // First try the name of an overloaded operator 1866 if (OverloadedOperatorKind Op = TryParseOperatorFunctionId(&EndLoc)) { 1867 D.setOverloadedOperator(Op, OperatorLoc, EndLoc); 1868 } else { 1869 // This must be a conversion function (C++ [class.conv.fct]). 1870 if (TypeTy *ConvType = ParseConversionFunctionId(&EndLoc)) 1871 D.setConversionFunction(ConvType, OperatorLoc, EndLoc); 1872 else { 1873 D.SetIdentifier(0, Tok.getLocation()); 1874 } 1875 } 1876 goto PastIdentifier; 1877 } else if (Tok.is(tok::tilde)) { 1878 // This should be a C++ destructor. 1879 SourceLocation TildeLoc = ConsumeToken(); 1880 if (Tok.is(tok::identifier)) { 1881 // FIXME: Inaccurate. 1882 SourceLocation NameLoc = Tok.getLocation(); 1883 SourceLocation EndLoc; 1884 if (TypeTy *Type = ParseClassName(EndLoc)) { 1885 D.setDestructor(Type, TildeLoc, NameLoc); 1886 } else { 1887 D.SetIdentifier(0, TildeLoc); 1888 } 1889 } else { 1890 Diag(Tok, diag::err_expected_class_name); 1891 D.SetIdentifier(0, TildeLoc); 1892 } 1893 goto PastIdentifier; 1894 } 1895 1896 // If we reached this point, token is not identifier and not '~'. 1897 1898 if (afterCXXScope) { 1899 Diag(Tok, diag::err_expected_unqualified_id); 1900 D.SetIdentifier(0, Tok.getLocation()); 1901 D.setInvalidType(true); 1902 goto PastIdentifier; 1903 } 1904 } 1905 } 1906 1907 // If we reached this point, we are either in C/ObjC or the token didn't 1908 // satisfy any of the C++-specific checks. 1909 if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) { 1910 assert(!getLang().CPlusPlus && 1911 "There's a C++-specific check for tok::identifier above"); 1912 assert(Tok.getIdentifierInfo() && "Not an identifier?"); 1913 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 1914 ConsumeToken(); 1915 } else if (Tok.is(tok::l_paren)) { 1916 // direct-declarator: '(' declarator ')' 1917 // direct-declarator: '(' attributes declarator ')' 1918 // Example: 'char (*X)' or 'int (*XX)(void)' 1919 ParseParenDeclarator(D); 1920 } else if (D.mayOmitIdentifier()) { 1921 // This could be something simple like "int" (in which case the declarator 1922 // portion is empty), if an abstract-declarator is allowed. 1923 D.SetIdentifier(0, Tok.getLocation()); 1924 } else { 1925 if (D.getContext() == Declarator::MemberContext) 1926 Diag(Tok, diag::err_expected_member_name_or_semi) 1927 << D.getDeclSpec().getSourceRange(); 1928 else if (getLang().CPlusPlus) 1929 Diag(Tok, diag::err_expected_unqualified_id); 1930 else 1931 Diag(Tok, diag::err_expected_ident_lparen); 1932 D.SetIdentifier(0, Tok.getLocation()); 1933 D.setInvalidType(true); 1934 } 1935 1936 PastIdentifier: 1937 assert(D.isPastIdentifier() && 1938 "Haven't past the location of the identifier yet?"); 1939 1940 while (1) { 1941 if (Tok.is(tok::l_paren)) { 1942 // The paren may be part of a C++ direct initializer, eg. "int x(1);". 1943 // In such a case, check if we actually have a function declarator; if it 1944 // is not, the declarator has been fully parsed. 1945 if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) { 1946 // When not in file scope, warn for ambiguous function declarators, just 1947 // in case the author intended it as a variable definition. 1948 bool warnIfAmbiguous = D.getContext() != Declarator::FileContext; 1949 if (!isCXXFunctionDeclarator(warnIfAmbiguous)) 1950 break; 1951 } 1952 ParseFunctionDeclarator(ConsumeParen(), D); 1953 } else if (Tok.is(tok::l_square)) { 1954 ParseBracketDeclarator(D); 1955 } else { 1956 break; 1957 } 1958 } 1959} 1960 1961/// ParseParenDeclarator - We parsed the declarator D up to a paren. This is 1962/// only called before the identifier, so these are most likely just grouping 1963/// parens for precedence. If we find that these are actually function 1964/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator. 1965/// 1966/// direct-declarator: 1967/// '(' declarator ')' 1968/// [GNU] '(' attributes declarator ')' 1969/// direct-declarator '(' parameter-type-list ')' 1970/// direct-declarator '(' identifier-list[opt] ')' 1971/// [GNU] direct-declarator '(' parameter-forward-declarations 1972/// parameter-type-list[opt] ')' 1973/// 1974void Parser::ParseParenDeclarator(Declarator &D) { 1975 SourceLocation StartLoc = ConsumeParen(); 1976 assert(!D.isPastIdentifier() && "Should be called before passing identifier"); 1977 1978 // Eat any attributes before we look at whether this is a grouping or function 1979 // declarator paren. If this is a grouping paren, the attribute applies to 1980 // the type being built up, for example: 1981 // int (__attribute__(()) *x)(long y) 1982 // If this ends up not being a grouping paren, the attribute applies to the 1983 // first argument, for example: 1984 // int (__attribute__(()) int x) 1985 // In either case, we need to eat any attributes to be able to determine what 1986 // sort of paren this is. 1987 // 1988 AttributeList *AttrList = 0; 1989 bool RequiresArg = false; 1990 if (Tok.is(tok::kw___attribute)) { 1991 AttrList = ParseAttributes(); 1992 1993 // We require that the argument list (if this is a non-grouping paren) be 1994 // present even if the attribute list was empty. 1995 RequiresArg = true; 1996 } 1997 // Eat any Microsoft extensions. 1998 while ((Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) || 1999 (Tok.is(tok::kw___fastcall))) && PP.getLangOptions().Microsoft) 2000 ConsumeToken(); 2001 2002 // If we haven't past the identifier yet (or where the identifier would be 2003 // stored, if this is an abstract declarator), then this is probably just 2004 // grouping parens. However, if this could be an abstract-declarator, then 2005 // this could also be the start of function arguments (consider 'void()'). 2006 bool isGrouping; 2007 2008 if (!D.mayOmitIdentifier()) { 2009 // If this can't be an abstract-declarator, this *must* be a grouping 2010 // paren, because we haven't seen the identifier yet. 2011 isGrouping = true; 2012 } else if (Tok.is(tok::r_paren) || // 'int()' is a function. 2013 (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...) 2014 isDeclarationSpecifier()) { // 'int(int)' is a function. 2015 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is 2016 // considered to be a type, not a K&R identifier-list. 2017 isGrouping = false; 2018 } else { 2019 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'. 2020 isGrouping = true; 2021 } 2022 2023 // If this is a grouping paren, handle: 2024 // direct-declarator: '(' declarator ')' 2025 // direct-declarator: '(' attributes declarator ')' 2026 if (isGrouping) { 2027 bool hadGroupingParens = D.hasGroupingParens(); 2028 D.setGroupingParens(true); 2029 if (AttrList) 2030 D.AddAttributes(AttrList, SourceLocation()); 2031 2032 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 2033 // Match the ')'. 2034 SourceLocation Loc = MatchRHSPunctuation(tok::r_paren, StartLoc); 2035 2036 D.setGroupingParens(hadGroupingParens); 2037 D.SetRangeEnd(Loc); 2038 return; 2039 } 2040 2041 // Okay, if this wasn't a grouping paren, it must be the start of a function 2042 // argument list. Recognize that this declarator will never have an 2043 // identifier (and remember where it would have been), then call into 2044 // ParseFunctionDeclarator to handle of argument list. 2045 D.SetIdentifier(0, Tok.getLocation()); 2046 2047 ParseFunctionDeclarator(StartLoc, D, AttrList, RequiresArg); 2048} 2049 2050/// ParseFunctionDeclarator - We are after the identifier and have parsed the 2051/// declarator D up to a paren, which indicates that we are parsing function 2052/// arguments. 2053/// 2054/// If AttrList is non-null, then the caller parsed those arguments immediately 2055/// after the open paren - they should be considered to be the first argument of 2056/// a parameter. If RequiresArg is true, then the first argument of the 2057/// function is required to be present and required to not be an identifier 2058/// list. 2059/// 2060/// This method also handles this portion of the grammar: 2061/// parameter-type-list: [C99 6.7.5] 2062/// parameter-list 2063/// parameter-list ',' '...' 2064/// 2065/// parameter-list: [C99 6.7.5] 2066/// parameter-declaration 2067/// parameter-list ',' parameter-declaration 2068/// 2069/// parameter-declaration: [C99 6.7.5] 2070/// declaration-specifiers declarator 2071/// [C++] declaration-specifiers declarator '=' assignment-expression 2072/// [GNU] declaration-specifiers declarator attributes 2073/// declaration-specifiers abstract-declarator[opt] 2074/// [C++] declaration-specifiers abstract-declarator[opt] 2075/// '=' assignment-expression 2076/// [GNU] declaration-specifiers abstract-declarator[opt] attributes 2077/// 2078/// For C++, after the parameter-list, it also parses "cv-qualifier-seq[opt]" 2079/// and "exception-specification[opt]". 2080/// 2081void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D, 2082 AttributeList *AttrList, 2083 bool RequiresArg) { 2084 // lparen is already consumed! 2085 assert(D.isPastIdentifier() && "Should not call before identifier!"); 2086 2087 // This parameter list may be empty. 2088 if (Tok.is(tok::r_paren)) { 2089 if (RequiresArg) { 2090 Diag(Tok, diag::err_argument_required_after_attribute); 2091 delete AttrList; 2092 } 2093 2094 SourceLocation Loc = ConsumeParen(); // Eat the closing ')'. 2095 2096 // cv-qualifier-seq[opt]. 2097 DeclSpec DS; 2098 if (getLang().CPlusPlus) { 2099 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 2100 if (!DS.getSourceRange().getEnd().isInvalid()) 2101 Loc = DS.getSourceRange().getEnd(); 2102 2103 // Parse exception-specification[opt]. 2104 if (Tok.is(tok::kw_throw)) 2105 ParseExceptionSpecification(Loc); 2106 } 2107 2108 // Remember that we parsed a function type, and remember the attributes. 2109 // int() -> no prototype, no '...'. 2110 D.AddTypeInfo(DeclaratorChunk::getFunction(/*prototype*/getLang().CPlusPlus, 2111 /*variadic*/ false, 2112 SourceLocation(), 2113 /*arglist*/ 0, 0, 2114 DS.getTypeQualifiers(), 2115 LParenLoc, D), 2116 Loc); 2117 return; 2118 } 2119 2120 // Alternatively, this parameter list may be an identifier list form for a 2121 // K&R-style function: void foo(a,b,c) 2122 if (!getLang().CPlusPlus && Tok.is(tok::identifier)) { 2123 if (!TryAnnotateTypeOrScopeToken()) { 2124 // K&R identifier lists can't have typedefs as identifiers, per 2125 // C99 6.7.5.3p11. 2126 if (RequiresArg) { 2127 Diag(Tok, diag::err_argument_required_after_attribute); 2128 delete AttrList; 2129 } 2130 // Identifier list. Note that '(' identifier-list ')' is only allowed for 2131 // normal declarators, not for abstract-declarators. 2132 return ParseFunctionDeclaratorIdentifierList(LParenLoc, D); 2133 } 2134 } 2135 2136 // Finally, a normal, non-empty parameter type list. 2137 2138 // Build up an array of information about the parsed arguments. 2139 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 2140 2141 // Enter function-declaration scope, limiting any declarators to the 2142 // function prototype scope, including parameter declarators. 2143 ParseScope PrototypeScope(this, 2144 Scope::FunctionPrototypeScope|Scope::DeclScope); 2145 2146 bool IsVariadic = false; 2147 SourceLocation EllipsisLoc; 2148 while (1) { 2149 if (Tok.is(tok::ellipsis)) { 2150 IsVariadic = true; 2151 EllipsisLoc = ConsumeToken(); // Consume the ellipsis. 2152 break; 2153 } 2154 2155 SourceLocation DSStart = Tok.getLocation(); 2156 2157 // Parse the declaration-specifiers. 2158 DeclSpec DS; 2159 2160 // If the caller parsed attributes for the first argument, add them now. 2161 if (AttrList) { 2162 DS.AddAttributes(AttrList); 2163 AttrList = 0; // Only apply the attributes to the first parameter. 2164 } 2165 ParseDeclarationSpecifiers(DS); 2166 2167 // Parse the declarator. This is "PrototypeContext", because we must 2168 // accept either 'declarator' or 'abstract-declarator' here. 2169 Declarator ParmDecl(DS, Declarator::PrototypeContext); 2170 ParseDeclarator(ParmDecl); 2171 2172 // Parse GNU attributes, if present. 2173 if (Tok.is(tok::kw___attribute)) { 2174 SourceLocation Loc; 2175 AttributeList *AttrList = ParseAttributes(&Loc); 2176 ParmDecl.AddAttributes(AttrList, Loc); 2177 } 2178 2179 // Remember this parsed parameter in ParamInfo. 2180 IdentifierInfo *ParmII = ParmDecl.getIdentifier(); 2181 2182 // DefArgToks is used when the parsing of default arguments needs 2183 // to be delayed. 2184 CachedTokens *DefArgToks = 0; 2185 2186 // If no parameter was specified, verify that *something* was specified, 2187 // otherwise we have a missing type and identifier. 2188 if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 && 2189 ParmDecl.getNumTypeObjects() == 0) { 2190 // Completely missing, emit error. 2191 Diag(DSStart, diag::err_missing_param); 2192 } else { 2193 // Otherwise, we have something. Add it and let semantic analysis try 2194 // to grok it and add the result to the ParamInfo we are building. 2195 2196 // Inform the actions module about the parameter declarator, so it gets 2197 // added to the current scope. 2198 DeclTy *Param = Actions.ActOnParamDeclarator(CurScope, ParmDecl); 2199 2200 // Parse the default argument, if any. We parse the default 2201 // arguments in all dialects; the semantic analysis in 2202 // ActOnParamDefaultArgument will reject the default argument in 2203 // C. 2204 if (Tok.is(tok::equal)) { 2205 SourceLocation EqualLoc = Tok.getLocation(); 2206 2207 // Parse the default argument 2208 if (D.getContext() == Declarator::MemberContext) { 2209 // If we're inside a class definition, cache the tokens 2210 // corresponding to the default argument. We'll actually parse 2211 // them when we see the end of the class definition. 2212 // FIXME: Templates will require something similar. 2213 // FIXME: Can we use a smart pointer for Toks? 2214 DefArgToks = new CachedTokens; 2215 2216 if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks, 2217 tok::semi, false)) { 2218 delete DefArgToks; 2219 DefArgToks = 0; 2220 Actions.ActOnParamDefaultArgumentError(Param); 2221 } else 2222 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc); 2223 } else { 2224 // Consume the '='. 2225 ConsumeToken(); 2226 2227 OwningExprResult DefArgResult(ParseAssignmentExpression()); 2228 if (DefArgResult.isInvalid()) { 2229 Actions.ActOnParamDefaultArgumentError(Param); 2230 SkipUntil(tok::comma, tok::r_paren, true, true); 2231 } else { 2232 // Inform the actions module about the default argument 2233 Actions.ActOnParamDefaultArgument(Param, EqualLoc, 2234 move(DefArgResult)); 2235 } 2236 } 2237 } 2238 2239 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 2240 ParmDecl.getIdentifierLoc(), Param, 2241 DefArgToks)); 2242 } 2243 2244 // If the next token is a comma, consume it and keep reading arguments. 2245 if (Tok.isNot(tok::comma)) break; 2246 2247 // Consume the comma. 2248 ConsumeToken(); 2249 } 2250 2251 // Leave prototype scope. 2252 PrototypeScope.Exit(); 2253 2254 // If we have the closing ')', eat it. 2255 SourceLocation Loc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 2256 2257 DeclSpec DS; 2258 if (getLang().CPlusPlus) { 2259 // Parse cv-qualifier-seq[opt]. 2260 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 2261 if (!DS.getSourceRange().getEnd().isInvalid()) 2262 Loc = DS.getSourceRange().getEnd(); 2263 2264 // Parse exception-specification[opt]. 2265 if (Tok.is(tok::kw_throw)) 2266 ParseExceptionSpecification(Loc); 2267 } 2268 2269 // Remember that we parsed a function type, and remember the attributes. 2270 D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/true, IsVariadic, 2271 EllipsisLoc, 2272 &ParamInfo[0], ParamInfo.size(), 2273 DS.getTypeQualifiers(), 2274 LParenLoc, D), 2275 Loc); 2276} 2277 2278/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator 2279/// we found a K&R-style identifier list instead of a type argument list. The 2280/// current token is known to be the first identifier in the list. 2281/// 2282/// identifier-list: [C99 6.7.5] 2283/// identifier 2284/// identifier-list ',' identifier 2285/// 2286void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc, 2287 Declarator &D) { 2288 // Build up an array of information about the parsed arguments. 2289 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 2290 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar; 2291 2292 // If there was no identifier specified for the declarator, either we are in 2293 // an abstract-declarator, or we are in a parameter declarator which was found 2294 // to be abstract. In abstract-declarators, identifier lists are not valid: 2295 // diagnose this. 2296 if (!D.getIdentifier()) 2297 Diag(Tok, diag::ext_ident_list_in_param); 2298 2299 // Tok is known to be the first identifier in the list. Remember this 2300 // identifier in ParamInfo. 2301 ParamsSoFar.insert(Tok.getIdentifierInfo()); 2302 ParamInfo.push_back(DeclaratorChunk::ParamInfo(Tok.getIdentifierInfo(), 2303 Tok.getLocation(), 0)); 2304 2305 ConsumeToken(); // eat the first identifier. 2306 2307 while (Tok.is(tok::comma)) { 2308 // Eat the comma. 2309 ConsumeToken(); 2310 2311 // If this isn't an identifier, report the error and skip until ')'. 2312 if (Tok.isNot(tok::identifier)) { 2313 Diag(Tok, diag::err_expected_ident); 2314 SkipUntil(tok::r_paren); 2315 return; 2316 } 2317 2318 IdentifierInfo *ParmII = Tok.getIdentifierInfo(); 2319 2320 // Reject 'typedef int y; int test(x, y)', but continue parsing. 2321 if (Actions.getTypeName(*ParmII, Tok.getLocation(), CurScope)) 2322 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII; 2323 2324 // Verify that the argument identifier has not already been mentioned. 2325 if (!ParamsSoFar.insert(ParmII)) { 2326 Diag(Tok, diag::err_param_redefinition) << ParmII; 2327 } else { 2328 // Remember this identifier in ParamInfo. 2329 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 2330 Tok.getLocation(), 0)); 2331 } 2332 2333 // Eat the identifier. 2334 ConsumeToken(); 2335 } 2336 2337 // If we have the closing ')', eat it and we're done. 2338 SourceLocation RLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 2339 2340 // Remember that we parsed a function type, and remember the attributes. This 2341 // function type is always a K&R style function type, which is not varargs and 2342 // has no prototype. 2343 D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/false, /*varargs*/false, 2344 SourceLocation(), 2345 &ParamInfo[0], ParamInfo.size(), 2346 /*TypeQuals*/0, LParenLoc, D), 2347 RLoc); 2348} 2349 2350/// [C90] direct-declarator '[' constant-expression[opt] ']' 2351/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 2352/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 2353/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 2354/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 2355void Parser::ParseBracketDeclarator(Declarator &D) { 2356 SourceLocation StartLoc = ConsumeBracket(); 2357 2358 // C array syntax has many features, but by-far the most common is [] and [4]. 2359 // This code does a fast path to handle some of the most obvious cases. 2360 if (Tok.getKind() == tok::r_square) { 2361 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc); 2362 // Remember that we parsed the empty array type. 2363 OwningExprResult NumElements(Actions); 2364 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0, StartLoc), 2365 EndLoc); 2366 return; 2367 } else if (Tok.getKind() == tok::numeric_constant && 2368 GetLookAheadToken(1).is(tok::r_square)) { 2369 // [4] is very common. Parse the numeric constant expression. 2370 OwningExprResult ExprRes(Actions.ActOnNumericConstant(Tok)); 2371 ConsumeToken(); 2372 2373 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc); 2374 2375 // If there was an error parsing the assignment-expression, recover. 2376 if (ExprRes.isInvalid()) 2377 ExprRes.release(); // Deallocate expr, just use []. 2378 2379 // Remember that we parsed a array type, and remember its features. 2380 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0, 2381 ExprRes.release(), StartLoc), 2382 EndLoc); 2383 return; 2384 } 2385 2386 // If valid, this location is the position where we read the 'static' keyword. 2387 SourceLocation StaticLoc; 2388 if (Tok.is(tok::kw_static)) 2389 StaticLoc = ConsumeToken(); 2390 2391 // If there is a type-qualifier-list, read it now. 2392 // Type qualifiers in an array subscript are a C99 feature. 2393 DeclSpec DS; 2394 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 2395 2396 // If we haven't already read 'static', check to see if there is one after the 2397 // type-qualifier-list. 2398 if (!StaticLoc.isValid() && Tok.is(tok::kw_static)) 2399 StaticLoc = ConsumeToken(); 2400 2401 // Handle "direct-declarator [ type-qual-list[opt] * ]". 2402 bool isStar = false; 2403 OwningExprResult NumElements(Actions); 2404 2405 // Handle the case where we have '[*]' as the array size. However, a leading 2406 // star could be the start of an expression, for example 'X[*p + 4]'. Verify 2407 // the the token after the star is a ']'. Since stars in arrays are 2408 // infrequent, use of lookahead is not costly here. 2409 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) { 2410 ConsumeToken(); // Eat the '*'. 2411 2412 if (StaticLoc.isValid()) { 2413 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static); 2414 StaticLoc = SourceLocation(); // Drop the static. 2415 } 2416 isStar = true; 2417 } else if (Tok.isNot(tok::r_square)) { 2418 // Note, in C89, this production uses the constant-expr production instead 2419 // of assignment-expr. The only difference is that assignment-expr allows 2420 // things like '=' and '*='. Sema rejects these in C89 mode because they 2421 // are not i-c-e's, so we don't need to distinguish between the two here. 2422 2423 // Parse the assignment-expression now. 2424 NumElements = ParseAssignmentExpression(); 2425 } 2426 2427 // If there was an error parsing the assignment-expression, recover. 2428 if (NumElements.isInvalid()) { 2429 // If the expression was invalid, skip it. 2430 SkipUntil(tok::r_square); 2431 return; 2432 } 2433 2434 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc); 2435 2436 // Remember that we parsed a array type, and remember its features. 2437 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(), 2438 StaticLoc.isValid(), isStar, 2439 NumElements.release(), StartLoc), 2440 EndLoc); 2441} 2442 2443/// [GNU] typeof-specifier: 2444/// typeof ( expressions ) 2445/// typeof ( type-name ) 2446/// [GNU/C++] typeof unary-expression 2447/// 2448void Parser::ParseTypeofSpecifier(DeclSpec &DS) { 2449 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier"); 2450 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo(); 2451 SourceLocation StartLoc = ConsumeToken(); 2452 2453 if (Tok.isNot(tok::l_paren)) { 2454 if (!getLang().CPlusPlus) { 2455 Diag(Tok, diag::err_expected_lparen_after_id) << BuiltinII; 2456 return; 2457 } 2458 2459 OwningExprResult Result(ParseCastExpression(true/*isUnaryExpression*/)); 2460 if (Result.isInvalid()) { 2461 DS.SetTypeSpecError(); 2462 return; 2463 } 2464 2465 const char *PrevSpec = 0; 2466 // Check for duplicate type specifiers. 2467 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec, 2468 Result.release())) 2469 Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec; 2470 2471 // FIXME: Not accurate, the range gets one token more than it should. 2472 DS.SetRangeEnd(Tok.getLocation()); 2473 return; 2474 } 2475 2476 SourceLocation LParenLoc = ConsumeParen(), RParenLoc; 2477 2478 if (isTypeIdInParens()) { 2479 Action::TypeResult Ty = ParseTypeName(); 2480 2481 assert((Ty.isInvalid() || Ty.get()) && 2482 "Parser::ParseTypeofSpecifier(): missing type"); 2483 2484 if (Tok.isNot(tok::r_paren)) { 2485 MatchRHSPunctuation(tok::r_paren, LParenLoc); 2486 return; 2487 } 2488 RParenLoc = ConsumeParen(); 2489 2490 if (Ty.isInvalid()) 2491 DS.SetTypeSpecError(); 2492 else { 2493 const char *PrevSpec = 0; 2494 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 2495 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec, 2496 Ty.get())) 2497 Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec; 2498 } 2499 } else { // we have an expression. 2500 OwningExprResult Result(ParseExpression()); 2501 2502 if (Result.isInvalid() || Tok.isNot(tok::r_paren)) { 2503 MatchRHSPunctuation(tok::r_paren, LParenLoc); 2504 DS.SetTypeSpecError(); 2505 return; 2506 } 2507 RParenLoc = ConsumeParen(); 2508 const char *PrevSpec = 0; 2509 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 2510 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec, 2511 Result.release())) 2512 Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec; 2513 } 2514 DS.SetRangeEnd(RParenLoc); 2515} 2516 2517 2518