clang-tools 3.8.0

- Main Page
- Namespaces
- Classes
- Files

- File List
- File Members

SwappedArgumentsCheck.cpp
Go to the documentation of this file.
1 //===--- SwappedArgumentsCheck.cpp - clang-tidy ---------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "SwappedArgumentsCheck.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/Lex/Lexer.h"
13 #include "llvm/ADT/SmallPtrSet.h"
14
15 using namespace clang::ast_matchers;
16
17 namespace clang {
18 namespace tidy {
19 namespace misc {
20
21 void SwappedArgumentsCheck::registerMatchers(MatchFinder *Finder) {
22 Finder->addMatcher(callExpr().bind("call"), this);
23 }
24
25 /// \brief Look through lvalue to rvalue and nop casts. This filters out
26 /// implicit conversions that have no effect on the input but block our view for
27 /// other implicit casts.
28 static const Expr *ignoreNoOpCasts(const Expr *E) {
29 if (auto *Cast = dyn_cast<CastExpr>(E))
30 if (Cast->getCastKind() == CK_LValueToRValue ||
31 Cast->getCastKind() == CK_NoOp)
32 return ignoreNoOpCasts(Cast->getSubExpr());
33 return E;
34 }
35
36 /// \brief Restrict the warning to implicit casts that are most likely
37 /// accidental. User defined or integral conversions fit in this category,
38 /// lvalue to rvalue or derived to base does not.
39 static bool isImplicitCastCandidate(const CastExpr *Cast) {
40 return Cast->getCastKind() == CK_UserDefinedConversion ||
41 Cast->getCastKind() == CK_FloatingToBoolean ||
42 Cast->getCastKind() == CK_FloatingToIntegral ||
43 Cast->getCastKind() == CK_IntegralToBoolean ||
44 Cast->getCastKind() == CK_IntegralToFloating ||
45 Cast->getCastKind() == CK_MemberPointerToBoolean ||
46 Cast->getCastKind() == CK_PointerToBoolean;
47 }
48
49 /// \brief Get a StringRef representing a SourceRange.
50 static StringRef getAsString(const MatchFinder::MatchResult &Result,
51 SourceRange R) {
52 const SourceManager &SM = *Result.SourceManager;
53 // Don't even try to resolve macro or include contraptions. Not worth emitting
54 // a fixit for.
55 if (R.getBegin().isMacroID() ||
56 !SM.isWrittenInSameFile(R.getBegin(), R.getEnd()))
57 return StringRef();
58
59 const char *Begin = SM.getCharacterData(R.getBegin());
60 const char *End = SM.getCharacterData(Lexer::getLocForEndOfToken(
61 R.getEnd(), 0, SM, Result.Context->getLangOpts()));
62
63 return StringRef(Begin, End - Begin);
64 }
65
66 void SwappedArgumentsCheck::check(const MatchFinder::MatchResult &Result) {
67 auto *Call = Result.Nodes.getStmtAs<CallExpr>("call");
68
69 llvm::SmallPtrSet<const Expr *, 4> UsedArgs;
70 for (unsigned I = 1, E = Call->getNumArgs(); I < E; ++I) {
71 const Expr *LHS = Call->getArg(I - 1);
72 const Expr *RHS = Call->getArg(I);
73
74 // Only need to check RHS, as LHS has already been covered. We don't want to
75 // emit two warnings for a single argument.
76 if (UsedArgs.count(RHS))
77 continue;
78
79 const auto *LHSCast = dyn_cast<ImplicitCastExpr>(ignoreNoOpCasts(LHS));
80 const auto *RHSCast = dyn_cast<ImplicitCastExpr>(ignoreNoOpCasts(RHS));
81
82 // Look if this is a potentially swapped argument pair. First look for
83 // implicit casts.
84 if (!LHSCast || !RHSCast || !isImplicitCastCandidate(LHSCast) ||
85 !isImplicitCastCandidate(RHSCast))
86 continue;
87
88 // If the types that go into the implicit casts match the types of the other
89 // argument in the declaration there is a high probability that the
90 // arguments were swapped.
91 // TODO: We could make use of the edit distance between the argument name
92 // and the name of the passed variable in addition to this type based
93 // heuristic.
94 const Expr *LHSFrom = ignoreNoOpCasts(LHSCast->getSubExpr());
95 const Expr *RHSFrom = ignoreNoOpCasts(RHSCast->getSubExpr());
96 if (LHS->getType() == RHS->getType() ||
97 LHS->getType() != RHSFrom->getType() ||
98 RHS->getType() != LHSFrom->getType())
99 continue;
100
101 // Emit a warning and fix-its that swap the arguments.
102 SourceRange LHSRange = LHS->getSourceRange(),
103 RHSRange = RHS->getSourceRange();
104 auto D =
105 diag(Call->getLocStart(), "argument with implicit conversion from %0 "
106 "to %1 followed by argument converted from "
107 "%2 to %3, potentially swapped arguments.")
108 << LHS->getType() << LHSFrom->getType() << RHS->getType()
109 << RHSFrom->getType() << LHSRange << RHSRange;
110
111 StringRef RHSString = getAsString(Result, RHSRange);
112 StringRef LHSString = getAsString(Result, LHSRange);
113 if (!LHSString.empty() && !RHSString.empty()) {
114 D << FixItHint::CreateReplacement(
115 CharSourceRange::getTokenRange(LHSRange), RHSString)
116 << FixItHint::CreateReplacement(
117 CharSourceRange::getTokenRange(RHSRange), LHSString);
118 }
119
120 // Remember that we emitted a warning for this argument.
121 UsedArgs.insert(RHSCast);
122 }
123 }
124
125 } // namespace misc
126 } // namespace tidy
127 } // namespace clang
clang::tidy::misc::ignoreNoOpCasts
static const Expr * ignoreNoOpCasts(const Expr *E)
Look through lvalue to rvalue and nop casts.
Definition: SwappedArgumentsCheck.cpp:28
Finder
std::unique_ptr< ast_matchers::MatchFinder > Finder
Definition: ClangTidy.cpp:188
SwappedArgumentsCheck.h
SM
SourceManager & SM
Definition: IncludeOrderCheck.cpp:44
clang::tidy::misc::getAsString
static StringRef getAsString(const MatchFinder::MatchResult &Result, SourceRange R)
Get a StringRef representing a SourceRange.
Definition: SwappedArgumentsCheck.cpp:50
clang::tidy::misc::isImplicitCastCandidate
static bool isImplicitCastCandidate(const CastExpr *Cast)
Restrict the warning to implicit casts that are most likely accidental.
Definition: SwappedArgumentsCheck.cpp:39
Result
const NamedDecl * Result
Definition: USRFinder.cpp:121