Coverage Report

Created: 2020-10-24 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/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
555
  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
  PathDiagnosticPieceRef VisitNode(const ExplodedNode *Succ,
127
                                   BugReporterContext &BRC,
128
                                   PathSensitiveBugReport &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
156
  // UI Methods
157
2
  NEW_RECEIVER(UISearchDisplayController)
158
2
  ADD_UNARY_METHOD(UISearchDisplayController, setSearchResultsTitle, 0)
159
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
170
2
  NEW_RECEIVER(NSDockTile)
171
2
  ADD_UNARY_METHOD(NSDockTile, setBadgeLabel, 0)
172
173
2
  NEW_RECEIVER(NSStatusItem)
174
2
  ADD_UNARY_METHOD(NSStatusItem, setTitle, 0)
175
2
  ADD_UNARY_METHOD(NSStatusItem, setToolTip, 0)
176
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
184
2
  NEW_RECEIVER(NSBox)
185
2
  ADD_UNARY_METHOD(NSBox, setTitle, 0)
186
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
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
214
2
  NEW_RECEIVER(UIPrintInfo)
215
2
  ADD_UNARY_METHOD(UIPrintInfo, setJobName, 0)
216
217
2
  NEW_RECEIVER(NSTabViewItem)
218
2
  ADD_UNARY_METHOD(NSTabViewItem, setLabel, 0)
219
2
  ADD_UNARY_METHOD(NSTabViewItem, setToolTip, 0)
220
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
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
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
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
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
253
2
  NEW_RECEIVER(NSImage)
254
2
  ADD_UNARY_METHOD(NSImage, setAccessibilityDescription, 0)
255
256
2
  NEW_RECEIVER(NSUserActivity)
257
2
  ADD_UNARY_METHOD(NSUserActivity, setTitle, 0)
258
259
2
  NEW_RECEIVER(NSPathControlItem)
260
2
  ADD_UNARY_METHOD(NSPathControlItem, setTitle, 0)
261
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
267
2
  NEW_RECEIVER(NSPathControl)
268
2
  ADD_UNARY_METHOD(NSPathControl, setPlaceholderString, 0)
269
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
275
2
  NEW_RECEIVER(NSTableColumn)
276
2
  ADD_UNARY_METHOD(NSTableColumn, setTitle, 0)
277
2
  ADD_UNARY_METHOD(NSTableColumn, setHeaderToolTip, 0)
278
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
287
2
  NEW_RECEIVER(NSButtonCell)
288
2
  ADD_UNARY_METHOD(NSButtonCell, setTitle, 0)
289
2
  ADD_UNARY_METHOD(NSButtonCell, setAlternateTitle, 0)
290
291
2
  NEW_RECEIVER(NSDatePickerCell)
292
2
  ADD_UNARY_METHOD(NSDatePickerCell, initTextCell, 0)
293
294
2
  NEW_RECEIVER(NSSliderCell)
295
2
  ADD_UNARY_METHOD(NSSliderCell, setTitle, 0)
296
297
2
  NEW_RECEIVER(NSControl)
298
2
  ADD_UNARY_METHOD(NSControl, setStringValue, 0)
299
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
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
312
2
  NEW_RECEIVER(NSPrintPanel)
313
2
  ADD_UNARY_METHOD(NSPrintPanel, setDefaultButtonTitle, 0)
314
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
320
2
  NEW_RECEIVER(NSSlider)
321
2
  ADD_UNARY_METHOD(NSSlider, setTitle, 0)
322
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
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
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
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
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
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
372
2
  NEW_RECEIVER(UIBarItem)
373
2
  ADD_UNARY_METHOD(UIBarItem, setTitle, 0)
374
375
2
  NEW_RECEIVER(UITextView)
376
2
  ADD_UNARY_METHOD(UITextView, setText, 0)
377
378
2
  NEW_RECEIVER(NSView)
379
2
  ADD_UNARY_METHOD(NSView, setToolTip, 0)
380
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
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
393
2
  NEW_RECEIVER(NSText)
394
2
  ADD_UNARY_METHOD(NSText, setString, 0)
395
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
403
2
  NEW_RECEIVER(UILabel)
404
2
  ADD_UNARY_METHOD(UILabel, setText, 0)
405
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
417
2
  NEW_RECEIVER(UIMutableApplicationShortcutItem)
418
2
  ADD_UNARY_METHOD(UIMutableApplicationShortcutItem, setLocalizedTitle, 0)
419
2
  ADD_UNARY_METHOD(UIMutableApplicationShortcutItem, setLocalizedSubtitle, 0)
420
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
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
433
2
  NEW_RECEIVER(NSPathCell)
434
2
  ADD_UNARY_METHOD(NSPathCell, setPlaceholderString, 0)
435
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
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
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
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
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
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
476
2
  NEW_RECEIVER(NSProgress)
477
2
  ADD_UNARY_METHOD(NSProgress, setLocalizedDescription, 0)
478
2
  ADD_UNARY_METHOD(NSProgress, setLocalizedAdditionalDescription, 0)
479
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
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
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
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
513
2
  NEW_RECEIVER(NSViewController)
514
2
  ADD_UNARY_METHOD(NSViewController, setTitle, 0)
515
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
528
2
  NEW_RECEIVER(UIMutableUserNotificationAction)
529
2
  ADD_UNARY_METHOD(UIMutableUserNotificationAction, setTitle, 0)
530
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
537
2
  NEW_RECEIVER(NSTextFieldCell)
538
2
  ADD_UNARY_METHOD(NSTextFieldCell, setPlaceholderString, 0)
539
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
546
2
  NEW_RECEIVER(UITextField)
547
2
  ADD_UNARY_METHOD(UITextField, setText, 0)
548
2
  ADD_UNARY_METHOD(UITextField, setPlaceholder, 0)
549
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
556
2
  NEW_RECEIVER(UIViewController)
557
2
  ADD_UNARY_METHOD(UIViewController, setTitle, 0)
558
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
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
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
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
592
2
  NEW_RECEIVER(NSWindowTab)
593
2
  ADD_UNARY_METHOD(NSWindowTab, setTitle, 0)
594
2
  ADD_UNARY_METHOD(NSWindowTab, setToolTip, 0)
595
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
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
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
2
      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
5
      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
731
13
  if (auto *ND = dyn_cast<NamedDecl>(D)) {
732
13
    if (isDebuggingName(ND->getNameAsString()))
733
1
      return true;
734
12
  }
735
736
12
  const DeclContext *DC = D->getDeclContext();
737
738
12
  if (auto *CD = dyn_cast<ObjCContainerDecl>(DC)) {
739
12
    if (isDebuggingName(CD->getNameAsString()))
740
1
      return true;
741
11
  }
742
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
751
  // Don't warn about localization errors in classes and methods that
752
  // may be debug code.
753
13
  if (isDebuggingContext(C))
754
2
    return;
755
756
11
  static CheckerProgramPointTag Tag("NonLocalizedStringChecker",
757
11
                                    "UnlocalizedString");
758
11
  ExplodedNode *ErrNode = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
759
760
11
  if (!ErrNode)
761
0
    return;
762
763
  // Generate the bug report.
764
11
  auto R = std::make_unique<PathSensitiveBugReport>(
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
1
  } else {
769
1
    R->addRange(M.getSourceRange());
770
1
  }
771
11
  R->markInteresting(S);
772
773
11
  const MemRegion *StringRegion = S.getAsRegion();
774
11
  if (StringRegion)
775
11
    R->addVisitor(std::make_unique<NonLocalizedStringBRVisitor>(StringRegion));
776
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
786
334
  if (method == UIMethods.end())
787
230
    return -1;
788
789
104
  auto argumentIterator = method->getSecond().find(S);
790
791
104
  if (argumentIterator == method->getSecond().end())
792
75
    return -1;
793
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
803
175
  const ObjCInterfaceDecl *OD = msg.getReceiverInterface();
804
175
  if (!OD)
805
0
    return;
806
175
  const IdentifierInfo *odInfo = OD->getIdentifier();
807
808
175
  Selector S = msg.getSelector();
809
810
175
  std::string SelectorString = S.getAsString();
811
175
  StringRef SelectorName = SelectorString;
812
175
  assert(!SelectorName.empty());
813
814
175
  if (odInfo->isStr("NSString")) {
815
    // Handle the case where the receiver is an NSString
816
    // These special NSString methods draw to the screen
817
818
13
    if (!(SelectorName.startswith("drawAtPoint") ||
819
11
          SelectorName.startswith("drawInRect") ||
820
11
          SelectorName.startswith("drawWithRect")))
821
11
      return;
822
823
2
    SVal svTitle = msg.getReceiverSVal();
824
825
2
    bool isNonLocalized = hasNonLocalizedState(svTitle, C);
826
827
2
    if (isNonLocalized) {
828
1
      reportLocalizationError(svTitle, msg, C);
829
1
    }
830
2
  }
831
832
164
  int argumentNumber = getLocalizedArgumentForSelector(odInfo, S);
833
  // Go up each hierarchy of superclasses and their protocols
834
303
  while (argumentNumber < 0 && 
OD->getSuperClass() != nullptr274
) {
835
32
    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
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
860
164
  if (argumentNumber < 0) // Still no match
861
132
    return;
862
863
32
  SVal svTitle = msg.getArgSVal(argumentNumber);
864
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
876
28
  bool isNonLocalized = hasNonLocalizedState(svTitle, C);
877
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 auto *FD = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
886
196
  if (!FD)
887
175
    return;
888
889
21
  auto formals = FD->parameters();
890
21
  for (unsigned i = 0, ei = std::min(static_cast<unsigned>(formals.size()),
891
44
                                     Call.getNumArgs()); 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
901
373
static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
902
903
373
  const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
904
373
  if (!PT)
905
86
    return false;
906
907
287
  ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
908
287
  if (!Cls)
909
0
    return false;
910
911
287
  IdentifierInfo *ClsName = Cls->getIdentifier();
912
913
  // FIXME: Should we walk the chain of classes?
914
287
  return ClsName == &Ctx.Idents.get("NSString") ||
915
166
         ClsName == &Ctx.Idents.get("NSMutableString");
916
287
}
917
918
/// Marks a string being returned by any call as localized
919
/// if it is in LocStringFunctions (LSF) or the function is annotated.
920
/// Otherwise, we mark it as NonLocalized (Aggressive) or
921
/// NonLocalized only if it is not backed by a SymRegion (Non-Aggressive),
922
/// basically leaving only string literals as NonLocalized.
923
void NonLocalizedStringChecker::checkPostCall(const CallEvent &Call,
924
196
                                              CheckerContext &C) const {
925
196
  initLocStringsMethods(C.getASTContext());
926
927
196
  if (!Call.getOriginExpr())
928
0
    return;
929
930
  // Anything that takes in a localized NSString as an argument
931
  // and returns an NSString will be assumed to be returning a
932
  // localized NSString. (Counter: Incorrectly combining two LocalizedStrings)
933
196
  const QualType RT = Call.getResultType();
934
196
  if (isNSStringType(RT, C.getASTContext())) {
935
213
    for (unsigned i = 0; i < Call.getNumArgs(); 
++i143
) {
936
159
      SVal argValue = Call.getArgSVal(i);
937
159
      if (hasLocalizedState(argValue, C)) {
938
16
        SVal sv = Call.getReturnValue();
939
16
        setLocalizedState(sv, C);
940
16
        return;
941
16
      }
942
159
    }
943
70
  }
944
945
180
  const Decl *D = Call.getDecl();
946
180
  if (!D)
947
0
    return;
948
949
180
  const IdentifierInfo *Identifier = Call.getCalleeIdentifier();
950
951
180
  SVal sv = Call.getReturnValue();
952
180
  if (isAnnotatedAsReturningLocalized(D) || 
LSF.count(Identifier) != 0178
) {
953
3
    setLocalizedState(sv, C);
954
177
  } else if (isNSStringType(RT, C.getASTContext()) &&
955
51
             !hasLocalizedState(sv, C)) {
956
44
    if (IsAggressive) {
957
28
      setNonLocalizedState(sv, C);
958
16
    } else {
959
16
      const SymbolicRegion *SymReg =
960
16
          dyn_cast_or_null<SymbolicRegion>(sv.getAsRegion());
961
16
      if (!SymReg)
962
0
        setNonLocalizedState(sv, C);
963
16
    }
964
44
  }
965
180
}
966
967
/// Marks a string being returned by an ObjC method as localized
968
/// if it is in LocStringMethods or the method is annotated
969
void NonLocalizedStringChecker::checkPostObjCMessage(const ObjCMethodCall &msg,
970
175
                                                     CheckerContext &C) const {
971
175
  initLocStringsMethods(C.getASTContext());
972
973
175
  if (!msg.isInstanceMessage())
974
75
    return;
975
976
100
  const ObjCInterfaceDecl *OD = msg.getReceiverInterface();
977
100
  if (!OD)
978
0
    return;
979
100
  const IdentifierInfo *odInfo = OD->getIdentifier();
980
981
100
  Selector S = msg.getSelector();
982
100
  std::string SelectorName = S.getAsString();
983
984
100
  std::pair<const IdentifierInfo *, Selector> MethodDescription = {odInfo, S};
985
986
100
  if (LSM.count(MethodDescription) ||
987
61
      isAnnotatedAsReturningLocalized(msg.getDecl())) {
988
39
    SVal sv = msg.getReturnValue();
989
39
    setLocalizedState(sv, C);
990
39
  }
991
100
}
992
993
/// Marks all empty string literals as localized
994
void NonLocalizedStringChecker::checkPostStmt(const ObjCStringLiteral *SL,
995
108
                                              CheckerContext &C) const {
996
108
  SVal sv = C.getSVal(SL);
997
108
  setNonLocalizedState(sv, C);
998
108
}
999
1000
PathDiagnosticPieceRef
1001
NonLocalizedStringBRVisitor::VisitNode(const ExplodedNode *Succ,
1002
                                       BugReporterContext &BRC,
1003
557
                                       PathSensitiveBugReport &BR) {
1004
557
  if (Satisfied)
1005
390
    return nullptr;
1006
1007
167
  Optional<StmtPoint> Point = Succ->getLocation().getAs<StmtPoint>();
1008
167
  if (!Point.hasValue())
1009
12
    return nullptr;
1010
1011
155
  auto *LiteralExpr = dyn_cast<ObjCStringLiteral>(Point->getStmt());
1012
155
  if (!LiteralExpr)
1013
142
    return nullptr;
1014
1015
13
  SVal LiteralSVal = Succ->getSVal(LiteralExpr);
1016
13
  if (LiteralSVal.getAsRegion() != NonLocalizedString)
1017
2
    return nullptr;
1018
1019
11
  Satisfied = true;
1020
1021
11
  PathDiagnosticLocation L =
1022
11
      PathDiagnosticLocation::create(*Point, BRC.getSourceManager());
1023
1024
11
  if (!L.isValid() || !L.asLocation().isValid())
1025
0
    return nullptr;
1026
1027
11
  auto Piece = std::make_shared<PathDiagnosticEventPiece>(
1028
11
      L, "Non-localized string literal here");
1029
11
  Piece->addRange(LiteralExpr->getSourceRange());
1030
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
2
    BugReporter &BR) const {
1075
1076
30
  for (const ObjCMethodDecl *M : D->methods()) {
1077
30
    AnalysisDeclContext *DCtx = Mgr.getAnalysisDeclContext(M);
1078
1079
30
    const Stmt *Body = M->getBody();
1080
30
    if (!Body) {
1081
2
      assert(M->isSynthesizedAccessorStub());
1082
2
      continue;
1083
2
    }
1084
1085
28
    MethodCrawler MC(M->getCanonicalDecl(), BR, this, Mgr, DCtx);
1086
28
    MC.VisitStmt(Body);
1087
28
  }
1088
2
}
1089
1090
/// This check attempts to match these macros, assuming they are defined as
1091
/// follows:
1092
///
1093
/// #define NSLocalizedString(key, comment) \
1094
/// [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil]
1095
/// #define NSLocalizedStringFromTable(key, tbl, comment) \
1096
/// [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:(tbl)]
1097
/// #define NSLocalizedStringFromTableInBundle(key, tbl, bundle, comment) \
1098
/// [bundle localizedStringForKey:(key) value:@"" table:(tbl)]
1099
/// #define NSLocalizedStringWithDefaultValue(key, tbl, bundle, val, comment)
1100
///
1101
/// We cannot use the path sensitive check because the macro argument we are
1102
/// checking for (comment) is not used and thus not present in the AST,
1103
/// so we use Lexer on the original macro call and retrieve the value of
1104
/// the comment. If it's empty or nil, we raise a warning.
1105
void EmptyLocalizationContextChecker::MethodCrawler::VisitObjCMessageExpr(
1106
61
    const ObjCMessageExpr *ME) {
1107
1108
  // FIXME: We may be able to use PPCallbacks to check for empty context
1109
  // comments as part of preprocessing and avoid this re-lexing hack.
1110
61
  const ObjCInterfaceDecl *OD = ME->getReceiverInterface();
1111
61
  if (!OD)
1112
0
    return;
1113
1114
61
  const IdentifierInfo *odInfo = OD->getIdentifier();
1115
1116
61
  if (!(odInfo->isStr("NSBundle") &&
1117
25
        ME->getSelector().getAsString() ==
1118
36
            "localizedStringForKey:value:table:")) {
1119
36
    return;
1120
36
  }
1121
1122
25
  SourceRange R = ME->getSourceRange();
1123
25
  if (!R.getBegin().isMacroID())
1124
0
    return;
1125
1126
  // getImmediateMacroCallerLoc gets the location of the immediate macro
1127
  // caller, one level up the stack toward the initial macro typed into the
1128
  // source, so SL should point to the NSLocalizedString macro.
1129
25
  SourceLocation SL =
1130
25
      Mgr.getSourceManager().getImmediateMacroCallerLoc(R.getBegin());
1131
25
  std::pair<FileID, unsigned> SLInfo =
1132
25
      Mgr.getSourceManager().getDecomposedLoc(SL);
1133
1134
25
  SrcMgr::SLocEntry SE = Mgr.getSourceManager().getSLocEntry(SLInfo.first);
1135
1136
  // If NSLocalizedString macro is wrapped in another macro, we need to
1137
  // unwrap the expansion until we get to the NSLocalizedStringMacro.
1138
33
  while (SE.isExpansion()) {
1139
8
    SL = SE.getExpansion().getSpellingLoc();
1140
8
    SLInfo = Mgr.getSourceManager().getDecomposedLoc(SL);
1141
8
    SE = Mgr.getSourceManager().getSLocEntry(SLInfo.first);
1142
8
  }
1143
1144
25
  llvm::Optional<llvm::MemoryBufferRef> BF =
1145
25
      Mgr.getSourceManager().getBufferOrNone(SLInfo.first, SL);
1146
25
  if (!BF)
1147
0
    return;
1148
1149
25
  Lexer TheLexer(SL, LangOptions(), BF->getBufferStart(),
1150
25
                 BF->getBufferStart() + SLInfo.second, BF->getBufferEnd());
1151
1152
25
  Token I;
1153
25
  Token Result;    // This will hold the token just before the last ')'
1154
25
  int p_count = 0; // This is for parenthesis matching
1155
214
  while (!TheLexer.LexFromRawLexer(I)) {
1156
214
    if (I.getKind() == tok::l_paren)
1157
27
      ++p_count;
1158
214
    if (I.getKind() == tok::r_paren) {
1159
27
      if (p_count == 1)
1160
25
        break;
1161
2
      --p_count;
1162
2
    }
1163
189
    Result = I;
1164
189
  }
1165
1166
25
  if (isAnyIdentifier(Result.getKind())) {
1167
11
    if (Result.getRawIdentifier().equals("nil")) {
1168
6
      reportEmptyContextError(ME);
1169
6
      return;
1170
6
    }
1171
19
  }
1172
1173
19
  if (!isStringLiteral(Result.getKind()))
1174
5
    return;
1175
1176
14
  StringRef Comment =
1177
14
      StringRef(Result.getLiteralData(), Result.getLength()).trim('"');
1178
1179
14
  if ((Comment.trim().size() == 0 && 
Comment.size() > 07
) || // Is Whitespace
1180
12
      Comment.empty()) {
1181
7
    reportEmptyContextError(ME);
1182
7
  }
1183
14
}
1184
1185
void EmptyLocalizationContextChecker::MethodCrawler::reportEmptyContextError(
1186
13
    const ObjCMessageExpr *ME) const {
1187
  // Generate the bug report.
1188
13
  BR.EmitBasicReport(MD, Checker, "Context Missing",
1189
13
                     "Localizability Issue (Apple)",
1190
13
                     "Localized string macro should include a non-empty "
1191
13
                     "comment for translators",
1192
13
                     PathDiagnosticLocation(ME, BR.getSourceManager(), DCtx));
1193
13
}
1194
1195
namespace {
1196
class PluralMisuseChecker : public Checker<check::ASTCodeBody> {
1197
1198
  // A helper class, which walks the AST
1199
  class MethodCrawler : public RecursiveASTVisitor<MethodCrawler> {
1200
    BugReporter &BR;
1201
    const CheckerBase *Checker;
1202
    AnalysisDeclContext *AC;
1203
1204
    // This functions like a stack. We push on any IfStmt or
1205
    // ConditionalOperator that matches the condition
1206
    // and pop it off when we leave that statement
1207
    llvm::SmallVector<const clang::Stmt *, 8> MatchingStatements;
1208
    // This is true when we are the direct-child of a
1209
    // matching statement
1210
    bool InMatchingStatement = false;
1211
1212
  public:
1213
    explicit MethodCrawler(BugReporter &InBR, const CheckerBase *Checker,
1214
                           AnalysisDeclContext *InAC)
1215
14
        : BR(InBR), Checker(Checker), AC(InAC) {}
1216
1217
    bool VisitIfStmt(const IfStmt *I);
1218
    bool EndVisitIfStmt(IfStmt *I);
1219
    bool TraverseIfStmt(IfStmt *x);
1220
    bool VisitConditionalOperator(const ConditionalOperator *C);
1221
    bool TraverseConditionalOperator(ConditionalOperator *C);
1222
    bool VisitCallExpr(const CallExpr *CE);
1223
    bool VisitObjCMessageExpr(const ObjCMessageExpr *ME);
1224
1225
  private:
1226
    void reportPluralMisuseError(const Stmt *S) const;
1227
    bool isCheckingPlurality(const Expr *E) const;
1228
  };
1229
1230
public:
1231
  void checkASTCodeBody(const Decl *D, AnalysisManager &Mgr,
1232
14
                        BugReporter &BR) const {
1233
14
    MethodCrawler Visitor(BR, this, Mgr.getAnalysisDeclContext(D));
1234
14
    Visitor.TraverseDecl(const_cast<Decl *>(D));
1235
14
  }
1236
};
1237
} // end anonymous namespace
1238
1239
// Checks the condition of the IfStmt and returns true if one
1240
// of the following heuristics are met:
1241
// 1) The conidtion is a variable with "singular" or "plural" in the name
1242
// 2) The condition is a binary operator with 1 or 2 on the right-hand side
1243
bool PluralMisuseChecker::MethodCrawler::isCheckingPlurality(
1244
11
    const Expr *Condition) const {
1245
11
  const BinaryOperator *BO = nullptr;
1246
  // Accounts for when a VarDecl represents a BinaryOperator
1247
11
  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Condition)) {
1248
3
    if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
1249
3
      const Expr *InitExpr = VD->getInit();
1250
3
      if (InitExpr) {
1251
2
        if (const BinaryOperator *B =
1252
1
                dyn_cast<BinaryOperator>(InitExpr->IgnoreParenImpCasts())) {
1253
1
          BO = B;
1254
1
        }
1255
2
      }
1256
3
      if (VD->getName().lower().find("plural") != StringRef::npos ||
1257
2
          VD->getName().lower().find("singular") != StringRef::npos) {
1258
1
        return true;
1259
1
      }
1260
8
    }
1261
8
  } else if (const BinaryOperator *B = dyn_cast<BinaryOperator>(Condition)) {
1262
5
    BO = B;
1263
5
  }
