clang API Documentation

ParseObjc.cpp
Go to the documentation of this file.
00001 //===--- ParseObjC.cpp - Objective C Parsing ------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements the Objective-C portions of the Parser interface.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Parse/ParseDiagnostic.h"
00015 #include "clang/Parse/Parser.h"
00016 #include "RAIIObjectsForParser.h"
00017 #include "clang/Sema/DeclSpec.h"
00018 #include "clang/Sema/PrettyDeclStackTrace.h"
00019 #include "clang/Sema/Scope.h"
00020 #include "llvm/ADT/SmallVector.h"
00021 using namespace clang;
00022 
00023 
00024 /// ParseObjCAtDirectives - Handle parts of the external-declaration production:
00025 ///       external-declaration: [C99 6.9]
00026 /// [OBJC]  objc-class-definition
00027 /// [OBJC]  objc-class-declaration
00028 /// [OBJC]  objc-alias-declaration
00029 /// [OBJC]  objc-protocol-definition
00030 /// [OBJC]  objc-method-definition
00031 /// [OBJC]  '@' 'end'
00032 Parser::DeclGroupPtrTy Parser::ParseObjCAtDirectives() {
00033   SourceLocation AtLoc = ConsumeToken(); // the "@"
00034 
00035   if (Tok.is(tok::code_completion)) {
00036     Actions.CodeCompleteObjCAtDirective(getCurScope());
00037     cutOffParsing();
00038     return DeclGroupPtrTy();
00039   }
00040     
00041   Decl *SingleDecl = 0;
00042   switch (Tok.getObjCKeywordID()) {
00043   case tok::objc_class:
00044     return ParseObjCAtClassDeclaration(AtLoc);
00045   case tok::objc_interface: {
00046     ParsedAttributes attrs(AttrFactory);
00047     SingleDecl = ParseObjCAtInterfaceDeclaration(AtLoc, attrs);
00048     break;
00049   }
00050   case tok::objc_protocol: {
00051     ParsedAttributes attrs(AttrFactory);
00052     return ParseObjCAtProtocolDeclaration(AtLoc, attrs);
00053   }
00054   case tok::objc_implementation:
00055     return ParseObjCAtImplementationDeclaration(AtLoc);
00056   case tok::objc_end:
00057     return ParseObjCAtEndDeclaration(AtLoc);
00058   case tok::objc_compatibility_alias:
00059     SingleDecl = ParseObjCAtAliasDeclaration(AtLoc);
00060     break;
00061   case tok::objc_synthesize:
00062     SingleDecl = ParseObjCPropertySynthesize(AtLoc);
00063     break;
00064   case tok::objc_dynamic:
00065     SingleDecl = ParseObjCPropertyDynamic(AtLoc);
00066     break;
00067   case tok::objc___experimental_modules_import:
00068     if (getLangOpts().Modules)
00069       return ParseModuleImport(AtLoc);
00070       
00071     // Fall through
00072       
00073   default:
00074     Diag(AtLoc, diag::err_unexpected_at);
00075     SkipUntil(tok::semi);
00076     SingleDecl = 0;
00077     break;
00078   }
00079   return Actions.ConvertDeclToDeclGroup(SingleDecl);
00080 }
00081 
00082 ///
00083 /// objc-class-declaration:
00084 ///    '@' 'class' identifier-list ';'
00085 ///
00086 Parser::DeclGroupPtrTy
00087 Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) {
00088   ConsumeToken(); // the identifier "class"
00089   SmallVector<IdentifierInfo *, 8> ClassNames;
00090   SmallVector<SourceLocation, 8> ClassLocs;
00091 
00092 
00093   while (1) {
00094     if (Tok.isNot(tok::identifier)) {
00095       Diag(Tok, diag::err_expected_ident);
00096       SkipUntil(tok::semi);
00097       return Actions.ConvertDeclToDeclGroup(0);
00098     }
00099     ClassNames.push_back(Tok.getIdentifierInfo());
00100     ClassLocs.push_back(Tok.getLocation());
00101     ConsumeToken();
00102 
00103     if (Tok.isNot(tok::comma))
00104       break;
00105 
00106     ConsumeToken();
00107   }
00108 
00109   // Consume the ';'.
00110   if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@class"))
00111     return Actions.ConvertDeclToDeclGroup(0);
00112 
00113   return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(),
00114                                               ClassLocs.data(),
00115                                               ClassNames.size());
00116 }
00117 
00118 void Parser::CheckNestedObjCContexts(SourceLocation AtLoc)
00119 {
00120   Sema::ObjCContainerKind ock = Actions.getObjCContainerKind();
00121   if (ock == Sema::OCK_None)
00122     return;
00123 
00124   Decl *Decl = Actions.getObjCDeclContext();
00125   if (CurParsedObjCImpl) {
00126     CurParsedObjCImpl->finish(AtLoc);
00127   } else {
00128     Actions.ActOnAtEnd(getCurScope(), AtLoc);
00129   }
00130   Diag(AtLoc, diag::err_objc_missing_end)
00131       << FixItHint::CreateInsertion(AtLoc, "@end\n");
00132   if (Decl)
00133     Diag(Decl->getLocStart(), diag::note_objc_container_start)
00134         << (int) ock;
00135 }
00136 
00137 ///
00138 ///   objc-interface:
00139 ///     objc-class-interface-attributes[opt] objc-class-interface
00140 ///     objc-category-interface
00141 ///
00142 ///   objc-class-interface:
00143 ///     '@' 'interface' identifier objc-superclass[opt]
00144 ///       objc-protocol-refs[opt]
00145 ///       objc-class-instance-variables[opt]
00146 ///       objc-interface-decl-list
00147 ///     @end
00148 ///
00149 ///   objc-category-interface:
00150 ///     '@' 'interface' identifier '(' identifier[opt] ')'
00151 ///       objc-protocol-refs[opt]
00152 ///       objc-interface-decl-list
00153 ///     @end
00154 ///
00155 ///   objc-superclass:
00156 ///     ':' identifier
00157 ///
00158 ///   objc-class-interface-attributes:
00159 ///     __attribute__((visibility("default")))
00160 ///     __attribute__((visibility("hidden")))
00161 ///     __attribute__((deprecated))
00162 ///     __attribute__((unavailable))
00163 ///     __attribute__((objc_exception)) - used by NSException on 64-bit
00164 ///     __attribute__((objc_root_class))
00165 ///
00166 Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
00167                                               ParsedAttributes &attrs) {
00168   assert(Tok.isObjCAtKeyword(tok::objc_interface) &&
00169          "ParseObjCAtInterfaceDeclaration(): Expected @interface");
00170   CheckNestedObjCContexts(AtLoc);
00171   ConsumeToken(); // the "interface" identifier
00172 
00173   // Code completion after '@interface'.
00174   if (Tok.is(tok::code_completion)) {
00175     Actions.CodeCompleteObjCInterfaceDecl(getCurScope());
00176     cutOffParsing();
00177     return 0;
00178   }
00179 
00180   if (Tok.isNot(tok::identifier)) {
00181     Diag(Tok, diag::err_expected_ident); // missing class or category name.
00182     return 0;
00183   }
00184 
00185   // We have a class or category name - consume it.
00186   IdentifierInfo *nameId = Tok.getIdentifierInfo();
00187   SourceLocation nameLoc = ConsumeToken();
00188   if (Tok.is(tok::l_paren) && 
00189       !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category.
00190     
00191     BalancedDelimiterTracker T(*this, tok::l_paren);
00192     T.consumeOpen();
00193 
00194     SourceLocation categoryLoc;
00195     IdentifierInfo *categoryId = 0;
00196     if (Tok.is(tok::code_completion)) {
00197       Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc);
00198       cutOffParsing();
00199       return 0;
00200     }
00201     
00202     // For ObjC2, the category name is optional (not an error).
00203     if (Tok.is(tok::identifier)) {
00204       categoryId = Tok.getIdentifierInfo();
00205       categoryLoc = ConsumeToken();
00206     }
00207     else if (!getLangOpts().ObjC2) {
00208       Diag(Tok, diag::err_expected_ident); // missing category name.
00209       return 0;
00210     }
00211    
00212     T.consumeClose();
00213     if (T.getCloseLocation().isInvalid())
00214       return 0;
00215     
00216     if (!attrs.empty()) { // categories don't support attributes.
00217       Diag(nameLoc, diag::err_objc_no_attributes_on_category);
00218       attrs.clear();
00219     }
00220     
00221     // Next, we need to check for any protocol references.
00222     SourceLocation LAngleLoc, EndProtoLoc;
00223     SmallVector<Decl *, 8> ProtocolRefs;
00224     SmallVector<SourceLocation, 8> ProtocolLocs;
00225     if (Tok.is(tok::less) &&
00226         ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true,
00227                                     LAngleLoc, EndProtoLoc))
00228       return 0;
00229 
00230     Decl *CategoryType =
00231     Actions.ActOnStartCategoryInterface(AtLoc,
00232                                         nameId, nameLoc,
00233                                         categoryId, categoryLoc,
00234                                         ProtocolRefs.data(),
00235                                         ProtocolRefs.size(),
00236                                         ProtocolLocs.data(),
00237                                         EndProtoLoc);
00238     
00239     if (Tok.is(tok::l_brace))
00240       ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, AtLoc);
00241       
00242     ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType);
00243     return CategoryType;
00244   }
00245   // Parse a class interface.
00246   IdentifierInfo *superClassId = 0;
00247   SourceLocation superClassLoc;
00248 
00249   if (Tok.is(tok::colon)) { // a super class is specified.
00250     ConsumeToken();
00251 
00252     // Code completion of superclass names.
00253     if (Tok.is(tok::code_completion)) {
00254       Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc);
00255       cutOffParsing();
00256       return 0;
00257     }
00258 
00259     if (Tok.isNot(tok::identifier)) {
00260       Diag(Tok, diag::err_expected_ident); // missing super class name.
00261       return 0;
00262     }
00263     superClassId = Tok.getIdentifierInfo();
00264     superClassLoc = ConsumeToken();
00265   }
00266   // Next, we need to check for any protocol references.
00267   SmallVector<Decl *, 8> ProtocolRefs;
00268   SmallVector<SourceLocation, 8> ProtocolLocs;
00269   SourceLocation LAngleLoc, EndProtoLoc;
00270   if (Tok.is(tok::less) &&
00271       ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true,
00272                                   LAngleLoc, EndProtoLoc))
00273     return 0;
00274 
00275   Decl *ClsType =
00276     Actions.ActOnStartClassInterface(AtLoc, nameId, nameLoc,
00277                                      superClassId, superClassLoc,
00278                                      ProtocolRefs.data(), ProtocolRefs.size(),
00279                                      ProtocolLocs.data(),
00280                                      EndProtoLoc, attrs.getList());
00281 
00282   if (Tok.is(tok::l_brace))
00283     ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, AtLoc);
00284 
00285   ParseObjCInterfaceDeclList(tok::objc_interface, ClsType);
00286   return ClsType;
00287 }
00288 
00289 /// The Objective-C property callback.  This should be defined where
00290 /// it's used, but instead it's been lifted to here to support VS2005.
00291 struct Parser::ObjCPropertyCallback : FieldCallback {
00292 private:
00293   virtual void anchor();
00294 public:
00295   Parser &P;
00296   SmallVectorImpl<Decl *> &Props;
00297   ObjCDeclSpec &OCDS;
00298   SourceLocation AtLoc;
00299   SourceLocation LParenLoc;
00300   tok::ObjCKeywordKind MethodImplKind;
00301         
00302   ObjCPropertyCallback(Parser &P, 
00303                        SmallVectorImpl<Decl *> &Props,
00304                        ObjCDeclSpec &OCDS, SourceLocation AtLoc,
00305                        SourceLocation LParenLoc,
00306                        tok::ObjCKeywordKind MethodImplKind) :
00307     P(P), Props(Props), OCDS(OCDS), AtLoc(AtLoc), LParenLoc(LParenLoc),
00308     MethodImplKind(MethodImplKind) {
00309   }
00310 
00311   Decl *invoke(FieldDeclarator &FD) {
00312     if (FD.D.getIdentifier() == 0) {
00313       P.Diag(AtLoc, diag::err_objc_property_requires_field_name)
00314         << FD.D.getSourceRange();
00315       return 0;
00316     }
00317     if (FD.BitfieldSize) {
00318       P.Diag(AtLoc, diag::err_objc_property_bitfield)
00319         << FD.D.getSourceRange();
00320       return 0;
00321     }
00322 
00323     // Install the property declarator into interfaceDecl.
00324     IdentifierInfo *SelName =
00325       OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier();
00326 
00327     Selector GetterSel =
00328       P.PP.getSelectorTable().getNullarySelector(SelName);
00329     IdentifierInfo *SetterName = OCDS.getSetterName();
00330     Selector SetterSel;
00331     if (SetterName)
00332       SetterSel = P.PP.getSelectorTable().getSelector(1, &SetterName);
00333     else
00334       SetterSel = SelectorTable::constructSetterName(P.PP.getIdentifierTable(),
00335                                                      P.PP.getSelectorTable(),
00336                                                      FD.D.getIdentifier());
00337     bool isOverridingProperty = false;
00338     Decl *Property =
00339       P.Actions.ActOnProperty(P.getCurScope(), AtLoc, LParenLoc,
00340                               FD, OCDS,
00341                               GetterSel, SetterSel, 
00342                               &isOverridingProperty,
00343                               MethodImplKind);
00344     if (!isOverridingProperty)
00345       Props.push_back(Property);
00346 
00347     return Property;
00348   }
00349 };
00350 
00351 void Parser::ObjCPropertyCallback::anchor() {
00352 }
00353 
00354 ///   objc-interface-decl-list:
00355 ///     empty
00356 ///     objc-interface-decl-list objc-property-decl [OBJC2]
00357 ///     objc-interface-decl-list objc-method-requirement [OBJC2]
00358 ///     objc-interface-decl-list objc-method-proto ';'
00359 ///     objc-interface-decl-list declaration
00360 ///     objc-interface-decl-list ';'
00361 ///
00362 ///   objc-method-requirement: [OBJC2]
00363 ///     @required
00364 ///     @optional
00365 ///
00366 void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, 
00367                                         Decl *CDecl) {
00368   SmallVector<Decl *, 32> allMethods;
00369   SmallVector<Decl *, 16> allProperties;
00370   SmallVector<DeclGroupPtrTy, 8> allTUVariables;
00371   tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword;
00372 
00373   SourceRange AtEnd;
00374     
00375   while (1) {
00376     // If this is a method prototype, parse it.
00377     if (Tok.is(tok::minus) || Tok.is(tok::plus)) {
00378       Decl *methodPrototype =
00379         ParseObjCMethodPrototype(MethodImplKind, false);
00380       allMethods.push_back(methodPrototype);
00381       // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for
00382       // method definitions.
00383       if (ExpectAndConsumeSemi(diag::err_expected_semi_after_method_proto)) {
00384         // We didn't find a semi and we error'ed out. Skip until a ';' or '@'.
00385         SkipUntil(tok::at, /*StopAtSemi=*/true, /*DontConsume=*/true);
00386         if (Tok.is(tok::semi))
00387           ConsumeToken();
00388       }
00389       continue;
00390     }
00391     if (Tok.is(tok::l_paren)) {
00392       Diag(Tok, diag::err_expected_minus_or_plus);
00393       ParseObjCMethodDecl(Tok.getLocation(), 
00394                           tok::minus, 
00395                           MethodImplKind, false);
00396       continue;
00397     }
00398     // Ignore excess semicolons.
00399     if (Tok.is(tok::semi)) {
00400       ConsumeToken();
00401       continue;
00402     }
00403 
00404     // If we got to the end of the file, exit the loop.
00405     if (Tok.is(tok::eof))
00406       break;
00407 
00408     // Code completion within an Objective-C interface.
00409     if (Tok.is(tok::code_completion)) {
00410       Actions.CodeCompleteOrdinaryName(getCurScope(), 
00411                             CurParsedObjCImpl? Sema::PCC_ObjCImplementation
00412                                              : Sema::PCC_ObjCInterface);
00413       return cutOffParsing();
00414     }
00415     
00416     // If we don't have an @ directive, parse it as a function definition.
00417     if (Tok.isNot(tok::at)) {
00418       // The code below does not consume '}'s because it is afraid of eating the
00419       // end of a namespace.  Because of the way this code is structured, an
00420       // erroneous r_brace would cause an infinite loop if not handled here.
00421       if (Tok.is(tok::r_brace))
00422         break;
00423       ParsedAttributes attrs(AttrFactory);
00424       allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(attrs));
00425       continue;
00426     }
00427 
00428     // Otherwise, we have an @ directive, eat the @.
00429     SourceLocation AtLoc = ConsumeToken(); // the "@"
00430     if (Tok.is(tok::code_completion)) {
00431       Actions.CodeCompleteObjCAtDirective(getCurScope());
00432       return cutOffParsing();
00433     }
00434 
00435     tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID();
00436 
00437     if (DirectiveKind == tok::objc_end) { // @end -> terminate list
00438       AtEnd.setBegin(AtLoc);
00439       AtEnd.setEnd(Tok.getLocation());
00440       break;
00441     } else if (DirectiveKind == tok::objc_not_keyword) {
00442       Diag(Tok, diag::err_objc_unknown_at);
00443       SkipUntil(tok::semi);
00444       continue;
00445     }
00446 
00447     // Eat the identifier.
00448     ConsumeToken();
00449 
00450     switch (DirectiveKind) {
00451     default:
00452       // FIXME: If someone forgets an @end on a protocol, this loop will
00453       // continue to eat up tons of stuff and spew lots of nonsense errors.  It
00454       // would probably be better to bail out if we saw an @class or @interface
00455       // or something like that.
00456       Diag(AtLoc, diag::err_objc_illegal_interface_qual);
00457       // Skip until we see an '@' or '}' or ';'.
00458       SkipUntil(tok::r_brace, tok::at);
00459       break;
00460         
00461     case tok::objc_implementation:
00462     case tok::objc_interface:
00463       Diag(AtLoc, diag::err_objc_missing_end)
00464           << FixItHint::CreateInsertion(AtLoc, "@end\n");
00465       Diag(CDecl->getLocStart(), diag::note_objc_container_start)
00466           << (int) Actions.getObjCContainerKind();
00467       ConsumeToken();
00468       break;
00469         
00470     case tok::objc_required:
00471     case tok::objc_optional:
00472       // This is only valid on protocols.
00473       // FIXME: Should this check for ObjC2 being enabled?
00474       if (contextKey != tok::objc_protocol)
00475         Diag(AtLoc, diag::err_objc_directive_only_in_protocol);
00476       else
00477         MethodImplKind = DirectiveKind;
00478       break;
00479 
00480     case tok::objc_property:
00481       if (!getLangOpts().ObjC2)
00482         Diag(AtLoc, diag::err_objc_properties_require_objc2);
00483 
00484       ObjCDeclSpec OCDS;
00485       SourceLocation LParenLoc;
00486       // Parse property attribute list, if any.
00487       if (Tok.is(tok::l_paren)) {
00488         LParenLoc = Tok.getLocation();
00489         ParseObjCPropertyAttribute(OCDS);
00490       }
00491 
00492       ObjCPropertyCallback Callback(*this, allProperties,
00493                                     OCDS, AtLoc, LParenLoc, MethodImplKind);
00494 
00495       // Parse all the comma separated declarators.
00496       DeclSpec DS(AttrFactory);
00497       ParseStructDeclaration(DS, Callback);
00498 
00499       ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
00500       break;
00501     }
00502   }
00503 
00504   // We break out of the big loop in two cases: when we see @end or when we see
00505   // EOF.  In the former case, eat the @end.  In the later case, emit an error.
00506   if (Tok.is(tok::code_completion)) {
00507     Actions.CodeCompleteObjCAtDirective(getCurScope());
00508     return cutOffParsing();
00509   } else if (Tok.isObjCAtKeyword(tok::objc_end)) {
00510     ConsumeToken(); // the "end" identifier
00511   } else {
00512     Diag(Tok, diag::err_objc_missing_end)
00513         << FixItHint::CreateInsertion(Tok.getLocation(), "\n@end\n");
00514     Diag(CDecl->getLocStart(), diag::note_objc_container_start)
00515         << (int) Actions.getObjCContainerKind();
00516     AtEnd.setBegin(Tok.getLocation());
00517     AtEnd.setEnd(Tok.getLocation());
00518   }
00519 
00520   // Insert collected methods declarations into the @interface object.
00521   // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit.
00522   Actions.ActOnAtEnd(getCurScope(), AtEnd,
00523                      allMethods.data(), allMethods.size(),
00524                      allProperties.data(), allProperties.size(),
00525                      allTUVariables.data(), allTUVariables.size());
00526 }
00527 
00528 ///   Parse property attribute declarations.
00529 ///
00530 ///   property-attr-decl: '(' property-attrlist ')'
00531 ///   property-attrlist:
00532 ///     property-attribute
00533 ///     property-attrlist ',' property-attribute
00534 ///   property-attribute:
00535 ///     getter '=' identifier
00536 ///     setter '=' identifier ':'
00537 ///     readonly
00538 ///     readwrite
00539 ///     assign
00540 ///     retain
00541 ///     copy
00542 ///     nonatomic
00543 ///     atomic
00544 ///     strong
00545 ///     weak
00546 ///     unsafe_unretained
00547 ///
00548 void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) {
00549   assert(Tok.getKind() == tok::l_paren);
00550   BalancedDelimiterTracker T(*this, tok::l_paren);
00551   T.consumeOpen();
00552 
00553   while (1) {
00554     if (Tok.is(tok::code_completion)) {
00555       Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS);
00556       return cutOffParsing();
00557     }
00558     const IdentifierInfo *II = Tok.getIdentifierInfo();
00559 
00560     // If this is not an identifier at all, bail out early.
00561     if (II == 0) {
00562       T.consumeClose();
00563       return;
00564     }
00565 
00566     SourceLocation AttrName = ConsumeToken(); // consume last attribute name
00567 
00568     if (II->isStr("readonly"))
00569       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly);
00570     else if (II->isStr("assign"))
00571       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign);
00572     else if (II->isStr("unsafe_unretained"))
00573       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_unsafe_unretained);
00574     else if (II->isStr("readwrite"))
00575       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite);
00576     else if (II->isStr("retain"))
00577       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain);
00578     else if (II->isStr("strong"))
00579       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_strong);
00580     else if (II->isStr("copy"))
00581       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy);
00582     else if (II->isStr("nonatomic"))
00583       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic);
00584     else if (II->isStr("atomic"))
00585       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_atomic);
00586     else if (II->isStr("weak"))
00587       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_weak);
00588     else if (II->isStr("getter") || II->isStr("setter")) {
00589       bool IsSetter = II->getNameStart()[0] == 's';
00590 
00591       // getter/setter require extra treatment.
00592       unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter :
00593         diag::err_objc_expected_equal_for_getter;
00594 
00595       if (ExpectAndConsume(tok::equal, DiagID, "", tok::r_paren))
00596         return;
00597 
00598       if (Tok.is(tok::code_completion)) {
00599         if (IsSetter)
00600           Actions.CodeCompleteObjCPropertySetter(getCurScope());
00601         else
00602           Actions.CodeCompleteObjCPropertyGetter(getCurScope());
00603         return cutOffParsing();
00604       }
00605 
00606       
00607       SourceLocation SelLoc;
00608       IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc);
00609 
00610       if (!SelIdent) {
00611         Diag(Tok, diag::err_objc_expected_selector_for_getter_setter)
00612           << IsSetter;
00613         SkipUntil(tok::r_paren);
00614         return;
00615       }
00616 
00617       if (IsSetter) {
00618         DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter);
00619         DS.setSetterName(SelIdent);
00620 
00621         if (ExpectAndConsume(tok::colon, 
00622                              diag::err_expected_colon_after_setter_name, "",
00623                              tok::r_paren))
00624           return;
00625       } else {
00626         DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter);
00627         DS.setGetterName(SelIdent);
00628       }
00629     } else {
00630       Diag(AttrName, diag::err_objc_expected_property_attr) << II;
00631       SkipUntil(tok::r_paren);
00632       return;
00633     }
00634 
00635     if (Tok.isNot(tok::comma))
00636       break;
00637 
00638     ConsumeToken();
00639   }
00640 
00641   T.consumeClose();
00642 }
00643 
00644 ///   objc-method-proto:
00645 ///     objc-instance-method objc-method-decl objc-method-attributes[opt]
00646 ///     objc-class-method objc-method-decl objc-method-attributes[opt]
00647 ///
00648 ///   objc-instance-method: '-'
00649 ///   objc-class-method: '+'
00650 ///
00651 ///   objc-method-attributes:         [OBJC2]
00652 ///     __attribute__((deprecated))
00653 ///
00654 Decl *Parser::ParseObjCMethodPrototype(tok::ObjCKeywordKind MethodImplKind,
00655                                        bool MethodDefinition) {
00656   assert((Tok.is(tok::minus) || Tok.is(tok::plus)) && "expected +/-");
00657 
00658   tok::TokenKind methodType = Tok.getKind();
00659   SourceLocation mLoc = ConsumeToken();
00660   Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, MethodImplKind,
00661                                     MethodDefinition);
00662   // Since this rule is used for both method declarations and definitions,
00663   // the caller is (optionally) responsible for consuming the ';'.
00664   return MDecl;
00665 }
00666 
00667 ///   objc-selector:
00668 ///     identifier
00669 ///     one of
00670 ///       enum struct union if else while do for switch case default
00671 ///       break continue return goto asm sizeof typeof __alignof
00672 ///       unsigned long const short volatile signed restrict _Complex
00673 ///       in out inout bycopy byref oneway int char float double void _Bool
00674 ///
00675 IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) {
00676 
00677   switch (Tok.getKind()) {
00678   default:
00679     return 0;
00680   case tok::ampamp:
00681   case tok::ampequal:
00682   case tok::amp:
00683   case tok::pipe:
00684   case tok::tilde:
00685   case tok::exclaim:
00686   case tok::exclaimequal:
00687   case tok::pipepipe:
00688   case tok::pipeequal:
00689   case tok::caret:
00690   case tok::caretequal: {
00691     std::string ThisTok(PP.getSpelling(Tok));
00692     if (isalpha(ThisTok[0])) {
00693       IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok.data());
00694       Tok.setKind(tok::identifier);
00695       SelectorLoc = ConsumeToken();
00696       return II;
00697     }
00698     return 0; 
00699   }
00700       
00701   case tok::identifier:
00702   case tok::kw_asm:
00703   case tok::kw_auto:
00704   case tok::kw_bool:
00705   case tok::kw_break:
00706   case tok::kw_case:
00707   case tok::kw_catch:
00708   case tok::kw_char:
00709   case tok::kw_class:
00710   case tok::kw_const:
00711   case tok::kw_const_cast:
00712   case tok::kw_continue:
00713   case tok::kw_default:
00714   case tok::kw_delete:
00715   case tok::kw_do:
00716   case tok::kw_double:
00717   case tok::kw_dynamic_cast:
00718   case tok::kw_else:
00719   case tok::kw_enum:
00720   case tok::kw_explicit:
00721   case tok::kw_export:
00722   case tok::kw_extern:
00723   case tok::kw_false:
00724   case tok::kw_float:
00725   case tok::kw_for:
00726   case tok::kw_friend:
00727   case tok::kw_goto:
00728   case tok::kw_if:
00729   case tok::kw_inline:
00730   case tok::kw_int:
00731   case tok::kw_long:
00732   case tok::kw_mutable:
00733   case tok::kw_namespace:
00734   case tok::kw_new:
00735   case tok::kw_operator:
00736   case tok::kw_private:
00737   case tok::kw_protected:
00738   case tok::kw_public:
00739   case tok::kw_register:
00740   case tok::kw_reinterpret_cast:
00741   case tok::kw_restrict:
00742   case tok::kw_return:
00743   case tok::kw_short:
00744   case tok::kw_signed:
00745   case tok::kw_sizeof:
00746   case tok::kw_static:
00747   case tok::kw_static_cast:
00748   case tok::kw_struct:
00749   case tok::kw_switch:
00750   case tok::kw_template:
00751   case tok::kw_this:
00752   case tok::kw_throw:
00753   case tok::kw_true:
00754   case tok::kw_try:
00755   case tok::kw_typedef:
00756   case tok::kw_typeid:
00757   case tok::kw_typename:
00758   case tok::kw_typeof:
00759   case tok::kw_union:
00760   case tok::kw_unsigned:
00761   case tok::kw_using:
00762   case tok::kw_virtual:
00763   case tok::kw_void:
00764   case tok::kw_volatile:
00765   case tok::kw_wchar_t:
00766   case tok::kw_while:
00767   case tok::kw__Bool:
00768   case tok::kw__Complex:
00769   case tok::kw___alignof:
00770     IdentifierInfo *II = Tok.getIdentifierInfo();
00771     SelectorLoc = ConsumeToken();
00772     return II;
00773   }
00774 }
00775 
00776 ///  objc-for-collection-in: 'in'
00777 ///
00778 bool Parser::isTokIdentifier_in() const {
00779   // FIXME: May have to do additional look-ahead to only allow for
00780   // valid tokens following an 'in'; such as an identifier, unary operators,
00781   // '[' etc.
00782   return (getLangOpts().ObjC2 && Tok.is(tok::identifier) &&
00783           Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]);
00784 }
00785 
00786 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
00787 /// qualifier list and builds their bitmask representation in the input
00788 /// argument.
00789 ///
00790 ///   objc-type-qualifiers:
00791 ///     objc-type-qualifier
00792 ///     objc-type-qualifiers objc-type-qualifier
00793 ///
00794 void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
00795                                         Declarator::TheContext Context) {
00796   assert(Context == Declarator::ObjCParameterContext ||
00797          Context == Declarator::ObjCResultContext);
00798 
00799   while (1) {
00800     if (Tok.is(tok::code_completion)) {
00801       Actions.CodeCompleteObjCPassingType(getCurScope(), DS, 
00802                           Context == Declarator::ObjCParameterContext);
00803       return cutOffParsing();
00804     }
00805     
00806     if (Tok.isNot(tok::identifier))
00807       return;
00808 
00809     const IdentifierInfo *II = Tok.getIdentifierInfo();
00810     for (unsigned i = 0; i != objc_NumQuals; ++i) {
00811       if (II != ObjCTypeQuals[i])
00812         continue;
00813 
00814       ObjCDeclSpec::ObjCDeclQualifier Qual;
00815       switch (i) {
00816       default: llvm_unreachable("Unknown decl qualifier");
00817       case objc_in:     Qual = ObjCDeclSpec::DQ_In; break;
00818       case objc_out:    Qual = ObjCDeclSpec::DQ_Out; break;
00819       case objc_inout:  Qual = ObjCDeclSpec::DQ_Inout; break;
00820       case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break;
00821       case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break;
00822       case objc_byref:  Qual = ObjCDeclSpec::DQ_Byref; break;
00823       }
00824       DS.setObjCDeclQualifier(Qual);
00825       ConsumeToken();
00826       II = 0;
00827       break;
00828     }
00829 
00830     // If this wasn't a recognized qualifier, bail out.
00831     if (II) return;
00832   }
00833 }
00834 
00835 /// Take all the decl attributes out of the given list and add
00836 /// them to the given attribute set.
00837 static void takeDeclAttributes(ParsedAttributes &attrs,
00838                                AttributeList *list) {
00839   while (list) {
00840     AttributeList *cur = list;
00841     list = cur->getNext();
00842 
00843     if (!cur->isUsedAsTypeAttr()) {
00844       // Clear out the next pointer.  We're really completely
00845       // destroying the internal invariants of the declarator here,
00846       // but it doesn't matter because we're done with it.
00847       cur->setNext(0);
00848       attrs.add(cur);
00849     }
00850   }
00851 }
00852 
00853 /// takeDeclAttributes - Take all the decl attributes from the given
00854 /// declarator and add them to the given list.
00855 static void takeDeclAttributes(ParsedAttributes &attrs,
00856                                Declarator &D) {
00857   // First, take ownership of all attributes.
00858   attrs.getPool().takeAllFrom(D.getAttributePool());
00859   attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool());
00860 
00861   // Now actually move the attributes over.
00862   takeDeclAttributes(attrs, D.getDeclSpec().getAttributes().getList());
00863   takeDeclAttributes(attrs, D.getAttributes());
00864   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
00865     takeDeclAttributes(attrs,
00866                   const_cast<AttributeList*>(D.getTypeObject(i).getAttrs()));
00867 }
00868 
00869 ///   objc-type-name:
00870 ///     '(' objc-type-qualifiers[opt] type-name ')'
00871 ///     '(' objc-type-qualifiers[opt] ')'
00872 ///
00873 ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS, 
00874                                      Declarator::TheContext context,
00875                                      ParsedAttributes *paramAttrs) {
00876   assert(context == Declarator::ObjCParameterContext ||
00877          context == Declarator::ObjCResultContext);
00878   assert((paramAttrs != 0) == (context == Declarator::ObjCParameterContext));
00879 
00880   assert(Tok.is(tok::l_paren) && "expected (");
00881 
00882   BalancedDelimiterTracker T(*this, tok::l_paren);
00883   T.consumeOpen();
00884 
00885   SourceLocation TypeStartLoc = Tok.getLocation();
00886   ObjCDeclContextSwitch ObjCDC(*this);
00887 
00888   // Parse type qualifiers, in, inout, etc.
00889   ParseObjCTypeQualifierList(DS, context);
00890 
00891   ParsedType Ty;
00892   if (isTypeSpecifierQualifier()) {
00893     // Parse an abstract declarator.
00894     DeclSpec declSpec(AttrFactory);
00895     declSpec.setObjCQualifiers(&DS);
00896     ParseSpecifierQualifierList(declSpec);
00897     declSpec.SetRangeEnd(Tok.getLocation().getLocWithOffset(-1));
00898     Declarator declarator(declSpec, context);
00899     ParseDeclarator(declarator);
00900 
00901     // If that's not invalid, extract a type.
00902     if (!declarator.isInvalidType()) {
00903       TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator);
00904       if (!type.isInvalid())
00905         Ty = type.get();
00906 
00907       // If we're parsing a parameter, steal all the decl attributes
00908       // and add them to the decl spec.
00909       if (context == Declarator::ObjCParameterContext)
00910         takeDeclAttributes(*paramAttrs, declarator);
00911     }
00912   } else if (context == Declarator::ObjCResultContext &&
00913              Tok.is(tok::identifier)) {
00914     if (!Ident_instancetype)
00915       Ident_instancetype = PP.getIdentifierInfo("instancetype");
00916     
00917     if (Tok.getIdentifierInfo() == Ident_instancetype) {
00918       Ty = Actions.ActOnObjCInstanceType(Tok.getLocation());
00919       ConsumeToken();
00920     }
00921   }
00922 
00923   if (Tok.is(tok::r_paren))
00924     T.consumeClose();
00925   else if (Tok.getLocation() == TypeStartLoc) {
00926     // If we didn't eat any tokens, then this isn't a type.
00927     Diag(Tok, diag::err_expected_type);
00928     SkipUntil(tok::r_paren);
00929   } else {
00930     // Otherwise, we found *something*, but didn't get a ')' in the right
00931     // place.  Emit an error then return what we have as the type.
00932     T.consumeClose();
00933   }
00934   return Ty;
00935 }
00936 
00937 ///   objc-method-decl:
00938 ///     objc-selector
00939 ///     objc-keyword-selector objc-parmlist[opt]
00940 ///     objc-type-name objc-selector
00941 ///     objc-type-name objc-keyword-selector objc-parmlist[opt]
00942 ///
00943 ///   objc-keyword-selector:
00944 ///     objc-keyword-decl
00945 ///     objc-keyword-selector objc-keyword-decl
00946 ///
00947 ///   objc-keyword-decl:
00948 ///     objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
00949 ///     objc-selector ':' objc-keyword-attributes[opt] identifier
00950 ///     ':' objc-type-name objc-keyword-attributes[opt] identifier
00951 ///     ':' objc-keyword-attributes[opt] identifier
00952 ///
00953 ///   objc-parmlist:
00954 ///     objc-parms objc-ellipsis[opt]
00955 ///
00956 ///   objc-parms:
00957 ///     objc-parms , parameter-declaration
00958 ///
00959 ///   objc-ellipsis:
00960 ///     , ...
00961 ///
00962 ///   objc-keyword-attributes:         [OBJC2]
00963 ///     __attribute__((unused))
00964 ///
00965 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
00966                                   tok::TokenKind mType,
00967                                   tok::ObjCKeywordKind MethodImplKind,
00968                                   bool MethodDefinition) {
00969   ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
00970 
00971   if (Tok.is(tok::code_completion)) {
00972     Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus, 
00973                                        /*ReturnType=*/ ParsedType());
00974     cutOffParsing();
00975     return 0;
00976   }
00977 
00978   // Parse the return type if present.
00979   ParsedType ReturnType;
00980   ObjCDeclSpec DSRet;
00981   if (Tok.is(tok::l_paren))
00982     ReturnType = ParseObjCTypeName(DSRet, Declarator::ObjCResultContext, 0);
00983 
00984   // If attributes exist before the method, parse them.
00985   ParsedAttributes methodAttrs(AttrFactory);
00986   if (getLangOpts().ObjC2)
00987     MaybeParseGNUAttributes(methodAttrs);
00988 
00989   if (Tok.is(tok::code_completion)) {
00990     Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus, 
00991                                        ReturnType);
00992     cutOffParsing();
00993     return 0;
00994   }
00995 
00996   // Now parse the selector.
00997   SourceLocation selLoc;
00998   IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc);
00999 
01000   // An unnamed colon is valid.
01001   if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name.
01002     Diag(Tok, diag::err_expected_selector_for_method)
01003       << SourceRange(mLoc, Tok.getLocation());
01004     // Skip until we get a ; or {}.
01005     SkipUntil(tok::r_brace);
01006     return 0;
01007   }
01008 
01009   SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
01010   if (Tok.isNot(tok::colon)) {
01011     // If attributes exist after the method, parse them.
01012     if (getLangOpts().ObjC2)
01013       MaybeParseGNUAttributes(methodAttrs);
01014 
01015     Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
01016     Decl *Result
01017          = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
01018                                           mType, DSRet, ReturnType, 
01019                                           selLoc, Sel, 0, 
01020                                           CParamInfo.data(), CParamInfo.size(),
01021                                           methodAttrs.getList(), MethodImplKind,
01022                                           false, MethodDefinition);
01023     PD.complete(Result);
01024     return Result;
01025   }
01026 
01027   SmallVector<IdentifierInfo *, 12> KeyIdents;
01028   SmallVector<SourceLocation, 12> KeyLocs;
01029   SmallVector<Sema::ObjCArgInfo, 12> ArgInfos;
01030   ParseScope PrototypeScope(this,
01031                             Scope::FunctionPrototypeScope|Scope::DeclScope);
01032 
01033   AttributePool allParamAttrs(AttrFactory);
01034   
01035   while (1) {
01036     ParsedAttributes paramAttrs(AttrFactory);
01037     Sema::ObjCArgInfo ArgInfo;
01038 
01039     // Each iteration parses a single keyword argument.
01040     if (Tok.isNot(tok::colon)) {
01041       Diag(Tok, diag::err_expected_colon);
01042       break;
01043     }
01044     ConsumeToken(); // Eat the ':'.
01045 
01046     ArgInfo.Type = ParsedType();
01047     if (Tok.is(tok::l_paren)) // Parse the argument type if present.
01048       ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec,
01049                                        Declarator::ObjCParameterContext,
01050                                        &paramAttrs);
01051 
01052     // If attributes exist before the argument name, parse them.
01053     // Regardless, collect all the attributes we've parsed so far.
01054     ArgInfo.ArgAttrs = 0;
01055     if (getLangOpts().ObjC2) {
01056       MaybeParseGNUAttributes(paramAttrs);
01057       ArgInfo.ArgAttrs = paramAttrs.getList();
01058     }
01059 
01060     // Code completion for the next piece of the selector.
01061     if (Tok.is(tok::code_completion)) {
01062       KeyIdents.push_back(SelIdent);
01063       Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(), 
01064                                                  mType == tok::minus,
01065                                                  /*AtParameterName=*/true,
01066                                                  ReturnType,
01067                                                  KeyIdents.data(), 
01068                                                  KeyIdents.size());
01069       cutOffParsing();
01070       return 0;
01071     }
01072     
01073     if (Tok.isNot(tok::identifier)) {
01074       Diag(Tok, diag::err_expected_ident); // missing argument name.
01075       break;
01076     }
01077 
01078     ArgInfo.Name = Tok.getIdentifierInfo();
01079     ArgInfo.NameLoc = Tok.getLocation();
01080     ConsumeToken(); // Eat the identifier.
01081 
01082     ArgInfos.push_back(ArgInfo);
01083     KeyIdents.push_back(SelIdent);
01084     KeyLocs.push_back(selLoc);
01085 
01086     // Make sure the attributes persist.
01087     allParamAttrs.takeAllFrom(paramAttrs.getPool());
01088 
01089     // Code completion for the next piece of the selector.
01090     if (Tok.is(tok::code_completion)) {
01091       Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(), 
01092                                                  mType == tok::minus,
01093                                                  /*AtParameterName=*/false,
01094                                                  ReturnType,
01095                                                  KeyIdents.data(), 
01096                                                  KeyIdents.size());
01097       cutOffParsing();
01098       return 0;
01099     }
01100     
01101     // Check for another keyword selector.
01102     SelIdent = ParseObjCSelectorPiece(selLoc);
01103     if (!SelIdent && Tok.isNot(tok::colon))
01104       break;
01105     // We have a selector or a colon, continue parsing.
01106   }
01107 
01108   bool isVariadic = false;
01109 
01110   // Parse the (optional) parameter list.
01111   while (Tok.is(tok::comma)) {
01112     ConsumeToken();
01113     if (Tok.is(tok::ellipsis)) {
01114       isVariadic = true;
01115       ConsumeToken();
01116       break;
01117     }
01118     DeclSpec DS(AttrFactory);
01119     ParseDeclarationSpecifiers(DS);
01120     // Parse the declarator.
01121     Declarator ParmDecl(DS, Declarator::PrototypeContext);
01122     ParseDeclarator(ParmDecl);
01123     IdentifierInfo *ParmII = ParmDecl.getIdentifier();
01124     Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
01125     CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
01126                                                     ParmDecl.getIdentifierLoc(), 
01127                                                     Param,
01128                                                    0));
01129 
01130   }
01131 
01132   // FIXME: Add support for optional parameter list...
01133   // If attributes exist after the method, parse them.
01134   if (getLangOpts().ObjC2)
01135     MaybeParseGNUAttributes(methodAttrs);
01136   
01137   if (KeyIdents.size() == 0)
01138     return 0;
01139   
01140   Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
01141                                                    &KeyIdents[0]);
01142   Decl *Result
01143        = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
01144                                         mType, DSRet, ReturnType, 
01145                                         KeyLocs, Sel, &ArgInfos[0], 
01146                                         CParamInfo.data(), CParamInfo.size(),
01147                                         methodAttrs.getList(),
01148                                         MethodImplKind, isVariadic, MethodDefinition);
01149   
01150   PD.complete(Result);
01151   return Result;
01152 }
01153 
01154 ///   objc-protocol-refs:
01155 ///     '<' identifier-list '>'
01156 ///
01157 bool Parser::
01158 ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols,
01159                             SmallVectorImpl<SourceLocation> &ProtocolLocs,
01160                             bool WarnOnDeclarations,
01161                             SourceLocation &LAngleLoc, SourceLocation &EndLoc) {
01162   assert(Tok.is(tok::less) && "expected <");
01163 
01164   LAngleLoc = ConsumeToken(); // the "<"
01165 
01166   SmallVector<IdentifierLocPair, 8> ProtocolIdents;
01167 
01168   while (1) {
01169     if (Tok.is(tok::code_completion)) {
01170       Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents.data(), 
01171                                                  ProtocolIdents.size());
01172       cutOffParsing();
01173       return true;
01174     }
01175 
01176     if (Tok.isNot(tok::identifier)) {
01177       Diag(Tok, diag::err_expected_ident);
01178       SkipUntil(tok::greater);
01179       return true;
01180     }
01181     ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
01182                                        Tok.getLocation()));
01183     ProtocolLocs.push_back(Tok.getLocation());
01184     ConsumeToken();
01185 
01186     if (Tok.isNot(tok::comma))
01187       break;
01188     ConsumeToken();
01189   }
01190 
01191   // Consume the '>'.
01192   if (Tok.isNot(tok::greater)) {
01193     Diag(Tok, diag::err_expected_greater);
01194     return true;
01195   }
01196 
01197   EndLoc = ConsumeToken();
01198 
01199   // Convert the list of protocols identifiers into a list of protocol decls.
01200   Actions.FindProtocolDeclaration(WarnOnDeclarations,
01201                                   &ProtocolIdents[0], ProtocolIdents.size(),
01202                                   Protocols);
01203   return false;
01204 }
01205 
01206 /// \brief Parse the Objective-C protocol qualifiers that follow a typename
01207 /// in a decl-specifier-seq, starting at the '<'.
01208 bool Parser::ParseObjCProtocolQualifiers(DeclSpec &DS) {
01209   assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
01210   assert(getLangOpts().ObjC1 && "Protocol qualifiers only exist in Objective-C");
01211   SourceLocation LAngleLoc, EndProtoLoc;
01212   SmallVector<Decl *, 8> ProtocolDecl;
01213   SmallVector<SourceLocation, 8> ProtocolLocs;
01214   bool Result = ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
01215                                             LAngleLoc, EndProtoLoc);
01216   DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
01217                            ProtocolLocs.data(), LAngleLoc);
01218   if (EndProtoLoc.isValid())
01219     DS.SetRangeEnd(EndProtoLoc);
01220   return Result;
01221 }
01222 
01223 
01224 ///   objc-class-instance-variables:
01225 ///     '{' objc-instance-variable-decl-list[opt] '}'
01226 ///
01227 ///   objc-instance-variable-decl-list:
01228 ///     objc-visibility-spec
01229 ///     objc-instance-variable-decl ';'
01230 ///     ';'
01231 ///     objc-instance-variable-decl-list objc-visibility-spec
01232 ///     objc-instance-variable-decl-list objc-instance-variable-decl ';'
01233 ///     objc-instance-variable-decl-list ';'
01234 ///
01235 ///   objc-visibility-spec:
01236 ///     @private
01237 ///     @protected
01238 ///     @public
01239 ///     @package [OBJC2]
01240 ///
01241 ///   objc-instance-variable-decl:
01242 ///     struct-declaration
01243 ///
01244 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl,
01245                                              tok::ObjCKeywordKind visibility,
01246                                              SourceLocation atLoc) {
01247   assert(Tok.is(tok::l_brace) && "expected {");
01248   SmallVector<Decl *, 32> AllIvarDecls;
01249     
01250   ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope);
01251   ObjCDeclContextSwitch ObjCDC(*this);
01252 
01253   BalancedDelimiterTracker T(*this, tok::l_brace);
01254   T.consumeOpen();
01255 
01256   // While we still have something to read, read the instance variables.
01257   while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
01258     // Each iteration of this loop reads one objc-instance-variable-decl.
01259 
01260     // Check for extraneous top-level semicolon.
01261     if (Tok.is(tok::semi)) {
01262       ConsumeExtraSemi(InstanceVariableList);
01263       continue;
01264     }
01265 
01266     // Set the default visibility to private.
01267     if (Tok.is(tok::at)) { // parse objc-visibility-spec
01268       ConsumeToken(); // eat the @ sign
01269       
01270       if (Tok.is(tok::code_completion)) {
01271         Actions.CodeCompleteObjCAtVisibility(getCurScope());
01272         return cutOffParsing();
01273       }
01274       
01275       switch (Tok.getObjCKeywordID()) {
01276       case tok::objc_private:
01277       case tok::objc_public:
01278       case tok::objc_protected:
01279       case tok::objc_package:
01280         visibility = Tok.getObjCKeywordID();
01281         ConsumeToken();
01282         continue;
01283       default:
01284         Diag(Tok, diag::err_objc_illegal_visibility_spec);
01285         continue;
01286       }
01287     }
01288 
01289     if (Tok.is(tok::code_completion)) {
01290       Actions.CodeCompleteOrdinaryName(getCurScope(), 
01291                                        Sema::PCC_ObjCInstanceVariableList);
01292       return cutOffParsing();
01293     }
01294     
01295     struct ObjCIvarCallback : FieldCallback {
01296       Parser &P;
01297       Decl *IDecl;
01298       tok::ObjCKeywordKind visibility;
01299       SmallVectorImpl<Decl *> &AllIvarDecls;
01300 
01301       ObjCIvarCallback(Parser &P, Decl *IDecl, tok::ObjCKeywordKind V,
01302                        SmallVectorImpl<Decl *> &AllIvarDecls) :
01303         P(P), IDecl(IDecl), visibility(V), AllIvarDecls(AllIvarDecls) {
01304       }
01305 
01306       Decl *invoke(FieldDeclarator &FD) {
01307         P.Actions.ActOnObjCContainerStartDefinition(IDecl);
01308         // Install the declarator into the interface decl.
01309         Decl *Field
01310           = P.Actions.ActOnIvar(P.getCurScope(),
01311                                 FD.D.getDeclSpec().getSourceRange().getBegin(),
01312                                 FD.D, FD.BitfieldSize, visibility);
01313         P.Actions.ActOnObjCContainerFinishDefinition();
01314         if (Field)
01315           AllIvarDecls.push_back(Field);
01316         return Field;
01317       }
01318     } Callback(*this, interfaceDecl, visibility, AllIvarDecls);
01319     
01320     // Parse all the comma separated declarators.
01321     DeclSpec DS(AttrFactory);
01322     ParseStructDeclaration(DS, Callback);
01323 
01324     if (Tok.is(tok::semi)) {
01325       ConsumeToken();
01326     } else {
01327       Diag(Tok, diag::err_expected_semi_decl_list);
01328       // Skip to end of block or statement
01329       SkipUntil(tok::r_brace, true, true);
01330     }
01331   }
01332   T.consumeClose();
01333 
01334   Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
01335   Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls);
01336   Actions.ActOnObjCContainerFinishDefinition();
01337   // Call ActOnFields() even if we don't have any decls. This is useful
01338   // for code rewriting tools that need to be aware of the empty list.
01339   Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl,
01340                       AllIvarDecls,
01341                       T.getOpenLocation(), T.getCloseLocation(), 0);
01342   return;
01343 }
01344 
01345 ///   objc-protocol-declaration:
01346 ///     objc-protocol-definition
01347 ///     objc-protocol-forward-reference
01348 ///
01349 ///   objc-protocol-definition:
01350 ///     @protocol identifier
01351 ///       objc-protocol-refs[opt]
01352 ///       objc-interface-decl-list
01353 ///     @end
01354 ///
01355 ///   objc-protocol-forward-reference:
01356 ///     @protocol identifier-list ';'
01357 ///
01358 ///   "@protocol identifier ;" should be resolved as "@protocol
01359 ///   identifier-list ;": objc-interface-decl-list may not start with a
01360 ///   semicolon in the first alternative if objc-protocol-refs are omitted.
01361 Parser::DeclGroupPtrTy 
01362 Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
01363                                        ParsedAttributes &attrs) {
01364   assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
01365          "ParseObjCAtProtocolDeclaration(): Expected @protocol");
01366   ConsumeToken(); // the "protocol" identifier
01367 
01368   if (Tok.is(tok::code_completion)) {
01369     Actions.CodeCompleteObjCProtocolDecl(getCurScope());
01370     cutOffParsing();
01371     return DeclGroupPtrTy();
01372   }
01373 
01374   if (Tok.isNot(tok::identifier)) {
01375     Diag(Tok, diag::err_expected_ident); // missing protocol name.
01376     return DeclGroupPtrTy();
01377   }
01378   // Save the protocol name, then consume it.
01379   IdentifierInfo *protocolName = Tok.getIdentifierInfo();
01380   SourceLocation nameLoc = ConsumeToken();
01381 
01382   if (Tok.is(tok::semi)) { // forward declaration of one protocol.
01383     IdentifierLocPair ProtoInfo(protocolName, nameLoc);
01384     ConsumeToken();
01385     return Actions.ActOnForwardProtocolDeclaration(AtLoc, &ProtoInfo, 1,
01386                                                    attrs.getList());
01387   }
01388 
01389   CheckNestedObjCContexts(AtLoc);
01390 
01391   if (Tok.is(tok::comma)) { // list of forward declarations.
01392     SmallVector<IdentifierLocPair, 8> ProtocolRefs;
01393     ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
01394 
01395     // Parse the list of forward declarations.
01396     while (1) {
01397       ConsumeToken(); // the ','
01398       if (Tok.isNot(tok::identifier)) {
01399         Diag(Tok, diag::err_expected_ident);
01400         SkipUntil(tok::semi);
01401         return DeclGroupPtrTy();
01402       }
01403       ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
01404                                                Tok.getLocation()));
01405       ConsumeToken(); // the identifier
01406 
01407       if (Tok.isNot(tok::comma))
01408         break;
01409     }
01410     // Consume the ';'.
01411     if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@protocol"))
01412       return DeclGroupPtrTy();
01413 
01414     return Actions.ActOnForwardProtocolDeclaration(AtLoc,
01415                                                    &ProtocolRefs[0],
01416                                                    ProtocolRefs.size(),
01417                                                    attrs.getList());
01418   }
01419 
01420   // Last, and definitely not least, parse a protocol declaration.
01421   SourceLocation LAngleLoc, EndProtoLoc;
01422 
01423   SmallVector<Decl *, 8> ProtocolRefs;
01424   SmallVector<SourceLocation, 8> ProtocolLocs;
01425   if (Tok.is(tok::less) &&
01426       ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false,
01427                                   LAngleLoc, EndProtoLoc))
01428     return DeclGroupPtrTy();
01429 
01430   Decl *ProtoType =
01431     Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc,
01432                                         ProtocolRefs.data(),
01433                                         ProtocolRefs.size(),
01434                                         ProtocolLocs.data(),
01435                                         EndProtoLoc, attrs.getList());
01436 
01437   ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType);
01438   return Actions.ConvertDeclToDeclGroup(ProtoType);
01439 }
01440 
01441 ///   objc-implementation:
01442 ///     objc-class-implementation-prologue
01443 ///     objc-category-implementation-prologue
01444 ///
01445 ///   objc-class-implementation-prologue:
01446 ///     @implementation identifier objc-superclass[opt]
01447 ///       objc-class-instance-variables[opt]
01448 ///
01449 ///   objc-category-implementation-prologue:
01450 ///     @implementation identifier ( identifier )
01451 Parser::DeclGroupPtrTy
01452 Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) {
01453   assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
01454          "ParseObjCAtImplementationDeclaration(): Expected @implementation");
01455   CheckNestedObjCContexts(AtLoc);
01456   ConsumeToken(); // the "implementation" identifier
01457 
01458   // Code completion after '@implementation'.
01459   if (Tok.is(tok::code_completion)) {
01460     Actions.CodeCompleteObjCImplementationDecl(getCurScope());
01461     cutOffParsing();
01462     return DeclGroupPtrTy();
01463   }
01464 
01465   if (Tok.isNot(tok::identifier)) {
01466     Diag(Tok, diag::err_expected_ident); // missing class or category name.
01467     return DeclGroupPtrTy();
01468   }
01469   // We have a class or category name - consume it.
01470   IdentifierInfo *nameId = Tok.getIdentifierInfo();
01471   SourceLocation nameLoc = ConsumeToken(); // consume class or category name
01472   Decl *ObjCImpDecl = 0;
01473 
01474   if (Tok.is(tok::l_paren)) {
01475     // we have a category implementation.
01476     ConsumeParen();
01477     SourceLocation categoryLoc, rparenLoc;
01478     IdentifierInfo *categoryId = 0;
01479 
01480     if (Tok.is(tok::code_completion)) {
01481       Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
01482       cutOffParsing();
01483       return DeclGroupPtrTy();
01484     }
01485     
01486     if (Tok.is(tok::identifier)) {
01487       categoryId = Tok.getIdentifierInfo();
01488       categoryLoc = ConsumeToken();
01489     } else {
01490       Diag(Tok, diag::err_expected_ident); // missing category name.
01491       return DeclGroupPtrTy();
01492     }
01493     if (Tok.isNot(tok::r_paren)) {
01494       Diag(Tok, diag::err_expected_rparen);
01495       SkipUntil(tok::r_paren, false); // don't stop at ';'
01496       return DeclGroupPtrTy();
01497     }
01498     rparenLoc = ConsumeParen();
01499     ObjCImpDecl = Actions.ActOnStartCategoryImplementation(
01500                                     AtLoc, nameId, nameLoc, categoryId,
01501                                     categoryLoc);
01502 
01503   } else {
01504     // We have a class implementation
01505     SourceLocation superClassLoc;
01506     IdentifierInfo *superClassId = 0;
01507     if (Tok.is(tok::colon)) {
01508       // We have a super class
01509       ConsumeToken();
01510       if (Tok.isNot(tok::identifier)) {
01511         Diag(Tok, diag::err_expected_ident); // missing super class name.
01512         return DeclGroupPtrTy();
01513       }
01514       superClassId = Tok.getIdentifierInfo();
01515       superClassLoc = ConsumeToken(); // Consume super class name
01516     }
01517     ObjCImpDecl = Actions.ActOnStartClassImplementation(
01518                                     AtLoc, nameId, nameLoc,
01519                                     superClassId, superClassLoc);
01520   
01521     if (Tok.is(tok::l_brace)) // we have ivars
01522       ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc);
01523   }
01524   assert(ObjCImpDecl);
01525 
01526   SmallVector<Decl *, 8> DeclsInGroup;
01527 
01528   {
01529     ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl);
01530     while (!ObjCImplParsing.isFinished() && Tok.isNot(tok::eof)) {
01531       ParsedAttributesWithRange attrs(AttrFactory);
01532       MaybeParseCXX0XAttributes(attrs);
01533       MaybeParseMicrosoftAttributes(attrs);
01534       if (DeclGroupPtrTy DGP = ParseExternalDeclaration(attrs)) {
01535         DeclGroupRef DG = DGP.get();
01536         DeclsInGroup.append(DG.begin(), DG.end());
01537       }
01538     }
01539   }
01540 
01541   return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup);
01542 }
01543 
01544 Parser::DeclGroupPtrTy
01545 Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
01546   assert(Tok.isObjCAtKeyword(tok::objc_end) &&
01547          "ParseObjCAtEndDeclaration(): Expected @end");
01548   ConsumeToken(); // the "end" identifier
01549   if (CurParsedObjCImpl)
01550     CurParsedObjCImpl->finish(atEnd);
01551   else
01552     // missing @implementation
01553     Diag(atEnd.getBegin(), diag::err_expected_objc_container);
01554   return DeclGroupPtrTy();
01555 }
01556 
01557 Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() {
01558   if (!Finished) {
01559     finish(P.Tok.getLocation());
01560     if (P.Tok.is(tok::eof)) {
01561       P.Diag(P.Tok, diag::err_objc_missing_end)
01562           << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n");
01563       P.Diag(Dcl->getLocStart(), diag::note_objc_container_start)
01564           << Sema::OCK_Implementation;
01565     }
01566   }
01567   P.CurParsedObjCImpl = 0;
01568   assert(LateParsedObjCMethods.empty());
01569 }
01570 
01571 void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) {
01572   assert(!Finished);
01573   P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl);
01574   for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
01575     P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i]);
01576 
01577   P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd);
01578 
01579   /// \brief Clear and free the cached objc methods.
01580   for (LateParsedObjCMethodContainer::iterator
01581          I = LateParsedObjCMethods.begin(),
01582          E = LateParsedObjCMethods.end(); I != E; ++I)
01583     delete *I;
01584   LateParsedObjCMethods.clear();
01585 
01586   Finished = true;
01587 }
01588 
01589 ///   compatibility-alias-decl:
01590 ///     @compatibility_alias alias-name  class-name ';'
01591 ///
01592 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
01593   assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
01594          "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
01595   ConsumeToken(); // consume compatibility_alias
01596   if (Tok.isNot(tok::identifier)) {
01597     Diag(Tok, diag::err_expected_ident);
01598     return 0;
01599   }
01600   IdentifierInfo *aliasId = Tok.getIdentifierInfo();
01601   SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
01602   if (Tok.isNot(tok::identifier)) {
01603     Diag(Tok, diag::err_expected_ident);
01604     return 0;
01605   }
01606   IdentifierInfo *classId = Tok.getIdentifierInfo();
01607   SourceLocation classLoc = ConsumeToken(); // consume class-name;
01608   ExpectAndConsume(tok::semi, diag::err_expected_semi_after, 
01609                    "@compatibility_alias");
01610   return Actions.ActOnCompatiblityAlias(atLoc, aliasId, aliasLoc,
01611                                         classId, classLoc);
01612 }
01613 
01614 ///   property-synthesis:
01615 ///     @synthesize property-ivar-list ';'
01616 ///
01617 ///   property-ivar-list:
01618 ///     property-ivar
01619 ///     property-ivar-list ',' property-ivar
01620 ///
01621 ///   property-ivar:
01622 ///     identifier
01623 ///     identifier '=' identifier
01624 ///
01625 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
01626   assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
01627          "ParseObjCPropertyDynamic(): Expected '@synthesize'");
01628   ConsumeToken(); // consume synthesize
01629 
01630   while (true) {
01631     if (Tok.is(tok::code_completion)) {
01632       Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
01633       cutOffParsing();
01634       return 0;
01635     }
01636     
01637     if (Tok.isNot(tok::identifier)) {
01638       Diag(Tok, diag::err_synthesized_property_name);
01639       SkipUntil(tok::semi);
01640       return 0;
01641     }
01642     
01643     IdentifierInfo *propertyIvar = 0;
01644     IdentifierInfo *propertyId = Tok.getIdentifierInfo();
01645     SourceLocation propertyLoc = ConsumeToken(); // consume property name
01646     SourceLocation propertyIvarLoc;
01647     if (Tok.is(tok::equal)) {
01648       // property '=' ivar-name
01649       ConsumeToken(); // consume '='
01650       
01651       if (Tok.is(tok::code_completion)) {
01652         Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId);
01653         cutOffParsing();
01654         return 0;
01655       }
01656       
01657       if (Tok.isNot(tok::identifier)) {
01658         Diag(Tok, diag::err_expected_ident);
01659         break;
01660       }
01661       propertyIvar = Tok.getIdentifierInfo();
01662       propertyIvarLoc = ConsumeToken(); // consume ivar-name
01663     }
01664     Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, true,
01665                                   propertyId, propertyIvar, propertyIvarLoc);
01666     if (Tok.isNot(tok::comma))
01667       break;
01668     ConsumeToken(); // consume ','
01669   }
01670   ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@synthesize");
01671   return 0;
01672 }
01673 
01674 ///   property-dynamic:
01675 ///     @dynamic  property-list
01676 ///
01677 ///   property-list:
01678 ///     identifier
01679 ///     property-list ',' identifier
01680 ///
01681 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
01682   assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
01683          "ParseObjCPropertyDynamic(): Expected '@dynamic'");
01684   ConsumeToken(); // consume dynamic
01685   while (true) {
01686     if (Tok.is(tok::code_completion)) {
01687       Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
01688       cutOffParsing();
01689       return 0;
01690     }
01691     
01692     if (Tok.isNot(tok::identifier)) {
01693       Diag(Tok, diag::err_expected_ident);
01694       SkipUntil(tok::semi);
01695       return 0;
01696     }
01697     
01698     IdentifierInfo *propertyId = Tok.getIdentifierInfo();
01699     SourceLocation propertyLoc = ConsumeToken(); // consume property name
01700     Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, false,
01701                                   propertyId, 0, SourceLocation());
01702 
01703     if (Tok.isNot(tok::comma))
01704       break;
01705     ConsumeToken(); // consume ','
01706   }
01707   ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@dynamic");
01708   return 0;
01709 }
01710 
01711 ///  objc-throw-statement:
01712 ///    throw expression[opt];
01713 ///
01714 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
01715   ExprResult Res;
01716   ConsumeToken(); // consume throw
01717   if (Tok.isNot(tok::semi)) {
01718     Res = ParseExpression();
01719     if (Res.isInvalid()) {
01720       SkipUntil(tok::semi);
01721       return StmtError();
01722     }
01723   }
01724   // consume ';'
01725   ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@throw");
01726   return Actions.ActOnObjCAtThrowStmt(atLoc, Res.take(), getCurScope());
01727 }
01728 
01729 /// objc-synchronized-statement:
01730 ///   @synchronized '(' expression ')' compound-statement
01731 ///
01732 StmtResult
01733 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
01734   ConsumeToken(); // consume synchronized
01735   if (Tok.isNot(tok::l_paren)) {
01736     Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
01737     return StmtError();
01738   }
01739 
01740   // The operand is surrounded with parentheses.
01741   ConsumeParen();  // '('
01742   ExprResult operand(ParseExpression());
01743 
01744   if (Tok.is(tok::r_paren)) {
01745     ConsumeParen();  // ')'
01746   } else {
01747     if (!operand.isInvalid())
01748       Diag(Tok, diag::err_expected_rparen);
01749 
01750     // Skip forward until we see a left brace, but don't consume it.
01751     SkipUntil(tok::l_brace, true, true);
01752   }
01753 
01754   // Require a compound statement.
01755   if (Tok.isNot(tok::l_brace)) {
01756     if (!operand.isInvalid())
01757       Diag(Tok, diag::err_expected_lbrace);
01758     return StmtError();
01759   }
01760 
01761   // Check the @synchronized operand now.
01762   if (!operand.isInvalid())
01763     operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.take());
01764 
01765   // Parse the compound statement within a new scope.
01766   ParseScope bodyScope(this, Scope::DeclScope);
01767   StmtResult body(ParseCompoundStatementBody());
01768   bodyScope.Exit();
01769 
01770   // If there was a semantic or parse error earlier with the
01771   // operand, fail now.
01772   if (operand.isInvalid())
01773     return StmtError();
01774 
01775   if (body.isInvalid())
01776     body = Actions.ActOnNullStmt(Tok.getLocation());
01777 
01778   return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get());
01779 }
01780 
01781 ///  objc-try-catch-statement:
01782 ///    @try compound-statement objc-catch-list[opt]
01783 ///    @try compound-statement objc-catch-list[opt] @finally compound-statement
01784 ///
01785 ///  objc-catch-list:
01786 ///    @catch ( parameter-declaration ) compound-statement
01787 ///    objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
01788 ///  catch-parameter-declaration:
01789 ///     parameter-declaration
01790 ///     '...' [OBJC2]
01791 ///
01792 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
01793   bool catch_or_finally_seen = false;
01794 
01795   ConsumeToken(); // consume try
01796   if (Tok.isNot(tok::l_brace)) {
01797     Diag(Tok, diag::err_expected_lbrace);
01798     return StmtError();
01799   }
01800   StmtVector CatchStmts(Actions);
01801   StmtResult FinallyStmt;
01802   ParseScope TryScope(this, Scope::DeclScope);
01803   StmtResult TryBody(ParseCompoundStatementBody());
01804   TryScope.Exit();
01805   if (TryBody.isInvalid())
01806     TryBody = Actions.ActOnNullStmt(Tok.getLocation());
01807 
01808   while (Tok.is(tok::at)) {
01809     // At this point, we need to lookahead to determine if this @ is the start
01810     // of an @catch or @finally.  We don't want to consume the @ token if this
01811     // is an @try or @encode or something else.
01812     Token AfterAt = GetLookAheadToken(1);
01813     if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
01814         !AfterAt.isObjCAtKeyword(tok::objc_finally))
01815       break;
01816 
01817     SourceLocation AtCatchFinallyLoc = ConsumeToken();
01818     if (Tok.isObjCAtKeyword(tok::objc_catch)) {
01819       Decl *FirstPart = 0;
01820       ConsumeToken(); // consume catch
01821       if (Tok.is(tok::l_paren)) {
01822         ConsumeParen();
01823         ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope);
01824         if (Tok.isNot(tok::ellipsis)) {
01825           DeclSpec DS(AttrFactory);
01826           ParseDeclarationSpecifiers(DS);
01827           Declarator ParmDecl(DS, Declarator::ObjCCatchContext);
01828           ParseDeclarator(ParmDecl);
01829 
01830           // Inform the actions module about the declarator, so it
01831           // gets added to the current scope.
01832           FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
01833         } else
01834           ConsumeToken(); // consume '...'
01835 
01836         SourceLocation RParenLoc;
01837 
01838         if (Tok.is(tok::r_paren))
01839           RParenLoc = ConsumeParen();
01840         else // Skip over garbage, until we get to ')'.  Eat the ')'.
01841           SkipUntil(tok::r_paren, true, false);
01842 
01843         StmtResult CatchBody(true);
01844         if (Tok.is(tok::l_brace))
01845           CatchBody = ParseCompoundStatementBody();
01846         else
01847           Diag(Tok, diag::err_expected_lbrace);
01848         if (CatchBody.isInvalid())
01849           CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
01850         
01851         StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
01852                                                               RParenLoc, 
01853                                                               FirstPart, 
01854                                                               CatchBody.take());
01855         if (!Catch.isInvalid())
01856           CatchStmts.push_back(Catch.release());
01857         
01858       } else {
01859         Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
01860           << "@catch clause";
01861         return StmtError();
01862       }
01863       catch_or_finally_seen = true;
01864     } else {
01865       assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
01866       ConsumeToken(); // consume finally
01867       ParseScope FinallyScope(this, Scope::DeclScope);
01868 
01869       StmtResult FinallyBody(true);
01870       if (Tok.is(tok::l_brace))
01871         FinallyBody = ParseCompoundStatementBody();
01872       else
01873         Diag(Tok, diag::err_expected_lbrace);
01874       if (FinallyBody.isInvalid())
01875         FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
01876       FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
01877                                                    FinallyBody.take());
01878       catch_or_finally_seen = true;
01879       break;
01880     }
01881   }
01882   if (!catch_or_finally_seen) {
01883     Diag(atLoc, diag::err_missing_catch_finally);
01884     return StmtError();
01885   }
01886   
01887   return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.take(), 
01888                                     move_arg(CatchStmts),
01889                                     FinallyStmt.take());
01890 }
01891 
01892 /// objc-autoreleasepool-statement:
01893 ///   @autoreleasepool compound-statement
01894 ///
01895 StmtResult
01896 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
01897   ConsumeToken(); // consume autoreleasepool
01898   if (Tok.isNot(tok::l_brace)) {
01899     Diag(Tok, diag::err_expected_lbrace);
01900     return StmtError();
01901   }
01902   // Enter a scope to hold everything within the compound stmt.  Compound
01903   // statements can always hold declarations.
01904   ParseScope BodyScope(this, Scope::DeclScope);
01905 
01906   StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
01907 
01908   BodyScope.Exit();
01909   if (AutoreleasePoolBody.isInvalid())
01910     AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
01911   return Actions.ActOnObjCAutoreleasePoolStmt(atLoc, 
01912                                                 AutoreleasePoolBody.take());
01913 }
01914 
01915 ///   objc-method-def: objc-method-proto ';'[opt] '{' body '}'
01916 ///
01917 Decl *Parser::ParseObjCMethodDefinition() {
01918   Decl *MDecl = ParseObjCMethodPrototype();
01919 
01920   PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(),
01921                                       "parsing Objective-C method");
01922 
01923   // parse optional ';'
01924   if (Tok.is(tok::semi)) {
01925     if (CurParsedObjCImpl) {
01926       Diag(Tok, diag::warn_semicolon_before_method_body)
01927         << FixItHint::CreateRemoval(Tok.getLocation());
01928     }
01929     ConsumeToken();
01930   }
01931 
01932   // We should have an opening brace now.
01933   if (Tok.isNot(tok::l_brace)) {
01934     Diag(Tok, diag::err_expected_method_body);
01935 
01936     // Skip over garbage, until we get to '{'.  Don't eat the '{'.
01937     SkipUntil(tok::l_brace, true, true);
01938 
01939     // If we didn't find the '{', bail out.
01940     if (Tok.isNot(tok::l_brace))
01941       return 0;
01942   }
01943 
01944   if (!MDecl) {
01945     ConsumeBrace();
01946     SkipUntil(tok::r_brace, /*StopAtSemi=*/false);
01947     return 0;
01948   }
01949 
01950   // Allow the rest of sema to find private method decl implementations.
01951   Actions.AddAnyMethodToGlobalPool(MDecl);
01952 
01953   if (CurParsedObjCImpl) {
01954     // Consume the tokens and store them for later parsing.
01955     LexedMethod* LM = new LexedMethod(this, MDecl);
01956     CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM);
01957     CachedTokens &Toks = LM->Toks;
01958     // Begin by storing the '{' token.
01959     Toks.push_back(Tok);
01960     ConsumeBrace();
01961     // Consume everything up to (and including) the matching right brace.
01962     ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
01963 
01964   } else {
01965     ConsumeBrace();
01966     SkipUntil(tok::r_brace, /*StopAtSemi=*/false);
01967   }
01968 
01969   return MDecl;
01970 }
01971 
01972 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
01973   if (Tok.is(tok::code_completion)) {
01974     Actions.CodeCompleteObjCAtStatement(getCurScope());
01975     cutOffParsing();
01976     return StmtError();
01977   }
01978   
01979   if (Tok.isObjCAtKeyword(tok::objc_try))
01980     return ParseObjCTryStmt(AtLoc);
01981   
01982   if (Tok.isObjCAtKeyword(tok::objc_throw))
01983     return ParseObjCThrowStmt(AtLoc);
01984   
01985   if (Tok.isObjCAtKeyword(tok::objc_synchronized))
01986     return ParseObjCSynchronizedStmt(AtLoc);
01987 
01988   if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
01989     return ParseObjCAutoreleasePoolStmt(AtLoc);
01990   
01991   ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
01992   if (Res.isInvalid()) {
01993     // If the expression is invalid, skip ahead to the next semicolon. Not
01994     // doing this opens us up to the possibility of infinite loops if
01995     // ParseExpression does not consume any tokens.
01996     SkipUntil(tok::semi);
01997     return StmtError();
01998   }
01999   
02000   // Otherwise, eat the semicolon.
02001   ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
02002   return Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.take()));
02003 }
02004 
02005 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
02006   switch (Tok.getKind()) {
02007   case tok::code_completion:
02008     Actions.CodeCompleteObjCAtExpression(getCurScope());
02009     cutOffParsing();
02010     return ExprError();
02011 
02012   case tok::minus:
02013   case tok::plus: {
02014     tok::TokenKind Kind = Tok.getKind();
02015     SourceLocation OpLoc = ConsumeToken();
02016 
02017     if (!Tok.is(tok::numeric_constant)) {
02018       const char *Symbol = 0;
02019       switch (Kind) {
02020       case tok::minus: Symbol = "-"; break;
02021       case tok::plus: Symbol = "+"; break;
02022       default: llvm_unreachable("missing unary operator case");
02023       }
02024       Diag(Tok, diag::err_nsnumber_nonliteral_unary)
02025         << Symbol;
02026       return ExprError();
02027     }
02028 
02029     ExprResult Lit(Actions.ActOnNumericConstant(Tok));
02030     if (Lit.isInvalid()) {
02031       return move(Lit);
02032     }
02033     ConsumeToken(); // Consume the literal token.
02034 
02035     Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.take());
02036     if (Lit.isInvalid())
02037       return move(Lit);
02038 
02039     return ParsePostfixExpressionSuffix(
02040              Actions.BuildObjCNumericLiteral(AtLoc, Lit.take()));
02041   }
02042 
02043   case tok::string_literal:    // primary-expression: string-literal
02044   case tok::wide_string_literal:
02045     return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
02046 
02047   case tok::char_constant:
02048     return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc));
02049       
02050   case tok::numeric_constant:
02051     return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc));
02052 
02053   case tok::kw_true:  // Objective-C++, etc.
02054   case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes
02055     return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true));
02056   case tok::kw_false: // Objective-C++, etc.
02057   case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no
02058     return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false));
02059     
02060   case tok::l_square:
02061     // Objective-C array literal
02062     return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc));
02063           
02064   case tok::l_brace:
02065     // Objective-C dictionary literal
02066     return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc));
02067           
02068   case tok::l_paren:
02069     // Objective-C boxed expression
02070     return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc));
02071           
02072   default:
02073     if (Tok.getIdentifierInfo() == 0)
02074       return ExprError(Diag(AtLoc, diag::err_unexpected_at));
02075 
02076     switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
02077     case tok::objc_encode:
02078       return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
02079     case tok::objc_protocol:
02080       return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
02081     case tok::objc_selector:
02082       return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
02083     default:
02084       return ExprError(Diag(AtLoc, diag::err_unexpected_at));
02085     }
02086   }
02087 }
02088 
02089 /// \brirg Parse the receiver of an Objective-C++ message send.
02090 ///
02091 /// This routine parses the receiver of a message send in
02092 /// Objective-C++ either as a type or as an expression. Note that this
02093 /// routine must not be called to parse a send to 'super', since it
02094 /// has no way to return such a result.
02095 /// 
02096 /// \param IsExpr Whether the receiver was parsed as an expression.
02097 ///
02098 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
02099 /// IsExpr is true), the parsed expression. If the receiver was parsed
02100 /// as a type (\c IsExpr is false), the parsed type.
02101 ///
02102 /// \returns True if an error occurred during parsing or semantic
02103 /// analysis, in which case the arguments do not have valid
02104 /// values. Otherwise, returns false for a successful parse.
02105 ///
02106 ///   objc-receiver: [C++]
02107 ///     'super' [not parsed here]
02108 ///     expression
02109 ///     simple-type-specifier
02110 ///     typename-specifier
02111 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
02112   InMessageExpressionRAIIObject InMessage(*this, true);
02113 
02114   if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || 
02115       Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope))
02116     TryAnnotateTypeOrScopeToken();
02117 
02118   if (!isCXXSimpleTypeSpecifier()) {
02119     //   objc-receiver:
02120     //     expression
02121     ExprResult Receiver = ParseExpression();
02122     if (Receiver.isInvalid())
02123       return true;
02124 
02125     IsExpr = true;
02126     TypeOrExpr = Receiver.take();
02127     return false;
02128   }
02129 
02130   // objc-receiver:
02131   //   typename-specifier
02132   //   simple-type-specifier
02133   //   expression (that starts with one of the above)
02134   DeclSpec DS(AttrFactory);
02135   ParseCXXSimpleTypeSpecifier(DS);
02136   
02137   if (Tok.is(tok::l_paren)) {
02138     // If we see an opening parentheses at this point, we are
02139     // actually parsing an expression that starts with a
02140     // function-style cast, e.g.,
02141     //
02142     //   postfix-expression:
02143     //     simple-type-specifier ( expression-list [opt] )
02144     //     typename-specifier ( expression-list [opt] )
02145     //
02146     // Parse the remainder of this case, then the (optional)
02147     // postfix-expression suffix, followed by the (optional)
02148     // right-hand side of the binary expression. We have an
02149     // instance method.
02150     ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
02151     if (!Receiver.isInvalid())
02152       Receiver = ParsePostfixExpressionSuffix(Receiver.take());
02153     if (!Receiver.isInvalid())
02154       Receiver = ParseRHSOfBinaryExpression(Receiver.take(), prec::Comma);
02155     if (Receiver.isInvalid())
02156       return true;
02157 
02158     IsExpr = true;
02159     TypeOrExpr = Receiver.take();
02160     return false;
02161   }
02162   
02163   // We have a class message. Turn the simple-type-specifier or
02164   // typename-specifier we parsed into a type and parse the
02165   // remainder of the class message.
02166   Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
02167   TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
02168   if (Type.isInvalid())
02169     return true;
02170 
02171   IsExpr = false;
02172   TypeOrExpr = Type.get().getAsOpaquePtr();
02173   return false;
02174 }
02175 
02176 /// \brief Determine whether the parser is currently referring to a an
02177 /// Objective-C message send, using a simplified heuristic to avoid overhead.
02178 ///
02179 /// This routine will only return true for a subset of valid message-send
02180 /// expressions.
02181 bool Parser::isSimpleObjCMessageExpression() {
02182   assert(Tok.is(tok::l_square) && getLangOpts().ObjC1 &&
02183          "Incorrect start for isSimpleObjCMessageExpression");
02184   return GetLookAheadToken(1).is(tok::identifier) &&
02185          GetLookAheadToken(2).is(tok::identifier);
02186 }
02187 
02188 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
02189   if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) || 
02190       InMessageExpression)
02191     return false;
02192   
02193   
02194   ParsedType Type;
02195 
02196   if (Tok.is(tok::annot_typename)) 
02197     Type = getTypeAnnotation(Tok);
02198   else if (Tok.is(tok::identifier))
02199     Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(), 
02200                                getCurScope());
02201   else
02202     return false;
02203   
02204   if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
02205     const Token &AfterNext = GetLookAheadToken(2);
02206     if (AfterNext.is(tok::colon) || AfterNext.is(tok::r_square)) {
02207       if (Tok.is(tok::identifier))
02208         TryAnnotateTypeOrScopeToken();
02209       
02210       return Tok.is(tok::annot_typename);
02211     }
02212   }
02213 
02214   return false;
02215 }
02216 
02217 ///   objc-message-expr:
02218 ///     '[' objc-receiver objc-message-args ']'
02219 ///
02220 ///   objc-receiver: [C]
02221 ///     'super'
02222 ///     expression
02223 ///     class-name
02224 ///     type-name
02225 ///
02226 ExprResult Parser::ParseObjCMessageExpression() {
02227   assert(Tok.is(tok::l_square) && "'[' expected");
02228   SourceLocation LBracLoc = ConsumeBracket(); // consume '['
02229 
02230   if (Tok.is(tok::code_completion)) {
02231     Actions.CodeCompleteObjCMessageReceiver(getCurScope());
02232     cutOffParsing();
02233     return ExprError();
02234   }
02235   
02236   InMessageExpressionRAIIObject InMessage(*this, true);
02237   
02238   if (getLangOpts().CPlusPlus) {
02239     // We completely separate the C and C++ cases because C++ requires
02240     // more complicated (read: slower) parsing. 
02241     
02242     // Handle send to super.  
02243     // FIXME: This doesn't benefit from the same typo-correction we
02244     // get in Objective-C.
02245     if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
02246         NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
02247       return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
02248                                             ParsedType(), 0);
02249 
02250     // Parse the receiver, which is either a type or an expression.
02251     bool IsExpr;
02252     void *TypeOrExpr = NULL;
02253     if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
02254       SkipUntil(tok::r_square);
02255       return ExprError();
02256     }
02257 
02258     if (IsExpr)
02259       return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
02260                                             ParsedType(),
02261                                             static_cast<Expr*>(TypeOrExpr));
02262 
02263     return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), 
02264                               ParsedType::getFromOpaquePtr(TypeOrExpr),
02265                                           0);
02266   }
02267   
02268   if (Tok.is(tok::identifier)) {
02269     IdentifierInfo *Name = Tok.getIdentifierInfo();
02270     SourceLocation NameLoc = Tok.getLocation();
02271     ParsedType ReceiverType;
02272     switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
02273                                        Name == Ident_super,
02274                                        NextToken().is(tok::period),
02275                                        ReceiverType)) {
02276     case Sema::ObjCSuperMessage:
02277       return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
02278                                             ParsedType(), 0);
02279 
02280     case Sema::ObjCClassMessage:
02281       if (!ReceiverType) {
02282         SkipUntil(tok::r_square);
02283         return ExprError();
02284       }
02285 
02286       ConsumeToken(); // the type name
02287 
02288       return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), 
02289                                             ReceiverType, 0);
02290         
02291     case Sema::ObjCInstanceMessage:
02292       // Fall through to parse an expression.
02293       break;
02294     }
02295   }
02296   
02297   // Otherwise, an arbitrary expression can be the receiver of a send.
02298   ExprResult Res(ParseExpression());
02299   if (Res.isInvalid()) {
02300     SkipUntil(tok::r_square);
02301     return move(Res);
02302   }
02303 
02304   return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
02305                                         ParsedType(), Res.take());
02306 }
02307 
02308 /// \brief Parse the remainder of an Objective-C message following the
02309 /// '[' objc-receiver.
02310 ///
02311 /// This routine handles sends to super, class messages (sent to a
02312 /// class name), and instance messages (sent to an object), and the
02313 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
02314 /// ReceiverExpr, respectively. Only one of these parameters may have
02315 /// a valid value.
02316 ///
02317 /// \param LBracLoc The location of the opening '['.
02318 ///
02319 /// \param SuperLoc If this is a send to 'super', the location of the
02320 /// 'super' keyword that indicates a send to the superclass.
02321 ///
02322 /// \param ReceiverType If this is a class message, the type of the
02323 /// class we are sending a message to.
02324 ///
02325 /// \param ReceiverExpr If this is an instance message, the expression
02326 /// used to compute the receiver object.
02327 ///
02328 ///   objc-message-args:
02329 ///     objc-selector
02330 ///     objc-keywordarg-list
02331 ///
02332 ///   objc-keywordarg-list:
02333 ///     objc-keywordarg
02334 ///     objc-keywordarg-list objc-keywordarg
02335 ///
02336 ///   objc-keywordarg:
02337 ///     selector-name[opt] ':' objc-keywordexpr
02338 ///
02339 ///   objc-keywordexpr:
02340 ///     nonempty-expr-list
02341 ///
02342 ///   nonempty-expr-list:
02343 ///     assignment-expression
02344 ///     nonempty-expr-list , assignment-expression
02345 ///
02346 ExprResult
02347 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
02348                                        SourceLocation SuperLoc,
02349                                        ParsedType ReceiverType,
02350                                        ExprArg ReceiverExpr) {
02351   InMessageExpressionRAIIObject InMessage(*this, true);
02352 
02353   if (Tok.is(tok::code_completion)) {
02354     if (SuperLoc.isValid())
02355       Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 0, 0,
02356                                            false);
02357     else if (ReceiverType)
02358       Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, 0, 0,
02359                                            false);
02360     else
02361       Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
02362                                               0, 0, false);
02363     cutOffParsing();
02364     return ExprError();
02365   }
02366   
02367   // Parse objc-selector
02368   SourceLocation Loc;
02369   IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
02370 
02371   SmallVector<IdentifierInfo *, 12> KeyIdents;
02372   SmallVector<SourceLocation, 12> KeyLocs;
02373   ExprVector KeyExprs(Actions);
02374 
02375   if (Tok.is(tok::colon)) {
02376     while (1) {
02377       // Each iteration parses a single keyword argument.
02378       KeyIdents.push_back(selIdent);
02379       KeyLocs.push_back(Loc);
02380 
02381       if (Tok.isNot(tok::colon)) {
02382         Diag(Tok, diag::err_expected_colon);
02383         // We must manually skip to a ']', otherwise the expression skipper will
02384         // stop at the ']' when it skips to the ';'.  We want it to skip beyond
02385         // the enclosing expression.
02386         SkipUntil(tok::r_square);
02387         return ExprError();
02388       }
02389 
02390       ConsumeToken(); // Eat the ':'.
02391       ///  Parse the expression after ':'
02392       
02393       if (Tok.is(tok::code_completion)) {
02394         if (SuperLoc.isValid())
02395           Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 
02396                                                KeyIdents.data(), 
02397                                                KeyIdents.size(),
02398                                                /*AtArgumentEpression=*/true);
02399         else if (ReceiverType)
02400           Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
02401                                                KeyIdents.data(), 
02402                                                KeyIdents.size(),
02403                                                /*AtArgumentEpression=*/true);
02404         else
02405           Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
02406                                                   KeyIdents.data(), 
02407                                                   KeyIdents.size(),
02408                                                   /*AtArgumentEpression=*/true);
02409 
02410         cutOffParsing();
02411         return ExprError();
02412       }
02413       
02414       ExprResult Res(ParseAssignmentExpression());
02415       if (Res.isInvalid()) {
02416         // We must manually skip to a ']', otherwise the expression skipper will
02417         // stop at the ']' when it skips to the ';'.  We want it to skip beyond
02418         // the enclosing expression.
02419         SkipUntil(tok::r_square);
02420         return move(Res);
02421       }
02422 
02423       // We have a valid expression.
02424       KeyExprs.push_back(Res.release());
02425 
02426       // Code completion after each argument.
02427       if (Tok.is(tok::code_completion)) {
02428         if (SuperLoc.isValid())
02429           Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 
02430                                                KeyIdents.data(), 
02431                                                KeyIdents.size(),
02432                                                /*AtArgumentEpression=*/false);
02433         else if (ReceiverType)
02434           Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
02435                                                KeyIdents.data(), 
02436                                                KeyIdents.size(),
02437                                                /*AtArgumentEpression=*/false);
02438         else
02439           Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
02440                                                   KeyIdents.data(), 
02441                                                   KeyIdents.size(),
02442                                                 /*AtArgumentEpression=*/false);
02443         cutOffParsing();
02444         return ExprError();
02445       }
02446             
02447       // Check for another keyword selector.
02448       selIdent = ParseObjCSelectorPiece(Loc);
02449       if (!selIdent && Tok.isNot(tok::colon))
02450         break;
02451       // We have a selector or a colon, continue parsing.
02452     }
02453     // Parse the, optional, argument list, comma separated.
02454     while (Tok.is(tok::comma)) {
02455       SourceLocation commaLoc = ConsumeToken(); // Eat the ','.
02456       ///  Parse the expression after ','
02457       ExprResult Res(ParseAssignmentExpression());
02458       if (Res.isInvalid()) {
02459         if (Tok.is(tok::colon)) {
02460           Diag(commaLoc, diag::note_extra_comma_message_arg) <<
02461             FixItHint::CreateRemoval(commaLoc);
02462         }
02463         // We must manually skip to a ']', otherwise the expression skipper will
02464         // stop at the ']' when it skips to the ';'.  We want it to skip beyond
02465         // the enclosing expression.
02466         SkipUntil(tok::r_square);
02467         return move(Res);
02468       }
02469 
02470       // We have a valid expression.
02471       KeyExprs.push_back(Res.release());
02472     }
02473   } else if (!selIdent) {
02474     Diag(Tok, diag::err_expected_ident); // missing selector name.
02475 
02476     // We must manually skip to a ']', otherwise the expression skipper will
02477     // stop at the ']' when it skips to the ';'.  We want it to skip beyond
02478     // the enclosing expression.
02479     SkipUntil(tok::r_square);
02480     return ExprError();
02481   }
02482     
02483   if (Tok.isNot(tok::r_square)) {
02484     if (Tok.is(tok::identifier))
02485       Diag(Tok, diag::err_expected_colon);
02486     else
02487       Diag(Tok, diag::err_expected_rsquare);
02488     // We must manually skip to a ']', otherwise the expression skipper will
02489     // stop at the ']' when it skips to the ';'.  We want it to skip beyond
02490     // the enclosing expression.
02491     SkipUntil(tok::r_square);
02492     return ExprError();
02493   }
02494 
02495   SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
02496 
02497   unsigned nKeys = KeyIdents.size();
02498   if (nKeys == 0) {
02499     KeyIdents.push_back(selIdent);
02500     KeyLocs.push_back(Loc);
02501   }
02502   Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
02503 
02504   if (SuperLoc.isValid())
02505     return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
02506                                      LBracLoc, KeyLocs, RBracLoc,
02507                                      MultiExprArg(Actions, 
02508                                                   KeyExprs.take(),
02509                                                   KeyExprs.size()));
02510   else if (ReceiverType)
02511     return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
02512                                      LBracLoc, KeyLocs, RBracLoc,
02513                                      MultiExprArg(Actions, 
02514                                                   KeyExprs.take(), 
02515                                                   KeyExprs.size()));
02516   return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
02517                                       LBracLoc, KeyLocs, RBracLoc,
02518                                       MultiExprArg(Actions, 
02519                                                    KeyExprs.take(), 
02520                                                    KeyExprs.size()));
02521 }
02522 
02523 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
02524   ExprResult Res(ParseStringLiteralExpression());
02525   if (Res.isInvalid()) return move(Res);
02526 
02527   // @"foo" @"bar" is a valid concatenated string.  Eat any subsequent string
02528   // expressions.  At this point, we know that the only valid thing that starts
02529   // with '@' is an @"".
02530   SmallVector<SourceLocation, 4> AtLocs;
02531   ExprVector AtStrings(Actions);
02532   AtLocs.push_back(AtLoc);
02533   AtStrings.push_back(Res.release());
02534 
02535   while (Tok.is(tok::at)) {
02536     AtLocs.push_back(ConsumeToken()); // eat the @.
02537 
02538     // Invalid unless there is a string literal.
02539     if (!isTokenStringLiteral())
02540       return ExprError(Diag(Tok, diag::err_objc_concat_string));
02541 
02542     ExprResult Lit(ParseStringLiteralExpression());
02543     if (Lit.isInvalid())
02544       return move(Lit);
02545 
02546     AtStrings.push_back(Lit.release());
02547   }
02548 
02549   return Owned(Actions.ParseObjCStringLiteral(&AtLocs[0], AtStrings.take(),
02550                                               AtStrings.size()));
02551 }
02552 
02553 /// ParseObjCBooleanLiteral -
02554 /// objc-scalar-literal : '@' boolean-keyword
02555 ///                        ;
02556 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
02557 ///                        ;
02558 ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc, 
02559                                            bool ArgValue) {
02560   SourceLocation EndLoc = ConsumeToken();             // consume the keyword.
02561   return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue);
02562 }
02563 
02564 /// ParseObjCCharacterLiteral -
02565 /// objc-scalar-literal : '@' character-literal
02566 ///                        ;
02567 ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) {
02568   ExprResult Lit(Actions.ActOnCharacterConstant(Tok));
02569   if (Lit.isInvalid()) {
02570     return move(Lit);
02571   }
02572   ConsumeToken(); // Consume the literal token.
02573   return Owned(Actions.BuildObjCNumericLiteral(AtLoc, Lit.take()));
02574 }
02575 
02576 /// ParseObjCNumericLiteral -
02577 /// objc-scalar-literal : '@' scalar-literal
02578 ///                        ;
02579 /// scalar-literal : | numeric-constant     /* any numeric constant. */
02580 ///                    ;
02581 ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) {
02582   ExprResult Lit(Actions.ActOnNumericConstant(Tok));
02583   if (Lit.isInvalid()) {
02584     return move(Lit);
02585   }
02586   ConsumeToken(); // Consume the literal token.
02587   return Owned(Actions.BuildObjCNumericLiteral(AtLoc, Lit.take()));
02588 }
02589 
02590 /// ParseObjCBoxedExpr -
02591 /// objc-box-expression:
02592 ///       @( assignment-expression )
02593 ExprResult
02594 Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) {
02595   if (Tok.isNot(tok::l_paren))
02596     return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@");
02597 
02598   BalancedDelimiterTracker T(*this, tok::l_paren);
02599   T.consumeOpen();
02600   ExprResult ValueExpr(ParseAssignmentExpression());
02601   if (T.consumeClose())
02602     return ExprError();
02603 
02604   if (ValueExpr.isInvalid())
02605     return ExprError();
02606 
02607   // Wrap the sub-expression in a parenthesized expression, to distinguish
02608   // a boxed expression from a literal.
02609   SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation();
02610   ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.take());
02611   return Owned(Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc),
02612                                           ValueExpr.take()));
02613 }
02614 
02615 ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) {
02616   ExprVector ElementExprs(Actions);                   // array elements.
02617   ConsumeBracket(); // consume the l_square.
02618 
02619   while (Tok.isNot(tok::r_square)) {
02620     // Parse list of array element expressions (all must be id types).
02621     ExprResult Res(ParseAssignmentExpression());
02622     if (Res.isInvalid()) {
02623       // We must manually skip to a ']', otherwise the expression skipper will
02624       // stop at the ']' when it skips to the ';'.  We want it to skip beyond
02625       // the enclosing expression.
02626       SkipUntil(tok::r_square);
02627       return move(Res);
02628     }    
02629     
02630     // Parse the ellipsis that indicates a pack expansion.
02631     if (Tok.is(tok::ellipsis))
02632       Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken());    
02633     if (Res.isInvalid())
02634       return true;
02635 
02636     ElementExprs.push_back(Res.release());
02637 
02638     if (Tok.is(tok::comma))
02639       ConsumeToken(); // Eat the ','.
02640     else if (Tok.isNot(tok::r_square))
02641      return ExprError(Diag(Tok, diag::err_expected_rsquare_or_comma));
02642   }
02643   SourceLocation EndLoc = ConsumeBracket(); // location of ']'
02644   MultiExprArg Args(Actions, ElementExprs.take(), ElementExprs.size());
02645   return Owned(Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args));
02646 }
02647 
02648 ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) {
02649   SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements.
02650   ConsumeBrace(); // consume the l_square.
02651   while (Tok.isNot(tok::r_brace)) {
02652     // Parse the comma separated key : value expressions.
02653     ExprResult KeyExpr;
02654     {
02655       ColonProtectionRAIIObject X(*this);
02656       KeyExpr = ParseAssignmentExpression();
02657       if (KeyExpr.isInvalid()) {
02658         // We must manually skip to a '}', otherwise the expression skipper will
02659         // stop at the '}' when it skips to the ';'.  We want it to skip beyond
02660         // the enclosing expression.
02661         SkipUntil(tok::r_brace);
02662         return move(KeyExpr);
02663       }
02664     }
02665 
02666     if (Tok.is(tok::colon)) {
02667       ConsumeToken();
02668     } else {
02669       return ExprError(Diag(Tok, diag::err_expected_colon));
02670     }
02671     
02672     ExprResult ValueExpr(ParseAssignmentExpression());
02673     if (ValueExpr.isInvalid()) {
02674       // We must manually skip to a '}', otherwise the expression skipper will
02675       // stop at the '}' when it skips to the ';'.  We want it to skip beyond
02676       // the enclosing expression.
02677       SkipUntil(tok::r_brace);
02678       return move(ValueExpr);
02679     }
02680     
02681     // Parse the ellipsis that designates this as a pack expansion.
02682     SourceLocation EllipsisLoc;
02683     if (Tok.is(tok::ellipsis) && getLangOpts().CPlusPlus)
02684       EllipsisLoc = ConsumeToken();
02685     
02686     // We have a valid expression. Collect it in a vector so we can
02687     // build the argument list.
02688     ObjCDictionaryElement Element = { 
02689       KeyExpr.get(), ValueExpr.get(), EllipsisLoc, llvm::Optional<unsigned>()
02690     };
02691     Elements.push_back(Element);
02692     
02693     if (Tok.is(tok::comma))
02694       ConsumeToken(); // Eat the ','.
02695     else if (Tok.isNot(tok::r_brace))
02696       return ExprError(Diag(Tok, diag::err_expected_rbrace_or_comma));
02697   }
02698   SourceLocation EndLoc = ConsumeBrace();
02699   
02700   // Create the ObjCDictionaryLiteral.
02701   return Owned(Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc),
02702                                                   Elements.data(),
02703                                                   Elements.size()));
02704 }
02705 
02706 ///    objc-encode-expression:
02707 ///      @encode ( type-name )
02708 ExprResult
02709 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
02710   assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
02711 
02712   SourceLocation EncLoc = ConsumeToken();
02713 
02714   if (Tok.isNot(tok::l_paren))
02715     return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
02716 
02717   BalancedDelimiterTracker T(*this, tok::l_paren);
02718   T.consumeOpen();
02719 
02720   TypeResult Ty = ParseTypeName();
02721 
02722   T.consumeClose();
02723 
02724   if (Ty.isInvalid())
02725     return ExprError();
02726 
02727   return Owned(Actions.ParseObjCEncodeExpression(AtLoc, EncLoc,
02728                                                  T.getOpenLocation(), Ty.get(),
02729                                                  T.getCloseLocation()));
02730 }
02731 
02732 ///     objc-protocol-expression
02733 ///       @protocol ( protocol-name )
02734 ExprResult
02735 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
02736   SourceLocation ProtoLoc = ConsumeToken();
02737 
02738   if (Tok.isNot(tok::l_paren))
02739     return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
02740 
02741   BalancedDelimiterTracker T(*this, tok::l_paren);
02742   T.consumeOpen();
02743 
02744   if (Tok.isNot(tok::identifier))
02745     return ExprError(Diag(Tok, diag::err_expected_ident));
02746 
02747   IdentifierInfo *protocolId = Tok.getIdentifierInfo();
02748   SourceLocation ProtoIdLoc = ConsumeToken();
02749 
02750   T.consumeClose();
02751 
02752   return Owned(Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
02753                                                    T.getOpenLocation(),
02754                                                    ProtoIdLoc,
02755                                                    T.getCloseLocation()));
02756 }
02757 
02758 ///     objc-selector-expression
02759 ///       @selector '(' objc-keyword-selector ')'
02760 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
02761   SourceLocation SelectorLoc = ConsumeToken();
02762 
02763   if (Tok.isNot(tok::l_paren))
02764     return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
02765 
02766   SmallVector<IdentifierInfo *, 12> KeyIdents;
02767   SourceLocation sLoc;
02768   
02769   BalancedDelimiterTracker T(*this, tok::l_paren);
02770   T.consumeOpen();
02771 
02772   if (Tok.is(tok::code_completion)) {
02773     Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(),
02774                                      KeyIdents.size());
02775     cutOffParsing();
02776     return ExprError();
02777   }
02778   
02779   IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
02780   if (!SelIdent &&  // missing selector name.
02781       Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
02782     return ExprError(Diag(Tok, diag::err_expected_ident));
02783 
02784   KeyIdents.push_back(SelIdent);
02785   unsigned nColons = 0;
02786   if (Tok.isNot(tok::r_paren)) {
02787     while (1) {
02788       if (Tok.is(tok::coloncolon)) { // Handle :: in C++.
02789         ++nColons;
02790         KeyIdents.push_back(0);
02791       } else if (Tok.isNot(tok::colon))
02792         return ExprError(Diag(Tok, diag::err_expected_colon));
02793 
02794       ++nColons;
02795       ConsumeToken(); // Eat the ':' or '::'.
02796       if (Tok.is(tok::r_paren))
02797         break;
02798       
02799       if (Tok.is(tok::code_completion)) {
02800         Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(),
02801                                          KeyIdents.size());
02802         cutOffParsing();
02803         return ExprError();
02804       }
02805 
02806       // Check for another keyword selector.
02807       SourceLocation Loc;
02808       SelIdent = ParseObjCSelectorPiece(Loc);
02809       KeyIdents.push_back(SelIdent);
02810       if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
02811         break;
02812     }
02813   }
02814   T.consumeClose();
02815   Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
02816   return Owned(Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
02817                                                    T.getOpenLocation(),
02818                                                    T.getCloseLocation()));
02819  }
02820 
02821 Decl *Parser::ParseLexedObjCMethodDefs(LexedMethod &LM) {
02822 
02823   // Save the current token position.
02824   SourceLocation OrigLoc = Tok.getLocation();
02825 
02826   assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!");
02827   // Append the current token at the end of the new token stream so that it
02828   // doesn't get lost.
02829   LM.Toks.push_back(Tok);
02830   PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
02831   
02832   // MDecl might be null due to error in method prototype, etc.
02833   Decl *MDecl = LM.D;
02834   // Consume the previously pushed token.
02835   ConsumeAnyToken();
02836     
02837   assert(Tok.is(tok::l_brace) && "Inline objective-c method not starting with '{'");
02838   SourceLocation BraceLoc = Tok.getLocation();
02839   // Enter a scope for the method body.
02840   ParseScope BodyScope(this,
02841                        Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope);
02842     
02843   // Tell the actions module that we have entered a method definition with the
02844   // specified Declarator for the method.
02845   Actions.ActOnStartOfObjCMethodDef(getCurScope(), MDecl);
02846     
02847   if (SkipFunctionBodies && trySkippingFunctionBody()) {
02848     BodyScope.Exit();
02849     return Actions.ActOnFinishFunctionBody(MDecl, 0);
02850   }
02851     
02852   StmtResult FnBody(ParseCompoundStatementBody());
02853     
02854   // If the function body could not be parsed, make a bogus compoundstmt.
02855   if (FnBody.isInvalid()) {
02856     Sema::CompoundScopeRAII CompoundScope(Actions);
02857     FnBody = Actions.ActOnCompoundStmt(BraceLoc, BraceLoc,
02858                                        MultiStmtArg(Actions), false);
02859   }
02860     
02861   // Leave the function body scope.
02862   BodyScope.Exit();
02863     
02864   MDecl = Actions.ActOnFinishFunctionBody(MDecl, FnBody.take());
02865 
02866   if (Tok.getLocation() != OrigLoc) {
02867     // Due to parsing error, we either went over the cached tokens or
02868     // there are still cached tokens left. If it's the latter case skip the
02869     // leftover tokens.
02870     // Since this is an uncommon situation that should be avoided, use the
02871     // expensive isBeforeInTranslationUnit call.
02872     if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
02873                                                      OrigLoc))
02874       while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
02875         ConsumeAnyToken();
02876   }
02877   
02878   return MDecl;
02879 }