blob: 442f9fa85059aaf1644d6c4922542289b56820c4 [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) ||
Daniel Jasper1a896a52013-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 Jasper6b2afe42013-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 Jasper4df1ff92013-08-23 11:57:34 +0000137 State.Column > State.Stack.back().Indent && // Breaking saves columns.
Daniel Jasper49c77b22013-10-18 16:47:55 +0000138 !Previous.isOneOf(tok::kw_return, tok::lessless) &&
139 Previous.Type != TT_InlineASMColon && NextIsMultilineString(State))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000140 return true;
Daniel Jasper3c6aea72013-10-24 10:31:50 +0000141 if (((Previous.Type == TT_DictLiteral && Previous.is(tok::l_brace)) ||
Daniel Jaspera07aa662013-10-22 15:30:28 +0000142 Previous.Type == TT_ArrayInitializerLSquare) &&
Daniel Jaspera53bbae2013-10-20 16:45:46 +0000143 getLengthToMatchingParen(Previous) + State.Column > getColumnLimit(State))
144 return true;
Daniel Jasper6b2afe42013-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 Jasperdb4813a2013-09-06 08:08:14 +0000164 Previous.Previous && Previous.Previous->EndsBinaryExpression;
Daniel Jasper6b2afe42013-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
180 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
181 // out whether it is the first parameter. Clean this up.
182 if (Current.Type == TT_ObjCSelectorName &&
183 Current.LongestObjCSelectorName == 0 &&
184 State.Stack.back().BreakBeforeParameter)
185 return true;
186 if ((Current.Type == TT_CtorInitializerColon ||
Daniel Jasper6e7f1932013-10-09 15:06:17 +0000187 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0 &&
188 !Current.isTrailingComment())))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000189 return true;
190
191 if ((Current.Type == TT_StartOfName || Current.is(tok::kw_operator)) &&
Daniel Jasper567dcf92013-09-05 09:29:45 +0000192 State.Line->MightBeFunctionDecl &&
193 State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000194 return true;
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000195 if (startsSegmentOfBuilderTypeCall(Current) &&
Daniel Jaspereb331832013-08-30 07:12:40 +0000196 (State.Stack.back().CallContinuation != 0 ||
197 (State.Stack.back().BreakBeforeParameter &&
198 State.Stack.back().ContainsUnwrappedBuilder)))
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000199 return true;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000200 return false;
201}
202
203unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000204 bool DryRun,
205 unsigned ExtraSpaces) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000206 const FormatToken &Current = *State.NextToken;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000207
Daniel Jasper84379572013-10-30 13:54:53 +0000208 if (State.Stack.size() == 0 ||
209 (Current.Type == TT_ImplicitStringLiteral &&
210 (Current.Previous->Tok.getIdentifierInfo() == NULL ||
211 Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
212 tok::pp_not_keyword))) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000213 // FIXME: Is this correct?
214 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
215 State.NextToken->WhitespaceRange.getEnd()) -
216 SourceMgr.getSpellingColumnNumber(
217 State.NextToken->WhitespaceRange.getBegin());
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000218 State.Column += WhitespaceLength + State.NextToken->ColumnWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000219 State.NextToken = State.NextToken->Next;
220 return 0;
221 }
222
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000223 unsigned Penalty = 0;
224 if (Newline)
225 Penalty = addTokenOnNewLine(State, DryRun);
226 else
227 addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
228
229 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
230}
231
232void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
233 unsigned ExtraSpaces) {
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000234 FormatToken &Current = *State.NextToken;
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000235 const FormatToken &Previous = *State.NextToken->Previous;
236 if (Current.is(tok::equal) &&
237 (State.Line->First->is(tok::kw_for) || State.ParenLevel == 0) &&
238 State.Stack.back().VariablePos == 0) {
239 State.Stack.back().VariablePos = State.Column;
240 // Move over * and & if they are bound to the variable name.
241 const FormatToken *Tok = &Previous;
242 while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
243 State.Stack.back().VariablePos -= Tok->ColumnWidth;
244 if (Tok->SpacesRequiredBefore != 0)
245 break;
246 Tok = Tok->Previous;
247 }
248 if (Previous.PartOfMultiVariableDeclStmt)
249 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
250 }
251
252 unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
253
254 if (!DryRun)
255 Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, /*IndentLevel=*/0,
256 Spaces, State.Column + Spaces);
257
258 if (Current.Type == TT_ObjCSelectorName && State.Stack.back().ColonPos == 0) {
259 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
260 State.Column + Spaces + Current.ColumnWidth)
261 State.Stack.back().ColonPos =
262 State.Stack.back().Indent + Current.LongestObjCSelectorName;
263 else
264 State.Stack.back().ColonPos = State.Column + Spaces + Current.ColumnWidth;
265 }
266
267 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
268 Current.Type != TT_LineComment)
269 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper19ccb122013-10-08 05:11:18 +0000270 if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000271 State.Stack.back().NoLineBreak = true;
272 if (startsSegmentOfBuilderTypeCall(Current))
273 State.Stack.back().ContainsUnwrappedBuilder = true;
274
275 State.Column += Spaces;
276 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
277 // Treat the condition inside an if as if it was a second function
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000278 // parameter, i.e. let nested calls have a continuation indent.
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000279 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
280 else if (Previous.is(tok::comma))
281 State.Stack.back().LastSpace = State.Column;
282 else if ((Previous.Type == TT_BinaryOperator ||
283 Previous.Type == TT_ConditionalExpr ||
284 Previous.Type == TT_UnaryOperator ||
285 Previous.Type == TT_CtorInitializerColon) &&
286 (Previous.getPrecedence() != prec::Assignment ||
287 Current.StartsBinaryExpression))
288 // Always indent relative to the RHS of the expression unless this is a
289 // simple assignment without binary expression on the RHS. Also indent
290 // relative to unary operators and the colons of constructor initializers.
291 State.Stack.back().LastSpace = State.Column;
Daniel Jaspercea014b2013-10-08 16:24:07 +0000292 else if (Previous.Type == TT_InheritanceColon) {
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000293 State.Stack.back().Indent = State.Column;
Daniel Jaspercea014b2013-10-08 16:24:07 +0000294 State.Stack.back().LastSpace = State.Column;
295 } else if (Previous.opensScope()) {
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000296 // If a function has a trailing call, indent all parameters from the
297 // opening parenthesis. This avoids confusing indents like:
298 // OuterFunction(InnerFunctionCall( // break
299 // ParameterToInnerFunction)) // break
300 // .SecondInnerFunctionCall();
301 bool HasTrailingCall = false;
302 if (Previous.MatchingParen) {
303 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
304 HasTrailingCall = Next && Next->isMemberAccess();
305 }
306 if (HasTrailingCall &&
307 State.Stack[State.Stack.size() - 2].CallContinuation == 0)
308 State.Stack.back().LastSpace = State.Column;
309 }
310}
311
312unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
313 bool DryRun) {
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000314 FormatToken &Current = *State.NextToken;
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000315 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000316 // If we are continuing an expression, we want to use the continuation indent.
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000317 unsigned ContinuationIndent =
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000318 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
319 Style.ContinuationIndentWidth;
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000320 // Extra penalty that needs to be added because of the way certain line
321 // breaks are chosen.
322 unsigned Penalty = 0;
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000323
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000324 const FormatToken *PreviousNonComment =
325 State.NextToken->getPreviousNonComment();
326 // The first line break on any ParenLevel causes an extra penalty in order
327 // prefer similar line breaks.
328 if (!State.Stack.back().ContainsLineBreak)
329 Penalty += 15;
330 State.Stack.back().ContainsLineBreak = true;
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000331
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000332 Penalty += State.NextToken->SplitPenalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000333
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000334 // Breaking before the first "<<" is generally not desirable if the LHS is
335 // short.
336 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0 &&
337 State.Column <= Style.ColumnLimit / 2)
338 Penalty += Style.PenaltyBreakFirstLessLess;
339
340 if (Current.is(tok::l_brace) && Current.BlockKind == BK_Block) {
341 State.Column = State.FirstIndent;
Daniel Jaspera07aa662013-10-22 15:30:28 +0000342 } else if (Current.isOneOf(tok::r_brace, tok::r_square)) {
Daniel Jasper16a8b0e2013-11-07 14:02:28 +0000343 if (Current.closesBlockTypeList(Style) ||
344 (Current.MatchingParen &&
345 Current.MatchingParen->BlockKind == BK_BracedInit))
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000346 State.Column = State.Stack[State.Stack.size() - 2].LastSpace;
347 else
Daniel Jasper57981202013-09-13 09:20:45 +0000348 State.Column = State.FirstIndent;
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000349 } else if (Current.is(tok::string_literal) &&
350 State.StartOfStringLiteral != 0) {
351 State.Column = State.StartOfStringLiteral;
352 State.Stack.back().BreakBeforeParameter = true;
353 } else if (Current.is(tok::lessless) &&
354 State.Stack.back().FirstLessLess != 0) {
355 State.Column = State.Stack.back().FirstLessLess;
356 } else if (Current.isMemberAccess()) {
357 if (State.Stack.back().CallContinuation == 0) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000358 State.Column = ContinuationIndent;
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000359 State.Stack.back().CallContinuation = State.Column;
360 } else {
361 State.Column = State.Stack.back().CallContinuation;
362 }
Daniel Jasper1a896a52013-11-08 00:57:11 +0000363 } else if (State.Stack.back().QuestionColumn != 0 &&
364 (Current.Type == TT_ConditionalExpr ||
365 Previous.Type == TT_ConditionalExpr)) {
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000366 State.Column = State.Stack.back().QuestionColumn;
367 } else if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0) {
368 State.Column = State.Stack.back().VariablePos;
369 } else if ((PreviousNonComment &&
370 PreviousNonComment->ClosesTemplateDeclaration) ||
371 ((Current.Type == TT_StartOfName ||
372 Current.is(tok::kw_operator)) &&
373 State.ParenLevel == 0 &&
374 (!Style.IndentFunctionDeclarationAfterType ||
375 State.Line->StartsDefinition))) {
376 State.Column = State.Stack.back().Indent;
377 } else if (Current.Type == TT_ObjCSelectorName) {
378 if (State.Stack.back().ColonPos > Current.ColumnWidth) {
379 State.Column = State.Stack.back().ColonPos - Current.ColumnWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000380 } else {
381 State.Column = State.Stack.back().Indent;
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000382 State.Stack.back().ColonPos = State.Column + Current.ColumnWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000383 }
Daniel Jaspera07aa662013-10-22 15:30:28 +0000384 } else if (Current.Type == TT_ArraySubscriptLSquare) {
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000385 if (State.Stack.back().StartOfArraySubscripts != 0)
386 State.Column = State.Stack.back().StartOfArraySubscripts;
387 else
388 State.Column = ContinuationIndent;
389 } else if (Current.Type == TT_StartOfName ||
390 Previous.isOneOf(tok::coloncolon, tok::equal) ||
391 Previous.Type == TT_ObjCMethodExpr) {
392 State.Column = ContinuationIndent;
393 } else if (Current.Type == TT_CtorInitializerColon) {
394 State.Column = State.FirstIndent + Style.ConstructorInitializerIndentWidth;
395 } else if (Current.Type == TT_CtorInitializerComma) {
396 State.Column = State.Stack.back().Indent;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000397 } else {
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000398 State.Column = State.Stack.back().Indent;
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000399 // Ensure that we fall back to the continuation indent width instead of just
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000400 // flushing continuations left.
Daniel Jasperdc837b12013-10-30 14:04:10 +0000401 if (State.Column == State.FirstIndent &&
402 PreviousNonComment->isNot(tok::r_brace))
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000403 State.Column += Style.ContinuationIndentWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000404 }
405
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000406 if ((Previous.isOneOf(tok::comma, tok::semi) &&
407 !State.Stack.back().AvoidBinPacking) ||
408 Previous.Type == TT_BinaryOperator)
409 State.Stack.back().BreakBeforeParameter = false;
410 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
411 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper1a896a52013-11-08 00:57:11 +0000412 if (Current.is(tok::question) ||
413 (PreviousNonComment && PreviousNonComment->is(tok::question)))
414 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000415
416 if (!DryRun) {
417 unsigned Newlines = 1;
418 if (Current.is(tok::comment))
419 Newlines = std::max(Newlines, std::min(Current.NewlinesBefore,
420 Style.MaxEmptyLinesToKeep + 1));
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000421 Whitespaces.replaceWhitespace(Current, Newlines,
422 State.Stack.back().IndentLevel, State.Column,
423 State.Column, State.Line->InPPDirective);
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000424 }
425
426 if (!Current.isTrailingComment())
427 State.Stack.back().LastSpace = State.Column;
428 if (Current.isMemberAccess())
429 State.Stack.back().LastSpace += Current.ColumnWidth;
430 State.StartOfLineLevel = State.ParenLevel;
431 State.LowestLevelOnLine = State.ParenLevel;
432
433 // Any break on this level means that the parent level has been broken
434 // and we need to avoid bin packing there.
435 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
436 State.Stack[i].BreakBeforeParameter = true;
437 }
438 const FormatToken *TokenBefore = Current.getPreviousNonComment();
439 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
440 TokenBefore->Type != TT_TemplateCloser &&
441 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
442 State.Stack.back().BreakBeforeParameter = true;
443
Daniel Jaspera07aa662013-10-22 15:30:28 +0000444 // If we break after { or the [ of an array initializer, we should also break
445 // before the corresponding } or ].
446 if (Previous.is(tok::l_brace) || Previous.Type == TT_ArrayInitializerLSquare)
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000447 State.Stack.back().BreakBeforeClosingBrace = true;
448
449 if (State.Stack.back().AvoidBinPacking) {
450 // If we are breaking after '(', '{', '<', this is not bin packing
451 // unless AllowAllParametersOfDeclarationOnNextLine is false.
452 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
453 Previous.Type == TT_BinaryOperator) ||
454 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
455 State.Line->MustBeDeclaration))
456 State.Stack.back().BreakBeforeParameter = true;
457 }
458
459 return Penalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000460}
461
462unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
463 bool DryRun, bool Newline) {
464 const FormatToken &Current = *State.NextToken;
465 assert(State.Stack.size());
466
467 if (Current.Type == TT_InheritanceColon)
468 State.Stack.back().AvoidBinPacking = true;
469 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
470 State.Stack.back().FirstLessLess = State.Column;
Daniel Jaspera07aa662013-10-22 15:30:28 +0000471 if (Current.Type == TT_ArraySubscriptLSquare &&
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000472 State.Stack.back().StartOfArraySubscripts == 0)
473 State.Stack.back().StartOfArraySubscripts = State.Column;
Daniel Jasper1a896a52013-11-08 00:57:11 +0000474 if ((Current.is(tok::question) && Style.BreakBeforeTernaryOperators) ||
475 (Current.getPreviousNonComment() && Current.isNot(tok::colon) &&
476 Current.getPreviousNonComment()->is(tok::question) &&
477 !Style.BreakBeforeTernaryOperators))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000478 State.Stack.back().QuestionColumn = State.Column;
479 if (!Current.opensScope() && !Current.closesScope())
480 State.LowestLevelOnLine =
481 std::min(State.LowestLevelOnLine, State.ParenLevel);
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000482 if (Current.isMemberAccess())
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000483 State.Stack.back().StartOfFunctionCall =
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000484 Current.LastInChainOfCalls ? 0 : State.Column + Current.ColumnWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000485 if (Current.Type == TT_CtorInitializerColon) {
486 // Indent 2 from the column, so:
487 // SomeClass::SomeClass()
488 // : First(...), ...
489 // Next(...)
490 // ^ line up here.
491 State.Stack.back().Indent =
492 State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
493 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
494 State.Stack.back().AvoidBinPacking = true;
495 State.Stack.back().BreakBeforeParameter = false;
496 }
497
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000498 // In ObjC method declaration we align on the ":" of parameters, but we need
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000499 // to ensure that we indent parameters on subsequent lines by at least our
500 // continuation indent width.
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000501 if (Current.Type == TT_ObjCMethodSpecifier)
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000502 State.Stack.back().Indent += Style.ContinuationIndentWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000503
504 // Insert scopes created by fake parenthesis.
505 const FormatToken *Previous = Current.getPreviousNonComment();
506 // Don't add extra indentation for the first fake parenthesis after
507 // 'return', assignements or opening <({[. The indentation for these cases
508 // is special cased.
509 bool SkipFirstExtraIndent =
Daniel Jasperf78bf4a2013-09-30 08:29:03 +0000510 (Previous && (Previous->opensScope() || Previous->is(tok::kw_return) ||
Daniel Jasper966e6d32013-11-07 19:23:49 +0000511 Previous->getPrecedence() == prec::Assignment ||
512 Previous->Type == TT_ObjCMethodExpr));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000513 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
514 I = Current.FakeLParens.rbegin(),
515 E = Current.FakeLParens.rend();
516 I != E; ++I) {
517 ParenState NewParenState = State.Stack.back();
518 NewParenState.ContainsLineBreak = false;
Daniel Jasperf78bf4a2013-09-30 08:29:03 +0000519
520 // Indent from 'LastSpace' unless this the fake parentheses encapsulating a
521 // builder type call after 'return'. If such a call is line-wrapped, we
522 // commonly just want to indent from the start of the line.
523 if (!Previous || Previous->isNot(tok::kw_return) || *I > 0)
524 NewParenState.Indent =
525 std::max(std::max(State.Column, NewParenState.Indent),
526 State.Stack.back().LastSpace);
527
Daniel Jasper567dcf92013-09-05 09:29:45 +0000528 // Do not indent relative to the fake parentheses inserted for "." or "->".
529 // This is a special case to make the following to statements consistent:
530 // OuterFunction(InnerFunctionCall( // break
531 // ParameterToInnerFunction));
532 // OuterFunction(SomeObject.InnerFunctionCall( // break
533 // ParameterToInnerFunction));
534 if (*I > prec::Unknown)
535 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000536
537 // Always indent conditional expressions. Never indent expression where
538 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
539 // prec::Assignment) as those have different indentation rules. Indent
540 // other expression, unless the indentation needs to be skipped.
541 if (*I == prec::Conditional ||
542 (!SkipFirstExtraIndent && *I > prec::Assignment &&
543 !Style.BreakBeforeBinaryOperators))
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000544 NewParenState.Indent += Style.ContinuationIndentWidth;
Daniel Jaspera07aa662013-10-22 15:30:28 +0000545 if ((Previous && !Previous->opensScope()) || *I > prec::Comma)
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000546 NewParenState.BreakBeforeParameter = false;
547 State.Stack.push_back(NewParenState);
548 SkipFirstExtraIndent = false;
549 }
550
551 // If we encounter an opening (, [, { or <, we add a level to our stacks to
552 // prepare for the following tokens.
553 if (Current.opensScope()) {
554 unsigned NewIndent;
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000555 unsigned NewIndentLevel = State.Stack.back().IndentLevel;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000556 bool AvoidBinPacking;
Daniel Jaspera07aa662013-10-22 15:30:28 +0000557 bool BreakBeforeParameter = false;
558 if (Current.is(tok::l_brace) ||
559 Current.Type == TT_ArrayInitializerLSquare) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000560 if (Current.MatchingParen && Current.BlockKind == BK_Block) {
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000561 // If this is an l_brace starting a nested block, we pretend (wrt. to
562 // indentation) that we already consumed the corresponding r_brace.
563 // Thus, we remove all ParenStates caused bake fake parentheses that end
564 // at the r_brace. The net effect of this is that we don't indent
565 // relative to the l_brace, if the nested block is the last parameter of
566 // a function. For example, this formats:
567 //
568 // SomeFunction(a, [] {
569 // f(); // break
570 // });
571 //
572 // instead of:
573 // SomeFunction(a, [] {
574 // f(); // break
575 // });
Daniel Jasper567dcf92013-09-05 09:29:45 +0000576 for (unsigned i = 0; i != Current.MatchingParen->FakeRParens; ++i)
577 State.Stack.pop_back();
Daniel Jasper57981202013-09-13 09:20:45 +0000578 NewIndent = State.Stack.back().LastSpace + Style.IndentWidth;
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000579 ++NewIndentLevel;
Daniel Jaspera07aa662013-10-22 15:30:28 +0000580 BreakBeforeParameter = true;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000581 } else {
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000582 NewIndent = State.Stack.back().LastSpace;
Daniel Jasperc9689432013-10-22 15:45:58 +0000583 if (Current.opensBlockTypeList(Style)) {
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000584 NewIndent += Style.IndentWidth;
585 ++NewIndentLevel;
Daniel Jasperc9689432013-10-22 15:45:58 +0000586 } else {
587 NewIndent += Style.ContinuationIndentWidth;
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000588 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000589 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000590 const FormatToken *NextNoComment = Current.getNextNonComment();
Daniel Jasper57981202013-09-13 09:20:45 +0000591 AvoidBinPacking = Current.BlockKind == BK_Block ||
Daniel Jaspera07aa662013-10-22 15:30:28 +0000592 Current.Type == TT_ArrayInitializerLSquare ||
Daniel Jasper3c6aea72013-10-24 10:31:50 +0000593 Current.Type == TT_DictLiteral ||
Daniel Jasper57981202013-09-13 09:20:45 +0000594 (NextNoComment &&
595 NextNoComment->Type == TT_DesignatedInitializerPeriod);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000596 } else {
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000597 NewIndent = Style.ContinuationIndentWidth +
598 std::max(State.Stack.back().LastSpace,
599 State.Stack.back().StartOfFunctionCall);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000600 AvoidBinPacking = !Style.BinPackParameters ||
601 (Style.ExperimentalAutoDetectBinPacking &&
602 (Current.PackingKind == PPK_OnePerLine ||
603 (!BinPackInconclusiveFunctions &&
604 Current.PackingKind == PPK_Inconclusive)));
Daniel Jaspera07aa662013-10-22 15:30:28 +0000605 // If this '[' opens an ObjC call, determine whether all parameters fit
606 // into one line and put one per line if they don't.
607 if (Current.Type == TT_ObjCMethodExpr &&
608 getLengthToMatchingParen(Current) + State.Column >
609 getColumnLimit(State))
610 BreakBeforeParameter = true;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000611 }
612
Daniel Jasper9b3cb442013-10-18 15:23:06 +0000613 bool NoLineBreak = State.Stack.back().NoLineBreak ||
614 (Current.Type == TT_TemplateOpener &&
615 State.Stack.back().ContainsUnwrappedBuilder);
616 State.Stack.push_back(ParenState(NewIndent, NewIndentLevel,
617 State.Stack.back().LastSpace,
618 AvoidBinPacking, NoLineBreak));
Daniel Jaspera07aa662013-10-22 15:30:28 +0000619 State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000620 ++State.ParenLevel;
621 }
622
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000623 // If we encounter a closing ), ], } or >, we can remove a level from our
624 // stacks.
Daniel Jasper7143a212013-08-28 09:17:37 +0000625 if (State.Stack.size() > 1 &&
626 (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper567dcf92013-09-05 09:29:45 +0000627 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
Daniel Jasper7143a212013-08-28 09:17:37 +0000628 State.NextToken->Type == TT_TemplateCloser)) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000629 State.Stack.pop_back();
630 --State.ParenLevel;
631 }
632 if (Current.is(tok::r_square)) {
633 // If this ends the array subscript expr, reset the corresponding value.
634 const FormatToken *NextNonComment = Current.getNextNonComment();
635 if (NextNonComment && NextNonComment->isNot(tok::l_square))
636 State.Stack.back().StartOfArraySubscripts = 0;
637 }
638
639 // Remove scopes created by fake parenthesis.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000640 if (Current.isNot(tok::r_brace) ||
641 (Current.MatchingParen && Current.MatchingParen->BlockKind != BK_Block)) {
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000642 // Don't remove FakeRParens attached to r_braces that surround nested blocks
643 // as they will have been removed early (see above).
Daniel Jasper567dcf92013-09-05 09:29:45 +0000644 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
645 unsigned VariablePos = State.Stack.back().VariablePos;
646 State.Stack.pop_back();
647 State.Stack.back().VariablePos = VariablePos;
648 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000649 }
650
651 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
652 State.StartOfStringLiteral = State.Column;
653 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
654 tok::string_literal)) {
655 State.StartOfStringLiteral = 0;
656 }
657
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000658 State.Column += Current.ColumnWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000659 State.NextToken = State.NextToken->Next;
Daniel Jasperd489f8c2013-08-27 11:09:05 +0000660 unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000661 if (State.Column > getColumnLimit(State)) {
662 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
663 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
664 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000665
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000666 // If the previous has a special role, let it consume tokens as appropriate.
667 // It is necessary to start at the previous token for the only implemented
668 // role (comma separated list). That way, the decision whether or not to break
669 // after the "{" is already done and both options are tried and evaluated.
670 // FIXME: This is ugly, find a better way.
671 if (Previous && Previous->Role)
672 Penalty += Previous->Role->format(State, this, DryRun);
673
674 return Penalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000675}
676
Alexander Kornienko6f6154c2013-09-10 12:29:48 +0000677unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
678 LineState &State) {
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000679 // Break before further function parameters on all levels.
680 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
681 State.Stack[i].BreakBeforeParameter = true;
682
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000683 unsigned ColumnsUsed = State.Column;
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000684 // We can only affect layout of the first and the last line, so the penalty
685 // for all other lines is constant, and we ignore it.
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000686 State.Column = Current.LastLineColumnWidth;
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000687
Daniel Jasper567dcf92013-09-05 09:29:45 +0000688 if (ColumnsUsed > getColumnLimit(State))
689 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000690 return 0;
691}
692
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000693static bool getRawStringLiteralPrefixPostfix(StringRef Text,
694 StringRef &Prefix,
695 StringRef &Postfix) {
696 if (Text.startswith(Prefix = "R\"") || Text.startswith(Prefix = "uR\"") ||
697 Text.startswith(Prefix = "UR\"") || Text.startswith(Prefix = "u8R\"") ||
698 Text.startswith(Prefix = "LR\"")) {
699 size_t ParenPos = Text.find('(');
700 if (ParenPos != StringRef::npos) {
701 StringRef Delimiter =
702 Text.substr(Prefix.size(), ParenPos - Prefix.size());
703 Prefix = Text.substr(0, ParenPos + 1);
704 Postfix = Text.substr(Text.size() - 2 - Delimiter.size());
705 return Postfix.front() == ')' && Postfix.back() == '"' &&
706 Postfix.substr(1).startswith(Delimiter);
707 }
708 }
709 return false;
710}
711
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000712unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
713 LineState &State,
714 bool DryRun) {
Alexander Kornienko6f6154c2013-09-10 12:29:48 +0000715 // Don't break multi-line tokens other than block comments. Instead, just
716 // update the state.
717 if (Current.Type != TT_BlockComment && Current.IsMultiline)
718 return addMultilineToken(Current, State);
719
Daniel Jasper84379572013-10-30 13:54:53 +0000720 // Don't break implicit string literals.
721 if (Current.Type == TT_ImplicitStringLiteral)
722 return 0;
723
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000724 if (!Current.isOneOf(tok::string_literal, tok::wide_string_literal,
725 tok::utf8_string_literal, tok::utf16_string_literal,
726 tok::utf32_string_literal, tok::comment))
Daniel Jaspered51c022013-08-23 10:05:49 +0000727 return 0;
728
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000729 llvm::OwningPtr<BreakableToken> Token;
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000730 unsigned StartColumn = State.Column - Current.ColumnWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000731
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000732 if (Current.isOneOf(tok::string_literal, tok::wide_string_literal,
733 tok::utf8_string_literal, tok::utf16_string_literal,
734 tok::utf32_string_literal) &&
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000735 Current.Type != TT_ImplicitStringLiteral) {
Alexander Kornienkob18c2582013-10-11 21:43:05 +0000736 // Don't break string literals inside preprocessor directives (except for
737 // #define directives, as their contents are stored in separate lines and
738 // are not affected by this check).
739 // This way we avoid breaking code with line directives and unknown
740 // preprocessor directives that contain long string literals.
741 if (State.Line->Type == LT_PreprocessorDirective)
742 return 0;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000743 // Exempts unterminated string literals from line breaking. The user will
744 // likely want to terminate the string before any line breaking is done.
745 if (Current.IsUnterminatedLiteral)
746 return 0;
747
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000748 StringRef Text = Current.TokenText;
749 StringRef Prefix;
750 StringRef Postfix;
751 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
752 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
753 // reduce the overhead) for each FormatToken, which is a string, so that we
754 // don't run multiple checks here on the hot path.
755 if ((Text.endswith(Postfix = "\"") &&
756 (Text.startswith(Prefix = "\"") || Text.startswith(Prefix = "u\"") ||
757 Text.startswith(Prefix = "U\"") || Text.startswith(Prefix = "u8\"") ||
758 Text.startswith(Prefix = "L\""))) ||
759 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")")) ||
760 getRawStringLiteralPrefixPostfix(Text, Prefix, Postfix)) {
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000761 Token.reset(new BreakableStringLiteral(
762 Current, State.Line->Level, StartColumn, Prefix, Postfix,
763 State.Line->InPPDirective, Encoding, Style));
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000764 } else {
765 return 0;
766 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000767 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
768 Token.reset(new BreakableBlockComment(
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000769 Current, State.Line->Level, StartColumn, Current.OriginalColumn,
770 !Current.Previous, State.Line->InPPDirective, Encoding, Style));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000771 } else if (Current.Type == TT_LineComment &&
772 (Current.Previous == NULL ||
773 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000774 Token.reset(new BreakableLineComment(Current, State.Line->Level,
775 StartColumn, State.Line->InPPDirective,
776 Encoding, Style));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000777 } else {
778 return 0;
779 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000780 if (Current.UnbreakableTailLength >= getColumnLimit(State))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000781 return 0;
782
Daniel Jasper567dcf92013-09-05 09:29:45 +0000783 unsigned RemainingSpace =
784 getColumnLimit(State) - Current.UnbreakableTailLength;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000785 bool BreakInserted = false;
786 unsigned Penalty = 0;
787 unsigned RemainingTokenColumns = 0;
788 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
789 LineIndex != EndIndex; ++LineIndex) {
790 if (!DryRun)
791 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
792 unsigned TailOffset = 0;
793 RemainingTokenColumns =
794 Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
795 while (RemainingTokenColumns > RemainingSpace) {
796 BreakableToken::Split Split =
Daniel Jasper567dcf92013-09-05 09:29:45 +0000797 Token->getSplit(LineIndex, TailOffset, getColumnLimit(State));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000798 if (Split.first == StringRef::npos) {
799 // The last line's penalty is handled in addNextStateToQueue().
800 if (LineIndex < EndIndex - 1)
801 Penalty += Style.PenaltyExcessCharacter *
802 (RemainingTokenColumns - RemainingSpace);
803 break;
804 }
805 assert(Split.first != 0);
806 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
807 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
808 assert(NewRemainingTokenColumns < RemainingTokenColumns);
809 if (!DryRun)
810 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Daniel Jasperf5461782013-08-28 10:03:58 +0000811 Penalty += Current.SplitPenalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000812 unsigned ColumnsUsed =
813 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000814 if (ColumnsUsed > getColumnLimit(State)) {
815 Penalty += Style.PenaltyExcessCharacter *
816 (ColumnsUsed - getColumnLimit(State));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000817 }
818 TailOffset += Split.first + Split.second;
819 RemainingTokenColumns = NewRemainingTokenColumns;
820 BreakInserted = true;
821 }
822 }
823
824 State.Column = RemainingTokenColumns;
825
826 if (BreakInserted) {
827 // If we break the token inside a parameter list, we need to break before
828 // the next parameter on all levels, so that the next parameter is clearly
829 // visible. Line comments already introduce a break.
830 if (Current.Type != TT_LineComment) {
831 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
832 State.Stack[i].BreakBeforeParameter = true;
833 }
834
Daniel Jasperf5461782013-08-28 10:03:58 +0000835 Penalty += Current.is(tok::string_literal) ? Style.PenaltyBreakString
836 : Style.PenaltyBreakComment;
837
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000838 State.Stack.back().LastSpace = StartColumn;
839 }
840 return Penalty;
841}
842
Daniel Jasper567dcf92013-09-05 09:29:45 +0000843unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000844 // In preprocessor directives reserve two chars for trailing " \"
Daniel Jasper567dcf92013-09-05 09:29:45 +0000845 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000846}
847
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000848bool ContinuationIndenter::NextIsMultilineString(const LineState &State) {
849 const FormatToken &Current = *State.NextToken;
850 if (!Current.is(tok::string_literal))
851 return false;
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000852 // We never consider raw string literals "multiline" for the purpose of
853 // AlwaysBreakBeforeMultilineStrings implementation.
854 if (Current.TokenText.startswith("R\""))
855 return false;
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000856 if (Current.IsMultiline)
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000857 return true;
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000858 if (Current.getNextNonComment() &&
859 Current.getNextNonComment()->is(tok::string_literal))
860 return true; // Implicit concatenation.
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000861 if (State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000862 Style.ColumnLimit)
863 return true; // String will be split.
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000864 return false;
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000865}
866
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000867} // namespace format
868} // namespace clang