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