clang  6.0.0svn
LocalizationChecker.cpp
Go to the documentation of this file.
1 //=- LocalizationChecker.cpp -------------------------------------*- C++ -*-==//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a set of checks for localizability including:
11 // 1) A checker that warns about uses of non-localized NSStrings passed to
12 // UI methods expecting localized strings
13 // 2) A syntactic checker that warns against the bad practice of
14 // not including a comment in NSLocalizedString macros.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "ClangSACheckers.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/StmtVisitor.h"
24 #include "clang/Lex/Lexer.h"
32 #include "llvm/Support/Unicode.h"
33 
34 using namespace clang;
35 using namespace ento;
36 
37 namespace {
38 struct LocalizedState {
39 private:
40  enum Kind { NonLocalized, Localized } K;
41  LocalizedState(Kind InK) : K(InK) {}
42 
43 public:
44  bool isLocalized() const { return K == Localized; }
45  bool isNonLocalized() const { return K == NonLocalized; }
46 
47  static LocalizedState getLocalized() { return LocalizedState(Localized); }
48  static LocalizedState getNonLocalized() {
49  return LocalizedState(NonLocalized);
50  }
51 
52  // Overload the == operator
53  bool operator==(const LocalizedState &X) const { return K == X.K; }
54 
55  // LLVMs equivalent of a hash function
56  void Profile(llvm::FoldingSetNodeID &ID) const { ID.AddInteger(K); }
57 };
58 
59 class NonLocalizedStringChecker
60  : public Checker<check::PreCall, check::PostCall, check::PreObjCMessage,
61  check::PostObjCMessage,
62  check::PostStmt<ObjCStringLiteral>> {
63 
64  mutable std::unique_ptr<BugType> BT;
65 
66  // Methods that require a localized string
67  mutable llvm::DenseMap<const IdentifierInfo *,
68  llvm::DenseMap<Selector, uint8_t>> UIMethods;
69  // Methods that return a localized string
70  mutable llvm::SmallSet<std::pair<const IdentifierInfo *, Selector>, 12> LSM;
71  // C Functions that return a localized string
72  mutable llvm::SmallSet<const IdentifierInfo *, 5> LSF;
73 
74  void initUIMethods(ASTContext &Ctx) const;
75  void initLocStringsMethods(ASTContext &Ctx) const;
76 
77  bool hasNonLocalizedState(SVal S, CheckerContext &C) const;
78  bool hasLocalizedState(SVal S, CheckerContext &C) const;
79  void setNonLocalizedState(SVal S, CheckerContext &C) const;
80  void setLocalizedState(SVal S, CheckerContext &C) const;
81 
82  bool isAnnotatedAsReturningLocalized(const Decl *D) const;
83  bool isAnnotatedAsTakingLocalized(const Decl *D) const;
84  void reportLocalizationError(SVal S, const CallEvent &M, CheckerContext &C,
85  int argumentNumber = 0) const;
86 
87  int getLocalizedArgumentForSelector(const IdentifierInfo *Receiver,
88  Selector S) const;
89 
90 public:
91  NonLocalizedStringChecker();
92 
93  // When this parameter is set to true, the checker assumes all
94  // methods that return NSStrings are unlocalized. Thus, more false
95  // positives will be reported.
96  DefaultBool IsAggressive;
97 
98  void checkPreObjCMessage(const ObjCMethodCall &msg, CheckerContext &C) const;
99  void checkPostObjCMessage(const ObjCMethodCall &msg, CheckerContext &C) const;
100  void checkPostStmt(const ObjCStringLiteral *SL, CheckerContext &C) const;
101  void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
102  void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
103 };
104 
105 } // end anonymous namespace
106 
107 REGISTER_MAP_WITH_PROGRAMSTATE(LocalizedMemMap, const MemRegion *,
108  LocalizedState)
109 
110 NonLocalizedStringChecker::NonLocalizedStringChecker() {
111  BT.reset(new BugType(this, "Unlocalizable string",
112  "Localizability Issue (Apple)"));
113 }
114 
115 namespace {
116 class NonLocalizedStringBRVisitor final
117  : public BugReporterVisitorImpl<NonLocalizedStringBRVisitor> {
118 
119  const MemRegion *NonLocalizedString;
120  bool Satisfied;
121 
122 public:
123  NonLocalizedStringBRVisitor(const MemRegion *NonLocalizedString)
124  : NonLocalizedString(NonLocalizedString), Satisfied(false) {
125  assert(NonLocalizedString);
126  }
127 
128  std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *Succ,
129  const ExplodedNode *Pred,
130  BugReporterContext &BRC,
131  BugReport &BR) override;
132 
133  void Profile(llvm::FoldingSetNodeID &ID) const override {
134  ID.Add(NonLocalizedString);
135  }
136 };
137 } // End anonymous namespace.
138 
139 #define NEW_RECEIVER(receiver) \
140  llvm::DenseMap<Selector, uint8_t> &receiver##M = \
141  UIMethods.insert({&Ctx.Idents.get(#receiver), \
142  llvm::DenseMap<Selector, uint8_t>()}) \
143  .first->second;
144 #define ADD_NULLARY_METHOD(receiver, method, argument) \
145  receiver##M.insert( \
146  {Ctx.Selectors.getNullarySelector(&Ctx.Idents.get(#method)), argument});
147 #define ADD_UNARY_METHOD(receiver, method, argument) \
148  receiver##M.insert( \
149  {Ctx.Selectors.getUnarySelector(&Ctx.Idents.get(#method)), argument});
150 #define ADD_METHOD(receiver, method_list, count, argument) \
151  receiver##M.insert({Ctx.Selectors.getSelector(count, method_list), argument});
152 
153 /// Initializes a list of methods that require a localized string
154 /// Format: {"ClassName", {{"selectorName:", LocStringArg#}, ...}, ...}
155 void NonLocalizedStringChecker::initUIMethods(ASTContext &Ctx) const {
156  if (!UIMethods.empty())
157  return;
158 
159  // UI Methods
160  NEW_RECEIVER(UISearchDisplayController)
161  ADD_UNARY_METHOD(UISearchDisplayController, setSearchResultsTitle, 0)
162 
163  NEW_RECEIVER(UITabBarItem)
164  IdentifierInfo *initWithTitleUITabBarItemTag[] = {
165  &Ctx.Idents.get("initWithTitle"), &Ctx.Idents.get("image"),
166  &Ctx.Idents.get("tag")};
167  ADD_METHOD(UITabBarItem, initWithTitleUITabBarItemTag, 3, 0)
168  IdentifierInfo *initWithTitleUITabBarItemImage[] = {
169  &Ctx.Idents.get("initWithTitle"), &Ctx.Idents.get("image"),
170  &Ctx.Idents.get("selectedImage")};
171  ADD_METHOD(UITabBarItem, initWithTitleUITabBarItemImage, 3, 0)
172 
173  NEW_RECEIVER(NSDockTile)
174  ADD_UNARY_METHOD(NSDockTile, setBadgeLabel, 0)
175 
176  NEW_RECEIVER(NSStatusItem)
177  ADD_UNARY_METHOD(NSStatusItem, setTitle, 0)
178  ADD_UNARY_METHOD(NSStatusItem, setToolTip, 0)
179 
180  NEW_RECEIVER(UITableViewRowAction)
181  IdentifierInfo *rowActionWithStyleUITableViewRowAction[] = {
182  &Ctx.Idents.get("rowActionWithStyle"), &Ctx.Idents.get("title"),
183  &Ctx.Idents.get("handler")};
184  ADD_METHOD(UITableViewRowAction, rowActionWithStyleUITableViewRowAction, 3, 1)
185  ADD_UNARY_METHOD(UITableViewRowAction, setTitle, 0)
186 
187  NEW_RECEIVER(NSBox)
188  ADD_UNARY_METHOD(NSBox, setTitle, 0)
189 
190  NEW_RECEIVER(NSButton)
191  ADD_UNARY_METHOD(NSButton, setTitle, 0)
192  ADD_UNARY_METHOD(NSButton, setAlternateTitle, 0)
193  IdentifierInfo *radioButtonWithTitleNSButton[] = {
194  &Ctx.Idents.get("radioButtonWithTitle"), &Ctx.Idents.get("target"),
195  &Ctx.Idents.get("action")};
196  ADD_METHOD(NSButton, radioButtonWithTitleNSButton, 3, 0)
197  IdentifierInfo *buttonWithTitleNSButtonImage[] = {
198  &Ctx.Idents.get("buttonWithTitle"), &Ctx.Idents.get("image"),
199  &Ctx.Idents.get("target"), &Ctx.Idents.get("action")};
200  ADD_METHOD(NSButton, buttonWithTitleNSButtonImage, 4, 0)
201  IdentifierInfo *checkboxWithTitleNSButton[] = {
202  &Ctx.Idents.get("checkboxWithTitle"), &Ctx.Idents.get("target"),
203  &Ctx.Idents.get("action")};
204  ADD_METHOD(NSButton, checkboxWithTitleNSButton, 3, 0)
205  IdentifierInfo *buttonWithTitleNSButtonTarget[] = {
206  &Ctx.Idents.get("buttonWithTitle"), &Ctx.Idents.get("target"),
207  &Ctx.Idents.get("action")};
208  ADD_METHOD(NSButton, buttonWithTitleNSButtonTarget, 3, 0)
209 
210  NEW_RECEIVER(NSSavePanel)
211  ADD_UNARY_METHOD(NSSavePanel, setPrompt, 0)
212  ADD_UNARY_METHOD(NSSavePanel, setTitle, 0)
213  ADD_UNARY_METHOD(NSSavePanel, setNameFieldLabel, 0)
214  ADD_UNARY_METHOD(NSSavePanel, setNameFieldStringValue, 0)
215  ADD_UNARY_METHOD(NSSavePanel, setMessage, 0)
216 
217  NEW_RECEIVER(UIPrintInfo)
218  ADD_UNARY_METHOD(UIPrintInfo, setJobName, 0)
219 
220  NEW_RECEIVER(NSTabViewItem)
221  ADD_UNARY_METHOD(NSTabViewItem, setLabel, 0)
222  ADD_UNARY_METHOD(NSTabViewItem, setToolTip, 0)
223 
224  NEW_RECEIVER(NSBrowser)
225  IdentifierInfo *setTitleNSBrowser[] = {&Ctx.Idents.get("setTitle"),
226  &Ctx.Idents.get("ofColumn")};
227  ADD_METHOD(NSBrowser, setTitleNSBrowser, 2, 0)
228 
229  NEW_RECEIVER(UIAccessibilityElement)
230  ADD_UNARY_METHOD(UIAccessibilityElement, setAccessibilityLabel, 0)
231  ADD_UNARY_METHOD(UIAccessibilityElement, setAccessibilityHint, 0)
232  ADD_UNARY_METHOD(UIAccessibilityElement, setAccessibilityValue, 0)
233 
234  NEW_RECEIVER(UIAlertAction)
235  IdentifierInfo *actionWithTitleUIAlertAction[] = {
236  &Ctx.Idents.get("actionWithTitle"), &Ctx.Idents.get("style"),
237  &Ctx.Idents.get("handler")};
238  ADD_METHOD(UIAlertAction, actionWithTitleUIAlertAction, 3, 0)
239 
240  NEW_RECEIVER(NSPopUpButton)
241  ADD_UNARY_METHOD(NSPopUpButton, addItemWithTitle, 0)
242  IdentifierInfo *insertItemWithTitleNSPopUpButton[] = {
243  &Ctx.Idents.get("insertItemWithTitle"), &Ctx.Idents.get("atIndex")};
244  ADD_METHOD(NSPopUpButton, insertItemWithTitleNSPopUpButton, 2, 0)
245  ADD_UNARY_METHOD(NSPopUpButton, removeItemWithTitle, 0)
246  ADD_UNARY_METHOD(NSPopUpButton, selectItemWithTitle, 0)
247  ADD_UNARY_METHOD(NSPopUpButton, setTitle, 0)
248 
249  NEW_RECEIVER(NSTableViewRowAction)
250  IdentifierInfo *rowActionWithStyleNSTableViewRowAction[] = {
251  &Ctx.Idents.get("rowActionWithStyle"), &Ctx.Idents.get("title"),
252  &Ctx.Idents.get("handler")};
253  ADD_METHOD(NSTableViewRowAction, rowActionWithStyleNSTableViewRowAction, 3, 1)
254  ADD_UNARY_METHOD(NSTableViewRowAction, setTitle, 0)
255 
256  NEW_RECEIVER(NSImage)
257  ADD_UNARY_METHOD(NSImage, setAccessibilityDescription, 0)
258 
259  NEW_RECEIVER(NSUserActivity)
260  ADD_UNARY_METHOD(NSUserActivity, setTitle, 0)
261 
262  NEW_RECEIVER(NSPathControlItem)
263  ADD_UNARY_METHOD(NSPathControlItem, setTitle, 0)
264 
265  NEW_RECEIVER(NSCell)
266  ADD_UNARY_METHOD(NSCell, initTextCell, 0)
267  ADD_UNARY_METHOD(NSCell, setTitle, 0)
268  ADD_UNARY_METHOD(NSCell, setStringValue, 0)
269 
270  NEW_RECEIVER(NSPathControl)
271  ADD_UNARY_METHOD(NSPathControl, setPlaceholderString, 0)
272 
273  NEW_RECEIVER(UIAccessibility)
274  ADD_UNARY_METHOD(UIAccessibility, setAccessibilityLabel, 0)
275  ADD_UNARY_METHOD(UIAccessibility, setAccessibilityHint, 0)
276  ADD_UNARY_METHOD(UIAccessibility, setAccessibilityValue, 0)
277 
278  NEW_RECEIVER(NSTableColumn)
279  ADD_UNARY_METHOD(NSTableColumn, setTitle, 0)
280  ADD_UNARY_METHOD(NSTableColumn, setHeaderToolTip, 0)
281 
282  NEW_RECEIVER(NSSegmentedControl)
283  IdentifierInfo *setLabelNSSegmentedControl[] = {
284  &Ctx.Idents.get("setLabel"), &Ctx.Idents.get("forSegment")};
285  ADD_METHOD(NSSegmentedControl, setLabelNSSegmentedControl, 2, 0)
286  IdentifierInfo *setToolTipNSSegmentedControl[] = {
287  &Ctx.Idents.get("setToolTip"), &Ctx.Idents.get("forSegment")};
288  ADD_METHOD(NSSegmentedControl, setToolTipNSSegmentedControl, 2, 0)
289 
290  NEW_RECEIVER(NSButtonCell)
291  ADD_UNARY_METHOD(NSButtonCell, setTitle, 0)
292  ADD_UNARY_METHOD(NSButtonCell, setAlternateTitle, 0)
293 
294  NEW_RECEIVER(NSDatePickerCell)
295  ADD_UNARY_METHOD(NSDatePickerCell, initTextCell, 0)
296 
297  NEW_RECEIVER(NSSliderCell)
298  ADD_UNARY_METHOD(NSSliderCell, setTitle, 0)
299 
300  NEW_RECEIVER(NSControl)
301  ADD_UNARY_METHOD(NSControl, setStringValue, 0)
302 
303  NEW_RECEIVER(NSAccessibility)
304  ADD_UNARY_METHOD(NSAccessibility, setAccessibilityValueDescription, 0)
305  ADD_UNARY_METHOD(NSAccessibility, setAccessibilityLabel, 0)
306  ADD_UNARY_METHOD(NSAccessibility, setAccessibilityTitle, 0)
307  ADD_UNARY_METHOD(NSAccessibility, setAccessibilityPlaceholderValue, 0)
308  ADD_UNARY_METHOD(NSAccessibility, setAccessibilityHelp, 0)
309 
310  NEW_RECEIVER(NSMatrix)
311  IdentifierInfo *setToolTipNSMatrix[] = {&Ctx.Idents.get("setToolTip"),
312  &Ctx.Idents.get("forCell")};
313  ADD_METHOD(NSMatrix, setToolTipNSMatrix, 2, 0)
314 
315  NEW_RECEIVER(NSPrintPanel)
316  ADD_UNARY_METHOD(NSPrintPanel, setDefaultButtonTitle, 0)
317 
318  NEW_RECEIVER(UILocalNotification)
319  ADD_UNARY_METHOD(UILocalNotification, setAlertBody, 0)
320  ADD_UNARY_METHOD(UILocalNotification, setAlertAction, 0)
321  ADD_UNARY_METHOD(UILocalNotification, setAlertTitle, 0)
322 
323  NEW_RECEIVER(NSSlider)
324  ADD_UNARY_METHOD(NSSlider, setTitle, 0)
325 
326  NEW_RECEIVER(UIMenuItem)
327  IdentifierInfo *initWithTitleUIMenuItem[] = {&Ctx.Idents.get("initWithTitle"),
328  &Ctx.Idents.get("action")};
329  ADD_METHOD(UIMenuItem, initWithTitleUIMenuItem, 2, 0)
330  ADD_UNARY_METHOD(UIMenuItem, setTitle, 0)
331 
332  NEW_RECEIVER(UIAlertController)
333  IdentifierInfo *alertControllerWithTitleUIAlertController[] = {
334  &Ctx.Idents.get("alertControllerWithTitle"), &Ctx.Idents.get("message"),
335  &Ctx.Idents.get("preferredStyle")};
336  ADD_METHOD(UIAlertController, alertControllerWithTitleUIAlertController, 3, 1)
337  ADD_UNARY_METHOD(UIAlertController, setTitle, 0)
338  ADD_UNARY_METHOD(UIAlertController, setMessage, 0)
339 
340  NEW_RECEIVER(UIApplicationShortcutItem)
341  IdentifierInfo *initWithTypeUIApplicationShortcutItemIcon[] = {
342  &Ctx.Idents.get("initWithType"), &Ctx.Idents.get("localizedTitle"),
343  &Ctx.Idents.get("localizedSubtitle"), &Ctx.Idents.get("icon"),
344  &Ctx.Idents.get("userInfo")};
345  ADD_METHOD(UIApplicationShortcutItem,
346  initWithTypeUIApplicationShortcutItemIcon, 5, 1)
347  IdentifierInfo *initWithTypeUIApplicationShortcutItem[] = {
348  &Ctx.Idents.get("initWithType"), &Ctx.Idents.get("localizedTitle")};
349  ADD_METHOD(UIApplicationShortcutItem, initWithTypeUIApplicationShortcutItem,
350  2, 1)
351 
352  NEW_RECEIVER(UIActionSheet)
353  IdentifierInfo *initWithTitleUIActionSheet[] = {
354  &Ctx.Idents.get("initWithTitle"), &Ctx.Idents.get("delegate"),
355  &Ctx.Idents.get("cancelButtonTitle"),
356  &Ctx.Idents.get("destructiveButtonTitle"),
357  &Ctx.Idents.get("otherButtonTitles")};
358  ADD_METHOD(UIActionSheet, initWithTitleUIActionSheet, 5, 0)
359  ADD_UNARY_METHOD(UIActionSheet, addButtonWithTitle, 0)
360  ADD_UNARY_METHOD(UIActionSheet, setTitle, 0)
361 
362  NEW_RECEIVER(UIAccessibilityCustomAction)
363  IdentifierInfo *initWithNameUIAccessibilityCustomAction[] = {
364  &Ctx.Idents.get("initWithName"), &Ctx.Idents.get("target"),
365  &Ctx.Idents.get("selector")};
366  ADD_METHOD(UIAccessibilityCustomAction,
367  initWithNameUIAccessibilityCustomAction, 3, 0)
368  ADD_UNARY_METHOD(UIAccessibilityCustomAction, setName, 0)
369 
370  NEW_RECEIVER(UISearchBar)
371  ADD_UNARY_METHOD(UISearchBar, setText, 0)
372  ADD_UNARY_METHOD(UISearchBar, setPrompt, 0)
373  ADD_UNARY_METHOD(UISearchBar, setPlaceholder, 0)
374 
375  NEW_RECEIVER(UIBarItem)
376  ADD_UNARY_METHOD(UIBarItem, setTitle, 0)
377 
378  NEW_RECEIVER(UITextView)
379  ADD_UNARY_METHOD(UITextView, setText, 0)
380 
381  NEW_RECEIVER(NSView)
382  ADD_UNARY_METHOD(NSView, setToolTip, 0)
383 
384  NEW_RECEIVER(NSTextField)
385  ADD_UNARY_METHOD(NSTextField, setPlaceholderString, 0)
386  ADD_UNARY_METHOD(NSTextField, textFieldWithString, 0)
387  ADD_UNARY_METHOD(NSTextField, wrappingLabelWithString, 0)
388  ADD_UNARY_METHOD(NSTextField, labelWithString, 0)
389 
390  NEW_RECEIVER(NSAttributedString)
391  ADD_UNARY_METHOD(NSAttributedString, initWithString, 0)
392  IdentifierInfo *initWithStringNSAttributedString[] = {
393  &Ctx.Idents.get("initWithString"), &Ctx.Idents.get("attributes")};
394  ADD_METHOD(NSAttributedString, initWithStringNSAttributedString, 2, 0)
395 
396  NEW_RECEIVER(NSText)
397  ADD_UNARY_METHOD(NSText, setString, 0)
398 
399  NEW_RECEIVER(UIKeyCommand)
400  IdentifierInfo *keyCommandWithInputUIKeyCommand[] = {
401  &Ctx.Idents.get("keyCommandWithInput"), &Ctx.Idents.get("modifierFlags"),
402  &Ctx.Idents.get("action"), &Ctx.Idents.get("discoverabilityTitle")};
403  ADD_METHOD(UIKeyCommand, keyCommandWithInputUIKeyCommand, 4, 3)
404  ADD_UNARY_METHOD(UIKeyCommand, setDiscoverabilityTitle, 0)
405 
406  NEW_RECEIVER(UILabel)
407  ADD_UNARY_METHOD(UILabel, setText, 0)
408 
409  NEW_RECEIVER(NSAlert)
410  IdentifierInfo *alertWithMessageTextNSAlert[] = {
411  &Ctx.Idents.get("alertWithMessageText"), &Ctx.Idents.get("defaultButton"),
412  &Ctx.Idents.get("alternateButton"), &Ctx.Idents.get("otherButton"),
413  &Ctx.Idents.get("informativeTextWithFormat")};
414  ADD_METHOD(NSAlert, alertWithMessageTextNSAlert, 5, 0)
415  ADD_UNARY_METHOD(NSAlert, addButtonWithTitle, 0)
416  ADD_UNARY_METHOD(NSAlert, setMessageText, 0)
417  ADD_UNARY_METHOD(NSAlert, setInformativeText, 0)
418  ADD_UNARY_METHOD(NSAlert, setHelpAnchor, 0)
419 
420  NEW_RECEIVER(UIMutableApplicationShortcutItem)
421  ADD_UNARY_METHOD(UIMutableApplicationShortcutItem, setLocalizedTitle, 0)
422  ADD_UNARY_METHOD(UIMutableApplicationShortcutItem, setLocalizedSubtitle, 0)
423 
424  NEW_RECEIVER(UIButton)
425  IdentifierInfo *setTitleUIButton[] = {&Ctx.Idents.get("setTitle"),
426  &Ctx.Idents.get("forState")};
427  ADD_METHOD(UIButton, setTitleUIButton, 2, 0)
428 
429  NEW_RECEIVER(NSWindow)
430  ADD_UNARY_METHOD(NSWindow, setTitle, 0)
431  IdentifierInfo *minFrameWidthWithTitleNSWindow[] = {
432  &Ctx.Idents.get("minFrameWidthWithTitle"), &Ctx.Idents.get("styleMask")};
433  ADD_METHOD(NSWindow, minFrameWidthWithTitleNSWindow, 2, 0)
434  ADD_UNARY_METHOD(NSWindow, setMiniwindowTitle, 0)
435 
436  NEW_RECEIVER(NSPathCell)
437  ADD_UNARY_METHOD(NSPathCell, setPlaceholderString, 0)
438 
439  NEW_RECEIVER(UIDocumentMenuViewController)
440  IdentifierInfo *addOptionWithTitleUIDocumentMenuViewController[] = {
441  &Ctx.Idents.get("addOptionWithTitle"), &Ctx.Idents.get("image"),
442  &Ctx.Idents.get("order"), &Ctx.Idents.get("handler")};
443  ADD_METHOD(UIDocumentMenuViewController,
444  addOptionWithTitleUIDocumentMenuViewController, 4, 0)
445 
446  NEW_RECEIVER(UINavigationItem)
447  ADD_UNARY_METHOD(UINavigationItem, initWithTitle, 0)
448  ADD_UNARY_METHOD(UINavigationItem, setTitle, 0)
449  ADD_UNARY_METHOD(UINavigationItem, setPrompt, 0)
450 
451  NEW_RECEIVER(UIAlertView)
452  IdentifierInfo *initWithTitleUIAlertView[] = {
453  &Ctx.Idents.get("initWithTitle"), &Ctx.Idents.get("message"),
454  &Ctx.Idents.get("delegate"), &Ctx.Idents.get("cancelButtonTitle"),
455  &Ctx.Idents.get("otherButtonTitles")};
456  ADD_METHOD(UIAlertView, initWithTitleUIAlertView, 5, 0)
457  ADD_UNARY_METHOD(UIAlertView, addButtonWithTitle, 0)
458  ADD_UNARY_METHOD(UIAlertView, setTitle, 0)
459  ADD_UNARY_METHOD(UIAlertView, setMessage, 0)
460 
461  NEW_RECEIVER(NSFormCell)
462  ADD_UNARY_METHOD(NSFormCell, initTextCell, 0)
463  ADD_UNARY_METHOD(NSFormCell, setTitle, 0)
464  ADD_UNARY_METHOD(NSFormCell, setPlaceholderString, 0)
465 
466  NEW_RECEIVER(NSUserNotification)
467  ADD_UNARY_METHOD(NSUserNotification, setTitle, 0)
468  ADD_UNARY_METHOD(NSUserNotification, setSubtitle, 0)
469  ADD_UNARY_METHOD(NSUserNotification, setInformativeText, 0)
470  ADD_UNARY_METHOD(NSUserNotification, setActionButtonTitle, 0)
471  ADD_UNARY_METHOD(NSUserNotification, setOtherButtonTitle, 0)
472  ADD_UNARY_METHOD(NSUserNotification, setResponsePlaceholder, 0)
473 
474  NEW_RECEIVER(NSToolbarItem)
475  ADD_UNARY_METHOD(NSToolbarItem, setLabel, 0)
476  ADD_UNARY_METHOD(NSToolbarItem, setPaletteLabel, 0)
477  ADD_UNARY_METHOD(NSToolbarItem, setToolTip, 0)
478 
479  NEW_RECEIVER(NSProgress)
480  ADD_UNARY_METHOD(NSProgress, setLocalizedDescription, 0)
481  ADD_UNARY_METHOD(NSProgress, setLocalizedAdditionalDescription, 0)
482 
483  NEW_RECEIVER(NSSegmentedCell)
484  IdentifierInfo *setLabelNSSegmentedCell[] = {&Ctx.Idents.get("setLabel"),
485  &Ctx.Idents.get("forSegment")};
486  ADD_METHOD(NSSegmentedCell, setLabelNSSegmentedCell, 2, 0)
487  IdentifierInfo *setToolTipNSSegmentedCell[] = {&Ctx.Idents.get("setToolTip"),
488  &Ctx.Idents.get("forSegment")};
489  ADD_METHOD(NSSegmentedCell, setToolTipNSSegmentedCell, 2, 0)
490 
491  NEW_RECEIVER(NSUndoManager)
492  ADD_UNARY_METHOD(NSUndoManager, setActionName, 0)
493  ADD_UNARY_METHOD(NSUndoManager, undoMenuTitleForUndoActionName, 0)
494  ADD_UNARY_METHOD(NSUndoManager, redoMenuTitleForUndoActionName, 0)
495 
496  NEW_RECEIVER(NSMenuItem)
497  IdentifierInfo *initWithTitleNSMenuItem[] = {
498  &Ctx.Idents.get("initWithTitle"), &Ctx.Idents.get("action"),
499  &Ctx.Idents.get("keyEquivalent")};
500  ADD_METHOD(NSMenuItem, initWithTitleNSMenuItem, 3, 0)
501  ADD_UNARY_METHOD(NSMenuItem, setTitle, 0)
502  ADD_UNARY_METHOD(NSMenuItem, setToolTip, 0)
503 
504  NEW_RECEIVER(NSPopUpButtonCell)
505  IdentifierInfo *initTextCellNSPopUpButtonCell[] = {
506  &Ctx.Idents.get("initTextCell"), &Ctx.Idents.get("pullsDown")};
507  ADD_METHOD(NSPopUpButtonCell, initTextCellNSPopUpButtonCell, 2, 0)
508  ADD_UNARY_METHOD(NSPopUpButtonCell, addItemWithTitle, 0)
509  IdentifierInfo *insertItemWithTitleNSPopUpButtonCell[] = {
510  &Ctx.Idents.get("insertItemWithTitle"), &Ctx.Idents.get("atIndex")};
511  ADD_METHOD(NSPopUpButtonCell, insertItemWithTitleNSPopUpButtonCell, 2, 0)
512  ADD_UNARY_METHOD(NSPopUpButtonCell, removeItemWithTitle, 0)
513  ADD_UNARY_METHOD(NSPopUpButtonCell, selectItemWithTitle, 0)
514  ADD_UNARY_METHOD(NSPopUpButtonCell, setTitle, 0)
515 
516  NEW_RECEIVER(NSViewController)
517  ADD_UNARY_METHOD(NSViewController, setTitle, 0)
518 
519  NEW_RECEIVER(NSMenu)
520  ADD_UNARY_METHOD(NSMenu, initWithTitle, 0)
521  IdentifierInfo *insertItemWithTitleNSMenu[] = {
522  &Ctx.Idents.get("insertItemWithTitle"), &Ctx.Idents.get("action"),
523  &Ctx.Idents.get("keyEquivalent"), &Ctx.Idents.get("atIndex")};
524  ADD_METHOD(NSMenu, insertItemWithTitleNSMenu, 4, 0)
525  IdentifierInfo *addItemWithTitleNSMenu[] = {
526  &Ctx.Idents.get("addItemWithTitle"), &Ctx.Idents.get("action"),
527  &Ctx.Idents.get("keyEquivalent")};
528  ADD_METHOD(NSMenu, addItemWithTitleNSMenu, 3, 0)
529  ADD_UNARY_METHOD(NSMenu, setTitle, 0)
530 
531  NEW_RECEIVER(UIMutableUserNotificationAction)
532  ADD_UNARY_METHOD(UIMutableUserNotificationAction, setTitle, 0)
533 
534  NEW_RECEIVER(NSForm)
535  ADD_UNARY_METHOD(NSForm, addEntry, 0)
536  IdentifierInfo *insertEntryNSForm[] = {&Ctx.Idents.get("insertEntry"),
537  &Ctx.Idents.get("atIndex")};
538  ADD_METHOD(NSForm, insertEntryNSForm, 2, 0)
539 
540  NEW_RECEIVER(NSTextFieldCell)
541  ADD_UNARY_METHOD(NSTextFieldCell, setPlaceholderString, 0)
542 
543  NEW_RECEIVER(NSUserNotificationAction)
544  IdentifierInfo *actionWithIdentifierNSUserNotificationAction[] = {
545  &Ctx.Idents.get("actionWithIdentifier"), &Ctx.Idents.get("title")};
546  ADD_METHOD(NSUserNotificationAction,
547  actionWithIdentifierNSUserNotificationAction, 2, 1)
548 
549  NEW_RECEIVER(UITextField)
550  ADD_UNARY_METHOD(UITextField, setText, 0)
551  ADD_UNARY_METHOD(UITextField, setPlaceholder, 0)
552 
553  NEW_RECEIVER(UIBarButtonItem)
554  IdentifierInfo *initWithTitleUIBarButtonItem[] = {
555  &Ctx.Idents.get("initWithTitle"), &Ctx.Idents.get("style"),
556  &Ctx.Idents.get("target"), &Ctx.Idents.get("action")};
557  ADD_METHOD(UIBarButtonItem, initWithTitleUIBarButtonItem, 4, 0)
558 
559  NEW_RECEIVER(UIViewController)
560  ADD_UNARY_METHOD(UIViewController, setTitle, 0)
561 
562  NEW_RECEIVER(UISegmentedControl)
563  IdentifierInfo *insertSegmentWithTitleUISegmentedControl[] = {
564  &Ctx.Idents.get("insertSegmentWithTitle"), &Ctx.Idents.get("atIndex"),
565  &Ctx.Idents.get("animated")};
566  ADD_METHOD(UISegmentedControl, insertSegmentWithTitleUISegmentedControl, 3, 0)
567  IdentifierInfo *setTitleUISegmentedControl[] = {
568  &Ctx.Idents.get("setTitle"), &Ctx.Idents.get("forSegmentAtIndex")};
569  ADD_METHOD(UISegmentedControl, setTitleUISegmentedControl, 2, 0)
570 
571  NEW_RECEIVER(NSAccessibilityCustomRotorItemResult)
573  *initWithItemLoadingTokenNSAccessibilityCustomRotorItemResult[] = {
574  &Ctx.Idents.get("initWithItemLoadingToken"),
575  &Ctx.Idents.get("customLabel")};
576  ADD_METHOD(NSAccessibilityCustomRotorItemResult,
577  initWithItemLoadingTokenNSAccessibilityCustomRotorItemResult, 2, 1)
578  ADD_UNARY_METHOD(NSAccessibilityCustomRotorItemResult, setCustomLabel, 0)
579 
580  NEW_RECEIVER(UIContextualAction)
581  IdentifierInfo *contextualActionWithStyleUIContextualAction[] = {
582  &Ctx.Idents.get("contextualActionWithStyle"), &Ctx.Idents.get("title"),
583  &Ctx.Idents.get("handler")};
584  ADD_METHOD(UIContextualAction, contextualActionWithStyleUIContextualAction, 3,
585  1)
586  ADD_UNARY_METHOD(UIContextualAction, setTitle, 0)
587 
588  NEW_RECEIVER(NSAccessibilityCustomRotor)
589  IdentifierInfo *initWithLabelNSAccessibilityCustomRotor[] = {
590  &Ctx.Idents.get("initWithLabel"), &Ctx.Idents.get("itemSearchDelegate")};
591  ADD_METHOD(NSAccessibilityCustomRotor,
592  initWithLabelNSAccessibilityCustomRotor, 2, 0)
593  ADD_UNARY_METHOD(NSAccessibilityCustomRotor, setLabel, 0)
594 
595  NEW_RECEIVER(NSWindowTab)
596  ADD_UNARY_METHOD(NSWindowTab, setTitle, 0)
597  ADD_UNARY_METHOD(NSWindowTab, setToolTip, 0)
598 
599  NEW_RECEIVER(NSAccessibilityCustomAction)
600  IdentifierInfo *initWithNameNSAccessibilityCustomAction[] = {
601  &Ctx.Idents.get("initWithName"), &Ctx.Idents.get("handler")};
602  ADD_METHOD(NSAccessibilityCustomAction,
603  initWithNameNSAccessibilityCustomAction, 2, 0)
604  IdentifierInfo *initWithNameTargetNSAccessibilityCustomAction[] = {
605  &Ctx.Idents.get("initWithName"), &Ctx.Idents.get("target"),
606  &Ctx.Idents.get("selector")};
607  ADD_METHOD(NSAccessibilityCustomAction,
608  initWithNameTargetNSAccessibilityCustomAction, 3, 0)
609  ADD_UNARY_METHOD(NSAccessibilityCustomAction, setName, 0)
610 }
611 
612 #define LSF_INSERT(function_name) LSF.insert(&Ctx.Idents.get(function_name));
613 #define LSM_INSERT_NULLARY(receiver, method_name) \
614  LSM.insert({&Ctx.Idents.get(receiver), Ctx.Selectors.getNullarySelector( \
615  &Ctx.Idents.get(method_name))});
616 #define LSM_INSERT_UNARY(receiver, method_name) \
617  LSM.insert({&Ctx.Idents.get(receiver), \
618  Ctx.Selectors.getUnarySelector(&Ctx.Idents.get(method_name))});
619 #define LSM_INSERT_SELECTOR(receiver, method_list, arguments) \
620  LSM.insert({&Ctx.Idents.get(receiver), \
621  Ctx.Selectors.getSelector(arguments, method_list)});
622 
623 /// Initializes a list of methods and C functions that return a localized string
624 void NonLocalizedStringChecker::initLocStringsMethods(ASTContext &Ctx) const {
625  if (!LSM.empty())
626  return;
627 
628  IdentifierInfo *LocalizedStringMacro[] = {
629  &Ctx.Idents.get("localizedStringForKey"), &Ctx.Idents.get("value"),
630  &Ctx.Idents.get("table")};
631  LSM_INSERT_SELECTOR("NSBundle", LocalizedStringMacro, 3)
632  LSM_INSERT_UNARY("NSDateFormatter", "stringFromDate")
633  IdentifierInfo *LocalizedStringFromDate[] = {
634  &Ctx.Idents.get("localizedStringFromDate"), &Ctx.Idents.get("dateStyle"),
635  &Ctx.Idents.get("timeStyle")};
636  LSM_INSERT_SELECTOR("NSDateFormatter", LocalizedStringFromDate, 3)
637  LSM_INSERT_UNARY("NSNumberFormatter", "stringFromNumber")
638  LSM_INSERT_NULLARY("UITextField", "text")
639  LSM_INSERT_NULLARY("UITextView", "text")
640  LSM_INSERT_NULLARY("UILabel", "text")
641 
642  LSF_INSERT("CFDateFormatterCreateStringWithDate");
643  LSF_INSERT("CFDateFormatterCreateStringWithAbsoluteTime");
644  LSF_INSERT("CFNumberFormatterCreateStringWithNumber");
645 }
646 
647 /// Checks to see if the method / function declaration includes
648 /// __attribute__((annotate("returns_localized_nsstring")))
649 bool NonLocalizedStringChecker::isAnnotatedAsReturningLocalized(
650  const Decl *D) const {
651  if (!D)
652  return false;
653  return std::any_of(
654  D->specific_attr_begin<AnnotateAttr>(),
655  D->specific_attr_end<AnnotateAttr>(), [](const AnnotateAttr *Ann) {
656  return Ann->getAnnotation() == "returns_localized_nsstring";
657  });
658 }
659 
660 /// Checks to see if the method / function declaration includes
661 /// __attribute__((annotate("takes_localized_nsstring")))
662 bool NonLocalizedStringChecker::isAnnotatedAsTakingLocalized(
663  const Decl *D) const {
664  if (!D)
665  return false;
666  return std::any_of(
667  D->specific_attr_begin<AnnotateAttr>(),
668  D->specific_attr_end<AnnotateAttr>(), [](const AnnotateAttr *Ann) {
669  return Ann->getAnnotation() == "takes_localized_nsstring";
670  });
671 }
672 
673 /// Returns true if the given SVal is marked as Localized in the program state
674 bool NonLocalizedStringChecker::hasLocalizedState(SVal S,
675  CheckerContext &C) const {
676  const MemRegion *mt = S.getAsRegion();
677  if (mt) {
678  const LocalizedState *LS = C.getState()->get<LocalizedMemMap>(mt);
679  if (LS && LS->isLocalized())
680  return true;
681  }
682  return false;
683 }
684 
685 /// Returns true if the given SVal is marked as NonLocalized in the program
686 /// state
687 bool NonLocalizedStringChecker::hasNonLocalizedState(SVal S,
688  CheckerContext &C) const {
689  const MemRegion *mt = S.getAsRegion();
690  if (mt) {
691  const LocalizedState *LS = C.getState()->get<LocalizedMemMap>(mt);
692  if (LS && LS->isNonLocalized())
693  return true;
694  }
695  return false;
696 }
697 
698 /// Marks the given SVal as Localized in the program state
699 void NonLocalizedStringChecker::setLocalizedState(const SVal S,
700  CheckerContext &C) const {
701  const MemRegion *mt = S.getAsRegion();
702  if (mt) {
704  C.getState()->set<LocalizedMemMap>(mt, LocalizedState::getLocalized());
705  C.addTransition(State);
706  }
707 }
708 
709 /// Marks the given SVal as NonLocalized in the program state
710 void NonLocalizedStringChecker::setNonLocalizedState(const SVal S,
711  CheckerContext &C) const {
712  const MemRegion *mt = S.getAsRegion();
713  if (mt) {
714  ProgramStateRef State = C.getState()->set<LocalizedMemMap>(
715  mt, LocalizedState::getNonLocalized());
716  C.addTransition(State);
717  }
718 }
719 
720 
721 static bool isDebuggingName(std::string name) {
722  return StringRef(name).lower().find("debug") != StringRef::npos;
723 }
724 
725 /// Returns true when, heuristically, the analyzer may be analyzing debugging
726 /// code. We use this to suppress localization diagnostics in un-localized user
727 /// interfaces that are only used for debugging and are therefore not user
728 /// facing.
730  const Decl *D = C.getCurrentAnalysisDeclContext()->getDecl();
731  if (!D)
732  return false;
733 
734  if (auto *ND = dyn_cast<NamedDecl>(D)) {
735  if (isDebuggingName(ND->getNameAsString()))
736  return true;
737  }
738 
739  const DeclContext *DC = D->getDeclContext();
740 
741  if (auto *CD = dyn_cast<ObjCContainerDecl>(DC)) {
742  if (isDebuggingName(CD->getNameAsString()))
743  return true;
744  }
745 
746  return false;
747 }
748 
749 
750 /// Reports a localization error for the passed in method call and SVal
751 void NonLocalizedStringChecker::reportLocalizationError(
752  SVal S, const CallEvent &M, CheckerContext &C, int argumentNumber) const {
753 
754  // Don't warn about localization errors in classes and methods that
755  // may be debug code.
756  if (isDebuggingContext(C))
757  return;
758 
759  ExplodedNode *ErrNode = C.getPredecessor();
760  static CheckerProgramPointTag Tag("NonLocalizedStringChecker",
761  "UnlocalizedString");
762  ErrNode = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
763 
764  if (!ErrNode)
765  return;
766 
767  // Generate the bug report.
768  std::unique_ptr<BugReport> R(new BugReport(
769  *BT, "User-facing text should use localized string macro", ErrNode));
770  if (argumentNumber) {
771  R->addRange(M.getArgExpr(argumentNumber - 1)->getSourceRange());
772  } else {
773  R->addRange(M.getSourceRange());
774  }
775  R->markInteresting(S);
776 
777  const MemRegion *StringRegion = S.getAsRegion();
778  if (StringRegion)
779  R->addVisitor(llvm::make_unique<NonLocalizedStringBRVisitor>(StringRegion));
780 
781  C.emitReport(std::move(R));
782 }
783 
784 /// Returns the argument number requiring localized string if it exists
785 /// otherwise, returns -1
786 int NonLocalizedStringChecker::getLocalizedArgumentForSelector(
787  const IdentifierInfo *Receiver, Selector S) const {
788  auto method = UIMethods.find(Receiver);
789 
790  if (method == UIMethods.end())
791  return -1;
792 
793  auto argumentIterator = method->getSecond().find(S);
794 
795  if (argumentIterator == method->getSecond().end())
796  return -1;
797 
798  int argumentNumber = argumentIterator->getSecond();
799  return argumentNumber;
800 }
801 
802 /// Check if the string being passed in has NonLocalized state
803 void NonLocalizedStringChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
804  CheckerContext &C) const {
805  initUIMethods(C.getASTContext());
806 
807  const ObjCInterfaceDecl *OD = msg.getReceiverInterface();
808  if (!OD)
809  return;
810  const IdentifierInfo *odInfo = OD->getIdentifier();
811 
812  Selector S = msg.getSelector();
813 
814  std::string SelectorString = S.getAsString();
815  StringRef SelectorName = SelectorString;
816  assert(!SelectorName.empty());
817 
818  if (odInfo->isStr("NSString")) {
819  // Handle the case where the receiver is an NSString
820  // These special NSString methods draw to the screen
821 
822  if (!(SelectorName.startswith("drawAtPoint") ||
823  SelectorName.startswith("drawInRect") ||
824  SelectorName.startswith("drawWithRect")))
825  return;
826 
827  SVal svTitle = msg.getReceiverSVal();
828 
829  bool isNonLocalized = hasNonLocalizedState(svTitle, C);
830 
831  if (isNonLocalized) {
832  reportLocalizationError(svTitle, msg, C);
833  }
834  }
835 
836  int argumentNumber = getLocalizedArgumentForSelector(odInfo, S);
837  // Go up each hierarchy of superclasses and their protocols
838  while (argumentNumber < 0 && OD->getSuperClass() != nullptr) {
839  for (const auto *P : OD->all_referenced_protocols()) {
840  argumentNumber = getLocalizedArgumentForSelector(P->getIdentifier(), S);
841  if (argumentNumber >= 0)
842  break;
843  }
844  if (argumentNumber < 0) {
845  OD = OD->getSuperClass();
846  argumentNumber = getLocalizedArgumentForSelector(OD->getIdentifier(), S);
847  }
848  }
849 
850  if (argumentNumber < 0) { // There was no match in UIMethods
851  if (const Decl *D = msg.getDecl()) {
852  if (const ObjCMethodDecl *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
853  auto formals = OMD->parameters();
854  for (unsigned i = 0, ei = formals.size(); i != ei; ++i) {
855  if (isAnnotatedAsTakingLocalized(formals[i])) {
856  argumentNumber = i;
857  break;
858  }
859  }
860  }
861  }
862  }
863 
864  if (argumentNumber < 0) // Still no match
865  return;
866 
867  SVal svTitle = msg.getArgSVal(argumentNumber);
868 
869  if (const ObjCStringRegion *SR =
870  dyn_cast_or_null<ObjCStringRegion>(svTitle.getAsRegion())) {
871  StringRef stringValue =
872  SR->getObjCStringLiteral()->getString()->getString();
873  if ((stringValue.trim().size() == 0 && stringValue.size() > 0) ||
874  stringValue.empty())
875  return;
876  if (!IsAggressive && llvm::sys::unicode::columnWidthUTF8(stringValue) < 2)
877  return;
878  }
879 
880  bool isNonLocalized = hasNonLocalizedState(svTitle, C);
881 
882  if (isNonLocalized) {
883  reportLocalizationError(svTitle, msg, C, argumentNumber + 1);
884  }
885 }
886 
887 void NonLocalizedStringChecker::checkPreCall(const CallEvent &Call,
888  CheckerContext &C) const {
889  const Decl *D = Call.getDecl();
890  if (D && isa<FunctionDecl>(D)) {
891  const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
892  auto formals = FD->parameters();
893  for (unsigned i = 0,
894  ei = std::min(unsigned(formals.size()), Call.getNumArgs());
895  i != ei; ++i) {
896  if (isAnnotatedAsTakingLocalized(formals[i])) {
897  auto actual = Call.getArgSVal(i);
898  if (hasNonLocalizedState(actual, C)) {
899  reportLocalizationError(actual, Call, C, i + 1);
900  }
901  }
902  }
903  }
904 }
905 
906 static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
907 
909  if (!PT)
910  return false;
911 
913  if (!Cls)
914  return false;
915 
916  IdentifierInfo *ClsName = Cls->getIdentifier();
917 
918  // FIXME: Should we walk the chain of classes?
919  return ClsName == &Ctx.Idents.get("NSString") ||
920  ClsName == &Ctx.Idents.get("NSMutableString");
921 }
922 
923 /// Marks a string being returned by any call as localized
924 /// if it is in LocStringFunctions (LSF) or the function is annotated.
925 /// Otherwise, we mark it as NonLocalized (Aggressive) or
926 /// NonLocalized only if it is not backed by a SymRegion (Non-Aggressive),
927 /// basically leaving only string literals as NonLocalized.
928 void NonLocalizedStringChecker::checkPostCall(const CallEvent &Call,
929  CheckerContext &C) const {
930  initLocStringsMethods(C.getASTContext());
931 
932  if (!Call.getOriginExpr())
933  return;
934 
935  // Anything that takes in a localized NSString as an argument
936  // and returns an NSString will be assumed to be returning a
937  // localized NSString. (Counter: Incorrectly combining two LocalizedStrings)
938  const QualType RT = Call.getResultType();
939  if (isNSStringType(RT, C.getASTContext())) {
940  for (unsigned i = 0; i < Call.getNumArgs(); ++i) {
941  SVal argValue = Call.getArgSVal(i);
942  if (hasLocalizedState(argValue, C)) {
943  SVal sv = Call.getReturnValue();
944  setLocalizedState(sv, C);
945  return;
946  }
947  }
948  }
949 
950  const Decl *D = Call.getDecl();
951  if (!D)
952  return;
953 
954  const IdentifierInfo *Identifier = Call.getCalleeIdentifier();
955 
956  SVal sv = Call.getReturnValue();
957  if (isAnnotatedAsReturningLocalized(D) || LSF.count(Identifier) != 0) {
958  setLocalizedState(sv, C);
959  } else if (isNSStringType(RT, C.getASTContext()) &&
960  !hasLocalizedState(sv, C)) {
961  if (IsAggressive) {
962  setNonLocalizedState(sv, C);
963  } else {
964  const SymbolicRegion *SymReg =
965  dyn_cast_or_null<SymbolicRegion>(sv.getAsRegion());
966  if (!SymReg)
967  setNonLocalizedState(sv, C);
968  }
969  }
970 }
971 
972 /// Marks a string being returned by an ObjC method as localized
973 /// if it is in LocStringMethods or the method is annotated
974 void NonLocalizedStringChecker::checkPostObjCMessage(const ObjCMethodCall &msg,
975  CheckerContext &C) const {
976  initLocStringsMethods(C.getASTContext());
977 
978  if (!msg.isInstanceMessage())
979  return;
980 
981  const ObjCInterfaceDecl *OD = msg.getReceiverInterface();
982  if (!OD)
983  return;
984  const IdentifierInfo *odInfo = OD->getIdentifier();
985 
986  Selector S = msg.getSelector();
987  std::string SelectorName = S.getAsString();
988 
989  std::pair<const IdentifierInfo *, Selector> MethodDescription = {odInfo, S};
990 
991  if (LSM.count(MethodDescription) ||
992  isAnnotatedAsReturningLocalized(msg.getDecl())) {
993  SVal sv = msg.getReturnValue();
994  setLocalizedState(sv, C);
995  }
996 }
997 
998 /// Marks all empty string literals as localized
999 void NonLocalizedStringChecker::checkPostStmt(const ObjCStringLiteral *SL,
1000  CheckerContext &C) const {
1001  SVal sv = C.getSVal(SL);
1002  setNonLocalizedState(sv, C);
1003 }
1004 
1005 std::shared_ptr<PathDiagnosticPiece>
1006 NonLocalizedStringBRVisitor::VisitNode(const ExplodedNode *Succ,
1007  const ExplodedNode *Pred,
1008  BugReporterContext &BRC, BugReport &BR) {
1009  if (Satisfied)
1010  return nullptr;
1011 
1012  Optional<StmtPoint> Point = Succ->getLocation().getAs<StmtPoint>();
1013  if (!Point.hasValue())
1014  return nullptr;
1015 
1016  auto *LiteralExpr = dyn_cast<ObjCStringLiteral>(Point->getStmt());
1017  if (!LiteralExpr)
1018  return nullptr;
1019 
1020  ProgramStateRef State = Succ->getState();
1021  SVal LiteralSVal = State->getSVal(LiteralExpr, Succ->getLocationContext());
1022  if (LiteralSVal.getAsRegion() != NonLocalizedString)
1023  return nullptr;
1024 
1025  Satisfied = true;
1026 
1029 
1030  if (!L.isValid() || !L.asLocation().isValid())
1031  return nullptr;
1032 
1033  auto Piece = std::make_shared<PathDiagnosticEventPiece>(
1034  L, "Non-localized string literal here");
1035  Piece->addRange(LiteralExpr->getSourceRange());
1036 
1037  return std::move(Piece);
1038 }
1039 
1040 namespace {
1041 class EmptyLocalizationContextChecker
1042  : public Checker<check::ASTDecl<ObjCImplementationDecl>> {
1043 
1044  // A helper class, which walks the AST
1045  class MethodCrawler : public ConstStmtVisitor<MethodCrawler> {
1046  const ObjCMethodDecl *MD;
1047  BugReporter &BR;
1048  AnalysisManager &Mgr;
1049  const CheckerBase *Checker;
1051 
1052  public:
1053  MethodCrawler(const ObjCMethodDecl *InMD, BugReporter &InBR,
1054  const CheckerBase *Checker, AnalysisManager &InMgr,
1055  AnalysisDeclContext *InDCtx)
1056  : MD(InMD), BR(InBR), Mgr(InMgr), Checker(Checker), DCtx(InDCtx) {}
1057 
1058  void VisitStmt(const Stmt *S) { VisitChildren(S); }
1059 
1060  void VisitObjCMessageExpr(const ObjCMessageExpr *ME);
1061 
1062  void reportEmptyContextError(const ObjCMessageExpr *M) const;
1063 
1064  void VisitChildren(const Stmt *S) {
1065  for (const Stmt *Child : S->children()) {
1066  if (Child)
1067  this->Visit(Child);
1068  }
1069  }
1070  };
1071 
1072 public:
1073  void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager &Mgr,
1074  BugReporter &BR) const;
1075 };
1076 } // end anonymous namespace
1077 
1078 void EmptyLocalizationContextChecker::checkASTDecl(
1079  const ObjCImplementationDecl *D, AnalysisManager &Mgr,
1080  BugReporter &BR) const {
1081 
1082  for (const ObjCMethodDecl *M : D->methods()) {
1084 
1085  const Stmt *Body = M->getBody();
1086  assert(Body);
1087 
1088  MethodCrawler MC(M->getCanonicalDecl(), BR, this, Mgr, DCtx);
1089  MC.VisitStmt(Body);
1090  }
1091 }
1092 
1093 /// This check attempts to match these macros, assuming they are defined as
1094 /// follows:
1095 ///
1096 /// #define NSLocalizedString(key, comment) \
1097 /// [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil]
1098 /// #define NSLocalizedStringFromTable(key, tbl, comment) \
1099 /// [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:(tbl)]
1100 /// #define NSLocalizedStringFromTableInBundle(key, tbl, bundle, comment) \
1101 /// [bundle localizedStringForKey:(key) value:@"" table:(tbl)]
1102 /// #define NSLocalizedStringWithDefaultValue(key, tbl, bundle, val, comment)
1103 ///
1104 /// We cannot use the path sensitive check because the macro argument we are
1105 /// checking for (comment) is not used and thus not present in the AST,
1106 /// so we use Lexer on the original macro call and retrieve the value of
1107 /// the comment. If it's empty or nil, we raise a warning.
1108 void EmptyLocalizationContextChecker::MethodCrawler::VisitObjCMessageExpr(
1109  const ObjCMessageExpr *ME) {
1110 
1111  // FIXME: We may be able to use PPCallbacks to check for empy context
1112  // comments as part of preprocessing and avoid this re-lexing hack.
1113  const ObjCInterfaceDecl *OD = ME->getReceiverInterface();
1114  if (!OD)
1115  return;
1116 
1117  const IdentifierInfo *odInfo = OD->getIdentifier();
1118 
1119  if (!(odInfo->isStr("NSBundle") &&
1120  ME->getSelector().getAsString() ==
1121  "localizedStringForKey:value:table:")) {
1122  return;
1123  }
1124 
1125  SourceRange R = ME->getSourceRange();
1126  if (!R.getBegin().isMacroID())
1127  return;
1128 
1129  // getImmediateMacroCallerLoc gets the location of the immediate macro
1130  // caller, one level up the stack toward the initial macro typed into the
1131  // source, so SL should point to the NSLocalizedString macro.
1132  SourceLocation SL =
1134  std::pair<FileID, unsigned> SLInfo =
1136 
1137  SrcMgr::SLocEntry SE = Mgr.getSourceManager().getSLocEntry(SLInfo.first);
1138 
1139  // If NSLocalizedString macro is wrapped in another macro, we need to
1140  // unwrap the expansion until we get to the NSLocalizedStringMacro.
1141  while (SE.isExpansion()) {
1142  SL = SE.getExpansion().getSpellingLoc();
1143  SLInfo = Mgr.getSourceManager().getDecomposedLoc(SL);
1144  SE = Mgr.getSourceManager().getSLocEntry(SLInfo.first);
1145  }
1146 
1147  bool Invalid = false;
1148  llvm::MemoryBuffer *BF =
1149  Mgr.getSourceManager().getBuffer(SLInfo.first, SL, &Invalid);
1150  if (Invalid)
1151  return;
1152 
1153  Lexer TheLexer(SL, LangOptions(), BF->getBufferStart(),
1154  BF->getBufferStart() + SLInfo.second, BF->getBufferEnd());
1155 
1156  Token I;
1157  Token Result; // This will hold the token just before the last ')'
1158  int p_count = 0; // This is for parenthesis matching
1159  while (!TheLexer.LexFromRawLexer(I)) {
1160  if (I.getKind() == tok::l_paren)
1161  ++p_count;
1162  if (I.getKind() == tok::r_paren) {
1163  if (p_count == 1)
1164  break;
1165  --p_count;
1166  }
1167  Result = I;
1168  }
1169 
1170  if (isAnyIdentifier(Result.getKind())) {
1171  if (Result.getRawIdentifier().equals("nil")) {
1172  reportEmptyContextError(ME);
1173  return;
1174  }
1175  }
1176 
1177  if (!isStringLiteral(Result.getKind()))
1178  return;
1179 
1180  StringRef Comment =
1181  StringRef(Result.getLiteralData(), Result.getLength()).trim('"');
1182 
1183  if ((Comment.trim().size() == 0 && Comment.size() > 0) || // Is Whitespace
1184  Comment.empty()) {
1185  reportEmptyContextError(ME);
1186  }
1187 }
1188 
1189 void EmptyLocalizationContextChecker::MethodCrawler::reportEmptyContextError(
1190  const ObjCMessageExpr *ME) const {
1191  // Generate the bug report.
1192  BR.EmitBasicReport(MD, Checker, "Context Missing",
1193  "Localizability Issue (Apple)",
1194  "Localized string macro should include a non-empty "
1195  "comment for translators",
1196  PathDiagnosticLocation(ME, BR.getSourceManager(), DCtx));
1197 }
1198 
1199 namespace {
1200 class PluralMisuseChecker : public Checker<check::ASTCodeBody> {
1201 
1202  // A helper class, which walks the AST
1203  class MethodCrawler : public RecursiveASTVisitor<MethodCrawler> {
1204  BugReporter &BR;
1205  const CheckerBase *Checker;
1206  AnalysisDeclContext *AC;
1207 
1208  // This functions like a stack. We push on any IfStmt or
1209  // ConditionalOperator that matches the condition
1210  // and pop it off when we leave that statement
1211  llvm::SmallVector<const clang::Stmt *, 8> MatchingStatements;
1212  // This is true when we are the direct-child of a
1213  // matching statement
1214  bool InMatchingStatement = false;
1215 
1216  public:
1217  explicit MethodCrawler(BugReporter &InBR, const CheckerBase *Checker,
1218  AnalysisDeclContext *InAC)
1219  : BR(InBR), Checker(Checker), AC(InAC) {}
1220 
1221  bool VisitIfStmt(const IfStmt *I);
1222  bool EndVisitIfStmt(IfStmt *I);
1223  bool TraverseIfStmt(IfStmt *x);
1224  bool VisitConditionalOperator(const ConditionalOperator *C);
1225  bool TraverseConditionalOperator(ConditionalOperator *C);
1226  bool VisitCallExpr(const CallExpr *CE);
1227  bool VisitObjCMessageExpr(const ObjCMessageExpr *ME);
1228 
1229  private:
1230  void reportPluralMisuseError(const Stmt *S) const;
1231  bool isCheckingPlurality(const Expr *E) const;
1232  };
1233 
1234 public:
1235  void checkASTCodeBody(const Decl *D, AnalysisManager &Mgr,
1236  BugReporter &BR) const {
1237  MethodCrawler Visitor(BR, this, Mgr.getAnalysisDeclContext(D));
1238  Visitor.TraverseDecl(const_cast<Decl *>(D));
1239  }
1240 };
1241 } // end anonymous namespace
1242 
1243 // Checks the condition of the IfStmt and returns true if one
1244 // of the following heuristics are met:
1245 // 1) The conidtion is a variable with "singular" or "plural" in the name
1246 // 2) The condition is a binary operator with 1 or 2 on the right-hand side
1247 bool PluralMisuseChecker::MethodCrawler::isCheckingPlurality(
1248  const Expr *Condition) const {
1249  const BinaryOperator *BO = nullptr;
1250  // Accounts for when a VarDecl represents a BinaryOperator
1251  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Condition)) {
1252  if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
1253  const Expr *InitExpr = VD->getInit();
1254  if (InitExpr) {
1255  if (const BinaryOperator *B =
1256  dyn_cast<BinaryOperator>(InitExpr->IgnoreParenImpCasts())) {
1257  BO = B;
1258  }
1259  }
1260  if (VD->getName().lower().find("plural") != StringRef::npos ||
1261  VD->getName().lower().find("singular") != StringRef::npos) {
1262  return true;
1263  }
1264  }
1265  } else if (const BinaryOperator *B = dyn_cast<BinaryOperator>(Condition)) {
1266  BO = B;
1267  }
1268 
1269  if (BO == nullptr)
1270  return false;
1271 
1272  if (IntegerLiteral *IL = dyn_cast_or_null<IntegerLiteral>(
1273  BO->getRHS()->IgnoreParenImpCasts())) {
1274  llvm::APInt Value = IL->getValue();
1275  if (Value == 1 || Value == 2) {
1276  return true;
1277  }
1278  }
1279  return false;
1280 }
1281 
1282 // A CallExpr with "LOC" in its identifier that takes in a string literal
1283 // has been shown to almost always be a function that returns a localized
1284 // string. Raise a diagnostic when this is in a statement that matches
1285 // the condition.
1286 bool PluralMisuseChecker::MethodCrawler::VisitCallExpr(const CallExpr *CE) {
1287  if (InMatchingStatement) {
1288  if (const FunctionDecl *FD = CE->getDirectCallee()) {
1289  std::string NormalizedName =
1290  StringRef(FD->getNameInfo().getAsString()).lower();
1291  if (NormalizedName.find("loc") != std::string::npos) {
1292  for (const Expr *Arg : CE->arguments()) {
1293  if (isa<ObjCStringLiteral>(Arg))
1294  reportPluralMisuseError(CE);
1295  }
1296  }
1297  }
1298  }
1299  return true;
1300 }
1301 
1302 // The other case is for NSLocalizedString which also returns
1303 // a localized string. It's a macro for the ObjCMessageExpr
1304 // [NSBundle localizedStringForKey:value:table:] Raise a
1305 // diagnostic when this is in a statement that matches
1306 // the condition.
1307 bool PluralMisuseChecker::MethodCrawler::VisitObjCMessageExpr(
1308  const ObjCMessageExpr *ME) {
1309  const ObjCInterfaceDecl *OD = ME->getReceiverInterface();
1310  if (!OD)
1311  return true;
1312 
1313  const IdentifierInfo *odInfo = OD->getIdentifier();
1314 
1315  if (odInfo->isStr("NSBundle") &&
1316  ME->getSelector().getAsString() == "localizedStringForKey:value:table:") {
1317  if (InMatchingStatement) {
1318  reportPluralMisuseError(ME);
1319  }
1320  }
1321  return true;
1322 }
1323 
1324 /// Override TraverseIfStmt so we know when we are done traversing an IfStmt
1325 bool PluralMisuseChecker::MethodCrawler::TraverseIfStmt(IfStmt *I) {
1327  return EndVisitIfStmt(I);
1328 }
1329 
1330 // EndVisit callbacks are not provided by the RecursiveASTVisitor
1331 // so we override TraverseIfStmt and make a call to EndVisitIfStmt
1332 // after traversing the IfStmt
1333 bool PluralMisuseChecker::MethodCrawler::EndVisitIfStmt(IfStmt *I) {
1334  MatchingStatements.pop_back();
1335  if (!MatchingStatements.empty()) {
1336  if (MatchingStatements.back() != nullptr) {
1337  InMatchingStatement = true;
1338  return true;
1339  }
1340  }
1341  InMatchingStatement = false;
1342  return true;
1343 }
1344 
1345 bool PluralMisuseChecker::MethodCrawler::VisitIfStmt(const IfStmt *I) {
1346  const Expr *Condition = I->getCond()->IgnoreParenImpCasts();
1347  if (isCheckingPlurality(Condition)) {
1348  MatchingStatements.push_back(I);
1349  InMatchingStatement = true;
1350  } else {
1351  MatchingStatements.push_back(nullptr);
1352  InMatchingStatement = false;
1353  }
1354 
1355  return true;
1356 }
1357 
1358 // Preliminary support for conditional operators.
1359 bool PluralMisuseChecker::MethodCrawler::TraverseConditionalOperator(
1360  ConditionalOperator *C) {
1362  MatchingStatements.pop_back();
1363  if (!MatchingStatements.empty()) {
1364  if (MatchingStatements.back() != nullptr)
1365  InMatchingStatement = true;
1366  else
1367  InMatchingStatement = false;
1368  } else {
1369  InMatchingStatement = false;
1370  }
1371  return true;
1372 }
1373 
1374 bool PluralMisuseChecker::MethodCrawler::VisitConditionalOperator(
1375  const ConditionalOperator *C) {
1376  const Expr *Condition = C->getCond()->IgnoreParenImpCasts();
1377  if (isCheckingPlurality(Condition)) {
1378  MatchingStatements.push_back(C);
1379  InMatchingStatement = true;
1380  } else {
1381  MatchingStatements.push_back(nullptr);
1382  InMatchingStatement = false;
1383  }
1384  return true;
1385 }
1386 
1387 void PluralMisuseChecker::MethodCrawler::reportPluralMisuseError(
1388  const Stmt *S) const {
1389  // Generate the bug report.
1390  BR.EmitBasicReport(AC->getDecl(), Checker, "Plural Misuse",
1391  "Localizability Issue (Apple)",
1392  "Plural cases are not supported accross all languages. "
1393  "Use a .stringsdict file instead",
1395 }
1396 
1397 //===----------------------------------------------------------------------===//
1398 // Checker registration.
1399 //===----------------------------------------------------------------------===//
1400 
1401 void ento::registerNonLocalizedStringChecker(CheckerManager &mgr) {
1402  NonLocalizedStringChecker *checker =
1403  mgr.registerChecker<NonLocalizedStringChecker>();
1404  checker->IsAggressive =
1405  mgr.getAnalyzerOptions().getBooleanOption("AggressiveReport", false);
1406 }
1407 
1408 void ento::registerEmptyLocalizationContextChecker(CheckerManager &mgr) {
1409  mgr.registerChecker<EmptyLocalizationContextChecker>();
1410 }
1411 
1412 void ento::registerPluralMisuseChecker(CheckerManager &mgr) {
1413  mgr.registerChecker<PluralMisuseChecker>();
1414 }
SVal getReceiverSVal() const
Returns the value of the receiver at the time of this call.
Definition: CallEvent.cpp:746
#define NEW_RECEIVER(receiver)
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1629
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens...
Definition: Lexer.h:63
Smart pointer class that efficiently represents Objective-C method names.
This is a discriminated union of FileInfo and ExpansionInfo.
A (possibly-)qualified type.
Definition: Type.h:614
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:79
Selector getSelector() const
Definition: ExprObjC.cpp:306
SourceLocation getSpellingLoc() const
bool operator==(CanQual< T > x, CanQual< U > y)
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:189
specific_attr_iterator< T > specific_attr_begin() const
Definition: DeclBase.h:510
Stmt - This represents one statement.
Definition: Stmt.h:60
#define ADD_METHOD(receiver, method_list, count, argument)
IfStmt - This represents an if/then/else.
Definition: Stmt.h:905
A helper class which wraps a boolean value set to false by default.
Definition: Checker.h:551
ObjCInterfaceDecl * getReceiverInterface() const
Retrieve the Objective-C interface to which this message is being directed, if known.
Definition: ExprObjC.cpp:327
ExplodedNode * addTransition(ProgramStateRef State=nullptr, const ProgramPointTag *Tag=nullptr)
Generates a new transition in the program state graph (ExplodedGraph).
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:81
StringRef P
REGISTER_MAP_WITH_PROGRAMSTATE(LocalizedMemMap, const MemRegion *, LocalizedState) NonLocalizedStringChecker
static bool isDebuggingName(std::string name)
const ProgramStateRef & getState() const
static bool isDebuggingContext(CheckerContext &C)
Returns true when, heuristically, the analyzer may be analyzing debugging code.
const Expr * getOriginExpr() const
Returns the expression whose value will be the result of this call.
Definition: CallEvent.h:225
SourceLocation getImmediateMacroCallerLoc(SourceLocation Loc) const
Gets the location of the immediate macro caller, one level up the stack toward the initial macro type...
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:769
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6052
bool isStringLiteral(TokenKind K)
Return true if this is a C or C++ string-literal (or C++11 user-defined-string-literal) token...
Definition: TokenKinds.h:79
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:113
ExplodedNode * getPredecessor()
Returns the previous node in the exploded graph, which includes the state of the program before the c...
SVal getSVal(const Stmt *S) const
Get the value of arbitrary expressions at this point in the path.
tok::TokenKind getKind() const
Definition: Token.h:90
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:232
One of these records is kept for each identifier that is lexed.
The region associated with an ObjCStringLiteral.
Definition: MemRegion.h:817
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:128
LineState State
AnalysisDeclContext contains the context data for the function or method under analysis.
This class provides a convenience implementation for clone() using the Curiously-Recurring Template P...
method_range methods() const
Definition: DeclObjC.h:982
const ObjCInterfaceDecl * getReceiverInterface() const
Get the interface for the receiver.
Definition: CallEvent.h:928
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
virtual const Expr * getArgExpr(unsigned Index) const
Returns the expression associated with a given argument.
Definition: CallEvent.h:275
specific_attr_iterator< T > specific_attr_end() const
Definition: DeclBase.h:514
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
IdentifierTable & Idents
Definition: ASTContext.h:513
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2077
Represents any expression that calls an Objective-C method.
Definition: CallEvent.h:870
child_range children()
Definition: Stmt.cpp:208
const LocationContext * getLocationContext() const
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:2980
SVal getReturnValue() const
Returns the return value of the call.
Definition: CallEvent.cpp:240
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition: ExprObjC.h:29
static PathDiagnosticLocation create(const Decl *D, const SourceManager &SM)
Create a location corresponding to the given declaration.
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
Represents an ObjC class declaration.
Definition: DeclObjC.h:1108
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface...
Definition: Type.h:5209
AnalysisDeclContext * getAnalysisDeclContext(const Decl *D)
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:3264
#define LSM_INSERT_NULLARY(receiver, method_name)
ID
Defines the address space values used by the address space qualifier of QualType. ...
Definition: AddressSpaces.h:26
SymbolicRegion - A special, "non-concrete" region.
Definition: MemRegion.h:742
Expr * getCond() const
Definition: Expr.h:3298
Expr - This represents one expression.
Definition: Expr.h:106
DeclContext * getDeclContext()
Definition: DeclBase.h:416
const IdentifierInfo * getCalleeIdentifier() const
Returns the name of the callee, if its name is a simple identifier.
Definition: CallEvent.h:335
char __ovld __cnfn min(char x, char y)
Returns y if y < x, otherwise it returns x.
virtual const Decl * getDecl() const
Returns the declaration of the function or method that will be called.
Definition: CallEvent.h:205
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:860
bool getBooleanOption(StringRef Name, bool DefaultVal, const ento::CheckerBase *C=nullptr, bool SearchInParents=false)
Interprets an option&#39;s string value as a boolean.
const ExpansionInfo & getExpansion() const
#define ADD_UNARY_METHOD(receiver, method, argument)
llvm::PointerUnion< const LocationContext *, AnalysisDeclContext * > LocationOrAnalysisDeclContext
void emitReport(std::unique_ptr< BugReport > R)
Emit the diagnostics report.
BugReporter is a utility class for generating PathDiagnostics for analysis.
Definition: BugReporter.h:403
virtual SourceRange getSourceRange() const
Returns a source range for the entire call, suitable for outputting in diagnostics.
Definition: CallEvent.h:266
std::string getAsString() const
Derive the full selector name (e.g.
Kind
llvm::MemoryBuffer * getBuffer(FileID FID, SourceLocation Loc, bool *Invalid=nullptr) const
Return the buffer for the specified FileID.
CHECKER * registerChecker()
Used to register checkers.
static bool isNSStringType(QualType T, ASTContext &Ctx)
Encodes a location in the source.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
void EmitBasicReport(const Decl *DeclWithIssue, const CheckerBase *Checker, StringRef BugName, StringRef BugCategory, StringRef BugStr, PathDiagnosticLocation Loc, ArrayRef< SourceRange > Ranges=None)
const MemRegion * getAsRegion() const
Definition: SVals.cpp:140
ProgramPoint getLocation() const
getLocation - Returns the edge associated with the given node.
SVal - This represents a symbolic expression, which can be either an L-value or an R-value...
Definition: SVals.h:63
#define LSF_INSERT(function_name)
const Decl * getDecl() const
arg_range arguments()
Definition: Expr.h:2303
const ObjCMethodDecl * getDecl() const override
Definition: CallEvent.h:896
SourceManager & getSourceManager() override
Selector getSelector() const
Definition: CallEvent.h:912
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1217
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return 0.
Definition: Expr.cpp:1216
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:5270
Represents an abstract call to a function or method along a particular path.
Definition: CallEvent.h:140
AnalyzerOptions & getAnalyzerOptions()
unsigned getLength() const
Definition: Token.h:127
Expr * IgnoreParenImpCasts() LLVM_READONLY
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
Definition: Expr.cpp:2538
Represents a pointer to an Objective C object.
Definition: Type.h:5230
bool isInstanceMessage() const
Definition: CallEvent.h:906
const char * getLiteralData() const
getLiteralData - For a literal token (numeric constant, string, etc), this returns a pointer to the s...
Definition: Token.h:215
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2448
const ProgramStateRef & getState() const
const SrcMgr::SLocEntry & getSLocEntry(FileID FID, bool *Invalid=nullptr) const
QualType getResultType() const
Returns the result type, adjusted for references.
Definition: CallEvent.cpp:31
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:13065
SourceManager & getSourceManager()
Definition: BugReporter.h:463
#define LSM_INSERT_UNARY(receiver, method_name)
AnalysisDeclContext * getCurrentAnalysisDeclContext() const
StringRef getRawIdentifier() const
getRawIdentifier - For a raw identifier token (i.e., an identifier lexed in raw mode), returns a reference to the text substring in the buffer if known.
Definition: Token.h:203
virtual unsigned getNumArgs() const =0
Returns the number of arguments (explicit and implicit).
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:245
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2209
StringRegion - Region associated with a StringLiteral.
Definition: MemRegion.h:779
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:956
Expr * getRHS() const
Definition: Expr.h:3026
#define LSM_INSERT_SELECTOR(receiver, method_list, arguments)
virtual SVal getArgSVal(unsigned Index) const
Returns the value of a given argument at the time of the call.
Definition: CallEvent.cpp:226
const Expr * getCond() const
Definition: Stmt.h:941
A trivial tuple used to represent a source range.
Tag that can use a checker name as a message provider (see SimpleProgramPointTag).
Definition: Checker.h:493
Optional< T > getAs() const
Convert to the specified ProgramPoint type, returning None if this ProgramPoint is not of the desired...
Definition: ProgramPoint.h:151
This class provides an interface through which checkers can create individual bug reports...
Definition: BugReporter.h:55
SourceLocation getBegin() const
bool isAnyIdentifier(TokenKind K)
Return true if this is a raw identifier or an identifier kind.
Definition: TokenKinds.h:73
SourceManager & getSourceManager()
Definition: BugReporter.h:565
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.