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