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