ParseObjc.cpp 128 KB

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