ParseObjc.cpp 95 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847
  1. //===--- ParseObjC.cpp - Objective C Parsing ------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the Objective-C portions of the Parser interface.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Parse/ParseDiagnostic.h"
  14. #include "clang/Parse/Parser.h"
  15. #include "RAIIObjectsForParser.h"
  16. #include "clang/Sema/DeclSpec.h"
  17. #include "clang/Sema/PrettyDeclStackTrace.h"
  18. #include "clang/Sema/Scope.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. using namespace clang;
  21. /// ParseObjCAtDirectives - Handle parts of the external-declaration production:
  22. /// external-declaration: [C99 6.9]
  23. /// [OBJC] objc-class-definition
  24. /// [OBJC] objc-class-declaration
  25. /// [OBJC] objc-alias-declaration
  26. /// [OBJC] objc-protocol-definition
  27. /// [OBJC] objc-method-definition
  28. /// [OBJC] '@' 'end'
  29. Parser::DeclGroupPtrTy Parser::ParseObjCAtDirectives() {
  30. SourceLocation AtLoc = ConsumeToken(); // the "@"
  31. if (Tok.is(tok::code_completion)) {
  32. Actions.CodeCompleteObjCAtDirective(getCurScope());
  33. cutOffParsing();
  34. return DeclGroupPtrTy();
  35. }
  36. Decl *SingleDecl = 0;
  37. switch (Tok.getObjCKeywordID()) {
  38. case tok::objc_class:
  39. return ParseObjCAtClassDeclaration(AtLoc);
  40. case tok::objc_interface: {
  41. ParsedAttributes attrs(AttrFactory);
  42. SingleDecl = ParseObjCAtInterfaceDeclaration(AtLoc, attrs);
  43. break;
  44. }
  45. case tok::objc_protocol: {
  46. ParsedAttributes attrs(AttrFactory);
  47. return ParseObjCAtProtocolDeclaration(AtLoc, attrs);
  48. }
  49. case tok::objc_implementation:
  50. return ParseObjCAtImplementationDeclaration(AtLoc);
  51. case tok::objc_end:
  52. return ParseObjCAtEndDeclaration(AtLoc);
  53. case tok::objc_compatibility_alias:
  54. SingleDecl = ParseObjCAtAliasDeclaration(AtLoc);
  55. break;
  56. case tok::objc_synthesize:
  57. SingleDecl = ParseObjCPropertySynthesize(AtLoc);
  58. break;
  59. case tok::objc_dynamic:
  60. SingleDecl = ParseObjCPropertyDynamic(AtLoc);
  61. break;
  62. case tok::objc___experimental_modules_import:
  63. if (getLangOpts().Modules)
  64. return ParseModuleImport(AtLoc);
  65. // Fall through
  66. default:
  67. Diag(AtLoc, diag::err_unexpected_at);
  68. SkipUntil(tok::semi);
  69. SingleDecl = 0;
  70. break;
  71. }
  72. return Actions.ConvertDeclToDeclGroup(SingleDecl);
  73. }
  74. ///
  75. /// objc-class-declaration:
  76. /// '@' 'class' identifier-list ';'
  77. ///
  78. Parser::DeclGroupPtrTy
  79. Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) {
  80. ConsumeToken(); // the identifier "class"
  81. SmallVector<IdentifierInfo *, 8> ClassNames;
  82. SmallVector<SourceLocation, 8> ClassLocs;
  83. while (1) {
  84. if (Tok.isNot(tok::identifier)) {
  85. Diag(Tok, diag::err_expected_ident);
  86. SkipUntil(tok::semi);
  87. return Actions.ConvertDeclToDeclGroup(0);
  88. }
  89. ClassNames.push_back(Tok.getIdentifierInfo());
  90. ClassLocs.push_back(Tok.getLocation());
  91. ConsumeToken();
  92. if (Tok.isNot(tok::comma))
  93. break;
  94. ConsumeToken();
  95. }
  96. // Consume the ';'.
  97. if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@class"))
  98. return Actions.ConvertDeclToDeclGroup(0);
  99. return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(),
  100. ClassLocs.data(),
  101. ClassNames.size());
  102. }
  103. void Parser::CheckNestedObjCContexts(SourceLocation AtLoc)
  104. {
  105. Sema::ObjCContainerKind ock = Actions.getObjCContainerKind();
  106. if (ock == Sema::OCK_None)
  107. return;
  108. Decl *Decl = Actions.getObjCDeclContext();
  109. if (CurParsedObjCImpl) {
  110. CurParsedObjCImpl->finish(AtLoc);
  111. } else {
  112. Actions.ActOnAtEnd(getCurScope(), AtLoc);
  113. }
  114. Diag(AtLoc, diag::err_objc_missing_end)
  115. << FixItHint::CreateInsertion(AtLoc, "@end\n");
  116. if (Decl)
  117. Diag(Decl->getLocStart(), diag::note_objc_container_start)
  118. << (int) ock;
  119. }
  120. ///
  121. /// objc-interface:
  122. /// objc-class-interface-attributes[opt] objc-class-interface
  123. /// objc-category-interface
  124. ///
  125. /// objc-class-interface:
  126. /// '@' 'interface' identifier objc-superclass[opt]
  127. /// objc-protocol-refs[opt]
  128. /// objc-class-instance-variables[opt]
  129. /// objc-interface-decl-list
  130. /// @end
  131. ///
  132. /// objc-category-interface:
  133. /// '@' 'interface' identifier '(' identifier[opt] ')'
  134. /// objc-protocol-refs[opt]
  135. /// objc-interface-decl-list
  136. /// @end
  137. ///
  138. /// objc-superclass:
  139. /// ':' identifier
  140. ///
  141. /// objc-class-interface-attributes:
  142. /// __attribute__((visibility("default")))
  143. /// __attribute__((visibility("hidden")))
  144. /// __attribute__((deprecated))
  145. /// __attribute__((unavailable))
  146. /// __attribute__((objc_exception)) - used by NSException on 64-bit
  147. ///
  148. Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
  149. ParsedAttributes &attrs) {
  150. assert(Tok.isObjCAtKeyword(tok::objc_interface) &&
  151. "ParseObjCAtInterfaceDeclaration(): Expected @interface");
  152. CheckNestedObjCContexts(AtLoc);
  153. ConsumeToken(); // the "interface" identifier
  154. // Code completion after '@interface'.
  155. if (Tok.is(tok::code_completion)) {
  156. Actions.CodeCompleteObjCInterfaceDecl(getCurScope());
  157. cutOffParsing();
  158. return 0;
  159. }
  160. if (Tok.isNot(tok::identifier)) {
  161. Diag(Tok, diag::err_expected_ident); // missing class or category name.
  162. return 0;
  163. }
  164. // We have a class or category name - consume it.
  165. IdentifierInfo *nameId = Tok.getIdentifierInfo();
  166. SourceLocation nameLoc = ConsumeToken();
  167. if (Tok.is(tok::l_paren) &&
  168. !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category.
  169. BalancedDelimiterTracker T(*this, tok::l_paren);
  170. T.consumeOpen();
  171. SourceLocation categoryLoc;
  172. IdentifierInfo *categoryId = 0;
  173. if (Tok.is(tok::code_completion)) {
  174. Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc);
  175. cutOffParsing();
  176. return 0;
  177. }
  178. // For ObjC2, the category name is optional (not an error).
  179. if (Tok.is(tok::identifier)) {
  180. categoryId = Tok.getIdentifierInfo();
  181. categoryLoc = ConsumeToken();
  182. }
  183. else if (!getLangOpts().ObjC2) {
  184. Diag(Tok, diag::err_expected_ident); // missing category name.
  185. return 0;
  186. }
  187. T.consumeClose();
  188. if (T.getCloseLocation().isInvalid())
  189. return 0;
  190. if (!attrs.empty()) { // categories don't support attributes.
  191. Diag(nameLoc, diag::err_objc_no_attributes_on_category);
  192. attrs.clear();
  193. }
  194. // Next, we need to check for any protocol references.
  195. SourceLocation LAngleLoc, EndProtoLoc;
  196. SmallVector<Decl *, 8> ProtocolRefs;
  197. SmallVector<SourceLocation, 8> ProtocolLocs;
  198. if (Tok.is(tok::less) &&
  199. ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true,
  200. LAngleLoc, EndProtoLoc))
  201. return 0;
  202. Decl *CategoryType =
  203. Actions.ActOnStartCategoryInterface(AtLoc,
  204. nameId, nameLoc,
  205. categoryId, categoryLoc,
  206. ProtocolRefs.data(),
  207. ProtocolRefs.size(),
  208. ProtocolLocs.data(),
  209. EndProtoLoc);
  210. if (Tok.is(tok::l_brace))
  211. ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, AtLoc);
  212. ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType);
  213. return CategoryType;
  214. }
  215. // Parse a class interface.
  216. IdentifierInfo *superClassId = 0;
  217. SourceLocation superClassLoc;
  218. if (Tok.is(tok::colon)) { // a super class is specified.
  219. ConsumeToken();
  220. // Code completion of superclass names.
  221. if (Tok.is(tok::code_completion)) {
  222. Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc);
  223. cutOffParsing();
  224. return 0;
  225. }
  226. if (Tok.isNot(tok::identifier)) {
  227. Diag(Tok, diag::err_expected_ident); // missing super class name.
  228. return 0;
  229. }
  230. superClassId = Tok.getIdentifierInfo();
  231. superClassLoc = ConsumeToken();
  232. }
  233. // Next, we need to check for any protocol references.
  234. SmallVector<Decl *, 8> ProtocolRefs;
  235. SmallVector<SourceLocation, 8> ProtocolLocs;
  236. SourceLocation LAngleLoc, EndProtoLoc;
  237. if (Tok.is(tok::less) &&
  238. ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true,
  239. LAngleLoc, EndProtoLoc))
  240. return 0;
  241. Decl *ClsType =
  242. Actions.ActOnStartClassInterface(AtLoc, nameId, nameLoc,
  243. superClassId, superClassLoc,
  244. ProtocolRefs.data(), ProtocolRefs.size(),
  245. ProtocolLocs.data(),
  246. EndProtoLoc, attrs.getList());
  247. if (Tok.is(tok::l_brace))
  248. ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, AtLoc);
  249. ParseObjCInterfaceDeclList(tok::objc_interface, ClsType);
  250. return ClsType;
  251. }
  252. /// The Objective-C property callback. This should be defined where
  253. /// it's used, but instead it's been lifted to here to support VS2005.
  254. struct Parser::ObjCPropertyCallback : FieldCallback {
  255. private:
  256. virtual void anchor();
  257. public:
  258. Parser &P;
  259. SmallVectorImpl<Decl *> &Props;
  260. ObjCDeclSpec &OCDS;
  261. SourceLocation AtLoc;
  262. SourceLocation LParenLoc;
  263. tok::ObjCKeywordKind MethodImplKind;
  264. ObjCPropertyCallback(Parser &P,
  265. SmallVectorImpl<Decl *> &Props,
  266. ObjCDeclSpec &OCDS, SourceLocation AtLoc,
  267. SourceLocation LParenLoc,
  268. tok::ObjCKeywordKind MethodImplKind) :
  269. P(P), Props(Props), OCDS(OCDS), AtLoc(AtLoc), LParenLoc(LParenLoc),
  270. MethodImplKind(MethodImplKind) {
  271. }
  272. Decl *invoke(FieldDeclarator &FD) {
  273. if (FD.D.getIdentifier() == 0) {
  274. P.Diag(AtLoc, diag::err_objc_property_requires_field_name)
  275. << FD.D.getSourceRange();
  276. return 0;
  277. }
  278. if (FD.BitfieldSize) {
  279. P.Diag(AtLoc, diag::err_objc_property_bitfield)
  280. << FD.D.getSourceRange();
  281. return 0;
  282. }
  283. // Install the property declarator into interfaceDecl.
  284. IdentifierInfo *SelName =
  285. OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier();
  286. Selector GetterSel =
  287. P.PP.getSelectorTable().getNullarySelector(SelName);
  288. IdentifierInfo *SetterName = OCDS.getSetterName();
  289. Selector SetterSel;
  290. if (SetterName)
  291. SetterSel = P.PP.getSelectorTable().getSelector(1, &SetterName);
  292. else
  293. SetterSel = SelectorTable::constructSetterName(P.PP.getIdentifierTable(),
  294. P.PP.getSelectorTable(),
  295. FD.D.getIdentifier());
  296. bool isOverridingProperty = false;
  297. Decl *Property =
  298. P.Actions.ActOnProperty(P.getCurScope(), AtLoc, LParenLoc,
  299. FD, OCDS,
  300. GetterSel, SetterSel,
  301. &isOverridingProperty,
  302. MethodImplKind);
  303. if (!isOverridingProperty)
  304. Props.push_back(Property);
  305. return Property;
  306. }
  307. };
  308. void Parser::ObjCPropertyCallback::anchor() {
  309. }
  310. /// objc-interface-decl-list:
  311. /// empty
  312. /// objc-interface-decl-list objc-property-decl [OBJC2]
  313. /// objc-interface-decl-list objc-method-requirement [OBJC2]
  314. /// objc-interface-decl-list objc-method-proto ';'
  315. /// objc-interface-decl-list declaration
  316. /// objc-interface-decl-list ';'
  317. ///
  318. /// objc-method-requirement: [OBJC2]
  319. /// @required
  320. /// @optional
  321. ///
  322. void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
  323. Decl *CDecl) {
  324. SmallVector<Decl *, 32> allMethods;
  325. SmallVector<Decl *, 16> allProperties;
  326. SmallVector<DeclGroupPtrTy, 8> allTUVariables;
  327. tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword;
  328. SourceRange AtEnd;
  329. while (1) {
  330. // If this is a method prototype, parse it.
  331. if (Tok.is(tok::minus) || Tok.is(tok::plus)) {
  332. Decl *methodPrototype =
  333. ParseObjCMethodPrototype(MethodImplKind, false);
  334. allMethods.push_back(methodPrototype);
  335. // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for
  336. // method definitions.
  337. if (ExpectAndConsumeSemi(diag::err_expected_semi_after_method_proto)) {
  338. // We didn't find a semi and we error'ed out. Skip until a ';' or '@'.
  339. SkipUntil(tok::at, /*StopAtSemi=*/true, /*DontConsume=*/true);
  340. if (Tok.is(tok::semi))
  341. ConsumeToken();
  342. }
  343. continue;
  344. }
  345. if (Tok.is(tok::l_paren)) {
  346. Diag(Tok, diag::err_expected_minus_or_plus);
  347. ParseObjCMethodDecl(Tok.getLocation(),
  348. tok::minus,
  349. MethodImplKind, false);
  350. continue;
  351. }
  352. // Ignore excess semicolons.
  353. if (Tok.is(tok::semi)) {
  354. ConsumeToken();
  355. continue;
  356. }
  357. // If we got to the end of the file, exit the loop.
  358. if (Tok.is(tok::eof))
  359. break;
  360. // Code completion within an Objective-C interface.
  361. if (Tok.is(tok::code_completion)) {
  362. Actions.CodeCompleteOrdinaryName(getCurScope(),
  363. CurParsedObjCImpl? Sema::PCC_ObjCImplementation
  364. : Sema::PCC_ObjCInterface);
  365. return cutOffParsing();
  366. }
  367. // If we don't have an @ directive, parse it as a function definition.
  368. if (Tok.isNot(tok::at)) {
  369. // The code below does not consume '}'s because it is afraid of eating the
  370. // end of a namespace. Because of the way this code is structured, an
  371. // erroneous r_brace would cause an infinite loop if not handled here.
  372. if (Tok.is(tok::r_brace))
  373. break;
  374. ParsedAttributes attrs(AttrFactory);
  375. allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(attrs));
  376. continue;
  377. }
  378. // Otherwise, we have an @ directive, eat the @.
  379. SourceLocation AtLoc = ConsumeToken(); // the "@"
  380. if (Tok.is(tok::code_completion)) {
  381. Actions.CodeCompleteObjCAtDirective(getCurScope());
  382. return cutOffParsing();
  383. }
  384. tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID();
  385. if (DirectiveKind == tok::objc_end) { // @end -> terminate list
  386. AtEnd.setBegin(AtLoc);
  387. AtEnd.setEnd(Tok.getLocation());
  388. break;
  389. } else if (DirectiveKind == tok::objc_not_keyword) {
  390. Diag(Tok, diag::err_objc_unknown_at);
  391. SkipUntil(tok::semi);
  392. continue;
  393. }
  394. // Eat the identifier.
  395. ConsumeToken();
  396. switch (DirectiveKind) {
  397. default:
  398. // FIXME: If someone forgets an @end on a protocol, this loop will
  399. // continue to eat up tons of stuff and spew lots of nonsense errors. It
  400. // would probably be better to bail out if we saw an @class or @interface
  401. // or something like that.
  402. Diag(AtLoc, diag::err_objc_illegal_interface_qual);
  403. // Skip until we see an '@' or '}' or ';'.
  404. SkipUntil(tok::r_brace, tok::at);
  405. break;
  406. case tok::objc_implementation:
  407. case tok::objc_interface:
  408. Diag(AtLoc, diag::err_objc_missing_end)
  409. << FixItHint::CreateInsertion(AtLoc, "@end\n");
  410. Diag(CDecl->getLocStart(), diag::note_objc_container_start)
  411. << (int) Actions.getObjCContainerKind();
  412. ConsumeToken();
  413. break;
  414. case tok::objc_required:
  415. case tok::objc_optional:
  416. // This is only valid on protocols.
  417. // FIXME: Should this check for ObjC2 being enabled?
  418. if (contextKey != tok::objc_protocol)
  419. Diag(AtLoc, diag::err_objc_directive_only_in_protocol);
  420. else
  421. MethodImplKind = DirectiveKind;
  422. break;
  423. case tok::objc_property:
  424. if (!getLangOpts().ObjC2)
  425. Diag(AtLoc, diag::err_objc_properties_require_objc2);
  426. ObjCDeclSpec OCDS;
  427. SourceLocation LParenLoc;
  428. // Parse property attribute list, if any.
  429. if (Tok.is(tok::l_paren)) {
  430. LParenLoc = Tok.getLocation();
  431. ParseObjCPropertyAttribute(OCDS);
  432. }
  433. ObjCPropertyCallback Callback(*this, allProperties,
  434. OCDS, AtLoc, LParenLoc, MethodImplKind);
  435. // Parse all the comma separated declarators.
  436. DeclSpec DS(AttrFactory);
  437. ParseStructDeclaration(DS, Callback);
  438. ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
  439. break;
  440. }
  441. }
  442. // We break out of the big loop in two cases: when we see @end or when we see
  443. // EOF. In the former case, eat the @end. In the later case, emit an error.
  444. if (Tok.is(tok::code_completion)) {
  445. Actions.CodeCompleteObjCAtDirective(getCurScope());
  446. return cutOffParsing();
  447. } else if (Tok.isObjCAtKeyword(tok::objc_end)) {
  448. ConsumeToken(); // the "end" identifier
  449. } else {
  450. Diag(Tok, diag::err_objc_missing_end)
  451. << FixItHint::CreateInsertion(Tok.getLocation(), "\n@end\n");
  452. Diag(CDecl->getLocStart(), diag::note_objc_container_start)
  453. << (int) Actions.getObjCContainerKind();
  454. AtEnd.setBegin(Tok.getLocation());
  455. AtEnd.setEnd(Tok.getLocation());
  456. }
  457. // Insert collected methods declarations into the @interface object.
  458. // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit.
  459. Actions.ActOnAtEnd(getCurScope(), AtEnd,
  460. allMethods.data(), allMethods.size(),
  461. allProperties.data(), allProperties.size(),
  462. allTUVariables.data(), allTUVariables.size());
  463. }
  464. /// Parse property attribute declarations.
  465. ///
  466. /// property-attr-decl: '(' property-attrlist ')'
  467. /// property-attrlist:
  468. /// property-attribute
  469. /// property-attrlist ',' property-attribute
  470. /// property-attribute:
  471. /// getter '=' identifier
  472. /// setter '=' identifier ':'
  473. /// readonly
  474. /// readwrite
  475. /// assign
  476. /// retain
  477. /// copy
  478. /// nonatomic
  479. /// atomic
  480. /// strong
  481. /// weak
  482. /// unsafe_unretained
  483. ///
  484. void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) {
  485. assert(Tok.getKind() == tok::l_paren);
  486. BalancedDelimiterTracker T(*this, tok::l_paren);
  487. T.consumeOpen();
  488. while (1) {
  489. if (Tok.is(tok::code_completion)) {
  490. Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS);
  491. return cutOffParsing();
  492. }
  493. const IdentifierInfo *II = Tok.getIdentifierInfo();
  494. // If this is not an identifier at all, bail out early.
  495. if (II == 0) {
  496. T.consumeClose();
  497. return;
  498. }
  499. SourceLocation AttrName = ConsumeToken(); // consume last attribute name
  500. if (II->isStr("readonly"))
  501. DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly);
  502. else if (II->isStr("assign"))
  503. DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign);
  504. else if (II->isStr("unsafe_unretained"))
  505. DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_unsafe_unretained);
  506. else if (II->isStr("readwrite"))
  507. DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite);
  508. else if (II->isStr("retain"))
  509. DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain);
  510. else if (II->isStr("strong"))
  511. DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_strong);
  512. else if (II->isStr("copy"))
  513. DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy);
  514. else if (II->isStr("nonatomic"))
  515. DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic);
  516. else if (II->isStr("atomic"))
  517. DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_atomic);
  518. else if (II->isStr("weak"))
  519. DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_weak);
  520. else if (II->isStr("getter") || II->isStr("setter")) {
  521. bool IsSetter = II->getNameStart()[0] == 's';
  522. // getter/setter require extra treatment.
  523. unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter :
  524. diag::err_objc_expected_equal_for_getter;
  525. if (ExpectAndConsume(tok::equal, DiagID, "", tok::r_paren))
  526. return;
  527. if (Tok.is(tok::code_completion)) {
  528. if (IsSetter)
  529. Actions.CodeCompleteObjCPropertySetter(getCurScope());
  530. else
  531. Actions.CodeCompleteObjCPropertyGetter(getCurScope());
  532. return cutOffParsing();
  533. }
  534. SourceLocation SelLoc;
  535. IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc);
  536. if (!SelIdent) {
  537. Diag(Tok, diag::err_objc_expected_selector_for_getter_setter)
  538. << IsSetter;
  539. SkipUntil(tok::r_paren);
  540. return;
  541. }
  542. if (IsSetter) {
  543. DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter);
  544. DS.setSetterName(SelIdent);
  545. if (ExpectAndConsume(tok::colon,
  546. diag::err_expected_colon_after_setter_name, "",
  547. tok::r_paren))
  548. return;
  549. } else {
  550. DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter);
  551. DS.setGetterName(SelIdent);
  552. }
  553. } else {
  554. Diag(AttrName, diag::err_objc_expected_property_attr) << II;
  555. SkipUntil(tok::r_paren);
  556. return;
  557. }
  558. if (Tok.isNot(tok::comma))
  559. break;
  560. ConsumeToken();
  561. }
  562. T.consumeClose();
  563. }
  564. /// objc-method-proto:
  565. /// objc-instance-method objc-method-decl objc-method-attributes[opt]
  566. /// objc-class-method objc-method-decl objc-method-attributes[opt]
  567. ///
  568. /// objc-instance-method: '-'
  569. /// objc-class-method: '+'
  570. ///
  571. /// objc-method-attributes: [OBJC2]
  572. /// __attribute__((deprecated))
  573. ///
  574. Decl *Parser::ParseObjCMethodPrototype(tok::ObjCKeywordKind MethodImplKind,
  575. bool MethodDefinition) {
  576. assert((Tok.is(tok::minus) || Tok.is(tok::plus)) && "expected +/-");
  577. tok::TokenKind methodType = Tok.getKind();
  578. SourceLocation mLoc = ConsumeToken();
  579. Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, MethodImplKind,
  580. MethodDefinition);
  581. // Since this rule is used for both method declarations and definitions,
  582. // the caller is (optionally) responsible for consuming the ';'.
  583. return MDecl;
  584. }
  585. /// objc-selector:
  586. /// identifier
  587. /// one of
  588. /// enum struct union if else while do for switch case default
  589. /// break continue return goto asm sizeof typeof __alignof
  590. /// unsigned long const short volatile signed restrict _Complex
  591. /// in out inout bycopy byref oneway int char float double void _Bool
  592. ///
  593. IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) {
  594. switch (Tok.getKind()) {
  595. default:
  596. return 0;
  597. case tok::ampamp:
  598. case tok::ampequal:
  599. case tok::amp:
  600. case tok::pipe:
  601. case tok::tilde:
  602. case tok::exclaim:
  603. case tok::exclaimequal:
  604. case tok::pipepipe:
  605. case tok::pipeequal:
  606. case tok::caret:
  607. case tok::caretequal: {
  608. std::string ThisTok(PP.getSpelling(Tok));
  609. if (isalpha(ThisTok[0])) {
  610. IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok.data());
  611. Tok.setKind(tok::identifier);
  612. SelectorLoc = ConsumeToken();
  613. return II;
  614. }
  615. return 0;
  616. }
  617. case tok::identifier:
  618. case tok::kw_asm:
  619. case tok::kw_auto:
  620. case tok::kw_bool:
  621. case tok::kw_break:
  622. case tok::kw_case:
  623. case tok::kw_catch:
  624. case tok::kw_char:
  625. case tok::kw_class:
  626. case tok::kw_const:
  627. case tok::kw_const_cast:
  628. case tok::kw_continue:
  629. case tok::kw_default:
  630. case tok::kw_delete:
  631. case tok::kw_do:
  632. case tok::kw_double:
  633. case tok::kw_dynamic_cast:
  634. case tok::kw_else:
  635. case tok::kw_enum:
  636. case tok::kw_explicit:
  637. case tok::kw_export:
  638. case tok::kw_extern:
  639. case tok::kw_false:
  640. case tok::kw_float:
  641. case tok::kw_for:
  642. case tok::kw_friend:
  643. case tok::kw_goto:
  644. case tok::kw_if:
  645. case tok::kw_inline:
  646. case tok::kw_int:
  647. case tok::kw_long:
  648. case tok::kw_mutable:
  649. case tok::kw_namespace:
  650. case tok::kw_new:
  651. case tok::kw_operator:
  652. case tok::kw_private:
  653. case tok::kw_protected:
  654. case tok::kw_public:
  655. case tok::kw_register:
  656. case tok::kw_reinterpret_cast:
  657. case tok::kw_restrict:
  658. case tok::kw_return:
  659. case tok::kw_short:
  660. case tok::kw_signed:
  661. case tok::kw_sizeof:
  662. case tok::kw_static:
  663. case tok::kw_static_cast:
  664. case tok::kw_struct:
  665. case tok::kw_switch:
  666. case tok::kw_template:
  667. case tok::kw_this:
  668. case tok::kw_throw:
  669. case tok::kw_true:
  670. case tok::kw_try:
  671. case tok::kw_typedef:
  672. case tok::kw_typeid:
  673. case tok::kw_typename:
  674. case tok::kw_typeof:
  675. case tok::kw_union:
  676. case tok::kw_unsigned:
  677. case tok::kw_using:
  678. case tok::kw_virtual:
  679. case tok::kw_void:
  680. case tok::kw_volatile:
  681. case tok::kw_wchar_t:
  682. case tok::kw_while:
  683. case tok::kw__Bool:
  684. case tok::kw__Complex:
  685. case tok::kw___alignof:
  686. IdentifierInfo *II = Tok.getIdentifierInfo();
  687. SelectorLoc = ConsumeToken();
  688. return II;
  689. }
  690. }
  691. /// objc-for-collection-in: 'in'
  692. ///
  693. bool Parser::isTokIdentifier_in() const {
  694. // FIXME: May have to do additional look-ahead to only allow for
  695. // valid tokens following an 'in'; such as an identifier, unary operators,
  696. // '[' etc.
  697. return (getLangOpts().ObjC2 && Tok.is(tok::identifier) &&
  698. Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]);
  699. }
  700. /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
  701. /// qualifier list and builds their bitmask representation in the input
  702. /// argument.
  703. ///
  704. /// objc-type-qualifiers:
  705. /// objc-type-qualifier
  706. /// objc-type-qualifiers objc-type-qualifier
  707. ///
  708. void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
  709. Declarator::TheContext Context) {
  710. assert(Context == Declarator::ObjCParameterContext ||
  711. Context == Declarator::ObjCResultContext);
  712. while (1) {
  713. if (Tok.is(tok::code_completion)) {
  714. Actions.CodeCompleteObjCPassingType(getCurScope(), DS,
  715. Context == Declarator::ObjCParameterContext);
  716. return cutOffParsing();
  717. }
  718. if (Tok.isNot(tok::identifier))
  719. return;
  720. const IdentifierInfo *II = Tok.getIdentifierInfo();
  721. for (unsigned i = 0; i != objc_NumQuals; ++i) {
  722. if (II != ObjCTypeQuals[i])
  723. continue;
  724. ObjCDeclSpec::ObjCDeclQualifier Qual;
  725. switch (i) {
  726. default: llvm_unreachable("Unknown decl qualifier");
  727. case objc_in: Qual = ObjCDeclSpec::DQ_In; break;
  728. case objc_out: Qual = ObjCDeclSpec::DQ_Out; break;
  729. case objc_inout: Qual = ObjCDeclSpec::DQ_Inout; break;
  730. case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break;
  731. case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break;
  732. case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break;
  733. }
  734. DS.setObjCDeclQualifier(Qual);
  735. ConsumeToken();
  736. II = 0;
  737. break;
  738. }
  739. // If this wasn't a recognized qualifier, bail out.
  740. if (II) return;
  741. }
  742. }
  743. /// Take all the decl attributes out of the given list and add
  744. /// them to the given attribute set.
  745. static void takeDeclAttributes(ParsedAttributes &attrs,
  746. AttributeList *list) {
  747. while (list) {
  748. AttributeList *cur = list;
  749. list = cur->getNext();
  750. if (!cur->isUsedAsTypeAttr()) {
  751. // Clear out the next pointer. We're really completely
  752. // destroying the internal invariants of the declarator here,
  753. // but it doesn't matter because we're done with it.
  754. cur->setNext(0);
  755. attrs.add(cur);
  756. }
  757. }
  758. }
  759. /// takeDeclAttributes - Take all the decl attributes from the given
  760. /// declarator and add them to the given list.
  761. static void takeDeclAttributes(ParsedAttributes &attrs,
  762. Declarator &D) {
  763. // First, take ownership of all attributes.
  764. attrs.getPool().takeAllFrom(D.getAttributePool());
  765. attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool());
  766. // Now actually move the attributes over.
  767. takeDeclAttributes(attrs, D.getDeclSpec().getAttributes().getList());
  768. takeDeclAttributes(attrs, D.getAttributes());
  769. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
  770. takeDeclAttributes(attrs,
  771. const_cast<AttributeList*>(D.getTypeObject(i).getAttrs()));
  772. }
  773. /// objc-type-name:
  774. /// '(' objc-type-qualifiers[opt] type-name ')'
  775. /// '(' objc-type-qualifiers[opt] ')'
  776. ///
  777. ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS,
  778. Declarator::TheContext context,
  779. ParsedAttributes *paramAttrs) {
  780. assert(context == Declarator::ObjCParameterContext ||
  781. context == Declarator::ObjCResultContext);
  782. assert((paramAttrs != 0) == (context == Declarator::ObjCParameterContext));
  783. assert(Tok.is(tok::l_paren) && "expected (");
  784. BalancedDelimiterTracker T(*this, tok::l_paren);
  785. T.consumeOpen();
  786. SourceLocation TypeStartLoc = Tok.getLocation();
  787. ObjCDeclContextSwitch ObjCDC(*this);
  788. // Parse type qualifiers, in, inout, etc.
  789. ParseObjCTypeQualifierList(DS, context);
  790. ParsedType Ty;
  791. if (isTypeSpecifierQualifier()) {
  792. // Parse an abstract declarator.
  793. DeclSpec declSpec(AttrFactory);
  794. declSpec.setObjCQualifiers(&DS);
  795. ParseSpecifierQualifierList(declSpec);
  796. Declarator declarator(declSpec, context);
  797. ParseDeclarator(declarator);
  798. // If that's not invalid, extract a type.
  799. if (!declarator.isInvalidType()) {
  800. TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator);
  801. if (!type.isInvalid())
  802. Ty = type.get();
  803. // If we're parsing a parameter, steal all the decl attributes
  804. // and add them to the decl spec.
  805. if (context == Declarator::ObjCParameterContext)
  806. takeDeclAttributes(*paramAttrs, declarator);
  807. }
  808. } else if (context == Declarator::ObjCResultContext &&
  809. Tok.is(tok::identifier)) {
  810. if (!Ident_instancetype)
  811. Ident_instancetype = PP.getIdentifierInfo("instancetype");
  812. if (Tok.getIdentifierInfo() == Ident_instancetype) {
  813. Ty = Actions.ActOnObjCInstanceType(Tok.getLocation());
  814. ConsumeToken();
  815. }
  816. }
  817. if (Tok.is(tok::r_paren))
  818. T.consumeClose();
  819. else if (Tok.getLocation() == TypeStartLoc) {
  820. // If we didn't eat any tokens, then this isn't a type.
  821. Diag(Tok, diag::err_expected_type);
  822. SkipUntil(tok::r_paren);
  823. } else {
  824. // Otherwise, we found *something*, but didn't get a ')' in the right
  825. // place. Emit an error then return what we have as the type.
  826. T.consumeClose();
  827. }
  828. return Ty;
  829. }
  830. /// objc-method-decl:
  831. /// objc-selector
  832. /// objc-keyword-selector objc-parmlist[opt]
  833. /// objc-type-name objc-selector
  834. /// objc-type-name objc-keyword-selector objc-parmlist[opt]
  835. ///
  836. /// objc-keyword-selector:
  837. /// objc-keyword-decl
  838. /// objc-keyword-selector objc-keyword-decl
  839. ///
  840. /// objc-keyword-decl:
  841. /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
  842. /// objc-selector ':' objc-keyword-attributes[opt] identifier
  843. /// ':' objc-type-name objc-keyword-attributes[opt] identifier
  844. /// ':' objc-keyword-attributes[opt] identifier
  845. ///
  846. /// objc-parmlist:
  847. /// objc-parms objc-ellipsis[opt]
  848. ///
  849. /// objc-parms:
  850. /// objc-parms , parameter-declaration
  851. ///
  852. /// objc-ellipsis:
  853. /// , ...
  854. ///
  855. /// objc-keyword-attributes: [OBJC2]
  856. /// __attribute__((unused))
  857. ///
  858. Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
  859. tok::TokenKind mType,
  860. tok::ObjCKeywordKind MethodImplKind,
  861. bool MethodDefinition) {
  862. ParsingDeclRAIIObject PD(*this);
  863. if (Tok.is(tok::code_completion)) {
  864. Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
  865. /*ReturnType=*/ ParsedType());
  866. cutOffParsing();
  867. return 0;
  868. }
  869. // Parse the return type if present.
  870. ParsedType ReturnType;
  871. ObjCDeclSpec DSRet;
  872. if (Tok.is(tok::l_paren))
  873. ReturnType = ParseObjCTypeName(DSRet, Declarator::ObjCResultContext, 0);
  874. // If attributes exist before the method, parse them.
  875. ParsedAttributes methodAttrs(AttrFactory);
  876. if (getLangOpts().ObjC2)
  877. MaybeParseGNUAttributes(methodAttrs);
  878. if (Tok.is(tok::code_completion)) {
  879. Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
  880. ReturnType);
  881. cutOffParsing();
  882. return 0;
  883. }
  884. // Now parse the selector.
  885. SourceLocation selLoc;
  886. IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc);
  887. // An unnamed colon is valid.
  888. if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name.
  889. Diag(Tok, diag::err_expected_selector_for_method)
  890. << SourceRange(mLoc, Tok.getLocation());
  891. // Skip until we get a ; or {}.
  892. SkipUntil(tok::r_brace);
  893. return 0;
  894. }
  895. SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
  896. if (Tok.isNot(tok::colon)) {
  897. // If attributes exist after the method, parse them.
  898. if (getLangOpts().ObjC2)
  899. MaybeParseGNUAttributes(methodAttrs);
  900. Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
  901. Decl *Result
  902. = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
  903. mType, DSRet, ReturnType,
  904. selLoc, Sel, 0,
  905. CParamInfo.data(), CParamInfo.size(),
  906. methodAttrs.getList(), MethodImplKind,
  907. false, MethodDefinition);
  908. PD.complete(Result);
  909. return Result;
  910. }
  911. SmallVector<IdentifierInfo *, 12> KeyIdents;
  912. SmallVector<SourceLocation, 12> KeyLocs;
  913. SmallVector<Sema::ObjCArgInfo, 12> ArgInfos;
  914. ParseScope PrototypeScope(this,
  915. Scope::FunctionPrototypeScope|Scope::DeclScope);
  916. AttributePool allParamAttrs(AttrFactory);
  917. while (1) {
  918. ParsedAttributes paramAttrs(AttrFactory);
  919. Sema::ObjCArgInfo ArgInfo;
  920. // Each iteration parses a single keyword argument.
  921. if (Tok.isNot(tok::colon)) {
  922. Diag(Tok, diag::err_expected_colon);
  923. break;
  924. }
  925. ConsumeToken(); // Eat the ':'.
  926. ArgInfo.Type = ParsedType();
  927. if (Tok.is(tok::l_paren)) // Parse the argument type if present.
  928. ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec,
  929. Declarator::ObjCParameterContext,
  930. &paramAttrs);
  931. // If attributes exist before the argument name, parse them.
  932. // Regardless, collect all the attributes we've parsed so far.
  933. ArgInfo.ArgAttrs = 0;
  934. if (getLangOpts().ObjC2) {
  935. MaybeParseGNUAttributes(paramAttrs);
  936. ArgInfo.ArgAttrs = paramAttrs.getList();
  937. }
  938. // Code completion for the next piece of the selector.
  939. if (Tok.is(tok::code_completion)) {
  940. KeyIdents.push_back(SelIdent);
  941. Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
  942. mType == tok::minus,
  943. /*AtParameterName=*/true,
  944. ReturnType,
  945. KeyIdents.data(),
  946. KeyIdents.size());
  947. cutOffParsing();
  948. return 0;
  949. }
  950. if (Tok.isNot(tok::identifier)) {
  951. Diag(Tok, diag::err_expected_ident); // missing argument name.
  952. break;
  953. }
  954. ArgInfo.Name = Tok.getIdentifierInfo();
  955. ArgInfo.NameLoc = Tok.getLocation();
  956. ConsumeToken(); // Eat the identifier.
  957. ArgInfos.push_back(ArgInfo);
  958. KeyIdents.push_back(SelIdent);
  959. KeyLocs.push_back(selLoc);
  960. // Make sure the attributes persist.
  961. allParamAttrs.takeAllFrom(paramAttrs.getPool());
  962. // Code completion for the next piece of the selector.
  963. if (Tok.is(tok::code_completion)) {
  964. Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
  965. mType == tok::minus,
  966. /*AtParameterName=*/false,
  967. ReturnType,
  968. KeyIdents.data(),
  969. KeyIdents.size());
  970. cutOffParsing();
  971. return 0;
  972. }
  973. // Check for another keyword selector.
  974. SelIdent = ParseObjCSelectorPiece(selLoc);
  975. if (!SelIdent && Tok.isNot(tok::colon))
  976. break;
  977. // We have a selector or a colon, continue parsing.
  978. }
  979. bool isVariadic = false;
  980. // Parse the (optional) parameter list.
  981. while (Tok.is(tok::comma)) {
  982. ConsumeToken();
  983. if (Tok.is(tok::ellipsis)) {
  984. isVariadic = true;
  985. ConsumeToken();
  986. break;
  987. }
  988. DeclSpec DS(AttrFactory);
  989. ParseDeclarationSpecifiers(DS);
  990. // Parse the declarator.
  991. Declarator ParmDecl(DS, Declarator::PrototypeContext);
  992. ParseDeclarator(ParmDecl);
  993. IdentifierInfo *ParmII = ParmDecl.getIdentifier();
  994. Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
  995. CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
  996. ParmDecl.getIdentifierLoc(),
  997. Param,
  998. 0));
  999. }
  1000. // FIXME: Add support for optional parameter list...
  1001. // If attributes exist after the method, parse them.
  1002. if (getLangOpts().ObjC2)
  1003. MaybeParseGNUAttributes(methodAttrs);
  1004. if (KeyIdents.size() == 0)
  1005. return 0;
  1006. Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
  1007. &KeyIdents[0]);
  1008. Decl *Result
  1009. = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
  1010. mType, DSRet, ReturnType,
  1011. KeyLocs, Sel, &ArgInfos[0],
  1012. CParamInfo.data(), CParamInfo.size(),
  1013. methodAttrs.getList(),
  1014. MethodImplKind, isVariadic, MethodDefinition);
  1015. PD.complete(Result);
  1016. return Result;
  1017. }
  1018. /// objc-protocol-refs:
  1019. /// '<' identifier-list '>'
  1020. ///
  1021. bool Parser::
  1022. ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols,
  1023. SmallVectorImpl<SourceLocation> &ProtocolLocs,
  1024. bool WarnOnDeclarations,
  1025. SourceLocation &LAngleLoc, SourceLocation &EndLoc) {
  1026. assert(Tok.is(tok::less) && "expected <");
  1027. LAngleLoc = ConsumeToken(); // the "<"
  1028. SmallVector<IdentifierLocPair, 8> ProtocolIdents;
  1029. while (1) {
  1030. if (Tok.is(tok::code_completion)) {
  1031. Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents.data(),
  1032. ProtocolIdents.size());
  1033. cutOffParsing();
  1034. return true;
  1035. }
  1036. if (Tok.isNot(tok::identifier)) {
  1037. Diag(Tok, diag::err_expected_ident);
  1038. SkipUntil(tok::greater);
  1039. return true;
  1040. }
  1041. ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
  1042. Tok.getLocation()));
  1043. ProtocolLocs.push_back(Tok.getLocation());
  1044. ConsumeToken();
  1045. if (Tok.isNot(tok::comma))
  1046. break;
  1047. ConsumeToken();
  1048. }
  1049. // Consume the '>'.
  1050. if (Tok.isNot(tok::greater)) {
  1051. Diag(Tok, diag::err_expected_greater);
  1052. return true;
  1053. }
  1054. EndLoc = ConsumeToken();
  1055. // Convert the list of protocols identifiers into a list of protocol decls.
  1056. Actions.FindProtocolDeclaration(WarnOnDeclarations,
  1057. &ProtocolIdents[0], ProtocolIdents.size(),
  1058. Protocols);
  1059. return false;
  1060. }
  1061. /// \brief Parse the Objective-C protocol qualifiers that follow a typename
  1062. /// in a decl-specifier-seq, starting at the '<'.
  1063. bool Parser::ParseObjCProtocolQualifiers(DeclSpec &DS) {
  1064. assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
  1065. assert(getLangOpts().ObjC1 && "Protocol qualifiers only exist in Objective-C");
  1066. SourceLocation LAngleLoc, EndProtoLoc;
  1067. SmallVector<Decl *, 8> ProtocolDecl;
  1068. SmallVector<SourceLocation, 8> ProtocolLocs;
  1069. bool Result = ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
  1070. LAngleLoc, EndProtoLoc);
  1071. DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
  1072. ProtocolLocs.data(), LAngleLoc);
  1073. if (EndProtoLoc.isValid())
  1074. DS.SetRangeEnd(EndProtoLoc);
  1075. return Result;
  1076. }
  1077. /// objc-class-instance-variables:
  1078. /// '{' objc-instance-variable-decl-list[opt] '}'
  1079. ///
  1080. /// objc-instance-variable-decl-list:
  1081. /// objc-visibility-spec
  1082. /// objc-instance-variable-decl ';'
  1083. /// ';'
  1084. /// objc-instance-variable-decl-list objc-visibility-spec
  1085. /// objc-instance-variable-decl-list objc-instance-variable-decl ';'
  1086. /// objc-instance-variable-decl-list ';'
  1087. ///
  1088. /// objc-visibility-spec:
  1089. /// @private
  1090. /// @protected
  1091. /// @public
  1092. /// @package [OBJC2]
  1093. ///
  1094. /// objc-instance-variable-decl:
  1095. /// struct-declaration
  1096. ///
  1097. void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl,
  1098. tok::ObjCKeywordKind visibility,
  1099. SourceLocation atLoc) {
  1100. assert(Tok.is(tok::l_brace) && "expected {");
  1101. SmallVector<Decl *, 32> AllIvarDecls;
  1102. ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope);
  1103. ObjCDeclContextSwitch ObjCDC(*this);
  1104. BalancedDelimiterTracker T(*this, tok::l_brace);
  1105. T.consumeOpen();
  1106. // While we still have something to read, read the instance variables.
  1107. while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
  1108. // Each iteration of this loop reads one objc-instance-variable-decl.
  1109. // Check for extraneous top-level semicolon.
  1110. if (Tok.is(tok::semi)) {
  1111. Diag(Tok, diag::ext_extra_ivar_semi)
  1112. << FixItHint::CreateRemoval(Tok.getLocation());
  1113. ConsumeToken();
  1114. continue;
  1115. }
  1116. // Set the default visibility to private.
  1117. if (Tok.is(tok::at)) { // parse objc-visibility-spec
  1118. ConsumeToken(); // eat the @ sign
  1119. if (Tok.is(tok::code_completion)) {
  1120. Actions.CodeCompleteObjCAtVisibility(getCurScope());
  1121. return cutOffParsing();
  1122. }
  1123. switch (Tok.getObjCKeywordID()) {
  1124. case tok::objc_private:
  1125. case tok::objc_public:
  1126. case tok::objc_protected:
  1127. case tok::objc_package:
  1128. visibility = Tok.getObjCKeywordID();
  1129. ConsumeToken();
  1130. continue;
  1131. default:
  1132. Diag(Tok, diag::err_objc_illegal_visibility_spec);
  1133. continue;
  1134. }
  1135. }
  1136. if (Tok.is(tok::code_completion)) {
  1137. Actions.CodeCompleteOrdinaryName(getCurScope(),
  1138. Sema::PCC_ObjCInstanceVariableList);
  1139. return cutOffParsing();
  1140. }
  1141. struct ObjCIvarCallback : FieldCallback {
  1142. Parser &P;
  1143. Decl *IDecl;
  1144. tok::ObjCKeywordKind visibility;
  1145. SmallVectorImpl<Decl *> &AllIvarDecls;
  1146. ObjCIvarCallback(Parser &P, Decl *IDecl, tok::ObjCKeywordKind V,
  1147. SmallVectorImpl<Decl *> &AllIvarDecls) :
  1148. P(P), IDecl(IDecl), visibility(V), AllIvarDecls(AllIvarDecls) {
  1149. }
  1150. Decl *invoke(FieldDeclarator &FD) {
  1151. P.Actions.ActOnObjCContainerStartDefinition(IDecl);
  1152. // Install the declarator into the interface decl.
  1153. Decl *Field
  1154. = P.Actions.ActOnIvar(P.getCurScope(),
  1155. FD.D.getDeclSpec().getSourceRange().getBegin(),
  1156. FD.D, FD.BitfieldSize, visibility);
  1157. P.Actions.ActOnObjCContainerFinishDefinition();
  1158. if (Field)
  1159. AllIvarDecls.push_back(Field);
  1160. return Field;
  1161. }
  1162. } Callback(*this, interfaceDecl, visibility, AllIvarDecls);
  1163. // Parse all the comma separated declarators.
  1164. DeclSpec DS(AttrFactory);
  1165. ParseStructDeclaration(DS, Callback);
  1166. if (Tok.is(tok::semi)) {
  1167. ConsumeToken();
  1168. } else {
  1169. Diag(Tok, diag::err_expected_semi_decl_list);
  1170. // Skip to end of block or statement
  1171. SkipUntil(tok::r_brace, true, true);
  1172. }
  1173. }
  1174. T.consumeClose();
  1175. Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
  1176. Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls);
  1177. Actions.ActOnObjCContainerFinishDefinition();
  1178. // Call ActOnFields() even if we don't have any decls. This is useful
  1179. // for code rewriting tools that need to be aware of the empty list.
  1180. Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl,
  1181. AllIvarDecls,
  1182. T.getOpenLocation(), T.getCloseLocation(), 0);
  1183. return;
  1184. }
  1185. /// objc-protocol-declaration:
  1186. /// objc-protocol-definition
  1187. /// objc-protocol-forward-reference
  1188. ///
  1189. /// objc-protocol-definition:
  1190. /// @protocol identifier
  1191. /// objc-protocol-refs[opt]
  1192. /// objc-interface-decl-list
  1193. /// @end
  1194. ///
  1195. /// objc-protocol-forward-reference:
  1196. /// @protocol identifier-list ';'
  1197. ///
  1198. /// "@protocol identifier ;" should be resolved as "@protocol
  1199. /// identifier-list ;": objc-interface-decl-list may not start with a
  1200. /// semicolon in the first alternative if objc-protocol-refs are omitted.
  1201. Parser::DeclGroupPtrTy
  1202. Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
  1203. ParsedAttributes &attrs) {
  1204. assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
  1205. "ParseObjCAtProtocolDeclaration(): Expected @protocol");
  1206. ConsumeToken(); // the "protocol" identifier
  1207. if (Tok.is(tok::code_completion)) {
  1208. Actions.CodeCompleteObjCProtocolDecl(getCurScope());
  1209. cutOffParsing();
  1210. return DeclGroupPtrTy();
  1211. }
  1212. if (Tok.isNot(tok::identifier)) {
  1213. Diag(Tok, diag::err_expected_ident); // missing protocol name.
  1214. return DeclGroupPtrTy();
  1215. }
  1216. // Save the protocol name, then consume it.
  1217. IdentifierInfo *protocolName = Tok.getIdentifierInfo();
  1218. SourceLocation nameLoc = ConsumeToken();
  1219. if (Tok.is(tok::semi)) { // forward declaration of one protocol.
  1220. IdentifierLocPair ProtoInfo(protocolName, nameLoc);
  1221. ConsumeToken();
  1222. return Actions.ActOnForwardProtocolDeclaration(AtLoc, &ProtoInfo, 1,
  1223. attrs.getList());
  1224. }
  1225. CheckNestedObjCContexts(AtLoc);
  1226. if (Tok.is(tok::comma)) { // list of forward declarations.
  1227. SmallVector<IdentifierLocPair, 8> ProtocolRefs;
  1228. ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
  1229. // Parse the list of forward declarations.
  1230. while (1) {
  1231. ConsumeToken(); // the ','
  1232. if (Tok.isNot(tok::identifier)) {
  1233. Diag(Tok, diag::err_expected_ident);
  1234. SkipUntil(tok::semi);
  1235. return DeclGroupPtrTy();
  1236. }
  1237. ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
  1238. Tok.getLocation()));
  1239. ConsumeToken(); // the identifier
  1240. if (Tok.isNot(tok::comma))
  1241. break;
  1242. }
  1243. // Consume the ';'.
  1244. if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@protocol"))
  1245. return DeclGroupPtrTy();
  1246. return Actions.ActOnForwardProtocolDeclaration(AtLoc,
  1247. &ProtocolRefs[0],
  1248. ProtocolRefs.size(),
  1249. attrs.getList());
  1250. }
  1251. // Last, and definitely not least, parse a protocol declaration.
  1252. SourceLocation LAngleLoc, EndProtoLoc;
  1253. SmallVector<Decl *, 8> ProtocolRefs;
  1254. SmallVector<SourceLocation, 8> ProtocolLocs;
  1255. if (Tok.is(tok::less) &&
  1256. ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false,
  1257. LAngleLoc, EndProtoLoc))
  1258. return DeclGroupPtrTy();
  1259. Decl *ProtoType =
  1260. Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc,
  1261. ProtocolRefs.data(),
  1262. ProtocolRefs.size(),
  1263. ProtocolLocs.data(),
  1264. EndProtoLoc, attrs.getList());
  1265. ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType);
  1266. return Actions.ConvertDeclToDeclGroup(ProtoType);
  1267. }
  1268. /// objc-implementation:
  1269. /// objc-class-implementation-prologue
  1270. /// objc-category-implementation-prologue
  1271. ///
  1272. /// objc-class-implementation-prologue:
  1273. /// @implementation identifier objc-superclass[opt]
  1274. /// objc-class-instance-variables[opt]
  1275. ///
  1276. /// objc-category-implementation-prologue:
  1277. /// @implementation identifier ( identifier )
  1278. Parser::DeclGroupPtrTy
  1279. Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) {
  1280. assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
  1281. "ParseObjCAtImplementationDeclaration(): Expected @implementation");
  1282. CheckNestedObjCContexts(AtLoc);
  1283. ConsumeToken(); // the "implementation" identifier
  1284. // Code completion after '@implementation'.
  1285. if (Tok.is(tok::code_completion)) {
  1286. Actions.CodeCompleteObjCImplementationDecl(getCurScope());
  1287. cutOffParsing();
  1288. return DeclGroupPtrTy();
  1289. }
  1290. if (Tok.isNot(tok::identifier)) {
  1291. Diag(Tok, diag::err_expected_ident); // missing class or category name.
  1292. return DeclGroupPtrTy();
  1293. }
  1294. // We have a class or category name - consume it.
  1295. IdentifierInfo *nameId = Tok.getIdentifierInfo();
  1296. SourceLocation nameLoc = ConsumeToken(); // consume class or category name
  1297. Decl *ObjCImpDecl = 0;
  1298. if (Tok.is(tok::l_paren)) {
  1299. // we have a category implementation.
  1300. ConsumeParen();
  1301. SourceLocation categoryLoc, rparenLoc;
  1302. IdentifierInfo *categoryId = 0;
  1303. if (Tok.is(tok::code_completion)) {
  1304. Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
  1305. cutOffParsing();
  1306. return DeclGroupPtrTy();
  1307. }
  1308. if (Tok.is(tok::identifier)) {
  1309. categoryId = Tok.getIdentifierInfo();
  1310. categoryLoc = ConsumeToken();
  1311. } else {
  1312. Diag(Tok, diag::err_expected_ident); // missing category name.
  1313. return DeclGroupPtrTy();
  1314. }
  1315. if (Tok.isNot(tok::r_paren)) {
  1316. Diag(Tok, diag::err_expected_rparen);
  1317. SkipUntil(tok::r_paren, false); // don't stop at ';'
  1318. return DeclGroupPtrTy();
  1319. }
  1320. rparenLoc = ConsumeParen();
  1321. ObjCImpDecl = Actions.ActOnStartCategoryImplementation(
  1322. AtLoc, nameId, nameLoc, categoryId,
  1323. categoryLoc);
  1324. } else {
  1325. // We have a class implementation
  1326. SourceLocation superClassLoc;
  1327. IdentifierInfo *superClassId = 0;
  1328. if (Tok.is(tok::colon)) {
  1329. // We have a super class
  1330. ConsumeToken();
  1331. if (Tok.isNot(tok::identifier)) {
  1332. Diag(Tok, diag::err_expected_ident); // missing super class name.
  1333. return DeclGroupPtrTy();
  1334. }
  1335. superClassId = Tok.getIdentifierInfo();
  1336. superClassLoc = ConsumeToken(); // Consume super class name
  1337. }
  1338. ObjCImpDecl = Actions.ActOnStartClassImplementation(
  1339. AtLoc, nameId, nameLoc,
  1340. superClassId, superClassLoc);
  1341. if (Tok.is(tok::l_brace)) // we have ivars
  1342. ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc);
  1343. }
  1344. assert(ObjCImpDecl);
  1345. SmallVector<Decl *, 8> DeclsInGroup;
  1346. {
  1347. ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl);
  1348. while (!ObjCImplParsing.isFinished() && Tok.isNot(tok::eof)) {
  1349. ParsedAttributesWithRange attrs(AttrFactory);
  1350. MaybeParseCXX0XAttributes(attrs);
  1351. MaybeParseMicrosoftAttributes(attrs);
  1352. if (DeclGroupPtrTy DGP = ParseExternalDeclaration(attrs)) {
  1353. DeclGroupRef DG = DGP.get();
  1354. DeclsInGroup.append(DG.begin(), DG.end());
  1355. }
  1356. }
  1357. }
  1358. return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup);
  1359. }
  1360. Parser::DeclGroupPtrTy
  1361. Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
  1362. assert(Tok.isObjCAtKeyword(tok::objc_end) &&
  1363. "ParseObjCAtEndDeclaration(): Expected @end");
  1364. ConsumeToken(); // the "end" identifier
  1365. if (CurParsedObjCImpl)
  1366. CurParsedObjCImpl->finish(atEnd);
  1367. else
  1368. // missing @implementation
  1369. Diag(atEnd.getBegin(), diag::err_expected_objc_container);
  1370. return DeclGroupPtrTy();
  1371. }
  1372. Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() {
  1373. if (!Finished) {
  1374. finish(P.Tok.getLocation());
  1375. if (P.Tok.is(tok::eof)) {
  1376. P.Diag(P.Tok, diag::err_objc_missing_end)
  1377. << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n");
  1378. P.Diag(Dcl->getLocStart(), diag::note_objc_container_start)
  1379. << Sema::OCK_Implementation;
  1380. }
  1381. }
  1382. P.CurParsedObjCImpl = 0;
  1383. assert(LateParsedObjCMethods.empty());
  1384. }
  1385. void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) {
  1386. assert(!Finished);
  1387. P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl);
  1388. for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
  1389. P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i]);
  1390. P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd);
  1391. /// \brief Clear and free the cached objc methods.
  1392. for (LateParsedObjCMethodContainer::iterator
  1393. I = LateParsedObjCMethods.begin(),
  1394. E = LateParsedObjCMethods.end(); I != E; ++I)
  1395. delete *I;
  1396. LateParsedObjCMethods.clear();
  1397. Finished = true;
  1398. }
  1399. /// compatibility-alias-decl:
  1400. /// @compatibility_alias alias-name class-name ';'
  1401. ///
  1402. Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
  1403. assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
  1404. "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
  1405. ConsumeToken(); // consume compatibility_alias
  1406. if (Tok.isNot(tok::identifier)) {
  1407. Diag(Tok, diag::err_expected_ident);
  1408. return 0;
  1409. }
  1410. IdentifierInfo *aliasId = Tok.getIdentifierInfo();
  1411. SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
  1412. if (Tok.isNot(tok::identifier)) {
  1413. Diag(Tok, diag::err_expected_ident);
  1414. return 0;
  1415. }
  1416. IdentifierInfo *classId = Tok.getIdentifierInfo();
  1417. SourceLocation classLoc = ConsumeToken(); // consume class-name;
  1418. ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
  1419. "@compatibility_alias");
  1420. return Actions.ActOnCompatiblityAlias(atLoc, aliasId, aliasLoc,
  1421. classId, classLoc);
  1422. }
  1423. /// property-synthesis:
  1424. /// @synthesize property-ivar-list ';'
  1425. ///
  1426. /// property-ivar-list:
  1427. /// property-ivar
  1428. /// property-ivar-list ',' property-ivar
  1429. ///
  1430. /// property-ivar:
  1431. /// identifier
  1432. /// identifier '=' identifier
  1433. ///
  1434. Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
  1435. assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
  1436. "ParseObjCPropertyDynamic(): Expected '@synthesize'");
  1437. ConsumeToken(); // consume synthesize
  1438. while (true) {
  1439. if (Tok.is(tok::code_completion)) {
  1440. Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
  1441. cutOffParsing();
  1442. return 0;
  1443. }
  1444. if (Tok.isNot(tok::identifier)) {
  1445. Diag(Tok, diag::err_synthesized_property_name);
  1446. SkipUntil(tok::semi);
  1447. return 0;
  1448. }
  1449. IdentifierInfo *propertyIvar = 0;
  1450. IdentifierInfo *propertyId = Tok.getIdentifierInfo();
  1451. SourceLocation propertyLoc = ConsumeToken(); // consume property name
  1452. SourceLocation propertyIvarLoc;
  1453. if (Tok.is(tok::equal)) {
  1454. // property '=' ivar-name
  1455. ConsumeToken(); // consume '='
  1456. if (Tok.is(tok::code_completion)) {
  1457. Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId);
  1458. cutOffParsing();
  1459. return 0;
  1460. }
  1461. if (Tok.isNot(tok::identifier)) {
  1462. Diag(Tok, diag::err_expected_ident);
  1463. break;
  1464. }
  1465. propertyIvar = Tok.getIdentifierInfo();
  1466. propertyIvarLoc = ConsumeToken(); // consume ivar-name
  1467. }
  1468. Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, true,
  1469. propertyId, propertyIvar, propertyIvarLoc);
  1470. if (Tok.isNot(tok::comma))
  1471. break;
  1472. ConsumeToken(); // consume ','
  1473. }
  1474. ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@synthesize");
  1475. return 0;
  1476. }
  1477. /// property-dynamic:
  1478. /// @dynamic property-list
  1479. ///
  1480. /// property-list:
  1481. /// identifier
  1482. /// property-list ',' identifier
  1483. ///
  1484. Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
  1485. assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
  1486. "ParseObjCPropertyDynamic(): Expected '@dynamic'");
  1487. ConsumeToken(); // consume dynamic
  1488. while (true) {
  1489. if (Tok.is(tok::code_completion)) {
  1490. Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
  1491. cutOffParsing();
  1492. return 0;
  1493. }
  1494. if (Tok.isNot(tok::identifier)) {
  1495. Diag(Tok, diag::err_expected_ident);
  1496. SkipUntil(tok::semi);
  1497. return 0;
  1498. }
  1499. IdentifierInfo *propertyId = Tok.getIdentifierInfo();
  1500. SourceLocation propertyLoc = ConsumeToken(); // consume property name
  1501. Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, false,
  1502. propertyId, 0, SourceLocation());
  1503. if (Tok.isNot(tok::comma))
  1504. break;
  1505. ConsumeToken(); // consume ','
  1506. }
  1507. ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@dynamic");
  1508. return 0;
  1509. }
  1510. /// objc-throw-statement:
  1511. /// throw expression[opt];
  1512. ///
  1513. StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
  1514. ExprResult Res;
  1515. ConsumeToken(); // consume throw
  1516. if (Tok.isNot(tok::semi)) {
  1517. Res = ParseExpression();
  1518. if (Res.isInvalid()) {
  1519. SkipUntil(tok::semi);
  1520. return StmtError();
  1521. }
  1522. }
  1523. // consume ';'
  1524. ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@throw");
  1525. return Actions.ActOnObjCAtThrowStmt(atLoc, Res.take(), getCurScope());
  1526. }
  1527. /// objc-synchronized-statement:
  1528. /// @synchronized '(' expression ')' compound-statement
  1529. ///
  1530. StmtResult
  1531. Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
  1532. ConsumeToken(); // consume synchronized
  1533. if (Tok.isNot(tok::l_paren)) {
  1534. Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
  1535. return StmtError();
  1536. }
  1537. // The operand is surrounded with parentheses.
  1538. ConsumeParen(); // '('
  1539. ExprResult operand(ParseExpression());
  1540. if (Tok.is(tok::r_paren)) {
  1541. ConsumeParen(); // ')'
  1542. } else {
  1543. if (!operand.isInvalid())
  1544. Diag(Tok, diag::err_expected_rparen);
  1545. // Skip forward until we see a left brace, but don't consume it.
  1546. SkipUntil(tok::l_brace, true, true);
  1547. }
  1548. // Require a compound statement.
  1549. if (Tok.isNot(tok::l_brace)) {
  1550. if (!operand.isInvalid())
  1551. Diag(Tok, diag::err_expected_lbrace);
  1552. return StmtError();
  1553. }
  1554. // Check the @synchronized operand now.
  1555. if (!operand.isInvalid())
  1556. operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.take());
  1557. // Parse the compound statement within a new scope.
  1558. ParseScope bodyScope(this, Scope::DeclScope);
  1559. StmtResult body(ParseCompoundStatementBody());
  1560. bodyScope.Exit();
  1561. // If there was a semantic or parse error earlier with the
  1562. // operand, fail now.
  1563. if (operand.isInvalid())
  1564. return StmtError();
  1565. if (body.isInvalid())
  1566. body = Actions.ActOnNullStmt(Tok.getLocation());
  1567. return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get());
  1568. }
  1569. /// objc-try-catch-statement:
  1570. /// @try compound-statement objc-catch-list[opt]
  1571. /// @try compound-statement objc-catch-list[opt] @finally compound-statement
  1572. ///
  1573. /// objc-catch-list:
  1574. /// @catch ( parameter-declaration ) compound-statement
  1575. /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
  1576. /// catch-parameter-declaration:
  1577. /// parameter-declaration
  1578. /// '...' [OBJC2]
  1579. ///
  1580. StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
  1581. bool catch_or_finally_seen = false;
  1582. ConsumeToken(); // consume try
  1583. if (Tok.isNot(tok::l_brace)) {
  1584. Diag(Tok, diag::err_expected_lbrace);
  1585. return StmtError();
  1586. }
  1587. StmtVector CatchStmts(Actions);
  1588. StmtResult FinallyStmt;
  1589. ParseScope TryScope(this, Scope::DeclScope);
  1590. StmtResult TryBody(ParseCompoundStatementBody());
  1591. TryScope.Exit();
  1592. if (TryBody.isInvalid())
  1593. TryBody = Actions.ActOnNullStmt(Tok.getLocation());
  1594. while (Tok.is(tok::at)) {
  1595. // At this point, we need to lookahead to determine if this @ is the start
  1596. // of an @catch or @finally. We don't want to consume the @ token if this
  1597. // is an @try or @encode or something else.
  1598. Token AfterAt = GetLookAheadToken(1);
  1599. if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
  1600. !AfterAt.isObjCAtKeyword(tok::objc_finally))
  1601. break;
  1602. SourceLocation AtCatchFinallyLoc = ConsumeToken();
  1603. if (Tok.isObjCAtKeyword(tok::objc_catch)) {
  1604. Decl *FirstPart = 0;
  1605. ConsumeToken(); // consume catch
  1606. if (Tok.is(tok::l_paren)) {
  1607. ConsumeParen();
  1608. ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope);
  1609. if (Tok.isNot(tok::ellipsis)) {
  1610. DeclSpec DS(AttrFactory);
  1611. ParseDeclarationSpecifiers(DS);
  1612. Declarator ParmDecl(DS, Declarator::ObjCCatchContext);
  1613. ParseDeclarator(ParmDecl);
  1614. // Inform the actions module about the declarator, so it
  1615. // gets added to the current scope.
  1616. FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
  1617. } else
  1618. ConsumeToken(); // consume '...'
  1619. SourceLocation RParenLoc;
  1620. if (Tok.is(tok::r_paren))
  1621. RParenLoc = ConsumeParen();
  1622. else // Skip over garbage, until we get to ')'. Eat the ')'.
  1623. SkipUntil(tok::r_paren, true, false);
  1624. StmtResult CatchBody(true);
  1625. if (Tok.is(tok::l_brace))
  1626. CatchBody = ParseCompoundStatementBody();
  1627. else
  1628. Diag(Tok, diag::err_expected_lbrace);
  1629. if (CatchBody.isInvalid())
  1630. CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
  1631. StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
  1632. RParenLoc,
  1633. FirstPart,
  1634. CatchBody.take());
  1635. if (!Catch.isInvalid())
  1636. CatchStmts.push_back(Catch.release());
  1637. } else {
  1638. Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
  1639. << "@catch clause";
  1640. return StmtError();
  1641. }
  1642. catch_or_finally_seen = true;
  1643. } else {
  1644. assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
  1645. ConsumeToken(); // consume finally
  1646. ParseScope FinallyScope(this, Scope::DeclScope);
  1647. StmtResult FinallyBody(true);
  1648. if (Tok.is(tok::l_brace))
  1649. FinallyBody = ParseCompoundStatementBody();
  1650. else
  1651. Diag(Tok, diag::err_expected_lbrace);
  1652. if (FinallyBody.isInvalid())
  1653. FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
  1654. FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
  1655. FinallyBody.take());
  1656. catch_or_finally_seen = true;
  1657. break;
  1658. }
  1659. }
  1660. if (!catch_or_finally_seen) {
  1661. Diag(atLoc, diag::err_missing_catch_finally);
  1662. return StmtError();
  1663. }
  1664. return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.take(),
  1665. move_arg(CatchStmts),
  1666. FinallyStmt.take());
  1667. }
  1668. /// objc-autoreleasepool-statement:
  1669. /// @autoreleasepool compound-statement
  1670. ///
  1671. StmtResult
  1672. Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
  1673. ConsumeToken(); // consume autoreleasepool
  1674. if (Tok.isNot(tok::l_brace)) {
  1675. Diag(Tok, diag::err_expected_lbrace);
  1676. return StmtError();
  1677. }
  1678. // Enter a scope to hold everything within the compound stmt. Compound
  1679. // statements can always hold declarations.
  1680. ParseScope BodyScope(this, Scope::DeclScope);
  1681. StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
  1682. BodyScope.Exit();
  1683. if (AutoreleasePoolBody.isInvalid())
  1684. AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
  1685. return Actions.ActOnObjCAutoreleasePoolStmt(atLoc,
  1686. AutoreleasePoolBody.take());
  1687. }
  1688. /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
  1689. ///
  1690. Decl *Parser::ParseObjCMethodDefinition() {
  1691. Decl *MDecl = ParseObjCMethodPrototype();
  1692. PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(),
  1693. "parsing Objective-C method");
  1694. // parse optional ';'
  1695. if (Tok.is(tok::semi)) {
  1696. if (CurParsedObjCImpl) {
  1697. Diag(Tok, diag::warn_semicolon_before_method_body)
  1698. << FixItHint::CreateRemoval(Tok.getLocation());
  1699. }
  1700. ConsumeToken();
  1701. }
  1702. // We should have an opening brace now.
  1703. if (Tok.isNot(tok::l_brace)) {
  1704. Diag(Tok, diag::err_expected_method_body);
  1705. // Skip over garbage, until we get to '{'. Don't eat the '{'.
  1706. SkipUntil(tok::l_brace, true, true);
  1707. // If we didn't find the '{', bail out.
  1708. if (Tok.isNot(tok::l_brace))
  1709. return 0;
  1710. }
  1711. if (!MDecl) {
  1712. ConsumeBrace();
  1713. SkipUntil(tok::r_brace, /*StopAtSemi=*/false);
  1714. return 0;
  1715. }
  1716. // Allow the rest of sema to find private method decl implementations.
  1717. Actions.AddAnyMethodToGlobalPool(MDecl);
  1718. if (CurParsedObjCImpl) {
  1719. // Consume the tokens and store them for later parsing.
  1720. LexedMethod* LM = new LexedMethod(this, MDecl);
  1721. CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM);
  1722. CachedTokens &Toks = LM->Toks;
  1723. // Begin by storing the '{' token.
  1724. Toks.push_back(Tok);
  1725. ConsumeBrace();
  1726. // Consume everything up to (and including) the matching right brace.
  1727. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
  1728. } else {
  1729. ConsumeBrace();
  1730. SkipUntil(tok::r_brace, /*StopAtSemi=*/false);
  1731. }
  1732. return MDecl;
  1733. }
  1734. StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
  1735. if (Tok.is(tok::code_completion)) {
  1736. Actions.CodeCompleteObjCAtStatement(getCurScope());
  1737. cutOffParsing();
  1738. return StmtError();
  1739. }
  1740. if (Tok.isObjCAtKeyword(tok::objc_try))
  1741. return ParseObjCTryStmt(AtLoc);
  1742. if (Tok.isObjCAtKeyword(tok::objc_throw))
  1743. return ParseObjCThrowStmt(AtLoc);
  1744. if (Tok.isObjCAtKeyword(tok::objc_synchronized))
  1745. return ParseObjCSynchronizedStmt(AtLoc);
  1746. if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
  1747. return ParseObjCAutoreleasePoolStmt(AtLoc);
  1748. ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
  1749. if (Res.isInvalid()) {
  1750. // If the expression is invalid, skip ahead to the next semicolon. Not
  1751. // doing this opens us up to the possibility of infinite loops if
  1752. // ParseExpression does not consume any tokens.
  1753. SkipUntil(tok::semi);
  1754. return StmtError();
  1755. }
  1756. // Otherwise, eat the semicolon.
  1757. ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
  1758. return Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.take()));
  1759. }
  1760. ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
  1761. switch (Tok.getKind()) {
  1762. case tok::code_completion:
  1763. Actions.CodeCompleteObjCAtExpression(getCurScope());
  1764. cutOffParsing();
  1765. return ExprError();
  1766. case tok::minus:
  1767. case tok::plus: {
  1768. tok::TokenKind Kind = Tok.getKind();
  1769. SourceLocation OpLoc = ConsumeToken();
  1770. if (!Tok.is(tok::numeric_constant)) {
  1771. const char *Symbol = 0;
  1772. switch (Kind) {
  1773. case tok::minus: Symbol = "-"; break;
  1774. case tok::plus: Symbol = "+"; break;
  1775. default: llvm_unreachable("missing unary operator case");
  1776. }
  1777. Diag(Tok, diag::err_nsnumber_nonliteral_unary)
  1778. << Symbol;
  1779. return ExprError();
  1780. }
  1781. ExprResult Lit(Actions.ActOnNumericConstant(Tok));
  1782. if (Lit.isInvalid()) {
  1783. return move(Lit);
  1784. }
  1785. ConsumeToken(); // Consume the literal token.
  1786. Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.take());
  1787. if (Lit.isInvalid())
  1788. return move(Lit);
  1789. return ParsePostfixExpressionSuffix(
  1790. Actions.BuildObjCNumericLiteral(AtLoc, Lit.take()));
  1791. }
  1792. case tok::string_literal: // primary-expression: string-literal
  1793. case tok::wide_string_literal:
  1794. return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
  1795. case tok::char_constant:
  1796. return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc));
  1797. case tok::numeric_constant:
  1798. return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc));
  1799. case tok::kw_true: // Objective-C++, etc.
  1800. case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes
  1801. return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true));
  1802. case tok::kw_false: // Objective-C++, etc.
  1803. case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no
  1804. return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false));
  1805. case tok::l_square:
  1806. // Objective-C array literal
  1807. return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc));
  1808. case tok::l_brace:
  1809. // Objective-C dictionary literal
  1810. return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc));
  1811. default:
  1812. if (Tok.getIdentifierInfo() == 0)
  1813. return ExprError(Diag(AtLoc, diag::err_unexpected_at));
  1814. switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
  1815. case tok::objc_encode:
  1816. return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
  1817. case tok::objc_protocol:
  1818. return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
  1819. case tok::objc_selector:
  1820. return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
  1821. default:
  1822. return ExprError(Diag(AtLoc, diag::err_unexpected_at));
  1823. }
  1824. }
  1825. }
  1826. /// \brirg Parse the receiver of an Objective-C++ message send.
  1827. ///
  1828. /// This routine parses the receiver of a message send in
  1829. /// Objective-C++ either as a type or as an expression. Note that this
  1830. /// routine must not be called to parse a send to 'super', since it
  1831. /// has no way to return such a result.
  1832. ///
  1833. /// \param IsExpr Whether the receiver was parsed as an expression.
  1834. ///
  1835. /// \param TypeOrExpr If the receiver was parsed as an expression (\c
  1836. /// IsExpr is true), the parsed expression. If the receiver was parsed
  1837. /// as a type (\c IsExpr is false), the parsed type.
  1838. ///
  1839. /// \returns True if an error occurred during parsing or semantic
  1840. /// analysis, in which case the arguments do not have valid
  1841. /// values. Otherwise, returns false for a successful parse.
  1842. ///
  1843. /// objc-receiver: [C++]
  1844. /// 'super' [not parsed here]
  1845. /// expression
  1846. /// simple-type-specifier
  1847. /// typename-specifier
  1848. bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
  1849. InMessageExpressionRAIIObject InMessage(*this, true);
  1850. if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
  1851. Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope))
  1852. TryAnnotateTypeOrScopeToken();
  1853. if (!isCXXSimpleTypeSpecifier()) {
  1854. // objc-receiver:
  1855. // expression
  1856. ExprResult Receiver = ParseExpression();
  1857. if (Receiver.isInvalid())
  1858. return true;
  1859. IsExpr = true;
  1860. TypeOrExpr = Receiver.take();
  1861. return false;
  1862. }
  1863. // objc-receiver:
  1864. // typename-specifier
  1865. // simple-type-specifier
  1866. // expression (that starts with one of the above)
  1867. DeclSpec DS(AttrFactory);
  1868. ParseCXXSimpleTypeSpecifier(DS);
  1869. if (Tok.is(tok::l_paren)) {
  1870. // If we see an opening parentheses at this point, we are
  1871. // actually parsing an expression that starts with a
  1872. // function-style cast, e.g.,
  1873. //
  1874. // postfix-expression:
  1875. // simple-type-specifier ( expression-list [opt] )
  1876. // typename-specifier ( expression-list [opt] )
  1877. //
  1878. // Parse the remainder of this case, then the (optional)
  1879. // postfix-expression suffix, followed by the (optional)
  1880. // right-hand side of the binary expression. We have an
  1881. // instance method.
  1882. ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
  1883. if (!Receiver.isInvalid())
  1884. Receiver = ParsePostfixExpressionSuffix(Receiver.take());
  1885. if (!Receiver.isInvalid())
  1886. Receiver = ParseRHSOfBinaryExpression(Receiver.take(), prec::Comma);
  1887. if (Receiver.isInvalid())
  1888. return true;
  1889. IsExpr = true;
  1890. TypeOrExpr = Receiver.take();
  1891. return false;
  1892. }
  1893. // We have a class message. Turn the simple-type-specifier or
  1894. // typename-specifier we parsed into a type and parse the
  1895. // remainder of the class message.
  1896. Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
  1897. TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
  1898. if (Type.isInvalid())
  1899. return true;
  1900. IsExpr = false;
  1901. TypeOrExpr = Type.get().getAsOpaquePtr();
  1902. return false;
  1903. }
  1904. /// \brief Determine whether the parser is currently referring to a an
  1905. /// Objective-C message send, using a simplified heuristic to avoid overhead.
  1906. ///
  1907. /// This routine will only return true for a subset of valid message-send
  1908. /// expressions.
  1909. bool Parser::isSimpleObjCMessageExpression() {
  1910. assert(Tok.is(tok::l_square) && getLangOpts().ObjC1 &&
  1911. "Incorrect start for isSimpleObjCMessageExpression");
  1912. return GetLookAheadToken(1).is(tok::identifier) &&
  1913. GetLookAheadToken(2).is(tok::identifier);
  1914. }
  1915. bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
  1916. if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) ||
  1917. InMessageExpression)
  1918. return false;
  1919. ParsedType Type;
  1920. if (Tok.is(tok::annot_typename))
  1921. Type = getTypeAnnotation(Tok);
  1922. else if (Tok.is(tok::identifier))
  1923. Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
  1924. getCurScope());
  1925. else
  1926. return false;
  1927. if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
  1928. const Token &AfterNext = GetLookAheadToken(2);
  1929. if (AfterNext.is(tok::colon) || AfterNext.is(tok::r_square)) {
  1930. if (Tok.is(tok::identifier))
  1931. TryAnnotateTypeOrScopeToken();
  1932. return Tok.is(tok::annot_typename);
  1933. }
  1934. }
  1935. return false;
  1936. }
  1937. /// objc-message-expr:
  1938. /// '[' objc-receiver objc-message-args ']'
  1939. ///
  1940. /// objc-receiver: [C]
  1941. /// 'super'
  1942. /// expression
  1943. /// class-name
  1944. /// type-name
  1945. ///
  1946. ExprResult Parser::ParseObjCMessageExpression() {
  1947. assert(Tok.is(tok::l_square) && "'[' expected");
  1948. SourceLocation LBracLoc = ConsumeBracket(); // consume '['
  1949. if (Tok.is(tok::code_completion)) {
  1950. Actions.CodeCompleteObjCMessageReceiver(getCurScope());
  1951. cutOffParsing();
  1952. return ExprError();
  1953. }
  1954. InMessageExpressionRAIIObject InMessage(*this, true);
  1955. if (getLangOpts().CPlusPlus) {
  1956. // We completely separate the C and C++ cases because C++ requires
  1957. // more complicated (read: slower) parsing.
  1958. // Handle send to super.
  1959. // FIXME: This doesn't benefit from the same typo-correction we
  1960. // get in Objective-C.
  1961. if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
  1962. NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
  1963. return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
  1964. ParsedType(), 0);
  1965. // Parse the receiver, which is either a type or an expression.
  1966. bool IsExpr;
  1967. void *TypeOrExpr = NULL;
  1968. if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
  1969. SkipUntil(tok::r_square);
  1970. return ExprError();
  1971. }
  1972. if (IsExpr)
  1973. return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
  1974. ParsedType(),
  1975. static_cast<Expr*>(TypeOrExpr));
  1976. return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
  1977. ParsedType::getFromOpaquePtr(TypeOrExpr),
  1978. 0);
  1979. }
  1980. if (Tok.is(tok::identifier)) {
  1981. IdentifierInfo *Name = Tok.getIdentifierInfo();
  1982. SourceLocation NameLoc = Tok.getLocation();
  1983. ParsedType ReceiverType;
  1984. switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
  1985. Name == Ident_super,
  1986. NextToken().is(tok::period),
  1987. ReceiverType)) {
  1988. case Sema::ObjCSuperMessage:
  1989. return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
  1990. ParsedType(), 0);
  1991. case Sema::ObjCClassMessage:
  1992. if (!ReceiverType) {
  1993. SkipUntil(tok::r_square);
  1994. return ExprError();
  1995. }
  1996. ConsumeToken(); // the type name
  1997. return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
  1998. ReceiverType, 0);
  1999. case Sema::ObjCInstanceMessage:
  2000. // Fall through to parse an expression.
  2001. break;
  2002. }
  2003. }
  2004. // Otherwise, an arbitrary expression can be the receiver of a send.
  2005. ExprResult Res(ParseExpression());
  2006. if (Res.isInvalid()) {
  2007. SkipUntil(tok::r_square);
  2008. return move(Res);
  2009. }
  2010. return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
  2011. ParsedType(), Res.take());
  2012. }
  2013. /// \brief Parse the remainder of an Objective-C message following the
  2014. /// '[' objc-receiver.
  2015. ///
  2016. /// This routine handles sends to super, class messages (sent to a
  2017. /// class name), and instance messages (sent to an object), and the
  2018. /// target is represented by \p SuperLoc, \p ReceiverType, or \p
  2019. /// ReceiverExpr, respectively. Only one of these parameters may have
  2020. /// a valid value.
  2021. ///
  2022. /// \param LBracLoc The location of the opening '['.
  2023. ///
  2024. /// \param SuperLoc If this is a send to 'super', the location of the
  2025. /// 'super' keyword that indicates a send to the superclass.
  2026. ///
  2027. /// \param ReceiverType If this is a class message, the type of the
  2028. /// class we are sending a message to.
  2029. ///
  2030. /// \param ReceiverExpr If this is an instance message, the expression
  2031. /// used to compute the receiver object.
  2032. ///
  2033. /// objc-message-args:
  2034. /// objc-selector
  2035. /// objc-keywordarg-list
  2036. ///
  2037. /// objc-keywordarg-list:
  2038. /// objc-keywordarg
  2039. /// objc-keywordarg-list objc-keywordarg
  2040. ///
  2041. /// objc-keywordarg:
  2042. /// selector-name[opt] ':' objc-keywordexpr
  2043. ///
  2044. /// objc-keywordexpr:
  2045. /// nonempty-expr-list
  2046. ///
  2047. /// nonempty-expr-list:
  2048. /// assignment-expression
  2049. /// nonempty-expr-list , assignment-expression
  2050. ///
  2051. ExprResult
  2052. Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
  2053. SourceLocation SuperLoc,
  2054. ParsedType ReceiverType,
  2055. ExprArg ReceiverExpr) {
  2056. InMessageExpressionRAIIObject InMessage(*this, true);
  2057. if (Tok.is(tok::code_completion)) {
  2058. if (SuperLoc.isValid())
  2059. Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 0, 0,
  2060. false);
  2061. else if (ReceiverType)
  2062. Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, 0, 0,
  2063. false);
  2064. else
  2065. Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
  2066. 0, 0, false);
  2067. cutOffParsing();
  2068. return ExprError();
  2069. }
  2070. // Parse objc-selector
  2071. SourceLocation Loc;
  2072. IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
  2073. SmallVector<IdentifierInfo *, 12> KeyIdents;
  2074. SmallVector<SourceLocation, 12> KeyLocs;
  2075. ExprVector KeyExprs(Actions);
  2076. if (Tok.is(tok::colon)) {
  2077. while (1) {
  2078. // Each iteration parses a single keyword argument.
  2079. KeyIdents.push_back(selIdent);
  2080. KeyLocs.push_back(Loc);
  2081. if (Tok.isNot(tok::colon)) {
  2082. Diag(Tok, diag::err_expected_colon);
  2083. // We must manually skip to a ']', otherwise the expression skipper will
  2084. // stop at the ']' when it skips to the ';'. We want it to skip beyond
  2085. // the enclosing expression.
  2086. SkipUntil(tok::r_square);
  2087. return ExprError();
  2088. }
  2089. ConsumeToken(); // Eat the ':'.
  2090. /// Parse the expression after ':'
  2091. if (Tok.is(tok::code_completion)) {
  2092. if (SuperLoc.isValid())
  2093. Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
  2094. KeyIdents.data(),
  2095. KeyIdents.size(),
  2096. /*AtArgumentEpression=*/true);
  2097. else if (ReceiverType)
  2098. Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
  2099. KeyIdents.data(),
  2100. KeyIdents.size(),
  2101. /*AtArgumentEpression=*/true);
  2102. else
  2103. Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
  2104. KeyIdents.data(),
  2105. KeyIdents.size(),
  2106. /*AtArgumentEpression=*/true);
  2107. cutOffParsing();
  2108. return ExprError();
  2109. }
  2110. ExprResult Res(ParseAssignmentExpression());
  2111. if (Res.isInvalid()) {
  2112. // We must manually skip to a ']', otherwise the expression skipper will
  2113. // stop at the ']' when it skips to the ';'. We want it to skip beyond
  2114. // the enclosing expression.
  2115. SkipUntil(tok::r_square);
  2116. return move(Res);
  2117. }
  2118. // We have a valid expression.
  2119. KeyExprs.push_back(Res.release());
  2120. // Code completion after each argument.
  2121. if (Tok.is(tok::code_completion)) {
  2122. if (SuperLoc.isValid())
  2123. Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
  2124. KeyIdents.data(),
  2125. KeyIdents.size(),
  2126. /*AtArgumentEpression=*/false);
  2127. else if (ReceiverType)
  2128. Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
  2129. KeyIdents.data(),
  2130. KeyIdents.size(),
  2131. /*AtArgumentEpression=*/false);
  2132. else
  2133. Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
  2134. KeyIdents.data(),
  2135. KeyIdents.size(),
  2136. /*AtArgumentEpression=*/false);
  2137. cutOffParsing();
  2138. return ExprError();
  2139. }
  2140. // Check for another keyword selector.
  2141. selIdent = ParseObjCSelectorPiece(Loc);
  2142. if (!selIdent && Tok.isNot(tok::colon))
  2143. break;
  2144. // We have a selector or a colon, continue parsing.
  2145. }
  2146. // Parse the, optional, argument list, comma separated.
  2147. while (Tok.is(tok::comma)) {
  2148. ConsumeToken(); // Eat the ','.
  2149. /// Parse the expression after ','
  2150. ExprResult Res(ParseAssignmentExpression());
  2151. if (Res.isInvalid()) {
  2152. // We must manually skip to a ']', otherwise the expression skipper will
  2153. // stop at the ']' when it skips to the ';'. We want it to skip beyond
  2154. // the enclosing expression.
  2155. SkipUntil(tok::r_square);
  2156. return move(Res);
  2157. }
  2158. // We have a valid expression.
  2159. KeyExprs.push_back(Res.release());
  2160. }
  2161. } else if (!selIdent) {
  2162. Diag(Tok, diag::err_expected_ident); // missing selector name.
  2163. // We must manually skip to a ']', otherwise the expression skipper will
  2164. // stop at the ']' when it skips to the ';'. We want it to skip beyond
  2165. // the enclosing expression.
  2166. SkipUntil(tok::r_square);
  2167. return ExprError();
  2168. }
  2169. if (Tok.isNot(tok::r_square)) {
  2170. if (Tok.is(tok::identifier))
  2171. Diag(Tok, diag::err_expected_colon);
  2172. else
  2173. Diag(Tok, diag::err_expected_rsquare);
  2174. // We must manually skip to a ']', otherwise the expression skipper will
  2175. // stop at the ']' when it skips to the ';'. We want it to skip beyond
  2176. // the enclosing expression.
  2177. SkipUntil(tok::r_square);
  2178. return ExprError();
  2179. }
  2180. SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
  2181. unsigned nKeys = KeyIdents.size();
  2182. if (nKeys == 0) {
  2183. KeyIdents.push_back(selIdent);
  2184. KeyLocs.push_back(Loc);
  2185. }
  2186. Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
  2187. if (SuperLoc.isValid())
  2188. return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
  2189. LBracLoc, KeyLocs, RBracLoc,
  2190. MultiExprArg(Actions,
  2191. KeyExprs.take(),
  2192. KeyExprs.size()));
  2193. else if (ReceiverType)
  2194. return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
  2195. LBracLoc, KeyLocs, RBracLoc,
  2196. MultiExprArg(Actions,
  2197. KeyExprs.take(),
  2198. KeyExprs.size()));
  2199. return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
  2200. LBracLoc, KeyLocs, RBracLoc,
  2201. MultiExprArg(Actions,
  2202. KeyExprs.take(),
  2203. KeyExprs.size()));
  2204. }
  2205. ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
  2206. ExprResult Res(ParseStringLiteralExpression());
  2207. if (Res.isInvalid()) return move(Res);
  2208. // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string
  2209. // expressions. At this point, we know that the only valid thing that starts
  2210. // with '@' is an @"".
  2211. SmallVector<SourceLocation, 4> AtLocs;
  2212. ExprVector AtStrings(Actions);
  2213. AtLocs.push_back(AtLoc);
  2214. AtStrings.push_back(Res.release());
  2215. while (Tok.is(tok::at)) {
  2216. AtLocs.push_back(ConsumeToken()); // eat the @.
  2217. // Invalid unless there is a string literal.
  2218. if (!isTokenStringLiteral())
  2219. return ExprError(Diag(Tok, diag::err_objc_concat_string));
  2220. ExprResult Lit(ParseStringLiteralExpression());
  2221. if (Lit.isInvalid())
  2222. return move(Lit);
  2223. AtStrings.push_back(Lit.release());
  2224. }
  2225. return Owned(Actions.ParseObjCStringLiteral(&AtLocs[0], AtStrings.take(),
  2226. AtStrings.size()));
  2227. }
  2228. /// ParseObjCBooleanLiteral -
  2229. /// objc-scalar-literal : '@' boolean-keyword
  2230. /// ;
  2231. /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
  2232. /// ;
  2233. ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc,
  2234. bool ArgValue) {
  2235. SourceLocation EndLoc = ConsumeToken(); // consume the keyword.
  2236. return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue);
  2237. }
  2238. /// ParseObjCCharacterLiteral -
  2239. /// objc-scalar-literal : '@' character-literal
  2240. /// ;
  2241. ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) {
  2242. ExprResult Lit(Actions.ActOnCharacterConstant(Tok));
  2243. if (Lit.isInvalid()) {
  2244. return move(Lit);
  2245. }
  2246. ConsumeToken(); // Consume the literal token.
  2247. return Owned(Actions.BuildObjCNumericLiteral(AtLoc, Lit.take()));
  2248. }
  2249. /// ParseObjCNumericLiteral -
  2250. /// objc-scalar-literal : '@' scalar-literal
  2251. /// ;
  2252. /// scalar-literal : | numeric-constant /* any numeric constant. */
  2253. /// ;
  2254. ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) {
  2255. ExprResult Lit(Actions.ActOnNumericConstant(Tok));
  2256. if (Lit.isInvalid()) {
  2257. return move(Lit);
  2258. }
  2259. ConsumeToken(); // Consume the literal token.
  2260. return Owned(Actions.BuildObjCNumericLiteral(AtLoc, Lit.take()));
  2261. }
  2262. ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) {
  2263. ExprVector ElementExprs(Actions); // array elements.
  2264. ConsumeBracket(); // consume the l_square.
  2265. while (Tok.isNot(tok::r_square)) {
  2266. // Parse list of array element expressions (all must be id types).
  2267. ExprResult Res(ParseAssignmentExpression());
  2268. if (Res.isInvalid()) {
  2269. // We must manually skip to a ']', otherwise the expression skipper will
  2270. // stop at the ']' when it skips to the ';'. We want it to skip beyond
  2271. // the enclosing expression.
  2272. SkipUntil(tok::r_square);
  2273. return move(Res);
  2274. }
  2275. // Parse the ellipsis that indicates a pack expansion.
  2276. if (Tok.is(tok::ellipsis))
  2277. Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken());
  2278. if (Res.isInvalid())
  2279. return true;
  2280. ElementExprs.push_back(Res.release());
  2281. if (Tok.is(tok::comma))
  2282. ConsumeToken(); // Eat the ','.
  2283. else if (Tok.isNot(tok::r_square))
  2284. return ExprError(Diag(Tok, diag::err_expected_rsquare_or_comma));
  2285. }
  2286. SourceLocation EndLoc = ConsumeBracket(); // location of ']'
  2287. MultiExprArg Args(Actions, ElementExprs.take(), ElementExprs.size());
  2288. return Owned(Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args));
  2289. }
  2290. ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) {
  2291. SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements.
  2292. ConsumeBrace(); // consume the l_square.
  2293. while (Tok.isNot(tok::r_brace)) {
  2294. // Parse the comma separated key : value expressions.
  2295. ExprResult KeyExpr;
  2296. {
  2297. ColonProtectionRAIIObject X(*this);
  2298. KeyExpr = ParseAssignmentExpression();
  2299. if (KeyExpr.isInvalid()) {
  2300. // We must manually skip to a '}', otherwise the expression skipper will
  2301. // stop at the '}' when it skips to the ';'. We want it to skip beyond
  2302. // the enclosing expression.
  2303. SkipUntil(tok::r_brace);
  2304. return move(KeyExpr);
  2305. }
  2306. }
  2307. if (Tok.is(tok::colon)) {
  2308. ConsumeToken();
  2309. } else {
  2310. return ExprError(Diag(Tok, diag::err_expected_colon));
  2311. }
  2312. ExprResult ValueExpr(ParseAssignmentExpression());
  2313. if (ValueExpr.isInvalid()) {
  2314. // We must manually skip to a '}', otherwise the expression skipper will
  2315. // stop at the '}' when it skips to the ';'. We want it to skip beyond
  2316. // the enclosing expression.
  2317. SkipUntil(tok::r_brace);
  2318. return move(ValueExpr);
  2319. }
  2320. // Parse the ellipsis that designates this as a pack expansion.
  2321. SourceLocation EllipsisLoc;
  2322. if (Tok.is(tok::ellipsis) && getLangOpts().CPlusPlus)
  2323. EllipsisLoc = ConsumeToken();
  2324. // We have a valid expression. Collect it in a vector so we can
  2325. // build the argument list.
  2326. ObjCDictionaryElement Element = {
  2327. KeyExpr.get(), ValueExpr.get(), EllipsisLoc, llvm::Optional<unsigned>()
  2328. };
  2329. Elements.push_back(Element);
  2330. if (Tok.is(tok::comma))
  2331. ConsumeToken(); // Eat the ','.
  2332. else if (Tok.isNot(tok::r_brace))
  2333. return ExprError(Diag(Tok, diag::err_expected_rbrace_or_comma));
  2334. }
  2335. SourceLocation EndLoc = ConsumeBrace();
  2336. // Create the ObjCDictionaryLiteral.
  2337. return Owned(Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc),
  2338. Elements.data(),
  2339. Elements.size()));
  2340. }
  2341. /// objc-encode-expression:
  2342. /// @encode ( type-name )
  2343. ExprResult
  2344. Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
  2345. assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
  2346. SourceLocation EncLoc = ConsumeToken();
  2347. if (Tok.isNot(tok::l_paren))
  2348. return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
  2349. BalancedDelimiterTracker T(*this, tok::l_paren);
  2350. T.consumeOpen();
  2351. TypeResult Ty = ParseTypeName();
  2352. T.consumeClose();
  2353. if (Ty.isInvalid())
  2354. return ExprError();
  2355. return Owned(Actions.ParseObjCEncodeExpression(AtLoc, EncLoc,
  2356. T.getOpenLocation(), Ty.get(),
  2357. T.getCloseLocation()));
  2358. }
  2359. /// objc-protocol-expression
  2360. /// @protocol ( protocol-name )
  2361. ExprResult
  2362. Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
  2363. SourceLocation ProtoLoc = ConsumeToken();
  2364. if (Tok.isNot(tok::l_paren))
  2365. return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
  2366. BalancedDelimiterTracker T(*this, tok::l_paren);
  2367. T.consumeOpen();
  2368. if (Tok.isNot(tok::identifier))
  2369. return ExprError(Diag(Tok, diag::err_expected_ident));
  2370. IdentifierInfo *protocolId = Tok.getIdentifierInfo();
  2371. ConsumeToken();
  2372. T.consumeClose();
  2373. return Owned(Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
  2374. T.getOpenLocation(),
  2375. T.getCloseLocation()));
  2376. }
  2377. /// objc-selector-expression
  2378. /// @selector '(' objc-keyword-selector ')'
  2379. ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
  2380. SourceLocation SelectorLoc = ConsumeToken();
  2381. if (Tok.isNot(tok::l_paren))
  2382. return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
  2383. SmallVector<IdentifierInfo *, 12> KeyIdents;
  2384. SourceLocation sLoc;
  2385. BalancedDelimiterTracker T(*this, tok::l_paren);
  2386. T.consumeOpen();
  2387. if (Tok.is(tok::code_completion)) {
  2388. Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(),
  2389. KeyIdents.size());
  2390. cutOffParsing();
  2391. return ExprError();
  2392. }
  2393. IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
  2394. if (!SelIdent && // missing selector name.
  2395. Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
  2396. return ExprError(Diag(Tok, diag::err_expected_ident));
  2397. KeyIdents.push_back(SelIdent);
  2398. unsigned nColons = 0;
  2399. if (Tok.isNot(tok::r_paren)) {
  2400. while (1) {
  2401. if (Tok.is(tok::coloncolon)) { // Handle :: in C++.
  2402. ++nColons;
  2403. KeyIdents.push_back(0);
  2404. } else if (Tok.isNot(tok::colon))
  2405. return ExprError(Diag(Tok, diag::err_expected_colon));
  2406. ++nColons;
  2407. ConsumeToken(); // Eat the ':' or '::'.
  2408. if (Tok.is(tok::r_paren))
  2409. break;
  2410. if (Tok.is(tok::code_completion)) {
  2411. Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(),
  2412. KeyIdents.size());
  2413. cutOffParsing();
  2414. return ExprError();
  2415. }
  2416. // Check for another keyword selector.
  2417. SourceLocation Loc;
  2418. SelIdent = ParseObjCSelectorPiece(Loc);
  2419. KeyIdents.push_back(SelIdent);
  2420. if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
  2421. break;
  2422. }
  2423. }
  2424. T.consumeClose();
  2425. Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
  2426. return Owned(Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
  2427. T.getOpenLocation(),
  2428. T.getCloseLocation()));
  2429. }
  2430. Decl *Parser::ParseLexedObjCMethodDefs(LexedMethod &LM) {
  2431. // Save the current token position.
  2432. SourceLocation OrigLoc = Tok.getLocation();
  2433. assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!");
  2434. // Append the current token at the end of the new token stream so that it
  2435. // doesn't get lost.
  2436. LM.Toks.push_back(Tok);
  2437. PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
  2438. // MDecl might be null due to error in method prototype, etc.
  2439. Decl *MDecl = LM.D;
  2440. // Consume the previously pushed token.
  2441. ConsumeAnyToken();
  2442. assert(Tok.is(tok::l_brace) && "Inline objective-c method not starting with '{'");
  2443. SourceLocation BraceLoc = Tok.getLocation();
  2444. // Enter a scope for the method body.
  2445. ParseScope BodyScope(this,
  2446. Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope);
  2447. // Tell the actions module that we have entered a method definition with the
  2448. // specified Declarator for the method.
  2449. Actions.ActOnStartOfObjCMethodDef(getCurScope(), MDecl);
  2450. if (PP.isCodeCompletionEnabled()) {
  2451. if (trySkippingFunctionBodyForCodeCompletion()) {
  2452. BodyScope.Exit();
  2453. return Actions.ActOnFinishFunctionBody(MDecl, 0);
  2454. }
  2455. }
  2456. StmtResult FnBody(ParseCompoundStatementBody());
  2457. // If the function body could not be parsed, make a bogus compoundstmt.
  2458. if (FnBody.isInvalid()) {
  2459. Sema::CompoundScopeRAII CompoundScope(Actions);
  2460. FnBody = Actions.ActOnCompoundStmt(BraceLoc, BraceLoc,
  2461. MultiStmtArg(Actions), false);
  2462. }
  2463. // Leave the function body scope.
  2464. BodyScope.Exit();
  2465. MDecl = Actions.ActOnFinishFunctionBody(MDecl, FnBody.take());
  2466. if (Tok.getLocation() != OrigLoc) {
  2467. // Due to parsing error, we either went over the cached tokens or
  2468. // there are still cached tokens left. If it's the latter case skip the
  2469. // leftover tokens.
  2470. // Since this is an uncommon situation that should be avoided, use the
  2471. // expensive isBeforeInTranslationUnit call.
  2472. if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
  2473. OrigLoc))
  2474. while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
  2475. ConsumeAnyToken();
  2476. }
  2477. return MDecl;
  2478. }