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