]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Format/ContinuationIndenter.cpp
Merge ^/head r279313 through r279595.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Format / ContinuationIndenter.cpp
1 //===--- ContinuationIndenter.cpp - Format C++ code -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief This file implements the continuation indenter.
12 ///
13 //===----------------------------------------------------------------------===//
14
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"
22 #include <string>
23
24 #define DEBUG_TYPE "format-formatter"
25
26 namespace clang {
27 namespace format {
28
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)
33     return 0;
34   FormatToken *End = Tok.MatchingParen;
35   while (End->Next && !End->Next->CanBreakBefore) {
36     End = End->Next;
37   }
38   return End->TotalLength - Tok.TotalLength + 1;
39 }
40
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();
45 }
46
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)
53     return true;
54   return Previous.is(tok::comma) && !Current.isTrailingComment() &&
55          (Previous.isNot(TT_CtorInitializerComma) ||
56           !Style.BreakConstructorInitializersBeforeComma);
57 }
58
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) {}
69
70 LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
71                                                 const AnnotatedLine *Line,
72                                                 bool DryRun) {
73   LineState State;
74   State.FirstIndent = FirstIndent;
75   State.Column = FirstIndent;
76   State.Line = Line;
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;
86
87   // The first token has already been indented and thus consumed.
88   moveStateToNextToken(State, DryRun, /*Newline=*/false);
89   return State;
90 }
91
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)))
99     return false;
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 &&
104       Previous.Previous &&
105       Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
106     return false;
107   // This prevents breaks like:
108   //   ...
109   //   SomeParameter, OtherParameter).DoSomething(
110   //   ...
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)
115     return false;
116   if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
117     return false;
118
119   // Don't create a 'hanging' indent if there are multiple blocks in a single
120   // statement.
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)
124     return false;
125
126   // Don't break after very short return types (e.g. "void") as that is often
127   // unexpected.
128   if (Current.is(TT_FunctionDeclarationName) &&
129       !Style.AlwaysBreakAfterDefinitionReturnType && State.Column < 6)
130     return false;
131
132   return !State.Stack.back().NoLineBreak;
133 }
134
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))
139     return true;
140   if (State.Stack.back().BreakBeforeClosingBrace &&
141       Current.closesBlockTypeList(Style))
142     return true;
143   if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
144     return true;
145   if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
146        (Style.BreakBeforeTernaryOperators &&
147         (Current.is(tok::question) ||
148          (Current.is(TT_ConditionalExpr) && Previous.isNot(tok::question)))) ||
149        (!Style.BreakBeforeTernaryOperators &&
150         (Previous.is(tok::question) || Previous.is(TT_ConditionalExpr)))) &&
151       State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
152       !Current.isOneOf(tok::r_paren, tok::r_brace))
153     return true;
154   if (Style.AlwaysBreakBeforeMultilineStrings &&
155       State.Column > State.Stack.back().Indent && // Breaking saves columns.
156       !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) &&
157       !Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) &&
158       nextIsMultilineString(State))
159     return true;
160   if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) ||
161        Previous.is(TT_ArrayInitializerLSquare)) &&
162       Style.ColumnLimit > 0 &&
163       getLengthToMatchingParen(Previous) + State.Column > getColumnLimit(State))
164     return true;
165   if (Current.is(TT_CtorInitializerColon) &&
166       ((Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All) ||
167        Style.BreakConstructorInitializersBeforeComma || Style.ColumnLimit != 0))
168     return true;
169
170   if (State.Column < getNewLineColumn(State))
171     return false;
172   if (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None) {
173     // If we need to break somewhere inside the LHS of a binary expression, we
174     // should also break after the operator. Otherwise, the formatting would
175     // hide the operator precedence, e.g. in:
176     //   if (aaaaaaaaaaaaaa ==
177     //           bbbbbbbbbbbbbb && c) {..
178     // For comparisons, we only apply this rule, if the LHS is a binary
179     // expression itself as otherwise, the line breaks seem superfluous.
180     // We need special cases for ">>" which we have split into two ">" while
181     // lexing in order to make template parsing easier.
182     bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
183                          Previous.getPrecedence() == prec::Equality) &&
184                         Previous.Previous &&
185                         Previous.Previous->isNot(TT_BinaryOperator); // For >>.
186     bool LHSIsBinaryExpr =
187         Previous.Previous && Previous.Previous->EndsBinaryExpression;
188     if (Previous.is(TT_BinaryOperator) && (!IsComparison || LHSIsBinaryExpr) &&
189         Current.isNot(TT_BinaryOperator) && // For >>.
190         !Current.isTrailingComment() && !Previous.is(tok::lessless) &&
191         Previous.getPrecedence() != prec::Assignment &&
192         State.Stack.back().BreakBeforeParameter)
193       return true;
194   } else {
195     if (Current.is(TT_BinaryOperator) && Previous.EndsBinaryExpression &&
196         State.Stack.back().BreakBeforeParameter)
197       return true;
198   }
199
200   // Same as above, but for the first "<<" operator.
201   if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator) &&
202       State.Stack.back().BreakBeforeParameter &&
203       State.Stack.back().FirstLessLess == 0)
204     return true;
205
206   if (Current.is(TT_SelectorName) && State.Stack.back().ObjCSelectorNameFound &&
207       State.Stack.back().BreakBeforeParameter)
208     return true;
209   if (Current.NestingLevel == 0 && !Current.isTrailingComment()) {
210     if (Previous.ClosesTemplateDeclaration)
211       return true;
212     if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) &&
213         Current.isNot(TT_LeadingJavaAnnotation))
214       return true;
215   }
216
217   // If the return type spans multiple lines, wrap before the function name.
218   if (Current.isOneOf(TT_FunctionDeclarationName, tok::kw_operator) &&
219       State.Stack.back().BreakBeforeParameter)
220     return true;
221
222   if (startsSegmentOfBuilderTypeCall(Current) &&
223       (State.Stack.back().CallContinuation != 0 ||
224        (State.Stack.back().BreakBeforeParameter &&
225         State.Stack.back().ContainsUnwrappedBuilder)))
226     return true;
227
228   // The following could be precomputed as they do not depend on the state.
229   // However, as they should take effect only if the UnwrappedLine does not fit
230   // into the ColumnLimit, they are checked here in the ContinuationIndenter.
231   if (Style.ColumnLimit != 0 && Previous.BlockKind == BK_Block &&
232       Previous.is(tok::l_brace) && !Current.isOneOf(tok::r_brace, tok::comment))
233     return true;
234
235   return false;
236 }
237
238 unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
239                                                bool DryRun,
240                                                unsigned ExtraSpaces) {
241   const FormatToken &Current = *State.NextToken;
242
243   assert(!State.Stack.empty());
244   if ((Current.is(TT_ImplicitStringLiteral) &&
245        (Current.Previous->Tok.getIdentifierInfo() == nullptr ||
246         Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
247             tok::pp_not_keyword))) {
248     // FIXME: Is this correct?
249     int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
250                                State.NextToken->WhitespaceRange.getEnd()) -
251                            SourceMgr.getSpellingColumnNumber(
252                                State.NextToken->WhitespaceRange.getBegin());
253     State.Column += WhitespaceLength;
254     moveStateToNextToken(State, DryRun, /*Newline=*/false);
255     return 0;
256   }
257
258   unsigned Penalty = 0;
259   if (Newline)
260     Penalty = addTokenOnNewLine(State, DryRun);
261   else
262     addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
263
264   return moveStateToNextToken(State, DryRun, Newline) + Penalty;
265 }
266
267 void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
268                                                  unsigned ExtraSpaces) {
269   FormatToken &Current = *State.NextToken;
270   const FormatToken &Previous = *State.NextToken->Previous;
271   if (Current.is(tok::equal) &&
272       (State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) &&
273       State.Stack.back().VariablePos == 0) {
274     State.Stack.back().VariablePos = State.Column;
275     // Move over * and & if they are bound to the variable name.
276     const FormatToken *Tok = &Previous;
277     while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
278       State.Stack.back().VariablePos -= Tok->ColumnWidth;
279       if (Tok->SpacesRequiredBefore != 0)
280         break;
281       Tok = Tok->Previous;
282     }
283     if (Previous.PartOfMultiVariableDeclStmt)
284       State.Stack.back().LastSpace = State.Stack.back().VariablePos;
285   }
286
287   unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
288
289   if (!DryRun)
290     Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, /*IndentLevel=*/0,
291                                   Spaces, State.Column + Spaces);
292
293   if (Current.is(TT_SelectorName) &&
294       !State.Stack.back().ObjCSelectorNameFound) {
295     if (Current.LongestObjCSelectorName == 0)
296       State.Stack.back().AlignColons = false;
297     else if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
298              State.Column + Spaces + Current.ColumnWidth)
299       State.Stack.back().ColonPos =
300           State.Stack.back().Indent + Current.LongestObjCSelectorName;
301     else
302       State.Stack.back().ColonPos = State.Column + Spaces + Current.ColumnWidth;
303   }
304
305   if (Style.AlignAfterOpenBracket && Previous.opensScope() &&
306       Previous.isNot(TT_ObjCMethodExpr) &&
307       (Current.isNot(TT_LineComment) || Previous.BlockKind == BK_BracedInit))
308     State.Stack.back().Indent = State.Column + Spaces;
309   if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
310     State.Stack.back().NoLineBreak = true;
311   if (startsSegmentOfBuilderTypeCall(Current))
312     State.Stack.back().ContainsUnwrappedBuilder = true;
313
314   if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&
315       (Previous.MatchingParen &&
316        (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10))) {
317     // If there is a function call with long parameters, break before trailing
318     // calls. This prevents things like:
319     //   EXPECT_CALL(SomeLongParameter).Times(
320     //       2);
321     // We don't want to do this for short parameters as they can just be
322     // indexes.
323     State.Stack.back().NoLineBreak = true;
324   }
325
326   State.Column += Spaces;
327   if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&
328       Previous.Previous &&
329       Previous.Previous->isOneOf(tok::kw_if, tok::kw_for)) {
330     // Treat the condition inside an if as if it was a second function
331     // parameter, i.e. let nested calls have a continuation indent.
332     State.Stack.back().LastSpace = State.Column;
333     State.Stack.back().NestedBlockIndent = State.Column;
334   } else if (!Current.isOneOf(tok::comment, tok::caret) &&
335              (Previous.is(tok::comma) ||
336               (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) {
337     State.Stack.back().LastSpace = State.Column;
338   } else if ((Previous.isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
339                                TT_CtorInitializerColon)) &&
340              ((Previous.getPrecedence() != prec::Assignment &&
341                (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||
342                 !Previous.LastOperator)) ||
343               Current.StartsBinaryExpression)) {
344     // Always indent relative to the RHS of the expression unless this is a
345     // simple assignment without binary expression on the RHS. Also indent
346     // relative to unary operators and the colons of constructor initializers.
347     State.Stack.back().LastSpace = State.Column;
348   } else if (Previous.is(TT_InheritanceColon)) {
349     State.Stack.back().Indent = State.Column;
350     State.Stack.back().LastSpace = State.Column;
351   } else if (Previous.opensScope()) {
352     // If a function has a trailing call, indent all parameters from the
353     // opening parenthesis. This avoids confusing indents like:
354     //   OuterFunction(InnerFunctionCall( // break
355     //       ParameterToInnerFunction))   // break
356     //       .SecondInnerFunctionCall();
357     bool HasTrailingCall = false;
358     if (Previous.MatchingParen) {
359       const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
360       HasTrailingCall = Next && Next->isMemberAccess();
361     }
362     if (HasTrailingCall &&
363         State.Stack[State.Stack.size() - 2].CallContinuation == 0)
364       State.Stack.back().LastSpace = State.Column;
365   }
366 }
367
368 unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
369                                                  bool DryRun) {
370   FormatToken &Current = *State.NextToken;
371   const FormatToken &Previous = *State.NextToken->Previous;
372
373   // Extra penalty that needs to be added because of the way certain line
374   // breaks are chosen.
375   unsigned Penalty = 0;
376
377   const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
378   const FormatToken *NextNonComment = Previous.getNextNonComment();
379   if (!NextNonComment)
380     NextNonComment = &Current;
381   // The first line break on any NestingLevel causes an extra penalty in order
382   // prefer similar line breaks.
383   if (!State.Stack.back().ContainsLineBreak)
384     Penalty += 15;
385   State.Stack.back().ContainsLineBreak = true;
386
387   Penalty += State.NextToken->SplitPenalty;
388
389   // Breaking before the first "<<" is generally not desirable if the LHS is
390   // short. Also always add the penalty if the LHS is split over mutliple lines
391   // to avoid unnecessary line breaks that just work around this penalty.
392   if (NextNonComment->is(tok::lessless) &&
393       State.Stack.back().FirstLessLess == 0 &&
394       (State.Column <= Style.ColumnLimit / 3 ||
395        State.Stack.back().BreakBeforeParameter))
396     Penalty += Style.PenaltyBreakFirstLessLess;
397
398   State.Column = getNewLineColumn(State);
399   State.Stack.back().NestedBlockIndent = State.Column;
400   if (NextNonComment->isMemberAccess()) {
401     if (State.Stack.back().CallContinuation == 0)
402       State.Stack.back().CallContinuation = State.Column;
403   } else if (NextNonComment->is(TT_SelectorName)) {
404     if (!State.Stack.back().ObjCSelectorNameFound) {
405       if (NextNonComment->LongestObjCSelectorName == 0) {
406         State.Stack.back().AlignColons = false;
407       } else {
408         State.Stack.back().ColonPos =
409             State.Stack.back().Indent + NextNonComment->LongestObjCSelectorName;
410       }
411     } else if (State.Stack.back().AlignColons &&
412                State.Stack.back().ColonPos <= NextNonComment->ColumnWidth) {
413       State.Stack.back().ColonPos = State.Column + NextNonComment->ColumnWidth;
414     }
415   } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
416              PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
417     // FIXME: This is hacky, find a better way. The problem is that in an ObjC
418     // method expression, the block should be aligned to the line starting it,
419     // e.g.:
420     //   [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
421     //                        ^(int *i) {
422     //                            // ...
423     //                        }];
424     // Thus, we set LastSpace of the next higher NestingLevel, to which we move
425     // when we consume all of the "}"'s FakeRParens at the "{".
426     if (State.Stack.size() > 1)
427       State.Stack[State.Stack.size() - 2].LastSpace =
428           std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
429           Style.ContinuationIndentWidth;
430   }
431
432   if ((Previous.isOneOf(tok::comma, tok::semi) &&
433        !State.Stack.back().AvoidBinPacking) ||
434       Previous.is(TT_BinaryOperator))
435     State.Stack.back().BreakBeforeParameter = false;
436   if (Previous.isOneOf(TT_TemplateCloser, TT_JavaAnnotation) &&
437       Current.NestingLevel == 0)
438     State.Stack.back().BreakBeforeParameter = false;
439   if (NextNonComment->is(tok::question) ||
440       (PreviousNonComment && PreviousNonComment->is(tok::question)))
441     State.Stack.back().BreakBeforeParameter = true;
442
443   if (!DryRun) {
444     unsigned Newlines = std::max(
445         1u, std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1));
446     Whitespaces.replaceWhitespace(Current, Newlines,
447                                   State.Stack.back().IndentLevel, State.Column,
448                                   State.Column, State.Line->InPPDirective);
449   }
450
451   if (!Current.isTrailingComment())
452     State.Stack.back().LastSpace = State.Column;
453   State.StartOfLineLevel = Current.NestingLevel;
454   State.LowestLevelOnLine = Current.NestingLevel;
455
456   // Any break on this level means that the parent level has been broken
457   // and we need to avoid bin packing there.
458   bool NestedBlockSpecialCase =
459       Current.is(tok::r_brace) && State.Stack.size() > 1 &&
460       State.Stack[State.Stack.size() - 2].NestedBlockInlined;
461   if (!NestedBlockSpecialCase) {
462     for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
463       State.Stack[i].BreakBeforeParameter = true;
464     }
465   }
466
467   if (PreviousNonComment &&
468       !PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
469       (PreviousNonComment->isNot(TT_TemplateCloser) ||
470        Current.NestingLevel != 0) &&
471       !PreviousNonComment->isOneOf(TT_BinaryOperator, TT_JavaAnnotation,
472                                    TT_LeadingJavaAnnotation) &&
473       Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope())
474     State.Stack.back().BreakBeforeParameter = true;
475
476   // If we break after { or the [ of an array initializer, we should also break
477   // before the corresponding } or ].
478   if (PreviousNonComment &&
479       (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)))
480     State.Stack.back().BreakBeforeClosingBrace = true;
481
482   if (State.Stack.back().AvoidBinPacking) {
483     // If we are breaking after '(', '{', '<', this is not bin packing
484     // unless AllowAllParametersOfDeclarationOnNextLine is false or this is a
485     // dict/object literal.
486     if (!Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) ||
487         (!Style.AllowAllParametersOfDeclarationOnNextLine &&
488          State.Line->MustBeDeclaration) ||
489         Previous.is(TT_DictLiteral))
490       State.Stack.back().BreakBeforeParameter = true;
491   }
492
493   return Penalty;
494 }
495
496 unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
497   if (!State.NextToken || !State.NextToken->Previous)
498     return 0;
499   FormatToken &Current = *State.NextToken;
500   const FormatToken &Previous = *Current.Previous;
501   // If we are continuing an expression, we want to use the continuation indent.
502   unsigned ContinuationIndent =
503       std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
504       Style.ContinuationIndentWidth;
505   const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
506   const FormatToken *NextNonComment = Previous.getNextNonComment();
507   if (!NextNonComment)
508     NextNonComment = &Current;
509
510   // Java specific bits.
511   if (Style.Language == FormatStyle::LK_Java &&
512       Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends))
513     return std::max(State.Stack.back().LastSpace,
514                     State.Stack.back().Indent + Style.ContinuationIndentWidth);
515
516   if (NextNonComment->is(tok::l_brace) && NextNonComment->BlockKind == BK_Block)
517     return Current.NestingLevel == 0 ? State.FirstIndent
518                                      : State.Stack.back().Indent;
519   if (Current.isOneOf(tok::r_brace, tok::r_square)) {
520     if (Current.closesBlockTypeList(Style))
521       return State.Stack[State.Stack.size() - 2].NestedBlockIndent;
522     if (Current.MatchingParen &&
523         Current.MatchingParen->BlockKind == BK_BracedInit)
524       return State.Stack[State.Stack.size() - 2].LastSpace;
525     return State.FirstIndent;
526   }
527   if (Current.is(tok::identifier) && Current.Next &&
528       Current.Next->is(TT_DictLiteral))
529     return State.Stack.back().Indent;
530   if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
531     return State.StartOfStringLiteral;
532   if (NextNonComment->is(tok::lessless) &&
533       State.Stack.back().FirstLessLess != 0)
534     return State.Stack.back().FirstLessLess;
535   if (NextNonComment->isMemberAccess()) {
536     if (State.Stack.back().CallContinuation == 0)
537       return ContinuationIndent;
538     return State.Stack.back().CallContinuation;
539   }
540   if (State.Stack.back().QuestionColumn != 0 &&
541       ((NextNonComment->is(tok::colon) &&
542         NextNonComment->is(TT_ConditionalExpr)) ||
543        Previous.is(TT_ConditionalExpr)))
544     return State.Stack.back().QuestionColumn;
545   if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0)
546     return State.Stack.back().VariablePos;
547   if ((PreviousNonComment &&
548        (PreviousNonComment->ClosesTemplateDeclaration ||
549         PreviousNonComment->isOneOf(TT_AttributeParen, TT_JavaAnnotation,
550                                     TT_LeadingJavaAnnotation))) ||
551       (!Style.IndentWrappedFunctionNames &&
552        NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName)))
553     return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
554   if (NextNonComment->is(TT_SelectorName)) {
555     if (!State.Stack.back().ObjCSelectorNameFound) {
556       if (NextNonComment->LongestObjCSelectorName == 0)
557         return State.Stack.back().Indent;
558       return State.Stack.back().Indent +
559              NextNonComment->LongestObjCSelectorName -
560              NextNonComment->ColumnWidth;
561     }
562     if (!State.Stack.back().AlignColons)
563       return State.Stack.back().Indent;
564     if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth)
565       return State.Stack.back().ColonPos - NextNonComment->ColumnWidth;
566     return State.Stack.back().Indent;
567   }
568   if (NextNonComment->is(TT_ArraySubscriptLSquare)) {
569     if (State.Stack.back().StartOfArraySubscripts != 0)
570       return State.Stack.back().StartOfArraySubscripts;
571     return ContinuationIndent;
572   }
573   if (NextNonComment->is(TT_StartOfName) ||
574       Previous.isOneOf(tok::coloncolon, tok::equal)) {
575     return ContinuationIndent;
576   }
577   if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
578       PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))
579     return ContinuationIndent;
580   if (NextNonComment->is(TT_CtorInitializerColon))
581     return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
582   if (NextNonComment->is(TT_CtorInitializerComma))
583     return State.Stack.back().Indent;
584   if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() &&
585       !Current.isOneOf(tok::colon, tok::comment))
586     return ContinuationIndent;
587   if (State.Stack.back().Indent == State.FirstIndent && PreviousNonComment &&
588       PreviousNonComment->isNot(tok::r_brace))
589     // Ensure that we fall back to the continuation indent width instead of
590     // just flushing continuations left.
591     return State.Stack.back().Indent + Style.ContinuationIndentWidth;
592   return State.Stack.back().Indent;
593 }
594
595 unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
596                                                     bool DryRun, bool Newline) {
597   assert(State.Stack.size());
598   const FormatToken &Current = *State.NextToken;
599
600   if (Current.is(TT_InheritanceColon))
601     State.Stack.back().AvoidBinPacking = true;
602   if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) {
603     if (State.Stack.back().FirstLessLess == 0)
604       State.Stack.back().FirstLessLess = State.Column;
605     else
606       State.Stack.back().LastOperatorWrapped = Newline;
607   }
608   if ((Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless)) ||
609       Current.is(TT_ConditionalExpr))
610     State.Stack.back().LastOperatorWrapped = Newline;
611   if (Current.is(TT_ArraySubscriptLSquare) &&
612       State.Stack.back().StartOfArraySubscripts == 0)
613     State.Stack.back().StartOfArraySubscripts = State.Column;
614   if ((Current.is(tok::question) && Style.BreakBeforeTernaryOperators) ||
615       (Current.getPreviousNonComment() && Current.isNot(tok::colon) &&
616        Current.getPreviousNonComment()->is(tok::question) &&
617        !Style.BreakBeforeTernaryOperators))
618     State.Stack.back().QuestionColumn = State.Column;
619   if (!Current.opensScope() && !Current.closesScope())
620     State.LowestLevelOnLine =
621         std::min(State.LowestLevelOnLine, Current.NestingLevel);
622   if (Current.isMemberAccess())
623     State.Stack.back().StartOfFunctionCall =
624         Current.LastOperator ? 0 : State.Column + Current.ColumnWidth;
625   if (Current.is(TT_SelectorName))
626     State.Stack.back().ObjCSelectorNameFound = true;
627   if (Current.is(TT_CtorInitializerColon)) {
628     // Indent 2 from the column, so:
629     // SomeClass::SomeClass()
630     //     : First(...), ...
631     //       Next(...)
632     //       ^ line up here.
633     State.Stack.back().Indent =
634         State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
635     State.Stack.back().NestedBlockIndent = State.Stack.back().Indent;
636     if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
637       State.Stack.back().AvoidBinPacking = true;
638     State.Stack.back().BreakBeforeParameter = false;
639   }
640
641   // In ObjC method declaration we align on the ":" of parameters, but we need
642   // to ensure that we indent parameters on subsequent lines by at least our
643   // continuation indent width.
644   if (Current.is(TT_ObjCMethodSpecifier))
645     State.Stack.back().Indent += Style.ContinuationIndentWidth;
646
647   // Insert scopes created by fake parenthesis.
648   const FormatToken *Previous = Current.getPreviousNonComment();
649
650   // Add special behavior to support a format commonly used for JavaScript
651   // closures:
652   //   SomeFunction(function() {
653   //     foo();
654   //     bar();
655   //   }, a, b, c);
656   if (Current.isNot(tok::comment) && Previous && Previous->is(tok::l_brace) &&
657       State.Stack.size() > 1) {
658     if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline) {
659       for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
660         State.Stack[i].NoLineBreak = true;
661       }
662     }
663     State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;
664   }
665   if (Previous && (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) ||
666                    Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr)) &&
667       !Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
668     State.Stack.back().NestedBlockInlined =
669         !Newline &&
670         (Previous->isNot(tok::l_paren) || Previous->ParameterCount > 1);
671   }
672
673   moveStatePastFakeLParens(State, Newline);
674   moveStatePastScopeOpener(State, Newline);
675   moveStatePastScopeCloser(State);
676   moveStatePastFakeRParens(State);
677
678   if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) {
679     State.StartOfStringLiteral = State.Column;
680   } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
681              !Current.isStringLiteral()) {
682     State.StartOfStringLiteral = 0;
683   }
684
685   State.Column += Current.ColumnWidth;
686   State.NextToken = State.NextToken->Next;
687   unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
688   if (State.Column > getColumnLimit(State)) {
689     unsigned ExcessCharacters = State.Column - getColumnLimit(State);
690     Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
691   }
692
693   if (Current.Role)
694     Current.Role->formatFromToken(State, this, DryRun);
695   // If the previous has a special role, let it consume tokens as appropriate.
696   // It is necessary to start at the previous token for the only implemented
697   // role (comma separated list). That way, the decision whether or not to break
698   // after the "{" is already done and both options are tried and evaluated.
699   // FIXME: This is ugly, find a better way.
700   if (Previous && Previous->Role)
701     Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
702
703   return Penalty;
704 }
705
706 void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
707                                                     bool Newline) {
708   const FormatToken &Current = *State.NextToken;
709   const FormatToken *Previous = Current.getPreviousNonComment();
710
711   // Don't add extra indentation for the first fake parenthesis after
712   // 'return', assignments or opening <({[. The indentation for these cases
713   // is special cased.
714   bool SkipFirstExtraIndent =
715       (Previous && (Previous->opensScope() || Previous->is(tok::kw_return) ||
716                     (Previous->getPrecedence() == prec::Assignment &&
717                      Style.AlignOperands) ||
718                     Previous->is(TT_ObjCMethodExpr)));
719   for (SmallVectorImpl<prec::Level>::const_reverse_iterator
720            I = Current.FakeLParens.rbegin(),
721            E = Current.FakeLParens.rend();
722        I != E; ++I) {
723     ParenState NewParenState = State.Stack.back();
724     NewParenState.ContainsLineBreak = false;
725
726     // Indent from 'LastSpace' unless these are fake parentheses encapsulating
727     // a builder type call after 'return' or, if the alignment after opening
728     // brackets is disabled.
729     if (!Current.isTrailingComment() &&
730         (Style.AlignOperands || *I < prec::Assignment) &&
731         (!Previous || Previous->isNot(tok::kw_return) ||
732          (Style.Language != FormatStyle::LK_Java && *I > 0)) &&
733         (Style.AlignAfterOpenBracket || *I != prec::Comma ||
734          Current.NestingLevel == 0))
735       NewParenState.Indent =
736           std::max(std::max(State.Column, NewParenState.Indent),
737                    State.Stack.back().LastSpace);
738
739     // Don't allow the RHS of an operator to be split over multiple lines unless
740     // there is a line-break right after the operator.
741     // Exclude relational operators, as there, it is always more desirable to
742     // have the LHS 'left' of the RHS.
743     if (Previous && Previous->getPrecedence() > prec::Assignment &&
744         Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
745         Previous->getPrecedence() != prec::Relational) {
746       bool BreakBeforeOperator =
747           Previous->is(tok::lessless) ||
748           (Previous->is(TT_BinaryOperator) &&
749            Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) ||
750           (Previous->is(TT_ConditionalExpr) &&
751            Style.BreakBeforeTernaryOperators);
752       if ((!Newline && !BreakBeforeOperator) ||
753           (!State.Stack.back().LastOperatorWrapped && BreakBeforeOperator))
754         NewParenState.NoLineBreak = true;
755     }
756
757     // Do not indent relative to the fake parentheses inserted for "." or "->".
758     // This is a special case to make the following to statements consistent:
759     //   OuterFunction(InnerFunctionCall( // break
760     //       ParameterToInnerFunction));
761     //   OuterFunction(SomeObject.InnerFunctionCall( // break
762     //       ParameterToInnerFunction));
763     if (*I > prec::Unknown)
764       NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
765     if (*I != prec::Conditional)
766       NewParenState.StartOfFunctionCall = State.Column;
767
768     // Always indent conditional expressions. Never indent expression where
769     // the 'operator' is ',', ';' or an assignment (i.e. *I <=
770     // prec::Assignment) as those have different indentation rules. Indent
771     // other expression, unless the indentation needs to be skipped.
772     if (*I == prec::Conditional ||
773         (!SkipFirstExtraIndent && *I > prec::Assignment &&
774          !Current.isTrailingComment()))
775       NewParenState.Indent += Style.ContinuationIndentWidth;
776     if ((Previous && !Previous->opensScope()) || *I > prec::Comma)
777       NewParenState.BreakBeforeParameter = false;
778     State.Stack.push_back(NewParenState);
779     SkipFirstExtraIndent = false;
780   }
781 }
782
783 void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
784   for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) {
785     unsigned VariablePos = State.Stack.back().VariablePos;
786     assert(State.Stack.size() > 1);
787     if (State.Stack.size() == 1) {
788       // Do not pop the last element.
789       break;
790     }
791     State.Stack.pop_back();
792     State.Stack.back().VariablePos = VariablePos;
793   }
794 }
795
796 void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
797                                                     bool Newline) {
798   const FormatToken &Current = *State.NextToken;
799   if (!Current.opensScope())
800     return;
801
802   if (Current.MatchingParen && Current.BlockKind == BK_Block) {
803     moveStateToNewBlock(State);
804     return;
805   }
806
807   unsigned NewIndent;
808   unsigned NewIndentLevel = State.Stack.back().IndentLevel;
809   bool AvoidBinPacking;
810   bool BreakBeforeParameter = false;
811   if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)) {
812     if (Current.opensBlockTypeList(Style)) {
813       NewIndent = State.Stack.back().NestedBlockIndent + Style.IndentWidth;
814       NewIndent = std::min(State.Column + 2, NewIndent);
815       ++NewIndentLevel;
816     } else {
817       NewIndent = State.Stack.back().LastSpace + Style.ContinuationIndentWidth;
818       NewIndent = std::min(State.Column + 1, NewIndent);
819     }
820     const FormatToken *NextNoComment = Current.getNextNonComment();
821     AvoidBinPacking =
822         Current.isOneOf(TT_ArrayInitializerLSquare, TT_DictLiteral) ||
823         Style.Language == FormatStyle::LK_Proto || !Style.BinPackParameters ||
824         (NextNoComment && NextNoComment->is(TT_DesignatedInitializerPeriod));
825   } else {
826     NewIndent = Style.ContinuationIndentWidth +
827                 std::max(State.Stack.back().LastSpace,
828                          State.Stack.back().StartOfFunctionCall);
829     AvoidBinPacking =
830         (State.Line->MustBeDeclaration && !Style.BinPackParameters) ||
831         (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||
832         (Style.ExperimentalAutoDetectBinPacking &&
833          (Current.PackingKind == PPK_OnePerLine ||
834           (!BinPackInconclusiveFunctions &&
835            Current.PackingKind == PPK_Inconclusive)));
836     // If this '[' opens an ObjC call, determine whether all parameters fit
837     // into one line and put one per line if they don't.
838     if (Current.is(TT_ObjCMethodExpr) && Style.ColumnLimit != 0 &&
839         getLengthToMatchingParen(Current) + State.Column >
840             getColumnLimit(State))
841       BreakBeforeParameter = true;
842   }
843   bool NoLineBreak = State.Stack.back().NoLineBreak ||
844                      (Current.is(TT_TemplateOpener) &&
845                       State.Stack.back().ContainsUnwrappedBuilder);
846   unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
847   State.Stack.push_back(ParenState(NewIndent, NewIndentLevel,
848                                    State.Stack.back().LastSpace,
849                                    AvoidBinPacking, NoLineBreak));
850   State.Stack.back().NestedBlockIndent = NestedBlockIndent;
851   State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
852   State.Stack.back().HasMultipleNestedBlocks = Current.BlockParameterCount > 1;
853 }
854
855 void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
856   const FormatToken &Current = *State.NextToken;
857   if (!Current.closesScope())
858     return;
859
860   // If we encounter a closing ), ], } or >, we can remove a level from our
861   // stacks.
862   if (State.Stack.size() > 1 &&
863       (Current.isOneOf(tok::r_paren, tok::r_square) ||
864        (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
865        State.NextToken->is(TT_TemplateCloser)))
866     State.Stack.pop_back();
867
868   if (Current.is(tok::r_square)) {
869     // If this ends the array subscript expr, reset the corresponding value.
870     const FormatToken *NextNonComment = Current.getNextNonComment();
871     if (NextNonComment && NextNonComment->isNot(tok::l_square))
872       State.Stack.back().StartOfArraySubscripts = 0;
873   }
874 }
875
876 void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
877   unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
878   // ObjC block sometimes follow special indentation rules.
879   unsigned NewIndent =
880       NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace)
881                                ? Style.ObjCBlockIndentWidth
882                                : Style.IndentWidth);
883   State.Stack.push_back(ParenState(
884       NewIndent, /*NewIndentLevel=*/State.Stack.back().IndentLevel + 1,
885       State.Stack.back().LastSpace, /*AvoidBinPacking=*/true,
886       State.Stack.back().NoLineBreak));
887   State.Stack.back().NestedBlockIndent = NestedBlockIndent;
888   State.Stack.back().BreakBeforeParameter = true;
889 }
890
891 unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
892                                                  LineState &State) {
893   // Break before further function parameters on all levels.
894   for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
895     State.Stack[i].BreakBeforeParameter = true;
896
897   unsigned ColumnsUsed = State.Column;
898   // We can only affect layout of the first and the last line, so the penalty
899   // for all other lines is constant, and we ignore it.
900   State.Column = Current.LastLineColumnWidth;
901
902   if (ColumnsUsed > getColumnLimit(State))
903     return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
904   return 0;
905 }
906
907 unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
908                                                     LineState &State,
909                                                     bool DryRun) {
910   // Don't break multi-line tokens other than block comments. Instead, just
911   // update the state.
912   if (Current.isNot(TT_BlockComment) && Current.IsMultiline)
913     return addMultilineToken(Current, State);
914
915   // Don't break implicit string literals or import statements.
916   if (Current.is(TT_ImplicitStringLiteral) ||
917       State.Line->Type == LT_ImportStatement)
918     return 0;
919
920   if (!Current.isStringLiteral() && !Current.is(tok::comment))
921     return 0;
922
923   std::unique_ptr<BreakableToken> Token;
924   unsigned StartColumn = State.Column - Current.ColumnWidth;
925   unsigned ColumnLimit = getColumnLimit(State);
926
927   if (Current.isStringLiteral()) {
928     // FIXME: String literal breaking is currently disabled for Java and JS, as
929     // it requires strings to be merged using "+" which we don't support.
930     if (Style.Language == FormatStyle::LK_Java ||
931         Style.Language == FormatStyle::LK_JavaScript)
932       return 0;
933
934     // Don't break string literals inside preprocessor directives (except for
935     // #define directives, as their contents are stored in separate lines and
936     // are not affected by this check).
937     // This way we avoid breaking code with line directives and unknown
938     // preprocessor directives that contain long string literals.
939     if (State.Line->Type == LT_PreprocessorDirective)
940       return 0;
941     // Exempts unterminated string literals from line breaking. The user will
942     // likely want to terminate the string before any line breaking is done.
943     if (Current.IsUnterminatedLiteral)
944       return 0;
945
946     StringRef Text = Current.TokenText;
947     StringRef Prefix;
948     StringRef Postfix;
949     bool IsNSStringLiteral = false;
950     // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
951     // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
952     // reduce the overhead) for each FormatToken, which is a string, so that we
953     // don't run multiple checks here on the hot path.
954     if (Text.startswith("\"") && Current.Previous &&
955         Current.Previous->is(tok::at)) {
956       IsNSStringLiteral = true;
957       Prefix = "@\"";
958     }
959     if ((Text.endswith(Postfix = "\"") &&
960          (IsNSStringLiteral || Text.startswith(Prefix = "\"") ||
961           Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
962           Text.startswith(Prefix = "u8\"") ||
963           Text.startswith(Prefix = "L\""))) ||
964         (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) {
965       Token.reset(new BreakableStringLiteral(
966           Current, State.Line->Level, StartColumn, Prefix, Postfix,
967           State.Line->InPPDirective, Encoding, Style));
968     } else {
969       return 0;
970     }
971   } else if (Current.is(TT_BlockComment) && Current.isTrailingComment()) {
972     if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
973       return 0;
974     Token.reset(new BreakableBlockComment(
975         Current, State.Line->Level, StartColumn, Current.OriginalColumn,
976         !Current.Previous, State.Line->InPPDirective, Encoding, Style));
977   } else if (Current.is(TT_LineComment) &&
978              (Current.Previous == nullptr ||
979               Current.Previous->isNot(TT_ImplicitStringLiteral))) {
980     if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
981       return 0;
982     Token.reset(new BreakableLineComment(Current, State.Line->Level,
983                                          StartColumn, /*InPPDirective=*/false,
984                                          Encoding, Style));
985     // We don't insert backslashes when breaking line comments.
986     ColumnLimit = Style.ColumnLimit;
987   } else {
988     return 0;
989   }
990   if (Current.UnbreakableTailLength >= ColumnLimit)
991     return 0;
992
993   unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength;
994   bool BreakInserted = false;
995   unsigned Penalty = 0;
996   unsigned RemainingTokenColumns = 0;
997   for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
998        LineIndex != EndIndex; ++LineIndex) {
999     if (!DryRun)
1000       Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
1001     unsigned TailOffset = 0;
1002     RemainingTokenColumns =
1003         Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
1004     while (RemainingTokenColumns > RemainingSpace) {
1005       BreakableToken::Split Split =
1006           Token->getSplit(LineIndex, TailOffset, ColumnLimit);
1007       if (Split.first == StringRef::npos) {
1008         // The last line's penalty is handled in addNextStateToQueue().
1009         if (LineIndex < EndIndex - 1)
1010           Penalty += Style.PenaltyExcessCharacter *
1011                      (RemainingTokenColumns - RemainingSpace);
1012         break;
1013       }
1014       assert(Split.first != 0);
1015       unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
1016           LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
1017
1018       // We can remove extra whitespace instead of breaking the line.
1019       if (RemainingTokenColumns + 1 - Split.second <= RemainingSpace) {
1020         RemainingTokenColumns = 0;
1021         if (!DryRun)
1022           Token->replaceWhitespace(LineIndex, TailOffset, Split, Whitespaces);
1023         break;
1024       }
1025
1026       // When breaking before a tab character, it may be moved by a few columns,
1027       // but will still be expanded to the next tab stop, so we don't save any
1028       // columns.
1029       if (NewRemainingTokenColumns == RemainingTokenColumns)
1030         break;
1031
1032       assert(NewRemainingTokenColumns < RemainingTokenColumns);
1033       if (!DryRun)
1034         Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
1035       Penalty += Current.SplitPenalty;
1036       unsigned ColumnsUsed =
1037           Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
1038       if (ColumnsUsed > ColumnLimit) {
1039         Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit);
1040       }
1041       TailOffset += Split.first + Split.second;
1042       RemainingTokenColumns = NewRemainingTokenColumns;
1043       BreakInserted = true;
1044     }
1045   }
1046
1047   State.Column = RemainingTokenColumns;
1048
1049   if (BreakInserted) {
1050     // If we break the token inside a parameter list, we need to break before
1051     // the next parameter on all levels, so that the next parameter is clearly
1052     // visible. Line comments already introduce a break.
1053     if (Current.isNot(TT_LineComment)) {
1054       for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1055         State.Stack[i].BreakBeforeParameter = true;
1056     }
1057
1058     Penalty += Current.isStringLiteral() ? Style.PenaltyBreakString
1059                                          : Style.PenaltyBreakComment;
1060
1061     State.Stack.back().LastSpace = StartColumn;
1062   }
1063   return Penalty;
1064 }
1065
1066 unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
1067   // In preprocessor directives reserve two chars for trailing " \"
1068   return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
1069 }
1070
1071 bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
1072   const FormatToken &Current = *State.NextToken;
1073   if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral))
1074     return false;
1075   // We never consider raw string literals "multiline" for the purpose of
1076   // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
1077   // (see TokenAnnotator::mustBreakBefore().
1078   if (Current.TokenText.startswith("R\""))
1079     return false;
1080   if (Current.IsMultiline)
1081     return true;
1082   if (Current.getNextNonComment() &&
1083       Current.getNextNonComment()->isStringLiteral())
1084     return true; // Implicit concatenation.
1085   if (State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
1086       Style.ColumnLimit)
1087     return true; // String will be split.
1088   return false;
1089 }
1090
1091 } // namespace format
1092 } // namespace clang