Coverage Report

Created: 2019-07-24 05:18

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