ParseObjc.cpp 131 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756
  1. //===--- ParseObjC.cpp - Objective C Parsing ------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the Objective-C portions of the Parser interface.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/ASTContext.h"
  13. #include "clang/AST/ODRDiagsEmitter.h"
  14. #include "clang/AST/PrettyDeclStackTrace.h"
  15. #include "clang/Basic/CharInfo.h"
  16. #include "clang/Basic/TargetInfo.h"
  17. #include "clang/Parse/ParseDiagnostic.h"
  18. #include "clang/Parse/Parser.h"
  19. #include "clang/Parse/RAIIObjectsForParser.h"
  20. #include "clang/Sema/DeclSpec.h"
  21. #include "clang/Sema/Scope.h"
  22. #include "llvm/ADT/SmallVector.h"
  23. #include "llvm/ADT/StringExtras.h"
  24. using namespace clang;
  25. /// Skips attributes after an Objective-C @ directive. Emits a diagnostic.
  26. void Parser::MaybeSkipAttributes(tok::ObjCKeywordKind Kind) {
  27. ParsedAttributes attrs(AttrFactory);
  28. if (Tok.is(tok::kw___attribute)) {
  29. if (Kind == tok::objc_interface || Kind == tok::objc_protocol)
  30. Diag(Tok, diag::err_objc_postfix_attribute_hint)
  31. << (Kind == tok::objc_protocol);
  32. else
  33. Diag(Tok, diag::err_objc_postfix_attribute);
  34. ParseGNUAttributes(attrs);
  35. }
  36. }
  37. /// ParseObjCAtDirectives - Handle parts of the external-declaration production:
  38. /// external-declaration: [C99 6.9]
  39. /// [OBJC] objc-class-definition
  40. /// [OBJC] objc-class-declaration
  41. /// [OBJC] objc-alias-declaration
  42. /// [OBJC] objc-protocol-definition
  43. /// [OBJC] objc-method-definition
  44. /// [OBJC] '@' 'end'
  45. Parser::DeclGroupPtrTy
  46. Parser::ParseObjCAtDirectives(ParsedAttributes &DeclAttrs,
  47. ParsedAttributes &DeclSpecAttrs) {
  48. DeclAttrs.takeAllFrom(DeclSpecAttrs);
  49. SourceLocation AtLoc = ConsumeToken(); // the "@"
  50. if (Tok.is(tok::code_completion)) {
  51. cutOffParsing();
  52. Actions.CodeCompleteObjCAtDirective(getCurScope());
  53. return nullptr;
  54. }
  55. switch (Tok.getObjCKeywordID()) {
  56. case tok::objc_interface:
  57. case tok::objc_protocol:
  58. case tok::objc_implementation:
  59. break;
  60. default:
  61. llvm::for_each(DeclAttrs, [this](const auto &Attr) {
  62. if (Attr.isGNUAttribute())
  63. Diag(Tok.getLocation(), diag::err_objc_unexpected_attr);
  64. });
  65. }
  66. Decl *SingleDecl = nullptr;
  67. switch (Tok.getObjCKeywordID()) {
  68. case tok::objc_class:
  69. return ParseObjCAtClassDeclaration(AtLoc);
  70. case tok::objc_interface:
  71. SingleDecl = ParseObjCAtInterfaceDeclaration(AtLoc, DeclAttrs);
  72. break;
  73. case tok::objc_protocol:
  74. return ParseObjCAtProtocolDeclaration(AtLoc, DeclAttrs);
  75. case tok::objc_implementation:
  76. return ParseObjCAtImplementationDeclaration(AtLoc, DeclAttrs);
  77. case tok::objc_end:
  78. return ParseObjCAtEndDeclaration(AtLoc);
  79. case tok::objc_compatibility_alias:
  80. SingleDecl = ParseObjCAtAliasDeclaration(AtLoc);
  81. break;
  82. case tok::objc_synthesize:
  83. SingleDecl = ParseObjCPropertySynthesize(AtLoc);
  84. break;
  85. case tok::objc_dynamic:
  86. SingleDecl = ParseObjCPropertyDynamic(AtLoc);
  87. break;
  88. case tok::objc_import:
  89. if (getLangOpts().Modules || getLangOpts().DebuggerSupport) {
  90. Sema::ModuleImportState IS = Sema::ModuleImportState::NotACXX20Module;
  91. SingleDecl = ParseModuleImport(AtLoc, IS);
  92. break;
  93. }
  94. Diag(AtLoc, diag::err_atimport);
  95. SkipUntil(tok::semi);
  96. return Actions.ConvertDeclToDeclGroup(nullptr);
  97. default:
  98. Diag(AtLoc, diag::err_unexpected_at);
  99. SkipUntil(tok::semi);
  100. SingleDecl = nullptr;
  101. break;
  102. }
  103. return Actions.ConvertDeclToDeclGroup(SingleDecl);
  104. }
  105. /// Class to handle popping type parameters when leaving the scope.
  106. class Parser::ObjCTypeParamListScope {
  107. Sema &Actions;
  108. Scope *S;
  109. ObjCTypeParamList *Params;
  110. public:
  111. ObjCTypeParamListScope(Sema &Actions, Scope *S)
  112. : Actions(Actions), S(S), Params(nullptr) {}
  113. ~ObjCTypeParamListScope() {
  114. leave();
  115. }
  116. void enter(ObjCTypeParamList *P) {
  117. assert(!Params);
  118. Params = P;
  119. }
  120. void leave() {
  121. if (Params)
  122. Actions.popObjCTypeParamList(S, Params);
  123. Params = nullptr;
  124. }
  125. };
  126. ///
  127. /// objc-class-declaration:
  128. /// '@' 'class' objc-class-forward-decl (',' objc-class-forward-decl)* ';'
  129. ///
  130. /// objc-class-forward-decl:
  131. /// identifier objc-type-parameter-list[opt]
  132. ///
  133. Parser::DeclGroupPtrTy
  134. Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) {
  135. ConsumeToken(); // the identifier "class"
  136. SmallVector<IdentifierInfo *, 8> ClassNames;
  137. SmallVector<SourceLocation, 8> ClassLocs;
  138. SmallVector<ObjCTypeParamList *, 8> ClassTypeParams;
  139. while (true) {
  140. MaybeSkipAttributes(tok::objc_class);
  141. if (expectIdentifier()) {
  142. SkipUntil(tok::semi);
  143. return Actions.ConvertDeclToDeclGroup(nullptr);
  144. }
  145. ClassNames.push_back(Tok.getIdentifierInfo());
  146. ClassLocs.push_back(Tok.getLocation());
  147. ConsumeToken();
  148. // Parse the optional objc-type-parameter-list.
  149. ObjCTypeParamList *TypeParams = nullptr;
  150. if (Tok.is(tok::less))
  151. TypeParams = parseObjCTypeParamList();
  152. ClassTypeParams.push_back(TypeParams);
  153. if (!TryConsumeToken(tok::comma))
  154. break;
  155. }
  156. // Consume the ';'.
  157. if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@class"))
  158. return Actions.ConvertDeclToDeclGroup(nullptr);
  159. return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(),
  160. ClassLocs.data(),
  161. ClassTypeParams,
  162. ClassNames.size());
  163. }
  164. void Parser::CheckNestedObjCContexts(SourceLocation AtLoc)
  165. {
  166. Sema::ObjCContainerKind ock = Actions.getObjCContainerKind();
  167. if (ock == Sema::OCK_None)
  168. return;
  169. Decl *Decl = Actions.getObjCDeclContext();
  170. if (CurParsedObjCImpl) {
  171. CurParsedObjCImpl->finish(AtLoc);
  172. } else {
  173. Actions.ActOnAtEnd(getCurScope(), AtLoc);
  174. }
  175. Diag(AtLoc, diag::err_objc_missing_end)
  176. << FixItHint::CreateInsertion(AtLoc, "@end\n");
  177. if (Decl)
  178. Diag(Decl->getBeginLoc(), diag::note_objc_container_start) << (int)ock;
  179. }
  180. ///
  181. /// objc-interface:
  182. /// objc-class-interface-attributes[opt] objc-class-interface
  183. /// objc-category-interface
  184. ///
  185. /// objc-class-interface:
  186. /// '@' 'interface' identifier objc-type-parameter-list[opt]
  187. /// objc-superclass[opt] objc-protocol-refs[opt]
  188. /// objc-class-instance-variables[opt]
  189. /// objc-interface-decl-list
  190. /// @end
  191. ///
  192. /// objc-category-interface:
  193. /// '@' 'interface' identifier objc-type-parameter-list[opt]
  194. /// '(' identifier[opt] ')' objc-protocol-refs[opt]
  195. /// objc-interface-decl-list
  196. /// @end
  197. ///
  198. /// objc-superclass:
  199. /// ':' identifier objc-type-arguments[opt]
  200. ///
  201. /// objc-class-interface-attributes:
  202. /// __attribute__((visibility("default")))
  203. /// __attribute__((visibility("hidden")))
  204. /// __attribute__((deprecated))
  205. /// __attribute__((unavailable))
  206. /// __attribute__((objc_exception)) - used by NSException on 64-bit
  207. /// __attribute__((objc_root_class))
  208. ///
  209. Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
  210. ParsedAttributes &attrs) {
  211. assert(Tok.isObjCAtKeyword(tok::objc_interface) &&
  212. "ParseObjCAtInterfaceDeclaration(): Expected @interface");
  213. CheckNestedObjCContexts(AtLoc);
  214. ConsumeToken(); // the "interface" identifier
  215. // Code completion after '@interface'.
  216. if (Tok.is(tok::code_completion)) {
  217. cutOffParsing();
  218. Actions.CodeCompleteObjCInterfaceDecl(getCurScope());
  219. return nullptr;
  220. }
  221. MaybeSkipAttributes(tok::objc_interface);
  222. if (expectIdentifier())
  223. return nullptr; // missing class or category name.
  224. // We have a class or category name - consume it.
  225. IdentifierInfo *nameId = Tok.getIdentifierInfo();
  226. SourceLocation nameLoc = ConsumeToken();
  227. // Parse the objc-type-parameter-list or objc-protocol-refs. For the latter
  228. // case, LAngleLoc will be valid and ProtocolIdents will capture the
  229. // protocol references (that have not yet been resolved).
  230. SourceLocation LAngleLoc, EndProtoLoc;
  231. SmallVector<IdentifierLocPair, 8> ProtocolIdents;
  232. ObjCTypeParamList *typeParameterList = nullptr;
  233. ObjCTypeParamListScope typeParamScope(Actions, getCurScope());
  234. if (Tok.is(tok::less))
  235. typeParameterList = parseObjCTypeParamListOrProtocolRefs(
  236. typeParamScope, LAngleLoc, ProtocolIdents, EndProtoLoc);
  237. if (Tok.is(tok::l_paren) &&
  238. !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category.
  239. BalancedDelimiterTracker T(*this, tok::l_paren);
  240. T.consumeOpen();
  241. SourceLocation categoryLoc;
  242. IdentifierInfo *categoryId = nullptr;
  243. if (Tok.is(tok::code_completion)) {
  244. cutOffParsing();
  245. Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc);
  246. return nullptr;
  247. }
  248. // For ObjC2, the category name is optional (not an error).
  249. if (Tok.is(tok::identifier)) {
  250. categoryId = Tok.getIdentifierInfo();
  251. categoryLoc = ConsumeToken();
  252. }
  253. else if (!getLangOpts().ObjC) {
  254. Diag(Tok, diag::err_expected)
  255. << tok::identifier; // missing category name.
  256. return nullptr;
  257. }
  258. T.consumeClose();
  259. if (T.getCloseLocation().isInvalid())
  260. return nullptr;
  261. // Next, we need to check for any protocol references.
  262. assert(LAngleLoc.isInvalid() && "Cannot have already parsed protocols");
  263. SmallVector<Decl *, 8> ProtocolRefs;
  264. SmallVector<SourceLocation, 8> ProtocolLocs;
  265. if (Tok.is(tok::less) &&
  266. ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true, true,
  267. LAngleLoc, EndProtoLoc,
  268. /*consumeLastToken=*/true))
  269. return nullptr;
  270. ObjCCategoryDecl *CategoryType = Actions.ActOnStartCategoryInterface(
  271. AtLoc, nameId, nameLoc, typeParameterList, categoryId, categoryLoc,
  272. ProtocolRefs.data(), ProtocolRefs.size(), ProtocolLocs.data(),
  273. EndProtoLoc, attrs);
  274. if (Tok.is(tok::l_brace))
  275. ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, AtLoc);
  276. ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType);
  277. return CategoryType;
  278. }
  279. // Parse a class interface.
  280. IdentifierInfo *superClassId = nullptr;
  281. SourceLocation superClassLoc;
  282. SourceLocation typeArgsLAngleLoc;
  283. SmallVector<ParsedType, 4> typeArgs;
  284. SourceLocation typeArgsRAngleLoc;
  285. SmallVector<Decl *, 4> protocols;
  286. SmallVector<SourceLocation, 4> protocolLocs;
  287. if (Tok.is(tok::colon)) { // a super class is specified.
  288. ConsumeToken();
  289. // Code completion of superclass names.
  290. if (Tok.is(tok::code_completion)) {
  291. cutOffParsing();
  292. Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc);
  293. return nullptr;
  294. }
  295. if (expectIdentifier())
  296. return nullptr; // missing super class name.
  297. superClassId = Tok.getIdentifierInfo();
  298. superClassLoc = ConsumeToken();
  299. // Type arguments for the superclass or protocol conformances.
  300. if (Tok.is(tok::less)) {
  301. parseObjCTypeArgsOrProtocolQualifiers(
  302. nullptr, typeArgsLAngleLoc, typeArgs, typeArgsRAngleLoc, LAngleLoc,
  303. protocols, protocolLocs, EndProtoLoc,
  304. /*consumeLastToken=*/true,
  305. /*warnOnIncompleteProtocols=*/true);
  306. if (Tok.is(tok::eof))
  307. return nullptr;
  308. }
  309. }
  310. // Next, we need to check for any protocol references.
  311. if (LAngleLoc.isValid()) {
  312. if (!ProtocolIdents.empty()) {
  313. // We already parsed the protocols named when we thought we had a
  314. // type parameter list. Translate them into actual protocol references.
  315. for (const auto &pair : ProtocolIdents) {
  316. protocolLocs.push_back(pair.second);
  317. }
  318. Actions.FindProtocolDeclaration(/*WarnOnDeclarations=*/true,
  319. /*ForObjCContainer=*/true,
  320. ProtocolIdents, protocols);
  321. }
  322. } else if (protocols.empty() && Tok.is(tok::less) &&
  323. ParseObjCProtocolReferences(protocols, protocolLocs, true, true,
  324. LAngleLoc, EndProtoLoc,
  325. /*consumeLastToken=*/true)) {
  326. return nullptr;
  327. }
  328. if (Tok.isNot(tok::less))
  329. Actions.ActOnTypedefedProtocols(protocols, protocolLocs,
  330. superClassId, superClassLoc);
  331. Sema::SkipBodyInfo SkipBody;
  332. ObjCInterfaceDecl *ClsType = Actions.ActOnStartClassInterface(
  333. getCurScope(), AtLoc, nameId, nameLoc, typeParameterList, superClassId,
  334. superClassLoc, typeArgs,
  335. SourceRange(typeArgsLAngleLoc, typeArgsRAngleLoc), protocols.data(),
  336. protocols.size(), protocolLocs.data(), EndProtoLoc, attrs, &SkipBody);
  337. if (Tok.is(tok::l_brace))
  338. ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, AtLoc);
  339. ParseObjCInterfaceDeclList(tok::objc_interface, ClsType);
  340. if (SkipBody.CheckSameAsPrevious) {
  341. auto *PreviousDef = cast<ObjCInterfaceDecl>(SkipBody.Previous);
  342. if (Actions.ActOnDuplicateODRHashDefinition(ClsType, PreviousDef)) {
  343. ClsType->mergeDuplicateDefinitionWithCommon(PreviousDef->getDefinition());
  344. } else {
  345. ODRDiagsEmitter DiagsEmitter(Diags, Actions.getASTContext(),
  346. getPreprocessor().getLangOpts());
  347. DiagsEmitter.diagnoseMismatch(PreviousDef, ClsType);
  348. ClsType->setInvalidDecl();
  349. }
  350. }
  351. return ClsType;
  352. }
  353. /// Add an attribute for a context-sensitive type nullability to the given
  354. /// declarator.
  355. static void addContextSensitiveTypeNullability(Parser &P,
  356. Declarator &D,
  357. NullabilityKind nullability,
  358. SourceLocation nullabilityLoc,
  359. bool &addedToDeclSpec) {
  360. // Create the attribute.
  361. auto getNullabilityAttr = [&](AttributePool &Pool) -> ParsedAttr * {
  362. return Pool.create(P.getNullabilityKeyword(nullability),
  363. SourceRange(nullabilityLoc), nullptr, SourceLocation(),
  364. nullptr, 0, ParsedAttr::AS_ContextSensitiveKeyword);
  365. };
  366. if (D.getNumTypeObjects() > 0) {
  367. // Add the attribute to the declarator chunk nearest the declarator.
  368. D.getTypeObject(0).getAttrs().addAtEnd(
  369. getNullabilityAttr(D.getAttributePool()));
  370. } else if (!addedToDeclSpec) {
  371. // Otherwise, just put it on the declaration specifiers (if one
  372. // isn't there already).
  373. D.getMutableDeclSpec().getAttributes().addAtEnd(
  374. getNullabilityAttr(D.getMutableDeclSpec().getAttributes().getPool()));
  375. addedToDeclSpec = true;
  376. }
  377. }
  378. /// Parse an Objective-C type parameter list, if present, or capture
  379. /// the locations of the protocol identifiers for a list of protocol
  380. /// references.
  381. ///
  382. /// objc-type-parameter-list:
  383. /// '<' objc-type-parameter (',' objc-type-parameter)* '>'
  384. ///
  385. /// objc-type-parameter:
  386. /// objc-type-parameter-variance? identifier objc-type-parameter-bound[opt]
  387. ///
  388. /// objc-type-parameter-bound:
  389. /// ':' type-name
  390. ///
  391. /// objc-type-parameter-variance:
  392. /// '__covariant'
  393. /// '__contravariant'
  394. ///
  395. /// \param lAngleLoc The location of the starting '<'.
  396. ///
  397. /// \param protocolIdents Will capture the list of identifiers, if the
  398. /// angle brackets contain a list of protocol references rather than a
  399. /// type parameter list.
  400. ///
  401. /// \param rAngleLoc The location of the ending '>'.
  402. ObjCTypeParamList *Parser::parseObjCTypeParamListOrProtocolRefs(
  403. ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
  404. SmallVectorImpl<IdentifierLocPair> &protocolIdents,
  405. SourceLocation &rAngleLoc, bool mayBeProtocolList) {
  406. assert(Tok.is(tok::less) && "Not at the beginning of a type parameter list");
  407. // Within the type parameter list, don't treat '>' as an operator.
  408. GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
  409. // Local function to "flush" the protocol identifiers, turning them into
  410. // type parameters.
  411. SmallVector<Decl *, 4> typeParams;
  412. auto makeProtocolIdentsIntoTypeParameters = [&]() {
  413. unsigned index = 0;
  414. for (const auto &pair : protocolIdents) {
  415. DeclResult typeParam = Actions.actOnObjCTypeParam(
  416. getCurScope(), ObjCTypeParamVariance::Invariant, SourceLocation(),
  417. index++, pair.first, pair.second, SourceLocation(), nullptr);
  418. if (typeParam.isUsable())
  419. typeParams.push_back(typeParam.get());
  420. }
  421. protocolIdents.clear();
  422. mayBeProtocolList = false;
  423. };
  424. bool invalid = false;
  425. lAngleLoc = ConsumeToken();
  426. do {
  427. // Parse the variance, if any.
  428. SourceLocation varianceLoc;
  429. ObjCTypeParamVariance variance = ObjCTypeParamVariance::Invariant;
  430. if (Tok.is(tok::kw___covariant) || Tok.is(tok::kw___contravariant)) {
  431. variance = Tok.is(tok::kw___covariant)
  432. ? ObjCTypeParamVariance::Covariant
  433. : ObjCTypeParamVariance::Contravariant;
  434. varianceLoc = ConsumeToken();
  435. // Once we've seen a variance specific , we know this is not a
  436. // list of protocol references.
  437. if (mayBeProtocolList) {
  438. // Up until now, we have been queuing up parameters because they
  439. // might be protocol references. Turn them into parameters now.
  440. makeProtocolIdentsIntoTypeParameters();
  441. }
  442. }
  443. // Parse the identifier.
  444. if (!Tok.is(tok::identifier)) {
  445. // Code completion.
  446. if (Tok.is(tok::code_completion)) {
  447. // FIXME: If these aren't protocol references, we'll need different
  448. // completions.
  449. cutOffParsing();
  450. Actions.CodeCompleteObjCProtocolReferences(protocolIdents);
  451. // FIXME: Better recovery here?.
  452. return nullptr;
  453. }
  454. Diag(Tok, diag::err_objc_expected_type_parameter);
  455. invalid = true;
  456. break;
  457. }
  458. IdentifierInfo *paramName = Tok.getIdentifierInfo();
  459. SourceLocation paramLoc = ConsumeToken();
  460. // If there is a bound, parse it.
  461. SourceLocation colonLoc;
  462. TypeResult boundType;
  463. if (TryConsumeToken(tok::colon, colonLoc)) {
  464. // Once we've seen a bound, we know this is not a list of protocol
  465. // references.
  466. if (mayBeProtocolList) {
  467. // Up until now, we have been queuing up parameters because they
  468. // might be protocol references. Turn them into parameters now.
  469. makeProtocolIdentsIntoTypeParameters();
  470. }
  471. // type-name
  472. boundType = ParseTypeName();
  473. if (boundType.isInvalid())
  474. invalid = true;
  475. } else if (mayBeProtocolList) {
  476. // If this could still be a protocol list, just capture the identifier.
  477. // We don't want to turn it into a parameter.
  478. protocolIdents.push_back(std::make_pair(paramName, paramLoc));
  479. continue;
  480. }
  481. // Create the type parameter.
  482. DeclResult typeParam = Actions.actOnObjCTypeParam(
  483. getCurScope(), variance, varianceLoc, typeParams.size(), paramName,
  484. paramLoc, colonLoc, boundType.isUsable() ? boundType.get() : nullptr);
  485. if (typeParam.isUsable())
  486. typeParams.push_back(typeParam.get());
  487. } while (TryConsumeToken(tok::comma));
  488. // Parse the '>'.
  489. if (invalid) {
  490. SkipUntil(tok::greater, tok::at, StopBeforeMatch);
  491. if (Tok.is(tok::greater))
  492. ConsumeToken();
  493. } else if (ParseGreaterThanInTemplateList(lAngleLoc, rAngleLoc,
  494. /*ConsumeLastToken=*/true,
  495. /*ObjCGenericList=*/true)) {
  496. SkipUntil({tok::greater, tok::greaterequal, tok::at, tok::minus,
  497. tok::minus, tok::plus, tok::colon, tok::l_paren, tok::l_brace,
  498. tok::comma, tok::semi },
  499. StopBeforeMatch);
  500. if (Tok.is(tok::greater))
  501. ConsumeToken();
  502. }
  503. if (mayBeProtocolList) {
  504. // A type parameter list must be followed by either a ':' (indicating the
  505. // presence of a superclass) or a '(' (indicating that this is a category
  506. // or extension). This disambiguates between an objc-type-parameter-list
  507. // and a objc-protocol-refs.
  508. if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_paren)) {
  509. // Returning null indicates that we don't have a type parameter list.
  510. // The results the caller needs to handle the protocol references are
  511. // captured in the reference parameters already.
  512. return nullptr;
  513. }
  514. // We have a type parameter list that looks like a list of protocol
  515. // references. Turn that parameter list into type parameters.
  516. makeProtocolIdentsIntoTypeParameters();
  517. }
  518. // Form the type parameter list and enter its scope.
  519. ObjCTypeParamList *list = Actions.actOnObjCTypeParamList(
  520. getCurScope(),
  521. lAngleLoc,
  522. typeParams,
  523. rAngleLoc);
  524. Scope.enter(list);
  525. // Clear out the angle locations; they're used by the caller to indicate
  526. // whether there are any protocol references.
  527. lAngleLoc = SourceLocation();
  528. rAngleLoc = SourceLocation();
  529. return invalid ? nullptr : list;
  530. }
  531. /// Parse an objc-type-parameter-list.
  532. ObjCTypeParamList *Parser::parseObjCTypeParamList() {
  533. SourceLocation lAngleLoc;
  534. SmallVector<IdentifierLocPair, 1> protocolIdents;
  535. SourceLocation rAngleLoc;
  536. ObjCTypeParamListScope Scope(Actions, getCurScope());
  537. return parseObjCTypeParamListOrProtocolRefs(Scope, lAngleLoc, protocolIdents,
  538. rAngleLoc,
  539. /*mayBeProtocolList=*/false);
  540. }
  541. /// objc-interface-decl-list:
  542. /// empty
  543. /// objc-interface-decl-list objc-property-decl [OBJC2]
  544. /// objc-interface-decl-list objc-method-requirement [OBJC2]
  545. /// objc-interface-decl-list objc-method-proto ';'
  546. /// objc-interface-decl-list declaration
  547. /// objc-interface-decl-list ';'
  548. ///
  549. /// objc-method-requirement: [OBJC2]
  550. /// @required
  551. /// @optional
  552. ///
  553. void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
  554. Decl *CDecl) {
  555. SmallVector<Decl *, 32> allMethods;
  556. SmallVector<DeclGroupPtrTy, 8> allTUVariables;
  557. tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword;
  558. SourceRange AtEnd;
  559. while (true) {
  560. // If this is a method prototype, parse it.
  561. if (Tok.isOneOf(tok::minus, tok::plus)) {
  562. if (Decl *methodPrototype =
  563. ParseObjCMethodPrototype(MethodImplKind, false))
  564. allMethods.push_back(methodPrototype);
  565. // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for
  566. // method definitions.
  567. if (ExpectAndConsumeSemi(diag::err_expected_semi_after_method_proto)) {
  568. // We didn't find a semi and we error'ed out. Skip until a ';' or '@'.
  569. SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
  570. if (Tok.is(tok::semi))
  571. ConsumeToken();
  572. }
  573. continue;
  574. }
  575. if (Tok.is(tok::l_paren)) {
  576. Diag(Tok, diag::err_expected_minus_or_plus);
  577. ParseObjCMethodDecl(Tok.getLocation(),
  578. tok::minus,
  579. MethodImplKind, false);
  580. continue;
  581. }
  582. // Ignore excess semicolons.
  583. if (Tok.is(tok::semi)) {
  584. // FIXME: This should use ConsumeExtraSemi() for extraneous semicolons,
  585. // to make -Wextra-semi diagnose them.
  586. ConsumeToken();
  587. continue;
  588. }
  589. // If we got to the end of the file, exit the loop.
  590. if (isEofOrEom())
  591. break;
  592. // Code completion within an Objective-C interface.
  593. if (Tok.is(tok::code_completion)) {
  594. cutOffParsing();
  595. Actions.CodeCompleteOrdinaryName(getCurScope(),
  596. CurParsedObjCImpl? Sema::PCC_ObjCImplementation
  597. : Sema::PCC_ObjCInterface);
  598. return;
  599. }
  600. // If we don't have an @ directive, parse it as a function definition.
  601. if (Tok.isNot(tok::at)) {
  602. // The code below does not consume '}'s because it is afraid of eating the
  603. // end of a namespace. Because of the way this code is structured, an
  604. // erroneous r_brace would cause an infinite loop if not handled here.
  605. if (Tok.is(tok::r_brace))
  606. break;
  607. ParsedAttributes EmptyDeclAttrs(AttrFactory);
  608. ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
  609. // Since we call ParseDeclarationOrFunctionDefinition() instead of
  610. // ParseExternalDeclaration() below (so that this doesn't parse nested
  611. // @interfaces), this needs to duplicate some code from the latter.
  612. if (Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
  613. SourceLocation DeclEnd;
  614. ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
  615. allTUVariables.push_back(ParseDeclaration(DeclaratorContext::File,
  616. DeclEnd, EmptyDeclAttrs,
  617. EmptyDeclSpecAttrs));
  618. continue;
  619. }
  620. allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(
  621. EmptyDeclAttrs, EmptyDeclSpecAttrs));
  622. continue;
  623. }
  624. // Otherwise, we have an @ directive, eat the @.
  625. SourceLocation AtLoc = ConsumeToken(); // the "@"
  626. if (Tok.is(tok::code_completion)) {
  627. cutOffParsing();
  628. Actions.CodeCompleteObjCAtDirective(getCurScope());
  629. return;
  630. }
  631. tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID();
  632. if (DirectiveKind == tok::objc_end) { // @end -> terminate list
  633. AtEnd.setBegin(AtLoc);
  634. AtEnd.setEnd(Tok.getLocation());
  635. break;
  636. } else if (DirectiveKind == tok::objc_not_keyword) {
  637. Diag(Tok, diag::err_objc_unknown_at);
  638. SkipUntil(tok::semi);
  639. continue;
  640. }
  641. // Eat the identifier.
  642. ConsumeToken();
  643. switch (DirectiveKind) {
  644. default:
  645. // FIXME: If someone forgets an @end on a protocol, this loop will
  646. // continue to eat up tons of stuff and spew lots of nonsense errors. It
  647. // would probably be better to bail out if we saw an @class or @interface
  648. // or something like that.
  649. Diag(AtLoc, diag::err_objc_illegal_interface_qual);
  650. // Skip until we see an '@' or '}' or ';'.
  651. SkipUntil(tok::r_brace, tok::at, StopAtSemi);
  652. break;
  653. case tok::objc_implementation:
  654. case tok::objc_interface:
  655. Diag(AtLoc, diag::err_objc_missing_end)
  656. << FixItHint::CreateInsertion(AtLoc, "@end\n");
  657. Diag(CDecl->getBeginLoc(), diag::note_objc_container_start)
  658. << (int)Actions.getObjCContainerKind();
  659. ConsumeToken();
  660. break;
  661. case tok::objc_required:
  662. case tok::objc_optional:
  663. // This is only valid on protocols.
  664. if (contextKey != tok::objc_protocol)
  665. Diag(AtLoc, diag::err_objc_directive_only_in_protocol);
  666. else
  667. MethodImplKind = DirectiveKind;
  668. break;
  669. case tok::objc_property:
  670. ObjCDeclSpec OCDS;
  671. SourceLocation LParenLoc;
  672. // Parse property attribute list, if any.
  673. if (Tok.is(tok::l_paren)) {
  674. LParenLoc = Tok.getLocation();
  675. ParseObjCPropertyAttribute(OCDS);
  676. }
  677. bool addedToDeclSpec = false;
  678. auto ObjCPropertyCallback = [&](ParsingFieldDeclarator &FD) {
  679. if (FD.D.getIdentifier() == nullptr) {
  680. Diag(AtLoc, diag::err_objc_property_requires_field_name)
  681. << FD.D.getSourceRange();
  682. return;
  683. }
  684. if (FD.BitfieldSize) {
  685. Diag(AtLoc, diag::err_objc_property_bitfield)
  686. << FD.D.getSourceRange();
  687. return;
  688. }
  689. // Map a nullability property attribute to a context-sensitive keyword
  690. // attribute.
  691. if (OCDS.getPropertyAttributes() &
  692. ObjCPropertyAttribute::kind_nullability)
  693. addContextSensitiveTypeNullability(*this, FD.D, OCDS.getNullability(),
  694. OCDS.getNullabilityLoc(),
  695. addedToDeclSpec);
  696. // Install the property declarator into interfaceDecl.
  697. IdentifierInfo *SelName =
  698. OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier();
  699. Selector GetterSel = PP.getSelectorTable().getNullarySelector(SelName);
  700. IdentifierInfo *SetterName = OCDS.getSetterName();
  701. Selector SetterSel;
  702. if (SetterName)
  703. SetterSel = PP.getSelectorTable().getSelector(1, &SetterName);
  704. else
  705. SetterSel = SelectorTable::constructSetterSelector(
  706. PP.getIdentifierTable(), PP.getSelectorTable(),
  707. FD.D.getIdentifier());
  708. Decl *Property = Actions.ActOnProperty(
  709. getCurScope(), AtLoc, LParenLoc, FD, OCDS, GetterSel, SetterSel,
  710. MethodImplKind);
  711. FD.complete(Property);
  712. };
  713. // Parse all the comma separated declarators.
  714. ParsingDeclSpec DS(*this);
  715. ParseStructDeclaration(DS, ObjCPropertyCallback);
  716. ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
  717. break;
  718. }
  719. }
  720. // We break out of the big loop in two cases: when we see @end or when we see
  721. // EOF. In the former case, eat the @end. In the later case, emit an error.
  722. if (Tok.is(tok::code_completion)) {
  723. cutOffParsing();
  724. Actions.CodeCompleteObjCAtDirective(getCurScope());
  725. return;
  726. } else if (Tok.isObjCAtKeyword(tok::objc_end)) {
  727. ConsumeToken(); // the "end" identifier
  728. } else {
  729. Diag(Tok, diag::err_objc_missing_end)
  730. << FixItHint::CreateInsertion(Tok.getLocation(), "\n@end\n");
  731. Diag(CDecl->getBeginLoc(), diag::note_objc_container_start)
  732. << (int)Actions.getObjCContainerKind();
  733. AtEnd.setBegin(Tok.getLocation());
  734. AtEnd.setEnd(Tok.getLocation());
  735. }
  736. // Insert collected methods declarations into the @interface object.
  737. // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit.
  738. Actions.ActOnAtEnd(getCurScope(), AtEnd, allMethods, allTUVariables);
  739. }
  740. /// Diagnose redundant or conflicting nullability information.
  741. static void diagnoseRedundantPropertyNullability(Parser &P,
  742. ObjCDeclSpec &DS,
  743. NullabilityKind nullability,
  744. SourceLocation nullabilityLoc){
  745. if (DS.getNullability() == nullability) {
  746. P.Diag(nullabilityLoc, diag::warn_nullability_duplicate)
  747. << DiagNullabilityKind(nullability, true)
  748. << SourceRange(DS.getNullabilityLoc());
  749. return;
  750. }
  751. P.Diag(nullabilityLoc, diag::err_nullability_conflicting)
  752. << DiagNullabilityKind(nullability, true)
  753. << DiagNullabilityKind(DS.getNullability(), true)
  754. << SourceRange(DS.getNullabilityLoc());
  755. }
  756. /// Parse property attribute declarations.
  757. ///
  758. /// property-attr-decl: '(' property-attrlist ')'
  759. /// property-attrlist:
  760. /// property-attribute
  761. /// property-attrlist ',' property-attribute
  762. /// property-attribute:
  763. /// getter '=' identifier
  764. /// setter '=' identifier ':'
  765. /// direct
  766. /// readonly
  767. /// readwrite
  768. /// assign
  769. /// retain
  770. /// copy
  771. /// nonatomic
  772. /// atomic
  773. /// strong
  774. /// weak
  775. /// unsafe_unretained
  776. /// nonnull
  777. /// nullable
  778. /// null_unspecified
  779. /// null_resettable
  780. /// class
  781. ///
  782. void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) {
  783. assert(Tok.getKind() == tok::l_paren);
  784. BalancedDelimiterTracker T(*this, tok::l_paren);
  785. T.consumeOpen();
  786. while (true) {
  787. if (Tok.is(tok::code_completion)) {
  788. cutOffParsing();
  789. Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS);
  790. return;
  791. }
  792. const IdentifierInfo *II = Tok.getIdentifierInfo();
  793. // If this is not an identifier at all, bail out early.
  794. if (!II) {
  795. T.consumeClose();
  796. return;
  797. }
  798. SourceLocation AttrName = ConsumeToken(); // consume last attribute name
  799. if (II->isStr("readonly"))
  800. DS.setPropertyAttributes(ObjCPropertyAttribute::kind_readonly);
  801. else if (II->isStr("assign"))
  802. DS.setPropertyAttributes(ObjCPropertyAttribute::kind_assign);
  803. else if (II->isStr("unsafe_unretained"))
  804. DS.setPropertyAttributes(ObjCPropertyAttribute::kind_unsafe_unretained);
  805. else if (II->isStr("readwrite"))
  806. DS.setPropertyAttributes(ObjCPropertyAttribute::kind_readwrite);
  807. else if (II->isStr("retain"))
  808. DS.setPropertyAttributes(ObjCPropertyAttribute::kind_retain);
  809. else if (II->isStr("strong"))
  810. DS.setPropertyAttributes(ObjCPropertyAttribute::kind_strong);
  811. else if (II->isStr("copy"))
  812. DS.setPropertyAttributes(ObjCPropertyAttribute::kind_copy);
  813. else if (II->isStr("nonatomic"))
  814. DS.setPropertyAttributes(ObjCPropertyAttribute::kind_nonatomic);
  815. else if (II->isStr("atomic"))
  816. DS.setPropertyAttributes(ObjCPropertyAttribute::kind_atomic);
  817. else if (II->isStr("weak"))
  818. DS.setPropertyAttributes(ObjCPropertyAttribute::kind_weak);
  819. else if (II->isStr("getter") || II->isStr("setter")) {
  820. bool IsSetter = II->getNameStart()[0] == 's';
  821. // getter/setter require extra treatment.
  822. unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter :
  823. diag::err_objc_expected_equal_for_getter;
  824. if (ExpectAndConsume(tok::equal, DiagID)) {
  825. SkipUntil(tok::r_paren, StopAtSemi);
  826. return;
  827. }
  828. if (Tok.is(tok::code_completion)) {
  829. cutOffParsing();
  830. if (IsSetter)
  831. Actions.CodeCompleteObjCPropertySetter(getCurScope());
  832. else
  833. Actions.CodeCompleteObjCPropertyGetter(getCurScope());
  834. return;
  835. }
  836. SourceLocation SelLoc;
  837. IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc);
  838. if (!SelIdent) {
  839. Diag(Tok, diag::err_objc_expected_selector_for_getter_setter)
  840. << IsSetter;
  841. SkipUntil(tok::r_paren, StopAtSemi);
  842. return;
  843. }
  844. if (IsSetter) {
  845. DS.setPropertyAttributes(ObjCPropertyAttribute::kind_setter);
  846. DS.setSetterName(SelIdent, SelLoc);
  847. if (ExpectAndConsume(tok::colon,
  848. diag::err_expected_colon_after_setter_name)) {
  849. SkipUntil(tok::r_paren, StopAtSemi);
  850. return;
  851. }
  852. } else {
  853. DS.setPropertyAttributes(ObjCPropertyAttribute::kind_getter);
  854. DS.setGetterName(SelIdent, SelLoc);
  855. }
  856. } else if (II->isStr("nonnull")) {
  857. if (DS.getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)
  858. diagnoseRedundantPropertyNullability(*this, DS,
  859. NullabilityKind::NonNull,
  860. Tok.getLocation());
  861. DS.setPropertyAttributes(ObjCPropertyAttribute::kind_nullability);
  862. DS.setNullability(Tok.getLocation(), NullabilityKind::NonNull);
  863. } else if (II->isStr("nullable")) {
  864. if (DS.getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)
  865. diagnoseRedundantPropertyNullability(*this, DS,
  866. NullabilityKind::Nullable,
  867. Tok.getLocation());
  868. DS.setPropertyAttributes(ObjCPropertyAttribute::kind_nullability);
  869. DS.setNullability(Tok.getLocation(), NullabilityKind::Nullable);
  870. } else if (II->isStr("null_unspecified")) {
  871. if (DS.getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)
  872. diagnoseRedundantPropertyNullability(*this, DS,
  873. NullabilityKind::Unspecified,
  874. Tok.getLocation());
  875. DS.setPropertyAttributes(ObjCPropertyAttribute::kind_nullability);
  876. DS.setNullability(Tok.getLocation(), NullabilityKind::Unspecified);
  877. } else if (II->isStr("null_resettable")) {
  878. if (DS.getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)
  879. diagnoseRedundantPropertyNullability(*this, DS,
  880. NullabilityKind::Unspecified,
  881. Tok.getLocation());
  882. DS.setPropertyAttributes(ObjCPropertyAttribute::kind_nullability);
  883. DS.setNullability(Tok.getLocation(), NullabilityKind::Unspecified);
  884. // Also set the null_resettable bit.
  885. DS.setPropertyAttributes(ObjCPropertyAttribute::kind_null_resettable);
  886. } else if (II->isStr("class")) {
  887. DS.setPropertyAttributes(ObjCPropertyAttribute::kind_class);
  888. } else if (II->isStr("direct")) {
  889. DS.setPropertyAttributes(ObjCPropertyAttribute::kind_direct);
  890. } else {
  891. Diag(AttrName, diag::err_objc_expected_property_attr) << II;
  892. SkipUntil(tok::r_paren, StopAtSemi);
  893. return;
  894. }
  895. if (Tok.isNot(tok::comma))
  896. break;
  897. ConsumeToken();
  898. }
  899. T.consumeClose();
  900. }
  901. /// objc-method-proto:
  902. /// objc-instance-method objc-method-decl objc-method-attributes[opt]
  903. /// objc-class-method objc-method-decl objc-method-attributes[opt]
  904. ///
  905. /// objc-instance-method: '-'
  906. /// objc-class-method: '+'
  907. ///
  908. /// objc-method-attributes: [OBJC2]
  909. /// __attribute__((deprecated))
  910. ///
  911. Decl *Parser::ParseObjCMethodPrototype(tok::ObjCKeywordKind MethodImplKind,
  912. bool MethodDefinition) {
  913. assert(Tok.isOneOf(tok::minus, tok::plus) && "expected +/-");
  914. tok::TokenKind methodType = Tok.getKind();
  915. SourceLocation mLoc = ConsumeToken();
  916. Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, MethodImplKind,
  917. MethodDefinition);
  918. // Since this rule is used for both method declarations and definitions,
  919. // the caller is (optionally) responsible for consuming the ';'.
  920. return MDecl;
  921. }
  922. /// objc-selector:
  923. /// identifier
  924. /// one of
  925. /// enum struct union if else while do for switch case default
  926. /// break continue return goto asm sizeof typeof __alignof
  927. /// unsigned long const short volatile signed restrict _Complex
  928. /// in out inout bycopy byref oneway int char float double void _Bool
  929. ///
  930. IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) {
  931. switch (Tok.getKind()) {
  932. default:
  933. return nullptr;
  934. case tok::colon:
  935. // Empty selector piece uses the location of the ':'.
  936. SelectorLoc = Tok.getLocation();
  937. return nullptr;
  938. case tok::ampamp:
  939. case tok::ampequal:
  940. case tok::amp:
  941. case tok::pipe:
  942. case tok::tilde:
  943. case tok::exclaim:
  944. case tok::exclaimequal:
  945. case tok::pipepipe:
  946. case tok::pipeequal:
  947. case tok::caret:
  948. case tok::caretequal: {
  949. std::string ThisTok(PP.getSpelling(Tok));
  950. if (isLetter(ThisTok[0])) {
  951. IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok);
  952. Tok.setKind(tok::identifier);
  953. SelectorLoc = ConsumeToken();
  954. return II;
  955. }
  956. return nullptr;
  957. }
  958. case tok::identifier:
  959. case tok::kw_asm:
  960. case tok::kw_auto:
  961. case tok::kw_bool:
  962. case tok::kw_break:
  963. case tok::kw_case:
  964. case tok::kw_catch:
  965. case tok::kw_char:
  966. case tok::kw_class:
  967. case tok::kw_const:
  968. case tok::kw_const_cast:
  969. case tok::kw_continue:
  970. case tok::kw_default:
  971. case tok::kw_delete:
  972. case tok::kw_do:
  973. case tok::kw_double:
  974. case tok::kw_dynamic_cast:
  975. case tok::kw_else:
  976. case tok::kw_enum:
  977. case tok::kw_explicit:
  978. case tok::kw_export:
  979. case tok::kw_extern:
  980. case tok::kw_false:
  981. case tok::kw_float:
  982. case tok::kw_for:
  983. case tok::kw_friend:
  984. case tok::kw_goto:
  985. case tok::kw_if:
  986. case tok::kw_inline:
  987. case tok::kw_int:
  988. case tok::kw_long:
  989. case tok::kw_mutable:
  990. case tok::kw_namespace:
  991. case tok::kw_new:
  992. case tok::kw_operator:
  993. case tok::kw_private:
  994. case tok::kw_protected:
  995. case tok::kw_public:
  996. case tok::kw_register:
  997. case tok::kw_reinterpret_cast:
  998. case tok::kw_restrict:
  999. case tok::kw_return:
  1000. case tok::kw_short:
  1001. case tok::kw_signed:
  1002. case tok::kw_sizeof:
  1003. case tok::kw_static:
  1004. case tok::kw_static_cast:
  1005. case tok::kw_struct:
  1006. case tok::kw_switch:
  1007. case tok::kw_template:
  1008. case tok::kw_this:
  1009. case tok::kw_throw:
  1010. case tok::kw_true:
  1011. case tok::kw_try:
  1012. case tok::kw_typedef:
  1013. case tok::kw_typeid:
  1014. case tok::kw_typename:
  1015. case tok::kw_typeof:
  1016. case tok::kw_union:
  1017. case tok::kw_unsigned:
  1018. case tok::kw_using:
  1019. case tok::kw_virtual:
  1020. case tok::kw_void:
  1021. case tok::kw_volatile:
  1022. case tok::kw_wchar_t:
  1023. case tok::kw_while:
  1024. case tok::kw__Bool:
  1025. case tok::kw__Complex:
  1026. case tok::kw___alignof:
  1027. case tok::kw___auto_type:
  1028. IdentifierInfo *II = Tok.getIdentifierInfo();
  1029. SelectorLoc = ConsumeToken();
  1030. return II;
  1031. }
  1032. }
  1033. /// objc-for-collection-in: 'in'
  1034. ///
  1035. bool Parser::isTokIdentifier_in() const {
  1036. // FIXME: May have to do additional look-ahead to only allow for
  1037. // valid tokens following an 'in'; such as an identifier, unary operators,
  1038. // '[' etc.
  1039. return (getLangOpts().ObjC && Tok.is(tok::identifier) &&
  1040. Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]);
  1041. }
  1042. /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
  1043. /// qualifier list and builds their bitmask representation in the input
  1044. /// argument.
  1045. ///
  1046. /// objc-type-qualifiers:
  1047. /// objc-type-qualifier
  1048. /// objc-type-qualifiers objc-type-qualifier
  1049. ///
  1050. /// objc-type-qualifier:
  1051. /// 'in'
  1052. /// 'out'
  1053. /// 'inout'
  1054. /// 'oneway'
  1055. /// 'bycopy'
  1056. /// 'byref'
  1057. /// 'nonnull'
  1058. /// 'nullable'
  1059. /// 'null_unspecified'
  1060. ///
  1061. void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
  1062. DeclaratorContext Context) {
  1063. assert(Context == DeclaratorContext::ObjCParameter ||
  1064. Context == DeclaratorContext::ObjCResult);
  1065. while (true) {
  1066. if (Tok.is(tok::code_completion)) {
  1067. cutOffParsing();
  1068. Actions.CodeCompleteObjCPassingType(
  1069. getCurScope(), DS, Context == DeclaratorContext::ObjCParameter);
  1070. return;
  1071. }
  1072. if (Tok.isNot(tok::identifier))
  1073. return;
  1074. const IdentifierInfo *II = Tok.getIdentifierInfo();
  1075. for (unsigned i = 0; i != objc_NumQuals; ++i) {
  1076. if (II != ObjCTypeQuals[i] ||
  1077. NextToken().is(tok::less) ||
  1078. NextToken().is(tok::coloncolon))
  1079. continue;
  1080. ObjCDeclSpec::ObjCDeclQualifier Qual;
  1081. NullabilityKind Nullability;
  1082. switch (i) {
  1083. default: llvm_unreachable("Unknown decl qualifier");
  1084. case objc_in: Qual = ObjCDeclSpec::DQ_In; break;
  1085. case objc_out: Qual = ObjCDeclSpec::DQ_Out; break;
  1086. case objc_inout: Qual = ObjCDeclSpec::DQ_Inout; break;
  1087. case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break;
  1088. case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break;
  1089. case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break;
  1090. case objc_nonnull:
  1091. Qual = ObjCDeclSpec::DQ_CSNullability;
  1092. Nullability = NullabilityKind::NonNull;
  1093. break;
  1094. case objc_nullable:
  1095. Qual = ObjCDeclSpec::DQ_CSNullability;
  1096. Nullability = NullabilityKind::Nullable;
  1097. break;
  1098. case objc_null_unspecified:
  1099. Qual = ObjCDeclSpec::DQ_CSNullability;
  1100. Nullability = NullabilityKind::Unspecified;
  1101. break;
  1102. }
  1103. // FIXME: Diagnose redundant specifiers.
  1104. DS.setObjCDeclQualifier(Qual);
  1105. if (Qual == ObjCDeclSpec::DQ_CSNullability)
  1106. DS.setNullability(Tok.getLocation(), Nullability);
  1107. ConsumeToken();
  1108. II = nullptr;
  1109. break;
  1110. }
  1111. // If this wasn't a recognized qualifier, bail out.
  1112. if (II) return;
  1113. }
  1114. }
  1115. /// Take all the decl attributes out of the given list and add
  1116. /// them to the given attribute set.
  1117. static void takeDeclAttributes(ParsedAttributesView &attrs,
  1118. ParsedAttributesView &from) {
  1119. for (auto &AL : llvm::reverse(from)) {
  1120. if (!AL.isUsedAsTypeAttr()) {
  1121. from.remove(&AL);
  1122. attrs.addAtEnd(&AL);
  1123. }
  1124. }
  1125. }
  1126. /// takeDeclAttributes - Take all the decl attributes from the given
  1127. /// declarator and add them to the given list.
  1128. static void takeDeclAttributes(ParsedAttributes &attrs,
  1129. Declarator &D) {
  1130. // This gets called only from Parser::ParseObjCTypeName(), and that should
  1131. // never add declaration attributes to the Declarator.
  1132. assert(D.getDeclarationAttributes().empty());
  1133. // First, take ownership of all attributes.
  1134. attrs.getPool().takeAllFrom(D.getAttributePool());
  1135. attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool());
  1136. // Now actually move the attributes over.
  1137. takeDeclAttributes(attrs, D.getMutableDeclSpec().getAttributes());
  1138. takeDeclAttributes(attrs, D.getAttributes());
  1139. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
  1140. takeDeclAttributes(attrs, D.getTypeObject(i).getAttrs());
  1141. }
  1142. /// objc-type-name:
  1143. /// '(' objc-type-qualifiers[opt] type-name ')'
  1144. /// '(' objc-type-qualifiers[opt] ')'
  1145. ///
  1146. ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS,
  1147. DeclaratorContext context,
  1148. ParsedAttributes *paramAttrs) {
  1149. assert(context == DeclaratorContext::ObjCParameter ||
  1150. context == DeclaratorContext::ObjCResult);
  1151. assert((paramAttrs != nullptr) ==
  1152. (context == DeclaratorContext::ObjCParameter));
  1153. assert(Tok.is(tok::l_paren) && "expected (");
  1154. BalancedDelimiterTracker T(*this, tok::l_paren);
  1155. T.consumeOpen();
  1156. ObjCDeclContextSwitch ObjCDC(*this);
  1157. // Parse type qualifiers, in, inout, etc.
  1158. ParseObjCTypeQualifierList(DS, context);
  1159. SourceLocation TypeStartLoc = Tok.getLocation();
  1160. ParsedType Ty;
  1161. if (isTypeSpecifierQualifier() || isObjCInstancetype()) {
  1162. // Parse an abstract declarator.
  1163. DeclSpec declSpec(AttrFactory);
  1164. declSpec.setObjCQualifiers(&DS);
  1165. DeclSpecContext dsContext = DeclSpecContext::DSC_normal;
  1166. if (context == DeclaratorContext::ObjCResult)
  1167. dsContext = DeclSpecContext::DSC_objc_method_result;
  1168. ParseSpecifierQualifierList(declSpec, AS_none, dsContext);
  1169. Declarator declarator(declSpec, ParsedAttributesView::none(), context);
  1170. ParseDeclarator(declarator);
  1171. // If that's not invalid, extract a type.
  1172. if (!declarator.isInvalidType()) {
  1173. // Map a nullability specifier to a context-sensitive keyword attribute.
  1174. bool addedToDeclSpec = false;
  1175. if (DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability)
  1176. addContextSensitiveTypeNullability(*this, declarator,
  1177. DS.getNullability(),
  1178. DS.getNullabilityLoc(),
  1179. addedToDeclSpec);
  1180. TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator);
  1181. if (!type.isInvalid())
  1182. Ty = type.get();
  1183. // If we're parsing a parameter, steal all the decl attributes
  1184. // and add them to the decl spec.
  1185. if (context == DeclaratorContext::ObjCParameter)
  1186. takeDeclAttributes(*paramAttrs, declarator);
  1187. }
  1188. }
  1189. if (Tok.is(tok::r_paren))
  1190. T.consumeClose();
  1191. else if (Tok.getLocation() == TypeStartLoc) {
  1192. // If we didn't eat any tokens, then this isn't a type.
  1193. Diag(Tok, diag::err_expected_type);
  1194. SkipUntil(tok::r_paren, StopAtSemi);
  1195. } else {
  1196. // Otherwise, we found *something*, but didn't get a ')' in the right
  1197. // place. Emit an error then return what we have as the type.
  1198. T.consumeClose();
  1199. }
  1200. return Ty;
  1201. }
  1202. /// objc-method-decl:
  1203. /// objc-selector
  1204. /// objc-keyword-selector objc-parmlist[opt]
  1205. /// objc-type-name objc-selector
  1206. /// objc-type-name objc-keyword-selector objc-parmlist[opt]
  1207. ///
  1208. /// objc-keyword-selector:
  1209. /// objc-keyword-decl
  1210. /// objc-keyword-selector objc-keyword-decl
  1211. ///
  1212. /// objc-keyword-decl:
  1213. /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
  1214. /// objc-selector ':' objc-keyword-attributes[opt] identifier
  1215. /// ':' objc-type-name objc-keyword-attributes[opt] identifier
  1216. /// ':' objc-keyword-attributes[opt] identifier
  1217. ///
  1218. /// objc-parmlist:
  1219. /// objc-parms objc-ellipsis[opt]
  1220. ///
  1221. /// objc-parms:
  1222. /// objc-parms , parameter-declaration
  1223. ///
  1224. /// objc-ellipsis:
  1225. /// , ...
  1226. ///
  1227. /// objc-keyword-attributes: [OBJC2]
  1228. /// __attribute__((unused))
  1229. ///
  1230. Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
  1231. tok::TokenKind mType,
  1232. tok::ObjCKeywordKind MethodImplKind,
  1233. bool MethodDefinition) {
  1234. ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
  1235. if (Tok.is(tok::code_completion)) {
  1236. cutOffParsing();
  1237. Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
  1238. /*ReturnType=*/nullptr);
  1239. return nullptr;
  1240. }
  1241. // Parse the return type if present.
  1242. ParsedType ReturnType;
  1243. ObjCDeclSpec DSRet;
  1244. if (Tok.is(tok::l_paren))
  1245. ReturnType =
  1246. ParseObjCTypeName(DSRet, DeclaratorContext::ObjCResult, nullptr);
  1247. // If attributes exist before the method, parse them.
  1248. ParsedAttributes methodAttrs(AttrFactory);
  1249. MaybeParseAttributes(PAKM_CXX11 | (getLangOpts().ObjC ? PAKM_GNU : 0),
  1250. methodAttrs);
  1251. if (Tok.is(tok::code_completion)) {
  1252. cutOffParsing();
  1253. Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
  1254. ReturnType);
  1255. return nullptr;
  1256. }
  1257. // Now parse the selector.
  1258. SourceLocation selLoc;
  1259. IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc);
  1260. // An unnamed colon is valid.
  1261. if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name.
  1262. Diag(Tok, diag::err_expected_selector_for_method)
  1263. << SourceRange(mLoc, Tok.getLocation());
  1264. // Skip until we get a ; or @.
  1265. SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
  1266. return nullptr;
  1267. }
  1268. SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
  1269. if (Tok.isNot(tok::colon)) {
  1270. // If attributes exist after the method, parse them.
  1271. MaybeParseAttributes(PAKM_CXX11 | (getLangOpts().ObjC ? PAKM_GNU : 0),
  1272. methodAttrs);
  1273. Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
  1274. Decl *Result = Actions.ActOnMethodDeclaration(
  1275. getCurScope(), mLoc, Tok.getLocation(), mType, DSRet, ReturnType,
  1276. selLoc, Sel, nullptr, CParamInfo.data(), CParamInfo.size(), methodAttrs,
  1277. MethodImplKind, false, MethodDefinition);
  1278. PD.complete(Result);
  1279. return Result;
  1280. }
  1281. SmallVector<IdentifierInfo *, 12> KeyIdents;
  1282. SmallVector<SourceLocation, 12> KeyLocs;
  1283. SmallVector<Sema::ObjCArgInfo, 12> ArgInfos;
  1284. ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
  1285. Scope::FunctionDeclarationScope | Scope::DeclScope);
  1286. AttributePool allParamAttrs(AttrFactory);
  1287. while (true) {
  1288. ParsedAttributes paramAttrs(AttrFactory);
  1289. Sema::ObjCArgInfo ArgInfo;
  1290. // Each iteration parses a single keyword argument.
  1291. if (ExpectAndConsume(tok::colon))
  1292. break;
  1293. ArgInfo.Type = nullptr;
  1294. if (Tok.is(tok::l_paren)) // Parse the argument type if present.
  1295. ArgInfo.Type = ParseObjCTypeName(
  1296. ArgInfo.DeclSpec, DeclaratorContext::ObjCParameter, &paramAttrs);
  1297. // If attributes exist before the argument name, parse them.
  1298. // Regardless, collect all the attributes we've parsed so far.
  1299. MaybeParseAttributes(PAKM_CXX11 | (getLangOpts().ObjC ? PAKM_GNU : 0),
  1300. paramAttrs);
  1301. ArgInfo.ArgAttrs = paramAttrs;
  1302. // Code completion for the next piece of the selector.
  1303. if (Tok.is(tok::code_completion)) {
  1304. cutOffParsing();
  1305. KeyIdents.push_back(SelIdent);
  1306. Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
  1307. mType == tok::minus,
  1308. /*AtParameterName=*/true,
  1309. ReturnType, KeyIdents);
  1310. return nullptr;
  1311. }
  1312. if (expectIdentifier())
  1313. break; // missing argument name.
  1314. ArgInfo.Name = Tok.getIdentifierInfo();
  1315. ArgInfo.NameLoc = Tok.getLocation();
  1316. ConsumeToken(); // Eat the identifier.
  1317. ArgInfos.push_back(ArgInfo);
  1318. KeyIdents.push_back(SelIdent);
  1319. KeyLocs.push_back(selLoc);
  1320. // Make sure the attributes persist.
  1321. allParamAttrs.takeAllFrom(paramAttrs.getPool());
  1322. // Code completion for the next piece of the selector.
  1323. if (Tok.is(tok::code_completion)) {
  1324. cutOffParsing();
  1325. Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
  1326. mType == tok::minus,
  1327. /*AtParameterName=*/false,
  1328. ReturnType, KeyIdents);
  1329. return nullptr;
  1330. }
  1331. // Check for another keyword selector.
  1332. SelIdent = ParseObjCSelectorPiece(selLoc);
  1333. if (!SelIdent && Tok.isNot(tok::colon))
  1334. break;
  1335. if (!SelIdent) {
  1336. SourceLocation ColonLoc = Tok.getLocation();
  1337. if (PP.getLocForEndOfToken(ArgInfo.NameLoc) == ColonLoc) {
  1338. Diag(ArgInfo.NameLoc, diag::warn_missing_selector_name) << ArgInfo.Name;
  1339. Diag(ArgInfo.NameLoc, diag::note_missing_selector_name) << ArgInfo.Name;
  1340. Diag(ColonLoc, diag::note_force_empty_selector_name) << ArgInfo.Name;
  1341. }
  1342. }
  1343. // We have a selector or a colon, continue parsing.
  1344. }
  1345. bool isVariadic = false;
  1346. bool cStyleParamWarned = false;
  1347. // Parse the (optional) parameter list.
  1348. while (Tok.is(tok::comma)) {
  1349. ConsumeToken();
  1350. if (Tok.is(tok::ellipsis)) {
  1351. isVariadic = true;
  1352. ConsumeToken();
  1353. break;
  1354. }
  1355. if (!cStyleParamWarned) {
  1356. Diag(Tok, diag::warn_cstyle_param);
  1357. cStyleParamWarned = true;
  1358. }
  1359. DeclSpec DS(AttrFactory);
  1360. ParseDeclarationSpecifiers(DS);
  1361. // Parse the declarator.
  1362. Declarator ParmDecl(DS, ParsedAttributesView::none(),
  1363. DeclaratorContext::Prototype);
  1364. ParseDeclarator(ParmDecl);
  1365. IdentifierInfo *ParmII = ParmDecl.getIdentifier();
  1366. Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
  1367. CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
  1368. ParmDecl.getIdentifierLoc(),
  1369. Param,
  1370. nullptr));
  1371. }
  1372. // FIXME: Add support for optional parameter list...
  1373. // If attributes exist after the method, parse them.
  1374. MaybeParseAttributes(PAKM_CXX11 | (getLangOpts().ObjC ? PAKM_GNU : 0),
  1375. methodAttrs);
  1376. if (KeyIdents.size() == 0)
  1377. return nullptr;
  1378. Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
  1379. &KeyIdents[0]);
  1380. Decl *Result = Actions.ActOnMethodDeclaration(
  1381. getCurScope(), mLoc, Tok.getLocation(), mType, DSRet, ReturnType, KeyLocs,
  1382. Sel, &ArgInfos[0], CParamInfo.data(), CParamInfo.size(), methodAttrs,
  1383. MethodImplKind, isVariadic, MethodDefinition);
  1384. PD.complete(Result);
  1385. return Result;
  1386. }
  1387. /// objc-protocol-refs:
  1388. /// '<' identifier-list '>'
  1389. ///
  1390. bool Parser::
  1391. ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols,
  1392. SmallVectorImpl<SourceLocation> &ProtocolLocs,
  1393. bool WarnOnDeclarations, bool ForObjCContainer,
  1394. SourceLocation &LAngleLoc, SourceLocation &EndLoc,
  1395. bool consumeLastToken) {
  1396. assert(Tok.is(tok::less) && "expected <");
  1397. LAngleLoc = ConsumeToken(); // the "<"
  1398. SmallVector<IdentifierLocPair, 8> ProtocolIdents;
  1399. while (true) {
  1400. if (Tok.is(tok::code_completion)) {
  1401. cutOffParsing();
  1402. Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents);
  1403. return true;
  1404. }
  1405. if (expectIdentifier()) {
  1406. SkipUntil(tok::greater, StopAtSemi);
  1407. return true;
  1408. }
  1409. ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
  1410. Tok.getLocation()));
  1411. ProtocolLocs.push_back(Tok.getLocation());
  1412. ConsumeToken();
  1413. if (!TryConsumeToken(tok::comma))
  1414. break;
  1415. }
  1416. // Consume the '>'.
  1417. if (ParseGreaterThanInTemplateList(LAngleLoc, EndLoc, consumeLastToken,
  1418. /*ObjCGenericList=*/false))
  1419. return true;
  1420. // Convert the list of protocols identifiers into a list of protocol decls.
  1421. Actions.FindProtocolDeclaration(WarnOnDeclarations, ForObjCContainer,
  1422. ProtocolIdents, Protocols);
  1423. return false;
  1424. }
  1425. TypeResult Parser::parseObjCProtocolQualifierType(SourceLocation &rAngleLoc) {
  1426. assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
  1427. assert(getLangOpts().ObjC && "Protocol qualifiers only exist in Objective-C");
  1428. SourceLocation lAngleLoc;
  1429. SmallVector<Decl *, 8> protocols;
  1430. SmallVector<SourceLocation, 8> protocolLocs;
  1431. (void)ParseObjCProtocolReferences(protocols, protocolLocs, false, false,
  1432. lAngleLoc, rAngleLoc,
  1433. /*consumeLastToken=*/true);
  1434. TypeResult result = Actions.actOnObjCProtocolQualifierType(lAngleLoc,
  1435. protocols,
  1436. protocolLocs,
  1437. rAngleLoc);
  1438. if (result.isUsable()) {
  1439. Diag(lAngleLoc, diag::warn_objc_protocol_qualifier_missing_id)
  1440. << FixItHint::CreateInsertion(lAngleLoc, "id")
  1441. << SourceRange(lAngleLoc, rAngleLoc);
  1442. }
  1443. return result;
  1444. }
  1445. /// Parse Objective-C type arguments or protocol qualifiers.
  1446. ///
  1447. /// objc-type-arguments:
  1448. /// '<' type-name '...'[opt] (',' type-name '...'[opt])* '>'
  1449. ///
  1450. void Parser::parseObjCTypeArgsOrProtocolQualifiers(
  1451. ParsedType baseType,
  1452. SourceLocation &typeArgsLAngleLoc,
  1453. SmallVectorImpl<ParsedType> &typeArgs,
  1454. SourceLocation &typeArgsRAngleLoc,
  1455. SourceLocation &protocolLAngleLoc,
  1456. SmallVectorImpl<Decl *> &protocols,
  1457. SmallVectorImpl<SourceLocation> &protocolLocs,
  1458. SourceLocation &protocolRAngleLoc,
  1459. bool consumeLastToken,
  1460. bool warnOnIncompleteProtocols) {
  1461. assert(Tok.is(tok::less) && "Not at the start of type args or protocols");
  1462. SourceLocation lAngleLoc = ConsumeToken();
  1463. // Whether all of the elements we've parsed thus far are single
  1464. // identifiers, which might be types or might be protocols.
  1465. bool allSingleIdentifiers = true;
  1466. SmallVector<IdentifierInfo *, 4> identifiers;
  1467. SmallVectorImpl<SourceLocation> &identifierLocs = protocolLocs;
  1468. // Parse a list of comma-separated identifiers, bailing out if we
  1469. // see something different.
  1470. do {
  1471. // Parse a single identifier.
  1472. if (Tok.is(tok::identifier) &&
  1473. (NextToken().is(tok::comma) ||
  1474. NextToken().is(tok::greater) ||
  1475. NextToken().is(tok::greatergreater))) {
  1476. identifiers.push_back(Tok.getIdentifierInfo());
  1477. identifierLocs.push_back(ConsumeToken());
  1478. continue;
  1479. }
  1480. if (Tok.is(tok::code_completion)) {
  1481. // FIXME: Also include types here.
  1482. SmallVector<IdentifierLocPair, 4> identifierLocPairs;
  1483. for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
  1484. identifierLocPairs.push_back(IdentifierLocPair(identifiers[i],
  1485. identifierLocs[i]));
  1486. }
  1487. QualType BaseT = Actions.GetTypeFromParser(baseType);
  1488. cutOffParsing();
  1489. if (!BaseT.isNull() && BaseT->acceptsObjCTypeParams()) {
  1490. Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
  1491. } else {
  1492. Actions.CodeCompleteObjCProtocolReferences(identifierLocPairs);
  1493. }
  1494. return;
  1495. }
  1496. allSingleIdentifiers = false;
  1497. break;
  1498. } while (TryConsumeToken(tok::comma));
  1499. // If we parsed an identifier list, semantic analysis sorts out
  1500. // whether it refers to protocols or to type arguments.
  1501. if (allSingleIdentifiers) {
  1502. // Parse the closing '>'.
  1503. SourceLocation rAngleLoc;
  1504. (void)ParseGreaterThanInTemplateList(lAngleLoc, rAngleLoc, consumeLastToken,
  1505. /*ObjCGenericList=*/true);
  1506. // Let Sema figure out what we parsed.
  1507. Actions.actOnObjCTypeArgsOrProtocolQualifiers(getCurScope(),
  1508. baseType,
  1509. lAngleLoc,
  1510. identifiers,
  1511. identifierLocs,
  1512. rAngleLoc,
  1513. typeArgsLAngleLoc,
  1514. typeArgs,
  1515. typeArgsRAngleLoc,
  1516. protocolLAngleLoc,
  1517. protocols,
  1518. protocolRAngleLoc,
  1519. warnOnIncompleteProtocols);
  1520. return;
  1521. }
  1522. // We parsed an identifier list but stumbled into non single identifiers, this
  1523. // means we might (a) check that what we already parsed is a legitimate type
  1524. // (not a protocol or unknown type) and (b) parse the remaining ones, which
  1525. // must all be type args.
  1526. // Convert the identifiers into type arguments.
  1527. bool invalid = false;
  1528. IdentifierInfo *foundProtocolId = nullptr, *foundValidTypeId = nullptr;
  1529. SourceLocation foundProtocolSrcLoc, foundValidTypeSrcLoc;
  1530. SmallVector<IdentifierInfo *, 2> unknownTypeArgs;
  1531. SmallVector<SourceLocation, 2> unknownTypeArgsLoc;
  1532. for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
  1533. ParsedType typeArg
  1534. = Actions.getTypeName(*identifiers[i], identifierLocs[i], getCurScope());
  1535. if (typeArg) {
  1536. DeclSpec DS(AttrFactory);
  1537. const char *prevSpec = nullptr;
  1538. unsigned diagID;
  1539. DS.SetTypeSpecType(TST_typename, identifierLocs[i], prevSpec, diagID,
  1540. typeArg, Actions.getASTContext().getPrintingPolicy());
  1541. // Form a declarator to turn this into a type.
  1542. Declarator D(DS, ParsedAttributesView::none(),
  1543. DeclaratorContext::TypeName);
  1544. TypeResult fullTypeArg = Actions.ActOnTypeName(getCurScope(), D);
  1545. if (fullTypeArg.isUsable()) {
  1546. typeArgs.push_back(fullTypeArg.get());
  1547. if (!foundValidTypeId) {
  1548. foundValidTypeId = identifiers[i];
  1549. foundValidTypeSrcLoc = identifierLocs[i];
  1550. }
  1551. } else {
  1552. invalid = true;
  1553. unknownTypeArgs.push_back(identifiers[i]);
  1554. unknownTypeArgsLoc.push_back(identifierLocs[i]);
  1555. }
  1556. } else {
  1557. invalid = true;
  1558. if (!Actions.LookupProtocol(identifiers[i], identifierLocs[i])) {
  1559. unknownTypeArgs.push_back(identifiers[i]);
  1560. unknownTypeArgsLoc.push_back(identifierLocs[i]);
  1561. } else if (!foundProtocolId) {
  1562. foundProtocolId = identifiers[i];
  1563. foundProtocolSrcLoc = identifierLocs[i];
  1564. }
  1565. }
  1566. }
  1567. // Continue parsing type-names.
  1568. do {
  1569. Token CurTypeTok = Tok;
  1570. TypeResult typeArg = ParseTypeName();
  1571. // Consume the '...' for a pack expansion.
  1572. SourceLocation ellipsisLoc;
  1573. TryConsumeToken(tok::ellipsis, ellipsisLoc);
  1574. if (typeArg.isUsable() && ellipsisLoc.isValid()) {
  1575. typeArg = Actions.ActOnPackExpansion(typeArg.get(), ellipsisLoc);
  1576. }
  1577. if (typeArg.isUsable()) {
  1578. typeArgs.push_back(typeArg.get());
  1579. if (!foundValidTypeId) {
  1580. foundValidTypeId = CurTypeTok.getIdentifierInfo();
  1581. foundValidTypeSrcLoc = CurTypeTok.getLocation();
  1582. }
  1583. } else {
  1584. invalid = true;
  1585. }
  1586. } while (TryConsumeToken(tok::comma));
  1587. // Diagnose the mix between type args and protocols.
  1588. if (foundProtocolId && foundValidTypeId)
  1589. Actions.DiagnoseTypeArgsAndProtocols(foundProtocolId, foundProtocolSrcLoc,
  1590. foundValidTypeId,
  1591. foundValidTypeSrcLoc);
  1592. // Diagnose unknown arg types.
  1593. ParsedType T;
  1594. if (unknownTypeArgs.size())
  1595. for (unsigned i = 0, e = unknownTypeArgsLoc.size(); i < e; ++i)
  1596. Actions.DiagnoseUnknownTypeName(unknownTypeArgs[i], unknownTypeArgsLoc[i],
  1597. getCurScope(), nullptr, T);
  1598. // Parse the closing '>'.
  1599. SourceLocation rAngleLoc;
  1600. (void)ParseGreaterThanInTemplateList(lAngleLoc, rAngleLoc, consumeLastToken,
  1601. /*ObjCGenericList=*/true);
  1602. if (invalid) {
  1603. typeArgs.clear();
  1604. return;
  1605. }
  1606. // Record left/right angle locations.
  1607. typeArgsLAngleLoc = lAngleLoc;
  1608. typeArgsRAngleLoc = rAngleLoc;
  1609. }
  1610. void Parser::parseObjCTypeArgsAndProtocolQualifiers(
  1611. ParsedType baseType,
  1612. SourceLocation &typeArgsLAngleLoc,
  1613. SmallVectorImpl<ParsedType> &typeArgs,
  1614. SourceLocation &typeArgsRAngleLoc,
  1615. SourceLocation &protocolLAngleLoc,
  1616. SmallVectorImpl<Decl *> &protocols,
  1617. SmallVectorImpl<SourceLocation> &protocolLocs,
  1618. SourceLocation &protocolRAngleLoc,
  1619. bool consumeLastToken) {
  1620. assert(Tok.is(tok::less));
  1621. // Parse the first angle-bracket-delimited clause.
  1622. parseObjCTypeArgsOrProtocolQualifiers(baseType,
  1623. typeArgsLAngleLoc,
  1624. typeArgs,
  1625. typeArgsRAngleLoc,
  1626. protocolLAngleLoc,
  1627. protocols,
  1628. protocolLocs,
  1629. protocolRAngleLoc,
  1630. consumeLastToken,
  1631. /*warnOnIncompleteProtocols=*/false);
  1632. if (Tok.is(tok::eof)) // Nothing else to do here...
  1633. return;
  1634. // An Objective-C object pointer followed by type arguments
  1635. // can then be followed again by a set of protocol references, e.g.,
  1636. // \c NSArray<NSView><NSTextDelegate>
  1637. if ((consumeLastToken && Tok.is(tok::less)) ||
  1638. (!consumeLastToken && NextToken().is(tok::less))) {
  1639. // If we aren't consuming the last token, the prior '>' is still hanging
  1640. // there. Consume it before we parse the protocol qualifiers.
  1641. if (!consumeLastToken)
  1642. ConsumeToken();
  1643. if (!protocols.empty()) {
  1644. SkipUntilFlags skipFlags = SkipUntilFlags();
  1645. if (!consumeLastToken)
  1646. skipFlags = skipFlags | StopBeforeMatch;
  1647. Diag(Tok, diag::err_objc_type_args_after_protocols)
  1648. << SourceRange(protocolLAngleLoc, protocolRAngleLoc);
  1649. SkipUntil(tok::greater, tok::greatergreater, skipFlags);
  1650. } else {
  1651. ParseObjCProtocolReferences(protocols, protocolLocs,
  1652. /*WarnOnDeclarations=*/false,
  1653. /*ForObjCContainer=*/false,
  1654. protocolLAngleLoc, protocolRAngleLoc,
  1655. consumeLastToken);
  1656. }
  1657. }
  1658. }
  1659. TypeResult Parser::parseObjCTypeArgsAndProtocolQualifiers(
  1660. SourceLocation loc,
  1661. ParsedType type,
  1662. bool consumeLastToken,
  1663. SourceLocation &endLoc) {
  1664. assert(Tok.is(tok::less));
  1665. SourceLocation typeArgsLAngleLoc;
  1666. SmallVector<ParsedType, 4> typeArgs;
  1667. SourceLocation typeArgsRAngleLoc;
  1668. SourceLocation protocolLAngleLoc;
  1669. SmallVector<Decl *, 4> protocols;
  1670. SmallVector<SourceLocation, 4> protocolLocs;
  1671. SourceLocation protocolRAngleLoc;
  1672. // Parse type arguments and protocol qualifiers.
  1673. parseObjCTypeArgsAndProtocolQualifiers(type, typeArgsLAngleLoc, typeArgs,
  1674. typeArgsRAngleLoc, protocolLAngleLoc,
  1675. protocols, protocolLocs,
  1676. protocolRAngleLoc, consumeLastToken);
  1677. if (Tok.is(tok::eof))
  1678. return true; // Invalid type result.
  1679. // Compute the location of the last token.
  1680. if (consumeLastToken)
  1681. endLoc = PrevTokLocation;
  1682. else
  1683. endLoc = Tok.getLocation();
  1684. return Actions.actOnObjCTypeArgsAndProtocolQualifiers(
  1685. getCurScope(),
  1686. loc,
  1687. type,
  1688. typeArgsLAngleLoc,
  1689. typeArgs,
  1690. typeArgsRAngleLoc,
  1691. protocolLAngleLoc,
  1692. protocols,
  1693. protocolLocs,
  1694. protocolRAngleLoc);
  1695. }
  1696. void Parser::HelperActionsForIvarDeclarations(
  1697. ObjCContainerDecl *interfaceDecl, SourceLocation atLoc,
  1698. BalancedDelimiterTracker &T, SmallVectorImpl<Decl *> &AllIvarDecls,
  1699. bool RBraceMissing) {
  1700. if (!RBraceMissing)
  1701. T.consumeClose();
  1702. assert(getObjCDeclContext() == interfaceDecl &&
  1703. "Ivars should have interfaceDecl as their decl context");
  1704. Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls);
  1705. // Call ActOnFields() even if we don't have any decls. This is useful
  1706. // for code rewriting tools that need to be aware of the empty list.
  1707. Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl, AllIvarDecls,
  1708. T.getOpenLocation(), T.getCloseLocation(),
  1709. ParsedAttributesView());
  1710. }
  1711. /// objc-class-instance-variables:
  1712. /// '{' objc-instance-variable-decl-list[opt] '}'
  1713. ///
  1714. /// objc-instance-variable-decl-list:
  1715. /// objc-visibility-spec
  1716. /// objc-instance-variable-decl ';'
  1717. /// ';'
  1718. /// objc-instance-variable-decl-list objc-visibility-spec
  1719. /// objc-instance-variable-decl-list objc-instance-variable-decl ';'
  1720. /// objc-instance-variable-decl-list static_assert-declaration
  1721. /// objc-instance-variable-decl-list ';'
  1722. ///
  1723. /// objc-visibility-spec:
  1724. /// @private
  1725. /// @protected
  1726. /// @public
  1727. /// @package [OBJC2]
  1728. ///
  1729. /// objc-instance-variable-decl:
  1730. /// struct-declaration
  1731. ///
  1732. void Parser::ParseObjCClassInstanceVariables(ObjCContainerDecl *interfaceDecl,
  1733. tok::ObjCKeywordKind visibility,
  1734. SourceLocation atLoc) {
  1735. assert(Tok.is(tok::l_brace) && "expected {");
  1736. SmallVector<Decl *, 32> AllIvarDecls;
  1737. ParseScope ClassScope(this, Scope::DeclScope | Scope::ClassScope);
  1738. BalancedDelimiterTracker T(*this, tok::l_brace);
  1739. T.consumeOpen();
  1740. // While we still have something to read, read the instance variables.
  1741. while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
  1742. // Each iteration of this loop reads one objc-instance-variable-decl.
  1743. // Check for extraneous top-level semicolon.
  1744. if (Tok.is(tok::semi)) {
  1745. ConsumeExtraSemi(InstanceVariableList);
  1746. continue;
  1747. }
  1748. // Set the default visibility to private.
  1749. if (TryConsumeToken(tok::at)) { // parse objc-visibility-spec
  1750. if (Tok.is(tok::code_completion)) {
  1751. cutOffParsing();
  1752. Actions.CodeCompleteObjCAtVisibility(getCurScope());
  1753. return;
  1754. }
  1755. switch (Tok.getObjCKeywordID()) {
  1756. case tok::objc_private:
  1757. case tok::objc_public:
  1758. case tok::objc_protected:
  1759. case tok::objc_package:
  1760. visibility = Tok.getObjCKeywordID();
  1761. ConsumeToken();
  1762. continue;
  1763. case tok::objc_end:
  1764. Diag(Tok, diag::err_objc_unexpected_atend);
  1765. Tok.setLocation(Tok.getLocation().getLocWithOffset(-1));
  1766. Tok.setKind(tok::at);
  1767. Tok.setLength(1);
  1768. PP.EnterToken(Tok, /*IsReinject*/true);
  1769. HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
  1770. T, AllIvarDecls, true);
  1771. return;
  1772. default:
  1773. Diag(Tok, diag::err_objc_illegal_visibility_spec);
  1774. continue;
  1775. }
  1776. }
  1777. if (Tok.is(tok::code_completion)) {
  1778. cutOffParsing();
  1779. Actions.CodeCompleteOrdinaryName(getCurScope(),
  1780. Sema::PCC_ObjCInstanceVariableList);
  1781. return;
  1782. }
  1783. // This needs to duplicate a small amount of code from
  1784. // ParseStructUnionBody() for things that should work in both
  1785. // C struct and in Objective-C class instance variables.
  1786. if (Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
  1787. SourceLocation DeclEnd;
  1788. ParseStaticAssertDeclaration(DeclEnd);
  1789. continue;
  1790. }
  1791. auto ObjCIvarCallback = [&](ParsingFieldDeclarator &FD) {
  1792. assert(getObjCDeclContext() == interfaceDecl &&
  1793. "Ivar should have interfaceDecl as its decl context");
  1794. // Install the declarator into the interface decl.
  1795. FD.D.setObjCIvar(true);
  1796. Decl *Field = Actions.ActOnIvar(
  1797. getCurScope(), FD.D.getDeclSpec().getSourceRange().getBegin(), FD.D,
  1798. FD.BitfieldSize, visibility);
  1799. if (Field)
  1800. AllIvarDecls.push_back(Field);
  1801. FD.complete(Field);
  1802. };
  1803. // Parse all the comma separated declarators.
  1804. ParsingDeclSpec DS(*this);
  1805. ParseStructDeclaration(DS, ObjCIvarCallback);
  1806. if (Tok.is(tok::semi)) {
  1807. ConsumeToken();
  1808. } else {
  1809. Diag(Tok, diag::err_expected_semi_decl_list);
  1810. // Skip to end of block or statement
  1811. SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
  1812. }
  1813. }
  1814. HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
  1815. T, AllIvarDecls, false);
  1816. }
  1817. /// objc-protocol-declaration:
  1818. /// objc-protocol-definition
  1819. /// objc-protocol-forward-reference
  1820. ///
  1821. /// objc-protocol-definition:
  1822. /// \@protocol identifier
  1823. /// objc-protocol-refs[opt]
  1824. /// objc-interface-decl-list
  1825. /// \@end
  1826. ///
  1827. /// objc-protocol-forward-reference:
  1828. /// \@protocol identifier-list ';'
  1829. ///
  1830. /// "\@protocol identifier ;" should be resolved as "\@protocol
  1831. /// identifier-list ;": objc-interface-decl-list may not start with a
  1832. /// semicolon in the first alternative if objc-protocol-refs are omitted.
  1833. Parser::DeclGroupPtrTy
  1834. Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
  1835. ParsedAttributes &attrs) {
  1836. assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
  1837. "ParseObjCAtProtocolDeclaration(): Expected @protocol");
  1838. ConsumeToken(); // the "protocol" identifier
  1839. if (Tok.is(tok::code_completion)) {
  1840. cutOffParsing();
  1841. Actions.CodeCompleteObjCProtocolDecl(getCurScope());
  1842. return nullptr;
  1843. }
  1844. MaybeSkipAttributes(tok::objc_protocol);
  1845. if (expectIdentifier())
  1846. return nullptr; // missing protocol name.
  1847. // Save the protocol name, then consume it.
  1848. IdentifierInfo *protocolName = Tok.getIdentifierInfo();
  1849. SourceLocation nameLoc = ConsumeToken();
  1850. if (TryConsumeToken(tok::semi)) { // forward declaration of one protocol.
  1851. IdentifierLocPair ProtoInfo(protocolName, nameLoc);
  1852. return Actions.ActOnForwardProtocolDeclaration(AtLoc, ProtoInfo, attrs);
  1853. }
  1854. CheckNestedObjCContexts(AtLoc);
  1855. if (Tok.is(tok::comma)) { // list of forward declarations.
  1856. SmallVector<IdentifierLocPair, 8> ProtocolRefs;
  1857. ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
  1858. // Parse the list of forward declarations.
  1859. while (true) {
  1860. ConsumeToken(); // the ','
  1861. if (expectIdentifier()) {
  1862. SkipUntil(tok::semi);
  1863. return nullptr;
  1864. }
  1865. ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
  1866. Tok.getLocation()));
  1867. ConsumeToken(); // the identifier
  1868. if (Tok.isNot(tok::comma))
  1869. break;
  1870. }
  1871. // Consume the ';'.
  1872. if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@protocol"))
  1873. return nullptr;
  1874. return Actions.ActOnForwardProtocolDeclaration(AtLoc, ProtocolRefs, attrs);
  1875. }
  1876. // Last, and definitely not least, parse a protocol declaration.
  1877. SourceLocation LAngleLoc, EndProtoLoc;
  1878. SmallVector<Decl *, 8> ProtocolRefs;
  1879. SmallVector<SourceLocation, 8> ProtocolLocs;
  1880. if (Tok.is(tok::less) &&
  1881. ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false, true,
  1882. LAngleLoc, EndProtoLoc,
  1883. /*consumeLastToken=*/true))
  1884. return nullptr;
  1885. Sema::SkipBodyInfo SkipBody;
  1886. ObjCProtocolDecl *ProtoType = Actions.ActOnStartProtocolInterface(
  1887. AtLoc, protocolName, nameLoc, ProtocolRefs.data(), ProtocolRefs.size(),
  1888. ProtocolLocs.data(), EndProtoLoc, attrs, &SkipBody);
  1889. ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType);
  1890. if (SkipBody.CheckSameAsPrevious) {
  1891. auto *PreviousDef = cast<ObjCProtocolDecl>(SkipBody.Previous);
  1892. if (Actions.ActOnDuplicateODRHashDefinition(ProtoType, PreviousDef)) {
  1893. ProtoType->mergeDuplicateDefinitionWithCommon(
  1894. PreviousDef->getDefinition());
  1895. } else {
  1896. ODRDiagsEmitter DiagsEmitter(Diags, Actions.getASTContext(),
  1897. getPreprocessor().getLangOpts());
  1898. DiagsEmitter.diagnoseMismatch(PreviousDef, ProtoType);
  1899. }
  1900. }
  1901. return Actions.ConvertDeclToDeclGroup(ProtoType);
  1902. }
  1903. /// objc-implementation:
  1904. /// objc-class-implementation-prologue
  1905. /// objc-category-implementation-prologue
  1906. ///
  1907. /// objc-class-implementation-prologue:
  1908. /// @implementation identifier objc-superclass[opt]
  1909. /// objc-class-instance-variables[opt]
  1910. ///
  1911. /// objc-category-implementation-prologue:
  1912. /// @implementation identifier ( identifier )
  1913. Parser::DeclGroupPtrTy
  1914. Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc,
  1915. ParsedAttributes &Attrs) {
  1916. assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
  1917. "ParseObjCAtImplementationDeclaration(): Expected @implementation");
  1918. CheckNestedObjCContexts(AtLoc);
  1919. ConsumeToken(); // the "implementation" identifier
  1920. // Code completion after '@implementation'.
  1921. if (Tok.is(tok::code_completion)) {
  1922. cutOffParsing();
  1923. Actions.CodeCompleteObjCImplementationDecl(getCurScope());
  1924. return nullptr;
  1925. }
  1926. MaybeSkipAttributes(tok::objc_implementation);
  1927. if (expectIdentifier())
  1928. return nullptr; // missing class or category name.
  1929. // We have a class or category name - consume it.
  1930. IdentifierInfo *nameId = Tok.getIdentifierInfo();
  1931. SourceLocation nameLoc = ConsumeToken(); // consume class or category name
  1932. ObjCImplDecl *ObjCImpDecl = nullptr;
  1933. // Neither a type parameter list nor a list of protocol references is
  1934. // permitted here. Parse and diagnose them.
  1935. if (Tok.is(tok::less)) {
  1936. SourceLocation lAngleLoc, rAngleLoc;
  1937. SmallVector<IdentifierLocPair, 8> protocolIdents;
  1938. SourceLocation diagLoc = Tok.getLocation();
  1939. ObjCTypeParamListScope typeParamScope(Actions, getCurScope());
  1940. if (parseObjCTypeParamListOrProtocolRefs(typeParamScope, lAngleLoc,
  1941. protocolIdents, rAngleLoc)) {
  1942. Diag(diagLoc, diag::err_objc_parameterized_implementation)
  1943. << SourceRange(diagLoc, PrevTokLocation);
  1944. } else if (lAngleLoc.isValid()) {
  1945. Diag(lAngleLoc, diag::err_unexpected_protocol_qualifier)
  1946. << FixItHint::CreateRemoval(SourceRange(lAngleLoc, rAngleLoc));
  1947. }
  1948. }
  1949. if (Tok.is(tok::l_paren)) {
  1950. // we have a category implementation.
  1951. ConsumeParen();
  1952. SourceLocation categoryLoc, rparenLoc;
  1953. IdentifierInfo *categoryId = nullptr;
  1954. if (Tok.is(tok::code_completion)) {
  1955. cutOffParsing();
  1956. Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
  1957. return nullptr;
  1958. }
  1959. if (Tok.is(tok::identifier)) {
  1960. categoryId = Tok.getIdentifierInfo();
  1961. categoryLoc = ConsumeToken();
  1962. } else {
  1963. Diag(Tok, diag::err_expected)
  1964. << tok::identifier; // missing category name.
  1965. return nullptr;
  1966. }
  1967. if (Tok.isNot(tok::r_paren)) {
  1968. Diag(Tok, diag::err_expected) << tok::r_paren;
  1969. SkipUntil(tok::r_paren); // don't stop at ';'
  1970. return nullptr;
  1971. }
  1972. rparenLoc = ConsumeParen();
  1973. if (Tok.is(tok::less)) { // we have illegal '<' try to recover
  1974. Diag(Tok, diag::err_unexpected_protocol_qualifier);
  1975. SourceLocation protocolLAngleLoc, protocolRAngleLoc;
  1976. SmallVector<Decl *, 4> protocols;
  1977. SmallVector<SourceLocation, 4> protocolLocs;
  1978. (void)ParseObjCProtocolReferences(protocols, protocolLocs,
  1979. /*warnOnIncompleteProtocols=*/false,
  1980. /*ForObjCContainer=*/false,
  1981. protocolLAngleLoc, protocolRAngleLoc,
  1982. /*consumeLastToken=*/true);
  1983. }
  1984. ObjCImpDecl = Actions.ActOnStartCategoryImplementation(
  1985. AtLoc, nameId, nameLoc, categoryId, categoryLoc, Attrs);
  1986. } else {
  1987. // We have a class implementation
  1988. SourceLocation superClassLoc;
  1989. IdentifierInfo *superClassId = nullptr;
  1990. if (TryConsumeToken(tok::colon)) {
  1991. // We have a super class
  1992. if (expectIdentifier())
  1993. return nullptr; // missing super class name.
  1994. superClassId = Tok.getIdentifierInfo();
  1995. superClassLoc = ConsumeToken(); // Consume super class name
  1996. }
  1997. ObjCImpDecl = Actions.ActOnStartClassImplementation(
  1998. AtLoc, nameId, nameLoc, superClassId, superClassLoc, Attrs);
  1999. if (Tok.is(tok::l_brace)) // we have ivars
  2000. ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc);
  2001. else if (Tok.is(tok::less)) { // we have illegal '<' try to recover
  2002. Diag(Tok, diag::err_unexpected_protocol_qualifier);
  2003. SourceLocation protocolLAngleLoc, protocolRAngleLoc;
  2004. SmallVector<Decl *, 4> protocols;
  2005. SmallVector<SourceLocation, 4> protocolLocs;
  2006. (void)ParseObjCProtocolReferences(protocols, protocolLocs,
  2007. /*warnOnIncompleteProtocols=*/false,
  2008. /*ForObjCContainer=*/false,
  2009. protocolLAngleLoc, protocolRAngleLoc,
  2010. /*consumeLastToken=*/true);
  2011. }
  2012. }
  2013. assert(ObjCImpDecl);
  2014. SmallVector<Decl *, 8> DeclsInGroup;
  2015. {
  2016. ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl);
  2017. while (!ObjCImplParsing.isFinished() && !isEofOrEom()) {
  2018. ParsedAttributes DeclAttrs(AttrFactory);
  2019. MaybeParseCXX11Attributes(DeclAttrs);
  2020. ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
  2021. if (DeclGroupPtrTy DGP =
  2022. ParseExternalDeclaration(DeclAttrs, EmptyDeclSpecAttrs)) {
  2023. DeclGroupRef DG = DGP.get();
  2024. DeclsInGroup.append(DG.begin(), DG.end());
  2025. }
  2026. }
  2027. }
  2028. return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup);
  2029. }
  2030. Parser::DeclGroupPtrTy
  2031. Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
  2032. assert(Tok.isObjCAtKeyword(tok::objc_end) &&
  2033. "ParseObjCAtEndDeclaration(): Expected @end");
  2034. ConsumeToken(); // the "end" identifier
  2035. if (CurParsedObjCImpl)
  2036. CurParsedObjCImpl->finish(atEnd);
  2037. else
  2038. // missing @implementation
  2039. Diag(atEnd.getBegin(), diag::err_expected_objc_container);
  2040. return nullptr;
  2041. }
  2042. Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() {
  2043. if (!Finished) {
  2044. finish(P.Tok.getLocation());
  2045. if (P.isEofOrEom()) {
  2046. P.Diag(P.Tok, diag::err_objc_missing_end)
  2047. << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n");
  2048. P.Diag(Dcl->getBeginLoc(), diag::note_objc_container_start)
  2049. << Sema::OCK_Implementation;
  2050. }
  2051. }
  2052. P.CurParsedObjCImpl = nullptr;
  2053. assert(LateParsedObjCMethods.empty());
  2054. }
  2055. void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) {
  2056. assert(!Finished);
  2057. P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl, AtEnd.getBegin());
  2058. for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
  2059. P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
  2060. true/*Methods*/);
  2061. P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd);
  2062. if (HasCFunction)
  2063. for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
  2064. P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
  2065. false/*c-functions*/);
  2066. /// Clear and free the cached objc methods.
  2067. for (LateParsedObjCMethodContainer::iterator
  2068. I = LateParsedObjCMethods.begin(),
  2069. E = LateParsedObjCMethods.end(); I != E; ++I)
  2070. delete *I;
  2071. LateParsedObjCMethods.clear();
  2072. Finished = true;
  2073. }
  2074. /// compatibility-alias-decl:
  2075. /// @compatibility_alias alias-name class-name ';'
  2076. ///
  2077. Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
  2078. assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
  2079. "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
  2080. ConsumeToken(); // consume compatibility_alias
  2081. if (expectIdentifier())
  2082. return nullptr;
  2083. IdentifierInfo *aliasId = Tok.getIdentifierInfo();
  2084. SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
  2085. if (expectIdentifier())
  2086. return nullptr;
  2087. IdentifierInfo *classId = Tok.getIdentifierInfo();
  2088. SourceLocation classLoc = ConsumeToken(); // consume class-name;
  2089. ExpectAndConsume(tok::semi, diag::err_expected_after, "@compatibility_alias");
  2090. return Actions.ActOnCompatibilityAlias(atLoc, aliasId, aliasLoc,
  2091. classId, classLoc);
  2092. }
  2093. /// property-synthesis:
  2094. /// @synthesize property-ivar-list ';'
  2095. ///
  2096. /// property-ivar-list:
  2097. /// property-ivar
  2098. /// property-ivar-list ',' property-ivar
  2099. ///
  2100. /// property-ivar:
  2101. /// identifier
  2102. /// identifier '=' identifier
  2103. ///
  2104. Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
  2105. assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
  2106. "ParseObjCPropertySynthesize(): Expected '@synthesize'");
  2107. ConsumeToken(); // consume synthesize
  2108. while (true) {
  2109. if (Tok.is(tok::code_completion)) {
  2110. cutOffParsing();
  2111. Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
  2112. return nullptr;
  2113. }
  2114. if (Tok.isNot(tok::identifier)) {
  2115. Diag(Tok, diag::err_synthesized_property_name);
  2116. SkipUntil(tok::semi);
  2117. return nullptr;
  2118. }
  2119. IdentifierInfo *propertyIvar = nullptr;
  2120. IdentifierInfo *propertyId = Tok.getIdentifierInfo();
  2121. SourceLocation propertyLoc = ConsumeToken(); // consume property name
  2122. SourceLocation propertyIvarLoc;
  2123. if (TryConsumeToken(tok::equal)) {
  2124. // property '=' ivar-name
  2125. if (Tok.is(tok::code_completion)) {
  2126. cutOffParsing();
  2127. Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId);
  2128. return nullptr;
  2129. }
  2130. if (expectIdentifier())
  2131. break;
  2132. propertyIvar = Tok.getIdentifierInfo();
  2133. propertyIvarLoc = ConsumeToken(); // consume ivar-name
  2134. }
  2135. Actions.ActOnPropertyImplDecl(
  2136. getCurScope(), atLoc, propertyLoc, true,
  2137. propertyId, propertyIvar, propertyIvarLoc,
  2138. ObjCPropertyQueryKind::OBJC_PR_query_unknown);
  2139. if (Tok.isNot(tok::comma))
  2140. break;
  2141. ConsumeToken(); // consume ','
  2142. }
  2143. ExpectAndConsume(tok::semi, diag::err_expected_after, "@synthesize");
  2144. return nullptr;
  2145. }
  2146. /// property-dynamic:
  2147. /// @dynamic property-list
  2148. ///
  2149. /// property-list:
  2150. /// identifier
  2151. /// property-list ',' identifier
  2152. ///
  2153. Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
  2154. assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
  2155. "ParseObjCPropertyDynamic(): Expected '@dynamic'");
  2156. ConsumeToken(); // consume dynamic
  2157. bool isClassProperty = false;
  2158. if (Tok.is(tok::l_paren)) {
  2159. ConsumeParen();
  2160. const IdentifierInfo *II = Tok.getIdentifierInfo();
  2161. if (!II) {
  2162. Diag(Tok, diag::err_objc_expected_property_attr) << II;
  2163. SkipUntil(tok::r_paren, StopAtSemi);
  2164. } else {
  2165. SourceLocation AttrName = ConsumeToken(); // consume attribute name
  2166. if (II->isStr("class")) {
  2167. isClassProperty = true;
  2168. if (Tok.isNot(tok::r_paren)) {
  2169. Diag(Tok, diag::err_expected) << tok::r_paren;
  2170. SkipUntil(tok::r_paren, StopAtSemi);
  2171. } else
  2172. ConsumeParen();
  2173. } else {
  2174. Diag(AttrName, diag::err_objc_expected_property_attr) << II;
  2175. SkipUntil(tok::r_paren, StopAtSemi);
  2176. }
  2177. }
  2178. }
  2179. while (true) {
  2180. if (Tok.is(tok::code_completion)) {
  2181. cutOffParsing();
  2182. Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
  2183. return nullptr;
  2184. }
  2185. if (expectIdentifier()) {
  2186. SkipUntil(tok::semi);
  2187. return nullptr;
  2188. }
  2189. IdentifierInfo *propertyId = Tok.getIdentifierInfo();
  2190. SourceLocation propertyLoc = ConsumeToken(); // consume property name
  2191. Actions.ActOnPropertyImplDecl(
  2192. getCurScope(), atLoc, propertyLoc, false,
  2193. propertyId, nullptr, SourceLocation(),
  2194. isClassProperty ? ObjCPropertyQueryKind::OBJC_PR_query_class :
  2195. ObjCPropertyQueryKind::OBJC_PR_query_unknown);
  2196. if (Tok.isNot(tok::comma))
  2197. break;
  2198. ConsumeToken(); // consume ','
  2199. }
  2200. ExpectAndConsume(tok::semi, diag::err_expected_after, "@dynamic");
  2201. return nullptr;
  2202. }
  2203. /// objc-throw-statement:
  2204. /// throw expression[opt];
  2205. ///
  2206. StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
  2207. ExprResult Res;
  2208. ConsumeToken(); // consume throw
  2209. if (Tok.isNot(tok::semi)) {
  2210. Res = ParseExpression();
  2211. if (Res.isInvalid()) {
  2212. SkipUntil(tok::semi);
  2213. return StmtError();
  2214. }
  2215. }
  2216. // consume ';'
  2217. ExpectAndConsume(tok::semi, diag::err_expected_after, "@throw");
  2218. return Actions.ActOnObjCAtThrowStmt(atLoc, Res.get(), getCurScope());
  2219. }
  2220. /// objc-synchronized-statement:
  2221. /// @synchronized '(' expression ')' compound-statement
  2222. ///
  2223. StmtResult
  2224. Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
  2225. ConsumeToken(); // consume synchronized
  2226. if (Tok.isNot(tok::l_paren)) {
  2227. Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
  2228. return StmtError();
  2229. }
  2230. // The operand is surrounded with parentheses.
  2231. ConsumeParen(); // '('
  2232. ExprResult operand(ParseExpression());
  2233. if (Tok.is(tok::r_paren)) {
  2234. ConsumeParen(); // ')'
  2235. } else {
  2236. if (!operand.isInvalid())
  2237. Diag(Tok, diag::err_expected) << tok::r_paren;
  2238. // Skip forward until we see a left brace, but don't consume it.
  2239. SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
  2240. }
  2241. // Require a compound statement.
  2242. if (Tok.isNot(tok::l_brace)) {
  2243. if (!operand.isInvalid())
  2244. Diag(Tok, diag::err_expected) << tok::l_brace;
  2245. return StmtError();
  2246. }
  2247. // Check the @synchronized operand now.
  2248. if (!operand.isInvalid())
  2249. operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.get());
  2250. // Parse the compound statement within a new scope.
  2251. ParseScope bodyScope(this, Scope::DeclScope | Scope::CompoundStmtScope);
  2252. StmtResult body(ParseCompoundStatementBody());
  2253. bodyScope.Exit();
  2254. // If there was a semantic or parse error earlier with the
  2255. // operand, fail now.
  2256. if (operand.isInvalid())
  2257. return StmtError();
  2258. if (body.isInvalid())
  2259. body = Actions.ActOnNullStmt(Tok.getLocation());
  2260. return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get());
  2261. }
  2262. /// objc-try-catch-statement:
  2263. /// @try compound-statement objc-catch-list[opt]
  2264. /// @try compound-statement objc-catch-list[opt] @finally compound-statement
  2265. ///
  2266. /// objc-catch-list:
  2267. /// @catch ( parameter-declaration ) compound-statement
  2268. /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
  2269. /// catch-parameter-declaration:
  2270. /// parameter-declaration
  2271. /// '...' [OBJC2]
  2272. ///
  2273. StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
  2274. bool catch_or_finally_seen = false;
  2275. ConsumeToken(); // consume try
  2276. if (Tok.isNot(tok::l_brace)) {
  2277. Diag(Tok, diag::err_expected) << tok::l_brace;
  2278. return StmtError();
  2279. }
  2280. StmtVector CatchStmts;
  2281. StmtResult FinallyStmt;
  2282. ParseScope TryScope(this, Scope::DeclScope | Scope::CompoundStmtScope);
  2283. StmtResult TryBody(ParseCompoundStatementBody());
  2284. TryScope.Exit();
  2285. if (TryBody.isInvalid())
  2286. TryBody = Actions.ActOnNullStmt(Tok.getLocation());
  2287. while (Tok.is(tok::at)) {
  2288. // At this point, we need to lookahead to determine if this @ is the start
  2289. // of an @catch or @finally. We don't want to consume the @ token if this
  2290. // is an @try or @encode or something else.
  2291. Token AfterAt = GetLookAheadToken(1);
  2292. if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
  2293. !AfterAt.isObjCAtKeyword(tok::objc_finally))
  2294. break;
  2295. SourceLocation AtCatchFinallyLoc = ConsumeToken();
  2296. if (Tok.isObjCAtKeyword(tok::objc_catch)) {
  2297. Decl *FirstPart = nullptr;
  2298. ConsumeToken(); // consume catch
  2299. if (Tok.is(tok::l_paren)) {
  2300. ConsumeParen();
  2301. ParseScope CatchScope(this, Scope::DeclScope |
  2302. Scope::CompoundStmtScope |
  2303. Scope::AtCatchScope);
  2304. if (Tok.isNot(tok::ellipsis)) {
  2305. DeclSpec DS(AttrFactory);
  2306. ParseDeclarationSpecifiers(DS);
  2307. Declarator ParmDecl(DS, ParsedAttributesView::none(),
  2308. DeclaratorContext::ObjCCatch);
  2309. ParseDeclarator(ParmDecl);
  2310. // Inform the actions module about the declarator, so it
  2311. // gets added to the current scope.
  2312. FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
  2313. } else
  2314. ConsumeToken(); // consume '...'
  2315. SourceLocation RParenLoc;
  2316. if (Tok.is(tok::r_paren))
  2317. RParenLoc = ConsumeParen();
  2318. else // Skip over garbage, until we get to ')'. Eat the ')'.
  2319. SkipUntil(tok::r_paren, StopAtSemi);
  2320. StmtResult CatchBody(true);
  2321. if (Tok.is(tok::l_brace))
  2322. CatchBody = ParseCompoundStatementBody();
  2323. else
  2324. Diag(Tok, diag::err_expected) << tok::l_brace;
  2325. if (CatchBody.isInvalid())
  2326. CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
  2327. StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
  2328. RParenLoc,
  2329. FirstPart,
  2330. CatchBody.get());
  2331. if (!Catch.isInvalid())
  2332. CatchStmts.push_back(Catch.get());
  2333. } else {
  2334. Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
  2335. << "@catch clause";
  2336. return StmtError();
  2337. }
  2338. catch_or_finally_seen = true;
  2339. } else {
  2340. assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
  2341. ConsumeToken(); // consume finally
  2342. ParseScope FinallyScope(this,
  2343. Scope::DeclScope | Scope::CompoundStmtScope);
  2344. bool ShouldCapture =
  2345. getTargetInfo().getTriple().isWindowsMSVCEnvironment();
  2346. if (ShouldCapture)
  2347. Actions.ActOnCapturedRegionStart(Tok.getLocation(), getCurScope(),
  2348. CR_ObjCAtFinally, 1);
  2349. StmtResult FinallyBody(true);
  2350. if (Tok.is(tok::l_brace))
  2351. FinallyBody = ParseCompoundStatementBody();
  2352. else
  2353. Diag(Tok, diag::err_expected) << tok::l_brace;
  2354. if (FinallyBody.isInvalid()) {
  2355. FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
  2356. if (ShouldCapture)
  2357. Actions.ActOnCapturedRegionError();
  2358. } else if (ShouldCapture) {
  2359. FinallyBody = Actions.ActOnCapturedRegionEnd(FinallyBody.get());
  2360. }
  2361. FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
  2362. FinallyBody.get());
  2363. catch_or_finally_seen = true;
  2364. break;
  2365. }
  2366. }
  2367. if (!catch_or_finally_seen) {
  2368. Diag(atLoc, diag::err_missing_catch_finally);
  2369. return StmtError();
  2370. }
  2371. return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.get(),
  2372. CatchStmts,
  2373. FinallyStmt.get());
  2374. }
  2375. /// objc-autoreleasepool-statement:
  2376. /// @autoreleasepool compound-statement
  2377. ///
  2378. StmtResult
  2379. Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
  2380. ConsumeToken(); // consume autoreleasepool
  2381. if (Tok.isNot(tok::l_brace)) {
  2382. Diag(Tok, diag::err_expected) << tok::l_brace;
  2383. return StmtError();
  2384. }
  2385. // Enter a scope to hold everything within the compound stmt. Compound
  2386. // statements can always hold declarations.
  2387. ParseScope BodyScope(this, Scope::DeclScope | Scope::CompoundStmtScope);
  2388. StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
  2389. BodyScope.Exit();
  2390. if (AutoreleasePoolBody.isInvalid())
  2391. AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
  2392. return Actions.ActOnObjCAutoreleasePoolStmt(atLoc,
  2393. AutoreleasePoolBody.get());
  2394. }
  2395. /// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them
  2396. /// for later parsing.
  2397. void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) {
  2398. if (SkipFunctionBodies && (!MDecl || Actions.canSkipFunctionBody(MDecl)) &&
  2399. trySkippingFunctionBody()) {
  2400. Actions.ActOnSkippedFunctionBody(MDecl);
  2401. return;
  2402. }
  2403. LexedMethod* LM = new LexedMethod(this, MDecl);
  2404. CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM);
  2405. CachedTokens &Toks = LM->Toks;
  2406. // Begin by storing the '{' or 'try' or ':' token.
  2407. Toks.push_back(Tok);
  2408. if (Tok.is(tok::kw_try)) {
  2409. ConsumeToken();
  2410. if (Tok.is(tok::colon)) {
  2411. Toks.push_back(Tok);
  2412. ConsumeToken();
  2413. while (Tok.isNot(tok::l_brace)) {
  2414. ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
  2415. ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
  2416. }
  2417. }
  2418. Toks.push_back(Tok); // also store '{'
  2419. }
  2420. else if (Tok.is(tok::colon)) {
  2421. ConsumeToken();
  2422. // FIXME: This is wrong, due to C++11 braced initialization.
  2423. while (Tok.isNot(tok::l_brace)) {
  2424. ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
  2425. ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
  2426. }
  2427. Toks.push_back(Tok); // also store '{'
  2428. }
  2429. ConsumeBrace();
  2430. // Consume everything up to (and including) the matching right brace.
  2431. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
  2432. while (Tok.is(tok::kw_catch)) {
  2433. ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
  2434. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
  2435. }
  2436. }
  2437. /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
  2438. ///
  2439. Decl *Parser::ParseObjCMethodDefinition() {
  2440. Decl *MDecl = ParseObjCMethodPrototype();
  2441. PrettyDeclStackTraceEntry CrashInfo(Actions.Context, MDecl, Tok.getLocation(),
  2442. "parsing Objective-C method");
  2443. // parse optional ';'
  2444. if (Tok.is(tok::semi)) {
  2445. if (CurParsedObjCImpl) {
  2446. Diag(Tok, diag::warn_semicolon_before_method_body)
  2447. << FixItHint::CreateRemoval(Tok.getLocation());
  2448. }
  2449. ConsumeToken();
  2450. }
  2451. // We should have an opening brace now.
  2452. if (Tok.isNot(tok::l_brace)) {
  2453. Diag(Tok, diag::err_expected_method_body);
  2454. // Skip over garbage, until we get to '{'. Don't eat the '{'.
  2455. SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
  2456. // If we didn't find the '{', bail out.
  2457. if (Tok.isNot(tok::l_brace))
  2458. return nullptr;
  2459. }
  2460. if (!MDecl) {
  2461. ConsumeBrace();
  2462. SkipUntil(tok::r_brace);
  2463. return nullptr;
  2464. }
  2465. // Allow the rest of sema to find private method decl implementations.
  2466. Actions.AddAnyMethodToGlobalPool(MDecl);
  2467. assert (CurParsedObjCImpl
  2468. && "ParseObjCMethodDefinition - Method out of @implementation");
  2469. // Consume the tokens and store them for later parsing.
  2470. StashAwayMethodOrFunctionBodyTokens(MDecl);
  2471. return MDecl;
  2472. }
  2473. StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc,
  2474. ParsedStmtContext StmtCtx) {
  2475. if (Tok.is(tok::code_completion)) {
  2476. cutOffParsing();
  2477. Actions.CodeCompleteObjCAtStatement(getCurScope());
  2478. return StmtError();
  2479. }
  2480. if (Tok.isObjCAtKeyword(tok::objc_try))
  2481. return ParseObjCTryStmt(AtLoc);
  2482. if (Tok.isObjCAtKeyword(tok::objc_throw))
  2483. return ParseObjCThrowStmt(AtLoc);
  2484. if (Tok.isObjCAtKeyword(tok::objc_synchronized))
  2485. return ParseObjCSynchronizedStmt(AtLoc);
  2486. if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
  2487. return ParseObjCAutoreleasePoolStmt(AtLoc);
  2488. if (Tok.isObjCAtKeyword(tok::objc_import) &&
  2489. getLangOpts().DebuggerSupport) {
  2490. SkipUntil(tok::semi);
  2491. return Actions.ActOnNullStmt(Tok.getLocation());
  2492. }
  2493. ExprStatementTokLoc = AtLoc;
  2494. ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
  2495. if (Res.isInvalid()) {
  2496. // If the expression is invalid, skip ahead to the next semicolon. Not
  2497. // doing this opens us up to the possibility of infinite loops if
  2498. // ParseExpression does not consume any tokens.
  2499. SkipUntil(tok::semi);
  2500. return StmtError();
  2501. }
  2502. // Otherwise, eat the semicolon.
  2503. ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
  2504. return handleExprStmt(Res, StmtCtx);
  2505. }
  2506. ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
  2507. switch (Tok.getKind()) {
  2508. case tok::code_completion:
  2509. cutOffParsing();
  2510. Actions.CodeCompleteObjCAtExpression(getCurScope());
  2511. return ExprError();
  2512. case tok::minus:
  2513. case tok::plus: {
  2514. tok::TokenKind Kind = Tok.getKind();
  2515. SourceLocation OpLoc = ConsumeToken();
  2516. if (!Tok.is(tok::numeric_constant)) {
  2517. const char *Symbol = nullptr;
  2518. switch (Kind) {
  2519. case tok::minus: Symbol = "-"; break;
  2520. case tok::plus: Symbol = "+"; break;
  2521. default: llvm_unreachable("missing unary operator case");
  2522. }
  2523. Diag(Tok, diag::err_nsnumber_nonliteral_unary)
  2524. << Symbol;
  2525. return ExprError();
  2526. }
  2527. ExprResult Lit(Actions.ActOnNumericConstant(Tok));
  2528. if (Lit.isInvalid()) {
  2529. return Lit;
  2530. }
  2531. ConsumeToken(); // Consume the literal token.
  2532. Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.get());
  2533. if (Lit.isInvalid())
  2534. return Lit;
  2535. return ParsePostfixExpressionSuffix(
  2536. Actions.BuildObjCNumericLiteral(AtLoc, Lit.get()));
  2537. }
  2538. case tok::string_literal: // primary-expression: string-literal
  2539. case tok::wide_string_literal:
  2540. return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
  2541. case tok::char_constant:
  2542. return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc));
  2543. case tok::numeric_constant:
  2544. return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc));
  2545. case tok::kw_true: // Objective-C++, etc.
  2546. case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes
  2547. return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true));
  2548. case tok::kw_false: // Objective-C++, etc.
  2549. case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no
  2550. return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false));
  2551. case tok::l_square:
  2552. // Objective-C array literal
  2553. return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc));
  2554. case tok::l_brace:
  2555. // Objective-C dictionary literal
  2556. return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc));
  2557. case tok::l_paren:
  2558. // Objective-C boxed expression
  2559. return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc));
  2560. default:
  2561. if (Tok.getIdentifierInfo() == nullptr)
  2562. return ExprError(Diag(AtLoc, diag::err_unexpected_at));
  2563. switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
  2564. case tok::objc_encode:
  2565. return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
  2566. case tok::objc_protocol:
  2567. return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
  2568. case tok::objc_selector:
  2569. return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
  2570. case tok::objc_available:
  2571. return ParseAvailabilityCheckExpr(AtLoc);
  2572. default: {
  2573. const char *str = nullptr;
  2574. // Only provide the @try/@finally/@autoreleasepool fixit when we're sure
  2575. // that this is a proper statement where such directives could actually
  2576. // occur.
  2577. if (GetLookAheadToken(1).is(tok::l_brace) &&
  2578. ExprStatementTokLoc == AtLoc) {
  2579. char ch = Tok.getIdentifierInfo()->getNameStart()[0];
  2580. str =
  2581. ch == 't' ? "try"
  2582. : (ch == 'f' ? "finally"
  2583. : (ch == 'a' ? "autoreleasepool" : nullptr));
  2584. }
  2585. if (str) {
  2586. SourceLocation kwLoc = Tok.getLocation();
  2587. return ExprError(Diag(AtLoc, diag::err_unexpected_at) <<
  2588. FixItHint::CreateReplacement(kwLoc, str));
  2589. }
  2590. else
  2591. return ExprError(Diag(AtLoc, diag::err_unexpected_at));
  2592. }
  2593. }
  2594. }
  2595. }
  2596. /// Parse the receiver of an Objective-C++ message send.
  2597. ///
  2598. /// This routine parses the receiver of a message send in
  2599. /// Objective-C++ either as a type or as an expression. Note that this
  2600. /// routine must not be called to parse a send to 'super', since it
  2601. /// has no way to return such a result.
  2602. ///
  2603. /// \param IsExpr Whether the receiver was parsed as an expression.
  2604. ///
  2605. /// \param TypeOrExpr If the receiver was parsed as an expression (\c
  2606. /// IsExpr is true), the parsed expression. If the receiver was parsed
  2607. /// as a type (\c IsExpr is false), the parsed type.
  2608. ///
  2609. /// \returns True if an error occurred during parsing or semantic
  2610. /// analysis, in which case the arguments do not have valid
  2611. /// values. Otherwise, returns false for a successful parse.
  2612. ///
  2613. /// objc-receiver: [C++]
  2614. /// 'super' [not parsed here]
  2615. /// expression
  2616. /// simple-type-specifier
  2617. /// typename-specifier
  2618. bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
  2619. InMessageExpressionRAIIObject InMessage(*this, true);
  2620. if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_typename,
  2621. tok::annot_cxxscope))
  2622. TryAnnotateTypeOrScopeToken();
  2623. if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) {
  2624. // objc-receiver:
  2625. // expression
  2626. // Make sure any typos in the receiver are corrected or diagnosed, so that
  2627. // proper recovery can happen. FIXME: Perhaps filter the corrected expr to
  2628. // only the things that are valid ObjC receivers?
  2629. ExprResult Receiver = Actions.CorrectDelayedTyposInExpr(ParseExpression());
  2630. if (Receiver.isInvalid())
  2631. return true;
  2632. IsExpr = true;
  2633. TypeOrExpr = Receiver.get();
  2634. return false;
  2635. }
  2636. // objc-receiver:
  2637. // typename-specifier
  2638. // simple-type-specifier
  2639. // expression (that starts with one of the above)
  2640. DeclSpec DS(AttrFactory);
  2641. ParseCXXSimpleTypeSpecifier(DS);
  2642. if (Tok.is(tok::l_paren)) {
  2643. // If we see an opening parentheses at this point, we are
  2644. // actually parsing an expression that starts with a
  2645. // function-style cast, e.g.,
  2646. //
  2647. // postfix-expression:
  2648. // simple-type-specifier ( expression-list [opt] )
  2649. // typename-specifier ( expression-list [opt] )
  2650. //
  2651. // Parse the remainder of this case, then the (optional)
  2652. // postfix-expression suffix, followed by the (optional)
  2653. // right-hand side of the binary expression. We have an
  2654. // instance method.
  2655. ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
  2656. if (!Receiver.isInvalid())
  2657. Receiver = ParsePostfixExpressionSuffix(Receiver.get());
  2658. if (!Receiver.isInvalid())
  2659. Receiver = ParseRHSOfBinaryExpression(Receiver.get(), prec::Comma);
  2660. if (Receiver.isInvalid())
  2661. return true;
  2662. IsExpr = true;
  2663. TypeOrExpr = Receiver.get();
  2664. return false;
  2665. }
  2666. // We have a class message. Turn the simple-type-specifier or
  2667. // typename-specifier we parsed into a type and parse the
  2668. // remainder of the class message.
  2669. Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
  2670. DeclaratorContext::TypeName);
  2671. TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
  2672. if (Type.isInvalid())
  2673. return true;
  2674. IsExpr = false;
  2675. TypeOrExpr = Type.get().getAsOpaquePtr();
  2676. return false;
  2677. }
  2678. /// Determine whether the parser is currently referring to a an
  2679. /// Objective-C message send, using a simplified heuristic to avoid overhead.
  2680. ///
  2681. /// This routine will only return true for a subset of valid message-send
  2682. /// expressions.
  2683. bool Parser::isSimpleObjCMessageExpression() {
  2684. assert(Tok.is(tok::l_square) && getLangOpts().ObjC &&
  2685. "Incorrect start for isSimpleObjCMessageExpression");
  2686. return GetLookAheadToken(1).is(tok::identifier) &&
  2687. GetLookAheadToken(2).is(tok::identifier);
  2688. }
  2689. bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
  2690. if (!getLangOpts().ObjC || !NextToken().is(tok::identifier) ||
  2691. InMessageExpression)
  2692. return false;
  2693. TypeResult Type;
  2694. if (Tok.is(tok::annot_typename))
  2695. Type = getTypeAnnotation(Tok);
  2696. else if (Tok.is(tok::identifier))
  2697. Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
  2698. getCurScope());
  2699. else
  2700. return false;
  2701. // FIXME: Should not be querying properties of types from the parser.
  2702. if (Type.isUsable() && Type.get().get()->isObjCObjectOrInterfaceType()) {
  2703. const Token &AfterNext = GetLookAheadToken(2);
  2704. if (AfterNext.isOneOf(tok::colon, tok::r_square)) {
  2705. if (Tok.is(tok::identifier))
  2706. TryAnnotateTypeOrScopeToken();
  2707. return Tok.is(tok::annot_typename);
  2708. }
  2709. }
  2710. return false;
  2711. }
  2712. /// objc-message-expr:
  2713. /// '[' objc-receiver objc-message-args ']'
  2714. ///
  2715. /// objc-receiver: [C]
  2716. /// 'super'
  2717. /// expression
  2718. /// class-name
  2719. /// type-name
  2720. ///
  2721. ExprResult Parser::ParseObjCMessageExpression() {
  2722. assert(Tok.is(tok::l_square) && "'[' expected");
  2723. SourceLocation LBracLoc = ConsumeBracket(); // consume '['
  2724. if (Tok.is(tok::code_completion)) {
  2725. cutOffParsing();
  2726. Actions.CodeCompleteObjCMessageReceiver(getCurScope());
  2727. return ExprError();
  2728. }
  2729. InMessageExpressionRAIIObject InMessage(*this, true);
  2730. if (getLangOpts().CPlusPlus) {
  2731. // We completely separate the C and C++ cases because C++ requires
  2732. // more complicated (read: slower) parsing.
  2733. // Handle send to super.
  2734. // FIXME: This doesn't benefit from the same typo-correction we
  2735. // get in Objective-C.
  2736. if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
  2737. NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
  2738. return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr,
  2739. nullptr);
  2740. // Parse the receiver, which is either a type or an expression.
  2741. bool IsExpr;
  2742. void *TypeOrExpr = nullptr;
  2743. if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
  2744. SkipUntil(tok::r_square, StopAtSemi);
  2745. return ExprError();
  2746. }
  2747. if (IsExpr)
  2748. return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr,
  2749. static_cast<Expr *>(TypeOrExpr));
  2750. return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
  2751. ParsedType::getFromOpaquePtr(TypeOrExpr),
  2752. nullptr);
  2753. }
  2754. if (Tok.is(tok::identifier)) {
  2755. IdentifierInfo *Name = Tok.getIdentifierInfo();
  2756. SourceLocation NameLoc = Tok.getLocation();
  2757. ParsedType ReceiverType;
  2758. switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
  2759. Name == Ident_super,
  2760. NextToken().is(tok::period),
  2761. ReceiverType)) {
  2762. case Sema::ObjCSuperMessage:
  2763. return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr,
  2764. nullptr);
  2765. case Sema::ObjCClassMessage:
  2766. if (!ReceiverType) {
  2767. SkipUntil(tok::r_square, StopAtSemi);
  2768. return ExprError();
  2769. }
  2770. ConsumeToken(); // the type name
  2771. // Parse type arguments and protocol qualifiers.
  2772. if (Tok.is(tok::less)) {
  2773. SourceLocation NewEndLoc;
  2774. TypeResult NewReceiverType
  2775. = parseObjCTypeArgsAndProtocolQualifiers(NameLoc, ReceiverType,
  2776. /*consumeLastToken=*/true,
  2777. NewEndLoc);
  2778. if (!NewReceiverType.isUsable()) {
  2779. SkipUntil(tok::r_square, StopAtSemi);
  2780. return ExprError();
  2781. }
  2782. ReceiverType = NewReceiverType.get();
  2783. }
  2784. return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
  2785. ReceiverType, nullptr);
  2786. case Sema::ObjCInstanceMessage:
  2787. // Fall through to parse an expression.
  2788. break;
  2789. }
  2790. }
  2791. // Otherwise, an arbitrary expression can be the receiver of a send.
  2792. ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());
  2793. if (Res.isInvalid()) {
  2794. SkipUntil(tok::r_square, StopAtSemi);
  2795. return Res;
  2796. }
  2797. return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr,
  2798. Res.get());
  2799. }
  2800. /// Parse the remainder of an Objective-C message following the
  2801. /// '[' objc-receiver.
  2802. ///
  2803. /// This routine handles sends to super, class messages (sent to a
  2804. /// class name), and instance messages (sent to an object), and the
  2805. /// target is represented by \p SuperLoc, \p ReceiverType, or \p
  2806. /// ReceiverExpr, respectively. Only one of these parameters may have
  2807. /// a valid value.
  2808. ///
  2809. /// \param LBracLoc The location of the opening '['.
  2810. ///
  2811. /// \param SuperLoc If this is a send to 'super', the location of the
  2812. /// 'super' keyword that indicates a send to the superclass.
  2813. ///
  2814. /// \param ReceiverType If this is a class message, the type of the
  2815. /// class we are sending a message to.
  2816. ///
  2817. /// \param ReceiverExpr If this is an instance message, the expression
  2818. /// used to compute the receiver object.
  2819. ///
  2820. /// objc-message-args:
  2821. /// objc-selector
  2822. /// objc-keywordarg-list
  2823. ///
  2824. /// objc-keywordarg-list:
  2825. /// objc-keywordarg
  2826. /// objc-keywordarg-list objc-keywordarg
  2827. ///
  2828. /// objc-keywordarg:
  2829. /// selector-name[opt] ':' objc-keywordexpr
  2830. ///
  2831. /// objc-keywordexpr:
  2832. /// nonempty-expr-list
  2833. ///
  2834. /// nonempty-expr-list:
  2835. /// assignment-expression
  2836. /// nonempty-expr-list , assignment-expression
  2837. ///
  2838. ExprResult
  2839. Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
  2840. SourceLocation SuperLoc,
  2841. ParsedType ReceiverType,
  2842. Expr *ReceiverExpr) {
  2843. InMessageExpressionRAIIObject InMessage(*this, true);
  2844. if (Tok.is(tok::code_completion)) {
  2845. cutOffParsing();
  2846. if (SuperLoc.isValid())
  2847. Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
  2848. std::nullopt, false);
  2849. else if (ReceiverType)
  2850. Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
  2851. std::nullopt, false);
  2852. else
  2853. Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
  2854. std::nullopt, false);
  2855. return ExprError();
  2856. }
  2857. // Parse objc-selector
  2858. SourceLocation Loc;
  2859. IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
  2860. SmallVector<IdentifierInfo *, 12> KeyIdents;
  2861. SmallVector<SourceLocation, 12> KeyLocs;
  2862. ExprVector KeyExprs;
  2863. if (Tok.is(tok::colon)) {
  2864. while (true) {
  2865. // Each iteration parses a single keyword argument.
  2866. KeyIdents.push_back(selIdent);
  2867. KeyLocs.push_back(Loc);
  2868. if (ExpectAndConsume(tok::colon)) {
  2869. // We must manually skip to a ']', otherwise the expression skipper will
  2870. // stop at the ']' when it skips to the ';'. We want it to skip beyond
  2871. // the enclosing expression.
  2872. SkipUntil(tok::r_square, StopAtSemi);
  2873. return ExprError();
  2874. }
  2875. /// Parse the expression after ':'
  2876. if (Tok.is(tok::code_completion)) {
  2877. cutOffParsing();
  2878. if (SuperLoc.isValid())
  2879. Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
  2880. KeyIdents,
  2881. /*AtArgumentExpression=*/true);
  2882. else if (ReceiverType)
  2883. Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
  2884. KeyIdents,
  2885. /*AtArgumentExpression=*/true);
  2886. else
  2887. Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
  2888. KeyIdents,
  2889. /*AtArgumentExpression=*/true);
  2890. return ExprError();
  2891. }
  2892. ExprResult Expr;
  2893. if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
  2894. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
  2895. Expr = ParseBraceInitializer();
  2896. } else
  2897. Expr = ParseAssignmentExpression();
  2898. ExprResult Res(Expr);
  2899. if (Res.isInvalid()) {
  2900. // We must manually skip to a ']', otherwise the expression skipper will
  2901. // stop at the ']' when it skips to the ';'. We want it to skip beyond
  2902. // the enclosing expression.
  2903. SkipUntil(tok::r_square, StopAtSemi);
  2904. return Res;
  2905. }
  2906. // We have a valid expression.
  2907. KeyExprs.push_back(Res.get());
  2908. // Code completion after each argument.
  2909. if (Tok.is(tok::code_completion)) {
  2910. cutOffParsing();
  2911. if (SuperLoc.isValid())
  2912. Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
  2913. KeyIdents,
  2914. /*AtArgumentExpression=*/false);
  2915. else if (ReceiverType)
  2916. Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
  2917. KeyIdents,
  2918. /*AtArgumentExpression=*/false);
  2919. else
  2920. Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
  2921. KeyIdents,
  2922. /*AtArgumentExpression=*/false);
  2923. return ExprError();
  2924. }
  2925. // Check for another keyword selector.
  2926. selIdent = ParseObjCSelectorPiece(Loc);
  2927. if (!selIdent && Tok.isNot(tok::colon))
  2928. break;
  2929. // We have a selector or a colon, continue parsing.
  2930. }
  2931. // Parse the, optional, argument list, comma separated.
  2932. while (Tok.is(tok::comma)) {
  2933. SourceLocation commaLoc = ConsumeToken(); // Eat the ','.
  2934. /// Parse the expression after ','
  2935. ExprResult Res(ParseAssignmentExpression());
  2936. if (Tok.is(tok::colon))
  2937. Res = Actions.CorrectDelayedTyposInExpr(Res);
  2938. if (Res.isInvalid()) {
  2939. if (Tok.is(tok::colon)) {
  2940. Diag(commaLoc, diag::note_extra_comma_message_arg) <<
  2941. FixItHint::CreateRemoval(commaLoc);
  2942. }
  2943. // We must manually skip to a ']', otherwise the expression skipper will
  2944. // stop at the ']' when it skips to the ';'. We want it to skip beyond
  2945. // the enclosing expression.
  2946. SkipUntil(tok::r_square, StopAtSemi);
  2947. return Res;
  2948. }
  2949. // We have a valid expression.
  2950. KeyExprs.push_back(Res.get());
  2951. }
  2952. } else if (!selIdent) {
  2953. Diag(Tok, diag::err_expected) << tok::identifier; // missing selector name.
  2954. // We must manually skip to a ']', otherwise the expression skipper will
  2955. // stop at the ']' when it skips to the ';'. We want it to skip beyond
  2956. // the enclosing expression.
  2957. SkipUntil(tok::r_square, StopAtSemi);
  2958. return ExprError();
  2959. }
  2960. if (Tok.isNot(tok::r_square)) {
  2961. Diag(Tok, diag::err_expected)
  2962. << (Tok.is(tok::identifier) ? tok::colon : tok::r_square);
  2963. // We must manually skip to a ']', otherwise the expression skipper will
  2964. // stop at the ']' when it skips to the ';'. We want it to skip beyond
  2965. // the enclosing expression.
  2966. SkipUntil(tok::r_square, StopAtSemi);
  2967. return ExprError();
  2968. }
  2969. SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
  2970. unsigned nKeys = KeyIdents.size();
  2971. if (nKeys == 0) {
  2972. KeyIdents.push_back(selIdent);
  2973. KeyLocs.push_back(Loc);
  2974. }
  2975. Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
  2976. if (SuperLoc.isValid())
  2977. return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
  2978. LBracLoc, KeyLocs, RBracLoc, KeyExprs);
  2979. else if (ReceiverType)
  2980. return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
  2981. LBracLoc, KeyLocs, RBracLoc, KeyExprs);
  2982. return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
  2983. LBracLoc, KeyLocs, RBracLoc, KeyExprs);
  2984. }
  2985. ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
  2986. ExprResult Res(ParseStringLiteralExpression());
  2987. if (Res.isInvalid()) return Res;
  2988. // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string
  2989. // expressions. At this point, we know that the only valid thing that starts
  2990. // with '@' is an @"".
  2991. SmallVector<SourceLocation, 4> AtLocs;
  2992. ExprVector AtStrings;
  2993. AtLocs.push_back(AtLoc);
  2994. AtStrings.push_back(Res.get());
  2995. while (Tok.is(tok::at)) {
  2996. AtLocs.push_back(ConsumeToken()); // eat the @.
  2997. // Invalid unless there is a string literal.
  2998. if (!isTokenStringLiteral())
  2999. return ExprError(Diag(Tok, diag::err_objc_concat_string));
  3000. ExprResult Lit(ParseStringLiteralExpression());
  3001. if (Lit.isInvalid())
  3002. return Lit;
  3003. AtStrings.push_back(Lit.get());
  3004. }
  3005. return Actions.ParseObjCStringLiteral(AtLocs.data(), AtStrings);
  3006. }
  3007. /// ParseObjCBooleanLiteral -
  3008. /// objc-scalar-literal : '@' boolean-keyword
  3009. /// ;
  3010. /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
  3011. /// ;
  3012. ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc,
  3013. bool ArgValue) {
  3014. SourceLocation EndLoc = ConsumeToken(); // consume the keyword.
  3015. return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue);
  3016. }
  3017. /// ParseObjCCharacterLiteral -
  3018. /// objc-scalar-literal : '@' character-literal
  3019. /// ;
  3020. ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) {
  3021. ExprResult Lit(Actions.ActOnCharacterConstant(Tok));
  3022. if (Lit.isInvalid()) {
  3023. return Lit;
  3024. }
  3025. ConsumeToken(); // Consume the literal token.
  3026. return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
  3027. }
  3028. /// ParseObjCNumericLiteral -
  3029. /// objc-scalar-literal : '@' scalar-literal
  3030. /// ;
  3031. /// scalar-literal : | numeric-constant /* any numeric constant. */
  3032. /// ;
  3033. ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) {
  3034. ExprResult Lit(Actions.ActOnNumericConstant(Tok));
  3035. if (Lit.isInvalid()) {
  3036. return Lit;
  3037. }
  3038. ConsumeToken(); // Consume the literal token.
  3039. return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
  3040. }
  3041. /// ParseObjCBoxedExpr -
  3042. /// objc-box-expression:
  3043. /// @( assignment-expression )
  3044. ExprResult
  3045. Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) {
  3046. if (Tok.isNot(tok::l_paren))
  3047. return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@");
  3048. BalancedDelimiterTracker T(*this, tok::l_paren);
  3049. T.consumeOpen();
  3050. ExprResult ValueExpr(ParseAssignmentExpression());
  3051. if (T.consumeClose())
  3052. return ExprError();
  3053. if (ValueExpr.isInvalid())
  3054. return ExprError();
  3055. // Wrap the sub-expression in a parenthesized expression, to distinguish
  3056. // a boxed expression from a literal.
  3057. SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation();
  3058. ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.get());
  3059. return Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc),
  3060. ValueExpr.get());
  3061. }
  3062. ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) {
  3063. ExprVector ElementExprs; // array elements.
  3064. ConsumeBracket(); // consume the l_square.
  3065. bool HasInvalidEltExpr = false;
  3066. while (Tok.isNot(tok::r_square)) {
  3067. // Parse list of array element expressions (all must be id types).
  3068. ExprResult Res(ParseAssignmentExpression());
  3069. if (Res.isInvalid()) {
  3070. // We must manually skip to a ']', otherwise the expression skipper will
  3071. // stop at the ']' when it skips to the ';'. We want it to skip beyond
  3072. // the enclosing expression.
  3073. SkipUntil(tok::r_square, StopAtSemi);
  3074. return Res;
  3075. }
  3076. Res = Actions.CorrectDelayedTyposInExpr(Res.get());
  3077. if (Res.isInvalid())
  3078. HasInvalidEltExpr = true;
  3079. // Parse the ellipsis that indicates a pack expansion.
  3080. if (Tok.is(tok::ellipsis))
  3081. Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken());
  3082. if (Res.isInvalid())
  3083. HasInvalidEltExpr = true;
  3084. ElementExprs.push_back(Res.get());
  3085. if (Tok.is(tok::comma))
  3086. ConsumeToken(); // Eat the ','.
  3087. else if (Tok.isNot(tok::r_square))
  3088. return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_square
  3089. << tok::comma);
  3090. }
  3091. SourceLocation EndLoc = ConsumeBracket(); // location of ']'
  3092. if (HasInvalidEltExpr)
  3093. return ExprError();
  3094. MultiExprArg Args(ElementExprs);
  3095. return Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args);
  3096. }
  3097. ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) {
  3098. SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements.
  3099. ConsumeBrace(); // consume the l_square.
  3100. bool HasInvalidEltExpr = false;
  3101. while (Tok.isNot(tok::r_brace)) {
  3102. // Parse the comma separated key : value expressions.
  3103. ExprResult KeyExpr;
  3104. {
  3105. ColonProtectionRAIIObject X(*this);
  3106. KeyExpr = ParseAssignmentExpression();
  3107. if (KeyExpr.isInvalid()) {
  3108. // We must manually skip to a '}', otherwise the expression skipper will
  3109. // stop at the '}' when it skips to the ';'. We want it to skip beyond
  3110. // the enclosing expression.
  3111. SkipUntil(tok::r_brace, StopAtSemi);
  3112. return KeyExpr;
  3113. }
  3114. }
  3115. if (ExpectAndConsume(tok::colon)) {
  3116. SkipUntil(tok::r_brace, StopAtSemi);
  3117. return ExprError();
  3118. }
  3119. ExprResult ValueExpr(ParseAssignmentExpression());
  3120. if (ValueExpr.isInvalid()) {
  3121. // We must manually skip to a '}', otherwise the expression skipper will
  3122. // stop at the '}' when it skips to the ';'. We want it to skip beyond
  3123. // the enclosing expression.
  3124. SkipUntil(tok::r_brace, StopAtSemi);
  3125. return ValueExpr;
  3126. }
  3127. // Check the key and value for possible typos
  3128. KeyExpr = Actions.CorrectDelayedTyposInExpr(KeyExpr.get());
  3129. ValueExpr = Actions.CorrectDelayedTyposInExpr(ValueExpr.get());
  3130. if (KeyExpr.isInvalid() || ValueExpr.isInvalid())
  3131. HasInvalidEltExpr = true;
  3132. // Parse the ellipsis that designates this as a pack expansion. Do not
  3133. // ActOnPackExpansion here, leave it to template instantiation time where
  3134. // we can get better diagnostics.
  3135. SourceLocation EllipsisLoc;
  3136. if (getLangOpts().CPlusPlus)
  3137. TryConsumeToken(tok::ellipsis, EllipsisLoc);
  3138. // We have a valid expression. Collect it in a vector so we can
  3139. // build the argument list.
  3140. ObjCDictionaryElement Element = {KeyExpr.get(), ValueExpr.get(),
  3141. EllipsisLoc, std::nullopt};
  3142. Elements.push_back(Element);
  3143. if (!TryConsumeToken(tok::comma) && Tok.isNot(tok::r_brace))
  3144. return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_brace
  3145. << tok::comma);
  3146. }
  3147. SourceLocation EndLoc = ConsumeBrace();
  3148. if (HasInvalidEltExpr)
  3149. return ExprError();
  3150. // Create the ObjCDictionaryLiteral.
  3151. return Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc),
  3152. Elements);
  3153. }
  3154. /// objc-encode-expression:
  3155. /// \@encode ( type-name )
  3156. ExprResult
  3157. Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
  3158. assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
  3159. SourceLocation EncLoc = ConsumeToken();
  3160. if (Tok.isNot(tok::l_paren))
  3161. return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
  3162. BalancedDelimiterTracker T(*this, tok::l_paren);
  3163. T.consumeOpen();
  3164. TypeResult Ty = ParseTypeName();
  3165. T.consumeClose();
  3166. if (Ty.isInvalid())
  3167. return ExprError();
  3168. return Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, T.getOpenLocation(),
  3169. Ty.get(), T.getCloseLocation());
  3170. }
  3171. /// objc-protocol-expression
  3172. /// \@protocol ( protocol-name )
  3173. ExprResult
  3174. Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
  3175. SourceLocation ProtoLoc = ConsumeToken();
  3176. if (Tok.isNot(tok::l_paren))
  3177. return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
  3178. BalancedDelimiterTracker T(*this, tok::l_paren);
  3179. T.consumeOpen();
  3180. if (expectIdentifier())
  3181. return ExprError();
  3182. IdentifierInfo *protocolId = Tok.getIdentifierInfo();
  3183. SourceLocation ProtoIdLoc = ConsumeToken();
  3184. T.consumeClose();
  3185. return Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
  3186. T.getOpenLocation(), ProtoIdLoc,
  3187. T.getCloseLocation());
  3188. }
  3189. /// objc-selector-expression
  3190. /// @selector '(' '('[opt] objc-keyword-selector ')'[opt] ')'
  3191. ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
  3192. SourceLocation SelectorLoc = ConsumeToken();
  3193. if (Tok.isNot(tok::l_paren))
  3194. return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
  3195. SmallVector<IdentifierInfo *, 12> KeyIdents;
  3196. SourceLocation sLoc;
  3197. BalancedDelimiterTracker T(*this, tok::l_paren);
  3198. T.consumeOpen();
  3199. bool HasOptionalParen = Tok.is(tok::l_paren);
  3200. if (HasOptionalParen)
  3201. ConsumeParen();
  3202. if (Tok.is(tok::code_completion)) {
  3203. cutOffParsing();
  3204. Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
  3205. return ExprError();
  3206. }
  3207. IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
  3208. if (!SelIdent && // missing selector name.
  3209. Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
  3210. return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
  3211. KeyIdents.push_back(SelIdent);
  3212. unsigned nColons = 0;
  3213. if (Tok.isNot(tok::r_paren)) {
  3214. while (true) {
  3215. if (TryConsumeToken(tok::coloncolon)) { // Handle :: in C++.
  3216. ++nColons;
  3217. KeyIdents.push_back(nullptr);
  3218. } else if (ExpectAndConsume(tok::colon)) // Otherwise expect ':'.
  3219. return ExprError();
  3220. ++nColons;
  3221. if (Tok.is(tok::r_paren))
  3222. break;
  3223. if (Tok.is(tok::code_completion)) {
  3224. cutOffParsing();
  3225. Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
  3226. return ExprError();
  3227. }
  3228. // Check for another keyword selector.
  3229. SourceLocation Loc;
  3230. SelIdent = ParseObjCSelectorPiece(Loc);
  3231. KeyIdents.push_back(SelIdent);
  3232. if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
  3233. break;
  3234. }
  3235. }
  3236. if (HasOptionalParen && Tok.is(tok::r_paren))
  3237. ConsumeParen(); // ')'
  3238. T.consumeClose();
  3239. Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
  3240. return Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
  3241. T.getOpenLocation(),
  3242. T.getCloseLocation(),
  3243. !HasOptionalParen);
  3244. }
  3245. void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) {
  3246. // MCDecl might be null due to error in method or c-function prototype, etc.
  3247. Decl *MCDecl = LM.D;
  3248. bool skip = MCDecl &&
  3249. ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) ||
  3250. (!parseMethod && Actions.isObjCMethodDecl(MCDecl)));
  3251. if (skip)
  3252. return;
  3253. // Save the current token position.
  3254. SourceLocation OrigLoc = Tok.getLocation();
  3255. assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!");
  3256. // Store an artificial EOF token to ensure that we don't run off the end of
  3257. // the method's body when we come to parse it.
  3258. Token Eof;
  3259. Eof.startToken();
  3260. Eof.setKind(tok::eof);
  3261. Eof.setEofData(MCDecl);
  3262. Eof.setLocation(OrigLoc);
  3263. LM.Toks.push_back(Eof);
  3264. // Append the current token at the end of the new token stream so that it
  3265. // doesn't get lost.
  3266. LM.Toks.push_back(Tok);
  3267. PP.EnterTokenStream(LM.Toks, true, /*IsReinject*/true);
  3268. // Consume the previously pushed token.
  3269. ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
  3270. assert(Tok.isOneOf(tok::l_brace, tok::kw_try, tok::colon) &&
  3271. "Inline objective-c method not starting with '{' or 'try' or ':'");
  3272. // Enter a scope for the method or c-function body.
  3273. ParseScope BodyScope(this, (parseMethod ? Scope::ObjCMethodScope : 0) |
  3274. Scope::FnScope | Scope::DeclScope |
  3275. Scope::CompoundStmtScope);
  3276. // Tell the actions module that we have entered a method or c-function definition
  3277. // with the specified Declarator for the method/function.
  3278. if (parseMethod)
  3279. Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl);
  3280. else
  3281. Actions.ActOnStartOfFunctionDef(getCurScope(), MCDecl);
  3282. if (Tok.is(tok::kw_try))
  3283. ParseFunctionTryBlock(MCDecl, BodyScope);
  3284. else {
  3285. if (Tok.is(tok::colon))
  3286. ParseConstructorInitializer(MCDecl);
  3287. else
  3288. Actions.ActOnDefaultCtorInitializers(MCDecl);
  3289. ParseFunctionStatementBody(MCDecl, BodyScope);
  3290. }
  3291. if (Tok.getLocation() != OrigLoc) {
  3292. // Due to parsing error, we either went over the cached tokens or
  3293. // there are still cached tokens left. If it's the latter case skip the
  3294. // leftover tokens.
  3295. // Since this is an uncommon situation that should be avoided, use the
  3296. // expensive isBeforeInTranslationUnit call.
  3297. if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
  3298. OrigLoc))
  3299. while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
  3300. ConsumeAnyToken();
  3301. }
  3302. // Clean up the remaining EOF token.
  3303. ConsumeAnyToken();
  3304. }