blob: 53b5867965145d839b05c5352c6142df31bfc039 [file] [log] [blame]
Daniel Jasperde0328a2013-08-16 11:20:30 +00001//===--- ContinuationIndenter.cpp - Format C++ code -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements the continuation indenter.
12///
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "format-formatter"
16
17#include "BreakableToken.h"
18#include "ContinuationIndenter.h"
19#include "WhitespaceManager.h"
20#include "clang/Basic/OperatorPrecedence.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Format/Format.h"
23#include "llvm/Support/Debug.h"
24#include <string>
25
26namespace clang {
27namespace format {
28
29// Returns the length of everything up to the first possible line break after
30// the ), ], } or > matching \c Tok.
31static unsigned getLengthToMatchingParen(const FormatToken &Tok) {
32 if (Tok.MatchingParen == NULL)
33 return 0;
34 FormatToken *End = Tok.MatchingParen;
35 while (End->Next && !End->Next->CanBreakBefore) {
36 End = End->Next;
37 }
38 return End->TotalLength - Tok.TotalLength + 1;
39}
40
Daniel Jasper4c6e0052013-08-27 14:24:43 +000041// Returns \c true if \c Tok is the "." or "->" of a call and starts the next
42// segment of a builder type call.
43static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) {
44 return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope();
45}
46
Daniel Jasperec01cd62013-10-08 05:11:18 +000047// Returns \c true if \c Current starts a new parameter.
48static bool startsNextParameter(const FormatToken &Current,
49 const FormatStyle &Style) {
50 const FormatToken &Previous = *Current.Previous;
51 if (Current.Type == TT_CtorInitializerComma &&
52 Style.BreakConstructorInitializersBeforeComma)
53 return true;
54 return Previous.is(tok::comma) && !Current.isTrailingComment() &&
55 (Previous.Type != TT_CtorInitializerComma ||
56 !Style.BreakConstructorInitializersBeforeComma);
57}
58
Daniel Jasperde0328a2013-08-16 11:20:30 +000059ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,
60 SourceManager &SourceMgr,
Daniel Jasperde0328a2013-08-16 11:20:30 +000061 WhitespaceManager &Whitespaces,
62 encoding::Encoding Encoding,
63 bool BinPackInconclusiveFunctions)
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000064 : Style(Style), SourceMgr(SourceMgr), Whitespaces(Whitespaces),
65 Encoding(Encoding),
Alexander Kornienkoce9161a2014-01-02 15:13:14 +000066 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
67 CommentPragmasRegex(Style.CommentPragmas) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +000068
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000069LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
Daniel Jasper1c5d9df2013-09-06 07:54:20 +000070 const AnnotatedLine *Line,
71 bool DryRun) {
Daniel Jasperde0328a2013-08-16 11:20:30 +000072 LineState State;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000073 State.FirstIndent = FirstIndent;
Daniel Jasperde0328a2013-08-16 11:20:30 +000074 State.Column = FirstIndent;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000075 State.Line = Line;
76 State.NextToken = Line->First;
Alexander Kornienkoe2e03872013-10-14 00:46:35 +000077 State.Stack.push_back(ParenState(FirstIndent, Line->Level, FirstIndent,
Daniel Jasperde0328a2013-08-16 11:20:30 +000078 /*AvoidBinPacking=*/false,
79 /*NoLineBreak=*/false));
80 State.LineContainsContinuedForLoopSection = false;
81 State.ParenLevel = 0;
82 State.StartOfStringLiteral = 0;
83 State.StartOfLineLevel = State.ParenLevel;
84 State.LowestLevelOnLine = State.ParenLevel;
85 State.IgnoreStackForComparison = false;
86
87 // The first token has already been indented and thus consumed.
Daniel Jasper1c5d9df2013-09-06 07:54:20 +000088 moveStateToNextToken(State, DryRun, /*Newline=*/false);
Daniel Jasperde0328a2013-08-16 11:20:30 +000089 return State;
90}
91
92bool ContinuationIndenter::canBreak(const LineState &State) {
93 const FormatToken &Current = *State.NextToken;
94 const FormatToken &Previous = *Current.Previous;
95 assert(&Previous == Current.Previous);
Daniel Jasper1db6c382013-10-22 15:30:28 +000096 if (!Current.CanBreakBefore && !(State.Stack.back().BreakBeforeClosingBrace &&
97 Current.closesBlockTypeList(Style)))
Daniel Jasperde0328a2013-08-16 11:20:30 +000098 return false;
99 // The opening "{" of a braced list has to be on the same line as the first
100 // element if it is nested in another braced init list or function call.
101 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
Daniel Jasperb596fb22013-10-24 10:31:50 +0000102 Previous.Type != TT_DictLiteral &&
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000103 Previous.BlockKind == BK_BracedInit && Previous.Previous &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000104 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
105 return false;
106 // This prevents breaks like:
107 // ...
108 // SomeParameter, OtherParameter).DoSomething(
109 // ...
110 // As they hide "DoSomething" and are generally bad for readability.
Daniel Jasper8f59ae52014-03-11 11:03:26 +0000111 if (Previous.opensScope() && Previous.isNot(tok::l_brace) &&
112 State.LowestLevelOnLine < State.StartOfLineLevel)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000113 return false;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000114 if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
115 return false;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000116 return !State.Stack.back().NoLineBreak;
117}
118
119bool ContinuationIndenter::mustBreak(const LineState &State) {
120 const FormatToken &Current = *State.NextToken;
121 const FormatToken &Previous = *Current.Previous;
122 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
123 return true;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000124 if (State.Stack.back().BreakBeforeClosingBrace &&
125 Current.closesBlockTypeList(Style))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000126 return true;
127 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
128 return true;
Daniel Jasperec01cd62013-10-08 05:11:18 +0000129 if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
Daniel Jasper165b29e2013-11-08 00:57:11 +0000130 (Style.BreakBeforeTernaryOperators &&
131 (Current.is(tok::question) || (Current.Type == TT_ConditionalExpr &&
132 Previous.isNot(tok::question)))) ||
133 (!Style.BreakBeforeTernaryOperators &&
134 (Previous.is(tok::question) || Previous.Type == TT_ConditionalExpr))) &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000135 State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
136 !Current.isOneOf(tok::r_paren, tok::r_brace))
137 return true;
138 if (Style.AlwaysBreakBeforeMultilineStrings &&
Daniel Jasperf438cb72013-08-23 11:57:34 +0000139 State.Column > State.Stack.back().Indent && // Breaking saves columns.
Daniel Jasper27943052013-11-09 03:08:25 +0000140 !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) &&
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000141 Previous.Type != TT_InlineASMColon && nextIsMultilineString(State))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000142 return true;
Daniel Jasperb596fb22013-10-24 10:31:50 +0000143 if (((Previous.Type == TT_DictLiteral && Previous.is(tok::l_brace)) ||
Daniel Jasper1db6c382013-10-22 15:30:28 +0000144 Previous.Type == TT_ArrayInitializerLSquare) &&
Daniel Jasperd489dd32013-10-20 16:45:46 +0000145 getLengthToMatchingParen(Previous) + State.Column > getColumnLimit(State))
146 return true;
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000147 if (Current.Type == TT_CtorInitializerColon &&
Daniel Jasperd74cf402014-04-08 12:46:38 +0000148 ((Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All) ||
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000149 Style.BreakConstructorInitializersBeforeComma || Style.ColumnLimit != 0))
150 return true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000151
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000152 if (State.Column < getNewLineColumn(State))
153 return false;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000154 if (!Style.BreakBeforeBinaryOperators) {
155 // If we need to break somewhere inside the LHS of a binary expression, we
156 // should also break after the operator. Otherwise, the formatting would
157 // hide the operator precedence, e.g. in:
158 // if (aaaaaaaaaaaaaa ==
159 // bbbbbbbbbbbbbb && c) {..
160 // For comparisons, we only apply this rule, if the LHS is a binary
161 // expression itself as otherwise, the line breaks seem superfluous.
162 // We need special cases for ">>" which we have split into two ">" while
163 // lexing in order to make template parsing easier.
164 //
165 // FIXME: We'll need something similar for styles that break before binary
166 // operators.
167 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
168 Previous.getPrecedence() == prec::Equality) &&
169 Previous.Previous &&
170 Previous.Previous->Type != TT_BinaryOperator; // For >>.
171 bool LHSIsBinaryExpr =
Daniel Jasper562ecd42013-09-06 08:08:14 +0000172 Previous.Previous && Previous.Previous->EndsBinaryExpression;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000173 if (Previous.Type == TT_BinaryOperator &&
174 (!IsComparison || LHSIsBinaryExpr) &&
175 Current.Type != TT_BinaryOperator && // For >>.
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000176 !Current.isTrailingComment() && !Previous.is(tok::lessless) &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000177 Previous.getPrecedence() != prec::Assignment &&
178 State.Stack.back().BreakBeforeParameter)
179 return true;
180 }
181
182 // Same as above, but for the first "<<" operator.
Alexander Kornienko86b2dfd2014-03-06 15:13:08 +0000183 if (Current.is(tok::lessless) && Current.Type != TT_OverloadedOperator &&
184 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000185 State.Stack.back().FirstLessLess == 0)
186 return true;
187
Daniel Jasperde0328a2013-08-16 11:20:30 +0000188 if (Current.Type == TT_ObjCSelectorName &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000189 State.Stack.back().ObjCSelectorNameFound &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000190 State.Stack.back().BreakBeforeParameter)
191 return true;
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000192 if (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0 &&
193 !Current.isTrailingComment())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000194 return true;
195
196 if ((Current.Type == TT_StartOfName || Current.is(tok::kw_operator)) &&
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000197 State.Line->MightBeFunctionDecl &&
198 State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000199 return true;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000200 if (startsSegmentOfBuilderTypeCall(Current) &&
Daniel Jasperf8151e92013-08-30 07:12:40 +0000201 (State.Stack.back().CallContinuation != 0 ||
202 (State.Stack.back().BreakBeforeParameter &&
203 State.Stack.back().ContainsUnwrappedBuilder)))
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000204 return true;
Daniel Jasper96972812014-01-05 12:38:10 +0000205
206 // The following could be precomputed as they do not depend on the state.
207 // However, as they should take effect only if the UnwrappedLine does not fit
208 // into the ColumnLimit, they are checked here in the ContinuationIndenter.
209 if (Previous.BlockKind == BK_Block && Previous.is(tok::l_brace) &&
210 !Current.isOneOf(tok::r_brace, tok::comment))
211 return true;
Daniel Jasper96972812014-01-05 12:38:10 +0000212
Daniel Jasperde0328a2013-08-16 11:20:30 +0000213 return false;
214}
215
216unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000217 bool DryRun,
218 unsigned ExtraSpaces) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000219 const FormatToken &Current = *State.NextToken;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000220
Manuel Klimek819788d2014-03-18 11:22:45 +0000221 assert(!State.Stack.empty());
222 if ((Current.Type == TT_ImplicitStringLiteral &&
Daniel Jasper98857842013-10-30 13:54:53 +0000223 (Current.Previous->Tok.getIdentifierInfo() == NULL ||
224 Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
225 tok::pp_not_keyword))) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000226 // FIXME: Is this correct?
227 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
228 State.NextToken->WhitespaceRange.getEnd()) -
229 SourceMgr.getSpellingColumnNumber(
230 State.NextToken->WhitespaceRange.getBegin());
Daniel Jasperda353cd2014-03-12 08:24:47 +0000231 State.Column += WhitespaceLength;
Daniel Jasper240dfda2014-03-31 14:23:49 +0000232 moveStateToNextToken(State, DryRun, /*Newline=*/false);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000233 return 0;
234 }
235
Alexander Kornienko1f803962013-10-01 14:41:18 +0000236 unsigned Penalty = 0;
237 if (Newline)
238 Penalty = addTokenOnNewLine(State, DryRun);
239 else
Daniel Jasper48437ce2013-11-20 14:54:39 +0000240 addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000241
242 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
243}
244
Daniel Jasper48437ce2013-11-20 14:54:39 +0000245void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
246 unsigned ExtraSpaces) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000247 FormatToken &Current = *State.NextToken;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000248 const FormatToken &Previous = *State.NextToken->Previous;
249 if (Current.is(tok::equal) &&
250 (State.Line->First->is(tok::kw_for) || State.ParenLevel == 0) &&
251 State.Stack.back().VariablePos == 0) {
252 State.Stack.back().VariablePos = State.Column;
253 // Move over * and & if they are bound to the variable name.
254 const FormatToken *Tok = &Previous;
255 while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
256 State.Stack.back().VariablePos -= Tok->ColumnWidth;
257 if (Tok->SpacesRequiredBefore != 0)
258 break;
259 Tok = Tok->Previous;
260 }
261 if (Previous.PartOfMultiVariableDeclStmt)
262 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
263 }
264
265 unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
266
267 if (!DryRun)
268 Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, /*IndentLevel=*/0,
269 Spaces, State.Column + Spaces);
270
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000271 if (Current.Type == TT_ObjCSelectorName &&
272 !State.Stack.back().ObjCSelectorNameFound) {
273 if (Current.LongestObjCSelectorName == 0)
274 State.Stack.back().AlignColons = false;
275 else if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
276 State.Column + Spaces + Current.ColumnWidth)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000277 State.Stack.back().ColonPos =
278 State.Stack.back().Indent + Current.LongestObjCSelectorName;
279 else
280 State.Stack.back().ColonPos = State.Column + Spaces + Current.ColumnWidth;
281 }
282
283 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper5a611392013-12-19 21:41:37 +0000284 (Current.Type != TT_LineComment || Previous.BlockKind == BK_BracedInit))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000285 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasperec01cd62013-10-08 05:11:18 +0000286 if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000287 State.Stack.back().NoLineBreak = true;
288 if (startsSegmentOfBuilderTypeCall(Current))
289 State.Stack.back().ContainsUnwrappedBuilder = true;
290
291 State.Column += Spaces;
292 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
293 // Treat the condition inside an if as if it was a second function
Daniel Jasper6633ab82013-10-18 10:38:14 +0000294 // parameter, i.e. let nested calls have a continuation indent.
Alexander Kornienko1f803962013-10-01 14:41:18 +0000295 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000296 else if (Current.isNot(tok::comment) &&
297 (Previous.is(tok::comma) ||
298 (Previous.is(tok::colon) && Previous.Type == TT_ObjCMethodExpr)))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000299 State.Stack.back().LastSpace = State.Column;
300 else if ((Previous.Type == TT_BinaryOperator ||
301 Previous.Type == TT_ConditionalExpr ||
Alexander Kornienko1f803962013-10-01 14:41:18 +0000302 Previous.Type == TT_CtorInitializerColon) &&
303 (Previous.getPrecedence() != prec::Assignment ||
304 Current.StartsBinaryExpression))
305 // Always indent relative to the RHS of the expression unless this is a
306 // simple assignment without binary expression on the RHS. Also indent
307 // relative to unary operators and the colons of constructor initializers.
308 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf9a5e402013-10-08 16:24:07 +0000309 else if (Previous.Type == TT_InheritanceColon) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000310 State.Stack.back().Indent = State.Column;
Daniel Jasperf9a5e402013-10-08 16:24:07 +0000311 State.Stack.back().LastSpace = State.Column;
312 } else if (Previous.opensScope()) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000313 // If a function has a trailing call, indent all parameters from the
314 // opening parenthesis. This avoids confusing indents like:
315 // OuterFunction(InnerFunctionCall( // break
316 // ParameterToInnerFunction)) // break
317 // .SecondInnerFunctionCall();
318 bool HasTrailingCall = false;
319 if (Previous.MatchingParen) {
320 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
321 HasTrailingCall = Next && Next->isMemberAccess();
322 }
323 if (HasTrailingCall &&
324 State.Stack[State.Stack.size() - 2].CallContinuation == 0)
325 State.Stack.back().LastSpace = State.Column;
326 }
327}
328
329unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
330 bool DryRun) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000331 FormatToken &Current = *State.NextToken;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000332 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000333
Alexander Kornienko1f803962013-10-01 14:41:18 +0000334 // Extra penalty that needs to be added because of the way certain line
335 // breaks are chosen.
336 unsigned Penalty = 0;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000337
Daniel Jaspera0407742014-02-11 10:08:11 +0000338 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
339 const FormatToken *NextNonComment = Previous.getNextNonComment();
340 if (!NextNonComment)
341 NextNonComment = &Current;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000342 // The first line break on any ParenLevel causes an extra penalty in order
343 // prefer similar line breaks.
344 if (!State.Stack.back().ContainsLineBreak)
345 Penalty += 15;
346 State.Stack.back().ContainsLineBreak = true;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000347
Alexander Kornienko1f803962013-10-01 14:41:18 +0000348 Penalty += State.NextToken->SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000349
Alexander Kornienko1f803962013-10-01 14:41:18 +0000350 // Breaking before the first "<<" is generally not desirable if the LHS is
Daniel Jasper48437ce2013-11-20 14:54:39 +0000351 // short. Also always add the penalty if the LHS is split over mutliple lines
Daniel Jasper2b7556e2014-04-03 12:00:27 +0000352 // to avoid unnecessary line breaks that just work around this penalty.
Daniel Jaspera0407742014-02-11 10:08:11 +0000353 if (NextNonComment->is(tok::lessless) &&
354 State.Stack.back().FirstLessLess == 0 &&
Daniel Jasper004177e2013-12-19 16:06:40 +0000355 (State.Column <= Style.ColumnLimit / 3 ||
Daniel Jasper48437ce2013-11-20 14:54:39 +0000356 State.Stack.back().BreakBeforeParameter))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000357 Penalty += Style.PenaltyBreakFirstLessLess;
358
Daniel Jasper9f388d02014-03-27 14:33:30 +0000359 State.Column = getNewLineColumn(State);
360 if (NextNonComment->isMemberAccess()) {
361 if (State.Stack.back().CallContinuation == 0)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000362 State.Stack.back().CallContinuation = State.Column;
Daniel Jaspera0407742014-02-11 10:08:11 +0000363 } else if (NextNonComment->Type == TT_ObjCSelectorName) {
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000364 if (!State.Stack.back().ObjCSelectorNameFound) {
Daniel Jaspera0407742014-02-11 10:08:11 +0000365 if (NextNonComment->LongestObjCSelectorName == 0) {
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000366 State.Stack.back().AlignColons = false;
367 } else {
368 State.Stack.back().ColonPos =
Daniel Jaspera0407742014-02-11 10:08:11 +0000369 State.Stack.back().Indent + NextNonComment->LongestObjCSelectorName;
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000370 }
Daniel Jasper9f388d02014-03-27 14:33:30 +0000371 } else if (State.Stack.back().AlignColons &&
372 State.Stack.back().ColonPos <= NextNonComment->ColumnWidth) {
Daniel Jaspera0407742014-02-11 10:08:11 +0000373 State.Stack.back().ColonPos = State.Column + NextNonComment->ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000374 }
Daniel Jasper1fd6f1f2014-03-17 14:32:47 +0000375 } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
376 (PreviousNonComment->Type == TT_ObjCMethodExpr ||
377 PreviousNonComment->Type == TT_DictLiteral)) {
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000378 // FIXME: This is hacky, find a better way. The problem is that in an ObjC
379 // method expression, the block should be aligned to the line starting it,
380 // e.g.:
381 // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
382 // ^(int *i) {
383 // // ...
384 // }];
385 // Thus, we set LastSpace of the next higher ParenLevel, to which we move
386 // when we consume all of the "}"'s FakeRParens at the "{".
Daniel Jasper9a26e772013-12-23 11:25:40 +0000387 if (State.Stack.size() > 1)
Daniel Jasper9f388d02014-03-27 14:33:30 +0000388 State.Stack[State.Stack.size() - 2].LastSpace =
389 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
390 Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000391 }
392
Alexander Kornienko1f803962013-10-01 14:41:18 +0000393 if ((Previous.isOneOf(tok::comma, tok::semi) &&
394 !State.Stack.back().AvoidBinPacking) ||
395 Previous.Type == TT_BinaryOperator)
396 State.Stack.back().BreakBeforeParameter = false;
397 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
398 State.Stack.back().BreakBeforeParameter = false;
Daniel Jaspera0407742014-02-11 10:08:11 +0000399 if (NextNonComment->is(tok::question) ||
Daniel Jasper165b29e2013-11-08 00:57:11 +0000400 (PreviousNonComment && PreviousNonComment->is(tok::question)))
401 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000402
403 if (!DryRun) {
404 unsigned Newlines = 1;
405 if (Current.is(tok::comment))
406 Newlines = std::max(Newlines, std::min(Current.NewlinesBefore,
407 Style.MaxEmptyLinesToKeep + 1));
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000408 Whitespaces.replaceWhitespace(Current, Newlines,
409 State.Stack.back().IndentLevel, State.Column,
410 State.Column, State.Line->InPPDirective);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000411 }
412
413 if (!Current.isTrailingComment())
414 State.Stack.back().LastSpace = State.Column;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000415 State.StartOfLineLevel = State.ParenLevel;
416 State.LowestLevelOnLine = State.ParenLevel;
417
418 // Any break on this level means that the parent level has been broken
419 // and we need to avoid bin packing there.
420 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
421 State.Stack[i].BreakBeforeParameter = true;
422 }
Daniel Jasper9e5ede02013-11-08 19:56:28 +0000423 if (PreviousNonComment &&
424 !PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
425 PreviousNonComment->Type != TT_TemplateCloser &&
426 PreviousNonComment->Type != TT_BinaryOperator &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000427 Current.Type != TT_BinaryOperator &&
Daniel Jasper9e5ede02013-11-08 19:56:28 +0000428 !PreviousNonComment->opensScope())
Alexander Kornienko1f803962013-10-01 14:41:18 +0000429 State.Stack.back().BreakBeforeParameter = true;
430
Daniel Jasper1db6c382013-10-22 15:30:28 +0000431 // If we break after { or the [ of an array initializer, we should also break
432 // before the corresponding } or ].
433 if (Previous.is(tok::l_brace) || Previous.Type == TT_ArrayInitializerLSquare)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000434 State.Stack.back().BreakBeforeClosingBrace = true;
435
436 if (State.Stack.back().AvoidBinPacking) {
437 // If we are breaking after '(', '{', '<', this is not bin packing
438 // unless AllowAllParametersOfDeclarationOnNextLine is false.
439 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
440 Previous.Type == TT_BinaryOperator) ||
441 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
442 State.Line->MustBeDeclaration))
443 State.Stack.back().BreakBeforeParameter = true;
444 }
445
446 return Penalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000447}
448
Daniel Jasper9f388d02014-03-27 14:33:30 +0000449unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000450 if (!State.NextToken || !State.NextToken->Previous)
451 return 0;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000452 FormatToken &Current = *State.NextToken;
453 const FormatToken &Previous = *State.NextToken->Previous;
454 // If we are continuing an expression, we want to use the continuation indent.
455 unsigned ContinuationIndent =
456 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
457 Style.ContinuationIndentWidth;
458 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
459 const FormatToken *NextNonComment = Previous.getNextNonComment();
460 if (!NextNonComment)
461 NextNonComment = &Current;
462 if (NextNonComment->is(tok::l_brace) &&
463 NextNonComment->BlockKind == BK_Block)
464 return State.ParenLevel == 0 ? State.FirstIndent
465 : State.Stack.back().Indent;
466 if (Current.isOneOf(tok::r_brace, tok::r_square)) {
467 if (Current.closesBlockTypeList(Style) ||
468 (Current.MatchingParen &&
469 Current.MatchingParen->BlockKind == BK_BracedInit))
470 return State.Stack[State.Stack.size() - 2].LastSpace;
471 else
472 return State.FirstIndent;
473 }
474 if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
475 return State.StartOfStringLiteral;
476 if (NextNonComment->is(tok::lessless) &&
477 State.Stack.back().FirstLessLess != 0)
478 return State.Stack.back().FirstLessLess;
479 if (NextNonComment->isMemberAccess()) {
480 if (State.Stack.back().CallContinuation == 0) {
481 return ContinuationIndent;
482 } else {
483 return State.Stack.back().CallContinuation;
484 }
485 }
486 if (State.Stack.back().QuestionColumn != 0 &&
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000487 ((NextNonComment->is(tok::colon) &&
488 NextNonComment->Type == TT_ConditionalExpr) ||
Daniel Jasper9f388d02014-03-27 14:33:30 +0000489 Previous.Type == TT_ConditionalExpr))
490 return State.Stack.back().QuestionColumn;
491 if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0)
492 return State.Stack.back().VariablePos;
493 if ((PreviousNonComment && (PreviousNonComment->ClosesTemplateDeclaration ||
494 PreviousNonComment->Type == TT_AttributeParen)) ||
495 ((NextNonComment->Type == TT_StartOfName ||
496 NextNonComment->is(tok::kw_operator)) &&
497 State.ParenLevel == 0 && (!Style.IndentFunctionDeclarationAfterType ||
498 State.Line->StartsDefinition)))
499 return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
500 if (NextNonComment->Type == TT_ObjCSelectorName) {
501 if (!State.Stack.back().ObjCSelectorNameFound) {
502 if (NextNonComment->LongestObjCSelectorName == 0) {
503 return State.Stack.back().Indent;
504 } else {
505 return State.Stack.back().Indent +
506 NextNonComment->LongestObjCSelectorName -
507 NextNonComment->ColumnWidth;
508 }
509 } else if (!State.Stack.back().AlignColons) {
510 return State.Stack.back().Indent;
511 } else if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth) {
512 return State.Stack.back().ColonPos - NextNonComment->ColumnWidth;
513 } else {
514 return State.Stack.back().Indent;
515 }
516 }
517 if (NextNonComment->Type == TT_ArraySubscriptLSquare) {
518 if (State.Stack.back().StartOfArraySubscripts != 0)
519 return State.Stack.back().StartOfArraySubscripts;
520 else
521 return ContinuationIndent;
522 }
523 if (NextNonComment->Type == TT_StartOfName ||
524 Previous.isOneOf(tok::coloncolon, tok::equal)) {
525 return ContinuationIndent;
526 }
527 if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
528 (PreviousNonComment->Type == TT_ObjCMethodExpr ||
529 PreviousNonComment->Type == TT_DictLiteral))
530 return ContinuationIndent;
531 if (NextNonComment->Type == TT_CtorInitializerColon)
532 return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
533 if (NextNonComment->Type == TT_CtorInitializerComma)
534 return State.Stack.back().Indent;
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000535 if (State.Stack.back().Indent == State.FirstIndent && PreviousNonComment &&
Daniel Jasper9f388d02014-03-27 14:33:30 +0000536 PreviousNonComment->isNot(tok::r_brace))
537 // Ensure that we fall back to the continuation indent width instead of
538 // just flushing continuations left.
539 return State.Stack.back().Indent + Style.ContinuationIndentWidth;
540 return State.Stack.back().Indent;
541}
542
Daniel Jasperde0328a2013-08-16 11:20:30 +0000543unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
544 bool DryRun, bool Newline) {
545 const FormatToken &Current = *State.NextToken;
546 assert(State.Stack.size());
547
548 if (Current.Type == TT_InheritanceColon)
549 State.Stack.back().AvoidBinPacking = true;
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000550 if (Current.is(tok::lessless) && Current.Type != TT_OverloadedOperator) {
551 if (State.Stack.back().FirstLessLess == 0)
552 State.Stack.back().FirstLessLess = State.Column;
553 else
554 State.Stack.back().LastOperatorWrapped = Newline;
555 }
556 if ((Current.Type == TT_BinaryOperator && Current.isNot(tok::lessless)) ||
557 Current.Type == TT_ConditionalExpr)
558 State.Stack.back().LastOperatorWrapped = Newline;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000559 if (Current.Type == TT_ArraySubscriptLSquare &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000560 State.Stack.back().StartOfArraySubscripts == 0)
561 State.Stack.back().StartOfArraySubscripts = State.Column;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000562 if ((Current.is(tok::question) && Style.BreakBeforeTernaryOperators) ||
563 (Current.getPreviousNonComment() && Current.isNot(tok::colon) &&
564 Current.getPreviousNonComment()->is(tok::question) &&
565 !Style.BreakBeforeTernaryOperators))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000566 State.Stack.back().QuestionColumn = State.Column;
567 if (!Current.opensScope() && !Current.closesScope())
568 State.LowestLevelOnLine =
569 std::min(State.LowestLevelOnLine, State.ParenLevel);
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000570 if (Current.isMemberAccess())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000571 State.Stack.back().StartOfFunctionCall =
Alexander Kornienko39856b72013-09-10 09:38:25 +0000572 Current.LastInChainOfCalls ? 0 : State.Column + Current.ColumnWidth;
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000573 if (Current.Type == TT_ObjCSelectorName)
574 State.Stack.back().ObjCSelectorNameFound = true;
Daniel Jasper3ae6f5a2014-04-09 12:08:39 +0000575 if (Current.Type == TT_LambdaLSquare)
576 ++State.Stack.back().LambdasFound;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000577 if (Current.Type == TT_CtorInitializerColon) {
578 // Indent 2 from the column, so:
579 // SomeClass::SomeClass()
580 // : First(...), ...
581 // Next(...)
582 // ^ line up here.
583 State.Stack.back().Indent =
584 State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
585 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
586 State.Stack.back().AvoidBinPacking = true;
587 State.Stack.back().BreakBeforeParameter = false;
588 }
589
Daniel Jasperde0328a2013-08-16 11:20:30 +0000590 // In ObjC method declaration we align on the ":" of parameters, but we need
Daniel Jasper6633ab82013-10-18 10:38:14 +0000591 // to ensure that we indent parameters on subsequent lines by at least our
592 // continuation indent width.
Daniel Jasperde0328a2013-08-16 11:20:30 +0000593 if (Current.Type == TT_ObjCMethodSpecifier)
Daniel Jasper6633ab82013-10-18 10:38:14 +0000594 State.Stack.back().Indent += Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000595
596 // Insert scopes created by fake parenthesis.
597 const FormatToken *Previous = Current.getPreviousNonComment();
598 // Don't add extra indentation for the first fake parenthesis after
599 // 'return', assignements or opening <({[. The indentation for these cases
600 // is special cased.
601 bool SkipFirstExtraIndent =
Daniel Jaspereabede62013-09-30 08:29:03 +0000602 (Previous && (Previous->opensScope() || Previous->is(tok::kw_return) ||
Daniel Jasperf48b5ab2013-11-07 19:23:49 +0000603 Previous->getPrecedence() == prec::Assignment ||
604 Previous->Type == TT_ObjCMethodExpr));
Daniel Jasperde0328a2013-08-16 11:20:30 +0000605 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
606 I = Current.FakeLParens.rbegin(),
607 E = Current.FakeLParens.rend();
608 I != E; ++I) {
609 ParenState NewParenState = State.Stack.back();
610 NewParenState.ContainsLineBreak = false;
Daniel Jaspereabede62013-09-30 08:29:03 +0000611
612 // Indent from 'LastSpace' unless this the fake parentheses encapsulating a
613 // builder type call after 'return'. If such a call is line-wrapped, we
614 // commonly just want to indent from the start of the line.
615 if (!Previous || Previous->isNot(tok::kw_return) || *I > 0)
616 NewParenState.Indent =
617 std::max(std::max(State.Column, NewParenState.Indent),
618 State.Stack.back().LastSpace);
619
Daniel Jasper5c332652014-04-03 12:00:33 +0000620 // Don't allow the RHS of an operator to be split over multiple lines unless
621 // there is a line-break right after the operator.
622 // Exclude relational operators, as there, it is always more desirable to
623 // have the LHS 'left' of the RHS.
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000624 if (Previous && Previous->getPrecedence() > prec::Assignment &&
625 (Previous->Type == TT_BinaryOperator ||
626 Previous->Type == TT_ConditionalExpr) &&
627 Previous->getPrecedence() != prec::Relational) {
628 bool BreakBeforeOperator = Previous->is(tok::lessless) ||
629 (Previous->Type == TT_BinaryOperator &&
630 Style.BreakBeforeBinaryOperators) ||
631 (Previous->Type == TT_ConditionalExpr &&
632 Style.BreakBeforeTernaryOperators);
633 if ((!Newline && !BreakBeforeOperator) ||
634 (!State.Stack.back().LastOperatorWrapped && BreakBeforeOperator))
635 NewParenState.NoLineBreak = true;
636 }
Daniel Jasper5c332652014-04-03 12:00:33 +0000637
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000638 // Do not indent relative to the fake parentheses inserted for "." or "->".
639 // This is a special case to make the following to statements consistent:
640 // OuterFunction(InnerFunctionCall( // break
641 // ParameterToInnerFunction));
642 // OuterFunction(SomeObject.InnerFunctionCall( // break
643 // ParameterToInnerFunction));
644 if (*I > prec::Unknown)
645 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
Daniel Jasper96964352013-12-18 10:44:36 +0000646 NewParenState.StartOfFunctionCall = State.Column;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000647
648 // Always indent conditional expressions. Never indent expression where
649 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
650 // prec::Assignment) as those have different indentation rules. Indent
651 // other expression, unless the indentation needs to be skipped.
652 if (*I == prec::Conditional ||
653 (!SkipFirstExtraIndent && *I > prec::Assignment &&
654 !Style.BreakBeforeBinaryOperators))
Daniel Jasper6633ab82013-10-18 10:38:14 +0000655 NewParenState.Indent += Style.ContinuationIndentWidth;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000656 if ((Previous && !Previous->opensScope()) || *I > prec::Comma)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000657 NewParenState.BreakBeforeParameter = false;
658 State.Stack.push_back(NewParenState);
659 SkipFirstExtraIndent = false;
660 }
661
662 // If we encounter an opening (, [, { or <, we add a level to our stacks to
663 // prepare for the following tokens.
664 if (Current.opensScope()) {
665 unsigned NewIndent;
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000666 unsigned NewIndentLevel = State.Stack.back().IndentLevel;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000667 bool AvoidBinPacking;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000668 bool BreakBeforeParameter = false;
669 if (Current.is(tok::l_brace) ||
670 Current.Type == TT_ArrayInitializerLSquare) {
Daniel Jasper3ae6f5a2014-04-09 12:08:39 +0000671 if (Current.MatchingParen && Current.BlockKind == BK_Block &&
672 State.Stack.back().LambdasFound <= 1) {
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000673 // If this is an l_brace starting a nested block, we pretend (wrt. to
674 // indentation) that we already consumed the corresponding r_brace.
Daniel Jasper96964352013-12-18 10:44:36 +0000675 // Thus, we remove all ParenStates caused by fake parentheses that end
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000676 // at the r_brace. The net effect of this is that we don't indent
677 // relative to the l_brace, if the nested block is the last parameter of
678 // a function. For example, this formats:
679 //
680 // SomeFunction(a, [] {
681 // f(); // break
682 // });
683 //
684 // instead of:
685 // SomeFunction(a, [] {
Daniel Jasper5500f612013-11-25 11:08:59 +0000686 // f(); // break
687 // });
Daniel Jasper3ae6f5a2014-04-09 12:08:39 +0000688 //
689 // If we have already found more than one lambda introducers on this
690 // level, we opt out of this because similarity between the lambdas is
691 // more important.
Manuel Klimek819788d2014-03-18 11:22:45 +0000692 for (unsigned i = 0; i != Current.MatchingParen->FakeRParens; ++i) {
693 assert(State.Stack.size() > 1);
694 if (State.Stack.size() == 1) {
695 // Do not pop the last element.
696 break;
697 }
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000698 State.Stack.pop_back();
Manuel Klimek819788d2014-03-18 11:22:45 +0000699 }
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000700 // For some reason, ObjC blocks are indented like continuations.
701 NewIndent =
Daniel Jasperc13ee342014-03-27 09:43:54 +0000702 State.Stack.back().LastSpace + (Current.Type == TT_ObjCBlockLBrace
703 ? Style.ContinuationIndentWidth
704 : Style.IndentWidth);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000705 ++NewIndentLevel;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000706 BreakBeforeParameter = true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000707 } else {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000708 NewIndent = State.Stack.back().LastSpace;
Daniel Jasperb8f61682013-10-22 15:45:58 +0000709 if (Current.opensBlockTypeList(Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000710 NewIndent += Style.IndentWidth;
Daniel Jasper5a611392013-12-19 21:41:37 +0000711 NewIndent = std::min(State.Column + 2, NewIndent);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000712 ++NewIndentLevel;
Daniel Jasperb8f61682013-10-22 15:45:58 +0000713 } else {
714 NewIndent += Style.ContinuationIndentWidth;
Daniel Jasper5a611392013-12-19 21:41:37 +0000715 NewIndent = std::min(State.Column + 1, NewIndent);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000716 }
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000717 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000718 const FormatToken *NextNoComment = Current.getNextNonComment();
Daniel Jasper015ed022013-09-13 09:20:45 +0000719 AvoidBinPacking = Current.BlockKind == BK_Block ||
Daniel Jasper1db6c382013-10-22 15:30:28 +0000720 Current.Type == TT_ArrayInitializerLSquare ||
Daniel Jasperb596fb22013-10-24 10:31:50 +0000721 Current.Type == TT_DictLiteral ||
Daniel Jasper015ed022013-09-13 09:20:45 +0000722 (NextNoComment &&
723 NextNoComment->Type == TT_DesignatedInitializerPeriod);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000724 } else {
Daniel Jasper6633ab82013-10-18 10:38:14 +0000725 NewIndent = Style.ContinuationIndentWidth +
726 std::max(State.Stack.back().LastSpace,
727 State.Stack.back().StartOfFunctionCall);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000728 AvoidBinPacking = !Style.BinPackParameters ||
729 (Style.ExperimentalAutoDetectBinPacking &&
730 (Current.PackingKind == PPK_OnePerLine ||
731 (!BinPackInconclusiveFunctions &&
732 Current.PackingKind == PPK_Inconclusive)));
Daniel Jasper1db6c382013-10-22 15:30:28 +0000733 // If this '[' opens an ObjC call, determine whether all parameters fit
734 // into one line and put one per line if they don't.
735 if (Current.Type == TT_ObjCMethodExpr &&
736 getLengthToMatchingParen(Current) + State.Column >
737 getColumnLimit(State))
738 BreakBeforeParameter = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000739 }
740
Daniel Jaspercc3114d2013-10-18 15:23:06 +0000741 bool NoLineBreak = State.Stack.back().NoLineBreak ||
742 (Current.Type == TT_TemplateOpener &&
743 State.Stack.back().ContainsUnwrappedBuilder);
744 State.Stack.push_back(ParenState(NewIndent, NewIndentLevel,
745 State.Stack.back().LastSpace,
746 AvoidBinPacking, NoLineBreak));
Daniel Jasper1db6c382013-10-22 15:30:28 +0000747 State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000748 ++State.ParenLevel;
749 }
750
Daniel Jasperde0328a2013-08-16 11:20:30 +0000751 // If we encounter a closing ), ], } or >, we can remove a level from our
752 // stacks.
Daniel Jasper96df37a2013-08-28 09:17:37 +0000753 if (State.Stack.size() > 1 &&
754 (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000755 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
Daniel Jasper96df37a2013-08-28 09:17:37 +0000756 State.NextToken->Type == TT_TemplateCloser)) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000757 State.Stack.pop_back();
758 --State.ParenLevel;
759 }
760 if (Current.is(tok::r_square)) {
761 // If this ends the array subscript expr, reset the corresponding value.
762 const FormatToken *NextNonComment = Current.getNextNonComment();
763 if (NextNonComment && NextNonComment->isNot(tok::l_square))
764 State.Stack.back().StartOfArraySubscripts = 0;
765 }
766
767 // Remove scopes created by fake parenthesis.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000768 if (Current.isNot(tok::r_brace) ||
769 (Current.MatchingParen && Current.MatchingParen->BlockKind != BK_Block)) {
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000770 // Don't remove FakeRParens attached to r_braces that surround nested blocks
771 // as they will have been removed early (see above).
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000772 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
773 unsigned VariablePos = State.Stack.back().VariablePos;
Manuel Klimek819788d2014-03-18 11:22:45 +0000774 assert(State.Stack.size() > 1);
775 if (State.Stack.size() == 1) {
776 // Do not pop the last element.
777 break;
778 }
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000779 State.Stack.pop_back();
780 State.Stack.back().VariablePos = VariablePos;
781 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000782 }
783
Daniel Jasper04b6a082013-12-20 06:22:01 +0000784 if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000785 State.StartOfStringLiteral = State.Column;
Daniel Jasper04b6a082013-12-20 06:22:01 +0000786 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
787 !Current.isStringLiteral()) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000788 State.StartOfStringLiteral = 0;
789 }
790
Alexander Kornienko39856b72013-09-10 09:38:25 +0000791 State.Column += Current.ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000792 State.NextToken = State.NextToken->Next;
Daniel Jasperb27c4b72013-08-27 11:09:05 +0000793 unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000794 if (State.Column > getColumnLimit(State)) {
795 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
796 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
797 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000798
Daniel Jasper01603472014-01-09 13:42:56 +0000799 if (Current.Role)
800 Current.Role->formatFromToken(State, this, DryRun);
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000801 // If the previous has a special role, let it consume tokens as appropriate.
802 // It is necessary to start at the previous token for the only implemented
803 // role (comma separated list). That way, the decision whether or not to break
804 // after the "{" is already done and both options are tried and evaluated.
805 // FIXME: This is ugly, find a better way.
806 if (Previous && Previous->Role)
Daniel Jasper01603472014-01-09 13:42:56 +0000807 Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000808
809 return Penalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000810}
811
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000812unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
813 LineState &State) {
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000814 // Break before further function parameters on all levels.
815 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
816 State.Stack[i].BreakBeforeParameter = true;
817
Alexander Kornienko39856b72013-09-10 09:38:25 +0000818 unsigned ColumnsUsed = State.Column;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000819 // We can only affect layout of the first and the last line, so the penalty
820 // for all other lines is constant, and we ignore it.
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000821 State.Column = Current.LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000822
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000823 if (ColumnsUsed > getColumnLimit(State))
824 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000825 return 0;
826}
827
Alexander Kornienko81e32942013-09-16 20:20:49 +0000828static bool getRawStringLiteralPrefixPostfix(StringRef Text,
829 StringRef &Prefix,
830 StringRef &Postfix) {
831 if (Text.startswith(Prefix = "R\"") || Text.startswith(Prefix = "uR\"") ||
832 Text.startswith(Prefix = "UR\"") || Text.startswith(Prefix = "u8R\"") ||
833 Text.startswith(Prefix = "LR\"")) {
834 size_t ParenPos = Text.find('(');
835 if (ParenPos != StringRef::npos) {
836 StringRef Delimiter =
837 Text.substr(Prefix.size(), ParenPos - Prefix.size());
838 Prefix = Text.substr(0, ParenPos + 1);
839 Postfix = Text.substr(Text.size() - 2 - Delimiter.size());
840 return Postfix.front() == ')' && Postfix.back() == '"' &&
841 Postfix.substr(1).startswith(Delimiter);
842 }
843 }
844 return false;
845}
846
Daniel Jasperde0328a2013-08-16 11:20:30 +0000847unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
848 LineState &State,
849 bool DryRun) {
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000850 // Don't break multi-line tokens other than block comments. Instead, just
851 // update the state.
852 if (Current.Type != TT_BlockComment && Current.IsMultiline)
853 return addMultilineToken(Current, State);
854
Daniel Jasper98857842013-10-30 13:54:53 +0000855 // Don't break implicit string literals.
856 if (Current.Type == TT_ImplicitStringLiteral)
857 return 0;
858
Daniel Jasper04b6a082013-12-20 06:22:01 +0000859 if (!Current.isStringLiteral() && !Current.is(tok::comment))
Daniel Jasperf93551c2013-08-23 10:05:49 +0000860 return 0;
861
Ahmed Charlesb8984322014-03-07 20:03:18 +0000862 std::unique_ptr<BreakableToken> Token;
Alexander Kornienko39856b72013-09-10 09:38:25 +0000863 unsigned StartColumn = State.Column - Current.ColumnWidth;
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000864 unsigned ColumnLimit = getColumnLimit(State);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000865
Daniel Jasper04b6a082013-12-20 06:22:01 +0000866 if (Current.isStringLiteral()) {
Alexander Kornienko384b40b2013-10-11 21:43:05 +0000867 // Don't break string literals inside preprocessor directives (except for
868 // #define directives, as their contents are stored in separate lines and
869 // are not affected by this check).
870 // This way we avoid breaking code with line directives and unknown
871 // preprocessor directives that contain long string literals.
872 if (State.Line->Type == LT_PreprocessorDirective)
873 return 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000874 // Exempts unterminated string literals from line breaking. The user will
875 // likely want to terminate the string before any line breaking is done.
876 if (Current.IsUnterminatedLiteral)
877 return 0;
878
Alexander Kornienko81e32942013-09-16 20:20:49 +0000879 StringRef Text = Current.TokenText;
880 StringRef Prefix;
881 StringRef Postfix;
Daniel Jasper174b0122014-01-09 14:18:12 +0000882 bool IsNSStringLiteral = false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000883 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
884 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
885 // reduce the overhead) for each FormatToken, which is a string, so that we
886 // don't run multiple checks here on the hot path.
Daniel Jasper174b0122014-01-09 14:18:12 +0000887 if (Text.startswith("\"") && Current.Previous &&
888 Current.Previous->is(tok::at)) {
889 IsNSStringLiteral = true;
890 Prefix = "@\"";
Daniel Jasper174b0122014-01-09 14:18:12 +0000891 }
Alexander Kornienko81e32942013-09-16 20:20:49 +0000892 if ((Text.endswith(Postfix = "\"") &&
Daniel Jasper174b0122014-01-09 14:18:12 +0000893 (IsNSStringLiteral || Text.startswith(Prefix = "\"") ||
894 Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
895 Text.startswith(Prefix = "u8\"") ||
Alexander Kornienko81e32942013-09-16 20:20:49 +0000896 Text.startswith(Prefix = "L\""))) ||
897 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")")) ||
898 getRawStringLiteralPrefixPostfix(Text, Prefix, Postfix)) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000899 Token.reset(new BreakableStringLiteral(
900 Current, State.Line->Level, StartColumn, Prefix, Postfix,
901 State.Line->InPPDirective, Encoding, Style));
Alexander Kornienko81e32942013-09-16 20:20:49 +0000902 } else {
903 return 0;
904 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000905 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000906 if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
907 return 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000908 Token.reset(new BreakableBlockComment(
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000909 Current, State.Line->Level, StartColumn, Current.OriginalColumn,
910 !Current.Previous, State.Line->InPPDirective, Encoding, Style));
Daniel Jasperde0328a2013-08-16 11:20:30 +0000911 } else if (Current.Type == TT_LineComment &&
912 (Current.Previous == NULL ||
913 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000914 if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
915 return 0;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000916 Token.reset(new BreakableLineComment(Current, State.Line->Level,
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000917 StartColumn, /*InPPDirective=*/false,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000918 Encoding, Style));
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000919 // We don't insert backslashes when breaking line comments.
920 ColumnLimit = Style.ColumnLimit;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000921 } else {
922 return 0;
923 }
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000924 if (Current.UnbreakableTailLength >= ColumnLimit)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000925 return 0;
926
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000927 unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000928 bool BreakInserted = false;
929 unsigned Penalty = 0;
930 unsigned RemainingTokenColumns = 0;
931 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
932 LineIndex != EndIndex; ++LineIndex) {
933 if (!DryRun)
934 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
935 unsigned TailOffset = 0;
936 RemainingTokenColumns =
937 Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
938 while (RemainingTokenColumns > RemainingSpace) {
939 BreakableToken::Split Split =
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000940 Token->getSplit(LineIndex, TailOffset, ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000941 if (Split.first == StringRef::npos) {
942 // The last line's penalty is handled in addNextStateToQueue().
943 if (LineIndex < EndIndex - 1)
944 Penalty += Style.PenaltyExcessCharacter *
945 (RemainingTokenColumns - RemainingSpace);
946 break;
947 }
948 assert(Split.first != 0);
949 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
950 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
Alexander Kornienko875395f2013-11-12 17:50:13 +0000951
952 // We can remove extra whitespace instead of breaking the line.
953 if (RemainingTokenColumns + 1 - Split.second <= RemainingSpace) {
954 RemainingTokenColumns = 0;
955 if (!DryRun)
956 Token->replaceWhitespace(LineIndex, TailOffset, Split, Whitespaces);
957 break;
958 }
959
Daniel Jasperde0328a2013-08-16 11:20:30 +0000960 assert(NewRemainingTokenColumns < RemainingTokenColumns);
961 if (!DryRun)
962 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Daniel Jasper2739af32013-08-28 10:03:58 +0000963 Penalty += Current.SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000964 unsigned ColumnsUsed =
965 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000966 if (ColumnsUsed > ColumnLimit) {
967 Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000968 }
969 TailOffset += Split.first + Split.second;
970 RemainingTokenColumns = NewRemainingTokenColumns;
971 BreakInserted = true;
972 }
973 }
974
975 State.Column = RemainingTokenColumns;
976
977 if (BreakInserted) {
978 // If we break the token inside a parameter list, we need to break before
979 // the next parameter on all levels, so that the next parameter is clearly
980 // visible. Line comments already introduce a break.
981 if (Current.Type != TT_LineComment) {
982 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
983 State.Stack[i].BreakBeforeParameter = true;
984 }
985
Daniel Jasper04b6a082013-12-20 06:22:01 +0000986 Penalty += Current.isStringLiteral() ? Style.PenaltyBreakString
987 : Style.PenaltyBreakComment;
Daniel Jasper2739af32013-08-28 10:03:58 +0000988
Daniel Jasperde0328a2013-08-16 11:20:30 +0000989 State.Stack.back().LastSpace = StartColumn;
990 }
991 return Penalty;
992}
993
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000994unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000995 // In preprocessor directives reserve two chars for trailing " \"
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000996 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000997}
998
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000999bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
Daniel Jasperf438cb72013-08-23 11:57:34 +00001000 const FormatToken &Current = *State.NextToken;
Daniel Jasper04b6a082013-12-20 06:22:01 +00001001 if (!Current.isStringLiteral())
Daniel Jasperf438cb72013-08-23 11:57:34 +00001002 return false;
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00001003 // We never consider raw string literals "multiline" for the purpose of
Daniel Jasperc39b56f2013-12-16 07:23:08 +00001004 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
1005 // (see TokenAnnotator::mustBreakBefore().
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00001006 if (Current.TokenText.startswith("R\""))
1007 return false;
Alexander Kornienko39856b72013-09-10 09:38:25 +00001008 if (Current.IsMultiline)
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00001009 return true;
Daniel Jasperf438cb72013-08-23 11:57:34 +00001010 if (Current.getNextNonComment() &&
Daniel Jasper04b6a082013-12-20 06:22:01 +00001011 Current.getNextNonComment()->isStringLiteral())
Daniel Jasperf438cb72013-08-23 11:57:34 +00001012 return true; // Implicit concatenation.
Alexander Kornienko39856b72013-09-10 09:38:25 +00001013 if (State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
Daniel Jasperf438cb72013-08-23 11:57:34 +00001014 Style.ColumnLimit)
1015 return true; // String will be split.
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00001016 return false;
Daniel Jasperf438cb72013-08-23 11:57:34 +00001017}
1018
Daniel Jasperde0328a2013-08-16 11:20:30 +00001019} // namespace format
1020} // namespace clang