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 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 SourceLocation PreviousLocation = StartLoc.getLocWithOffset(-1);
100 bool NeedsSpace = isAlphanumeric(*SM.getCharacterData(PreviousLocation));
101 Check.diag(Range.getBegin(), "use nullptr") << FixItHint::CreateReplacement(
102 Range, NeedsSpace ? " nullptr" : "nullptr");
103}
104
105/// Returns the name of the outermost macro.
106///
107/// Given
108/// \code
109/// #define MY_NULL NULL
110/// \endcode
111/// If \p Loc points to NULL, this function will return the name MY_NULL.
112static StringRef getOutermostMacroName(SourceLocation Loc,
113 const SourceManager &SM,
114 const LangOptions &LO) {
115 assert(Loc.isMacroID());
116 SourceLocation OutermostMacroLoc;
117
118 while (Loc.isMacroID()) {
119 OutermostMacroLoc = Loc;
120 Loc = SM.getImmediateMacroCallerLoc(Loc);
121 }
122
123 return Lexer::getImmediateMacroName(OutermostMacroLoc, SM, LO);
124}
125
126namespace {
127
128/// RecursiveASTVisitor for ensuring all nodes rooted at a given AST
129/// subtree that have file-level source locations corresponding to a macro
130/// argument have implicit NullTo(Member)Pointer nodes as ancestors.
131class MacroArgUsageVisitor : public RecursiveASTVisitor<MacroArgUsageVisitor> {
132public:
133 MacroArgUsageVisitor(SourceLocation CastLoc, const SourceManager &SM)
134 : CastLoc(CastLoc), SM(SM) {
135 assert(CastLoc.isFileID());
136 }
137
138 bool TraverseStmt(Stmt *S) {
139 bool VisitedPreviously = Visited;
140
141 if (!RecursiveASTVisitor<MacroArgUsageVisitor>::TraverseStmt(S))
142 return false;
143
144 // The point at which VisitedPreviously is false and Visited is true is the
145 // root of a subtree containing nodes whose locations match CastLoc. It's
146 // at this point we test that the Implicit NullTo(Member)Pointer cast was
147 // found or not.
148 if (!VisitedPreviously) {
149 if (Visited && !CastFound) {
150 // Found nodes with matching SourceLocations but didn't come across a
151 // cast. This is an invalid macro arg use. Can stop traversal
152 // completely now.
153 InvalidFound = true;
154 return false;
155 }
156 // Reset state as we unwind back up the tree.
157 CastFound = false;
158 Visited = false;
159 }
160 return true;
161 }
162
163 bool VisitStmt(Stmt *S) {
164 if (SM.getFileLoc(S->getBeginLoc()) != CastLoc)
165 return true;
166 Visited = true;
167
168 const ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(S);
169 if (Cast && (Cast->getCastKind() == CK_NullToPointer ||
170 Cast->getCastKind() == CK_NullToMemberPointer))
171 CastFound = true;
172
173 return true;
174 }
175
176 bool TraverseInitListExpr(InitListExpr *S) {
177 // Only go through the semantic form of the InitListExpr, because
178 // ImplicitCast might not appear in the syntactic form, and this results in
179 // finding usages of the macro argument that don't have a ImplicitCast as an
180 // ancestor (thus invalidating the replacement) when they actually have.
181 return RecursiveASTVisitor<MacroArgUsageVisitor>::
182 TraverseSynOrSemInitListExpr(
183 S->isSemanticForm() ? S : S->getSemanticForm());
184 }
185
186 bool foundInvalid() const { return InvalidFound; }
187
188private:
189 SourceLocation CastLoc;
190 const SourceManager &SM;
191
192 bool Visited = false;
193 bool CastFound = false;
194 bool InvalidFound = false;
195};
196
197/// Looks for implicit casts as well as sequences of 0 or more explicit
198/// casts with an implicit null-to-pointer cast within.
199///
200/// The matcher this visitor is used with will find a single implicit cast or a
201/// top-most explicit cast (i.e. it has no explicit casts as an ancestor) where
202/// an implicit cast is nested within. However, there is no guarantee that only
203/// explicit casts exist between the found top-most explicit cast and the
204/// possibly more than one nested implicit cast. This visitor finds all cast
205/// sequences with an implicit cast to null within and creates a replacement
206/// leaving the outermost explicit cast unchanged to avoid introducing
207/// ambiguities.
208class CastSequenceVisitor : public RecursiveASTVisitor<CastSequenceVisitor> {
209public:
210 CastSequenceVisitor(ASTContext &Context, ArrayRef<StringRef> NullMacros,
211 ClangTidyCheck &Check)
212 : SM(Context.getSourceManager()), Context(Context),
213 NullMacros(NullMacros), Check(Check) {}
214
215 bool TraverseStmt(Stmt *S) {
216 // Stop traversing down the tree if requested.
217 if (PruneSubtree) {
218 PruneSubtree = false;
219 return true;
220 }
221 return RecursiveASTVisitor<CastSequenceVisitor>::TraverseStmt(S);
222 }
223
224 // Only VisitStmt is overridden as we shouldn't find other base AST types
225 // within a cast expression.
226 bool VisitStmt(Stmt *S) {
227 auto *C = dyn_cast<CastExpr>(S);
228 // Catch the castExpr inside cxxDefaultArgExpr.
229 if (auto *E = dyn_cast<CXXDefaultArgExpr>(S)) {
230 C = dyn_cast<CastExpr>(E->getExpr());
231 FirstSubExpr = nullptr;
232 }
233 if (!C) {
234 FirstSubExpr = nullptr;
235 return true;
236 }
237
238 auto *CastSubExpr = C->getSubExpr()->IgnoreParens();
239 // Ignore cast expressions which cast nullptr literal.
240 if (isa<CXXNullPtrLiteralExpr>(CastSubExpr)) {
241 return true;
242 }
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 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 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 }
291 replaceWithNullptr(Check, SM, StartLoc, EndLoc);
292
293 return true;
294 }
295
296private:
297 bool skipSubTree() {
298 PruneSubtree = true;
299 return true;
300 }
301
302 /// Tests that all expansions of a macro arg, one of which expands to
303 /// result in \p CE, yield NullTo(Member)Pointer casts.
304 bool allArgUsesValid(const CastExpr *CE) {
305 SourceLocation CastLoc = CE->getBeginLoc();
306
307 // Step 1: Get location of macro arg and location of the macro the arg was
308 // provided to.
309 SourceLocation ArgLoc, MacroLoc;
310 if (!getMacroAndArgLocations(CastLoc, ArgLoc, MacroLoc))
311 return false;
312
313 // Step 2: Find the first ancestor that doesn't expand from this macro.
314 DynTypedNode ContainingAncestor;
315 if (!findContainingAncestor(DynTypedNode::create<Stmt>(*CE), MacroLoc,
316 ContainingAncestor))
317 return false;
318
319 // Step 3:
320 // Visit children of this containing parent looking for the least-descended
321 // nodes of the containing parent which are macro arg expansions that expand
322 // from the given arg location.
323 // Visitor needs: arg loc.
324 MacroArgUsageVisitor ArgUsageVisitor(SM.getFileLoc(CastLoc), SM);
325 if (const auto *D = ContainingAncestor.get<Decl>())
326 ArgUsageVisitor.TraverseDecl(const_cast<Decl *>(D));
327 else if (const auto *S = ContainingAncestor.get<Stmt>())
328 ArgUsageVisitor.TraverseStmt(const_cast<Stmt *>(S));
329 else
330 llvm_unreachable("Unhandled ContainingAncestor node type");
331
332 return !ArgUsageVisitor.foundInvalid();
333 }
334
335 /// Given the SourceLocation for a macro arg expansion, finds the
336 /// non-macro SourceLocation of the macro the arg was passed to and the
337 /// non-macro SourceLocation of the argument in the arg list to that macro.
338 /// These results are returned via \c MacroLoc and \c ArgLoc respectively.
339 /// These values are undefined if the return value is false.
340 ///
341 /// \returns false if one of the returned SourceLocations would be a
342 /// SourceLocation pointing within the definition of another macro.
343 bool getMacroAndArgLocations(SourceLocation Loc, SourceLocation &ArgLoc,
344 SourceLocation &MacroLoc) {
345 assert(Loc.isMacroID() && "Only reasonable to call this on macros");
346
347 ArgLoc = Loc;
348
349 // Find the location of the immediate macro expansion.
350 while (true) {
351 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(ArgLoc);
352 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(LocInfo.first);
353 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
354
355 SourceLocation OldArgLoc = ArgLoc;
356 ArgLoc = Expansion.getExpansionLocStart();
357 if (!Expansion.isMacroArgExpansion()) {
358 if (!MacroLoc.isFileID())
359 return false;
360
361 StringRef Name =
362 Lexer::getImmediateMacroName(OldArgLoc, SM, Context.getLangOpts());
363 return llvm::is_contained(NullMacros, Name);
364 }
365
366 MacroLoc = SM.getExpansionRange(ArgLoc).getBegin();
367
368 ArgLoc = Expansion.getSpellingLoc().getLocWithOffset(LocInfo.second);
369 if (ArgLoc.isFileID())
370 return true;
371
372 // If spelling location resides in the same FileID as macro expansion
373 // location, it means there is no inner macro.
374 FileID MacroFID = SM.getFileID(MacroLoc);
375 if (SM.isInFileID(ArgLoc, MacroFID)) {
376 // Don't transform this case. If the characters that caused the
377 // null-conversion come from within a macro, they can't be changed.
378 return false;
379 }
380 }
381
382 llvm_unreachable("getMacroAndArgLocations");
383 }
384
385 /// Tests if TestMacroLoc is found while recursively unravelling
386 /// expansions starting at TestLoc. TestMacroLoc.isFileID() must be true.
387 /// Implementation is very similar to getMacroAndArgLocations() except in this
388 /// case, it's not assumed that TestLoc is expanded from a macro argument.
389 /// While unravelling expansions macro arguments are handled as with
390 /// getMacroAndArgLocations() but in this function macro body expansions are
391 /// also handled.
392 ///
393 /// False means either:
394 /// - TestLoc is not from a macro expansion.
395 /// - TestLoc is from a different macro expansion.
396 bool expandsFrom(SourceLocation TestLoc, SourceLocation TestMacroLoc) {
397 if (TestLoc.isFileID()) {
398 return false;
399 }
400
401 SourceLocation Loc = TestLoc, MacroLoc;
402
403 while (true) {
404 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
405 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(LocInfo.first);
406 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
407
408 Loc = Expansion.getExpansionLocStart();
409
410 if (!Expansion.isMacroArgExpansion()) {
411 if (Loc.isFileID()) {
412 return Loc == TestMacroLoc;
413 }
414 // Since Loc is still a macro ID and it's not an argument expansion, we
415 // don't need to do the work of handling an argument expansion. Simply
416 // keep recursively expanding until we hit a FileID or a macro arg
417 // expansion or a macro arg expansion.
418 continue;
419 }
420
421 MacroLoc = SM.getImmediateExpansionRange(Loc).getBegin();
422 if (MacroLoc.isFileID() && MacroLoc == TestMacroLoc) {
423 // Match made.
424 return true;
425 }
426
427 Loc = Expansion.getSpellingLoc().getLocWithOffset(LocInfo.second);
428 if (Loc.isFileID()) {
429 // If we made it this far without finding a match, there is no match to
430 // be made.
431 return false;
432 }
433 }
434
435 llvm_unreachable("expandsFrom");
436 }
437
438 /// Given a starting point \c Start in the AST, find an ancestor that
439 /// doesn't expand from the macro called at file location \c MacroLoc.
440 ///
441 /// \pre MacroLoc.isFileID()
442 /// \returns true if such an ancestor was found, false otherwise.
443 bool findContainingAncestor(DynTypedNode Start, SourceLocation MacroLoc,
444 DynTypedNode &Result) {
445 // Below we're only following the first parent back up the AST. This should
446 // be fine since for the statements we care about there should only be one
447 // parent, except for the case specified below.
448
449 assert(MacroLoc.isFileID());
450
451 while (true) {
452 const auto &Parents = Context.getParents(Start);
453 if (Parents.empty())
454 return false;
455 if (Parents.size() > 1) {
456 // If there are more than one parents, don't do the replacement unless
457 // they are InitListsExpr (semantic and syntactic form). In this case we
458 // can choose any one here, and the ASTVisitor will take care of
459 // traversing the right one.
460 for (const auto &Parent : Parents) {
461 if (!Parent.get<InitListExpr>())
462 return false;
463 }
464 }
465
466 const DynTypedNode &Parent = Parents[0];
467
468 SourceLocation Loc;
469 if (const auto *D = Parent.get<Decl>())
470 Loc = D->getBeginLoc();
471 else if (const auto *S = Parent.get<Stmt>())
472 Loc = S->getBeginLoc();
473
474 // TypeLoc and NestedNameSpecifierLoc are members of the parent map. Skip
475 // them and keep going up.
476 if (Loc.isValid()) {
477 if (!expandsFrom(Loc, MacroLoc)) {
478 Result = Parent;
479 return true;
480 }
481 }
482 Start = Parent;
483 }
484
485 llvm_unreachable("findContainingAncestor");
486 }
487
488 SourceManager &SM;
489 ASTContext &Context;
490 ArrayRef<StringRef> NullMacros;
491 ClangTidyCheck &Check;
492 Expr *FirstSubExpr = nullptr;
493 bool PruneSubtree = false;
494};
495
496} // namespace
497
499 : ClangTidyCheck(Name, Context),
500 NullMacrosStr(Options.get("NullMacros", "NULL")),
501 IgnoredTypes(utils::options::parseStringList(Options.get(
502 "IgnoredTypes", "_CmpUnspecifiedParam;^std::__cmp_cat::__unspec"))) {
503 NullMacrosStr.split(NullMacros, ",");
504}
505
507 Options.store(Opts, "NullMacros", NullMacrosStr);
508 Options.store(Opts, "IgnoredTypes",
510}
511
512void UseNullptrCheck::registerMatchers(MatchFinder *Finder) {
513 Finder->addMatcher(makeCastSequenceMatcher(IgnoredTypes), this);
514}
515
516void UseNullptrCheck::check(const MatchFinder::MatchResult &Result) {
517 const auto *NullCast = Result.Nodes.getNodeAs<CastExpr>(CastSequence);
518 assert(NullCast && "Bad Callback. No node provided");
519
520 if (Result.Nodes.getNodeAs<CXXRewrittenBinaryOperator>(
521 "matchBinopOperands") !=
522 Result.Nodes.getNodeAs<CXXRewrittenBinaryOperator>("checkBinopOperands"))
523 return;
524
525 // Given an implicit null-ptr cast or an explicit cast with an implicit
526 // null-to-pointer cast within use CastSequenceVisitor to identify sequences
527 // of explicit casts that can be converted into 'nullptr'.
528 CastSequenceVisitor(*Result.Context, NullMacros, *this)
529 .TraverseStmt(const_cast<CastExpr *>(NullCast));
530}
531
532} // 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:66
llvm::StringMap< ClangTidyValue > OptionMap