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)) {
246 FirstSubExpr = CastSubExpr;
248 if (
C->getCastKind() != CK_NullToPointer &&
249 C->getCastKind() != CK_NullToMemberPointer) {
253 SourceLocation StartLoc = FirstSubExpr->getBeginLoc();
254 SourceLocation EndLoc = FirstSubExpr->getEndLoc();
261 if (SM.isMacroArgExpansion(StartLoc) && SM.isMacroArgExpansion(EndLoc)) {
262 const SourceLocation FileLocStart = SM.getFileLoc(StartLoc),
263 FileLocEnd = SM.getFileLoc(EndLoc);
264 SourceLocation ImmediateMacroArgLoc, MacroLoc;
266 if (!getMacroAndArgLocations(StartLoc, ImmediateMacroArgLoc, MacroLoc) ||
267 ImmediateMacroArgLoc != FileLocStart)
268 return skipSubTree();
271 allArgUsesValid(C)) {
277 if (SM.isMacroBodyExpansion(StartLoc) && SM.isMacroBodyExpansion(EndLoc)) {
278 const StringRef OutermostMacroName =
282 if (!llvm::is_contained(NullMacros, OutermostMacroName))
283 return skipSubTree();
285 StartLoc = SM.getFileLoc(StartLoc);
286 EndLoc = SM.getFileLoc(EndLoc);
290 return skipSubTree();
305 bool allArgUsesValid(
const CastExpr *CE) {
306 const SourceLocation CastLoc = CE->getBeginLoc();
310 SourceLocation ArgLoc, MacroLoc;
311 if (!getMacroAndArgLocations(CastLoc, ArgLoc, MacroLoc))
315 DynTypedNode ContainingAncestor;
316 if (!findContainingAncestor(DynTypedNode::create<Stmt>(*CE), MacroLoc,
325 MacroArgUsageVisitor ArgUsageVisitor(SM.getFileLoc(CastLoc), SM);
326 if (
const auto *D = ContainingAncestor.get<Decl>())
327 ArgUsageVisitor.TraverseDecl(
const_cast<Decl *
>(D));
328 else if (
const auto *S = ContainingAncestor.get<Stmt>())
329 ArgUsageVisitor.TraverseStmt(
const_cast<Stmt *
>(S));
331 llvm_unreachable(
"Unhandled ContainingAncestor node type");
333 return !ArgUsageVisitor.foundInvalid();
344 bool getMacroAndArgLocations(SourceLocation Loc, SourceLocation &ArgLoc,
345 SourceLocation &MacroLoc) {
346 assert(Loc.isMacroID() &&
"Only reasonable to call this on macros");
352 const std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(ArgLoc);
353 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(LocInfo.first);
354 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
356 const SourceLocation OldArgLoc = ArgLoc;
357 ArgLoc = Expansion.getExpansionLocStart();
358 if (!Expansion.isMacroArgExpansion()) {
359 if (!MacroLoc.isFileID())
362 const StringRef Name =
363 Lexer::getImmediateMacroName(OldArgLoc, SM, Context.getLangOpts());
364 return llvm::is_contained(NullMacros, Name);
367 MacroLoc = SM.getExpansionRange(ArgLoc).getBegin();
369 ArgLoc = Expansion.getSpellingLoc().getLocWithOffset(LocInfo.second);
370 if (ArgLoc.isFileID())
375 const FileID MacroFID = SM.getFileID(MacroLoc);
376 if (SM.isInFileID(ArgLoc, MacroFID)) {
383 llvm_unreachable(
"getMacroAndArgLocations");
397 bool expandsFrom(SourceLocation TestLoc, SourceLocation TestMacroLoc) {
398 if (TestLoc.isFileID()) {
402 SourceLocation Loc = TestLoc, MacroLoc;
405 const std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
406 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(LocInfo.first);
407 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
409 Loc = Expansion.getExpansionLocStart();
411 if (!Expansion.isMacroArgExpansion()) {
412 if (Loc.isFileID()) {
413 return Loc == TestMacroLoc;
422 MacroLoc = SM.getImmediateExpansionRange(Loc).getBegin();
423 if (MacroLoc.isFileID() && MacroLoc == TestMacroLoc) {
428 Loc = Expansion.getSpellingLoc().getLocWithOffset(LocInfo.second);
429 if (Loc.isFileID()) {
436 llvm_unreachable(
"expandsFrom");
444 bool findContainingAncestor(DynTypedNode Start, SourceLocation MacroLoc,
445 DynTypedNode &Result) {
450 assert(MacroLoc.isFileID());
453 const auto &
Parents = Context.getParents(Start);
461 for (
const auto &Parent : Parents) {
462 if (!Parent.get<InitListExpr>())
467 const DynTypedNode &Parent =
Parents[0];
470 if (
const auto *D = Parent.get<Decl>())
471 Loc =
D->getBeginLoc();
472 else if (
const auto *S = Parent.get<Stmt>())
473 Loc = S->getBeginLoc();
478 if (!expandsFrom(Loc, MacroLoc)) {
486 llvm_unreachable(
"findContainingAncestor");
491 ArrayRef<StringRef> NullMacros;
492 ClangTidyCheck &Check;
493 Expr *FirstSubExpr =
nullptr;
494 bool PruneSubtree =
false;
501 NullMacrosStr(Options.get(
"NullMacros",
"NULL")),
502 IgnoredTypes(
utils::options::parseStringList(Options.get(
503 "IgnoredTypes",
"_CmpUnspecifiedParam;^std::__cmp_cat::__unspec"))) {
504 NullMacrosStr.split(NullMacros,
",");
508 Options.store(Opts,
"NullMacros", NullMacrosStr);
509 Options.store(Opts,
"IgnoredTypes",
518 const auto *NullCast = Result.Nodes.getNodeAs<CastExpr>(
CastSequence);
519 assert(NullCast &&
"Bad Callback. No node provided");
521 if (Result.Nodes.getNodeAs<CXXRewrittenBinaryOperator>(
522 "matchBinopOperands") !=
523 Result.Nodes.getNodeAs<CXXRewrittenBinaryOperator>(
"checkBinopOperands"))
529 CastSequenceVisitor(*Result.Context, NullMacros, *
this)
530 .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