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