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 const CharSourceRange Range(SourceRange(StartLoc, EndLoc),
true);
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");
114 const SourceManager &SM,
115 const LangOptions &LO) {
116 assert(Loc.isMacroID());
117 SourceLocation OutermostMacroLoc;
119 while (Loc.isMacroID()) {
120 OutermostMacroLoc = Loc;
121 Loc = SM.getImmediateMacroCallerLoc(Loc);
124 return Lexer::getImmediateMacroName(OutermostMacroLoc, SM, LO);
132class MacroArgUsageVisitor :
public RecursiveASTVisitor<MacroArgUsageVisitor> {
134 MacroArgUsageVisitor(SourceLocation CastLoc,
const SourceManager &SM)
135 : CastLoc(CastLoc), SM(SM) {
136 assert(CastLoc.isFileID());
139 bool TraverseStmt(Stmt *S) {
140 const bool VisitedPreviously = Visited;
142 if (!RecursiveASTVisitor<MacroArgUsageVisitor>::TraverseStmt(S))
149 if (!VisitedPreviously) {
150 if (Visited && !CastFound) {
164 bool VisitStmt(Stmt *S) {
165 if (SM.getFileLoc(S->getBeginLoc()) != CastLoc)
169 const ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(S);
170 if (Cast && (Cast->getCastKind() == CK_NullToPointer ||
171 Cast->getCastKind() == CK_NullToMemberPointer))
177 bool TraverseInitListExpr(InitListExpr *S) {
182 return RecursiveASTVisitor<MacroArgUsageVisitor>::
183 TraverseSynOrSemInitListExpr(
184 S->isSemanticForm() ? S : S->getSemanticForm());
187 bool foundInvalid()
const {
return InvalidFound; }
190 SourceLocation CastLoc;
191 const SourceManager &SM;
193 bool Visited =
false;
194 bool CastFound =
false;
195 bool InvalidFound =
false;
209class CastSequenceVisitor :
public RecursiveASTVisitor<CastSequenceVisitor> {
211 CastSequenceVisitor(ASTContext &Context, ArrayRef<StringRef> NullMacros,
212 ClangTidyCheck &Check)
213 : SM(Context.getSourceManager()), Context(Context),
214 NullMacros(NullMacros), Check(Check) {}
216 bool TraverseStmt(Stmt *S) {
219 PruneSubtree =
false;
222 return RecursiveASTVisitor<CastSequenceVisitor>::TraverseStmt(S);
227 bool VisitStmt(Stmt *S) {
228 auto *
C = dyn_cast<CastExpr>(S);
230 if (
auto *E = dyn_cast<CXXDefaultArgExpr>(S)) {
231 C = dyn_cast<CastExpr>(E->getExpr());
232 FirstSubExpr =
nullptr;
235 FirstSubExpr =
nullptr;
239 auto *CastSubExpr =
C->getSubExpr()->IgnoreParens();
241 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 const 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 const 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();
303 bool allArgUsesValid(
const CastExpr *CE) {
304 const SourceLocation CastLoc = CE->getBeginLoc();
308 SourceLocation ArgLoc, MacroLoc;
309 if (!getMacroAndArgLocations(CastLoc, ArgLoc, MacroLoc))
313 DynTypedNode ContainingAncestor;
314 if (!findContainingAncestor(DynTypedNode::create<Stmt>(*CE), MacroLoc,
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));
329 llvm_unreachable(
"Unhandled ContainingAncestor node type");
331 return !ArgUsageVisitor.foundInvalid();
342 bool getMacroAndArgLocations(SourceLocation Loc, SourceLocation &ArgLoc,
343 SourceLocation &MacroLoc) {
344 assert(Loc.isMacroID() &&
"Only reasonable to call this on macros");
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();
354 const SourceLocation OldArgLoc = ArgLoc;
355 ArgLoc = Expansion.getExpansionLocStart();
356 if (!Expansion.isMacroArgExpansion()) {
357 if (!MacroLoc.isFileID())
360 const StringRef Name =
361 Lexer::getImmediateMacroName(OldArgLoc, SM, Context.getLangOpts());
362 return llvm::is_contained(NullMacros, Name);
365 MacroLoc = SM.getExpansionRange(ArgLoc).getBegin();
367 ArgLoc = Expansion.getSpellingLoc().getLocWithOffset(LocInfo.second);
368 if (ArgLoc.isFileID())
373 const FileID MacroFID = SM.getFileID(MacroLoc);
374 if (SM.isInFileID(ArgLoc, MacroFID)) {
381 llvm_unreachable(
"getMacroAndArgLocations");
395 bool expandsFrom(SourceLocation TestLoc, SourceLocation TestMacroLoc) {
396 if (TestLoc.isFileID())
399 SourceLocation Loc = TestLoc, MacroLoc;
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();
406 Loc = Expansion.getExpansionLocStart();
408 if (!Expansion.isMacroArgExpansion()) {
410 return Loc == TestMacroLoc;
418 MacroLoc = SM.getImmediateExpansionRange(Loc).getBegin();
419 if (MacroLoc.isFileID() && MacroLoc == TestMacroLoc) {
424 Loc = Expansion.getSpellingLoc().getLocWithOffset(LocInfo.second);
425 if (Loc.isFileID()) {
432 llvm_unreachable(
"expandsFrom");
440 bool findContainingAncestor(DynTypedNode Start, SourceLocation MacroLoc,
441 DynTypedNode &Result) {
446 assert(MacroLoc.isFileID());
449 const auto &
Parents = Context.getParents(Start);
457 for (
const auto &Parent : Parents)
458 if (!Parent.get<InitListExpr>())
462 const DynTypedNode &Parent =
Parents[0];
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();
473 if (!expandsFrom(Loc, MacroLoc)) {
481 llvm_unreachable(
"findContainingAncestor");
486 ArrayRef<StringRef> NullMacros;
487 ClangTidyCheck &Check;
488 Expr *FirstSubExpr =
nullptr;
489 bool PruneSubtree =
false;
496 NullMacrosStr(Options.get(
"NullMacros",
"NULL")),
497 IgnoredTypes(
utils::options::parseStringList(Options.get(
498 "IgnoredTypes",
"_CmpUnspecifiedParam;^std::__cmp_cat::__unspec"))) {
499 NullMacrosStr.split(NullMacros,
",");
503 Options.store(Opts,
"NullMacros", NullMacrosStr);
504 Options.store(Opts,
"IgnoredTypes",
513 const auto *NullCast = Result.Nodes.getNodeAs<CastExpr>(
CastSequence);
514 assert(NullCast &&
"Bad Callback. No node provided");
516 if (Result.Nodes.getNodeAs<CXXRewrittenBinaryOperator>(
517 "matchBinopOperands") !=
518 Result.Nodes.getNodeAs<CXXRewrittenBinaryOperator>(
"checkBinopOperands"))
524 CastSequenceVisitor(*Result.Context, NullMacros, *
this)
525 .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