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