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