blob: 7b3f5cb67fe44763c0f3e50ce388ebb30d53edfc [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),
Daniel Jasperde0328a2013-08-16 11:20:30 +000066 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions) {}
67
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000068LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
Daniel Jasper1c5d9df2013-09-06 07:54:20 +000069 const AnnotatedLine *Line,
70 bool DryRun) {
Daniel Jasperde0328a2013-08-16 11:20:30 +000071 LineState State;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000072 State.FirstIndent = FirstIndent;
Daniel Jasperde0328a2013-08-16 11:20:30 +000073 State.Column = FirstIndent;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000074 State.Line = Line;
75 State.NextToken = Line->First;
Alexander Kornienkoe2e03872013-10-14 00:46:35 +000076 State.Stack.push_back(ParenState(FirstIndent, Line->Level, FirstIndent,
Daniel Jasperde0328a2013-08-16 11:20:30 +000077 /*AvoidBinPacking=*/false,
78 /*NoLineBreak=*/false));
79 State.LineContainsContinuedForLoopSection = false;
80 State.ParenLevel = 0;
81 State.StartOfStringLiteral = 0;
82 State.StartOfLineLevel = State.ParenLevel;
83 State.LowestLevelOnLine = State.ParenLevel;
84 State.IgnoreStackForComparison = false;
85
86 // The first token has already been indented and thus consumed.
Daniel Jasper1c5d9df2013-09-06 07:54:20 +000087 moveStateToNextToken(State, DryRun, /*Newline=*/false);
Daniel Jasperde0328a2013-08-16 11:20:30 +000088 return State;
89}
90
91bool ContinuationIndenter::canBreak(const LineState &State) {
92 const FormatToken &Current = *State.NextToken;
93 const FormatToken &Previous = *Current.Previous;
94 assert(&Previous == Current.Previous);
Daniel Jasper1db6c382013-10-22 15:30:28 +000095 if (!Current.CanBreakBefore && !(State.Stack.back().BreakBeforeClosingBrace &&
96 Current.closesBlockTypeList(Style)))
Daniel Jasperde0328a2013-08-16 11:20:30 +000097 return false;
98 // The opening "{" of a braced list has to be on the same line as the first
99 // element if it is nested in another braced init list or function call.
100 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
Daniel Jasperb596fb22013-10-24 10:31:50 +0000101 Previous.Type != TT_DictLiteral &&
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000102 Previous.BlockKind == BK_BracedInit && Previous.Previous &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000103 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
104 return false;
105 // This prevents breaks like:
106 // ...
107 // SomeParameter, OtherParameter).DoSomething(
108 // ...
109 // As they hide "DoSomething" and are generally bad for readability.
110 if (Previous.opensScope() && State.LowestLevelOnLine < State.StartOfLineLevel)
111 return false;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000112 if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
113 return false;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000114 return !State.Stack.back().NoLineBreak;
115}
116
117bool ContinuationIndenter::mustBreak(const LineState &State) {
118 const FormatToken &Current = *State.NextToken;
119 const FormatToken &Previous = *Current.Previous;
120 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
121 return true;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000122 if (State.Stack.back().BreakBeforeClosingBrace &&
123 Current.closesBlockTypeList(Style))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000124 return true;
125 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
126 return true;
Daniel Jasperec01cd62013-10-08 05:11:18 +0000127 if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
Daniel Jasper165b29e2013-11-08 00:57:11 +0000128 (Style.BreakBeforeTernaryOperators &&
129 (Current.is(tok::question) || (Current.Type == TT_ConditionalExpr &&
130 Previous.isNot(tok::question)))) ||
131 (!Style.BreakBeforeTernaryOperators &&
132 (Previous.is(tok::question) || Previous.Type == TT_ConditionalExpr))) &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000133 State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
134 !Current.isOneOf(tok::r_paren, tok::r_brace))
135 return true;
136 if (Style.AlwaysBreakBeforeMultilineStrings &&
Daniel Jasperf438cb72013-08-23 11:57:34 +0000137 State.Column > State.Stack.back().Indent && // Breaking saves columns.
Daniel Jasper27943052013-11-09 03:08:25 +0000138 !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) &&
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000139 Previous.Type != TT_InlineASMColon && nextIsMultilineString(State))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000140 return true;
Daniel Jasperb596fb22013-10-24 10:31:50 +0000141 if (((Previous.Type == TT_DictLiteral && Previous.is(tok::l_brace)) ||
Daniel Jasper1db6c382013-10-22 15:30:28 +0000142 Previous.Type == TT_ArrayInitializerLSquare) &&
Daniel Jasperd489dd32013-10-20 16:45:46 +0000143 getLengthToMatchingParen(Previous) + State.Column > getColumnLimit(State))
144 return true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000145
146 if (!Style.BreakBeforeBinaryOperators) {
147 // If we need to break somewhere inside the LHS of a binary expression, we
148 // should also break after the operator. Otherwise, the formatting would
149 // hide the operator precedence, e.g. in:
150 // if (aaaaaaaaaaaaaa ==
151 // bbbbbbbbbbbbbb && c) {..
152 // For comparisons, we only apply this rule, if the LHS is a binary
153 // expression itself as otherwise, the line breaks seem superfluous.
154 // We need special cases for ">>" which we have split into two ">" while
155 // lexing in order to make template parsing easier.
156 //
157 // FIXME: We'll need something similar for styles that break before binary
158 // operators.
159 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
160 Previous.getPrecedence() == prec::Equality) &&
161 Previous.Previous &&
162 Previous.Previous->Type != TT_BinaryOperator; // For >>.
163 bool LHSIsBinaryExpr =
Daniel Jasper562ecd42013-09-06 08:08:14 +0000164 Previous.Previous && Previous.Previous->EndsBinaryExpression;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000165 if (Previous.Type == TT_BinaryOperator &&
166 (!IsComparison || LHSIsBinaryExpr) &&
167 Current.Type != TT_BinaryOperator && // For >>.
168 !Current.isTrailingComment() &&
169 !Previous.isOneOf(tok::lessless, tok::question) &&
170 Previous.getPrecedence() != prec::Assignment &&
171 State.Stack.back().BreakBeforeParameter)
172 return true;
173 }
174
175 // Same as above, but for the first "<<" operator.
176 if (Current.is(tok::lessless) && State.Stack.back().BreakBeforeParameter &&
177 State.Stack.back().FirstLessLess == 0)
178 return true;
179
Daniel Jasperde0328a2013-08-16 11:20:30 +0000180 if (Current.Type == TT_ObjCSelectorName &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000181 State.Stack.back().ObjCSelectorNameFound &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000182 State.Stack.back().BreakBeforeParameter)
183 return true;
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000184 if (Current.Type == TT_CtorInitializerColon &&
185 (!Style.AllowShortFunctionsOnASingleLine ||
186 Style.BreakConstructorInitializersBeforeComma || Style.ColumnLimit != 0))
187 return true;
188 if (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0 &&
189 !Current.isTrailingComment())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000190 return true;
191
192 if ((Current.Type == TT_StartOfName || Current.is(tok::kw_operator)) &&
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000193 State.Line->MightBeFunctionDecl &&
194 State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000195 return true;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000196 if (startsSegmentOfBuilderTypeCall(Current) &&
Daniel Jasperf8151e92013-08-30 07:12:40 +0000197 (State.Stack.back().CallContinuation != 0 ||
198 (State.Stack.back().BreakBeforeParameter &&
199 State.Stack.back().ContainsUnwrappedBuilder)))
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000200 return true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000201 return false;
202}
203
204unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000205 bool DryRun,
206 unsigned ExtraSpaces) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000207 const FormatToken &Current = *State.NextToken;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000208
Daniel Jasper98857842013-10-30 13:54:53 +0000209 if (State.Stack.size() == 0 ||
210 (Current.Type == TT_ImplicitStringLiteral &&
211 (Current.Previous->Tok.getIdentifierInfo() == NULL ||
212 Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
213 tok::pp_not_keyword))) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000214 // FIXME: Is this correct?
215 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
216 State.NextToken->WhitespaceRange.getEnd()) -
217 SourceMgr.getSpellingColumnNumber(
218 State.NextToken->WhitespaceRange.getBegin());
Alexander Kornienko39856b72013-09-10 09:38:25 +0000219 State.Column += WhitespaceLength + State.NextToken->ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000220 State.NextToken = State.NextToken->Next;
221 return 0;
222 }
223
Alexander Kornienko1f803962013-10-01 14:41:18 +0000224 unsigned Penalty = 0;
225 if (Newline)
226 Penalty = addTokenOnNewLine(State, DryRun);
227 else
Daniel Jasper48437ce2013-11-20 14:54:39 +0000228 addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000229
230 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
231}
232
Daniel Jasper48437ce2013-11-20 14:54:39 +0000233void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
234 unsigned ExtraSpaces) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000235 FormatToken &Current = *State.NextToken;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000236 const FormatToken &Previous = *State.NextToken->Previous;
237 if (Current.is(tok::equal) &&
238 (State.Line->First->is(tok::kw_for) || State.ParenLevel == 0) &&
239 State.Stack.back().VariablePos == 0) {
240 State.Stack.back().VariablePos = State.Column;
241 // Move over * and & if they are bound to the variable name.
242 const FormatToken *Tok = &Previous;
243 while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
244 State.Stack.back().VariablePos -= Tok->ColumnWidth;
245 if (Tok->SpacesRequiredBefore != 0)
246 break;
247 Tok = Tok->Previous;
248 }
249 if (Previous.PartOfMultiVariableDeclStmt)
250 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
251 }
252
253 unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
254
255 if (!DryRun)
256 Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, /*IndentLevel=*/0,
257 Spaces, State.Column + Spaces);
258
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000259 if (Current.Type == TT_ObjCSelectorName &&
260 !State.Stack.back().ObjCSelectorNameFound) {
261 if (Current.LongestObjCSelectorName == 0)
262 State.Stack.back().AlignColons = false;
263 else if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
264 State.Column + Spaces + Current.ColumnWidth)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000265 State.Stack.back().ColonPos =
266 State.Stack.back().Indent + Current.LongestObjCSelectorName;
267 else
268 State.Stack.back().ColonPos = State.Column + Spaces + Current.ColumnWidth;
269 }
270
271 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper5a611392013-12-19 21:41:37 +0000272 (Current.Type != TT_LineComment || Previous.BlockKind == BK_BracedInit))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000273 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasperec01cd62013-10-08 05:11:18 +0000274 if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000275 State.Stack.back().NoLineBreak = true;
276 if (startsSegmentOfBuilderTypeCall(Current))
277 State.Stack.back().ContainsUnwrappedBuilder = true;
278
279 State.Column += Spaces;
280 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
281 // Treat the condition inside an if as if it was a second function
Daniel Jasper6633ab82013-10-18 10:38:14 +0000282 // parameter, i.e. let nested calls have a continuation indent.
Alexander Kornienko1f803962013-10-01 14:41:18 +0000283 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000284 else if (Current.isNot(tok::comment) &&
285 (Previous.is(tok::comma) ||
286 (Previous.is(tok::colon) && Previous.Type == TT_ObjCMethodExpr)))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000287 State.Stack.back().LastSpace = State.Column;
288 else if ((Previous.Type == TT_BinaryOperator ||
289 Previous.Type == TT_ConditionalExpr ||
290 Previous.Type == TT_UnaryOperator ||
291 Previous.Type == TT_CtorInitializerColon) &&
292 (Previous.getPrecedence() != prec::Assignment ||
293 Current.StartsBinaryExpression))
294 // Always indent relative to the RHS of the expression unless this is a
295 // simple assignment without binary expression on the RHS. Also indent
296 // relative to unary operators and the colons of constructor initializers.
297 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf9a5e402013-10-08 16:24:07 +0000298 else if (Previous.Type == TT_InheritanceColon) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000299 State.Stack.back().Indent = State.Column;
Daniel Jasperf9a5e402013-10-08 16:24:07 +0000300 State.Stack.back().LastSpace = State.Column;
301 } else if (Previous.opensScope()) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000302 // If a function has a trailing call, indent all parameters from the
303 // opening parenthesis. This avoids confusing indents like:
304 // OuterFunction(InnerFunctionCall( // break
305 // ParameterToInnerFunction)) // break
306 // .SecondInnerFunctionCall();
307 bool HasTrailingCall = false;
308 if (Previous.MatchingParen) {
309 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
310 HasTrailingCall = Next && Next->isMemberAccess();
311 }
312 if (HasTrailingCall &&
313 State.Stack[State.Stack.size() - 2].CallContinuation == 0)
314 State.Stack.back().LastSpace = State.Column;
315 }
316}
317
318unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
319 bool DryRun) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000320 FormatToken &Current = *State.NextToken;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000321 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasper6633ab82013-10-18 10:38:14 +0000322 // If we are continuing an expression, we want to use the continuation indent.
Daniel Jasperde0328a2013-08-16 11:20:30 +0000323 unsigned ContinuationIndent =
Daniel Jasper6633ab82013-10-18 10:38:14 +0000324 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
325 Style.ContinuationIndentWidth;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000326 // Extra penalty that needs to be added because of the way certain line
327 // breaks are chosen.
328 unsigned Penalty = 0;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000329
Alexander Kornienko1f803962013-10-01 14:41:18 +0000330 const FormatToken *PreviousNonComment =
331 State.NextToken->getPreviousNonComment();
332 // The first line break on any ParenLevel causes an extra penalty in order
333 // prefer similar line breaks.
334 if (!State.Stack.back().ContainsLineBreak)
335 Penalty += 15;
336 State.Stack.back().ContainsLineBreak = true;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000337
Alexander Kornienko1f803962013-10-01 14:41:18 +0000338 Penalty += State.NextToken->SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000339
Alexander Kornienko1f803962013-10-01 14:41:18 +0000340 // Breaking before the first "<<" is generally not desirable if the LHS is
Daniel Jasper48437ce2013-11-20 14:54:39 +0000341 // short. Also always add the penalty if the LHS is split over mutliple lines
342 // to avoid unncessary line breaks that just work around this penalty.
343 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0 &&
Daniel Jasper004177e2013-12-19 16:06:40 +0000344 (State.Column <= Style.ColumnLimit / 3 ||
Daniel Jasper48437ce2013-11-20 14:54:39 +0000345 State.Stack.back().BreakBeforeParameter))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000346 Penalty += Style.PenaltyBreakFirstLessLess;
347
348 if (Current.is(tok::l_brace) && Current.BlockKind == BK_Block) {
Daniel Jaspere40caf92013-11-29 08:46:20 +0000349 State.Column =
350 State.ParenLevel == 0 ? State.FirstIndent : State.Stack.back().Indent;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000351 } else if (Current.isOneOf(tok::r_brace, tok::r_square)) {
Daniel Jasper6b6e7c32013-11-07 14:02:28 +0000352 if (Current.closesBlockTypeList(Style) ||
353 (Current.MatchingParen &&
354 Current.MatchingParen->BlockKind == BK_BracedInit))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000355 State.Column = State.Stack[State.Stack.size() - 2].LastSpace;
356 else
Daniel Jasper015ed022013-09-13 09:20:45 +0000357 State.Column = State.FirstIndent;
Daniel Jasper04b6a082013-12-20 06:22:01 +0000358 } else if (Current.isStringLiteral() && State.StartOfStringLiteral != 0) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000359 State.Column = State.StartOfStringLiteral;
360 State.Stack.back().BreakBeforeParameter = true;
361 } else if (Current.is(tok::lessless) &&
362 State.Stack.back().FirstLessLess != 0) {
363 State.Column = State.Stack.back().FirstLessLess;
364 } else if (Current.isMemberAccess()) {
365 if (State.Stack.back().CallContinuation == 0) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000366 State.Column = ContinuationIndent;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000367 State.Stack.back().CallContinuation = State.Column;
368 } else {
369 State.Column = State.Stack.back().CallContinuation;
370 }
Daniel Jasper165b29e2013-11-08 00:57:11 +0000371 } else if (State.Stack.back().QuestionColumn != 0 &&
372 (Current.Type == TT_ConditionalExpr ||
373 Previous.Type == TT_ConditionalExpr)) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000374 State.Column = State.Stack.back().QuestionColumn;
375 } else if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0) {
376 State.Column = State.Stack.back().VariablePos;
377 } else if ((PreviousNonComment &&
378 PreviousNonComment->ClosesTemplateDeclaration) ||
379 ((Current.Type == TT_StartOfName ||
380 Current.is(tok::kw_operator)) &&
381 State.ParenLevel == 0 &&
382 (!Style.IndentFunctionDeclarationAfterType ||
383 State.Line->StartsDefinition))) {
Daniel Jasper298c3402013-11-22 07:48:15 +0000384 State.Column =
385 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000386 } else if (Current.Type == TT_ObjCSelectorName) {
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000387 if (!State.Stack.back().ObjCSelectorNameFound) {
388 if (Current.LongestObjCSelectorName == 0) {
389 State.Column = State.Stack.back().Indent;
390 State.Stack.back().AlignColons = false;
391 } else {
392 State.Stack.back().ColonPos =
393 State.Stack.back().Indent + Current.LongestObjCSelectorName;
394 State.Column = State.Stack.back().ColonPos - Current.ColumnWidth;
395 }
396 } else if (!State.Stack.back().AlignColons) {
397 State.Column = State.Stack.back().Indent;
Daniel Jasperb302f9a2013-11-08 02:08:01 +0000398 } else if (State.Stack.back().ColonPos > Current.ColumnWidth) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000399 State.Column = State.Stack.back().ColonPos - Current.ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000400 } else {
401 State.Column = State.Stack.back().Indent;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000402 State.Stack.back().ColonPos = State.Column + Current.ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000403 }
Daniel Jasper1db6c382013-10-22 15:30:28 +0000404 } else if (Current.Type == TT_ArraySubscriptLSquare) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000405 if (State.Stack.back().StartOfArraySubscripts != 0)
406 State.Column = State.Stack.back().StartOfArraySubscripts;
407 else
408 State.Column = ContinuationIndent;
409 } else if (Current.Type == TT_StartOfName ||
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000410 Previous.isOneOf(tok::coloncolon, tok::equal)) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000411 State.Column = ContinuationIndent;
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000412 } else if (PreviousNonComment &&
413 PreviousNonComment->Type == TT_ObjCMethodExpr) {
414 State.Column = ContinuationIndent;
415 // FIXME: This is hacky, find a better way. The problem is that in an ObjC
416 // method expression, the block should be aligned to the line starting it,
417 // e.g.:
418 // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
419 // ^(int *i) {
420 // // ...
421 // }];
422 // Thus, we set LastSpace of the next higher ParenLevel, to which we move
423 // when we consume all of the "}"'s FakeRParens at the "{".
424 State.Stack[State.Stack.size() - 2].LastSpace = ContinuationIndent;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000425 } else if (Current.Type == TT_CtorInitializerColon) {
426 State.Column = State.FirstIndent + Style.ConstructorInitializerIndentWidth;
427 } else if (Current.Type == TT_CtorInitializerComma) {
428 State.Column = State.Stack.back().Indent;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000429 } else {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000430 State.Column = State.Stack.back().Indent;
Daniel Jasper6633ab82013-10-18 10:38:14 +0000431 // Ensure that we fall back to the continuation indent width instead of just
Alexander Kornienko1f803962013-10-01 14:41:18 +0000432 // flushing continuations left.
Daniel Jasper16fc7542013-10-30 14:04:10 +0000433 if (State.Column == State.FirstIndent &&
434 PreviousNonComment->isNot(tok::r_brace))
Daniel Jasper6633ab82013-10-18 10:38:14 +0000435 State.Column += Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000436 }
437
Alexander Kornienko1f803962013-10-01 14:41:18 +0000438 if ((Previous.isOneOf(tok::comma, tok::semi) &&
439 !State.Stack.back().AvoidBinPacking) ||
440 Previous.Type == TT_BinaryOperator)
441 State.Stack.back().BreakBeforeParameter = false;
442 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
443 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000444 if (Current.is(tok::question) ||
445 (PreviousNonComment && PreviousNonComment->is(tok::question)))
446 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000447
448 if (!DryRun) {
449 unsigned Newlines = 1;
450 if (Current.is(tok::comment))
451 Newlines = std::max(Newlines, std::min(Current.NewlinesBefore,
452 Style.MaxEmptyLinesToKeep + 1));
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000453 Whitespaces.replaceWhitespace(Current, Newlines,
454 State.Stack.back().IndentLevel, State.Column,
455 State.Column, State.Line->InPPDirective);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000456 }
457
458 if (!Current.isTrailingComment())
459 State.Stack.back().LastSpace = State.Column;
460 if (Current.isMemberAccess())
461 State.Stack.back().LastSpace += Current.ColumnWidth;
462 State.StartOfLineLevel = State.ParenLevel;
463 State.LowestLevelOnLine = State.ParenLevel;
464
465 // Any break on this level means that the parent level has been broken
466 // and we need to avoid bin packing there.
467 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
468 State.Stack[i].BreakBeforeParameter = true;
469 }
Daniel Jasper9e5ede02013-11-08 19:56:28 +0000470 if (PreviousNonComment &&
471 !PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
472 PreviousNonComment->Type != TT_TemplateCloser &&
473 PreviousNonComment->Type != TT_BinaryOperator &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000474 Current.Type != TT_BinaryOperator &&
Daniel Jasper9e5ede02013-11-08 19:56:28 +0000475 !PreviousNonComment->opensScope())
Alexander Kornienko1f803962013-10-01 14:41:18 +0000476 State.Stack.back().BreakBeforeParameter = true;
477
Daniel Jasper1db6c382013-10-22 15:30:28 +0000478 // If we break after { or the [ of an array initializer, we should also break
479 // before the corresponding } or ].
480 if (Previous.is(tok::l_brace) || Previous.Type == TT_ArrayInitializerLSquare)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000481 State.Stack.back().BreakBeforeClosingBrace = true;
482
483 if (State.Stack.back().AvoidBinPacking) {
484 // If we are breaking after '(', '{', '<', this is not bin packing
485 // unless AllowAllParametersOfDeclarationOnNextLine is false.
486 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
487 Previous.Type == TT_BinaryOperator) ||
488 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
489 State.Line->MustBeDeclaration))
490 State.Stack.back().BreakBeforeParameter = true;
491 }
492
493 return Penalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000494}
495
496unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
497 bool DryRun, bool Newline) {
498 const FormatToken &Current = *State.NextToken;
499 assert(State.Stack.size());
500
501 if (Current.Type == TT_InheritanceColon)
502 State.Stack.back().AvoidBinPacking = true;
503 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
504 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000505 if (Current.Type == TT_ArraySubscriptLSquare &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000506 State.Stack.back().StartOfArraySubscripts == 0)
507 State.Stack.back().StartOfArraySubscripts = State.Column;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000508 if ((Current.is(tok::question) && Style.BreakBeforeTernaryOperators) ||
509 (Current.getPreviousNonComment() && Current.isNot(tok::colon) &&
510 Current.getPreviousNonComment()->is(tok::question) &&
511 !Style.BreakBeforeTernaryOperators))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000512 State.Stack.back().QuestionColumn = State.Column;
513 if (!Current.opensScope() && !Current.closesScope())
514 State.LowestLevelOnLine =
515 std::min(State.LowestLevelOnLine, State.ParenLevel);
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000516 if (Current.isMemberAccess())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000517 State.Stack.back().StartOfFunctionCall =
Alexander Kornienko39856b72013-09-10 09:38:25 +0000518 Current.LastInChainOfCalls ? 0 : State.Column + Current.ColumnWidth;
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000519 if (Current.Type == TT_ObjCSelectorName)
520 State.Stack.back().ObjCSelectorNameFound = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000521 if (Current.Type == TT_CtorInitializerColon) {
522 // Indent 2 from the column, so:
523 // SomeClass::SomeClass()
524 // : First(...), ...
525 // Next(...)
526 // ^ line up here.
527 State.Stack.back().Indent =
528 State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
529 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
530 State.Stack.back().AvoidBinPacking = true;
531 State.Stack.back().BreakBeforeParameter = false;
532 }
533
Daniel Jasperde0328a2013-08-16 11:20:30 +0000534 // In ObjC method declaration we align on the ":" of parameters, but we need
Daniel Jasper6633ab82013-10-18 10:38:14 +0000535 // to ensure that we indent parameters on subsequent lines by at least our
536 // continuation indent width.
Daniel Jasperde0328a2013-08-16 11:20:30 +0000537 if (Current.Type == TT_ObjCMethodSpecifier)
Daniel Jasper6633ab82013-10-18 10:38:14 +0000538 State.Stack.back().Indent += Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000539
540 // Insert scopes created by fake parenthesis.
541 const FormatToken *Previous = Current.getPreviousNonComment();
542 // Don't add extra indentation for the first fake parenthesis after
543 // 'return', assignements or opening <({[. The indentation for these cases
544 // is special cased.
545 bool SkipFirstExtraIndent =
Daniel Jaspereabede62013-09-30 08:29:03 +0000546 (Previous && (Previous->opensScope() || Previous->is(tok::kw_return) ||
Daniel Jasperf48b5ab2013-11-07 19:23:49 +0000547 Previous->getPrecedence() == prec::Assignment ||
548 Previous->Type == TT_ObjCMethodExpr));
Daniel Jasperde0328a2013-08-16 11:20:30 +0000549 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
550 I = Current.FakeLParens.rbegin(),
551 E = Current.FakeLParens.rend();
552 I != E; ++I) {
553 ParenState NewParenState = State.Stack.back();
554 NewParenState.ContainsLineBreak = false;
Daniel Jaspereabede62013-09-30 08:29:03 +0000555
556 // Indent from 'LastSpace' unless this the fake parentheses encapsulating a
557 // builder type call after 'return'. If such a call is line-wrapped, we
558 // commonly just want to indent from the start of the line.
559 if (!Previous || Previous->isNot(tok::kw_return) || *I > 0)
560 NewParenState.Indent =
561 std::max(std::max(State.Column, NewParenState.Indent),
562 State.Stack.back().LastSpace);
563
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000564 // Do not indent relative to the fake parentheses inserted for "." or "->".
565 // This is a special case to make the following to statements consistent:
566 // OuterFunction(InnerFunctionCall( // break
567 // ParameterToInnerFunction));
568 // OuterFunction(SomeObject.InnerFunctionCall( // break
569 // ParameterToInnerFunction));
570 if (*I > prec::Unknown)
571 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
Daniel Jasper96964352013-12-18 10:44:36 +0000572 NewParenState.StartOfFunctionCall = State.Column;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000573
574 // Always indent conditional expressions. Never indent expression where
575 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
576 // prec::Assignment) as those have different indentation rules. Indent
577 // other expression, unless the indentation needs to be skipped.
578 if (*I == prec::Conditional ||
579 (!SkipFirstExtraIndent && *I > prec::Assignment &&
580 !Style.BreakBeforeBinaryOperators))
Daniel Jasper6633ab82013-10-18 10:38:14 +0000581 NewParenState.Indent += Style.ContinuationIndentWidth;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000582 if ((Previous && !Previous->opensScope()) || *I > prec::Comma)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000583 NewParenState.BreakBeforeParameter = false;
584 State.Stack.push_back(NewParenState);
585 SkipFirstExtraIndent = false;
586 }
587
588 // If we encounter an opening (, [, { or <, we add a level to our stacks to
589 // prepare for the following tokens.
590 if (Current.opensScope()) {
591 unsigned NewIndent;
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000592 unsigned NewIndentLevel = State.Stack.back().IndentLevel;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000593 bool AvoidBinPacking;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000594 bool BreakBeforeParameter = false;
595 if (Current.is(tok::l_brace) ||
596 Current.Type == TT_ArrayInitializerLSquare) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000597 if (Current.MatchingParen && Current.BlockKind == BK_Block) {
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000598 // If this is an l_brace starting a nested block, we pretend (wrt. to
599 // indentation) that we already consumed the corresponding r_brace.
Daniel Jasper96964352013-12-18 10:44:36 +0000600 // Thus, we remove all ParenStates caused by fake parentheses that end
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000601 // at the r_brace. The net effect of this is that we don't indent
602 // relative to the l_brace, if the nested block is the last parameter of
603 // a function. For example, this formats:
604 //
605 // SomeFunction(a, [] {
606 // f(); // break
607 // });
608 //
609 // instead of:
610 // SomeFunction(a, [] {
Daniel Jasper5500f612013-11-25 11:08:59 +0000611 // f(); // break
612 // });
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000613 for (unsigned i = 0; i != Current.MatchingParen->FakeRParens; ++i)
614 State.Stack.pop_back();
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000615 bool IsObjCBlock =
616 Previous &&
617 (Previous->is(tok::caret) ||
618 (Previous->is(tok::r_paren) && Previous->MatchingParen &&
619 Previous->MatchingParen->Previous &&
620 Previous->MatchingParen->Previous->is(tok::caret)));
621 // For some reason, ObjC blocks are indented like continuations.
622 NewIndent =
623 State.Stack.back().LastSpace +
624 (IsObjCBlock ? Style.ContinuationIndentWidth : Style.IndentWidth);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000625 ++NewIndentLevel;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000626 BreakBeforeParameter = true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000627 } else {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000628 NewIndent = State.Stack.back().LastSpace;
Daniel Jasperb8f61682013-10-22 15:45:58 +0000629 if (Current.opensBlockTypeList(Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000630 NewIndent += Style.IndentWidth;
Daniel Jasper5a611392013-12-19 21:41:37 +0000631 NewIndent = std::min(State.Column + 2, NewIndent);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000632 ++NewIndentLevel;
Daniel Jasperb8f61682013-10-22 15:45:58 +0000633 } else {
634 NewIndent += Style.ContinuationIndentWidth;
Daniel Jasper5a611392013-12-19 21:41:37 +0000635 NewIndent = std::min(State.Column + 1, NewIndent);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000636 }
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000637 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000638 const FormatToken *NextNoComment = Current.getNextNonComment();
Daniel Jasper015ed022013-09-13 09:20:45 +0000639 AvoidBinPacking = Current.BlockKind == BK_Block ||
Daniel Jasper1db6c382013-10-22 15:30:28 +0000640 Current.Type == TT_ArrayInitializerLSquare ||
Daniel Jasperb596fb22013-10-24 10:31:50 +0000641 Current.Type == TT_DictLiteral ||
Daniel Jasper015ed022013-09-13 09:20:45 +0000642 (NextNoComment &&
643 NextNoComment->Type == TT_DesignatedInitializerPeriod);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000644 } else {
Daniel Jasper6633ab82013-10-18 10:38:14 +0000645 NewIndent = Style.ContinuationIndentWidth +
646 std::max(State.Stack.back().LastSpace,
647 State.Stack.back().StartOfFunctionCall);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000648 AvoidBinPacking = !Style.BinPackParameters ||
649 (Style.ExperimentalAutoDetectBinPacking &&
650 (Current.PackingKind == PPK_OnePerLine ||
651 (!BinPackInconclusiveFunctions &&
652 Current.PackingKind == PPK_Inconclusive)));
Daniel Jasper1db6c382013-10-22 15:30:28 +0000653 // If this '[' opens an ObjC call, determine whether all parameters fit
654 // into one line and put one per line if they don't.
655 if (Current.Type == TT_ObjCMethodExpr &&
656 getLengthToMatchingParen(Current) + State.Column >
657 getColumnLimit(State))
658 BreakBeforeParameter = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000659 }
660
Daniel Jaspercc3114d2013-10-18 15:23:06 +0000661 bool NoLineBreak = State.Stack.back().NoLineBreak ||
662 (Current.Type == TT_TemplateOpener &&
663 State.Stack.back().ContainsUnwrappedBuilder);
664 State.Stack.push_back(ParenState(NewIndent, NewIndentLevel,
665 State.Stack.back().LastSpace,
666 AvoidBinPacking, NoLineBreak));
Daniel Jasper1db6c382013-10-22 15:30:28 +0000667 State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000668 ++State.ParenLevel;
669 }
670
Daniel Jasperde0328a2013-08-16 11:20:30 +0000671 // If we encounter a closing ), ], } or >, we can remove a level from our
672 // stacks.
Daniel Jasper96df37a2013-08-28 09:17:37 +0000673 if (State.Stack.size() > 1 &&
674 (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000675 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
Daniel Jasper96df37a2013-08-28 09:17:37 +0000676 State.NextToken->Type == TT_TemplateCloser)) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000677 State.Stack.pop_back();
678 --State.ParenLevel;
679 }
680 if (Current.is(tok::r_square)) {
681 // If this ends the array subscript expr, reset the corresponding value.
682 const FormatToken *NextNonComment = Current.getNextNonComment();
683 if (NextNonComment && NextNonComment->isNot(tok::l_square))
684 State.Stack.back().StartOfArraySubscripts = 0;
685 }
686
687 // Remove scopes created by fake parenthesis.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000688 if (Current.isNot(tok::r_brace) ||
689 (Current.MatchingParen && Current.MatchingParen->BlockKind != BK_Block)) {
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000690 // Don't remove FakeRParens attached to r_braces that surround nested blocks
691 // as they will have been removed early (see above).
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000692 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
693 unsigned VariablePos = State.Stack.back().VariablePos;
694 State.Stack.pop_back();
695 State.Stack.back().VariablePos = VariablePos;
696 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000697 }
698
Daniel Jasper04b6a082013-12-20 06:22:01 +0000699 if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000700 State.StartOfStringLiteral = State.Column;
Daniel Jasper04b6a082013-12-20 06:22:01 +0000701 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
702 !Current.isStringLiteral()) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000703 State.StartOfStringLiteral = 0;
704 }
705
Alexander Kornienko39856b72013-09-10 09:38:25 +0000706 State.Column += Current.ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000707 State.NextToken = State.NextToken->Next;
Daniel Jasperb27c4b72013-08-27 11:09:05 +0000708 unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000709 if (State.Column > getColumnLimit(State)) {
710 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
711 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
712 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000713
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000714 // If the previous has a special role, let it consume tokens as appropriate.
715 // It is necessary to start at the previous token for the only implemented
716 // role (comma separated list). That way, the decision whether or not to break
717 // after the "{" is already done and both options are tried and evaluated.
718 // FIXME: This is ugly, find a better way.
719 if (Previous && Previous->Role)
720 Penalty += Previous->Role->format(State, this, DryRun);
721
722 return Penalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000723}
724
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000725unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
726 LineState &State) {
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000727 // Break before further function parameters on all levels.
728 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
729 State.Stack[i].BreakBeforeParameter = true;
730
Alexander Kornienko39856b72013-09-10 09:38:25 +0000731 unsigned ColumnsUsed = State.Column;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000732 // We can only affect layout of the first and the last line, so the penalty
733 // for all other lines is constant, and we ignore it.
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000734 State.Column = Current.LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000735
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000736 if (ColumnsUsed > getColumnLimit(State))
737 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000738 return 0;
739}
740
Alexander Kornienko81e32942013-09-16 20:20:49 +0000741static bool getRawStringLiteralPrefixPostfix(StringRef Text,
742 StringRef &Prefix,
743 StringRef &Postfix) {
744 if (Text.startswith(Prefix = "R\"") || Text.startswith(Prefix = "uR\"") ||
745 Text.startswith(Prefix = "UR\"") || Text.startswith(Prefix = "u8R\"") ||
746 Text.startswith(Prefix = "LR\"")) {
747 size_t ParenPos = Text.find('(');
748 if (ParenPos != StringRef::npos) {
749 StringRef Delimiter =
750 Text.substr(Prefix.size(), ParenPos - Prefix.size());
751 Prefix = Text.substr(0, ParenPos + 1);
752 Postfix = Text.substr(Text.size() - 2 - Delimiter.size());
753 return Postfix.front() == ')' && Postfix.back() == '"' &&
754 Postfix.substr(1).startswith(Delimiter);
755 }
756 }
757 return false;
758}
759
Daniel Jasperde0328a2013-08-16 11:20:30 +0000760unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
761 LineState &State,
762 bool DryRun) {
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000763 // Don't break multi-line tokens other than block comments. Instead, just
764 // update the state.
765 if (Current.Type != TT_BlockComment && Current.IsMultiline)
766 return addMultilineToken(Current, State);
767
Daniel Jasper98857842013-10-30 13:54:53 +0000768 // Don't break implicit string literals.
769 if (Current.Type == TT_ImplicitStringLiteral)
770 return 0;
771
Daniel Jasper04b6a082013-12-20 06:22:01 +0000772 if (!Current.isStringLiteral() && !Current.is(tok::comment))
Daniel Jasperf93551c2013-08-23 10:05:49 +0000773 return 0;
774
Daniel Jasperde0328a2013-08-16 11:20:30 +0000775 llvm::OwningPtr<BreakableToken> Token;
Alexander Kornienko39856b72013-09-10 09:38:25 +0000776 unsigned StartColumn = State.Column - Current.ColumnWidth;
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000777 unsigned ColumnLimit = getColumnLimit(State);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000778
Daniel Jasper04b6a082013-12-20 06:22:01 +0000779 if (Current.isStringLiteral()) {
Alexander Kornienko384b40b2013-10-11 21:43:05 +0000780 // Don't break string literals inside preprocessor directives (except for
781 // #define directives, as their contents are stored in separate lines and
782 // are not affected by this check).
783 // This way we avoid breaking code with line directives and unknown
784 // preprocessor directives that contain long string literals.
785 if (State.Line->Type == LT_PreprocessorDirective)
786 return 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000787 // Exempts unterminated string literals from line breaking. The user will
788 // likely want to terminate the string before any line breaking is done.
789 if (Current.IsUnterminatedLiteral)
790 return 0;
791
Alexander Kornienko81e32942013-09-16 20:20:49 +0000792 StringRef Text = Current.TokenText;
793 StringRef Prefix;
794 StringRef Postfix;
795 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
796 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
797 // reduce the overhead) for each FormatToken, which is a string, so that we
798 // don't run multiple checks here on the hot path.
799 if ((Text.endswith(Postfix = "\"") &&
800 (Text.startswith(Prefix = "\"") || Text.startswith(Prefix = "u\"") ||
801 Text.startswith(Prefix = "U\"") || Text.startswith(Prefix = "u8\"") ||
802 Text.startswith(Prefix = "L\""))) ||
803 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")")) ||
804 getRawStringLiteralPrefixPostfix(Text, Prefix, Postfix)) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000805 Token.reset(new BreakableStringLiteral(
806 Current, State.Line->Level, StartColumn, Prefix, Postfix,
807 State.Line->InPPDirective, Encoding, Style));
Alexander Kornienko81e32942013-09-16 20:20:49 +0000808 } else {
809 return 0;
810 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000811 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
812 Token.reset(new BreakableBlockComment(
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000813 Current, State.Line->Level, StartColumn, Current.OriginalColumn,
814 !Current.Previous, State.Line->InPPDirective, Encoding, Style));
Daniel Jasperde0328a2013-08-16 11:20:30 +0000815 } else if (Current.Type == TT_LineComment &&
816 (Current.Previous == NULL ||
817 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000818 Token.reset(new BreakableLineComment(Current, State.Line->Level,
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000819 StartColumn, /*InPPDirective=*/false,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000820 Encoding, Style));
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000821 // We don't insert backslashes when breaking line comments.
822 ColumnLimit = Style.ColumnLimit;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000823 } else {
824 return 0;
825 }
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000826 if (Current.UnbreakableTailLength >= ColumnLimit)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000827 return 0;
828
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000829 unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000830 bool BreakInserted = false;
831 unsigned Penalty = 0;
832 unsigned RemainingTokenColumns = 0;
833 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
834 LineIndex != EndIndex; ++LineIndex) {
835 if (!DryRun)
836 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
837 unsigned TailOffset = 0;
838 RemainingTokenColumns =
839 Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
840 while (RemainingTokenColumns > RemainingSpace) {
841 BreakableToken::Split Split =
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000842 Token->getSplit(LineIndex, TailOffset, ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000843 if (Split.first == StringRef::npos) {
844 // The last line's penalty is handled in addNextStateToQueue().
845 if (LineIndex < EndIndex - 1)
846 Penalty += Style.PenaltyExcessCharacter *
847 (RemainingTokenColumns - RemainingSpace);
848 break;
849 }
850 assert(Split.first != 0);
851 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
852 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
Alexander Kornienko875395f2013-11-12 17:50:13 +0000853
854 // We can remove extra whitespace instead of breaking the line.
855 if (RemainingTokenColumns + 1 - Split.second <= RemainingSpace) {
856 RemainingTokenColumns = 0;
857 if (!DryRun)
858 Token->replaceWhitespace(LineIndex, TailOffset, Split, Whitespaces);
859 break;
860 }
861
Daniel Jasperde0328a2013-08-16 11:20:30 +0000862 assert(NewRemainingTokenColumns < RemainingTokenColumns);
863 if (!DryRun)
864 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Daniel Jasper2739af32013-08-28 10:03:58 +0000865 Penalty += Current.SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000866 unsigned ColumnsUsed =
867 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000868 if (ColumnsUsed > ColumnLimit) {
869 Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000870 }
871 TailOffset += Split.first + Split.second;
872 RemainingTokenColumns = NewRemainingTokenColumns;
873 BreakInserted = true;
874 }
875 }
876
877 State.Column = RemainingTokenColumns;
878
879 if (BreakInserted) {
880 // If we break the token inside a parameter list, we need to break before
881 // the next parameter on all levels, so that the next parameter is clearly
882 // visible. Line comments already introduce a break.
883 if (Current.Type != TT_LineComment) {
884 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
885 State.Stack[i].BreakBeforeParameter = true;
886 }
887
Daniel Jasper04b6a082013-12-20 06:22:01 +0000888 Penalty += Current.isStringLiteral() ? Style.PenaltyBreakString
889 : Style.PenaltyBreakComment;
Daniel Jasper2739af32013-08-28 10:03:58 +0000890
Daniel Jasperde0328a2013-08-16 11:20:30 +0000891 State.Stack.back().LastSpace = StartColumn;
892 }
893 return Penalty;
894}
895
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000896unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000897 // In preprocessor directives reserve two chars for trailing " \"
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000898 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000899}
900
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000901bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
Daniel Jasperf438cb72013-08-23 11:57:34 +0000902 const FormatToken &Current = *State.NextToken;
Daniel Jasper04b6a082013-12-20 06:22:01 +0000903 if (!Current.isStringLiteral())
Daniel Jasperf438cb72013-08-23 11:57:34 +0000904 return false;
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000905 // We never consider raw string literals "multiline" for the purpose of
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000906 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
907 // (see TokenAnnotator::mustBreakBefore().
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000908 if (Current.TokenText.startswith("R\""))
909 return false;
Alexander Kornienko39856b72013-09-10 09:38:25 +0000910 if (Current.IsMultiline)
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000911 return true;
Daniel Jasperf438cb72013-08-23 11:57:34 +0000912 if (Current.getNextNonComment() &&
Daniel Jasper04b6a082013-12-20 06:22:01 +0000913 Current.getNextNonComment()->isStringLiteral())
Daniel Jasperf438cb72013-08-23 11:57:34 +0000914 return true; // Implicit concatenation.
Alexander Kornienko39856b72013-09-10 09:38:25 +0000915 if (State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
Daniel Jasperf438cb72013-08-23 11:57:34 +0000916 Style.ColumnLimit)
917 return true; // String will be split.
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000918 return false;
Daniel Jasperf438cb72013-08-23 11:57:34 +0000919}
920
Daniel Jasperde0328a2013-08-16 11:20:30 +0000921} // namespace format
922} // namespace clang