xref: /aosp_15_r20/external/clang/lib/Format/ContinuationIndenter.cpp (revision 67e74705e28f6214e480b399dd47ea732279e315)
1*67e74705SXin Li //===--- ContinuationIndenter.cpp - Format C++ code -----------------------===//
2*67e74705SXin Li //
3*67e74705SXin Li //                     The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li ///
10*67e74705SXin Li /// \file
11*67e74705SXin Li /// \brief This file implements the continuation indenter.
12*67e74705SXin Li ///
13*67e74705SXin Li //===----------------------------------------------------------------------===//
14*67e74705SXin Li 
15*67e74705SXin Li #include "BreakableToken.h"
16*67e74705SXin Li #include "ContinuationIndenter.h"
17*67e74705SXin Li #include "WhitespaceManager.h"
18*67e74705SXin Li #include "clang/Basic/OperatorPrecedence.h"
19*67e74705SXin Li #include "clang/Basic/SourceManager.h"
20*67e74705SXin Li #include "clang/Format/Format.h"
21*67e74705SXin Li #include "llvm/Support/Debug.h"
22*67e74705SXin Li #include <string>
23*67e74705SXin Li 
24*67e74705SXin Li #define DEBUG_TYPE "format-formatter"
25*67e74705SXin Li 
26*67e74705SXin Li namespace clang {
27*67e74705SXin Li namespace format {
28*67e74705SXin Li 
29*67e74705SXin Li // Returns the length of everything up to the first possible line break after
30*67e74705SXin Li // the ), ], } or > matching \c Tok.
getLengthToMatchingParen(const FormatToken & Tok)31*67e74705SXin Li static unsigned getLengthToMatchingParen(const FormatToken &Tok) {
32*67e74705SXin Li   if (!Tok.MatchingParen)
33*67e74705SXin Li     return 0;
34*67e74705SXin Li   FormatToken *End = Tok.MatchingParen;
35*67e74705SXin Li   while (End->Next && !End->Next->CanBreakBefore) {
36*67e74705SXin Li     End = End->Next;
37*67e74705SXin Li   }
38*67e74705SXin Li   return End->TotalLength - Tok.TotalLength + 1;
39*67e74705SXin Li }
40*67e74705SXin Li 
getLengthToNextOperator(const FormatToken & Tok)41*67e74705SXin Li static unsigned getLengthToNextOperator(const FormatToken &Tok) {
42*67e74705SXin Li   if (!Tok.NextOperator)
43*67e74705SXin Li     return 0;
44*67e74705SXin Li   return Tok.NextOperator->TotalLength - Tok.TotalLength;
45*67e74705SXin Li }
46*67e74705SXin Li 
47*67e74705SXin Li // Returns \c true if \c Tok is the "." or "->" of a call and starts the next
48*67e74705SXin Li // segment of a builder type call.
startsSegmentOfBuilderTypeCall(const FormatToken & Tok)49*67e74705SXin Li static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) {
50*67e74705SXin Li   return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope();
51*67e74705SXin Li }
52*67e74705SXin Li 
53*67e74705SXin Li // Returns \c true if \c Current starts a new parameter.
startsNextParameter(const FormatToken & Current,const FormatStyle & Style)54*67e74705SXin Li static bool startsNextParameter(const FormatToken &Current,
55*67e74705SXin Li                                 const FormatStyle &Style) {
56*67e74705SXin Li   const FormatToken &Previous = *Current.Previous;
57*67e74705SXin Li   if (Current.is(TT_CtorInitializerComma) &&
58*67e74705SXin Li       Style.BreakConstructorInitializersBeforeComma)
59*67e74705SXin Li     return true;
60*67e74705SXin Li   return Previous.is(tok::comma) && !Current.isTrailingComment() &&
61*67e74705SXin Li          (Previous.isNot(TT_CtorInitializerComma) ||
62*67e74705SXin Li           !Style.BreakConstructorInitializersBeforeComma);
63*67e74705SXin Li }
64*67e74705SXin Li 
ContinuationIndenter(const FormatStyle & Style,const AdditionalKeywords & Keywords,const SourceManager & SourceMgr,WhitespaceManager & Whitespaces,encoding::Encoding Encoding,bool BinPackInconclusiveFunctions)65*67e74705SXin Li ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,
66*67e74705SXin Li                                            const AdditionalKeywords &Keywords,
67*67e74705SXin Li                                            const SourceManager &SourceMgr,
68*67e74705SXin Li                                            WhitespaceManager &Whitespaces,
69*67e74705SXin Li                                            encoding::Encoding Encoding,
70*67e74705SXin Li                                            bool BinPackInconclusiveFunctions)
71*67e74705SXin Li     : Style(Style), Keywords(Keywords), SourceMgr(SourceMgr),
72*67e74705SXin Li       Whitespaces(Whitespaces), Encoding(Encoding),
73*67e74705SXin Li       BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
74*67e74705SXin Li       CommentPragmasRegex(Style.CommentPragmas) {}
75*67e74705SXin Li 
getInitialState(unsigned FirstIndent,const AnnotatedLine * Line,bool DryRun)76*67e74705SXin Li LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
77*67e74705SXin Li                                                 const AnnotatedLine *Line,
78*67e74705SXin Li                                                 bool DryRun) {
79*67e74705SXin Li   LineState State;
80*67e74705SXin Li   State.FirstIndent = FirstIndent;
81*67e74705SXin Li   State.Column = FirstIndent;
82*67e74705SXin Li   State.Line = Line;
83*67e74705SXin Li   State.NextToken = Line->First;
84*67e74705SXin Li   State.Stack.push_back(ParenState(FirstIndent, Line->Level, FirstIndent,
85*67e74705SXin Li                                    /*AvoidBinPacking=*/false,
86*67e74705SXin Li                                    /*NoLineBreak=*/false));
87*67e74705SXin Li   State.LineContainsContinuedForLoopSection = false;
88*67e74705SXin Li   State.StartOfStringLiteral = 0;
89*67e74705SXin Li   State.StartOfLineLevel = 0;
90*67e74705SXin Li   State.LowestLevelOnLine = 0;
91*67e74705SXin Li   State.IgnoreStackForComparison = false;
92*67e74705SXin Li 
93*67e74705SXin Li   // The first token has already been indented and thus consumed.
94*67e74705SXin Li   moveStateToNextToken(State, DryRun, /*Newline=*/false);
95*67e74705SXin Li   return State;
96*67e74705SXin Li }
97*67e74705SXin Li 
canBreak(const LineState & State)98*67e74705SXin Li bool ContinuationIndenter::canBreak(const LineState &State) {
99*67e74705SXin Li   const FormatToken &Current = *State.NextToken;
100*67e74705SXin Li   const FormatToken &Previous = *Current.Previous;
101*67e74705SXin Li   assert(&Previous == Current.Previous);
102*67e74705SXin Li   if (!Current.CanBreakBefore &&
103*67e74705SXin Li       !(State.Stack.back().BreakBeforeClosingBrace &&
104*67e74705SXin Li         Current.closesBlockOrBlockTypeList(Style)))
105*67e74705SXin Li     return false;
106*67e74705SXin Li   // The opening "{" of a braced list has to be on the same line as the first
107*67e74705SXin Li   // element if it is nested in another braced init list or function call.
108*67e74705SXin Li   if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
109*67e74705SXin Li       Previous.isNot(TT_DictLiteral) && Previous.BlockKind == BK_BracedInit &&
110*67e74705SXin Li       Previous.Previous &&
111*67e74705SXin Li       Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
112*67e74705SXin Li     return false;
113*67e74705SXin Li   // This prevents breaks like:
114*67e74705SXin Li   //   ...
115*67e74705SXin Li   //   SomeParameter, OtherParameter).DoSomething(
116*67e74705SXin Li   //   ...
117*67e74705SXin Li   // As they hide "DoSomething" and are generally bad for readability.
118*67e74705SXin Li   if (Previous.opensScope() && Previous.isNot(tok::l_brace) &&
119*67e74705SXin Li       State.LowestLevelOnLine < State.StartOfLineLevel &&
120*67e74705SXin Li       State.LowestLevelOnLine < Current.NestingLevel)
121*67e74705SXin Li     return false;
122*67e74705SXin Li   if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
123*67e74705SXin Li     return false;
124*67e74705SXin Li 
125*67e74705SXin Li   // Don't create a 'hanging' indent if there are multiple blocks in a single
126*67e74705SXin Li   // statement.
127*67e74705SXin Li   if (Previous.is(tok::l_brace) && State.Stack.size() > 1 &&
128*67e74705SXin Li       State.Stack[State.Stack.size() - 2].NestedBlockInlined &&
129*67e74705SXin Li       State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks)
130*67e74705SXin Li     return false;
131*67e74705SXin Li 
132*67e74705SXin Li   // Don't break after very short return types (e.g. "void") as that is often
133*67e74705SXin Li   // unexpected.
134*67e74705SXin Li   if (Current.is(TT_FunctionDeclarationName) && State.Column < 6) {
135*67e74705SXin Li     if (Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None)
136*67e74705SXin Li       return false;
137*67e74705SXin Li   }
138*67e74705SXin Li 
139*67e74705SXin Li   return !State.Stack.back().NoLineBreak;
140*67e74705SXin Li }
141*67e74705SXin Li 
mustBreak(const LineState & State)142*67e74705SXin Li bool ContinuationIndenter::mustBreak(const LineState &State) {
143*67e74705SXin Li   const FormatToken &Current = *State.NextToken;
144*67e74705SXin Li   const FormatToken &Previous = *Current.Previous;
145*67e74705SXin Li   if (Current.MustBreakBefore || Current.is(TT_InlineASMColon))
146*67e74705SXin Li     return true;
147*67e74705SXin Li   if (State.Stack.back().BreakBeforeClosingBrace &&
148*67e74705SXin Li       Current.closesBlockOrBlockTypeList(Style))
149*67e74705SXin Li     return true;
150*67e74705SXin Li   if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
151*67e74705SXin Li     return true;
152*67e74705SXin Li   if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
153*67e74705SXin Li        (Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) &&
154*67e74705SXin Li         Style.Language == FormatStyle::LK_Cpp &&
155*67e74705SXin Li         // FIXME: This is a temporary workaround for the case where clang-format
156*67e74705SXin Li         // sets BreakBeforeParameter to avoid bin packing and this creates a
157*67e74705SXin Li         // completely unnecessary line break after a template type that isn't
158*67e74705SXin Li         // line-wrapped.
159*67e74705SXin Li         (Previous.NestingLevel == 1 || Style.BinPackParameters)) ||
160*67e74705SXin Li        (Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&
161*67e74705SXin Li         Previous.isNot(tok::question)) ||
162*67e74705SXin Li        (!Style.BreakBeforeTernaryOperators &&
163*67e74705SXin Li         Previous.is(TT_ConditionalExpr))) &&
164*67e74705SXin Li       State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
165*67e74705SXin Li       !Current.isOneOf(tok::r_paren, tok::r_brace))
166*67e74705SXin Li     return true;
167*67e74705SXin Li   if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) ||
168*67e74705SXin Li        (Previous.is(TT_ArrayInitializerLSquare) &&
169*67e74705SXin Li         Previous.ParameterCount > 1)) &&
170*67e74705SXin Li       Style.ColumnLimit > 0 &&
171*67e74705SXin Li       getLengthToMatchingParen(Previous) + State.Column - 1 >
172*67e74705SXin Li           getColumnLimit(State))
173*67e74705SXin Li     return true;
174*67e74705SXin Li   if (Current.is(TT_CtorInitializerColon) &&
175*67e74705SXin Li       (State.Column + State.Line->Last->TotalLength - Current.TotalLength + 2 >
176*67e74705SXin Li            getColumnLimit(State) ||
177*67e74705SXin Li        State.Stack.back().BreakBeforeParameter) &&
178*67e74705SXin Li       ((Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All) ||
179*67e74705SXin Li        Style.BreakConstructorInitializersBeforeComma || Style.ColumnLimit != 0))
180*67e74705SXin Li     return true;
181*67e74705SXin Li   if (Current.is(TT_SelectorName) && State.Stack.back().ObjCSelectorNameFound &&
182*67e74705SXin Li       State.Stack.back().BreakBeforeParameter)
183*67e74705SXin Li     return true;
184*67e74705SXin Li 
185*67e74705SXin Li   unsigned NewLineColumn = getNewLineColumn(State);
186*67e74705SXin Li   if (Current.isMemberAccess() && Style.ColumnLimit != 0 &&
187*67e74705SXin Li       State.Column + getLengthToNextOperator(Current) > Style.ColumnLimit &&
188*67e74705SXin Li       (State.Column > NewLineColumn ||
189*67e74705SXin Li        Current.NestingLevel < State.StartOfLineLevel))
190*67e74705SXin Li     return true;
191*67e74705SXin Li 
192*67e74705SXin Li   if (State.Column <= NewLineColumn)
193*67e74705SXin Li     return false;
194*67e74705SXin Li 
195*67e74705SXin Li   if (Style.AlwaysBreakBeforeMultilineStrings &&
196*67e74705SXin Li       (NewLineColumn == State.FirstIndent + Style.ContinuationIndentWidth ||
197*67e74705SXin Li        Previous.is(tok::comma) || Current.NestingLevel < 2) &&
198*67e74705SXin Li       !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) &&
199*67e74705SXin Li       !Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) &&
200*67e74705SXin Li       nextIsMultilineString(State))
201*67e74705SXin Li     return true;
202*67e74705SXin Li 
203*67e74705SXin Li   // Using CanBreakBefore here and below takes care of the decision whether the
204*67e74705SXin Li   // current style uses wrapping before or after operators for the given
205*67e74705SXin Li   // operator.
206*67e74705SXin Li   if (Previous.is(TT_BinaryOperator) && Current.CanBreakBefore) {
207*67e74705SXin Li     // If we need to break somewhere inside the LHS of a binary expression, we
208*67e74705SXin Li     // should also break after the operator. Otherwise, the formatting would
209*67e74705SXin Li     // hide the operator precedence, e.g. in:
210*67e74705SXin Li     //   if (aaaaaaaaaaaaaa ==
211*67e74705SXin Li     //           bbbbbbbbbbbbbb && c) {..
212*67e74705SXin Li     // For comparisons, we only apply this rule, if the LHS is a binary
213*67e74705SXin Li     // expression itself as otherwise, the line breaks seem superfluous.
214*67e74705SXin Li     // We need special cases for ">>" which we have split into two ">" while
215*67e74705SXin Li     // lexing in order to make template parsing easier.
216*67e74705SXin Li     bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
217*67e74705SXin Li                          Previous.getPrecedence() == prec::Equality) &&
218*67e74705SXin Li                         Previous.Previous &&
219*67e74705SXin Li                         Previous.Previous->isNot(TT_BinaryOperator); // For >>.
220*67e74705SXin Li     bool LHSIsBinaryExpr =
221*67e74705SXin Li         Previous.Previous && Previous.Previous->EndsBinaryExpression;
222*67e74705SXin Li     if ((!IsComparison || LHSIsBinaryExpr) && !Current.isTrailingComment() &&
223*67e74705SXin Li         Previous.getPrecedence() != prec::Assignment &&
224*67e74705SXin Li         State.Stack.back().BreakBeforeParameter)
225*67e74705SXin Li       return true;
226*67e74705SXin Li   } else if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore &&
227*67e74705SXin Li              State.Stack.back().BreakBeforeParameter) {
228*67e74705SXin Li     return true;
229*67e74705SXin Li   }
230*67e74705SXin Li 
231*67e74705SXin Li   // Same as above, but for the first "<<" operator.
232*67e74705SXin Li   if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator) &&
233*67e74705SXin Li       State.Stack.back().BreakBeforeParameter &&
234*67e74705SXin Li       State.Stack.back().FirstLessLess == 0)
235*67e74705SXin Li     return true;
236*67e74705SXin Li 
237*67e74705SXin Li   if (Current.NestingLevel == 0 && !Current.isTrailingComment()) {
238*67e74705SXin Li     // Always break after "template <...>" and leading annotations. This is only
239*67e74705SXin Li     // for cases where the entire line does not fit on a single line as a
240*67e74705SXin Li     // different LineFormatter would be used otherwise.
241*67e74705SXin Li     if (Previous.ClosesTemplateDeclaration)
242*67e74705SXin Li       return true;
243*67e74705SXin Li     if (Previous.is(TT_FunctionAnnotationRParen))
244*67e74705SXin Li       return true;
245*67e74705SXin Li     if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) &&
246*67e74705SXin Li         Current.isNot(TT_LeadingJavaAnnotation))
247*67e74705SXin Li       return true;
248*67e74705SXin Li   }
249*67e74705SXin Li 
250*67e74705SXin Li   // If the return type spans multiple lines, wrap before the function name.
251*67e74705SXin Li   if ((Current.is(TT_FunctionDeclarationName) ||
252*67e74705SXin Li        (Current.is(tok::kw_operator) && !Previous.is(tok::coloncolon))) &&
253*67e74705SXin Li       !Previous.is(tok::kw_template) && State.Stack.back().BreakBeforeParameter)
254*67e74705SXin Li     return true;
255*67e74705SXin Li 
256*67e74705SXin Li   if (startsSegmentOfBuilderTypeCall(Current) &&
257*67e74705SXin Li       (State.Stack.back().CallContinuation != 0 ||
258*67e74705SXin Li        State.Stack.back().BreakBeforeParameter))
259*67e74705SXin Li     return true;
260*67e74705SXin Li 
261*67e74705SXin Li   // The following could be precomputed as they do not depend on the state.
262*67e74705SXin Li   // However, as they should take effect only if the UnwrappedLine does not fit
263*67e74705SXin Li   // into the ColumnLimit, they are checked here in the ContinuationIndenter.
264*67e74705SXin Li   if (Style.ColumnLimit != 0 && Previous.BlockKind == BK_Block &&
265*67e74705SXin Li       Previous.is(tok::l_brace) && !Current.isOneOf(tok::r_brace, tok::comment))
266*67e74705SXin Li     return true;
267*67e74705SXin Li 
268*67e74705SXin Li   if (Current.is(tok::lessless) &&
269*67e74705SXin Li       ((Previous.is(tok::identifier) && Previous.TokenText == "endl") ||
270*67e74705SXin Li        (Previous.Tok.isLiteral() && (Previous.TokenText.endswith("\\n\"") ||
271*67e74705SXin Li                                      Previous.TokenText == "\'\\n\'"))))
272*67e74705SXin Li     return true;
273*67e74705SXin Li 
274*67e74705SXin Li   return false;
275*67e74705SXin Li }
276*67e74705SXin Li 
addTokenToState(LineState & State,bool Newline,bool DryRun,unsigned ExtraSpaces)277*67e74705SXin Li unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
278*67e74705SXin Li                                                bool DryRun,
279*67e74705SXin Li                                                unsigned ExtraSpaces) {
280*67e74705SXin Li   const FormatToken &Current = *State.NextToken;
281*67e74705SXin Li 
282*67e74705SXin Li   assert(!State.Stack.empty());
283*67e74705SXin Li   if ((Current.is(TT_ImplicitStringLiteral) &&
284*67e74705SXin Li        (Current.Previous->Tok.getIdentifierInfo() == nullptr ||
285*67e74705SXin Li         Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
286*67e74705SXin Li             tok::pp_not_keyword))) {
287*67e74705SXin Li     unsigned EndColumn =
288*67e74705SXin Li         SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getEnd());
289*67e74705SXin Li     if (Current.LastNewlineOffset != 0) {
290*67e74705SXin Li       // If there is a newline within this token, the final column will solely
291*67e74705SXin Li       // determined by the current end column.
292*67e74705SXin Li       State.Column = EndColumn;
293*67e74705SXin Li     } else {
294*67e74705SXin Li       unsigned StartColumn =
295*67e74705SXin Li           SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getBegin());
296*67e74705SXin Li       assert(EndColumn >= StartColumn);
297*67e74705SXin Li       State.Column += EndColumn - StartColumn;
298*67e74705SXin Li     }
299*67e74705SXin Li     moveStateToNextToken(State, DryRun, /*Newline=*/false);
300*67e74705SXin Li     return 0;
301*67e74705SXin Li   }
302*67e74705SXin Li 
303*67e74705SXin Li   unsigned Penalty = 0;
304*67e74705SXin Li   if (Newline)
305*67e74705SXin Li     Penalty = addTokenOnNewLine(State, DryRun);
306*67e74705SXin Li   else
307*67e74705SXin Li     addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
308*67e74705SXin Li 
309*67e74705SXin Li   return moveStateToNextToken(State, DryRun, Newline) + Penalty;
310*67e74705SXin Li }
311*67e74705SXin Li 
addTokenOnCurrentLine(LineState & State,bool DryRun,unsigned ExtraSpaces)312*67e74705SXin Li void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
313*67e74705SXin Li                                                  unsigned ExtraSpaces) {
314*67e74705SXin Li   FormatToken &Current = *State.NextToken;
315*67e74705SXin Li   const FormatToken &Previous = *State.NextToken->Previous;
316*67e74705SXin Li   if (Current.is(tok::equal) &&
317*67e74705SXin Li       (State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) &&
318*67e74705SXin Li       State.Stack.back().VariablePos == 0) {
319*67e74705SXin Li     State.Stack.back().VariablePos = State.Column;
320*67e74705SXin Li     // Move over * and & if they are bound to the variable name.
321*67e74705SXin Li     const FormatToken *Tok = &Previous;
322*67e74705SXin Li     while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
323*67e74705SXin Li       State.Stack.back().VariablePos -= Tok->ColumnWidth;
324*67e74705SXin Li       if (Tok->SpacesRequiredBefore != 0)
325*67e74705SXin Li         break;
326*67e74705SXin Li       Tok = Tok->Previous;
327*67e74705SXin Li     }
328*67e74705SXin Li     if (Previous.PartOfMultiVariableDeclStmt)
329*67e74705SXin Li       State.Stack.back().LastSpace = State.Stack.back().VariablePos;
330*67e74705SXin Li   }
331*67e74705SXin Li 
332*67e74705SXin Li   unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
333*67e74705SXin Li 
334*67e74705SXin Li   if (!DryRun)
335*67e74705SXin Li     Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, /*IndentLevel=*/0,
336*67e74705SXin Li                                   Spaces, State.Column + Spaces);
337*67e74705SXin Li 
338*67e74705SXin Li   if (Current.is(TT_SelectorName) &&
339*67e74705SXin Li       !State.Stack.back().ObjCSelectorNameFound) {
340*67e74705SXin Li     unsigned MinIndent =
341*67e74705SXin Li         std::max(State.FirstIndent + Style.ContinuationIndentWidth,
342*67e74705SXin Li                  State.Stack.back().Indent);
343*67e74705SXin Li     unsigned FirstColonPos = State.Column + Spaces + Current.ColumnWidth;
344*67e74705SXin Li     if (Current.LongestObjCSelectorName == 0)
345*67e74705SXin Li       State.Stack.back().AlignColons = false;
346*67e74705SXin Li     else if (MinIndent + Current.LongestObjCSelectorName > FirstColonPos)
347*67e74705SXin Li       State.Stack.back().ColonPos = MinIndent + Current.LongestObjCSelectorName;
348*67e74705SXin Li     else
349*67e74705SXin Li       State.Stack.back().ColonPos = FirstColonPos;
350*67e74705SXin Li   }
351*67e74705SXin Li 
352*67e74705SXin Li   // In "AlwaysBreak" mode, enforce wrapping directly after the parenthesis by
353*67e74705SXin Li   // disallowing any further line breaks if there is no line break after the
354*67e74705SXin Li   // opening parenthesis. Don't break if it doesn't conserve columns.
355*67e74705SXin Li   if (Style.AlignAfterOpenBracket == FormatStyle::BAS_AlwaysBreak &&
356*67e74705SXin Li       Previous.isOneOf(tok::l_paren, TT_TemplateOpener, tok::l_square) &&
357*67e74705SXin Li       State.Column > getNewLineColumn(State) &&
358*67e74705SXin Li       (!Previous.Previous ||
359*67e74705SXin Li        !Previous.Previous->isOneOf(tok::kw_for, tok::kw_while,
360*67e74705SXin Li                                    tok::kw_switch)) &&
361*67e74705SXin Li       // Don't do this for simple (no expressions) one-argument function calls
362*67e74705SXin Li       // as that feels like needlessly wasting whitespace, e.g.:
363*67e74705SXin Li       //
364*67e74705SXin Li       //   caaaaaaaaaaaall(
365*67e74705SXin Li       //       caaaaaaaaaaaall(
366*67e74705SXin Li       //           caaaaaaaaaaaall(
367*67e74705SXin Li       //               caaaaaaaaaaaaaaaaaaaaaaall(aaaaaaaaaaaaaa, aaaaaaaaa))));
368*67e74705SXin Li       Current.FakeLParens.size() > 0 &&
369*67e74705SXin Li       Current.FakeLParens.back() > prec::Unknown)
370*67e74705SXin Li     State.Stack.back().NoLineBreak = true;
371*67e74705SXin Li 
372*67e74705SXin Li   if (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign &&
373*67e74705SXin Li       Previous.opensScope() && Previous.isNot(TT_ObjCMethodExpr) &&
374*67e74705SXin Li       (Current.isNot(TT_LineComment) || Previous.BlockKind == BK_BracedInit))
375*67e74705SXin Li     State.Stack.back().Indent = State.Column + Spaces;
376*67e74705SXin Li   if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
377*67e74705SXin Li     State.Stack.back().NoLineBreak = true;
378*67e74705SXin Li   if (startsSegmentOfBuilderTypeCall(Current) &&
379*67e74705SXin Li       State.Column > getNewLineColumn(State))
380*67e74705SXin Li     State.Stack.back().ContainsUnwrappedBuilder = true;
381*67e74705SXin Li 
382*67e74705SXin Li   if (Current.is(TT_LambdaArrow) && Style.Language == FormatStyle::LK_Java)
383*67e74705SXin Li     State.Stack.back().NoLineBreak = true;
384*67e74705SXin Li   if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&
385*67e74705SXin Li       (Previous.MatchingParen &&
386*67e74705SXin Li        (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10))) {
387*67e74705SXin Li     // If there is a function call with long parameters, break before trailing
388*67e74705SXin Li     // calls. This prevents things like:
389*67e74705SXin Li     //   EXPECT_CALL(SomeLongParameter).Times(
390*67e74705SXin Li     //       2);
391*67e74705SXin Li     // We don't want to do this for short parameters as they can just be
392*67e74705SXin Li     // indexes.
393*67e74705SXin Li     State.Stack.back().NoLineBreak = true;
394*67e74705SXin Li   }
395*67e74705SXin Li 
396*67e74705SXin Li   State.Column += Spaces;
397*67e74705SXin Li   if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&
398*67e74705SXin Li       Previous.Previous &&
399*67e74705SXin Li       Previous.Previous->isOneOf(tok::kw_if, tok::kw_for)) {
400*67e74705SXin Li     // Treat the condition inside an if as if it was a second function
401*67e74705SXin Li     // parameter, i.e. let nested calls have a continuation indent.
402*67e74705SXin Li     State.Stack.back().LastSpace = State.Column;
403*67e74705SXin Li     State.Stack.back().NestedBlockIndent = State.Column;
404*67e74705SXin Li   } else if (!Current.isOneOf(tok::comment, tok::caret) &&
405*67e74705SXin Li              ((Previous.is(tok::comma) &&
406*67e74705SXin Li                !Previous.is(TT_OverloadedOperator)) ||
407*67e74705SXin Li               (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) {
408*67e74705SXin Li     State.Stack.back().LastSpace = State.Column;
409*67e74705SXin Li   } else if ((Previous.isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
410*67e74705SXin Li                                TT_CtorInitializerColon)) &&
411*67e74705SXin Li              ((Previous.getPrecedence() != prec::Assignment &&
412*67e74705SXin Li                (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||
413*67e74705SXin Li                 Previous.NextOperator)) ||
414*67e74705SXin Li               Current.StartsBinaryExpression)) {
415*67e74705SXin Li     // Indent relative to the RHS of the expression unless this is a simple
416*67e74705SXin Li     // assignment without binary expression on the RHS. Also indent relative to
417*67e74705SXin Li     // unary operators and the colons of constructor initializers.
418*67e74705SXin Li     State.Stack.back().LastSpace = State.Column;
419*67e74705SXin Li   } else if (Previous.is(TT_InheritanceColon)) {
420*67e74705SXin Li     State.Stack.back().Indent = State.Column;
421*67e74705SXin Li     State.Stack.back().LastSpace = State.Column;
422*67e74705SXin Li   } else if (Previous.opensScope()) {
423*67e74705SXin Li     // If a function has a trailing call, indent all parameters from the
424*67e74705SXin Li     // opening parenthesis. This avoids confusing indents like:
425*67e74705SXin Li     //   OuterFunction(InnerFunctionCall( // break
426*67e74705SXin Li     //       ParameterToInnerFunction))   // break
427*67e74705SXin Li     //       .SecondInnerFunctionCall();
428*67e74705SXin Li     bool HasTrailingCall = false;
429*67e74705SXin Li     if (Previous.MatchingParen) {
430*67e74705SXin Li       const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
431*67e74705SXin Li       HasTrailingCall = Next && Next->isMemberAccess();
432*67e74705SXin Li     }
433*67e74705SXin Li     if (HasTrailingCall && State.Stack.size() > 1 &&
434*67e74705SXin Li         State.Stack[State.Stack.size() - 2].CallContinuation == 0)
435*67e74705SXin Li       State.Stack.back().LastSpace = State.Column;
436*67e74705SXin Li   }
437*67e74705SXin Li }
438*67e74705SXin Li 
addTokenOnNewLine(LineState & State,bool DryRun)439*67e74705SXin Li unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
440*67e74705SXin Li                                                  bool DryRun) {
441*67e74705SXin Li   FormatToken &Current = *State.NextToken;
442*67e74705SXin Li   const FormatToken &Previous = *State.NextToken->Previous;
443*67e74705SXin Li 
444*67e74705SXin Li   // Extra penalty that needs to be added because of the way certain line
445*67e74705SXin Li   // breaks are chosen.
446*67e74705SXin Li   unsigned Penalty = 0;
447*67e74705SXin Li 
448*67e74705SXin Li   const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
449*67e74705SXin Li   const FormatToken *NextNonComment = Previous.getNextNonComment();
450*67e74705SXin Li   if (!NextNonComment)
451*67e74705SXin Li     NextNonComment = &Current;
452*67e74705SXin Li   // The first line break on any NestingLevel causes an extra penalty in order
453*67e74705SXin Li   // prefer similar line breaks.
454*67e74705SXin Li   if (!State.Stack.back().ContainsLineBreak)
455*67e74705SXin Li     Penalty += 15;
456*67e74705SXin Li   State.Stack.back().ContainsLineBreak = true;
457*67e74705SXin Li 
458*67e74705SXin Li   Penalty += State.NextToken->SplitPenalty;
459*67e74705SXin Li 
460*67e74705SXin Li   // Breaking before the first "<<" is generally not desirable if the LHS is
461*67e74705SXin Li   // short. Also always add the penalty if the LHS is split over mutliple lines
462*67e74705SXin Li   // to avoid unnecessary line breaks that just work around this penalty.
463*67e74705SXin Li   if (NextNonComment->is(tok::lessless) &&
464*67e74705SXin Li       State.Stack.back().FirstLessLess == 0 &&
465*67e74705SXin Li       (State.Column <= Style.ColumnLimit / 3 ||
466*67e74705SXin Li        State.Stack.back().BreakBeforeParameter))
467*67e74705SXin Li     Penalty += Style.PenaltyBreakFirstLessLess;
468*67e74705SXin Li 
469*67e74705SXin Li   State.Column = getNewLineColumn(State);
470*67e74705SXin Li 
471*67e74705SXin Li   // Indent nested blocks relative to this column, unless in a very specific
472*67e74705SXin Li   // JavaScript special case where:
473*67e74705SXin Li   //
474*67e74705SXin Li   //   var loooooong_name =
475*67e74705SXin Li   //       function() {
476*67e74705SXin Li   //     // code
477*67e74705SXin Li   //   }
478*67e74705SXin Li   //
479*67e74705SXin Li   // is common and should be formatted like a free-standing function. The same
480*67e74705SXin Li   // goes for wrapping before the lambda return type arrow.
481*67e74705SXin Li   if (!Current.is(TT_LambdaArrow) &&
482*67e74705SXin Li       (Style.Language != FormatStyle::LK_JavaScript ||
483*67e74705SXin Li        Current.NestingLevel != 0 || !PreviousNonComment ||
484*67e74705SXin Li        !PreviousNonComment->is(tok::equal) ||
485*67e74705SXin Li        !Current.isOneOf(Keywords.kw_async, Keywords.kw_function)))
486*67e74705SXin Li     State.Stack.back().NestedBlockIndent = State.Column;
487*67e74705SXin Li 
488*67e74705SXin Li   if (NextNonComment->isMemberAccess()) {
489*67e74705SXin Li     if (State.Stack.back().CallContinuation == 0)
490*67e74705SXin Li       State.Stack.back().CallContinuation = State.Column;
491*67e74705SXin Li   } else if (NextNonComment->is(TT_SelectorName)) {
492*67e74705SXin Li     if (!State.Stack.back().ObjCSelectorNameFound) {
493*67e74705SXin Li       if (NextNonComment->LongestObjCSelectorName == 0) {
494*67e74705SXin Li         State.Stack.back().AlignColons = false;
495*67e74705SXin Li       } else {
496*67e74705SXin Li         State.Stack.back().ColonPos =
497*67e74705SXin Li             (Style.IndentWrappedFunctionNames
498*67e74705SXin Li                  ? std::max(State.Stack.back().Indent,
499*67e74705SXin Li                             State.FirstIndent + Style.ContinuationIndentWidth)
500*67e74705SXin Li                  : State.Stack.back().Indent) +
501*67e74705SXin Li             NextNonComment->LongestObjCSelectorName;
502*67e74705SXin Li       }
503*67e74705SXin Li     } else if (State.Stack.back().AlignColons &&
504*67e74705SXin Li                State.Stack.back().ColonPos <= NextNonComment->ColumnWidth) {
505*67e74705SXin Li       State.Stack.back().ColonPos = State.Column + NextNonComment->ColumnWidth;
506*67e74705SXin Li     }
507*67e74705SXin Li   } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
508*67e74705SXin Li              PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
509*67e74705SXin Li     // FIXME: This is hacky, find a better way. The problem is that in an ObjC
510*67e74705SXin Li     // method expression, the block should be aligned to the line starting it,
511*67e74705SXin Li     // e.g.:
512*67e74705SXin Li     //   [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
513*67e74705SXin Li     //                        ^(int *i) {
514*67e74705SXin Li     //                            // ...
515*67e74705SXin Li     //                        }];
516*67e74705SXin Li     // Thus, we set LastSpace of the next higher NestingLevel, to which we move
517*67e74705SXin Li     // when we consume all of the "}"'s FakeRParens at the "{".
518*67e74705SXin Li     if (State.Stack.size() > 1)
519*67e74705SXin Li       State.Stack[State.Stack.size() - 2].LastSpace =
520*67e74705SXin Li           std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
521*67e74705SXin Li           Style.ContinuationIndentWidth;
522*67e74705SXin Li   }
523*67e74705SXin Li 
524*67e74705SXin Li   if ((Previous.isOneOf(tok::comma, tok::semi) &&
525*67e74705SXin Li        !State.Stack.back().AvoidBinPacking) ||
526*67e74705SXin Li       Previous.is(TT_BinaryOperator))
527*67e74705SXin Li     State.Stack.back().BreakBeforeParameter = false;
528*67e74705SXin Li   if (Previous.isOneOf(TT_TemplateCloser, TT_JavaAnnotation) &&
529*67e74705SXin Li       Current.NestingLevel == 0)
530*67e74705SXin Li     State.Stack.back().BreakBeforeParameter = false;
531*67e74705SXin Li   if (NextNonComment->is(tok::question) ||
532*67e74705SXin Li       (PreviousNonComment && PreviousNonComment->is(tok::question)))
533*67e74705SXin Li     State.Stack.back().BreakBeforeParameter = true;
534*67e74705SXin Li   if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore)
535*67e74705SXin Li     State.Stack.back().BreakBeforeParameter = false;
536*67e74705SXin Li 
537*67e74705SXin Li   if (!DryRun) {
538*67e74705SXin Li     unsigned Newlines = std::max(
539*67e74705SXin Li         1u, std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1));
540*67e74705SXin Li     Whitespaces.replaceWhitespace(Current, Newlines,
541*67e74705SXin Li                                   State.Stack.back().IndentLevel, State.Column,
542*67e74705SXin Li                                   State.Column, State.Line->InPPDirective);
543*67e74705SXin Li   }
544*67e74705SXin Li 
545*67e74705SXin Li   if (!Current.isTrailingComment())
546*67e74705SXin Li     State.Stack.back().LastSpace = State.Column;
547*67e74705SXin Li   if (Current.is(tok::lessless))
548*67e74705SXin Li     // If we are breaking before a "<<", we always want to indent relative to
549*67e74705SXin Li     // RHS. This is necessary only for "<<", as we special-case it and don't
550*67e74705SXin Li     // always indent relative to the RHS.
551*67e74705SXin Li     State.Stack.back().LastSpace += 3; // 3 -> width of "<< ".
552*67e74705SXin Li 
553*67e74705SXin Li   State.StartOfLineLevel = Current.NestingLevel;
554*67e74705SXin Li   State.LowestLevelOnLine = Current.NestingLevel;
555*67e74705SXin Li 
556*67e74705SXin Li   // Any break on this level means that the parent level has been broken
557*67e74705SXin Li   // and we need to avoid bin packing there.
558*67e74705SXin Li   bool NestedBlockSpecialCase =
559*67e74705SXin Li       Style.Language != FormatStyle::LK_Cpp &&
560*67e74705SXin Li       Current.is(tok::r_brace) && State.Stack.size() > 1 &&
561*67e74705SXin Li       State.Stack[State.Stack.size() - 2].NestedBlockInlined;
562*67e74705SXin Li   if (!NestedBlockSpecialCase)
563*67e74705SXin Li     for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
564*67e74705SXin Li       State.Stack[i].BreakBeforeParameter = true;
565*67e74705SXin Li 
566*67e74705SXin Li   if (PreviousNonComment &&
567*67e74705SXin Li       !PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
568*67e74705SXin Li       (PreviousNonComment->isNot(TT_TemplateCloser) ||
569*67e74705SXin Li        Current.NestingLevel != 0) &&
570*67e74705SXin Li       !PreviousNonComment->isOneOf(
571*67e74705SXin Li           TT_BinaryOperator, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
572*67e74705SXin Li           TT_LeadingJavaAnnotation) &&
573*67e74705SXin Li       Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope())
574*67e74705SXin Li     State.Stack.back().BreakBeforeParameter = true;
575*67e74705SXin Li 
576*67e74705SXin Li   // If we break after { or the [ of an array initializer, we should also break
577*67e74705SXin Li   // before the corresponding } or ].
578*67e74705SXin Li   if (PreviousNonComment &&
579*67e74705SXin Li       (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)))
580*67e74705SXin Li     State.Stack.back().BreakBeforeClosingBrace = true;
581*67e74705SXin Li 
582*67e74705SXin Li   if (State.Stack.back().AvoidBinPacking) {
583*67e74705SXin Li     // If we are breaking after '(', '{', '<', this is not bin packing
584*67e74705SXin Li     // unless AllowAllParametersOfDeclarationOnNextLine is false or this is a
585*67e74705SXin Li     // dict/object literal.
586*67e74705SXin Li     if (!Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) ||
587*67e74705SXin Li         (!Style.AllowAllParametersOfDeclarationOnNextLine &&
588*67e74705SXin Li          State.Line->MustBeDeclaration) ||
589*67e74705SXin Li         Previous.is(TT_DictLiteral))
590*67e74705SXin Li       State.Stack.back().BreakBeforeParameter = true;
591*67e74705SXin Li   }
592*67e74705SXin Li 
593*67e74705SXin Li   return Penalty;
594*67e74705SXin Li }
595*67e74705SXin Li 
getNewLineColumn(const LineState & State)596*67e74705SXin Li unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
597*67e74705SXin Li   if (!State.NextToken || !State.NextToken->Previous)
598*67e74705SXin Li     return 0;
599*67e74705SXin Li   FormatToken &Current = *State.NextToken;
600*67e74705SXin Li   const FormatToken &Previous = *Current.Previous;
601*67e74705SXin Li   // If we are continuing an expression, we want to use the continuation indent.
602*67e74705SXin Li   unsigned ContinuationIndent =
603*67e74705SXin Li       std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
604*67e74705SXin Li       Style.ContinuationIndentWidth;
605*67e74705SXin Li   const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
606*67e74705SXin Li   const FormatToken *NextNonComment = Previous.getNextNonComment();
607*67e74705SXin Li   if (!NextNonComment)
608*67e74705SXin Li     NextNonComment = &Current;
609*67e74705SXin Li 
610*67e74705SXin Li   // Java specific bits.
611*67e74705SXin Li   if (Style.Language == FormatStyle::LK_Java &&
612*67e74705SXin Li       Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends))
613*67e74705SXin Li     return std::max(State.Stack.back().LastSpace,
614*67e74705SXin Li                     State.Stack.back().Indent + Style.ContinuationIndentWidth);
615*67e74705SXin Li 
616*67e74705SXin Li   if (NextNonComment->is(tok::l_brace) && NextNonComment->BlockKind == BK_Block)
617*67e74705SXin Li     return Current.NestingLevel == 0 ? State.FirstIndent
618*67e74705SXin Li                                      : State.Stack.back().Indent;
619*67e74705SXin Li   if (Current.isOneOf(tok::r_brace, tok::r_square) && State.Stack.size() > 1) {
620*67e74705SXin Li     if (Current.closesBlockOrBlockTypeList(Style))
621*67e74705SXin Li       return State.Stack[State.Stack.size() - 2].NestedBlockIndent;
622*67e74705SXin Li     if (Current.MatchingParen &&
623*67e74705SXin Li         Current.MatchingParen->BlockKind == BK_BracedInit)
624*67e74705SXin Li       return State.Stack[State.Stack.size() - 2].LastSpace;
625*67e74705SXin Li     return State.FirstIndent;
626*67e74705SXin Li   }
627*67e74705SXin Li   if (Current.is(tok::identifier) && Current.Next &&
628*67e74705SXin Li       Current.Next->is(TT_DictLiteral))
629*67e74705SXin Li     return State.Stack.back().Indent;
630*67e74705SXin Li   if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
631*67e74705SXin Li     return State.StartOfStringLiteral;
632*67e74705SXin Li   if (NextNonComment->is(TT_ObjCStringLiteral) &&
633*67e74705SXin Li       State.StartOfStringLiteral != 0)
634*67e74705SXin Li     return State.StartOfStringLiteral - 1;
635*67e74705SXin Li   if (NextNonComment->is(tok::lessless) &&
636*67e74705SXin Li       State.Stack.back().FirstLessLess != 0)
637*67e74705SXin Li     return State.Stack.back().FirstLessLess;
638*67e74705SXin Li   if (NextNonComment->isMemberAccess()) {
639*67e74705SXin Li     if (State.Stack.back().CallContinuation == 0)
640*67e74705SXin Li       return ContinuationIndent;
641*67e74705SXin Li     return State.Stack.back().CallContinuation;
642*67e74705SXin Li   }
643*67e74705SXin Li   if (State.Stack.back().QuestionColumn != 0 &&
644*67e74705SXin Li       ((NextNonComment->is(tok::colon) &&
645*67e74705SXin Li         NextNonComment->is(TT_ConditionalExpr)) ||
646*67e74705SXin Li        Previous.is(TT_ConditionalExpr)))
647*67e74705SXin Li     return State.Stack.back().QuestionColumn;
648*67e74705SXin Li   if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0)
649*67e74705SXin Li     return State.Stack.back().VariablePos;
650*67e74705SXin Li   if ((PreviousNonComment &&
651*67e74705SXin Li        (PreviousNonComment->ClosesTemplateDeclaration ||
652*67e74705SXin Li         PreviousNonComment->isOneOf(
653*67e74705SXin Li             TT_AttributeParen, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
654*67e74705SXin Li             TT_LeadingJavaAnnotation))) ||
655*67e74705SXin Li       (!Style.IndentWrappedFunctionNames &&
656*67e74705SXin Li        NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName)))
657*67e74705SXin Li     return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
658*67e74705SXin Li   if (NextNonComment->is(TT_SelectorName)) {
659*67e74705SXin Li     if (!State.Stack.back().ObjCSelectorNameFound) {
660*67e74705SXin Li       if (NextNonComment->LongestObjCSelectorName == 0)
661*67e74705SXin Li         return State.Stack.back().Indent;
662*67e74705SXin Li       return (Style.IndentWrappedFunctionNames
663*67e74705SXin Li                   ? std::max(State.Stack.back().Indent,
664*67e74705SXin Li                              State.FirstIndent + Style.ContinuationIndentWidth)
665*67e74705SXin Li                   : State.Stack.back().Indent) +
666*67e74705SXin Li              NextNonComment->LongestObjCSelectorName -
667*67e74705SXin Li              NextNonComment->ColumnWidth;
668*67e74705SXin Li     }
669*67e74705SXin Li     if (!State.Stack.back().AlignColons)
670*67e74705SXin Li       return State.Stack.back().Indent;
671*67e74705SXin Li     if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth)
672*67e74705SXin Li       return State.Stack.back().ColonPos - NextNonComment->ColumnWidth;
673*67e74705SXin Li     return State.Stack.back().Indent;
674*67e74705SXin Li   }
675*67e74705SXin Li   if (NextNonComment->is(TT_ArraySubscriptLSquare)) {
676*67e74705SXin Li     if (State.Stack.back().StartOfArraySubscripts != 0)
677*67e74705SXin Li       return State.Stack.back().StartOfArraySubscripts;
678*67e74705SXin Li     return ContinuationIndent;
679*67e74705SXin Li   }
680*67e74705SXin Li 
681*67e74705SXin Li   // This ensure that we correctly format ObjC methods calls without inputs,
682*67e74705SXin Li   // i.e. where the last element isn't selector like: [callee method];
683*67e74705SXin Li   if (NextNonComment->is(tok::identifier) && NextNonComment->FakeRParens == 0 &&
684*67e74705SXin Li       NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr))
685*67e74705SXin Li     return State.Stack.back().Indent;
686*67e74705SXin Li 
687*67e74705SXin Li   if (NextNonComment->isOneOf(TT_StartOfName, TT_PointerOrReference) ||
688*67e74705SXin Li       Previous.isOneOf(tok::coloncolon, tok::equal, TT_JsTypeColon))
689*67e74705SXin Li     return ContinuationIndent;
690*67e74705SXin Li   if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
691*67e74705SXin Li       PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))
692*67e74705SXin Li     return ContinuationIndent;
693*67e74705SXin Li   if (NextNonComment->is(TT_CtorInitializerColon))
694*67e74705SXin Li     return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
695*67e74705SXin Li   if (NextNonComment->is(TT_CtorInitializerComma))
696*67e74705SXin Li     return State.Stack.back().Indent;
697*67e74705SXin Li   if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() &&
698*67e74705SXin Li       !Current.isOneOf(tok::colon, tok::comment))
699*67e74705SXin Li     return ContinuationIndent;
700*67e74705SXin Li   if (State.Stack.back().Indent == State.FirstIndent && PreviousNonComment &&
701*67e74705SXin Li       PreviousNonComment->isNot(tok::r_brace))
702*67e74705SXin Li     // Ensure that we fall back to the continuation indent width instead of
703*67e74705SXin Li     // just flushing continuations left.
704*67e74705SXin Li     return State.Stack.back().Indent + Style.ContinuationIndentWidth;
705*67e74705SXin Li   return State.Stack.back().Indent;
706*67e74705SXin Li }
707*67e74705SXin Li 
moveStateToNextToken(LineState & State,bool DryRun,bool Newline)708*67e74705SXin Li unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
709*67e74705SXin Li                                                     bool DryRun, bool Newline) {
710*67e74705SXin Li   assert(State.Stack.size());
711*67e74705SXin Li   const FormatToken &Current = *State.NextToken;
712*67e74705SXin Li 
713*67e74705SXin Li   if (Current.is(TT_InheritanceColon))
714*67e74705SXin Li     State.Stack.back().AvoidBinPacking = true;
715*67e74705SXin Li   if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) {
716*67e74705SXin Li     if (State.Stack.back().FirstLessLess == 0)
717*67e74705SXin Li       State.Stack.back().FirstLessLess = State.Column;
718*67e74705SXin Li     else
719*67e74705SXin Li       State.Stack.back().LastOperatorWrapped = Newline;
720*67e74705SXin Li   }
721*67e74705SXin Li   if ((Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless)) ||
722*67e74705SXin Li       Current.is(TT_ConditionalExpr))
723*67e74705SXin Li     State.Stack.back().LastOperatorWrapped = Newline;
724*67e74705SXin Li   if (Current.is(TT_ArraySubscriptLSquare) &&
725*67e74705SXin Li       State.Stack.back().StartOfArraySubscripts == 0)
726*67e74705SXin Li     State.Stack.back().StartOfArraySubscripts = State.Column;
727*67e74705SXin Li   if (Style.BreakBeforeTernaryOperators && Current.is(tok::question))
728*67e74705SXin Li     State.Stack.back().QuestionColumn = State.Column;
729*67e74705SXin Li   if (!Style.BreakBeforeTernaryOperators && Current.isNot(tok::colon)) {
730*67e74705SXin Li     const FormatToken *Previous = Current.Previous;
731*67e74705SXin Li     while (Previous && Previous->isTrailingComment())
732*67e74705SXin Li       Previous = Previous->Previous;
733*67e74705SXin Li     if (Previous && Previous->is(tok::question))
734*67e74705SXin Li       State.Stack.back().QuestionColumn = State.Column;
735*67e74705SXin Li   }
736*67e74705SXin Li   if (!Current.opensScope() && !Current.closesScope())
737*67e74705SXin Li     State.LowestLevelOnLine =
738*67e74705SXin Li         std::min(State.LowestLevelOnLine, Current.NestingLevel);
739*67e74705SXin Li   if (Current.isMemberAccess())
740*67e74705SXin Li     State.Stack.back().StartOfFunctionCall =
741*67e74705SXin Li         !Current.NextOperator ? 0 : State.Column;
742*67e74705SXin Li   if (Current.is(TT_SelectorName)) {
743*67e74705SXin Li     State.Stack.back().ObjCSelectorNameFound = true;
744*67e74705SXin Li     if (Style.IndentWrappedFunctionNames) {
745*67e74705SXin Li       State.Stack.back().Indent =
746*67e74705SXin Li           State.FirstIndent + Style.ContinuationIndentWidth;
747*67e74705SXin Li     }
748*67e74705SXin Li   }
749*67e74705SXin Li   if (Current.is(TT_CtorInitializerColon)) {
750*67e74705SXin Li     // Indent 2 from the column, so:
751*67e74705SXin Li     // SomeClass::SomeClass()
752*67e74705SXin Li     //     : First(...), ...
753*67e74705SXin Li     //       Next(...)
754*67e74705SXin Li     //       ^ line up here.
755*67e74705SXin Li     State.Stack.back().Indent =
756*67e74705SXin Li         State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
757*67e74705SXin Li     State.Stack.back().NestedBlockIndent = State.Stack.back().Indent;
758*67e74705SXin Li     if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
759*67e74705SXin Li       State.Stack.back().AvoidBinPacking = true;
760*67e74705SXin Li     State.Stack.back().BreakBeforeParameter = false;
761*67e74705SXin Li   }
762*67e74705SXin Li   if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline)
763*67e74705SXin Li     State.Stack.back().NestedBlockIndent =
764*67e74705SXin Li         State.Column + Current.ColumnWidth + 1;
765*67e74705SXin Li 
766*67e74705SXin Li   // Insert scopes created by fake parenthesis.
767*67e74705SXin Li   const FormatToken *Previous = Current.getPreviousNonComment();
768*67e74705SXin Li 
769*67e74705SXin Li   // Add special behavior to support a format commonly used for JavaScript
770*67e74705SXin Li   // closures:
771*67e74705SXin Li   //   SomeFunction(function() {
772*67e74705SXin Li   //     foo();
773*67e74705SXin Li   //     bar();
774*67e74705SXin Li   //   }, a, b, c);
775*67e74705SXin Li   if (Current.isNot(tok::comment) && Previous &&
776*67e74705SXin Li       Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
777*67e74705SXin Li       !Previous->is(TT_DictLiteral) && State.Stack.size() > 1) {
778*67e74705SXin Li     if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline)
779*67e74705SXin Li       for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
780*67e74705SXin Li         State.Stack[i].NoLineBreak = true;
781*67e74705SXin Li     State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;
782*67e74705SXin Li   }
783*67e74705SXin Li   if (Previous && (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) ||
784*67e74705SXin Li                    Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr)) &&
785*67e74705SXin Li       !Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
786*67e74705SXin Li     State.Stack.back().NestedBlockInlined =
787*67e74705SXin Li         !Newline &&
788*67e74705SXin Li         (Previous->isNot(tok::l_paren) || Previous->ParameterCount > 1);
789*67e74705SXin Li   }
790*67e74705SXin Li 
791*67e74705SXin Li   moveStatePastFakeLParens(State, Newline);
792*67e74705SXin Li   moveStatePastScopeOpener(State, Newline);
793*67e74705SXin Li   moveStatePastScopeCloser(State);
794*67e74705SXin Li   moveStatePastFakeRParens(State);
795*67e74705SXin Li 
796*67e74705SXin Li   if (Current.isStringLiteral() && State.StartOfStringLiteral == 0)
797*67e74705SXin Li     State.StartOfStringLiteral = State.Column;
798*67e74705SXin Li   if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0)
799*67e74705SXin Li     State.StartOfStringLiteral = State.Column + 1;
800*67e74705SXin Li   else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
801*67e74705SXin Li            !Current.isStringLiteral())
802*67e74705SXin Li     State.StartOfStringLiteral = 0;
803*67e74705SXin Li 
804*67e74705SXin Li   State.Column += Current.ColumnWidth;
805*67e74705SXin Li   State.NextToken = State.NextToken->Next;
806*67e74705SXin Li   unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
807*67e74705SXin Li   if (State.Column > getColumnLimit(State)) {
808*67e74705SXin Li     unsigned ExcessCharacters = State.Column - getColumnLimit(State);
809*67e74705SXin Li     Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
810*67e74705SXin Li   }
811*67e74705SXin Li 
812*67e74705SXin Li   if (Current.Role)
813*67e74705SXin Li     Current.Role->formatFromToken(State, this, DryRun);
814*67e74705SXin Li   // If the previous has a special role, let it consume tokens as appropriate.
815*67e74705SXin Li   // It is necessary to start at the previous token for the only implemented
816*67e74705SXin Li   // role (comma separated list). That way, the decision whether or not to break
817*67e74705SXin Li   // after the "{" is already done and both options are tried and evaluated.
818*67e74705SXin Li   // FIXME: This is ugly, find a better way.
819*67e74705SXin Li   if (Previous && Previous->Role)
820*67e74705SXin Li     Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
821*67e74705SXin Li 
822*67e74705SXin Li   return Penalty;
823*67e74705SXin Li }
824*67e74705SXin Li 
moveStatePastFakeLParens(LineState & State,bool Newline)825*67e74705SXin Li void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
826*67e74705SXin Li                                                     bool Newline) {
827*67e74705SXin Li   const FormatToken &Current = *State.NextToken;
828*67e74705SXin Li   const FormatToken *Previous = Current.getPreviousNonComment();
829*67e74705SXin Li 
830*67e74705SXin Li   // Don't add extra indentation for the first fake parenthesis after
831*67e74705SXin Li   // 'return', assignments or opening <({[. The indentation for these cases
832*67e74705SXin Li   // is special cased.
833*67e74705SXin Li   bool SkipFirstExtraIndent =
834*67e74705SXin Li       (Previous && (Previous->opensScope() ||
835*67e74705SXin Li                     Previous->isOneOf(tok::semi, tok::kw_return) ||
836*67e74705SXin Li                     (Previous->getPrecedence() == prec::Assignment &&
837*67e74705SXin Li                      Style.AlignOperands) ||
838*67e74705SXin Li                     Previous->is(TT_ObjCMethodExpr)));
839*67e74705SXin Li   for (SmallVectorImpl<prec::Level>::const_reverse_iterator
840*67e74705SXin Li            I = Current.FakeLParens.rbegin(),
841*67e74705SXin Li            E = Current.FakeLParens.rend();
842*67e74705SXin Li        I != E; ++I) {
843*67e74705SXin Li     ParenState NewParenState = State.Stack.back();
844*67e74705SXin Li     NewParenState.ContainsLineBreak = false;
845*67e74705SXin Li 
846*67e74705SXin Li     // Indent from 'LastSpace' unless these are fake parentheses encapsulating
847*67e74705SXin Li     // a builder type call after 'return' or, if the alignment after opening
848*67e74705SXin Li     // brackets is disabled.
849*67e74705SXin Li     if (!Current.isTrailingComment() &&
850*67e74705SXin Li         (Style.AlignOperands || *I < prec::Assignment) &&
851*67e74705SXin Li         (!Previous || Previous->isNot(tok::kw_return) ||
852*67e74705SXin Li          (Style.Language != FormatStyle::LK_Java && *I > 0)) &&
853*67e74705SXin Li         (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign ||
854*67e74705SXin Li          *I != prec::Comma || Current.NestingLevel == 0))
855*67e74705SXin Li       NewParenState.Indent =
856*67e74705SXin Li           std::max(std::max(State.Column, NewParenState.Indent),
857*67e74705SXin Li                    State.Stack.back().LastSpace);
858*67e74705SXin Li 
859*67e74705SXin Li     // Don't allow the RHS of an operator to be split over multiple lines unless
860*67e74705SXin Li     // there is a line-break right after the operator.
861*67e74705SXin Li     // Exclude relational operators, as there, it is always more desirable to
862*67e74705SXin Li     // have the LHS 'left' of the RHS.
863*67e74705SXin Li     if (Previous && Previous->getPrecedence() != prec::Assignment &&
864*67e74705SXin Li         Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
865*67e74705SXin Li         Previous->getPrecedence() != prec::Relational) {
866*67e74705SXin Li       bool BreakBeforeOperator =
867*67e74705SXin Li           Previous->is(tok::lessless) ||
868*67e74705SXin Li           (Previous->is(TT_BinaryOperator) &&
869*67e74705SXin Li            Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) ||
870*67e74705SXin Li           (Previous->is(TT_ConditionalExpr) &&
871*67e74705SXin Li            Style.BreakBeforeTernaryOperators);
872*67e74705SXin Li       if ((!Newline && !BreakBeforeOperator) ||
873*67e74705SXin Li           (!State.Stack.back().LastOperatorWrapped && BreakBeforeOperator))
874*67e74705SXin Li         NewParenState.NoLineBreak = true;
875*67e74705SXin Li     }
876*67e74705SXin Li 
877*67e74705SXin Li     // Do not indent relative to the fake parentheses inserted for "." or "->".
878*67e74705SXin Li     // This is a special case to make the following to statements consistent:
879*67e74705SXin Li     //   OuterFunction(InnerFunctionCall( // break
880*67e74705SXin Li     //       ParameterToInnerFunction));
881*67e74705SXin Li     //   OuterFunction(SomeObject.InnerFunctionCall( // break
882*67e74705SXin Li     //       ParameterToInnerFunction));
883*67e74705SXin Li     if (*I > prec::Unknown)
884*67e74705SXin Li       NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
885*67e74705SXin Li     if (*I != prec::Conditional && !Current.is(TT_UnaryOperator) &&
886*67e74705SXin Li         Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
887*67e74705SXin Li       NewParenState.StartOfFunctionCall = State.Column;
888*67e74705SXin Li 
889*67e74705SXin Li     // Always indent conditional expressions. Never indent expression where
890*67e74705SXin Li     // the 'operator' is ',', ';' or an assignment (i.e. *I <=
891*67e74705SXin Li     // prec::Assignment) as those have different indentation rules. Indent
892*67e74705SXin Li     // other expression, unless the indentation needs to be skipped.
893*67e74705SXin Li     if (*I == prec::Conditional ||
894*67e74705SXin Li         (!SkipFirstExtraIndent && *I > prec::Assignment &&
895*67e74705SXin Li          !Current.isTrailingComment()))
896*67e74705SXin Li       NewParenState.Indent += Style.ContinuationIndentWidth;
897*67e74705SXin Li     if ((Previous && !Previous->opensScope()) || *I != prec::Comma)
898*67e74705SXin Li       NewParenState.BreakBeforeParameter = false;
899*67e74705SXin Li     State.Stack.push_back(NewParenState);
900*67e74705SXin Li     SkipFirstExtraIndent = false;
901*67e74705SXin Li   }
902*67e74705SXin Li }
903*67e74705SXin Li 
moveStatePastFakeRParens(LineState & State)904*67e74705SXin Li void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
905*67e74705SXin Li   for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) {
906*67e74705SXin Li     unsigned VariablePos = State.Stack.back().VariablePos;
907*67e74705SXin Li     if (State.Stack.size() == 1) {
908*67e74705SXin Li       // Do not pop the last element.
909*67e74705SXin Li       break;
910*67e74705SXin Li     }
911*67e74705SXin Li     State.Stack.pop_back();
912*67e74705SXin Li     State.Stack.back().VariablePos = VariablePos;
913*67e74705SXin Li   }
914*67e74705SXin Li }
915*67e74705SXin Li 
moveStatePastScopeOpener(LineState & State,bool Newline)916*67e74705SXin Li void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
917*67e74705SXin Li                                                     bool Newline) {
918*67e74705SXin Li   const FormatToken &Current = *State.NextToken;
919*67e74705SXin Li   if (!Current.opensScope())
920*67e74705SXin Li     return;
921*67e74705SXin Li 
922*67e74705SXin Li   if (Current.MatchingParen && Current.BlockKind == BK_Block) {
923*67e74705SXin Li     moveStateToNewBlock(State);
924*67e74705SXin Li     return;
925*67e74705SXin Li   }
926*67e74705SXin Li 
927*67e74705SXin Li   unsigned NewIndent;
928*67e74705SXin Li   unsigned NewIndentLevel = State.Stack.back().IndentLevel;
929*67e74705SXin Li   unsigned LastSpace = State.Stack.back().LastSpace;
930*67e74705SXin Li   bool AvoidBinPacking;
931*67e74705SXin Li   bool BreakBeforeParameter = false;
932*67e74705SXin Li   unsigned NestedBlockIndent = std::max(State.Stack.back().StartOfFunctionCall,
933*67e74705SXin Li                                         State.Stack.back().NestedBlockIndent);
934*67e74705SXin Li   if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)) {
935*67e74705SXin Li     if (Current.opensBlockOrBlockTypeList(Style)) {
936*67e74705SXin Li       NewIndent = State.Stack.back().NestedBlockIndent + Style.IndentWidth;
937*67e74705SXin Li       NewIndent = std::min(State.Column + 2, NewIndent);
938*67e74705SXin Li       ++NewIndentLevel;
939*67e74705SXin Li     } else {
940*67e74705SXin Li       NewIndent = State.Stack.back().LastSpace + Style.ContinuationIndentWidth;
941*67e74705SXin Li     }
942*67e74705SXin Li     const FormatToken *NextNoComment = Current.getNextNonComment();
943*67e74705SXin Li     bool EndsInComma = Current.MatchingParen &&
944*67e74705SXin Li                        Current.MatchingParen->Previous &&
945*67e74705SXin Li                        Current.MatchingParen->Previous->is(tok::comma);
946*67e74705SXin Li     AvoidBinPacking =
947*67e74705SXin Li         (Current.is(TT_ArrayInitializerLSquare) && EndsInComma) ||
948*67e74705SXin Li         Current.is(TT_DictLiteral) ||
949*67e74705SXin Li         Style.Language == FormatStyle::LK_Proto || !Style.BinPackArguments ||
950*67e74705SXin Li         (NextNoComment && NextNoComment->is(TT_DesignatedInitializerPeriod));
951*67e74705SXin Li     if (Current.ParameterCount > 1)
952*67e74705SXin Li       NestedBlockIndent = std::max(NestedBlockIndent, State.Column + 1);
953*67e74705SXin Li   } else {
954*67e74705SXin Li     NewIndent = Style.ContinuationIndentWidth +
955*67e74705SXin Li                 std::max(State.Stack.back().LastSpace,
956*67e74705SXin Li                          State.Stack.back().StartOfFunctionCall);
957*67e74705SXin Li 
958*67e74705SXin Li     // Ensure that different different brackets force relative alignment, e.g.:
959*67e74705SXin Li     // void SomeFunction(vector<  // break
960*67e74705SXin Li     //                       int> v);
961*67e74705SXin Li     // FIXME: We likely want to do this for more combinations of brackets.
962*67e74705SXin Li     // Verify that it is wanted for ObjC, too.
963*67e74705SXin Li     if (Current.Tok.getKind() == tok::less &&
964*67e74705SXin Li         Current.ParentBracket == tok::l_paren) {
965*67e74705SXin Li       NewIndent = std::max(NewIndent, State.Stack.back().Indent);
966*67e74705SXin Li       LastSpace = std::max(LastSpace, State.Stack.back().Indent);
967*67e74705SXin Li     }
968*67e74705SXin Li 
969*67e74705SXin Li     AvoidBinPacking =
970*67e74705SXin Li         (State.Line->MustBeDeclaration && !Style.BinPackParameters) ||
971*67e74705SXin Li         (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||
972*67e74705SXin Li         (Style.ExperimentalAutoDetectBinPacking &&
973*67e74705SXin Li          (Current.PackingKind == PPK_OnePerLine ||
974*67e74705SXin Li           (!BinPackInconclusiveFunctions &&
975*67e74705SXin Li            Current.PackingKind == PPK_Inconclusive)));
976*67e74705SXin Li     if (Current.is(TT_ObjCMethodExpr) && Current.MatchingParen) {
977*67e74705SXin Li       if (Style.ColumnLimit) {
978*67e74705SXin Li         // If this '[' opens an ObjC call, determine whether all parameters fit
979*67e74705SXin Li         // into one line and put one per line if they don't.
980*67e74705SXin Li         if (getLengthToMatchingParen(Current) + State.Column >
981*67e74705SXin Li             getColumnLimit(State))
982*67e74705SXin Li           BreakBeforeParameter = true;
983*67e74705SXin Li       } else {
984*67e74705SXin Li         // For ColumnLimit = 0, we have to figure out whether there is or has to
985*67e74705SXin Li         // be a line break within this call.
986*67e74705SXin Li         for (const FormatToken *Tok = &Current;
987*67e74705SXin Li              Tok && Tok != Current.MatchingParen; Tok = Tok->Next) {
988*67e74705SXin Li           if (Tok->MustBreakBefore ||
989*67e74705SXin Li               (Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) {
990*67e74705SXin Li             BreakBeforeParameter = true;
991*67e74705SXin Li             break;
992*67e74705SXin Li           }
993*67e74705SXin Li         }
994*67e74705SXin Li       }
995*67e74705SXin Li     }
996*67e74705SXin Li   }
997*67e74705SXin Li   // Generally inherit NoLineBreak from the current scope to nested scope.
998*67e74705SXin Li   // However, don't do this for non-empty nested blocks, dict literals and
999*67e74705SXin Li   // array literals as these follow different indentation rules.
1000*67e74705SXin Li   bool NoLineBreak =
1001*67e74705SXin Li       Current.Children.empty() &&
1002*67e74705SXin Li       !Current.isOneOf(TT_DictLiteral, TT_ArrayInitializerLSquare) &&
1003*67e74705SXin Li       (State.Stack.back().NoLineBreak ||
1004*67e74705SXin Li        (Current.is(TT_TemplateOpener) &&
1005*67e74705SXin Li         State.Stack.back().ContainsUnwrappedBuilder));
1006*67e74705SXin Li   State.Stack.push_back(ParenState(NewIndent, NewIndentLevel, LastSpace,
1007*67e74705SXin Li                                    AvoidBinPacking, NoLineBreak));
1008*67e74705SXin Li   State.Stack.back().NestedBlockIndent = NestedBlockIndent;
1009*67e74705SXin Li   State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
1010*67e74705SXin Li   State.Stack.back().HasMultipleNestedBlocks = Current.BlockParameterCount > 1;
1011*67e74705SXin Li }
1012*67e74705SXin Li 
moveStatePastScopeCloser(LineState & State)1013*67e74705SXin Li void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
1014*67e74705SXin Li   const FormatToken &Current = *State.NextToken;
1015*67e74705SXin Li   if (!Current.closesScope())
1016*67e74705SXin Li     return;
1017*67e74705SXin Li 
1018*67e74705SXin Li   // If we encounter a closing ), ], } or >, we can remove a level from our
1019*67e74705SXin Li   // stacks.
1020*67e74705SXin Li   if (State.Stack.size() > 1 &&
1021*67e74705SXin Li       (Current.isOneOf(tok::r_paren, tok::r_square) ||
1022*67e74705SXin Li        (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
1023*67e74705SXin Li        State.NextToken->is(TT_TemplateCloser)))
1024*67e74705SXin Li     State.Stack.pop_back();
1025*67e74705SXin Li 
1026*67e74705SXin Li   if (Current.is(tok::r_square)) {
1027*67e74705SXin Li     // If this ends the array subscript expr, reset the corresponding value.
1028*67e74705SXin Li     const FormatToken *NextNonComment = Current.getNextNonComment();
1029*67e74705SXin Li     if (NextNonComment && NextNonComment->isNot(tok::l_square))
1030*67e74705SXin Li       State.Stack.back().StartOfArraySubscripts = 0;
1031*67e74705SXin Li   }
1032*67e74705SXin Li }
1033*67e74705SXin Li 
moveStateToNewBlock(LineState & State)1034*67e74705SXin Li void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
1035*67e74705SXin Li   unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
1036*67e74705SXin Li   // ObjC block sometimes follow special indentation rules.
1037*67e74705SXin Li   unsigned NewIndent =
1038*67e74705SXin Li       NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace)
1039*67e74705SXin Li                                ? Style.ObjCBlockIndentWidth
1040*67e74705SXin Li                                : Style.IndentWidth);
1041*67e74705SXin Li   State.Stack.push_back(ParenState(
1042*67e74705SXin Li       NewIndent, /*NewIndentLevel=*/State.Stack.back().IndentLevel + 1,
1043*67e74705SXin Li       State.Stack.back().LastSpace, /*AvoidBinPacking=*/true,
1044*67e74705SXin Li       /*NoLineBreak=*/false));
1045*67e74705SXin Li   State.Stack.back().NestedBlockIndent = NestedBlockIndent;
1046*67e74705SXin Li   State.Stack.back().BreakBeforeParameter = true;
1047*67e74705SXin Li }
1048*67e74705SXin Li 
addMultilineToken(const FormatToken & Current,LineState & State)1049*67e74705SXin Li unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
1050*67e74705SXin Li                                                  LineState &State) {
1051*67e74705SXin Li   if (!Current.IsMultiline)
1052*67e74705SXin Li     return 0;
1053*67e74705SXin Li 
1054*67e74705SXin Li   // Break before further function parameters on all levels.
1055*67e74705SXin Li   for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1056*67e74705SXin Li     State.Stack[i].BreakBeforeParameter = true;
1057*67e74705SXin Li 
1058*67e74705SXin Li   unsigned ColumnsUsed = State.Column;
1059*67e74705SXin Li   // We can only affect layout of the first and the last line, so the penalty
1060*67e74705SXin Li   // for all other lines is constant, and we ignore it.
1061*67e74705SXin Li   State.Column = Current.LastLineColumnWidth;
1062*67e74705SXin Li 
1063*67e74705SXin Li   if (ColumnsUsed > getColumnLimit(State))
1064*67e74705SXin Li     return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
1065*67e74705SXin Li   return 0;
1066*67e74705SXin Li }
1067*67e74705SXin Li 
breakProtrudingToken(const FormatToken & Current,LineState & State,bool DryRun)1068*67e74705SXin Li unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
1069*67e74705SXin Li                                                     LineState &State,
1070*67e74705SXin Li                                                     bool DryRun) {
1071*67e74705SXin Li   // Don't break multi-line tokens other than block comments. Instead, just
1072*67e74705SXin Li   // update the state.
1073*67e74705SXin Li   if (Current.isNot(TT_BlockComment) && Current.IsMultiline)
1074*67e74705SXin Li     return addMultilineToken(Current, State);
1075*67e74705SXin Li 
1076*67e74705SXin Li   // Don't break implicit string literals or import statements.
1077*67e74705SXin Li   if (Current.is(TT_ImplicitStringLiteral) ||
1078*67e74705SXin Li       State.Line->Type == LT_ImportStatement)
1079*67e74705SXin Li     return 0;
1080*67e74705SXin Li 
1081*67e74705SXin Li   if (!Current.isStringLiteral() && !Current.is(tok::comment))
1082*67e74705SXin Li     return 0;
1083*67e74705SXin Li 
1084*67e74705SXin Li   std::unique_ptr<BreakableToken> Token;
1085*67e74705SXin Li   unsigned StartColumn = State.Column - Current.ColumnWidth;
1086*67e74705SXin Li   unsigned ColumnLimit = getColumnLimit(State);
1087*67e74705SXin Li 
1088*67e74705SXin Li   if (Current.isStringLiteral()) {
1089*67e74705SXin Li     // FIXME: String literal breaking is currently disabled for Java and JS, as
1090*67e74705SXin Li     // it requires strings to be merged using "+" which we don't support.
1091*67e74705SXin Li     if (Style.Language == FormatStyle::LK_Java ||
1092*67e74705SXin Li         Style.Language == FormatStyle::LK_JavaScript ||
1093*67e74705SXin Li         !Style.BreakStringLiterals)
1094*67e74705SXin Li       return 0;
1095*67e74705SXin Li 
1096*67e74705SXin Li     // Don't break string literals inside preprocessor directives (except for
1097*67e74705SXin Li     // #define directives, as their contents are stored in separate lines and
1098*67e74705SXin Li     // are not affected by this check).
1099*67e74705SXin Li     // This way we avoid breaking code with line directives and unknown
1100*67e74705SXin Li     // preprocessor directives that contain long string literals.
1101*67e74705SXin Li     if (State.Line->Type == LT_PreprocessorDirective)
1102*67e74705SXin Li       return 0;
1103*67e74705SXin Li     // Exempts unterminated string literals from line breaking. The user will
1104*67e74705SXin Li     // likely want to terminate the string before any line breaking is done.
1105*67e74705SXin Li     if (Current.IsUnterminatedLiteral)
1106*67e74705SXin Li       return 0;
1107*67e74705SXin Li 
1108*67e74705SXin Li     StringRef Text = Current.TokenText;
1109*67e74705SXin Li     StringRef Prefix;
1110*67e74705SXin Li     StringRef Postfix;
1111*67e74705SXin Li     bool IsNSStringLiteral = false;
1112*67e74705SXin Li     // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
1113*67e74705SXin Li     // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
1114*67e74705SXin Li     // reduce the overhead) for each FormatToken, which is a string, so that we
1115*67e74705SXin Li     // don't run multiple checks here on the hot path.
1116*67e74705SXin Li     if (Text.startswith("\"") && Current.Previous &&
1117*67e74705SXin Li         Current.Previous->is(tok::at)) {
1118*67e74705SXin Li       IsNSStringLiteral = true;
1119*67e74705SXin Li       Prefix = "@\"";
1120*67e74705SXin Li     }
1121*67e74705SXin Li     if ((Text.endswith(Postfix = "\"") &&
1122*67e74705SXin Li          (IsNSStringLiteral || Text.startswith(Prefix = "\"") ||
1123*67e74705SXin Li           Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
1124*67e74705SXin Li           Text.startswith(Prefix = "u8\"") ||
1125*67e74705SXin Li           Text.startswith(Prefix = "L\""))) ||
1126*67e74705SXin Li         (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) {
1127*67e74705SXin Li       Token.reset(new BreakableStringLiteral(
1128*67e74705SXin Li           Current, State.Line->Level, StartColumn, Prefix, Postfix,
1129*67e74705SXin Li           State.Line->InPPDirective, Encoding, Style));
1130*67e74705SXin Li     } else {
1131*67e74705SXin Li       return 0;
1132*67e74705SXin Li     }
1133*67e74705SXin Li   } else if (Current.is(TT_BlockComment)) {
1134*67e74705SXin Li     if (!Current.isTrailingComment() || !Style.ReflowComments ||
1135*67e74705SXin Li         CommentPragmasRegex.match(Current.TokenText.substr(2)))
1136*67e74705SXin Li       return addMultilineToken(Current, State);
1137*67e74705SXin Li     Token.reset(new BreakableBlockComment(
1138*67e74705SXin Li         Current, State.Line->Level, StartColumn, Current.OriginalColumn,
1139*67e74705SXin Li         !Current.Previous, State.Line->InPPDirective, Encoding, Style));
1140*67e74705SXin Li   } else if (Current.is(TT_LineComment) &&
1141*67e74705SXin Li              (Current.Previous == nullptr ||
1142*67e74705SXin Li               Current.Previous->isNot(TT_ImplicitStringLiteral))) {
1143*67e74705SXin Li     if (!Style.ReflowComments ||
1144*67e74705SXin Li         CommentPragmasRegex.match(Current.TokenText.substr(2)))
1145*67e74705SXin Li       return 0;
1146*67e74705SXin Li     Token.reset(new BreakableLineComment(Current, State.Line->Level,
1147*67e74705SXin Li                                          StartColumn, /*InPPDirective=*/false,
1148*67e74705SXin Li                                          Encoding, Style));
1149*67e74705SXin Li     // We don't insert backslashes when breaking line comments.
1150*67e74705SXin Li     ColumnLimit = Style.ColumnLimit;
1151*67e74705SXin Li   } else {
1152*67e74705SXin Li     return 0;
1153*67e74705SXin Li   }
1154*67e74705SXin Li   if (Current.UnbreakableTailLength >= ColumnLimit)
1155*67e74705SXin Li     return 0;
1156*67e74705SXin Li 
1157*67e74705SXin Li   unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength;
1158*67e74705SXin Li   bool BreakInserted = false;
1159*67e74705SXin Li   unsigned Penalty = 0;
1160*67e74705SXin Li   unsigned RemainingTokenColumns = 0;
1161*67e74705SXin Li   for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
1162*67e74705SXin Li        LineIndex != EndIndex; ++LineIndex) {
1163*67e74705SXin Li     if (!DryRun)
1164*67e74705SXin Li       Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
1165*67e74705SXin Li     unsigned TailOffset = 0;
1166*67e74705SXin Li     RemainingTokenColumns =
1167*67e74705SXin Li         Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
1168*67e74705SXin Li     while (RemainingTokenColumns > RemainingSpace) {
1169*67e74705SXin Li       BreakableToken::Split Split =
1170*67e74705SXin Li           Token->getSplit(LineIndex, TailOffset, ColumnLimit);
1171*67e74705SXin Li       if (Split.first == StringRef::npos) {
1172*67e74705SXin Li         // The last line's penalty is handled in addNextStateToQueue().
1173*67e74705SXin Li         if (LineIndex < EndIndex - 1)
1174*67e74705SXin Li           Penalty += Style.PenaltyExcessCharacter *
1175*67e74705SXin Li                      (RemainingTokenColumns - RemainingSpace);
1176*67e74705SXin Li         break;
1177*67e74705SXin Li       }
1178*67e74705SXin Li       assert(Split.first != 0);
1179*67e74705SXin Li       unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
1180*67e74705SXin Li           LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
1181*67e74705SXin Li 
1182*67e74705SXin Li       // We can remove extra whitespace instead of breaking the line.
1183*67e74705SXin Li       if (RemainingTokenColumns + 1 - Split.second <= RemainingSpace) {
1184*67e74705SXin Li         RemainingTokenColumns = 0;
1185*67e74705SXin Li         if (!DryRun)
1186*67e74705SXin Li           Token->replaceWhitespace(LineIndex, TailOffset, Split, Whitespaces);
1187*67e74705SXin Li         break;
1188*67e74705SXin Li       }
1189*67e74705SXin Li 
1190*67e74705SXin Li       // When breaking before a tab character, it may be moved by a few columns,
1191*67e74705SXin Li       // but will still be expanded to the next tab stop, so we don't save any
1192*67e74705SXin Li       // columns.
1193*67e74705SXin Li       if (NewRemainingTokenColumns == RemainingTokenColumns)
1194*67e74705SXin Li         break;
1195*67e74705SXin Li 
1196*67e74705SXin Li       assert(NewRemainingTokenColumns < RemainingTokenColumns);
1197*67e74705SXin Li       if (!DryRun)
1198*67e74705SXin Li         Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
1199*67e74705SXin Li       Penalty += Current.SplitPenalty;
1200*67e74705SXin Li       unsigned ColumnsUsed =
1201*67e74705SXin Li           Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
1202*67e74705SXin Li       if (ColumnsUsed > ColumnLimit) {
1203*67e74705SXin Li         Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit);
1204*67e74705SXin Li       }
1205*67e74705SXin Li       TailOffset += Split.first + Split.second;
1206*67e74705SXin Li       RemainingTokenColumns = NewRemainingTokenColumns;
1207*67e74705SXin Li       BreakInserted = true;
1208*67e74705SXin Li     }
1209*67e74705SXin Li   }
1210*67e74705SXin Li 
1211*67e74705SXin Li   State.Column = RemainingTokenColumns;
1212*67e74705SXin Li 
1213*67e74705SXin Li   if (BreakInserted) {
1214*67e74705SXin Li     // If we break the token inside a parameter list, we need to break before
1215*67e74705SXin Li     // the next parameter on all levels, so that the next parameter is clearly
1216*67e74705SXin Li     // visible. Line comments already introduce a break.
1217*67e74705SXin Li     if (Current.isNot(TT_LineComment)) {
1218*67e74705SXin Li       for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1219*67e74705SXin Li         State.Stack[i].BreakBeforeParameter = true;
1220*67e74705SXin Li     }
1221*67e74705SXin Li 
1222*67e74705SXin Li     Penalty += Current.isStringLiteral() ? Style.PenaltyBreakString
1223*67e74705SXin Li                                          : Style.PenaltyBreakComment;
1224*67e74705SXin Li 
1225*67e74705SXin Li     State.Stack.back().LastSpace = StartColumn;
1226*67e74705SXin Li   }
1227*67e74705SXin Li   return Penalty;
1228*67e74705SXin Li }
1229*67e74705SXin Li 
getColumnLimit(const LineState & State) const1230*67e74705SXin Li unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
1231*67e74705SXin Li   // In preprocessor directives reserve two chars for trailing " \"
1232*67e74705SXin Li   return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
1233*67e74705SXin Li }
1234*67e74705SXin Li 
nextIsMultilineString(const LineState & State)1235*67e74705SXin Li bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
1236*67e74705SXin Li   const FormatToken &Current = *State.NextToken;
1237*67e74705SXin Li   if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral))
1238*67e74705SXin Li     return false;
1239*67e74705SXin Li   // We never consider raw string literals "multiline" for the purpose of
1240*67e74705SXin Li   // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
1241*67e74705SXin Li   // (see TokenAnnotator::mustBreakBefore().
1242*67e74705SXin Li   if (Current.TokenText.startswith("R\""))
1243*67e74705SXin Li     return false;
1244*67e74705SXin Li   if (Current.IsMultiline)
1245*67e74705SXin Li     return true;
1246*67e74705SXin Li   if (Current.getNextNonComment() &&
1247*67e74705SXin Li       Current.getNextNonComment()->isStringLiteral())
1248*67e74705SXin Li     return true; // Implicit concatenation.
1249*67e74705SXin Li   if (Style.ColumnLimit != 0 &&
1250*67e74705SXin Li       State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
1251*67e74705SXin Li           Style.ColumnLimit)
1252*67e74705SXin Li     return true; // String will be split.
1253*67e74705SXin Li   return false;
1254*67e74705SXin Li }
1255*67e74705SXin Li 
1256*67e74705SXin Li } // namespace format
1257*67e74705SXin Li } // namespace clang
1258