Bug Summary

File:clang/lib/Format/ContinuationIndenter.cpp
Warning:line 564, column 9
Access to field 'PartOfMultiVariableDeclStmt' results in a dereference of a null pointer (loaded from variable 'Previous')

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ContinuationIndenter.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Format -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Format -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-11/lib/clang/11.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Format -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Format/ContinuationIndenter.cpp

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Format/ContinuationIndenter.cpp

1//===--- ContinuationIndenter.cpp - Format C++ code -----------------------===//
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 the continuation indenter.
11///
12//===----------------------------------------------------------------------===//
13
14#include "ContinuationIndenter.h"
15#include "BreakableToken.h"
16#include "FormatInternal.h"
17#include "WhitespaceManager.h"
18#include "clang/Basic/OperatorPrecedence.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Format/Format.h"
21#include "llvm/Support/Debug.h"
22
23#define DEBUG_TYPE"format-indenter" "format-indenter"
24
25namespace clang {
26namespace format {
27
28// Returns true if a TT_SelectorName should be indented when wrapped,
29// false otherwise.
30static bool shouldIndentWrappedSelectorName(const FormatStyle &Style,
31 LineType LineType) {
32 return Style.IndentWrappedFunctionNames || LineType == LT_ObjCMethodDecl;
33}
34
35// Returns the length of everything up to the first possible line break after
36// the ), ], } or > matching \c Tok.
37static unsigned getLengthToMatchingParen(const FormatToken &Tok,
38 const std::vector<ParenState> &Stack) {
39 // Normally whether or not a break before T is possible is calculated and
40 // stored in T.CanBreakBefore. Braces, array initializers and text proto
41 // messages like `key: < ... >` are an exception: a break is possible
42 // before a closing brace R if a break was inserted after the corresponding
43 // opening brace. The information about whether or not a break is needed
44 // before a closing brace R is stored in the ParenState field
45 // S.BreakBeforeClosingBrace where S is the state that R closes.
46 //
47 // In order to decide whether there can be a break before encountered right
48 // braces, this implementation iterates over the sequence of tokens and over
49 // the paren stack in lockstep, keeping track of the stack level which visited
50 // right braces correspond to in MatchingStackIndex.
51 //
52 // For example, consider:
53 // L. <- line number
54 // 1. {
55 // 2. {1},
56 // 3. {2},
57 // 4. {{3}}}
58 // ^ where we call this method with this token.
59 // The paren stack at this point contains 3 brace levels:
60 // 0. { at line 1, BreakBeforeClosingBrace: true
61 // 1. first { at line 4, BreakBeforeClosingBrace: false
62 // 2. second { at line 4, BreakBeforeClosingBrace: false,
63 // where there might be fake parens levels in-between these levels.
64 // The algorithm will start at the first } on line 4, which is the matching
65 // brace of the initial left brace and at level 2 of the stack. Then,
66 // examining BreakBeforeClosingBrace: false at level 2, it will continue to
67 // the second } on line 4, and will traverse the stack downwards until it
68 // finds the matching { on level 1. Then, examining BreakBeforeClosingBrace:
69 // false at level 1, it will continue to the third } on line 4 and will
70 // traverse the stack downwards until it finds the matching { on level 0.
71 // Then, examining BreakBeforeClosingBrace: true at level 0, the algorithm
72 // will stop and will use the second } on line 4 to determine the length to
73 // return, as in this example the range will include the tokens: {3}}
74 //
75 // The algorithm will only traverse the stack if it encounters braces, array
76 // initializer squares or text proto angle brackets.
77 if (!Tok.MatchingParen)
78 return 0;
79 FormatToken *End = Tok.MatchingParen;
80 // Maintains a stack level corresponding to the current End token.
81 int MatchingStackIndex = Stack.size() - 1;
82 // Traverses the stack downwards, looking for the level to which LBrace
83 // corresponds. Returns either a pointer to the matching level or nullptr if
84 // LParen is not found in the initial portion of the stack up to
85 // MatchingStackIndex.
86 auto FindParenState = [&](const FormatToken *LBrace) -> const ParenState * {
87 while (MatchingStackIndex >= 0 && Stack[MatchingStackIndex].Tok != LBrace)
88 --MatchingStackIndex;
89 return MatchingStackIndex >= 0 ? &Stack[MatchingStackIndex] : nullptr;
90 };
91 for (; End->Next; End = End->Next) {
92 if (End->Next->CanBreakBefore)
93 break;
94 if (!End->Next->closesScope())
95 continue;
96 if (End->Next->MatchingParen &&
97 End->Next->MatchingParen->isOneOf(
98 tok::l_brace, TT_ArrayInitializerLSquare, tok::less)) {
99 const ParenState *State = FindParenState(End->Next->MatchingParen);
100 if (State && State->BreakBeforeClosingBrace)
101 break;
102 }
103 }
104 return End->TotalLength - Tok.TotalLength + 1;
105}
106
107static unsigned getLengthToNextOperator(const FormatToken &Tok) {
108 if (!Tok.NextOperator)
109 return 0;
110 return Tok.NextOperator->TotalLength - Tok.TotalLength;
111}
112
113// Returns \c true if \c Tok is the "." or "->" of a call and starts the next
114// segment of a builder type call.
115static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) {
116 return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope();
117}
118
119// Returns \c true if \c Current starts a new parameter.
120static bool startsNextParameter(const FormatToken &Current,
121 const FormatStyle &Style) {
122 const FormatToken &Previous = *Current.Previous;
123 if (Current.is(TT_CtorInitializerComma) &&
124 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
125 return true;
126 if (Style.Language == FormatStyle::LK_Proto && Current.is(TT_SelectorName))
127 return true;
128 return Previous.is(tok::comma) && !Current.isTrailingComment() &&
129 ((Previous.isNot(TT_CtorInitializerComma) ||
130 Style.BreakConstructorInitializers !=
131 FormatStyle::BCIS_BeforeComma) &&
132 (Previous.isNot(TT_InheritanceComma) ||
133 Style.BreakInheritanceList != FormatStyle::BILS_BeforeComma));
134}
135
136static bool opensProtoMessageField(const FormatToken &LessTok,
137 const FormatStyle &Style) {
138 if (LessTok.isNot(tok::less))
139 return false;
140 return Style.Language == FormatStyle::LK_TextProto ||
141 (Style.Language == FormatStyle::LK_Proto &&
142 (LessTok.NestingLevel > 0 ||
143 (LessTok.Previous && LessTok.Previous->is(tok::equal))));
144}
145
146// Returns the delimiter of a raw string literal, or None if TokenText is not
147// the text of a raw string literal. The delimiter could be the empty string.
148// For example, the delimiter of R"deli(cont)deli" is deli.
149static llvm::Optional<StringRef> getRawStringDelimiter(StringRef TokenText) {
150 if (TokenText.size() < 5 // The smallest raw string possible is 'R"()"'.
151 || !TokenText.startswith("R\"") || !TokenText.endswith("\""))
152 return None;
153
154 // A raw string starts with 'R"<delimiter>(' and delimiter is ascii and has
155 // size at most 16 by the standard, so the first '(' must be among the first
156 // 19 bytes.
157 size_t LParenPos = TokenText.substr(0, 19).find_first_of('(');
158 if (LParenPos == StringRef::npos)
159 return None;
160 StringRef Delimiter = TokenText.substr(2, LParenPos - 2);
161
162 // Check that the string ends in ')Delimiter"'.
163 size_t RParenPos = TokenText.size() - Delimiter.size() - 2;
164 if (TokenText[RParenPos] != ')')
165 return None;
166 if (!TokenText.substr(RParenPos + 1).startswith(Delimiter))
167 return None;
168 return Delimiter;
169}
170
171// Returns the canonical delimiter for \p Language, or the empty string if no
172// canonical delimiter is specified.
173static StringRef
174getCanonicalRawStringDelimiter(const FormatStyle &Style,
175 FormatStyle::LanguageKind Language) {
176 for (const auto &Format : Style.RawStringFormats) {
177 if (Format.Language == Language)
178 return StringRef(Format.CanonicalDelimiter);
179 }
180 return "";
181}
182
183RawStringFormatStyleManager::RawStringFormatStyleManager(
184 const FormatStyle &CodeStyle) {
185 for (const auto &RawStringFormat : CodeStyle.RawStringFormats) {
186 llvm::Optional<FormatStyle> LanguageStyle =
187 CodeStyle.GetLanguageStyle(RawStringFormat.Language);
188 if (!LanguageStyle) {
189 FormatStyle PredefinedStyle;
190 if (!getPredefinedStyle(RawStringFormat.BasedOnStyle,
191 RawStringFormat.Language, &PredefinedStyle)) {
192 PredefinedStyle = getLLVMStyle();
193 PredefinedStyle.Language = RawStringFormat.Language;
194 }
195 LanguageStyle = PredefinedStyle;
196 }
197 LanguageStyle->ColumnLimit = CodeStyle.ColumnLimit;
198 for (StringRef Delimiter : RawStringFormat.Delimiters) {
199 DelimiterStyle.insert({Delimiter, *LanguageStyle});
200 }
201 for (StringRef EnclosingFunction : RawStringFormat.EnclosingFunctions) {
202 EnclosingFunctionStyle.insert({EnclosingFunction, *LanguageStyle});
203 }
204 }
205}
206
207llvm::Optional<FormatStyle>
208RawStringFormatStyleManager::getDelimiterStyle(StringRef Delimiter) const {
209 auto It = DelimiterStyle.find(Delimiter);
210 if (It == DelimiterStyle.end())
211 return None;
212 return It->second;
213}
214
215llvm::Optional<FormatStyle>
216RawStringFormatStyleManager::getEnclosingFunctionStyle(
217 StringRef EnclosingFunction) const {
218 auto It = EnclosingFunctionStyle.find(EnclosingFunction);
219 if (It == EnclosingFunctionStyle.end())
220 return None;
221 return It->second;
222}
223
224ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,
225 const AdditionalKeywords &Keywords,
226 const SourceManager &SourceMgr,
227 WhitespaceManager &Whitespaces,
228 encoding::Encoding Encoding,
229 bool BinPackInconclusiveFunctions)
230 : Style(Style), Keywords(Keywords), SourceMgr(SourceMgr),
231 Whitespaces(Whitespaces), Encoding(Encoding),
232 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
233 CommentPragmasRegex(Style.CommentPragmas), RawStringFormats(Style) {}
234
235LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
236 unsigned FirstStartColumn,
237 const AnnotatedLine *Line,
238 bool DryRun) {
239 LineState State;
240 State.FirstIndent = FirstIndent;
241 if (FirstStartColumn && Line->First->NewlinesBefore == 0)
242 State.Column = FirstStartColumn;
243 else
244 State.Column = FirstIndent;
245 // With preprocessor directive indentation, the line starts on column 0
246 // since it's indented after the hash, but FirstIndent is set to the
247 // preprocessor indent.
248 if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash &&
249 (Line->Type == LT_PreprocessorDirective ||
250 Line->Type == LT_ImportStatement))
251 State.Column = 0;
252 State.Line = Line;
253 State.NextToken = Line->First;
254 State.Stack.push_back(ParenState(/*Tok=*/nullptr, FirstIndent, FirstIndent,
255 /*AvoidBinPacking=*/false,
256 /*NoLineBreak=*/false));
257 State.LineContainsContinuedForLoopSection = false;
258 State.NoContinuation = false;
259 State.StartOfStringLiteral = 0;
260 State.StartOfLineLevel = 0;
261 State.LowestLevelOnLine = 0;
262 State.IgnoreStackForComparison = false;
263
264 if (Style.Language == FormatStyle::LK_TextProto) {
265 // We need this in order to deal with the bin packing of text fields at
266 // global scope.
267 State.Stack.back().AvoidBinPacking = true;
268 State.Stack.back().BreakBeforeParameter = true;
269 State.Stack.back().AlignColons = false;
270 }
271
272 // The first token has already been indented and thus consumed.
273 moveStateToNextToken(State, DryRun, /*Newline=*/false);
274 return State;
275}
276
277bool ContinuationIndenter::canBreak(const LineState &State) {
278 const FormatToken &Current = *State.NextToken;
279 const FormatToken &Previous = *Current.Previous;
280 assert(&Previous == Current.Previous)((&Previous == Current.Previous) ? static_cast<void>
(0) : __assert_fail ("&Previous == Current.Previous", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Format/ContinuationIndenter.cpp"
, 280, __PRETTY_FUNCTION__))
;
281 if (!Current.CanBreakBefore && !(State.Stack.back().BreakBeforeClosingBrace &&
282 Current.closesBlockOrBlockTypeList(Style)))
283 return false;
284 // The opening "{" of a braced list has to be on the same line as the first
285 // element if it is nested in another braced init list or function call.
286 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
287 Previous.isNot(TT_DictLiteral) && Previous.BlockKind == BK_BracedInit &&
288 Previous.Previous &&
289 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
290 return false;
291 // This prevents breaks like:
292 // ...
293 // SomeParameter, OtherParameter).DoSomething(
294 // ...
295 // As they hide "DoSomething" and are generally bad for readability.
296 if (Previous.opensScope() && Previous.isNot(tok::l_brace) &&
297 State.LowestLevelOnLine < State.StartOfLineLevel &&
298 State.LowestLevelOnLine < Current.NestingLevel)
299 return false;
300 if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
301 return false;
302
303 // Don't create a 'hanging' indent if there are multiple blocks in a single
304 // statement.
305 if (Previous.is(tok::l_brace) && State.Stack.size() > 1 &&
306 State.Stack[State.Stack.size() - 2].NestedBlockInlined &&
307 State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks)
308 return false;
309
310 // Don't break after very short return types (e.g. "void") as that is often
311 // unexpected.
312 if (Current.is(TT_FunctionDeclarationName) && State.Column < 6) {
313 if (Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None)
314 return false;
315 }
316
317 // If binary operators are moved to the next line (including commas for some
318 // styles of constructor initializers), that's always ok.
319 if (!Current.isOneOf(TT_BinaryOperator, tok::comma) &&
320 State.Stack.back().NoLineBreakInOperand)
321 return false;
322
323 if (Previous.is(tok::l_square) && Previous.is(TT_ObjCMethodExpr))
324 return false;
325
326 return !State.Stack.back().NoLineBreak;
327}
328
329bool ContinuationIndenter::mustBreak(const LineState &State) {
330 const FormatToken &Current = *State.NextToken;
331 const FormatToken &Previous = *Current.Previous;
332 if (Style.BraceWrapping.BeforeLambdaBody && Current.CanBreakBefore &&
333 Current.is(TT_LambdaLBrace)) {
334 auto LambdaBodyLength = getLengthToMatchingParen(Current, State.Stack);
335 return (LambdaBodyLength > getColumnLimit(State));
336 }
337 if (Current.MustBreakBefore || Current.is(TT_InlineASMColon))
338 return true;
339 if (State.Stack.back().BreakBeforeClosingBrace &&
340 Current.closesBlockOrBlockTypeList(Style))
341 return true;
342 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
343 return true;
344 if (Style.Language == FormatStyle::LK_ObjC &&
345 Current.ObjCSelectorNameParts > 1 &&
346 Current.startsSequence(TT_SelectorName, tok::colon, tok::caret)) {
347 return true;
348 }
349 if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
350 (Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) &&
351 Style.isCpp() &&
352 // FIXME: This is a temporary workaround for the case where clang-format
353 // sets BreakBeforeParameter to avoid bin packing and this creates a
354 // completely unnecessary line break after a template type that isn't
355 // line-wrapped.
356 (Previous.NestingLevel == 1 || Style.BinPackParameters)) ||
357 (Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&
358 Previous.isNot(tok::question)) ||
359 (!Style.BreakBeforeTernaryOperators &&
360 Previous.is(TT_ConditionalExpr))) &&
361 State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
362 !Current.isOneOf(tok::r_paren, tok::r_brace))
363 return true;
364 if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) ||
365 (Previous.is(TT_ArrayInitializerLSquare) &&
366 Previous.ParameterCount > 1) ||
367 opensProtoMessageField(Previous, Style)) &&
368 Style.ColumnLimit > 0 &&
369 getLengthToMatchingParen(Previous, State.Stack) + State.Column - 1 >
370 getColumnLimit(State))
371 return true;
372
373 const FormatToken &BreakConstructorInitializersToken =
374 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon
375 ? Previous
376 : Current;
377 if (BreakConstructorInitializersToken.is(TT_CtorInitializerColon) &&
378 (State.Column + State.Line->Last->TotalLength - Previous.TotalLength >
379 getColumnLimit(State) ||
380 State.Stack.back().BreakBeforeParameter) &&
381 (Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All ||
382 Style.BreakConstructorInitializers != FormatStyle::BCIS_BeforeColon ||
383 Style.ColumnLimit != 0))
384 return true;
385
386 if (Current.is(TT_ObjCMethodExpr) && !Previous.is(TT_SelectorName) &&
387 State.Line->startsWith(TT_ObjCMethodSpecifier))
388 return true;
389 if (Current.is(TT_SelectorName) && !Previous.is(tok::at) &&
390 State.Stack.back().ObjCSelectorNameFound &&
391 State.Stack.back().BreakBeforeParameter)
392 return true;
393
394 unsigned NewLineColumn = getNewLineColumn(State);
395 if (Current.isMemberAccess() && Style.ColumnLimit != 0 &&
396 State.Column + getLengthToNextOperator(Current) > Style.ColumnLimit &&
397 (State.Column > NewLineColumn ||
398 Current.NestingLevel < State.StartOfLineLevel))
399 return true;
400
401 if (startsSegmentOfBuilderTypeCall(Current) &&
402 (State.Stack.back().CallContinuation != 0 ||
403 State.Stack.back().BreakBeforeParameter) &&
404 // JavaScript is treated different here as there is a frequent pattern:
405 // SomeFunction(function() {
406 // ...
407 // }.bind(...));
408 // FIXME: We should find a more generic solution to this problem.
409 !(State.Column <= NewLineColumn &&
410 Style.Language == FormatStyle::LK_JavaScript) &&
411 !(Previous.closesScopeAfterBlock() && State.Column <= NewLineColumn))
412 return true;
413
414 // If the template declaration spans multiple lines, force wrap before the
415 // function/class declaration
416 if (Previous.ClosesTemplateDeclaration &&
417 State.Stack.back().BreakBeforeParameter && Current.CanBreakBefore)
418 return true;
419
420 if (State.Column <= NewLineColumn)
421 return false;
422
423 if (Style.AlwaysBreakBeforeMultilineStrings &&
424 (NewLineColumn == State.FirstIndent + Style.ContinuationIndentWidth ||
425 Previous.is(tok::comma) || Current.NestingLevel < 2) &&
426 !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at,
427 Keywords.kw_dollar) &&
428 !Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) &&
429 nextIsMultilineString(State))
430 return true;
431
432 // Using CanBreakBefore here and below takes care of the decision whether the
433 // current style uses wrapping before or after operators for the given
434 // operator.
435 if (Previous.is(TT_BinaryOperator) && Current.CanBreakBefore) {
436 // If we need to break somewhere inside the LHS of a binary expression, we
437 // should also break after the operator. Otherwise, the formatting would
438 // hide the operator precedence, e.g. in:
439 // if (aaaaaaaaaaaaaa ==
440 // bbbbbbbbbbbbbb && c) {..
441 // For comparisons, we only apply this rule, if the LHS is a binary
442 // expression itself as otherwise, the line breaks seem superfluous.
443 // We need special cases for ">>" which we have split into two ">" while
444 // lexing in order to make template parsing easier.
445 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
446 Previous.getPrecedence() == prec::Equality ||
447 Previous.getPrecedence() == prec::Spaceship) &&
448 Previous.Previous &&
449 Previous.Previous->isNot(TT_BinaryOperator); // For >>.
450 bool LHSIsBinaryExpr =
451 Previous.Previous && Previous.Previous->EndsBinaryExpression;
452 if ((!IsComparison || LHSIsBinaryExpr) && !Current.isTrailingComment() &&
453 Previous.getPrecedence() != prec::Assignment &&
454 State.Stack.back().BreakBeforeParameter)
455 return true;
456 } else if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore &&
457 State.Stack.back().BreakBeforeParameter) {
458 return true;
459 }
460
461 // Same as above, but for the first "<<" operator.
462 if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator) &&
463 State.Stack.back().BreakBeforeParameter &&
464 State.Stack.back().FirstLessLess == 0)
465 return true;
466
467 if (Current.NestingLevel == 0 && !Current.isTrailingComment()) {
468 // Always break after "template <...>" and leading annotations. This is only
469 // for cases where the entire line does not fit on a single line as a
470 // different LineFormatter would be used otherwise.
471 if (Previous.ClosesTemplateDeclaration)
472 return Style.AlwaysBreakTemplateDeclarations != FormatStyle::BTDS_No;
473 if (Previous.is(TT_FunctionAnnotationRParen))
474 return true;
475 if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) &&
476 Current.isNot(TT_LeadingJavaAnnotation))
477 return true;
478 }
479
480 // If the return type spans multiple lines, wrap before the function name.
481 if (((Current.is(TT_FunctionDeclarationName) &&
482 // Don't break before a C# function when no break after return type
483 (!Style.isCSharp() ||
484 Style.AlwaysBreakAfterReturnType != FormatStyle::RTBS_None)) ||
485 (Current.is(tok::kw_operator) && !Previous.is(tok::coloncolon))) &&
486 !Previous.is(tok::kw_template) && State.Stack.back().BreakBeforeParameter)
487 return true;
488
489 // The following could be precomputed as they do not depend on the state.
490 // However, as they should take effect only if the UnwrappedLine does not fit
491 // into the ColumnLimit, they are checked here in the ContinuationIndenter.
492 if (Style.ColumnLimit != 0 && Previous.BlockKind == BK_Block &&
493 Previous.is(tok::l_brace) && !Current.isOneOf(tok::r_brace, tok::comment))
494 return true;
495
496 if (Current.is(tok::lessless) &&
497 ((Previous.is(tok::identifier) && Previous.TokenText == "endl") ||
498 (Previous.Tok.isLiteral() && (Previous.TokenText.endswith("\\n\"") ||
499 Previous.TokenText == "\'\\n\'"))))
500 return true;
501
502 if (Previous.is(TT_BlockComment) && Previous.IsMultiline)
503 return true;
504
505 if (State.NoContinuation)
506 return true;
507
508 return false;
509}
510
511unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
512 bool DryRun,
513 unsigned ExtraSpaces) {
514 const FormatToken &Current = *State.NextToken;
515
516 assert(!State.Stack.empty())((!State.Stack.empty()) ? static_cast<void> (0) : __assert_fail
("!State.Stack.empty()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Format/ContinuationIndenter.cpp"
, 516, __PRETTY_FUNCTION__))
;
517 State.NoContinuation = false;
518
519 if ((Current.is(TT_ImplicitStringLiteral) &&
520 (Current.Previous->Tok.getIdentifierInfo() == nullptr ||
521 Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
522 tok::pp_not_keyword))) {
523 unsigned EndColumn =
524 SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getEnd());
525 if (Current.LastNewlineOffset != 0) {
526 // If there is a newline within this token, the final column will solely
527 // determined by the current end column.
528 State.Column = EndColumn;
529 } else {
530 unsigned StartColumn =
531 SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getBegin());
532 assert(EndColumn >= StartColumn)((EndColumn >= StartColumn) ? static_cast<void> (0) :
__assert_fail ("EndColumn >= StartColumn", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Format/ContinuationIndenter.cpp"
, 532, __PRETTY_FUNCTION__))
;
533 State.Column += EndColumn - StartColumn;
534 }
535 moveStateToNextToken(State, DryRun, /*Newline=*/false);
536 return 0;
537 }
538
539 unsigned Penalty = 0;
540 if (Newline)
541 Penalty = addTokenOnNewLine(State, DryRun);
542 else
543 addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
544
545 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
546}
547
548void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
549 unsigned ExtraSpaces) {
550 FormatToken &Current = *State.NextToken;
551 const FormatToken &Previous = *State.NextToken->Previous;
1
'Previous' initialized here
552 if (Current.is(tok::equal) &&
2
Calling 'FormatToken::is'
8
Returning from 'FormatToken::is'
17
Taking true branch
553 (State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) &&
9
Calling 'FormatToken::is'
15
Returning from 'FormatToken::is'
554 State.Stack.back().VariablePos == 0) {
16
Assuming field 'VariablePos' is equal to 0
555 State.Stack.back().VariablePos = State.Column;
556 // Move over * and & if they are bound to the variable name.
557 const FormatToken *Tok = &Previous;
558 while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
18
Assuming 'Tok' is null
559 State.Stack.back().VariablePos -= Tok->ColumnWidth;
560 if (Tok->SpacesRequiredBefore != 0)
561 break;
562 Tok = Tok->Previous;
563 }
564 if (Previous.PartOfMultiVariableDeclStmt)
19
Access to field 'PartOfMultiVariableDeclStmt' results in a dereference of a null pointer (loaded from variable 'Previous')
565 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
566 }
567
568 unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
569
570 // Indent preprocessor directives after the hash if required.
571 int PPColumnCorrection = 0;
572 if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash &&
573 Previous.is(tok::hash) && State.FirstIndent > 0 &&
574 (State.Line->Type == LT_PreprocessorDirective ||
575 State.Line->Type == LT_ImportStatement)) {
576 Spaces += State.FirstIndent;
577
578 // For preprocessor indent with tabs, State.Column will be 1 because of the
579 // hash. This causes second-level indents onward to have an extra space
580 // after the tabs. We avoid this misalignment by subtracting 1 from the
581 // column value passed to replaceWhitespace().
582 if (Style.UseTab != FormatStyle::UT_Never)
583 PPColumnCorrection = -1;
584 }
585
586 if (!DryRun)
587 Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, Spaces,
588 State.Column + Spaces + PPColumnCorrection);
589
590 // If "BreakBeforeInheritanceComma" mode, don't break within the inheritance
591 // declaration unless there is multiple inheritance.
592 if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&
593 Current.is(TT_InheritanceColon))
594 State.Stack.back().NoLineBreak = true;
595 if (Style.BreakInheritanceList == FormatStyle::BILS_AfterColon &&
596 Previous.is(TT_InheritanceColon))
597 State.Stack.back().NoLineBreak = true;
598
599 if (Current.is(TT_SelectorName) &&
600 !State.Stack.back().ObjCSelectorNameFound) {
601 unsigned MinIndent =
602 std::max(State.FirstIndent + Style.ContinuationIndentWidth,
603 State.Stack.back().Indent);
604 unsigned FirstColonPos = State.Column + Spaces + Current.ColumnWidth;
605 if (Current.LongestObjCSelectorName == 0)
606 State.Stack.back().AlignColons = false;
607 else if (MinIndent + Current.LongestObjCSelectorName > FirstColonPos)
608 State.Stack.back().ColonPos = MinIndent + Current.LongestObjCSelectorName;
609 else
610 State.Stack.back().ColonPos = FirstColonPos;
611 }
612
613 // In "AlwaysBreak" mode, enforce wrapping directly after the parenthesis by
614 // disallowing any further line breaks if there is no line break after the
615 // opening parenthesis. Don't break if it doesn't conserve columns.
616 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_AlwaysBreak &&
617 (Previous.isOneOf(tok::l_paren, TT_TemplateOpener, tok::l_square) ||
618 (Previous.is(tok::l_brace) && Previous.BlockKind != BK_Block &&
619 Style.Cpp11BracedListStyle)) &&
620 State.Column > getNewLineColumn(State) &&
621 (!Previous.Previous || !Previous.Previous->isOneOf(
622 tok::kw_for, tok::kw_while, tok::kw_switch)) &&
623 // Don't do this for simple (no expressions) one-argument function calls
624 // as that feels like needlessly wasting whitespace, e.g.:
625 //
626 // caaaaaaaaaaaall(
627 // caaaaaaaaaaaall(
628 // caaaaaaaaaaaall(
629 // caaaaaaaaaaaaaaaaaaaaaaall(aaaaaaaaaaaaaa, aaaaaaaaa))));
630 Current.FakeLParens.size() > 0 &&
631 Current.FakeLParens.back() > prec::Unknown)
632 State.Stack.back().NoLineBreak = true;
633 if (Previous.is(TT_TemplateString) && Previous.opensScope())
634 State.Stack.back().NoLineBreak = true;
635
636 if (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign &&
637 Previous.opensScope() && Previous.isNot(TT_ObjCMethodExpr) &&
638 (Current.isNot(TT_LineComment) || Previous.BlockKind == BK_BracedInit))
639 State.Stack.back().Indent = State.Column + Spaces;
640 if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
641 State.Stack.back().NoLineBreak = true;
642 if (startsSegmentOfBuilderTypeCall(Current) &&
643 State.Column > getNewLineColumn(State))
644 State.Stack.back().ContainsUnwrappedBuilder = true;
645
646 if (Current.is(TT_LambdaArrow) && Style.Language == FormatStyle::LK_Java)
647 State.Stack.back().NoLineBreak = true;
648 if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&
649 (Previous.MatchingParen &&
650 (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10)))
651 // If there is a function call with long parameters, break before trailing
652 // calls. This prevents things like:
653 // EXPECT_CALL(SomeLongParameter).Times(
654 // 2);
655 // We don't want to do this for short parameters as they can just be
656 // indexes.
657 State.Stack.back().NoLineBreak = true;
658
659 // Don't allow the RHS of an operator to be split over multiple lines unless
660 // there is a line-break right after the operator.
661 // Exclude relational operators, as there, it is always more desirable to
662 // have the LHS 'left' of the RHS.
663 const FormatToken *P = Current.getPreviousNonComment();
664 if (!Current.is(tok::comment) && P &&
665 (P->isOneOf(TT_BinaryOperator, tok::comma) ||
666 (P->is(TT_ConditionalExpr) && P->is(tok::colon))) &&
667 !P->isOneOf(TT_OverloadedOperator, TT_CtorInitializerComma) &&
668 P->getPrecedence() != prec::Assignment &&
669 P->getPrecedence() != prec::Relational &&
670 P->getPrecedence() != prec::Spaceship) {
671 bool BreakBeforeOperator =
672 P->MustBreakBefore || P->is(tok::lessless) ||
673 (P->is(TT_BinaryOperator) &&
674 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) ||
675 (P->is(TT_ConditionalExpr) && Style.BreakBeforeTernaryOperators);
676 // Don't do this if there are only two operands. In these cases, there is
677 // always a nice vertical separation between them and the extra line break
678 // does not help.
679 bool HasTwoOperands =
680 P->OperatorIndex == 0 && !P->NextOperator && !P->is(TT_ConditionalExpr);
681 if ((!BreakBeforeOperator && !(HasTwoOperands && Style.AlignOperands)) ||
682 (!State.Stack.back().LastOperatorWrapped && BreakBeforeOperator))
683 State.Stack.back().NoLineBreakInOperand = true;
684 }
685
686 State.Column += Spaces;
687 if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&
688 Previous.Previous &&
689 (Previous.Previous->is(tok::kw_for) || Previous.Previous->isIf())) {
690 // Treat the condition inside an if as if it was a second function
691 // parameter, i.e. let nested calls have a continuation indent.
692 State.Stack.back().LastSpace = State.Column;
693 State.Stack.back().NestedBlockIndent = State.Column;
694 } else if (!Current.isOneOf(tok::comment, tok::caret) &&
695 ((Previous.is(tok::comma) &&
696 !Previous.is(TT_OverloadedOperator)) ||
697 (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) {
698 State.Stack.back().LastSpace = State.Column;
699 } else if (Previous.is(TT_CtorInitializerColon) &&
700 Style.BreakConstructorInitializers ==
701 FormatStyle::BCIS_AfterColon) {
702 State.Stack.back().Indent = State.Column;
703 State.Stack.back().LastSpace = State.Column;
704 } else if ((Previous.isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
705 TT_CtorInitializerColon)) &&
706 ((Previous.getPrecedence() != prec::Assignment &&
707 (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||
708 Previous.NextOperator)) ||
709 Current.StartsBinaryExpression)) {
710 // Indent relative to the RHS of the expression unless this is a simple
711 // assignment without binary expression on the RHS. Also indent relative to
712 // unary operators and the colons of constructor initializers.
713 if (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None)
714 State.Stack.back().LastSpace = State.Column;
715 } else if (Previous.is(TT_InheritanceColon)) {
716 State.Stack.back().Indent = State.Column;
717 State.Stack.back().LastSpace = State.Column;
718 } else if (Previous.opensScope()) {
719 // If a function has a trailing call, indent all parameters from the
720 // opening parenthesis. This avoids confusing indents like:
721 // OuterFunction(InnerFunctionCall( // break
722 // ParameterToInnerFunction)) // break
723 // .SecondInnerFunctionCall();
724 bool HasTrailingCall = false;
725 if (Previous.MatchingParen) {
726 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
727 HasTrailingCall = Next && Next->isMemberAccess();
728 }
729 if (HasTrailingCall && State.Stack.size() > 1 &&
730 State.Stack[State.Stack.size() - 2].CallContinuation == 0)
731 State.Stack.back().LastSpace = State.Column;
732 }
733}
734
735unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
736 bool DryRun) {
737 FormatToken &Current = *State.NextToken;
738 const FormatToken &Previous = *State.NextToken->Previous;
739
740 // Extra penalty that needs to be added because of the way certain line
741 // breaks are chosen.
742 unsigned Penalty = 0;
743
744 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
745 const FormatToken *NextNonComment = Previous.getNextNonComment();
746 if (!NextNonComment)
747 NextNonComment = &Current;
748 // The first line break on any NestingLevel causes an extra penalty in order
749 // prefer similar line breaks.
750 if (!State.Stack.back().ContainsLineBreak)
751 Penalty += 15;
752 State.Stack.back().ContainsLineBreak = true;
753
754 Penalty += State.NextToken->SplitPenalty;
755
756 // Breaking before the first "<<" is generally not desirable if the LHS is
757 // short. Also always add the penalty if the LHS is split over multiple lines
758 // to avoid unnecessary line breaks that just work around this penalty.
759 if (NextNonComment->is(tok::lessless) &&
760 State.Stack.back().FirstLessLess == 0 &&
761 (State.Column <= Style.ColumnLimit / 3 ||
762 State.Stack.back().BreakBeforeParameter))
763 Penalty += Style.PenaltyBreakFirstLessLess;
764
765 State.Column = getNewLineColumn(State);
766
767 // Indent nested blocks relative to this column, unless in a very specific
768 // JavaScript special case where:
769 //
770 // var loooooong_name =
771 // function() {
772 // // code
773 // }
774 //
775 // is common and should be formatted like a free-standing function. The same
776 // goes for wrapping before the lambda return type arrow.
777 if (!Current.is(TT_LambdaArrow) &&
778 (Style.Language != FormatStyle::LK_JavaScript ||
779 Current.NestingLevel != 0 || !PreviousNonComment ||
780 !PreviousNonComment->is(tok::equal) ||
781 !Current.isOneOf(Keywords.kw_async, Keywords.kw_function)))
782 State.Stack.back().NestedBlockIndent = State.Column;
783
784 if (NextNonComment->isMemberAccess()) {
785 if (State.Stack.back().CallContinuation == 0)
786 State.Stack.back().CallContinuation = State.Column;
787 } else if (NextNonComment->is(TT_SelectorName)) {
788 if (!State.Stack.back().ObjCSelectorNameFound) {
789 if (NextNonComment->LongestObjCSelectorName == 0) {
790 State.Stack.back().AlignColons = false;
791 } else {
792 State.Stack.back().ColonPos =
793 (shouldIndentWrappedSelectorName(Style, State.Line->Type)
794 ? std::max(State.Stack.back().Indent,
795 State.FirstIndent + Style.ContinuationIndentWidth)
796 : State.Stack.back().Indent) +
797 std::max(NextNonComment->LongestObjCSelectorName,
798 NextNonComment->ColumnWidth);
799 }
800 } else if (State.Stack.back().AlignColons &&
801 State.Stack.back().ColonPos <= NextNonComment->ColumnWidth) {
802 State.Stack.back().ColonPos = State.Column + NextNonComment->ColumnWidth;
803 }
804 } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
805 PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
806 // FIXME: This is hacky, find a better way. The problem is that in an ObjC
807 // method expression, the block should be aligned to the line starting it,
808 // e.g.:
809 // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
810 // ^(int *i) {
811 // // ...
812 // }];
813 // Thus, we set LastSpace of the next higher NestingLevel, to which we move
814 // when we consume all of the "}"'s FakeRParens at the "{".
815 if (State.Stack.size() > 1)
816 State.Stack[State.Stack.size() - 2].LastSpace =
817 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
818 Style.ContinuationIndentWidth;
819 }
820
821 if ((PreviousNonComment &&
822 PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
823 !State.Stack.back().AvoidBinPacking) ||
824 Previous.is(TT_BinaryOperator))
825 State.Stack.back().BreakBeforeParameter = false;
826 if (PreviousNonComment &&
827 PreviousNonComment->isOneOf(TT_TemplateCloser, TT_JavaAnnotation) &&
828 Current.NestingLevel == 0)
829 State.Stack.back().BreakBeforeParameter = false;
830 if (NextNonComment->is(tok::question) ||
831 (PreviousNonComment && PreviousNonComment->is(tok::question)))
832 State.Stack.back().BreakBeforeParameter = true;
833 if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore)
834 State.Stack.back().BreakBeforeParameter = false;
835
836 if (!DryRun) {
837 unsigned MaxEmptyLinesToKeep = Style.MaxEmptyLinesToKeep + 1;
838 if (Current.is(tok::r_brace) && Current.MatchingParen &&
839 // Only strip trailing empty lines for l_braces that have children, i.e.
840 // for function expressions (lambdas, arrows, etc).
841 !Current.MatchingParen->Children.empty()) {
842 // lambdas and arrow functions are expressions, thus their r_brace is not
843 // on its own line, and thus not covered by UnwrappedLineFormatter's logic
844 // about removing empty lines on closing blocks. Special case them here.
845 MaxEmptyLinesToKeep = 1;
846 }
847 unsigned Newlines =
848 std::max(1u, std::min(Current.NewlinesBefore, MaxEmptyLinesToKeep));
849 bool ContinuePPDirective =
850 State.Line->InPPDirective && State.Line->Type != LT_ImportStatement;
851 Whitespaces.replaceWhitespace(Current, Newlines, State.Column, State.Column,
852 ContinuePPDirective);
853 }
854
855 if (!Current.isTrailingComment())
856 State.Stack.back().LastSpace = State.Column;
857 if (Current.is(tok::lessless))
858 // If we are breaking before a "<<", we always want to indent relative to
859 // RHS. This is necessary only for "<<", as we special-case it and don't
860 // always indent relative to the RHS.
861 State.Stack.back().LastSpace += 3; // 3 -> width of "<< ".
862
863 State.StartOfLineLevel = Current.NestingLevel;
864 State.LowestLevelOnLine = Current.NestingLevel;
865
866 // Any break on this level means that the parent level has been broken
867 // and we need to avoid bin packing there.
868 bool NestedBlockSpecialCase =
869 (!Style.isCpp() && Current.is(tok::r_brace) && State.Stack.size() > 1 &&
870 State.Stack[State.Stack.size() - 2].NestedBlockInlined) ||
871 (Style.Language == FormatStyle::LK_ObjC && Current.is(tok::r_brace) &&
872 State.Stack.size() > 1 && !Style.ObjCBreakBeforeNestedBlockParam);
873 if (!NestedBlockSpecialCase)
874 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
875 State.Stack[i].BreakBeforeParameter = true;
876
877 if (PreviousNonComment &&
878 !PreviousNonComment->isOneOf(tok::comma, tok::colon, tok::semi) &&
879 (PreviousNonComment->isNot(TT_TemplateCloser) ||
880 Current.NestingLevel != 0) &&
881 !PreviousNonComment->isOneOf(
882 TT_BinaryOperator, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
883 TT_LeadingJavaAnnotation) &&
884 Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope())
885 State.Stack.back().BreakBeforeParameter = true;
886
887 // If we break after { or the [ of an array initializer, we should also break
888 // before the corresponding } or ].
889 if (PreviousNonComment &&
890 (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
891 opensProtoMessageField(*PreviousNonComment, Style)))
892 State.Stack.back().BreakBeforeClosingBrace = true;
893
894 if (State.Stack.back().AvoidBinPacking) {
895 // If we are breaking after '(', '{', '<', or this is the break after a ':'
896 // to start a member initializater list in a constructor, this should not
897 // be considered bin packing unless the relevant AllowAll option is false or
898 // this is a dict/object literal.
899 bool PreviousIsBreakingCtorInitializerColon =
900 Previous.is(TT_CtorInitializerColon) &&
901 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon;
902 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) ||
903 PreviousIsBreakingCtorInitializerColon) ||
904 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
905 State.Line->MustBeDeclaration) ||
906 (!Style.AllowAllArgumentsOnNextLine &&
907 !State.Line->MustBeDeclaration) ||
908 (!Style.AllowAllConstructorInitializersOnNextLine &&
909 PreviousIsBreakingCtorInitializerColon) ||
910 Previous.is(TT_DictLiteral))
911 State.Stack.back().BreakBeforeParameter = true;
912
913 // If we are breaking after a ':' to start a member initializer list,
914 // and we allow all arguments on the next line, we should not break
915 // before the next parameter.
916 if (PreviousIsBreakingCtorInitializerColon &&
917 Style.AllowAllConstructorInitializersOnNextLine)
918 State.Stack.back().BreakBeforeParameter = false;
919 }
920
921 return Penalty;
922}
923
924unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
925 if (!State.NextToken || !State.NextToken->Previous)
926 return 0;
927 FormatToken &Current = *State.NextToken;
928 const FormatToken &Previous = *Current.Previous;
929 // If we are continuing an expression, we want to use the continuation indent.
930 unsigned ContinuationIndent =
931 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
932 Style.ContinuationIndentWidth;
933 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
934 const FormatToken *NextNonComment = Previous.getNextNonComment();
935 if (!NextNonComment)
936 NextNonComment = &Current;
937
938 // Java specific bits.
939 if (Style.Language == FormatStyle::LK_Java &&
940 Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends))
941 return std::max(State.Stack.back().LastSpace,
942 State.Stack.back().Indent + Style.ContinuationIndentWidth);
943
944 if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths &&
945 State.Line->First->is(tok::kw_enum))
946 return (Style.IndentWidth * State.Line->First->IndentLevel) +
947 Style.IndentWidth;
948
949 if (NextNonComment->is(tok::l_brace) && NextNonComment->BlockKind == BK_Block)
950 return Current.NestingLevel == 0 ? State.FirstIndent
951 : State.Stack.back().Indent;
952 if ((Current.isOneOf(tok::r_brace, tok::r_square) ||
953 (Current.is(tok::greater) &&
954 (Style.Language == FormatStyle::LK_Proto ||
955 Style.Language == FormatStyle::LK_TextProto))) &&
956 State.Stack.size() > 1) {
957 if (Current.closesBlockOrBlockTypeList(Style))
958 return State.Stack[State.Stack.size() - 2].NestedBlockIndent;
959 if (Current.MatchingParen &&
960 Current.MatchingParen->BlockKind == BK_BracedInit)
961 return State.Stack[State.Stack.size() - 2].LastSpace;
962 return State.FirstIndent;
963 }
964 // Indent a closing parenthesis at the previous level if followed by a semi,
965 // const, or opening brace. This allows indentations such as:
966 // foo(
967 // a,
968 // );
969 // int Foo::getter(
970 // //
971 // ) const {
972 // return foo;
973 // }
974 // function foo(
975 // a,
976 // ) {
977 // code(); //
978 // }
979 if (Current.is(tok::r_paren) && State.Stack.size() > 1 &&
980 (!Current.Next ||
981 Current.Next->isOneOf(tok::semi, tok::kw_const, tok::l_brace)))
982 return State.Stack[State.Stack.size() - 2].LastSpace;
983 if (NextNonComment->is(TT_TemplateString) && NextNonComment->closesScope())
984 return State.Stack[State.Stack.size() - 2].LastSpace;
985 if (Current.is(tok::identifier) && Current.Next &&
986 (Current.Next->is(TT_DictLiteral) ||
987 ((Style.Language == FormatStyle::LK_Proto ||
988 Style.Language == FormatStyle::LK_TextProto) &&
989 Current.Next->isOneOf(tok::less, tok::l_brace))))
990 return State.Stack.back().Indent;
991 if (NextNonComment->is(TT_ObjCStringLiteral) &&
992 State.StartOfStringLiteral != 0)
993 return State.StartOfStringLiteral - 1;
994 if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
995 return State.StartOfStringLiteral;
996 if (NextNonComment->is(tok::lessless) &&
997 State.Stack.back().FirstLessLess != 0)
998 return State.Stack.back().FirstLessLess;
999 if (NextNonComment->isMemberAccess()) {
1000 if (State.Stack.back().CallContinuation == 0)
1001 return ContinuationIndent;
1002 return State.Stack.back().CallContinuation;
1003 }
1004 if (State.Stack.back().QuestionColumn != 0 &&
1005 ((NextNonComment->is(tok::colon) &&
1006 NextNonComment->is(TT_ConditionalExpr)) ||
1007 Previous.is(TT_ConditionalExpr)))
1008 return State.Stack.back().QuestionColumn;
1009 if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0)
1010 return State.Stack.back().VariablePos;
1011 if ((PreviousNonComment &&
1012 (PreviousNonComment->ClosesTemplateDeclaration ||
1013 PreviousNonComment->isOneOf(
1014 TT_AttributeParen, TT_AttributeSquare, TT_FunctionAnnotationRParen,
1015 TT_JavaAnnotation, TT_LeadingJavaAnnotation))) ||
1016 (!Style.IndentWrappedFunctionNames &&
1017 NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName)))
1018 return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
1019 if (NextNonComment->is(TT_SelectorName)) {
1020 if (!State.Stack.back().ObjCSelectorNameFound) {
1021 unsigned MinIndent = State.Stack.back().Indent;
1022 if (shouldIndentWrappedSelectorName(Style, State.Line->Type))
1023 MinIndent = std::max(MinIndent,
1024 State.FirstIndent + Style.ContinuationIndentWidth);
1025 // If LongestObjCSelectorName is 0, we are indenting the first
1026 // part of an ObjC selector (or a selector component which is
1027 // not colon-aligned due to block formatting).
1028 //
1029 // Otherwise, we are indenting a subsequent part of an ObjC
1030 // selector which should be colon-aligned to the longest
1031 // component of the ObjC selector.
1032 //
1033 // In either case, we want to respect Style.IndentWrappedFunctionNames.
1034 return MinIndent +
1035 std::max(NextNonComment->LongestObjCSelectorName,
1036 NextNonComment->ColumnWidth) -
1037 NextNonComment->ColumnWidth;
1038 }
1039 if (!State.Stack.back().AlignColons)
1040 return State.Stack.back().Indent;
1041 if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth)
1042 return State.Stack.back().ColonPos - NextNonComment->ColumnWidth;
1043 return State.Stack.back().Indent;
1044 }
1045 if (NextNonComment->is(tok::colon) && NextNonComment->is(TT_ObjCMethodExpr))
1046 return State.Stack.back().ColonPos;
1047 if (NextNonComment->is(TT_ArraySubscriptLSquare)) {
1048 if (State.Stack.back().StartOfArraySubscripts != 0)
1049 return State.Stack.back().StartOfArraySubscripts;
1050 return ContinuationIndent;
1051 }
1052
1053 // This ensure that we correctly format ObjC methods calls without inputs,
1054 // i.e. where the last element isn't selector like: [callee method];
1055 if (NextNonComment->is(tok::identifier) && NextNonComment->FakeRParens == 0 &&
1056 NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr))
1057 return State.Stack.back().Indent;
1058
1059 if (NextNonComment->isOneOf(TT_StartOfName, TT_PointerOrReference) ||
1060 Previous.isOneOf(tok::coloncolon, tok::equal, TT_JsTypeColon))
1061 return ContinuationIndent;
1062 if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
1063 PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))
1064 return ContinuationIndent;
1065 if (NextNonComment->is(TT_CtorInitializerComma))
1066 return State.Stack.back().Indent;
1067 if (PreviousNonComment && PreviousNonComment->is(TT_CtorInitializerColon) &&
1068 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon)
1069 return State.Stack.back().Indent;
1070 if (PreviousNonComment && PreviousNonComment->is(TT_InheritanceColon) &&
1071 Style.BreakInheritanceList == FormatStyle::BILS_AfterColon)
1072 return State.Stack.back().Indent;
1073 if (NextNonComment->isOneOf(TT_CtorInitializerColon, TT_InheritanceColon,
1074 TT_InheritanceComma))
1075 return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1076 if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() &&
1077 !Current.isOneOf(tok::colon, tok::comment))
1078 return ContinuationIndent;
1079 if (Current.is(TT_ProtoExtensionLSquare))
1080 return State.Stack.back().Indent;
1081 if (State.Stack.back().Indent == State.FirstIndent && PreviousNonComment &&
1082 !PreviousNonComment->isOneOf(tok::r_brace, TT_CtorInitializerComma))
1083 // Ensure that we fall back to the continuation indent width instead of
1084 // just flushing continuations left.
1085 return State.Stack.back().Indent + Style.ContinuationIndentWidth;
1086 return State.Stack.back().Indent;
1087}
1088
1089static bool hasNestedBlockInlined(const FormatToken *Previous,
1090 const FormatToken &Current,
1091 const FormatStyle &Style) {
1092 if (Previous->isNot(tok::l_paren))
1093 return true;
1094 if (Previous->ParameterCount > 1)
1095 return true;
1096
1097 // Also a nested block if contains a lambda inside function with 1 parameter
1098 return (Style.BraceWrapping.BeforeLambdaBody && Current.is(TT_LambdaLSquare));
1099}
1100
1101unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
1102 bool DryRun, bool Newline) {
1103 assert(State.Stack.size())((State.Stack.size()) ? static_cast<void> (0) : __assert_fail
("State.Stack.size()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Format/ContinuationIndenter.cpp"
, 1103, __PRETTY_FUNCTION__))
;
1104 const FormatToken &Current = *State.NextToken;
1105
1106 if (Current.isOneOf(tok::comma, TT_BinaryOperator))
1107 State.Stack.back().NoLineBreakInOperand = false;
1108 if (Current.is(TT_InheritanceColon))
1109 State.Stack.back().AvoidBinPacking = true;
1110 if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) {
1111 if (State.Stack.back().FirstLessLess == 0)
1112 State.Stack.back().FirstLessLess = State.Column;
1113 else
1114 State.Stack.back().LastOperatorWrapped = Newline;
1115 }
1116 if (Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless))
1117 State.Stack.back().LastOperatorWrapped = Newline;
1118 if (Current.is(TT_ConditionalExpr) && Current.Previous &&
1119 !Current.Previous->is(TT_ConditionalExpr))
1120 State.Stack.back().LastOperatorWrapped = Newline;
1121 if (Current.is(TT_ArraySubscriptLSquare) &&
1122 State.Stack.back().StartOfArraySubscripts == 0)
1123 State.Stack.back().StartOfArraySubscripts = State.Column;
1124 if (Style.BreakBeforeTernaryOperators && Current.is(tok::question))
1125 State.Stack.back().QuestionColumn = State.Column;
1126 if (!Style.BreakBeforeTernaryOperators && Current.isNot(tok::colon)) {
1127 const FormatToken *Previous = Current.Previous;
1128 while (Previous && Previous->isTrailingComment())
1129 Previous = Previous->Previous;
1130 if (Previous && Previous->is(tok::question))
1131 State.Stack.back().QuestionColumn = State.Column;
1132 }
1133 if (!Current.opensScope() && !Current.closesScope() &&
1134 !Current.is(TT_PointerOrReference))
1135 State.LowestLevelOnLine =
1136 std::min(State.LowestLevelOnLine, Current.NestingLevel);
1137 if (Current.isMemberAccess())
1138 State.Stack.back().StartOfFunctionCall =
1139 !Current.NextOperator ? 0 : State.Column;
1140 if (Current.is(TT_SelectorName))
1141 State.Stack.back().ObjCSelectorNameFound = true;
1142 if (Current.is(TT_CtorInitializerColon) &&
1143 Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon) {
1144 // Indent 2 from the column, so:
1145 // SomeClass::SomeClass()
1146 // : First(...), ...
1147 // Next(...)
1148 // ^ line up here.
1149 State.Stack.back().Indent =
1150 State.Column +
1151 (Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma
1152 ? 0
1153 : 2);
1154 State.Stack.back().NestedBlockIndent = State.Stack.back().Indent;
1155 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine) {
1156 State.Stack.back().AvoidBinPacking = true;
1157 State.Stack.back().BreakBeforeParameter =
1158 !Style.AllowAllConstructorInitializersOnNextLine;
1159 } else {
1160 State.Stack.back().BreakBeforeParameter = false;
1161 }
1162 }
1163 if (Current.is(TT_CtorInitializerColon) &&
1164 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) {
1165 State.Stack.back().Indent =
1166 State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1167 State.Stack.back().NestedBlockIndent = State.Stack.back().Indent;
1168 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
1169 State.Stack.back().AvoidBinPacking = true;
1170 }
1171 if (Current.is(TT_InheritanceColon))
1172 State.Stack.back().Indent =
1173 State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1174 if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline)
1175 State.Stack.back().NestedBlockIndent =
1176 State.Column + Current.ColumnWidth + 1;
1177 if (Current.isOneOf(TT_LambdaLSquare, TT_LambdaArrow))
1178 State.Stack.back().LastSpace = State.Column;
1179
1180 // Insert scopes created by fake parenthesis.
1181 const FormatToken *Previous = Current.getPreviousNonComment();
1182
1183 // Add special behavior to support a format commonly used for JavaScript
1184 // closures:
1185 // SomeFunction(function() {
1186 // foo();
1187 // bar();
1188 // }, a, b, c);
1189 if (Current.isNot(tok::comment) && Previous &&
1190 Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
1191 !Previous->is(TT_DictLiteral) && State.Stack.size() > 1 &&
1192 !State.Stack.back().HasMultipleNestedBlocks) {
1193 if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline)
1194 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
1195 State.Stack[i].NoLineBreak = true;
1196 State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;
1197 }
1198 if (Previous &&
1199 (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) ||
1200 Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr)) &&
1201 !Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
1202 State.Stack.back().NestedBlockInlined =
1203 !Newline && hasNestedBlockInlined(Previous, Current, Style);
1204 }
1205
1206 moveStatePastFakeLParens(State, Newline);
1207 moveStatePastScopeCloser(State);
1208 bool AllowBreak = !State.Stack.back().NoLineBreak &&
1209 !State.Stack.back().NoLineBreakInOperand;
1210 moveStatePastScopeOpener(State, Newline);
1211 moveStatePastFakeRParens(State);
1212
1213 if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0)
1214 State.StartOfStringLiteral = State.Column + 1;
1215 if (Current.is(TT_CSharpStringLiteral) && State.StartOfStringLiteral == 0)
1216 State.StartOfStringLiteral = State.Column + 1;
1217 else if (Current.isStringLiteral() && State.StartOfStringLiteral == 0)
1218 State.StartOfStringLiteral = State.Column;
1219 else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
1220 !Current.isStringLiteral())
1221 State.StartOfStringLiteral = 0;
1222
1223 State.Column += Current.ColumnWidth;
1224 State.NextToken = State.NextToken->Next;
1225
1226 unsigned Penalty =
1227 handleEndOfLine(Current, State, DryRun, AllowBreak, Newline);
1228
1229 if (Current.Role)
1230 Current.Role->formatFromToken(State, this, DryRun);
1231 // If the previous has a special role, let it consume tokens as appropriate.
1232 // It is necessary to start at the previous token for the only implemented
1233 // role (comma separated list). That way, the decision whether or not to break
1234 // after the "{" is already done and both options are tried and evaluated.
1235 // FIXME: This is ugly, find a better way.
1236 if (Previous && Previous->Role)
1237 Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
1238
1239 return Penalty;
1240}
1241
1242void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
1243 bool Newline) {
1244 const FormatToken &Current = *State.NextToken;
1245 const FormatToken *Previous = Current.getPreviousNonComment();
1246
1247 // Don't add extra indentation for the first fake parenthesis after
1248 // 'return', assignments or opening <({[. The indentation for these cases
1249 // is special cased.
1250 bool SkipFirstExtraIndent =
1251 (Previous && (Previous->opensScope() ||
1252 Previous->isOneOf(tok::semi, tok::kw_return) ||
1253 (Previous->getPrecedence() == prec::Assignment &&
1254 Style.AlignOperands) ||
1255 Previous->is(TT_ObjCMethodExpr)));
1256 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
1257 I = Current.FakeLParens.rbegin(),
1258 E = Current.FakeLParens.rend();
1259 I != E; ++I) {
1260 ParenState NewParenState = State.Stack.back();
1261 NewParenState.Tok = nullptr;
1262 NewParenState.ContainsLineBreak = false;
1263 NewParenState.LastOperatorWrapped = true;
1264 NewParenState.NoLineBreak =
1265 NewParenState.NoLineBreak || State.Stack.back().NoLineBreakInOperand;
1266
1267 // Don't propagate AvoidBinPacking into subexpressions of arg/param lists.
1268 if (*I > prec::Comma)
1269 NewParenState.AvoidBinPacking = false;
1270
1271 // Indent from 'LastSpace' unless these are fake parentheses encapsulating
1272 // a builder type call after 'return' or, if the alignment after opening
1273 // brackets is disabled.
1274 if (!Current.isTrailingComment() &&
1275 (Style.AlignOperands || *I < prec::Assignment) &&
1276 (!Previous || Previous->isNot(tok::kw_return) ||
1277 (Style.Language != FormatStyle::LK_Java && *I > 0)) &&
1278 (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign ||
1279 *I != prec::Comma || Current.NestingLevel == 0))
1280 NewParenState.Indent =
1281 std::max(std::max(State.Column, NewParenState.Indent),
1282 State.Stack.back().LastSpace);
1283
1284 // Do not indent relative to the fake parentheses inserted for "." or "->".
1285 // This is a special case to make the following to statements consistent:
1286 // OuterFunction(InnerFunctionCall( // break
1287 // ParameterToInnerFunction));
1288 // OuterFunction(SomeObject.InnerFunctionCall( // break
1289 // ParameterToInnerFunction));
1290 if (*I > prec::Unknown)
1291 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
1292 if (*I != prec::Conditional && !Current.is(TT_UnaryOperator) &&
1293 Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
1294 NewParenState.StartOfFunctionCall = State.Column;
1295
1296 // Always indent conditional expressions. Never indent expression where
1297 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
1298 // prec::Assignment) as those have different indentation rules. Indent
1299 // other expression, unless the indentation needs to be skipped.
1300 if (*I == prec::Conditional ||
1301 (!SkipFirstExtraIndent && *I > prec::Assignment &&
1302 !Current.isTrailingComment()))
1303 NewParenState.Indent += Style.ContinuationIndentWidth;
1304 if ((Previous && !Previous->opensScope()) || *I != prec::Comma)
1305 NewParenState.BreakBeforeParameter = false;
1306 State.Stack.push_back(NewParenState);
1307 SkipFirstExtraIndent = false;
1308 }
1309}
1310
1311void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
1312 for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) {
1313 unsigned VariablePos = State.Stack.back().VariablePos;
1314 if (State.Stack.size() == 1) {
1315 // Do not pop the last element.
1316 break;
1317 }
1318 State.Stack.pop_back();
1319 State.Stack.back().VariablePos = VariablePos;
1320 }
1321}
1322
1323void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
1324 bool Newline) {
1325 const FormatToken &Current = *State.NextToken;
1326 if (!Current.opensScope())
1327 return;
1328
1329 if (Current.MatchingParen && Current.BlockKind == BK_Block) {
1330 moveStateToNewBlock(State);
1331 return;
1332 }
1333
1334 unsigned NewIndent;
1335 unsigned LastSpace = State.Stack.back().LastSpace;
1336 bool AvoidBinPacking;
1337 bool BreakBeforeParameter = false;
1338 unsigned NestedBlockIndent = std::max(State.Stack.back().StartOfFunctionCall,
1339 State.Stack.back().NestedBlockIndent);
1340 if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
1341 opensProtoMessageField(Current, Style)) {
1342 if (Current.opensBlockOrBlockTypeList(Style)) {
1343 NewIndent = Style.IndentWidth +
1344 std::min(State.Column, State.Stack.back().NestedBlockIndent);
1345 } else {
1346 NewIndent = State.Stack.back().LastSpace + Style.ContinuationIndentWidth;
1347 }
1348 const FormatToken *NextNoComment = Current.getNextNonComment();
1349 bool EndsInComma = Current.MatchingParen &&
1350 Current.MatchingParen->Previous &&
1351 Current.MatchingParen->Previous->is(tok::comma);
1352 AvoidBinPacking = EndsInComma || Current.is(TT_DictLiteral) ||
1353 Style.Language == FormatStyle::LK_Proto ||
1354 Style.Language == FormatStyle::LK_TextProto ||
1355 !Style.BinPackArguments ||
1356 (NextNoComment &&
1357 NextNoComment->isOneOf(TT_DesignatedInitializerPeriod,
1358 TT_DesignatedInitializerLSquare));
1359 BreakBeforeParameter = EndsInComma;
1360 if (Current.ParameterCount > 1)
1361 NestedBlockIndent = std::max(NestedBlockIndent, State.Column + 1);
1362 } else {
1363 NewIndent = Style.ContinuationIndentWidth +
1364 std::max(State.Stack.back().LastSpace,
1365 State.Stack.back().StartOfFunctionCall);
1366
1367 // Ensure that different different brackets force relative alignment, e.g.:
1368 // void SomeFunction(vector< // break
1369 // int> v);
1370 // FIXME: We likely want to do this for more combinations of brackets.
1371 if (Current.is(tok::less) && Current.ParentBracket == tok::l_paren) {
1372 NewIndent = std::max(NewIndent, State.Stack.back().Indent);
1373 LastSpace = std::max(LastSpace, State.Stack.back().Indent);
1374 }
1375
1376 bool EndsInComma =
1377 Current.MatchingParen &&
1378 Current.MatchingParen->getPreviousNonComment() &&
1379 Current.MatchingParen->getPreviousNonComment()->is(tok::comma);
1380
1381 // If ObjCBinPackProtocolList is unspecified, fall back to BinPackParameters
1382 // for backwards compatibility.
1383 bool ObjCBinPackProtocolList =
1384 (Style.ObjCBinPackProtocolList == FormatStyle::BPS_Auto &&
1385 Style.BinPackParameters) ||
1386 Style.ObjCBinPackProtocolList == FormatStyle::BPS_Always;
1387
1388 bool BinPackDeclaration =
1389 (State.Line->Type != LT_ObjCDecl && Style.BinPackParameters) ||
1390 (State.Line->Type == LT_ObjCDecl && ObjCBinPackProtocolList);
1391
1392 AvoidBinPacking =
1393 (Style.Language == FormatStyle::LK_JavaScript && EndsInComma) ||
1394 (State.Line->MustBeDeclaration && !BinPackDeclaration) ||
1395 (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||
1396 (Style.ExperimentalAutoDetectBinPacking &&
1397 (Current.PackingKind == PPK_OnePerLine ||
1398 (!BinPackInconclusiveFunctions &&
1399 Current.PackingKind == PPK_Inconclusive)));
1400
1401 if (Current.is(TT_ObjCMethodExpr) && Current.MatchingParen &&
1402 Style.ObjCBreakBeforeNestedBlockParam) {
1403 if (Style.ColumnLimit) {
1404 // If this '[' opens an ObjC call, determine whether all parameters fit
1405 // into one line and put one per line if they don't.
1406 if (getLengthToMatchingParen(Current, State.Stack) + State.Column >
1407 getColumnLimit(State))
1408 BreakBeforeParameter = true;
1409 } else {
1410 // For ColumnLimit = 0, we have to figure out whether there is or has to
1411 // be a line break within this call.
1412 for (const FormatToken *Tok = &Current;
1413 Tok && Tok != Current.MatchingParen; Tok = Tok->Next) {
1414 if (Tok->MustBreakBefore ||
1415 (Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) {
1416 BreakBeforeParameter = true;
1417 break;
1418 }
1419 }
1420 }
1421 }
1422
1423 if (Style.Language == FormatStyle::LK_JavaScript && EndsInComma)
1424 BreakBeforeParameter = true;
1425 }
1426 // Generally inherit NoLineBreak from the current scope to nested scope.
1427 // However, don't do this for non-empty nested blocks, dict literals and
1428 // array literals as these follow different indentation rules.
1429 bool NoLineBreak =
1430 Current.Children.empty() &&
1431 !Current.isOneOf(TT_DictLiteral, TT_ArrayInitializerLSquare) &&
1432 (State.Stack.back().NoLineBreak ||
1433 State.Stack.back().NoLineBreakInOperand ||
1434 (Current.is(TT_TemplateOpener) &&
1435 State.Stack.back().ContainsUnwrappedBuilder));
1436 State.Stack.push_back(
1437 ParenState(&Current, NewIndent, LastSpace, AvoidBinPacking, NoLineBreak));
1438 State.Stack.back().NestedBlockIndent = NestedBlockIndent;
1439 State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
1440 State.Stack.back().HasMultipleNestedBlocks = (Current.BlockParameterCount > 1);
1441
1442 if (Style.BraceWrapping.BeforeLambdaBody &&
1443 Current.Next != nullptr && Current.Tok.is(tok::l_paren)) {
1444 // Search for any parameter that is a lambda
1445 FormatToken const *next = Current.Next;
1446 while (next != nullptr) {
1447 if (next->is(TT_LambdaLSquare)) {
1448 State.Stack.back().HasMultipleNestedBlocks = true;
1449 break;
1450 }
1451 next = next->Next;
1452 }
1453 }
1454
1455 State.Stack.back().IsInsideObjCArrayLiteral =
1456 Current.is(TT_ArrayInitializerLSquare) && Current.Previous &&
1457 Current.Previous->is(tok::at);
1458}
1459
1460void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
1461 const FormatToken &Current = *State.NextToken;
1462 if (!Current.closesScope())
1463 return;
1464
1465 // If we encounter a closing ), ], } or >, we can remove a level from our
1466 // stacks.
1467 if (State.Stack.size() > 1 &&
1468 (Current.isOneOf(tok::r_paren, tok::r_square, TT_TemplateString) ||
1469 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
1470 State.NextToken->is(TT_TemplateCloser) ||
1471 (Current.is(tok::greater) && Current.is(TT_DictLiteral))))
1472 State.Stack.pop_back();
1473
1474 // Reevaluate whether ObjC message arguments fit into one line.
1475 // If a receiver spans multiple lines, e.g.:
1476 // [[object block:^{
1477 // return 42;
1478 // }] a:42 b:42];
1479 // BreakBeforeParameter is calculated based on an incorrect assumption
1480 // (it is checked whether the whole expression fits into one line without
1481 // considering a line break inside a message receiver).
1482 // We check whether arguements fit after receiver scope closer (into the same
1483 // line).
1484 if (State.Stack.back().BreakBeforeParameter && Current.MatchingParen &&
1485 Current.MatchingParen->Previous) {
1486 const FormatToken &CurrentScopeOpener = *Current.MatchingParen->Previous;
1487 if (CurrentScopeOpener.is(TT_ObjCMethodExpr) &&
1488 CurrentScopeOpener.MatchingParen) {
1489 int NecessarySpaceInLine =
1490 getLengthToMatchingParen(CurrentScopeOpener, State.Stack) +
1491 CurrentScopeOpener.TotalLength - Current.TotalLength - 1;
1492 if (State.Column + Current.ColumnWidth + NecessarySpaceInLine <=
1493 Style.ColumnLimit)
1494 State.Stack.back().BreakBeforeParameter = false;
1495 }
1496 }
1497
1498 if (Current.is(tok::r_square)) {
1499 // If this ends the array subscript expr, reset the corresponding value.
1500 const FormatToken *NextNonComment = Current.getNextNonComment();
1501 if (NextNonComment && NextNonComment->isNot(tok::l_square))
1502 State.Stack.back().StartOfArraySubscripts = 0;
1503 }
1504}
1505
1506void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
1507 unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
1508 // ObjC block sometimes follow special indentation rules.
1509 unsigned NewIndent =
1510 NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace)
1511 ? Style.ObjCBlockIndentWidth
1512 : Style.IndentWidth);
1513 State.Stack.push_back(ParenState(State.NextToken, NewIndent,
1514 State.Stack.back().LastSpace,
1515 /*AvoidBinPacking=*/true,
1516 /*NoLineBreak=*/false));
1517 State.Stack.back().NestedBlockIndent = NestedBlockIndent;
1518 State.Stack.back().BreakBeforeParameter = true;
1519}
1520
1521static unsigned getLastLineEndColumn(StringRef Text, unsigned StartColumn,
1522 unsigned TabWidth,
1523 encoding::Encoding Encoding) {
1524 size_t LastNewlinePos = Text.find_last_of("\n");
1525 if (LastNewlinePos == StringRef::npos) {
1526 return StartColumn +
1527 encoding::columnWidthWithTabs(Text, StartColumn, TabWidth, Encoding);
1528 } else {
1529 return encoding::columnWidthWithTabs(Text.substr(LastNewlinePos),
1530 /*StartColumn=*/0, TabWidth, Encoding);
1531 }
1532}
1533
1534unsigned ContinuationIndenter::reformatRawStringLiteral(
1535 const FormatToken &Current, LineState &State,
1536 const FormatStyle &RawStringStyle, bool DryRun, bool Newline) {
1537 unsigned StartColumn = State.Column - Current.ColumnWidth;
1538 StringRef OldDelimiter = *getRawStringDelimiter(Current.TokenText);
1539 StringRef NewDelimiter =
1540 getCanonicalRawStringDelimiter(Style, RawStringStyle.Language);
1541 if (NewDelimiter.empty() || OldDelimiter.empty())
1542 NewDelimiter = OldDelimiter;
1543 // The text of a raw string is between the leading 'R"delimiter(' and the
1544 // trailing 'delimiter)"'.
1545 unsigned OldPrefixSize = 3 + OldDelimiter.size();
1546 unsigned OldSuffixSize = 2 + OldDelimiter.size();
1547 // We create a virtual text environment which expects a null-terminated
1548 // string, so we cannot use StringRef.
1549 std::string RawText = std::string(
1550 Current.TokenText.substr(OldPrefixSize).drop_back(OldSuffixSize));
1551 if (NewDelimiter != OldDelimiter) {
1552 // Don't update to the canonical delimiter 'deli' if ')deli"' occurs in the
1553 // raw string.
1554 std::string CanonicalDelimiterSuffix = (")" + NewDelimiter + "\"").str();
1555 if (StringRef(RawText).contains(CanonicalDelimiterSuffix))
1556 NewDelimiter = OldDelimiter;
1557 }
1558
1559 unsigned NewPrefixSize = 3 + NewDelimiter.size();
1560 unsigned NewSuffixSize = 2 + NewDelimiter.size();
1561
1562 // The first start column is the column the raw text starts after formatting.
1563 unsigned FirstStartColumn = StartColumn + NewPrefixSize;
1564
1565 // The next start column is the intended indentation a line break inside
1566 // the raw string at level 0. It is determined by the following rules:
1567 // - if the content starts on newline, it is one level more than the current
1568 // indent, and
1569 // - if the content does not start on a newline, it is the first start
1570 // column.
1571 // These rules have the advantage that the formatted content both does not
1572 // violate the rectangle rule and visually flows within the surrounding
1573 // source.
1574 bool ContentStartsOnNewline = Current.TokenText[OldPrefixSize] == '\n';
1575 // If this token is the last parameter (checked by looking if it's followed by
1576 // `)` and is not on a newline, the base the indent off the line's nested
1577 // block indent. Otherwise, base the indent off the arguments indent, so we
1578 // can achieve:
1579 //
1580 // fffffffffff(1, 2, 3, R"pb(
1581 // key1: 1 #
1582 // key2: 2)pb");
1583 //
1584 // fffffffffff(1, 2, 3,
1585 // R"pb(
1586 // key1: 1 #
1587 // key2: 2
1588 // )pb");
1589 //
1590 // fffffffffff(1, 2, 3,
1591 // R"pb(
1592 // key1: 1 #
1593 // key2: 2
1594 // )pb",
1595 // 5);
1596 unsigned CurrentIndent =
1597 (!Newline && Current.Next && Current.Next->is(tok::r_paren))
1598 ? State.Stack.back().NestedBlockIndent
1599 : State.Stack.back().Indent;
1600 unsigned NextStartColumn = ContentStartsOnNewline
1601 ? CurrentIndent + Style.IndentWidth
1602 : FirstStartColumn;
1603
1604 // The last start column is the column the raw string suffix starts if it is
1605 // put on a newline.
1606 // The last start column is the intended indentation of the raw string postfix
1607 // if it is put on a newline. It is determined by the following rules:
1608 // - if the raw string prefix starts on a newline, it is the column where
1609 // that raw string prefix starts, and
1610 // - if the raw string prefix does not start on a newline, it is the current
1611 // indent.
1612 unsigned LastStartColumn =
1613 Current.NewlinesBefore ? FirstStartColumn - NewPrefixSize : CurrentIndent;
1614
1615 std::pair<tooling::Replacements, unsigned> Fixes = internal::reformat(
1616 RawStringStyle, RawText, {tooling::Range(0, RawText.size())},
1617 FirstStartColumn, NextStartColumn, LastStartColumn, "<stdin>",
1618 /*Status=*/nullptr);
1619
1620 auto NewCode = applyAllReplacements(RawText, Fixes.first);
1621 tooling::Replacements NoFixes;
1622 if (!NewCode) {
1623 return addMultilineToken(Current, State);
1624 }
1625 if (!DryRun) {
1626 if (NewDelimiter != OldDelimiter) {
1627 // In 'R"delimiter(...', the delimiter starts 2 characters after the start
1628 // of the token.
1629 SourceLocation PrefixDelimiterStart =
1630 Current.Tok.getLocation().getLocWithOffset(2);
1631 auto PrefixErr = Whitespaces.addReplacement(tooling::Replacement(
1632 SourceMgr, PrefixDelimiterStart, OldDelimiter.size(), NewDelimiter));
1633 if (PrefixErr) {
1634 llvm::errs()
1635 << "Failed to update the prefix delimiter of a raw string: "
1636 << llvm::toString(std::move(PrefixErr)) << "\n";
1637 }
1638 // In 'R"delimiter(...)delimiter"', the suffix delimiter starts at
1639 // position length - 1 - |delimiter|.
1640 SourceLocation SuffixDelimiterStart =
1641 Current.Tok.getLocation().getLocWithOffset(Current.TokenText.size() -
1642 1 - OldDelimiter.size());
1643 auto SuffixErr = Whitespaces.addReplacement(tooling::Replacement(
1644 SourceMgr, SuffixDelimiterStart, OldDelimiter.size(), NewDelimiter));
1645 if (SuffixErr) {
1646 llvm::errs()
1647 << "Failed to update the suffix delimiter of a raw string: "
1648 << llvm::toString(std::move(SuffixErr)) << "\n";
1649 }
1650 }
1651 SourceLocation OriginLoc =
1652 Current.Tok.getLocation().getLocWithOffset(OldPrefixSize);
1653 for (const tooling::Replacement &Fix : Fixes.first) {
1654 auto Err = Whitespaces.addReplacement(tooling::Replacement(
1655 SourceMgr, OriginLoc.getLocWithOffset(Fix.getOffset()),
1656 Fix.getLength(), Fix.getReplacementText()));
1657 if (Err) {
1658 llvm::errs() << "Failed to reformat raw string: "
1659 << llvm::toString(std::move(Err)) << "\n";
1660 }
1661 }
1662 }
1663 unsigned RawLastLineEndColumn = getLastLineEndColumn(
1664 *NewCode, FirstStartColumn, Style.TabWidth, Encoding);
1665 State.Column = RawLastLineEndColumn + NewSuffixSize;
1666 // Since we're updating the column to after the raw string literal here, we
1667 // have to manually add the penalty for the prefix R"delim( over the column
1668 // limit.
1669 unsigned PrefixExcessCharacters =
1670 StartColumn + NewPrefixSize > Style.ColumnLimit
1671 ? StartColumn + NewPrefixSize - Style.ColumnLimit
1672 : 0;
1673 bool IsMultiline =
1674 ContentStartsOnNewline || (NewCode->find('\n') != std::string::npos);
1675 if (IsMultiline) {
1676 // Break before further function parameters on all levels.
1677 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1678 State.Stack[i].BreakBeforeParameter = true;
1679 }
1680 return Fixes.second + PrefixExcessCharacters * Style.PenaltyExcessCharacter;
1681}
1682
1683unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
1684 LineState &State) {
1685 // Break before further function parameters on all levels.
1686 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1687 State.Stack[i].BreakBeforeParameter = true;
1688
1689 unsigned ColumnsUsed = State.Column;
1690 // We can only affect layout of the first and the last line, so the penalty
1691 // for all other lines is constant, and we ignore it.
1692 State.Column = Current.LastLineColumnWidth;
1693
1694 if (ColumnsUsed > getColumnLimit(State))
1695 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
1696 return 0;
1697}
1698
1699unsigned ContinuationIndenter::handleEndOfLine(const FormatToken &Current,
1700 LineState &State, bool DryRun,
1701 bool AllowBreak, bool Newline) {
1702 unsigned Penalty = 0;
1703 // Compute the raw string style to use in case this is a raw string literal
1704 // that can be reformatted.
1705 auto RawStringStyle = getRawStringStyle(Current, State);
1706 if (RawStringStyle && !Current.Finalized) {
1707 Penalty = reformatRawStringLiteral(Current, State, *RawStringStyle, DryRun,
1708 Newline);
1709 } else if (Current.IsMultiline && Current.isNot(TT_BlockComment)) {
1710 // Don't break multi-line tokens other than block comments and raw string
1711 // literals. Instead, just update the state.
1712 Penalty = addMultilineToken(Current, State);
1713 } else if (State.Line->Type != LT_ImportStatement) {
1714 // We generally don't break import statements.
1715 LineState OriginalState = State;
1716
1717 // Whether we force the reflowing algorithm to stay strictly within the
1718 // column limit.
1719 bool Strict = false;
1720 // Whether the first non-strict attempt at reflowing did intentionally
1721 // exceed the column limit.
1722 bool Exceeded = false;
1723 std::tie(Penalty, Exceeded) = breakProtrudingToken(
1724 Current, State, AllowBreak, /*DryRun=*/true, Strict);
1725 if (Exceeded) {
1726 // If non-strict reflowing exceeds the column limit, try whether strict
1727 // reflowing leads to an overall lower penalty.
1728 LineState StrictState = OriginalState;
1729 unsigned StrictPenalty =
1730 breakProtrudingToken(Current, StrictState, AllowBreak,
1731 /*DryRun=*/true, /*Strict=*/true)
1732 .first;
1733 Strict = StrictPenalty <= Penalty;
1734 if (Strict) {
1735 Penalty = StrictPenalty;
1736 State = StrictState;
1737 }
1738 }
1739 if (!DryRun) {
1740 // If we're not in dry-run mode, apply the changes with the decision on
1741 // strictness made above.
1742 breakProtrudingToken(Current, OriginalState, AllowBreak, /*DryRun=*/false,
1743 Strict);
1744 }
1745 }
1746 if (State.Column > getColumnLimit(State)) {
1747 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
1748 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
1749 }
1750 return Penalty;
1751}
1752
1753// Returns the enclosing function name of a token, or the empty string if not
1754// found.
1755static StringRef getEnclosingFunctionName(const FormatToken &Current) {
1756 // Look for: 'function(' or 'function<templates>(' before Current.
1757 auto Tok = Current.getPreviousNonComment();
1758 if (!Tok || !Tok->is(tok::l_paren))
1759 return "";
1760 Tok = Tok->getPreviousNonComment();
1761 if (!Tok)
1762 return "";
1763 if (Tok->is(TT_TemplateCloser)) {
1764 Tok = Tok->MatchingParen;
1765 if (Tok)
1766 Tok = Tok->getPreviousNonComment();
1767 }
1768 if (!Tok || !Tok->is(tok::identifier))
1769 return "";
1770 return Tok->TokenText;
1771}
1772
1773llvm::Optional<FormatStyle>
1774ContinuationIndenter::getRawStringStyle(const FormatToken &Current,
1775 const LineState &State) {
1776 if (!Current.isStringLiteral())
1777 return None;
1778 auto Delimiter = getRawStringDelimiter(Current.TokenText);
1779 if (!Delimiter)
1780 return None;
1781 auto RawStringStyle = RawStringFormats.getDelimiterStyle(*Delimiter);
1782 if (!RawStringStyle && Delimiter->empty())
1783 RawStringStyle = RawStringFormats.getEnclosingFunctionStyle(
1784 getEnclosingFunctionName(Current));
1785 if (!RawStringStyle)
1786 return None;
1787 RawStringStyle->ColumnLimit = getColumnLimit(State);
1788 return RawStringStyle;
1789}
1790
1791std::unique_ptr<BreakableToken>
1792ContinuationIndenter::createBreakableToken(const FormatToken &Current,
1793 LineState &State, bool AllowBreak) {
1794 unsigned StartColumn = State.Column - Current.ColumnWidth;
1795 if (Current.isStringLiteral()) {
1796 // FIXME: String literal breaking is currently disabled for C#, Java and
1797 // JavaScript, as it requires strings to be merged using "+" which we
1798 // don't support.
1799 if (Style.Language == FormatStyle::LK_Java ||
1800 Style.Language == FormatStyle::LK_JavaScript || Style.isCSharp() ||
1801 !Style.BreakStringLiterals || !AllowBreak)
1802 return nullptr;
1803
1804 // Don't break string literals inside preprocessor directives (except for
1805 // #define directives, as their contents are stored in separate lines and
1806 // are not affected by this check).
1807 // This way we avoid breaking code with line directives and unknown
1808 // preprocessor directives that contain long string literals.
1809 if (State.Line->Type == LT_PreprocessorDirective)
1810 return nullptr;
1811 // Exempts unterminated string literals from line breaking. The user will
1812 // likely want to terminate the string before any line breaking is done.
1813 if (Current.IsUnterminatedLiteral)
1814 return nullptr;
1815 // Don't break string literals inside Objective-C array literals (doing so
1816 // raises the warning -Wobjc-string-concatenation).
1817 if (State.Stack.back().IsInsideObjCArrayLiteral) {
1818 return nullptr;
1819 }
1820
1821 StringRef Text = Current.TokenText;
1822 StringRef Prefix;
1823 StringRef Postfix;
1824 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
1825 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
1826 // reduce the overhead) for each FormatToken, which is a string, so that we
1827 // don't run multiple checks here on the hot path.
1828 if ((Text.endswith(Postfix = "\"") &&
1829 (Text.startswith(Prefix = "@\"") || Text.startswith(Prefix = "\"") ||
1830 Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
1831 Text.startswith(Prefix = "u8\"") ||
1832 Text.startswith(Prefix = "L\""))) ||
1833 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) {
1834 // We need this to address the case where there is an unbreakable tail
1835 // only if certain other formatting decisions have been taken. The
1836 // UnbreakableTailLength of Current is an overapproximation is that case
1837 // and we need to be correct here.
1838 unsigned UnbreakableTailLength = (State.NextToken && canBreak(State))
1839 ? 0
1840 : Current.UnbreakableTailLength;
1841 return std::make_unique<BreakableStringLiteral>(
1842 Current, StartColumn, Prefix, Postfix, UnbreakableTailLength,
1843 State.Line->InPPDirective, Encoding, Style);
1844 }
1845 } else if (Current.is(TT_BlockComment)) {
1846 if (!Style.ReflowComments ||
1847 // If a comment token switches formatting, like
1848 // /* clang-format on */, we don't want to break it further,
1849 // but we may still want to adjust its indentation.
1850 switchesFormatting(Current)) {
1851 return nullptr;
1852 }
1853 return std::make_unique<BreakableBlockComment>(
1854 Current, StartColumn, Current.OriginalColumn, !Current.Previous,
1855 State.Line->InPPDirective, Encoding, Style, Whitespaces.useCRLF());
1856 } else if (Current.is(TT_LineComment) &&
1857 (Current.Previous == nullptr ||
1858 Current.Previous->isNot(TT_ImplicitStringLiteral))) {
1859 if (!Style.ReflowComments ||
1860 CommentPragmasRegex.match(Current.TokenText.substr(2)) ||
1861 switchesFormatting(Current))
1862 return nullptr;
1863 return std::make_unique<BreakableLineCommentSection>(
1864 Current, StartColumn, Current.OriginalColumn, !Current.Previous,
1865 /*InPPDirective=*/false, Encoding, Style);
1866 }
1867 return nullptr;
1868}
1869
1870std::pair<unsigned, bool>
1871ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
1872 LineState &State, bool AllowBreak,
1873 bool DryRun, bool Strict) {
1874 std::unique_ptr<const BreakableToken> Token =
1875 createBreakableToken(Current, State, AllowBreak);
1876 if (!Token)
1877 return {0, false};
1878 assert(Token->getLineCount() > 0)((Token->getLineCount() > 0) ? static_cast<void> (
0) : __assert_fail ("Token->getLineCount() > 0", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Format/ContinuationIndenter.cpp"
, 1878, __PRETTY_FUNCTION__))
;
1879 unsigned ColumnLimit = getColumnLimit(State);
1880 if (Current.is(TT_LineComment)) {
1881 // We don't insert backslashes when breaking line comments.
1882 ColumnLimit = Style.ColumnLimit;
1883 }
1884 if (Current.UnbreakableTailLength >= ColumnLimit)
1885 return {0, false};
1886 // ColumnWidth was already accounted into State.Column before calling
1887 // breakProtrudingToken.
1888 unsigned StartColumn = State.Column - Current.ColumnWidth;
1889 unsigned NewBreakPenalty = Current.isStringLiteral()
1890 ? Style.PenaltyBreakString
1891 : Style.PenaltyBreakComment;
1892 // Stores whether we intentionally decide to let a line exceed the column
1893 // limit.
1894 bool Exceeded = false;
1895 // Stores whether we introduce a break anywhere in the token.
1896 bool BreakInserted = Token->introducesBreakBeforeToken();
1897 // Store whether we inserted a new line break at the end of the previous
1898 // logical line.
1899 bool NewBreakBefore = false;
1900 // We use a conservative reflowing strategy. Reflow starts after a line is
1901 // broken or the corresponding whitespace compressed. Reflow ends as soon as a
1902 // line that doesn't get reflown with the previous line is reached.
1903 bool Reflow = false;
1904 // Keep track of where we are in the token:
1905 // Where we are in the content of the current logical line.
1906 unsigned TailOffset = 0;
1907 // The column number we're currently at.
1908 unsigned ContentStartColumn =
1909 Token->getContentStartColumn(0, /*Break=*/false);
1910 // The number of columns left in the current logical line after TailOffset.
1911 unsigned RemainingTokenColumns =
1912 Token->getRemainingLength(0, TailOffset, ContentStartColumn);
1913 // Adapt the start of the token, for example indent.
1914 if (!DryRun)
1915 Token->adaptStartOfLine(0, Whitespaces);
1916
1917 unsigned ContentIndent = 0;
1918 unsigned Penalty = 0;
1919 LLVM_DEBUG(llvm::dbgs() << "Breaking protruding token at column "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << "Breaking protruding token at column "
<< StartColumn << ".\n"; } } while (false)
1920 << StartColumn << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << "Breaking protruding token at column "
<< StartColumn << ".\n"; } } while (false)
;
1921 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
1922 LineIndex != EndIndex; ++LineIndex) {
1923 LLVM_DEBUG(llvm::dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Line: " <<
LineIndex << " (Reflow: " << Reflow << ")\n"
; } } while (false)
1924 << " Line: " << LineIndex << " (Reflow: " << Reflow << ")\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Line: " <<
LineIndex << " (Reflow: " << Reflow << ")\n"
; } } while (false)
;
1925 NewBreakBefore = false;
1926 // If we did reflow the previous line, we'll try reflowing again. Otherwise
1927 // we'll start reflowing if the current line is broken or whitespace is
1928 // compressed.
1929 bool TryReflow = Reflow;
1930 // Break the current token until we can fit the rest of the line.
1931 while (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {
1932 LLVM_DEBUG(llvm::dbgs() << " Over limit, need: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Over limit, need: "
<< (ContentStartColumn + RemainingTokenColumns) <<
", space: " << ColumnLimit << ", reflown prefix: "
<< ContentStartColumn << ", offset in line: " <<
TailOffset << "\n"; } } while (false)
1933 << (ContentStartColumn + RemainingTokenColumns)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Over limit, need: "
<< (ContentStartColumn + RemainingTokenColumns) <<
", space: " << ColumnLimit << ", reflown prefix: "
<< ContentStartColumn << ", offset in line: " <<
TailOffset << "\n"; } } while (false)
1934 << ", space: " << ColumnLimitdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Over limit, need: "
<< (ContentStartColumn + RemainingTokenColumns) <<
", space: " << ColumnLimit << ", reflown prefix: "
<< ContentStartColumn << ", offset in line: " <<
TailOffset << "\n"; } } while (false)
1935 << ", reflown prefix: " << ContentStartColumndo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Over limit, need: "
<< (ContentStartColumn + RemainingTokenColumns) <<
", space: " << ColumnLimit << ", reflown prefix: "
<< ContentStartColumn << ", offset in line: " <<
TailOffset << "\n"; } } while (false)
1936 << ", offset in line: " << TailOffset << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Over limit, need: "
<< (ContentStartColumn + RemainingTokenColumns) <<
", space: " << ColumnLimit << ", reflown prefix: "
<< ContentStartColumn << ", offset in line: " <<
TailOffset << "\n"; } } while (false)
;
1937 // If the current token doesn't fit, find the latest possible split in the
1938 // current line so that breaking at it will be under the column limit.
1939 // FIXME: Use the earliest possible split while reflowing to correctly
1940 // compress whitespace within a line.
1941 BreakableToken::Split Split =
1942 Token->getSplit(LineIndex, TailOffset, ColumnLimit,
1943 ContentStartColumn, CommentPragmasRegex);
1944 if (Split.first == StringRef::npos) {
1945 // No break opportunity - update the penalty and continue with the next
1946 // logical line.
1947 if (LineIndex < EndIndex - 1)
1948 // The last line's penalty is handled in addNextStateToQueue() or when
1949 // calling replaceWhitespaceAfterLastLine below.
1950 Penalty += Style.PenaltyExcessCharacter *
1951 (ContentStartColumn + RemainingTokenColumns - ColumnLimit);
1952 LLVM_DEBUG(llvm::dbgs() << " No break opportunity.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " No break opportunity.\n"
; } } while (false)
;
1953 break;
1954 }
1955 assert(Split.first != 0)((Split.first != 0) ? static_cast<void> (0) : __assert_fail
("Split.first != 0", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Format/ContinuationIndenter.cpp"
, 1955, __PRETTY_FUNCTION__))
;
1956
1957 if (Token->supportsReflow()) {
1958 // Check whether the next natural split point after the current one can
1959 // still fit the line, either because we can compress away whitespace,
1960 // or because the penalty the excess characters introduce is lower than
1961 // the break penalty.
1962 // We only do this for tokens that support reflowing, and thus allow us
1963 // to change the whitespace arbitrarily (e.g. comments).
1964 // Other tokens, like string literals, can be broken on arbitrary
1965 // positions.
1966
1967 // First, compute the columns from TailOffset to the next possible split
1968 // position.
1969 // For example:
1970 // ColumnLimit: |
1971 // // Some text that breaks
1972 // ^ tail offset
1973 // ^-- split
1974 // ^-------- to split columns
1975 // ^--- next split
1976 // ^--------------- to next split columns
1977 unsigned ToSplitColumns = Token->getRangeLength(
1978 LineIndex, TailOffset, Split.first, ContentStartColumn);
1979 LLVM_DEBUG(llvm::dbgs() << " ToSplit: " << ToSplitColumns << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " ToSplit: " <<
ToSplitColumns << "\n"; } } while (false)
;
1980
1981 BreakableToken::Split NextSplit = Token->getSplit(
1982 LineIndex, TailOffset + Split.first + Split.second, ColumnLimit,
1983 ContentStartColumn + ToSplitColumns + 1, CommentPragmasRegex);
1984 // Compute the columns necessary to fit the next non-breakable sequence
1985 // into the current line.
1986 unsigned ToNextSplitColumns = 0;
1987 if (NextSplit.first == StringRef::npos) {
1988 ToNextSplitColumns = Token->getRemainingLength(LineIndex, TailOffset,
1989 ContentStartColumn);
1990 } else {
1991 ToNextSplitColumns = Token->getRangeLength(
1992 LineIndex, TailOffset,
1993 Split.first + Split.second + NextSplit.first, ContentStartColumn);
1994 }
1995 // Compress the whitespace between the break and the start of the next
1996 // unbreakable sequence.
1997 ToNextSplitColumns =
1998 Token->getLengthAfterCompression(ToNextSplitColumns, Split);
1999 LLVM_DEBUG(llvm::dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " ContentStartColumn: "
<< ContentStartColumn << "\n"; } } while (false)
2000 << " ContentStartColumn: " << ContentStartColumn << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " ContentStartColumn: "
<< ContentStartColumn << "\n"; } } while (false)
;
2001 LLVM_DEBUG(llvm::dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " ToNextSplit: "
<< ToNextSplitColumns << "\n"; } } while (false)
2002 << " ToNextSplit: " << ToNextSplitColumns << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " ToNextSplit: "
<< ToNextSplitColumns << "\n"; } } while (false)
;
2003 // If the whitespace compression makes us fit, continue on the current
2004 // line.
2005 bool ContinueOnLine =
2006 ContentStartColumn + ToNextSplitColumns <= ColumnLimit;
2007 unsigned ExcessCharactersPenalty = 0;
2008 if (!ContinueOnLine && !Strict) {
2009 // Similarly, if the excess characters' penalty is lower than the
2010 // penalty of introducing a new break, continue on the current line.
2011 ExcessCharactersPenalty =
2012 (ContentStartColumn + ToNextSplitColumns - ColumnLimit) *
2013 Style.PenaltyExcessCharacter;
2014 LLVM_DEBUG(llvm::dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Penalty excess: "
<< ExcessCharactersPenalty << "\n break : "
<< NewBreakPenalty << "\n"; } } while (false)
2015 << " Penalty excess: " << ExcessCharactersPenaltydo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Penalty excess: "
<< ExcessCharactersPenalty << "\n break : "
<< NewBreakPenalty << "\n"; } } while (false)
2016 << "\n break : " << NewBreakPenalty << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Penalty excess: "
<< ExcessCharactersPenalty << "\n break : "
<< NewBreakPenalty << "\n"; } } while (false)
;
2017 if (ExcessCharactersPenalty < NewBreakPenalty) {
2018 Exceeded = true;
2019 ContinueOnLine = true;
2020 }
2021 }
2022 if (ContinueOnLine) {
2023 LLVM_DEBUG(llvm::dbgs() << " Continuing on line...\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Continuing on line...\n"
; } } while (false)
;
2024 // The current line fits after compressing the whitespace - reflow
2025 // the next line into it if possible.
2026 TryReflow = true;
2027 if (!DryRun)
2028 Token->compressWhitespace(LineIndex, TailOffset, Split,
2029 Whitespaces);
2030 // When we continue on the same line, leave one space between content.
2031 ContentStartColumn += ToSplitColumns + 1;
2032 Penalty += ExcessCharactersPenalty;
2033 TailOffset += Split.first + Split.second;
2034 RemainingTokenColumns = Token->getRemainingLength(
2035 LineIndex, TailOffset, ContentStartColumn);
2036 continue;
2037 }
2038 }
2039 LLVM_DEBUG(llvm::dbgs() << " Breaking...\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Breaking...\n"
; } } while (false)
;
2040 // Update the ContentIndent only if the current line was not reflown with
2041 // the previous line, since in that case the previous line should still
2042 // determine the ContentIndent. Also never intent the last line.
2043 if (!Reflow)
2044 ContentIndent = Token->getContentIndent(LineIndex);
2045 LLVM_DEBUG(llvm::dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " ContentIndent: "
<< ContentIndent << "\n"; } } while (false)
2046 << " ContentIndent: " << ContentIndent << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " ContentIndent: "
<< ContentIndent << "\n"; } } while (false)
;
2047 ContentStartColumn = ContentIndent + Token->getContentStartColumn(
2048 LineIndex, /*Break=*/true);
2049
2050 unsigned NewRemainingTokenColumns = Token->getRemainingLength(
2051 LineIndex, TailOffset + Split.first + Split.second,
2052 ContentStartColumn);
2053 if (NewRemainingTokenColumns == 0) {
2054 // No content to indent.
2055 ContentIndent = 0;
2056 ContentStartColumn =
2057 Token->getContentStartColumn(LineIndex, /*Break=*/true);
2058 NewRemainingTokenColumns = Token->getRemainingLength(
2059 LineIndex, TailOffset + Split.first + Split.second,
2060 ContentStartColumn);
2061 }
2062
2063 // When breaking before a tab character, it may be moved by a few columns,
2064 // but will still be expanded to the next tab stop, so we don't save any
2065 // columns.
2066 if (NewRemainingTokenColumns == RemainingTokenColumns) {
2067 // FIXME: Do we need to adjust the penalty?
2068 break;
2069 }
2070 assert(NewRemainingTokenColumns < RemainingTokenColumns)((NewRemainingTokenColumns < RemainingTokenColumns) ? static_cast
<void> (0) : __assert_fail ("NewRemainingTokenColumns < RemainingTokenColumns"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Format/ContinuationIndenter.cpp"
, 2070, __PRETTY_FUNCTION__))
;
2071
2072 LLVM_DEBUG(llvm::dbgs() << " Breaking at: " << TailOffset + Split.firstdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Breaking at: "
<< TailOffset + Split.first << ", " << Split
.second << "\n"; } } while (false)
2073 << ", " << Split.second << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Breaking at: "
<< TailOffset + Split.first << ", " << Split
.second << "\n"; } } while (false)
;
2074 if (!DryRun)
2075 Token->insertBreak(LineIndex, TailOffset, Split, ContentIndent,
2076 Whitespaces);
2077
2078 Penalty += NewBreakPenalty;
2079 TailOffset += Split.first + Split.second;
2080 RemainingTokenColumns = NewRemainingTokenColumns;
2081 BreakInserted = true;
2082 NewBreakBefore = true;
2083 }
2084 // In case there's another line, prepare the state for the start of the next
2085 // line.
2086 if (LineIndex + 1 != EndIndex) {
2087 unsigned NextLineIndex = LineIndex + 1;
2088 if (NewBreakBefore)
2089 // After breaking a line, try to reflow the next line into the current
2090 // one once RemainingTokenColumns fits.
2091 TryReflow = true;
2092 if (TryReflow) {
2093 // We decided that we want to try reflowing the next line into the
2094 // current one.
2095 // We will now adjust the state as if the reflow is successful (in
2096 // preparation for the next line), and see whether that works. If we
2097 // decide that we cannot reflow, we will later reset the state to the
2098 // start of the next line.
2099 Reflow = false;
2100 // As we did not continue breaking the line, RemainingTokenColumns is
2101 // known to fit after ContentStartColumn. Adapt ContentStartColumn to
2102 // the position at which we want to format the next line if we do
2103 // actually reflow.
2104 // When we reflow, we need to add a space between the end of the current
2105 // line and the next line's start column.
2106 ContentStartColumn += RemainingTokenColumns + 1;
2107 // Get the split that we need to reflow next logical line into the end
2108 // of the current one; the split will include any leading whitespace of
2109 // the next logical line.
2110 BreakableToken::Split SplitBeforeNext =
2111 Token->getReflowSplit(NextLineIndex, CommentPragmasRegex);
2112 LLVM_DEBUG(llvm::dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Size of reflown text: "
<< ContentStartColumn << "\n Potential reflow split: "
; } } while (false)
2113 << " Size of reflown text: " << ContentStartColumndo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Size of reflown text: "
<< ContentStartColumn << "\n Potential reflow split: "
; } } while (false)
2114 << "\n Potential reflow split: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Size of reflown text: "
<< ContentStartColumn << "\n Potential reflow split: "
; } } while (false)
;
2115 if (SplitBeforeNext.first != StringRef::npos) {
2116 LLVM_DEBUG(llvm::dbgs() << SplitBeforeNext.first << ", "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << SplitBeforeNext.
first << ", " << SplitBeforeNext.second << "\n"
; } } while (false)
2117 << SplitBeforeNext.second << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << SplitBeforeNext.
first << ", " << SplitBeforeNext.second << "\n"
; } } while (false)
;
2118 TailOffset = SplitBeforeNext.first + SplitBeforeNext.second;
2119 // If the rest of the next line fits into the current line below the
2120 // column limit, we can safely reflow.
2121 RemainingTokenColumns = Token->getRemainingLength(
2122 NextLineIndex, TailOffset, ContentStartColumn);
2123 Reflow = true;
2124 if (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {
2125 LLVM_DEBUG(llvm::dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Over limit after reflow, need: "
<< (ContentStartColumn + RemainingTokenColumns) <<
", space: " << ColumnLimit << ", reflown prefix: "
<< ContentStartColumn << ", offset in line: " <<
TailOffset << "\n"; } } while (false)
2126 << " Over limit after reflow, need: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Over limit after reflow, need: "
<< (ContentStartColumn + RemainingTokenColumns) <<
", space: " << ColumnLimit << ", reflown prefix: "
<< ContentStartColumn << ", offset in line: " <<
TailOffset << "\n"; } } while (false)
2127 << (ContentStartColumn + RemainingTokenColumns)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Over limit after reflow, need: "
<< (ContentStartColumn + RemainingTokenColumns) <<
", space: " << ColumnLimit << ", reflown prefix: "
<< ContentStartColumn << ", offset in line: " <<
TailOffset << "\n"; } } while (false)
2128 << ", space: " << ColumnLimitdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Over limit after reflow, need: "
<< (ContentStartColumn + RemainingTokenColumns) <<
", space: " << ColumnLimit << ", reflown prefix: "
<< ContentStartColumn << ", offset in line: " <<
TailOffset << "\n"; } } while (false)
2129 << ", reflown prefix: " << ContentStartColumndo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Over limit after reflow, need: "
<< (ContentStartColumn + RemainingTokenColumns) <<
", space: " << ColumnLimit << ", reflown prefix: "
<< ContentStartColumn << ", offset in line: " <<
TailOffset << "\n"; } } while (false)
2130 << ", offset in line: " << TailOffset << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Over limit after reflow, need: "
<< (ContentStartColumn + RemainingTokenColumns) <<
", space: " << ColumnLimit << ", reflown prefix: "
<< ContentStartColumn << ", offset in line: " <<
TailOffset << "\n"; } } while (false)
;
2131 // If the whole next line does not fit, try to find a point in
2132 // the next line at which we can break so that attaching the part
2133 // of the next line to that break point onto the current line is
2134 // below the column limit.
2135 BreakableToken::Split Split =
2136 Token->getSplit(NextLineIndex, TailOffset, ColumnLimit,
2137 ContentStartColumn, CommentPragmasRegex);
2138 if (Split.first == StringRef::npos) {
2139 LLVM_DEBUG(llvm::dbgs() << " Did not find later break\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Did not find later break\n"
; } } while (false)
;
2140 Reflow = false;
2141 } else {
2142 // Check whether the first split point gets us below the column
2143 // limit. Note that we will execute this split below as part of
2144 // the normal token breaking and reflow logic within the line.
2145 unsigned ToSplitColumns = Token->getRangeLength(
2146 NextLineIndex, TailOffset, Split.first, ContentStartColumn);
2147 if (ContentStartColumn + ToSplitColumns > ColumnLimit) {
2148 LLVM_DEBUG(llvm::dbgs() << " Next split protrudes, need: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Next split protrudes, need: "
<< (ContentStartColumn + ToSplitColumns) << ", space: "
<< ColumnLimit; } } while (false)
2149 << (ContentStartColumn + ToSplitColumns)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Next split protrudes, need: "
<< (ContentStartColumn + ToSplitColumns) << ", space: "
<< ColumnLimit; } } while (false)
2150 << ", space: " << ColumnLimit)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << " Next split protrudes, need: "
<< (ContentStartColumn + ToSplitColumns) << ", space: "
<< ColumnLimit; } } while (false)
;
2151 unsigned ExcessCharactersPenalty =
2152 (ContentStartColumn + ToSplitColumns - ColumnLimit) *
2153 Style.PenaltyExcessCharacter;
2154 if (NewBreakPenalty < ExcessCharactersPenalty) {
2155 Reflow = false;
2156 }
2157 }
2158 }
2159 }
2160 } else {
2161 LLVM_DEBUG(llvm::dbgs() << "not found.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << "not found.\n"; }
} while (false)
;
2162 }
2163 }
2164 if (!Reflow) {
2165 // If we didn't reflow into the next line, the only space to consider is
2166 // the next logical line. Reset our state to match the start of the next
2167 // line.
2168 TailOffset = 0;
2169 ContentStartColumn =
2170 Token->getContentStartColumn(NextLineIndex, /*Break=*/false);
2171 RemainingTokenColumns = Token->getRemainingLength(
2172 NextLineIndex, TailOffset, ContentStartColumn);
2173 // Adapt the start of the token, for example indent.
2174 if (!DryRun)
2175 Token->adaptStartOfLine(NextLineIndex, Whitespaces);
2176 } else {
2177 // If we found a reflow split and have added a new break before the next
2178 // line, we are going to remove the line break at the start of the next
2179 // logical line. For example, here we'll add a new line break after
2180 // 'text', and subsequently delete the line break between 'that' and
2181 // 'reflows'.
2182 // // some text that
2183 // // reflows
2184 // ->
2185 // // some text
2186 // // that reflows
2187 // When adding the line break, we also added the penalty for it, so we
2188 // need to subtract that penalty again when we remove the line break due
2189 // to reflowing.
2190 if (NewBreakBefore) {
2191 assert(Penalty >= NewBreakPenalty)((Penalty >= NewBreakPenalty) ? static_cast<void> (0
) : __assert_fail ("Penalty >= NewBreakPenalty", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Format/ContinuationIndenter.cpp"
, 2191, __PRETTY_FUNCTION__))
;
2192 Penalty -= NewBreakPenalty;
2193 }
2194 if (!DryRun)
2195 Token->reflow(NextLineIndex, Whitespaces);
2196 }
2197 }
2198 }
2199
2200 BreakableToken::Split SplitAfterLastLine =
2201 Token->getSplitAfterLastLine(TailOffset);
2202 if (SplitAfterLastLine.first != StringRef::npos) {
2203 LLVM_DEBUG(llvm::dbgs() << "Replacing whitespace after last line.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-indenter")) { llvm::dbgs() << "Replacing whitespace after last line.\n"
; } } while (false)
;
2204
2205 // We add the last line's penalty here, since that line is going to be split
2206 // now.
2207 Penalty += Style.PenaltyExcessCharacter *
2208 (ContentStartColumn + RemainingTokenColumns - ColumnLimit);
2209
2210 if (!DryRun)
2211 Token->replaceWhitespaceAfterLastLine(TailOffset, SplitAfterLastLine,
2212 Whitespaces);
2213 ContentStartColumn =
2214 Token->getContentStartColumn(Token->getLineCount() - 1, /*Break=*/true);
2215 RemainingTokenColumns = Token->getRemainingLength(
2216 Token->getLineCount() - 1,
2217 TailOffset + SplitAfterLastLine.first + SplitAfterLastLine.second,
2218 ContentStartColumn);
2219 }
2220
2221 State.Column = ContentStartColumn + RemainingTokenColumns -
2222 Current.UnbreakableTailLength;
2223
2224 if (BreakInserted) {
2225 // If we break the token inside a parameter list, we need to break before
2226 // the next parameter on all levels, so that the next parameter is clearly
2227 // visible. Line comments already introduce a break.
2228 if (Current.isNot(TT_LineComment)) {
2229 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
2230 State.Stack[i].BreakBeforeParameter = true;
2231 }
2232
2233 if (Current.is(TT_BlockComment))
2234 State.NoContinuation = true;
2235
2236 State.Stack.back().LastSpace = StartColumn;
2237 }
2238
2239 Token->updateNextToken(State);
2240
2241 return {Penalty, Exceeded};
2242}
2243
2244unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
2245 // In preprocessor directives reserve two chars for trailing " \"
2246 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
2247}
2248
2249bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
2250 const FormatToken &Current = *State.NextToken;
2251 if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral))
2252 return false;
2253 // We never consider raw string literals "multiline" for the purpose of
2254 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
2255 // (see TokenAnnotator::mustBreakBefore().
2256 if (Current.TokenText.startswith("R\""))
2257 return false;
2258 if (Current.IsMultiline)
2259 return true;
2260 if (Current.getNextNonComment() &&
2261 Current.getNextNonComment()->isStringLiteral())
2262 return true; // Implicit concatenation.
2263 if (Style.ColumnLimit != 0 && Style.BreakStringLiterals &&
2264 State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
2265 Style.ColumnLimit)
2266 return true; // String will be split.
2267 return false;
2268}
2269
2270} // namespace format
2271} // namespace clang

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Format/FormatToken.h

