clang-tools 23.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"
12#include "clang/AST/ASTContext.h"
13#include "clang/ASTMatchers/ASTMatchFinder.h"
14#include "clang/Lex/Lexer.h"
15#include <optional>
16
17using namespace clang::ast_matchers;
18
20
21namespace {
22
23struct NewSuffix {
24 SourceRange LiteralLocation;
25 StringRef OldSuffix;
26 std::optional<FixItHint> FixIt;
27};
28
29struct LiteralParameters {
30 // What characters should be skipped before looking for the Suffixes?
31 StringRef SkipFirst;
32 // What characters can a suffix start with?
33 StringRef Suffixes;
34};
35
36} // namespace
37
38static constexpr LiteralParameters IntegerParameters = {
39 "",
40 // Suffix can only consist of 'u', 'l', and 'z' chars, can be a
41 // bit-precise integer (wb), and can be a complex number ('i', 'j'). In MS
42 // compatibility mode, suffixes like i32 are supported.
43 "uUlLzZwWiIjJ",
44};
45
46static constexpr LiteralParameters FloatParameters = {
47 // C++17 introduced hexadecimal floating-point literals, and 'f' is both a
48 // valid hexadecimal digit in a hex float literal and a valid floating-point
49 // literal suffix.
50 // So we can't just "skip to the chars that can be in the suffix".
51 // Since the exponent ('p'/'P') is mandatory for hexadecimal floating-point
52 // literals, we first skip everything before the exponent.
53 "pP",
54 // Suffix can only consist of 'f', 'l', "f16", "bf16", "df", "dd", "dl",
55 // 'h', 'q' chars, and can be a complex number ('i', 'j').
56 "fFlLbBdDhHqQiIjJ",
57};
58
59static std::optional<SourceLocation>
60getMacroAwareLocation(SourceLocation Loc, const SourceManager &SM) {
61 // Do nothing if the provided location is invalid.
62 if (Loc.isInvalid())
63 return std::nullopt;
64 // Look where the location was *actually* written.
65 SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
66 if (SpellingLoc.isInvalid())
67 return std::nullopt;
68 return SpellingLoc;
69}
70
71static std::optional<SourceRange>
72getMacroAwareSourceRange(SourceRange Loc, const SourceManager &SM) {
73 std::optional<SourceLocation> Begin =
74 getMacroAwareLocation(Loc.getBegin(), SM);
75 std::optional<SourceLocation> End = getMacroAwareLocation(Loc.getEnd(), SM);
76 if (!Begin || !End)
77 return std::nullopt;
78 return SourceRange(*Begin, *End);
79}
80
81static std::optional<std::string>
82getNewSuffix(StringRef OldSuffix, 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
98static std::optional<NewSuffix>
99shouldReplaceLiteralSuffix(const Expr &Literal,
100 const LiteralParameters &Parameters,
101 const std::vector<StringRef> &NewSuffixes,
102 const SourceManager &SM, const LangOptions &LO) {
103 NewSuffix ReplacementDsc;
104
105 // The naive location of the literal. Is always valid.
106 ReplacementDsc.LiteralLocation = Literal.getSourceRange();
107
108 // Was this literal fully spelled or is it a product of macro expansion?
109 const bool RangeCanBeFixed =
110 utils::rangeCanBeFixed(ReplacementDsc.LiteralLocation, &SM);
111
112 // The literal may have macro expansion, we need the final expanded src range.
113 std::optional<SourceRange> Range =
114 getMacroAwareSourceRange(ReplacementDsc.LiteralLocation, SM);
115 if (!Range)
116 return std::nullopt;
117
118 if (RangeCanBeFixed)
119 ReplacementDsc.LiteralLocation = *Range;
120 // Else keep the naive literal location!
121
122 // Get the whole literal from the source buffer.
123 bool Invalid = false;
124 const StringRef LiteralSourceText = Lexer::getSourceText(
125 CharSourceRange::getTokenRange(*Range), SM, LO, &Invalid);
126 assert(!Invalid && "Failed to retrieve the source text.");
127
128 // Make sure the first character is actually a digit, instead of
129 // something else, like a non-type template parameter.
130 if (!std::isdigit(static_cast<unsigned char>(LiteralSourceText.front())))
131 return std::nullopt;
132
133 size_t Skip = 0;
134
135 // Do we need to ignore something before actually looking for the suffix?
136 if (!Parameters.SkipFirst.empty()) {
137 // E.g. we can't look for 'f' suffix in hexadecimal floating-point literals
138 // until after we skip to the exponent (which is mandatory there),
139 // because hex-digit-sequence may contain 'f'.
140 Skip = LiteralSourceText.find_first_of(Parameters.SkipFirst);
141 // We could be in non-hexadecimal floating-point literal, with no exponent.
142 if (Skip == StringRef::npos)
143 Skip = 0;
144 }
145
146 // Find the beginning of the suffix by looking for the first char that is
147 // one of these chars that can be in the suffix, potentially starting looking
148 // in the exponent, if we are skipping hex-digit-sequence.
149 Skip = LiteralSourceText.find_first_of(Parameters.Suffixes, /*From=*/Skip);
150
151 // We can't check whether the *Literal has any suffix or not without actually
152 // looking for the suffix. So it is totally possible that there is no suffix.
153 if (Skip == StringRef::npos)
154 return std::nullopt;
155
156 // Move the cursor in the source range to the beginning of the suffix.
157 Range->setBegin(Range->getBegin().getLocWithOffset(Skip));
158 // And in our textual representation too.
159 ReplacementDsc.OldSuffix = LiteralSourceText.drop_front(Skip);
160 assert(!ReplacementDsc.OldSuffix.empty() &&
161 "We still should have some chars left.");
162
163 // And get the replacement suffix.
164 std::optional<std::string> NewSuffix =
165 getNewSuffix(ReplacementDsc.OldSuffix, NewSuffixes);
166 if (!NewSuffix || ReplacementDsc.OldSuffix == *NewSuffix)
167 return std::nullopt; // The suffix was already the way it should be.
168
169 if (RangeCanBeFixed)
170 ReplacementDsc.FixIt = FixItHint::CreateReplacement(*Range, *NewSuffix);
171
172 return ReplacementDsc;
173}
174
176 StringRef Name, ClangTidyContext *Context)
177 : ClangTidyCheck(Name, Context),
178 NewSuffixes(
179 utils::options::parseStringList(Options.get("NewSuffixes", ""))),
180 IgnoreMacros(Options.get("IgnoreMacros", true)) {}
181
184 Options.store(Opts, "NewSuffixes",
186 Options.store(Opts, "IgnoreMacros", IgnoreMacros);
187}
188
190 // Sadly, we can't check whether the literal has suffix or not.
191 // E.g. i32 suffix still results in 'BuiltinType::Kind::Int'.
192 // And such an info is not stored in the *Literal itself.
193
194 Finder->addMatcher(
195 integerLiteral(unless(hasParent(userDefinedLiteral()))).bind("expr"),
196 this);
197 Finder->addMatcher(
198 floatLiteral(unless(hasParent(userDefinedLiteral()))).bind("expr"), this);
199}
200
202 const MatchFinder::MatchResult &Result) {
203 const auto *const Literal = Result.Nodes.getNodeAs<Expr>("expr");
204 const bool IsInteger = isa<IntegerLiteral>(Literal);
205
206 // We won't *always* want to diagnose.
207 // We might have a suffix that is already uppercase.
208 if (auto Details = shouldReplaceLiteralSuffix(
209 *Literal, IsInteger ? IntegerParameters : FloatParameters,
210 NewSuffixes, *Result.SourceManager, getLangOpts())) {
211 if (Details->LiteralLocation.getBegin().isMacroID() && IgnoreMacros)
212 return;
213 auto Complaint = diag(Details->LiteralLocation.getBegin(),
214 "%select{floating point|integer}0 literal has suffix "
215 "'%1', which is not uppercase")
216 << IsInteger << Details->OldSuffix;
217 if (Details->FixIt) // Similarly, a fix-it is not always possible.
218 Complaint << *(Details->FixIt);
219 }
220}
221
222} // 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
static std::optional< NewSuffix > shouldReplaceLiteralSuffix(const Expr &Literal, const LiteralParameters &Parameters, const std::vector< StringRef > &NewSuffixes, const SourceManager &SM, const LangOptions &LO)
static std::optional< SourceRange > getMacroAwareSourceRange(SourceRange Loc, const SourceManager &SM)
static constexpr LiteralParameters IntegerParameters
static std::optional< std::string > getNewSuffix(StringRef OldSuffix, const std::vector< StringRef > &NewSuffixes)
static std::optional< SourceLocation > getMacroAwareLocation(SourceLocation Loc, const SourceManager &SM)
static constexpr LiteralParameters FloatParameters
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:84
llvm::StringMap< ClangTidyValue > OptionMap