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