blob: 3a305ecd94ecc00ec76caf089849fde12e985262 [file] [log] [blame]
Ted Kremenekf7639e12012-03-06 20:06:33 +00001//===--- RewriteObjCFoundationAPI.cpp - Foundation API Rewriter -----------===//
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// Rewrites legacy method calls to modern syntax.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Edit/Rewriters.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ExprObjC.h"
18#include "clang/AST/NSAPI.h"
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +000019#include "clang/AST/ParentMap.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000020#include "clang/Edit/Commit.h"
21#include "clang/Lex/Lexer.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000022
23using namespace clang;
24using namespace edit;
25
26static bool checkForLiteralCreation(const ObjCMessageExpr *Msg,
Argyrios Kyrtzidis63aebfb2012-06-06 22:23:12 +000027 IdentifierInfo *&ClassId,
28 const LangOptions &LangOpts) {
Ted Kremenekf7639e12012-03-06 20:06:33 +000029 if (!Msg || Msg->isImplicit() || !Msg->getMethodDecl())
30 return false;
31
32 const ObjCInterfaceDecl *Receiver = Msg->getReceiverInterface();
33 if (!Receiver)
34 return false;
35 ClassId = Receiver->getIdentifier();
36
37 if (Msg->getReceiverKind() == ObjCMessageExpr::Class)
38 return true;
39
Argyrios Kyrtzidis63aebfb2012-06-06 22:23:12 +000040 // When in ARC mode we also convert "[[.. alloc] init]" messages to literals,
41 // since the change from +1 to +0 will be handled fine by ARC.
42 if (LangOpts.ObjCAutoRefCount) {
43 if (Msg->getReceiverKind() == ObjCMessageExpr::Instance) {
44 if (const ObjCMessageExpr *Rec = dyn_cast<ObjCMessageExpr>(
45 Msg->getInstanceReceiver()->IgnoreParenImpCasts())) {
46 if (Rec->getMethodFamily() == OMF_alloc)
47 return true;
48 }
49 }
50 }
51
Ted Kremenekf7639e12012-03-06 20:06:33 +000052 return false;
53}
54
55//===----------------------------------------------------------------------===//
56// rewriteObjCRedundantCallWithLiteral.
57//===----------------------------------------------------------------------===//
58
59bool edit::rewriteObjCRedundantCallWithLiteral(const ObjCMessageExpr *Msg,
60 const NSAPI &NS, Commit &commit) {
Craig Topper2145bc02014-05-09 08:15:10 +000061 IdentifierInfo *II = nullptr;
Argyrios Kyrtzidis63aebfb2012-06-06 22:23:12 +000062 if (!checkForLiteralCreation(Msg, II, NS.getASTContext().getLangOpts()))
Ted Kremenekf7639e12012-03-06 20:06:33 +000063 return false;
64 if (Msg->getNumArgs() != 1)
65 return false;
66
67 const Expr *Arg = Msg->getArg(0)->IgnoreParenImpCasts();
68 Selector Sel = Msg->getSelector();
69
70 if ((isa<ObjCStringLiteral>(Arg) &&
71 NS.getNSClassId(NSAPI::ClassId_NSString) == II &&
Argyrios Kyrtzidis63aebfb2012-06-06 22:23:12 +000072 (NS.getNSStringSelector(NSAPI::NSStr_stringWithString) == Sel ||
73 NS.getNSStringSelector(NSAPI::NSStr_initWithString) == Sel)) ||
Ted Kremenekf7639e12012-03-06 20:06:33 +000074
75 (isa<ObjCArrayLiteral>(Arg) &&
76 NS.getNSClassId(NSAPI::ClassId_NSArray) == II &&
Argyrios Kyrtzidis63aebfb2012-06-06 22:23:12 +000077 (NS.getNSArraySelector(NSAPI::NSArr_arrayWithArray) == Sel ||
78 NS.getNSArraySelector(NSAPI::NSArr_initWithArray) == Sel)) ||
Ted Kremenekf7639e12012-03-06 20:06:33 +000079
80 (isa<ObjCDictionaryLiteral>(Arg) &&
81 NS.getNSClassId(NSAPI::ClassId_NSDictionary) == II &&
Argyrios Kyrtzidis63aebfb2012-06-06 22:23:12 +000082 (NS.getNSDictionarySelector(
83 NSAPI::NSDict_dictionaryWithDictionary) == Sel ||
84 NS.getNSDictionarySelector(NSAPI::NSDict_initWithDictionary) == Sel))) {
Fangrui Song6907ce22018-07-30 19:24:48 +000085
Ted Kremenekf7639e12012-03-06 20:06:33 +000086 commit.replaceWithInner(Msg->getSourceRange(),
87 Msg->getArg(0)->getSourceRange());
88 return true;
89 }
90
91 return false;
92}
93
94//===----------------------------------------------------------------------===//
95// rewriteToObjCSubscriptSyntax.
96//===----------------------------------------------------------------------===//
97
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000098/// Check for classes that accept 'objectForKey:' (or the other selectors
Argyrios Kyrtzidis89b928e2012-07-06 00:07:09 +000099/// that the migrator handles) but return their instances as 'id', resulting
100/// in the compiler resolving 'objectForKey:' as the method from NSDictionary.
101///
102/// When checking if we can convert to subscripting syntax, check whether
103/// the receiver is a result of a class method from a hardcoded list of
104/// such classes. In such a case return the specific class as the interface
105/// of the receiver.
106///
107/// FIXME: Remove this when these classes start using 'instancetype'.
108static const ObjCInterfaceDecl *
109maybeAdjustInterfaceForSubscriptingCheck(const ObjCInterfaceDecl *IFace,
110 const Expr *Receiver,
111 ASTContext &Ctx) {
112 assert(IFace && Receiver);
113
114 // If the receiver has type 'id'...
115 if (!Ctx.isObjCIdType(Receiver->getType().getUnqualifiedType()))
116 return IFace;
117
118 const ObjCMessageExpr *
119 InnerMsg = dyn_cast<ObjCMessageExpr>(Receiver->IgnoreParenCasts());
120 if (!InnerMsg)
121 return IFace;
122
123 QualType ClassRec;
124 switch (InnerMsg->getReceiverKind()) {
125 case ObjCMessageExpr::Instance:
126 case ObjCMessageExpr::SuperInstance:
127 return IFace;
128
129 case ObjCMessageExpr::Class:
130 ClassRec = InnerMsg->getClassReceiver();
131 break;
132 case ObjCMessageExpr::SuperClass:
133 ClassRec = InnerMsg->getSuperType();
134 break;
135 }
136
137 if (ClassRec.isNull())
138 return IFace;
139
140 // ...and it is the result of a class message...
141
142 const ObjCObjectType *ObjTy = ClassRec->getAs<ObjCObjectType>();
143 if (!ObjTy)
144 return IFace;
145 const ObjCInterfaceDecl *OID = ObjTy->getInterface();
146
147 // ...and the receiving class is NSMapTable or NSLocale, return that
148 // class as the receiving interface.
149 if (OID->getName() == "NSMapTable" ||
150 OID->getName() == "NSLocale")
151 return OID;
152
153 return IFace;
154}
155
156static bool canRewriteToSubscriptSyntax(const ObjCInterfaceDecl *&IFace,
157 const ObjCMessageExpr *Msg,
158 ASTContext &Ctx,
Argyrios Kyrtzidis13b92922012-07-05 21:49:51 +0000159 Selector subscriptSel) {
Argyrios Kyrtzidis89b928e2012-07-06 00:07:09 +0000160 const Expr *Rec = Msg->getInstanceReceiver();
161 if (!Rec)
162 return false;
163 IFace = maybeAdjustInterfaceForSubscriptingCheck(IFace, Rec, Ctx);
164
Argyrios Kyrtzidis13b92922012-07-05 21:49:51 +0000165 if (const ObjCMethodDecl *MD = IFace->lookupInstanceMethod(subscriptSel)) {
166 if (!MD->isUnavailable())
167 return true;
168 }
169 return false;
170}
171
Argyrios Kyrtzidis0bbe94f2012-05-14 23:33:49 +0000172static bool subscriptOperatorNeedsParens(const Expr *FullExpr);
173
Ted Kremenekf7639e12012-03-06 20:06:33 +0000174static void maybePutParensOnReceiver(const Expr *Receiver, Commit &commit) {
Argyrios Kyrtzidis0bbe94f2012-05-14 23:33:49 +0000175 if (subscriptOperatorNeedsParens(Receiver)) {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000176 SourceRange RecRange = Receiver->getSourceRange();
177 commit.insertWrap("(", RecRange, ")");
178 }
179}
180
Argyrios Kyrtzidis6310fdd2012-06-04 21:23:26 +0000181static bool rewriteToSubscriptGetCommon(const ObjCMessageExpr *Msg,
182 Commit &commit) {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000183 if (Msg->getNumArgs() != 1)
184 return false;
185 const Expr *Rec = Msg->getInstanceReceiver();
186 if (!Rec)
187 return false;
188
189 SourceRange MsgRange = Msg->getSourceRange();
190 SourceRange RecRange = Rec->getSourceRange();
191 SourceRange ArgRange = Msg->getArg(0)->getSourceRange();
192
193 commit.replaceWithInner(CharSourceRange::getCharRange(MsgRange.getBegin(),
194 ArgRange.getBegin()),
195 CharSourceRange::getTokenRange(RecRange));
196 commit.replaceWithInner(SourceRange(ArgRange.getBegin(), MsgRange.getEnd()),
197 ArgRange);
198 commit.insertWrap("[", ArgRange, "]");
199 maybePutParensOnReceiver(Rec, commit);
200 return true;
201}
202
Argyrios Kyrtzidis6310fdd2012-06-04 21:23:26 +0000203static bool rewriteToArraySubscriptGet(const ObjCInterfaceDecl *IFace,
204 const ObjCMessageExpr *Msg,
205 const NSAPI &NS,
206 Commit &commit) {
Argyrios Kyrtzidis89b928e2012-07-06 00:07:09 +0000207 if (!canRewriteToSubscriptSyntax(IFace, Msg, NS.getASTContext(),
Argyrios Kyrtzidis13b92922012-07-05 21:49:51 +0000208 NS.getObjectAtIndexedSubscriptSelector()))
Argyrios Kyrtzidis6310fdd2012-06-04 21:23:26 +0000209 return false;
210 return rewriteToSubscriptGetCommon(Msg, commit);
211}
212
213static bool rewriteToDictionarySubscriptGet(const ObjCInterfaceDecl *IFace,
214 const ObjCMessageExpr *Msg,
215 const NSAPI &NS,
216 Commit &commit) {
Argyrios Kyrtzidis89b928e2012-07-06 00:07:09 +0000217 if (!canRewriteToSubscriptSyntax(IFace, Msg, NS.getASTContext(),
Argyrios Kyrtzidis13b92922012-07-05 21:49:51 +0000218 NS.getObjectForKeyedSubscriptSelector()))
Argyrios Kyrtzidis6310fdd2012-06-04 21:23:26 +0000219 return false;
220 return rewriteToSubscriptGetCommon(Msg, commit);
221}
222
223static bool rewriteToArraySubscriptSet(const ObjCInterfaceDecl *IFace,
224 const ObjCMessageExpr *Msg,
225 const NSAPI &NS,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000226 Commit &commit) {
Argyrios Kyrtzidis89b928e2012-07-06 00:07:09 +0000227 if (!canRewriteToSubscriptSyntax(IFace, Msg, NS.getASTContext(),
Argyrios Kyrtzidis13b92922012-07-05 21:49:51 +0000228 NS.getSetObjectAtIndexedSubscriptSelector()))
229 return false;
230
Ted Kremenekf7639e12012-03-06 20:06:33 +0000231 if (Msg->getNumArgs() != 2)
232 return false;
233 const Expr *Rec = Msg->getInstanceReceiver();
234 if (!Rec)
235 return false;
236
237 SourceRange MsgRange = Msg->getSourceRange();
238 SourceRange RecRange = Rec->getSourceRange();
239 SourceRange Arg0Range = Msg->getArg(0)->getSourceRange();
240 SourceRange Arg1Range = Msg->getArg(1)->getSourceRange();
241
242 commit.replaceWithInner(CharSourceRange::getCharRange(MsgRange.getBegin(),
243 Arg0Range.getBegin()),
244 CharSourceRange::getTokenRange(RecRange));
245 commit.replaceWithInner(CharSourceRange::getCharRange(Arg0Range.getBegin(),
246 Arg1Range.getBegin()),
247 CharSourceRange::getTokenRange(Arg0Range));
248 commit.replaceWithInner(SourceRange(Arg1Range.getBegin(), MsgRange.getEnd()),
249 Arg1Range);
250 commit.insertWrap("[", CharSourceRange::getCharRange(Arg0Range.getBegin(),
251 Arg1Range.getBegin()),
252 "] = ");
253 maybePutParensOnReceiver(Rec, commit);
254 return true;
255}
256
Argyrios Kyrtzidis6310fdd2012-06-04 21:23:26 +0000257static bool rewriteToDictionarySubscriptSet(const ObjCInterfaceDecl *IFace,
258 const ObjCMessageExpr *Msg,
259 const NSAPI &NS,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000260 Commit &commit) {
Argyrios Kyrtzidis89b928e2012-07-06 00:07:09 +0000261 if (!canRewriteToSubscriptSyntax(IFace, Msg, NS.getASTContext(),
Argyrios Kyrtzidis13b92922012-07-05 21:49:51 +0000262 NS.getSetObjectForKeyedSubscriptSelector()))
263 return false;
264
Ted Kremenekf7639e12012-03-06 20:06:33 +0000265 if (Msg->getNumArgs() != 2)
266 return false;
267 const Expr *Rec = Msg->getInstanceReceiver();
268 if (!Rec)
269 return false;
270
271 SourceRange MsgRange = Msg->getSourceRange();
272 SourceRange RecRange = Rec->getSourceRange();
273 SourceRange Arg0Range = Msg->getArg(0)->getSourceRange();
274 SourceRange Arg1Range = Msg->getArg(1)->getSourceRange();
275
276 SourceLocation LocBeforeVal = Arg0Range.getBegin();
277 commit.insertBefore(LocBeforeVal, "] = ");
278 commit.insertFromRange(LocBeforeVal, Arg1Range, /*afterToken=*/false,
279 /*beforePreviousInsertions=*/true);
280 commit.insertBefore(LocBeforeVal, "[");
281 commit.replaceWithInner(CharSourceRange::getCharRange(MsgRange.getBegin(),
282 Arg0Range.getBegin()),
283 CharSourceRange::getTokenRange(RecRange));
284 commit.replaceWithInner(SourceRange(Arg0Range.getBegin(), MsgRange.getEnd()),
285 Arg0Range);
286 maybePutParensOnReceiver(Rec, commit);
287 return true;
288}
289
290bool edit::rewriteToObjCSubscriptSyntax(const ObjCMessageExpr *Msg,
Argyrios Kyrtzidis6310fdd2012-06-04 21:23:26 +0000291 const NSAPI &NS, Commit &commit) {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000292 if (!Msg || Msg->isImplicit() ||
293 Msg->getReceiverKind() != ObjCMessageExpr::Instance)
294 return false;
295 const ObjCMethodDecl *Method = Msg->getMethodDecl();
296 if (!Method)
297 return false;
298
Dmitri Gribenko60e92e52013-02-14 13:49:48 +0000299 const ObjCInterfaceDecl *IFace =
300 NS.getASTContext().getObjContainingInterface(Method);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000301 if (!IFace)
302 return false;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000303 Selector Sel = Msg->getSelector();
304
Argyrios Kyrtzidis13b92922012-07-05 21:49:51 +0000305 if (Sel == NS.getNSArraySelector(NSAPI::NSArr_objectAtIndex))
Argyrios Kyrtzidis6310fdd2012-06-04 21:23:26 +0000306 return rewriteToArraySubscriptGet(IFace, Msg, NS, commit);
307
Argyrios Kyrtzidis13b92922012-07-05 21:49:51 +0000308 if (Sel == NS.getNSDictionarySelector(NSAPI::NSDict_objectForKey))
Argyrios Kyrtzidis6310fdd2012-06-04 21:23:26 +0000309 return rewriteToDictionarySubscriptGet(IFace, Msg, NS, commit);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000310
311 if (Msg->getNumArgs() != 2)
312 return false;
313
Argyrios Kyrtzidis13b92922012-07-05 21:49:51 +0000314 if (Sel == NS.getNSArraySelector(NSAPI::NSMutableArr_replaceObjectAtIndex))
Argyrios Kyrtzidis6310fdd2012-06-04 21:23:26 +0000315 return rewriteToArraySubscriptSet(IFace, Msg, NS, commit);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000316
Argyrios Kyrtzidis13b92922012-07-05 21:49:51 +0000317 if (Sel == NS.getNSDictionarySelector(NSAPI::NSMutableDict_setObjectForKey))
Argyrios Kyrtzidis6310fdd2012-06-04 21:23:26 +0000318 return rewriteToDictionarySubscriptSet(IFace, Msg, NS, commit);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000319
320 return false;
321}
322
323//===----------------------------------------------------------------------===//
324// rewriteToObjCLiteralSyntax.
325//===----------------------------------------------------------------------===//
326
327static bool rewriteToArrayLiteral(const ObjCMessageExpr *Msg,
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000328 const NSAPI &NS, Commit &commit,
329 const ParentMap *PMap);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000330static bool rewriteToDictionaryLiteral(const ObjCMessageExpr *Msg,
331 const NSAPI &NS, Commit &commit);
332static bool rewriteToNumberLiteral(const ObjCMessageExpr *Msg,
333 const NSAPI &NS, Commit &commit);
Argyrios Kyrtzidis491e4ae2012-05-15 19:17:49 +0000334static bool rewriteToNumericBoxedExpression(const ObjCMessageExpr *Msg,
335 const NSAPI &NS, Commit &commit);
Argyrios Kyrtzidis7bd957c2012-05-15 22:22:10 +0000336static bool rewriteToStringBoxedExpression(const ObjCMessageExpr *Msg,
337 const NSAPI &NS, Commit &commit);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000338
339bool edit::rewriteToObjCLiteralSyntax(const ObjCMessageExpr *Msg,
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000340 const NSAPI &NS, Commit &commit,
341 const ParentMap *PMap) {
Craig Topper2145bc02014-05-09 08:15:10 +0000342 IdentifierInfo *II = nullptr;
Argyrios Kyrtzidis63aebfb2012-06-06 22:23:12 +0000343 if (!checkForLiteralCreation(Msg, II, NS.getASTContext().getLangOpts()))
Ted Kremenekf7639e12012-03-06 20:06:33 +0000344 return false;
345
346 if (II == NS.getNSClassId(NSAPI::ClassId_NSArray))
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000347 return rewriteToArrayLiteral(Msg, NS, commit, PMap);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000348 if (II == NS.getNSClassId(NSAPI::ClassId_NSDictionary))
349 return rewriteToDictionaryLiteral(Msg, NS, commit);
350 if (II == NS.getNSClassId(NSAPI::ClassId_NSNumber))
351 return rewriteToNumberLiteral(Msg, NS, commit);
Argyrios Kyrtzidis7bd957c2012-05-15 22:22:10 +0000352 if (II == NS.getNSClassId(NSAPI::ClassId_NSString))
353 return rewriteToStringBoxedExpression(Msg, NS, commit);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000354
355 return false;
356}
357
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000358/// Returns true if the immediate message arguments of \c Msg should not
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000359/// be rewritten because it will interfere with the rewrite of the parent
360/// message expression. e.g.
361/// \code
362/// [NSDictionary dictionaryWithObjects:
363/// [NSArray arrayWithObjects:@"1", @"2", nil]
364/// forKeys:[NSArray arrayWithObjects:@"A", @"B", nil]];
365/// \endcode
366/// It will return true for this because we are going to rewrite this directly
367/// to a dictionary literal without any array literals.
368static bool shouldNotRewriteImmediateMessageArgs(const ObjCMessageExpr *Msg,
369 const NSAPI &NS);
370
Ted Kremenekf7639e12012-03-06 20:06:33 +0000371//===----------------------------------------------------------------------===//
372// rewriteToArrayLiteral.
373//===----------------------------------------------------------------------===//
374
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000375/// Adds an explicit cast to 'id' if the type is not objc object.
Argyrios Kyrtzidisc1dfed62012-05-14 22:01:53 +0000376static void objectifyExpr(const Expr *E, Commit &commit);
377
Ted Kremenekf7639e12012-03-06 20:06:33 +0000378static bool rewriteToArrayLiteral(const ObjCMessageExpr *Msg,
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000379 const NSAPI &NS, Commit &commit,
380 const ParentMap *PMap) {
381 if (PMap) {
382 const ObjCMessageExpr *ParentMsg =
383 dyn_cast_or_null<ObjCMessageExpr>(PMap->getParentIgnoreParenCasts(Msg));
384 if (shouldNotRewriteImmediateMessageArgs(ParentMsg, NS))
385 return false;
386 }
387
Ted Kremenekf7639e12012-03-06 20:06:33 +0000388 Selector Sel = Msg->getSelector();
389 SourceRange MsgRange = Msg->getSourceRange();
390
391 if (Sel == NS.getNSArraySelector(NSAPI::NSArr_array)) {
392 if (Msg->getNumArgs() != 0)
393 return false;
394 commit.replace(MsgRange, "@[]");
395 return true;
396 }
397
398 if (Sel == NS.getNSArraySelector(NSAPI::NSArr_arrayWithObject)) {
399 if (Msg->getNumArgs() != 1)
400 return false;
Argyrios Kyrtzidisc1dfed62012-05-14 22:01:53 +0000401 objectifyExpr(Msg->getArg(0), commit);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000402 SourceRange ArgRange = Msg->getArg(0)->getSourceRange();
403 commit.replaceWithInner(MsgRange, ArgRange);
404 commit.insertWrap("@[", ArgRange, "]");
405 return true;
406 }
407
Argyrios Kyrtzidis63aebfb2012-06-06 22:23:12 +0000408 if (Sel == NS.getNSArraySelector(NSAPI::NSArr_arrayWithObjects) ||
409 Sel == NS.getNSArraySelector(NSAPI::NSArr_initWithObjects)) {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000410 if (Msg->getNumArgs() == 0)
411 return false;
412 const Expr *SentinelExpr = Msg->getArg(Msg->getNumArgs() - 1);
413 if (!NS.getASTContext().isSentinelNullExpr(SentinelExpr))
414 return false;
415
Argyrios Kyrtzidisc1dfed62012-05-14 22:01:53 +0000416 for (unsigned i = 0, e = Msg->getNumArgs() - 1; i != e; ++i)
417 objectifyExpr(Msg->getArg(i), commit);
418
Ted Kremenekf7639e12012-03-06 20:06:33 +0000419 if (Msg->getNumArgs() == 1) {
420 commit.replace(MsgRange, "@[]");
421 return true;
422 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000423 SourceRange ArgRange(Msg->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000424 Msg->getArg(Msg->getNumArgs() - 2)->getEndLoc());
Ted Kremenekf7639e12012-03-06 20:06:33 +0000425 commit.replaceWithInner(MsgRange, ArgRange);
426 commit.insertWrap("@[", ArgRange, "]");
427 return true;
428 }
429
430 return false;
431}
432
433//===----------------------------------------------------------------------===//
434// rewriteToDictionaryLiteral.
435//===----------------------------------------------------------------------===//
436
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000437/// If \c Msg is an NSArray creation message or literal, this gets the
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000438/// objects that were used to create it.
439/// \returns true if it is an NSArray and we got objects, or false otherwise.
440static bool getNSArrayObjects(const Expr *E, const NSAPI &NS,
441 SmallVectorImpl<const Expr *> &Objs) {
442 if (!E)
443 return false;
444
445 E = E->IgnoreParenCasts();
446 if (!E)
447 return false;
448
449 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
Craig Topper2145bc02014-05-09 08:15:10 +0000450 IdentifierInfo *Cls = nullptr;
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000451 if (!checkForLiteralCreation(Msg, Cls, NS.getASTContext().getLangOpts()))
452 return false;
453
454 if (Cls != NS.getNSClassId(NSAPI::ClassId_NSArray))
455 return false;
456
457 Selector Sel = Msg->getSelector();
458 if (Sel == NS.getNSArraySelector(NSAPI::NSArr_array))
459 return true; // empty array.
460
461 if (Sel == NS.getNSArraySelector(NSAPI::NSArr_arrayWithObject)) {
462 if (Msg->getNumArgs() != 1)
463 return false;
464 Objs.push_back(Msg->getArg(0));
465 return true;
466 }
467
468 if (Sel == NS.getNSArraySelector(NSAPI::NSArr_arrayWithObjects) ||
469 Sel == NS.getNSArraySelector(NSAPI::NSArr_initWithObjects)) {
470 if (Msg->getNumArgs() == 0)
471 return false;
472 const Expr *SentinelExpr = Msg->getArg(Msg->getNumArgs() - 1);
473 if (!NS.getASTContext().isSentinelNullExpr(SentinelExpr))
474 return false;
475
476 for (unsigned i = 0, e = Msg->getNumArgs() - 1; i != e; ++i)
477 Objs.push_back(Msg->getArg(i));
478 return true;
479 }
480
481 } else if (const ObjCArrayLiteral *ArrLit = dyn_cast<ObjCArrayLiteral>(E)) {
482 for (unsigned i = 0, e = ArrLit->getNumElements(); i != e; ++i)
483 Objs.push_back(ArrLit->getElement(i));
484 return true;
485 }
486
487 return false;
488}
489
Ted Kremenekf7639e12012-03-06 20:06:33 +0000490static bool rewriteToDictionaryLiteral(const ObjCMessageExpr *Msg,
491 const NSAPI &NS, Commit &commit) {
492 Selector Sel = Msg->getSelector();
493 SourceRange MsgRange = Msg->getSourceRange();
494
495 if (Sel == NS.getNSDictionarySelector(NSAPI::NSDict_dictionary)) {
496 if (Msg->getNumArgs() != 0)
497 return false;
498 commit.replace(MsgRange, "@{}");
499 return true;
500 }
501
502 if (Sel == NS.getNSDictionarySelector(
503 NSAPI::NSDict_dictionaryWithObjectForKey)) {
504 if (Msg->getNumArgs() != 2)
505 return false;
Argyrios Kyrtzidisc1dfed62012-05-14 22:01:53 +0000506
507 objectifyExpr(Msg->getArg(0), commit);
508 objectifyExpr(Msg->getArg(1), commit);
509
Ted Kremenekf7639e12012-03-06 20:06:33 +0000510 SourceRange ValRange = Msg->getArg(0)->getSourceRange();
511 SourceRange KeyRange = Msg->getArg(1)->getSourceRange();
512 // Insert key before the value.
513 commit.insertBefore(ValRange.getBegin(), ": ");
514 commit.insertFromRange(ValRange.getBegin(),
515 CharSourceRange::getTokenRange(KeyRange),
516 /*afterToken=*/false, /*beforePreviousInsertions=*/true);
517 commit.insertBefore(ValRange.getBegin(), "@{");
518 commit.insertAfterToken(ValRange.getEnd(), "}");
519 commit.replaceWithInner(MsgRange, ValRange);
520 return true;
521 }
522
523 if (Sel == NS.getNSDictionarySelector(
Argyrios Kyrtzidis63aebfb2012-06-06 22:23:12 +0000524 NSAPI::NSDict_dictionaryWithObjectsAndKeys) ||
525 Sel == NS.getNSDictionarySelector(NSAPI::NSDict_initWithObjectsAndKeys)) {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000526 if (Msg->getNumArgs() % 2 != 1)
527 return false;
528 unsigned SentinelIdx = Msg->getNumArgs() - 1;
529 const Expr *SentinelExpr = Msg->getArg(SentinelIdx);
530 if (!NS.getASTContext().isSentinelNullExpr(SentinelExpr))
531 return false;
532
533 if (Msg->getNumArgs() == 1) {
534 commit.replace(MsgRange, "@{}");
535 return true;
536 }
537
538 for (unsigned i = 0; i < SentinelIdx; i += 2) {
Argyrios Kyrtzidisc1dfed62012-05-14 22:01:53 +0000539 objectifyExpr(Msg->getArg(i), commit);
540 objectifyExpr(Msg->getArg(i+1), commit);
541
Ted Kremenekf7639e12012-03-06 20:06:33 +0000542 SourceRange ValRange = Msg->getArg(i)->getSourceRange();
543 SourceRange KeyRange = Msg->getArg(i+1)->getSourceRange();
544 // Insert value after key.
545 commit.insertAfterToken(KeyRange.getEnd(), ": ");
546 commit.insertFromRange(KeyRange.getEnd(), ValRange, /*afterToken=*/true);
547 commit.remove(CharSourceRange::getCharRange(ValRange.getBegin(),
548 KeyRange.getBegin()));
549 }
550 // Range of arguments up until and including the last key.
551 // The sentinel and first value are cut off, the value will move after the
552 // key.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000553 SourceRange ArgRange(Msg->getArg(1)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000554 Msg->getArg(SentinelIdx - 1)->getEndLoc());
Ted Kremenekf7639e12012-03-06 20:06:33 +0000555 commit.insertWrap("@{", ArgRange, "}");
556 commit.replaceWithInner(MsgRange, ArgRange);
557 return true;
558 }
559
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000560 if (Sel == NS.getNSDictionarySelector(
561 NSAPI::NSDict_dictionaryWithObjectsForKeys) ||
562 Sel == NS.getNSDictionarySelector(NSAPI::NSDict_initWithObjectsForKeys)) {
563 if (Msg->getNumArgs() != 2)
564 return false;
565
566 SmallVector<const Expr *, 8> Vals;
567 if (!getNSArrayObjects(Msg->getArg(0), NS, Vals))
568 return false;
569
570 SmallVector<const Expr *, 8> Keys;
571 if (!getNSArrayObjects(Msg->getArg(1), NS, Keys))
572 return false;
573
574 if (Vals.size() != Keys.size())
575 return false;
576
577 if (Vals.empty()) {
578 commit.replace(MsgRange, "@{}");
579 return true;
580 }
581
582 for (unsigned i = 0, n = Vals.size(); i < n; ++i) {
583 objectifyExpr(Vals[i], commit);
584 objectifyExpr(Keys[i], commit);
585
586 SourceRange ValRange = Vals[i]->getSourceRange();
587 SourceRange KeyRange = Keys[i]->getSourceRange();
588 // Insert value after key.
589 commit.insertAfterToken(KeyRange.getEnd(), ": ");
590 commit.insertFromRange(KeyRange.getEnd(), ValRange, /*afterToken=*/true);
591 }
592 // Range of arguments up until and including the last key.
593 // The first value is cut off, the value will move after the key.
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000594 SourceRange ArgRange(Keys.front()->getBeginLoc(), Keys.back()->getEndLoc());
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000595 commit.insertWrap("@{", ArgRange, "}");
596 commit.replaceWithInner(MsgRange, ArgRange);
597 return true;
598 }
599
600 return false;
601}
602
603static bool shouldNotRewriteImmediateMessageArgs(const ObjCMessageExpr *Msg,
604 const NSAPI &NS) {
605 if (!Msg)
606 return false;
607
Craig Topper2145bc02014-05-09 08:15:10 +0000608 IdentifierInfo *II = nullptr;
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000609 if (!checkForLiteralCreation(Msg, II, NS.getASTContext().getLangOpts()))
610 return false;
611
612 if (II != NS.getNSClassId(NSAPI::ClassId_NSDictionary))
613 return false;
614
615 Selector Sel = Msg->getSelector();
616 if (Sel == NS.getNSDictionarySelector(
617 NSAPI::NSDict_dictionaryWithObjectsForKeys) ||
618 Sel == NS.getNSDictionarySelector(NSAPI::NSDict_initWithObjectsForKeys)) {
619 if (Msg->getNumArgs() != 2)
620 return false;
621
622 SmallVector<const Expr *, 8> Vals;
623 if (!getNSArrayObjects(Msg->getArg(0), NS, Vals))
624 return false;
625
626 SmallVector<const Expr *, 8> Keys;
627 if (!getNSArrayObjects(Msg->getArg(1), NS, Keys))
628 return false;
629
630 if (Vals.size() != Keys.size())
631 return false;
632
633 return true;
634 }
635
Ted Kremenekf7639e12012-03-06 20:06:33 +0000636 return false;
637}
638
639//===----------------------------------------------------------------------===//
640// rewriteToNumberLiteral.
641//===----------------------------------------------------------------------===//
642
643static bool rewriteToCharLiteral(const ObjCMessageExpr *Msg,
644 const CharacterLiteral *Arg,
645 const NSAPI &NS, Commit &commit) {
646 if (Arg->getKind() != CharacterLiteral::Ascii)
647 return false;
648 if (NS.isNSNumberLiteralSelector(NSAPI::NSNumberWithChar,
649 Msg->getSelector())) {
650 SourceRange ArgRange = Arg->getSourceRange();
651 commit.replaceWithInner(Msg->getSourceRange(), ArgRange);
652 commit.insert(ArgRange.getBegin(), "@");
653 return true;
654 }
655
Argyrios Kyrtzidis491e4ae2012-05-15 19:17:49 +0000656 return rewriteToNumericBoxedExpression(Msg, NS, commit);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000657}
658
659static bool rewriteToBoolLiteral(const ObjCMessageExpr *Msg,
660 const Expr *Arg,
661 const NSAPI &NS, Commit &commit) {
662 if (NS.isNSNumberLiteralSelector(NSAPI::NSNumberWithBool,
663 Msg->getSelector())) {
664 SourceRange ArgRange = Arg->getSourceRange();
665 commit.replaceWithInner(Msg->getSourceRange(), ArgRange);
666 commit.insert(ArgRange.getBegin(), "@");
667 return true;
668 }
669
Argyrios Kyrtzidis491e4ae2012-05-15 19:17:49 +0000670 return rewriteToNumericBoxedExpression(Msg, NS, commit);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000671}
672
673namespace {
674
675struct LiteralInfo {
676 bool Hex, Octal;
677 StringRef U, F, L, LL;
678 CharSourceRange WithoutSuffRange;
679};
680
681}
682
683static bool getLiteralInfo(SourceRange literalRange,
684 bool isFloat, bool isIntZero,
685 ASTContext &Ctx, LiteralInfo &Info) {
686 if (literalRange.getBegin().isMacroID() ||
687 literalRange.getEnd().isMacroID())
688 return false;
689 StringRef text = Lexer::getSourceText(
690 CharSourceRange::getTokenRange(literalRange),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000691 Ctx.getSourceManager(), Ctx.getLangOpts());
Ted Kremenekf7639e12012-03-06 20:06:33 +0000692 if (text.empty())
693 return false;
694
David Blaikie05785d12013-02-20 22:23:23 +0000695 Optional<bool> UpperU, UpperL;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000696 bool UpperF = false;
697
698 struct Suff {
699 static bool has(StringRef suff, StringRef &text) {
700 if (text.endswith(suff)) {
701 text = text.substr(0, text.size()-suff.size());
702 return true;
703 }
704 return false;
705 }
706 };
707
708 while (1) {
709 if (Suff::has("u", text)) {
710 UpperU = false;
711 } else if (Suff::has("U", text)) {
712 UpperU = true;
713 } else if (Suff::has("ll", text)) {
714 UpperL = false;
715 } else if (Suff::has("LL", text)) {
716 UpperL = true;
717 } else if (Suff::has("l", text)) {
718 UpperL = false;
719 } else if (Suff::has("L", text)) {
720 UpperL = true;
721 } else if (isFloat && Suff::has("f", text)) {
722 UpperF = false;
723 } else if (isFloat && Suff::has("F", text)) {
724 UpperF = true;
725 } else
726 break;
727 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000728
Ted Kremenekf7639e12012-03-06 20:06:33 +0000729 if (!UpperU.hasValue() && !UpperL.hasValue())
730 UpperU = UpperL = true;
731 else if (UpperU.hasValue() && !UpperL.hasValue())
732 UpperL = UpperU;
733 else if (UpperL.hasValue() && !UpperU.hasValue())
734 UpperU = UpperL;
735
736 Info.U = *UpperU ? "U" : "u";
737 Info.L = *UpperL ? "L" : "l";
738 Info.LL = *UpperL ? "LL" : "ll";
739 Info.F = UpperF ? "F" : "f";
Fangrui Song6907ce22018-07-30 19:24:48 +0000740
Ted Kremenekf7639e12012-03-06 20:06:33 +0000741 Info.Hex = Info.Octal = false;
742 if (text.startswith("0x"))
743 Info.Hex = true;
744 else if (!isFloat && !isIntZero && text.startswith("0"))
745 Info.Octal = true;
746
747 SourceLocation B = literalRange.getBegin();
748 Info.WithoutSuffRange =
749 CharSourceRange::getCharRange(B, B.getLocWithOffset(text.size()));
750 return true;
751}
752
753static bool rewriteToNumberLiteral(const ObjCMessageExpr *Msg,
754 const NSAPI &NS, Commit &commit) {
755 if (Msg->getNumArgs() != 1)
756 return false;
757
758 const Expr *Arg = Msg->getArg(0)->IgnoreParenImpCasts();
759 if (const CharacterLiteral *CharE = dyn_cast<CharacterLiteral>(Arg))
760 return rewriteToCharLiteral(Msg, CharE, NS, commit);
761 if (const ObjCBoolLiteralExpr *BE = dyn_cast<ObjCBoolLiteralExpr>(Arg))
762 return rewriteToBoolLiteral(Msg, BE, NS, commit);
763 if (const CXXBoolLiteralExpr *BE = dyn_cast<CXXBoolLiteralExpr>(Arg))
764 return rewriteToBoolLiteral(Msg, BE, NS, commit);
765
766 const Expr *literalE = Arg;
767 if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(literalE)) {
768 if (UOE->getOpcode() == UO_Plus || UOE->getOpcode() == UO_Minus)
769 literalE = UOE->getSubExpr();
770 }
771
Argyrios Kyrtzidis491e4ae2012-05-15 19:17:49 +0000772 // Only integer and floating literals, otherwise try to rewrite to boxed
773 // expression.
Ted Kremenekf7639e12012-03-06 20:06:33 +0000774 if (!isa<IntegerLiteral>(literalE) && !isa<FloatingLiteral>(literalE))
Argyrios Kyrtzidis491e4ae2012-05-15 19:17:49 +0000775 return rewriteToNumericBoxedExpression(Msg, NS, commit);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000776
777 ASTContext &Ctx = NS.getASTContext();
778 Selector Sel = Msg->getSelector();
David Blaikie05785d12013-02-20 22:23:23 +0000779 Optional<NSAPI::NSNumberLiteralMethodKind>
Ted Kremenekf7639e12012-03-06 20:06:33 +0000780 MKOpt = NS.getNSNumberLiteralMethodKind(Sel);
781 if (!MKOpt)
782 return false;
783 NSAPI::NSNumberLiteralMethodKind MK = *MKOpt;
784
Benjamin Kramerece209a2012-03-13 17:05:43 +0000785 bool CallIsUnsigned = false, CallIsLong = false, CallIsLongLong = false;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000786 bool CallIsFloating = false, CallIsDouble = false;
787
788 switch (MK) {
789 // We cannot have these calls with int/float literals.
790 case NSAPI::NSNumberWithChar:
791 case NSAPI::NSNumberWithUnsignedChar:
792 case NSAPI::NSNumberWithShort:
793 case NSAPI::NSNumberWithUnsignedShort:
794 case NSAPI::NSNumberWithBool:
Argyrios Kyrtzidis491e4ae2012-05-15 19:17:49 +0000795 return rewriteToNumericBoxedExpression(Msg, NS, commit);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000796
797 case NSAPI::NSNumberWithUnsignedInt:
798 case NSAPI::NSNumberWithUnsignedInteger:
799 CallIsUnsigned = true;
Galina Kistanovaefa71242017-06-03 06:30:08 +0000800 LLVM_FALLTHROUGH;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000801 case NSAPI::NSNumberWithInt:
802 case NSAPI::NSNumberWithInteger:
Ted Kremenekf7639e12012-03-06 20:06:33 +0000803 break;
804
805 case NSAPI::NSNumberWithUnsignedLong:
806 CallIsUnsigned = true;
Galina Kistanovaefa71242017-06-03 06:30:08 +0000807 LLVM_FALLTHROUGH;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000808 case NSAPI::NSNumberWithLong:
Benjamin Kramerece209a2012-03-13 17:05:43 +0000809 CallIsLong = true;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000810 break;
811
812 case NSAPI::NSNumberWithUnsignedLongLong:
813 CallIsUnsigned = true;
Galina Kistanovaefa71242017-06-03 06:30:08 +0000814 LLVM_FALLTHROUGH;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000815 case NSAPI::NSNumberWithLongLong:
Benjamin Kramerece209a2012-03-13 17:05:43 +0000816 CallIsLongLong = true;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000817 break;
818
819 case NSAPI::NSNumberWithDouble:
820 CallIsDouble = true;
Galina Kistanovaefa71242017-06-03 06:30:08 +0000821 LLVM_FALLTHROUGH;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000822 case NSAPI::NSNumberWithFloat:
823 CallIsFloating = true;
824 break;
825 }
826
827 SourceRange ArgRange = Arg->getSourceRange();
828 QualType ArgTy = Arg->getType();
829 QualType CallTy = Msg->getArg(0)->getType();
830
831 // Check for the easy case, the literal maps directly to the call.
832 if (Ctx.hasSameType(ArgTy, CallTy)) {
833 commit.replaceWithInner(Msg->getSourceRange(), ArgRange);
834 commit.insert(ArgRange.getBegin(), "@");
835 return true;
836 }
837
838 // We will need to modify the literal suffix to get the same type as the call.
Argyrios Kyrtzidis491e4ae2012-05-15 19:17:49 +0000839 // Try with boxed expression if it came from a macro.
Ted Kremenekf7639e12012-03-06 20:06:33 +0000840 if (ArgRange.getBegin().isMacroID())
Argyrios Kyrtzidis491e4ae2012-05-15 19:17:49 +0000841 return rewriteToNumericBoxedExpression(Msg, NS, commit);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000842
843 bool LitIsFloat = ArgTy->isFloatingType();
Argyrios Kyrtzidis491e4ae2012-05-15 19:17:49 +0000844 // For a float passed to integer call, don't try rewriting to objc literal.
845 // It is difficult and a very uncommon case anyway.
846 // But try with boxed expression.
Ted Kremenekf7639e12012-03-06 20:06:33 +0000847 if (LitIsFloat && !CallIsFloating)
Argyrios Kyrtzidis491e4ae2012-05-15 19:17:49 +0000848 return rewriteToNumericBoxedExpression(Msg, NS, commit);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000849
850 // Try to modify the literal make it the same type as the method call.
851 // -Modify the suffix, and/or
852 // -Change integer to float
Fangrui Song6907ce22018-07-30 19:24:48 +0000853
Ted Kremenekf7639e12012-03-06 20:06:33 +0000854 LiteralInfo LitInfo;
855 bool isIntZero = false;
856 if (const IntegerLiteral *IntE = dyn_cast<IntegerLiteral>(literalE))
857 isIntZero = !IntE->getValue().getBoolValue();
858 if (!getLiteralInfo(ArgRange, LitIsFloat, isIntZero, Ctx, LitInfo))
Argyrios Kyrtzidis491e4ae2012-05-15 19:17:49 +0000859 return rewriteToNumericBoxedExpression(Msg, NS, commit);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000860
861 // Not easy to do int -> float with hex/octal and uncommon anyway.
862 if (!LitIsFloat && CallIsFloating && (LitInfo.Hex || LitInfo.Octal))
Argyrios Kyrtzidis491e4ae2012-05-15 19:17:49 +0000863 return rewriteToNumericBoxedExpression(Msg, NS, commit);
Fangrui Song6907ce22018-07-30 19:24:48 +0000864
Ted Kremenekf7639e12012-03-06 20:06:33 +0000865 SourceLocation LitB = LitInfo.WithoutSuffRange.getBegin();
866 SourceLocation LitE = LitInfo.WithoutSuffRange.getEnd();
867
868 commit.replaceWithInner(CharSourceRange::getTokenRange(Msg->getSourceRange()),
869 LitInfo.WithoutSuffRange);
870 commit.insert(LitB, "@");
871
872 if (!LitIsFloat && CallIsFloating)
873 commit.insert(LitE, ".0");
874
875 if (CallIsFloating) {
876 if (!CallIsDouble)
877 commit.insert(LitE, LitInfo.F);
878 } else {
879 if (CallIsUnsigned)
880 commit.insert(LitE, LitInfo.U);
Fangrui Song6907ce22018-07-30 19:24:48 +0000881
Ted Kremenekf7639e12012-03-06 20:06:33 +0000882 if (CallIsLong)
883 commit.insert(LitE, LitInfo.L);
884 else if (CallIsLongLong)
885 commit.insert(LitE, LitInfo.LL);
886 }
887 return true;
888}
Argyrios Kyrtzidisc1dfed62012-05-14 22:01:53 +0000889
Argyrios Kyrtzidis0bbe94f2012-05-14 23:33:49 +0000890// FIXME: Make determination of operator precedence more general and
891// make it broadly available.
892static bool subscriptOperatorNeedsParens(const Expr *FullExpr) {
893 const Expr* Expr = FullExpr->IgnoreImpCasts();
894 if (isa<ArraySubscriptExpr>(Expr) ||
895 isa<CallExpr>(Expr) ||
896 isa<DeclRefExpr>(Expr) ||
897 isa<CXXNamedCastExpr>(Expr) ||
898 isa<CXXConstructExpr>(Expr) ||
899 isa<CXXThisExpr>(Expr) ||
900 isa<CXXTypeidExpr>(Expr) ||
901 isa<CXXUnresolvedConstructExpr>(Expr) ||
902 isa<ObjCMessageExpr>(Expr) ||
903 isa<ObjCPropertyRefExpr>(Expr) ||
904 isa<ObjCProtocolExpr>(Expr) ||
905 isa<MemberExpr>(Expr) ||
Argyrios Kyrtzidis94442982012-05-22 00:47:53 +0000906 isa<ObjCIvarRefExpr>(Expr) ||
Argyrios Kyrtzidis0bbe94f2012-05-14 23:33:49 +0000907 isa<ParenExpr>(FullExpr) ||
908 isa<ParenListExpr>(Expr) ||
909 isa<SizeOfPackExpr>(Expr))
910 return false;
911
912 return true;
913}
Argyrios Kyrtzidisc1dfed62012-05-14 22:01:53 +0000914static bool castOperatorNeedsParens(const Expr *FullExpr) {
915 const Expr* Expr = FullExpr->IgnoreImpCasts();
916 if (isa<ArraySubscriptExpr>(Expr) ||
917 isa<CallExpr>(Expr) ||
918 isa<DeclRefExpr>(Expr) ||
919 isa<CastExpr>(Expr) ||
920 isa<CXXNewExpr>(Expr) ||
921 isa<CXXConstructExpr>(Expr) ||
922 isa<CXXDeleteExpr>(Expr) ||
923 isa<CXXNoexceptExpr>(Expr) ||
924 isa<CXXPseudoDestructorExpr>(Expr) ||
925 isa<CXXScalarValueInitExpr>(Expr) ||
926 isa<CXXThisExpr>(Expr) ||
927 isa<CXXTypeidExpr>(Expr) ||
928 isa<CXXUnresolvedConstructExpr>(Expr) ||
929 isa<ObjCMessageExpr>(Expr) ||
930 isa<ObjCPropertyRefExpr>(Expr) ||
931 isa<ObjCProtocolExpr>(Expr) ||
932 isa<MemberExpr>(Expr) ||
Argyrios Kyrtzidis94442982012-05-22 00:47:53 +0000933 isa<ObjCIvarRefExpr>(Expr) ||
Argyrios Kyrtzidisc1dfed62012-05-14 22:01:53 +0000934 isa<ParenExpr>(FullExpr) ||
935 isa<ParenListExpr>(Expr) ||
936 isa<SizeOfPackExpr>(Expr) ||
937 isa<UnaryOperator>(Expr))
938 return false;
939
940 return true;
941}
942
943static void objectifyExpr(const Expr *E, Commit &commit) {
944 if (!E) return;
945
946 QualType T = E->getType();
947 if (T->isObjCObjectPointerType()) {
948 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
949 if (ICE->getCastKind() != CK_CPointerToObjCPointerCast)
950 return;
951 } else {
952 return;
953 }
954 } else if (!T->isPointerType()) {
955 return;
956 }
957
958 SourceRange Range = E->getSourceRange();
959 if (castOperatorNeedsParens(E))
960 commit.insertWrap("(", Range, ")");
961 commit.insertBefore(Range.getBegin(), "(id)");
962}
Argyrios Kyrtzidis491e4ae2012-05-15 19:17:49 +0000963
964//===----------------------------------------------------------------------===//
965// rewriteToNumericBoxedExpression.
966//===----------------------------------------------------------------------===//
967
Argyrios Kyrtzidiscebe7222012-05-15 22:59:54 +0000968static bool isEnumConstant(const Expr *E) {
969 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
970 if (const ValueDecl *VD = DRE->getDecl())
971 return isa<EnumConstantDecl>(VD);
972
973 return false;
974}
975
Argyrios Kyrtzidis491e4ae2012-05-15 19:17:49 +0000976static bool rewriteToNumericBoxedExpression(const ObjCMessageExpr *Msg,
977 const NSAPI &NS, Commit &commit) {
978 if (Msg->getNumArgs() != 1)
979 return false;
980
981 const Expr *Arg = Msg->getArg(0);
982 if (Arg->isTypeDependent())
983 return false;
984
985 ASTContext &Ctx = NS.getASTContext();
986 Selector Sel = Msg->getSelector();
David Blaikie05785d12013-02-20 22:23:23 +0000987 Optional<NSAPI::NSNumberLiteralMethodKind>
Argyrios Kyrtzidis491e4ae2012-05-15 19:17:49 +0000988 MKOpt = NS.getNSNumberLiteralMethodKind(Sel);
989 if (!MKOpt)
990 return false;
991 NSAPI::NSNumberLiteralMethodKind MK = *MKOpt;
992
993 const Expr *OrigArg = Arg->IgnoreImpCasts();
994 QualType FinalTy = Arg->getType();
995 QualType OrigTy = OrigArg->getType();
996 uint64_t FinalTySize = Ctx.getTypeSize(FinalTy);
997 uint64_t OrigTySize = Ctx.getTypeSize(OrigTy);
998
Fangrui Song6907ce22018-07-30 19:24:48 +0000999 bool isTruncated = FinalTySize < OrigTySize;
Argyrios Kyrtzidis491e4ae2012-05-15 19:17:49 +00001000 bool needsCast = false;
1001
1002 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
1003 switch (ICE->getCastKind()) {
1004 case CK_LValueToRValue:
1005 case CK_NoOp:
1006 case CK_UserDefinedConversion:
1007 break;
1008
1009 case CK_IntegralCast: {
1010 if (MK == NSAPI::NSNumberWithBool && OrigTy->isBooleanType())
1011 break;
1012 // Be more liberal with Integer/UnsignedInteger which are very commonly
1013 // used.
1014 if ((MK == NSAPI::NSNumberWithInteger ||
1015 MK == NSAPI::NSNumberWithUnsignedInteger) &&
1016 !isTruncated) {
Argyrios Kyrtzidiscebe7222012-05-15 22:59:54 +00001017 if (OrigTy->getAs<EnumType>() || isEnumConstant(OrigArg))
Argyrios Kyrtzidis491e4ae2012-05-15 19:17:49 +00001018 break;
1019 if ((MK==NSAPI::NSNumberWithInteger) == OrigTy->isSignedIntegerType() &&
1020 OrigTySize >= Ctx.getTypeSize(Ctx.IntTy))
1021 break;
1022 }
1023
1024 needsCast = true;
1025 break;
1026 }
1027
1028 case CK_PointerToBoolean:
1029 case CK_IntegralToBoolean:
1030 case CK_IntegralToFloating:
1031 case CK_FloatingToIntegral:
1032 case CK_FloatingToBoolean:
1033 case CK_FloatingCast:
1034 case CK_FloatingComplexToReal:
1035 case CK_FloatingComplexToBoolean:
1036 case CK_IntegralComplexToReal:
1037 case CK_IntegralComplexToBoolean:
1038 case CK_AtomicToNonAtomic:
David Tweede1468322013-12-11 13:39:46 +00001039 case CK_AddressSpaceConversion:
Argyrios Kyrtzidis491e4ae2012-05-15 19:17:49 +00001040 needsCast = true;
1041 break;
1042
1043 case CK_Dependent:
1044 case CK_BitCast:
1045 case CK_LValueBitCast:
1046 case CK_BaseToDerived:
1047 case CK_DerivedToBase:
1048 case CK_UncheckedDerivedToBase:
1049 case CK_Dynamic:
1050 case CK_ToUnion:
1051 case CK_ArrayToPointerDecay:
1052 case CK_FunctionToPointerDecay:
1053 case CK_NullToPointer:
1054 case CK_NullToMemberPointer:
1055 case CK_BaseToDerivedMemberPointer:
1056 case CK_DerivedToBaseMemberPointer:
1057 case CK_MemberPointerToBoolean:
1058 case CK_ReinterpretMemberPointer:
1059 case CK_ConstructorConversion:
1060 case CK_IntegralToPointer:
1061 case CK_PointerToIntegral:
1062 case CK_ToVoid:
1063 case CK_VectorSplat:
1064 case CK_CPointerToObjCPointerCast:
1065 case CK_BlockPointerToObjCPointerCast:
1066 case CK_AnyPointerToBlockPointerCast:
1067 case CK_ObjCObjectLValueCast:
1068 case CK_FloatingRealToComplex:
1069 case CK_FloatingComplexCast:
1070 case CK_FloatingComplexToIntegralComplex:
1071 case CK_IntegralRealToComplex:
1072 case CK_IntegralComplexCast:
1073 case CK_IntegralComplexToFloatingComplex:
1074 case CK_ARCProduceObject:
1075 case CK_ARCConsumeObject:
1076 case CK_ARCReclaimReturnedObject:
1077 case CK_ARCExtendBlockObject:
1078 case CK_NonAtomicToAtomic:
1079 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00001080 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001081 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00001082 case CK_ZeroToOCLQueue:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001083 case CK_IntToOCLSampler:
Argyrios Kyrtzidis491e4ae2012-05-15 19:17:49 +00001084 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00001085
1086 case CK_BooleanToSignedIntegral:
1087 llvm_unreachable("OpenCL-specific cast in Objective-C?");
Argyrios Kyrtzidis491e4ae2012-05-15 19:17:49 +00001088 }
1089 }
1090
Argyrios Kyrtzidisb4822602012-05-24 16:48:23 +00001091 if (needsCast) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001092 DiagnosticsEngine &Diags = Ctx.getDiagnostics();
Argyrios Kyrtzidisb4822602012-05-24 16:48:23 +00001093 // FIXME: Use a custom category name to distinguish migration diagnostics.
1094 unsigned diagID = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Argyrios Kyrtzidis927a4372012-06-20 01:28:32 +00001095 "converting to boxing syntax requires casting %0 to %1");
1096 Diags.Report(Msg->getExprLoc(), diagID) << OrigTy << FinalTy
1097 << Msg->getSourceRange();
Argyrios Kyrtzidis491e4ae2012-05-15 19:17:49 +00001098 return false;
Argyrios Kyrtzidisb4822602012-05-24 16:48:23 +00001099 }
Argyrios Kyrtzidis491e4ae2012-05-15 19:17:49 +00001100
1101 SourceRange ArgRange = OrigArg->getSourceRange();
Argyrios Kyrtzidis7bd957c2012-05-15 22:22:10 +00001102 commit.replaceWithInner(Msg->getSourceRange(), ArgRange);
Argyrios Kyrtzidis491e4ae2012-05-15 19:17:49 +00001103
1104 if (isa<ParenExpr>(OrigArg) || isa<IntegerLiteral>(OrigArg))
1105 commit.insertBefore(ArgRange.getBegin(), "@");
1106 else
1107 commit.insertWrap("@(", ArgRange, ")");
1108
1109 return true;
1110}
Argyrios Kyrtzidis7bd957c2012-05-15 22:22:10 +00001111
1112//===----------------------------------------------------------------------===//
1113// rewriteToStringBoxedExpression.
1114//===----------------------------------------------------------------------===//
1115
1116static bool doRewriteToUTF8StringBoxedExpressionHelper(
1117 const ObjCMessageExpr *Msg,
1118 const NSAPI &NS, Commit &commit) {
1119 const Expr *Arg = Msg->getArg(0);
1120 if (Arg->isTypeDependent())
1121 return false;
1122
Argyrios Kyrtzidis81541472012-05-16 00:21:21 +00001123 ASTContext &Ctx = NS.getASTContext();
1124
Argyrios Kyrtzidis7bd957c2012-05-15 22:22:10 +00001125 const Expr *OrigArg = Arg->IgnoreImpCasts();
1126 QualType OrigTy = OrigArg->getType();
Argyrios Kyrtzidis81541472012-05-16 00:21:21 +00001127 if (OrigTy->isArrayType())
1128 OrigTy = Ctx.getArrayDecayedType(OrigTy);
Argyrios Kyrtzidis7bd957c2012-05-15 22:22:10 +00001129
1130 if (const StringLiteral *
1131 StrE = dyn_cast<StringLiteral>(OrigArg->IgnoreParens())) {
1132 commit.replaceWithInner(Msg->getSourceRange(), StrE->getSourceRange());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001133 commit.insert(StrE->getBeginLoc(), "@");
Argyrios Kyrtzidis7bd957c2012-05-15 22:22:10 +00001134 return true;
1135 }
1136
Argyrios Kyrtzidis7bd957c2012-05-15 22:22:10 +00001137 if (const PointerType *PT = OrigTy->getAs<PointerType>()) {
1138 QualType PointeeType = PT->getPointeeType();
1139 if (Ctx.hasSameUnqualifiedType(PointeeType, Ctx.CharTy)) {
1140 SourceRange ArgRange = OrigArg->getSourceRange();
1141 commit.replaceWithInner(Msg->getSourceRange(), ArgRange);
1142
1143 if (isa<ParenExpr>(OrigArg) || isa<IntegerLiteral>(OrigArg))
1144 commit.insertBefore(ArgRange.getBegin(), "@");
1145 else
1146 commit.insertWrap("@(", ArgRange, ")");
Fangrui Song6907ce22018-07-30 19:24:48 +00001147
Argyrios Kyrtzidis7bd957c2012-05-15 22:22:10 +00001148 return true;
1149 }
1150 }
1151
1152 return false;
1153}
1154
1155static bool rewriteToStringBoxedExpression(const ObjCMessageExpr *Msg,
1156 const NSAPI &NS, Commit &commit) {
1157 Selector Sel = Msg->getSelector();
1158
1159 if (Sel == NS.getNSStringSelector(NSAPI::NSStr_stringWithUTF8String) ||
Fariborz Jahanianbe7bf722014-08-25 20:22:25 +00001160 Sel == NS.getNSStringSelector(NSAPI::NSStr_stringWithCString) ||
1161 Sel == NS.getNSStringSelector(NSAPI::NSStr_initWithUTF8String)) {
Argyrios Kyrtzidis7bd957c2012-05-15 22:22:10 +00001162 if (Msg->getNumArgs() != 1)
1163 return false;
1164 return doRewriteToUTF8StringBoxedExpressionHelper(Msg, NS, commit);
1165 }
1166
1167 if (Sel == NS.getNSStringSelector(NSAPI::NSStr_stringWithCStringEncoding)) {
1168 if (Msg->getNumArgs() != 2)
1169 return false;
1170
1171 const Expr *encodingArg = Msg->getArg(1);
1172 if (NS.isNSUTF8StringEncodingConstant(encodingArg) ||
1173 NS.isNSASCIIStringEncodingConstant(encodingArg))
1174 return doRewriteToUTF8StringBoxedExpressionHelper(Msg, NS, commit);
1175 }
1176
1177 return false;
1178}