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