clang-tools  3.9.0
UseNullptrCheck.cpp
Go to the documentation of this file.
1 //===--- UseNullptrCheck.cpp - clang-tidy----------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "UseNullptrCheck.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/AST/RecursiveASTVisitor.h"
13 #include "clang/ASTMatchers/ASTMatchFinder.h"
14 #include "clang/Lex/Lexer.h"
15 
16 using namespace clang;
17 using namespace clang::ast_matchers;
18 using namespace llvm;
19 
20 namespace clang {
21 namespace tidy {
22 namespace modernize {
23 namespace {
24 
25 const char CastSequence[] = "sequence";
26 
27 AST_MATCHER(Type, sugaredNullptrType) {
28  const Type *DesugaredType = Node.getUnqualifiedDesugaredType();
29  if (const BuiltinType *BT = dyn_cast<BuiltinType>(DesugaredType))
30  return BT->getKind() == BuiltinType::NullPtr;
31  return false;
32 }
33 
34 /// \brief Create a matcher that finds implicit casts as well as the head of a
35 /// sequence of zero or more nested explicit casts that have an implicit cast
36 /// to null within.
37 /// Finding sequences of explict casts is necessary so that an entire sequence
38 /// can be replaced instead of just the inner-most implicit cast.
39 StatementMatcher makeCastSequenceMatcher() {
40  StatementMatcher ImplicitCastToNull = implicitCastExpr(
41  anyOf(hasCastKind(CK_NullToPointer),
42  hasCastKind(CK_NullToMemberPointer)),
43  unless(hasSourceExpression(hasType(sugaredNullptrType()))));
44 
45  return castExpr(anyOf(ImplicitCastToNull,
46  explicitCastExpr(hasDescendant(ImplicitCastToNull))),
47  unless(hasAncestor(explicitCastExpr())))
48  .bind(CastSequence);
49 }
50 
51 bool isReplaceableRange(SourceLocation StartLoc, SourceLocation EndLoc,
52  const SourceManager &SM) {
53  return SM.isWrittenInSameFile(StartLoc, EndLoc);
54 }
55 
56 /// \brief Replaces the provided range with the text "nullptr", but only if
57 /// the start and end location are both in main file.
58 /// Returns true if and only if a replacement was made.
59 void replaceWithNullptr(ClangTidyCheck &Check, SourceManager &SM,
60  SourceLocation StartLoc, SourceLocation EndLoc) {
61  CharSourceRange Range(SourceRange(StartLoc, EndLoc), true);
62  // Add a space if nullptr follows an alphanumeric character. This happens
63  // whenever there is an c-style explicit cast to nullptr not surrounded by
64  // parentheses and right beside a return statement.
65  SourceLocation PreviousLocation = StartLoc.getLocWithOffset(-1);
66  bool NeedsSpace = isAlphanumeric(*SM.getCharacterData(PreviousLocation));
67  Check.diag(Range.getBegin(), "use nullptr") << FixItHint::CreateReplacement(
68  Range, NeedsSpace ? " nullptr" : "nullptr");
69 }
70 
71 /// \brief Returns the name of the outermost macro.
72 ///
73 /// Given
74 /// \code
75 /// #define MY_NULL NULL
76 /// \endcode
77 /// If \p Loc points to NULL, this function will return the name MY_NULL.
78 StringRef getOutermostMacroName(SourceLocation Loc, const SourceManager &SM,
79  const LangOptions &LO) {
80  assert(Loc.isMacroID());
81  SourceLocation OutermostMacroLoc;
82 
83  while (Loc.isMacroID()) {
84  OutermostMacroLoc = Loc;
85  Loc = SM.getImmediateMacroCallerLoc(Loc);
86  }
87 
88  return Lexer::getImmediateMacroName(OutermostMacroLoc, SM, LO);
89 }
90 
91 /// \brief RecursiveASTVisitor for ensuring all nodes rooted at a given AST
92 /// subtree that have file-level source locations corresponding to a macro
93 /// argument have implicit NullTo(Member)Pointer nodes as ancestors.
94 class MacroArgUsageVisitor : public RecursiveASTVisitor<MacroArgUsageVisitor> {
95 public:
96  MacroArgUsageVisitor(SourceLocation CastLoc, const SourceManager &SM)
97  : CastLoc(CastLoc), SM(SM), Visited(false), CastFound(false),
98  InvalidFound(false) {
99  assert(CastLoc.isFileID());
100  }
101 
102  bool TraverseStmt(Stmt *S) {
103  bool VisitedPreviously = Visited;
104 
105  if (!RecursiveASTVisitor<MacroArgUsageVisitor>::TraverseStmt(S))
106  return false;
107 
108  // The point at which VisitedPreviously is false and Visited is true is the
109  // root of a subtree containing nodes whose locations match CastLoc. It's
110  // at this point we test that the Implicit NullTo(Member)Pointer cast was
111  // found or not.
112  if (!VisitedPreviously) {
113  if (Visited && !CastFound) {
114  // Found nodes with matching SourceLocations but didn't come across a
115  // cast. This is an invalid macro arg use. Can stop traversal
116  // completely now.
117  InvalidFound = true;
118  return false;
119  }
120  // Reset state as we unwind back up the tree.
121  CastFound = false;
122  Visited = false;
123  }
124  return true;
125  }
126 
127  bool VisitStmt(Stmt *S) {
128  if (SM.getFileLoc(S->getLocStart()) != CastLoc)
129  return true;
130  Visited = true;
131 
132  const ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(S);
133  if (Cast && (Cast->getCastKind() == CK_NullToPointer ||
134  Cast->getCastKind() == CK_NullToMemberPointer))
135  CastFound = true;
136 
137  return true;
138  }
139 
140  bool TraverseInitListExpr(InitListExpr *S) {
141  // Only go through the semantic form of the InitListExpr, because
142  // ImplicitCast might not appear in the syntactic form, and this results in
143  // finding usages of the macro argument that don't have a ImplicitCast as an
144  // ancestor (thus invalidating the replacement) when they actually have.
145  return RecursiveASTVisitor<MacroArgUsageVisitor>::
146  TraverseSynOrSemInitListExpr(
147  S->isSemanticForm() ? S : S->getSemanticForm());
148  }
149 
150  bool foundInvalid() const { return InvalidFound; }
151 
152 private:
153  SourceLocation CastLoc;
154  const SourceManager &SM;
155 
156  bool Visited;
157  bool CastFound;
159 };
160 
161 /// \brief Looks for implicit casts as well as sequences of 0 or more explicit
162 /// casts with an implicit null-to-pointer cast within.
163 ///
164 /// The matcher this visitor is used with will find a single implicit cast or a
165 /// top-most explicit cast (i.e. it has no explicit casts as an ancestor) where
166 /// an implicit cast is nested within. However, there is no guarantee that only
167 /// explicit casts exist between the found top-most explicit cast and the
168 /// possibly more than one nested implicit cast. This visitor finds all cast
169 /// sequences with an implicit cast to null within and creates a replacement
170 /// leaving the outermost explicit cast unchanged to avoid introducing
171 /// ambiguities.
172 class CastSequenceVisitor : public RecursiveASTVisitor<CastSequenceVisitor> {
173 public:
174  CastSequenceVisitor(ASTContext &Context, ArrayRef<StringRef> NullMacros,
175  ClangTidyCheck &check)
176  : SM(Context.getSourceManager()), Context(Context),
177  NullMacros(NullMacros), Check(check), FirstSubExpr(nullptr),
178  PruneSubtree(false) {}
179 
180  bool TraverseStmt(Stmt *S) {
181  // Stop traversing down the tree if requested.
182  if (PruneSubtree) {
183  PruneSubtree = false;
184  return true;
185  }
186  return RecursiveASTVisitor<CastSequenceVisitor>::TraverseStmt(S);
187  }
188 
189  // Only VisitStmt is overridden as we shouldn't find other base AST types
190  // within a cast expression.
191  bool VisitStmt(Stmt *S) {
192  CastExpr *C = dyn_cast<CastExpr>(S);
193  if (!C) {
194  FirstSubExpr = nullptr;
195  return true;
196  }
197  if (!FirstSubExpr)
198  FirstSubExpr = C->getSubExpr()->IgnoreParens();
199 
200  if (C->getCastKind() != CK_NullToPointer &&
201  C->getCastKind() != CK_NullToMemberPointer) {
202  return true;
203  }
204 
205  SourceLocation StartLoc = FirstSubExpr->getLocStart();
206  SourceLocation EndLoc = FirstSubExpr->getLocEnd();
207 
208  // If the location comes from a macro arg expansion, *all* uses of that
209  // arg must be checked to result in NullTo(Member)Pointer casts.
210  //
211  // If the location comes from a macro body expansion, check to see if its
212  // coming from one of the allowed 'NULL' macros.
213  if (SM.isMacroArgExpansion(StartLoc) && SM.isMacroArgExpansion(EndLoc)) {
214  SourceLocation FileLocStart = SM.getFileLoc(StartLoc),
215  FileLocEnd = SM.getFileLoc(EndLoc);
216  SourceLocation ImmediateMarcoArgLoc, MacroLoc;
217  // Skip NULL macros used in macro.
218  if (!getMacroAndArgLocations(StartLoc, ImmediateMarcoArgLoc, MacroLoc) ||
219  ImmediateMarcoArgLoc != FileLocStart)
220  return skipSubTree();
221 
222  if (isReplaceableRange(FileLocStart, FileLocEnd, SM) &&
223  allArgUsesValid(C)) {
224  replaceWithNullptr(Check, SM, FileLocStart, FileLocEnd);
225  }
226  return skipSubTree();
227  }
228 
229  if (SM.isMacroBodyExpansion(StartLoc) && SM.isMacroBodyExpansion(EndLoc)) {
230  StringRef OutermostMacroName =
231  getOutermostMacroName(StartLoc, SM, Context.getLangOpts());
232 
233  // Check to see if the user wants to replace the macro being expanded.
234  if (std::find(NullMacros.begin(), NullMacros.end(), OutermostMacroName) ==
235  NullMacros.end()) {
236  return skipSubTree();
237  }
238 
239  StartLoc = SM.getFileLoc(StartLoc);
240  EndLoc = SM.getFileLoc(EndLoc);
241  }
242 
243  if (!isReplaceableRange(StartLoc, EndLoc, SM)) {
244  return skipSubTree();
245  }
246  replaceWithNullptr(Check, SM, StartLoc, EndLoc);
247 
248  return true;
249  }
250 
251 private:
252  bool skipSubTree() {
253  PruneSubtree = true;
254  return true;
255  }
256 
257  /// \brief Tests that all expansions of a macro arg, one of which expands to
258  /// result in \p CE, yield NullTo(Member)Pointer casts.
259  bool allArgUsesValid(const CastExpr *CE) {
260  SourceLocation CastLoc = CE->getLocStart();
261 
262  // Step 1: Get location of macro arg and location of the macro the arg was
263  // provided to.
264  SourceLocation ArgLoc, MacroLoc;
265  if (!getMacroAndArgLocations(CastLoc, ArgLoc, MacroLoc))
266  return false;
267 
268  // Step 2: Find the first ancestor that doesn't expand from this macro.
269  ast_type_traits::DynTypedNode ContainingAncestor;
270  if (!findContainingAncestor(
271  ast_type_traits::DynTypedNode::create<Stmt>(*CE), MacroLoc,
272  ContainingAncestor))
273  return false;
274 
275  // Step 3:
276  // Visit children of this containing parent looking for the least-descended
277  // nodes of the containing parent which are macro arg expansions that expand
278  // from the given arg location.
279  // Visitor needs: arg loc.
280  MacroArgUsageVisitor ArgUsageVisitor(SM.getFileLoc(CastLoc), SM);
281  if (const auto *D = ContainingAncestor.get<Decl>())
282  ArgUsageVisitor.TraverseDecl(const_cast<Decl *>(D));
283  else if (const auto *S = ContainingAncestor.get<Stmt>())
284  ArgUsageVisitor.TraverseStmt(const_cast<Stmt *>(S));
285  else
286  llvm_unreachable("Unhandled ContainingAncestor node type");
287 
288  return !ArgUsageVisitor.foundInvalid();
289  }
290 
291  /// \brief Given the SourceLocation for a macro arg expansion, finds the
292  /// non-macro SourceLocation of the macro the arg was passed to and the
293  /// non-macro SourceLocation of the argument in the arg list to that macro.
294  /// These results are returned via \c MacroLoc and \c ArgLoc respectively.
295  /// These values are undefined if the return value is false.
296  ///
297  /// \returns false if one of the returned SourceLocations would be a
298  /// SourceLocation pointing within the definition of another macro.
299  bool getMacroAndArgLocations(SourceLocation Loc, SourceLocation &ArgLoc,
300  SourceLocation &MacroLoc) {
301  assert(Loc.isMacroID() && "Only reasonble to call this on macros");
302 
303  ArgLoc = Loc;
304 
305  // Find the location of the immediate macro expansion.
306  while (true) {
307  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(ArgLoc);
308  const SrcMgr::SLocEntry *E = &SM.getSLocEntry(LocInfo.first);
309  const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
310 
311  SourceLocation OldArgLoc = ArgLoc;
312  ArgLoc = Expansion.getExpansionLocStart();
313  if (!Expansion.isMacroArgExpansion()) {
314  if (!MacroLoc.isFileID())
315  return false;
316 
317  StringRef Name =
318  Lexer::getImmediateMacroName(OldArgLoc, SM, Context.getLangOpts());
319  return std::find(NullMacros.begin(), NullMacros.end(), Name) !=
320  NullMacros.end();
321  }
322 
323  MacroLoc = SM.getExpansionRange(ArgLoc).first;
324 
325  ArgLoc = Expansion.getSpellingLoc().getLocWithOffset(LocInfo.second);
326  if (ArgLoc.isFileID())
327  return true;
328 
329  // If spelling location resides in the same FileID as macro expansion
330  // location, it means there is no inner macro.
331  FileID MacroFID = SM.getFileID(MacroLoc);
332  if (SM.isInFileID(ArgLoc, MacroFID)) {
333  // Don't transform this case. If the characters that caused the
334  // null-conversion come from within a macro, they can't be changed.
335  return false;
336  }
337  }
338 
339  llvm_unreachable("getMacroAndArgLocations");
340  }
341 
342  /// \brief Tests if TestMacroLoc is found while recursively unravelling
343  /// expansions starting at TestLoc. TestMacroLoc.isFileID() must be true.
344  /// Implementation is very similar to getMacroAndArgLocations() except in this
345  /// case, it's not assumed that TestLoc is expanded from a macro argument.
346  /// While unravelling expansions macro arguments are handled as with
347  /// getMacroAndArgLocations() but in this function macro body expansions are
348  /// also handled.
349  ///
350  /// False means either:
351  /// - TestLoc is not from a macro expansion.
352  /// - TestLoc is from a different macro expansion.
353  bool expandsFrom(SourceLocation TestLoc, SourceLocation TestMacroLoc) {
354  if (TestLoc.isFileID()) {
355  return false;
356  }
357 
358  SourceLocation Loc = TestLoc, MacroLoc;
359 
360  while (true) {
361  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
362  const SrcMgr::SLocEntry *E = &SM.getSLocEntry(LocInfo.first);
363  const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
364 
365  Loc = Expansion.getExpansionLocStart();
366 
367  if (!Expansion.isMacroArgExpansion()) {
368  if (Loc.isFileID()) {
369  return Loc == TestMacroLoc;
370  }
371  // Since Loc is still a macro ID and it's not an argument expansion, we
372  // don't need to do the work of handling an argument expansion. Simply
373  // keep recursively expanding until we hit a FileID or a macro arg
374  // expansion or a macro arg expansion.
375  continue;
376  }
377 
378  MacroLoc = SM.getImmediateExpansionRange(Loc).first;
379  if (MacroLoc.isFileID() && MacroLoc == TestMacroLoc) {
380  // Match made.
381  return true;
382  }
383 
384  Loc = Expansion.getSpellingLoc().getLocWithOffset(LocInfo.second);
385  if (Loc.isFileID()) {
386  // If we made it this far without finding a match, there is no match to
387  // be made.
388  return false;
389  }
390  }
391 
392  llvm_unreachable("expandsFrom");
393  }
394 
395  /// \brief Given a starting point \c Start in the AST, find an ancestor that
396  /// doesn't expand from the macro called at file location \c MacroLoc.
397  ///
398  /// \pre MacroLoc.isFileID()
399  /// \returns true if such an ancestor was found, false otherwise.
400  bool findContainingAncestor(ast_type_traits::DynTypedNode Start,
401  SourceLocation MacroLoc,
402  ast_type_traits::DynTypedNode &Result) {
403  // Below we're only following the first parent back up the AST. This should
404  // be fine since for the statements we care about there should only be one
405  // parent, except for the case specified below.
406 
407  assert(MacroLoc.isFileID());
408 
409  while (true) {
410  const auto &Parents = Context.getParents(Start);
411  if (Parents.empty())
412  return false;
413  if (Parents.size() > 1) {
414  // If there are more than one parents, don't do the replacement unless
415  // they are InitListsExpr (semantic and syntactic form). In this case we
416  // can choose any one here, and the ASTVisitor will take care of
417  // traversing the right one.
418  for (const auto &Parent : Parents) {
419  if (!Parent.get<InitListExpr>())
420  return false;
421  }
422  }
423 
424  const ast_type_traits::DynTypedNode &Parent = Parents[0];
425 
426  SourceLocation Loc;
427  if (const auto *D = Parent.get<Decl>())
428  Loc = D->getLocStart();
429  else if (const auto *S = Parent.get<Stmt>())
430  Loc = S->getLocStart();
431 
432  // TypeLoc and NestedNameSpecifierLoc are members of the parent map. Skip
433  // them and keep going up.
434  if (Loc.isValid()) {
435  if (!expandsFrom(Loc, MacroLoc)) {
436  Result = Parent;
437  return true;
438  }
439  }
440  Start = Parent;
441  }
442 
443  llvm_unreachable("findContainingAncestor");
444  }
445 
446 private:
447  SourceManager &SM;
448  ASTContext &Context;
449  ArrayRef<StringRef> NullMacros;
450  ClangTidyCheck &Check;
453 };
454 
455 } // namespace
456 
457 UseNullptrCheck::UseNullptrCheck(StringRef Name, ClangTidyContext *Context)
458  : ClangTidyCheck(Name, Context),
459  NullMacrosStr(Options.get("NullMacros", "")) {
460  StringRef(NullMacrosStr).split(NullMacros, ",");
461 }
462 
464  Options.store(Opts, "NullMacros", NullMacrosStr);
465 }
466 
468  // Only register the matcher for C++. Because this checker is used for
469  // modernization, it is reasonable to run it on any C++ standard with the
470  // assumption the user is trying to modernize their codebase.
471  if (getLangOpts().CPlusPlus)
472  Finder->addMatcher(makeCastSequenceMatcher(), this);
473 }
474 
475 void UseNullptrCheck::check(const MatchFinder::MatchResult &Result) {
476  const auto *NullCast = Result.Nodes.getNodeAs<CastExpr>(CastSequence);
477  assert(NullCast && "Bad Callback. No node provided");
478 
479  // Given an implicit null-ptr cast or an explicit cast with an implicit
480  // null-to-pointer cast within use CastSequenceVisitor to identify sequences
481  // of explicit casts that can be converted into 'nullptr'.
482  CastSequenceVisitor(*Result.Context, NullMacros, *this)
483  .TraverseStmt(const_cast<CastExpr *>(NullCast));
484 }
485 
486 } // namespace modernize
487 } // namespace tidy
488 } // namespace clang
SourceLocation Loc
'#' location in the include directive
AST_MATCHER(Type, isStrictlyInteger)
const std::string Name
Definition: USRFinder.cpp:140
LangOptions getLangOpts() const
Returns the language options from the context.
Definition: ClangTidy.h:170
ASTContext & Context
std::unique_ptr< ast_matchers::MatchFinder > Finder
Definition: ClangTidy.cpp:210
Base class for all clang-tidy checks.
Definition: ClangTidy.h:110
bool CastFound
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
const SourceManager & SM
bool Visited
bool InvalidFound
bool PruneSubtree
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Definition: ClangTidy.cpp:385
std::map< std::string, std::string > OptionMap
Expr * FirstSubExpr
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
CharSourceRange Range
SourceRange for the file name.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
ClangTidyCheck & Check
const NamedDecl * Result
Definition: USRFinder.cpp:137
ArrayRef< StringRef > NullMacros
SourceLocation CastLoc