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