1 | //===--- UppercaseLiteralSuffixCheck.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 "UppercaseLiteralSuffixCheck.h" |
10 | #include "../utils/ASTUtils.h" |
11 | #include "clang/AST/ASTContext.h" |
12 | #include "clang/ASTMatchers/ASTMatchFinder.h" |
13 | #include "clang/Lex/Lexer.h" |
14 | #include <cctype> |
15 | #include <optional> |
16 | |
17 | using namespace clang::ast_matchers; |
18 | |
19 | namespace clang::tidy::readability { |
20 | |
21 | namespace { |
22 | |
23 | struct IntegerLiteralCheck { |
24 | using type = clang::IntegerLiteral; |
25 | static constexpr llvm::StringLiteral Name = llvm::StringLiteral("integer" ); |
26 | // What should be skipped before looking for the Suffixes? (Nothing here.) |
27 | static constexpr llvm::StringLiteral SkipFirst = llvm::StringLiteral("" ); |
28 | // Suffix can only consist of 'u' and 'l' chars, and can be a complex number |
29 | // ('i', 'j'). In MS compatibility mode, suffixes like i32 are supported. |
30 | static constexpr llvm::StringLiteral Suffixes = |
31 | llvm::StringLiteral("uUlLiIjJ" ); |
32 | }; |
33 | constexpr llvm::StringLiteral IntegerLiteralCheck::Name; |
34 | constexpr llvm::StringLiteral IntegerLiteralCheck::SkipFirst; |
35 | constexpr llvm::StringLiteral IntegerLiteralCheck::Suffixes; |
36 | |
37 | struct FloatingLiteralCheck { |
38 | using type = clang::FloatingLiteral; |
39 | static constexpr llvm::StringLiteral Name = |
40 | llvm::StringLiteral("floating point" ); |
41 | // C++17 introduced hexadecimal floating-point literals, and 'f' is both a |
42 | // valid hexadecimal digit in a hex float literal and a valid floating-point |
43 | // literal suffix. |
44 | // So we can't just "skip to the chars that can be in the suffix". |
45 | // Since the exponent ('p'/'P') is mandatory for hexadecimal floating-point |
46 | // literals, we first skip everything before the exponent. |
47 | static constexpr llvm::StringLiteral SkipFirst = llvm::StringLiteral("pP" ); |
48 | // Suffix can only consist of 'f', 'l', "f16", 'h', 'q' chars, |
49 | // and can be a complex number ('i', 'j'). |
50 | static constexpr llvm::StringLiteral Suffixes = |
51 | llvm::StringLiteral("fFlLhHqQiIjJ" ); |
52 | }; |
53 | constexpr llvm::StringLiteral FloatingLiteralCheck::Name; |
54 | constexpr llvm::StringLiteral FloatingLiteralCheck::SkipFirst; |
55 | constexpr llvm::StringLiteral FloatingLiteralCheck::Suffixes; |
56 | |
57 | struct NewSuffix { |
58 | SourceRange LiteralLocation; |
59 | StringRef OldSuffix; |
60 | std::optional<FixItHint> FixIt; |
61 | }; |
62 | |
63 | std::optional<SourceLocation> getMacroAwareLocation(SourceLocation Loc, |
64 | const SourceManager &SM) { |
65 | // Do nothing if the provided location is invalid. |
66 | if (Loc.isInvalid()) |
67 | return std::nullopt; |
68 | // Look where the location was *actually* written. |
69 | SourceLocation SpellingLoc = SM.getSpellingLoc(Loc); |
70 | if (SpellingLoc.isInvalid()) |
71 | return std::nullopt; |
72 | return SpellingLoc; |
73 | } |
74 | |
75 | std::optional<SourceRange> getMacroAwareSourceRange(SourceRange Loc, |
76 | const SourceManager &SM) { |
77 | std::optional<SourceLocation> Begin = |
78 | getMacroAwareLocation(Loc: Loc.getBegin(), SM); |
79 | std::optional<SourceLocation> End = getMacroAwareLocation(Loc: Loc.getEnd(), SM); |
80 | if (!Begin || !End) |
81 | return std::nullopt; |
82 | return SourceRange(*Begin, *End); |
83 | } |
84 | |
85 | std::optional<std::string> |
86 | getNewSuffix(llvm::StringRef OldSuffix, |
87 | const std::vector<StringRef> &NewSuffixes) { |
88 | // If there is no config, just uppercase the entirety of the suffix. |
89 | if (NewSuffixes.empty()) |
90 | return OldSuffix.upper(); |
91 | // Else, find matching suffix, case-*insensitive*ly. |
92 | auto NewSuffix = |
93 | llvm::find_if(Range: NewSuffixes, P: [OldSuffix](StringRef PotentialNewSuffix) { |
94 | return OldSuffix.equals_insensitive(RHS: PotentialNewSuffix); |
95 | }); |
96 | // Have a match, return it. |
97 | if (NewSuffix != NewSuffixes.end()) |
98 | return NewSuffix->str(); |
99 | // Nope, I guess we have to keep it as-is. |
100 | return std::nullopt; |
101 | } |
102 | |
103 | template <typename LiteralType> |
104 | std::optional<NewSuffix> |
105 | shouldReplaceLiteralSuffix(const Expr &Literal, |
106 | const std::vector<StringRef> &NewSuffixes, |
107 | const SourceManager &SM, const LangOptions &LO) { |
108 | NewSuffix ReplacementDsc; |
109 | |
110 | const auto &L = cast<typename LiteralType::type>(Literal); |
111 | |
112 | // The naive location of the literal. Is always valid. |
113 | ReplacementDsc.LiteralLocation = L.getSourceRange(); |
114 | |
115 | // Was this literal fully spelled or is it a product of macro expansion? |
116 | bool RangeCanBeFixed = |
117 | utils::rangeCanBeFixed(Range: ReplacementDsc.LiteralLocation, SM: &SM); |
118 | |
119 | // The literal may have macro expansion, we need the final expanded src range. |
120 | std::optional<SourceRange> Range = |
121 | getMacroAwareSourceRange(Loc: ReplacementDsc.LiteralLocation, SM); |
122 | if (!Range) |
123 | return std::nullopt; |
124 | |
125 | if (RangeCanBeFixed) |
126 | ReplacementDsc.LiteralLocation = *Range; |
127 | // Else keep the naive literal location! |
128 | |
129 | // Get the whole literal from the source buffer. |
130 | bool Invalid = false; |
131 | const StringRef LiteralSourceText = Lexer::getSourceText( |
132 | Range: CharSourceRange::getTokenRange(R: *Range), SM, LangOpts: LO, Invalid: &Invalid); |
133 | assert(!Invalid && "Failed to retrieve the source text." ); |
134 | |
135 | // Make sure the first character is actually a digit, instead of |
136 | // something else, like a non-type template parameter. |
137 | if (!std::isdigit(static_cast<unsigned char>(LiteralSourceText.front()))) |
138 | return std::nullopt; |
139 | |
140 | size_t Skip = 0; |
141 | |
142 | // Do we need to ignore something before actually looking for the suffix? |
143 | if (!LiteralType::SkipFirst.empty()) { |
144 | // E.g. we can't look for 'f' suffix in hexadecimal floating-point literals |
145 | // until after we skip to the exponent (which is mandatory there), |
146 | // because hex-digit-sequence may contain 'f'. |
147 | Skip = LiteralSourceText.find_first_of(LiteralType::SkipFirst); |
148 | // We could be in non-hexadecimal floating-point literal, with no exponent. |
149 | if (Skip == StringRef::npos) |
150 | Skip = 0; |
151 | } |
152 | |
153 | // Find the beginning of the suffix by looking for the first char that is |
154 | // one of these chars that can be in the suffix, potentially starting looking |
155 | // in the exponent, if we are skipping hex-digit-sequence. |
156 | Skip = LiteralSourceText.find_first_of(LiteralType::Suffixes, /*From=*/Skip); |
157 | |
158 | // We can't check whether the *Literal has any suffix or not without actually |
159 | // looking for the suffix. So it is totally possible that there is no suffix. |
160 | if (Skip == StringRef::npos) |
161 | return std::nullopt; |
162 | |
163 | // Move the cursor in the source range to the beginning of the suffix. |
164 | Range->setBegin(Range->getBegin().getLocWithOffset(Offset: Skip)); |
165 | // And in our textual representation too. |
166 | ReplacementDsc.OldSuffix = LiteralSourceText.drop_front(N: Skip); |
167 | assert(!ReplacementDsc.OldSuffix.empty() && |
168 | "We still should have some chars left." ); |
169 | |
170 | // And get the replacement suffix. |
171 | std::optional<std::string> NewSuffix = |
172 | getNewSuffix(OldSuffix: ReplacementDsc.OldSuffix, NewSuffixes); |
173 | if (!NewSuffix || ReplacementDsc.OldSuffix == *NewSuffix) |
174 | return std::nullopt; // The suffix was already the way it should be. |
175 | |
176 | if (RangeCanBeFixed) |
177 | ReplacementDsc.FixIt = FixItHint::CreateReplacement(RemoveRange: *Range, Code: *NewSuffix); |
178 | |
179 | return ReplacementDsc; |
180 | } |
181 | |
182 | } // namespace |
183 | |
184 | UppercaseLiteralSuffixCheck::UppercaseLiteralSuffixCheck( |
185 | StringRef Name, ClangTidyContext *Context) |
186 | : ClangTidyCheck(Name, Context), |
187 | NewSuffixes( |
188 | utils::options::parseStringList(Option: Options.get(LocalName: "NewSuffixes" , Default: "" ))), |
189 | IgnoreMacros(Options.getLocalOrGlobal(LocalName: "IgnoreMacros" , Default: true)) {} |
190 | |
191 | void UppercaseLiteralSuffixCheck::storeOptions( |
192 | ClangTidyOptions::OptionMap &Opts) { |
193 | Options.store(Options&: Opts, LocalName: "NewSuffixes" , |
194 | Value: utils::options::serializeStringList(Strings: NewSuffixes)); |
195 | Options.store(Options&: Opts, LocalName: "IgnoreMacros" , Value: IgnoreMacros); |
196 | } |
197 | |
198 | void UppercaseLiteralSuffixCheck::registerMatchers(MatchFinder *Finder) { |
199 | // Sadly, we can't check whether the literal has suffix or not. |
200 | // E.g. i32 suffix still results in 'BuiltinType::Kind::Int'. |
201 | // And such an info is not stored in the *Literal itself. |
202 | Finder->addMatcher( |
203 | NodeMatch: stmt(eachOf(integerLiteral().bind(ID: IntegerLiteralCheck::Name), |
204 | floatLiteral().bind(ID: FloatingLiteralCheck::Name)), |
205 | unless(anyOf(hasParent(userDefinedLiteral()), |
206 | hasAncestor(substNonTypeTemplateParmExpr())))), |
207 | Action: this); |
208 | } |
209 | |
210 | template <typename LiteralType> |
211 | bool UppercaseLiteralSuffixCheck::checkBoundMatch( |
212 | const MatchFinder::MatchResult &Result) { |
213 | const auto *Literal = |
214 | Result.Nodes.getNodeAs<typename LiteralType::type>(LiteralType::Name); |
215 | if (!Literal) |
216 | return false; |
217 | |
218 | // We won't *always* want to diagnose. |
219 | // We might have a suffix that is already uppercase. |
220 | if (auto Details = shouldReplaceLiteralSuffix<LiteralType>( |
221 | *Literal, NewSuffixes, *Result.SourceManager, getLangOpts())) { |
222 | if (Details->LiteralLocation.getBegin().isMacroID() && IgnoreMacros) |
223 | return true; |
224 | auto Complaint = diag(Details->LiteralLocation.getBegin(), |
225 | "%0 literal has suffix '%1', which is not uppercase" ) |
226 | << LiteralType::Name << Details->OldSuffix; |
227 | if (Details->FixIt) // Similarly, a fix-it is not always possible. |
228 | Complaint << *(Details->FixIt); |
229 | } |
230 | |
231 | return true; |
232 | } |
233 | |
234 | void UppercaseLiteralSuffixCheck::check( |
235 | const MatchFinder::MatchResult &Result) { |
236 | if (checkBoundMatch<IntegerLiteralCheck>(Result)) |
237 | return; // If it *was* IntegerLiteral, don't check for FloatingLiteral. |
238 | checkBoundMatch<FloatingLiteralCheck>(Result); |
239 | } |
240 | |
241 | } // namespace clang::tidy::readability |
242 | |