1 //===--- ContinuationIndenter.cpp - Format C++ code -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief This file implements the continuation indenter.
13 //===----------------------------------------------------------------------===//
15 #include "BreakableToken.h"
16 #include "ContinuationIndenter.h"
17 #include "WhitespaceManager.h"
18 #include "clang/Basic/OperatorPrecedence.h"
19 #include "clang/Basic/SourceManager.h"
20 #include "clang/Format/Format.h"
21 #include "llvm/Support/Debug.h"
24 #define DEBUG_TYPE "format-formatter"
29 // Returns the length of everything up to the first possible line break after
30 // the ), ], } or > matching \c Tok.
31 static unsigned getLengthToMatchingParen(const FormatToken &Tok) {
32 if (!Tok.MatchingParen)
34 FormatToken *End = Tok.MatchingParen;
35 while (End->Next && !End->Next->CanBreakBefore) {
38 return End->TotalLength - Tok.TotalLength + 1;
41 static unsigned getLengthToNextOperator(const FormatToken &Tok) {
42 if (!Tok.NextOperator)
44 return Tok.NextOperator->TotalLength - Tok.TotalLength;
47 // Returns \c true if \c Tok is the "." or "->" of a call and starts the next
48 // segment of a builder type call.
49 static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) {
50 return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope();
53 // Returns \c true if \c Current starts a new parameter.
54 static bool startsNextParameter(const FormatToken &Current,
55 const FormatStyle &Style) {
56 const FormatToken &Previous = *Current.Previous;
57 if (Current.is(TT_CtorInitializerComma) &&
58 Style.BreakConstructorInitializersBeforeComma)
60 return Previous.is(tok::comma) && !Current.isTrailingComment() &&
61 (Previous.isNot(TT_CtorInitializerComma) ||
62 !Style.BreakConstructorInitializersBeforeComma);
65 ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,
66 const AdditionalKeywords &Keywords,
67 SourceManager &SourceMgr,
68 WhitespaceManager &Whitespaces,
69 encoding::Encoding Encoding,
70 bool BinPackInconclusiveFunctions)
71 : Style(Style), Keywords(Keywords), SourceMgr(SourceMgr),
72 Whitespaces(Whitespaces), Encoding(Encoding),
73 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
74 CommentPragmasRegex(Style.CommentPragmas) {}
76 LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
77 const AnnotatedLine *Line,
80 State.FirstIndent = FirstIndent;
81 State.Column = FirstIndent;
83 State.NextToken = Line->First;
84 State.Stack.push_back(ParenState(FirstIndent, Line->Level, FirstIndent,
85 /*AvoidBinPacking=*/false,
86 /*NoLineBreak=*/false));
87 State.LineContainsContinuedForLoopSection = false;
88 State.StartOfStringLiteral = 0;
89 State.StartOfLineLevel = 0;
90 State.LowestLevelOnLine = 0;
91 State.IgnoreStackForComparison = false;
93 // The first token has already been indented and thus consumed.
94 moveStateToNextToken(State, DryRun, /*Newline=*/false);
98 bool ContinuationIndenter::canBreak(const LineState &State) {
99 const FormatToken &Current = *State.NextToken;
100 const FormatToken &Previous = *Current.Previous;
101 assert(&Previous == Current.Previous);
102 if (!Current.CanBreakBefore &&
103 !(State.Stack.back().BreakBeforeClosingBrace &&
104 Current.closesBlockOrBlockTypeList(Style)))
106 // The opening "{" of a braced list has to be on the same line as the first
107 // element if it is nested in another braced init list or function call.
108 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
109 Previous.isNot(TT_DictLiteral) && Previous.BlockKind == BK_BracedInit &&
111 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
113 // This prevents breaks like:
115 // SomeParameter, OtherParameter).DoSomething(
117 // As they hide "DoSomething" and are generally bad for readability.
118 if (Previous.opensScope() && Previous.isNot(tok::l_brace) &&
119 State.LowestLevelOnLine < State.StartOfLineLevel &&
120 State.LowestLevelOnLine < Current.NestingLevel)
122 if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
125 // Don't create a 'hanging' indent if there are multiple blocks in a single
127 if (Previous.is(tok::l_brace) && State.Stack.size() > 1 &&
128 State.Stack[State.Stack.size() - 2].NestedBlockInlined &&
129 State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks)
132 // Don't break after very short return types (e.g. "void") as that is often
134 if (Current.is(TT_FunctionDeclarationName) && State.Column < 6) {
135 if (Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None)
139 return !State.Stack.back().NoLineBreak;
142 bool ContinuationIndenter::mustBreak(const LineState &State) {
143 const FormatToken &Current = *State.NextToken;
144 const FormatToken &Previous = *Current.Previous;
145 if (Current.MustBreakBefore || Current.is(TT_InlineASMColon))
147 if (State.Stack.back().BreakBeforeClosingBrace &&
148 Current.closesBlockOrBlockTypeList(Style))
150 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
152 if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
153 (Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName)) ||
154 (Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&
155 Previous.isNot(tok::question)) ||
156 (!Style.BreakBeforeTernaryOperators &&
157 Previous.is(TT_ConditionalExpr))) &&
158 State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
159 !Current.isOneOf(tok::r_paren, tok::r_brace))
161 if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) ||
162 (Previous.is(TT_ArrayInitializerLSquare) &&
163 Previous.ParameterCount > 1)) &&
164 Style.ColumnLimit > 0 &&
165 getLengthToMatchingParen(Previous) + State.Column - 1 >
166 getColumnLimit(State))
168 if (Current.is(TT_CtorInitializerColon) &&
169 (State.Column + State.Line->Last->TotalLength - Current.TotalLength + 2 >
170 getColumnLimit(State) ||
171 State.Stack.back().BreakBeforeParameter) &&
172 ((Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All) ||
173 Style.BreakConstructorInitializersBeforeComma || Style.ColumnLimit != 0))
175 if (Current.is(TT_SelectorName) && State.Stack.back().ObjCSelectorNameFound &&
176 State.Stack.back().BreakBeforeParameter)
179 unsigned NewLineColumn = getNewLineColumn(State);
180 if (State.Column <= NewLineColumn)
183 if (Current.isMemberAccess() &&
184 State.Column + getLengthToNextOperator(Current) > Style.ColumnLimit)
187 if (Style.AlwaysBreakBeforeMultilineStrings &&
188 (NewLineColumn == State.FirstIndent + Style.ContinuationIndentWidth ||
189 Previous.is(tok::comma) || Current.NestingLevel < 2) &&
190 !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) &&
191 !Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) &&
192 nextIsMultilineString(State))
195 // Using CanBreakBefore here and below takes care of the decision whether the
196 // current style uses wrapping before or after operators for the given
198 if (Previous.is(TT_BinaryOperator) && Current.CanBreakBefore) {
199 // If we need to break somewhere inside the LHS of a binary expression, we
200 // should also break after the operator. Otherwise, the formatting would
201 // hide the operator precedence, e.g. in:
202 // if (aaaaaaaaaaaaaa ==
203 // bbbbbbbbbbbbbb && c) {..
204 // For comparisons, we only apply this rule, if the LHS is a binary
205 // expression itself as otherwise, the line breaks seem superfluous.
206 // We need special cases for ">>" which we have split into two ">" while
207 // lexing in order to make template parsing easier.
208 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
209 Previous.getPrecedence() == prec::Equality) &&
211 Previous.Previous->isNot(TT_BinaryOperator); // For >>.
212 bool LHSIsBinaryExpr =
213 Previous.Previous && Previous.Previous->EndsBinaryExpression;
214 if ((!IsComparison || LHSIsBinaryExpr) && !Current.isTrailingComment() &&
215 Previous.getPrecedence() != prec::Assignment &&
216 State.Stack.back().BreakBeforeParameter)
218 } else if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore &&
219 State.Stack.back().BreakBeforeParameter) {
223 // Same as above, but for the first "<<" operator.
224 if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator) &&
225 State.Stack.back().BreakBeforeParameter &&
226 State.Stack.back().FirstLessLess == 0)
229 if (Current.NestingLevel == 0 && !Current.isTrailingComment()) {
230 // Always break after "template <...>" and leading annotations. This is only
231 // for cases where the entire line does not fit on a single line as a
232 // different LineFormatter would be used otherwise.
233 if (Previous.ClosesTemplateDeclaration)
235 if (Previous.is(TT_FunctionAnnotationRParen))
237 if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) &&
238 Current.isNot(TT_LeadingJavaAnnotation))
242 // If the return type spans multiple lines, wrap before the function name.
243 if ((Current.is(TT_FunctionDeclarationName) ||
244 (Current.is(tok::kw_operator) && !Previous.is(tok::coloncolon))) &&
245 State.Stack.back().BreakBeforeParameter)
248 if (startsSegmentOfBuilderTypeCall(Current) &&
249 (State.Stack.back().CallContinuation != 0 ||
250 State.Stack.back().BreakBeforeParameter))
253 // The following could be precomputed as they do not depend on the state.
254 // However, as they should take effect only if the UnwrappedLine does not fit
255 // into the ColumnLimit, they are checked here in the ContinuationIndenter.
256 if (Style.ColumnLimit != 0 && Previous.BlockKind == BK_Block &&
257 Previous.is(tok::l_brace) && !Current.isOneOf(tok::r_brace, tok::comment))
260 if (Current.is(tok::lessless) &&
261 ((Previous.is(tok::identifier) && Previous.TokenText == "endl") ||
262 (Previous.Tok.isLiteral() && (Previous.TokenText.endswith("\\n\"") ||
263 Previous.TokenText == "\'\\n\'"))))
269 unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
271 unsigned ExtraSpaces) {
272 const FormatToken &Current = *State.NextToken;
274 assert(!State.Stack.empty());
275 if ((Current.is(TT_ImplicitStringLiteral) &&
276 (Current.Previous->Tok.getIdentifierInfo() == nullptr ||
277 Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
278 tok::pp_not_keyword))) {
280 SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getEnd());
281 if (Current.LastNewlineOffset != 0) {
282 // If there is a newline within this token, the final column will solely
283 // determined by the current end column.
284 State.Column = EndColumn;
286 unsigned StartColumn =
287 SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getBegin());
288 assert(EndColumn >= StartColumn);
289 State.Column += EndColumn - StartColumn;
291 moveStateToNextToken(State, DryRun, /*Newline=*/false);
295 unsigned Penalty = 0;
297 Penalty = addTokenOnNewLine(State, DryRun);
299 addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
301 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
304 void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
305 unsigned ExtraSpaces) {
306 FormatToken &Current = *State.NextToken;
307 const FormatToken &Previous = *State.NextToken->Previous;
308 if (Current.is(tok::equal) &&
309 (State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) &&
310 State.Stack.back().VariablePos == 0) {
311 State.Stack.back().VariablePos = State.Column;
312 // Move over * and & if they are bound to the variable name.
313 const FormatToken *Tok = &Previous;
314 while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
315 State.Stack.back().VariablePos -= Tok->ColumnWidth;
316 if (Tok->SpacesRequiredBefore != 0)
320 if (Previous.PartOfMultiVariableDeclStmt)
321 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
324 unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
327 Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, /*IndentLevel=*/0,
328 Spaces, State.Column + Spaces);
330 if (Current.is(TT_SelectorName) &&
331 !State.Stack.back().ObjCSelectorNameFound) {
333 std::max(State.FirstIndent + Style.ContinuationIndentWidth,
334 State.Stack.back().Indent);
335 unsigned FirstColonPos = State.Column + Spaces + Current.ColumnWidth;
336 if (Current.LongestObjCSelectorName == 0)
337 State.Stack.back().AlignColons = false;
338 else if (MinIndent + Current.LongestObjCSelectorName > FirstColonPos)
339 State.Stack.back().ColonPos = MinIndent + Current.LongestObjCSelectorName;
341 State.Stack.back().ColonPos = FirstColonPos;
344 // In "AlwaysBreak" mode, enforce wrapping directly after the parenthesis by
345 // disallowing any further line breaks if there is no line break after the
346 // opening parenthesis. Don't break if it doesn't conserve columns.
347 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_AlwaysBreak &&
348 Previous.is(tok::l_paren) && State.Column > getNewLineColumn(State) &&
349 (!Previous.Previous ||
350 !Previous.Previous->isOneOf(tok::kw_for, tok::kw_while, tok::kw_switch)))
351 State.Stack.back().NoLineBreak = true;
353 if (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign &&
354 Previous.opensScope() && Previous.isNot(TT_ObjCMethodExpr) &&
355 (Current.isNot(TT_LineComment) || Previous.BlockKind == BK_BracedInit))
356 State.Stack.back().Indent = State.Column + Spaces;
357 if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
358 State.Stack.back().NoLineBreak = true;
359 if (startsSegmentOfBuilderTypeCall(Current) &&
360 State.Column > getNewLineColumn(State))
361 State.Stack.back().ContainsUnwrappedBuilder = true;
363 if (Current.is(TT_LambdaArrow) && Style.Language == FormatStyle::LK_Java)
364 State.Stack.back().NoLineBreak = true;
365 if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&
366 (Previous.MatchingParen &&
367 (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10))) {
368 // If there is a function call with long parameters, break before trailing
369 // calls. This prevents things like:
370 // EXPECT_CALL(SomeLongParameter).Times(
372 // We don't want to do this for short parameters as they can just be
374 State.Stack.back().NoLineBreak = true;
377 State.Column += Spaces;
378 if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&
380 Previous.Previous->isOneOf(tok::kw_if, tok::kw_for)) {
381 // Treat the condition inside an if as if it was a second function
382 // parameter, i.e. let nested calls have a continuation indent.
383 State.Stack.back().LastSpace = State.Column;
384 State.Stack.back().NestedBlockIndent = State.Column;
385 } else if (!Current.isOneOf(tok::comment, tok::caret) &&
386 (Previous.is(tok::comma) ||
387 (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) {
388 State.Stack.back().LastSpace = State.Column;
389 } else if ((Previous.isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
390 TT_CtorInitializerColon)) &&
391 ((Previous.getPrecedence() != prec::Assignment &&
392 (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||
393 Previous.NextOperator)) ||
394 Current.StartsBinaryExpression)) {
395 // Always indent relative to the RHS of the expression unless this is a
396 // simple assignment without binary expression on the RHS. Also indent
397 // relative to unary operators and the colons of constructor initializers.
398 State.Stack.back().LastSpace = State.Column;
399 } else if (Previous.is(TT_InheritanceColon)) {
400 State.Stack.back().Indent = State.Column;
401 State.Stack.back().LastSpace = State.Column;
402 } else if (Previous.opensScope()) {
403 // If a function has a trailing call, indent all parameters from the
404 // opening parenthesis. This avoids confusing indents like:
405 // OuterFunction(InnerFunctionCall( // break
406 // ParameterToInnerFunction)) // break
407 // .SecondInnerFunctionCall();
408 bool HasTrailingCall = false;
409 if (Previous.MatchingParen) {
410 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
411 HasTrailingCall = Next && Next->isMemberAccess();
413 if (HasTrailingCall && State.Stack.size() > 1 &&
414 State.Stack[State.Stack.size() - 2].CallContinuation == 0)
415 State.Stack.back().LastSpace = State.Column;
419 unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
421 FormatToken &Current = *State.NextToken;
422 const FormatToken &Previous = *State.NextToken->Previous;
424 // Extra penalty that needs to be added because of the way certain line
425 // breaks are chosen.
426 unsigned Penalty = 0;
428 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
429 const FormatToken *NextNonComment = Previous.getNextNonComment();
431 NextNonComment = &Current;
432 // The first line break on any NestingLevel causes an extra penalty in order
433 // prefer similar line breaks.
434 if (!State.Stack.back().ContainsLineBreak)
436 State.Stack.back().ContainsLineBreak = true;
438 Penalty += State.NextToken->SplitPenalty;
440 // Breaking before the first "<<" is generally not desirable if the LHS is
441 // short. Also always add the penalty if the LHS is split over mutliple lines
442 // to avoid unnecessary line breaks that just work around this penalty.
443 if (NextNonComment->is(tok::lessless) &&
444 State.Stack.back().FirstLessLess == 0 &&
445 (State.Column <= Style.ColumnLimit / 3 ||
446 State.Stack.back().BreakBeforeParameter))
447 Penalty += Style.PenaltyBreakFirstLessLess;
449 State.Column = getNewLineColumn(State);
451 // Indent nested blocks relative to this column, unless in a very specific
452 // JavaScript special case where:
454 // var loooooong_name =
459 // is common and should be formatted like a free-standing function.
460 if (Style.Language != FormatStyle::LK_JavaScript ||
461 Current.NestingLevel != 0 || !PreviousNonComment->is(tok::equal) ||
462 !Current.is(Keywords.kw_function))
463 State.Stack.back().NestedBlockIndent = State.Column;
465 if (NextNonComment->isMemberAccess()) {
466 if (State.Stack.back().CallContinuation == 0)
467 State.Stack.back().CallContinuation = State.Column;
468 } else if (NextNonComment->is(TT_SelectorName)) {
469 if (!State.Stack.back().ObjCSelectorNameFound) {
470 if (NextNonComment->LongestObjCSelectorName == 0) {
471 State.Stack.back().AlignColons = false;
473 State.Stack.back().ColonPos =
474 (Style.IndentWrappedFunctionNames
475 ? std::max(State.Stack.back().Indent,
476 State.FirstIndent + Style.ContinuationIndentWidth)
477 : State.Stack.back().Indent) +
478 NextNonComment->LongestObjCSelectorName;
480 } else if (State.Stack.back().AlignColons &&
481 State.Stack.back().ColonPos <= NextNonComment->ColumnWidth) {
482 State.Stack.back().ColonPos = State.Column + NextNonComment->ColumnWidth;
484 } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
485 PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
486 // FIXME: This is hacky, find a better way. The problem is that in an ObjC
487 // method expression, the block should be aligned to the line starting it,
489 // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
493 // Thus, we set LastSpace of the next higher NestingLevel, to which we move
494 // when we consume all of the "}"'s FakeRParens at the "{".
495 if (State.Stack.size() > 1)
496 State.Stack[State.Stack.size() - 2].LastSpace =
497 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
498 Style.ContinuationIndentWidth;
501 if ((Previous.isOneOf(tok::comma, tok::semi) &&
502 !State.Stack.back().AvoidBinPacking) ||
503 Previous.is(TT_BinaryOperator))
504 State.Stack.back().BreakBeforeParameter = false;
505 if (Previous.isOneOf(TT_TemplateCloser, TT_JavaAnnotation) &&
506 Current.NestingLevel == 0)
507 State.Stack.back().BreakBeforeParameter = false;
508 if (NextNonComment->is(tok::question) ||
509 (PreviousNonComment && PreviousNonComment->is(tok::question)))
510 State.Stack.back().BreakBeforeParameter = true;
511 if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore)
512 State.Stack.back().BreakBeforeParameter = false;
515 unsigned Newlines = std::max(
516 1u, std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1));
517 Whitespaces.replaceWhitespace(Current, Newlines,
518 State.Stack.back().IndentLevel, State.Column,
519 State.Column, State.Line->InPPDirective);
522 if (!Current.isTrailingComment())
523 State.Stack.back().LastSpace = State.Column;
524 State.StartOfLineLevel = Current.NestingLevel;
525 State.LowestLevelOnLine = Current.NestingLevel;
527 // Any break on this level means that the parent level has been broken
528 // and we need to avoid bin packing there.
529 bool NestedBlockSpecialCase =
530 Style.Language != FormatStyle::LK_Cpp &&
531 Current.is(tok::r_brace) && State.Stack.size() > 1 &&
532 State.Stack[State.Stack.size() - 2].NestedBlockInlined;
533 if (!NestedBlockSpecialCase)
534 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
535 State.Stack[i].BreakBeforeParameter = true;
537 if (PreviousNonComment &&
538 !PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
539 (PreviousNonComment->isNot(TT_TemplateCloser) ||
540 Current.NestingLevel != 0) &&
541 !PreviousNonComment->isOneOf(
542 TT_BinaryOperator, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
543 TT_LeadingJavaAnnotation) &&
544 Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope())
545 State.Stack.back().BreakBeforeParameter = true;
547 // If we break after { or the [ of an array initializer, we should also break
548 // before the corresponding } or ].
549 if (PreviousNonComment &&
550 (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)))
551 State.Stack.back().BreakBeforeClosingBrace = true;
553 if (State.Stack.back().AvoidBinPacking) {
554 // If we are breaking after '(', '{', '<', this is not bin packing
555 // unless AllowAllParametersOfDeclarationOnNextLine is false or this is a
556 // dict/object literal.
557 if (!Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) ||
558 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
559 State.Line->MustBeDeclaration) ||
560 Previous.is(TT_DictLiteral))
561 State.Stack.back().BreakBeforeParameter = true;
567 unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
568 if (!State.NextToken || !State.NextToken->Previous)
570 FormatToken &Current = *State.NextToken;
571 const FormatToken &Previous = *Current.Previous;
572 // If we are continuing an expression, we want to use the continuation indent.
573 unsigned ContinuationIndent =
574 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
575 Style.ContinuationIndentWidth;
576 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
577 const FormatToken *NextNonComment = Previous.getNextNonComment();
579 NextNonComment = &Current;
581 // Java specific bits.
582 if (Style.Language == FormatStyle::LK_Java &&
583 Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends))
584 return std::max(State.Stack.back().LastSpace,
585 State.Stack.back().Indent + Style.ContinuationIndentWidth);
587 if (NextNonComment->is(tok::l_brace) && NextNonComment->BlockKind == BK_Block)
588 return Current.NestingLevel == 0 ? State.FirstIndent
589 : State.Stack.back().Indent;
590 if (Current.isOneOf(tok::r_brace, tok::r_square) && State.Stack.size() > 1) {
591 if (Current.closesBlockOrBlockTypeList(Style))
592 return State.Stack[State.Stack.size() - 2].NestedBlockIndent;
593 if (Current.MatchingParen &&
594 Current.MatchingParen->BlockKind == BK_BracedInit)
595 return State.Stack[State.Stack.size() - 2].LastSpace;
596 return State.FirstIndent;
598 if (Current.is(tok::identifier) && Current.Next &&
599 Current.Next->is(TT_DictLiteral))
600 return State.Stack.back().Indent;
601 if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
602 return State.StartOfStringLiteral;
603 if (NextNonComment->is(TT_ObjCStringLiteral) &&
604 State.StartOfStringLiteral != 0)
605 return State.StartOfStringLiteral - 1;
606 if (NextNonComment->is(tok::lessless) &&
607 State.Stack.back().FirstLessLess != 0)
608 return State.Stack.back().FirstLessLess;
609 if (NextNonComment->isMemberAccess()) {
610 if (State.Stack.back().CallContinuation == 0)
611 return ContinuationIndent;
612 return State.Stack.back().CallContinuation;
614 if (State.Stack.back().QuestionColumn != 0 &&
615 ((NextNonComment->is(tok::colon) &&
616 NextNonComment->is(TT_ConditionalExpr)) ||
617 Previous.is(TT_ConditionalExpr)))
618 return State.Stack.back().QuestionColumn;
619 if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0)
620 return State.Stack.back().VariablePos;
621 if ((PreviousNonComment &&
622 (PreviousNonComment->ClosesTemplateDeclaration ||
623 PreviousNonComment->isOneOf(
624 TT_AttributeParen, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
625 TT_LeadingJavaAnnotation))) ||
626 (!Style.IndentWrappedFunctionNames &&
627 NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName)))
628 return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
629 if (NextNonComment->is(TT_SelectorName)) {
630 if (!State.Stack.back().ObjCSelectorNameFound) {
631 if (NextNonComment->LongestObjCSelectorName == 0)
632 return State.Stack.back().Indent;
633 return (Style.IndentWrappedFunctionNames
634 ? std::max(State.Stack.back().Indent,
635 State.FirstIndent + Style.ContinuationIndentWidth)
636 : State.Stack.back().Indent) +
637 NextNonComment->LongestObjCSelectorName -
638 NextNonComment->ColumnWidth;
640 if (!State.Stack.back().AlignColons)
641 return State.Stack.back().Indent;
642 if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth)
643 return State.Stack.back().ColonPos - NextNonComment->ColumnWidth;
644 return State.Stack.back().Indent;
646 if (NextNonComment->is(TT_ArraySubscriptLSquare)) {
647 if (State.Stack.back().StartOfArraySubscripts != 0)
648 return State.Stack.back().StartOfArraySubscripts;
649 return ContinuationIndent;
652 // This ensure that we correctly format ObjC methods calls without inputs,
653 // i.e. where the last element isn't selector like: [callee method];
654 if (NextNonComment->is(tok::identifier) && NextNonComment->FakeRParens == 0 &&
655 NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr))
656 return State.Stack.back().Indent;
658 if (NextNonComment->isOneOf(TT_StartOfName, TT_PointerOrReference) ||
659 Previous.isOneOf(tok::coloncolon, tok::equal, TT_JsTypeColon))
660 return ContinuationIndent;
661 if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
662 PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))
663 return ContinuationIndent;
664 if (NextNonComment->is(TT_CtorInitializerColon))
665 return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
666 if (NextNonComment->is(TT_CtorInitializerComma))
667 return State.Stack.back().Indent;
668 if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() &&
669 !Current.isOneOf(tok::colon, tok::comment))
670 return ContinuationIndent;
671 if (State.Stack.back().Indent == State.FirstIndent && PreviousNonComment &&
672 PreviousNonComment->isNot(tok::r_brace))
673 // Ensure that we fall back to the continuation indent width instead of
674 // just flushing continuations left.
675 return State.Stack.back().Indent + Style.ContinuationIndentWidth;
676 return State.Stack.back().Indent;
679 unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
680 bool DryRun, bool Newline) {
681 assert(State.Stack.size());
682 const FormatToken &Current = *State.NextToken;
684 if (Current.is(TT_InheritanceColon))
685 State.Stack.back().AvoidBinPacking = true;
686 if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) {
687 if (State.Stack.back().FirstLessLess == 0)
688 State.Stack.back().FirstLessLess = State.Column;
690 State.Stack.back().LastOperatorWrapped = Newline;
692 if ((Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless)) ||
693 Current.is(TT_ConditionalExpr))
694 State.Stack.back().LastOperatorWrapped = Newline;
695 if (Current.is(TT_ArraySubscriptLSquare) &&
696 State.Stack.back().StartOfArraySubscripts == 0)
697 State.Stack.back().StartOfArraySubscripts = State.Column;
698 if ((Current.is(tok::question) && Style.BreakBeforeTernaryOperators) ||
699 (Current.getPreviousNonComment() && Current.isNot(tok::colon) &&
700 Current.getPreviousNonComment()->is(tok::question) &&
701 !Style.BreakBeforeTernaryOperators))
702 State.Stack.back().QuestionColumn = State.Column;
703 if (!Current.opensScope() && !Current.closesScope())
704 State.LowestLevelOnLine =
705 std::min(State.LowestLevelOnLine, Current.NestingLevel);
706 if (Current.isMemberAccess())
707 State.Stack.back().StartOfFunctionCall =
708 !Current.NextOperator ? 0 : State.Column;
709 if (Current.is(TT_SelectorName)) {
710 State.Stack.back().ObjCSelectorNameFound = true;
711 if (Style.IndentWrappedFunctionNames) {
712 State.Stack.back().Indent =
713 State.FirstIndent + Style.ContinuationIndentWidth;
716 if (Current.is(TT_CtorInitializerColon)) {
717 // Indent 2 from the column, so:
718 // SomeClass::SomeClass()
722 State.Stack.back().Indent =
723 State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
724 State.Stack.back().NestedBlockIndent = State.Stack.back().Indent;
725 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
726 State.Stack.back().AvoidBinPacking = true;
727 State.Stack.back().BreakBeforeParameter = false;
729 if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline)
730 State.Stack.back().NestedBlockIndent =
731 State.Column + Current.ColumnWidth + 1;
733 // Insert scopes created by fake parenthesis.
734 const FormatToken *Previous = Current.getPreviousNonComment();
736 // Add special behavior to support a format commonly used for JavaScript
738 // SomeFunction(function() {
742 if (Current.isNot(tok::comment) && Previous &&
743 Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
744 !Previous->is(TT_DictLiteral) && State.Stack.size() > 1) {
745 if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline)
746 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
747 State.Stack[i].NoLineBreak = true;
748 State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;
750 if (Previous && (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) ||
751 Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr)) &&
752 !Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
753 State.Stack.back().NestedBlockInlined =
755 (Previous->isNot(tok::l_paren) || Previous->ParameterCount > 1);
758 moveStatePastFakeLParens(State, Newline);
759 moveStatePastScopeOpener(State, Newline);
760 moveStatePastScopeCloser(State);
761 moveStatePastFakeRParens(State);
763 if (Current.isStringLiteral() && State.StartOfStringLiteral == 0)
764 State.StartOfStringLiteral = State.Column;
765 if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0)
766 State.StartOfStringLiteral = State.Column + 1;
767 else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
768 !Current.isStringLiteral())
769 State.StartOfStringLiteral = 0;
771 State.Column += Current.ColumnWidth;
772 State.NextToken = State.NextToken->Next;
773 unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
774 if (State.Column > getColumnLimit(State)) {
775 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
776 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
780 Current.Role->formatFromToken(State, this, DryRun);
781 // If the previous has a special role, let it consume tokens as appropriate.
782 // It is necessary to start at the previous token for the only implemented
783 // role (comma separated list). That way, the decision whether or not to break
784 // after the "{" is already done and both options are tried and evaluated.
785 // FIXME: This is ugly, find a better way.
786 if (Previous && Previous->Role)
787 Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
792 void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
794 const FormatToken &Current = *State.NextToken;
795 const FormatToken *Previous = Current.getPreviousNonComment();
797 // Don't add extra indentation for the first fake parenthesis after
798 // 'return', assignments or opening <({[. The indentation for these cases
800 bool SkipFirstExtraIndent =
801 (Previous && (Previous->opensScope() ||
802 Previous->isOneOf(tok::semi, tok::kw_return) ||
803 (Previous->getPrecedence() == prec::Assignment &&
804 Style.AlignOperands) ||
805 Previous->is(TT_ObjCMethodExpr)));
806 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
807 I = Current.FakeLParens.rbegin(),
808 E = Current.FakeLParens.rend();
810 ParenState NewParenState = State.Stack.back();
811 NewParenState.ContainsLineBreak = false;
813 // Indent from 'LastSpace' unless these are fake parentheses encapsulating
814 // a builder type call after 'return' or, if the alignment after opening
815 // brackets is disabled.
816 if (!Current.isTrailingComment() &&
817 (Style.AlignOperands || *I < prec::Assignment) &&
818 (!Previous || Previous->isNot(tok::kw_return) ||
819 (Style.Language != FormatStyle::LK_Java && *I > 0)) &&
820 (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign ||
821 *I != prec::Comma || Current.NestingLevel == 0))
822 NewParenState.Indent =
823 std::max(std::max(State.Column, NewParenState.Indent),
824 State.Stack.back().LastSpace);
826 // Don't allow the RHS of an operator to be split over multiple lines unless
827 // there is a line-break right after the operator.
828 // Exclude relational operators, as there, it is always more desirable to
829 // have the LHS 'left' of the RHS.
830 if (Previous && Previous->getPrecedence() > prec::Assignment &&
831 Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
832 Previous->getPrecedence() != prec::Relational) {
833 bool BreakBeforeOperator =
834 Previous->is(tok::lessless) ||
835 (Previous->is(TT_BinaryOperator) &&
836 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) ||
837 (Previous->is(TT_ConditionalExpr) &&
838 Style.BreakBeforeTernaryOperators);
839 if ((!Newline && !BreakBeforeOperator) ||
840 (!State.Stack.back().LastOperatorWrapped && BreakBeforeOperator))
841 NewParenState.NoLineBreak = true;
844 // Do not indent relative to the fake parentheses inserted for "." or "->".
845 // This is a special case to make the following to statements consistent:
846 // OuterFunction(InnerFunctionCall( // break
847 // ParameterToInnerFunction));
848 // OuterFunction(SomeObject.InnerFunctionCall( // break
849 // ParameterToInnerFunction));
850 if (*I > prec::Unknown)
851 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
852 if (*I != prec::Conditional && !Current.is(TT_UnaryOperator))
853 NewParenState.StartOfFunctionCall = State.Column;
855 // Always indent conditional expressions. Never indent expression where
856 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
857 // prec::Assignment) as those have different indentation rules. Indent
858 // other expression, unless the indentation needs to be skipped.
859 if (*I == prec::Conditional ||
860 (!SkipFirstExtraIndent && *I > prec::Assignment &&
861 !Current.isTrailingComment()))
862 NewParenState.Indent += Style.ContinuationIndentWidth;
863 if ((Previous && !Previous->opensScope()) || *I > prec::Comma)
864 NewParenState.BreakBeforeParameter = false;
865 State.Stack.push_back(NewParenState);
866 SkipFirstExtraIndent = false;
870 void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
871 for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) {
872 unsigned VariablePos = State.Stack.back().VariablePos;
873 if (State.Stack.size() == 1) {
874 // Do not pop the last element.
877 State.Stack.pop_back();
878 State.Stack.back().VariablePos = VariablePos;
882 void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
884 const FormatToken &Current = *State.NextToken;
885 if (!Current.opensScope())
888 if (Current.MatchingParen && Current.BlockKind == BK_Block) {
889 moveStateToNewBlock(State);
894 unsigned NewIndentLevel = State.Stack.back().IndentLevel;
895 unsigned LastSpace = State.Stack.back().LastSpace;
896 bool AvoidBinPacking;
897 bool BreakBeforeParameter = false;
898 unsigned NestedBlockIndent = std::max(State.Stack.back().StartOfFunctionCall,
899 State.Stack.back().NestedBlockIndent);
900 if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)) {
901 if (Current.opensBlockOrBlockTypeList(Style)) {
902 NewIndent = State.Stack.back().NestedBlockIndent + Style.IndentWidth;
903 NewIndent = std::min(State.Column + 2, NewIndent);
906 NewIndent = State.Stack.back().LastSpace + Style.ContinuationIndentWidth;
908 const FormatToken *NextNoComment = Current.getNextNonComment();
910 Current.isOneOf(TT_ArrayInitializerLSquare, TT_DictLiteral) ||
911 Style.Language == FormatStyle::LK_Proto || !Style.BinPackArguments ||
912 (NextNoComment && NextNoComment->is(TT_DesignatedInitializerPeriod));
913 if (Current.ParameterCount > 1)
914 NestedBlockIndent = std::max(NestedBlockIndent, State.Column + 1);
916 NewIndent = Style.ContinuationIndentWidth +
917 std::max(State.Stack.back().LastSpace,
918 State.Stack.back().StartOfFunctionCall);
920 // Ensure that different different brackets force relative alignment, e.g.:
921 // void SomeFunction(vector< // break
923 // FIXME: We likely want to do this for more combinations of brackets.
924 // Verify that it is wanted for ObjC, too.
925 if (Current.Tok.getKind() == tok::less &&
926 Current.ParentBracket == tok::l_paren) {
927 NewIndent = std::max(NewIndent, State.Stack.back().Indent);
928 LastSpace = std::max(LastSpace, State.Stack.back().Indent);
932 (State.Line->MustBeDeclaration && !Style.BinPackParameters) ||
933 (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||
934 (Style.ExperimentalAutoDetectBinPacking &&
935 (Current.PackingKind == PPK_OnePerLine ||
936 (!BinPackInconclusiveFunctions &&
937 Current.PackingKind == PPK_Inconclusive)));
938 if (Current.is(TT_ObjCMethodExpr) && Current.MatchingParen) {
939 if (Style.ColumnLimit) {
940 // If this '[' opens an ObjC call, determine whether all parameters fit
941 // into one line and put one per line if they don't.
942 if (getLengthToMatchingParen(Current) + State.Column >
943 getColumnLimit(State))
944 BreakBeforeParameter = true;
946 // For ColumnLimit = 0, we have to figure out whether there is or has to
947 // be a line break within this call.
948 for (const FormatToken *Tok = &Current;
949 Tok && Tok != Current.MatchingParen; Tok = Tok->Next) {
950 if (Tok->MustBreakBefore ||
951 (Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) {
952 BreakBeforeParameter = true;
959 // Generally inherit NoLineBreak from the current scope to nested scope.
960 // However, don't do this for non-empty nested blocks, dict literals and
961 // array literals as these follow different indentation rules.
963 Current.Children.empty() &&
964 !Current.isOneOf(TT_DictLiteral, TT_ArrayInitializerLSquare) &&
965 (State.Stack.back().NoLineBreak ||
966 (Current.is(TT_TemplateOpener) &&
967 State.Stack.back().ContainsUnwrappedBuilder));
968 State.Stack.push_back(ParenState(NewIndent, NewIndentLevel, LastSpace,
969 AvoidBinPacking, NoLineBreak));
970 State.Stack.back().NestedBlockIndent = NestedBlockIndent;
971 State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
972 State.Stack.back().HasMultipleNestedBlocks = Current.BlockParameterCount > 1;
975 void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
976 const FormatToken &Current = *State.NextToken;
977 if (!Current.closesScope())
980 // If we encounter a closing ), ], } or >, we can remove a level from our
982 if (State.Stack.size() > 1 &&
983 (Current.isOneOf(tok::r_paren, tok::r_square) ||
984 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
985 State.NextToken->is(TT_TemplateCloser)))
986 State.Stack.pop_back();
988 if (Current.is(tok::r_square)) {
989 // If this ends the array subscript expr, reset the corresponding value.
990 const FormatToken *NextNonComment = Current.getNextNonComment();
991 if (NextNonComment && NextNonComment->isNot(tok::l_square))
992 State.Stack.back().StartOfArraySubscripts = 0;
996 void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
997 unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
998 // ObjC block sometimes follow special indentation rules.
1000 NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace)
1001 ? Style.ObjCBlockIndentWidth
1002 : Style.IndentWidth);
1003 State.Stack.push_back(ParenState(
1004 NewIndent, /*NewIndentLevel=*/State.Stack.back().IndentLevel + 1,
1005 State.Stack.back().LastSpace, /*AvoidBinPacking=*/true,
1006 /*NoLineBreak=*/false));
1007 State.Stack.back().NestedBlockIndent = NestedBlockIndent;
1008 State.Stack.back().BreakBeforeParameter = true;
1011 unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
1013 // Break before further function parameters on all levels.
1014 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1015 State.Stack[i].BreakBeforeParameter = true;
1017 unsigned ColumnsUsed = State.Column;
1018 // We can only affect layout of the first and the last line, so the penalty
1019 // for all other lines is constant, and we ignore it.
1020 State.Column = Current.LastLineColumnWidth;
1022 if (ColumnsUsed > getColumnLimit(State))
1023 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
1027 unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
1030 // Don't break multi-line tokens other than block comments. Instead, just
1031 // update the state.
1032 if (Current.isNot(TT_BlockComment) && Current.IsMultiline)
1033 return addMultilineToken(Current, State);
1035 // Don't break implicit string literals or import statements.
1036 if (Current.is(TT_ImplicitStringLiteral) ||
1037 State.Line->Type == LT_ImportStatement)
1040 if (!Current.isStringLiteral() && !Current.is(tok::comment))
1043 std::unique_ptr<BreakableToken> Token;
1044 unsigned StartColumn = State.Column - Current.ColumnWidth;
1045 unsigned ColumnLimit = getColumnLimit(State);
1047 if (Current.isStringLiteral()) {
1048 // FIXME: String literal breaking is currently disabled for Java and JS, as
1049 // it requires strings to be merged using "+" which we don't support.
1050 if (Style.Language == FormatStyle::LK_Java ||
1051 Style.Language == FormatStyle::LK_JavaScript)
1054 // Don't break string literals inside preprocessor directives (except for
1055 // #define directives, as their contents are stored in separate lines and
1056 // are not affected by this check).
1057 // This way we avoid breaking code with line directives and unknown
1058 // preprocessor directives that contain long string literals.
1059 if (State.Line->Type == LT_PreprocessorDirective)
1061 // Exempts unterminated string literals from line breaking. The user will
1062 // likely want to terminate the string before any line breaking is done.
1063 if (Current.IsUnterminatedLiteral)
1066 StringRef Text = Current.TokenText;
1069 bool IsNSStringLiteral = false;
1070 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
1071 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
1072 // reduce the overhead) for each FormatToken, which is a string, so that we
1073 // don't run multiple checks here on the hot path.
1074 if (Text.startswith("\"") && Current.Previous &&
1075 Current.Previous->is(tok::at)) {
1076 IsNSStringLiteral = true;
1079 if ((Text.endswith(Postfix = "\"") &&
1080 (IsNSStringLiteral || Text.startswith(Prefix = "\"") ||
1081 Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
1082 Text.startswith(Prefix = "u8\"") ||
1083 Text.startswith(Prefix = "L\""))) ||
1084 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) {
1085 Token.reset(new BreakableStringLiteral(
1086 Current, State.Line->Level, StartColumn, Prefix, Postfix,
1087 State.Line->InPPDirective, Encoding, Style));
1091 } else if (Current.is(TT_BlockComment) && Current.isTrailingComment()) {
1092 if (!Style.ReflowComments ||
1093 CommentPragmasRegex.match(Current.TokenText.substr(2)))
1095 Token.reset(new BreakableBlockComment(
1096 Current, State.Line->Level, StartColumn, Current.OriginalColumn,
1097 !Current.Previous, State.Line->InPPDirective, Encoding, Style));
1098 } else if (Current.is(TT_LineComment) &&
1099 (Current.Previous == nullptr ||
1100 Current.Previous->isNot(TT_ImplicitStringLiteral))) {
1101 if (!Style.ReflowComments ||
1102 CommentPragmasRegex.match(Current.TokenText.substr(2)))
1104 Token.reset(new BreakableLineComment(Current, State.Line->Level,
1105 StartColumn, /*InPPDirective=*/false,
1107 // We don't insert backslashes when breaking line comments.
1108 ColumnLimit = Style.ColumnLimit;
1112 if (Current.UnbreakableTailLength >= ColumnLimit)
1115 unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength;
1116 bool BreakInserted = false;
1117 unsigned Penalty = 0;
1118 unsigned RemainingTokenColumns = 0;
1119 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
1120 LineIndex != EndIndex; ++LineIndex) {
1122 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
1123 unsigned TailOffset = 0;
1124 RemainingTokenColumns =
1125 Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
1126 while (RemainingTokenColumns > RemainingSpace) {
1127 BreakableToken::Split Split =
1128 Token->getSplit(LineIndex, TailOffset, ColumnLimit);
1129 if (Split.first == StringRef::npos) {
1130 // The last line's penalty is handled in addNextStateToQueue().
1131 if (LineIndex < EndIndex - 1)
1132 Penalty += Style.PenaltyExcessCharacter *
1133 (RemainingTokenColumns - RemainingSpace);
1136 assert(Split.first != 0);
1137 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
1138 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
1140 // We can remove extra whitespace instead of breaking the line.
1141 if (RemainingTokenColumns + 1 - Split.second <= RemainingSpace) {
1142 RemainingTokenColumns = 0;
1144 Token->replaceWhitespace(LineIndex, TailOffset, Split, Whitespaces);
1148 // When breaking before a tab character, it may be moved by a few columns,
1149 // but will still be expanded to the next tab stop, so we don't save any
1151 if (NewRemainingTokenColumns == RemainingTokenColumns)
1154 assert(NewRemainingTokenColumns < RemainingTokenColumns);
1156 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
1157 Penalty += Current.SplitPenalty;
1158 unsigned ColumnsUsed =
1159 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
1160 if (ColumnsUsed > ColumnLimit) {
1161 Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit);
1163 TailOffset += Split.first + Split.second;
1164 RemainingTokenColumns = NewRemainingTokenColumns;
1165 BreakInserted = true;
1169 State.Column = RemainingTokenColumns;
1171 if (BreakInserted) {
1172 // If we break the token inside a parameter list, we need to break before
1173 // the next parameter on all levels, so that the next parameter is clearly
1174 // visible. Line comments already introduce a break.
1175 if (Current.isNot(TT_LineComment)) {
1176 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1177 State.Stack[i].BreakBeforeParameter = true;
1180 Penalty += Current.isStringLiteral() ? Style.PenaltyBreakString
1181 : Style.PenaltyBreakComment;
1183 State.Stack.back().LastSpace = StartColumn;
1188 unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
1189 // In preprocessor directives reserve two chars for trailing " \"
1190 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
1193 bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
1194 const FormatToken &Current = *State.NextToken;
1195 if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral))
1197 // We never consider raw string literals "multiline" for the purpose of
1198 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
1199 // (see TokenAnnotator::mustBreakBefore().
1200 if (Current.TokenText.startswith("R\""))
1202 if (Current.IsMultiline)
1204 if (Current.getNextNonComment() &&
1205 Current.getNextNonComment()->isStringLiteral())
1206 return true; // Implicit concatenation.
1207 if (Style.ColumnLimit != 0 &&
1208 State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
1210 return true; // String will be split.
1214 } // namespace format
1215 } // namespace clang