Bug Summary

File:clang/lib/Format/ContinuationIndenter.cpp
Warning:line 593, 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 -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 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Format -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Format -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/Format -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include -D NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/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-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Format -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-09-04-040900-46481-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/Format/ContinuationIndenter.cpp

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

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

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/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 SourceLocation::UIntTy 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 SourceLocation::UIntTy 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")(static_cast<void> (0));
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")(static_cast<void> (0));
137 UintData = Len;
138 }
139
140 SourceLocation getAnnotationEndLoc() const {
141 assert(isAnnotation() && "Used AnnotEndLocID on non-annotation token")(static_cast<void> (0));
142 return SourceLocation::getFromRawEncoding(UintData ? UintData : Loc);
143 }
144 void setAnnotationEndLoc(SourceLocation L) {
145 assert(isAnnotation() && "Used AnnotEndLocID on non-annotation token")(static_cast<void> (0));
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) &&(static_cast<void> (0))
181 "getIdentifierInfo() on a tok::raw_identifier token!")(static_cast<void> (0));
182 assert(!isAnnotation() &&(static_cast<void> (0))
183 "getIdentifierInfo() on an annotation token!")(static_cast<void> (0));
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))(static_cast<void> (0));
194 return reinterpret_cast<const void *>(PtrData);
195 }
196 void setEofData(const void *D) {
197 assert(is(tok::eof))(static_cast<void> (0));
198 assert(!PtrData)(static_cast<void> (0));
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))(static_cast<void> (0));
207 return StringRef(reinterpret_cast<const char *>(PtrData), getLength());
208 }
209 void setRawIdentifierData(const char *Ptr) {
210 assert(is(tok::raw_identifier))(static_cast<void> (0));
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")(static_cast<void> (0));
219 return reinterpret_cast<const char*>(PtrData);
220 }
221 void setLiteralData(const char *Ptr) {
222 assert(isLiteral() && "Cannot set literal data of non-literal")(static_cast<void> (0));
223 PtrData = const_cast<char*>(Ptr);
224 }
225
226 void *getAnnotationValue() const {
227 assert(isAnnotation() && "Used AnnotVal on non-annotation token")(static_cast<void> (0));
228 return PtrData;
229 }
230 void setAnnotationValue(void *val) {
231 assert(isAnnotation() && "Used AnnotVal on non-annotation token")(static_cast<void> (0));
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