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 // Returns \c true if \c Tok is the "." or "->" of a call and starts the next
42 // segment of a builder type call.
43 static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) {
44 return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope();
47 // Returns \c true if \c Current starts a new parameter.
48 static bool startsNextParameter(const FormatToken &Current,
49 const FormatStyle &Style) {
50 const FormatToken &Previous = *Current.Previous;
51 if (Current.is(TT_CtorInitializerComma) &&
52 Style.BreakConstructorInitializersBeforeComma)
54 return Previous.is(tok::comma) && !Current.isTrailingComment() &&
55 (Previous.isNot(TT_CtorInitializerComma) ||
56 !Style.BreakConstructorInitializersBeforeComma);
59 ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,
60 const AdditionalKeywords &Keywords,
61 SourceManager &SourceMgr,
62 WhitespaceManager &Whitespaces,
63 encoding::Encoding Encoding,
64 bool BinPackInconclusiveFunctions)
65 : Style(Style), Keywords(Keywords), SourceMgr(SourceMgr),
66 Whitespaces(Whitespaces), Encoding(Encoding),
67 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
68 CommentPragmasRegex(Style.CommentPragmas) {}
70 LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
71 const AnnotatedLine *Line,
74 State.FirstIndent = FirstIndent;
75 State.Column = FirstIndent;
77 State.NextToken = Line->First;
78 State.Stack.push_back(ParenState(FirstIndent, Line->Level, FirstIndent,
79 /*AvoidBinPacking=*/false,
80 /*NoLineBreak=*/false));
81 State.LineContainsContinuedForLoopSection = false;
82 State.StartOfStringLiteral = 0;
83 State.StartOfLineLevel = 0;
84 State.LowestLevelOnLine = 0;
85 State.IgnoreStackForComparison = false;
87 // The first token has already been indented and thus consumed.
88 moveStateToNextToken(State, DryRun, /*Newline=*/false);
92 bool ContinuationIndenter::canBreak(const LineState &State) {
93 const FormatToken &Current = *State.NextToken;
94 const FormatToken &Previous = *Current.Previous;
95 assert(&Previous == Current.Previous);
96 if (!Current.CanBreakBefore &&
97 !(State.Stack.back().BreakBeforeClosingBrace &&
98 Current.closesBlockTypeList(Style)))
100 // The opening "{" of a braced list has to be on the same line as the first
101 // element if it is nested in another braced init list or function call.
102 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
103 Previous.isNot(TT_DictLiteral) && Previous.BlockKind == BK_BracedInit &&
105 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
107 // This prevents breaks like:
109 // SomeParameter, OtherParameter).DoSomething(
111 // As they hide "DoSomething" and are generally bad for readability.
112 if (Previous.opensScope() && Previous.isNot(tok::l_brace) &&
113 State.LowestLevelOnLine < State.StartOfLineLevel &&
114 State.LowestLevelOnLine < Current.NestingLevel)
116 if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
119 // Don't create a 'hanging' indent if there are multiple blocks in a single
121 if (Previous.is(tok::l_brace) && State.Stack.size() > 1 &&
122 State.Stack[State.Stack.size() - 2].NestedBlockInlined &&
123 State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks)
126 // Don't break after very short return types (e.g. "void") as that is often
128 if (Current.is(TT_FunctionDeclarationName) &&
129 !Style.AlwaysBreakAfterDefinitionReturnType && State.Column < 6)
132 return !State.Stack.back().NoLineBreak;
135 bool ContinuationIndenter::mustBreak(const LineState &State) {
136 const FormatToken &Current = *State.NextToken;
137 const FormatToken &Previous = *Current.Previous;
138 if (Current.MustBreakBefore || Current.is(TT_InlineASMColon))
140 if (State.Stack.back().BreakBeforeClosingBrace &&
141 Current.closesBlockTypeList(Style))
143 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
145 if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
146 (Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&
147 Previous.isNot(tok::question)) ||
148 (!Style.BreakBeforeTernaryOperators &&
149 Previous.is(TT_ConditionalExpr))) &&
150 State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
151 !Current.isOneOf(tok::r_paren, tok::r_brace))
153 if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) ||
154 Previous.is(TT_ArrayInitializerLSquare)) &&
155 Style.ColumnLimit > 0 &&
156 getLengthToMatchingParen(Previous) + State.Column - 1 >
157 getColumnLimit(State))
159 if (Current.is(TT_CtorInitializerColon) &&
160 ((Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All) ||
161 Style.BreakConstructorInitializersBeforeComma || Style.ColumnLimit != 0))
163 if (Current.is(TT_SelectorName) && State.Stack.back().ObjCSelectorNameFound &&
164 State.Stack.back().BreakBeforeParameter)
167 unsigned NewLineColumn = getNewLineColumn(State);
168 if (State.Column < NewLineColumn)
171 if (Style.AlwaysBreakBeforeMultilineStrings &&
172 (NewLineColumn == State.FirstIndent + Style.ContinuationIndentWidth ||
173 Previous.is(tok::comma) || Current.NestingLevel < 2) &&
174 !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) &&
175 !Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) &&
176 nextIsMultilineString(State))
179 // Using CanBreakBefore here and below takes care of the decision whether the
180 // current style uses wrapping before or after operators for the given
182 if (Previous.is(TT_BinaryOperator) && Current.CanBreakBefore) {
183 // If we need to break somewhere inside the LHS of a binary expression, we
184 // should also break after the operator. Otherwise, the formatting would
185 // hide the operator precedence, e.g. in:
186 // if (aaaaaaaaaaaaaa ==
187 // bbbbbbbbbbbbbb && c) {..
188 // For comparisons, we only apply this rule, if the LHS is a binary
189 // expression itself as otherwise, the line breaks seem superfluous.
190 // We need special cases for ">>" which we have split into two ">" while
191 // lexing in order to make template parsing easier.
192 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
193 Previous.getPrecedence() == prec::Equality) &&
195 Previous.Previous->isNot(TT_BinaryOperator); // For >>.
196 bool LHSIsBinaryExpr =
197 Previous.Previous && Previous.Previous->EndsBinaryExpression;
198 if ((!IsComparison || LHSIsBinaryExpr) && !Current.isTrailingComment() &&
199 Previous.getPrecedence() != prec::Assignment &&
200 State.Stack.back().BreakBeforeParameter)
202 } else if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore &&
203 State.Stack.back().BreakBeforeParameter) {
207 // Same as above, but for the first "<<" operator.
208 if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator) &&
209 State.Stack.back().BreakBeforeParameter &&
210 State.Stack.back().FirstLessLess == 0)
213 if (Current.NestingLevel == 0 && !Current.isTrailingComment()) {
214 // Always break after "template <...>" and leading annotations. This is only
215 // for cases where the entire line does not fit on a single line as a
216 // different LineFormatter would be used otherwise.
217 if (Previous.ClosesTemplateDeclaration)
219 if (Previous.is(TT_FunctionAnnotationRParen))
221 if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) &&
222 Current.isNot(TT_LeadingJavaAnnotation))
226 // If the return type spans multiple lines, wrap before the function name.
227 if (Current.isOneOf(TT_FunctionDeclarationName, tok::kw_operator) &&
228 State.Stack.back().BreakBeforeParameter)
231 if (startsSegmentOfBuilderTypeCall(Current) &&
232 (State.Stack.back().CallContinuation != 0 ||
233 State.Stack.back().BreakBeforeParameter))
236 // The following could be precomputed as they do not depend on the state.
237 // However, as they should take effect only if the UnwrappedLine does not fit
238 // into the ColumnLimit, they are checked here in the ContinuationIndenter.
239 if (Style.ColumnLimit != 0 && Previous.BlockKind == BK_Block &&
240 Previous.is(tok::l_brace) && !Current.isOneOf(tok::r_brace, tok::comment))
243 if (Current.is(tok::lessless) && Previous.is(tok::identifier) &&
244 Previous.TokenText == "endl")
250 unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
252 unsigned ExtraSpaces) {
253 const FormatToken &Current = *State.NextToken;
255 assert(!State.Stack.empty());
256 if ((Current.is(TT_ImplicitStringLiteral) &&
257 (Current.Previous->Tok.getIdentifierInfo() == nullptr ||
258 Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
259 tok::pp_not_keyword))) {
261 SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getEnd());
262 if (Current.LastNewlineOffset != 0) {
263 // If there is a newline within this token, the final column will solely
264 // determined by the current end column.
265 State.Column = EndColumn;
267 unsigned StartColumn =
268 SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getBegin());
269 assert(EndColumn >= StartColumn);
270 State.Column += EndColumn - StartColumn;
272 moveStateToNextToken(State, DryRun, /*Newline=*/false);
276 unsigned Penalty = 0;
278 Penalty = addTokenOnNewLine(State, DryRun);
280 addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
282 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
285 void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
286 unsigned ExtraSpaces) {
287 FormatToken &Current = *State.NextToken;
288 const FormatToken &Previous = *State.NextToken->Previous;
289 if (Current.is(tok::equal) &&
290 (State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) &&
291 State.Stack.back().VariablePos == 0) {
292 State.Stack.back().VariablePos = State.Column;
293 // Move over * and & if they are bound to the variable name.
294 const FormatToken *Tok = &Previous;
295 while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
296 State.Stack.back().VariablePos -= Tok->ColumnWidth;
297 if (Tok->SpacesRequiredBefore != 0)
301 if (Previous.PartOfMultiVariableDeclStmt)
302 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
305 unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
308 Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, /*IndentLevel=*/0,
309 Spaces, State.Column + Spaces);
311 if (Current.is(TT_SelectorName) &&
312 !State.Stack.back().ObjCSelectorNameFound) {
313 if (Current.LongestObjCSelectorName == 0)
314 State.Stack.back().AlignColons = false;
315 else if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
316 State.Column + Spaces + Current.ColumnWidth)
317 State.Stack.back().ColonPos =
318 std::max(State.FirstIndent + Style.ContinuationIndentWidth,
319 State.Stack.back().Indent) +
320 Current.LongestObjCSelectorName;
322 State.Stack.back().ColonPos = State.Column + Spaces + Current.ColumnWidth;
325 if (Style.AlignAfterOpenBracket && Previous.opensScope() &&
326 Previous.isNot(TT_ObjCMethodExpr) &&
327 (Current.isNot(TT_LineComment) || Previous.BlockKind == BK_BracedInit))
328 State.Stack.back().Indent = State.Column + Spaces;
329 if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
330 State.Stack.back().NoLineBreak = true;
331 if (startsSegmentOfBuilderTypeCall(Current) &&
332 State.Column > getNewLineColumn(State))
333 State.Stack.back().ContainsUnwrappedBuilder = true;
335 if (Current.is(TT_LambdaArrow) && Style.Language == FormatStyle::LK_Java)
336 State.Stack.back().NoLineBreak = true;
337 if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&
338 (Previous.MatchingParen &&
339 (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10))) {
340 // If there is a function call with long parameters, break before trailing
341 // calls. This prevents things like:
342 // EXPECT_CALL(SomeLongParameter).Times(
344 // We don't want to do this for short parameters as they can just be
346 State.Stack.back().NoLineBreak = true;
349 State.Column += Spaces;
350 if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&
352 Previous.Previous->isOneOf(tok::kw_if, tok::kw_for)) {
353 // Treat the condition inside an if as if it was a second function
354 // parameter, i.e. let nested calls have a continuation indent.
355 State.Stack.back().LastSpace = State.Column;
356 State.Stack.back().NestedBlockIndent = State.Column;
357 } else if (!Current.isOneOf(tok::comment, tok::caret) &&
358 (Previous.is(tok::comma) ||
359 (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) {
360 State.Stack.back().LastSpace = State.Column;
361 } else if ((Previous.isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
362 TT_CtorInitializerColon)) &&
363 ((Previous.getPrecedence() != prec::Assignment &&
364 (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||
365 !Previous.LastOperator)) ||
366 Current.StartsBinaryExpression)) {
367 // Always indent relative to the RHS of the expression unless this is a
368 // simple assignment without binary expression on the RHS. Also indent
369 // relative to unary operators and the colons of constructor initializers.
370 State.Stack.back().LastSpace = State.Column;
371 } else if (Previous.is(TT_InheritanceColon)) {
372 State.Stack.back().Indent = State.Column;
373 State.Stack.back().LastSpace = State.Column;
374 } else if (Previous.opensScope()) {
375 // If a function has a trailing call, indent all parameters from the
376 // opening parenthesis. This avoids confusing indents like:
377 // OuterFunction(InnerFunctionCall( // break
378 // ParameterToInnerFunction)) // break
379 // .SecondInnerFunctionCall();
380 bool HasTrailingCall = false;
381 if (Previous.MatchingParen) {
382 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
383 HasTrailingCall = Next && Next->isMemberAccess();
385 if (HasTrailingCall && State.Stack.size() > 1 &&
386 State.Stack[State.Stack.size() - 2].CallContinuation == 0)
387 State.Stack.back().LastSpace = State.Column;
391 unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
393 FormatToken &Current = *State.NextToken;
394 const FormatToken &Previous = *State.NextToken->Previous;
396 // Extra penalty that needs to be added because of the way certain line
397 // breaks are chosen.
398 unsigned Penalty = 0;
400 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
401 const FormatToken *NextNonComment = Previous.getNextNonComment();
403 NextNonComment = &Current;
404 // The first line break on any NestingLevel causes an extra penalty in order
405 // prefer similar line breaks.
406 if (!State.Stack.back().ContainsLineBreak)
408 State.Stack.back().ContainsLineBreak = true;
410 Penalty += State.NextToken->SplitPenalty;
412 // Breaking before the first "<<" is generally not desirable if the LHS is
413 // short. Also always add the penalty if the LHS is split over mutliple lines
414 // to avoid unnecessary line breaks that just work around this penalty.
415 if (NextNonComment->is(tok::lessless) &&
416 State.Stack.back().FirstLessLess == 0 &&
417 (State.Column <= Style.ColumnLimit / 3 ||
418 State.Stack.back().BreakBeforeParameter))
419 Penalty += Style.PenaltyBreakFirstLessLess;
421 State.Column = getNewLineColumn(State);
423 // Indent nested blocks relative to this column, unless in a very specific
424 // JavaScript special case where:
426 // var loooooong_name =
431 // is common and should be formatted like a free-standing function.
432 if (Style.Language != FormatStyle::LK_JavaScript ||
433 Current.NestingLevel != 0 || !PreviousNonComment->is(tok::equal) ||
434 !Current.is(Keywords.kw_function))
435 State.Stack.back().NestedBlockIndent = State.Column;
437 if (NextNonComment->isMemberAccess()) {
438 if (State.Stack.back().CallContinuation == 0)
439 State.Stack.back().CallContinuation = State.Column;
440 } else if (NextNonComment->is(TT_SelectorName)) {
441 if (!State.Stack.back().ObjCSelectorNameFound) {
442 if (NextNonComment->LongestObjCSelectorName == 0) {
443 State.Stack.back().AlignColons = false;
445 State.Stack.back().ColonPos =
446 (Style.IndentWrappedFunctionNames
447 ? std::max(State.Stack.back().Indent,
448 State.FirstIndent + Style.ContinuationIndentWidth)
449 : State.Stack.back().Indent) +
450 NextNonComment->LongestObjCSelectorName;
452 } else if (State.Stack.back().AlignColons &&
453 State.Stack.back().ColonPos <= NextNonComment->ColumnWidth) {
454 State.Stack.back().ColonPos = State.Column + NextNonComment->ColumnWidth;
456 } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
457 PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
458 // FIXME: This is hacky, find a better way. The problem is that in an ObjC
459 // method expression, the block should be aligned to the line starting it,
461 // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
465 // Thus, we set LastSpace of the next higher NestingLevel, to which we move
466 // when we consume all of the "}"'s FakeRParens at the "{".
467 if (State.Stack.size() > 1)
468 State.Stack[State.Stack.size() - 2].LastSpace =
469 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
470 Style.ContinuationIndentWidth;
473 if ((Previous.isOneOf(tok::comma, tok::semi) &&
474 !State.Stack.back().AvoidBinPacking) ||
475 Previous.is(TT_BinaryOperator))
476 State.Stack.back().BreakBeforeParameter = false;
477 if (Previous.isOneOf(TT_TemplateCloser, TT_JavaAnnotation) &&
478 Current.NestingLevel == 0)
479 State.Stack.back().BreakBeforeParameter = false;
480 if (NextNonComment->is(tok::question) ||
481 (PreviousNonComment && PreviousNonComment->is(tok::question)))
482 State.Stack.back().BreakBeforeParameter = true;
483 if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore)
484 State.Stack.back().BreakBeforeParameter = false;
487 unsigned Newlines = std::max(
488 1u, std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1));
489 Whitespaces.replaceWhitespace(Current, Newlines,
490 State.Stack.back().IndentLevel, State.Column,
491 State.Column, State.Line->InPPDirective);
494 if (!Current.isTrailingComment())
495 State.Stack.back().LastSpace = State.Column;
496 State.StartOfLineLevel = Current.NestingLevel;
497 State.LowestLevelOnLine = Current.NestingLevel;
499 // Any break on this level means that the parent level has been broken
500 // and we need to avoid bin packing there.
501 bool NestedBlockSpecialCase =
502 Current.is(tok::r_brace) && State.Stack.size() > 1 &&
503 State.Stack[State.Stack.size() - 2].NestedBlockInlined;
504 if (!NestedBlockSpecialCase)
505 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
506 State.Stack[i].BreakBeforeParameter = true;
508 if (PreviousNonComment &&
509 !PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
510 (PreviousNonComment->isNot(TT_TemplateCloser) ||
511 Current.NestingLevel != 0) &&
512 !PreviousNonComment->isOneOf(
513 TT_BinaryOperator, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
514 TT_LeadingJavaAnnotation) &&
515 Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope())
516 State.Stack.back().BreakBeforeParameter = true;
518 // If we break after { or the [ of an array initializer, we should also break
519 // before the corresponding } or ].
520 if (PreviousNonComment &&
521 (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)))
522 State.Stack.back().BreakBeforeClosingBrace = true;
524 if (State.Stack.back().AvoidBinPacking) {
525 // If we are breaking after '(', '{', '<', this is not bin packing
526 // unless AllowAllParametersOfDeclarationOnNextLine is false or this is a
527 // dict/object literal.
528 if (!Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) ||
529 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
530 State.Line->MustBeDeclaration) ||
531 Previous.is(TT_DictLiteral))
532 State.Stack.back().BreakBeforeParameter = true;
538 unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
539 if (!State.NextToken || !State.NextToken->Previous)
541 FormatToken &Current = *State.NextToken;
542 const FormatToken &Previous = *Current.Previous;
543 // If we are continuing an expression, we want to use the continuation indent.
544 unsigned ContinuationIndent =
545 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
546 Style.ContinuationIndentWidth;
547 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
548 const FormatToken *NextNonComment = Previous.getNextNonComment();
550 NextNonComment = &Current;
552 // Java specific bits.
553 if (Style.Language == FormatStyle::LK_Java &&
554 Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends))
555 return std::max(State.Stack.back().LastSpace,
556 State.Stack.back().Indent + Style.ContinuationIndentWidth);
558 if (NextNonComment->is(tok::l_brace) && NextNonComment->BlockKind == BK_Block)
559 return Current.NestingLevel == 0 ? State.FirstIndent
560 : State.Stack.back().Indent;
561 if (Current.isOneOf(tok::r_brace, tok::r_square) && State.Stack.size() > 1) {
562 if (Current.closesBlockTypeList(Style))
563 return State.Stack[State.Stack.size() - 2].NestedBlockIndent;
564 if (Current.MatchingParen &&
565 Current.MatchingParen->BlockKind == BK_BracedInit)
566 return State.Stack[State.Stack.size() - 2].LastSpace;
567 return State.FirstIndent;
569 if (Current.is(tok::identifier) && Current.Next &&
570 Current.Next->is(TT_DictLiteral))
571 return State.Stack.back().Indent;
572 if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
573 return State.StartOfStringLiteral;
574 if (NextNonComment->is(TT_ObjCStringLiteral) &&
575 State.StartOfStringLiteral != 0)
576 return State.StartOfStringLiteral - 1;
577 if (NextNonComment->is(tok::lessless) &&
578 State.Stack.back().FirstLessLess != 0)
579 return State.Stack.back().FirstLessLess;
580 if (NextNonComment->isMemberAccess()) {
581 if (State.Stack.back().CallContinuation == 0)
582 return ContinuationIndent;
583 return State.Stack.back().CallContinuation;
585 if (State.Stack.back().QuestionColumn != 0 &&
586 ((NextNonComment->is(tok::colon) &&
587 NextNonComment->is(TT_ConditionalExpr)) ||
588 Previous.is(TT_ConditionalExpr)))
589 return State.Stack.back().QuestionColumn;
590 if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0)
591 return State.Stack.back().VariablePos;
592 if ((PreviousNonComment &&
593 (PreviousNonComment->ClosesTemplateDeclaration ||
594 PreviousNonComment->isOneOf(
595 TT_AttributeParen, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
596 TT_LeadingJavaAnnotation))) ||
597 (!Style.IndentWrappedFunctionNames &&
598 NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName)))
599 return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
600 if (NextNonComment->is(TT_SelectorName)) {
601 if (!State.Stack.back().ObjCSelectorNameFound) {
602 if (NextNonComment->LongestObjCSelectorName == 0)
603 return State.Stack.back().Indent;
604 return (Style.IndentWrappedFunctionNames
605 ? std::max(State.Stack.back().Indent,
606 State.FirstIndent + Style.ContinuationIndentWidth)
607 : State.Stack.back().Indent) +
608 NextNonComment->LongestObjCSelectorName -
609 NextNonComment->ColumnWidth;
611 if (!State.Stack.back().AlignColons)
612 return State.Stack.back().Indent;
613 if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth)
614 return State.Stack.back().ColonPos - NextNonComment->ColumnWidth;
615 return State.Stack.back().Indent;
617 if (NextNonComment->is(TT_ArraySubscriptLSquare)) {
618 if (State.Stack.back().StartOfArraySubscripts != 0)
619 return State.Stack.back().StartOfArraySubscripts;
620 return ContinuationIndent;
623 // This ensure that we correctly format ObjC methods calls without inputs,
624 // i.e. where the last element isn't selector like: [callee method];
625 if (NextNonComment->is(tok::identifier) && NextNonComment->FakeRParens == 0 &&
626 NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr))
627 return State.Stack.back().Indent;
629 if (NextNonComment->isOneOf(TT_StartOfName, TT_PointerOrReference) ||
630 Previous.isOneOf(tok::coloncolon, tok::equal))
631 return ContinuationIndent;
632 if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
633 PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))
634 return ContinuationIndent;
635 if (NextNonComment->is(TT_CtorInitializerColon))
636 return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
637 if (NextNonComment->is(TT_CtorInitializerComma))
638 return State.Stack.back().Indent;
639 if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() &&
640 !Current.isOneOf(tok::colon, tok::comment))
641 return ContinuationIndent;
642 if (State.Stack.back().Indent == State.FirstIndent && PreviousNonComment &&
643 PreviousNonComment->isNot(tok::r_brace))
644 // Ensure that we fall back to the continuation indent width instead of
645 // just flushing continuations left.
646 return State.Stack.back().Indent + Style.ContinuationIndentWidth;
647 return State.Stack.back().Indent;
650 unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
651 bool DryRun, bool Newline) {
652 assert(State.Stack.size());
653 const FormatToken &Current = *State.NextToken;
655 if (Current.is(TT_InheritanceColon))
656 State.Stack.back().AvoidBinPacking = true;
657 if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) {
658 if (State.Stack.back().FirstLessLess == 0)
659 State.Stack.back().FirstLessLess = State.Column;
661 State.Stack.back().LastOperatorWrapped = Newline;
663 if ((Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless)) ||
664 Current.is(TT_ConditionalExpr))
665 State.Stack.back().LastOperatorWrapped = Newline;
666 if (Current.is(TT_ArraySubscriptLSquare) &&
667 State.Stack.back().StartOfArraySubscripts == 0)
668 State.Stack.back().StartOfArraySubscripts = State.Column;
669 if ((Current.is(tok::question) && Style.BreakBeforeTernaryOperators) ||
670 (Current.getPreviousNonComment() && Current.isNot(tok::colon) &&
671 Current.getPreviousNonComment()->is(tok::question) &&
672 !Style.BreakBeforeTernaryOperators))
673 State.Stack.back().QuestionColumn = State.Column;
674 if (!Current.opensScope() && !Current.closesScope())
675 State.LowestLevelOnLine =
676 std::min(State.LowestLevelOnLine, Current.NestingLevel);
677 if (Current.isMemberAccess())
678 State.Stack.back().StartOfFunctionCall =
679 Current.LastOperator ? 0 : State.Column;
680 if (Current.is(TT_SelectorName))
681 State.Stack.back().ObjCSelectorNameFound = true;
682 if (Current.is(TT_CtorInitializerColon)) {
683 // Indent 2 from the column, so:
684 // SomeClass::SomeClass()
688 State.Stack.back().Indent =
689 State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
690 State.Stack.back().NestedBlockIndent = State.Stack.back().Indent;
691 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
692 State.Stack.back().AvoidBinPacking = true;
693 State.Stack.back().BreakBeforeParameter = false;
695 if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline)
696 State.Stack.back().NestedBlockIndent =
697 State.Column + Current.ColumnWidth + 1;
699 // Insert scopes created by fake parenthesis.
700 const FormatToken *Previous = Current.getPreviousNonComment();
702 // Add special behavior to support a format commonly used for JavaScript
704 // SomeFunction(function() {
708 if (Current.isNot(tok::comment) && Previous &&
709 Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
710 State.Stack.size() > 1) {
711 if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline)
712 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
713 State.Stack[i].NoLineBreak = true;
714 State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;
716 if (Previous && (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) ||
717 Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr)) &&
718 !Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
719 State.Stack.back().NestedBlockInlined =
721 (Previous->isNot(tok::l_paren) || Previous->ParameterCount > 1);
724 moveStatePastFakeLParens(State, Newline);
725 moveStatePastScopeOpener(State, Newline);
726 moveStatePastScopeCloser(State);
727 moveStatePastFakeRParens(State);
729 if (Current.isStringLiteral() && State.StartOfStringLiteral == 0)
730 State.StartOfStringLiteral = State.Column;
731 if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0)
732 State.StartOfStringLiteral = State.Column + 1;
733 else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
734 !Current.isStringLiteral())
735 State.StartOfStringLiteral = 0;
737 State.Column += Current.ColumnWidth;
738 State.NextToken = State.NextToken->Next;
739 unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
740 if (State.Column > getColumnLimit(State)) {
741 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
742 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
746 Current.Role->formatFromToken(State, this, DryRun);
747 // If the previous has a special role, let it consume tokens as appropriate.
748 // It is necessary to start at the previous token for the only implemented
749 // role (comma separated list). That way, the decision whether or not to break
750 // after the "{" is already done and both options are tried and evaluated.
751 // FIXME: This is ugly, find a better way.
752 if (Previous && Previous->Role)
753 Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
758 void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
760 const FormatToken &Current = *State.NextToken;
761 const FormatToken *Previous = Current.getPreviousNonComment();
763 // Don't add extra indentation for the first fake parenthesis after
764 // 'return', assignments or opening <({[. The indentation for these cases
766 bool SkipFirstExtraIndent =
767 (Previous && (Previous->opensScope() ||
768 Previous->isOneOf(tok::semi, tok::kw_return) ||
769 (Previous->getPrecedence() == prec::Assignment &&
770 Style.AlignOperands) ||
771 Previous->is(TT_ObjCMethodExpr)));
772 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
773 I = Current.FakeLParens.rbegin(),
774 E = Current.FakeLParens.rend();
776 ParenState NewParenState = State.Stack.back();
777 NewParenState.ContainsLineBreak = false;
779 // Indent from 'LastSpace' unless these are fake parentheses encapsulating
780 // a builder type call after 'return' or, if the alignment after opening
781 // brackets is disabled.
782 if (!Current.isTrailingComment() &&
783 (Style.AlignOperands || *I < prec::Assignment) &&
784 (!Previous || Previous->isNot(tok::kw_return) ||
785 (Style.Language != FormatStyle::LK_Java && *I > 0)) &&
786 (Style.AlignAfterOpenBracket || *I != prec::Comma ||
787 Current.NestingLevel == 0))
788 NewParenState.Indent =
789 std::max(std::max(State.Column, NewParenState.Indent),
790 State.Stack.back().LastSpace);
792 // Don't allow the RHS of an operator to be split over multiple lines unless
793 // there is a line-break right after the operator.
794 // Exclude relational operators, as there, it is always more desirable to
795 // have the LHS 'left' of the RHS.
796 if (Previous && Previous->getPrecedence() > prec::Assignment &&
797 Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
798 Previous->getPrecedence() != prec::Relational) {
799 bool BreakBeforeOperator =
800 Previous->is(tok::lessless) ||
801 (Previous->is(TT_BinaryOperator) &&
802 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) ||
803 (Previous->is(TT_ConditionalExpr) &&
804 Style.BreakBeforeTernaryOperators);
805 if ((!Newline && !BreakBeforeOperator) ||
806 (!State.Stack.back().LastOperatorWrapped && BreakBeforeOperator))
807 NewParenState.NoLineBreak = true;
810 // Do not indent relative to the fake parentheses inserted for "." or "->".
811 // This is a special case to make the following to statements consistent:
812 // OuterFunction(InnerFunctionCall( // break
813 // ParameterToInnerFunction));
814 // OuterFunction(SomeObject.InnerFunctionCall( // break
815 // ParameterToInnerFunction));
816 if (*I > prec::Unknown)
817 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
818 if (*I != prec::Conditional)
819 NewParenState.StartOfFunctionCall = State.Column;
821 // Always indent conditional expressions. Never indent expression where
822 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
823 // prec::Assignment) as those have different indentation rules. Indent
824 // other expression, unless the indentation needs to be skipped.
825 if (*I == prec::Conditional ||
826 (!SkipFirstExtraIndent && *I > prec::Assignment &&
827 !Current.isTrailingComment()))
828 NewParenState.Indent += Style.ContinuationIndentWidth;
829 if ((Previous && !Previous->opensScope()) || *I > prec::Comma)
830 NewParenState.BreakBeforeParameter = false;
831 State.Stack.push_back(NewParenState);
832 SkipFirstExtraIndent = false;
836 void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
837 for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) {
838 unsigned VariablePos = State.Stack.back().VariablePos;
839 if (State.Stack.size() == 1) {
840 // Do not pop the last element.
843 State.Stack.pop_back();
844 State.Stack.back().VariablePos = VariablePos;
848 void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
850 const FormatToken &Current = *State.NextToken;
851 if (!Current.opensScope())
854 if (Current.MatchingParen && Current.BlockKind == BK_Block) {
855 moveStateToNewBlock(State);
860 unsigned NewIndentLevel = State.Stack.back().IndentLevel;
861 unsigned LastSpace = State.Stack.back().LastSpace;
862 bool AvoidBinPacking;
863 bool BreakBeforeParameter = false;
864 if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)) {
865 if (Current.opensBlockTypeList(Style)) {
866 NewIndent = State.Stack.back().NestedBlockIndent + Style.IndentWidth;
867 NewIndent = std::min(State.Column + 2, NewIndent);
870 NewIndent = State.Stack.back().LastSpace + Style.ContinuationIndentWidth;
872 const FormatToken *NextNoComment = Current.getNextNonComment();
874 Current.isOneOf(TT_ArrayInitializerLSquare, TT_DictLiteral) ||
875 Style.Language == FormatStyle::LK_Proto || !Style.BinPackArguments ||
876 (NextNoComment && NextNoComment->is(TT_DesignatedInitializerPeriod));
878 NewIndent = Style.ContinuationIndentWidth +
879 std::max(State.Stack.back().LastSpace,
880 State.Stack.back().StartOfFunctionCall);
882 // Ensure that different different brackets force relative alignment, e.g.:
883 // void SomeFunction(vector< // break
885 // FIXME: We likely want to do this for more combinations of brackets.
886 // Verify that it is wanted for ObjC, too.
887 if (Current.Tok.getKind() == tok::less &&
888 Current.ParentBracket == tok::l_paren) {
889 NewIndent = std::max(NewIndent, State.Stack.back().Indent);
890 LastSpace = std::max(LastSpace, State.Stack.back().Indent);
894 (State.Line->MustBeDeclaration && !Style.BinPackParameters) ||
895 (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||
896 (Style.ExperimentalAutoDetectBinPacking &&
897 (Current.PackingKind == PPK_OnePerLine ||
898 (!BinPackInconclusiveFunctions &&
899 Current.PackingKind == PPK_Inconclusive)));
900 if (Current.is(TT_ObjCMethodExpr) && Current.MatchingParen) {
901 if (Style.ColumnLimit) {
902 // If this '[' opens an ObjC call, determine whether all parameters fit
903 // into one line and put one per line if they don't.
904 if (getLengthToMatchingParen(Current) + State.Column >
905 getColumnLimit(State))
906 BreakBeforeParameter = true;
908 // For ColumnLimit = 0, we have to figure out whether there is or has to
909 // be a line break within this call.
910 for (const FormatToken *Tok = &Current;
911 Tok && Tok != Current.MatchingParen; Tok = Tok->Next) {
912 if (Tok->MustBreakBefore ||
913 (Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) {
914 BreakBeforeParameter = true;
921 bool NoLineBreak = State.Stack.back().NoLineBreak ||
922 (Current.is(TT_TemplateOpener) &&
923 State.Stack.back().ContainsUnwrappedBuilder);
924 unsigned NestedBlockIndent = std::max(State.Stack.back().StartOfFunctionCall,
925 State.Stack.back().NestedBlockIndent);
926 State.Stack.push_back(ParenState(NewIndent, NewIndentLevel, LastSpace,
927 AvoidBinPacking, NoLineBreak));
928 State.Stack.back().NestedBlockIndent = NestedBlockIndent;
929 State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
930 State.Stack.back().HasMultipleNestedBlocks = Current.BlockParameterCount > 1;
933 void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
934 const FormatToken &Current = *State.NextToken;
935 if (!Current.closesScope())
938 // If we encounter a closing ), ], } or >, we can remove a level from our
940 if (State.Stack.size() > 1 &&
941 (Current.isOneOf(tok::r_paren, tok::r_square) ||
942 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
943 State.NextToken->is(TT_TemplateCloser)))
944 State.Stack.pop_back();
946 if (Current.is(tok::r_square)) {
947 // If this ends the array subscript expr, reset the corresponding value.
948 const FormatToken *NextNonComment = Current.getNextNonComment();
949 if (NextNonComment && NextNonComment->isNot(tok::l_square))
950 State.Stack.back().StartOfArraySubscripts = 0;
954 void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
955 unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
956 // ObjC block sometimes follow special indentation rules.
958 NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace)
959 ? Style.ObjCBlockIndentWidth
960 : Style.IndentWidth);
961 State.Stack.push_back(ParenState(
962 NewIndent, /*NewIndentLevel=*/State.Stack.back().IndentLevel + 1,
963 State.Stack.back().LastSpace, /*AvoidBinPacking=*/true,
964 State.Stack.back().NoLineBreak));
965 State.Stack.back().NestedBlockIndent = NestedBlockIndent;
966 State.Stack.back().BreakBeforeParameter = true;
969 unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
971 // Break before further function parameters on all levels.
972 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
973 State.Stack[i].BreakBeforeParameter = true;
975 unsigned ColumnsUsed = State.Column;
976 // We can only affect layout of the first and the last line, so the penalty
977 // for all other lines is constant, and we ignore it.
978 State.Column = Current.LastLineColumnWidth;
980 if (ColumnsUsed > getColumnLimit(State))
981 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
985 unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
988 // Don't break multi-line tokens other than block comments. Instead, just
990 if (Current.isNot(TT_BlockComment) && Current.IsMultiline)
991 return addMultilineToken(Current, State);
993 // Don't break implicit string literals or import statements.
994 if (Current.is(TT_ImplicitStringLiteral) ||
995 State.Line->Type == LT_ImportStatement)
998 if (!Current.isStringLiteral() && !Current.is(tok::comment))
1001 std::unique_ptr<BreakableToken> Token;
1002 unsigned StartColumn = State.Column - Current.ColumnWidth;
1003 unsigned ColumnLimit = getColumnLimit(State);
1005 if (Current.isStringLiteral()) {
1006 // FIXME: String literal breaking is currently disabled for Java and JS, as
1007 // it requires strings to be merged using "+" which we don't support.
1008 if (Style.Language == FormatStyle::LK_Java ||
1009 Style.Language == FormatStyle::LK_JavaScript)
1012 // Don't break string literals inside preprocessor directives (except for
1013 // #define directives, as their contents are stored in separate lines and
1014 // are not affected by this check).
1015 // This way we avoid breaking code with line directives and unknown
1016 // preprocessor directives that contain long string literals.
1017 if (State.Line->Type == LT_PreprocessorDirective)
1019 // Exempts unterminated string literals from line breaking. The user will
1020 // likely want to terminate the string before any line breaking is done.
1021 if (Current.IsUnterminatedLiteral)
1024 StringRef Text = Current.TokenText;
1027 bool IsNSStringLiteral = false;
1028 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
1029 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
1030 // reduce the overhead) for each FormatToken, which is a string, so that we
1031 // don't run multiple checks here on the hot path.
1032 if (Text.startswith("\"") && Current.Previous &&
1033 Current.Previous->is(tok::at)) {
1034 IsNSStringLiteral = true;
1037 if ((Text.endswith(Postfix = "\"") &&
1038 (IsNSStringLiteral || Text.startswith(Prefix = "\"") ||
1039 Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
1040 Text.startswith(Prefix = "u8\"") ||
1041 Text.startswith(Prefix = "L\""))) ||
1042 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) {
1043 Token.reset(new BreakableStringLiteral(
1044 Current, State.Line->Level, StartColumn, Prefix, Postfix,
1045 State.Line->InPPDirective, Encoding, Style));
1049 } else if (Current.is(TT_BlockComment) && Current.isTrailingComment()) {
1050 if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
1052 Token.reset(new BreakableBlockComment(
1053 Current, State.Line->Level, StartColumn, Current.OriginalColumn,
1054 !Current.Previous, State.Line->InPPDirective, Encoding, Style));
1055 } else if (Current.is(TT_LineComment) &&
1056 (Current.Previous == nullptr ||
1057 Current.Previous->isNot(TT_ImplicitStringLiteral))) {
1058 if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
1060 Token.reset(new BreakableLineComment(Current, State.Line->Level,
1061 StartColumn, /*InPPDirective=*/false,
1063 // We don't insert backslashes when breaking line comments.
1064 ColumnLimit = Style.ColumnLimit;
1068 if (Current.UnbreakableTailLength >= ColumnLimit)
1071 unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength;
1072 bool BreakInserted = false;
1073 unsigned Penalty = 0;
1074 unsigned RemainingTokenColumns = 0;
1075 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
1076 LineIndex != EndIndex; ++LineIndex) {
1078 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
1079 unsigned TailOffset = 0;
1080 RemainingTokenColumns =
1081 Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
1082 while (RemainingTokenColumns > RemainingSpace) {
1083 BreakableToken::Split Split =
1084 Token->getSplit(LineIndex, TailOffset, ColumnLimit);
1085 if (Split.first == StringRef::npos) {
1086 // The last line's penalty is handled in addNextStateToQueue().
1087 if (LineIndex < EndIndex - 1)
1088 Penalty += Style.PenaltyExcessCharacter *
1089 (RemainingTokenColumns - RemainingSpace);
1092 assert(Split.first != 0);
1093 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
1094 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
1096 // We can remove extra whitespace instead of breaking the line.
1097 if (RemainingTokenColumns + 1 - Split.second <= RemainingSpace) {
1098 RemainingTokenColumns = 0;
1100 Token->replaceWhitespace(LineIndex, TailOffset, Split, Whitespaces);
1104 // When breaking before a tab character, it may be moved by a few columns,
1105 // but will still be expanded to the next tab stop, so we don't save any
1107 if (NewRemainingTokenColumns == RemainingTokenColumns)
1110 assert(NewRemainingTokenColumns < RemainingTokenColumns);
1112 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
1113 Penalty += Current.SplitPenalty;
1114 unsigned ColumnsUsed =
1115 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
1116 if (ColumnsUsed > ColumnLimit) {
1117 Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit);
1119 TailOffset += Split.first + Split.second;
1120 RemainingTokenColumns = NewRemainingTokenColumns;
1121 BreakInserted = true;
1125 State.Column = RemainingTokenColumns;
1127 if (BreakInserted) {
1128 // If we break the token inside a parameter list, we need to break before
1129 // the next parameter on all levels, so that the next parameter is clearly
1130 // visible. Line comments already introduce a break.
1131 if (Current.isNot(TT_LineComment)) {
1132 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1133 State.Stack[i].BreakBeforeParameter = true;
1136 Penalty += Current.isStringLiteral() ? Style.PenaltyBreakString
1137 : Style.PenaltyBreakComment;
1139 State.Stack.back().LastSpace = StartColumn;
1144 unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
1145 // In preprocessor directives reserve two chars for trailing " \"
1146 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
1149 bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
1150 const FormatToken &Current = *State.NextToken;
1151 if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral))
1153 // We never consider raw string literals "multiline" for the purpose of
1154 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
1155 // (see TokenAnnotator::mustBreakBefore().
1156 if (Current.TokenText.startswith("R\""))
1158 if (Current.IsMultiline)
1160 if (Current.getNextNonComment() &&
1161 Current.getNextNonComment()->isStringLiteral())
1162 return true; // Implicit concatenation.
1163 if (Style.ColumnLimit != 0 &&
1164 State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
1166 return true; // String will be split.
1170 } // namespace format
1171 } // namespace clang