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