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