blob: 6db3ca98240ee89d050d3b727511836595687f1e [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.
111 if (Previous.opensScope() && State.LowestLevelOnLine < State.StartOfLineLevel)
112 return false;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000113 if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
114 return false;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000115 return !State.Stack.back().NoLineBreak;
116}
117
118bool ContinuationIndenter::mustBreak(const LineState &State) {
119 const FormatToken &Current = *State.NextToken;
120 const FormatToken &Previous = *Current.Previous;
121 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
122 return true;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000123 if (State.Stack.back().BreakBeforeClosingBrace &&
124 Current.closesBlockTypeList(Style))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000125 return true;
126 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
127 return true;
Daniel Jasperec01cd62013-10-08 05:11:18 +0000128 if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
Daniel Jasper165b29e2013-11-08 00:57:11 +0000129 (Style.BreakBeforeTernaryOperators &&
130 (Current.is(tok::question) || (Current.Type == TT_ConditionalExpr &&
131 Previous.isNot(tok::question)))) ||
132 (!Style.BreakBeforeTernaryOperators &&
133 (Previous.is(tok::question) || Previous.Type == TT_ConditionalExpr))) &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000134 State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
135 !Current.isOneOf(tok::r_paren, tok::r_brace))
136 return true;
137 if (Style.AlwaysBreakBeforeMultilineStrings &&
Daniel Jasperf438cb72013-08-23 11:57:34 +0000138 State.Column > State.Stack.back().Indent && // Breaking saves columns.
Daniel Jasper27943052013-11-09 03:08:25 +0000139 !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) &&
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000140 Previous.Type != TT_InlineASMColon && nextIsMultilineString(State))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000141 return true;
Daniel Jasperb596fb22013-10-24 10:31:50 +0000142 if (((Previous.Type == TT_DictLiteral && Previous.is(tok::l_brace)) ||
Daniel Jasper1db6c382013-10-22 15:30:28 +0000143 Previous.Type == TT_ArrayInitializerLSquare) &&
Daniel Jasperd489dd32013-10-20 16:45:46 +0000144 getLengthToMatchingParen(Previous) + State.Column > getColumnLimit(State))
145 return true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000146
147 if (!Style.BreakBeforeBinaryOperators) {
148 // If we need to break somewhere inside the LHS of a binary expression, we
149 // should also break after the operator. Otherwise, the formatting would
150 // hide the operator precedence, e.g. in:
151 // if (aaaaaaaaaaaaaa ==
152 // bbbbbbbbbbbbbb && c) {..
153 // For comparisons, we only apply this rule, if the LHS is a binary
154 // expression itself as otherwise, the line breaks seem superfluous.
155 // We need special cases for ">>" which we have split into two ">" while
156 // lexing in order to make template parsing easier.
157 //
158 // FIXME: We'll need something similar for styles that break before binary
159 // operators.
160 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
161 Previous.getPrecedence() == prec::Equality) &&
162 Previous.Previous &&
163 Previous.Previous->Type != TT_BinaryOperator; // For >>.
164 bool LHSIsBinaryExpr =
Daniel Jasper562ecd42013-09-06 08:08:14 +0000165 Previous.Previous && Previous.Previous->EndsBinaryExpression;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000166 if (Previous.Type == TT_BinaryOperator &&
167 (!IsComparison || LHSIsBinaryExpr) &&
168 Current.Type != TT_BinaryOperator && // For >>.
169 !Current.isTrailingComment() &&
170 !Previous.isOneOf(tok::lessless, tok::question) &&
171 Previous.getPrecedence() != prec::Assignment &&
172 State.Stack.back().BreakBeforeParameter)
173 return true;
174 }
175
176 // Same as above, but for the first "<<" operator.
177 if (Current.is(tok::lessless) && State.Stack.back().BreakBeforeParameter &&
178 State.Stack.back().FirstLessLess == 0)
179 return true;
180
Daniel Jasperde0328a2013-08-16 11:20:30 +0000181 if (Current.Type == TT_ObjCSelectorName &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000182 State.Stack.back().ObjCSelectorNameFound &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000183 State.Stack.back().BreakBeforeParameter)
184 return true;
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000185 if (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0 &&
186 !Current.isTrailingComment())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000187 return true;
188
189 if ((Current.Type == TT_StartOfName || Current.is(tok::kw_operator)) &&
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000190 State.Line->MightBeFunctionDecl &&
191 State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000192 return true;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000193 if (startsSegmentOfBuilderTypeCall(Current) &&
Daniel Jasperf8151e92013-08-30 07:12:40 +0000194 (State.Stack.back().CallContinuation != 0 ||
195 (State.Stack.back().BreakBeforeParameter &&
196 State.Stack.back().ContainsUnwrappedBuilder)))
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000197 return true;
Daniel Jasper96972812014-01-05 12:38:10 +0000198
199 // The following could be precomputed as they do not depend on the state.
200 // However, as they should take effect only if the UnwrappedLine does not fit
201 // into the ColumnLimit, they are checked here in the ContinuationIndenter.
202 if (Previous.BlockKind == BK_Block && Previous.is(tok::l_brace) &&
203 !Current.isOneOf(tok::r_brace, tok::comment))
204 return true;
205 if (Current.Type == TT_CtorInitializerColon &&
206 (!Style.AllowShortFunctionsOnASingleLine ||
207 Style.BreakConstructorInitializersBeforeComma || Style.ColumnLimit != 0))
208 return true;
209
Daniel Jasperde0328a2013-08-16 11:20:30 +0000210 return false;
211}
212
213unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000214 bool DryRun,
215 unsigned ExtraSpaces) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000216 const FormatToken &Current = *State.NextToken;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000217
Daniel Jasper98857842013-10-30 13:54:53 +0000218 if (State.Stack.size() == 0 ||
219 (Current.Type == TT_ImplicitStringLiteral &&
220 (Current.Previous->Tok.getIdentifierInfo() == NULL ||
221 Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
222 tok::pp_not_keyword))) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000223 // FIXME: Is this correct?
224 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
225 State.NextToken->WhitespaceRange.getEnd()) -
226 SourceMgr.getSpellingColumnNumber(
227 State.NextToken->WhitespaceRange.getBegin());
Alexander Kornienko39856b72013-09-10 09:38:25 +0000228 State.Column += WhitespaceLength + State.NextToken->ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000229 State.NextToken = State.NextToken->Next;
230 return 0;
231 }
232
Alexander Kornienko1f803962013-10-01 14:41:18 +0000233 unsigned Penalty = 0;
234 if (Newline)
235 Penalty = addTokenOnNewLine(State, DryRun);
236 else
Daniel Jasper48437ce2013-11-20 14:54:39 +0000237 addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000238
239 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
240}
241
Daniel Jasper48437ce2013-11-20 14:54:39 +0000242void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
243 unsigned ExtraSpaces) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000244 FormatToken &Current = *State.NextToken;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000245 const FormatToken &Previous = *State.NextToken->Previous;
246 if (Current.is(tok::equal) &&
247 (State.Line->First->is(tok::kw_for) || State.ParenLevel == 0) &&
248 State.Stack.back().VariablePos == 0) {
249 State.Stack.back().VariablePos = State.Column;
250 // Move over * and & if they are bound to the variable name.
251 const FormatToken *Tok = &Previous;
252 while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
253 State.Stack.back().VariablePos -= Tok->ColumnWidth;
254 if (Tok->SpacesRequiredBefore != 0)
255 break;
256 Tok = Tok->Previous;
257 }
258 if (Previous.PartOfMultiVariableDeclStmt)
259 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
260 }
261
262 unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
263
264 if (!DryRun)
265 Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, /*IndentLevel=*/0,
266 Spaces, State.Column + Spaces);
267
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000268 if (Current.Type == TT_ObjCSelectorName &&
269 !State.Stack.back().ObjCSelectorNameFound) {
270 if (Current.LongestObjCSelectorName == 0)
271 State.Stack.back().AlignColons = false;
272 else if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
273 State.Column + Spaces + Current.ColumnWidth)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000274 State.Stack.back().ColonPos =
275 State.Stack.back().Indent + Current.LongestObjCSelectorName;
276 else
277 State.Stack.back().ColonPos = State.Column + Spaces + Current.ColumnWidth;
278 }
279
280 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper5a611392013-12-19 21:41:37 +0000281 (Current.Type != TT_LineComment || Previous.BlockKind == BK_BracedInit))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000282 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasperec01cd62013-10-08 05:11:18 +0000283 if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000284 State.Stack.back().NoLineBreak = true;
285 if (startsSegmentOfBuilderTypeCall(Current))
286 State.Stack.back().ContainsUnwrappedBuilder = true;
287
288 State.Column += Spaces;
289 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
290 // Treat the condition inside an if as if it was a second function
Daniel Jasper6633ab82013-10-18 10:38:14 +0000291 // parameter, i.e. let nested calls have a continuation indent.
Alexander Kornienko1f803962013-10-01 14:41:18 +0000292 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000293 else if (Current.isNot(tok::comment) &&
294 (Previous.is(tok::comma) ||
295 (Previous.is(tok::colon) && Previous.Type == TT_ObjCMethodExpr)))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000296 State.Stack.back().LastSpace = State.Column;
297 else if ((Previous.Type == TT_BinaryOperator ||
298 Previous.Type == TT_ConditionalExpr ||
299 Previous.Type == TT_UnaryOperator ||
300 Previous.Type == TT_CtorInitializerColon) &&
301 (Previous.getPrecedence() != prec::Assignment ||
302 Current.StartsBinaryExpression))
303 // Always indent relative to the RHS of the expression unless this is a
304 // simple assignment without binary expression on the RHS. Also indent
305 // relative to unary operators and the colons of constructor initializers.
306 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf9a5e402013-10-08 16:24:07 +0000307 else if (Previous.Type == TT_InheritanceColon) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000308 State.Stack.back().Indent = State.Column;
Daniel Jasperf9a5e402013-10-08 16:24:07 +0000309 State.Stack.back().LastSpace = State.Column;
310 } else if (Previous.opensScope()) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000311 // If a function has a trailing call, indent all parameters from the
312 // opening parenthesis. This avoids confusing indents like:
313 // OuterFunction(InnerFunctionCall( // break
314 // ParameterToInnerFunction)) // break
315 // .SecondInnerFunctionCall();
316 bool HasTrailingCall = false;
317 if (Previous.MatchingParen) {
318 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
319 HasTrailingCall = Next && Next->isMemberAccess();
320 }
321 if (HasTrailingCall &&
322 State.Stack[State.Stack.size() - 2].CallContinuation == 0)
323 State.Stack.back().LastSpace = State.Column;
324 }
325}
326
327unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
328 bool DryRun) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000329 FormatToken &Current = *State.NextToken;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000330 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasper6633ab82013-10-18 10:38:14 +0000331 // If we are continuing an expression, we want to use the continuation indent.
Daniel Jasperde0328a2013-08-16 11:20:30 +0000332 unsigned ContinuationIndent =
Daniel Jasper6633ab82013-10-18 10:38:14 +0000333 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
334 Style.ContinuationIndentWidth;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000335 // Extra penalty that needs to be added because of the way certain line
336 // breaks are chosen.
337 unsigned Penalty = 0;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000338
Alexander Kornienko1f803962013-10-01 14:41:18 +0000339 const FormatToken *PreviousNonComment =
340 State.NextToken->getPreviousNonComment();
341 // The first line break on any ParenLevel causes an extra penalty in order
342 // prefer similar line breaks.
343 if (!State.Stack.back().ContainsLineBreak)
344 Penalty += 15;
345 State.Stack.back().ContainsLineBreak = true;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000346
Alexander Kornienko1f803962013-10-01 14:41:18 +0000347 Penalty += State.NextToken->SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000348
Alexander Kornienko1f803962013-10-01 14:41:18 +0000349 // Breaking before the first "<<" is generally not desirable if the LHS is
Daniel Jasper48437ce2013-11-20 14:54:39 +0000350 // short. Also always add the penalty if the LHS is split over mutliple lines
351 // to avoid unncessary line breaks that just work around this penalty.
352 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0 &&
Daniel Jasper004177e2013-12-19 16:06:40 +0000353 (State.Column <= Style.ColumnLimit / 3 ||
Daniel Jasper48437ce2013-11-20 14:54:39 +0000354 State.Stack.back().BreakBeforeParameter))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000355 Penalty += Style.PenaltyBreakFirstLessLess;
356
357 if (Current.is(tok::l_brace) && Current.BlockKind == BK_Block) {
Daniel Jaspere40caf92013-11-29 08:46:20 +0000358 State.Column =
359 State.ParenLevel == 0 ? State.FirstIndent : State.Stack.back().Indent;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000360 } else if (Current.isOneOf(tok::r_brace, tok::r_square)) {
Daniel Jasper6b6e7c32013-11-07 14:02:28 +0000361 if (Current.closesBlockTypeList(Style) ||
362 (Current.MatchingParen &&
363 Current.MatchingParen->BlockKind == BK_BracedInit))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000364 State.Column = State.Stack[State.Stack.size() - 2].LastSpace;
365 else
Daniel Jasper015ed022013-09-13 09:20:45 +0000366 State.Column = State.FirstIndent;
Daniel Jasper04b6a082013-12-20 06:22:01 +0000367 } else if (Current.isStringLiteral() && State.StartOfStringLiteral != 0) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000368 State.Column = State.StartOfStringLiteral;
369 State.Stack.back().BreakBeforeParameter = true;
370 } else if (Current.is(tok::lessless) &&
371 State.Stack.back().FirstLessLess != 0) {
372 State.Column = State.Stack.back().FirstLessLess;
373 } else if (Current.isMemberAccess()) {
374 if (State.Stack.back().CallContinuation == 0) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000375 State.Column = ContinuationIndent;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000376 State.Stack.back().CallContinuation = State.Column;
377 } else {
378 State.Column = State.Stack.back().CallContinuation;
379 }
Daniel Jasper165b29e2013-11-08 00:57:11 +0000380 } else if (State.Stack.back().QuestionColumn != 0 &&
381 (Current.Type == TT_ConditionalExpr ||
382 Previous.Type == TT_ConditionalExpr)) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000383 State.Column = State.Stack.back().QuestionColumn;
384 } else if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0) {
385 State.Column = State.Stack.back().VariablePos;
386 } else if ((PreviousNonComment &&
Daniel Jasper559b63c2014-01-28 20:13:43 +0000387 (PreviousNonComment->ClosesTemplateDeclaration ||
388 PreviousNonComment->Type == TT_AttributeParen)) ||
Alexander Kornienko1f803962013-10-01 14:41:18 +0000389 ((Current.Type == TT_StartOfName ||
390 Current.is(tok::kw_operator)) &&
391 State.ParenLevel == 0 &&
392 (!Style.IndentFunctionDeclarationAfterType ||
393 State.Line->StartsDefinition))) {
Daniel Jasper298c3402013-11-22 07:48:15 +0000394 State.Column =
395 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000396 } else if (Current.Type == TT_ObjCSelectorName) {
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000397 if (!State.Stack.back().ObjCSelectorNameFound) {
398 if (Current.LongestObjCSelectorName == 0) {
399 State.Column = State.Stack.back().Indent;
400 State.Stack.back().AlignColons = false;
401 } else {
402 State.Stack.back().ColonPos =
403 State.Stack.back().Indent + Current.LongestObjCSelectorName;
404 State.Column = State.Stack.back().ColonPos - Current.ColumnWidth;
405 }
406 } else if (!State.Stack.back().AlignColons) {
407 State.Column = State.Stack.back().Indent;
Daniel Jasperb302f9a2013-11-08 02:08:01 +0000408 } else if (State.Stack.back().ColonPos > Current.ColumnWidth) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000409 State.Column = State.Stack.back().ColonPos - Current.ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000410 } else {
411 State.Column = State.Stack.back().Indent;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000412 State.Stack.back().ColonPos = State.Column + Current.ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000413 }
Daniel Jasper1db6c382013-10-22 15:30:28 +0000414 } else if (Current.Type == TT_ArraySubscriptLSquare) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000415 if (State.Stack.back().StartOfArraySubscripts != 0)
416 State.Column = State.Stack.back().StartOfArraySubscripts;
417 else
418 State.Column = ContinuationIndent;
419 } else if (Current.Type == TT_StartOfName ||
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000420 Previous.isOneOf(tok::coloncolon, tok::equal)) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000421 State.Column = ContinuationIndent;
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000422 } else if (PreviousNonComment &&
423 PreviousNonComment->Type == TT_ObjCMethodExpr) {
424 State.Column = ContinuationIndent;
425 // FIXME: This is hacky, find a better way. The problem is that in an ObjC
426 // method expression, the block should be aligned to the line starting it,
427 // e.g.:
428 // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
429 // ^(int *i) {
430 // // ...
431 // }];
432 // Thus, we set LastSpace of the next higher ParenLevel, to which we move
433 // when we consume all of the "}"'s FakeRParens at the "{".
Daniel Jasper9a26e772013-12-23 11:25:40 +0000434 if (State.Stack.size() > 1)
435 State.Stack[State.Stack.size() - 2].LastSpace = ContinuationIndent;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000436 } else if (Current.Type == TT_CtorInitializerColon) {
437 State.Column = State.FirstIndent + Style.ConstructorInitializerIndentWidth;
438 } else if (Current.Type == TT_CtorInitializerComma) {
439 State.Column = State.Stack.back().Indent;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000440 } else {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000441 State.Column = State.Stack.back().Indent;
Daniel Jasper6633ab82013-10-18 10:38:14 +0000442 // Ensure that we fall back to the continuation indent width instead of just
Alexander Kornienko1f803962013-10-01 14:41:18 +0000443 // flushing continuations left.
Daniel Jasper16fc7542013-10-30 14:04:10 +0000444 if (State.Column == State.FirstIndent &&
445 PreviousNonComment->isNot(tok::r_brace))
Daniel Jasper6633ab82013-10-18 10:38:14 +0000446 State.Column += Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000447 }
448
Alexander Kornienko1f803962013-10-01 14:41:18 +0000449 if ((Previous.isOneOf(tok::comma, tok::semi) &&
450 !State.Stack.back().AvoidBinPacking) ||
451 Previous.Type == TT_BinaryOperator)
452 State.Stack.back().BreakBeforeParameter = false;
453 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
454 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000455 if (Current.is(tok::question) ||
456 (PreviousNonComment && PreviousNonComment->is(tok::question)))
457 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000458
459 if (!DryRun) {
460 unsigned Newlines = 1;
461 if (Current.is(tok::comment))
462 Newlines = std::max(Newlines, std::min(Current.NewlinesBefore,
463 Style.MaxEmptyLinesToKeep + 1));
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000464 Whitespaces.replaceWhitespace(Current, Newlines,
465 State.Stack.back().IndentLevel, State.Column,
466 State.Column, State.Line->InPPDirective);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000467 }
468
469 if (!Current.isTrailingComment())
470 State.Stack.back().LastSpace = State.Column;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000471 State.StartOfLineLevel = State.ParenLevel;
472 State.LowestLevelOnLine = State.ParenLevel;
473
474 // Any break on this level means that the parent level has been broken
475 // and we need to avoid bin packing there.
476 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
477 State.Stack[i].BreakBeforeParameter = true;
478 }
Daniel Jasper9e5ede02013-11-08 19:56:28 +0000479 if (PreviousNonComment &&
480 !PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
481 PreviousNonComment->Type != TT_TemplateCloser &&
482 PreviousNonComment->Type != TT_BinaryOperator &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000483 Current.Type != TT_BinaryOperator &&
Daniel Jasper9e5ede02013-11-08 19:56:28 +0000484 !PreviousNonComment->opensScope())
Alexander Kornienko1f803962013-10-01 14:41:18 +0000485 State.Stack.back().BreakBeforeParameter = true;
486
Daniel Jasper1db6c382013-10-22 15:30:28 +0000487 // If we break after { or the [ of an array initializer, we should also break
488 // before the corresponding } or ].
489 if (Previous.is(tok::l_brace) || Previous.Type == TT_ArrayInitializerLSquare)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000490 State.Stack.back().BreakBeforeClosingBrace = true;
491
492 if (State.Stack.back().AvoidBinPacking) {
493 // If we are breaking after '(', '{', '<', this is not bin packing
494 // unless AllowAllParametersOfDeclarationOnNextLine is false.
495 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
496 Previous.Type == TT_BinaryOperator) ||
497 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
498 State.Line->MustBeDeclaration))
499 State.Stack.back().BreakBeforeParameter = true;
500 }
501
502 return Penalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000503}
504
505unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
506 bool DryRun, bool Newline) {
507 const FormatToken &Current = *State.NextToken;
508 assert(State.Stack.size());
509
510 if (Current.Type == TT_InheritanceColon)
511 State.Stack.back().AvoidBinPacking = true;
512 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
513 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000514 if (Current.Type == TT_ArraySubscriptLSquare &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000515 State.Stack.back().StartOfArraySubscripts == 0)
516 State.Stack.back().StartOfArraySubscripts = State.Column;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000517 if ((Current.is(tok::question) && Style.BreakBeforeTernaryOperators) ||
518 (Current.getPreviousNonComment() && Current.isNot(tok::colon) &&
519 Current.getPreviousNonComment()->is(tok::question) &&
520 !Style.BreakBeforeTernaryOperators))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000521 State.Stack.back().QuestionColumn = State.Column;
522 if (!Current.opensScope() && !Current.closesScope())
523 State.LowestLevelOnLine =
524 std::min(State.LowestLevelOnLine, State.ParenLevel);
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000525 if (Current.isMemberAccess())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000526 State.Stack.back().StartOfFunctionCall =
Alexander Kornienko39856b72013-09-10 09:38:25 +0000527 Current.LastInChainOfCalls ? 0 : State.Column + Current.ColumnWidth;
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000528 if (Current.Type == TT_ObjCSelectorName)
529 State.Stack.back().ObjCSelectorNameFound = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000530 if (Current.Type == TT_CtorInitializerColon) {
531 // Indent 2 from the column, so:
532 // SomeClass::SomeClass()
533 // : First(...), ...
534 // Next(...)
535 // ^ line up here.
536 State.Stack.back().Indent =
537 State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
538 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
539 State.Stack.back().AvoidBinPacking = true;
540 State.Stack.back().BreakBeforeParameter = false;
541 }
542
Daniel Jasperde0328a2013-08-16 11:20:30 +0000543 // In ObjC method declaration we align on the ":" of parameters, but we need
Daniel Jasper6633ab82013-10-18 10:38:14 +0000544 // to ensure that we indent parameters on subsequent lines by at least our
545 // continuation indent width.
Daniel Jasperde0328a2013-08-16 11:20:30 +0000546 if (Current.Type == TT_ObjCMethodSpecifier)
Daniel Jasper6633ab82013-10-18 10:38:14 +0000547 State.Stack.back().Indent += Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000548
549 // Insert scopes created by fake parenthesis.
550 const FormatToken *Previous = Current.getPreviousNonComment();
551 // Don't add extra indentation for the first fake parenthesis after
552 // 'return', assignements or opening <({[. The indentation for these cases
553 // is special cased.
554 bool SkipFirstExtraIndent =
Daniel Jaspereabede62013-09-30 08:29:03 +0000555 (Previous && (Previous->opensScope() || Previous->is(tok::kw_return) ||
Daniel Jasperf48b5ab2013-11-07 19:23:49 +0000556 Previous->getPrecedence() == prec::Assignment ||
557 Previous->Type == TT_ObjCMethodExpr));
Daniel Jasperde0328a2013-08-16 11:20:30 +0000558 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
559 I = Current.FakeLParens.rbegin(),
560 E = Current.FakeLParens.rend();
561 I != E; ++I) {
562 ParenState NewParenState = State.Stack.back();
563 NewParenState.ContainsLineBreak = false;
Daniel Jaspereabede62013-09-30 08:29:03 +0000564
565 // Indent from 'LastSpace' unless this the fake parentheses encapsulating a
566 // builder type call after 'return'. If such a call is line-wrapped, we
567 // commonly just want to indent from the start of the line.
568 if (!Previous || Previous->isNot(tok::kw_return) || *I > 0)
569 NewParenState.Indent =
570 std::max(std::max(State.Column, NewParenState.Indent),
571 State.Stack.back().LastSpace);
572
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000573 // Do not indent relative to the fake parentheses inserted for "." or "->".
574 // This is a special case to make the following to statements consistent:
575 // OuterFunction(InnerFunctionCall( // break
576 // ParameterToInnerFunction));
577 // OuterFunction(SomeObject.InnerFunctionCall( // break
578 // ParameterToInnerFunction));
579 if (*I > prec::Unknown)
580 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
Daniel Jasper96964352013-12-18 10:44:36 +0000581 NewParenState.StartOfFunctionCall = State.Column;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000582
583 // Always indent conditional expressions. Never indent expression where
584 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
585 // prec::Assignment) as those have different indentation rules. Indent
586 // other expression, unless the indentation needs to be skipped.
587 if (*I == prec::Conditional ||
588 (!SkipFirstExtraIndent && *I > prec::Assignment &&
589 !Style.BreakBeforeBinaryOperators))
Daniel Jasper6633ab82013-10-18 10:38:14 +0000590 NewParenState.Indent += Style.ContinuationIndentWidth;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000591 if ((Previous && !Previous->opensScope()) || *I > prec::Comma)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000592 NewParenState.BreakBeforeParameter = false;
593 State.Stack.push_back(NewParenState);
594 SkipFirstExtraIndent = false;
595 }
596
597 // If we encounter an opening (, [, { or <, we add a level to our stacks to
598 // prepare for the following tokens.
599 if (Current.opensScope()) {
600 unsigned NewIndent;
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000601 unsigned NewIndentLevel = State.Stack.back().IndentLevel;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000602 bool AvoidBinPacking;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000603 bool BreakBeforeParameter = false;
604 if (Current.is(tok::l_brace) ||
605 Current.Type == TT_ArrayInitializerLSquare) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000606 if (Current.MatchingParen && Current.BlockKind == BK_Block) {
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000607 // If this is an l_brace starting a nested block, we pretend (wrt. to
608 // indentation) that we already consumed the corresponding r_brace.
Daniel Jasper96964352013-12-18 10:44:36 +0000609 // Thus, we remove all ParenStates caused by fake parentheses that end
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000610 // at the r_brace. The net effect of this is that we don't indent
611 // relative to the l_brace, if the nested block is the last parameter of
612 // a function. For example, this formats:
613 //
614 // SomeFunction(a, [] {
615 // f(); // break
616 // });
617 //
618 // instead of:
619 // SomeFunction(a, [] {
Daniel Jasper5500f612013-11-25 11:08:59 +0000620 // f(); // break
621 // });
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000622 for (unsigned i = 0; i != Current.MatchingParen->FakeRParens; ++i)
623 State.Stack.pop_back();
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000624 bool IsObjCBlock =
625 Previous &&
626 (Previous->is(tok::caret) ||
627 (Previous->is(tok::r_paren) && Previous->MatchingParen &&
628 Previous->MatchingParen->Previous &&
629 Previous->MatchingParen->Previous->is(tok::caret)));
630 // For some reason, ObjC blocks are indented like continuations.
631 NewIndent =
632 State.Stack.back().LastSpace +
633 (IsObjCBlock ? Style.ContinuationIndentWidth : Style.IndentWidth);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000634 ++NewIndentLevel;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000635 BreakBeforeParameter = true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000636 } else {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000637 NewIndent = State.Stack.back().LastSpace;
Daniel Jasperb8f61682013-10-22 15:45:58 +0000638 if (Current.opensBlockTypeList(Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000639 NewIndent += Style.IndentWidth;
Daniel Jasper5a611392013-12-19 21:41:37 +0000640 NewIndent = std::min(State.Column + 2, NewIndent);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000641 ++NewIndentLevel;
Daniel Jasperb8f61682013-10-22 15:45:58 +0000642 } else {
643 NewIndent += Style.ContinuationIndentWidth;
Daniel Jasper5a611392013-12-19 21:41:37 +0000644 NewIndent = std::min(State.Column + 1, NewIndent);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000645 }
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000646 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000647 const FormatToken *NextNoComment = Current.getNextNonComment();
Daniel Jasper015ed022013-09-13 09:20:45 +0000648 AvoidBinPacking = Current.BlockKind == BK_Block ||
Daniel Jasper1db6c382013-10-22 15:30:28 +0000649 Current.Type == TT_ArrayInitializerLSquare ||
Daniel Jasperb596fb22013-10-24 10:31:50 +0000650 Current.Type == TT_DictLiteral ||
Daniel Jasper015ed022013-09-13 09:20:45 +0000651 (NextNoComment &&
652 NextNoComment->Type == TT_DesignatedInitializerPeriod);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000653 } else {
Daniel Jasper6633ab82013-10-18 10:38:14 +0000654 NewIndent = Style.ContinuationIndentWidth +
655 std::max(State.Stack.back().LastSpace,
656 State.Stack.back().StartOfFunctionCall);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000657 AvoidBinPacking = !Style.BinPackParameters ||
658 (Style.ExperimentalAutoDetectBinPacking &&
659 (Current.PackingKind == PPK_OnePerLine ||
660 (!BinPackInconclusiveFunctions &&
661 Current.PackingKind == PPK_Inconclusive)));
Daniel Jasper1db6c382013-10-22 15:30:28 +0000662 // If this '[' opens an ObjC call, determine whether all parameters fit
663 // into one line and put one per line if they don't.
664 if (Current.Type == TT_ObjCMethodExpr &&
665 getLengthToMatchingParen(Current) + State.Column >
666 getColumnLimit(State))
667 BreakBeforeParameter = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000668 }
669
Daniel Jaspercc3114d2013-10-18 15:23:06 +0000670 bool NoLineBreak = State.Stack.back().NoLineBreak ||
671 (Current.Type == TT_TemplateOpener &&
672 State.Stack.back().ContainsUnwrappedBuilder);
673 State.Stack.push_back(ParenState(NewIndent, NewIndentLevel,
674 State.Stack.back().LastSpace,
675 AvoidBinPacking, NoLineBreak));
Daniel Jasper1db6c382013-10-22 15:30:28 +0000676 State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000677 ++State.ParenLevel;
678 }
679
Daniel Jasperde0328a2013-08-16 11:20:30 +0000680 // If we encounter a closing ), ], } or >, we can remove a level from our
681 // stacks.
Daniel Jasper96df37a2013-08-28 09:17:37 +0000682 if (State.Stack.size() > 1 &&
683 (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000684 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
Daniel Jasper96df37a2013-08-28 09:17:37 +0000685 State.NextToken->Type == TT_TemplateCloser)) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000686 State.Stack.pop_back();
687 --State.ParenLevel;
688 }
689 if (Current.is(tok::r_square)) {
690 // If this ends the array subscript expr, reset the corresponding value.
691 const FormatToken *NextNonComment = Current.getNextNonComment();
692 if (NextNonComment && NextNonComment->isNot(tok::l_square))
693 State.Stack.back().StartOfArraySubscripts = 0;
694 }
695
696 // Remove scopes created by fake parenthesis.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000697 if (Current.isNot(tok::r_brace) ||
698 (Current.MatchingParen && Current.MatchingParen->BlockKind != BK_Block)) {
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000699 // Don't remove FakeRParens attached to r_braces that surround nested blocks
700 // as they will have been removed early (see above).
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000701 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
702 unsigned VariablePos = State.Stack.back().VariablePos;
703 State.Stack.pop_back();
704 State.Stack.back().VariablePos = VariablePos;
705 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000706 }
707
Daniel Jasper04b6a082013-12-20 06:22:01 +0000708 if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000709 State.StartOfStringLiteral = State.Column;
Daniel Jasper04b6a082013-12-20 06:22:01 +0000710 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
711 !Current.isStringLiteral()) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000712 State.StartOfStringLiteral = 0;
713 }
714
Alexander Kornienko39856b72013-09-10 09:38:25 +0000715 State.Column += Current.ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000716 State.NextToken = State.NextToken->Next;
Daniel Jasperb27c4b72013-08-27 11:09:05 +0000717 unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000718 if (State.Column > getColumnLimit(State)) {
719 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
720 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
721 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000722
Daniel Jasper01603472014-01-09 13:42:56 +0000723 if (Current.Role)
724 Current.Role->formatFromToken(State, this, DryRun);
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000725 // If the previous has a special role, let it consume tokens as appropriate.
726 // It is necessary to start at the previous token for the only implemented
727 // role (comma separated list). That way, the decision whether or not to break
728 // after the "{" is already done and both options are tried and evaluated.
729 // FIXME: This is ugly, find a better way.
730 if (Previous && Previous->Role)
Daniel Jasper01603472014-01-09 13:42:56 +0000731 Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000732
733 return Penalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000734}
735
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000736unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
737 LineState &State) {
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000738 // Break before further function parameters on all levels.
739 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
740 State.Stack[i].BreakBeforeParameter = true;
741
Alexander Kornienko39856b72013-09-10 09:38:25 +0000742 unsigned ColumnsUsed = State.Column;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000743 // We can only affect layout of the first and the last line, so the penalty
744 // for all other lines is constant, and we ignore it.
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000745 State.Column = Current.LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000746
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000747 if (ColumnsUsed > getColumnLimit(State))
748 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000749 return 0;
750}
751
Alexander Kornienko81e32942013-09-16 20:20:49 +0000752static bool getRawStringLiteralPrefixPostfix(StringRef Text,
753 StringRef &Prefix,
754 StringRef &Postfix) {
755 if (Text.startswith(Prefix = "R\"") || Text.startswith(Prefix = "uR\"") ||
756 Text.startswith(Prefix = "UR\"") || Text.startswith(Prefix = "u8R\"") ||
757 Text.startswith(Prefix = "LR\"")) {
758 size_t ParenPos = Text.find('(');
759 if (ParenPos != StringRef::npos) {
760 StringRef Delimiter =
761 Text.substr(Prefix.size(), ParenPos - Prefix.size());
762 Prefix = Text.substr(0, ParenPos + 1);
763 Postfix = Text.substr(Text.size() - 2 - Delimiter.size());
764 return Postfix.front() == ')' && Postfix.back() == '"' &&
765 Postfix.substr(1).startswith(Delimiter);
766 }
767 }
768 return false;
769}
770
Daniel Jasperde0328a2013-08-16 11:20:30 +0000771unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
772 LineState &State,
773 bool DryRun) {
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000774 // Don't break multi-line tokens other than block comments. Instead, just
775 // update the state.
776 if (Current.Type != TT_BlockComment && Current.IsMultiline)
777 return addMultilineToken(Current, State);
778
Daniel Jasper98857842013-10-30 13:54:53 +0000779 // Don't break implicit string literals.
780 if (Current.Type == TT_ImplicitStringLiteral)
781 return 0;
782
Daniel Jasper04b6a082013-12-20 06:22:01 +0000783 if (!Current.isStringLiteral() && !Current.is(tok::comment))
Daniel Jasperf93551c2013-08-23 10:05:49 +0000784 return 0;
785
Daniel Jasperde0328a2013-08-16 11:20:30 +0000786 llvm::OwningPtr<BreakableToken> Token;
Alexander Kornienko39856b72013-09-10 09:38:25 +0000787 unsigned StartColumn = State.Column - Current.ColumnWidth;
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000788 unsigned ColumnLimit = getColumnLimit(State);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000789
Daniel Jasper04b6a082013-12-20 06:22:01 +0000790 if (Current.isStringLiteral()) {
Alexander Kornienko384b40b2013-10-11 21:43:05 +0000791 // Don't break string literals inside preprocessor directives (except for
792 // #define directives, as their contents are stored in separate lines and
793 // are not affected by this check).
794 // This way we avoid breaking code with line directives and unknown
795 // preprocessor directives that contain long string literals.
796 if (State.Line->Type == LT_PreprocessorDirective)
797 return 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000798 // Exempts unterminated string literals from line breaking. The user will
799 // likely want to terminate the string before any line breaking is done.
800 if (Current.IsUnterminatedLiteral)
801 return 0;
802
Alexander Kornienko81e32942013-09-16 20:20:49 +0000803 StringRef Text = Current.TokenText;
804 StringRef Prefix;
805 StringRef Postfix;
Daniel Jasper174b0122014-01-09 14:18:12 +0000806 bool IsNSStringLiteral = false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000807 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
808 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
809 // reduce the overhead) for each FormatToken, which is a string, so that we
810 // don't run multiple checks here on the hot path.
Daniel Jasper174b0122014-01-09 14:18:12 +0000811 if (Text.startswith("\"") && Current.Previous &&
812 Current.Previous->is(tok::at)) {
813 IsNSStringLiteral = true;
814 Prefix = "@\"";
Daniel Jasper174b0122014-01-09 14:18:12 +0000815 }
Alexander Kornienko81e32942013-09-16 20:20:49 +0000816 if ((Text.endswith(Postfix = "\"") &&
Daniel Jasper174b0122014-01-09 14:18:12 +0000817 (IsNSStringLiteral || Text.startswith(Prefix = "\"") ||
818 Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
819 Text.startswith(Prefix = "u8\"") ||
Alexander Kornienko81e32942013-09-16 20:20:49 +0000820 Text.startswith(Prefix = "L\""))) ||
821 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")")) ||
822 getRawStringLiteralPrefixPostfix(Text, Prefix, Postfix)) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000823 Token.reset(new BreakableStringLiteral(
824 Current, State.Line->Level, StartColumn, Prefix, Postfix,
825 State.Line->InPPDirective, Encoding, Style));
Alexander Kornienko81e32942013-09-16 20:20:49 +0000826 } else {
827 return 0;
828 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000829 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000830 if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
831 return 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000832 Token.reset(new BreakableBlockComment(
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000833 Current, State.Line->Level, StartColumn, Current.OriginalColumn,
834 !Current.Previous, State.Line->InPPDirective, Encoding, Style));
Daniel Jasperde0328a2013-08-16 11:20:30 +0000835 } else if (Current.Type == TT_LineComment &&
836 (Current.Previous == NULL ||
837 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000838 if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
839 return 0;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000840 Token.reset(new BreakableLineComment(Current, State.Line->Level,
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000841 StartColumn, /*InPPDirective=*/false,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000842 Encoding, Style));
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000843 // We don't insert backslashes when breaking line comments.
844 ColumnLimit = Style.ColumnLimit;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000845 } else {
846 return 0;
847 }
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000848 if (Current.UnbreakableTailLength >= ColumnLimit)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000849 return 0;
850
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000851 unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000852 bool BreakInserted = false;
853 unsigned Penalty = 0;
854 unsigned RemainingTokenColumns = 0;
855 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
856 LineIndex != EndIndex; ++LineIndex) {
857 if (!DryRun)
858 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
859 unsigned TailOffset = 0;
860 RemainingTokenColumns =
861 Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
862 while (RemainingTokenColumns > RemainingSpace) {
863 BreakableToken::Split Split =
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000864 Token->getSplit(LineIndex, TailOffset, ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000865 if (Split.first == StringRef::npos) {
866 // The last line's penalty is handled in addNextStateToQueue().
867 if (LineIndex < EndIndex - 1)
868 Penalty += Style.PenaltyExcessCharacter *
869 (RemainingTokenColumns - RemainingSpace);
870 break;
871 }
872 assert(Split.first != 0);
873 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
874 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
Alexander Kornienko875395f2013-11-12 17:50:13 +0000875
876 // We can remove extra whitespace instead of breaking the line.
877 if (RemainingTokenColumns + 1 - Split.second <= RemainingSpace) {
878 RemainingTokenColumns = 0;
879 if (!DryRun)
880 Token->replaceWhitespace(LineIndex, TailOffset, Split, Whitespaces);
881 break;
882 }
883
Daniel Jasperde0328a2013-08-16 11:20:30 +0000884 assert(NewRemainingTokenColumns < RemainingTokenColumns);
885 if (!DryRun)
886 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Daniel Jasper2739af32013-08-28 10:03:58 +0000887 Penalty += Current.SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000888 unsigned ColumnsUsed =
889 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000890 if (ColumnsUsed > ColumnLimit) {
891 Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000892 }
893 TailOffset += Split.first + Split.second;
894 RemainingTokenColumns = NewRemainingTokenColumns;
895 BreakInserted = true;
896 }
897 }
898
899 State.Column = RemainingTokenColumns;
900
901 if (BreakInserted) {
902 // If we break the token inside a parameter list, we need to break before
903 // the next parameter on all levels, so that the next parameter is clearly
904 // visible. Line comments already introduce a break.
905 if (Current.Type != TT_LineComment) {
906 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
907 State.Stack[i].BreakBeforeParameter = true;
908 }
909
Daniel Jasper04b6a082013-12-20 06:22:01 +0000910 Penalty += Current.isStringLiteral() ? Style.PenaltyBreakString
911 : Style.PenaltyBreakComment;
Daniel Jasper2739af32013-08-28 10:03:58 +0000912
Daniel Jasperde0328a2013-08-16 11:20:30 +0000913 State.Stack.back().LastSpace = StartColumn;
914 }
915 return Penalty;
916}
917
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000918unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000919 // In preprocessor directives reserve two chars for trailing " \"
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000920 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000921}
922
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000923bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
Daniel Jasperf438cb72013-08-23 11:57:34 +0000924 const FormatToken &Current = *State.NextToken;
Daniel Jasper04b6a082013-12-20 06:22:01 +0000925 if (!Current.isStringLiteral())
Daniel Jasperf438cb72013-08-23 11:57:34 +0000926 return false;
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000927 // We never consider raw string literals "multiline" for the purpose of
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000928 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
929 // (see TokenAnnotator::mustBreakBefore().
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000930 if (Current.TokenText.startswith("R\""))
931 return false;
Alexander Kornienko39856b72013-09-10 09:38:25 +0000932 if (Current.IsMultiline)
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000933 return true;
Daniel Jasperf438cb72013-08-23 11:57:34 +0000934 if (Current.getNextNonComment() &&
Daniel Jasper04b6a082013-12-20 06:22:01 +0000935 Current.getNextNonComment()->isStringLiteral())
Daniel Jasperf438cb72013-08-23 11:57:34 +0000936 return true; // Implicit concatenation.
Alexander Kornienko39856b72013-09-10 09:38:25 +0000937 if (State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
Daniel Jasperf438cb72013-08-23 11:57:34 +0000938 Style.ColumnLimit)
939 return true; // String will be split.
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000940 return false;
Daniel Jasperf438cb72013-08-23 11:57:34 +0000941}
942
Daniel Jasperde0328a2013-08-16 11:20:30 +0000943} // namespace format
944} // namespace clang