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