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