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