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