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