RewriteObjCFoundationAPI.cpp 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187
  1. //===--- RewriteObjCFoundationAPI.cpp - Foundation API Rewriter -----------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Rewrites legacy method calls to modern syntax.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Edit/Rewriters.h"
  13. #include "clang/AST/ASTContext.h"
  14. #include "clang/AST/ExprCXX.h"
  15. #include "clang/AST/ExprObjC.h"
  16. #include "clang/AST/NSAPI.h"
  17. #include "clang/AST/ParentMap.h"
  18. #include "clang/Edit/Commit.h"
  19. #include "clang/Lex/Lexer.h"
  20. #include <optional>
  21. using namespace clang;
  22. using namespace edit;
  23. static bool checkForLiteralCreation(const ObjCMessageExpr *Msg,
  24. IdentifierInfo *&ClassId,
  25. const LangOptions &LangOpts) {
  26. if (!Msg || Msg->isImplicit() || !Msg->getMethodDecl())
  27. return false;
  28. const ObjCInterfaceDecl *Receiver = Msg->getReceiverInterface();
  29. if (!Receiver)
  30. return false;
  31. ClassId = Receiver->getIdentifier();
  32. if (Msg->getReceiverKind() == ObjCMessageExpr::Class)
  33. return true;
  34. // When in ARC mode we also convert "[[.. alloc] init]" messages to literals,
  35. // since the change from +1 to +0 will be handled fine by ARC.
  36. if (LangOpts.ObjCAutoRefCount) {
  37. if (Msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  38. if (const ObjCMessageExpr *Rec = dyn_cast<ObjCMessageExpr>(
  39. Msg->getInstanceReceiver()->IgnoreParenImpCasts())) {
  40. if (Rec->getMethodFamily() == OMF_alloc)
  41. return true;
  42. }
  43. }
  44. }
  45. return false;
  46. }
  47. //===----------------------------------------------------------------------===//
  48. // rewriteObjCRedundantCallWithLiteral.
  49. //===----------------------------------------------------------------------===//
  50. bool edit::rewriteObjCRedundantCallWithLiteral(const ObjCMessageExpr *Msg,
  51. const NSAPI &NS, Commit &commit) {
  52. IdentifierInfo *II = nullptr;
  53. if (!checkForLiteralCreation(Msg, II, NS.getASTContext().getLangOpts()))
  54. return false;
  55. if (Msg->getNumArgs() != 1)
  56. return false;
  57. const Expr *Arg = Msg->getArg(0)->IgnoreParenImpCasts();
  58. Selector Sel = Msg->getSelector();
  59. if ((isa<ObjCStringLiteral>(Arg) &&
  60. NS.getNSClassId(NSAPI::ClassId_NSString) == II &&
  61. (NS.getNSStringSelector(NSAPI::NSStr_stringWithString) == Sel ||
  62. NS.getNSStringSelector(NSAPI::NSStr_initWithString) == Sel)) ||
  63. (isa<ObjCArrayLiteral>(Arg) &&
  64. NS.getNSClassId(NSAPI::ClassId_NSArray) == II &&
  65. (NS.getNSArraySelector(NSAPI::NSArr_arrayWithArray) == Sel ||
  66. NS.getNSArraySelector(NSAPI::NSArr_initWithArray) == Sel)) ||
  67. (isa<ObjCDictionaryLiteral>(Arg) &&
  68. NS.getNSClassId(NSAPI::ClassId_NSDictionary) == II &&
  69. (NS.getNSDictionarySelector(
  70. NSAPI::NSDict_dictionaryWithDictionary) == Sel ||
  71. NS.getNSDictionarySelector(NSAPI::NSDict_initWithDictionary) == Sel))) {
  72. commit.replaceWithInner(Msg->getSourceRange(),
  73. Msg->getArg(0)->getSourceRange());
  74. return true;
  75. }
  76. return false;
  77. }
  78. //===----------------------------------------------------------------------===//
  79. // rewriteToObjCSubscriptSyntax.
  80. //===----------------------------------------------------------------------===//
  81. /// Check for classes that accept 'objectForKey:' (or the other selectors
  82. /// that the migrator handles) but return their instances as 'id', resulting
  83. /// in the compiler resolving 'objectForKey:' as the method from NSDictionary.
  84. ///
  85. /// When checking if we can convert to subscripting syntax, check whether
  86. /// the receiver is a result of a class method from a hardcoded list of
  87. /// such classes. In such a case return the specific class as the interface
  88. /// of the receiver.
  89. ///
  90. /// FIXME: Remove this when these classes start using 'instancetype'.
  91. static const ObjCInterfaceDecl *
  92. maybeAdjustInterfaceForSubscriptingCheck(const ObjCInterfaceDecl *IFace,
  93. const Expr *Receiver,
  94. ASTContext &Ctx) {
  95. assert(IFace && Receiver);
  96. // If the receiver has type 'id'...
  97. if (!Ctx.isObjCIdType(Receiver->getType().getUnqualifiedType()))
  98. return IFace;
  99. const ObjCMessageExpr *
  100. InnerMsg = dyn_cast<ObjCMessageExpr>(Receiver->IgnoreParenCasts());
  101. if (!InnerMsg)
  102. return IFace;
  103. QualType ClassRec;
  104. switch (InnerMsg->getReceiverKind()) {
  105. case ObjCMessageExpr::Instance:
  106. case ObjCMessageExpr::SuperInstance:
  107. return IFace;
  108. case ObjCMessageExpr::Class:
  109. ClassRec = InnerMsg->getClassReceiver();
  110. break;
  111. case ObjCMessageExpr::SuperClass:
  112. ClassRec = InnerMsg->getSuperType();
  113. break;
  114. }
  115. if (ClassRec.isNull())
  116. return IFace;
  117. // ...and it is the result of a class message...
  118. const ObjCObjectType *ObjTy = ClassRec->getAs<ObjCObjectType>();
  119. if (!ObjTy)
  120. return IFace;
  121. const ObjCInterfaceDecl *OID = ObjTy->getInterface();
  122. // ...and the receiving class is NSMapTable or NSLocale, return that
  123. // class as the receiving interface.
  124. if (OID->getName() == "NSMapTable" ||
  125. OID->getName() == "NSLocale")
  126. return OID;
  127. return IFace;
  128. }
  129. static bool canRewriteToSubscriptSyntax(const ObjCInterfaceDecl *&IFace,
  130. const ObjCMessageExpr *Msg,
  131. ASTContext &Ctx,
  132. Selector subscriptSel) {
  133. const Expr *Rec = Msg->getInstanceReceiver();
  134. if (!Rec)
  135. return false;
  136. IFace = maybeAdjustInterfaceForSubscriptingCheck(IFace, Rec, Ctx);
  137. if (const ObjCMethodDecl *MD = IFace->lookupInstanceMethod(subscriptSel)) {
  138. if (!MD->isUnavailable())
  139. return true;
  140. }
  141. return false;
  142. }
  143. static bool subscriptOperatorNeedsParens(const Expr *FullExpr);
  144. static void maybePutParensOnReceiver(const Expr *Receiver, Commit &commit) {
  145. if (subscriptOperatorNeedsParens(Receiver)) {
  146. SourceRange RecRange = Receiver->getSourceRange();
  147. commit.insertWrap("(", RecRange, ")");
  148. }
  149. }
  150. static bool rewriteToSubscriptGetCommon(const ObjCMessageExpr *Msg,
  151. Commit &commit) {
  152. if (Msg->getNumArgs() != 1)
  153. return false;
  154. const Expr *Rec = Msg->getInstanceReceiver();
  155. if (!Rec)
  156. return false;
  157. SourceRange MsgRange = Msg->getSourceRange();
  158. SourceRange RecRange = Rec->getSourceRange();
  159. SourceRange ArgRange = Msg->getArg(0)->getSourceRange();
  160. commit.replaceWithInner(CharSourceRange::getCharRange(MsgRange.getBegin(),
  161. ArgRange.getBegin()),
  162. CharSourceRange::getTokenRange(RecRange));
  163. commit.replaceWithInner(SourceRange(ArgRange.getBegin(), MsgRange.getEnd()),
  164. ArgRange);
  165. commit.insertWrap("[", ArgRange, "]");
  166. maybePutParensOnReceiver(Rec, commit);
  167. return true;
  168. }
  169. static bool rewriteToArraySubscriptGet(const ObjCInterfaceDecl *IFace,
  170. const ObjCMessageExpr *Msg,
  171. const NSAPI &NS,
  172. Commit &commit) {
  173. if (!canRewriteToSubscriptSyntax(IFace, Msg, NS.getASTContext(),
  174. NS.getObjectAtIndexedSubscriptSelector()))
  175. return false;
  176. return rewriteToSubscriptGetCommon(Msg, commit);
  177. }
  178. static bool rewriteToDictionarySubscriptGet(const ObjCInterfaceDecl *IFace,
  179. const ObjCMessageExpr *Msg,
  180. const NSAPI &NS,
  181. Commit &commit) {
  182. if (!canRewriteToSubscriptSyntax(IFace, Msg, NS.getASTContext(),
  183. NS.getObjectForKeyedSubscriptSelector()))
  184. return false;
  185. return rewriteToSubscriptGetCommon(Msg, commit);
  186. }
  187. static bool rewriteToArraySubscriptSet(const ObjCInterfaceDecl *IFace,
  188. const ObjCMessageExpr *Msg,
  189. const NSAPI &NS,
  190. Commit &commit) {
  191. if (!canRewriteToSubscriptSyntax(IFace, Msg, NS.getASTContext(),
  192. NS.getSetObjectAtIndexedSubscriptSelector()))
  193. return false;
  194. if (Msg->getNumArgs() != 2)
  195. return false;
  196. const Expr *Rec = Msg->getInstanceReceiver();
  197. if (!Rec)
  198. return false;
  199. SourceRange MsgRange = Msg->getSourceRange();
  200. SourceRange RecRange = Rec->getSourceRange();
  201. SourceRange Arg0Range = Msg->getArg(0)->getSourceRange();
  202. SourceRange Arg1Range = Msg->getArg(1)->getSourceRange();
  203. commit.replaceWithInner(CharSourceRange::getCharRange(MsgRange.getBegin(),
  204. Arg0Range.getBegin()),
  205. CharSourceRange::getTokenRange(RecRange));
  206. commit.replaceWithInner(CharSourceRange::getCharRange(Arg0Range.getBegin(),
  207. Arg1Range.getBegin()),
  208. CharSourceRange::getTokenRange(Arg0Range));
  209. commit.replaceWithInner(SourceRange(Arg1Range.getBegin(), MsgRange.getEnd()),
  210. Arg1Range);
  211. commit.insertWrap("[", CharSourceRange::getCharRange(Arg0Range.getBegin(),
  212. Arg1Range.getBegin()),
  213. "] = ");
  214. maybePutParensOnReceiver(Rec, commit);
  215. return true;
  216. }
  217. static bool rewriteToDictionarySubscriptSet(const ObjCInterfaceDecl *IFace,
  218. const ObjCMessageExpr *Msg,
  219. const NSAPI &NS,
  220. Commit &commit) {
  221. if (!canRewriteToSubscriptSyntax(IFace, Msg, NS.getASTContext(),
  222. NS.getSetObjectForKeyedSubscriptSelector()))
  223. return false;
  224. if (Msg->getNumArgs() != 2)
  225. return false;
  226. const Expr *Rec = Msg->getInstanceReceiver();
  227. if (!Rec)
  228. return false;
  229. SourceRange MsgRange = Msg->getSourceRange();
  230. SourceRange RecRange = Rec->getSourceRange();
  231. SourceRange Arg0Range = Msg->getArg(0)->getSourceRange();
  232. SourceRange Arg1Range = Msg->getArg(1)->getSourceRange();
  233. SourceLocation LocBeforeVal = Arg0Range.getBegin();
  234. commit.insertBefore(LocBeforeVal, "] = ");
  235. commit.insertFromRange(LocBeforeVal, Arg1Range, /*afterToken=*/false,
  236. /*beforePreviousInsertions=*/true);
  237. commit.insertBefore(LocBeforeVal, "[");
  238. commit.replaceWithInner(CharSourceRange::getCharRange(MsgRange.getBegin(),
  239. Arg0Range.getBegin()),
  240. CharSourceRange::getTokenRange(RecRange));
  241. commit.replaceWithInner(SourceRange(Arg0Range.getBegin(), MsgRange.getEnd()),
  242. Arg0Range);
  243. maybePutParensOnReceiver(Rec, commit);
  244. return true;
  245. }
  246. bool edit::rewriteToObjCSubscriptSyntax(const ObjCMessageExpr *Msg,
  247. const NSAPI &NS, Commit &commit) {
  248. if (!Msg || Msg->isImplicit() ||
  249. Msg->getReceiverKind() != ObjCMessageExpr::Instance)
  250. return false;
  251. const ObjCMethodDecl *Method = Msg->getMethodDecl();
  252. if (!Method)
  253. return false;
  254. const ObjCInterfaceDecl *IFace =
  255. NS.getASTContext().getObjContainingInterface(Method);
  256. if (!IFace)
  257. return false;
  258. Selector Sel = Msg->getSelector();
  259. if (Sel == NS.getNSArraySelector(NSAPI::NSArr_objectAtIndex))
  260. return rewriteToArraySubscriptGet(IFace, Msg, NS, commit);
  261. if (Sel == NS.getNSDictionarySelector(NSAPI::NSDict_objectForKey))
  262. return rewriteToDictionarySubscriptGet(IFace, Msg, NS, commit);
  263. if (Msg->getNumArgs() != 2)
  264. return false;
  265. if (Sel == NS.getNSArraySelector(NSAPI::NSMutableArr_replaceObjectAtIndex))
  266. return rewriteToArraySubscriptSet(IFace, Msg, NS, commit);
  267. if (Sel == NS.getNSDictionarySelector(NSAPI::NSMutableDict_setObjectForKey))
  268. return rewriteToDictionarySubscriptSet(IFace, Msg, NS, commit);
  269. return false;
  270. }
  271. //===----------------------------------------------------------------------===//
  272. // rewriteToObjCLiteralSyntax.
  273. //===----------------------------------------------------------------------===//
  274. static bool rewriteToArrayLiteral(const ObjCMessageExpr *Msg,
  275. const NSAPI &NS, Commit &commit,
  276. const ParentMap *PMap);
  277. static bool rewriteToDictionaryLiteral(const ObjCMessageExpr *Msg,
  278. const NSAPI &NS, Commit &commit);
  279. static bool rewriteToNumberLiteral(const ObjCMessageExpr *Msg,
  280. const NSAPI &NS, Commit &commit);
  281. static bool rewriteToNumericBoxedExpression(const ObjCMessageExpr *Msg,
  282. const NSAPI &NS, Commit &commit);
  283. static bool rewriteToStringBoxedExpression(const ObjCMessageExpr *Msg,
  284. const NSAPI &NS, Commit &commit);
  285. bool edit::rewriteToObjCLiteralSyntax(const ObjCMessageExpr *Msg,
  286. const NSAPI &NS, Commit &commit,
  287. const ParentMap *PMap) {
  288. IdentifierInfo *II = nullptr;
  289. if (!checkForLiteralCreation(Msg, II, NS.getASTContext().getLangOpts()))
  290. return false;
  291. if (II == NS.getNSClassId(NSAPI::ClassId_NSArray))
  292. return rewriteToArrayLiteral(Msg, NS, commit, PMap);
  293. if (II == NS.getNSClassId(NSAPI::ClassId_NSDictionary))
  294. return rewriteToDictionaryLiteral(Msg, NS, commit);
  295. if (II == NS.getNSClassId(NSAPI::ClassId_NSNumber))
  296. return rewriteToNumberLiteral(Msg, NS, commit);
  297. if (II == NS.getNSClassId(NSAPI::ClassId_NSString))
  298. return rewriteToStringBoxedExpression(Msg, NS, commit);
  299. return false;
  300. }
  301. /// Returns true if the immediate message arguments of \c Msg should not
  302. /// be rewritten because it will interfere with the rewrite of the parent
  303. /// message expression. e.g.
  304. /// \code
  305. /// [NSDictionary dictionaryWithObjects:
  306. /// [NSArray arrayWithObjects:@"1", @"2", nil]
  307. /// forKeys:[NSArray arrayWithObjects:@"A", @"B", nil]];
  308. /// \endcode
  309. /// It will return true for this because we are going to rewrite this directly
  310. /// to a dictionary literal without any array literals.
  311. static bool shouldNotRewriteImmediateMessageArgs(const ObjCMessageExpr *Msg,
  312. const NSAPI &NS);
  313. //===----------------------------------------------------------------------===//
  314. // rewriteToArrayLiteral.
  315. //===----------------------------------------------------------------------===//
  316. /// Adds an explicit cast to 'id' if the type is not objc object.
  317. static void objectifyExpr(const Expr *E, Commit &commit);
  318. static bool rewriteToArrayLiteral(const ObjCMessageExpr *Msg,
  319. const NSAPI &NS, Commit &commit,
  320. const ParentMap *PMap) {
  321. if (PMap) {
  322. const ObjCMessageExpr *ParentMsg =
  323. dyn_cast_or_null<ObjCMessageExpr>(PMap->getParentIgnoreParenCasts(Msg));
  324. if (shouldNotRewriteImmediateMessageArgs(ParentMsg, NS))
  325. return false;
  326. }
  327. Selector Sel = Msg->getSelector();
  328. SourceRange MsgRange = Msg->getSourceRange();
  329. if (Sel == NS.getNSArraySelector(NSAPI::NSArr_array)) {
  330. if (Msg->getNumArgs() != 0)
  331. return false;
  332. commit.replace(MsgRange, "@[]");
  333. return true;
  334. }
  335. if (Sel == NS.getNSArraySelector(NSAPI::NSArr_arrayWithObject)) {
  336. if (Msg->getNumArgs() != 1)
  337. return false;
  338. objectifyExpr(Msg->getArg(0), commit);
  339. SourceRange ArgRange = Msg->getArg(0)->getSourceRange();
  340. commit.replaceWithInner(MsgRange, ArgRange);
  341. commit.insertWrap("@[", ArgRange, "]");
  342. return true;
  343. }
  344. if (Sel == NS.getNSArraySelector(NSAPI::NSArr_arrayWithObjects) ||
  345. Sel == NS.getNSArraySelector(NSAPI::NSArr_initWithObjects)) {
  346. if (Msg->getNumArgs() == 0)
  347. return false;
  348. const Expr *SentinelExpr = Msg->getArg(Msg->getNumArgs() - 1);
  349. if (!NS.getASTContext().isSentinelNullExpr(SentinelExpr))
  350. return false;
  351. for (unsigned i = 0, e = Msg->getNumArgs() - 1; i != e; ++i)
  352. objectifyExpr(Msg->getArg(i), commit);
  353. if (Msg->getNumArgs() == 1) {
  354. commit.replace(MsgRange, "@[]");
  355. return true;
  356. }
  357. SourceRange ArgRange(Msg->getArg(0)->getBeginLoc(),
  358. Msg->getArg(Msg->getNumArgs() - 2)->getEndLoc());
  359. commit.replaceWithInner(MsgRange, ArgRange);
  360. commit.insertWrap("@[", ArgRange, "]");
  361. return true;
  362. }
  363. return false;
  364. }
  365. //===----------------------------------------------------------------------===//
  366. // rewriteToDictionaryLiteral.
  367. //===----------------------------------------------------------------------===//
  368. /// If \c Msg is an NSArray creation message or literal, this gets the
  369. /// objects that were used to create it.
  370. /// \returns true if it is an NSArray and we got objects, or false otherwise.
  371. static bool getNSArrayObjects(const Expr *E, const NSAPI &NS,
  372. SmallVectorImpl<const Expr *> &Objs) {
  373. if (!E)
  374. return false;
  375. E = E->IgnoreParenCasts();
  376. if (!E)
  377. return false;
  378. if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
  379. IdentifierInfo *Cls = nullptr;
  380. if (!checkForLiteralCreation(Msg, Cls, NS.getASTContext().getLangOpts()))
  381. return false;
  382. if (Cls != NS.getNSClassId(NSAPI::ClassId_NSArray))
  383. return false;
  384. Selector Sel = Msg->getSelector();
  385. if (Sel == NS.getNSArraySelector(NSAPI::NSArr_array))
  386. return true; // empty array.
  387. if (Sel == NS.getNSArraySelector(NSAPI::NSArr_arrayWithObject)) {
  388. if (Msg->getNumArgs() != 1)
  389. return false;
  390. Objs.push_back(Msg->getArg(0));
  391. return true;
  392. }
  393. if (Sel == NS.getNSArraySelector(NSAPI::NSArr_arrayWithObjects) ||
  394. Sel == NS.getNSArraySelector(NSAPI::NSArr_initWithObjects)) {
  395. if (Msg->getNumArgs() == 0)
  396. return false;
  397. const Expr *SentinelExpr = Msg->getArg(Msg->getNumArgs() - 1);
  398. if (!NS.getASTContext().isSentinelNullExpr(SentinelExpr))
  399. return false;
  400. for (unsigned i = 0, e = Msg->getNumArgs() - 1; i != e; ++i)
  401. Objs.push_back(Msg->getArg(i));
  402. return true;
  403. }
  404. } else if (const ObjCArrayLiteral *ArrLit = dyn_cast<ObjCArrayLiteral>(E)) {
  405. for (unsigned i = 0, e = ArrLit->getNumElements(); i != e; ++i)
  406. Objs.push_back(ArrLit->getElement(i));
  407. return true;
  408. }
  409. return false;
  410. }
  411. static bool rewriteToDictionaryLiteral(const ObjCMessageExpr *Msg,
  412. const NSAPI &NS, Commit &commit) {
  413. Selector Sel = Msg->getSelector();
  414. SourceRange MsgRange = Msg->getSourceRange();
  415. if (Sel == NS.getNSDictionarySelector(NSAPI::NSDict_dictionary)) {
  416. if (Msg->getNumArgs() != 0)
  417. return false;
  418. commit.replace(MsgRange, "@{}");
  419. return true;
  420. }
  421. if (Sel == NS.getNSDictionarySelector(
  422. NSAPI::NSDict_dictionaryWithObjectForKey)) {
  423. if (Msg->getNumArgs() != 2)
  424. return false;
  425. objectifyExpr(Msg->getArg(0), commit);
  426. objectifyExpr(Msg->getArg(1), commit);
  427. SourceRange ValRange = Msg->getArg(0)->getSourceRange();
  428. SourceRange KeyRange = Msg->getArg(1)->getSourceRange();
  429. // Insert key before the value.
  430. commit.insertBefore(ValRange.getBegin(), ": ");
  431. commit.insertFromRange(ValRange.getBegin(),
  432. CharSourceRange::getTokenRange(KeyRange),
  433. /*afterToken=*/false, /*beforePreviousInsertions=*/true);
  434. commit.insertBefore(ValRange.getBegin(), "@{");
  435. commit.insertAfterToken(ValRange.getEnd(), "}");
  436. commit.replaceWithInner(MsgRange, ValRange);
  437. return true;
  438. }
  439. if (Sel == NS.getNSDictionarySelector(
  440. NSAPI::NSDict_dictionaryWithObjectsAndKeys) ||
  441. Sel == NS.getNSDictionarySelector(NSAPI::NSDict_initWithObjectsAndKeys)) {
  442. if (Msg->getNumArgs() % 2 != 1)
  443. return false;
  444. unsigned SentinelIdx = Msg->getNumArgs() - 1;
  445. const Expr *SentinelExpr = Msg->getArg(SentinelIdx);
  446. if (!NS.getASTContext().isSentinelNullExpr(SentinelExpr))
  447. return false;
  448. if (Msg->getNumArgs() == 1) {
  449. commit.replace(MsgRange, "@{}");
  450. return true;
  451. }
  452. for (unsigned i = 0; i < SentinelIdx; i += 2) {
  453. objectifyExpr(Msg->getArg(i), commit);
  454. objectifyExpr(Msg->getArg(i+1), commit);
  455. SourceRange ValRange = Msg->getArg(i)->getSourceRange();
  456. SourceRange KeyRange = Msg->getArg(i+1)->getSourceRange();
  457. // Insert value after key.
  458. commit.insertAfterToken(KeyRange.getEnd(), ": ");
  459. commit.insertFromRange(KeyRange.getEnd(), ValRange, /*afterToken=*/true);
  460. commit.remove(CharSourceRange::getCharRange(ValRange.getBegin(),
  461. KeyRange.getBegin()));
  462. }
  463. // Range of arguments up until and including the last key.
  464. // The sentinel and first value are cut off, the value will move after the
  465. // key.
  466. SourceRange ArgRange(Msg->getArg(1)->getBeginLoc(),
  467. Msg->getArg(SentinelIdx - 1)->getEndLoc());
  468. commit.insertWrap("@{", ArgRange, "}");
  469. commit.replaceWithInner(MsgRange, ArgRange);
  470. return true;
  471. }
  472. if (Sel == NS.getNSDictionarySelector(
  473. NSAPI::NSDict_dictionaryWithObjectsForKeys) ||
  474. Sel == NS.getNSDictionarySelector(NSAPI::NSDict_initWithObjectsForKeys)) {
  475. if (Msg->getNumArgs() != 2)
  476. return false;
  477. SmallVector<const Expr *, 8> Vals;
  478. if (!getNSArrayObjects(Msg->getArg(0), NS, Vals))
  479. return false;
  480. SmallVector<const Expr *, 8> Keys;
  481. if (!getNSArrayObjects(Msg->getArg(1), NS, Keys))
  482. return false;
  483. if (Vals.size() != Keys.size())
  484. return false;
  485. if (Vals.empty()) {
  486. commit.replace(MsgRange, "@{}");
  487. return true;
  488. }
  489. for (unsigned i = 0, n = Vals.size(); i < n; ++i) {
  490. objectifyExpr(Vals[i], commit);
  491. objectifyExpr(Keys[i], commit);
  492. SourceRange ValRange = Vals[i]->getSourceRange();
  493. SourceRange KeyRange = Keys[i]->getSourceRange();
  494. // Insert value after key.
  495. commit.insertAfterToken(KeyRange.getEnd(), ": ");
  496. commit.insertFromRange(KeyRange.getEnd(), ValRange, /*afterToken=*/true);
  497. }
  498. // Range of arguments up until and including the last key.
  499. // The first value is cut off, the value will move after the key.
  500. SourceRange ArgRange(Keys.front()->getBeginLoc(), Keys.back()->getEndLoc());
  501. commit.insertWrap("@{", ArgRange, "}");
  502. commit.replaceWithInner(MsgRange, ArgRange);
  503. return true;
  504. }
  505. return false;
  506. }
  507. static bool shouldNotRewriteImmediateMessageArgs(const ObjCMessageExpr *Msg,
  508. const NSAPI &NS) {
  509. if (!Msg)
  510. return false;
  511. IdentifierInfo *II = nullptr;
  512. if (!checkForLiteralCreation(Msg, II, NS.getASTContext().getLangOpts()))
  513. return false;
  514. if (II != NS.getNSClassId(NSAPI::ClassId_NSDictionary))
  515. return false;
  516. Selector Sel = Msg->getSelector();
  517. if (Sel == NS.getNSDictionarySelector(
  518. NSAPI::NSDict_dictionaryWithObjectsForKeys) ||
  519. Sel == NS.getNSDictionarySelector(NSAPI::NSDict_initWithObjectsForKeys)) {
  520. if (Msg->getNumArgs() != 2)
  521. return false;
  522. SmallVector<const Expr *, 8> Vals;
  523. if (!getNSArrayObjects(Msg->getArg(0), NS, Vals))
  524. return false;
  525. SmallVector<const Expr *, 8> Keys;
  526. if (!getNSArrayObjects(Msg->getArg(1), NS, Keys))
  527. return false;
  528. if (Vals.size() != Keys.size())
  529. return false;
  530. return true;
  531. }
  532. return false;
  533. }
  534. //===----------------------------------------------------------------------===//
  535. // rewriteToNumberLiteral.
  536. //===----------------------------------------------------------------------===//
  537. static bool rewriteToCharLiteral(const ObjCMessageExpr *Msg,
  538. const CharacterLiteral *Arg,
  539. const NSAPI &NS, Commit &commit) {
  540. if (Arg->getKind() != CharacterLiteral::Ascii)
  541. return false;
  542. if (NS.isNSNumberLiteralSelector(NSAPI::NSNumberWithChar,
  543. Msg->getSelector())) {
  544. SourceRange ArgRange = Arg->getSourceRange();
  545. commit.replaceWithInner(Msg->getSourceRange(), ArgRange);
  546. commit.insert(ArgRange.getBegin(), "@");
  547. return true;
  548. }
  549. return rewriteToNumericBoxedExpression(Msg, NS, commit);
  550. }
  551. static bool rewriteToBoolLiteral(const ObjCMessageExpr *Msg,
  552. const Expr *Arg,
  553. const NSAPI &NS, Commit &commit) {
  554. if (NS.isNSNumberLiteralSelector(NSAPI::NSNumberWithBool,
  555. Msg->getSelector())) {
  556. SourceRange ArgRange = Arg->getSourceRange();
  557. commit.replaceWithInner(Msg->getSourceRange(), ArgRange);
  558. commit.insert(ArgRange.getBegin(), "@");
  559. return true;
  560. }
  561. return rewriteToNumericBoxedExpression(Msg, NS, commit);
  562. }
  563. namespace {
  564. struct LiteralInfo {
  565. bool Hex, Octal;
  566. StringRef U, F, L, LL;
  567. CharSourceRange WithoutSuffRange;
  568. };
  569. }
  570. static bool getLiteralInfo(SourceRange literalRange,
  571. bool isFloat, bool isIntZero,
  572. ASTContext &Ctx, LiteralInfo &Info) {
  573. if (literalRange.getBegin().isMacroID() ||
  574. literalRange.getEnd().isMacroID())
  575. return false;
  576. StringRef text = Lexer::getSourceText(
  577. CharSourceRange::getTokenRange(literalRange),
  578. Ctx.getSourceManager(), Ctx.getLangOpts());
  579. if (text.empty())
  580. return false;
  581. std::optional<bool> UpperU, UpperL;
  582. bool UpperF = false;
  583. struct Suff {
  584. static bool has(StringRef suff, StringRef &text) {
  585. if (text.endswith(suff)) {
  586. text = text.substr(0, text.size()-suff.size());
  587. return true;
  588. }
  589. return false;
  590. }
  591. };
  592. while (true) {
  593. if (Suff::has("u", text)) {
  594. UpperU = false;
  595. } else if (Suff::has("U", text)) {
  596. UpperU = true;
  597. } else if (Suff::has("ll", text)) {
  598. UpperL = false;
  599. } else if (Suff::has("LL", text)) {
  600. UpperL = true;
  601. } else if (Suff::has("l", text)) {
  602. UpperL = false;
  603. } else if (Suff::has("L", text)) {
  604. UpperL = true;
  605. } else if (isFloat && Suff::has("f", text)) {
  606. UpperF = false;
  607. } else if (isFloat && Suff::has("F", text)) {
  608. UpperF = true;
  609. } else
  610. break;
  611. }
  612. if (!UpperU && !UpperL)
  613. UpperU = UpperL = true;
  614. else if (UpperU && !UpperL)
  615. UpperL = UpperU;
  616. else if (UpperL && !UpperU)
  617. UpperU = UpperL;
  618. Info.U = *UpperU ? "U" : "u";
  619. Info.L = *UpperL ? "L" : "l";
  620. Info.LL = *UpperL ? "LL" : "ll";
  621. Info.F = UpperF ? "F" : "f";
  622. Info.Hex = Info.Octal = false;
  623. if (text.startswith("0x"))
  624. Info.Hex = true;
  625. else if (!isFloat && !isIntZero && text.startswith("0"))
  626. Info.Octal = true;
  627. SourceLocation B = literalRange.getBegin();
  628. Info.WithoutSuffRange =
  629. CharSourceRange::getCharRange(B, B.getLocWithOffset(text.size()));
  630. return true;
  631. }
  632. static bool rewriteToNumberLiteral(const ObjCMessageExpr *Msg,
  633. const NSAPI &NS, Commit &commit) {
  634. if (Msg->getNumArgs() != 1)
  635. return false;
  636. const Expr *Arg = Msg->getArg(0)->IgnoreParenImpCasts();
  637. if (const CharacterLiteral *CharE = dyn_cast<CharacterLiteral>(Arg))
  638. return rewriteToCharLiteral(Msg, CharE, NS, commit);
  639. if (const ObjCBoolLiteralExpr *BE = dyn_cast<ObjCBoolLiteralExpr>(Arg))
  640. return rewriteToBoolLiteral(Msg, BE, NS, commit);
  641. if (const CXXBoolLiteralExpr *BE = dyn_cast<CXXBoolLiteralExpr>(Arg))
  642. return rewriteToBoolLiteral(Msg, BE, NS, commit);
  643. const Expr *literalE = Arg;
  644. if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(literalE)) {
  645. if (UOE->getOpcode() == UO_Plus || UOE->getOpcode() == UO_Minus)
  646. literalE = UOE->getSubExpr();
  647. }
  648. // Only integer and floating literals, otherwise try to rewrite to boxed
  649. // expression.
  650. if (!isa<IntegerLiteral>(literalE) && !isa<FloatingLiteral>(literalE))
  651. return rewriteToNumericBoxedExpression(Msg, NS, commit);
  652. ASTContext &Ctx = NS.getASTContext();
  653. Selector Sel = Msg->getSelector();
  654. std::optional<NSAPI::NSNumberLiteralMethodKind> MKOpt =
  655. NS.getNSNumberLiteralMethodKind(Sel);
  656. if (!MKOpt)
  657. return false;
  658. NSAPI::NSNumberLiteralMethodKind MK = *MKOpt;
  659. bool CallIsUnsigned = false, CallIsLong = false, CallIsLongLong = false;
  660. bool CallIsFloating = false, CallIsDouble = false;
  661. switch (MK) {
  662. // We cannot have these calls with int/float literals.
  663. case NSAPI::NSNumberWithChar:
  664. case NSAPI::NSNumberWithUnsignedChar:
  665. case NSAPI::NSNumberWithShort:
  666. case NSAPI::NSNumberWithUnsignedShort:
  667. case NSAPI::NSNumberWithBool:
  668. return rewriteToNumericBoxedExpression(Msg, NS, commit);
  669. case NSAPI::NSNumberWithUnsignedInt:
  670. case NSAPI::NSNumberWithUnsignedInteger:
  671. CallIsUnsigned = true;
  672. [[fallthrough]];
  673. case NSAPI::NSNumberWithInt:
  674. case NSAPI::NSNumberWithInteger:
  675. break;
  676. case NSAPI::NSNumberWithUnsignedLong:
  677. CallIsUnsigned = true;
  678. [[fallthrough]];
  679. case NSAPI::NSNumberWithLong:
  680. CallIsLong = true;
  681. break;
  682. case NSAPI::NSNumberWithUnsignedLongLong:
  683. CallIsUnsigned = true;
  684. [[fallthrough]];
  685. case NSAPI::NSNumberWithLongLong:
  686. CallIsLongLong = true;
  687. break;
  688. case NSAPI::NSNumberWithDouble:
  689. CallIsDouble = true;
  690. [[fallthrough]];
  691. case NSAPI::NSNumberWithFloat:
  692. CallIsFloating = true;
  693. break;
  694. }
  695. SourceRange ArgRange = Arg->getSourceRange();
  696. QualType ArgTy = Arg->getType();
  697. QualType CallTy = Msg->getArg(0)->getType();
  698. // Check for the easy case, the literal maps directly to the call.
  699. if (Ctx.hasSameType(ArgTy, CallTy)) {
  700. commit.replaceWithInner(Msg->getSourceRange(), ArgRange);
  701. commit.insert(ArgRange.getBegin(), "@");
  702. return true;
  703. }
  704. // We will need to modify the literal suffix to get the same type as the call.
  705. // Try with boxed expression if it came from a macro.
  706. if (ArgRange.getBegin().isMacroID())
  707. return rewriteToNumericBoxedExpression(Msg, NS, commit);
  708. bool LitIsFloat = ArgTy->isFloatingType();
  709. // For a float passed to integer call, don't try rewriting to objc literal.
  710. // It is difficult and a very uncommon case anyway.
  711. // But try with boxed expression.
  712. if (LitIsFloat && !CallIsFloating)
  713. return rewriteToNumericBoxedExpression(Msg, NS, commit);
  714. // Try to modify the literal make it the same type as the method call.
  715. // -Modify the suffix, and/or
  716. // -Change integer to float
  717. LiteralInfo LitInfo;
  718. bool isIntZero = false;
  719. if (const IntegerLiteral *IntE = dyn_cast<IntegerLiteral>(literalE))
  720. isIntZero = !IntE->getValue().getBoolValue();
  721. if (!getLiteralInfo(ArgRange, LitIsFloat, isIntZero, Ctx, LitInfo))
  722. return rewriteToNumericBoxedExpression(Msg, NS, commit);
  723. // Not easy to do int -> float with hex/octal and uncommon anyway.
  724. if (!LitIsFloat && CallIsFloating && (LitInfo.Hex || LitInfo.Octal))
  725. return rewriteToNumericBoxedExpression(Msg, NS, commit);
  726. SourceLocation LitB = LitInfo.WithoutSuffRange.getBegin();
  727. SourceLocation LitE = LitInfo.WithoutSuffRange.getEnd();
  728. commit.replaceWithInner(CharSourceRange::getTokenRange(Msg->getSourceRange()),
  729. LitInfo.WithoutSuffRange);
  730. commit.insert(LitB, "@");
  731. if (!LitIsFloat && CallIsFloating)
  732. commit.insert(LitE, ".0");
  733. if (CallIsFloating) {
  734. if (!CallIsDouble)
  735. commit.insert(LitE, LitInfo.F);
  736. } else {
  737. if (CallIsUnsigned)
  738. commit.insert(LitE, LitInfo.U);
  739. if (CallIsLong)
  740. commit.insert(LitE, LitInfo.L);
  741. else if (CallIsLongLong)
  742. commit.insert(LitE, LitInfo.LL);
  743. }
  744. return true;
  745. }
  746. // FIXME: Make determination of operator precedence more general and
  747. // make it broadly available.
  748. static bool subscriptOperatorNeedsParens(const Expr *FullExpr) {
  749. const Expr* Expr = FullExpr->IgnoreImpCasts();
  750. if (isa<ArraySubscriptExpr>(Expr) ||
  751. isa<CallExpr>(Expr) ||
  752. isa<DeclRefExpr>(Expr) ||
  753. isa<CXXNamedCastExpr>(Expr) ||
  754. isa<CXXConstructExpr>(Expr) ||
  755. isa<CXXThisExpr>(Expr) ||
  756. isa<CXXTypeidExpr>(Expr) ||
  757. isa<CXXUnresolvedConstructExpr>(Expr) ||
  758. isa<ObjCMessageExpr>(Expr) ||
  759. isa<ObjCPropertyRefExpr>(Expr) ||
  760. isa<ObjCProtocolExpr>(Expr) ||
  761. isa<MemberExpr>(Expr) ||
  762. isa<ObjCIvarRefExpr>(Expr) ||
  763. isa<ParenExpr>(FullExpr) ||
  764. isa<ParenListExpr>(Expr) ||
  765. isa<SizeOfPackExpr>(Expr))
  766. return false;
  767. return true;
  768. }
  769. static bool castOperatorNeedsParens(const Expr *FullExpr) {
  770. const Expr* Expr = FullExpr->IgnoreImpCasts();
  771. if (isa<ArraySubscriptExpr>(Expr) ||
  772. isa<CallExpr>(Expr) ||
  773. isa<DeclRefExpr>(Expr) ||
  774. isa<CastExpr>(Expr) ||
  775. isa<CXXNewExpr>(Expr) ||
  776. isa<CXXConstructExpr>(Expr) ||
  777. isa<CXXDeleteExpr>(Expr) ||
  778. isa<CXXNoexceptExpr>(Expr) ||
  779. isa<CXXPseudoDestructorExpr>(Expr) ||
  780. isa<CXXScalarValueInitExpr>(Expr) ||
  781. isa<CXXThisExpr>(Expr) ||
  782. isa<CXXTypeidExpr>(Expr) ||
  783. isa<CXXUnresolvedConstructExpr>(Expr) ||
  784. isa<ObjCMessageExpr>(Expr) ||
  785. isa<ObjCPropertyRefExpr>(Expr) ||
  786. isa<ObjCProtocolExpr>(Expr) ||
  787. isa<MemberExpr>(Expr) ||
  788. isa<ObjCIvarRefExpr>(Expr) ||
  789. isa<ParenExpr>(FullExpr) ||
  790. isa<ParenListExpr>(Expr) ||
  791. isa<SizeOfPackExpr>(Expr) ||
  792. isa<UnaryOperator>(Expr))
  793. return false;
  794. return true;
  795. }
  796. static void objectifyExpr(const Expr *E, Commit &commit) {
  797. if (!E) return;
  798. QualType T = E->getType();
  799. if (T->isObjCObjectPointerType()) {
  800. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  801. if (ICE->getCastKind() != CK_CPointerToObjCPointerCast)
  802. return;
  803. } else {
  804. return;
  805. }
  806. } else if (!T->isPointerType()) {
  807. return;
  808. }
  809. SourceRange Range = E->getSourceRange();
  810. if (castOperatorNeedsParens(E))
  811. commit.insertWrap("(", Range, ")");
  812. commit.insertBefore(Range.getBegin(), "(id)");
  813. }
  814. //===----------------------------------------------------------------------===//
  815. // rewriteToNumericBoxedExpression.
  816. //===----------------------------------------------------------------------===//
  817. static bool isEnumConstant(const Expr *E) {
  818. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  819. if (const ValueDecl *VD = DRE->getDecl())
  820. return isa<EnumConstantDecl>(VD);
  821. return false;
  822. }
  823. static bool rewriteToNumericBoxedExpression(const ObjCMessageExpr *Msg,
  824. const NSAPI &NS, Commit &commit) {
  825. if (Msg->getNumArgs() != 1)
  826. return false;
  827. const Expr *Arg = Msg->getArg(0);
  828. if (Arg->isTypeDependent())
  829. return false;
  830. ASTContext &Ctx = NS.getASTContext();
  831. Selector Sel = Msg->getSelector();
  832. std::optional<NSAPI::NSNumberLiteralMethodKind> MKOpt =
  833. NS.getNSNumberLiteralMethodKind(Sel);
  834. if (!MKOpt)
  835. return false;
  836. NSAPI::NSNumberLiteralMethodKind MK = *MKOpt;
  837. const Expr *OrigArg = Arg->IgnoreImpCasts();
  838. QualType FinalTy = Arg->getType();
  839. QualType OrigTy = OrigArg->getType();
  840. uint64_t FinalTySize = Ctx.getTypeSize(FinalTy);
  841. uint64_t OrigTySize = Ctx.getTypeSize(OrigTy);
  842. bool isTruncated = FinalTySize < OrigTySize;
  843. bool needsCast = false;
  844. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
  845. switch (ICE->getCastKind()) {
  846. case CK_LValueToRValue:
  847. case CK_NoOp:
  848. case CK_UserDefinedConversion:
  849. break;
  850. case CK_IntegralCast: {
  851. if (MK == NSAPI::NSNumberWithBool && OrigTy->isBooleanType())
  852. break;
  853. // Be more liberal with Integer/UnsignedInteger which are very commonly
  854. // used.
  855. if ((MK == NSAPI::NSNumberWithInteger ||
  856. MK == NSAPI::NSNumberWithUnsignedInteger) &&
  857. !isTruncated) {
  858. if (OrigTy->getAs<EnumType>() || isEnumConstant(OrigArg))
  859. break;
  860. if ((MK==NSAPI::NSNumberWithInteger) == OrigTy->isSignedIntegerType() &&
  861. OrigTySize >= Ctx.getTypeSize(Ctx.IntTy))
  862. break;
  863. }
  864. needsCast = true;
  865. break;
  866. }
  867. case CK_PointerToBoolean:
  868. case CK_IntegralToBoolean:
  869. case CK_IntegralToFloating:
  870. case CK_FloatingToIntegral:
  871. case CK_FloatingToBoolean:
  872. case CK_FloatingCast:
  873. case CK_FloatingComplexToReal:
  874. case CK_FloatingComplexToBoolean:
  875. case CK_IntegralComplexToReal:
  876. case CK_IntegralComplexToBoolean:
  877. case CK_AtomicToNonAtomic:
  878. case CK_AddressSpaceConversion:
  879. needsCast = true;
  880. break;
  881. case CK_Dependent:
  882. case CK_BitCast:
  883. case CK_LValueBitCast:
  884. case CK_LValueToRValueBitCast:
  885. case CK_BaseToDerived:
  886. case CK_DerivedToBase:
  887. case CK_UncheckedDerivedToBase:
  888. case CK_Dynamic:
  889. case CK_ToUnion:
  890. case CK_ArrayToPointerDecay:
  891. case CK_FunctionToPointerDecay:
  892. case CK_NullToPointer:
  893. case CK_NullToMemberPointer:
  894. case CK_BaseToDerivedMemberPointer:
  895. case CK_DerivedToBaseMemberPointer:
  896. case CK_MemberPointerToBoolean:
  897. case CK_ReinterpretMemberPointer:
  898. case CK_ConstructorConversion:
  899. case CK_IntegralToPointer:
  900. case CK_PointerToIntegral:
  901. case CK_ToVoid:
  902. case CK_VectorSplat:
  903. case CK_CPointerToObjCPointerCast:
  904. case CK_BlockPointerToObjCPointerCast:
  905. case CK_AnyPointerToBlockPointerCast:
  906. case CK_ObjCObjectLValueCast:
  907. case CK_FloatingRealToComplex:
  908. case CK_FloatingComplexCast:
  909. case CK_FloatingComplexToIntegralComplex:
  910. case CK_IntegralRealToComplex:
  911. case CK_IntegralComplexCast:
  912. case CK_IntegralComplexToFloatingComplex:
  913. case CK_ARCProduceObject:
  914. case CK_ARCConsumeObject:
  915. case CK_ARCReclaimReturnedObject:
  916. case CK_ARCExtendBlockObject:
  917. case CK_NonAtomicToAtomic:
  918. case CK_CopyAndAutoreleaseBlockObject:
  919. case CK_BuiltinFnToFnPtr:
  920. case CK_ZeroToOCLOpaqueType:
  921. case CK_IntToOCLSampler:
  922. case CK_MatrixCast:
  923. return false;
  924. case CK_BooleanToSignedIntegral:
  925. llvm_unreachable("OpenCL-specific cast in Objective-C?");
  926. case CK_FloatingToFixedPoint:
  927. case CK_FixedPointToFloating:
  928. case CK_FixedPointCast:
  929. case CK_FixedPointToBoolean:
  930. case CK_FixedPointToIntegral:
  931. case CK_IntegralToFixedPoint:
  932. llvm_unreachable("Fixed point types are disabled for Objective-C");
  933. }
  934. }
  935. if (needsCast) {
  936. DiagnosticsEngine &Diags = Ctx.getDiagnostics();
  937. // FIXME: Use a custom category name to distinguish migration diagnostics.
  938. unsigned diagID = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
  939. "converting to boxing syntax requires casting %0 to %1");
  940. Diags.Report(Msg->getExprLoc(), diagID) << OrigTy << FinalTy
  941. << Msg->getSourceRange();
  942. return false;
  943. }
  944. SourceRange ArgRange = OrigArg->getSourceRange();
  945. commit.replaceWithInner(Msg->getSourceRange(), ArgRange);
  946. if (isa<ParenExpr>(OrigArg) || isa<IntegerLiteral>(OrigArg))
  947. commit.insertBefore(ArgRange.getBegin(), "@");
  948. else
  949. commit.insertWrap("@(", ArgRange, ")");
  950. return true;
  951. }
  952. //===----------------------------------------------------------------------===//
  953. // rewriteToStringBoxedExpression.
  954. //===----------------------------------------------------------------------===//
  955. static bool doRewriteToUTF8StringBoxedExpressionHelper(
  956. const ObjCMessageExpr *Msg,
  957. const NSAPI &NS, Commit &commit) {
  958. const Expr *Arg = Msg->getArg(0);
  959. if (Arg->isTypeDependent())
  960. return false;
  961. ASTContext &Ctx = NS.getASTContext();
  962. const Expr *OrigArg = Arg->IgnoreImpCasts();
  963. QualType OrigTy = OrigArg->getType();
  964. if (OrigTy->isArrayType())
  965. OrigTy = Ctx.getArrayDecayedType(OrigTy);
  966. if (const StringLiteral *
  967. StrE = dyn_cast<StringLiteral>(OrigArg->IgnoreParens())) {
  968. commit.replaceWithInner(Msg->getSourceRange(), StrE->getSourceRange());
  969. commit.insert(StrE->getBeginLoc(), "@");
  970. return true;
  971. }
  972. if (const PointerType *PT = OrigTy->getAs<PointerType>()) {
  973. QualType PointeeType = PT->getPointeeType();
  974. if (Ctx.hasSameUnqualifiedType(PointeeType, Ctx.CharTy)) {
  975. SourceRange ArgRange = OrigArg->getSourceRange();
  976. commit.replaceWithInner(Msg->getSourceRange(), ArgRange);
  977. if (isa<ParenExpr>(OrigArg) || isa<IntegerLiteral>(OrigArg))
  978. commit.insertBefore(ArgRange.getBegin(), "@");
  979. else
  980. commit.insertWrap("@(", ArgRange, ")");
  981. return true;
  982. }
  983. }
  984. return false;
  985. }
  986. static bool rewriteToStringBoxedExpression(const ObjCMessageExpr *Msg,
  987. const NSAPI &NS, Commit &commit) {
  988. Selector Sel = Msg->getSelector();
  989. if (Sel == NS.getNSStringSelector(NSAPI::NSStr_stringWithUTF8String) ||
  990. Sel == NS.getNSStringSelector(NSAPI::NSStr_stringWithCString) ||
  991. Sel == NS.getNSStringSelector(NSAPI::NSStr_initWithUTF8String)) {
  992. if (Msg->getNumArgs() != 1)
  993. return false;
  994. return doRewriteToUTF8StringBoxedExpressionHelper(Msg, NS, commit);
  995. }
  996. if (Sel == NS.getNSStringSelector(NSAPI::NSStr_stringWithCStringEncoding)) {
  997. if (Msg->getNumArgs() != 2)
  998. return false;
  999. const Expr *encodingArg = Msg->getArg(1);
  1000. if (NS.isNSUTF8StringEncodingConstant(encodingArg) ||
  1001. NS.isNSASCIIStringEncodingConstant(encodingArg))
  1002. return doRewriteToUTF8StringBoxedExpressionHelper(Msg, NS, commit);
  1003. }
  1004. return false;
  1005. }