clang 23.0.0git
IntegerLiteralSeparatorFixer.cpp
Go to the documentation of this file.
1//===--- IntegerLiteralSeparatorFixer.cpp -----------------------*- C++ -*-===//
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/// \file
10/// This file implements IntegerLiteralSeparatorFixer that fixes C++ integer
11/// literal separators.
12///
13//===----------------------------------------------------------------------===//
14
16
17namespace clang {
18namespace format {
19
20enum class Base { Binary, Decimal, Hex, Other };
21
22static Base getBase(StringRef IntegerLiteral) {
23 assert(IntegerLiteral.size() > 1);
24
25 if (IntegerLiteral[0] > '0') {
26 assert(IntegerLiteral[0] <= '9');
27 return Base::Decimal;
28 }
29
30 assert(IntegerLiteral[0] == '0');
31
32 switch (IntegerLiteral[1]) {
33 case 'b':
34 case 'B':
35 return Base::Binary;
36 case 'x':
37 case 'X':
38 return Base::Hex;
39 default:
40 return Base::Other;
41 }
42}
43
44std::pair<tooling::Replacements, unsigned>
46 const FormatStyle &Style) {
47 const auto LangOpts = getFormattingLangOpts(Style);
48
49 switch (Style.Language) {
50 case FormatStyle::LK_CSharp:
51 case FormatStyle::LK_Java:
52 case FormatStyle::LK_JavaScript:
53 Separator = '_';
54 break;
55 case FormatStyle::LK_C:
56 case FormatStyle::LK_Cpp:
57 case FormatStyle::LK_ObjC:
58 if (!LangOpts.AllowLiteralDigitSeparator)
59 return {};
60 Separator = '\'';
61 break;
62 default:
63 return {};
64 }
65
66 const auto &Option = Style.IntegerLiteralSeparator;
67 const auto Binary = Option.Binary;
68 const auto Decimal = Option.Decimal;
69 const auto Hex = Option.Hex;
70 const bool SkipBinary = Binary == 0;
71 const bool SkipDecimal = Decimal == 0;
72 const bool SkipHex = Hex == 0;
73
74 if (SkipBinary && SkipDecimal && SkipHex)
75 return {};
76
77 auto CalcMinAndMax = [](int DigitsPerGroup, int MinDigitsInsert,
78 int MaxDigitsRemove) {
79 MinDigitsInsert = std::max(MinDigitsInsert, DigitsPerGroup + 1);
80 if (MinDigitsInsert < 1)
81 MaxDigitsRemove = 0;
82 else if (MaxDigitsRemove < 1 || MaxDigitsRemove >= MinDigitsInsert)
83 MaxDigitsRemove = MinDigitsInsert - 1;
84 return std::pair(MinDigitsInsert, MaxDigitsRemove);
85 };
86
87 const auto [BinaryMinDigitsInsert, BinaryMaxDigitsRemove] = CalcMinAndMax(
88 Binary, Option.BinaryMinDigitsInsert, Option.BinaryMaxDigitsRemove);
89 const auto [DecimalMinDigitsInsert, DecimalMaxDigitsRemove] = CalcMinAndMax(
90 Decimal, Option.DecimalMinDigitsInsert, Option.DecimalMaxDigitsRemove);
91 const auto [HexMinDigitsInsert, HexMaxDigitsRemove] =
92 CalcMinAndMax(Hex, Option.HexMinDigitsInsert, Option.HexMaxDigitsRemove);
93
94 const auto &SourceMgr = Env.getSourceManager();
95 AffectedRangeManager AffectedRangeMgr(SourceMgr, Env.getCharRanges());
96
97 const auto ID = Env.getFileID();
98 Lexer Lex(ID, SourceMgr.getBufferOrFake(ID), SourceMgr, LangOpts);
100
101 Token Tok;
103
104 for (bool Skip = false; !Lex.LexFromRawLexer(Tok);) {
105 auto Length = Tok.getLength();
106 if (Length < 2)
107 continue;
108 auto Location = Tok.getLocation();
109 auto Text = StringRef(SourceMgr.getCharacterData(Location), Length);
110 if (Tok.is(tok::comment)) {
112 Skip = true;
113 else if (isClangFormatOn(Text))
114 Skip = false;
115 continue;
116 }
117 if (Skip || Tok.isNot(tok::numeric_constant) || Text[0] == '.' ||
118 !AffectedRangeMgr.affectsCharSourceRange(
119 CharSourceRange::getCharRange(Location, Tok.getEndLoc()))) {
120 continue;
121 }
122 const auto B = getBase(Text);
123 const bool IsBase2 = B == Base::Binary;
124 const bool IsBase10 = B == Base::Decimal;
125 const bool IsBase16 = B == Base::Hex;
126 if ((IsBase2 && SkipBinary) || (IsBase10 && SkipDecimal) ||
127 (IsBase16 && SkipHex) || B == Base::Other) {
128 continue;
129 }
130 if (Style.isCpp()) {
131 // Hex alpha digits a-f/A-F must be at the end of the string literal.
132 static constexpr StringRef Suffixes("_himnsuyd");
133 if (const auto Pos =
134 Text.find_first_of(IsBase16 ? Suffixes.drop_back() : Suffixes);
135 Pos != StringRef::npos) {
136 Text = Text.substr(0, Pos);
137 Length = Pos;
138 }
139 }
140 if ((IsBase10 && Text.find_last_of(".eEfFdDmM") != StringRef::npos) ||
141 (IsBase16 && Text.find_last_of(".pP") != StringRef::npos)) {
142 continue;
143 }
144 const auto Start = Text[0] == '0' ? 2 : 0;
145 auto End = Text.find_first_of("uUlLzZn", Start);
146 if (End == StringRef::npos)
147 End = Length;
148 if (Start > 0 || End < Length) {
149 Length = End - Start;
150 Text = Text.substr(Start, Length);
151 }
152 auto DigitsPerGroup = Decimal;
153 auto MinDigitsInsert = DecimalMinDigitsInsert;
154 auto MaxDigitsRemove = DecimalMaxDigitsRemove;
155 if (IsBase2) {
156 DigitsPerGroup = Binary;
157 MinDigitsInsert = BinaryMinDigitsInsert;
158 MaxDigitsRemove = BinaryMaxDigitsRemove;
159 } else if (IsBase16) {
160 DigitsPerGroup = Hex;
161 MinDigitsInsert = HexMinDigitsInsert;
162 MaxDigitsRemove = HexMaxDigitsRemove;
163 }
164 const auto SeparatorCount = Text.count(Separator);
165 const int DigitCount = Length - SeparatorCount;
166 if (DigitCount > MaxDigitsRemove && DigitCount < MinDigitsInsert)
167 continue;
168 const bool RemoveSeparator =
169 DigitsPerGroup < 0 || DigitCount <= MaxDigitsRemove;
170 if (RemoveSeparator && SeparatorCount == 0)
171 continue;
172 if (!RemoveSeparator && SeparatorCount > 0 &&
173 checkSeparator(Text, DigitsPerGroup)) {
174 continue;
175 }
176 const auto &Formatted =
177 format(Text, DigitsPerGroup, DigitCount, RemoveSeparator);
178 assert(Formatted != Text);
179 if (Start > 0)
180 Location = Location.getLocWithOffset(Start);
181 cantFail(Result.add(
182 tooling::Replacement(SourceMgr, Location, Length, Formatted)));
183 }
184
185 return {Result, 0};
186}
187
188bool IntegerLiteralSeparatorFixer::checkSeparator(StringRef IntegerLiteral,
189 int DigitsPerGroup) const {
190 assert(DigitsPerGroup > 0);
191
192 int I = 0;
193 for (auto C : llvm::reverse(IntegerLiteral)) {
194 if (C == Separator) {
195 if (I < DigitsPerGroup)
196 return false;
197 I = 0;
198 } else {
199 if (I == DigitsPerGroup)
200 return false;
201 ++I;
202 }
203 }
204
205 return true;
206}
207
208std::string IntegerLiteralSeparatorFixer::format(StringRef IntegerLiteral,
209 int DigitsPerGroup,
210 int DigitCount,
211 bool RemoveSeparator) const {
212 assert(DigitsPerGroup != 0);
213
214 std::string Formatted;
215
216 if (RemoveSeparator) {
217 for (auto C : IntegerLiteral)
218 if (C != Separator)
219 Formatted.push_back(C);
220 return Formatted;
221 }
222
223 int Remainder = DigitCount % DigitsPerGroup;
224
225 int I = 0;
226 for (auto C : IntegerLiteral) {
227 if (C == Separator)
228 continue;
229 if (I == (Remainder > 0 ? Remainder : DigitsPerGroup)) {
230 Formatted.push_back(Separator);
231 I = 0;
232 Remainder = 0;
233 }
234 Formatted.push_back(C);
235 ++I;
236 }
237
238 return Formatted;
239}
240
241} // namespace format
242} // namespace clang
static constexpr CPUSuffix Suffixes[]
Definition Hexagon.cpp:261
Token Tok
The Token.
This file declares IntegerLiteralSeparatorFixer that fixes C++ integer literal separators.
static CharSourceRange getCharRange(SourceRange R)
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens.
Definition Lexer.h:78
bool LexFromRawLexer(Token &Result)
LexFromRawLexer - Lex a token from a designated raw lexer (one with no associated preprocessor object...
Definition Lexer.h:236
void SetCommentRetentionState(bool Mode)
SetCommentRetentionMode - Change the comment retention mode of the lexer to the specified mode.
Definition Lexer.h:269
Token - This structure provides full information about a lexed token.
Definition Token.h:36
bool affectsCharSourceRange(const CharSourceRange &Range)
SourceManager & getSourceManager() const
ArrayRef< CharSourceRange > getCharRanges() const
std::pair< tooling::Replacements, unsigned > process(const Environment &Env, const FormatStyle &Style)
A text replacement.
Definition Replacement.h:83
Maintains a set of replacements that are conflict-free.
static Base getBase(StringRef IntegerLiteral)
bool isClangFormatOff(StringRef Comment)
Definition Format.cpp:4712
bool isClangFormatOn(StringRef Comment)
Definition Format.cpp:4708
LangOptions getFormattingLangOpts(const FormatStyle &Style)
Definition Format.cpp:4316
The JSON file list parser is used to communicate input to InstallAPI.
@ Result
The result type of a method or function.
Definition TypeBase.h:905