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