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