1//===--- FormatToken.h - Format C++ code ------------------------*- 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 contains the declaration of the FormatToken, a wrapper
11/// around Token with additional information related to formatting.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H
16#define LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H
17
18#include "clang/Basic/IdentifierTable.h"
19#include "clang/Basic/OperatorPrecedence.h"
20#include "clang/Format/Format.h"
21#include "clang/Lex/Lexer.h"
22#include <memory>
23#include <unordered_set>
24
25namespace clang {
26namespace format {
27
28#define LIST_TOKEN_TYPESTYPE(ArrayInitializerLSquare) TYPE(ArraySubscriptLSquare) TYPE
(AttributeColon) TYPE(AttributeParen) TYPE(AttributeSquare) TYPE
(BinaryOperator) TYPE(BitFieldColon) TYPE(BlockComment) TYPE(
CastRParen) TYPE(ConditionalExpr) TYPE(ConflictAlternative) TYPE
(ConflictEnd) TYPE(ConflictStart) TYPE(CtorInitializerColon) TYPE
(CtorInitializerComma) TYPE(DesignatedInitializerLSquare) TYPE
(DesignatedInitializerPeriod) TYPE(DictLiteral) TYPE(ForEachMacro
) TYPE(FunctionAnnotationRParen) TYPE(FunctionDeclarationName
) TYPE(FunctionLBrace) TYPE(FunctionTypeLParen) TYPE(ImplicitStringLiteral
) TYPE(InheritanceColon) TYPE(InheritanceComma) TYPE(InlineASMBrace
) TYPE(InlineASMColon) TYPE(InlineASMSymbolicNameLSquare) TYPE
(JavaAnnotation) TYPE(JsComputedPropertyName) TYPE(JsExponentiation
) TYPE(JsExponentiationEqual) TYPE(JsFatArrow) TYPE(JsNonNullAssertion
) TYPE(JsNullishCoalescingOperator) TYPE(JsNullPropagatingOperator
) TYPE(JsPrivateIdentifier) TYPE(JsTypeColon) TYPE(JsTypeOperator
) TYPE(JsTypeOptionalQuestion) TYPE(LambdaArrow) TYPE(LambdaLBrace
) TYPE(LambdaLSquare) TYPE(LeadingJavaAnnotation) TYPE(LineComment
) TYPE(MacroBlockBegin) TYPE(MacroBlockEnd) TYPE(NamespaceMacro
) TYPE(ObjCBlockLBrace) TYPE(ObjCBlockLParen) TYPE(ObjCDecl) TYPE
(ObjCForIn) TYPE(ObjCMethodExpr) TYPE(ObjCMethodSpecifier) TYPE
(ObjCProperty) TYPE(ObjCStringLiteral) TYPE(OverloadedOperator
) TYPE(OverloadedOperatorLParen) TYPE(PointerOrReference) TYPE
(PureVirtualSpecifier) TYPE(RangeBasedForLoopColon) TYPE(RegexLiteral
) TYPE(SelectorName) TYPE(StartOfName) TYPE(StatementMacro) TYPE
(StructuredBindingLSquare) TYPE(TemplateCloser) TYPE(TemplateOpener
) TYPE(TemplateString) TYPE(ProtoExtensionLSquare) TYPE(TrailingAnnotation
) TYPE(TrailingReturnArrow) TYPE(TrailingUnaryOperator) TYPE(
TypenameMacro) TYPE(UnaryOperator) TYPE(CSharpStringLiteral) TYPE
(CSharpNamedArgumentColon) TYPE(CSharpNullable) TYPE(CSharpNullCoalescing
) TYPE(CSharpNullConditional) TYPE(CSharpNullConditionalLSquare
) TYPE(Unknown)
\
29 TYPE(ArrayInitializerLSquare) \
30 TYPE(ArraySubscriptLSquare) \
31 TYPE(AttributeColon) \
32 TYPE(AttributeParen) \
33 TYPE(AttributeSquare) \
34 TYPE(BinaryOperator) \
35 TYPE(BitFieldColon) \
36 TYPE(BlockComment) \
37 TYPE(CastRParen) \
38 TYPE(ConditionalExpr) \
39 TYPE(ConflictAlternative) \
40 TYPE(ConflictEnd) \
41 TYPE(ConflictStart) \
42 TYPE(CtorInitializerColon) \
43 TYPE(CtorInitializerComma) \
44 TYPE(DesignatedInitializerLSquare) \
45 TYPE(DesignatedInitializerPeriod) \
46 TYPE(DictLiteral) \
47 TYPE(ForEachMacro) \
48 TYPE(FunctionAnnotationRParen) \
49 TYPE(FunctionDeclarationName) \
50 TYPE(FunctionLBrace) \
51 TYPE(FunctionTypeLParen) \
52 TYPE(ImplicitStringLiteral) \
53 TYPE(InheritanceColon) \
54 TYPE(InheritanceComma) \
55 TYPE(InlineASMBrace) \
56 TYPE(InlineASMColon) \
57 TYPE(InlineASMSymbolicNameLSquare) \
58 TYPE(JavaAnnotation) \
59 TYPE(JsComputedPropertyName) \
60 TYPE(JsExponentiation) \
61 TYPE(JsExponentiationEqual) \
62 TYPE(JsFatArrow) \
63 TYPE(JsNonNullAssertion) \
64 TYPE(JsNullishCoalescingOperator) \
65 TYPE(JsNullPropagatingOperator) \
66 TYPE(JsPrivateIdentifier) \
67 TYPE(JsTypeColon) \
68 TYPE(JsTypeOperator) \
69 TYPE(JsTypeOptionalQuestion) \
70 TYPE(LambdaArrow) \
71 TYPE(LambdaLBrace) \
72 TYPE(LambdaLSquare) \
73 TYPE(LeadingJavaAnnotation) \
74 TYPE(LineComment) \
75 TYPE(MacroBlockBegin) \
76 TYPE(MacroBlockEnd) \
77 TYPE(NamespaceMacro) \
78 TYPE(ObjCBlockLBrace) \
79 TYPE(ObjCBlockLParen) \
80 TYPE(ObjCDecl) \
81 TYPE(ObjCForIn) \
82 TYPE(ObjCMethodExpr) \
83 TYPE(ObjCMethodSpecifier) \
84 TYPE(ObjCProperty) \
85 TYPE(ObjCStringLiteral) \
86 TYPE(OverloadedOperator) \
87 TYPE(OverloadedOperatorLParen) \
88 TYPE(PointerOrReference) \
89 TYPE(PureVirtualSpecifier) \
90 TYPE(RangeBasedForLoopColon) \
91 TYPE(RegexLiteral) \
92 TYPE(SelectorName) \
93 TYPE(StartOfName) \
94 TYPE(StatementMacro) \
95 TYPE(StructuredBindingLSquare) \
96 TYPE(TemplateCloser) \
97 TYPE(TemplateOpener) \
98 TYPE(TemplateString) \
99 TYPE(ProtoExtensionLSquare) \
100 TYPE(TrailingAnnotation) \
101 TYPE(TrailingReturnArrow) \
102 TYPE(TrailingUnaryOperator) \
103 TYPE(TypenameMacro) \
104 TYPE(UnaryOperator) \
105 TYPE(CSharpStringLiteral) \
106 TYPE(CSharpNamedArgumentColon) \
107 TYPE(CSharpNullable) \
108 TYPE(CSharpNullCoalescing) \
109 TYPE(CSharpNullConditional) \
110 TYPE(CSharpNullConditionalLSquare) \
111 TYPE(Unknown)
112
113enum TokenType {
114#define TYPE(X) TT_##X,
115 LIST_TOKEN_TYPESTYPE(ArrayInitializerLSquare) TYPE(ArraySubscriptLSquare) TYPE
(AttributeColon) TYPE(AttributeParen) TYPE(AttributeSquare) TYPE
(BinaryOperator) TYPE(BitFieldColon) TYPE(BlockComment) TYPE(
CastRParen) TYPE(ConditionalExpr) TYPE(ConflictAlternative) TYPE
(ConflictEnd) TYPE(ConflictStart) TYPE(CtorInitializerColon) TYPE
(CtorInitializerComma) TYPE(DesignatedInitializerLSquare) TYPE
(DesignatedInitializerPeriod) TYPE(DictLiteral) TYPE(ForEachMacro
) TYPE(FunctionAnnotationRParen) TYPE(FunctionDeclarationName
) TYPE(FunctionLBrace) TYPE(FunctionTypeLParen) TYPE(ImplicitStringLiteral
) TYPE(InheritanceColon) TYPE(InheritanceComma) TYPE(InlineASMBrace
) TYPE(InlineASMColon) TYPE(InlineASMSymbolicNameLSquare) TYPE
(JavaAnnotation) TYPE(JsComputedPropertyName) TYPE(JsExponentiation
) TYPE(JsExponentiationEqual) TYPE(JsFatArrow) TYPE(JsNonNullAssertion
) TYPE(JsNullishCoalescingOperator) TYPE(JsNullPropagatingOperator
) TYPE(JsPrivateIdentifier) TYPE(JsTypeColon) TYPE(JsTypeOperator
) TYPE(JsTypeOptionalQuestion) TYPE(LambdaArrow) TYPE(LambdaLBrace
) TYPE(LambdaLSquare) TYPE(LeadingJavaAnnotation) TYPE(LineComment
) TYPE(MacroBlockBegin) TYPE(MacroBlockEnd) TYPE(NamespaceMacro
) TYPE(ObjCBlockLBrace) TYPE(ObjCBlockLParen) TYPE(ObjCDecl) TYPE
(ObjCForIn) TYPE(ObjCMethodExpr) TYPE(ObjCMethodSpecifier) TYPE
(ObjCProperty) TYPE(ObjCStringLiteral) TYPE(OverloadedOperator
) TYPE(OverloadedOperatorLParen) TYPE(PointerOrReference) TYPE
(PureVirtualSpecifier) TYPE(RangeBasedForLoopColon) TYPE(RegexLiteral
) TYPE(SelectorName) TYPE(StartOfName) TYPE(StatementMacro) TYPE
(StructuredBindingLSquare) TYPE(TemplateCloser) TYPE(TemplateOpener
) TYPE(TemplateString) TYPE(ProtoExtensionLSquare) TYPE(TrailingAnnotation
) TYPE(TrailingReturnArrow) TYPE(TrailingUnaryOperator) TYPE(
TypenameMacro) TYPE(UnaryOperator) TYPE(CSharpStringLiteral) TYPE
(CSharpNamedArgumentColon) TYPE(CSharpNullable) TYPE(CSharpNullCoalescing
) TYPE(CSharpNullConditional) TYPE(CSharpNullConditionalLSquare
) TYPE(Unknown)
116#undef TYPE
117 NUM_TOKEN_TYPES
118};
119
120/// Determines the name of a token type.
121const char *getTokenTypeName(TokenType Type);
122
123// Represents what type of block a set of braces open.
124enum BraceBlockKind { BK_Unknown, BK_Block, BK_BracedInit };
125
126// The packing kind of a function's parameters.
127enum ParameterPackingKind { PPK_BinPacked, PPK_OnePerLine, PPK_Inconclusive };
128
129enum FormatDecision { FD_Unformatted, FD_Continue, FD_Break };
130
131class TokenRole;
132class AnnotatedLine;
133
134/// A wrapper around a \c Token storing information about the
135/// whitespace characters preceding it.
136struct FormatToken {
137 FormatToken() {}
138
139 /// The \c Token.
140 Token Tok;
141
142 /// The number of newlines immediately before the \c Token.
143 ///
144 /// This can be used to determine what the user wrote in the original code
145 /// and thereby e.g. leave an empty line between two function definitions.
146 unsigned NewlinesBefore = 0;
147
148 /// Whether there is at least one unescaped newline before the \c
149 /// Token.
150 bool HasUnescapedNewline = false;
151
152 /// The range of the whitespace immediately preceding the \c Token.
153 SourceRange WhitespaceRange;
154
155 /// The offset just past the last '\n' in this token's leading
156 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
157 unsigned LastNewlineOffset = 0;
158
159 /// The width of the non-whitespace parts of the token (or its first
160 /// line for multi-line tokens) in columns.
161 /// We need this to correctly measure number of columns a token spans.
162 unsigned ColumnWidth = 0;
163
164 /// Contains the width in columns of the last line of a multi-line
165 /// token.
166 unsigned LastLineColumnWidth = 0;
167
168 /// Whether the token text contains newlines (escaped or not).
169 bool IsMultiline = false;
170
171 /// Indicates that this is the first token of the file.
172 bool IsFirst = false;
173
174 /// Whether there must be a line break before this token.
175 ///
176 /// This happens for example when a preprocessor directive ended directly
177 /// before the token.
178 bool MustBreakBefore = false;
179
180 /// The raw text of the token.
181 ///
182 /// Contains the raw token text without leading whitespace and without leading
183 /// escaped newlines.
184 StringRef TokenText;
185
186 /// Set to \c true if this token is an unterminated literal.
187 bool IsUnterminatedLiteral = 0;
188
189 /// Contains the kind of block if this token is a brace.
190 BraceBlockKind BlockKind = BK_Unknown;
191
192 TokenType Type = TT_Unknown;
193
194 /// The number of spaces that should be inserted before this token.
195 unsigned SpacesRequiredBefore = 0;
196
197 /// \c true if it is allowed to break before this token.
198 bool CanBreakBefore = false;
199
200 /// \c true if this is the ">" of "template<..>".
201 bool ClosesTemplateDeclaration = false;
202
203 /// Number of parameters, if this is "(", "[" or "<".
204 unsigned ParameterCount = 0;
205
206 /// Number of parameters that are nested blocks,
207 /// if this is "(", "[" or "<".
208 unsigned BlockParameterCount = 0;
209
210 /// If this is a bracket ("<", "(", "[" or "{"), contains the kind of
211 /// the surrounding bracket.
212 tok::TokenKind ParentBracket = tok::unknown;
213
214 /// A token can have a special role that can carry extra information
215 /// about the token's formatting.
216 std::unique_ptr<TokenRole> Role;
217
218 /// If this is an opening parenthesis, how are the parameters packed?
219 ParameterPackingKind PackingKind = PPK_Inconclusive;
220
221 /// The total length of the unwrapped line up to and including this
222 /// token.
223 unsigned TotalLength = 0;
224
225 /// The original 0-based column of this token, including expanded tabs.
226 /// The configured TabWidth is used as tab width.
227 unsigned OriginalColumn = 0;
228
229 /// The length of following tokens until the next natural split point,
230 /// or the next token that can be broken.
231 unsigned UnbreakableTailLength = 0;
232
233 // FIXME: Come up with a 'cleaner' concept.
234 /// The binding strength of a token. This is a combined value of
235 /// operator precedence, parenthesis nesting, etc.
236 unsigned BindingStrength = 0;
237
238 /// The nesting level of this token, i.e. the number of surrounding (),
239 /// [], {} or <>.
240 unsigned NestingLevel = 0;
241
242 /// The indent level of this token. Copied from the surrounding line.
243 unsigned IndentLevel = 0;
244
245 /// Penalty for inserting a line break before this token.
246 unsigned SplitPenalty = 0;
247
248 /// If this is the first ObjC selector name in an ObjC method
249 /// definition or call, this contains the length of the longest name.
250 ///
251 /// This being set to 0 means that the selectors should not be colon-aligned,
252 /// e.g. because several of them are block-type.
253 unsigned LongestObjCSelectorName = 0;
254
255 /// If this is the first ObjC selector name in an ObjC method
256 /// definition or call, this contains the number of parts that the whole
257 /// selector consist of.
258 unsigned ObjCSelectorNameParts = 0;
259
260 /// The 0-based index of the parameter/argument. For ObjC it is set
261 /// for the selector name token.
262 /// For now calculated only for ObjC.
263 unsigned ParameterIndex = 0;
264
265 /// Stores the number of required fake parentheses and the
266 /// corresponding operator precedence.
267 ///
268 /// If multiple fake parentheses start at a token, this vector stores them in
269 /// reverse order, i.e. inner fake parenthesis first.
270 SmallVector<prec::Level, 4> FakeLParens;
271 /// Insert this many fake ) after this token for correct indentation.
272 unsigned FakeRParens = 0;
273
274 /// \c true if this token starts a binary expression, i.e. has at least
275 /// one fake l_paren with a precedence greater than prec::Unknown.
276 bool StartsBinaryExpression = false;
277 /// \c true if this token ends a binary expression.
278 bool EndsBinaryExpression = false;
279
280 /// If this is an operator (or "."/"->") in a sequence of operators
281 /// with the same precedence, contains the 0-based operator index.
282 unsigned OperatorIndex = 0;
283
284 /// If this is an operator (or "."/"->") in a sequence of operators
285 /// with the same precedence, points to the next operator.
286 FormatToken *NextOperator = nullptr;
287
288 /// Is this token part of a \c DeclStmt defining multiple variables?
289 ///
290 /// Only set if \c Type == \c TT_StartOfName.
291 bool PartOfMultiVariableDeclStmt = false;
292
293 /// Does this line comment continue a line comment section?
294 ///
295 /// Only set to true if \c Type == \c TT_LineComment.
296 bool ContinuesLineCommentSection = false;
297
298 /// If this is a bracket, this points to the matching one.
299 FormatToken *MatchingParen = nullptr;
300
301 /// The previous token in the unwrapped line.
302 FormatToken *Previous = nullptr;
303
304 /// The next token in the unwrapped line.
305 FormatToken *Next = nullptr;
306
307 /// If this token starts a block, this contains all the unwrapped lines
308 /// in it.
309 SmallVector<AnnotatedLine *, 1> Children;
310
311 /// Stores the formatting decision for the token once it was made.
312 FormatDecision Decision = FD_Unformatted;
313
314 /// If \c true, this token has been fully formatted (indented and
315 /// potentially re-formatted inside), and we do not allow further formatting
316 /// changes.
317 bool Finalized = false;
318
319 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
3
Calling 'Token::is'
6
Returning from 'Token::is'
7
Returning the value 1, which participates in a condition later
10
Calling 'Token::is'
13
Returning from 'Token::is'
14
Returning the value 1, which participates in a condition later
320 bool is(TokenType TT) const { return Type == TT; }
321 bool is(const IdentifierInfo *II) const {
322 return II && II == Tok.getIdentifierInfo();
323 }
324 bool is(tok::PPKeywordKind Kind) const {
325 return Tok.getIdentifierInfo() &&
326 Tok.getIdentifierInfo()->getPPKeywordID() == Kind;
327 }
328 template <typename A, typename B> bool isOneOf(A K1, B K2) const {
329 return is(K1) || is(K2);
330 }
331 template <typename A, typename B, typename... Ts>
332 bool isOneOf(A K1, B K2, Ts... Ks) const {
333 return is(K1) || isOneOf(K2, Ks...);
334 }
335 template <typename T> bool isNot(T Kind) const { return !is(Kind); }
336
337 bool isIf(bool AllowConstexprMacro = true) const {
338 return is(tok::kw_if) || endsSequence(tok::kw_constexpr, tok::kw_if) ||
339 (endsSequence(tok::identifier, tok::kw_if) && AllowConstexprMacro);
340 }
341
342 bool closesScopeAfterBlock() const {
343 if (BlockKind == BK_Block)
344 return true;
345 if (closesScope())
346 return Previous->closesScopeAfterBlock();
347 return false;
348 }
349
350 /// \c true if this token starts a sequence with the given tokens in order,
351 /// following the ``Next`` pointers, ignoring comments.
352 template <typename A, typename... Ts>
353 bool startsSequence(A K1, Ts... Tokens) const {
354 return startsSequenceInternal(K1, Tokens...);
355 }
356
357 /// \c true if this token ends a sequence with the given tokens in order,
358 /// following the ``Previous`` pointers, ignoring comments.
359 /// For example, given tokens [T1, T2, T3], the function returns true if
360 /// 3 tokens ending at this (ignoring comments) are [T3, T2, T1]. In other
361 /// words, the tokens passed to this function need to the reverse of the
362 /// order the tokens appear in code.
363 template <typename A, typename... Ts>
364 bool endsSequence(A K1, Ts... Tokens) const {
365 return endsSequenceInternal(K1, Tokens...);
366 }
367
368 bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); }
369
370 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
371 return Tok.isObjCAtKeyword(Kind);
372 }
373
374 bool isAccessSpecifier(bool ColonRequired = true) const {
375 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
376 (!ColonRequired || (Next && Next->is(tok::colon)));
377 }
378
379 /// Determine whether the token is a simple-type-specifier.
380 bool isSimpleTypeSpecifier() const;
381
382 bool isObjCAccessSpecifier() const {
383 return is(tok::at) && Next &&
384 (Next->isObjCAtKeyword(tok::objc_public) ||
385 Next->isObjCAtKeyword(tok::objc_protected) ||
386 Next->isObjCAtKeyword(tok::objc_package) ||
387 Next->isObjCAtKeyword(tok::objc_private));
388 }
389
390 /// Returns whether \p Tok is ([{ or an opening < of a template or in
391 /// protos.
392 bool opensScope() const {
393 if (is(TT_TemplateString) && TokenText.endswith("${"))
394 return true;
395 if (is(TT_DictLiteral) && is(tok::less))
396 return true;
397 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
398 TT_TemplateOpener);
399 }
400 /// Returns whether \p Tok is )]} or a closing > of a template or in
401 /// protos.
402 bool closesScope() const {
403 if (is(TT_TemplateString) && TokenText.startswith("}"))
404 return true;
405 if (is(TT_DictLiteral) && is(tok::greater))
406 return true;
407 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square,
408 TT_TemplateCloser);
409 }
410
411 /// Returns \c true if this is a "." or "->" accessing a member.
412 bool isMemberAccess() const {
413 return isOneOf(tok::arrow, tok::period, tok::arrowstar) &&
414 !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow,
415 TT_LambdaArrow, TT_LeadingJavaAnnotation);
416 }
417
418 bool isUnaryOperator() const {
419 switch (Tok.getKind()) {
420 case tok::plus:
421 case tok::plusplus:
422 case tok::minus:
423 case tok::minusminus:
424 case tok::exclaim:
425 case tok::tilde:
426 case tok::kw_sizeof:
427 case tok::kw_alignof:
428 return true;
429 default:
430 return false;
431 }
432 }
433
434 bool isBinaryOperator() const {
435 // Comma is a binary operator, but does not behave as such wrt. formatting.
436 return getPrecedence() > prec::Comma;
437 }
438
439 bool isTrailingComment() const {
440 return is(tok::comment) &&
441 (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0);
442 }
443
444 /// Returns \c true if this is a keyword that can be used
445 /// like a function call (e.g. sizeof, typeid, ...).
446 bool isFunctionLikeKeyword() const {
447 switch (Tok.getKind()) {
448 case tok::kw_throw:
449 case tok::kw_typeid:
450 case tok::kw_return:
451 case tok::kw_sizeof:
452 case tok::kw_alignof:
453 case tok::kw_alignas:
454 case tok::kw_decltype:
455 case tok::kw_noexcept:
456 case tok::kw_static_assert:
457 case tok::kw___attribute:
458 return true;
459 default:
460 return false;
461 }
462 }
463
464 /// Returns \c true if this is a string literal that's like a label,
465 /// e.g. ends with "=" or ":".
466 bool isLabelString() const {
467 if (!is(tok::string_literal))
468 return false;
469 StringRef Content = TokenText;
470 if (Content.startswith("\"") || Content.startswith("'"))
471 Content = Content.drop_front(1);
472 if (Content.endswith("\"") || Content.endswith("'"))
473 Content = Content.drop_back(1);
474 Content = Content.trim();
475 return Content.size() > 1 &&
476 (Content.back() == ':' || Content.back() == '=');
477 }
478
479 /// Returns actual token start location without leading escaped
480 /// newlines and whitespace.
481 ///
482 /// This can be different to Tok.getLocation(), which includes leading escaped
483 /// newlines.
484 SourceLocation getStartOfNonWhitespace() const {
485 return WhitespaceRange.getEnd();
486 }
487
488 prec::Level getPrecedence() const {
489 return getBinOpPrecedence(Tok.getKind(), /*GreaterThanIsOperator=*/true,
490 /*CPlusPlus11=*/true);
491 }
492
493 /// Returns the previous token ignoring comments.
494 FormatToken *getPreviousNonComment() const {
495 FormatToken *Tok = Previous;
496 while (Tok && Tok->is(tok::comment))
497 Tok = Tok->Previous;
498 return Tok;
499 }
500
501 /// Returns the next token ignoring comments.
502 const FormatToken *getNextNonComment() const {
503 const FormatToken *Tok = Next;
504 while (Tok && Tok->is(tok::comment))
505 Tok = Tok->Next;
506 return Tok;
507 }
508
509 /// Returns \c true if this tokens starts a block-type list, i.e. a
510 /// list that should be indented with a block indent.
511 bool opensBlockOrBlockTypeList(const FormatStyle &Style) const {
512 if (is(TT_TemplateString) && opensScope())
513 return true;
514 return is(TT_ArrayInitializerLSquare) || is(TT_ProtoExtensionLSquare) ||
515 (is(tok::l_brace) &&
516 (BlockKind == BK_Block || is(TT_DictLiteral) ||
517 (!Style.Cpp11BracedListStyle && NestingLevel == 0))) ||
518 (is(tok::less) && (Style.Language == FormatStyle::LK_Proto ||
519 Style.Language == FormatStyle::LK_TextProto));
520 }
521
522 /// Returns whether the token is the left square bracket of a C++
523 /// structured binding declaration.
524 bool isCppStructuredBinding(const FormatStyle &Style) const {
525 if (!Style.isCpp() || isNot(tok::l_square))
526 return false;
527 const FormatToken *T = this;
528 do {
529 T = T->getPreviousNonComment();
530 } while (T && T->isOneOf(tok::kw_const, tok::kw_volatile, tok::amp,
531 tok::ampamp));
532 return T && T->is(tok::kw_auto);
533 }
534
535 /// Same as opensBlockOrBlockTypeList, but for the closing token.
536 bool closesBlockOrBlockTypeList(const FormatStyle &Style) const {
537 if (is(TT_TemplateString) && closesScope())
538 return true;
539 return MatchingParen && MatchingParen->opensBlockOrBlockTypeList(Style);
540 }
541
542 /// Return the actual namespace token, if this token starts a namespace
543 /// block.
544 const FormatToken *getNamespaceToken() const {
545 const FormatToken *NamespaceTok = this;
546 if (is(tok::comment))
547 NamespaceTok = NamespaceTok->getNextNonComment();
548 // Detect "(inline|export)? namespace" in the beginning of a line.
549 if (NamespaceTok && NamespaceTok->isOneOf(tok::kw_inline, tok::kw_export))
550 NamespaceTok = NamespaceTok->getNextNonComment();
551 return NamespaceTok &&
552 NamespaceTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro)
553 ? NamespaceTok
554 : nullptr;
555 }
556
557private:
558 // Disallow copying.
559 FormatToken(const FormatToken &) = delete;
560 void operator=(const FormatToken &) = delete;
561
562 template <typename A, typename... Ts>
563 bool startsSequenceInternal(A K1, Ts... Tokens) const {
564 if (is(tok::comment) && Next)
565 return Next->startsSequenceInternal(K1, Tokens...);
566 return is(K1) && Next && Next->startsSequenceInternal(Tokens...);
567 }
568
569 template <typename A> bool startsSequenceInternal(A K1) const {
570 if (is(tok::comment) && Next)
571 return Next->startsSequenceInternal(K1);
572 return is(K1);
573 }
574
575 template <typename A, typename... Ts> bool endsSequenceInternal(A K1) const {
576 if (is(tok::comment) && Previous)
577 return Previous->endsSequenceInternal(K1);
578 return is(K1);
579 }
580
581 template <typename A, typename... Ts>
582 bool endsSequenceInternal(A K1, Ts... Tokens) const {
583 if (is(tok::comment) && Previous)
584 return Previous->endsSequenceInternal(K1, Tokens...);
585 return is(K1) && Previous && Previous->endsSequenceInternal(Tokens...);
586 }
587};
588
589class ContinuationIndenter;
590struct LineState;
591
592class TokenRole {
593public:
594 TokenRole(const FormatStyle &Style) : Style(Style) {}
595 virtual ~TokenRole();
596
597 /// After the \c TokenAnnotator has finished annotating all the tokens,
598 /// this function precomputes required information for formatting.
599 virtual void precomputeFormattingInfos(const FormatToken *Token);
600
601 /// Apply the special formatting that the given role demands.
602 ///
603 /// Assumes that the token having this role is already formatted.
604 ///
605 /// Continues formatting from \p State leaving indentation to \p Indenter and
606 /// returns the total penalty that this formatting incurs.
607 virtual unsigned formatFromToken(LineState &State,
608 ContinuationIndenter *Indenter,
609 bool DryRun) {
610 return 0;
611 }
612
613 /// Same as \c formatFromToken, but assumes that the first token has
614 /// already been set thereby deciding on the first line break.
615 virtual unsigned formatAfterToken(LineState &State,
616 ContinuationIndenter *Indenter,
617 bool DryRun) {
618 return 0;
619 }
620
621 /// Notifies the \c Role that a comma was found.
622 virtual void CommaFound(const FormatToken *Token) {}
623
624 virtual const FormatToken *lastComma() { return nullptr; }
625
626protected:
627 const FormatStyle &Style;
628};
629
630class CommaSeparatedList : public TokenRole {
631public:
632 CommaSeparatedList(const FormatStyle &Style)
633 : TokenRole(Style), HasNestedBracedList(false) {}
634
635 void precomputeFormattingInfos(const FormatToken *Token) override;
636
637 unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter,
638 bool DryRun) override;
639
640 unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter,
641 bool DryRun) override;
642
643 /// Adds \p Token as the next comma to the \c CommaSeparated list.
644 void CommaFound(const FormatToken *Token) override {
645 Commas.push_back(Token);
646 }
647
648 const FormatToken *lastComma() override {
649 if (Commas.empty())
650 return nullptr;
651 return Commas.back();
652 }
653
654private:
655 /// A struct that holds information on how to format a given list with
656 /// a specific number of columns.
657 struct ColumnFormat {
658 /// The number of columns to use.
659 unsigned Columns;
660
661 /// The total width in characters.
662 unsigned TotalWidth;
663
664 /// The number of lines required for this format.
665 unsigned LineCount;
666
667 /// The size of each column in characters.
668 SmallVector<unsigned, 8> ColumnSizes;
669 };
670
671 /// Calculate which \c ColumnFormat fits best into
672 /// \p RemainingCharacters.
673 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
674
675 /// The ordered \c FormatTokens making up the commas of this list.
676 SmallVector<const FormatToken *, 8> Commas;
677
678 /// The length of each of the list's items in characters including the
679 /// trailing comma.
680 SmallVector<unsigned, 8> ItemLengths;
681
682 /// Precomputed formats that can be used for this list.
683 SmallVector<ColumnFormat, 4> Formats;
684
685 bool HasNestedBracedList;
686};
687
688/// Encapsulates keywords that are context sensitive or for languages not
689/// properly supported by Clang's lexer.
690struct AdditionalKeywords {
691 AdditionalKeywords(IdentifierTable &IdentTable) {
692 kw_final = &IdentTable.get("final");
693 kw_override = &IdentTable.get("override");
694 kw_in = &IdentTable.get("in");
695 kw_of = &IdentTable.get("of");
696 kw_CF_CLOSED_ENUM = &IdentTable.get("CF_CLOSED_ENUM");
697 kw_CF_ENUM = &IdentTable.get("CF_ENUM");
698 kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS");
699 kw_NS_CLOSED_ENUM = &IdentTable.get("NS_CLOSED_ENUM");
700 kw_NS_ENUM = &IdentTable.get("NS_ENUM");
701 kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS");
702
703 kw_as = &IdentTable.get("as");
704 kw_async = &IdentTable.get("async");
705 kw_await = &IdentTable.get("await");
706 kw_declare = &IdentTable.get("declare");
707 kw_finally = &IdentTable.get("finally");
708 kw_from = &IdentTable.get("from");
709 kw_function = &IdentTable.get("function");
710 kw_get = &IdentTable.get("get");
711 kw_import = &IdentTable.get("import");
712 kw_infer = &IdentTable.get("infer");
713 kw_is = &IdentTable.get("is");
714 kw_let = &IdentTable.get("let");
715 kw_module = &IdentTable.get("module");
716 kw_readonly = &IdentTable.get("readonly");
717 kw_set = &IdentTable.get("set");
718 kw_type = &IdentTable.get("type");
719 kw_typeof = &IdentTable.get("typeof");
720 kw_var = &IdentTable.get("var");
721 kw_yield = &IdentTable.get("yield");
722
723 kw_abstract = &IdentTable.get("abstract");
724 kw_assert = &IdentTable.get("assert");
725 kw_extends = &IdentTable.get("extends");
726 kw_implements = &IdentTable.get("implements");
727 kw_instanceof = &IdentTable.get("instanceof");
728 kw_interface = &IdentTable.get("interface");
729 kw_native = &IdentTable.get("native");
730 kw_package = &IdentTable.get("package");
731 kw_synchronized = &IdentTable.get("synchronized");
732 kw_throws = &IdentTable.get("throws");
733 kw___except = &IdentTable.get("__except");
734 kw___has_include = &IdentTable.get("__has_include");
735 kw___has_include_next = &IdentTable.get("__has_include_next");
736
737 kw_mark = &IdentTable.get("mark");
738
739 kw_extend = &IdentTable.get("extend");
740 kw_option = &IdentTable.get("option");
741 kw_optional = &IdentTable.get("optional");
742 kw_repeated = &IdentTable.get("repeated");
743 kw_required = &IdentTable.get("required");
744 kw_returns = &IdentTable.get("returns");
745
746 kw_signals = &IdentTable.get("signals");
747 kw_qsignals = &IdentTable.get("Q_SIGNALS");
748 kw_slots = &IdentTable.get("slots");
749 kw_qslots = &IdentTable.get("Q_SLOTS");
750
751 // C# keywords
752 kw_dollar = &IdentTable.get("dollar");
753 kw_base = &IdentTable.get("base");
754 kw_byte = &IdentTable.get("byte");
755 kw_checked = &IdentTable.get("checked");
756 kw_decimal = &IdentTable.get("decimal");
757 kw_delegate = &IdentTable.get("delegate");
758 kw_event = &IdentTable.get("event");
759 kw_fixed = &IdentTable.get("fixed");
760 kw_foreach = &IdentTable.get("foreach");
761 kw_implicit = &IdentTable.get("implicit");
762 kw_internal = &IdentTable.get("internal");
763 kw_lock = &IdentTable.get("lock");
764 kw_null = &IdentTable.get("null");
765 kw_object = &IdentTable.get("object");
766 kw_out = &IdentTable.get("out");
767 kw_params = &IdentTable.get("params");
768 kw_ref = &IdentTable.get("ref");
769 kw_string = &IdentTable.get("string");
770 kw_stackalloc = &IdentTable.get("stackalloc");
771 kw_sbyte = &IdentTable.get("sbyte");
772 kw_sealed = &IdentTable.get("sealed");
773 kw_uint = &IdentTable.get("uint");
774 kw_ulong = &IdentTable.get("ulong");
775 kw_unchecked = &IdentTable.get("unchecked");
776 kw_unsafe = &IdentTable.get("unsafe");
777 kw_ushort = &IdentTable.get("ushort");
778 kw_when = &IdentTable.get("when");
779
780 // Keep this at the end of the constructor to make sure everything here
781 // is
782 // already initialized.
783 JsExtraKeywords = std::unordered_set<IdentifierInfo *>(
784 {kw_as, kw_async, kw_await, kw_declare, kw_finally, kw_from,
785 kw_function, kw_get, kw_import, kw_is, kw_let, kw_module, kw_readonly,
786 kw_set, kw_type, kw_typeof, kw_var, kw_yield,
787 // Keywords from the Java section.
788 kw_abstract, kw_extends, kw_implements, kw_instanceof, kw_interface});
789
790 CSharpExtraKeywords = std::unordered_set<IdentifierInfo *>(
791 {kw_base, kw_byte, kw_checked, kw_decimal, kw_delegate, kw_event,
792 kw_fixed, kw_foreach, kw_implicit, kw_in, kw_interface, kw_internal,
793 kw_is, kw_lock, kw_null, kw_object, kw_out, kw_override, kw_params,
794 kw_readonly, kw_ref, kw_string, kw_stackalloc, kw_sbyte, kw_sealed,
795 kw_uint, kw_ulong, kw_unchecked, kw_unsafe, kw_ushort, kw_when,
796 // Keywords from the JavaScript section.
797 kw_as, kw_async, kw_await, kw_declare, kw_finally, kw_from,
798 kw_function, kw_get, kw_import, kw_is, kw_let, kw_module, kw_readonly,
799 kw_set, kw_type, kw_typeof, kw_var, kw_yield,
800 // Keywords from the Java section.
801 kw_abstract, kw_extends, kw_implements, kw_instanceof, kw_interface});
802 }
803
804 // Context sensitive keywords.
805 IdentifierInfo *kw_final;
806 IdentifierInfo *kw_override;
807 IdentifierInfo *kw_in;
808 IdentifierInfo *kw_of;
809 IdentifierInfo *kw_CF_CLOSED_ENUM;
810 IdentifierInfo *kw_CF_ENUM;
811 IdentifierInfo *kw_CF_OPTIONS;
812 IdentifierInfo *kw_NS_CLOSED_ENUM;
813 IdentifierInfo *kw_NS_ENUM;
814 IdentifierInfo *kw_NS_OPTIONS;
815 IdentifierInfo *kw___except;
816 IdentifierInfo *kw___has_include;
817 IdentifierInfo *kw___has_include_next;
818
819 // JavaScript keywords.
820 IdentifierInfo *kw_as;
821 IdentifierInfo *kw_async;
822 IdentifierInfo *kw_await;
823 IdentifierInfo *kw_declare;
824 IdentifierInfo *kw_finally;
825 IdentifierInfo *kw_from;
826 IdentifierInfo *kw_function;
827 IdentifierInfo *kw_get;
828 IdentifierInfo *kw_import;
829 IdentifierInfo *kw_infer;
830 IdentifierInfo *kw_is;
831 IdentifierInfo *kw_let;
832 IdentifierInfo *kw_module;
833 IdentifierInfo *kw_readonly;
834 IdentifierInfo *kw_set;
835 IdentifierInfo *kw_type;
836 IdentifierInfo *kw_typeof;
837 IdentifierInfo *kw_var;
838 IdentifierInfo *kw_yield;
839
840 // Java keywords.
841 IdentifierInfo *kw_abstract;
842 IdentifierInfo *kw_assert;
843 IdentifierInfo *kw_extends;
844 IdentifierInfo *kw_implements;
845 IdentifierInfo *kw_instanceof;
846 IdentifierInfo *kw_interface;
847 IdentifierInfo *kw_native;
848 IdentifierInfo *kw_package;
849 IdentifierInfo *kw_synchronized;
850 IdentifierInfo *kw_throws;
851
852 // Pragma keywords.
853 IdentifierInfo *kw_mark;
854
855 // Proto keywords.
856 IdentifierInfo *kw_extend;
857 IdentifierInfo *kw_option;
858 IdentifierInfo *kw_optional;
859 IdentifierInfo *kw_repeated;
860 IdentifierInfo *kw_required;
861 IdentifierInfo *kw_returns;
862
863 // QT keywords.
864 IdentifierInfo *kw_signals;
865 IdentifierInfo *kw_qsignals;
866 IdentifierInfo *kw_slots;
867 IdentifierInfo *kw_qslots;
868
869 // C# keywords
870 IdentifierInfo *kw_dollar;
871 IdentifierInfo *kw_base;
872 IdentifierInfo *kw_byte;
873 IdentifierInfo *kw_checked;
874 IdentifierInfo *kw_decimal;
875 IdentifierInfo *kw_delegate;
876 IdentifierInfo *kw_event;
877 IdentifierInfo *kw_fixed;
878 IdentifierInfo *kw_foreach;
879 IdentifierInfo *kw_implicit;
880 IdentifierInfo *kw_internal;
881
882 IdentifierInfo *kw_lock;
883 IdentifierInfo *kw_null;
884 IdentifierInfo *kw_object;
885 IdentifierInfo *kw_out;
886
887 IdentifierInfo *kw_params;
888
889 IdentifierInfo *kw_ref;
890 IdentifierInfo *kw_string;
891 IdentifierInfo *kw_stackalloc;
892 IdentifierInfo *kw_sbyte;
893 IdentifierInfo *kw_sealed;
894 IdentifierInfo *kw_uint;
895 IdentifierInfo *kw_ulong;
896 IdentifierInfo *kw_unchecked;
897 IdentifierInfo *kw_unsafe;
898 IdentifierInfo *kw_ushort;
899 IdentifierInfo *kw_when;
900
901 /// Returns \c true if \p Tok is a true JavaScript identifier, returns
902 /// \c false if it is a keyword or a pseudo keyword.
903 bool IsJavaScriptIdentifier(const FormatToken &Tok) const {
904 return Tok.is(tok::identifier) &&
905 JsExtraKeywords.find(Tok.Tok.getIdentifierInfo()) ==
906 JsExtraKeywords.end();
907 }
908
909 /// Returns \c true if \p Tok is a C# keyword, returns
910 /// \c false if it is a anything else.
911 bool isCSharpKeyword(const FormatToken &Tok) const {
912 switch (Tok.Tok.getKind()) {
913 case tok::kw_bool:
914 case tok::kw_break:
915 case tok::kw_case:
916 case tok::kw_catch:
917 case tok::kw_char:
918 case tok::kw_class:
919 case tok::kw_const:
920 case tok::kw_continue:
921 case tok::kw_default:
922 case tok::kw_do:
923 case tok::kw_double:
924 case tok::kw_else:
925 case tok::kw_enum:
926 case tok::kw_explicit:
927 case tok::kw_extern:
928 case tok::kw_false:
929 case tok::kw_float:
930 case tok::kw_for:
931 case tok::kw_goto:
932 case tok::kw_if:
933 case tok::kw_int:
934 case tok::kw_long:
935 case tok::kw_namespace:
936 case tok::kw_new:
937 case tok::kw_operator:
938 case tok::kw_private:
939 case tok::kw_protected:
940 case tok::kw_public:
941 case tok::kw_return:
942 case tok::kw_short:
943 case tok::kw_sizeof:
944 case tok::kw_static:
945 case tok::kw_struct:
946 case tok::kw_switch:
947 case tok::kw_this:
948 case tok::kw_throw:
949 case tok::kw_true:
950 case tok::kw_try:
951 case tok::kw_typeof:
952 case tok::kw_using:
953 case tok::kw_virtual:
954 case tok::kw_void:
955 case tok::kw_volatile:
956 case tok::kw_while:
957 return true;
958 default:
959 return Tok.is(tok::identifier) &&
960 CSharpExtraKeywords.find(Tok.Tok.getIdentifierInfo()) ==
961 CSharpExtraKeywords.end();
962 }
963 }
964
965private:
966 /// The JavaScript keywords beyond the C++ keyword set.
967 std::unordered_set<IdentifierInfo *> JsExtraKeywords;
968
969 /// The C# keywords beyond the C++ keyword set
970 std::unordered_set<IdentifierInfo *> CSharpExtraKeywords;
971};
972
973} // namespace format
974} // namespace clang
975
976#endif

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Lex/Token.h

