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 BuiltinType *BT = dyn_cast<BuiltinType>(DesugaredType))
30 return BT->getKind() == BuiltinType::NullPtr;
39 StatementMatcher makeCastSequenceMatcher() {
40 StatementMatcher ImplicitCastToNull = implicitCastExpr(
41 anyOf(hasCastKind(CK_NullToPointer),
42 hasCastKind(CK_NullToMemberPointer)),
43 unless(hasSourceExpression(hasType(sugaredNullptrType()))));
45 return castExpr(anyOf(ImplicitCastToNull,
46 explicitCastExpr(hasDescendant(ImplicitCastToNull))),
47 unless(hasAncestor(explicitCastExpr())))
51 bool isReplaceableRange(SourceLocation StartLoc, SourceLocation EndLoc,
52 const SourceManager &
SM) {
53 return SM.isWrittenInSameFile(StartLoc, EndLoc);
59 void replaceWithNullptr(ClangTidyCheck &
Check, SourceManager &SM,
60 SourceLocation StartLoc, SourceLocation EndLoc) {
61 CharSourceRange
Range(SourceRange(StartLoc, EndLoc),
true);
65 SourceLocation PreviousLocation = StartLoc.getLocWithOffset(-1);
66 bool NeedsSpace = isAlphanumeric(*SM.getCharacterData(PreviousLocation));
67 Check.diag(
Range.getBegin(),
"use nullptr") << FixItHint::CreateReplacement(
68 Range, NeedsSpace ?
" nullptr" :
"nullptr");
78 StringRef getOutermostMacroName(SourceLocation
Loc,
const SourceManager &SM,
79 const LangOptions &LO) {
80 assert(Loc.isMacroID());
81 SourceLocation OutermostMacroLoc;
83 while (Loc.isMacroID()) {
84 OutermostMacroLoc =
Loc;
85 Loc = SM.getImmediateMacroCallerLoc(Loc);
88 return Lexer::getImmediateMacroName(OutermostMacroLoc, SM, LO);
94 class MacroArgUsageVisitor :
public RecursiveASTVisitor<MacroArgUsageVisitor> {
96 MacroArgUsageVisitor(SourceLocation
CastLoc,
const SourceManager &SM)
99 assert(CastLoc.isFileID());
102 bool TraverseStmt(Stmt *S) {
103 bool VisitedPreviously =
Visited;
105 if (!RecursiveASTVisitor<MacroArgUsageVisitor>::TraverseStmt(S))
112 if (!VisitedPreviously) {
127 bool VisitStmt(Stmt *S) {
128 if (SM.getFileLoc(S->getLocStart()) != CastLoc)
132 const ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(S);
133 if (Cast && (Cast->getCastKind() == CK_NullToPointer ||
134 Cast->getCastKind() == CK_NullToMemberPointer))
140 bool TraverseInitListExpr(InitListExpr *S) {
145 return RecursiveASTVisitor<MacroArgUsageVisitor>::
146 TraverseSynOrSemInitListExpr(
147 S->isSemanticForm() ? S : S->getSemanticForm());
154 const SourceManager &
SM;
172 class CastSequenceVisitor :
public RecursiveASTVisitor<CastSequenceVisitor> {
175 ClangTidyCheck &check)
176 :
SM(Context.getSourceManager()),
Context(Context),
180 bool TraverseStmt(Stmt *S) {
186 return RecursiveASTVisitor<CastSequenceVisitor>::TraverseStmt(S);
191 bool VisitStmt(Stmt *S) {
192 CastExpr *C = dyn_cast<CastExpr>(S);
200 if (C->getCastKind() != CK_NullToPointer &&
201 C->getCastKind() != CK_NullToMemberPointer) {
213 if (SM.isMacroArgExpansion(StartLoc) && SM.isMacroArgExpansion(EndLoc)) {
214 SourceLocation FileLocStart = SM.getFileLoc(StartLoc),
215 FileLocEnd = SM.getFileLoc(EndLoc);
216 SourceLocation ImmediateMarcoArgLoc, MacroLoc;
218 if (!getMacroAndArgLocations(StartLoc, ImmediateMarcoArgLoc, MacroLoc) ||
219 ImmediateMarcoArgLoc != FileLocStart)
220 return skipSubTree();
222 if (isReplaceableRange(FileLocStart, FileLocEnd, SM) &&
223 allArgUsesValid(C)) {
224 replaceWithNullptr(Check, SM, FileLocStart, FileLocEnd);
226 return skipSubTree();
229 if (SM.isMacroBodyExpansion(StartLoc) && SM.isMacroBodyExpansion(EndLoc)) {
230 StringRef OutermostMacroName =
231 getOutermostMacroName(StartLoc, SM, Context.getLangOpts());
234 if (std::find(NullMacros.begin(), NullMacros.end(), OutermostMacroName) ==
236 return skipSubTree();
239 StartLoc = SM.getFileLoc(StartLoc);
240 EndLoc = SM.getFileLoc(EndLoc);
243 if (!isReplaceableRange(StartLoc, EndLoc, SM)) {
244 return skipSubTree();
246 replaceWithNullptr(Check, SM, StartLoc, EndLoc);
259 bool allArgUsesValid(
const CastExpr *CE) {
260 SourceLocation CastLoc = CE->getLocStart();
264 SourceLocation ArgLoc, MacroLoc;
265 if (!getMacroAndArgLocations(CastLoc, ArgLoc, MacroLoc))
269 ast_type_traits::DynTypedNode ContainingAncestor;
270 if (!findContainingAncestor(
271 ast_type_traits::DynTypedNode::create<Stmt>(*CE), MacroLoc,
280 MacroArgUsageVisitor ArgUsageVisitor(SM.getFileLoc(CastLoc),
SM);
281 if (
const auto *D = ContainingAncestor.get<Decl>())
282 ArgUsageVisitor.TraverseDecl(const_cast<Decl *>(D));
283 else if (
const auto *S = ContainingAncestor.get<Stmt>())
284 ArgUsageVisitor.TraverseStmt(const_cast<Stmt *>(S));
286 llvm_unreachable(
"Unhandled ContainingAncestor node type");
288 return !ArgUsageVisitor.foundInvalid();
299 bool getMacroAndArgLocations(SourceLocation Loc, SourceLocation &ArgLoc,
300 SourceLocation &MacroLoc) {
301 assert(Loc.isMacroID() &&
"Only reasonble to call this on macros");
307 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(ArgLoc);
308 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(LocInfo.first);
309 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
311 SourceLocation OldArgLoc = ArgLoc;
312 ArgLoc = Expansion.getExpansionLocStart();
313 if (!Expansion.isMacroArgExpansion()) {
314 if (!MacroLoc.isFileID())
318 Lexer::getImmediateMacroName(OldArgLoc, SM, Context.getLangOpts());
319 return std::find(NullMacros.begin(), NullMacros.end(),
Name) !=
323 MacroLoc = SM.getExpansionRange(ArgLoc).first;
325 ArgLoc = Expansion.getSpellingLoc().getLocWithOffset(LocInfo.second);
326 if (ArgLoc.isFileID())
331 FileID MacroFID = SM.getFileID(MacroLoc);
332 if (SM.isInFileID(ArgLoc, MacroFID)) {
339 llvm_unreachable(
"getMacroAndArgLocations");
353 bool expandsFrom(SourceLocation TestLoc, SourceLocation TestMacroLoc) {
354 if (TestLoc.isFileID()) {
358 SourceLocation Loc = TestLoc, MacroLoc;
361 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
362 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(LocInfo.first);
363 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
365 Loc = Expansion.getExpansionLocStart();
367 if (!Expansion.isMacroArgExpansion()) {
368 if (Loc.isFileID()) {
369 return Loc == TestMacroLoc;
378 MacroLoc = SM.getImmediateExpansionRange(Loc).first;
379 if (MacroLoc.isFileID() && MacroLoc == TestMacroLoc) {
384 Loc = Expansion.getSpellingLoc().getLocWithOffset(LocInfo.second);
385 if (Loc.isFileID()) {
392 llvm_unreachable(
"expandsFrom");
400 bool findContainingAncestor(ast_type_traits::DynTypedNode Start,
401 SourceLocation MacroLoc,
402 ast_type_traits::DynTypedNode &
Result) {
407 assert(MacroLoc.isFileID());
410 const auto &Parents = Context.getParents(Start);
413 if (Parents.size() > 1) {
418 for (
const auto &Parent : Parents) {
419 if (!Parent.get<InitListExpr>())
424 const ast_type_traits::DynTypedNode &Parent = Parents[0];
427 if (
const auto *D = Parent.get<Decl>())
428 Loc = D->getLocStart();
429 else if (
const auto *S = Parent.get<Stmt>())
430 Loc = S->getLocStart();
435 if (!expandsFrom(Loc, MacroLoc)) {
443 llvm_unreachable(
"findContainingAncestor");
459 NullMacrosStr(Options.get(
"NullMacros",
"")) {
460 StringRef(NullMacrosStr).split(NullMacros,
",");
472 Finder->addMatcher(makeCastSequenceMatcher(),
this);
476 const auto *NullCast = Result.Nodes.getNodeAs<CastExpr>(CastSequence);
477 assert(NullCast &&
"Bad Callback. No node provided");
482 CastSequenceVisitor(*Result.Context, NullMacros, *
this)
483 .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