1264
1265
10
  if (BO == nullptr)
1266
4
    return false;
1267
1268
6
  if (IntegerLiteral *IL = dyn_cast_or_null<IntegerLiteral>(
1269
6
          BO->getRHS()->IgnoreParenImpCasts())) {
1270
6
    llvm::APInt Value = IL->getValue();
1271
6
    if (Value == 1 || 
Value == 21
) {
1272
5
      return true;
1273
5
    }
1274
1
  }
1275
1
  return false;
1276
1
}
1277
1278
// A CallExpr with "LOC" in its identifier that takes in a string literal
1279
// has been shown to almost always be a function that returns a localized
1280
// string. Raise a diagnostic when this is in a statement that matches
1281
// the condition.
1282
11
bool PluralMisuseChecker::MethodCrawler::VisitCallExpr(const CallExpr *CE) {
1283
11
  if (InMatchingStatement) {
1284
7
    if (const FunctionDecl *FD = CE->getDirectCallee()) {
1285
7
      std::string NormalizedName =
1286
7
          StringRef(FD->getNameInfo().getAsString()).lower();
1287
7
      if (NormalizedName.find("loc") != std::string::npos) {
1288
14
        for (const Expr *Arg : CE->arguments()) {
1289
14
          if (isa<ObjCStringLiteral>(Arg))
1290
9
            reportPluralMisuseError(CE);
1291
14
        }
1292
7
      }
1293
7
    }
1294
7
  }
1295
11
  return true;
1296
11
}
1297
1298
// The other case is for NSLocalizedString which also returns
1299
// a localized string. It's a macro for the ObjCMessageExpr
1300
// [NSBundle localizedStringForKey:value:table:] Raise a
1301
// diagnostic when this is in a statement that matches
1302
// the condition.
1303
bool PluralMisuseChecker::MethodCrawler::VisitObjCMessageExpr(
1304
46
    const ObjCMessageExpr *ME) {
1305
46
  const ObjCInterfaceDecl *OD = ME->getReceiverInterface();
1306
46
  if (!OD)
1307
0
    return true;
1308
1309
46
  const IdentifierInfo *odInfo = OD->getIdentifier();
1310
1311
46
  if (odInfo->isStr("NSBundle") &&
1312
16
      ME->getSelector().getAsString() == "localizedStringForKey:value:table:") {
1313
8
    if (InMatchingStatement) {
1314
3
      reportPluralMisuseError(ME);
1315
3
    }
1316
8
  }
1317
46
  return true;
1318
46
}
1319
1320
/// Override TraverseIfStmt so we know when we are done traversing an IfStmt
1321
10
bool PluralMisuseChecker::MethodCrawler::TraverseIfStmt(IfStmt *I) {
1322
10
  RecursiveASTVisitor<MethodCrawler>::TraverseIfStmt(I);
1323
10
  return EndVisitIfStmt(I);
1324
10
}
1325
1326
// EndVisit callbacks are not provided by the RecursiveASTVisitor
1327
// so we override TraverseIfStmt and make a call to EndVisitIfStmt
1328
// after traversing the IfStmt
1329
10
bool PluralMisuseChecker::MethodCrawler::EndVisitIfStmt(IfStmt *I) {
1330
10
  MatchingStatements.pop_back();
1331
10
  if (!MatchingStatements.empty()) {
1332
1
    if (MatchingStatements.back() != nullptr) {
1333
1
      InMatchingStatement = true;
1334
1
      return true;
1335
1
    }
1336
9
  }
1337
9
  InMatchingStatement = false;
1338
9
  return true;
1339
9
}
1340
1341
10
bool PluralMisuseChecker::MethodCrawler::VisitIfStmt(const IfStmt *I) {
1342
10
  const Expr *Condition = I->getCond()->IgnoreParenImpCasts();
1343
10
  if (isCheckingPlurality(Condition)) {
1344
5
    MatchingStatements.push_back(I);
1345
5
    InMatchingStatement = true;
1346
5
  } else {
1347
5
    MatchingStatements.push_back(nullptr);
1348
5
    InMatchingStatement = false;
1349
5
  }
1350
1351
10
  return true;
1352
10
}
1353
1354
// Preliminary support for conditional operators.
1355
bool PluralMisuseChecker::MethodCrawler::TraverseConditionalOperator(
1356
1
    ConditionalOperator *C) {
1357
1
  RecursiveASTVisitor<MethodCrawler>::TraverseConditionalOperator(C);
1358
1
  MatchingStatements.pop_back();
1359
1
  if (!MatchingStatements.empty()) {
1360
1
    if (MatchingStatements.back() != nullptr)
1361
0
      InMatchingStatement = true;
1362
1
    else
1363
1
      InMatchingStatement = false;
1364
0
  } else {
1365
0
    InMatchingStatement = false;
1366
0
  }
1367
1
  return true;
1368
1
}
1369
1370
bool PluralMisuseChecker::MethodCrawler::VisitConditionalOperator(
1371
1
    const ConditionalOperator *C) {
1372
1
  const Expr *Condition = C->getCond()->IgnoreParenImpCasts();
1373
1
  if (isCheckingPlurality(Condition)) {
1374
1
    MatchingStatements.push_back(C);
1375
1
    InMatchingStatement = true;
1376
0
  } else {
1377
0
    MatchingStatements.push_back(nullptr);
1378
0
    InMatchingStatement = false;
1379
0
  }
1380
1
  return true;
1381
1
}
1382
1383
void PluralMisuseChecker::MethodCrawler::reportPluralMisuseError(
1384
12
    const Stmt *S) const {
1385
  // Generate the bug report.
1386
12
  BR.EmitBasicReport(AC->getDecl(), Checker, "Plural Misuse",
1387
12
                     "Localizability Issue (Apple)",
1388
12
                     "Plural cases are not supported across all languages. "
1389
12
                     "Use a .stringsdict file instead",
1390
12
                     PathDiagnosticLocation(S, BR.getSourceManager(), AC));
1391
12
}
1392
1393
//===----------------------------------------------------------------------===//
1394
// Checker registration.
1395
//===----------------------------------------------------------------------===//
1396
1397
2
void ento::registerNonLocalizedStringChecker(CheckerManager &mgr) {
1398
2
  NonLocalizedStringChecker *checker =
1399
2
      mgr.registerChecker<NonLocalizedStringChecker>();
1400
2
  checker->IsAggressive =
1401
2
      mgr.getAnalyzerOptions().getCheckerBooleanOption(
1402
2
          checker, "AggressiveReport");
1403
2
}
1404
1405
4
bool ento::shouldRegisterNonLocalizedStringChecker(const CheckerManager &mgr) {
1406
4
  return true;
1407
4
}
1408
1409
1
void ento::registerEmptyLocalizationContextChecker(CheckerManager &mgr) {
1410
1
  mgr.registerChecker<EmptyLocalizationContextChecker>();
1411
1
}
1412
1413
bool ento::shouldRegisterEmptyLocalizationContextChecker(
1414
2
                                                    const CheckerManager &mgr) {
1415
2
  return true;
1416
2
}
1417
1418
1
void ento::registerPluralMisuseChecker(CheckerManager &mgr) {
1419
1
  mgr.registerChecker<PluralMisuseChecker>();
1420
1
}
1421
1422
2
bool ento::shouldRegisterPluralMisuseChecker(const CheckerManager &mgr) {
1423
2
  return true;
1424
2
}