1 //===--- 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"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ExprCXX.h"
17 #include "clang/AST/ExprObjC.h"
18 #include "clang/AST/NSAPI.h"
19 #include "clang/AST/ParentMap.h"
20 #include "clang/Edit/Commit.h"
21 #include "clang/Lex/Lexer.h"
22 
23 using namespace clang;
24 using namespace edit;
25 
26 static bool checkForLiteralCreation(const ObjCMessageExpr *Msg,
27                                     IdentifierInfo *&ClassId,
28                                     const LangOptions &LangOpts) {
29   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 
40   // 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 
52   return false;
53 }
54 
55 //===----------------------------------------------------------------------===//
56 // rewriteObjCRedundantCallWithLiteral.
57 //===----------------------------------------------------------------------===//
58 
59 bool edit::rewriteObjCRedundantCallWithLiteral(const ObjCMessageExpr *Msg,
60                                               const NSAPI &NS, Commit &commit) {
61   IdentifierInfo *II = 0;
62   if (!checkForLiteralCreation(Msg, II, NS.getASTContext().getLangOpts()))
63     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 &&
72        (NS.getNSStringSelector(NSAPI::NSStr_stringWithString) == Sel ||
73         NS.getNSStringSelector(NSAPI::NSStr_initWithString) == Sel))   ||
74 
75       (isa<ObjCArrayLiteral>(Arg) &&
76        NS.getNSClassId(NSAPI::ClassId_NSArray) == II &&
77        (NS.getNSArraySelector(NSAPI::NSArr_arrayWithArray) == Sel ||
78         NS.getNSArraySelector(NSAPI::NSArr_initWithArray) == Sel))     ||
79 
80       (isa<ObjCDictionaryLiteral>(Arg) &&
81        NS.getNSClassId(NSAPI::ClassId_NSDictionary) == II &&
82        (NS.getNSDictionarySelector(
83                               NSAPI::NSDict_dictionaryWithDictionary) == Sel ||
84         NS.getNSDictionarySelector(NSAPI::NSDict_initWithDictionary) == Sel))) {
85 
86     commit.replaceWithInner(Msg->getSourceRange(),
87                            Msg->getArg(0)->getSourceRange());
88     return true;
89   }
90 
91   return false;
92 }
93 
94 //===----------------------------------------------------------------------===//
95 // rewriteToObjCSubscriptSyntax.
96 //===----------------------------------------------------------------------===//
97 
98 /// \brief Check for classes that accept 'objectForKey:' (or the other selectors
99 /// 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'.
108 static const ObjCInterfaceDecl *
109 maybeAdjustInterfaceForSubscriptingCheck(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 
156 static bool canRewriteToSubscriptSyntax(const ObjCInterfaceDecl *&IFace,
157                                         const ObjCMessageExpr *Msg,
158                                         ASTContext &Ctx,
159                                         Selector subscriptSel) {
160   const Expr *Rec = Msg->getInstanceReceiver();
161   if (!Rec)
162     return false;
163   IFace = maybeAdjustInterfaceForSubscriptingCheck(IFace, Rec, Ctx);
164 
165   if (const ObjCMethodDecl *MD = IFace->lookupInstanceMethod(subscriptSel)) {
166     if (!MD->isUnavailable())
167       return true;
168   }
169   return false;
170 }
171 
172 static bool subscriptOperatorNeedsParens(const Expr *FullExpr);
173 
174 static void maybePutParensOnReceiver(const Expr *Receiver, Commit &commit) {
175   if (subscriptOperatorNeedsParens(Receiver)) {
176     SourceRange RecRange = Receiver->getSourceRange();
177     commit.insertWrap("(", RecRange, ")");
178   }
179 }
180 
181 static bool rewriteToSubscriptGetCommon(const ObjCMessageExpr *Msg,
182                                         Commit &commit) {
183   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 
203 static bool rewriteToArraySubscriptGet(const ObjCInterfaceDecl *IFace,
204                                        const ObjCMessageExpr *Msg,
205                                        const NSAPI &NS,
206                                        Commit &commit) {
207   if (!canRewriteToSubscriptSyntax(IFace, Msg, NS.getASTContext(),
208                                    NS.getObjectAtIndexedSubscriptSelector()))
209     return false;
210   return rewriteToSubscriptGetCommon(Msg, commit);
211 }
212 
213 static bool rewriteToDictionarySubscriptGet(const ObjCInterfaceDecl *IFace,
214                                             const ObjCMessageExpr *Msg,
215                                             const NSAPI &NS,
216                                             Commit &commit) {
217   if (!canRewriteToSubscriptSyntax(IFace, Msg, NS.getASTContext(),
218                                   NS.getObjectForKeyedSubscriptSelector()))
219     return false;
220   return rewriteToSubscriptGetCommon(Msg, commit);
221 }
222 
223 static bool rewriteToArraySubscriptSet(const ObjCInterfaceDecl *IFace,
224                                        const ObjCMessageExpr *Msg,
225                                        const NSAPI &NS,
226                                        Commit &commit) {
227   if (!canRewriteToSubscriptSyntax(IFace, Msg, NS.getASTContext(),
228                                    NS.getSetObjectAtIndexedSubscriptSelector()))
229     return false;
230 
231   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 
257 static bool rewriteToDictionarySubscriptSet(const ObjCInterfaceDecl *IFace,
258                                             const ObjCMessageExpr *Msg,
259                                             const NSAPI &NS,
260                                             Commit &commit) {
261   if (!canRewriteToSubscriptSyntax(IFace, Msg, NS.getASTContext(),
262                                    NS.getSetObjectForKeyedSubscriptSelector()))
263     return false;
264 
265   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 
290 bool edit::rewriteToObjCSubscriptSyntax(const ObjCMessageExpr *Msg,
291                                         const NSAPI &NS, Commit &commit) {
292   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 
299   const ObjCInterfaceDecl *IFace =
300       NS.getASTContext().getObjContainingInterface(Method);
301   if (!IFace)
302     return false;
303   Selector Sel = Msg->getSelector();
304 
305   if (Sel == NS.getNSArraySelector(NSAPI::NSArr_objectAtIndex))
306     return rewriteToArraySubscriptGet(IFace, Msg, NS, commit);
307 
308   if (Sel == NS.getNSDictionarySelector(NSAPI::NSDict_objectForKey))
309     return rewriteToDictionarySubscriptGet(IFace, Msg, NS, commit);
310 
311   if (Msg->getNumArgs() != 2)
312     return false;
313 
314   if (Sel == NS.getNSArraySelector(NSAPI::NSMutableArr_replaceObjectAtIndex))
315     return rewriteToArraySubscriptSet(IFace, Msg, NS, commit);
316 
317   if (Sel == NS.getNSDictionarySelector(NSAPI::NSMutableDict_setObjectForKey))
318     return rewriteToDictionarySubscriptSet(IFace, Msg, NS, commit);
319 
320   return false;
321 }
322 
323 //===----------------------------------------------------------------------===//
324 // rewriteToObjCLiteralSyntax.
325 //===----------------------------------------------------------------------===//
326 
327 static bool rewriteToArrayLiteral(const ObjCMessageExpr *Msg,
328                                   const NSAPI &NS, Commit &commit,
329                                   const ParentMap *PMap);
330 static bool rewriteToDictionaryLiteral(const ObjCMessageExpr *Msg,
331                                   const NSAPI &NS, Commit &commit);
332 static bool rewriteToNumberLiteral(const ObjCMessageExpr *Msg,
333                                   const NSAPI &NS, Commit &commit);
334 static bool rewriteToNumericBoxedExpression(const ObjCMessageExpr *Msg,
335                                             const NSAPI &NS, Commit &commit);
336 static bool rewriteToStringBoxedExpression(const ObjCMessageExpr *Msg,
337                                            const NSAPI &NS, Commit &commit);
338 
339 bool edit::rewriteToObjCLiteralSyntax(const ObjCMessageExpr *Msg,
340                                       const NSAPI &NS, Commit &commit,
341                                       const ParentMap *PMap) {
342   IdentifierInfo *II = 0;
343   if (!checkForLiteralCreation(Msg, II, NS.getASTContext().getLangOpts()))
344     return false;
345 
346   if (II == NS.getNSClassId(NSAPI::ClassId_NSArray))
347     return rewriteToArrayLiteral(Msg, NS, commit, PMap);
348   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);
352   if (II == NS.getNSClassId(NSAPI::ClassId_NSString))
353     return rewriteToStringBoxedExpression(Msg, NS, commit);
354 
355   return false;
356 }
357 
358 bool edit::rewriteToObjCProperty(const ObjCMethodDecl *Getter,
359                                  const ObjCMethodDecl *Setter,
360                                  const NSAPI &NS, Commit &commit) {
361   ASTContext &Context = NS.getASTContext();
362   std::string PropertyString = "@property";
363   const ParmVarDecl *argDecl = *Setter->param_begin();
364   QualType ArgType = Context.getCanonicalType(argDecl->getType());
365   Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
366 
367   if (ArgType->isObjCRetainableType() &&
368       propertyLifetime == Qualifiers::OCL_Strong) {
369     if (const ObjCObjectPointerType *ObjPtrTy =
370           ArgType->getAs<ObjCObjectPointerType>()) {
371       ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
372       if (IDecl &&
373           IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
374         PropertyString += "(copy)";
375     }
376   }
377   else if (propertyLifetime == Qualifiers::OCL_Weak)
378     // TODO. More precise determination of 'weak' attribute requires
379     // looking into setter's implementation for backing weak ivar.
380     PropertyString += "(weak)";
381   else
382     PropertyString += "(unsafe_unretained)";
383 
384   // strip off any ARC lifetime qualifier.
385   QualType CanResultTy = Context.getCanonicalType(Getter->getResultType());
386   if (CanResultTy.getQualifiers().hasObjCLifetime()) {
387     Qualifiers Qs = CanResultTy.getQualifiers();
388     Qs.removeObjCLifetime();
389     CanResultTy = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
390   }
391   PropertyString += " ";
392   PropertyString += CanResultTy.getAsString(Context.getPrintingPolicy());
393   PropertyString += " ";
394   PropertyString += Getter->getNameAsString();
395   commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(),
396                                                Getter->getDeclaratorEndLoc()),
397                  PropertyString);
398   SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
399   // Get location past ';'
400   EndLoc = EndLoc.getLocWithOffset(1);
401   commit.remove(CharSourceRange::getCharRange(Setter->getLocStart(), EndLoc));
402   return true;
403 }
404 
405 /// \brief Returns true if the immediate message arguments of \c Msg should not
406 /// be rewritten because it will interfere with the rewrite of the parent
407 /// message expression. e.g.
408 /// \code
409 ///   [NSDictionary dictionaryWithObjects:
410 ///                                 [NSArray arrayWithObjects:@"1", @"2", nil]
411 ///                         forKeys:[NSArray arrayWithObjects:@"A", @"B", nil]];
412 /// \endcode
413 /// It will return true for this because we are going to rewrite this directly
414 /// to a dictionary literal without any array literals.
415 static bool shouldNotRewriteImmediateMessageArgs(const ObjCMessageExpr *Msg,
416                                                  const NSAPI &NS);
417 
418 //===----------------------------------------------------------------------===//
419 // rewriteToArrayLiteral.
420 //===----------------------------------------------------------------------===//
421 
422 /// \brief Adds an explicit cast to 'id' if the type is not objc object.
423 static void objectifyExpr(const Expr *E, Commit &commit);
424 
425 static bool rewriteToArrayLiteral(const ObjCMessageExpr *Msg,
426                                   const NSAPI &NS, Commit &commit,
427                                   const ParentMap *PMap) {
428   if (PMap) {
429     const ObjCMessageExpr *ParentMsg =
430         dyn_cast_or_null<ObjCMessageExpr>(PMap->getParentIgnoreParenCasts(Msg));
431     if (shouldNotRewriteImmediateMessageArgs(ParentMsg, NS))
432       return false;
433   }
434 
435   Selector Sel = Msg->getSelector();
436   SourceRange MsgRange = Msg->getSourceRange();
437 
438   if (Sel == NS.getNSArraySelector(NSAPI::NSArr_array)) {
439     if (Msg->getNumArgs() != 0)
440       return false;
441     commit.replace(MsgRange, "@[]");
442     return true;
443   }
444 
445   if (Sel == NS.getNSArraySelector(NSAPI::NSArr_arrayWithObject)) {
446     if (Msg->getNumArgs() != 1)
447       return false;
448     objectifyExpr(Msg->getArg(0), commit);
449     SourceRange ArgRange = Msg->getArg(0)->getSourceRange();
450     commit.replaceWithInner(MsgRange, ArgRange);
451     commit.insertWrap("@[", ArgRange, "]");
452     return true;
453   }
454 
455   if (Sel == NS.getNSArraySelector(NSAPI::NSArr_arrayWithObjects) ||
456       Sel == NS.getNSArraySelector(NSAPI::NSArr_initWithObjects)) {
457     if (Msg->getNumArgs() == 0)
458       return false;
459     const Expr *SentinelExpr = Msg->getArg(Msg->getNumArgs() - 1);
460     if (!NS.getASTContext().isSentinelNullExpr(SentinelExpr))
461       return false;
462 
463     for (unsigned i = 0, e = Msg->getNumArgs() - 1; i != e; ++i)
464       objectifyExpr(Msg->getArg(i), commit);
465 
466     if (Msg->getNumArgs() == 1) {
467       commit.replace(MsgRange, "@[]");
468       return true;
469     }
470     SourceRange ArgRange(Msg->getArg(0)->getLocStart(),
471                          Msg->getArg(Msg->getNumArgs()-2)->getLocEnd());
472     commit.replaceWithInner(MsgRange, ArgRange);
473     commit.insertWrap("@[", ArgRange, "]");
474     return true;
475   }
476 
477   return false;
478 }
479 
480 //===----------------------------------------------------------------------===//
481 // rewriteToDictionaryLiteral.
482 //===----------------------------------------------------------------------===//
483 
484 /// \brief If \c Msg is an NSArray creation message or literal, this gets the
485 /// objects that were used to create it.
486 /// \returns true if it is an NSArray and we got objects, or false otherwise.
487 static bool getNSArrayObjects(const Expr *E, const NSAPI &NS,
488                               SmallVectorImpl<const Expr *> &Objs) {
489   if (!E)
490     return false;
491 
492   E = E->IgnoreParenCasts();
493   if (!E)
494     return false;
495 
496   if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
497     IdentifierInfo *Cls = 0;
498     if (!checkForLiteralCreation(Msg, Cls, NS.getASTContext().getLangOpts()))
499       return false;
500 
501     if (Cls != NS.getNSClassId(NSAPI::ClassId_NSArray))
502       return false;
503 
504     Selector Sel = Msg->getSelector();
505     if (Sel == NS.getNSArraySelector(NSAPI::NSArr_array))
506       return true; // empty array.
507 
508     if (Sel == NS.getNSArraySelector(NSAPI::NSArr_arrayWithObject)) {
509       if (Msg->getNumArgs() != 1)
510         return false;
511       Objs.push_back(Msg->getArg(0));
512       return true;
513     }
514 
515     if (Sel == NS.getNSArraySelector(NSAPI::NSArr_arrayWithObjects) ||
516         Sel == NS.getNSArraySelector(NSAPI::NSArr_initWithObjects)) {
517       if (Msg->getNumArgs() == 0)
518         return false;
519       const Expr *SentinelExpr = Msg->getArg(Msg->getNumArgs() - 1);
520       if (!NS.getASTContext().isSentinelNullExpr(SentinelExpr))
521         return false;
522 
523       for (unsigned i = 0, e = Msg->getNumArgs() - 1; i != e; ++i)
524         Objs.push_back(Msg->getArg(i));
525       return true;
526     }
527 
528   } else if (const ObjCArrayLiteral *ArrLit = dyn_cast<ObjCArrayLiteral>(E)) {
529     for (unsigned i = 0, e = ArrLit->getNumElements(); i != e; ++i)
530       Objs.push_back(ArrLit->getElement(i));
531     return true;
532   }
533 
534   return false;
535 }
536 
537 static bool rewriteToDictionaryLiteral(const ObjCMessageExpr *Msg,
538                                        const NSAPI &NS, Commit &commit) {
539   Selector Sel = Msg->getSelector();
540   SourceRange MsgRange = Msg->getSourceRange();
541 
542   if (Sel == NS.getNSDictionarySelector(NSAPI::NSDict_dictionary)) {
543     if (Msg->getNumArgs() != 0)
544       return false;
545     commit.replace(MsgRange, "@{}");
546     return true;
547   }
548 
549   if (Sel == NS.getNSDictionarySelector(
550                                     NSAPI::NSDict_dictionaryWithObjectForKey)) {
551     if (Msg->getNumArgs() != 2)
552       return false;
553 
554     objectifyExpr(Msg->getArg(0), commit);
555     objectifyExpr(Msg->getArg(1), commit);
556 
557     SourceRange ValRange = Msg->getArg(0)->getSourceRange();
558     SourceRange KeyRange = Msg->getArg(1)->getSourceRange();
559     // Insert key before the value.
560     commit.insertBefore(ValRange.getBegin(), ": ");
561     commit.insertFromRange(ValRange.getBegin(),
562                            CharSourceRange::getTokenRange(KeyRange),
563                        /*afterToken=*/false, /*beforePreviousInsertions=*/true);
564     commit.insertBefore(ValRange.getBegin(), "@{");
565     commit.insertAfterToken(ValRange.getEnd(), "}");
566     commit.replaceWithInner(MsgRange, ValRange);
567     return true;
568   }
569 
570   if (Sel == NS.getNSDictionarySelector(
571                                   NSAPI::NSDict_dictionaryWithObjectsAndKeys) ||
572       Sel == NS.getNSDictionarySelector(NSAPI::NSDict_initWithObjectsAndKeys)) {
573     if (Msg->getNumArgs() % 2 != 1)
574       return false;
575     unsigned SentinelIdx = Msg->getNumArgs() - 1;
576     const Expr *SentinelExpr = Msg->getArg(SentinelIdx);
577     if (!NS.getASTContext().isSentinelNullExpr(SentinelExpr))
578       return false;
579 
580     if (Msg->getNumArgs() == 1) {
581       commit.replace(MsgRange, "@{}");
582       return true;
583     }
584 
585     for (unsigned i = 0; i < SentinelIdx; i += 2) {
586       objectifyExpr(Msg->getArg(i), commit);
587       objectifyExpr(Msg->getArg(i+1), commit);
588 
589       SourceRange ValRange = Msg->getArg(i)->getSourceRange();
590       SourceRange KeyRange = Msg->getArg(i+1)->getSourceRange();
591       // Insert value after key.
592       commit.insertAfterToken(KeyRange.getEnd(), ": ");
593       commit.insertFromRange(KeyRange.getEnd(), ValRange, /*afterToken=*/true);
594       commit.remove(CharSourceRange::getCharRange(ValRange.getBegin(),
595                                                   KeyRange.getBegin()));
596     }
597     // Range of arguments up until and including the last key.
598     // The sentinel and first value are cut off, the value will move after the
599     // key.
600     SourceRange ArgRange(Msg->getArg(1)->getLocStart(),
601                          Msg->getArg(SentinelIdx-1)->getLocEnd());
602     commit.insertWrap("@{", ArgRange, "}");
603     commit.replaceWithInner(MsgRange, ArgRange);
604     return true;
605   }
606 
607   if (Sel == NS.getNSDictionarySelector(
608                                   NSAPI::NSDict_dictionaryWithObjectsForKeys) ||
609       Sel == NS.getNSDictionarySelector(NSAPI::NSDict_initWithObjectsForKeys)) {
610     if (Msg->getNumArgs() != 2)
611       return false;
612 
613     SmallVector<const Expr *, 8> Vals;
614     if (!getNSArrayObjects(Msg->getArg(0), NS, Vals))
615       return false;
616 
617     SmallVector<const Expr *, 8> Keys;
618     if (!getNSArrayObjects(Msg->getArg(1), NS, Keys))
619       return false;
620 
621     if (Vals.size() != Keys.size())
622       return false;
623 
624     if (Vals.empty()) {
625       commit.replace(MsgRange, "@{}");
626       return true;
627     }
628 
629     for (unsigned i = 0, n = Vals.size(); i < n; ++i) {
630       objectifyExpr(Vals[i], commit);
631       objectifyExpr(Keys[i], commit);
632 
633       SourceRange ValRange = Vals[i]->getSourceRange();
634       SourceRange KeyRange = Keys[i]->getSourceRange();
635       // Insert value after key.
636       commit.insertAfterToken(KeyRange.getEnd(), ": ");
637       commit.insertFromRange(KeyRange.getEnd(), ValRange, /*afterToken=*/true);
638     }
639     // Range of arguments up until and including the last key.
640     // The first value is cut off, the value will move after the key.
641     SourceRange ArgRange(Keys.front()->getLocStart(),
642                          Keys.back()->getLocEnd());
643     commit.insertWrap("@{", ArgRange, "}");
644     commit.replaceWithInner(MsgRange, ArgRange);
645     return true;
646   }
647 
648   return false;
649 }
650 
651 static bool shouldNotRewriteImmediateMessageArgs(const ObjCMessageExpr *Msg,
652                                                  const NSAPI &NS) {
653   if (!Msg)
654     return false;
655 
656   IdentifierInfo *II = 0;
657   if (!checkForLiteralCreation(Msg, II, NS.getASTContext().getLangOpts()))
658     return false;
659 
660   if (II != NS.getNSClassId(NSAPI::ClassId_NSDictionary))
661     return false;
662 
663   Selector Sel = Msg->getSelector();
664   if (Sel == NS.getNSDictionarySelector(
665                                   NSAPI::NSDict_dictionaryWithObjectsForKeys) ||
666       Sel == NS.getNSDictionarySelector(NSAPI::NSDict_initWithObjectsForKeys)) {
667     if (Msg->getNumArgs() != 2)
668       return false;
669 
670     SmallVector<const Expr *, 8> Vals;
671     if (!getNSArrayObjects(Msg->getArg(0), NS, Vals))
672       return false;
673 
674     SmallVector<const Expr *, 8> Keys;
675     if (!getNSArrayObjects(Msg->getArg(1), NS, Keys))
676       return false;
677 
678     if (Vals.size() != Keys.size())
679       return false;
680 
681     return true;
682   }
683 
684   return false;
685 }
686 
687 //===----------------------------------------------------------------------===//
688 // rewriteToNumberLiteral.
689 //===----------------------------------------------------------------------===//
690 
691 static bool rewriteToCharLiteral(const ObjCMessageExpr *Msg,
692                                    const CharacterLiteral *Arg,
693                                    const NSAPI &NS, Commit &commit) {
694   if (Arg->getKind() != CharacterLiteral::Ascii)
695     return false;
696   if (NS.isNSNumberLiteralSelector(NSAPI::NSNumberWithChar,
697                                    Msg->getSelector())) {
698     SourceRange ArgRange = Arg->getSourceRange();
699     commit.replaceWithInner(Msg->getSourceRange(), ArgRange);
700     commit.insert(ArgRange.getBegin(), "@");
701     return true;
702   }
703 
704   return rewriteToNumericBoxedExpression(Msg, NS, commit);
705 }
706 
707 static bool rewriteToBoolLiteral(const ObjCMessageExpr *Msg,
708                                    const Expr *Arg,
709                                    const NSAPI &NS, Commit &commit) {
710   if (NS.isNSNumberLiteralSelector(NSAPI::NSNumberWithBool,
711                                    Msg->getSelector())) {
712     SourceRange ArgRange = Arg->getSourceRange();
713     commit.replaceWithInner(Msg->getSourceRange(), ArgRange);
714     commit.insert(ArgRange.getBegin(), "@");
715     return true;
716   }
717 
718   return rewriteToNumericBoxedExpression(Msg, NS, commit);
719 }
720 
721 namespace {
722 
723 struct LiteralInfo {
724   bool Hex, Octal;
725   StringRef U, F, L, LL;
726   CharSourceRange WithoutSuffRange;
727 };
728 
729 }
730 
731 static bool getLiteralInfo(SourceRange literalRange,
732                            bool isFloat, bool isIntZero,
733                           ASTContext &Ctx, LiteralInfo &Info) {
734   if (literalRange.getBegin().isMacroID() ||
735       literalRange.getEnd().isMacroID())
736     return false;
737   StringRef text = Lexer::getSourceText(
738                                   CharSourceRange::getTokenRange(literalRange),
739                                   Ctx.getSourceManager(), Ctx.getLangOpts());
740   if (text.empty())
741     return false;
742 
743   Optional<bool> UpperU, UpperL;
744   bool UpperF = false;
745 
746   struct Suff {
747     static bool has(StringRef suff, StringRef &text) {
748       if (text.endswith(suff)) {
749         text = text.substr(0, text.size()-suff.size());
750         return true;
751       }
752       return false;
753     }
754   };
755 
756   while (1) {
757     if (Suff::has("u", text)) {
758       UpperU = false;
759     } else if (Suff::has("U", text)) {
760       UpperU = true;
761     } else if (Suff::has("ll", text)) {
762       UpperL = false;
763     } else if (Suff::has("LL", text)) {
764       UpperL = true;
765     } else if (Suff::has("l", text)) {
766       UpperL = false;
767     } else if (Suff::has("L", text)) {
768       UpperL = true;
769     } else if (isFloat && Suff::has("f", text)) {
770       UpperF = false;
771     } else if (isFloat && Suff::has("F", text)) {
772       UpperF = true;
773     } else
774       break;
775   }
776 
777   if (!UpperU.hasValue() && !UpperL.hasValue())
778     UpperU = UpperL = true;
779   else if (UpperU.hasValue() && !UpperL.hasValue())
780     UpperL = UpperU;
781   else if (UpperL.hasValue() && !UpperU.hasValue())
782     UpperU = UpperL;
783 
784   Info.U = *UpperU ? "U" : "u";
785   Info.L = *UpperL ? "L" : "l";
786   Info.LL = *UpperL ? "LL" : "ll";
787   Info.F = UpperF ? "F" : "f";
788 
789   Info.Hex = Info.Octal = false;
790   if (text.startswith("0x"))
791     Info.Hex = true;
792   else if (!isFloat && !isIntZero && text.startswith("0"))
793     Info.Octal = true;
794 
795   SourceLocation B = literalRange.getBegin();
796   Info.WithoutSuffRange =
797       CharSourceRange::getCharRange(B, B.getLocWithOffset(text.size()));
798   return true;
799 }
800 
801 static bool rewriteToNumberLiteral(const ObjCMessageExpr *Msg,
802                                    const NSAPI &NS, Commit &commit) {
803   if (Msg->getNumArgs() != 1)
804     return false;
805 
806   const Expr *Arg = Msg->getArg(0)->IgnoreParenImpCasts();
807   if (const CharacterLiteral *CharE = dyn_cast<CharacterLiteral>(Arg))
808     return rewriteToCharLiteral(Msg, CharE, NS, commit);
809   if (const ObjCBoolLiteralExpr *BE = dyn_cast<ObjCBoolLiteralExpr>(Arg))
810     return rewriteToBoolLiteral(Msg, BE, NS, commit);
811   if (const CXXBoolLiteralExpr *BE = dyn_cast<CXXBoolLiteralExpr>(Arg))
812     return rewriteToBoolLiteral(Msg, BE, NS, commit);
813 
814   const Expr *literalE = Arg;
815   if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(literalE)) {
816     if (UOE->getOpcode() == UO_Plus || UOE->getOpcode() == UO_Minus)
817       literalE = UOE->getSubExpr();
818   }
819 
820   // Only integer and floating literals, otherwise try to rewrite to boxed
821   // expression.
822   if (!isa<IntegerLiteral>(literalE) && !isa<FloatingLiteral>(literalE))
823     return rewriteToNumericBoxedExpression(Msg, NS, commit);
824 
825   ASTContext &Ctx = NS.getASTContext();
826   Selector Sel = Msg->getSelector();
827   Optional<NSAPI::NSNumberLiteralMethodKind>
828     MKOpt = NS.getNSNumberLiteralMethodKind(Sel);
829   if (!MKOpt)
830     return false;
831   NSAPI::NSNumberLiteralMethodKind MK = *MKOpt;
832 
833   bool CallIsUnsigned = false, CallIsLong = false, CallIsLongLong = false;
834   bool CallIsFloating = false, CallIsDouble = false;
835 
836   switch (MK) {
837   // We cannot have these calls with int/float literals.
838   case NSAPI::NSNumberWithChar:
839   case NSAPI::NSNumberWithUnsignedChar:
840   case NSAPI::NSNumberWithShort:
841   case NSAPI::NSNumberWithUnsignedShort:
842   case NSAPI::NSNumberWithBool:
843     return rewriteToNumericBoxedExpression(Msg, NS, commit);
844 
845   case NSAPI::NSNumberWithUnsignedInt:
846   case NSAPI::NSNumberWithUnsignedInteger:
847     CallIsUnsigned = true;
848   case NSAPI::NSNumberWithInt:
849   case NSAPI::NSNumberWithInteger:
850     break;
851 
852   case NSAPI::NSNumberWithUnsignedLong:
853     CallIsUnsigned = true;
854   case NSAPI::NSNumberWithLong:
855     CallIsLong = true;
856     break;
857 
858   case NSAPI::NSNumberWithUnsignedLongLong:
859     CallIsUnsigned = true;
860   case NSAPI::NSNumberWithLongLong:
861     CallIsLongLong = true;
862     break;
863 
864   case NSAPI::NSNumberWithDouble:
865     CallIsDouble = true;
866   case NSAPI::NSNumberWithFloat:
867     CallIsFloating = true;
868     break;
869   }
870 
871   SourceRange ArgRange = Arg->getSourceRange();
872   QualType ArgTy = Arg->getType();
873   QualType CallTy = Msg->getArg(0)->getType();
874 
875   // Check for the easy case, the literal maps directly to the call.
876   if (Ctx.hasSameType(ArgTy, CallTy)) {
877     commit.replaceWithInner(Msg->getSourceRange(), ArgRange);
878     commit.insert(ArgRange.getBegin(), "@");
879     return true;
880   }
881 
882   // We will need to modify the literal suffix to get the same type as the call.
883   // Try with boxed expression if it came from a macro.
884   if (ArgRange.getBegin().isMacroID())
885     return rewriteToNumericBoxedExpression(Msg, NS, commit);
886 
887   bool LitIsFloat = ArgTy->isFloatingType();
888   // For a float passed to integer call, don't try rewriting to objc literal.
889   // It is difficult and a very uncommon case anyway.
890   // But try with boxed expression.
891   if (LitIsFloat && !CallIsFloating)
892     return rewriteToNumericBoxedExpression(Msg, NS, commit);
893 
894   // Try to modify the literal make it the same type as the method call.
895   // -Modify the suffix, and/or
896   // -Change integer to float
897 
898   LiteralInfo LitInfo;
899   bool isIntZero = false;
900   if (const IntegerLiteral *IntE = dyn_cast<IntegerLiteral>(literalE))
901     isIntZero = !IntE->getValue().getBoolValue();
902   if (!getLiteralInfo(ArgRange, LitIsFloat, isIntZero, Ctx, LitInfo))
903     return rewriteToNumericBoxedExpression(Msg, NS, commit);
904 
905   // Not easy to do int -> float with hex/octal and uncommon anyway.
906   if (!LitIsFloat && CallIsFloating && (LitInfo.Hex || LitInfo.Octal))
907     return rewriteToNumericBoxedExpression(Msg, NS, commit);
908 
909   SourceLocation LitB = LitInfo.WithoutSuffRange.getBegin();
910   SourceLocation LitE = LitInfo.WithoutSuffRange.getEnd();
911 
912   commit.replaceWithInner(CharSourceRange::getTokenRange(Msg->getSourceRange()),
913                          LitInfo.WithoutSuffRange);
914   commit.insert(LitB, "@");
915 
916   if (!LitIsFloat && CallIsFloating)
917     commit.insert(LitE, ".0");
918 
919   if (CallIsFloating) {
920     if (!CallIsDouble)
921       commit.insert(LitE, LitInfo.F);
922   } else {
923     if (CallIsUnsigned)
924       commit.insert(LitE, LitInfo.U);
925 
926     if (CallIsLong)
927       commit.insert(LitE, LitInfo.L);
928     else if (CallIsLongLong)
929       commit.insert(LitE, LitInfo.LL);
930   }
931   return true;
932 }
933 
934 // FIXME: Make determination of operator precedence more general and
935 // make it broadly available.
936 static bool subscriptOperatorNeedsParens(const Expr *FullExpr) {
937   const Expr* Expr = FullExpr->IgnoreImpCasts();
938   if (isa<ArraySubscriptExpr>(Expr) ||
939       isa<CallExpr>(Expr) ||
940       isa<DeclRefExpr>(Expr) ||
941       isa<CXXNamedCastExpr>(Expr) ||
942       isa<CXXConstructExpr>(Expr) ||
943       isa<CXXThisExpr>(Expr) ||
944       isa<CXXTypeidExpr>(Expr) ||
945       isa<CXXUnresolvedConstructExpr>(Expr) ||
946       isa<ObjCMessageExpr>(Expr) ||
947       isa<ObjCPropertyRefExpr>(Expr) ||
948       isa<ObjCProtocolExpr>(Expr) ||
949       isa<MemberExpr>(Expr) ||
950       isa<ObjCIvarRefExpr>(Expr) ||
951       isa<ParenExpr>(FullExpr) ||
952       isa<ParenListExpr>(Expr) ||
953       isa<SizeOfPackExpr>(Expr))
954     return false;
955 
956   return true;
957 }
958 static bool castOperatorNeedsParens(const Expr *FullExpr) {
959   const Expr* Expr = FullExpr->IgnoreImpCasts();
960   if (isa<ArraySubscriptExpr>(Expr) ||
961       isa<CallExpr>(Expr) ||
962       isa<DeclRefExpr>(Expr) ||
963       isa<CastExpr>(Expr) ||
964       isa<CXXNewExpr>(Expr) ||
965       isa<CXXConstructExpr>(Expr) ||
966       isa<CXXDeleteExpr>(Expr) ||
967       isa<CXXNoexceptExpr>(Expr) ||
968       isa<CXXPseudoDestructorExpr>(Expr) ||
969       isa<CXXScalarValueInitExpr>(Expr) ||
970       isa<CXXThisExpr>(Expr) ||
971       isa<CXXTypeidExpr>(Expr) ||
972       isa<CXXUnresolvedConstructExpr>(Expr) ||
973       isa<ObjCMessageExpr>(Expr) ||
974       isa<ObjCPropertyRefExpr>(Expr) ||
975       isa<ObjCProtocolExpr>(Expr) ||
976       isa<MemberExpr>(Expr) ||
977       isa<ObjCIvarRefExpr>(Expr) ||
978       isa<ParenExpr>(FullExpr) ||
979       isa<ParenListExpr>(Expr) ||
980       isa<SizeOfPackExpr>(Expr) ||
981       isa<UnaryOperator>(Expr))
982     return false;
983 
984   return true;
985 }
986 
987 static void objectifyExpr(const Expr *E, Commit &commit) {
988   if (!E) return;
989 
990   QualType T = E->getType();
991   if (T->isObjCObjectPointerType()) {
992     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
993       if (ICE->getCastKind() != CK_CPointerToObjCPointerCast)
994         return;
995     } else {
996       return;
997     }
998   } else if (!T->isPointerType()) {
999     return;
1000   }
1001 
1002   SourceRange Range = E->getSourceRange();
1003   if (castOperatorNeedsParens(E))
1004     commit.insertWrap("(", Range, ")");
1005   commit.insertBefore(Range.getBegin(), "(id)");
1006 }
1007 
1008 //===----------------------------------------------------------------------===//
1009 // rewriteToNumericBoxedExpression.
1010 //===----------------------------------------------------------------------===//
1011 
1012 static bool isEnumConstant(const Expr *E) {
1013   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
1014     if (const ValueDecl *VD = DRE->getDecl())
1015       return isa<EnumConstantDecl>(VD);
1016 
1017   return false;
1018 }
1019 
1020 static bool rewriteToNumericBoxedExpression(const ObjCMessageExpr *Msg,
1021                                             const NSAPI &NS, Commit &commit) {
1022   if (Msg->getNumArgs() != 1)
1023     return false;
1024 
1025   const Expr *Arg = Msg->getArg(0);
1026   if (Arg->isTypeDependent())
1027     return false;
1028 
1029   ASTContext &Ctx = NS.getASTContext();
1030   Selector Sel = Msg->getSelector();
1031   Optional<NSAPI::NSNumberLiteralMethodKind>
1032     MKOpt = NS.getNSNumberLiteralMethodKind(Sel);
1033   if (!MKOpt)
1034     return false;
1035   NSAPI::NSNumberLiteralMethodKind MK = *MKOpt;
1036 
1037   const Expr *OrigArg = Arg->IgnoreImpCasts();
1038   QualType FinalTy = Arg->getType();
1039   QualType OrigTy = OrigArg->getType();
1040   uint64_t FinalTySize = Ctx.getTypeSize(FinalTy);
1041   uint64_t OrigTySize = Ctx.getTypeSize(OrigTy);
1042 
1043   bool isTruncated = FinalTySize < OrigTySize;
1044   bool needsCast = false;
1045 
1046   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
1047     switch (ICE->getCastKind()) {
1048     case CK_LValueToRValue:
1049     case CK_NoOp:
1050     case CK_UserDefinedConversion:
1051       break;
1052 
1053     case CK_IntegralCast: {
1054       if (MK == NSAPI::NSNumberWithBool && OrigTy->isBooleanType())
1055         break;
1056       // Be more liberal with Integer/UnsignedInteger which are very commonly
1057       // used.
1058       if ((MK == NSAPI::NSNumberWithInteger ||
1059            MK == NSAPI::NSNumberWithUnsignedInteger) &&
1060           !isTruncated) {
1061         if (OrigTy->getAs<EnumType>() || isEnumConstant(OrigArg))
1062           break;
1063         if ((MK==NSAPI::NSNumberWithInteger) == OrigTy->isSignedIntegerType() &&
1064             OrigTySize >= Ctx.getTypeSize(Ctx.IntTy))
1065           break;
1066       }
1067 
1068       needsCast = true;
1069       break;
1070     }
1071 
1072     case CK_PointerToBoolean:
1073     case CK_IntegralToBoolean:
1074     case CK_IntegralToFloating:
1075     case CK_FloatingToIntegral:
1076     case CK_FloatingToBoolean:
1077     case CK_FloatingCast:
1078     case CK_FloatingComplexToReal:
1079     case CK_FloatingComplexToBoolean:
1080     case CK_IntegralComplexToReal:
1081     case CK_IntegralComplexToBoolean:
1082     case CK_AtomicToNonAtomic:
1083       needsCast = true;
1084       break;
1085 
1086     case CK_Dependent:
1087     case CK_BitCast:
1088     case CK_LValueBitCast:
1089     case CK_BaseToDerived:
1090     case CK_DerivedToBase:
1091     case CK_UncheckedDerivedToBase:
1092     case CK_Dynamic:
1093     case CK_ToUnion:
1094     case CK_ArrayToPointerDecay:
1095     case CK_FunctionToPointerDecay:
1096     case CK_NullToPointer:
1097     case CK_NullToMemberPointer:
1098     case CK_BaseToDerivedMemberPointer:
1099     case CK_DerivedToBaseMemberPointer:
1100     case CK_MemberPointerToBoolean:
1101     case CK_ReinterpretMemberPointer:
1102     case CK_ConstructorConversion:
1103     case CK_IntegralToPointer:
1104     case CK_PointerToIntegral:
1105     case CK_ToVoid:
1106     case CK_VectorSplat:
1107     case CK_CPointerToObjCPointerCast:
1108     case CK_BlockPointerToObjCPointerCast:
1109     case CK_AnyPointerToBlockPointerCast:
1110     case CK_ObjCObjectLValueCast:
1111     case CK_FloatingRealToComplex:
1112     case CK_FloatingComplexCast:
1113     case CK_FloatingComplexToIntegralComplex:
1114     case CK_IntegralRealToComplex:
1115     case CK_IntegralComplexCast:
1116     case CK_IntegralComplexToFloatingComplex:
1117     case CK_ARCProduceObject:
1118     case CK_ARCConsumeObject:
1119     case CK_ARCReclaimReturnedObject:
1120     case CK_ARCExtendBlockObject:
1121     case CK_NonAtomicToAtomic:
1122     case CK_CopyAndAutoreleaseBlockObject:
1123     case CK_BuiltinFnToFnPtr:
1124     case CK_ZeroToOCLEvent:
1125       return false;
1126     }
1127   }
1128 
1129   if (needsCast) {
1130     DiagnosticsEngine &Diags = Ctx.getDiagnostics();
1131     // FIXME: Use a custom category name to distinguish migration diagnostics.
1132     unsigned diagID = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
1133                        "converting to boxing syntax requires casting %0 to %1");
1134     Diags.Report(Msg->getExprLoc(), diagID) << OrigTy << FinalTy
1135         << Msg->getSourceRange();
1136     return false;
1137   }
1138 
1139   SourceRange ArgRange = OrigArg->getSourceRange();
1140   commit.replaceWithInner(Msg->getSourceRange(), ArgRange);
1141 
1142   if (isa<ParenExpr>(OrigArg) || isa<IntegerLiteral>(OrigArg))
1143     commit.insertBefore(ArgRange.getBegin(), "@");
1144   else
1145     commit.insertWrap("@(", ArgRange, ")");
1146 
1147   return true;
1148 }
1149 
1150 //===----------------------------------------------------------------------===//
1151 // rewriteToStringBoxedExpression.
1152 //===----------------------------------------------------------------------===//
1153 
1154 static bool doRewriteToUTF8StringBoxedExpressionHelper(
1155                                               const ObjCMessageExpr *Msg,
1156                                               const NSAPI &NS, Commit &commit) {
1157   const Expr *Arg = Msg->getArg(0);
1158   if (Arg->isTypeDependent())
1159     return false;
1160 
1161   ASTContext &Ctx = NS.getASTContext();
1162 
1163   const Expr *OrigArg = Arg->IgnoreImpCasts();
1164   QualType OrigTy = OrigArg->getType();
1165   if (OrigTy->isArrayType())
1166     OrigTy = Ctx.getArrayDecayedType(OrigTy);
1167 
1168   if (const StringLiteral *
1169         StrE = dyn_cast<StringLiteral>(OrigArg->IgnoreParens())) {
1170     commit.replaceWithInner(Msg->getSourceRange(), StrE->getSourceRange());
1171     commit.insert(StrE->getLocStart(), "@");
1172     return true;
1173   }
1174 
1175   if (const PointerType *PT = OrigTy->getAs<PointerType>()) {
1176     QualType PointeeType = PT->getPointeeType();
1177     if (Ctx.hasSameUnqualifiedType(PointeeType, Ctx.CharTy)) {
1178       SourceRange ArgRange = OrigArg->getSourceRange();
1179       commit.replaceWithInner(Msg->getSourceRange(), ArgRange);
1180 
1181       if (isa<ParenExpr>(OrigArg) || isa<IntegerLiteral>(OrigArg))
1182         commit.insertBefore(ArgRange.getBegin(), "@");
1183       else
1184         commit.insertWrap("@(", ArgRange, ")");
1185 
1186       return true;
1187     }
1188   }
1189 
1190   return false;
1191 }
1192 
1193 static bool rewriteToStringBoxedExpression(const ObjCMessageExpr *Msg,
1194                                            const NSAPI &NS, Commit &commit) {
1195   Selector Sel = Msg->getSelector();
1196 
1197   if (Sel == NS.getNSStringSelector(NSAPI::NSStr_stringWithUTF8String) ||
1198       Sel == NS.getNSStringSelector(NSAPI::NSStr_stringWithCString)) {
1199     if (Msg->getNumArgs() != 1)
1200       return false;
1201     return doRewriteToUTF8StringBoxedExpressionHelper(Msg, NS, commit);
1202   }
1203 
1204   if (Sel == NS.getNSStringSelector(NSAPI::NSStr_stringWithCStringEncoding)) {
1205     if (Msg->getNumArgs() != 2)
1206       return false;
1207 
1208     const Expr *encodingArg = Msg->getArg(1);
1209     if (NS.isNSUTF8StringEncodingConstant(encodingArg) ||
1210         NS.isNSASCIIStringEncodingConstant(encodingArg))
1211       return doRewriteToUTF8StringBoxedExpressionHelper(Msg, NS, commit);
1212   }
1213 
1214   return false;
1215 }
1216