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