blob: cb4e4f53b2f3c0994aa03a774801b5b62d430d7a [file] [log] [blame]
Daniel Jasperde0328a2013-08-16 11:20:30 +00001//===--- ContinuationIndenter.cpp - Format C++ code -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements the continuation indenter.
12///
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "format-formatter"
16
17#include "BreakableToken.h"
18#include "ContinuationIndenter.h"
19#include "WhitespaceManager.h"
20#include "clang/Basic/OperatorPrecedence.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Format/Format.h"
23#include "llvm/Support/Debug.h"
24#include <string>
25
26namespace clang {
27namespace format {
28
29// Returns the length of everything up to the first possible line break after
30// the ), ], } or > matching \c Tok.
31static unsigned getLengthToMatchingParen(const FormatToken &Tok) {
32 if (Tok.MatchingParen == NULL)
33 return 0;
34 FormatToken *End = Tok.MatchingParen;
35 while (End->Next && !End->Next->CanBreakBefore) {
36 End = End->Next;
37 }
38 return End->TotalLength - Tok.TotalLength + 1;
39}
40
Daniel Jasper4c6e0052013-08-27 14:24:43 +000041// Returns \c true if \c Tok is the "." or "->" of a call and starts the next
42// segment of a builder type call.
43static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) {
44 return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope();
45}
46
Daniel Jasperec01cd62013-10-08 05:11:18 +000047// Returns \c true if \c Current starts a new parameter.
48static bool startsNextParameter(const FormatToken &Current,
49 const FormatStyle &Style) {
50 const FormatToken &Previous = *Current.Previous;
51 if (Current.Type == TT_CtorInitializerComma &&
52 Style.BreakConstructorInitializersBeforeComma)
53 return true;
54 return Previous.is(tok::comma) && !Current.isTrailingComment() &&
55 (Previous.Type != TT_CtorInitializerComma ||
56 !Style.BreakConstructorInitializersBeforeComma);
57}
58
Daniel Jasperde0328a2013-08-16 11:20:30 +000059ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,
60 SourceManager &SourceMgr,
Daniel Jasperde0328a2013-08-16 11:20:30 +000061 WhitespaceManager &Whitespaces,
62 encoding::Encoding Encoding,
63 bool BinPackInconclusiveFunctions)
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000064 : Style(Style), SourceMgr(SourceMgr), Whitespaces(Whitespaces),
65 Encoding(Encoding),
Alexander Kornienkoce9161a2014-01-02 15:13:14 +000066 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
67 CommentPragmasRegex(Style.CommentPragmas) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +000068
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000069LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
Daniel Jasper1c5d9df2013-09-06 07:54:20 +000070 const AnnotatedLine *Line,
71 bool DryRun) {
Daniel Jasperde0328a2013-08-16 11:20:30 +000072 LineState State;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000073 State.FirstIndent = FirstIndent;
Daniel Jasperde0328a2013-08-16 11:20:30 +000074 State.Column = FirstIndent;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000075 State.Line = Line;
76 State.NextToken = Line->First;
Alexander Kornienkoe2e03872013-10-14 00:46:35 +000077 State.Stack.push_back(ParenState(FirstIndent, Line->Level, FirstIndent,
Daniel Jasperde0328a2013-08-16 11:20:30 +000078 /*AvoidBinPacking=*/false,
79 /*NoLineBreak=*/false));
80 State.LineContainsContinuedForLoopSection = false;
81 State.ParenLevel = 0;
82 State.StartOfStringLiteral = 0;
83 State.StartOfLineLevel = State.ParenLevel;
84 State.LowestLevelOnLine = State.ParenLevel;
85 State.IgnoreStackForComparison = false;
86
87 // The first token has already been indented and thus consumed.
Daniel Jasper1c5d9df2013-09-06 07:54:20 +000088 moveStateToNextToken(State, DryRun, /*Newline=*/false);
Daniel Jasperde0328a2013-08-16 11:20:30 +000089 return State;
90}
91
92bool ContinuationIndenter::canBreak(const LineState &State) {
93 const FormatToken &Current = *State.NextToken;
94 const FormatToken &Previous = *Current.Previous;
95 assert(&Previous == Current.Previous);
Daniel Jasper1db6c382013-10-22 15:30:28 +000096 if (!Current.CanBreakBefore && !(State.Stack.back().BreakBeforeClosingBrace &&
97 Current.closesBlockTypeList(Style)))
Daniel Jasperde0328a2013-08-16 11:20:30 +000098 return false;
99 // The opening "{" of a braced list has to be on the same line as the first
100 // element if it is nested in another braced init list or function call.
101 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
Daniel Jasperb596fb22013-10-24 10:31:50 +0000102 Previous.Type != TT_DictLiteral &&
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000103 Previous.BlockKind == BK_BracedInit && Previous.Previous &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000104 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
105 return false;
106 // This prevents breaks like:
107 // ...
108 // SomeParameter, OtherParameter).DoSomething(
109 // ...
110 // As they hide "DoSomething" and are generally bad for readability.
Daniel Jasper8f59ae52014-03-11 11:03:26 +0000111 if (Previous.opensScope() && Previous.isNot(tok::l_brace) &&
112 State.LowestLevelOnLine < State.StartOfLineLevel)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000113 return false;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000114 if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
115 return false;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000116 return !State.Stack.back().NoLineBreak;
117}
118
119bool ContinuationIndenter::mustBreak(const LineState &State) {
120 const FormatToken &Current = *State.NextToken;
121 const FormatToken &Previous = *Current.Previous;
122 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
123 return true;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000124 if (State.Stack.back().BreakBeforeClosingBrace &&
125 Current.closesBlockTypeList(Style))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000126 return true;
127 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
128 return true;
Daniel Jasperec01cd62013-10-08 05:11:18 +0000129 if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
Daniel Jasper165b29e2013-11-08 00:57:11 +0000130 (Style.BreakBeforeTernaryOperators &&
131 (Current.is(tok::question) || (Current.Type == TT_ConditionalExpr &&
132 Previous.isNot(tok::question)))) ||
133 (!Style.BreakBeforeTernaryOperators &&
134 (Previous.is(tok::question) || Previous.Type == TT_ConditionalExpr))) &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000135 State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
136 !Current.isOneOf(tok::r_paren, tok::r_brace))
137 return true;
138 if (Style.AlwaysBreakBeforeMultilineStrings &&
Daniel Jasperf438cb72013-08-23 11:57:34 +0000139 State.Column > State.Stack.back().Indent && // Breaking saves columns.
Daniel Jasper27943052013-11-09 03:08:25 +0000140 !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) &&
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000141 Previous.Type != TT_InlineASMColon && nextIsMultilineString(State))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000142 return true;
Daniel Jasperb596fb22013-10-24 10:31:50 +0000143 if (((Previous.Type == TT_DictLiteral && Previous.is(tok::l_brace)) ||
Daniel Jasper1db6c382013-10-22 15:30:28 +0000144 Previous.Type == TT_ArrayInitializerLSquare) &&
Daniel Jasperd489dd32013-10-20 16:45:46 +0000145 getLengthToMatchingParen(Previous) + State.Column > getColumnLimit(State))
146 return true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000147
148 if (!Style.BreakBeforeBinaryOperators) {
149 // If we need to break somewhere inside the LHS of a binary expression, we
150 // should also break after the operator. Otherwise, the formatting would
151 // hide the operator precedence, e.g. in:
152 // if (aaaaaaaaaaaaaa ==
153 // bbbbbbbbbbbbbb && c) {..
154 // For comparisons, we only apply this rule, if the LHS is a binary
155 // expression itself as otherwise, the line breaks seem superfluous.
156 // We need special cases for ">>" which we have split into two ">" while
157 // lexing in order to make template parsing easier.
158 //
159 // FIXME: We'll need something similar for styles that break before binary
160 // operators.
161 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
162 Previous.getPrecedence() == prec::Equality) &&
163 Previous.Previous &&
164 Previous.Previous->Type != TT_BinaryOperator; // For >>.
165 bool LHSIsBinaryExpr =
Daniel Jasper562ecd42013-09-06 08:08:14 +0000166 Previous.Previous && Previous.Previous->EndsBinaryExpression;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000167 if (Previous.Type == TT_BinaryOperator &&
168 (!IsComparison || LHSIsBinaryExpr) &&
169 Current.Type != TT_BinaryOperator && // For >>.
170 !Current.isTrailingComment() &&
171 !Previous.isOneOf(tok::lessless, tok::question) &&
172 Previous.getPrecedence() != prec::Assignment &&
173 State.Stack.back().BreakBeforeParameter)
174 return true;
175 }
176
177 // Same as above, but for the first "<<" operator.
Alexander Kornienko86b2dfd2014-03-06 15:13:08 +0000178 if (Current.is(tok::lessless) && Current.Type != TT_OverloadedOperator &&
179 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000180 State.Stack.back().FirstLessLess == 0)
181 return true;
182
Daniel Jasperde0328a2013-08-16 11:20:30 +0000183 if (Current.Type == TT_ObjCSelectorName &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000184 State.Stack.back().ObjCSelectorNameFound &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000185 State.Stack.back().BreakBeforeParameter)
186 return true;
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000187 if (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0 &&
188 !Current.isTrailingComment())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000189 return true;
190
191 if ((Current.Type == TT_StartOfName || Current.is(tok::kw_operator)) &&
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000192 State.Line->MightBeFunctionDecl &&
193 State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000194 return true;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000195 if (startsSegmentOfBuilderTypeCall(Current) &&
Daniel Jasperf8151e92013-08-30 07:12:40 +0000196 (State.Stack.back().CallContinuation != 0 ||
197 (State.Stack.back().BreakBeforeParameter &&
198 State.Stack.back().ContainsUnwrappedBuilder)))
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000199 return true;
Daniel Jasper96972812014-01-05 12:38:10 +0000200
201 // The following could be precomputed as they do not depend on the state.
202 // However, as they should take effect only if the UnwrappedLine does not fit
203 // into the ColumnLimit, they are checked here in the ContinuationIndenter.
204 if (Previous.BlockKind == BK_Block && Previous.is(tok::l_brace) &&
205 !Current.isOneOf(tok::r_brace, tok::comment))
206 return true;
207 if (Current.Type == TT_CtorInitializerColon &&
208 (!Style.AllowShortFunctionsOnASingleLine ||
209 Style.BreakConstructorInitializersBeforeComma || Style.ColumnLimit != 0))
210 return true;
211
Daniel Jasperde0328a2013-08-16 11:20:30 +0000212 return false;
213}
214
215unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000216 bool DryRun,
217 unsigned ExtraSpaces) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000218 const FormatToken &Current = *State.NextToken;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000219
Manuel Klimek819788d2014-03-18 11:22:45 +0000220 assert(!State.Stack.empty());
221 if ((Current.Type == TT_ImplicitStringLiteral &&
Daniel Jasper98857842013-10-30 13:54:53 +0000222 (Current.Previous->Tok.getIdentifierInfo() == NULL ||
223 Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
224 tok::pp_not_keyword))) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000225 // FIXME: Is this correct?
226 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
227 State.NextToken->WhitespaceRange.getEnd()) -
228 SourceMgr.getSpellingColumnNumber(
229 State.NextToken->WhitespaceRange.getBegin());
Daniel Jasperda353cd2014-03-12 08:24:47 +0000230 State.Column += WhitespaceLength;
231 moveStateToNextToken(State, DryRun, /*NewLine=*/false);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000232 return 0;
233 }
234
Alexander Kornienko1f803962013-10-01 14:41:18 +0000235 unsigned Penalty = 0;
236 if (Newline)
237 Penalty = addTokenOnNewLine(State, DryRun);
238 else
Daniel Jasper48437ce2013-11-20 14:54:39 +0000239 addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000240
241 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
242}
243
Daniel Jasper48437ce2013-11-20 14:54:39 +0000244void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
245 unsigned ExtraSpaces) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000246 FormatToken &Current = *State.NextToken;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000247 const FormatToken &Previous = *State.NextToken->Previous;
248 if (Current.is(tok::equal) &&
249 (State.Line->First->is(tok::kw_for) || State.ParenLevel == 0) &&
250 State.Stack.back().VariablePos == 0) {
251 State.Stack.back().VariablePos = State.Column;
252 // Move over * and & if they are bound to the variable name.
253 const FormatToken *Tok = &Previous;
254 while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
255 State.Stack.back().VariablePos -= Tok->ColumnWidth;
256 if (Tok->SpacesRequiredBefore != 0)
257 break;
258 Tok = Tok->Previous;
259 }
260 if (Previous.PartOfMultiVariableDeclStmt)
261 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
262 }
263
264 unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
265
266 if (!DryRun)
267 Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, /*IndentLevel=*/0,
268 Spaces, State.Column + Spaces);
269
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000270 if (Current.Type == TT_ObjCSelectorName &&
271 !State.Stack.back().ObjCSelectorNameFound) {
272 if (Current.LongestObjCSelectorName == 0)
273 State.Stack.back().AlignColons = false;
274 else if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
275 State.Column + Spaces + Current.ColumnWidth)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000276 State.Stack.back().ColonPos =
277 State.Stack.back().Indent + Current.LongestObjCSelectorName;
278 else
279 State.Stack.back().ColonPos = State.Column + Spaces + Current.ColumnWidth;
280 }
281
282 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper5a611392013-12-19 21:41:37 +0000283 (Current.Type != TT_LineComment || Previous.BlockKind == BK_BracedInit))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000284 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasperec01cd62013-10-08 05:11:18 +0000285 if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000286 State.Stack.back().NoLineBreak = true;
287 if (startsSegmentOfBuilderTypeCall(Current))
288 State.Stack.back().ContainsUnwrappedBuilder = true;
289
290 State.Column += Spaces;
291 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
292 // Treat the condition inside an if as if it was a second function
Daniel Jasper6633ab82013-10-18 10:38:14 +0000293 // parameter, i.e. let nested calls have a continuation indent.
Alexander Kornienko1f803962013-10-01 14:41:18 +0000294 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000295 else if (Current.isNot(tok::comment) &&
296 (Previous.is(tok::comma) ||
297 (Previous.is(tok::colon) && Previous.Type == TT_ObjCMethodExpr)))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000298 State.Stack.back().LastSpace = State.Column;
299 else if ((Previous.Type == TT_BinaryOperator ||
300 Previous.Type == TT_ConditionalExpr ||
Alexander Kornienko1f803962013-10-01 14:41:18 +0000301 Previous.Type == TT_CtorInitializerColon) &&
302 (Previous.getPrecedence() != prec::Assignment ||
303 Current.StartsBinaryExpression))
304 // Always indent relative to the RHS of the expression unless this is a
305 // simple assignment without binary expression on the RHS. Also indent
306 // relative to unary operators and the colons of constructor initializers.
307 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf9a5e402013-10-08 16:24:07 +0000308 else if (Previous.Type == TT_InheritanceColon) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000309 State.Stack.back().Indent = State.Column;
Daniel Jasperf9a5e402013-10-08 16:24:07 +0000310 State.Stack.back().LastSpace = State.Column;
311 } else if (Previous.opensScope()) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000312 // If a function has a trailing call, indent all parameters from the
313 // opening parenthesis. This avoids confusing indents like:
314 // OuterFunction(InnerFunctionCall( // break
315 // ParameterToInnerFunction)) // break
316 // .SecondInnerFunctionCall();
317 bool HasTrailingCall = false;
318 if (Previous.MatchingParen) {
319 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
320 HasTrailingCall = Next && Next->isMemberAccess();
321 }
322 if (HasTrailingCall &&
323 State.Stack[State.Stack.size() - 2].CallContinuation == 0)
324 State.Stack.back().LastSpace = State.Column;
325 }
326}
327
328unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
329 bool DryRun) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000330 FormatToken &Current = *State.NextToken;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000331 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasper6633ab82013-10-18 10:38:14 +0000332 // If we are continuing an expression, we want to use the continuation indent.
Daniel Jasperde0328a2013-08-16 11:20:30 +0000333 unsigned ContinuationIndent =
Daniel Jasper6633ab82013-10-18 10:38:14 +0000334 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
335 Style.ContinuationIndentWidth;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000336 // Extra penalty that needs to be added because of the way certain line
337 // breaks are chosen.
338 unsigned Penalty = 0;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000339
Daniel Jaspera0407742014-02-11 10:08:11 +0000340 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
341 const FormatToken *NextNonComment = Previous.getNextNonComment();
342 if (!NextNonComment)
343 NextNonComment = &Current;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000344 // The first line break on any ParenLevel causes an extra penalty in order
345 // prefer similar line breaks.
346 if (!State.Stack.back().ContainsLineBreak)
347 Penalty += 15;
348 State.Stack.back().ContainsLineBreak = true;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000349
Alexander Kornienko1f803962013-10-01 14:41:18 +0000350 Penalty += State.NextToken->SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +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 Jasper1fd6f1f2014-03-17 14:32:47 +0000429 } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
430 (PreviousNonComment->Type == TT_ObjCMethodExpr ||
431 PreviousNonComment->Type == TT_DictLiteral)) {
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000432 State.Column = ContinuationIndent;
433 // FIXME: This is hacky, find a better way. The problem is that in an ObjC
434 // method expression, the block should be aligned to the line starting it,
435 // e.g.:
436 // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
437 // ^(int *i) {
438 // // ...
439 // }];
440 // Thus, we set LastSpace of the next higher ParenLevel, to which we move
441 // when we consume all of the "}"'s FakeRParens at the "{".
Daniel Jasper9a26e772013-12-23 11:25:40 +0000442 if (State.Stack.size() > 1)
443 State.Stack[State.Stack.size() - 2].LastSpace = ContinuationIndent;
Daniel Jaspera0407742014-02-11 10:08:11 +0000444 } else if (NextNonComment->Type == TT_CtorInitializerColon) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000445 State.Column = State.FirstIndent + Style.ConstructorInitializerIndentWidth;
Daniel Jaspera0407742014-02-11 10:08:11 +0000446 } else if (NextNonComment->Type == TT_CtorInitializerComma) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000447 State.Column = State.Stack.back().Indent;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000448 } else {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000449 State.Column = State.Stack.back().Indent;
Daniel Jasper6633ab82013-10-18 10:38:14 +0000450 // Ensure that we fall back to the continuation indent width instead of just
Alexander Kornienko1f803962013-10-01 14:41:18 +0000451 // flushing continuations left.
Daniel Jasper16fc7542013-10-30 14:04:10 +0000452 if (State.Column == State.FirstIndent &&
453 PreviousNonComment->isNot(tok::r_brace))
Daniel Jasper6633ab82013-10-18 10:38:14 +0000454 State.Column += Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000455 }
456
Alexander Kornienko1f803962013-10-01 14:41:18 +0000457 if ((Previous.isOneOf(tok::comma, tok::semi) &&
458 !State.Stack.back().AvoidBinPacking) ||
459 Previous.Type == TT_BinaryOperator)
460 State.Stack.back().BreakBeforeParameter = false;
461 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
462 State.Stack.back().BreakBeforeParameter = false;
Daniel Jaspera0407742014-02-11 10:08:11 +0000463 if (NextNonComment->is(tok::question) ||
Daniel Jasper165b29e2013-11-08 00:57:11 +0000464 (PreviousNonComment && PreviousNonComment->is(tok::question)))
465 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000466
467 if (!DryRun) {
468 unsigned Newlines = 1;
469 if (Current.is(tok::comment))
470 Newlines = std::max(Newlines, std::min(Current.NewlinesBefore,
471 Style.MaxEmptyLinesToKeep + 1));
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000472 Whitespaces.replaceWhitespace(Current, Newlines,
473 State.Stack.back().IndentLevel, State.Column,
474 State.Column, State.Line->InPPDirective);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000475 }
476
477 if (!Current.isTrailingComment())
478 State.Stack.back().LastSpace = State.Column;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000479 State.StartOfLineLevel = State.ParenLevel;
480 State.LowestLevelOnLine = State.ParenLevel;
481
482 // Any break on this level means that the parent level has been broken
483 // and we need to avoid bin packing there.
484 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
485 State.Stack[i].BreakBeforeParameter = true;
486 }
Daniel Jasper9e5ede02013-11-08 19:56:28 +0000487 if (PreviousNonComment &&
488 !PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
489 PreviousNonComment->Type != TT_TemplateCloser &&
490 PreviousNonComment->Type != TT_BinaryOperator &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000491 Current.Type != TT_BinaryOperator &&
Daniel Jasper9e5ede02013-11-08 19:56:28 +0000492 !PreviousNonComment->opensScope())
Alexander Kornienko1f803962013-10-01 14:41:18 +0000493 State.Stack.back().BreakBeforeParameter = true;
494
Daniel Jasper1db6c382013-10-22 15:30:28 +0000495 // If we break after { or the [ of an array initializer, we should also break
496 // before the corresponding } or ].
497 if (Previous.is(tok::l_brace) || Previous.Type == TT_ArrayInitializerLSquare)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000498 State.Stack.back().BreakBeforeClosingBrace = true;
499
500 if (State.Stack.back().AvoidBinPacking) {
501 // If we are breaking after '(', '{', '<', this is not bin packing
502 // unless AllowAllParametersOfDeclarationOnNextLine is false.
503 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
504 Previous.Type == TT_BinaryOperator) ||
505 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
506 State.Line->MustBeDeclaration))
507 State.Stack.back().BreakBeforeParameter = true;
508 }
509
510 return Penalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000511}
512
513unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
514 bool DryRun, bool Newline) {
515 const FormatToken &Current = *State.NextToken;
516 assert(State.Stack.size());
517
518 if (Current.Type == TT_InheritanceColon)
519 State.Stack.back().AvoidBinPacking = true;
Alexander Kornienko86b2dfd2014-03-06 15:13:08 +0000520 if (Current.is(tok::lessless) && Current.Type != TT_OverloadedOperator &&
521 State.Stack.back().FirstLessLess == 0)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000522 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000523 if (Current.Type == TT_ArraySubscriptLSquare &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000524 State.Stack.back().StartOfArraySubscripts == 0)
525 State.Stack.back().StartOfArraySubscripts = State.Column;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000526 if ((Current.is(tok::question) && Style.BreakBeforeTernaryOperators) ||
527 (Current.getPreviousNonComment() && Current.isNot(tok::colon) &&
528 Current.getPreviousNonComment()->is(tok::question) &&
529 !Style.BreakBeforeTernaryOperators))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000530 State.Stack.back().QuestionColumn = State.Column;
531 if (!Current.opensScope() && !Current.closesScope())
532 State.LowestLevelOnLine =
533 std::min(State.LowestLevelOnLine, State.ParenLevel);
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000534 if (Current.isMemberAccess())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000535 State.Stack.back().StartOfFunctionCall =
Alexander Kornienko39856b72013-09-10 09:38:25 +0000536 Current.LastInChainOfCalls ? 0 : State.Column + Current.ColumnWidth;
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000537 if (Current.Type == TT_ObjCSelectorName)
538 State.Stack.back().ObjCSelectorNameFound = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000539 if (Current.Type == TT_CtorInitializerColon) {
540 // Indent 2 from the column, so:
541 // SomeClass::SomeClass()
542 // : First(...), ...
543 // Next(...)
544 // ^ line up here.
545 State.Stack.back().Indent =
546 State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
547 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
548 State.Stack.back().AvoidBinPacking = true;
549 State.Stack.back().BreakBeforeParameter = false;
550 }
551
Daniel Jasperde0328a2013-08-16 11:20:30 +0000552 // In ObjC method declaration we align on the ":" of parameters, but we need
Daniel Jasper6633ab82013-10-18 10:38:14 +0000553 // to ensure that we indent parameters on subsequent lines by at least our
554 // continuation indent width.
Daniel Jasperde0328a2013-08-16 11:20:30 +0000555 if (Current.Type == TT_ObjCMethodSpecifier)
Daniel Jasper6633ab82013-10-18 10:38:14 +0000556 State.Stack.back().Indent += Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000557
558 // Insert scopes created by fake parenthesis.
559 const FormatToken *Previous = Current.getPreviousNonComment();
560 // Don't add extra indentation for the first fake parenthesis after
561 // 'return', assignements or opening <({[. The indentation for these cases
562 // is special cased.
563 bool SkipFirstExtraIndent =
Daniel Jaspereabede62013-09-30 08:29:03 +0000564 (Previous && (Previous->opensScope() || Previous->is(tok::kw_return) ||
Daniel Jasperf48b5ab2013-11-07 19:23:49 +0000565 Previous->getPrecedence() == prec::Assignment ||
566 Previous->Type == TT_ObjCMethodExpr));
Daniel Jasperde0328a2013-08-16 11:20:30 +0000567 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
568 I = Current.FakeLParens.rbegin(),
569 E = Current.FakeLParens.rend();
570 I != E; ++I) {
571 ParenState NewParenState = State.Stack.back();
572 NewParenState.ContainsLineBreak = false;
Daniel Jaspereabede62013-09-30 08:29:03 +0000573
574 // Indent from 'LastSpace' unless this the fake parentheses encapsulating a
575 // builder type call after 'return'. If such a call is line-wrapped, we
576 // commonly just want to indent from the start of the line.
577 if (!Previous || Previous->isNot(tok::kw_return) || *I > 0)
578 NewParenState.Indent =
579 std::max(std::max(State.Column, NewParenState.Indent),
580 State.Stack.back().LastSpace);
581
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000582 // Do not indent relative to the fake parentheses inserted for "." or "->".
583 // This is a special case to make the following to statements consistent:
584 // OuterFunction(InnerFunctionCall( // break
585 // ParameterToInnerFunction));
586 // OuterFunction(SomeObject.InnerFunctionCall( // break
587 // ParameterToInnerFunction));
588 if (*I > prec::Unknown)
589 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
Daniel Jasper96964352013-12-18 10:44:36 +0000590 NewParenState.StartOfFunctionCall = State.Column;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000591
592 // Always indent conditional expressions. Never indent expression where
593 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
594 // prec::Assignment) as those have different indentation rules. Indent
595 // other expression, unless the indentation needs to be skipped.
596 if (*I == prec::Conditional ||
597 (!SkipFirstExtraIndent && *I > prec::Assignment &&
598 !Style.BreakBeforeBinaryOperators))
Daniel Jasper6633ab82013-10-18 10:38:14 +0000599 NewParenState.Indent += Style.ContinuationIndentWidth;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000600 if ((Previous && !Previous->opensScope()) || *I > prec::Comma)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000601 NewParenState.BreakBeforeParameter = false;
602 State.Stack.push_back(NewParenState);
603 SkipFirstExtraIndent = false;
604 }
605
606 // If we encounter an opening (, [, { or <, we add a level to our stacks to
607 // prepare for the following tokens.
608 if (Current.opensScope()) {
609 unsigned NewIndent;
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000610 unsigned NewIndentLevel = State.Stack.back().IndentLevel;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000611 bool AvoidBinPacking;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000612 bool BreakBeforeParameter = false;
613 if (Current.is(tok::l_brace) ||
614 Current.Type == TT_ArrayInitializerLSquare) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000615 if (Current.MatchingParen && Current.BlockKind == BK_Block) {
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000616 // If this is an l_brace starting a nested block, we pretend (wrt. to
617 // indentation) that we already consumed the corresponding r_brace.
Daniel Jasper96964352013-12-18 10:44:36 +0000618 // Thus, we remove all ParenStates caused by fake parentheses that end
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000619 // at the r_brace. The net effect of this is that we don't indent
620 // relative to the l_brace, if the nested block is the last parameter of
621 // a function. For example, this formats:
622 //
623 // SomeFunction(a, [] {
624 // f(); // break
625 // });
626 //
627 // instead of:
628 // SomeFunction(a, [] {
Daniel Jasper5500f612013-11-25 11:08:59 +0000629 // f(); // break
630 // });
Manuel Klimek819788d2014-03-18 11:22:45 +0000631 for (unsigned i = 0; i != Current.MatchingParen->FakeRParens; ++i) {
632 assert(State.Stack.size() > 1);
633 if (State.Stack.size() == 1) {
634 // Do not pop the last element.
635 break;
636 }
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000637 State.Stack.pop_back();
Manuel Klimek819788d2014-03-18 11:22:45 +0000638 }
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000639 bool IsObjCBlock =
640 Previous &&
641 (Previous->is(tok::caret) ||
642 (Previous->is(tok::r_paren) && Previous->MatchingParen &&
643 Previous->MatchingParen->Previous &&
644 Previous->MatchingParen->Previous->is(tok::caret)));
645 // For some reason, ObjC blocks are indented like continuations.
646 NewIndent =
647 State.Stack.back().LastSpace +
648 (IsObjCBlock ? Style.ContinuationIndentWidth : Style.IndentWidth);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000649 ++NewIndentLevel;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000650 BreakBeforeParameter = true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000651 } else {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000652 NewIndent = State.Stack.back().LastSpace;
Daniel Jasperb8f61682013-10-22 15:45:58 +0000653 if (Current.opensBlockTypeList(Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000654 NewIndent += Style.IndentWidth;
Daniel Jasper5a611392013-12-19 21:41:37 +0000655 NewIndent = std::min(State.Column + 2, NewIndent);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000656 ++NewIndentLevel;
Daniel Jasperb8f61682013-10-22 15:45:58 +0000657 } else {
658 NewIndent += Style.ContinuationIndentWidth;
Daniel Jasper5a611392013-12-19 21:41:37 +0000659 NewIndent = std::min(State.Column + 1, NewIndent);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000660 }
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000661 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000662 const FormatToken *NextNoComment = Current.getNextNonComment();
Daniel Jasper015ed022013-09-13 09:20:45 +0000663 AvoidBinPacking = Current.BlockKind == BK_Block ||
Daniel Jasper1db6c382013-10-22 15:30:28 +0000664 Current.Type == TT_ArrayInitializerLSquare ||
Daniel Jasperb596fb22013-10-24 10:31:50 +0000665 Current.Type == TT_DictLiteral ||
Daniel Jasper015ed022013-09-13 09:20:45 +0000666 (NextNoComment &&
667 NextNoComment->Type == TT_DesignatedInitializerPeriod);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000668 } else {
Daniel Jasper6633ab82013-10-18 10:38:14 +0000669 NewIndent = Style.ContinuationIndentWidth +
670 std::max(State.Stack.back().LastSpace,
671 State.Stack.back().StartOfFunctionCall);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000672 AvoidBinPacking = !Style.BinPackParameters ||
673 (Style.ExperimentalAutoDetectBinPacking &&
674 (Current.PackingKind == PPK_OnePerLine ||
675 (!BinPackInconclusiveFunctions &&
676 Current.PackingKind == PPK_Inconclusive)));
Daniel Jasper1db6c382013-10-22 15:30:28 +0000677 // If this '[' opens an ObjC call, determine whether all parameters fit
678 // into one line and put one per line if they don't.
679 if (Current.Type == TT_ObjCMethodExpr &&
680 getLengthToMatchingParen(Current) + State.Column >
681 getColumnLimit(State))
682 BreakBeforeParameter = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000683 }
684
Daniel Jaspercc3114d2013-10-18 15:23:06 +0000685 bool NoLineBreak = State.Stack.back().NoLineBreak ||
686 (Current.Type == TT_TemplateOpener &&
687 State.Stack.back().ContainsUnwrappedBuilder);
688 State.Stack.push_back(ParenState(NewIndent, NewIndentLevel,
689 State.Stack.back().LastSpace,
690 AvoidBinPacking, NoLineBreak));
Daniel Jasper1db6c382013-10-22 15:30:28 +0000691 State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000692 ++State.ParenLevel;
693 }
694
Daniel Jasperde0328a2013-08-16 11:20:30 +0000695 // If we encounter a closing ), ], } or >, we can remove a level from our
696 // stacks.
Daniel Jasper96df37a2013-08-28 09:17:37 +0000697 if (State.Stack.size() > 1 &&
698 (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000699 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
Daniel Jasper96df37a2013-08-28 09:17:37 +0000700 State.NextToken->Type == TT_TemplateCloser)) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000701 State.Stack.pop_back();
702 --State.ParenLevel;
703 }
704 if (Current.is(tok::r_square)) {
705 // If this ends the array subscript expr, reset the corresponding value.
706 const FormatToken *NextNonComment = Current.getNextNonComment();
707 if (NextNonComment && NextNonComment->isNot(tok::l_square))
708 State.Stack.back().StartOfArraySubscripts = 0;
709 }
710
711 // Remove scopes created by fake parenthesis.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000712 if (Current.isNot(tok::r_brace) ||
713 (Current.MatchingParen && Current.MatchingParen->BlockKind != BK_Block)) {
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000714 // Don't remove FakeRParens attached to r_braces that surround nested blocks
715 // as they will have been removed early (see above).
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000716 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
717 unsigned VariablePos = State.Stack.back().VariablePos;
Manuel Klimek819788d2014-03-18 11:22:45 +0000718 assert(State.Stack.size() > 1);
719 if (State.Stack.size() == 1) {
720 // Do not pop the last element.
721 break;
722 }
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000723 State.Stack.pop_back();
724 State.Stack.back().VariablePos = VariablePos;
725 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000726 }
727
Daniel Jasper04b6a082013-12-20 06:22:01 +0000728 if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000729 State.StartOfStringLiteral = State.Column;
Daniel Jasper04b6a082013-12-20 06:22:01 +0000730 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
731 !Current.isStringLiteral()) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000732 State.StartOfStringLiteral = 0;
733 }
734
Alexander Kornienko39856b72013-09-10 09:38:25 +0000735 State.Column += Current.ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000736 State.NextToken = State.NextToken->Next;
Daniel Jasperb27c4b72013-08-27 11:09:05 +0000737 unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000738 if (State.Column > getColumnLimit(State)) {
739 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
740 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
741 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000742
Daniel Jasper01603472014-01-09 13:42:56 +0000743 if (Current.Role)
744 Current.Role->formatFromToken(State, this, DryRun);
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000745 // If the previous has a special role, let it consume tokens as appropriate.
746 // It is necessary to start at the previous token for the only implemented
747 // role (comma separated list). That way, the decision whether or not to break
748 // after the "{" is already done and both options are tried and evaluated.
749 // FIXME: This is ugly, find a better way.
750 if (Previous && Previous->Role)
Daniel Jasper01603472014-01-09 13:42:56 +0000751 Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000752
753 return Penalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000754}
755
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000756unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
757 LineState &State) {
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000758 // Break before further function parameters on all levels.
759 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
760 State.Stack[i].BreakBeforeParameter = true;
761
Alexander Kornienko39856b72013-09-10 09:38:25 +0000762 unsigned ColumnsUsed = State.Column;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000763 // We can only affect layout of the first and the last line, so the penalty
764 // for all other lines is constant, and we ignore it.
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000765 State.Column = Current.LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000766
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000767 if (ColumnsUsed > getColumnLimit(State))
768 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000769 return 0;
770}
771
Alexander Kornienko81e32942013-09-16 20:20:49 +0000772static bool getRawStringLiteralPrefixPostfix(StringRef Text,
773 StringRef &Prefix,
774 StringRef &Postfix) {
775 if (Text.startswith(Prefix = "R\"") || Text.startswith(Prefix = "uR\"") ||
776 Text.startswith(Prefix = "UR\"") || Text.startswith(Prefix = "u8R\"") ||
777 Text.startswith(Prefix = "LR\"")) {
778 size_t ParenPos = Text.find('(');
779 if (ParenPos != StringRef::npos) {
780 StringRef Delimiter =
781 Text.substr(Prefix.size(), ParenPos - Prefix.size());
782 Prefix = Text.substr(0, ParenPos + 1);
783 Postfix = Text.substr(Text.size() - 2 - Delimiter.size());
784 return Postfix.front() == ')' && Postfix.back() == '"' &&
785 Postfix.substr(1).startswith(Delimiter);
786 }
787 }
788 return false;
789}
790
Daniel Jasperde0328a2013-08-16 11:20:30 +0000791unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
792 LineState &State,
793 bool DryRun) {
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000794 // Don't break multi-line tokens other than block comments. Instead, just
795 // update the state.
796 if (Current.Type != TT_BlockComment && Current.IsMultiline)
797 return addMultilineToken(Current, State);
798
Daniel Jasper98857842013-10-30 13:54:53 +0000799 // Don't break implicit string literals.
800 if (Current.Type == TT_ImplicitStringLiteral)
801 return 0;
802
Daniel Jasper04b6a082013-12-20 06:22:01 +0000803 if (!Current.isStringLiteral() && !Current.is(tok::comment))
Daniel Jasperf93551c2013-08-23 10:05:49 +0000804 return 0;
805
Ahmed Charlesb8984322014-03-07 20:03:18 +0000806 std::unique_ptr<BreakableToken> Token;
Alexander Kornienko39856b72013-09-10 09:38:25 +0000807 unsigned StartColumn = State.Column - Current.ColumnWidth;
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000808 unsigned ColumnLimit = getColumnLimit(State);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000809
Daniel Jasper04b6a082013-12-20 06:22:01 +0000810 if (Current.isStringLiteral()) {
Alexander Kornienko384b40b2013-10-11 21:43:05 +0000811 // Don't break string literals inside preprocessor directives (except for
812 // #define directives, as their contents are stored in separate lines and
813 // are not affected by this check).
814 // This way we avoid breaking code with line directives and unknown
815 // preprocessor directives that contain long string literals.
816 if (State.Line->Type == LT_PreprocessorDirective)
817 return 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000818 // Exempts unterminated string literals from line breaking. The user will
819 // likely want to terminate the string before any line breaking is done.
820 if (Current.IsUnterminatedLiteral)
821 return 0;
822
Alexander Kornienko81e32942013-09-16 20:20:49 +0000823 StringRef Text = Current.TokenText;
824 StringRef Prefix;
825 StringRef Postfix;
Daniel Jasper174b0122014-01-09 14:18:12 +0000826 bool IsNSStringLiteral = false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000827 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
828 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
829 // reduce the overhead) for each FormatToken, which is a string, so that we
830 // don't run multiple checks here on the hot path.
Daniel Jasper174b0122014-01-09 14:18:12 +0000831 if (Text.startswith("\"") && Current.Previous &&
832 Current.Previous->is(tok::at)) {
833 IsNSStringLiteral = true;
834 Prefix = "@\"";
Daniel Jasper174b0122014-01-09 14:18:12 +0000835 }
Alexander Kornienko81e32942013-09-16 20:20:49 +0000836 if ((Text.endswith(Postfix = "\"") &&
Daniel Jasper174b0122014-01-09 14:18:12 +0000837 (IsNSStringLiteral || Text.startswith(Prefix = "\"") ||
838 Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
839 Text.startswith(Prefix = "u8\"") ||
Alexander Kornienko81e32942013-09-16 20:20:49 +0000840 Text.startswith(Prefix = "L\""))) ||
841 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")")) ||
842 getRawStringLiteralPrefixPostfix(Text, Prefix, Postfix)) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000843 Token.reset(new BreakableStringLiteral(
844 Current, State.Line->Level, StartColumn, Prefix, Postfix,
845 State.Line->InPPDirective, Encoding, Style));
Alexander Kornienko81e32942013-09-16 20:20:49 +0000846 } else {
847 return 0;
848 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000849 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000850 if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
851 return 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000852 Token.reset(new BreakableBlockComment(
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000853 Current, State.Line->Level, StartColumn, Current.OriginalColumn,
854 !Current.Previous, State.Line->InPPDirective, Encoding, Style));
Daniel Jasperde0328a2013-08-16 11:20:30 +0000855 } else if (Current.Type == TT_LineComment &&
856 (Current.Previous == NULL ||
857 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000858 if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
859 return 0;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000860 Token.reset(new BreakableLineComment(Current, State.Line->Level,
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000861 StartColumn, /*InPPDirective=*/false,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000862 Encoding, Style));
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000863 // We don't insert backslashes when breaking line comments.
864 ColumnLimit = Style.ColumnLimit;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000865 } else {
866 return 0;
867 }
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000868 if (Current.UnbreakableTailLength >= ColumnLimit)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000869 return 0;
870
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000871 unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000872 bool BreakInserted = false;
873 unsigned Penalty = 0;
874 unsigned RemainingTokenColumns = 0;
875 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
876 LineIndex != EndIndex; ++LineIndex) {
877 if (!DryRun)
878 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
879 unsigned TailOffset = 0;
880 RemainingTokenColumns =
881 Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
882 while (RemainingTokenColumns > RemainingSpace) {
883 BreakableToken::Split Split =
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000884 Token->getSplit(LineIndex, TailOffset, ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000885 if (Split.first == StringRef::npos) {
886 // The last line's penalty is handled in addNextStateToQueue().
887 if (LineIndex < EndIndex - 1)
888 Penalty += Style.PenaltyExcessCharacter *
889 (RemainingTokenColumns - RemainingSpace);
890 break;
891 }
892 assert(Split.first != 0);
893 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
894 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
Alexander Kornienko875395f2013-11-12 17:50:13 +0000895
896 // We can remove extra whitespace instead of breaking the line.
897 if (RemainingTokenColumns + 1 - Split.second <= RemainingSpace) {
898 RemainingTokenColumns = 0;
899 if (!DryRun)
900 Token->replaceWhitespace(LineIndex, TailOffset, Split, Whitespaces);
901 break;
902 }
903
Daniel Jasperde0328a2013-08-16 11:20:30 +0000904 assert(NewRemainingTokenColumns < RemainingTokenColumns);
905 if (!DryRun)
906 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Daniel Jasper2739af32013-08-28 10:03:58 +0000907 Penalty += Current.SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000908 unsigned ColumnsUsed =
909 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000910 if (ColumnsUsed > ColumnLimit) {
911 Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000912 }
913 TailOffset += Split.first + Split.second;
914 RemainingTokenColumns = NewRemainingTokenColumns;
915 BreakInserted = true;
916 }
917 }
918
919 State.Column = RemainingTokenColumns;
920
921 if (BreakInserted) {
922 // If we break the token inside a parameter list, we need to break before
923 // the next parameter on all levels, so that the next parameter is clearly
924 // visible. Line comments already introduce a break.
925 if (Current.Type != TT_LineComment) {
926 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
927 State.Stack[i].BreakBeforeParameter = true;
928 }
929
Daniel Jasper04b6a082013-12-20 06:22:01 +0000930 Penalty += Current.isStringLiteral() ? Style.PenaltyBreakString
931 : Style.PenaltyBreakComment;
Daniel Jasper2739af32013-08-28 10:03:58 +0000932
Daniel Jasperde0328a2013-08-16 11:20:30 +0000933 State.Stack.back().LastSpace = StartColumn;
934 }
935 return Penalty;
936}
937
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000938unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000939 // In preprocessor directives reserve two chars for trailing " \"
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000940 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000941}
942
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000943bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
Daniel Jasperf438cb72013-08-23 11:57:34 +0000944 const FormatToken &Current = *State.NextToken;
Daniel Jasper04b6a082013-12-20 06:22:01 +0000945 if (!Current.isStringLiteral())
Daniel Jasperf438cb72013-08-23 11:57:34 +0000946 return false;
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000947 // We never consider raw string literals "multiline" for the purpose of
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000948 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
949 // (see TokenAnnotator::mustBreakBefore().
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000950 if (Current.TokenText.startswith("R\""))
951 return false;
Alexander Kornienko39856b72013-09-10 09:38:25 +0000952 if (Current.IsMultiline)
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000953 return true;
Daniel Jasperf438cb72013-08-23 11:57:34 +0000954 if (Current.getNextNonComment() &&
Daniel Jasper04b6a082013-12-20 06:22:01 +0000955 Current.getNextNonComment()->isStringLiteral())
Daniel Jasperf438cb72013-08-23 11:57:34 +0000956 return true; // Implicit concatenation.
Alexander Kornienko39856b72013-09-10 09:38:25 +0000957 if (State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
Daniel Jasperf438cb72013-08-23 11:57:34 +0000958 Style.ColumnLimit)
959 return true; // String will be split.
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000960 return false;
Daniel Jasperf438cb72013-08-23 11:57:34 +0000961}
962
Daniel Jasperde0328a2013-08-16 11:20:30 +0000963} // namespace format
964} // namespace clang