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"
23 #define DEBUG_TYPE "format-indenter"
28 // Returns the length of everything up to the first possible line break after
29 // the ), ], } or > matching \c Tok.
30 static unsigned getLengthToMatchingParen(const FormatToken &Tok) {
31 if (!Tok.MatchingParen)
33 FormatToken *End = Tok.MatchingParen;
34 while (End->Next && !End->Next->CanBreakBefore) {
37 return End->TotalLength - Tok.TotalLength + 1;
40 static unsigned getLengthToNextOperator(const FormatToken &Tok) {
41 if (!Tok.NextOperator)
43 return Tok.NextOperator->TotalLength - Tok.TotalLength;
46 // Returns \c true if \c Tok is the "." or "->" of a call and starts the next
47 // segment of a builder type call.
48 static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) {
49 return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope();
52 // Returns \c true if \c Current starts a new parameter.
53 static bool startsNextParameter(const FormatToken &Current,
54 const FormatStyle &Style) {
55 const FormatToken &Previous = *Current.Previous;
56 if (Current.is(TT_CtorInitializerComma) &&
57 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
59 if (Style.Language == FormatStyle::LK_Proto && Current.is(TT_SelectorName))
61 return Previous.is(tok::comma) && !Current.isTrailingComment() &&
62 ((Previous.isNot(TT_CtorInitializerComma) ||
63 Style.BreakConstructorInitializers !=
64 FormatStyle::BCIS_BeforeComma) &&
65 (Previous.isNot(TT_InheritanceComma) ||
66 !Style.BreakBeforeInheritanceComma));
69 static bool opensProtoMessageField(const FormatToken &LessTok,
70 const FormatStyle &Style) {
71 if (LessTok.isNot(tok::less))
73 return Style.Language == FormatStyle::LK_TextProto ||
74 (Style.Language == FormatStyle::LK_Proto &&
75 (LessTok.NestingLevel > 0 ||
76 (LessTok.Previous && LessTok.Previous->is(tok::equal))));
79 ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,
80 const AdditionalKeywords &Keywords,
81 const SourceManager &SourceMgr,
82 WhitespaceManager &Whitespaces,
83 encoding::Encoding Encoding,
84 bool BinPackInconclusiveFunctions)
85 : Style(Style), Keywords(Keywords), SourceMgr(SourceMgr),
86 Whitespaces(Whitespaces), Encoding(Encoding),
87 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
88 CommentPragmasRegex(Style.CommentPragmas) {}
90 LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
91 const AnnotatedLine *Line,
94 State.FirstIndent = FirstIndent;
95 State.Column = FirstIndent;
97 State.NextToken = Line->First;
98 State.Stack.push_back(ParenState(FirstIndent, FirstIndent,
99 /*AvoidBinPacking=*/false,
100 /*NoLineBreak=*/false));
101 State.LineContainsContinuedForLoopSection = false;
102 State.StartOfStringLiteral = 0;
103 State.StartOfLineLevel = 0;
104 State.LowestLevelOnLine = 0;
105 State.IgnoreStackForComparison = false;
107 if (Style.Language == FormatStyle::LK_TextProto) {
108 // We need this in order to deal with the bin packing of text fields at
110 State.Stack.back().AvoidBinPacking = true;
111 State.Stack.back().BreakBeforeParameter = true;
114 // The first token has already been indented and thus consumed.
115 moveStateToNextToken(State, DryRun, /*Newline=*/false);
119 bool ContinuationIndenter::canBreak(const LineState &State) {
120 const FormatToken &Current = *State.NextToken;
121 const FormatToken &Previous = *Current.Previous;
122 assert(&Previous == Current.Previous);
123 if (!Current.CanBreakBefore &&
124 !(State.Stack.back().BreakBeforeClosingBrace &&
125 Current.closesBlockOrBlockTypeList(Style)))
127 // The opening "{" of a braced list has to be on the same line as the first
128 // element if it is nested in another braced init list or function call.
129 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
130 Previous.isNot(TT_DictLiteral) && Previous.BlockKind == BK_BracedInit &&
132 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
134 // This prevents breaks like:
136 // SomeParameter, OtherParameter).DoSomething(
138 // As they hide "DoSomething" and are generally bad for readability.
139 if (Previous.opensScope() && Previous.isNot(tok::l_brace) &&
140 State.LowestLevelOnLine < State.StartOfLineLevel &&
141 State.LowestLevelOnLine < Current.NestingLevel)
143 if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
146 // Don't create a 'hanging' indent if there are multiple blocks in a single
148 if (Previous.is(tok::l_brace) && State.Stack.size() > 1 &&
149 State.Stack[State.Stack.size() - 2].NestedBlockInlined &&
150 State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks)
153 // Don't break after very short return types (e.g. "void") as that is often
155 if (Current.is(TT_FunctionDeclarationName) && State.Column < 6) {
156 if (Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None)
160 // If binary operators are moved to the next line (including commas for some
161 // styles of constructor initializers), that's always ok.
162 if (!Current.isOneOf(TT_BinaryOperator, tok::comma) &&
163 State.Stack.back().NoLineBreakInOperand)
166 return !State.Stack.back().NoLineBreak;
169 bool ContinuationIndenter::mustBreak(const LineState &State) {
170 const FormatToken &Current = *State.NextToken;
171 const FormatToken &Previous = *Current.Previous;
172 if (Current.MustBreakBefore || Current.is(TT_InlineASMColon))
174 if (State.Stack.back().BreakBeforeClosingBrace &&
175 Current.closesBlockOrBlockTypeList(Style))
177 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
179 if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
180 (Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) &&
182 // FIXME: This is a temporary workaround for the case where clang-format
183 // sets BreakBeforeParameter to avoid bin packing and this creates a
184 // completely unnecessary line break after a template type that isn't
186 (Previous.NestingLevel == 1 || Style.BinPackParameters)) ||
187 (Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&
188 Previous.isNot(tok::question)) ||
189 (!Style.BreakBeforeTernaryOperators &&
190 Previous.is(TT_ConditionalExpr))) &&
191 State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
192 !Current.isOneOf(tok::r_paren, tok::r_brace))
194 if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) ||
195 (Previous.is(TT_ArrayInitializerLSquare) &&
196 Previous.ParameterCount > 1) ||
197 opensProtoMessageField(Previous, Style)) &&
198 Style.ColumnLimit > 0 &&
199 getLengthToMatchingParen(Previous) + State.Column - 1 >
200 getColumnLimit(State))
203 const FormatToken &BreakConstructorInitializersToken =
204 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon
207 if (BreakConstructorInitializersToken.is(TT_CtorInitializerColon) &&
208 (State.Column + State.Line->Last->TotalLength - Previous.TotalLength >
209 getColumnLimit(State) ||
210 State.Stack.back().BreakBeforeParameter) &&
211 (Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All ||
212 Style.BreakConstructorInitializers != FormatStyle::BCIS_BeforeColon ||
213 Style.ColumnLimit != 0))
216 if (Current.is(TT_ObjCMethodExpr) && !Previous.is(TT_SelectorName) &&
217 State.Line->startsWith(TT_ObjCMethodSpecifier))
219 if (Current.is(TT_SelectorName) && State.Stack.back().ObjCSelectorNameFound &&
220 State.Stack.back().BreakBeforeParameter)
223 unsigned NewLineColumn = getNewLineColumn(State);
224 if (Current.isMemberAccess() && Style.ColumnLimit != 0 &&
225 State.Column + getLengthToNextOperator(Current) > Style.ColumnLimit &&
226 (State.Column > NewLineColumn ||
227 Current.NestingLevel < State.StartOfLineLevel))
230 if (startsSegmentOfBuilderTypeCall(Current) &&
231 (State.Stack.back().CallContinuation != 0 ||
232 State.Stack.back().BreakBeforeParameter) &&
233 // JavaScript is treated different here as there is a frequent pattern:
234 // SomeFunction(function() {
237 // FIXME: We should find a more generic solution to this problem.
238 !(State.Column <= NewLineColumn &&
239 Style.Language == FormatStyle::LK_JavaScript))
242 if (State.Column <= NewLineColumn)
245 if (Style.AlwaysBreakBeforeMultilineStrings &&
246 (NewLineColumn == State.FirstIndent + Style.ContinuationIndentWidth ||
247 Previous.is(tok::comma) || Current.NestingLevel < 2) &&
248 !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) &&
249 !Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) &&
250 nextIsMultilineString(State))
253 // Using CanBreakBefore here and below takes care of the decision whether the
254 // current style uses wrapping before or after operators for the given
256 if (Previous.is(TT_BinaryOperator) && Current.CanBreakBefore) {
257 // If we need to break somewhere inside the LHS of a binary expression, we
258 // should also break after the operator. Otherwise, the formatting would
259 // hide the operator precedence, e.g. in:
260 // if (aaaaaaaaaaaaaa ==
261 // bbbbbbbbbbbbbb && c) {..
262 // For comparisons, we only apply this rule, if the LHS is a binary
263 // expression itself as otherwise, the line breaks seem superfluous.
264 // We need special cases for ">>" which we have split into two ">" while
265 // lexing in order to make template parsing easier.
266 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
267 Previous.getPrecedence() == prec::Equality) &&
269 Previous.Previous->isNot(TT_BinaryOperator); // For >>.
270 bool LHSIsBinaryExpr =
271 Previous.Previous && Previous.Previous->EndsBinaryExpression;
272 if ((!IsComparison || LHSIsBinaryExpr) && !Current.isTrailingComment() &&
273 Previous.getPrecedence() != prec::Assignment &&
274 State.Stack.back().BreakBeforeParameter)
276 } else if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore &&
277 State.Stack.back().BreakBeforeParameter) {
281 // Same as above, but for the first "<<" operator.
282 if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator) &&
283 State.Stack.back().BreakBeforeParameter &&
284 State.Stack.back().FirstLessLess == 0)
287 if (Current.NestingLevel == 0 && !Current.isTrailingComment()) {
288 // Always break after "template <...>" and leading annotations. This is only
289 // for cases where the entire line does not fit on a single line as a
290 // different LineFormatter would be used otherwise.
291 if (Previous.ClosesTemplateDeclaration)
293 if (Previous.is(TT_FunctionAnnotationRParen))
295 if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) &&
296 Current.isNot(TT_LeadingJavaAnnotation))
300 // If the return type spans multiple lines, wrap before the function name.
301 if ((Current.is(TT_FunctionDeclarationName) ||
302 (Current.is(tok::kw_operator) && !Previous.is(tok::coloncolon))) &&
303 !Previous.is(tok::kw_template) && State.Stack.back().BreakBeforeParameter)
306 // The following could be precomputed as they do not depend on the state.
307 // However, as they should take effect only if the UnwrappedLine does not fit
308 // into the ColumnLimit, they are checked here in the ContinuationIndenter.
309 if (Style.ColumnLimit != 0 && Previous.BlockKind == BK_Block &&
310 Previous.is(tok::l_brace) && !Current.isOneOf(tok::r_brace, tok::comment))
313 if (Current.is(tok::lessless) &&
314 ((Previous.is(tok::identifier) && Previous.TokenText == "endl") ||
315 (Previous.Tok.isLiteral() && (Previous.TokenText.endswith("\\n\"") ||
316 Previous.TokenText == "\'\\n\'"))))
322 unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
324 unsigned ExtraSpaces) {
325 const FormatToken &Current = *State.NextToken;
327 assert(!State.Stack.empty());
328 if ((Current.is(TT_ImplicitStringLiteral) &&
329 (Current.Previous->Tok.getIdentifierInfo() == nullptr ||
330 Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
331 tok::pp_not_keyword))) {
333 SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getEnd());
334 if (Current.LastNewlineOffset != 0) {
335 // If there is a newline within this token, the final column will solely
336 // determined by the current end column.
337 State.Column = EndColumn;
339 unsigned StartColumn =
340 SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getBegin());
341 assert(EndColumn >= StartColumn);
342 State.Column += EndColumn - StartColumn;
344 moveStateToNextToken(State, DryRun, /*Newline=*/false);
348 unsigned Penalty = 0;
350 Penalty = addTokenOnNewLine(State, DryRun);
352 addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
354 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
357 void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
358 unsigned ExtraSpaces) {
359 FormatToken &Current = *State.NextToken;
360 const FormatToken &Previous = *State.NextToken->Previous;
361 if (Current.is(tok::equal) &&
362 (State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) &&
363 State.Stack.back().VariablePos == 0) {
364 State.Stack.back().VariablePos = State.Column;
365 // Move over * and & if they are bound to the variable name.
366 const FormatToken *Tok = &Previous;
367 while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
368 State.Stack.back().VariablePos -= Tok->ColumnWidth;
369 if (Tok->SpacesRequiredBefore != 0)
373 if (Previous.PartOfMultiVariableDeclStmt)
374 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
377 unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
380 Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, Spaces,
381 State.Column + Spaces);
383 // If "BreakBeforeInheritanceComma" mode, don't break within the inheritance
384 // declaration unless there is multiple inheritance.
385 if (Style.BreakBeforeInheritanceComma && Current.is(TT_InheritanceColon))
386 State.Stack.back().NoLineBreak = true;
388 if (Current.is(TT_SelectorName) &&
389 !State.Stack.back().ObjCSelectorNameFound) {
391 std::max(State.FirstIndent + Style.ContinuationIndentWidth,
392 State.Stack.back().Indent);
393 unsigned FirstColonPos = State.Column + Spaces + Current.ColumnWidth;
394 if (Current.LongestObjCSelectorName == 0)
395 State.Stack.back().AlignColons = false;
396 else if (MinIndent + Current.LongestObjCSelectorName > FirstColonPos)
397 State.Stack.back().ColonPos = MinIndent + Current.LongestObjCSelectorName;
399 State.Stack.back().ColonPos = FirstColonPos;
402 // In "AlwaysBreak" mode, enforce wrapping directly after the parenthesis by
403 // disallowing any further line breaks if there is no line break after the
404 // opening parenthesis. Don't break if it doesn't conserve columns.
405 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_AlwaysBreak &&
406 Previous.isOneOf(tok::l_paren, TT_TemplateOpener, tok::l_square) &&
407 State.Column > getNewLineColumn(State) &&
408 (!Previous.Previous ||
409 !Previous.Previous->isOneOf(tok::kw_for, tok::kw_while,
411 // Don't do this for simple (no expressions) one-argument function calls
412 // as that feels like needlessly wasting whitespace, e.g.:
417 // caaaaaaaaaaaaaaaaaaaaaaall(aaaaaaaaaaaaaa, aaaaaaaaa))));
418 Current.FakeLParens.size() > 0 &&
419 Current.FakeLParens.back() > prec::Unknown)
420 State.Stack.back().NoLineBreak = true;
421 if (Previous.is(TT_TemplateString) && Previous.opensScope())
422 State.Stack.back().NoLineBreak = true;
424 if (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign &&
425 Previous.opensScope() && Previous.isNot(TT_ObjCMethodExpr) &&
426 (Current.isNot(TT_LineComment) || Previous.BlockKind == BK_BracedInit))
427 State.Stack.back().Indent = State.Column + Spaces;
428 if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
429 State.Stack.back().NoLineBreak = true;
430 if (startsSegmentOfBuilderTypeCall(Current) &&
431 State.Column > getNewLineColumn(State))
432 State.Stack.back().ContainsUnwrappedBuilder = true;
434 if (Current.is(TT_LambdaArrow) && Style.Language == FormatStyle::LK_Java)
435 State.Stack.back().NoLineBreak = true;
436 if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&
437 (Previous.MatchingParen &&
438 (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10)))
439 // If there is a function call with long parameters, break before trailing
440 // calls. This prevents things like:
441 // EXPECT_CALL(SomeLongParameter).Times(
443 // We don't want to do this for short parameters as they can just be
445 State.Stack.back().NoLineBreak = true;
447 // Don't allow the RHS of an operator to be split over multiple lines unless
448 // there is a line-break right after the operator.
449 // Exclude relational operators, as there, it is always more desirable to
450 // have the LHS 'left' of the RHS.
451 const FormatToken *P = Current.getPreviousNonComment();
452 if (!Current.is(tok::comment) && P &&
453 (P->isOneOf(TT_BinaryOperator, tok::comma) ||
454 (P->is(TT_ConditionalExpr) && P->is(tok::colon))) &&
455 !P->isOneOf(TT_OverloadedOperator, TT_CtorInitializerComma) &&
456 P->getPrecedence() != prec::Assignment &&
457 P->getPrecedence() != prec::Relational) {
458 bool BreakBeforeOperator =
459 P->MustBreakBefore || P->is(tok::lessless) ||
460 (P->is(TT_BinaryOperator) &&
461 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) ||
462 (P->is(TT_ConditionalExpr) && Style.BreakBeforeTernaryOperators);
463 // Don't do this if there are only two operands. In these cases, there is
464 // always a nice vertical separation between them and the extra line break
466 bool HasTwoOperands =
467 P->OperatorIndex == 0 && !P->NextOperator && !P->is(TT_ConditionalExpr);
468 if ((!BreakBeforeOperator && !(HasTwoOperands && Style.AlignOperands)) ||
469 (!State.Stack.back().LastOperatorWrapped && BreakBeforeOperator))
470 State.Stack.back().NoLineBreakInOperand = true;
473 State.Column += Spaces;
474 if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&
476 (Previous.Previous->isOneOf(tok::kw_if, tok::kw_for) ||
477 Previous.Previous->endsSequence(tok::kw_constexpr, tok::kw_if))) {
478 // Treat the condition inside an if as if it was a second function
479 // parameter, i.e. let nested calls have a continuation indent.
480 State.Stack.back().LastSpace = State.Column;
481 State.Stack.back().NestedBlockIndent = State.Column;
482 } else if (!Current.isOneOf(tok::comment, tok::caret) &&
483 ((Previous.is(tok::comma) &&
484 !Previous.is(TT_OverloadedOperator)) ||
485 (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) {
486 State.Stack.back().LastSpace = State.Column;
487 } else if (Previous.is(TT_CtorInitializerColon) &&
488 Style.BreakConstructorInitializers ==
489 FormatStyle::BCIS_AfterColon) {
490 State.Stack.back().Indent = State.Column;
491 State.Stack.back().LastSpace = State.Column;
492 } else if ((Previous.isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
493 TT_CtorInitializerColon)) &&
494 ((Previous.getPrecedence() != prec::Assignment &&
495 (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||
496 Previous.NextOperator)) ||
497 Current.StartsBinaryExpression)) {
498 // Indent relative to the RHS of the expression unless this is a simple
499 // assignment without binary expression on the RHS. Also indent relative to
500 // unary operators and the colons of constructor initializers.
501 State.Stack.back().LastSpace = State.Column;
502 } else if (Previous.is(TT_InheritanceColon)) {
503 State.Stack.back().Indent = State.Column;
504 State.Stack.back().LastSpace = State.Column;
505 } else if (Previous.opensScope()) {
506 // If a function has a trailing call, indent all parameters from the
507 // opening parenthesis. This avoids confusing indents like:
508 // OuterFunction(InnerFunctionCall( // break
509 // ParameterToInnerFunction)) // break
510 // .SecondInnerFunctionCall();
511 bool HasTrailingCall = false;
512 if (Previous.MatchingParen) {
513 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
514 HasTrailingCall = Next && Next->isMemberAccess();
516 if (HasTrailingCall && State.Stack.size() > 1 &&
517 State.Stack[State.Stack.size() - 2].CallContinuation == 0)
518 State.Stack.back().LastSpace = State.Column;
522 unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
524 FormatToken &Current = *State.NextToken;
525 const FormatToken &Previous = *State.NextToken->Previous;
527 // Extra penalty that needs to be added because of the way certain line
528 // breaks are chosen.
529 unsigned Penalty = 0;
531 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
532 const FormatToken *NextNonComment = Previous.getNextNonComment();
534 NextNonComment = &Current;
535 // The first line break on any NestingLevel causes an extra penalty in order
536 // prefer similar line breaks.
537 if (!State.Stack.back().ContainsLineBreak)
539 State.Stack.back().ContainsLineBreak = true;
541 Penalty += State.NextToken->SplitPenalty;
543 // Breaking before the first "<<" is generally not desirable if the LHS is
544 // short. Also always add the penalty if the LHS is split over multiple lines
545 // to avoid unnecessary line breaks that just work around this penalty.
546 if (NextNonComment->is(tok::lessless) &&
547 State.Stack.back().FirstLessLess == 0 &&
548 (State.Column <= Style.ColumnLimit / 3 ||
549 State.Stack.back().BreakBeforeParameter))
550 Penalty += Style.PenaltyBreakFirstLessLess;
552 State.Column = getNewLineColumn(State);
554 // Indent nested blocks relative to this column, unless in a very specific
555 // JavaScript special case where:
557 // var loooooong_name =
562 // is common and should be formatted like a free-standing function. The same
563 // goes for wrapping before the lambda return type arrow.
564 if (!Current.is(TT_LambdaArrow) &&
565 (Style.Language != FormatStyle::LK_JavaScript ||
566 Current.NestingLevel != 0 || !PreviousNonComment ||
567 !PreviousNonComment->is(tok::equal) ||
568 !Current.isOneOf(Keywords.kw_async, Keywords.kw_function)))
569 State.Stack.back().NestedBlockIndent = State.Column;
571 if (NextNonComment->isMemberAccess()) {
572 if (State.Stack.back().CallContinuation == 0)
573 State.Stack.back().CallContinuation = State.Column;
574 } else if (NextNonComment->is(TT_SelectorName)) {
575 if (!State.Stack.back().ObjCSelectorNameFound) {
576 if (NextNonComment->LongestObjCSelectorName == 0) {
577 State.Stack.back().AlignColons = false;
579 State.Stack.back().ColonPos =
580 (Style.IndentWrappedFunctionNames
581 ? std::max(State.Stack.back().Indent,
582 State.FirstIndent + Style.ContinuationIndentWidth)
583 : State.Stack.back().Indent) +
584 NextNonComment->LongestObjCSelectorName;
586 } else if (State.Stack.back().AlignColons &&
587 State.Stack.back().ColonPos <= NextNonComment->ColumnWidth) {
588 State.Stack.back().ColonPos = State.Column + NextNonComment->ColumnWidth;
590 } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
591 PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
592 // FIXME: This is hacky, find a better way. The problem is that in an ObjC
593 // method expression, the block should be aligned to the line starting it,
595 // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
599 // Thus, we set LastSpace of the next higher NestingLevel, to which we move
600 // when we consume all of the "}"'s FakeRParens at the "{".
601 if (State.Stack.size() > 1)
602 State.Stack[State.Stack.size() - 2].LastSpace =
603 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
604 Style.ContinuationIndentWidth;
607 if ((PreviousNonComment &&
608 PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
609 !State.Stack.back().AvoidBinPacking) ||
610 Previous.is(TT_BinaryOperator))
611 State.Stack.back().BreakBeforeParameter = false;
612 if (Previous.isOneOf(TT_TemplateCloser, TT_JavaAnnotation) &&
613 Current.NestingLevel == 0)
614 State.Stack.back().BreakBeforeParameter = false;
615 if (NextNonComment->is(tok::question) ||
616 (PreviousNonComment && PreviousNonComment->is(tok::question)))
617 State.Stack.back().BreakBeforeParameter = true;
618 if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore)
619 State.Stack.back().BreakBeforeParameter = false;
622 unsigned Newlines = std::max(
623 1u, std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1));
624 bool ContinuePPDirective =
625 State.Line->InPPDirective && State.Line->Type != LT_ImportStatement;
626 Whitespaces.replaceWhitespace(Current, Newlines, State.Column, State.Column,
627 ContinuePPDirective);
630 if (!Current.isTrailingComment())
631 State.Stack.back().LastSpace = State.Column;
632 if (Current.is(tok::lessless))
633 // If we are breaking before a "<<", we always want to indent relative to
634 // RHS. This is necessary only for "<<", as we special-case it and don't
635 // always indent relative to the RHS.
636 State.Stack.back().LastSpace += 3; // 3 -> width of "<< ".
638 State.StartOfLineLevel = Current.NestingLevel;
639 State.LowestLevelOnLine = Current.NestingLevel;
641 // Any break on this level means that the parent level has been broken
642 // and we need to avoid bin packing there.
643 bool NestedBlockSpecialCase =
644 !Style.isCpp() && Current.is(tok::r_brace) && State.Stack.size() > 1 &&
645 State.Stack[State.Stack.size() - 2].NestedBlockInlined;
646 if (!NestedBlockSpecialCase)
647 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
648 State.Stack[i].BreakBeforeParameter = true;
650 if (PreviousNonComment &&
651 !PreviousNonComment->isOneOf(tok::comma, tok::colon, tok::semi) &&
652 (PreviousNonComment->isNot(TT_TemplateCloser) ||
653 Current.NestingLevel != 0) &&
654 !PreviousNonComment->isOneOf(
655 TT_BinaryOperator, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
656 TT_LeadingJavaAnnotation) &&
657 Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope())
658 State.Stack.back().BreakBeforeParameter = true;
660 // If we break after { or the [ of an array initializer, we should also break
661 // before the corresponding } or ].
662 if (PreviousNonComment &&
663 (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
664 opensProtoMessageField(*PreviousNonComment, Style) ||
665 (PreviousNonComment->is(TT_TemplateString) &&
666 PreviousNonComment->opensScope())))
667 State.Stack.back().BreakBeforeClosingBrace = true;
669 if (State.Stack.back().AvoidBinPacking) {
670 // If we are breaking after '(', '{', '<', this is not bin packing
671 // unless AllowAllParametersOfDeclarationOnNextLine is false or this is a
672 // dict/object literal.
673 if (!Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) ||
674 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
675 State.Line->MustBeDeclaration) ||
676 Previous.is(TT_DictLiteral))
677 State.Stack.back().BreakBeforeParameter = true;
683 unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
684 if (!State.NextToken || !State.NextToken->Previous)
686 FormatToken &Current = *State.NextToken;
687 const FormatToken &Previous = *Current.Previous;
688 // If we are continuing an expression, we want to use the continuation indent.
689 unsigned ContinuationIndent =
690 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
691 Style.ContinuationIndentWidth;
692 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
693 const FormatToken *NextNonComment = Previous.getNextNonComment();
695 NextNonComment = &Current;
697 // Java specific bits.
698 if (Style.Language == FormatStyle::LK_Java &&
699 Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends))
700 return std::max(State.Stack.back().LastSpace,
701 State.Stack.back().Indent + Style.ContinuationIndentWidth);
703 if (NextNonComment->is(tok::l_brace) && NextNonComment->BlockKind == BK_Block)
704 return Current.NestingLevel == 0 ? State.FirstIndent
705 : State.Stack.back().Indent;
706 if ((Current.isOneOf(tok::r_brace, tok::r_square) ||
707 (Current.is(tok::greater) &&
708 (Style.Language == FormatStyle::LK_Proto ||
709 Style.Language == FormatStyle::LK_TextProto))) &&
710 State.Stack.size() > 1) {
711 if (Current.closesBlockOrBlockTypeList(Style))
712 return State.Stack[State.Stack.size() - 2].NestedBlockIndent;
713 if (Current.MatchingParen &&
714 Current.MatchingParen->BlockKind == BK_BracedInit)
715 return State.Stack[State.Stack.size() - 2].LastSpace;
716 return State.FirstIndent;
718 // Indent a closing parenthesis at the previous level if followed by a semi or
719 // opening brace. This allows indentations such as:
728 if (Current.is(tok::r_paren) && State.Stack.size() > 1 &&
729 (!Current.Next || Current.Next->isOneOf(tok::semi, tok::l_brace)))
730 return State.Stack[State.Stack.size() - 2].LastSpace;
731 if (NextNonComment->is(TT_TemplateString) && NextNonComment->closesScope())
732 return State.Stack[State.Stack.size() - 2].LastSpace;
733 if (Current.is(tok::identifier) && Current.Next &&
734 Current.Next->is(TT_DictLiteral))
735 return State.Stack.back().Indent;
736 if (NextNonComment->is(TT_ObjCStringLiteral) &&
737 State.StartOfStringLiteral != 0)
738 return State.StartOfStringLiteral - 1;
739 if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
740 return State.StartOfStringLiteral;
741 if (NextNonComment->is(tok::lessless) &&
742 State.Stack.back().FirstLessLess != 0)
743 return State.Stack.back().FirstLessLess;
744 if (NextNonComment->isMemberAccess()) {
745 if (State.Stack.back().CallContinuation == 0)
746 return ContinuationIndent;
747 return State.Stack.back().CallContinuation;
749 if (State.Stack.back().QuestionColumn != 0 &&
750 ((NextNonComment->is(tok::colon) &&
751 NextNonComment->is(TT_ConditionalExpr)) ||
752 Previous.is(TT_ConditionalExpr)))
753 return State.Stack.back().QuestionColumn;
754 if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0)
755 return State.Stack.back().VariablePos;
756 if ((PreviousNonComment &&
757 (PreviousNonComment->ClosesTemplateDeclaration ||
758 PreviousNonComment->isOneOf(
759 TT_AttributeParen, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
760 TT_LeadingJavaAnnotation))) ||
761 (!Style.IndentWrappedFunctionNames &&
762 NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName)))
763 return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
764 if (NextNonComment->is(TT_SelectorName)) {
765 if (!State.Stack.back().ObjCSelectorNameFound) {
766 if (NextNonComment->LongestObjCSelectorName == 0)
767 return State.Stack.back().Indent;
768 return (Style.IndentWrappedFunctionNames
769 ? std::max(State.Stack.back().Indent,
770 State.FirstIndent + Style.ContinuationIndentWidth)
771 : State.Stack.back().Indent) +
772 NextNonComment->LongestObjCSelectorName -
773 NextNonComment->ColumnWidth;
775 if (!State.Stack.back().AlignColons)
776 return State.Stack.back().Indent;
777 if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth)
778 return State.Stack.back().ColonPos - NextNonComment->ColumnWidth;
779 return State.Stack.back().Indent;
781 if (NextNonComment->is(tok::colon) && NextNonComment->is(TT_ObjCMethodExpr))
782 return State.Stack.back().ColonPos;
783 if (NextNonComment->is(TT_ArraySubscriptLSquare)) {
784 if (State.Stack.back().StartOfArraySubscripts != 0)
785 return State.Stack.back().StartOfArraySubscripts;
786 return ContinuationIndent;
789 // This ensure that we correctly format ObjC methods calls without inputs,
790 // i.e. where the last element isn't selector like: [callee method];
791 if (NextNonComment->is(tok::identifier) && NextNonComment->FakeRParens == 0 &&
792 NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr))
793 return State.Stack.back().Indent;
795 if (NextNonComment->isOneOf(TT_StartOfName, TT_PointerOrReference) ||
796 Previous.isOneOf(tok::coloncolon, tok::equal, TT_JsTypeColon))
797 return ContinuationIndent;
798 if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
799 PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))
800 return ContinuationIndent;
801 if (NextNonComment->is(TT_CtorInitializerComma))
802 return State.Stack.back().Indent;
803 if (PreviousNonComment && PreviousNonComment->is(TT_CtorInitializerColon) &&
804 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon)
805 return State.Stack.back().Indent;
806 if (NextNonComment->isOneOf(TT_CtorInitializerColon, TT_InheritanceColon,
807 TT_InheritanceComma))
808 return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
809 if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() &&
810 !Current.isOneOf(tok::colon, tok::comment))
811 return ContinuationIndent;
812 if (State.Stack.back().Indent == State.FirstIndent && PreviousNonComment &&
813 PreviousNonComment->isNot(tok::r_brace))
814 // Ensure that we fall back to the continuation indent width instead of
815 // just flushing continuations left.
816 return State.Stack.back().Indent + Style.ContinuationIndentWidth;
817 return State.Stack.back().Indent;
820 unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
821 bool DryRun, bool Newline) {
822 assert(State.Stack.size());
823 const FormatToken &Current = *State.NextToken;
825 if (Current.isOneOf(tok::comma, TT_BinaryOperator))
826 State.Stack.back().NoLineBreakInOperand = false;
827 if (Current.is(TT_InheritanceColon))
828 State.Stack.back().AvoidBinPacking = true;
829 if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) {
830 if (State.Stack.back().FirstLessLess == 0)
831 State.Stack.back().FirstLessLess = State.Column;
833 State.Stack.back().LastOperatorWrapped = Newline;
835 if (Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless))
836 State.Stack.back().LastOperatorWrapped = Newline;
837 if (Current.is(TT_ConditionalExpr) && Current.Previous &&
838 !Current.Previous->is(TT_ConditionalExpr))
839 State.Stack.back().LastOperatorWrapped = Newline;
840 if (Current.is(TT_ArraySubscriptLSquare) &&
841 State.Stack.back().StartOfArraySubscripts == 0)
842 State.Stack.back().StartOfArraySubscripts = State.Column;
843 if (Style.BreakBeforeTernaryOperators && Current.is(tok::question))
844 State.Stack.back().QuestionColumn = State.Column;
845 if (!Style.BreakBeforeTernaryOperators && Current.isNot(tok::colon)) {
846 const FormatToken *Previous = Current.Previous;
847 while (Previous && Previous->isTrailingComment())
848 Previous = Previous->Previous;
849 if (Previous && Previous->is(tok::question))
850 State.Stack.back().QuestionColumn = State.Column;
852 if (!Current.opensScope() && !Current.closesScope() &&
853 !Current.is(TT_PointerOrReference))
854 State.LowestLevelOnLine =
855 std::min(State.LowestLevelOnLine, Current.NestingLevel);
856 if (Current.isMemberAccess())
857 State.Stack.back().StartOfFunctionCall =
858 !Current.NextOperator ? 0 : State.Column;
859 if (Current.is(TT_SelectorName)) {
860 State.Stack.back().ObjCSelectorNameFound = true;
861 if (Style.IndentWrappedFunctionNames) {
862 State.Stack.back().Indent =
863 State.FirstIndent + Style.ContinuationIndentWidth;
866 if (Current.is(TT_CtorInitializerColon) &&
867 Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon) {
868 // Indent 2 from the column, so:
869 // SomeClass::SomeClass()
873 State.Stack.back().Indent =
874 State.Column + (Style.BreakConstructorInitializers ==
875 FormatStyle::BCIS_BeforeComma ? 0 : 2);
876 State.Stack.back().NestedBlockIndent = State.Stack.back().Indent;
877 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
878 State.Stack.back().AvoidBinPacking = true;
879 State.Stack.back().BreakBeforeParameter = false;
881 if (Current.is(TT_CtorInitializerColon) &&
882 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) {
883 State.Stack.back().Indent =
884 State.FirstIndent + Style.ConstructorInitializerIndentWidth;
885 State.Stack.back().NestedBlockIndent = State.Stack.back().Indent;
886 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
887 State.Stack.back().AvoidBinPacking = true;
889 if (Current.is(TT_InheritanceColon))
890 State.Stack.back().Indent =
891 State.FirstIndent + Style.ContinuationIndentWidth;
892 if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline)
893 State.Stack.back().NestedBlockIndent =
894 State.Column + Current.ColumnWidth + 1;
895 if (Current.isOneOf(TT_LambdaLSquare, TT_LambdaArrow))
896 State.Stack.back().LastSpace = State.Column;
898 // Insert scopes created by fake parenthesis.
899 const FormatToken *Previous = Current.getPreviousNonComment();
901 // Add special behavior to support a format commonly used for JavaScript
903 // SomeFunction(function() {
907 if (Current.isNot(tok::comment) && Previous &&
908 Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
909 !Previous->is(TT_DictLiteral) && State.Stack.size() > 1) {
910 if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline)
911 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
912 State.Stack[i].NoLineBreak = true;
913 State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;
915 if (Previous && (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) ||
916 Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr)) &&
917 !Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
918 State.Stack.back().NestedBlockInlined =
920 (Previous->isNot(tok::l_paren) || Previous->ParameterCount > 1);
923 moveStatePastFakeLParens(State, Newline);
924 moveStatePastScopeCloser(State);
925 if (Current.is(TT_TemplateString) && Current.opensScope())
926 State.Stack.back().LastSpace =
927 (Current.IsMultiline ? Current.LastLineColumnWidth
928 : State.Column + Current.ColumnWidth) -
930 bool CanBreakProtrudingToken = !State.Stack.back().NoLineBreak &&
931 !State.Stack.back().NoLineBreakInOperand;
932 moveStatePastScopeOpener(State, Newline);
933 moveStatePastFakeRParens(State);
935 if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0)
936 State.StartOfStringLiteral = State.Column + 1;
937 else if (Current.isStringLiteral() && State.StartOfStringLiteral == 0)
938 State.StartOfStringLiteral = State.Column;
939 else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
940 !Current.isStringLiteral())
941 State.StartOfStringLiteral = 0;
943 State.Column += Current.ColumnWidth;
944 State.NextToken = State.NextToken->Next;
945 unsigned Penalty = 0;
946 if (CanBreakProtrudingToken)
947 Penalty = breakProtrudingToken(Current, State, DryRun);
948 if (State.Column > getColumnLimit(State)) {
949 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
950 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
954 Current.Role->formatFromToken(State, this, DryRun);
955 // If the previous has a special role, let it consume tokens as appropriate.
956 // It is necessary to start at the previous token for the only implemented
957 // role (comma separated list). That way, the decision whether or not to break
958 // after the "{" is already done and both options are tried and evaluated.
959 // FIXME: This is ugly, find a better way.
960 if (Previous && Previous->Role)
961 Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
966 void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
968 const FormatToken &Current = *State.NextToken;
969 const FormatToken *Previous = Current.getPreviousNonComment();
971 // Don't add extra indentation for the first fake parenthesis after
972 // 'return', assignments or opening <({[. The indentation for these cases
974 bool SkipFirstExtraIndent =
975 (Previous && (Previous->opensScope() ||
976 Previous->isOneOf(tok::semi, tok::kw_return) ||
977 (Previous->getPrecedence() == prec::Assignment &&
978 Style.AlignOperands) ||
979 Previous->is(TT_ObjCMethodExpr)));
980 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
981 I = Current.FakeLParens.rbegin(),
982 E = Current.FakeLParens.rend();
984 ParenState NewParenState = State.Stack.back();
985 NewParenState.ContainsLineBreak = false;
986 NewParenState.LastOperatorWrapped = true;
987 NewParenState.NoLineBreak =
988 NewParenState.NoLineBreak || State.Stack.back().NoLineBreakInOperand;
990 // Don't propagate AvoidBinPacking into subexpressions of arg/param lists.
991 if (*I > prec::Comma)
992 NewParenState.AvoidBinPacking = false;
994 // Indent from 'LastSpace' unless these are fake parentheses encapsulating
995 // a builder type call after 'return' or, if the alignment after opening
996 // brackets is disabled.
997 if (!Current.isTrailingComment() &&
998 (Style.AlignOperands || *I < prec::Assignment) &&
999 (!Previous || Previous->isNot(tok::kw_return) ||
1000 (Style.Language != FormatStyle::LK_Java && *I > 0)) &&
1001 (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign ||
1002 *I != prec::Comma || Current.NestingLevel == 0))
1003 NewParenState.Indent =
1004 std::max(std::max(State.Column, NewParenState.Indent),
1005 State.Stack.back().LastSpace);
1007 // Do not indent relative to the fake parentheses inserted for "." or "->".
1008 // This is a special case to make the following to statements consistent:
1009 // OuterFunction(InnerFunctionCall( // break
1010 // ParameterToInnerFunction));
1011 // OuterFunction(SomeObject.InnerFunctionCall( // break
1012 // ParameterToInnerFunction));
1013 if (*I > prec::Unknown)
1014 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
1015 if (*I != prec::Conditional && !Current.is(TT_UnaryOperator) &&
1016 Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
1017 NewParenState.StartOfFunctionCall = State.Column;
1019 // Always indent conditional expressions. Never indent expression where
1020 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
1021 // prec::Assignment) as those have different indentation rules. Indent
1022 // other expression, unless the indentation needs to be skipped.
1023 if (*I == prec::Conditional ||
1024 (!SkipFirstExtraIndent && *I > prec::Assignment &&
1025 !Current.isTrailingComment()))
1026 NewParenState.Indent += Style.ContinuationIndentWidth;
1027 if ((Previous && !Previous->opensScope()) || *I != prec::Comma)
1028 NewParenState.BreakBeforeParameter = false;
1029 State.Stack.push_back(NewParenState);
1030 SkipFirstExtraIndent = false;
1034 void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
1035 for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) {
1036 unsigned VariablePos = State.Stack.back().VariablePos;
1037 if (State.Stack.size() == 1) {
1038 // Do not pop the last element.
1041 State.Stack.pop_back();
1042 State.Stack.back().VariablePos = VariablePos;
1046 void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
1048 const FormatToken &Current = *State.NextToken;
1049 if (!Current.opensScope())
1052 if (Current.MatchingParen && Current.BlockKind == BK_Block) {
1053 moveStateToNewBlock(State);
1058 unsigned LastSpace = State.Stack.back().LastSpace;
1059 bool AvoidBinPacking;
1060 bool BreakBeforeParameter = false;
1061 unsigned NestedBlockIndent = std::max(State.Stack.back().StartOfFunctionCall,
1062 State.Stack.back().NestedBlockIndent);
1063 if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
1064 opensProtoMessageField(Current, Style)) {
1065 if (Current.opensBlockOrBlockTypeList(Style)) {
1066 NewIndent = Style.IndentWidth +
1067 std::min(State.Column, State.Stack.back().NestedBlockIndent);
1069 NewIndent = State.Stack.back().LastSpace + Style.ContinuationIndentWidth;
1071 const FormatToken *NextNoComment = Current.getNextNonComment();
1072 bool EndsInComma = Current.MatchingParen &&
1073 Current.MatchingParen->Previous &&
1074 Current.MatchingParen->Previous->is(tok::comma);
1076 EndsInComma || Current.is(TT_DictLiteral) ||
1077 Style.Language == FormatStyle::LK_Proto ||
1078 Style.Language == FormatStyle::LK_TextProto ||
1079 !Style.BinPackArguments ||
1081 NextNoComment->isOneOf(TT_DesignatedInitializerPeriod,
1082 TT_DesignatedInitializerLSquare));
1083 BreakBeforeParameter = EndsInComma;
1084 if (Current.ParameterCount > 1)
1085 NestedBlockIndent = std::max(NestedBlockIndent, State.Column + 1);
1087 NewIndent = Style.ContinuationIndentWidth +
1088 std::max(State.Stack.back().LastSpace,
1089 State.Stack.back().StartOfFunctionCall);
1091 // Ensure that different different brackets force relative alignment, e.g.:
1092 // void SomeFunction(vector< // break
1094 // FIXME: We likely want to do this for more combinations of brackets.
1095 // Verify that it is wanted for ObjC, too.
1096 if (Current.is(tok::less) && Current.ParentBracket == tok::l_paren) {
1097 NewIndent = std::max(NewIndent, State.Stack.back().Indent);
1098 LastSpace = std::max(LastSpace, State.Stack.back().Indent);
1101 // JavaScript template strings are special as we always want to indent
1102 // nested expressions relative to the ${}. Otherwise, this can create quite
1104 if (Current.is(TT_TemplateString)) {
1105 unsigned Column = Current.IsMultiline
1106 ? Current.LastLineColumnWidth
1107 : State.Column + Current.ColumnWidth;
1110 NestedBlockIndent = Column;
1114 Current.MatchingParen &&
1115 Current.MatchingParen->getPreviousNonComment() &&
1116 Current.MatchingParen->getPreviousNonComment()->is(tok::comma);
1119 (Style.Language == FormatStyle::LK_JavaScript && EndsInComma) ||
1120 (State.Line->MustBeDeclaration && !Style.BinPackParameters) ||
1121 (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||
1122 (Style.ExperimentalAutoDetectBinPacking &&
1123 (Current.PackingKind == PPK_OnePerLine ||
1124 (!BinPackInconclusiveFunctions &&
1125 Current.PackingKind == PPK_Inconclusive)));
1127 if (Current.is(TT_ObjCMethodExpr) && Current.MatchingParen) {
1128 if (Style.ColumnLimit) {
1129 // If this '[' opens an ObjC call, determine whether all parameters fit
1130 // into one line and put one per line if they don't.
1131 if (getLengthToMatchingParen(Current) + State.Column >
1132 getColumnLimit(State))
1133 BreakBeforeParameter = true;
1135 // For ColumnLimit = 0, we have to figure out whether there is or has to
1136 // be a line break within this call.
1137 for (const FormatToken *Tok = &Current;
1138 Tok && Tok != Current.MatchingParen; Tok = Tok->Next) {
1139 if (Tok->MustBreakBefore ||
1140 (Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) {
1141 BreakBeforeParameter = true;
1148 if (Style.Language == FormatStyle::LK_JavaScript && EndsInComma)
1149 BreakBeforeParameter = true;
1151 // Generally inherit NoLineBreak from the current scope to nested scope.
1152 // However, don't do this for non-empty nested blocks, dict literals and
1153 // array literals as these follow different indentation rules.
1155 Current.Children.empty() &&
1156 !Current.isOneOf(TT_DictLiteral, TT_ArrayInitializerLSquare) &&
1157 (State.Stack.back().NoLineBreak ||
1158 State.Stack.back().NoLineBreakInOperand ||
1159 (Current.is(TT_TemplateOpener) &&
1160 State.Stack.back().ContainsUnwrappedBuilder));
1161 State.Stack.push_back(
1162 ParenState(NewIndent, LastSpace, AvoidBinPacking, NoLineBreak));
1163 State.Stack.back().NestedBlockIndent = NestedBlockIndent;
1164 State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
1165 State.Stack.back().HasMultipleNestedBlocks = Current.BlockParameterCount > 1;
1168 void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
1169 const FormatToken &Current = *State.NextToken;
1170 if (!Current.closesScope())
1173 // If we encounter a closing ), ], } or >, we can remove a level from our
1175 if (State.Stack.size() > 1 &&
1176 (Current.isOneOf(tok::r_paren, tok::r_square, TT_TemplateString) ||
1177 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
1178 State.NextToken->is(TT_TemplateCloser)))
1179 State.Stack.pop_back();
1181 if (Current.is(tok::r_square)) {
1182 // If this ends the array subscript expr, reset the corresponding value.
1183 const FormatToken *NextNonComment = Current.getNextNonComment();
1184 if (NextNonComment && NextNonComment->isNot(tok::l_square))
1185 State.Stack.back().StartOfArraySubscripts = 0;
1189 void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
1190 unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
1191 // ObjC block sometimes follow special indentation rules.
1192 unsigned NewIndent =
1193 NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace)
1194 ? Style.ObjCBlockIndentWidth
1195 : Style.IndentWidth);
1196 State.Stack.push_back(ParenState(NewIndent, State.Stack.back().LastSpace,
1197 /*AvoidBinPacking=*/true,
1198 /*NoLineBreak=*/false));
1199 State.Stack.back().NestedBlockIndent = NestedBlockIndent;
1200 State.Stack.back().BreakBeforeParameter = true;
1203 unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
1205 if (!Current.IsMultiline)
1208 // Break before further function parameters on all levels.
1209 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1210 State.Stack[i].BreakBeforeParameter = true;
1212 unsigned ColumnsUsed = State.Column;
1213 // We can only affect layout of the first and the last line, so the penalty
1214 // for all other lines is constant, and we ignore it.
1215 State.Column = Current.LastLineColumnWidth;
1217 if (ColumnsUsed > getColumnLimit(State))
1218 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
1222 unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
1225 // Don't break multi-line tokens other than block comments. Instead, just
1226 // update the state.
1227 if (Current.isNot(TT_BlockComment) && Current.IsMultiline)
1228 return addMultilineToken(Current, State);
1230 // Don't break implicit string literals or import statements.
1231 if (Current.is(TT_ImplicitStringLiteral) ||
1232 State.Line->Type == LT_ImportStatement)
1235 if (!Current.isStringLiteral() && !Current.is(tok::comment))
1238 std::unique_ptr<BreakableToken> Token;
1239 unsigned StartColumn = State.Column - Current.ColumnWidth;
1240 unsigned ColumnLimit = getColumnLimit(State);
1242 if (Current.isStringLiteral()) {
1243 // FIXME: String literal breaking is currently disabled for Java and JS, as
1244 // it requires strings to be merged using "+" which we don't support.
1245 if (Style.Language == FormatStyle::LK_Java ||
1246 Style.Language == FormatStyle::LK_JavaScript ||
1247 !Style.BreakStringLiterals)
1250 // Don't break string literals inside preprocessor directives (except for
1251 // #define directives, as their contents are stored in separate lines and
1252 // are not affected by this check).
1253 // This way we avoid breaking code with line directives and unknown
1254 // preprocessor directives that contain long string literals.
1255 if (State.Line->Type == LT_PreprocessorDirective)
1257 // Exempts unterminated string literals from line breaking. The user will
1258 // likely want to terminate the string before any line breaking is done.
1259 if (Current.IsUnterminatedLiteral)
1262 StringRef Text = Current.TokenText;
1265 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
1266 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
1267 // reduce the overhead) for each FormatToken, which is a string, so that we
1268 // don't run multiple checks here on the hot path.
1269 if ((Text.endswith(Postfix = "\"") &&
1270 (Text.startswith(Prefix = "@\"") || Text.startswith(Prefix = "\"") ||
1271 Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
1272 Text.startswith(Prefix = "u8\"") ||
1273 Text.startswith(Prefix = "L\""))) ||
1274 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) {
1275 Token.reset(new BreakableStringLiteral(Current, StartColumn, Prefix,
1276 Postfix, State.Line->InPPDirective,
1281 } else if (Current.is(TT_BlockComment)) {
1282 if (!Current.isTrailingComment() || !Style.ReflowComments ||
1283 // If a comment token switches formatting, like
1284 // /* clang-format on */, we don't want to break it further,
1285 // but we may still want to adjust its indentation.
1286 switchesFormatting(Current))
1287 return addMultilineToken(Current, State);
1288 Token.reset(new BreakableBlockComment(
1289 Current, StartColumn, Current.OriginalColumn, !Current.Previous,
1290 State.Line->InPPDirective, Encoding, Style));
1291 } else if (Current.is(TT_LineComment) &&
1292 (Current.Previous == nullptr ||
1293 Current.Previous->isNot(TT_ImplicitStringLiteral))) {
1294 if (!Style.ReflowComments ||
1295 CommentPragmasRegex.match(Current.TokenText.substr(2)) ||
1296 switchesFormatting(Current))
1298 Token.reset(new BreakableLineCommentSection(
1299 Current, StartColumn, Current.OriginalColumn, !Current.Previous,
1300 /*InPPDirective=*/false, Encoding, Style));
1301 // We don't insert backslashes when breaking line comments.
1302 ColumnLimit = Style.ColumnLimit;
1306 if (Current.UnbreakableTailLength >= ColumnLimit)
1309 unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength;
1310 bool BreakInserted = false;
1311 // We use a conservative reflowing strategy. Reflow starts after a line is
1312 // broken or the corresponding whitespace compressed. Reflow ends as soon as a
1313 // line that doesn't get reflown with the previous line is reached.
1314 bool ReflowInProgress = false;
1315 unsigned Penalty = 0;
1316 unsigned RemainingTokenColumns = 0;
1317 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
1318 LineIndex != EndIndex; ++LineIndex) {
1319 BreakableToken::Split SplitBefore(StringRef::npos, 0);
1320 if (ReflowInProgress) {
1321 SplitBefore = Token->getSplitBefore(LineIndex, RemainingTokenColumns,
1322 RemainingSpace, CommentPragmasRegex);
1324 ReflowInProgress = SplitBefore.first != StringRef::npos;
1325 unsigned TailOffset =
1326 ReflowInProgress ? (SplitBefore.first + SplitBefore.second) : 0;
1328 Token->replaceWhitespaceBefore(LineIndex, RemainingTokenColumns,
1329 RemainingSpace, SplitBefore, Whitespaces);
1330 RemainingTokenColumns = Token->getLineLengthAfterSplitBefore(
1331 LineIndex, TailOffset, RemainingTokenColumns, ColumnLimit, SplitBefore);
1332 while (RemainingTokenColumns > RemainingSpace) {
1333 BreakableToken::Split Split = Token->getSplit(
1334 LineIndex, TailOffset, ColumnLimit, CommentPragmasRegex);
1335 if (Split.first == StringRef::npos) {
1336 // The last line's penalty is handled in addNextStateToQueue().
1337 if (LineIndex < EndIndex - 1)
1338 Penalty += Style.PenaltyExcessCharacter *
1339 (RemainingTokenColumns - RemainingSpace);
1342 assert(Split.first != 0);
1344 // Check if compressing the whitespace range will bring the line length
1345 // under the limit. If that is the case, we perform whitespace compression
1346 // instead of inserting a line break.
1347 unsigned RemainingTokenColumnsAfterCompression =
1348 Token->getLineLengthAfterCompression(RemainingTokenColumns, Split);
1349 if (RemainingTokenColumnsAfterCompression <= RemainingSpace) {
1350 RemainingTokenColumns = RemainingTokenColumnsAfterCompression;
1351 ReflowInProgress = true;
1353 Token->compressWhitespace(LineIndex, TailOffset, Split, Whitespaces);
1357 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
1358 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
1360 // When breaking before a tab character, it may be moved by a few columns,
1361 // but will still be expanded to the next tab stop, so we don't save any
1363 if (NewRemainingTokenColumns == RemainingTokenColumns)
1366 assert(NewRemainingTokenColumns < RemainingTokenColumns);
1368 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
1369 Penalty += Current.SplitPenalty;
1370 unsigned ColumnsUsed =
1371 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
1372 if (ColumnsUsed > ColumnLimit) {
1373 Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit);
1375 TailOffset += Split.first + Split.second;
1376 RemainingTokenColumns = NewRemainingTokenColumns;
1377 ReflowInProgress = true;
1378 BreakInserted = true;
1382 State.Column = RemainingTokenColumns;
1384 if (BreakInserted) {
1385 // If we break the token inside a parameter list, we need to break before
1386 // the next parameter on all levels, so that the next parameter is clearly
1387 // visible. Line comments already introduce a break.
1388 if (Current.isNot(TT_LineComment)) {
1389 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1390 State.Stack[i].BreakBeforeParameter = true;
1393 Penalty += Current.isStringLiteral() ? Style.PenaltyBreakString
1394 : Style.PenaltyBreakComment;
1396 State.Stack.back().LastSpace = StartColumn;
1399 Token->updateNextToken(State);
1404 unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
1405 // In preprocessor directives reserve two chars for trailing " \"
1406 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
1409 bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
1410 const FormatToken &Current = *State.NextToken;
1411 if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral))
1413 // We never consider raw string literals "multiline" for the purpose of
1414 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
1415 // (see TokenAnnotator::mustBreakBefore().
1416 if (Current.TokenText.startswith("R\""))
1418 if (Current.IsMultiline)
1420 if (Current.getNextNonComment() &&
1421 Current.getNextNonComment()->isStringLiteral())
1422 return true; // Implicit concatenation.
1423 if (Style.ColumnLimit != 0 &&
1424 State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
1426 return true; // String will be split.
1430 } // namespace format
1431 } // namespace clang