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