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