blob: e8dc8d4a7f11cf606020d5aa62328b983f870ed9 [file] [log] [blame]
Daniel Jasperde0328a2013-08-16 11:20:30 +00001//===--- ContinuationIndenter.cpp - Format C++ code -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements the continuation indenter.
12///
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "format-formatter"
16
17#include "BreakableToken.h"
18#include "ContinuationIndenter.h"
19#include "WhitespaceManager.h"
20#include "clang/Basic/OperatorPrecedence.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Format/Format.h"
23#include "llvm/Support/Debug.h"
24#include <string>
25
26namespace clang {
27namespace format {
28
29// Returns the length of everything up to the first possible line break after
30// the ), ], } or > matching \c Tok.
31static unsigned getLengthToMatchingParen(const FormatToken &Tok) {
32 if (Tok.MatchingParen == NULL)
33 return 0;
34 FormatToken *End = Tok.MatchingParen;
35 while (End->Next && !End->Next->CanBreakBefore) {
36 End = End->Next;
37 }
38 return End->TotalLength - Tok.TotalLength + 1;
39}
40
Daniel Jasper4c6e0052013-08-27 14:24:43 +000041// Returns \c true if \c Tok is the "." or "->" of a call and starts the next
42// segment of a builder type call.
43static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) {
44 return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope();
45}
46
Daniel Jasperec01cd62013-10-08 05:11:18 +000047// Returns \c true if \c Current starts a new parameter.
48static bool startsNextParameter(const FormatToken &Current,
49 const FormatStyle &Style) {
50 const FormatToken &Previous = *Current.Previous;
51 if (Current.Type == TT_CtorInitializerComma &&
52 Style.BreakConstructorInitializersBeforeComma)
53 return true;
54 return Previous.is(tok::comma) && !Current.isTrailingComment() &&
55 (Previous.Type != TT_CtorInitializerComma ||
56 !Style.BreakConstructorInitializersBeforeComma);
57}
58
Daniel Jasperde0328a2013-08-16 11:20:30 +000059ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,
60 SourceManager &SourceMgr,
Daniel Jasperde0328a2013-08-16 11:20:30 +000061 WhitespaceManager &Whitespaces,
62 encoding::Encoding Encoding,
63 bool BinPackInconclusiveFunctions)
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000064 : Style(Style), SourceMgr(SourceMgr), Whitespaces(Whitespaces),
65 Encoding(Encoding),
Daniel Jasperde0328a2013-08-16 11:20:30 +000066 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions) {}
67
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000068LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
Daniel Jasper1c5d9df2013-09-06 07:54:20 +000069 const AnnotatedLine *Line,
70 bool DryRun) {
Daniel Jasperde0328a2013-08-16 11:20:30 +000071 LineState State;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000072 State.FirstIndent = FirstIndent;
Daniel Jasperde0328a2013-08-16 11:20:30 +000073 State.Column = FirstIndent;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000074 State.Line = Line;
75 State.NextToken = Line->First;
Alexander Kornienkoe2e03872013-10-14 00:46:35 +000076 State.Stack.push_back(ParenState(FirstIndent, Line->Level, FirstIndent,
Daniel Jasperde0328a2013-08-16 11:20:30 +000077 /*AvoidBinPacking=*/false,
78 /*NoLineBreak=*/false));
79 State.LineContainsContinuedForLoopSection = false;
80 State.ParenLevel = 0;
81 State.StartOfStringLiteral = 0;
82 State.StartOfLineLevel = State.ParenLevel;
83 State.LowestLevelOnLine = State.ParenLevel;
84 State.IgnoreStackForComparison = false;
85
86 // The first token has already been indented and thus consumed.
Daniel Jasper1c5d9df2013-09-06 07:54:20 +000087 moveStateToNextToken(State, DryRun, /*Newline=*/false);
Daniel Jasperde0328a2013-08-16 11:20:30 +000088 return State;
89}
90
91bool ContinuationIndenter::canBreak(const LineState &State) {
92 const FormatToken &Current = *State.NextToken;
93 const FormatToken &Previous = *Current.Previous;
94 assert(&Previous == Current.Previous);
Daniel Jasper1db6c382013-10-22 15:30:28 +000095 if (!Current.CanBreakBefore && !(State.Stack.back().BreakBeforeClosingBrace &&
96 Current.closesBlockTypeList(Style)))
Daniel Jasperde0328a2013-08-16 11:20:30 +000097 return false;
98 // The opening "{" of a braced list has to be on the same line as the first
99 // element if it is nested in another braced init list or function call.
100 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
Daniel Jasperb596fb22013-10-24 10:31:50 +0000101 Previous.Type != TT_DictLiteral &&
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000102 Previous.BlockKind == BK_BracedInit && Previous.Previous &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000103 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
104 return false;
105 // This prevents breaks like:
106 // ...
107 // SomeParameter, OtherParameter).DoSomething(
108 // ...
109 // As they hide "DoSomething" and are generally bad for readability.
110 if (Previous.opensScope() && State.LowestLevelOnLine < State.StartOfLineLevel)
111 return false;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000112 if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
113 return false;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000114 return !State.Stack.back().NoLineBreak;
115}
116
117bool ContinuationIndenter::mustBreak(const LineState &State) {
118 const FormatToken &Current = *State.NextToken;
119 const FormatToken &Previous = *Current.Previous;
120 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
121 return true;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000122 if (State.Stack.back().BreakBeforeClosingBrace &&
123 Current.closesBlockTypeList(Style))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000124 return true;
125 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
126 return true;
Daniel Jasperec01cd62013-10-08 05:11:18 +0000127 if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
Daniel Jasper165b29e2013-11-08 00:57:11 +0000128 (Style.BreakBeforeTernaryOperators &&
129 (Current.is(tok::question) || (Current.Type == TT_ConditionalExpr &&
130 Previous.isNot(tok::question)))) ||
131 (!Style.BreakBeforeTernaryOperators &&
132 (Previous.is(tok::question) || Previous.Type == TT_ConditionalExpr))) &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000133 State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
134 !Current.isOneOf(tok::r_paren, tok::r_brace))
135 return true;
136 if (Style.AlwaysBreakBeforeMultilineStrings &&
Daniel Jasperf438cb72013-08-23 11:57:34 +0000137 State.Column > State.Stack.back().Indent && // Breaking saves columns.
Daniel Jasper27943052013-11-09 03:08:25 +0000138 !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) &&
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000139 Previous.Type != TT_InlineASMColon && nextIsMultilineString(State))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000140 return true;
Daniel Jasperb596fb22013-10-24 10:31:50 +0000141 if (((Previous.Type == TT_DictLiteral && Previous.is(tok::l_brace)) ||
Daniel Jasper1db6c382013-10-22 15:30:28 +0000142 Previous.Type == TT_ArrayInitializerLSquare) &&
Daniel Jasperd489dd32013-10-20 16:45:46 +0000143 getLengthToMatchingParen(Previous) + State.Column > getColumnLimit(State))
144 return true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000145
146 if (!Style.BreakBeforeBinaryOperators) {
147 // If we need to break somewhere inside the LHS of a binary expression, we
148 // should also break after the operator. Otherwise, the formatting would
149 // hide the operator precedence, e.g. in:
150 // if (aaaaaaaaaaaaaa ==
151 // bbbbbbbbbbbbbb && c) {..
152 // For comparisons, we only apply this rule, if the LHS is a binary
153 // expression itself as otherwise, the line breaks seem superfluous.
154 // We need special cases for ">>" which we have split into two ">" while
155 // lexing in order to make template parsing easier.
156 //
157 // FIXME: We'll need something similar for styles that break before binary
158 // operators.
159 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
160 Previous.getPrecedence() == prec::Equality) &&
161 Previous.Previous &&
162 Previous.Previous->Type != TT_BinaryOperator; // For >>.
163 bool LHSIsBinaryExpr =
Daniel Jasper562ecd42013-09-06 08:08:14 +0000164 Previous.Previous && Previous.Previous->EndsBinaryExpression;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000165 if (Previous.Type == TT_BinaryOperator &&
166 (!IsComparison || LHSIsBinaryExpr) &&
167 Current.Type != TT_BinaryOperator && // For >>.
168 !Current.isTrailingComment() &&
169 !Previous.isOneOf(tok::lessless, tok::question) &&
170 Previous.getPrecedence() != prec::Assignment &&
171 State.Stack.back().BreakBeforeParameter)
172 return true;
173 }
174
175 // Same as above, but for the first "<<" operator.
176 if (Current.is(tok::lessless) && State.Stack.back().BreakBeforeParameter &&
177 State.Stack.back().FirstLessLess == 0)
178 return true;
179
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;
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000186 if (Current.Type == TT_CtorInitializerColon &&
187 (!Style.AllowShortFunctionsOnASingleLine ||
188 Style.BreakConstructorInitializersBeforeComma || Style.ColumnLimit != 0))
189 return true;
190 if (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0 &&
191 !Current.isTrailingComment())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000192 return true;
193
194 if ((Current.Type == TT_StartOfName || Current.is(tok::kw_operator)) &&
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000195 State.Line->MightBeFunctionDecl &&
196 State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000197 return true;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000198 if (startsSegmentOfBuilderTypeCall(Current) &&
Daniel Jasperf8151e92013-08-30 07:12:40 +0000199 (State.Stack.back().CallContinuation != 0 ||
200 (State.Stack.back().BreakBeforeParameter &&
201 State.Stack.back().ContainsUnwrappedBuilder)))
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000202 return true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000203 return false;
204}
205
206unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000207 bool DryRun,
208 unsigned ExtraSpaces) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000209 const FormatToken &Current = *State.NextToken;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000210
Daniel Jasper98857842013-10-30 13:54:53 +0000211 if (State.Stack.size() == 0 ||
212 (Current.Type == TT_ImplicitStringLiteral &&
213 (Current.Previous->Tok.getIdentifierInfo() == NULL ||
214 Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
215 tok::pp_not_keyword))) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000216 // FIXME: Is this correct?
217 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
218 State.NextToken->WhitespaceRange.getEnd()) -
219 SourceMgr.getSpellingColumnNumber(
220 State.NextToken->WhitespaceRange.getBegin());
Alexander Kornienko39856b72013-09-10 09:38:25 +0000221 State.Column += WhitespaceLength + State.NextToken->ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000222 State.NextToken = State.NextToken->Next;
223 return 0;
224 }
225
Alexander Kornienko1f803962013-10-01 14:41:18 +0000226 unsigned Penalty = 0;
227 if (Newline)
228 Penalty = addTokenOnNewLine(State, DryRun);
229 else
Daniel Jasper48437ce2013-11-20 14:54:39 +0000230 addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000231
232 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
233}
234
Daniel Jasper48437ce2013-11-20 14:54:39 +0000235void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
236 unsigned ExtraSpaces) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000237 FormatToken &Current = *State.NextToken;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000238 const FormatToken &Previous = *State.NextToken->Previous;
239 if (Current.is(tok::equal) &&
240 (State.Line->First->is(tok::kw_for) || State.ParenLevel == 0) &&
241 State.Stack.back().VariablePos == 0) {
242 State.Stack.back().VariablePos = State.Column;
243 // Move over * and & if they are bound to the variable name.
244 const FormatToken *Tok = &Previous;
245 while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
246 State.Stack.back().VariablePos -= Tok->ColumnWidth;
247 if (Tok->SpacesRequiredBefore != 0)
248 break;
249 Tok = Tok->Previous;
250 }
251 if (Previous.PartOfMultiVariableDeclStmt)
252 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
253 }
254
255 unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
256
257 if (!DryRun)
258 Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, /*IndentLevel=*/0,
259 Spaces, State.Column + Spaces);
260
261 if (Current.Type == TT_ObjCSelectorName && State.Stack.back().ColonPos == 0) {
262 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
263 State.Column + Spaces + Current.ColumnWidth)
264 State.Stack.back().ColonPos =
265 State.Stack.back().Indent + Current.LongestObjCSelectorName;
266 else
267 State.Stack.back().ColonPos = State.Column + Spaces + Current.ColumnWidth;
268 }
269
270 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
271 Current.Type != TT_LineComment)
272 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasperec01cd62013-10-08 05:11:18 +0000273 if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000274 State.Stack.back().NoLineBreak = true;
275 if (startsSegmentOfBuilderTypeCall(Current))
276 State.Stack.back().ContainsUnwrappedBuilder = true;
277
278 State.Column += Spaces;
279 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
280 // Treat the condition inside an if as if it was a second function
Daniel Jasper6633ab82013-10-18 10:38:14 +0000281 // parameter, i.e. let nested calls have a continuation indent.
Alexander Kornienko1f803962013-10-01 14:41:18 +0000282 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper4478e522013-11-08 17:33:24 +0000283 else if (Previous.is(tok::comma) || Previous.Type == TT_ObjCMethodExpr)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000284 State.Stack.back().LastSpace = State.Column;
285 else if ((Previous.Type == TT_BinaryOperator ||
286 Previous.Type == TT_ConditionalExpr ||
287 Previous.Type == TT_UnaryOperator ||
288 Previous.Type == TT_CtorInitializerColon) &&
289 (Previous.getPrecedence() != prec::Assignment ||
290 Current.StartsBinaryExpression))
291 // Always indent relative to the RHS of the expression unless this is a
292 // simple assignment without binary expression on the RHS. Also indent
293 // relative to unary operators and the colons of constructor initializers.
294 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf9a5e402013-10-08 16:24:07 +0000295 else if (Previous.Type == TT_InheritanceColon) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000296 State.Stack.back().Indent = State.Column;
Daniel Jasperf9a5e402013-10-08 16:24:07 +0000297 State.Stack.back().LastSpace = State.Column;
298 } else if (Previous.opensScope()) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000299 // If a function has a trailing call, indent all parameters from the
300 // opening parenthesis. This avoids confusing indents like:
301 // OuterFunction(InnerFunctionCall( // break
302 // ParameterToInnerFunction)) // break
303 // .SecondInnerFunctionCall();
304 bool HasTrailingCall = false;
305 if (Previous.MatchingParen) {
306 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
307 HasTrailingCall = Next && Next->isMemberAccess();
308 }
309 if (HasTrailingCall &&
310 State.Stack[State.Stack.size() - 2].CallContinuation == 0)
311 State.Stack.back().LastSpace = State.Column;
312 }
313}
314
315unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
316 bool DryRun) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000317 FormatToken &Current = *State.NextToken;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000318 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasper6633ab82013-10-18 10:38:14 +0000319 // If we are continuing an expression, we want to use the continuation indent.
Daniel Jasperde0328a2013-08-16 11:20:30 +0000320 unsigned ContinuationIndent =
Daniel Jasper6633ab82013-10-18 10:38:14 +0000321 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
322 Style.ContinuationIndentWidth;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000323 // Extra penalty that needs to be added because of the way certain line
324 // breaks are chosen.
325 unsigned Penalty = 0;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000326
Alexander Kornienko1f803962013-10-01 14:41:18 +0000327 const FormatToken *PreviousNonComment =
328 State.NextToken->getPreviousNonComment();
329 // The first line break on any ParenLevel causes an extra penalty in order
330 // prefer similar line breaks.
331 if (!State.Stack.back().ContainsLineBreak)
332 Penalty += 15;
333 State.Stack.back().ContainsLineBreak = true;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000334
Alexander Kornienko1f803962013-10-01 14:41:18 +0000335 Penalty += State.NextToken->SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000336
Alexander Kornienko1f803962013-10-01 14:41:18 +0000337 // Breaking before the first "<<" is generally not desirable if the LHS is
Daniel Jasper48437ce2013-11-20 14:54:39 +0000338 // short. Also always add the penalty if the LHS is split over mutliple lines
339 // to avoid unncessary line breaks that just work around this penalty.
340 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0 &&
341 (State.Column <= Style.ColumnLimit / 2 ||
342 State.Stack.back().BreakBeforeParameter))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000343 Penalty += Style.PenaltyBreakFirstLessLess;
344
345 if (Current.is(tok::l_brace) && Current.BlockKind == BK_Block) {
Daniel Jaspere40caf92013-11-29 08:46:20 +0000346 State.Column =
347 State.ParenLevel == 0 ? State.FirstIndent : State.Stack.back().Indent;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000348 } else if (Current.isOneOf(tok::r_brace, tok::r_square)) {
Daniel Jasper6b6e7c32013-11-07 14:02:28 +0000349 if (Current.closesBlockTypeList(Style) ||
350 (Current.MatchingParen &&
351 Current.MatchingParen->BlockKind == BK_BracedInit))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000352 State.Column = State.Stack[State.Stack.size() - 2].LastSpace;
353 else
Daniel Jasper015ed022013-09-13 09:20:45 +0000354 State.Column = State.FirstIndent;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000355 } else if (Current.is(tok::string_literal) &&
356 State.StartOfStringLiteral != 0) {
357 State.Column = State.StartOfStringLiteral;
358 State.Stack.back().BreakBeforeParameter = true;
359 } else if (Current.is(tok::lessless) &&
360 State.Stack.back().FirstLessLess != 0) {
361 State.Column = State.Stack.back().FirstLessLess;
362 } else if (Current.isMemberAccess()) {
363 if (State.Stack.back().CallContinuation == 0) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000364 State.Column = ContinuationIndent;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000365 State.Stack.back().CallContinuation = State.Column;
366 } else {
367 State.Column = State.Stack.back().CallContinuation;
368 }
Daniel Jasper165b29e2013-11-08 00:57:11 +0000369 } else if (State.Stack.back().QuestionColumn != 0 &&
370 (Current.Type == TT_ConditionalExpr ||
371 Previous.Type == TT_ConditionalExpr)) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000372 State.Column = State.Stack.back().QuestionColumn;
373 } else if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0) {
374 State.Column = State.Stack.back().VariablePos;
375 } else if ((PreviousNonComment &&
376 PreviousNonComment->ClosesTemplateDeclaration) ||
377 ((Current.Type == TT_StartOfName ||
378 Current.is(tok::kw_operator)) &&
379 State.ParenLevel == 0 &&
380 (!Style.IndentFunctionDeclarationAfterType ||
381 State.Line->StartsDefinition))) {
Daniel Jasper298c3402013-11-22 07:48:15 +0000382 State.Column =
383 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000384 } else if (Current.Type == TT_ObjCSelectorName) {
Daniel Jasperb302f9a2013-11-08 02:08:01 +0000385 if (State.Stack.back().ColonPos == 0) {
386 State.Stack.back().ColonPos =
387 State.Stack.back().Indent + Current.LongestObjCSelectorName;
388 State.Column = State.Stack.back().ColonPos - Current.ColumnWidth;
389 } else if (State.Stack.back().ColonPos > Current.ColumnWidth) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000390 State.Column = State.Stack.back().ColonPos - Current.ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000391 } else {
392 State.Column = State.Stack.back().Indent;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000393 State.Stack.back().ColonPos = State.Column + Current.ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000394 }
Daniel Jasper1db6c382013-10-22 15:30:28 +0000395 } else if (Current.Type == TT_ArraySubscriptLSquare) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000396 if (State.Stack.back().StartOfArraySubscripts != 0)
397 State.Column = State.Stack.back().StartOfArraySubscripts;
398 else
399 State.Column = ContinuationIndent;
400 } else if (Current.Type == TT_StartOfName ||
401 Previous.isOneOf(tok::coloncolon, tok::equal) ||
402 Previous.Type == TT_ObjCMethodExpr) {
403 State.Column = ContinuationIndent;
404 } else if (Current.Type == TT_CtorInitializerColon) {
405 State.Column = State.FirstIndent + Style.ConstructorInitializerIndentWidth;
406 } else if (Current.Type == TT_CtorInitializerComma) {
407 State.Column = State.Stack.back().Indent;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000408 } else {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000409 State.Column = State.Stack.back().Indent;
Daniel Jasper6633ab82013-10-18 10:38:14 +0000410 // Ensure that we fall back to the continuation indent width instead of just
Alexander Kornienko1f803962013-10-01 14:41:18 +0000411 // flushing continuations left.
Daniel Jasper16fc7542013-10-30 14:04:10 +0000412 if (State.Column == State.FirstIndent &&
413 PreviousNonComment->isNot(tok::r_brace))
Daniel Jasper6633ab82013-10-18 10:38:14 +0000414 State.Column += Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000415 }
416
Alexander Kornienko1f803962013-10-01 14:41:18 +0000417 if ((Previous.isOneOf(tok::comma, tok::semi) &&
418 !State.Stack.back().AvoidBinPacking) ||
419 Previous.Type == TT_BinaryOperator)
420 State.Stack.back().BreakBeforeParameter = false;
421 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
422 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000423 if (Current.is(tok::question) ||
424 (PreviousNonComment && PreviousNonComment->is(tok::question)))
425 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000426
427 if (!DryRun) {
428 unsigned Newlines = 1;
429 if (Current.is(tok::comment))
430 Newlines = std::max(Newlines, std::min(Current.NewlinesBefore,
431 Style.MaxEmptyLinesToKeep + 1));
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000432 Whitespaces.replaceWhitespace(Current, Newlines,
433 State.Stack.back().IndentLevel, State.Column,
434 State.Column, State.Line->InPPDirective);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000435 }
436
437 if (!Current.isTrailingComment())
438 State.Stack.back().LastSpace = State.Column;
439 if (Current.isMemberAccess())
440 State.Stack.back().LastSpace += Current.ColumnWidth;
441 State.StartOfLineLevel = State.ParenLevel;
442 State.LowestLevelOnLine = State.ParenLevel;
443
444 // Any break on this level means that the parent level has been broken
445 // and we need to avoid bin packing there.
446 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
447 State.Stack[i].BreakBeforeParameter = true;
448 }
Daniel Jasper9e5ede02013-11-08 19:56:28 +0000449 if (PreviousNonComment &&
450 !PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
451 PreviousNonComment->Type != TT_TemplateCloser &&
452 PreviousNonComment->Type != TT_BinaryOperator &&
453 Current.Type != TT_BinaryOperator &&
454 !PreviousNonComment->opensScope())
Alexander Kornienko1f803962013-10-01 14:41:18 +0000455 State.Stack.back().BreakBeforeParameter = true;
456
Daniel Jasper1db6c382013-10-22 15:30:28 +0000457 // If we break after { or the [ of an array initializer, we should also break
458 // before the corresponding } or ].
459 if (Previous.is(tok::l_brace) || Previous.Type == TT_ArrayInitializerLSquare)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000460 State.Stack.back().BreakBeforeClosingBrace = true;
461
462 if (State.Stack.back().AvoidBinPacking) {
463 // If we are breaking after '(', '{', '<', this is not bin packing
464 // unless AllowAllParametersOfDeclarationOnNextLine is false.
465 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
466 Previous.Type == TT_BinaryOperator) ||
467 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
468 State.Line->MustBeDeclaration))
469 State.Stack.back().BreakBeforeParameter = true;
470 }
471
472 return Penalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000473}
474
475unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
476 bool DryRun, bool Newline) {
477 const FormatToken &Current = *State.NextToken;
478 assert(State.Stack.size());
479
480 if (Current.Type == TT_InheritanceColon)
481 State.Stack.back().AvoidBinPacking = true;
482 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
483 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000484 if (Current.Type == TT_ArraySubscriptLSquare &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000485 State.Stack.back().StartOfArraySubscripts == 0)
486 State.Stack.back().StartOfArraySubscripts = State.Column;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000487 if ((Current.is(tok::question) && Style.BreakBeforeTernaryOperators) ||
488 (Current.getPreviousNonComment() && Current.isNot(tok::colon) &&
489 Current.getPreviousNonComment()->is(tok::question) &&
490 !Style.BreakBeforeTernaryOperators))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000491 State.Stack.back().QuestionColumn = State.Column;
492 if (!Current.opensScope() && !Current.closesScope())
493 State.LowestLevelOnLine =
494 std::min(State.LowestLevelOnLine, State.ParenLevel);
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000495 if (Current.isMemberAccess())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000496 State.Stack.back().StartOfFunctionCall =
Alexander Kornienko39856b72013-09-10 09:38:25 +0000497 Current.LastInChainOfCalls ? 0 : State.Column + Current.ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000498 if (Current.Type == TT_CtorInitializerColon) {
499 // Indent 2 from the column, so:
500 // SomeClass::SomeClass()
501 // : First(...), ...
502 // Next(...)
503 // ^ line up here.
504 State.Stack.back().Indent =
505 State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
506 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
507 State.Stack.back().AvoidBinPacking = true;
508 State.Stack.back().BreakBeforeParameter = false;
509 }
510
Daniel Jasperde0328a2013-08-16 11:20:30 +0000511 // In ObjC method declaration we align on the ":" of parameters, but we need
Daniel Jasper6633ab82013-10-18 10:38:14 +0000512 // to ensure that we indent parameters on subsequent lines by at least our
513 // continuation indent width.
Daniel Jasperde0328a2013-08-16 11:20:30 +0000514 if (Current.Type == TT_ObjCMethodSpecifier)
Daniel Jasper6633ab82013-10-18 10:38:14 +0000515 State.Stack.back().Indent += Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000516
517 // Insert scopes created by fake parenthesis.
518 const FormatToken *Previous = Current.getPreviousNonComment();
519 // Don't add extra indentation for the first fake parenthesis after
520 // 'return', assignements or opening <({[. The indentation for these cases
521 // is special cased.
522 bool SkipFirstExtraIndent =
Daniel Jaspereabede62013-09-30 08:29:03 +0000523 (Previous && (Previous->opensScope() || Previous->is(tok::kw_return) ||
Daniel Jasperf48b5ab2013-11-07 19:23:49 +0000524 Previous->getPrecedence() == prec::Assignment ||
525 Previous->Type == TT_ObjCMethodExpr));
Daniel Jasperde0328a2013-08-16 11:20:30 +0000526 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
527 I = Current.FakeLParens.rbegin(),
528 E = Current.FakeLParens.rend();
529 I != E; ++I) {
530 ParenState NewParenState = State.Stack.back();
531 NewParenState.ContainsLineBreak = false;
Daniel Jaspereabede62013-09-30 08:29:03 +0000532
533 // Indent from 'LastSpace' unless this the fake parentheses encapsulating a
534 // builder type call after 'return'. If such a call is line-wrapped, we
535 // commonly just want to indent from the start of the line.
536 if (!Previous || Previous->isNot(tok::kw_return) || *I > 0)
537 NewParenState.Indent =
538 std::max(std::max(State.Column, NewParenState.Indent),
539 State.Stack.back().LastSpace);
540
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000541 // Do not indent relative to the fake parentheses inserted for "." or "->".
542 // This is a special case to make the following to statements consistent:
543 // OuterFunction(InnerFunctionCall( // break
544 // ParameterToInnerFunction));
545 // OuterFunction(SomeObject.InnerFunctionCall( // break
546 // ParameterToInnerFunction));
547 if (*I > prec::Unknown)
548 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000549
550 // Always indent conditional expressions. Never indent expression where
551 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
552 // prec::Assignment) as those have different indentation rules. Indent
553 // other expression, unless the indentation needs to be skipped.
554 if (*I == prec::Conditional ||
555 (!SkipFirstExtraIndent && *I > prec::Assignment &&
556 !Style.BreakBeforeBinaryOperators))
Daniel Jasper6633ab82013-10-18 10:38:14 +0000557 NewParenState.Indent += Style.ContinuationIndentWidth;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000558 if ((Previous && !Previous->opensScope()) || *I > prec::Comma)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000559 NewParenState.BreakBeforeParameter = false;
560 State.Stack.push_back(NewParenState);
561 SkipFirstExtraIndent = false;
562 }
563
564 // If we encounter an opening (, [, { or <, we add a level to our stacks to
565 // prepare for the following tokens.
566 if (Current.opensScope()) {
567 unsigned NewIndent;
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000568 unsigned NewIndentLevel = State.Stack.back().IndentLevel;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000569 bool AvoidBinPacking;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000570 bool BreakBeforeParameter = false;
571 if (Current.is(tok::l_brace) ||
572 Current.Type == TT_ArrayInitializerLSquare) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000573 if (Current.MatchingParen && Current.BlockKind == BK_Block) {
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000574 // If this is an l_brace starting a nested block, we pretend (wrt. to
575 // indentation) that we already consumed the corresponding r_brace.
576 // Thus, we remove all ParenStates caused bake fake parentheses that end
577 // at the r_brace. The net effect of this is that we don't indent
578 // relative to the l_brace, if the nested block is the last parameter of
579 // a function. For example, this formats:
580 //
581 // SomeFunction(a, [] {
582 // f(); // break
583 // });
584 //
585 // instead of:
586 // SomeFunction(a, [] {
Daniel Jasper5500f612013-11-25 11:08:59 +0000587 // f(); // break
588 // });
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000589 for (unsigned i = 0; i != Current.MatchingParen->FakeRParens; ++i)
590 State.Stack.pop_back();
Daniel Jasper015ed022013-09-13 09:20:45 +0000591 NewIndent = State.Stack.back().LastSpace + Style.IndentWidth;
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000592 ++NewIndentLevel;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000593 BreakBeforeParameter = true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000594 } else {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000595 NewIndent = State.Stack.back().LastSpace;
Daniel Jasperb8f61682013-10-22 15:45:58 +0000596 if (Current.opensBlockTypeList(Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000597 NewIndent += Style.IndentWidth;
598 ++NewIndentLevel;
Daniel Jasperb8f61682013-10-22 15:45:58 +0000599 } else {
600 NewIndent += Style.ContinuationIndentWidth;
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000601 }
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000602 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000603 const FormatToken *NextNoComment = Current.getNextNonComment();
Daniel Jasper015ed022013-09-13 09:20:45 +0000604 AvoidBinPacking = Current.BlockKind == BK_Block ||
Daniel Jasper1db6c382013-10-22 15:30:28 +0000605 Current.Type == TT_ArrayInitializerLSquare ||
Daniel Jasperb596fb22013-10-24 10:31:50 +0000606 Current.Type == TT_DictLiteral ||
Daniel Jasper015ed022013-09-13 09:20:45 +0000607 (NextNoComment &&
608 NextNoComment->Type == TT_DesignatedInitializerPeriod);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000609 } else {
Daniel Jasper6633ab82013-10-18 10:38:14 +0000610 NewIndent = Style.ContinuationIndentWidth +
611 std::max(State.Stack.back().LastSpace,
612 State.Stack.back().StartOfFunctionCall);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000613 AvoidBinPacking = !Style.BinPackParameters ||
614 (Style.ExperimentalAutoDetectBinPacking &&
615 (Current.PackingKind == PPK_OnePerLine ||
616 (!BinPackInconclusiveFunctions &&
617 Current.PackingKind == PPK_Inconclusive)));
Daniel Jasper1db6c382013-10-22 15:30:28 +0000618 // If this '[' opens an ObjC call, determine whether all parameters fit
619 // into one line and put one per line if they don't.
620 if (Current.Type == TT_ObjCMethodExpr &&
621 getLengthToMatchingParen(Current) + State.Column >
622 getColumnLimit(State))
623 BreakBeforeParameter = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000624 }
625
Daniel Jaspercc3114d2013-10-18 15:23:06 +0000626 bool NoLineBreak = State.Stack.back().NoLineBreak ||
627 (Current.Type == TT_TemplateOpener &&
628 State.Stack.back().ContainsUnwrappedBuilder);
629 State.Stack.push_back(ParenState(NewIndent, NewIndentLevel,
630 State.Stack.back().LastSpace,
631 AvoidBinPacking, NoLineBreak));
Daniel Jasper1db6c382013-10-22 15:30:28 +0000632 State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000633 ++State.ParenLevel;
634 }
635
Daniel Jasperde0328a2013-08-16 11:20:30 +0000636 // If we encounter a closing ), ], } or >, we can remove a level from our
637 // stacks.
Daniel Jasper96df37a2013-08-28 09:17:37 +0000638 if (State.Stack.size() > 1 &&
639 (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000640 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
Daniel Jasper96df37a2013-08-28 09:17:37 +0000641 State.NextToken->Type == TT_TemplateCloser)) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000642 State.Stack.pop_back();
643 --State.ParenLevel;
644 }
645 if (Current.is(tok::r_square)) {
646 // If this ends the array subscript expr, reset the corresponding value.
647 const FormatToken *NextNonComment = Current.getNextNonComment();
648 if (NextNonComment && NextNonComment->isNot(tok::l_square))
649 State.Stack.back().StartOfArraySubscripts = 0;
650 }
651
652 // Remove scopes created by fake parenthesis.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000653 if (Current.isNot(tok::r_brace) ||
654 (Current.MatchingParen && Current.MatchingParen->BlockKind != BK_Block)) {
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000655 // Don't remove FakeRParens attached to r_braces that surround nested blocks
656 // as they will have been removed early (see above).
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000657 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
658 unsigned VariablePos = State.Stack.back().VariablePos;
659 State.Stack.pop_back();
660 State.Stack.back().VariablePos = VariablePos;
661 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000662 }
663
664 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
665 State.StartOfStringLiteral = State.Column;
666 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
667 tok::string_literal)) {
668 State.StartOfStringLiteral = 0;
669 }
670
Alexander Kornienko39856b72013-09-10 09:38:25 +0000671 State.Column += Current.ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000672 State.NextToken = State.NextToken->Next;
Daniel Jasperb27c4b72013-08-27 11:09:05 +0000673 unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000674 if (State.Column > getColumnLimit(State)) {
675 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
676 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
677 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000678
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000679 // If the previous has a special role, let it consume tokens as appropriate.
680 // It is necessary to start at the previous token for the only implemented
681 // role (comma separated list). That way, the decision whether or not to break
682 // after the "{" is already done and both options are tried and evaluated.
683 // FIXME: This is ugly, find a better way.
684 if (Previous && Previous->Role)
685 Penalty += Previous->Role->format(State, this, DryRun);
686
687 return Penalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000688}
689
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000690unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
691 LineState &State) {
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000692 // Break before further function parameters on all levels.
693 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
694 State.Stack[i].BreakBeforeParameter = true;
695
Alexander Kornienko39856b72013-09-10 09:38:25 +0000696 unsigned ColumnsUsed = State.Column;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000697 // We can only affect layout of the first and the last line, so the penalty
698 // for all other lines is constant, and we ignore it.
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000699 State.Column = Current.LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000700
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000701 if (ColumnsUsed > getColumnLimit(State))
702 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000703 return 0;
704}
705
Alexander Kornienko81e32942013-09-16 20:20:49 +0000706static bool getRawStringLiteralPrefixPostfix(StringRef Text,
707 StringRef &Prefix,
708 StringRef &Postfix) {
709 if (Text.startswith(Prefix = "R\"") || Text.startswith(Prefix = "uR\"") ||
710 Text.startswith(Prefix = "UR\"") || Text.startswith(Prefix = "u8R\"") ||
711 Text.startswith(Prefix = "LR\"")) {
712 size_t ParenPos = Text.find('(');
713 if (ParenPos != StringRef::npos) {
714 StringRef Delimiter =
715 Text.substr(Prefix.size(), ParenPos - Prefix.size());
716 Prefix = Text.substr(0, ParenPos + 1);
717 Postfix = Text.substr(Text.size() - 2 - Delimiter.size());
718 return Postfix.front() == ')' && Postfix.back() == '"' &&
719 Postfix.substr(1).startswith(Delimiter);
720 }
721 }
722 return false;
723}
724
Daniel Jasperde0328a2013-08-16 11:20:30 +0000725unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
726 LineState &State,
727 bool DryRun) {
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000728 // Don't break multi-line tokens other than block comments. Instead, just
729 // update the state.
730 if (Current.Type != TT_BlockComment && Current.IsMultiline)
731 return addMultilineToken(Current, State);
732
Daniel Jasper98857842013-10-30 13:54:53 +0000733 // Don't break implicit string literals.
734 if (Current.Type == TT_ImplicitStringLiteral)
735 return 0;
736
Alexander Kornienko81e32942013-09-16 20:20:49 +0000737 if (!Current.isOneOf(tok::string_literal, tok::wide_string_literal,
738 tok::utf8_string_literal, tok::utf16_string_literal,
739 tok::utf32_string_literal, tok::comment))
Daniel Jasperf93551c2013-08-23 10:05:49 +0000740 return 0;
741
Daniel Jasperde0328a2013-08-16 11:20:30 +0000742 llvm::OwningPtr<BreakableToken> Token;
Alexander Kornienko39856b72013-09-10 09:38:25 +0000743 unsigned StartColumn = State.Column - Current.ColumnWidth;
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000744 unsigned ColumnLimit = getColumnLimit(State);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000745
Alexander Kornienko81e32942013-09-16 20:20:49 +0000746 if (Current.isOneOf(tok::string_literal, tok::wide_string_literal,
747 tok::utf8_string_literal, tok::utf16_string_literal,
748 tok::utf32_string_literal) &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000749 Current.Type != TT_ImplicitStringLiteral) {
Alexander Kornienko384b40b2013-10-11 21:43:05 +0000750 // Don't break string literals inside preprocessor directives (except for
751 // #define directives, as their contents are stored in separate lines and
752 // are not affected by this check).
753 // This way we avoid breaking code with line directives and unknown
754 // preprocessor directives that contain long string literals.
755 if (State.Line->Type == LT_PreprocessorDirective)
756 return 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000757 // Exempts unterminated string literals from line breaking. The user will
758 // likely want to terminate the string before any line breaking is done.
759 if (Current.IsUnterminatedLiteral)
760 return 0;
761
Alexander Kornienko81e32942013-09-16 20:20:49 +0000762 StringRef Text = Current.TokenText;
763 StringRef Prefix;
764 StringRef Postfix;
765 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
766 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
767 // reduce the overhead) for each FormatToken, which is a string, so that we
768 // don't run multiple checks here on the hot path.
769 if ((Text.endswith(Postfix = "\"") &&
770 (Text.startswith(Prefix = "\"") || Text.startswith(Prefix = "u\"") ||
771 Text.startswith(Prefix = "U\"") || Text.startswith(Prefix = "u8\"") ||
772 Text.startswith(Prefix = "L\""))) ||
773 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")")) ||
774 getRawStringLiteralPrefixPostfix(Text, Prefix, Postfix)) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000775 Token.reset(new BreakableStringLiteral(
776 Current, State.Line->Level, StartColumn, Prefix, Postfix,
777 State.Line->InPPDirective, Encoding, Style));
Alexander Kornienko81e32942013-09-16 20:20:49 +0000778 } else {
779 return 0;
780 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000781 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
782 Token.reset(new BreakableBlockComment(
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000783 Current, State.Line->Level, StartColumn, Current.OriginalColumn,
784 !Current.Previous, State.Line->InPPDirective, Encoding, Style));
Daniel Jasperde0328a2013-08-16 11:20:30 +0000785 } else if (Current.Type == TT_LineComment &&
786 (Current.Previous == NULL ||
787 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000788 Token.reset(new BreakableLineComment(Current, State.Line->Level,
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000789 StartColumn, /*InPPDirective=*/false,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000790 Encoding, Style));
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000791 // We don't insert backslashes when breaking line comments.
792 ColumnLimit = Style.ColumnLimit;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000793 } else {
794 return 0;
795 }
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000796 if (Current.UnbreakableTailLength >= ColumnLimit)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000797 return 0;
798
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000799 unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000800 bool BreakInserted = false;
801 unsigned Penalty = 0;
802 unsigned RemainingTokenColumns = 0;
803 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
804 LineIndex != EndIndex; ++LineIndex) {
805 if (!DryRun)
806 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
807 unsigned TailOffset = 0;
808 RemainingTokenColumns =
809 Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
810 while (RemainingTokenColumns > RemainingSpace) {
811 BreakableToken::Split Split =
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000812 Token->getSplit(LineIndex, TailOffset, ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000813 if (Split.first == StringRef::npos) {
814 // The last line's penalty is handled in addNextStateToQueue().
815 if (LineIndex < EndIndex - 1)
816 Penalty += Style.PenaltyExcessCharacter *
817 (RemainingTokenColumns - RemainingSpace);
818 break;
819 }
820 assert(Split.first != 0);
821 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
822 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
Alexander Kornienko875395f2013-11-12 17:50:13 +0000823
824 // We can remove extra whitespace instead of breaking the line.
825 if (RemainingTokenColumns + 1 - Split.second <= RemainingSpace) {
826 RemainingTokenColumns = 0;
827 if (!DryRun)
828 Token->replaceWhitespace(LineIndex, TailOffset, Split, Whitespaces);
829 break;
830 }
831
Daniel Jasperde0328a2013-08-16 11:20:30 +0000832 assert(NewRemainingTokenColumns < RemainingTokenColumns);
833 if (!DryRun)
834 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Daniel Jasper2739af32013-08-28 10:03:58 +0000835 Penalty += Current.SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000836 unsigned ColumnsUsed =
837 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000838 if (ColumnsUsed > ColumnLimit) {
839 Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000840 }
841 TailOffset += Split.first + Split.second;
842 RemainingTokenColumns = NewRemainingTokenColumns;
843 BreakInserted = true;
844 }
845 }
846
847 State.Column = RemainingTokenColumns;
848
849 if (BreakInserted) {
850 // If we break the token inside a parameter list, we need to break before
851 // the next parameter on all levels, so that the next parameter is clearly
852 // visible. Line comments already introduce a break.
853 if (Current.Type != TT_LineComment) {
854 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
855 State.Stack[i].BreakBeforeParameter = true;
856 }
857
Daniel Jasper2739af32013-08-28 10:03:58 +0000858 Penalty += Current.is(tok::string_literal) ? Style.PenaltyBreakString
859 : Style.PenaltyBreakComment;
860
Daniel Jasperde0328a2013-08-16 11:20:30 +0000861 State.Stack.back().LastSpace = StartColumn;
862 }
863 return Penalty;
864}
865
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000866unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000867 // In preprocessor directives reserve two chars for trailing " \"
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000868 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000869}
870
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000871bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
Daniel Jasperf438cb72013-08-23 11:57:34 +0000872 const FormatToken &Current = *State.NextToken;
873 if (!Current.is(tok::string_literal))
874 return false;
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000875 // We never consider raw string literals "multiline" for the purpose of
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000876 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
877 // (see TokenAnnotator::mustBreakBefore().
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000878 if (Current.TokenText.startswith("R\""))
879 return false;
Alexander Kornienko39856b72013-09-10 09:38:25 +0000880 if (Current.IsMultiline)
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000881 return true;
Daniel Jasperf438cb72013-08-23 11:57:34 +0000882 if (Current.getNextNonComment() &&
883 Current.getNextNonComment()->is(tok::string_literal))
884 return true; // Implicit concatenation.
Alexander Kornienko39856b72013-09-10 09:38:25 +0000885 if (State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
Daniel Jasperf438cb72013-08-23 11:57:34 +0000886 Style.ColumnLimit)
887 return true; // String will be split.
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000888 return false;
Daniel Jasperf438cb72013-08-23 11:57:34 +0000889}
890
Daniel Jasperde0328a2013-08-16 11:20:30 +0000891} // namespace format
892} // namespace clang