ParseObjc.cpp 129 KB

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