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