1 //===--- DeprecatedIosBaseAliasesCheck.cpp - clang-tidy--------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "DeprecatedIosBaseAliasesCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
14 using namespace clang::ast_matchers
;
16 namespace clang::tidy::modernize
{
18 static constexpr std::array
<StringRef
, 5> DeprecatedTypes
= {
19 "::std::ios_base::io_state", "::std::ios_base::open_mode",
20 "::std::ios_base::seek_dir", "::std::ios_base::streamoff",
21 "::std::ios_base::streampos"};
23 static std::optional
<const char *> getReplacementType(StringRef Type
) {
24 return llvm::StringSwitch
<std::optional
<const char *>>(Type
)
25 .Case("io_state", "iostate")
26 .Case("open_mode", "openmode")
27 .Case("seek_dir", "seekdir")
28 .Default(std::nullopt
);
31 void DeprecatedIosBaseAliasesCheck::registerMatchers(MatchFinder
*Finder
) {
32 auto IoStateDecl
= typedefDecl(hasAnyName(DeprecatedTypes
)).bind("TypeDecl");
34 qualType(hasDeclaration(IoStateDecl
), unless(elaboratedType()));
36 Finder
->addMatcher(typeLoc(loc(IoStateType
)).bind("TypeLoc"), this);
39 void DeprecatedIosBaseAliasesCheck::check(
40 const MatchFinder::MatchResult
&Result
) {
41 SourceManager
&SM
= *Result
.SourceManager
;
43 const auto *Typedef
= Result
.Nodes
.getNodeAs
<TypedefDecl
>("TypeDecl");
44 StringRef TypeName
= Typedef
->getName();
45 auto Replacement
= getReplacementType(TypeName
);
47 const auto *TL
= Result
.Nodes
.getNodeAs
<TypeLoc
>("TypeLoc");
48 SourceLocation IoStateLoc
= TL
->getBeginLoc();
50 // Do not generate fixits for matches depending on template arguments and
52 bool Fix
= Replacement
&& !TL
->getType()->isDependentType();
53 if (IoStateLoc
.isMacroID()) {
54 IoStateLoc
= SM
.getSpellingLoc(IoStateLoc
);
58 SourceLocation EndLoc
= IoStateLoc
.getLocWithOffset(TypeName
.size() - 1);
61 const char *FixName
= *Replacement
;
62 auto Builder
= diag(IoStateLoc
, "'std::ios_base::%0' is deprecated; use "
63 "'std::ios_base::%1' instead")
64 << TypeName
<< FixName
;
67 Builder
<< FixItHint::CreateReplacement(SourceRange(IoStateLoc
, EndLoc
),
70 diag(IoStateLoc
, "'std::ios_base::%0' is deprecated") << TypeName
;
73 } // namespace clang::tidy::modernize