blob: b82726a6b83e09807ecacce2fe5e075b1492c67e [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.
Alexander Kornienko86b2dfd2014-03-06 15:13:08 +0000177 if (Current.is(tok::lessless) && Current.Type != TT_OverloadedOperator &&
178 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000179 State.Stack.back().FirstLessLess == 0)
180 return true;
181
Daniel Jasperde0328a2013-08-16 11:20:30 +0000182 if (Current.Type == TT_ObjCSelectorName &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000183 State.Stack.back().ObjCSelectorNameFound &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000184 State.Stack.back().BreakBeforeParameter)
185 return true;
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000186 if (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0 &&
187 !Current.isTrailingComment())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000188 return true;
189
190 if ((Current.Type == TT_StartOfName || Current.is(tok::kw_operator)) &&
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000191 State.Line->MightBeFunctionDecl &&
192 State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000193 return true;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000194 if (startsSegmentOfBuilderTypeCall(Current) &&
Daniel Jasperf8151e92013-08-30 07:12:40 +0000195 (State.Stack.back().CallContinuation != 0 ||
196 (State.Stack.back().BreakBeforeParameter &&
197 State.Stack.back().ContainsUnwrappedBuilder)))
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000198 return true;
Daniel Jasper96972812014-01-05 12:38:10 +0000199
200 // The following could be precomputed as they do not depend on the state.
201 // However, as they should take effect only if the UnwrappedLine does not fit
202 // into the ColumnLimit, they are checked here in the ContinuationIndenter.
203 if (Previous.BlockKind == BK_Block && Previous.is(tok::l_brace) &&
204 !Current.isOneOf(tok::r_brace, tok::comment))
205 return true;
206 if (Current.Type == TT_CtorInitializerColon &&
207 (!Style.AllowShortFunctionsOnASingleLine ||
208 Style.BreakConstructorInitializersBeforeComma || Style.ColumnLimit != 0))
209 return true;
210
Daniel Jasperde0328a2013-08-16 11:20:30 +0000211 return false;
212}
213
214unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000215 bool DryRun,
216 unsigned ExtraSpaces) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000217 const FormatToken &Current = *State.NextToken;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000218
Daniel Jasper98857842013-10-30 13:54:53 +0000219 if (State.Stack.size() == 0 ||
220 (Current.Type == TT_ImplicitStringLiteral &&
221 (Current.Previous->Tok.getIdentifierInfo() == NULL ||
222 Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
223 tok::pp_not_keyword))) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000224 // FIXME: Is this correct?
225 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
226 State.NextToken->WhitespaceRange.getEnd()) -
227 SourceMgr.getSpellingColumnNumber(
228 State.NextToken->WhitespaceRange.getBegin());
Alexander Kornienko39856b72013-09-10 09:38:25 +0000229 State.Column += WhitespaceLength + State.NextToken->ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000230 State.NextToken = State.NextToken->Next;
231 return 0;
232 }
233
Alexander Kornienko1f803962013-10-01 14:41:18 +0000234 unsigned Penalty = 0;
235 if (Newline)
236 Penalty = addTokenOnNewLine(State, DryRun);
237 else
Daniel Jasper48437ce2013-11-20 14:54:39 +0000238 addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000239
240 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
241}
242
Daniel Jasper48437ce2013-11-20 14:54:39 +0000243void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
244 unsigned ExtraSpaces) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000245 FormatToken &Current = *State.NextToken;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000246 const FormatToken &Previous = *State.NextToken->Previous;
247 if (Current.is(tok::equal) &&
248 (State.Line->First->is(tok::kw_for) || State.ParenLevel == 0) &&
249 State.Stack.back().VariablePos == 0) {
250 State.Stack.back().VariablePos = State.Column;
251 // Move over * and & if they are bound to the variable name.
252 const FormatToken *Tok = &Previous;
253 while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
254 State.Stack.back().VariablePos -= Tok->ColumnWidth;
255 if (Tok->SpacesRequiredBefore != 0)
256 break;
257 Tok = Tok->Previous;
258 }
259 if (Previous.PartOfMultiVariableDeclStmt)
260 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
261 }
262
263 unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
264
265 if (!DryRun)
266 Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, /*IndentLevel=*/0,
267 Spaces, State.Column + Spaces);
268
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000269 if (Current.Type == TT_ObjCSelectorName &&
270 !State.Stack.back().ObjCSelectorNameFound) {
271 if (Current.LongestObjCSelectorName == 0)
272 State.Stack.back().AlignColons = false;
273 else if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
274 State.Column + Spaces + Current.ColumnWidth)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000275 State.Stack.back().ColonPos =
276 State.Stack.back().Indent + Current.LongestObjCSelectorName;
277 else
278 State.Stack.back().ColonPos = State.Column + Spaces + Current.ColumnWidth;
279 }
280
281 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper5a611392013-12-19 21:41:37 +0000282 (Current.Type != TT_LineComment || Previous.BlockKind == BK_BracedInit))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000283 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasperec01cd62013-10-08 05:11:18 +0000284 if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000285 State.Stack.back().NoLineBreak = true;
286 if (startsSegmentOfBuilderTypeCall(Current))
287 State.Stack.back().ContainsUnwrappedBuilder = true;
288
289 State.Column += Spaces;
290 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
291 // Treat the condition inside an if as if it was a second function
Daniel Jasper6633ab82013-10-18 10:38:14 +0000292 // parameter, i.e. let nested calls have a continuation indent.
Alexander Kornienko1f803962013-10-01 14:41:18 +0000293 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000294 else if (Current.isNot(tok::comment) &&
295 (Previous.is(tok::comma) ||
296 (Previous.is(tok::colon) && Previous.Type == TT_ObjCMethodExpr)))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000297 State.Stack.back().LastSpace = State.Column;
298 else if ((Previous.Type == TT_BinaryOperator ||
299 Previous.Type == TT_ConditionalExpr ||
Alexander Kornienko1f803962013-10-01 14:41:18 +0000300 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
Daniel Jaspera0407742014-02-11 10:08:11 +0000339 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
340 const FormatToken *NextNonComment = Previous.getNextNonComment();
341 if (!NextNonComment)
342 NextNonComment = &Current;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000343 // The first line break on any ParenLevel causes an extra penalty in order
344 // prefer similar line breaks.
345 if (!State.Stack.back().ContainsLineBreak)
346 Penalty += 15;
347 State.Stack.back().ContainsLineBreak = true;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000348
Alexander Kornienko1f803962013-10-01 14:41:18 +0000349 Penalty += State.NextToken->SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000350
Daniel Jaspera0407742014-02-11 10:08:11 +0000351
Alexander Kornienko1f803962013-10-01 14:41:18 +0000352 // Breaking before the first "<<" is generally not desirable if the LHS is
Daniel Jasper48437ce2013-11-20 14:54:39 +0000353 // short. Also always add the penalty if the LHS is split over mutliple lines
354 // to avoid unncessary line breaks that just work around this penalty.
Daniel Jaspera0407742014-02-11 10:08:11 +0000355 if (NextNonComment->is(tok::lessless) &&
356 State.Stack.back().FirstLessLess == 0 &&
Daniel Jasper004177e2013-12-19 16:06:40 +0000357 (State.Column <= Style.ColumnLimit / 3 ||
Daniel Jasper48437ce2013-11-20 14:54:39 +0000358 State.Stack.back().BreakBeforeParameter))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000359 Penalty += Style.PenaltyBreakFirstLessLess;
360
Daniel Jaspera0407742014-02-11 10:08:11 +0000361 if (NextNonComment->is(tok::l_brace) &&
362 NextNonComment->BlockKind == BK_Block) {
Daniel Jaspere40caf92013-11-29 08:46:20 +0000363 State.Column =
364 State.ParenLevel == 0 ? State.FirstIndent : State.Stack.back().Indent;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000365 } else if (Current.isOneOf(tok::r_brace, tok::r_square)) {
Daniel Jasper6b6e7c32013-11-07 14:02:28 +0000366 if (Current.closesBlockTypeList(Style) ||
367 (Current.MatchingParen &&
368 Current.MatchingParen->BlockKind == BK_BracedInit))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000369 State.Column = State.Stack[State.Stack.size() - 2].LastSpace;
370 else
Daniel Jasper015ed022013-09-13 09:20:45 +0000371 State.Column = State.FirstIndent;
Daniel Jaspera0407742014-02-11 10:08:11 +0000372 } else if (NextNonComment->isStringLiteral() &&
373 State.StartOfStringLiteral != 0) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000374 State.Column = State.StartOfStringLiteral;
375 State.Stack.back().BreakBeforeParameter = true;
Daniel Jaspera0407742014-02-11 10:08:11 +0000376 } else if (NextNonComment->is(tok::lessless) &&
Alexander Kornienko1f803962013-10-01 14:41:18 +0000377 State.Stack.back().FirstLessLess != 0) {
378 State.Column = State.Stack.back().FirstLessLess;
Daniel Jaspera0407742014-02-11 10:08:11 +0000379 } else if (NextNonComment->isMemberAccess()) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000380 if (State.Stack.back().CallContinuation == 0) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000381 State.Column = ContinuationIndent;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000382 State.Stack.back().CallContinuation = State.Column;
383 } else {
384 State.Column = State.Stack.back().CallContinuation;
385 }
Daniel Jasper165b29e2013-11-08 00:57:11 +0000386 } else if (State.Stack.back().QuestionColumn != 0 &&
Daniel Jaspera0407742014-02-11 10:08:11 +0000387 (NextNonComment->Type == TT_ConditionalExpr ||
Daniel Jasper165b29e2013-11-08 00:57:11 +0000388 Previous.Type == TT_ConditionalExpr)) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000389 State.Column = State.Stack.back().QuestionColumn;
390 } else if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0) {
391 State.Column = State.Stack.back().VariablePos;
392 } else if ((PreviousNonComment &&
Daniel Jasper559b63c2014-01-28 20:13:43 +0000393 (PreviousNonComment->ClosesTemplateDeclaration ||
394 PreviousNonComment->Type == TT_AttributeParen)) ||
Daniel Jaspera0407742014-02-11 10:08:11 +0000395 ((NextNonComment->Type == TT_StartOfName ||
396 NextNonComment->is(tok::kw_operator)) &&
Alexander Kornienko1f803962013-10-01 14:41:18 +0000397 State.ParenLevel == 0 &&
398 (!Style.IndentFunctionDeclarationAfterType ||
399 State.Line->StartsDefinition))) {
Daniel Jasper298c3402013-11-22 07:48:15 +0000400 State.Column =
401 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
Daniel Jaspera0407742014-02-11 10:08:11 +0000402 } else if (NextNonComment->Type == TT_ObjCSelectorName) {
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000403 if (!State.Stack.back().ObjCSelectorNameFound) {
Daniel Jaspera0407742014-02-11 10:08:11 +0000404 if (NextNonComment->LongestObjCSelectorName == 0) {
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000405 State.Column = State.Stack.back().Indent;
406 State.Stack.back().AlignColons = false;
407 } else {
408 State.Stack.back().ColonPos =
Daniel Jaspera0407742014-02-11 10:08:11 +0000409 State.Stack.back().Indent + NextNonComment->LongestObjCSelectorName;
410 State.Column =
411 State.Stack.back().ColonPos - NextNonComment->ColumnWidth;
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000412 }
413 } else if (!State.Stack.back().AlignColons) {
414 State.Column = State.Stack.back().Indent;
Daniel Jaspera0407742014-02-11 10:08:11 +0000415 } else if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth) {
416 State.Column = State.Stack.back().ColonPos - NextNonComment->ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000417 } else {
418 State.Column = State.Stack.back().Indent;
Daniel Jaspera0407742014-02-11 10:08:11 +0000419 State.Stack.back().ColonPos = State.Column + NextNonComment->ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000420 }
Daniel Jaspera0407742014-02-11 10:08:11 +0000421 } else if (NextNonComment->Type == TT_ArraySubscriptLSquare) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000422 if (State.Stack.back().StartOfArraySubscripts != 0)
423 State.Column = State.Stack.back().StartOfArraySubscripts;
424 else
425 State.Column = ContinuationIndent;
Daniel Jaspera0407742014-02-11 10:08:11 +0000426 } else if (NextNonComment->Type == TT_StartOfName ||
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000427 Previous.isOneOf(tok::coloncolon, tok::equal)) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000428 State.Column = ContinuationIndent;
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000429 } else if (PreviousNonComment &&
430 PreviousNonComment->Type == TT_ObjCMethodExpr) {
431 State.Column = ContinuationIndent;
432 // FIXME: This is hacky, find a better way. The problem is that in an ObjC
433 // method expression, the block should be aligned to the line starting it,
434 // e.g.:
435 // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
436 // ^(int *i) {
437 // // ...
438 // }];
439 // Thus, we set LastSpace of the next higher ParenLevel, to which we move
440 // when we consume all of the "}"'s FakeRParens at the "{".
Daniel Jasper9a26e772013-12-23 11:25:40 +0000441 if (State.Stack.size() > 1)
442 State.Stack[State.Stack.size() - 2].LastSpace = ContinuationIndent;
Daniel Jaspera0407742014-02-11 10:08:11 +0000443 } else if (NextNonComment->Type == TT_CtorInitializerColon) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000444 State.Column = State.FirstIndent + Style.ConstructorInitializerIndentWidth;
Daniel Jaspera0407742014-02-11 10:08:11 +0000445 } else if (NextNonComment->Type == TT_CtorInitializerComma) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000446 State.Column = State.Stack.back().Indent;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000447 } else {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000448 State.Column = State.Stack.back().Indent;
Daniel Jasper6633ab82013-10-18 10:38:14 +0000449 // Ensure that we fall back to the continuation indent width instead of just
Alexander Kornienko1f803962013-10-01 14:41:18 +0000450 // flushing continuations left.
Daniel Jasper16fc7542013-10-30 14:04:10 +0000451 if (State.Column == State.FirstIndent &&
452 PreviousNonComment->isNot(tok::r_brace))
Daniel Jasper6633ab82013-10-18 10:38:14 +0000453 State.Column += Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000454 }
455
Alexander Kornienko1f803962013-10-01 14:41:18 +0000456 if ((Previous.isOneOf(tok::comma, tok::semi) &&
457 !State.Stack.back().AvoidBinPacking) ||
458 Previous.Type == TT_BinaryOperator)
459 State.Stack.back().BreakBeforeParameter = false;
460 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
461 State.Stack.back().BreakBeforeParameter = false;
Daniel Jaspera0407742014-02-11 10:08:11 +0000462 if (NextNonComment->is(tok::question) ||
Daniel Jasper165b29e2013-11-08 00:57:11 +0000463 (PreviousNonComment && PreviousNonComment->is(tok::question)))
464 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000465
466 if (!DryRun) {
467 unsigned Newlines = 1;
468 if (Current.is(tok::comment))
469 Newlines = std::max(Newlines, std::min(Current.NewlinesBefore,
470 Style.MaxEmptyLinesToKeep + 1));
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000471 Whitespaces.replaceWhitespace(Current, Newlines,
472 State.Stack.back().IndentLevel, State.Column,
473 State.Column, State.Line->InPPDirective);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000474 }
475
476 if (!Current.isTrailingComment())
477 State.Stack.back().LastSpace = State.Column;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000478 State.StartOfLineLevel = State.ParenLevel;
479 State.LowestLevelOnLine = State.ParenLevel;
480
481 // Any break on this level means that the parent level has been broken
482 // and we need to avoid bin packing there.
483 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
484 State.Stack[i].BreakBeforeParameter = true;
485 }
Daniel Jasper9e5ede02013-11-08 19:56:28 +0000486 if (PreviousNonComment &&
487 !PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
488 PreviousNonComment->Type != TT_TemplateCloser &&
489 PreviousNonComment->Type != TT_BinaryOperator &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000490 Current.Type != TT_BinaryOperator &&
Daniel Jasper9e5ede02013-11-08 19:56:28 +0000491 !PreviousNonComment->opensScope())
Alexander Kornienko1f803962013-10-01 14:41:18 +0000492 State.Stack.back().BreakBeforeParameter = true;
493
Daniel Jasper1db6c382013-10-22 15:30:28 +0000494 // If we break after { or the [ of an array initializer, we should also break
495 // before the corresponding } or ].
496 if (Previous.is(tok::l_brace) || Previous.Type == TT_ArrayInitializerLSquare)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000497 State.Stack.back().BreakBeforeClosingBrace = true;
498
499 if (State.Stack.back().AvoidBinPacking) {
500 // If we are breaking after '(', '{', '<', this is not bin packing
501 // unless AllowAllParametersOfDeclarationOnNextLine is false.
502 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
503 Previous.Type == TT_BinaryOperator) ||
504 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
505 State.Line->MustBeDeclaration))
506 State.Stack.back().BreakBeforeParameter = true;
507 }
508
509 return Penalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000510}
511
512unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
513 bool DryRun, bool Newline) {
514 const FormatToken &Current = *State.NextToken;
515 assert(State.Stack.size());
516
517 if (Current.Type == TT_InheritanceColon)
518 State.Stack.back().AvoidBinPacking = true;
Alexander Kornienko86b2dfd2014-03-06 15:13:08 +0000519 if (Current.is(tok::lessless) && Current.Type != TT_OverloadedOperator &&
520 State.Stack.back().FirstLessLess == 0)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000521 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000522 if (Current.Type == TT_ArraySubscriptLSquare &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000523 State.Stack.back().StartOfArraySubscripts == 0)
524 State.Stack.back().StartOfArraySubscripts = State.Column;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000525 if ((Current.is(tok::question) && Style.BreakBeforeTernaryOperators) ||
526 (Current.getPreviousNonComment() && Current.isNot(tok::colon) &&
527 Current.getPreviousNonComment()->is(tok::question) &&
528 !Style.BreakBeforeTernaryOperators))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000529 State.Stack.back().QuestionColumn = State.Column;
530 if (!Current.opensScope() && !Current.closesScope())
531 State.LowestLevelOnLine =
532 std::min(State.LowestLevelOnLine, State.ParenLevel);
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000533 if (Current.isMemberAccess())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000534 State.Stack.back().StartOfFunctionCall =
Alexander Kornienko39856b72013-09-10 09:38:25 +0000535 Current.LastInChainOfCalls ? 0 : State.Column + Current.ColumnWidth;
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000536 if (Current.Type == TT_ObjCSelectorName)
537 State.Stack.back().ObjCSelectorNameFound = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000538 if (Current.Type == TT_CtorInitializerColon) {
539 // Indent 2 from the column, so:
540 // SomeClass::SomeClass()
541 // : First(...), ...
542 // Next(...)
543 // ^ line up here.
544 State.Stack.back().Indent =
545 State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
546 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
547 State.Stack.back().AvoidBinPacking = true;
548 State.Stack.back().BreakBeforeParameter = false;
549 }
550
Daniel Jasperde0328a2013-08-16 11:20:30 +0000551 // In ObjC method declaration we align on the ":" of parameters, but we need
Daniel Jasper6633ab82013-10-18 10:38:14 +0000552 // to ensure that we indent parameters on subsequent lines by at least our
553 // continuation indent width.
Daniel Jasperde0328a2013-08-16 11:20:30 +0000554 if (Current.Type == TT_ObjCMethodSpecifier)
Daniel Jasper6633ab82013-10-18 10:38:14 +0000555 State.Stack.back().Indent += Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000556
557 // Insert scopes created by fake parenthesis.
558 const FormatToken *Previous = Current.getPreviousNonComment();
559 // Don't add extra indentation for the first fake parenthesis after
560 // 'return', assignements or opening <({[. The indentation for these cases
561 // is special cased.
562 bool SkipFirstExtraIndent =
Daniel Jaspereabede62013-09-30 08:29:03 +0000563 (Previous && (Previous->opensScope() || Previous->is(tok::kw_return) ||
Daniel Jasperf48b5ab2013-11-07 19:23:49 +0000564 Previous->getPrecedence() == prec::Assignment ||
565 Previous->Type == TT_ObjCMethodExpr));
Daniel Jasperde0328a2013-08-16 11:20:30 +0000566 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
567 I = Current.FakeLParens.rbegin(),
568 E = Current.FakeLParens.rend();
569 I != E; ++I) {
570 ParenState NewParenState = State.Stack.back();
571 NewParenState.ContainsLineBreak = false;
Daniel Jaspereabede62013-09-30 08:29:03 +0000572
573 // Indent from 'LastSpace' unless this the fake parentheses encapsulating a
574 // builder type call after 'return'. If such a call is line-wrapped, we
575 // commonly just want to indent from the start of the line.
576 if (!Previous || Previous->isNot(tok::kw_return) || *I > 0)
577 NewParenState.Indent =
578 std::max(std::max(State.Column, NewParenState.Indent),
579 State.Stack.back().LastSpace);
580
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000581 // Do not indent relative to the fake parentheses inserted for "." or "->".
582 // This is a special case to make the following to statements consistent:
583 // OuterFunction(InnerFunctionCall( // break
584 // ParameterToInnerFunction));
585 // OuterFunction(SomeObject.InnerFunctionCall( // break
586 // ParameterToInnerFunction));
587 if (*I > prec::Unknown)
588 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
Daniel Jasper96964352013-12-18 10:44:36 +0000589 NewParenState.StartOfFunctionCall = State.Column;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000590
591 // Always indent conditional expressions. Never indent expression where
592 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
593 // prec::Assignment) as those have different indentation rules. Indent
594 // other expression, unless the indentation needs to be skipped.
595 if (*I == prec::Conditional ||
596 (!SkipFirstExtraIndent && *I > prec::Assignment &&
597 !Style.BreakBeforeBinaryOperators))
Daniel Jasper6633ab82013-10-18 10:38:14 +0000598 NewParenState.Indent += Style.ContinuationIndentWidth;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000599 if ((Previous && !Previous->opensScope()) || *I > prec::Comma)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000600 NewParenState.BreakBeforeParameter = false;
601 State.Stack.push_back(NewParenState);
602 SkipFirstExtraIndent = false;
603 }
604
605 // If we encounter an opening (, [, { or <, we add a level to our stacks to
606 // prepare for the following tokens.
607 if (Current.opensScope()) {
608 unsigned NewIndent;
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000609 unsigned NewIndentLevel = State.Stack.back().IndentLevel;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000610 bool AvoidBinPacking;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000611 bool BreakBeforeParameter = false;
612 if (Current.is(tok::l_brace) ||
613 Current.Type == TT_ArrayInitializerLSquare) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000614 if (Current.MatchingParen && Current.BlockKind == BK_Block) {
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000615 // If this is an l_brace starting a nested block, we pretend (wrt. to
616 // indentation) that we already consumed the corresponding r_brace.
Daniel Jasper96964352013-12-18 10:44:36 +0000617 // Thus, we remove all ParenStates caused by fake parentheses that end
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000618 // at the r_brace. The net effect of this is that we don't indent
619 // relative to the l_brace, if the nested block is the last parameter of
620 // a function. For example, this formats:
621 //
622 // SomeFunction(a, [] {
623 // f(); // break
624 // });
625 //
626 // instead of:
627 // SomeFunction(a, [] {
Daniel Jasper5500f612013-11-25 11:08:59 +0000628 // f(); // break
629 // });
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000630 for (unsigned i = 0; i != Current.MatchingParen->FakeRParens; ++i)
631 State.Stack.pop_back();
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000632 bool IsObjCBlock =
633 Previous &&
634 (Previous->is(tok::caret) ||
635 (Previous->is(tok::r_paren) && Previous->MatchingParen &&
636 Previous->MatchingParen->Previous &&
637 Previous->MatchingParen->Previous->is(tok::caret)));
638 // For some reason, ObjC blocks are indented like continuations.
639 NewIndent =
640 State.Stack.back().LastSpace +
641 (IsObjCBlock ? Style.ContinuationIndentWidth : Style.IndentWidth);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000642 ++NewIndentLevel;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000643 BreakBeforeParameter = true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000644 } else {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000645 NewIndent = State.Stack.back().LastSpace;
Daniel Jasperb8f61682013-10-22 15:45:58 +0000646 if (Current.opensBlockTypeList(Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000647 NewIndent += Style.IndentWidth;
Daniel Jasper5a611392013-12-19 21:41:37 +0000648 NewIndent = std::min(State.Column + 2, NewIndent);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000649 ++NewIndentLevel;
Daniel Jasperb8f61682013-10-22 15:45:58 +0000650 } else {
651 NewIndent += Style.ContinuationIndentWidth;
Daniel Jasper5a611392013-12-19 21:41:37 +0000652 NewIndent = std::min(State.Column + 1, NewIndent);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000653 }
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000654 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000655 const FormatToken *NextNoComment = Current.getNextNonComment();
Daniel Jasper015ed022013-09-13 09:20:45 +0000656 AvoidBinPacking = Current.BlockKind == BK_Block ||
Daniel Jasper1db6c382013-10-22 15:30:28 +0000657 Current.Type == TT_ArrayInitializerLSquare ||
Daniel Jasperb596fb22013-10-24 10:31:50 +0000658 Current.Type == TT_DictLiteral ||
Daniel Jasper015ed022013-09-13 09:20:45 +0000659 (NextNoComment &&
660 NextNoComment->Type == TT_DesignatedInitializerPeriod);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000661 } else {
Daniel Jasper6633ab82013-10-18 10:38:14 +0000662 NewIndent = Style.ContinuationIndentWidth +
663 std::max(State.Stack.back().LastSpace,
664 State.Stack.back().StartOfFunctionCall);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000665 AvoidBinPacking = !Style.BinPackParameters ||
666 (Style.ExperimentalAutoDetectBinPacking &&
667 (Current.PackingKind == PPK_OnePerLine ||
668 (!BinPackInconclusiveFunctions &&
669 Current.PackingKind == PPK_Inconclusive)));
Daniel Jasper1db6c382013-10-22 15:30:28 +0000670 // If this '[' opens an ObjC call, determine whether all parameters fit
671 // into one line and put one per line if they don't.
672 if (Current.Type == TT_ObjCMethodExpr &&
673 getLengthToMatchingParen(Current) + State.Column >
674 getColumnLimit(State))
675 BreakBeforeParameter = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000676 }
677
Daniel Jaspercc3114d2013-10-18 15:23:06 +0000678 bool NoLineBreak = State.Stack.back().NoLineBreak ||
679 (Current.Type == TT_TemplateOpener &&
680 State.Stack.back().ContainsUnwrappedBuilder);
681 State.Stack.push_back(ParenState(NewIndent, NewIndentLevel,
682 State.Stack.back().LastSpace,
683 AvoidBinPacking, NoLineBreak));
Daniel Jasper1db6c382013-10-22 15:30:28 +0000684 State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000685 ++State.ParenLevel;
686 }
687
Daniel Jasperde0328a2013-08-16 11:20:30 +0000688 // If we encounter a closing ), ], } or >, we can remove a level from our
689 // stacks.
Daniel Jasper96df37a2013-08-28 09:17:37 +0000690 if (State.Stack.size() > 1 &&
691 (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000692 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
Daniel Jasper96df37a2013-08-28 09:17:37 +0000693 State.NextToken->Type == TT_TemplateCloser)) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000694 State.Stack.pop_back();
695 --State.ParenLevel;
696 }
697 if (Current.is(tok::r_square)) {
698 // If this ends the array subscript expr, reset the corresponding value.
699 const FormatToken *NextNonComment = Current.getNextNonComment();
700 if (NextNonComment && NextNonComment->isNot(tok::l_square))
701 State.Stack.back().StartOfArraySubscripts = 0;
702 }
703
704 // Remove scopes created by fake parenthesis.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000705 if (Current.isNot(tok::r_brace) ||
706 (Current.MatchingParen && Current.MatchingParen->BlockKind != BK_Block)) {
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000707 // Don't remove FakeRParens attached to r_braces that surround nested blocks
708 // as they will have been removed early (see above).
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000709 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
710 unsigned VariablePos = State.Stack.back().VariablePos;
711 State.Stack.pop_back();
712 State.Stack.back().VariablePos = VariablePos;
713 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000714 }
715
Daniel Jasper04b6a082013-12-20 06:22:01 +0000716 if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000717 State.StartOfStringLiteral = State.Column;
Daniel Jasper04b6a082013-12-20 06:22:01 +0000718 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
719 !Current.isStringLiteral()) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000720 State.StartOfStringLiteral = 0;
721 }
722
Alexander Kornienko39856b72013-09-10 09:38:25 +0000723 State.Column += Current.ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000724 State.NextToken = State.NextToken->Next;
Daniel Jasperb27c4b72013-08-27 11:09:05 +0000725 unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000726 if (State.Column > getColumnLimit(State)) {
727 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
728 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
729 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000730
Daniel Jasper01603472014-01-09 13:42:56 +0000731 if (Current.Role)
732 Current.Role->formatFromToken(State, this, DryRun);
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000733 // If the previous has a special role, let it consume tokens as appropriate.
734 // It is necessary to start at the previous token for the only implemented
735 // role (comma separated list). That way, the decision whether or not to break
736 // after the "{" is already done and both options are tried and evaluated.
737 // FIXME: This is ugly, find a better way.
738 if (Previous && Previous->Role)
Daniel Jasper01603472014-01-09 13:42:56 +0000739 Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000740
741 return Penalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000742}
743
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000744unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
745 LineState &State) {
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000746 // Break before further function parameters on all levels.
747 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
748 State.Stack[i].BreakBeforeParameter = true;
749
Alexander Kornienko39856b72013-09-10 09:38:25 +0000750 unsigned ColumnsUsed = State.Column;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000751 // We can only affect layout of the first and the last line, so the penalty
752 // for all other lines is constant, and we ignore it.
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000753 State.Column = Current.LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000754
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000755 if (ColumnsUsed > getColumnLimit(State))
756 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000757 return 0;
758}
759
Alexander Kornienko81e32942013-09-16 20:20:49 +0000760static bool getRawStringLiteralPrefixPostfix(StringRef Text,
761 StringRef &Prefix,
762 StringRef &Postfix) {
763 if (Text.startswith(Prefix = "R\"") || Text.startswith(Prefix = "uR\"") ||
764 Text.startswith(Prefix = "UR\"") || Text.startswith(Prefix = "u8R\"") ||
765 Text.startswith(Prefix = "LR\"")) {
766 size_t ParenPos = Text.find('(');
767 if (ParenPos != StringRef::npos) {
768 StringRef Delimiter =
769 Text.substr(Prefix.size(), ParenPos - Prefix.size());
770 Prefix = Text.substr(0, ParenPos + 1);
771 Postfix = Text.substr(Text.size() - 2 - Delimiter.size());
772 return Postfix.front() == ')' && Postfix.back() == '"' &&
773 Postfix.substr(1).startswith(Delimiter);
774 }
775 }
776 return false;
777}
778
Daniel Jasperde0328a2013-08-16 11:20:30 +0000779unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
780 LineState &State,
781 bool DryRun) {
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000782 // Don't break multi-line tokens other than block comments. Instead, just
783 // update the state.
784 if (Current.Type != TT_BlockComment && Current.IsMultiline)
785 return addMultilineToken(Current, State);
786
Daniel Jasper98857842013-10-30 13:54:53 +0000787 // Don't break implicit string literals.
788 if (Current.Type == TT_ImplicitStringLiteral)
789 return 0;
790
Daniel Jasper04b6a082013-12-20 06:22:01 +0000791 if (!Current.isStringLiteral() && !Current.is(tok::comment))
Daniel Jasperf93551c2013-08-23 10:05:49 +0000792 return 0;
793
Daniel Jasperde0328a2013-08-16 11:20:30 +0000794 llvm::OwningPtr<BreakableToken> Token;
Alexander Kornienko39856b72013-09-10 09:38:25 +0000795 unsigned StartColumn = State.Column - Current.ColumnWidth;
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000796 unsigned ColumnLimit = getColumnLimit(State);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000797
Daniel Jasper04b6a082013-12-20 06:22:01 +0000798 if (Current.isStringLiteral()) {
Alexander Kornienko384b40b2013-10-11 21:43:05 +0000799 // Don't break string literals inside preprocessor directives (except for
800 // #define directives, as their contents are stored in separate lines and
801 // are not affected by this check).
802 // This way we avoid breaking code with line directives and unknown
803 // preprocessor directives that contain long string literals.
804 if (State.Line->Type == LT_PreprocessorDirective)
805 return 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000806 // Exempts unterminated string literals from line breaking. The user will
807 // likely want to terminate the string before any line breaking is done.
808 if (Current.IsUnterminatedLiteral)
809 return 0;
810
Alexander Kornienko81e32942013-09-16 20:20:49 +0000811 StringRef Text = Current.TokenText;
812 StringRef Prefix;
813 StringRef Postfix;
Daniel Jasper174b0122014-01-09 14:18:12 +0000814 bool IsNSStringLiteral = false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000815 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
816 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
817 // reduce the overhead) for each FormatToken, which is a string, so that we
818 // don't run multiple checks here on the hot path.
Daniel Jasper174b0122014-01-09 14:18:12 +0000819 if (Text.startswith("\"") && Current.Previous &&
820 Current.Previous->is(tok::at)) {
821 IsNSStringLiteral = true;
822 Prefix = "@\"";
Daniel Jasper174b0122014-01-09 14:18:12 +0000823 }
Alexander Kornienko81e32942013-09-16 20:20:49 +0000824 if ((Text.endswith(Postfix = "\"") &&
Daniel Jasper174b0122014-01-09 14:18:12 +0000825 (IsNSStringLiteral || Text.startswith(Prefix = "\"") ||
826 Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
827 Text.startswith(Prefix = "u8\"") ||
Alexander Kornienko81e32942013-09-16 20:20:49 +0000828 Text.startswith(Prefix = "L\""))) ||
829 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")")) ||
830 getRawStringLiteralPrefixPostfix(Text, Prefix, Postfix)) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000831 Token.reset(new BreakableStringLiteral(
832 Current, State.Line->Level, StartColumn, Prefix, Postfix,
833 State.Line->InPPDirective, Encoding, Style));
Alexander Kornienko81e32942013-09-16 20:20:49 +0000834 } else {
835 return 0;
836 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000837 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000838 if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
839 return 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000840 Token.reset(new BreakableBlockComment(
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000841 Current, State.Line->Level, StartColumn, Current.OriginalColumn,
842 !Current.Previous, State.Line->InPPDirective, Encoding, Style));
Daniel Jasperde0328a2013-08-16 11:20:30 +0000843 } else if (Current.Type == TT_LineComment &&
844 (Current.Previous == NULL ||
845 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000846 if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
847 return 0;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000848 Token.reset(new BreakableLineComment(Current, State.Line->Level,
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000849 StartColumn, /*InPPDirective=*/false,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000850 Encoding, Style));
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000851 // We don't insert backslashes when breaking line comments.
852 ColumnLimit = Style.ColumnLimit;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000853 } else {
854 return 0;
855 }
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000856 if (Current.UnbreakableTailLength >= ColumnLimit)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000857 return 0;
858
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000859 unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000860 bool BreakInserted = false;
861 unsigned Penalty = 0;
862 unsigned RemainingTokenColumns = 0;
863 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
864 LineIndex != EndIndex; ++LineIndex) {
865 if (!DryRun)
866 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
867 unsigned TailOffset = 0;
868 RemainingTokenColumns =
869 Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
870 while (RemainingTokenColumns > RemainingSpace) {
871 BreakableToken::Split Split =
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000872 Token->getSplit(LineIndex, TailOffset, ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000873 if (Split.first == StringRef::npos) {
874 // The last line's penalty is handled in addNextStateToQueue().
875 if (LineIndex < EndIndex - 1)
876 Penalty += Style.PenaltyExcessCharacter *
877 (RemainingTokenColumns - RemainingSpace);
878 break;
879 }
880 assert(Split.first != 0);
881 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
882 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
Alexander Kornienko875395f2013-11-12 17:50:13 +0000883
884 // We can remove extra whitespace instead of breaking the line.
885 if (RemainingTokenColumns + 1 - Split.second <= RemainingSpace) {
886 RemainingTokenColumns = 0;
887 if (!DryRun)
888 Token->replaceWhitespace(LineIndex, TailOffset, Split, Whitespaces);
889 break;
890 }
891
Daniel Jasperde0328a2013-08-16 11:20:30 +0000892 assert(NewRemainingTokenColumns < RemainingTokenColumns);
893 if (!DryRun)
894 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Daniel Jasper2739af32013-08-28 10:03:58 +0000895 Penalty += Current.SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000896 unsigned ColumnsUsed =
897 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000898 if (ColumnsUsed > ColumnLimit) {
899 Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000900 }
901 TailOffset += Split.first + Split.second;
902 RemainingTokenColumns = NewRemainingTokenColumns;
903 BreakInserted = true;
904 }
905 }
906
907 State.Column = RemainingTokenColumns;
908
909 if (BreakInserted) {
910 // If we break the token inside a parameter list, we need to break before
911 // the next parameter on all levels, so that the next parameter is clearly
912 // visible. Line comments already introduce a break.
913 if (Current.Type != TT_LineComment) {
914 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
915 State.Stack[i].BreakBeforeParameter = true;
916 }
917
Daniel Jasper04b6a082013-12-20 06:22:01 +0000918 Penalty += Current.isStringLiteral() ? Style.PenaltyBreakString
919 : Style.PenaltyBreakComment;
Daniel Jasper2739af32013-08-28 10:03:58 +0000920
Daniel Jasperde0328a2013-08-16 11:20:30 +0000921 State.Stack.back().LastSpace = StartColumn;
922 }
923 return Penalty;
924}
925
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000926unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000927 // In preprocessor directives reserve two chars for trailing " \"
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000928 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000929}
930
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000931bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
Daniel Jasperf438cb72013-08-23 11:57:34 +0000932 const FormatToken &Current = *State.NextToken;
Daniel Jasper04b6a082013-12-20 06:22:01 +0000933 if (!Current.isStringLiteral())
Daniel Jasperf438cb72013-08-23 11:57:34 +0000934 return false;
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000935 // We never consider raw string literals "multiline" for the purpose of
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000936 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
937 // (see TokenAnnotator::mustBreakBefore().
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000938 if (Current.TokenText.startswith("R\""))
939 return false;
Alexander Kornienko39856b72013-09-10 09:38:25 +0000940 if (Current.IsMultiline)
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000941 return true;
Daniel Jasperf438cb72013-08-23 11:57:34 +0000942 if (Current.getNextNonComment() &&
Daniel Jasper04b6a082013-12-20 06:22:01 +0000943 Current.getNextNonComment()->isStringLiteral())
Daniel Jasperf438cb72013-08-23 11:57:34 +0000944 return true; // Implicit concatenation.
Alexander Kornienko39856b72013-09-10 09:38:25 +0000945 if (State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
Daniel Jasperf438cb72013-08-23 11:57:34 +0000946 Style.ColumnLimit)
947 return true; // String will be split.
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000948 return false;
Daniel Jasperf438cb72013-08-23 11:57:34 +0000949}
950
Daniel Jasperde0328a2013-08-16 11:20:30 +0000951} // namespace format
952} // namespace clang