ParseObjc.cpp 99 KB

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