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