ParseObjc.cpp 127 KB

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