clang-tools  9.0.0svn
MisplacedConstCheck.cpp
Go to the documentation of this file.
1 //===--- MisplacedConstCheck.cpp - clang-tidy------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "MisplacedConstCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 
13 using namespace clang::ast_matchers;
14 
15 namespace clang {
16 namespace tidy {
17 namespace misc {
18 
19 void MisplacedConstCheck::registerMatchers(MatchFinder *Finder) {
20  Finder->addMatcher(
21  valueDecl(hasType(isConstQualified()),
22  hasType(typedefType(hasDeclaration(
23  typedefDecl(hasType(pointerType(unless(pointee(
24  anyOf(isConstQualified(),
25  ignoringParens(functionType())))))))
26  .bind("typedef")))))
27  .bind("decl"),
28  this);
29 }
30 
31 static QualType guessAlternateQualification(ASTContext &Context, QualType QT) {
32  // We're given a QualType from a typedef where the qualifiers apply to the
33  // pointer instead of the pointee. Strip the const qualifier from the pointer
34  // type and add it to the pointee instead.
35  if (!QT->isPointerType())
36  return QT;
37 
38  Qualifiers Quals = QT.getLocalQualifiers();
39  Quals.removeConst();
40 
41  QualType NewQT = Context.getPointerType(
42  QualType(QT->getPointeeType().getTypePtr(), Qualifiers::Const));
43  return NewQT.withCVRQualifiers(Quals.getCVRQualifiers());
44 }
45 
46 void MisplacedConstCheck::check(const MatchFinder::MatchResult &Result) {
47  const auto *Var = Result.Nodes.getNodeAs<ValueDecl>("decl");
48  const auto *Typedef = Result.Nodes.getNodeAs<TypedefDecl>("typedef");
49  ASTContext &Ctx = *Result.Context;
50  QualType CanQT = Var->getType().getCanonicalType();
51 
52  diag(Var->getLocation(), "%0 declared with a const-qualified typedef type; "
53  "results in the type being '%1' instead of '%2'")
54  << Var << CanQT.getAsString(Ctx.getPrintingPolicy())
55  << guessAlternateQualification(Ctx, CanQT)
56  .getAsString(Ctx.getPrintingPolicy());
57  diag(Typedef->getLocation(), "typedef declared here", DiagnosticIDs::Note);
58 }
59 
60 } // namespace misc
61 } // namespace tidy
62 } // namespace clang
Context Ctx
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
llvm::Optional< llvm::Expected< tooling::AtomicChanges > > Result
Definition: Rename.cpp:25
static QualType guessAlternateQualification(ASTContext &Context, QualType QT)