1//===--- Token.h - Token interface ------------------------------*- 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// This file defines the Token interface.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_LEX_TOKEN_H
14#define LLVM_CLANG_LEX_TOKEN_H
15
16#include "clang/Basic/SourceLocation.h"
17#include "clang/Basic/TokenKinds.h"
18#include "llvm/ADT/StringRef.h"
19#include <cassert>
20
21namespace clang {
22
23class IdentifierInfo;
24
25/// Token - This structure provides full information about a lexed token.
26/// It is not intended to be space efficient, it is intended to return as much
27/// information as possible about each returned token. This is expected to be
28/// compressed into a smaller form if memory footprint is important.
29///
30/// The parser can create a special "annotation token" representing a stream of
31/// tokens that were parsed and semantically resolved, e.g.: "foo::MyClass<int>"
32/// can be represented by a single typename annotation token that carries
33/// information about the SourceRange of the tokens and the type object.
34class Token {
35 /// The location of the token. This is actually a SourceLocation.
36 unsigned Loc;
37
38 // Conceptually these next two fields could be in a union. However, this
39 // causes gcc 4.2 to pessimize LexTokenInternal, a very performance critical
40 // routine. Keeping as separate members with casts until a more beautiful fix
41 // presents itself.
42
43 /// UintData - This holds either the length of the token text, when
44 /// a normal token, or the end of the SourceRange when an annotation
45 /// token.
46 unsigned UintData;
47
48 /// PtrData - This is a union of four different pointer types, which depends
49 /// on what type of token this is:
50 /// Identifiers, keywords, etc:
51 /// This is an IdentifierInfo*, which contains the uniqued identifier
52 /// spelling.
53 /// Literals: isLiteral() returns true.
54 /// This is a pointer to the start of the token in a text buffer, which
55 /// may be dirty (have trigraphs / escaped newlines).
56 /// Annotations (resolved type names, C++ scopes, etc): isAnnotation().
57 /// This is a pointer to sema-specific data for the annotation token.
58 /// Eof:
59 // This is a pointer to a Decl.
60 /// Other:
61 /// This is null.
62 void *PtrData;
63
64 /// Kind - The actual flavor of token this is.
65 tok::TokenKind Kind;
66
67 /// Flags - Bits we track about this token, members of the TokenFlags enum.
68 unsigned short Flags;
69
70public:
71 // Various flags set per token:
72 enum TokenFlags {
73 StartOfLine = 0x01, // At start of line or only after whitespace
74 // (considering the line after macro expansion).
75 LeadingSpace = 0x02, // Whitespace exists before this token (considering
76 // whitespace after macro expansion).
77 DisableExpand = 0x04, // This identifier may never be macro expanded.
78 NeedsCleaning = 0x08, // Contained an escaped newline or trigraph.
79 LeadingEmptyMacro = 0x10, // Empty macro exists before this token.
80 HasUDSuffix = 0x20, // This string or character literal has a ud-suffix.
81 HasUCN = 0x40, // This identifier contains a UCN.
82 IgnoredComma = 0x80, // This comma is not a macro argument separator (MS).
83 StringifiedInMacro = 0x100, // This string or character literal is formed by
84 // macro stringizing or charizing operator.
85 CommaAfterElided = 0x200, // The comma following this token was elided (MS).
86 IsEditorPlaceholder = 0x400, // This identifier is a placeholder.
87 IsReinjected = 0x800, // A phase 4 token that was produced before and
88 // re-added, e.g. via EnterTokenStream. Annotation
89 // tokens are *not* reinjected.
90 };
91
92 tok::TokenKind getKind() const { return Kind; }
93 void setKind(tok::TokenKind K) { Kind = K; }
94
95 /// is/isNot - Predicates to check if this token is a specific kind, as in
96 /// "if (Tok.is(tok::l_brace)) {...}".
97 bool is(tok::TokenKind K) const { return Kind == K; }
4
Assuming 'K' is equal to field 'Kind'
5
Returning the value 1, which participates in a condition later
11
Assuming 'K' is equal to field 'Kind'
12
Returning the value 1, which participates in a condition later
98 bool isNot(tok::TokenKind K) const { return Kind != K; }
99 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const {
100 return is(K1) || is(K2);
101 }
102 template <typename... Ts>
103 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, Ts... Ks) const {
104 return is(K1) || isOneOf(K2, Ks...);
105 }
106
107 /// Return true if this is a raw identifier (when lexing
108 /// in raw mode) or a non-keyword identifier (when lexing in non-raw mode).
109 bool isAnyIdentifier() const {
110 return tok::isAnyIdentifier(getKind());
111 }
112
113 /// Return true if this is a "literal", like a numeric
114 /// constant, string, etc.
115 bool isLiteral() const {
116 return tok::isLiteral(getKind());
117 }
118
119 /// Return true if this is any of tok::annot_* kind tokens.
120 bool isAnnotation() const {
121 return tok::isAnnotation(getKind());
122 }
123
124 /// Return a source location identifier for the specified
125 /// offset in the current file.
126 SourceLocation getLocation() const {
127 return SourceLocation::getFromRawEncoding(Loc);
128 }
129 unsigned getLength() const {
130 assert(!isAnnotation() && "Annotation tokens have no length field")((!isAnnotation() && "Annotation tokens have no length field"
) ? static_cast<void> (0) : __assert_fail ("!isAnnotation() && \"Annotation tokens have no length field\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Lex/Token.h"
, 130, __PRETTY_FUNCTION__))
;
131 return UintData;
132 }
133
134 void setLocation(SourceLocation L) { Loc = L.getRawEncoding(); }
135 void setLength(unsigned Len) {
136 assert(!isAnnotation() && "Annotation tokens have no length field")((!isAnnotation() && "Annotation tokens have no length field"
) ? static_cast<void> (0) : __assert_fail ("!isAnnotation() && \"Annotation tokens have no length field\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Lex/Token.h"
, 136, __PRETTY_FUNCTION__))
;
137 UintData = Len;
138 }
139
140 SourceLocation getAnnotationEndLoc() const {
141 assert(isAnnotation() && "Used AnnotEndLocID on non-annotation token")((isAnnotation() && "Used AnnotEndLocID on non-annotation token"
) ? static_cast<void> (0) : __assert_fail ("isAnnotation() && \"Used AnnotEndLocID on non-annotation token\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Lex/Token.h"
, 141, __PRETTY_FUNCTION__))
;
142 return SourceLocation::getFromRawEncoding(UintData ? UintData : Loc);
143 }
144 void setAnnotationEndLoc(SourceLocation L) {
145 assert(isAnnotation() && "Used AnnotEndLocID on non-annotation token")((isAnnotation() && "Used AnnotEndLocID on non-annotation token"
) ? static_cast<void> (0) : __assert_fail ("isAnnotation() && \"Used AnnotEndLocID on non-annotation token\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Lex/Token.h"
, 145, __PRETTY_FUNCTION__))
;
146 UintData = L.getRawEncoding();
147 }
148
149 SourceLocation getLastLoc() const {
150 return isAnnotation() ? getAnnotationEndLoc() : getLocation();
151 }
152
153 SourceLocation getEndLoc() const {
154 return isAnnotation() ? getAnnotationEndLoc()
155 : getLocation().getLocWithOffset(getLength());
156 }
157
158 /// SourceRange of the group of tokens that this annotation token
159 /// represents.
160 SourceRange getAnnotationRange() const {
161 return SourceRange(getLocation(), getAnnotationEndLoc());
162 }
163 void setAnnotationRange(SourceRange R) {
164 setLocation(R.getBegin());
165 setAnnotationEndLoc(R.getEnd());
166 }
167
168 const char *getName() const { return tok::getTokenName(Kind); }
169
170 /// Reset all flags to cleared.
171 void startToken() {
172 Kind = tok::unknown;
173 Flags = 0;
174 PtrData = nullptr;
175 UintData = 0;
176 Loc = SourceLocation().getRawEncoding();
177 }
178
179 IdentifierInfo *getIdentifierInfo() const {
180 assert(isNot(tok::raw_identifier) &&((isNot(tok::raw_identifier) && "getIdentifierInfo() on a tok::raw_identifier token!"
) ? static_cast<void> (0) : __assert_fail ("isNot(tok::raw_identifier) && \"getIdentifierInfo() on a tok::raw_identifier token!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Lex/Token.h"
, 181, __PRETTY_FUNCTION__))
181 "getIdentifierInfo() on a tok::raw_identifier token!")((isNot(tok::raw_identifier) && "getIdentifierInfo() on a tok::raw_identifier token!"
) ? static_cast<void> (0) : __assert_fail ("isNot(tok::raw_identifier) && \"getIdentifierInfo() on a tok::raw_identifier token!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Lex/Token.h"
, 181, __PRETTY_FUNCTION__))
;
182 assert(!isAnnotation() &&((!isAnnotation() && "getIdentifierInfo() on an annotation token!"
) ? static_cast<void> (0) : __assert_fail ("!isAnnotation() && \"getIdentifierInfo() on an annotation token!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Lex/Token.h"
, 183, __PRETTY_FUNCTION__))
183 "getIdentifierInfo() on an annotation token!")((!isAnnotation() && "getIdentifierInfo() on an annotation token!"
) ? static_cast<void> (0) : __assert_fail ("!isAnnotation() && \"getIdentifierInfo() on an annotation token!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Lex/Token.h"
, 183, __PRETTY_FUNCTION__))
;
184 if (isLiteral()) return nullptr;
185 if (is(tok::eof)) return nullptr;
186 return (IdentifierInfo*) PtrData;
187 }
188 void setIdentifierInfo(IdentifierInfo *II) {
189 PtrData = (void*) II;
190 }
191
192 const void *getEofData() const {
193 assert(is(tok::eof))((is(tok::eof)) ? static_cast<void> (0) : __assert_fail
("is(tok::eof)", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Lex/Token.h"
, 193, __PRETTY_FUNCTION__))
;
194 return reinterpret_cast<const void *>(PtrData);
195 }
196 void setEofData(const void *D) {
197 assert(is(tok::eof))((is(tok::eof)) ? static_cast<void> (0) : __assert_fail
("is(tok::eof)", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Lex/Token.h"
, 197, __PRETTY_FUNCTION__))
;
198 assert(!PtrData)((!PtrData) ? static_cast<void> (0) : __assert_fail ("!PtrData"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Lex/Token.h"
, 198, __PRETTY_FUNCTION__))
;
199 PtrData = const_cast<void *>(D);
200 }
201
202 /// getRawIdentifier - For a raw identifier token (i.e., an identifier
203 /// lexed in raw mode), returns a reference to the text substring in the
204 /// buffer if known.
205 StringRef getRawIdentifier() const {
206 assert(is(tok::raw_identifier))((is(tok::raw_identifier)) ? static_cast<void> (0) : __assert_fail
("is(tok::raw_identifier)", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Lex/Token.h"
, 206, __PRETTY_FUNCTION__))
;
207 return StringRef(reinterpret_cast<const char *>(PtrData), getLength());
208 }
209 void setRawIdentifierData(const char *Ptr) {
210 assert(is(tok::raw_identifier))((is(tok::raw_identifier)) ? static_cast<void> (0) : __assert_fail
("is(tok::raw_identifier)", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Lex/Token.h"
, 210, __PRETTY_FUNCTION__))
;
211 PtrData = const_cast<char*>(Ptr);
212 }
213
214 /// getLiteralData - For a literal token (numeric constant, string, etc), this
215 /// returns a pointer to the start of it in the text buffer if known, null
216 /// otherwise.
217 const char *getLiteralData() const {
218 assert(isLiteral() && "Cannot get literal data of non-literal")((isLiteral() && "Cannot get literal data of non-literal"
) ? static_cast<void> (0) : __assert_fail ("isLiteral() && \"Cannot get literal data of non-literal\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Lex/Token.h"
, 218, __PRETTY_FUNCTION__))
;
219 return reinterpret_cast<const char*>(PtrData);
220 }
221 void setLiteralData(const char *Ptr) {
222 assert(isLiteral() && "Cannot set literal data of non-literal")((isLiteral() && "Cannot set literal data of non-literal"
) ? static_cast<void> (0) : __assert_fail ("isLiteral() && \"Cannot set literal data of non-literal\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Lex/Token.h"
, 222, __PRETTY_FUNCTION__))
;
223 PtrData = const_cast<char*>(Ptr);
224 }
225
226 void *getAnnotationValue() const {
227 assert(isAnnotation() && "Used AnnotVal on non-annotation token")((isAnnotation() && "Used AnnotVal on non-annotation token"
) ? static_cast<void> (0) : __assert_fail ("isAnnotation() && \"Used AnnotVal on non-annotation token\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Lex/Token.h"
, 227, __PRETTY_FUNCTION__))
;
228 return PtrData;
229 }
230 void setAnnotationValue(void *val) {
231 assert(isAnnotation() && "Used AnnotVal on non-annotation token")((isAnnotation() && "Used AnnotVal on non-annotation token"
) ? static_cast<void> (0) : __assert_fail ("isAnnotation() && \"Used AnnotVal on non-annotation token\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Lex/Token.h"
, 231, __PRETTY_FUNCTION__))
;
232 PtrData = val;
233 }
234
235 /// Set the specified flag.
236 void setFlag(TokenFlags Flag) {
237 Flags |= Flag;
238 }
239
240 /// Get the specified flag.
241 bool getFlag(TokenFlags Flag) const {
242 return (Flags & Flag) != 0;
243 }
244
245 /// Unset the specified flag.
246 void clearFlag(TokenFlags Flag) {
247 Flags &= ~Flag;
248 }
249
250 /// Return the internal represtation of the flags.
251 ///
252 /// This is only intended for low-level operations such as writing tokens to
253 /// disk.
254 unsigned getFlags() const {
255 return Flags;
256 }
257
258 /// Set a flag to either true or false.
259 void setFlagValue(TokenFlags Flag, bool Val) {
260 if (Val)
261 setFlag(Flag);
262 else
263 clearFlag(Flag);
264 }
265
266 /// isAtStartOfLine - Return true if this token is at the start of a line.
267 ///
268 bool isAtStartOfLine() const { return getFlag(StartOfLine); }
269
270 /// Return true if this token has whitespace before it.
271 ///
272 bool hasLeadingSpace() const { return getFlag(LeadingSpace); }
273
274 /// Return true if this identifier token should never
275 /// be expanded in the future, due to C99 6.10.3.4p2.
276 bool isExpandDisabled() const { return getFlag(DisableExpand); }
277
278 /// Return true if we have an ObjC keyword identifier.
279 bool isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const;
280
281 /// Return the ObjC keyword kind.
282 tok::ObjCKeywordKind getObjCKeywordID() const;
283
284 /// Return true if this token has trigraphs or escaped newlines in it.
285 bool needsCleaning() const { return getFlag(NeedsCleaning); }
286
287 /// Return true if this token has an empty macro before it.
288 ///
289 bool hasLeadingEmptyMacro() const { return getFlag(LeadingEmptyMacro); }
290
291 /// Return true if this token is a string or character literal which
292 /// has a ud-suffix.
293 bool hasUDSuffix() const { return getFlag(HasUDSuffix); }
294
295 /// Returns true if this token contains a universal character name.
296 bool hasUCN() const { return getFlag(HasUCN); }
297
298 /// Returns true if this token is formed by macro by stringizing or charizing
299 /// operator.
300 bool stringifiedInMacro() const { return getFlag(StringifiedInMacro); }
301
302 /// Returns true if the comma after this token was elided.
303 bool commaAfterElided() const { return getFlag(CommaAfterElided); }
304
305 /// Returns true if this token is an editor placeholder.
306 ///
307 /// Editor placeholders are produced by the code-completion engine and are
308 /// represented as characters between '<#' and '#>' in the source code. The
309 /// lexer uses identifier tokens to represent placeholders.
310 bool isEditorPlaceholder() const { return getFlag(IsEditorPlaceholder); }
311};
312
313/// Information about the conditional stack (\#if directives)
314/// currently active.
315struct PPConditionalInfo {
316 /// Location where the conditional started.
317 SourceLocation IfLoc;
318
319 /// True if this was contained in a skipping directive, e.g.,
320 /// in a "\#if 0" block.
321 bool WasSkipping;
322
323 /// True if we have emitted tokens already, and now we're in
324 /// an \#else block or something. Only useful in Skipping blocks.
325 bool FoundNonSkip;
326
327 /// True if we've seen a \#else in this block. If so,
328 /// \#elif/\#else directives are not allowed.
329 bool FoundElse;
330};
331
332} // end namespace clang
333
334#endif // LLVM_CLANG_LEX_TOKEN_H