11 #include "clang/AST/ASTContext.h"
12 #include "clang/AST/RecursiveASTVisitor.h"
13 #include "clang/ASTMatchers/ASTMatchFinder.h"
14 #include "clang/Lex/Lexer.h"
16 using namespace clang;
17 using namespace clang::ast_matchers;
25 const char CastSequence[] =
"sequence";
28 const Type *DesugaredType = Node.getUnqualifiedDesugaredType();
29 if (
const auto *BT = dyn_cast<BuiltinType>(DesugaredType))
30 return BT->getKind() == BuiltinType::NullPtr;
39 StatementMatcher makeCastSequenceMatcher() {
40 StatementMatcher ImplicitCastToNull = implicitCastExpr(
41 anyOf(hasCastKind(CK_NullToPointer), hasCastKind(CK_NullToMemberPointer)),
42 unless(hasSourceExpression(hasType(sugaredNullptrType()))));
44 return castExpr(anyOf(ImplicitCastToNull,
45 explicitCastExpr(hasDescendant(ImplicitCastToNull))),
46 unless(hasAncestor(explicitCastExpr())))
50 bool isReplaceableRange(SourceLocation StartLoc, SourceLocation EndLoc,
51 const SourceManager &
SM) {
52 return SM.isWrittenInSameFile(StartLoc, EndLoc);
58 void replaceWithNullptr(ClangTidyCheck &
Check, SourceManager &SM,
59 SourceLocation StartLoc, SourceLocation EndLoc) {
60 CharSourceRange
Range(SourceRange(StartLoc, EndLoc),
true);
64 SourceLocation PreviousLocation = StartLoc.getLocWithOffset(-1);
65 bool NeedsSpace = isAlphanumeric(*SM.getCharacterData(PreviousLocation));
66 Check.diag(
Range.getBegin(),
"use nullptr") << FixItHint::CreateReplacement(
67 Range, NeedsSpace ?
" nullptr" :
"nullptr");
77 StringRef getOutermostMacroName(SourceLocation
Loc,
const SourceManager &SM,
78 const LangOptions &LO) {
79 assert(Loc.isMacroID());
80 SourceLocation OutermostMacroLoc;
82 while (Loc.isMacroID()) {
83 OutermostMacroLoc =
Loc;
84 Loc = SM.getImmediateMacroCallerLoc(Loc);
87 return Lexer::getImmediateMacroName(OutermostMacroLoc, SM, LO);
93 class MacroArgUsageVisitor :
public RecursiveASTVisitor<MacroArgUsageVisitor> {
95 MacroArgUsageVisitor(SourceLocation
CastLoc,
const SourceManager &SM)
98 assert(CastLoc.isFileID());
101 bool TraverseStmt(Stmt *S) {
102 bool VisitedPreviously =
Visited;
104 if (!RecursiveASTVisitor<MacroArgUsageVisitor>::TraverseStmt(S))
111 if (!VisitedPreviously) {
126 bool VisitStmt(Stmt *S) {
127 if (SM.getFileLoc(S->getLocStart()) != CastLoc)
131 const ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(S);
132 if (Cast && (Cast->getCastKind() == CK_NullToPointer ||
133 Cast->getCastKind() == CK_NullToMemberPointer))
139 bool TraverseInitListExpr(InitListExpr *S) {
144 return RecursiveASTVisitor<MacroArgUsageVisitor>::
145 TraverseSynOrSemInitListExpr(
146 S->isSemanticForm() ? S : S->getSemanticForm());
153 const SourceManager &
SM;
171 class CastSequenceVisitor :
public RecursiveASTVisitor<CastSequenceVisitor> {
174 ClangTidyCheck &check)
175 :
SM(Context.getSourceManager()),
Context(Context),
179 bool TraverseStmt(Stmt *S) {
185 return RecursiveASTVisitor<CastSequenceVisitor>::TraverseStmt(S);
190 bool VisitStmt(Stmt *S) {
191 auto *C = dyn_cast<CastExpr>(S);
193 if (
auto *E = dyn_cast<CXXDefaultArgExpr>(S))
194 C = dyn_cast<CastExpr>(E->getExpr());
207 if (C->getCastKind() != CK_NullToPointer &&
208 C->getCastKind() != CK_NullToMemberPointer) {
220 if (SM.isMacroArgExpansion(StartLoc) && SM.isMacroArgExpansion(EndLoc)) {
221 SourceLocation FileLocStart = SM.getFileLoc(StartLoc),
222 FileLocEnd = SM.getFileLoc(EndLoc);
223 SourceLocation ImmediateMarcoArgLoc, MacroLoc;
225 if (!getMacroAndArgLocations(StartLoc, ImmediateMarcoArgLoc, MacroLoc) ||
226 ImmediateMarcoArgLoc != FileLocStart)
227 return skipSubTree();
229 if (isReplaceableRange(FileLocStart, FileLocEnd, SM) &&
230 allArgUsesValid(C)) {
231 replaceWithNullptr(Check, SM, FileLocStart, FileLocEnd);
233 return skipSubTree();
236 if (SM.isMacroBodyExpansion(StartLoc) && SM.isMacroBodyExpansion(EndLoc)) {
237 StringRef OutermostMacroName =
238 getOutermostMacroName(StartLoc, SM, Context.getLangOpts());
241 if (std::find(NullMacros.begin(), NullMacros.end(), OutermostMacroName) ==
243 return skipSubTree();
246 StartLoc = SM.getFileLoc(StartLoc);
247 EndLoc = SM.getFileLoc(EndLoc);
250 if (!isReplaceableRange(StartLoc, EndLoc, SM)) {
251 return skipSubTree();
253 replaceWithNullptr(Check, SM, StartLoc, EndLoc);
266 bool allArgUsesValid(
const CastExpr *CE) {
267 SourceLocation CastLoc = CE->getLocStart();
271 SourceLocation ArgLoc, MacroLoc;
272 if (!getMacroAndArgLocations(CastLoc, ArgLoc, MacroLoc))
276 ast_type_traits::DynTypedNode ContainingAncestor;
277 if (!findContainingAncestor(
278 ast_type_traits::DynTypedNode::create<Stmt>(*CE), MacroLoc,
287 MacroArgUsageVisitor ArgUsageVisitor(SM.getFileLoc(CastLoc),
SM);
288 if (
const auto *D = ContainingAncestor.get<Decl>())
289 ArgUsageVisitor.TraverseDecl(const_cast<Decl *>(D));
290 else if (
const auto *S = ContainingAncestor.get<Stmt>())
291 ArgUsageVisitor.TraverseStmt(const_cast<Stmt *>(S));
293 llvm_unreachable(
"Unhandled ContainingAncestor node type");
295 return !ArgUsageVisitor.foundInvalid();
306 bool getMacroAndArgLocations(SourceLocation Loc, SourceLocation &ArgLoc,
307 SourceLocation &MacroLoc) {
308 assert(Loc.isMacroID() &&
"Only reasonble to call this on macros");
314 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(ArgLoc);
315 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(LocInfo.first);
316 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
318 SourceLocation OldArgLoc = ArgLoc;
319 ArgLoc = Expansion.getExpansionLocStart();
320 if (!Expansion.isMacroArgExpansion()) {
321 if (!MacroLoc.isFileID())
325 Lexer::getImmediateMacroName(OldArgLoc, SM, Context.getLangOpts());
326 return std::find(NullMacros.begin(), NullMacros.end(),
Name) !=
330 MacroLoc = SM.getExpansionRange(ArgLoc).first;
332 ArgLoc = Expansion.getSpellingLoc().getLocWithOffset(LocInfo.second);
333 if (ArgLoc.isFileID())
338 FileID MacroFID = SM.getFileID(MacroLoc);
339 if (SM.isInFileID(ArgLoc, MacroFID)) {
346 llvm_unreachable(
"getMacroAndArgLocations");
360 bool expandsFrom(SourceLocation TestLoc, SourceLocation TestMacroLoc) {
361 if (TestLoc.isFileID()) {
365 SourceLocation Loc = TestLoc, MacroLoc;
368 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
369 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(LocInfo.first);
370 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
372 Loc = Expansion.getExpansionLocStart();
374 if (!Expansion.isMacroArgExpansion()) {
375 if (Loc.isFileID()) {
376 return Loc == TestMacroLoc;
385 MacroLoc = SM.getImmediateExpansionRange(Loc).first;
386 if (MacroLoc.isFileID() && MacroLoc == TestMacroLoc) {
391 Loc = Expansion.getSpellingLoc().getLocWithOffset(LocInfo.second);
392 if (Loc.isFileID()) {
399 llvm_unreachable(
"expandsFrom");
407 bool findContainingAncestor(ast_type_traits::DynTypedNode Start,
408 SourceLocation MacroLoc,
409 ast_type_traits::DynTypedNode &
Result) {
414 assert(MacroLoc.isFileID());
417 const auto &Parents = Context.getParents(Start);
420 if (Parents.size() > 1) {
425 for (
const auto &Parent : Parents) {
426 if (!Parent.get<InitListExpr>())
431 const ast_type_traits::DynTypedNode &Parent = Parents[0];
434 if (
const auto *D = Parent.get<Decl>())
435 Loc = D->getLocStart();
436 else if (
const auto *S = Parent.get<Stmt>())
437 Loc = S->getLocStart();
442 if (!expandsFrom(Loc, MacroLoc)) {
450 llvm_unreachable(
"findContainingAncestor");
466 NullMacrosStr(Options.get(
"NullMacros",
"")) {
467 StringRef(NullMacrosStr).split(NullMacros,
",");
479 Finder->addMatcher(makeCastSequenceMatcher(),
this);
483 const auto *NullCast = Result.Nodes.getNodeAs<CastExpr>(CastSequence);
484 assert(NullCast &&
"Bad Callback. No node provided");
489 CastSequenceVisitor(*Result.Context, NullMacros, *
this)
490 .TraverseStmt(const_cast<CastExpr *>(NullCast));
SourceLocation Loc
'#' location in the include directive
AST_MATCHER(Type, isStrictlyInteger)
LangOptions getLangOpts() const
Returns the language options from the context.
std::unique_ptr< ast_matchers::MatchFinder > Finder
Base class for all clang-tidy checks.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
std::map< std::string, std::string > OptionMap
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
CharSourceRange Range
SourceRange for the file name.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
ArrayRef< StringRef > NullMacros