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