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