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 #define DEBUG_TYPE "format-formatter"
16 
17 #include "BreakableToken.h"
18 #include "ContinuationIndenter.h"
19 #include "WhitespaceManager.h"
20 #include "clang/Basic/OperatorPrecedence.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Format/Format.h"
23 #include "llvm/Support/Debug.h"
24 #include <string>
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 == NULL)
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.Type == TT_CtorInitializerComma &&
52       Style.BreakConstructorInitializersBeforeComma)
53     return true;
54   return Previous.is(tok::comma) && !Current.isTrailingComment() &&
55          (Previous.Type != TT_CtorInitializerComma ||
56           !Style.BreakConstructorInitializersBeforeComma);
57 }
58 
59 ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,
60                                            SourceManager &SourceMgr,
61                                            WhitespaceManager &Whitespaces,
62                                            encoding::Encoding Encoding,
63                                            bool BinPackInconclusiveFunctions)
64     : Style(Style), SourceMgr(SourceMgr), Whitespaces(Whitespaces),
65       Encoding(Encoding),
66       BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
67       CommentPragmasRegex(Style.CommentPragmas) {}
68 
69 LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
70                                                 const AnnotatedLine *Line,
71                                                 bool DryRun) {
72   LineState State;
73   State.FirstIndent = FirstIndent;
74   State.Column = FirstIndent;
75   State.Line = Line;
76   State.NextToken = Line->First;
77   State.Stack.push_back(ParenState(FirstIndent, Line->Level, FirstIndent,
78                                    /*AvoidBinPacking=*/false,
79                                    /*NoLineBreak=*/false));
80   State.LineContainsContinuedForLoopSection = false;
81   State.ParenLevel = 0;
82   State.StartOfStringLiteral = 0;
83   State.StartOfLineLevel = State.ParenLevel;
84   State.LowestLevelOnLine = State.ParenLevel;
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 && !(State.Stack.back().BreakBeforeClosingBrace &&
97                                    Current.closesBlockTypeList(Style)))
98     return false;
99   // The opening "{" of a braced list has to be on the same line as the first
100   // element if it is nested in another braced init list or function call.
101   if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
102       Previous.Type != TT_DictLiteral &&
103       Previous.BlockKind == BK_BracedInit && Previous.Previous &&
104       Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
105     return false;
106   // This prevents breaks like:
107   //   ...
108   //   SomeParameter, OtherParameter).DoSomething(
109   //   ...
110   // As they hide "DoSomething" and are generally bad for readability.
111   if (Previous.opensScope() && State.LowestLevelOnLine < State.StartOfLineLevel)
112     return false;
113   if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
114     return false;
115   return !State.Stack.back().NoLineBreak;
116 }
117 
118 bool ContinuationIndenter::mustBreak(const LineState &State) {
119   const FormatToken &Current = *State.NextToken;
120   const FormatToken &Previous = *Current.Previous;
121   if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
122     return true;
123   if (State.Stack.back().BreakBeforeClosingBrace &&
124       Current.closesBlockTypeList(Style))
125     return true;
126   if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
127     return true;
128   if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
129        (Style.BreakBeforeTernaryOperators &&
130         (Current.is(tok::question) || (Current.Type == TT_ConditionalExpr &&
131                                        Previous.isNot(tok::question)))) ||
132        (!Style.BreakBeforeTernaryOperators &&
133         (Previous.is(tok::question) || Previous.Type == TT_ConditionalExpr))) &&
134       State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
135       !Current.isOneOf(tok::r_paren, tok::r_brace))
136     return true;
137   if (Style.AlwaysBreakBeforeMultilineStrings &&
138       State.Column > State.Stack.back().Indent && // Breaking saves columns.
139       !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) &&
140       Previous.Type != TT_InlineASMColon && nextIsMultilineString(State))
141     return true;
142   if (((Previous.Type == TT_DictLiteral && Previous.is(tok::l_brace)) ||
143        Previous.Type == TT_ArrayInitializerLSquare) &&
144       getLengthToMatchingParen(Previous) + State.Column > getColumnLimit(State))
145     return true;
146 
147   if (!Style.BreakBeforeBinaryOperators) {
148     // If we need to break somewhere inside the LHS of a binary expression, we
149     // should also break after the operator. Otherwise, the formatting would
150     // hide the operator precedence, e.g. in:
151     //   if (aaaaaaaaaaaaaa ==
152     //           bbbbbbbbbbbbbb && c) {..
153     // For comparisons, we only apply this rule, if the LHS is a binary
154     // expression itself as otherwise, the line breaks seem superfluous.
155     // We need special cases for ">>" which we have split into two ">" while
156     // lexing in order to make template parsing easier.
157     //
158     // FIXME: We'll need something similar for styles that break before binary
159     // operators.
160     bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
161                          Previous.getPrecedence() == prec::Equality) &&
162                         Previous.Previous &&
163                         Previous.Previous->Type != TT_BinaryOperator; // For >>.
164     bool LHSIsBinaryExpr =
165         Previous.Previous && Previous.Previous->EndsBinaryExpression;
166     if (Previous.Type == TT_BinaryOperator &&
167         (!IsComparison || LHSIsBinaryExpr) &&
168         Current.Type != TT_BinaryOperator && // For >>.
169         !Current.isTrailingComment() &&
170         !Previous.isOneOf(tok::lessless, tok::question) &&
171         Previous.getPrecedence() != prec::Assignment &&
172         State.Stack.back().BreakBeforeParameter)
173       return true;
174   }
175 
176   // Same as above, but for the first "<<" operator.
177   if (Current.is(tok::lessless) && State.Stack.back().BreakBeforeParameter &&
178       State.Stack.back().FirstLessLess == 0)
179     return true;
180 
181   if (Current.Type == TT_ObjCSelectorName &&
182       State.Stack.back().ObjCSelectorNameFound &&
183       State.Stack.back().BreakBeforeParameter)
184     return true;
185   if (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0 &&
186       !Current.isTrailingComment())
187     return true;
188 
189   if ((Current.Type == TT_StartOfName || Current.is(tok::kw_operator)) &&
190       State.Line->MightBeFunctionDecl &&
191       State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
192     return true;
193   if (startsSegmentOfBuilderTypeCall(Current) &&
194       (State.Stack.back().CallContinuation != 0 ||
195        (State.Stack.back().BreakBeforeParameter &&
196         State.Stack.back().ContainsUnwrappedBuilder)))
197     return true;
198 
199   // The following could be precomputed as they do not depend on the state.
200   // However, as they should take effect only if the UnwrappedLine does not fit
201   // into the ColumnLimit, they are checked here in the ContinuationIndenter.
202   if (Previous.BlockKind == BK_Block && Previous.is(tok::l_brace) &&
203       !Current.isOneOf(tok::r_brace, tok::comment))
204     return true;
205   if (Current.Type == TT_CtorInitializerColon &&
206       (!Style.AllowShortFunctionsOnASingleLine ||
207        Style.BreakConstructorInitializersBeforeComma || Style.ColumnLimit != 0))
208     return true;
209 
210   return false;
211 }
212 
213 unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
214                                                bool DryRun,
215                                                unsigned ExtraSpaces) {
216   const FormatToken &Current = *State.NextToken;
217 
218   if (State.Stack.size() == 0 ||
219       (Current.Type == TT_ImplicitStringLiteral &&
220        (Current.Previous->Tok.getIdentifierInfo() == NULL ||
221         Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
222             tok::pp_not_keyword))) {
223     // FIXME: Is this correct?
224     int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
225                                State.NextToken->WhitespaceRange.getEnd()) -
226                            SourceMgr.getSpellingColumnNumber(
227                                State.NextToken->WhitespaceRange.getBegin());
228     State.Column += WhitespaceLength + State.NextToken->ColumnWidth;
229     State.NextToken = State.NextToken->Next;
230     return 0;
231   }
232 
233   unsigned Penalty = 0;
234   if (Newline)
235     Penalty = addTokenOnNewLine(State, DryRun);
236   else
237     addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
238 
239   return moveStateToNextToken(State, DryRun, Newline) + Penalty;
240 }
241 
242 void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
243                                                  unsigned ExtraSpaces) {
244   FormatToken &Current = *State.NextToken;
245   const FormatToken &Previous = *State.NextToken->Previous;
246   if (Current.is(tok::equal) &&
247       (State.Line->First->is(tok::kw_for) || State.ParenLevel == 0) &&
248       State.Stack.back().VariablePos == 0) {
249     State.Stack.back().VariablePos = State.Column;
250     // Move over * and & if they are bound to the variable name.
251     const FormatToken *Tok = &Previous;
252     while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
253       State.Stack.back().VariablePos -= Tok->ColumnWidth;
254       if (Tok->SpacesRequiredBefore != 0)
255         break;
256       Tok = Tok->Previous;
257     }
258     if (Previous.PartOfMultiVariableDeclStmt)
259       State.Stack.back().LastSpace = State.Stack.back().VariablePos;
260   }
261 
262   unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
263 
264   if (!DryRun)
265     Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, /*IndentLevel=*/0,
266                                   Spaces, State.Column + Spaces);
267 
268   if (Current.Type == TT_ObjCSelectorName &&
269       !State.Stack.back().ObjCSelectorNameFound) {
270     if (Current.LongestObjCSelectorName == 0)
271       State.Stack.back().AlignColons = false;
272     else if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
273              State.Column + Spaces + Current.ColumnWidth)
274       State.Stack.back().ColonPos =
275           State.Stack.back().Indent + Current.LongestObjCSelectorName;
276     else
277       State.Stack.back().ColonPos = State.Column + Spaces + Current.ColumnWidth;
278   }
279 
280   if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
281       (Current.Type != TT_LineComment || Previous.BlockKind == BK_BracedInit))
282     State.Stack.back().Indent = State.Column + Spaces;
283   if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
284     State.Stack.back().NoLineBreak = true;
285   if (startsSegmentOfBuilderTypeCall(Current))
286     State.Stack.back().ContainsUnwrappedBuilder = true;
287 
288   State.Column += Spaces;
289   if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
290     // Treat the condition inside an if as if it was a second function
291     // parameter, i.e. let nested calls have a continuation indent.
292     State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
293   else if (Current.isNot(tok::comment) &&
294            (Previous.is(tok::comma) ||
295             (Previous.is(tok::colon) && Previous.Type == TT_ObjCMethodExpr)))
296     State.Stack.back().LastSpace = State.Column;
297   else if ((Previous.Type == TT_BinaryOperator ||
298             Previous.Type == TT_ConditionalExpr ||
299             Previous.Type == TT_UnaryOperator ||
300             Previous.Type == TT_CtorInitializerColon) &&
301            (Previous.getPrecedence() != prec::Assignment ||
302             Current.StartsBinaryExpression))
303     // Always indent relative to the RHS of the expression unless this is a
304     // simple assignment without binary expression on the RHS. Also indent
305     // relative to unary operators and the colons of constructor initializers.
306     State.Stack.back().LastSpace = State.Column;
307   else if (Previous.Type == TT_InheritanceColon) {
308     State.Stack.back().Indent = State.Column;
309     State.Stack.back().LastSpace = State.Column;
310   } else if (Previous.opensScope()) {
311     // If a function has a trailing call, indent all parameters from the
312     // opening parenthesis. This avoids confusing indents like:
313     //   OuterFunction(InnerFunctionCall( // break
314     //       ParameterToInnerFunction))   // break
315     //       .SecondInnerFunctionCall();
316     bool HasTrailingCall = false;
317     if (Previous.MatchingParen) {
318       const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
319       HasTrailingCall = Next && Next->isMemberAccess();
320     }
321     if (HasTrailingCall &&
322         State.Stack[State.Stack.size() - 2].CallContinuation == 0)
323       State.Stack.back().LastSpace = State.Column;
324   }
325 }
326 
327 unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
328                                                  bool DryRun) {
329   FormatToken &Current = *State.NextToken;
330   const FormatToken &Previous = *State.NextToken->Previous;
331   // If we are continuing an expression, we want to use the continuation indent.
332   unsigned ContinuationIndent =
333       std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
334       Style.ContinuationIndentWidth;
335   // Extra penalty that needs to be added because of the way certain line
336   // breaks are chosen.
337   unsigned Penalty = 0;
338 
339   const FormatToken *PreviousNonComment =
340       State.NextToken->getPreviousNonComment();
341   // The first line break on any ParenLevel causes an extra penalty in order
342   // prefer similar line breaks.
343   if (!State.Stack.back().ContainsLineBreak)
344     Penalty += 15;
345   State.Stack.back().ContainsLineBreak = true;
346 
347   Penalty += State.NextToken->SplitPenalty;
348 
349   // Breaking before the first "<<" is generally not desirable if the LHS is
350   // short. Also always add the penalty if the LHS is split over mutliple lines
351   // to avoid unncessary line breaks that just work around this penalty.
352   if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0 &&
353       (State.Column <= Style.ColumnLimit / 3 ||
354        State.Stack.back().BreakBeforeParameter))
355     Penalty += Style.PenaltyBreakFirstLessLess;
356 
357   if (Current.is(tok::l_brace) && Current.BlockKind == BK_Block) {
358     State.Column =
359         State.ParenLevel == 0 ? State.FirstIndent : State.Stack.back().Indent;
360   } else if (Current.isOneOf(tok::r_brace, tok::r_square)) {
361     if (Current.closesBlockTypeList(Style) ||
362         (Current.MatchingParen &&
363          Current.MatchingParen->BlockKind == BK_BracedInit))
364       State.Column = State.Stack[State.Stack.size() - 2].LastSpace;
365     else
366       State.Column = State.FirstIndent;
367   } else if (Current.isStringLiteral() && State.StartOfStringLiteral != 0) {
368     State.Column = State.StartOfStringLiteral;
369     State.Stack.back().BreakBeforeParameter = true;
370   } else if (Current.is(tok::lessless) &&
371              State.Stack.back().FirstLessLess != 0) {
372     State.Column = State.Stack.back().FirstLessLess;
373   } else if (Current.isMemberAccess()) {
374     if (State.Stack.back().CallContinuation == 0) {
375       State.Column = ContinuationIndent;
376       State.Stack.back().CallContinuation = State.Column;
377     } else {
378       State.Column = State.Stack.back().CallContinuation;
379     }
380   } else if (State.Stack.back().QuestionColumn != 0 &&
381              (Current.Type == TT_ConditionalExpr ||
382               Previous.Type == TT_ConditionalExpr)) {
383     State.Column = State.Stack.back().QuestionColumn;
384   } else if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0) {
385     State.Column = State.Stack.back().VariablePos;
386   } else if ((PreviousNonComment &&
387               PreviousNonComment->ClosesTemplateDeclaration) ||
388              ((Current.Type == TT_StartOfName ||
389                Current.is(tok::kw_operator)) &&
390               State.ParenLevel == 0 &&
391               (!Style.IndentFunctionDeclarationAfterType ||
392                State.Line->StartsDefinition))) {
393     State.Column =
394         std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
395   } else if (Current.Type == TT_ObjCSelectorName) {
396     if (!State.Stack.back().ObjCSelectorNameFound) {
397       if (Current.LongestObjCSelectorName == 0) {
398         State.Column = State.Stack.back().Indent;
399         State.Stack.back().AlignColons = false;
400       } else {
401         State.Stack.back().ColonPos =
402             State.Stack.back().Indent + Current.LongestObjCSelectorName;
403         State.Column = State.Stack.back().ColonPos - Current.ColumnWidth;
404       }
405     } else if (!State.Stack.back().AlignColons) {
406       State.Column = State.Stack.back().Indent;
407     } else if (State.Stack.back().ColonPos > Current.ColumnWidth) {
408       State.Column = State.Stack.back().ColonPos - Current.ColumnWidth;
409     } else {
410       State.Column = State.Stack.back().Indent;
411       State.Stack.back().ColonPos = State.Column + Current.ColumnWidth;
412     }
413   } else if (Current.Type == TT_ArraySubscriptLSquare) {
414     if (State.Stack.back().StartOfArraySubscripts != 0)
415       State.Column = State.Stack.back().StartOfArraySubscripts;
416     else
417       State.Column = ContinuationIndent;
418   } else if (Current.Type == TT_StartOfName ||
419              Previous.isOneOf(tok::coloncolon, tok::equal)) {
420     State.Column = ContinuationIndent;
421   } else if (PreviousNonComment &&
422              PreviousNonComment->Type == TT_ObjCMethodExpr) {
423     State.Column = ContinuationIndent;
424     // FIXME: This is hacky, find a better way. The problem is that in an ObjC
425     // method expression, the block should be aligned to the line starting it,
426     // e.g.:
427     //   [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
428     //                        ^(int *i) {
429     //                            // ...
430     //                        }];
431     // Thus, we set LastSpace of the next higher ParenLevel, to which we move
432     // when we consume all of the "}"'s FakeRParens at the "{".
433     if (State.Stack.size() > 1)
434       State.Stack[State.Stack.size() - 2].LastSpace = ContinuationIndent;
435   } else if (Current.Type == TT_CtorInitializerColon) {
436     State.Column = State.FirstIndent + Style.ConstructorInitializerIndentWidth;
437   } else if (Current.Type == TT_CtorInitializerComma) {
438     State.Column = State.Stack.back().Indent;
439   } else {
440     State.Column = State.Stack.back().Indent;
441     // Ensure that we fall back to the continuation indent width instead of just
442     // flushing continuations left.
443     if (State.Column == State.FirstIndent &&
444         PreviousNonComment->isNot(tok::r_brace))
445       State.Column += Style.ContinuationIndentWidth;
446   }
447 
448   if ((Previous.isOneOf(tok::comma, tok::semi) &&
449        !State.Stack.back().AvoidBinPacking) ||
450       Previous.Type == TT_BinaryOperator)
451     State.Stack.back().BreakBeforeParameter = false;
452   if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
453     State.Stack.back().BreakBeforeParameter = false;
454   if (Current.is(tok::question) ||
455       (PreviousNonComment && PreviousNonComment->is(tok::question)))
456     State.Stack.back().BreakBeforeParameter = true;
457 
458   if (!DryRun) {
459     unsigned Newlines = 1;
460     if (Current.is(tok::comment))
461       Newlines = std::max(Newlines, std::min(Current.NewlinesBefore,
462                                              Style.MaxEmptyLinesToKeep + 1));
463     Whitespaces.replaceWhitespace(Current, Newlines,
464                                   State.Stack.back().IndentLevel, State.Column,
465                                   State.Column, State.Line->InPPDirective);
466   }
467 
468   if (!Current.isTrailingComment())
469     State.Stack.back().LastSpace = State.Column;
470   State.StartOfLineLevel = State.ParenLevel;
471   State.LowestLevelOnLine = State.ParenLevel;
472 
473   // Any break on this level means that the parent level has been broken
474   // and we need to avoid bin packing there.
475   for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
476     State.Stack[i].BreakBeforeParameter = true;
477   }
478   if (PreviousNonComment &&
479       !PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
480       PreviousNonComment->Type != TT_TemplateCloser &&
481       PreviousNonComment->Type != TT_BinaryOperator &&
482       Current.Type != TT_BinaryOperator &&
483       !PreviousNonComment->opensScope())
484     State.Stack.back().BreakBeforeParameter = true;
485 
486   // If we break after { or the [ of an array initializer, we should also break
487   // before the corresponding } or ].
488   if (Previous.is(tok::l_brace) || Previous.Type == TT_ArrayInitializerLSquare)
489     State.Stack.back().BreakBeforeClosingBrace = true;
490 
491   if (State.Stack.back().AvoidBinPacking) {
492     // If we are breaking after '(', '{', '<', this is not bin packing
493     // unless AllowAllParametersOfDeclarationOnNextLine is false.
494     if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
495           Previous.Type == TT_BinaryOperator) ||
496         (!Style.AllowAllParametersOfDeclarationOnNextLine &&
497          State.Line->MustBeDeclaration))
498       State.Stack.back().BreakBeforeParameter = true;
499   }
500 
501   return Penalty;
502 }
503 
504 unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
505                                                     bool DryRun, bool Newline) {
506   const FormatToken &Current = *State.NextToken;
507   assert(State.Stack.size());
508 
509   if (Current.Type == TT_InheritanceColon)
510     State.Stack.back().AvoidBinPacking = true;
511   if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
512     State.Stack.back().FirstLessLess = State.Column;
513   if (Current.Type == TT_ArraySubscriptLSquare &&
514       State.Stack.back().StartOfArraySubscripts == 0)
515     State.Stack.back().StartOfArraySubscripts = State.Column;
516   if ((Current.is(tok::question) && Style.BreakBeforeTernaryOperators) ||
517       (Current.getPreviousNonComment() && Current.isNot(tok::colon) &&
518        Current.getPreviousNonComment()->is(tok::question) &&
519        !Style.BreakBeforeTernaryOperators))
520     State.Stack.back().QuestionColumn = State.Column;
521   if (!Current.opensScope() && !Current.closesScope())
522     State.LowestLevelOnLine =
523         std::min(State.LowestLevelOnLine, State.ParenLevel);
524   if (Current.isMemberAccess())
525     State.Stack.back().StartOfFunctionCall =
526         Current.LastInChainOfCalls ? 0 : State.Column + Current.ColumnWidth;
527   if (Current.Type == TT_ObjCSelectorName)
528     State.Stack.back().ObjCSelectorNameFound = true;
529   if (Current.Type == TT_CtorInitializerColon) {
530     // Indent 2 from the column, so:
531     // SomeClass::SomeClass()
532     //     : First(...), ...
533     //       Next(...)
534     //       ^ line up here.
535     State.Stack.back().Indent =
536         State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
537     if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
538       State.Stack.back().AvoidBinPacking = true;
539     State.Stack.back().BreakBeforeParameter = false;
540   }
541 
542   // In ObjC method declaration we align on the ":" of parameters, but we need
543   // to ensure that we indent parameters on subsequent lines by at least our
544   // continuation indent width.
545   if (Current.Type == TT_ObjCMethodSpecifier)
546     State.Stack.back().Indent += Style.ContinuationIndentWidth;
547 
548   // Insert scopes created by fake parenthesis.
549   const FormatToken *Previous = Current.getPreviousNonComment();
550   // Don't add extra indentation for the first fake parenthesis after
551   // 'return', assignements or opening <({[. The indentation for these cases
552   // is special cased.
553   bool SkipFirstExtraIndent =
554       (Previous && (Previous->opensScope() || Previous->is(tok::kw_return) ||
555                     Previous->getPrecedence() == prec::Assignment ||
556                     Previous->Type == TT_ObjCMethodExpr));
557   for (SmallVectorImpl<prec::Level>::const_reverse_iterator
558            I = Current.FakeLParens.rbegin(),
559            E = Current.FakeLParens.rend();
560        I != E; ++I) {
561     ParenState NewParenState = State.Stack.back();
562     NewParenState.ContainsLineBreak = false;
563 
564     // Indent from 'LastSpace' unless this the fake parentheses encapsulating a
565     // builder type call after 'return'. If such a call is line-wrapped, we
566     // commonly just want to indent from the start of the line.
567     if (!Previous || Previous->isNot(tok::kw_return) || *I > 0)
568       NewParenState.Indent =
569           std::max(std::max(State.Column, NewParenState.Indent),
570                    State.Stack.back().LastSpace);
571 
572     // Do not indent relative to the fake parentheses inserted for "." or "->".
573     // This is a special case to make the following to statements consistent:
574     //   OuterFunction(InnerFunctionCall( // break
575     //       ParameterToInnerFunction));
576     //   OuterFunction(SomeObject.InnerFunctionCall( // break
577     //       ParameterToInnerFunction));
578     if (*I > prec::Unknown)
579       NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
580     NewParenState.StartOfFunctionCall = State.Column;
581 
582     // Always indent conditional expressions. Never indent expression where
583     // the 'operator' is ',', ';' or an assignment (i.e. *I <=
584     // prec::Assignment) as those have different indentation rules. Indent
585     // other expression, unless the indentation needs to be skipped.
586     if (*I == prec::Conditional ||
587         (!SkipFirstExtraIndent && *I > prec::Assignment &&
588          !Style.BreakBeforeBinaryOperators))
589       NewParenState.Indent += Style.ContinuationIndentWidth;
590     if ((Previous && !Previous->opensScope()) || *I > prec::Comma)
591       NewParenState.BreakBeforeParameter = false;
592     State.Stack.push_back(NewParenState);
593     SkipFirstExtraIndent = false;
594   }
595 
596   // If we encounter an opening (, [, { or <, we add a level to our stacks to
597   // prepare for the following tokens.
598   if (Current.opensScope()) {
599     unsigned NewIndent;
600     unsigned NewIndentLevel = State.Stack.back().IndentLevel;
601     bool AvoidBinPacking;
602     bool BreakBeforeParameter = false;
603     if (Current.is(tok::l_brace) ||
604         Current.Type == TT_ArrayInitializerLSquare) {
605       if (Current.MatchingParen && Current.BlockKind == BK_Block) {
606         // If this is an l_brace starting a nested block, we pretend (wrt. to
607         // indentation) that we already consumed the corresponding r_brace.
608         // Thus, we remove all ParenStates caused by fake parentheses that end
609         // at the r_brace. The net effect of this is that we don't indent
610         // relative to the l_brace, if the nested block is the last parameter of
611         // a function. For example, this formats:
612         //
613         //   SomeFunction(a, [] {
614         //     f();  // break
615         //   });
616         //
617         // instead of:
618         //   SomeFunction(a, [] {
619         //                     f();  // break
620         //                   });
621         for (unsigned i = 0; i != Current.MatchingParen->FakeRParens; ++i)
622           State.Stack.pop_back();
623         bool IsObjCBlock =
624             Previous &&
625             (Previous->is(tok::caret) ||
626              (Previous->is(tok::r_paren) && Previous->MatchingParen &&
627               Previous->MatchingParen->Previous &&
628               Previous->MatchingParen->Previous->is(tok::caret)));
629         // For some reason, ObjC blocks are indented like continuations.
630         NewIndent =
631             State.Stack.back().LastSpace +
632             (IsObjCBlock ? Style.ContinuationIndentWidth : Style.IndentWidth);
633         ++NewIndentLevel;
634         BreakBeforeParameter = true;
635       } else {
636         NewIndent = State.Stack.back().LastSpace;
637         if (Current.opensBlockTypeList(Style)) {
638           NewIndent += Style.IndentWidth;
639           NewIndent = std::min(State.Column + 2, NewIndent);
640           ++NewIndentLevel;
641         } else {
642           NewIndent += Style.ContinuationIndentWidth;
643           NewIndent = std::min(State.Column + 1, NewIndent);
644         }
645       }
646       const FormatToken *NextNoComment = Current.getNextNonComment();
647       AvoidBinPacking = Current.BlockKind == BK_Block ||
648                         Current.Type == TT_ArrayInitializerLSquare ||
649                         Current.Type == TT_DictLiteral ||
650                         (NextNoComment &&
651                          NextNoComment->Type == TT_DesignatedInitializerPeriod);
652     } else {
653       NewIndent = Style.ContinuationIndentWidth +
654                   std::max(State.Stack.back().LastSpace,
655                            State.Stack.back().StartOfFunctionCall);
656       AvoidBinPacking = !Style.BinPackParameters ||
657                         (Style.ExperimentalAutoDetectBinPacking &&
658                          (Current.PackingKind == PPK_OnePerLine ||
659                           (!BinPackInconclusiveFunctions &&
660                            Current.PackingKind == PPK_Inconclusive)));
661       // If this '[' opens an ObjC call, determine whether all parameters fit
662       // into one line and put one per line if they don't.
663       if (Current.Type == TT_ObjCMethodExpr &&
664           getLengthToMatchingParen(Current) + State.Column >
665               getColumnLimit(State))
666         BreakBeforeParameter = true;
667     }
668 
669     bool NoLineBreak = State.Stack.back().NoLineBreak ||
670                        (Current.Type == TT_TemplateOpener &&
671                         State.Stack.back().ContainsUnwrappedBuilder);
672     State.Stack.push_back(ParenState(NewIndent, NewIndentLevel,
673                                      State.Stack.back().LastSpace,
674                                      AvoidBinPacking, NoLineBreak));
675     State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
676     ++State.ParenLevel;
677   }
678 
679   // If we encounter a closing ), ], } or >, we can remove a level from our
680   // stacks.
681   if (State.Stack.size() > 1 &&
682       (Current.isOneOf(tok::r_paren, tok::r_square) ||
683        (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
684        State.NextToken->Type == TT_TemplateCloser)) {
685     State.Stack.pop_back();
686     --State.ParenLevel;
687   }
688   if (Current.is(tok::r_square)) {
689     // If this ends the array subscript expr, reset the corresponding value.
690     const FormatToken *NextNonComment = Current.getNextNonComment();
691     if (NextNonComment && NextNonComment->isNot(tok::l_square))
692       State.Stack.back().StartOfArraySubscripts = 0;
693   }
694 
695   // Remove scopes created by fake parenthesis.
696   if (Current.isNot(tok::r_brace) ||
697       (Current.MatchingParen && Current.MatchingParen->BlockKind != BK_Block)) {
698     // Don't remove FakeRParens attached to r_braces that surround nested blocks
699     // as they will have been removed early (see above).
700     for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
701       unsigned VariablePos = State.Stack.back().VariablePos;
702       State.Stack.pop_back();
703       State.Stack.back().VariablePos = VariablePos;
704     }
705   }
706 
707   if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) {
708     State.StartOfStringLiteral = State.Column;
709   } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
710              !Current.isStringLiteral()) {
711     State.StartOfStringLiteral = 0;
712   }
713 
714   State.Column += Current.ColumnWidth;
715   State.NextToken = State.NextToken->Next;
716   unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
717   if (State.Column > getColumnLimit(State)) {
718     unsigned ExcessCharacters = State.Column - getColumnLimit(State);
719     Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
720   }
721 
722   if (Current.Role)
723     Current.Role->formatFromToken(State, this, DryRun);
724   // If the previous has a special role, let it consume tokens as appropriate.
725   // It is necessary to start at the previous token for the only implemented
726   // role (comma separated list). That way, the decision whether or not to break
727   // after the "{" is already done and both options are tried and evaluated.
728   // FIXME: This is ugly, find a better way.
729   if (Previous && Previous->Role)
730     Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
731 
732   return Penalty;
733 }
734 
735 unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
736                                                  LineState &State) {
737   // Break before further function parameters on all levels.
738   for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
739     State.Stack[i].BreakBeforeParameter = true;
740 
741   unsigned ColumnsUsed = State.Column;
742   // We can only affect layout of the first and the last line, so the penalty
743   // for all other lines is constant, and we ignore it.
744   State.Column = Current.LastLineColumnWidth;
745 
746   if (ColumnsUsed > getColumnLimit(State))
747     return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
748   return 0;
749 }
750 
751 static bool getRawStringLiteralPrefixPostfix(StringRef Text,
752                                              StringRef &Prefix,
753                                              StringRef &Postfix) {
754   if (Text.startswith(Prefix = "R\"") || Text.startswith(Prefix = "uR\"") ||
755       Text.startswith(Prefix = "UR\"") || Text.startswith(Prefix = "u8R\"") ||
756       Text.startswith(Prefix = "LR\"")) {
757     size_t ParenPos = Text.find('(');
758     if (ParenPos != StringRef::npos) {
759       StringRef Delimiter =
760           Text.substr(Prefix.size(), ParenPos - Prefix.size());
761       Prefix = Text.substr(0, ParenPos + 1);
762       Postfix = Text.substr(Text.size() - 2 - Delimiter.size());
763       return Postfix.front() == ')' && Postfix.back() == '"' &&
764              Postfix.substr(1).startswith(Delimiter);
765     }
766   }
767   return false;
768 }
769 
770 unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
771                                                     LineState &State,
772                                                     bool DryRun) {
773   // Don't break multi-line tokens other than block comments. Instead, just
774   // update the state.
775   if (Current.Type != TT_BlockComment && Current.IsMultiline)
776     return addMultilineToken(Current, State);
777 
778   // Don't break implicit string literals.
779   if (Current.Type == TT_ImplicitStringLiteral)
780     return 0;
781 
782   if (!Current.isStringLiteral() && !Current.is(tok::comment))
783     return 0;
784 
785   llvm::OwningPtr<BreakableToken> Token;
786   unsigned StartColumn = State.Column - Current.ColumnWidth;
787   unsigned ColumnLimit = getColumnLimit(State);
788 
789   if (Current.isStringLiteral()) {
790     // Don't break string literals inside preprocessor directives (except for
791     // #define directives, as their contents are stored in separate lines and
792     // are not affected by this check).
793     // This way we avoid breaking code with line directives and unknown
794     // preprocessor directives that contain long string literals.
795     if (State.Line->Type == LT_PreprocessorDirective)
796       return 0;
797     // Exempts unterminated string literals from line breaking. The user will
798     // likely want to terminate the string before any line breaking is done.
799     if (Current.IsUnterminatedLiteral)
800       return 0;
801 
802     StringRef Text = Current.TokenText;
803     StringRef Prefix;
804     StringRef Postfix;
805     bool IsNSStringLiteral = false;
806     // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
807     // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
808     // reduce the overhead) for each FormatToken, which is a string, so that we
809     // don't run multiple checks here on the hot path.
810     if (Text.startswith("\"") && Current.Previous &&
811         Current.Previous->is(tok::at)) {
812       IsNSStringLiteral = true;
813       Prefix = "@\"";
814     }
815     if ((Text.endswith(Postfix = "\"") &&
816          (IsNSStringLiteral || Text.startswith(Prefix = "\"") ||
817           Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
818           Text.startswith(Prefix = "u8\"") ||
819           Text.startswith(Prefix = "L\""))) ||
820         (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")")) ||
821         getRawStringLiteralPrefixPostfix(Text, Prefix, Postfix)) {
822       Token.reset(new BreakableStringLiteral(
823           Current, State.Line->Level, StartColumn, Prefix, Postfix,
824           State.Line->InPPDirective, Encoding, Style));
825     } else {
826       return 0;
827     }
828   } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
829     if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
830       return 0;
831     Token.reset(new BreakableBlockComment(
832         Current, State.Line->Level, StartColumn, Current.OriginalColumn,
833         !Current.Previous, State.Line->InPPDirective, Encoding, Style));
834   } else if (Current.Type == TT_LineComment &&
835              (Current.Previous == NULL ||
836               Current.Previous->Type != TT_ImplicitStringLiteral)) {
837     if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
838       return 0;
839     Token.reset(new BreakableLineComment(Current, State.Line->Level,
840                                          StartColumn, /*InPPDirective=*/false,
841                                          Encoding, Style));
842     // We don't insert backslashes when breaking line comments.
843     ColumnLimit = Style.ColumnLimit;
844   } else {
845     return 0;
846   }
847   if (Current.UnbreakableTailLength >= ColumnLimit)
848     return 0;
849 
850   unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength;
851   bool BreakInserted = false;
852   unsigned Penalty = 0;
853   unsigned RemainingTokenColumns = 0;
854   for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
855        LineIndex != EndIndex; ++LineIndex) {
856     if (!DryRun)
857       Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
858     unsigned TailOffset = 0;
859     RemainingTokenColumns =
860         Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
861     while (RemainingTokenColumns > RemainingSpace) {
862       BreakableToken::Split Split =
863           Token->getSplit(LineIndex, TailOffset, ColumnLimit);
864       if (Split.first == StringRef::npos) {
865         // The last line's penalty is handled in addNextStateToQueue().
866         if (LineIndex < EndIndex - 1)
867           Penalty += Style.PenaltyExcessCharacter *
868                      (RemainingTokenColumns - RemainingSpace);
869         break;
870       }
871       assert(Split.first != 0);
872       unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
873           LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
874 
875       // We can remove extra whitespace instead of breaking the line.
876       if (RemainingTokenColumns + 1 - Split.second <= RemainingSpace) {
877         RemainingTokenColumns = 0;
878         if (!DryRun)
879           Token->replaceWhitespace(LineIndex, TailOffset, Split, Whitespaces);
880         break;
881       }
882 
883       assert(NewRemainingTokenColumns < RemainingTokenColumns);
884       if (!DryRun)
885         Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
886       Penalty += Current.SplitPenalty;
887       unsigned ColumnsUsed =
888           Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
889       if (ColumnsUsed > ColumnLimit) {
890         Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit);
891       }
892       TailOffset += Split.first + Split.second;
893       RemainingTokenColumns = NewRemainingTokenColumns;
894       BreakInserted = true;
895     }
896   }
897 
898   State.Column = RemainingTokenColumns;
899 
900   if (BreakInserted) {
901     // If we break the token inside a parameter list, we need to break before
902     // the next parameter on all levels, so that the next parameter is clearly
903     // visible. Line comments already introduce a break.
904     if (Current.Type != TT_LineComment) {
905       for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
906         State.Stack[i].BreakBeforeParameter = true;
907     }
908 
909     Penalty += Current.isStringLiteral() ? Style.PenaltyBreakString
910                                          : Style.PenaltyBreakComment;
911 
912     State.Stack.back().LastSpace = StartColumn;
913   }
914   return Penalty;
915 }
916 
917 unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
918   // In preprocessor directives reserve two chars for trailing " \"
919   return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
920 }
921 
922 bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
923   const FormatToken &Current = *State.NextToken;
924   if (!Current.isStringLiteral())
925     return false;
926   // We never consider raw string literals "multiline" for the purpose of
927   // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
928   // (see TokenAnnotator::mustBreakBefore().
929   if (Current.TokenText.startswith("R\""))
930     return false;
931   if (Current.IsMultiline)
932     return true;
933   if (Current.getNextNonComment() &&
934       Current.getNextNonComment()->isStringLiteral())
935     return true; // Implicit concatenation.
936   if (State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
937       Style.ColumnLimit)
938     return true; // String will be split.
939   return false;
940 }
941 
942 } // namespace format
943 } // namespace clang
944