blob: a80e87ddfc81f337508f49a2039e6991351d9c78 [file] [log] [blame]
Daniel Jasper6b2afe42013-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 Jasperd3fef0f2013-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 Jasper19ccb122013-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 Jasper6b2afe42013-08-16 11:20:30 +000059ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,
60 SourceManager &SourceMgr,
Daniel Jasper6b2afe42013-08-16 11:20:30 +000061 WhitespaceManager &Whitespaces,
62 encoding::Encoding Encoding,
63 bool BinPackInconclusiveFunctions)
Daniel Jasper567dcf92013-09-05 09:29:45 +000064 : Style(Style), SourceMgr(SourceMgr), Whitespaces(Whitespaces),
65 Encoding(Encoding),
Daniel Jasper6b2afe42013-08-16 11:20:30 +000066 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions) {}
67
Daniel Jasper567dcf92013-09-05 09:29:45 +000068LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
Daniel Jasperb77d7412013-09-06 07:54:20 +000069 const AnnotatedLine *Line,
70 bool DryRun) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +000071 LineState State;
Daniel Jasper567dcf92013-09-05 09:29:45 +000072 State.FirstIndent = FirstIndent;
Daniel Jasper6b2afe42013-08-16 11:20:30 +000073 State.Column = FirstIndent;
Daniel Jasper567dcf92013-09-05 09:29:45 +000074 State.Line = Line;
75 State.NextToken = Line->First;
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +000076 State.Stack.push_back(ParenState(FirstIndent, Line->Level, FirstIndent,
Daniel Jasper6b2afe42013-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 Jasperb77d7412013-09-06 07:54:20 +000087 moveStateToNextToken(State, DryRun, /*Newline=*/false);
Daniel Jasper6b2afe42013-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 Jaspera07aa662013-10-22 15:30:28 +000095 if (!Current.CanBreakBefore && !(State.Stack.back().BreakBeforeClosingBrace &&
96 Current.closesBlockTypeList(Style)))
Daniel Jasper6b2afe42013-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 Jasper3c6aea72013-10-24 10:31:50 +0000101 Previous.Type != TT_DictLiteral &&
Daniel Jasper567dcf92013-09-05 09:29:45 +0000102 Previous.BlockKind == BK_BracedInit && Previous.Previous &&
Daniel Jasper6b2afe42013-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 Jasperd3fef0f2013-08-27 14:24:43 +0000112 if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
113 return false;
Daniel Jasper6b2afe42013-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 Jaspera07aa662013-10-22 15:30:28 +0000122 if (State.Stack.back().BreakBeforeClosingBrace &&
123 Current.closesBlockTypeList(Style))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000124 return true;
125 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
126 return true;
Daniel Jasper19ccb122013-10-08 05:11:18 +0000127 if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
128 Current.is(tok::question) ||
129 (Current.Type == TT_ConditionalExpr && Previous.isNot(tok::question))) &&
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000130 State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
131 !Current.isOneOf(tok::r_paren, tok::r_brace))
132 return true;
133 if (Style.AlwaysBreakBeforeMultilineStrings &&
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000134 State.Column > State.Stack.back().Indent && // Breaking saves columns.
Daniel Jasper49c77b22013-10-18 16:47:55 +0000135 !Previous.isOneOf(tok::kw_return, tok::lessless) &&
136 Previous.Type != TT_InlineASMColon && NextIsMultilineString(State))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000137 return true;
Daniel Jasper3c6aea72013-10-24 10:31:50 +0000138 if (((Previous.Type == TT_DictLiteral && Previous.is(tok::l_brace)) ||
Daniel Jaspera07aa662013-10-22 15:30:28 +0000139 Previous.Type == TT_ArrayInitializerLSquare) &&
Daniel Jaspera53bbae2013-10-20 16:45:46 +0000140 getLengthToMatchingParen(Previous) + State.Column > getColumnLimit(State))
141 return true;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000142
143 if (!Style.BreakBeforeBinaryOperators) {
144 // If we need to break somewhere inside the LHS of a binary expression, we
145 // should also break after the operator. Otherwise, the formatting would
146 // hide the operator precedence, e.g. in:
147 // if (aaaaaaaaaaaaaa ==
148 // bbbbbbbbbbbbbb && c) {..
149 // For comparisons, we only apply this rule, if the LHS is a binary
150 // expression itself as otherwise, the line breaks seem superfluous.
151 // We need special cases for ">>" which we have split into two ">" while
152 // lexing in order to make template parsing easier.
153 //
154 // FIXME: We'll need something similar for styles that break before binary
155 // operators.
156 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
157 Previous.getPrecedence() == prec::Equality) &&
158 Previous.Previous &&
159 Previous.Previous->Type != TT_BinaryOperator; // For >>.
160 bool LHSIsBinaryExpr =
Daniel Jasperdb4813a2013-09-06 08:08:14 +0000161 Previous.Previous && Previous.Previous->EndsBinaryExpression;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000162 if (Previous.Type == TT_BinaryOperator &&
163 (!IsComparison || LHSIsBinaryExpr) &&
164 Current.Type != TT_BinaryOperator && // For >>.
165 !Current.isTrailingComment() &&
166 !Previous.isOneOf(tok::lessless, tok::question) &&
167 Previous.getPrecedence() != prec::Assignment &&
168 State.Stack.back().BreakBeforeParameter)
169 return true;
170 }
171
172 // Same as above, but for the first "<<" operator.
173 if (Current.is(tok::lessless) && State.Stack.back().BreakBeforeParameter &&
174 State.Stack.back().FirstLessLess == 0)
175 return true;
176
177 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
178 // out whether it is the first parameter. Clean this up.
179 if (Current.Type == TT_ObjCSelectorName &&
180 Current.LongestObjCSelectorName == 0 &&
181 State.Stack.back().BreakBeforeParameter)
182 return true;
183 if ((Current.Type == TT_CtorInitializerColon ||
Daniel Jasper6e7f1932013-10-09 15:06:17 +0000184 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0 &&
185 !Current.isTrailingComment())))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000186 return true;
187
188 if ((Current.Type == TT_StartOfName || Current.is(tok::kw_operator)) &&
Daniel Jasper567dcf92013-09-05 09:29:45 +0000189 State.Line->MightBeFunctionDecl &&
190 State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000191 return true;
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000192 if (startsSegmentOfBuilderTypeCall(Current) &&
Daniel Jaspereb331832013-08-30 07:12:40 +0000193 (State.Stack.back().CallContinuation != 0 ||
194 (State.Stack.back().BreakBeforeParameter &&
195 State.Stack.back().ContainsUnwrappedBuilder)))
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000196 return true;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000197 return false;
198}
199
200unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000201 bool DryRun,
202 unsigned ExtraSpaces) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000203 const FormatToken &Current = *State.NextToken;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000204
Daniel Jasper84379572013-10-30 13:54:53 +0000205 if (State.Stack.size() == 0 ||
206 (Current.Type == TT_ImplicitStringLiteral &&
207 (Current.Previous->Tok.getIdentifierInfo() == NULL ||
208 Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
209 tok::pp_not_keyword))) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000210 // FIXME: Is this correct?
211 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
212 State.NextToken->WhitespaceRange.getEnd()) -
213 SourceMgr.getSpellingColumnNumber(
214 State.NextToken->WhitespaceRange.getBegin());
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000215 State.Column += WhitespaceLength + State.NextToken->ColumnWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000216 State.NextToken = State.NextToken->Next;
217 return 0;
218 }
219
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000220 unsigned Penalty = 0;
221 if (Newline)
222 Penalty = addTokenOnNewLine(State, DryRun);
223 else
224 addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
225
226 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
227}
228
229void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
230 unsigned ExtraSpaces) {
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000231 FormatToken &Current = *State.NextToken;
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000232 const FormatToken &Previous = *State.NextToken->Previous;
233 if (Current.is(tok::equal) &&
234 (State.Line->First->is(tok::kw_for) || State.ParenLevel == 0) &&
235 State.Stack.back().VariablePos == 0) {
236 State.Stack.back().VariablePos = State.Column;
237 // Move over * and & if they are bound to the variable name.
238 const FormatToken *Tok = &Previous;
239 while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
240 State.Stack.back().VariablePos -= Tok->ColumnWidth;
241 if (Tok->SpacesRequiredBefore != 0)
242 break;
243 Tok = Tok->Previous;
244 }
245 if (Previous.PartOfMultiVariableDeclStmt)
246 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
247 }
248
249 unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
250
251 if (!DryRun)
252 Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, /*IndentLevel=*/0,
253 Spaces, State.Column + Spaces);
254
255 if (Current.Type == TT_ObjCSelectorName && State.Stack.back().ColonPos == 0) {
256 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
257 State.Column + Spaces + Current.ColumnWidth)
258 State.Stack.back().ColonPos =
259 State.Stack.back().Indent + Current.LongestObjCSelectorName;
260 else
261 State.Stack.back().ColonPos = State.Column + Spaces + Current.ColumnWidth;
262 }
263
264 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
265 Current.Type != TT_LineComment)
266 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper19ccb122013-10-08 05:11:18 +0000267 if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000268 State.Stack.back().NoLineBreak = true;
269 if (startsSegmentOfBuilderTypeCall(Current))
270 State.Stack.back().ContainsUnwrappedBuilder = true;
271
272 State.Column += Spaces;
273 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
274 // Treat the condition inside an if as if it was a second function
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000275 // parameter, i.e. let nested calls have a continuation indent.
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000276 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
277 else if (Previous.is(tok::comma))
278 State.Stack.back().LastSpace = State.Column;
279 else if ((Previous.Type == TT_BinaryOperator ||
280 Previous.Type == TT_ConditionalExpr ||
281 Previous.Type == TT_UnaryOperator ||
282 Previous.Type == TT_CtorInitializerColon) &&
283 (Previous.getPrecedence() != prec::Assignment ||
284 Current.StartsBinaryExpression))
285 // Always indent relative to the RHS of the expression unless this is a
286 // simple assignment without binary expression on the RHS. Also indent
287 // relative to unary operators and the colons of constructor initializers.
288 State.Stack.back().LastSpace = State.Column;
Daniel Jaspercea014b2013-10-08 16:24:07 +0000289 else if (Previous.Type == TT_InheritanceColon) {
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000290 State.Stack.back().Indent = State.Column;
Daniel Jaspercea014b2013-10-08 16:24:07 +0000291 State.Stack.back().LastSpace = State.Column;
292 } else if (Previous.opensScope()) {
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000293 // If a function has a trailing call, indent all parameters from the
294 // opening parenthesis. This avoids confusing indents like:
295 // OuterFunction(InnerFunctionCall( // break
296 // ParameterToInnerFunction)) // break
297 // .SecondInnerFunctionCall();
298 bool HasTrailingCall = false;
299 if (Previous.MatchingParen) {
300 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
301 HasTrailingCall = Next && Next->isMemberAccess();
302 }
303 if (HasTrailingCall &&
304 State.Stack[State.Stack.size() - 2].CallContinuation == 0)
305 State.Stack.back().LastSpace = State.Column;
306 }
307}
308
309unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
310 bool DryRun) {
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000311 FormatToken &Current = *State.NextToken;
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000312 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000313 // If we are continuing an expression, we want to use the continuation indent.
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000314 unsigned ContinuationIndent =
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000315 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
316 Style.ContinuationIndentWidth;
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000317 // Extra penalty that needs to be added because of the way certain line
318 // breaks are chosen.
319 unsigned Penalty = 0;
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000320
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000321 const FormatToken *PreviousNonComment =
322 State.NextToken->getPreviousNonComment();
323 // The first line break on any ParenLevel causes an extra penalty in order
324 // prefer similar line breaks.
325 if (!State.Stack.back().ContainsLineBreak)
326 Penalty += 15;
327 State.Stack.back().ContainsLineBreak = true;
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000328
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000329 Penalty += State.NextToken->SplitPenalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000330
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000331 // Breaking before the first "<<" is generally not desirable if the LHS is
332 // short.
333 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0 &&
334 State.Column <= Style.ColumnLimit / 2)
335 Penalty += Style.PenaltyBreakFirstLessLess;
336
337 if (Current.is(tok::l_brace) && Current.BlockKind == BK_Block) {
338 State.Column = State.FirstIndent;
Daniel Jaspera07aa662013-10-22 15:30:28 +0000339 } else if (Current.isOneOf(tok::r_brace, tok::r_square)) {
Daniel Jasper16a8b0e2013-11-07 14:02:28 +0000340 if (Current.closesBlockTypeList(Style) ||
341 (Current.MatchingParen &&
342 Current.MatchingParen->BlockKind == BK_BracedInit))
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000343 State.Column = State.Stack[State.Stack.size() - 2].LastSpace;
344 else
Daniel Jasper57981202013-09-13 09:20:45 +0000345 State.Column = State.FirstIndent;
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000346 } else if (Current.is(tok::string_literal) &&
347 State.StartOfStringLiteral != 0) {
348 State.Column = State.StartOfStringLiteral;
349 State.Stack.back().BreakBeforeParameter = true;
350 } else if (Current.is(tok::lessless) &&
351 State.Stack.back().FirstLessLess != 0) {
352 State.Column = State.Stack.back().FirstLessLess;
353 } else if (Current.isMemberAccess()) {
354 if (State.Stack.back().CallContinuation == 0) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000355 State.Column = ContinuationIndent;
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000356 State.Stack.back().CallContinuation = State.Column;
357 } else {
358 State.Column = State.Stack.back().CallContinuation;
359 }
360 } else if (Current.Type == TT_ConditionalExpr) {
361 State.Column = State.Stack.back().QuestionColumn;
362 } else if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0) {
363 State.Column = State.Stack.back().VariablePos;
364 } else if ((PreviousNonComment &&
365 PreviousNonComment->ClosesTemplateDeclaration) ||
366 ((Current.Type == TT_StartOfName ||
367 Current.is(tok::kw_operator)) &&
368 State.ParenLevel == 0 &&
369 (!Style.IndentFunctionDeclarationAfterType ||
370 State.Line->StartsDefinition))) {
371 State.Column = State.Stack.back().Indent;
372 } else if (Current.Type == TT_ObjCSelectorName) {
373 if (State.Stack.back().ColonPos > Current.ColumnWidth) {
374 State.Column = State.Stack.back().ColonPos - Current.ColumnWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000375 } else {
376 State.Column = State.Stack.back().Indent;
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000377 State.Stack.back().ColonPos = State.Column + Current.ColumnWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000378 }
Daniel Jaspera07aa662013-10-22 15:30:28 +0000379 } else if (Current.Type == TT_ArraySubscriptLSquare) {
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000380 if (State.Stack.back().StartOfArraySubscripts != 0)
381 State.Column = State.Stack.back().StartOfArraySubscripts;
382 else
383 State.Column = ContinuationIndent;
384 } else if (Current.Type == TT_StartOfName ||
385 Previous.isOneOf(tok::coloncolon, tok::equal) ||
386 Previous.Type == TT_ObjCMethodExpr) {
387 State.Column = ContinuationIndent;
388 } else if (Current.Type == TT_CtorInitializerColon) {
389 State.Column = State.FirstIndent + Style.ConstructorInitializerIndentWidth;
390 } else if (Current.Type == TT_CtorInitializerComma) {
391 State.Column = State.Stack.back().Indent;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000392 } else {
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000393 State.Column = State.Stack.back().Indent;
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000394 // Ensure that we fall back to the continuation indent width instead of just
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000395 // flushing continuations left.
Daniel Jasperdc837b12013-10-30 14:04:10 +0000396 if (State.Column == State.FirstIndent &&
397 PreviousNonComment->isNot(tok::r_brace))
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000398 State.Column += Style.ContinuationIndentWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000399 }
400
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000401 if (Current.is(tok::question))
402 State.Stack.back().BreakBeforeParameter = true;
403 if ((Previous.isOneOf(tok::comma, tok::semi) &&
404 !State.Stack.back().AvoidBinPacking) ||
405 Previous.Type == TT_BinaryOperator)
406 State.Stack.back().BreakBeforeParameter = false;
407 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
408 State.Stack.back().BreakBeforeParameter = false;
409
410 if (!DryRun) {
411 unsigned Newlines = 1;
412 if (Current.is(tok::comment))
413 Newlines = std::max(Newlines, std::min(Current.NewlinesBefore,
414 Style.MaxEmptyLinesToKeep + 1));
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000415 Whitespaces.replaceWhitespace(Current, Newlines,
416 State.Stack.back().IndentLevel, State.Column,
417 State.Column, State.Line->InPPDirective);
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000418 }
419
420 if (!Current.isTrailingComment())
421 State.Stack.back().LastSpace = State.Column;
422 if (Current.isMemberAccess())
423 State.Stack.back().LastSpace += Current.ColumnWidth;
424 State.StartOfLineLevel = State.ParenLevel;
425 State.LowestLevelOnLine = State.ParenLevel;
426
427 // Any break on this level means that the parent level has been broken
428 // and we need to avoid bin packing there.
429 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
430 State.Stack[i].BreakBeforeParameter = true;
431 }
432 const FormatToken *TokenBefore = Current.getPreviousNonComment();
433 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
434 TokenBefore->Type != TT_TemplateCloser &&
435 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
436 State.Stack.back().BreakBeforeParameter = true;
437
Daniel Jaspera07aa662013-10-22 15:30:28 +0000438 // If we break after { or the [ of an array initializer, we should also break
439 // before the corresponding } or ].
440 if (Previous.is(tok::l_brace) || Previous.Type == TT_ArrayInitializerLSquare)
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000441 State.Stack.back().BreakBeforeClosingBrace = true;
442
443 if (State.Stack.back().AvoidBinPacking) {
444 // If we are breaking after '(', '{', '<', this is not bin packing
445 // unless AllowAllParametersOfDeclarationOnNextLine is false.
446 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
447 Previous.Type == TT_BinaryOperator) ||
448 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
449 State.Line->MustBeDeclaration))
450 State.Stack.back().BreakBeforeParameter = true;
451 }
452
453 return Penalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000454}
455
456unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
457 bool DryRun, bool Newline) {
458 const FormatToken &Current = *State.NextToken;
459 assert(State.Stack.size());
460
461 if (Current.Type == TT_InheritanceColon)
462 State.Stack.back().AvoidBinPacking = true;
463 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
464 State.Stack.back().FirstLessLess = State.Column;
Daniel Jaspera07aa662013-10-22 15:30:28 +0000465 if (Current.Type == TT_ArraySubscriptLSquare &&
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000466 State.Stack.back().StartOfArraySubscripts == 0)
467 State.Stack.back().StartOfArraySubscripts = State.Column;
468 if (Current.is(tok::question))
469 State.Stack.back().QuestionColumn = State.Column;
470 if (!Current.opensScope() && !Current.closesScope())
471 State.LowestLevelOnLine =
472 std::min(State.LowestLevelOnLine, State.ParenLevel);
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000473 if (Current.isMemberAccess())
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000474 State.Stack.back().StartOfFunctionCall =
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000475 Current.LastInChainOfCalls ? 0 : State.Column + Current.ColumnWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000476 if (Current.Type == TT_CtorInitializerColon) {
477 // Indent 2 from the column, so:
478 // SomeClass::SomeClass()
479 // : First(...), ...
480 // Next(...)
481 // ^ line up here.
482 State.Stack.back().Indent =
483 State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
484 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
485 State.Stack.back().AvoidBinPacking = true;
486 State.Stack.back().BreakBeforeParameter = false;
487 }
488
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000489 // In ObjC method declaration we align on the ":" of parameters, but we need
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000490 // to ensure that we indent parameters on subsequent lines by at least our
491 // continuation indent width.
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000492 if (Current.Type == TT_ObjCMethodSpecifier)
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000493 State.Stack.back().Indent += Style.ContinuationIndentWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000494
495 // Insert scopes created by fake parenthesis.
496 const FormatToken *Previous = Current.getPreviousNonComment();
497 // Don't add extra indentation for the first fake parenthesis after
498 // 'return', assignements or opening <({[. The indentation for these cases
499 // is special cased.
500 bool SkipFirstExtraIndent =
Daniel Jasperf78bf4a2013-09-30 08:29:03 +0000501 (Previous && (Previous->opensScope() || Previous->is(tok::kw_return) ||
Daniel Jasper966e6d32013-11-07 19:23:49 +0000502 Previous->getPrecedence() == prec::Assignment ||
503 Previous->Type == TT_ObjCMethodExpr));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000504 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
505 I = Current.FakeLParens.rbegin(),
506 E = Current.FakeLParens.rend();
507 I != E; ++I) {
508 ParenState NewParenState = State.Stack.back();
509 NewParenState.ContainsLineBreak = false;
Daniel Jasperf78bf4a2013-09-30 08:29:03 +0000510
511 // Indent from 'LastSpace' unless this the fake parentheses encapsulating a
512 // builder type call after 'return'. If such a call is line-wrapped, we
513 // commonly just want to indent from the start of the line.
514 if (!Previous || Previous->isNot(tok::kw_return) || *I > 0)
515 NewParenState.Indent =
516 std::max(std::max(State.Column, NewParenState.Indent),
517 State.Stack.back().LastSpace);
518
Daniel Jasper567dcf92013-09-05 09:29:45 +0000519 // Do not indent relative to the fake parentheses inserted for "." or "->".
520 // This is a special case to make the following to statements consistent:
521 // OuterFunction(InnerFunctionCall( // break
522 // ParameterToInnerFunction));
523 // OuterFunction(SomeObject.InnerFunctionCall( // break
524 // ParameterToInnerFunction));
525 if (*I > prec::Unknown)
526 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000527
528 // Always indent conditional expressions. Never indent expression where
529 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
530 // prec::Assignment) as those have different indentation rules. Indent
531 // other expression, unless the indentation needs to be skipped.
532 if (*I == prec::Conditional ||
533 (!SkipFirstExtraIndent && *I > prec::Assignment &&
534 !Style.BreakBeforeBinaryOperators))
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000535 NewParenState.Indent += Style.ContinuationIndentWidth;
Daniel Jaspera07aa662013-10-22 15:30:28 +0000536 if ((Previous && !Previous->opensScope()) || *I > prec::Comma)
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000537 NewParenState.BreakBeforeParameter = false;
538 State.Stack.push_back(NewParenState);
539 SkipFirstExtraIndent = false;
540 }
541
542 // If we encounter an opening (, [, { or <, we add a level to our stacks to
543 // prepare for the following tokens.
544 if (Current.opensScope()) {
545 unsigned NewIndent;
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000546 unsigned NewIndentLevel = State.Stack.back().IndentLevel;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000547 bool AvoidBinPacking;
Daniel Jaspera07aa662013-10-22 15:30:28 +0000548 bool BreakBeforeParameter = false;
549 if (Current.is(tok::l_brace) ||
550 Current.Type == TT_ArrayInitializerLSquare) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000551 if (Current.MatchingParen && Current.BlockKind == BK_Block) {
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000552 // If this is an l_brace starting a nested block, we pretend (wrt. to
553 // indentation) that we already consumed the corresponding r_brace.
554 // Thus, we remove all ParenStates caused bake fake parentheses that end
555 // at the r_brace. The net effect of this is that we don't indent
556 // relative to the l_brace, if the nested block is the last parameter of
557 // a function. For example, this formats:
558 //
559 // SomeFunction(a, [] {
560 // f(); // break
561 // });
562 //
563 // instead of:
564 // SomeFunction(a, [] {
565 // f(); // break
566 // });
Daniel Jasper567dcf92013-09-05 09:29:45 +0000567 for (unsigned i = 0; i != Current.MatchingParen->FakeRParens; ++i)
568 State.Stack.pop_back();
Daniel Jasper57981202013-09-13 09:20:45 +0000569 NewIndent = State.Stack.back().LastSpace + Style.IndentWidth;
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000570 ++NewIndentLevel;
Daniel Jaspera07aa662013-10-22 15:30:28 +0000571 BreakBeforeParameter = true;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000572 } else {
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000573 NewIndent = State.Stack.back().LastSpace;
Daniel Jasperc9689432013-10-22 15:45:58 +0000574 if (Current.opensBlockTypeList(Style)) {
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000575 NewIndent += Style.IndentWidth;
576 ++NewIndentLevel;
Daniel Jasperc9689432013-10-22 15:45:58 +0000577 } else {
578 NewIndent += Style.ContinuationIndentWidth;
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000579 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000580 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000581 const FormatToken *NextNoComment = Current.getNextNonComment();
Daniel Jasper57981202013-09-13 09:20:45 +0000582 AvoidBinPacking = Current.BlockKind == BK_Block ||
Daniel Jaspera07aa662013-10-22 15:30:28 +0000583 Current.Type == TT_ArrayInitializerLSquare ||
Daniel Jasper3c6aea72013-10-24 10:31:50 +0000584 Current.Type == TT_DictLiteral ||
Daniel Jasper57981202013-09-13 09:20:45 +0000585 (NextNoComment &&
586 NextNoComment->Type == TT_DesignatedInitializerPeriod);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000587 } else {
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000588 NewIndent = Style.ContinuationIndentWidth +
589 std::max(State.Stack.back().LastSpace,
590 State.Stack.back().StartOfFunctionCall);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000591 AvoidBinPacking = !Style.BinPackParameters ||
592 (Style.ExperimentalAutoDetectBinPacking &&
593 (Current.PackingKind == PPK_OnePerLine ||
594 (!BinPackInconclusiveFunctions &&
595 Current.PackingKind == PPK_Inconclusive)));
Daniel Jaspera07aa662013-10-22 15:30:28 +0000596 // If this '[' opens an ObjC call, determine whether all parameters fit
597 // into one line and put one per line if they don't.
598 if (Current.Type == TT_ObjCMethodExpr &&
599 getLengthToMatchingParen(Current) + State.Column >
600 getColumnLimit(State))
601 BreakBeforeParameter = true;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000602 }
603
Daniel Jasper9b3cb442013-10-18 15:23:06 +0000604 bool NoLineBreak = State.Stack.back().NoLineBreak ||
605 (Current.Type == TT_TemplateOpener &&
606 State.Stack.back().ContainsUnwrappedBuilder);
607 State.Stack.push_back(ParenState(NewIndent, NewIndentLevel,
608 State.Stack.back().LastSpace,
609 AvoidBinPacking, NoLineBreak));
Daniel Jaspera07aa662013-10-22 15:30:28 +0000610 State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000611 ++State.ParenLevel;
612 }
613
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000614 // If we encounter a closing ), ], } or >, we can remove a level from our
615 // stacks.
Daniel Jasper7143a212013-08-28 09:17:37 +0000616 if (State.Stack.size() > 1 &&
617 (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper567dcf92013-09-05 09:29:45 +0000618 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
Daniel Jasper7143a212013-08-28 09:17:37 +0000619 State.NextToken->Type == TT_TemplateCloser)) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000620 State.Stack.pop_back();
621 --State.ParenLevel;
622 }
623 if (Current.is(tok::r_square)) {
624 // If this ends the array subscript expr, reset the corresponding value.
625 const FormatToken *NextNonComment = Current.getNextNonComment();
626 if (NextNonComment && NextNonComment->isNot(tok::l_square))
627 State.Stack.back().StartOfArraySubscripts = 0;
628 }
629
630 // Remove scopes created by fake parenthesis.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000631 if (Current.isNot(tok::r_brace) ||
632 (Current.MatchingParen && Current.MatchingParen->BlockKind != BK_Block)) {
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000633 // Don't remove FakeRParens attached to r_braces that surround nested blocks
634 // as they will have been removed early (see above).
Daniel Jasper567dcf92013-09-05 09:29:45 +0000635 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
636 unsigned VariablePos = State.Stack.back().VariablePos;
637 State.Stack.pop_back();
638 State.Stack.back().VariablePos = VariablePos;
639 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000640 }
641
642 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
643 State.StartOfStringLiteral = State.Column;
644 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
645 tok::string_literal)) {
646 State.StartOfStringLiteral = 0;
647 }
648
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000649 State.Column += Current.ColumnWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000650 State.NextToken = State.NextToken->Next;
Daniel Jasperd489f8c2013-08-27 11:09:05 +0000651 unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000652 if (State.Column > getColumnLimit(State)) {
653 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
654 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
655 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000656
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000657 // If the previous has a special role, let it consume tokens as appropriate.
658 // It is necessary to start at the previous token for the only implemented
659 // role (comma separated list). That way, the decision whether or not to break
660 // after the "{" is already done and both options are tried and evaluated.
661 // FIXME: This is ugly, find a better way.
662 if (Previous && Previous->Role)
663 Penalty += Previous->Role->format(State, this, DryRun);
664
665 return Penalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000666}
667
Alexander Kornienko6f6154c2013-09-10 12:29:48 +0000668unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
669 LineState &State) {
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000670 // Break before further function parameters on all levels.
671 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
672 State.Stack[i].BreakBeforeParameter = true;
673
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000674 unsigned ColumnsUsed = State.Column;
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000675 // We can only affect layout of the first and the last line, so the penalty
676 // for all other lines is constant, and we ignore it.
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000677 State.Column = Current.LastLineColumnWidth;
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000678
Daniel Jasper567dcf92013-09-05 09:29:45 +0000679 if (ColumnsUsed > getColumnLimit(State))
680 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000681 return 0;
682}
683
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000684static bool getRawStringLiteralPrefixPostfix(StringRef Text,
685 StringRef &Prefix,
686 StringRef &Postfix) {
687 if (Text.startswith(Prefix = "R\"") || Text.startswith(Prefix = "uR\"") ||
688 Text.startswith(Prefix = "UR\"") || Text.startswith(Prefix = "u8R\"") ||
689 Text.startswith(Prefix = "LR\"")) {
690 size_t ParenPos = Text.find('(');
691 if (ParenPos != StringRef::npos) {
692 StringRef Delimiter =
693 Text.substr(Prefix.size(), ParenPos - Prefix.size());
694 Prefix = Text.substr(0, ParenPos + 1);
695 Postfix = Text.substr(Text.size() - 2 - Delimiter.size());
696 return Postfix.front() == ')' && Postfix.back() == '"' &&
697 Postfix.substr(1).startswith(Delimiter);
698 }
699 }
700 return false;
701}
702
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000703unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
704 LineState &State,
705 bool DryRun) {
Alexander Kornienko6f6154c2013-09-10 12:29:48 +0000706 // Don't break multi-line tokens other than block comments. Instead, just
707 // update the state.
708 if (Current.Type != TT_BlockComment && Current.IsMultiline)
709 return addMultilineToken(Current, State);
710
Daniel Jasper84379572013-10-30 13:54:53 +0000711 // Don't break implicit string literals.
712 if (Current.Type == TT_ImplicitStringLiteral)
713 return 0;
714
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000715 if (!Current.isOneOf(tok::string_literal, tok::wide_string_literal,
716 tok::utf8_string_literal, tok::utf16_string_literal,
717 tok::utf32_string_literal, tok::comment))
Daniel Jaspered51c022013-08-23 10:05:49 +0000718 return 0;
719
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000720 llvm::OwningPtr<BreakableToken> Token;
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000721 unsigned StartColumn = State.Column - Current.ColumnWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000722
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000723 if (Current.isOneOf(tok::string_literal, tok::wide_string_literal,
724 tok::utf8_string_literal, tok::utf16_string_literal,
725 tok::utf32_string_literal) &&
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000726 Current.Type != TT_ImplicitStringLiteral) {
Alexander Kornienkob18c2582013-10-11 21:43:05 +0000727 // Don't break string literals inside preprocessor directives (except for
728 // #define directives, as their contents are stored in separate lines and
729 // are not affected by this check).
730 // This way we avoid breaking code with line directives and unknown
731 // preprocessor directives that contain long string literals.
732 if (State.Line->Type == LT_PreprocessorDirective)
733 return 0;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000734 // Exempts unterminated string literals from line breaking. The user will
735 // likely want to terminate the string before any line breaking is done.
736 if (Current.IsUnterminatedLiteral)
737 return 0;
738
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000739 StringRef Text = Current.TokenText;
740 StringRef Prefix;
741 StringRef Postfix;
742 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
743 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
744 // reduce the overhead) for each FormatToken, which is a string, so that we
745 // don't run multiple checks here on the hot path.
746 if ((Text.endswith(Postfix = "\"") &&
747 (Text.startswith(Prefix = "\"") || Text.startswith(Prefix = "u\"") ||
748 Text.startswith(Prefix = "U\"") || Text.startswith(Prefix = "u8\"") ||
749 Text.startswith(Prefix = "L\""))) ||
750 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")")) ||
751 getRawStringLiteralPrefixPostfix(Text, Prefix, Postfix)) {
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000752 Token.reset(new BreakableStringLiteral(
753 Current, State.Line->Level, StartColumn, Prefix, Postfix,
754 State.Line->InPPDirective, Encoding, Style));
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000755 } else {
756 return 0;
757 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000758 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
759 Token.reset(new BreakableBlockComment(
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000760 Current, State.Line->Level, StartColumn, Current.OriginalColumn,
761 !Current.Previous, State.Line->InPPDirective, Encoding, Style));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000762 } else if (Current.Type == TT_LineComment &&
763 (Current.Previous == NULL ||
764 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000765 Token.reset(new BreakableLineComment(Current, State.Line->Level,
766 StartColumn, State.Line->InPPDirective,
767 Encoding, Style));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000768 } else {
769 return 0;
770 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000771 if (Current.UnbreakableTailLength >= getColumnLimit(State))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000772 return 0;
773
Daniel Jasper567dcf92013-09-05 09:29:45 +0000774 unsigned RemainingSpace =
775 getColumnLimit(State) - Current.UnbreakableTailLength;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000776 bool BreakInserted = false;
777 unsigned Penalty = 0;
778 unsigned RemainingTokenColumns = 0;
779 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
780 LineIndex != EndIndex; ++LineIndex) {
781 if (!DryRun)
782 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
783 unsigned TailOffset = 0;
784 RemainingTokenColumns =
785 Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
786 while (RemainingTokenColumns > RemainingSpace) {
787 BreakableToken::Split Split =
Daniel Jasper567dcf92013-09-05 09:29:45 +0000788 Token->getSplit(LineIndex, TailOffset, getColumnLimit(State));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000789 if (Split.first == StringRef::npos) {
790 // The last line's penalty is handled in addNextStateToQueue().
791 if (LineIndex < EndIndex - 1)
792 Penalty += Style.PenaltyExcessCharacter *
793 (RemainingTokenColumns - RemainingSpace);
794 break;
795 }
796 assert(Split.first != 0);
797 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
798 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
799 assert(NewRemainingTokenColumns < RemainingTokenColumns);
800 if (!DryRun)
801 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Daniel Jasperf5461782013-08-28 10:03:58 +0000802 Penalty += Current.SplitPenalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000803 unsigned ColumnsUsed =
804 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000805 if (ColumnsUsed > getColumnLimit(State)) {
806 Penalty += Style.PenaltyExcessCharacter *
807 (ColumnsUsed - getColumnLimit(State));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000808 }
809 TailOffset += Split.first + Split.second;
810 RemainingTokenColumns = NewRemainingTokenColumns;
811 BreakInserted = true;
812 }
813 }
814
815 State.Column = RemainingTokenColumns;
816
817 if (BreakInserted) {
818 // If we break the token inside a parameter list, we need to break before
819 // the next parameter on all levels, so that the next parameter is clearly
820 // visible. Line comments already introduce a break.
821 if (Current.Type != TT_LineComment) {
822 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
823 State.Stack[i].BreakBeforeParameter = true;
824 }
825
Daniel Jasperf5461782013-08-28 10:03:58 +0000826 Penalty += Current.is(tok::string_literal) ? Style.PenaltyBreakString
827 : Style.PenaltyBreakComment;
828
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000829 State.Stack.back().LastSpace = StartColumn;
830 }
831 return Penalty;
832}
833
Daniel Jasper567dcf92013-09-05 09:29:45 +0000834unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000835 // In preprocessor directives reserve two chars for trailing " \"
Daniel Jasper567dcf92013-09-05 09:29:45 +0000836 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000837}
838
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000839bool ContinuationIndenter::NextIsMultilineString(const LineState &State) {
840 const FormatToken &Current = *State.NextToken;
841 if (!Current.is(tok::string_literal))
842 return false;
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000843 // We never consider raw string literals "multiline" for the purpose of
844 // AlwaysBreakBeforeMultilineStrings implementation.
845 if (Current.TokenText.startswith("R\""))
846 return false;
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000847 if (Current.IsMultiline)
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000848 return true;
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000849 if (Current.getNextNonComment() &&
850 Current.getNextNonComment()->is(tok::string_literal))
851 return true; // Implicit concatenation.
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000852 if (State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000853 Style.ColumnLimit)
854 return true; // String will be split.
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000855 return false;
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000856}
857
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000858} // namespace format
859} // namespace clang