12#include "clang/AST/ASTContext.h"
13#include "clang/AST/RecursiveASTVisitor.h"
14#include "clang/ASTMatchers/ASTMatchFinder.h"
15#include "clang/Lex/Lexer.h"
25 const Type *DesugaredType = Node.getUnqualifiedDesugaredType();
26 if (
const auto *BT = dyn_cast<BuiltinType>(DesugaredType))
27 return BT->getKind() == BuiltinType::NullPtr;
48static StatementMatcher
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(
59 auto IsOrHasDescendant = [](
const auto &InnerMatcher) {
60 return anyOf(InnerMatcher, hasDescendant(InnerMatcher));
65 anyOf(castExpr(anyOf(ImplicitCastToNull,
66 explicitCastExpr(hasDescendant(ImplicitCastToNull))),
67 unless(hasAncestor(explicitCastExpr())),
68 unless(hasAncestor(cxxRewrittenBinaryOperator())))
70 cxxRewrittenBinaryOperator(
74 expr().bind(
"matchBinopOperands"),
75 hasEitherOperand(IsOrHasDescendant(
78 hasAncestor(cxxRewrittenBinaryOperator().bind(
79 "checkBinopOperands")))
82 unless(hasAncestor(functionDecl(isDefaulted()))))));
86 const SourceManager &SM) {
87 return SM.isWrittenInSameFile(StartLoc, EndLoc);
94 SourceLocation StartLoc, SourceLocation EndLoc) {
95 CharSourceRange Range(SourceRange(StartLoc, EndLoc),
true);
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");
113 const SourceManager &SM,
114 const LangOptions &LO) {
115 assert(Loc.isMacroID());
116 SourceLocation OutermostMacroLoc;
118 while (Loc.isMacroID()) {
119 OutermostMacroLoc = Loc;
120 Loc = SM.getImmediateMacroCallerLoc(Loc);
123 return Lexer::getImmediateMacroName(OutermostMacroLoc, SM, LO);
131class MacroArgUsageVisitor :
public RecursiveASTVisitor<MacroArgUsageVisitor> {
133 MacroArgUsageVisitor(SourceLocation CastLoc,
const SourceManager &SM)
134 : CastLoc(CastLoc), SM(SM) {
135 assert(CastLoc.isFileID());
138 bool TraverseStmt(Stmt *S) {
139 bool VisitedPreviously = Visited;
141 if (!RecursiveASTVisitor<MacroArgUsageVisitor>::TraverseStmt(S))
148 if (!VisitedPreviously) {
149 if (Visited && !CastFound) {
163 bool VisitStmt(Stmt *S) {
164 if (SM.getFileLoc(S->getBeginLoc()) != CastLoc)
168 const ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(S);
169 if (Cast && (Cast->getCastKind() == CK_NullToPointer ||
170 Cast->getCastKind() == CK_NullToMemberPointer))
176 bool TraverseInitListExpr(InitListExpr *S) {
181 return RecursiveASTVisitor<MacroArgUsageVisitor>::
182 TraverseSynOrSemInitListExpr(
183 S->isSemanticForm() ? S : S->getSemanticForm());
186 bool foundInvalid()
const {
return InvalidFound; }
189 SourceLocation CastLoc;
190 const SourceManager &SM;
192 bool Visited =
false;
193 bool CastFound =
false;
194 bool InvalidFound =
false;
208class CastSequenceVisitor :
public RecursiveASTVisitor<CastSequenceVisitor> {
210 CastSequenceVisitor(ASTContext &Context, ArrayRef<StringRef> NullMacros,
211 ClangTidyCheck &Check)
212 : SM(Context.getSourceManager()), Context(Context),
213 NullMacros(NullMacros), Check(Check) {}
215 bool TraverseStmt(Stmt *S) {
218 PruneSubtree =
false;
221 return RecursiveASTVisitor<CastSequenceVisitor>::TraverseStmt(S);
226 bool VisitStmt(Stmt *S) {
227 auto *
C = dyn_cast<CastExpr>(S);
229 if (
auto *E = dyn_cast<CXXDefaultArgExpr>(S)) {
230 C = dyn_cast<CastExpr>(E->getExpr());
231 FirstSubExpr =
nullptr;
234 FirstSubExpr =
nullptr;
238 auto *CastSubExpr =
C->getSubExpr()->IgnoreParens();
240 if (isa<CXXNullPtrLiteralExpr>(CastSubExpr)) {
245 FirstSubExpr = CastSubExpr;
247 if (
C->getCastKind() != CK_NullToPointer &&
248 C->getCastKind() != CK_NullToMemberPointer) {
252 SourceLocation StartLoc = FirstSubExpr->getBeginLoc();
253 SourceLocation EndLoc = FirstSubExpr->getEndLoc();
260 if (SM.isMacroArgExpansion(StartLoc) && SM.isMacroArgExpansion(EndLoc)) {
261 SourceLocation FileLocStart = SM.getFileLoc(StartLoc),
262 FileLocEnd = SM.getFileLoc(EndLoc);
263 SourceLocation ImmediateMacroArgLoc, MacroLoc;
265 if (!getMacroAndArgLocations(StartLoc, ImmediateMacroArgLoc, MacroLoc) ||
266 ImmediateMacroArgLoc != FileLocStart)
267 return skipSubTree();
270 allArgUsesValid(C)) {
276 if (SM.isMacroBodyExpansion(StartLoc) && SM.isMacroBodyExpansion(EndLoc)) {
277 StringRef OutermostMacroName =
281 if (!llvm::is_contained(NullMacros, OutermostMacroName))
282 return skipSubTree();
284 StartLoc = SM.getFileLoc(StartLoc);
285 EndLoc = SM.getFileLoc(EndLoc);
289 return skipSubTree();
304 bool allArgUsesValid(
const CastExpr *CE) {
305 SourceLocation CastLoc = CE->getBeginLoc();
309 SourceLocation ArgLoc, MacroLoc;
310 if (!getMacroAndArgLocations(CastLoc, ArgLoc, MacroLoc))
314 DynTypedNode ContainingAncestor;
315 if (!findContainingAncestor(DynTypedNode::create<Stmt>(*CE), MacroLoc,
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));
330 llvm_unreachable(
"Unhandled ContainingAncestor node type");
332 return !ArgUsageVisitor.foundInvalid();
343 bool getMacroAndArgLocations(SourceLocation Loc, SourceLocation &ArgLoc,
344 SourceLocation &MacroLoc) {
345 assert(Loc.isMacroID() &&
"Only reasonable to call this on macros");
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();
355 SourceLocation OldArgLoc = ArgLoc;
356 ArgLoc = Expansion.getExpansionLocStart();
357 if (!Expansion.isMacroArgExpansion()) {
358 if (!MacroLoc.isFileID())
362 Lexer::getImmediateMacroName(OldArgLoc, SM, Context.getLangOpts());
363 return llvm::is_contained(NullMacros, Name);
366 MacroLoc = SM.getExpansionRange(ArgLoc).getBegin();
368 ArgLoc = Expansion.getSpellingLoc().getLocWithOffset(LocInfo.second);
369 if (ArgLoc.isFileID())
374 FileID MacroFID = SM.getFileID(MacroLoc);
375 if (SM.isInFileID(ArgLoc, MacroFID)) {
382 llvm_unreachable(
"getMacroAndArgLocations");
396 bool expandsFrom(SourceLocation TestLoc, SourceLocation TestMacroLoc) {
397 if (TestLoc.isFileID()) {
401 SourceLocation Loc = TestLoc, MacroLoc;
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();
408 Loc = Expansion.getExpansionLocStart();
410 if (!Expansion.isMacroArgExpansion()) {
411 if (Loc.isFileID()) {
412 return Loc == TestMacroLoc;
421 MacroLoc = SM.getImmediateExpansionRange(Loc).getBegin();
422 if (MacroLoc.isFileID() && MacroLoc == TestMacroLoc) {
427 Loc = Expansion.getSpellingLoc().getLocWithOffset(LocInfo.second);
428 if (Loc.isFileID()) {
435 llvm_unreachable(
"expandsFrom");
443 bool findContainingAncestor(DynTypedNode Start, SourceLocation MacroLoc,
444 DynTypedNode &Result) {
449 assert(MacroLoc.isFileID());
452 const auto &
Parents = Context.getParents(Start);
460 for (
const auto &Parent : Parents) {
461 if (!Parent.get<InitListExpr>())
466 const DynTypedNode &Parent =
Parents[0];
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();
477 if (!expandsFrom(Loc, MacroLoc)) {
485 llvm_unreachable(
"findContainingAncestor");
490 ArrayRef<StringRef> NullMacros;
491 ClangTidyCheck &Check;
492 Expr *FirstSubExpr =
nullptr;
493 bool PruneSubtree =
false;
500 NullMacrosStr(Options.get(
"NullMacros",
"NULL")),
501 IgnoredTypes(
utils::options::parseStringList(Options.get(
502 "IgnoredTypes",
"_CmpUnspecifiedParam;^std::__cmp_cat::__unspec"))) {
503 NullMacrosStr.split(NullMacros,
",");
507 Options.store(Opts,
"NullMacros", NullMacrosStr);
508 Options.store(Opts,
"IgnoredTypes",
517 const auto *NullCast = Result.Nodes.getNodeAs<CastExpr>(
CastSequence);
518 assert(NullCast &&
"Bad Callback. No node provided");
520 if (Result.Nodes.getNodeAs<CXXRewrittenBinaryOperator>(
521 "matchBinopOperands") !=
522 Result.Nodes.getNodeAs<CXXRewrittenBinaryOperator>(
"checkBinopOperands"))
528 CastSequenceVisitor(*Result.Context, NullMacros, *
this)
529 .TraverseStmt(
const_cast<CastExpr *
>(NullCast));
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.
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.
llvm::StringMap< ClangTidyValue > OptionMap