10 #include "clang/ASTMatchers/ASTMatchFinder.h"
11 #include "clang/ASTMatchers/ASTMatchers.h"
12 #include "clang/Lex/Lexer.h"
13 #include "llvm/ADT/Optional.h"
19 namespace readability {
22 SourceRange getTypeRange(
const ParmVarDecl &Param) {
23 if (Param.getIdentifier() !=
nullptr)
24 return SourceRange(Param.getBeginLoc(),
25 Param.getEndLoc().getLocWithOffset(-1));
26 return Param.getSourceRange();
31 void AvoidConstParamsInDecls::registerMatchers(MatchFinder *Finder) {
32 const auto ConstParamDecl =
33 parmVarDecl(hasType(qualType(isConstQualified()))).bind(
"param");
35 functionDecl(unless(isDefinition()),
42 unless(cxxMethodDecl(ofClass(cxxRecordDecl(anyOf(
43 isLambda(), ast_matchers::isTemplateInstantiation()))))),
44 has(typeLoc(forEach(ConstParamDecl))))
51 const MatchFinder::MatchResult &Result) {
52 const SourceManager &Sources = *Result.SourceManager;
53 std::pair<FileID, unsigned> LocInfo =
54 Sources.getDecomposedLoc(
Range.getBegin());
55 StringRef File = Sources.getBufferData(LocInfo.first);
56 const char *TokenBegin = File.data() + LocInfo.second;
57 Lexer RawLexer(Sources.getLocForStartOfFile(LocInfo.first),
58 Result.Context->getLangOpts(), File.begin(), TokenBegin,
62 while (!RawLexer.LexFromRawLexer(Tok)) {
63 if (Sources.isBeforeInTranslationUnit(
Range.getEnd(), Tok.getLocation()))
65 if (Tok.is(tok::raw_identifier)) {
66 IdentifierInfo &
Info = Result.Context->Idents.get(StringRef(
67 Sources.getCharacterData(Tok.getLocation()), Tok.getLength()));
68 Tok.setIdentifierInfo(&
Info);
69 Tok.setKind(
Info.getTokenID());
71 if (Tok.is(tok::kw_const))
77 void AvoidConstParamsInDecls::check(
const MatchFinder::MatchResult &Result) {
78 const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>(
"func");
79 const auto *Param = Result.Nodes.getNodeAs<ParmVarDecl>(
"param");
81 if (!Param->getType().isLocalConstQualified())
84 auto Diag = diag(Param->getBeginLoc(),
85 "parameter %0 is const-qualified in the function "
86 "declaration; const-qualification of parameters only has an "
87 "effect in function definitions");
88 if (Param->getName().empty()) {
89 for (
unsigned int i = 0; i < Func->getNumParams(); ++i) {
90 if (Param == Func->getParamDecl(i)) {
99 if (Param->getBeginLoc().isMacroID() != Param->getEndLoc().isMacroID()) {
105 CharSourceRange FileRange = Lexer::makeFileCharRange(
106 CharSourceRange::getTokenRange(getTypeRange(*Param)),
107 *Result.SourceManager, getLangOpts());
109 if (!FileRange.isValid())
112 auto Tok =
ConstTok(FileRange, Result);
115 Diag << FixItHint::CreateRemoval(
116 CharSourceRange::getTokenRange(Tok->getLocation(), Tok->getLocation()));