blob: 3860aeb9e758ce54951feba5058a71eb056f317a [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 &&
Daniel Jasper5a611392013-12-19 21:41:37 +0000271 (Current.Type != TT_LineComment || Previous.BlockKind == BK_BracedInit))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000272 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 &&
Daniel Jasper004177e2013-12-19 16:06:40 +0000341 (State.Column <= Style.ColumnLimit / 3 ||
Daniel Jasper48437ce2013-11-20 14:54:39 +0000342 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 Jasper96964352013-12-18 10:44:36 +0000549 NewParenState.StartOfFunctionCall = State.Column;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000550
551 // Always indent conditional expressions. Never indent expression where
552 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
553 // prec::Assignment) as those have different indentation rules. Indent
554 // other expression, unless the indentation needs to be skipped.
555 if (*I == prec::Conditional ||
556 (!SkipFirstExtraIndent && *I > prec::Assignment &&
557 !Style.BreakBeforeBinaryOperators))
Daniel Jasper6633ab82013-10-18 10:38:14 +0000558 NewParenState.Indent += Style.ContinuationIndentWidth;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000559 if ((Previous && !Previous->opensScope()) || *I > prec::Comma)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000560 NewParenState.BreakBeforeParameter = false;
561 State.Stack.push_back(NewParenState);
562 SkipFirstExtraIndent = false;
563 }
564
565 // If we encounter an opening (, [, { or <, we add a level to our stacks to
566 // prepare for the following tokens.
567 if (Current.opensScope()) {
568 unsigned NewIndent;
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000569 unsigned NewIndentLevel = State.Stack.back().IndentLevel;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000570 bool AvoidBinPacking;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000571 bool BreakBeforeParameter = false;
572 if (Current.is(tok::l_brace) ||
573 Current.Type == TT_ArrayInitializerLSquare) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000574 if (Current.MatchingParen && Current.BlockKind == BK_Block) {
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000575 // If this is an l_brace starting a nested block, we pretend (wrt. to
576 // indentation) that we already consumed the corresponding r_brace.
Daniel Jasper96964352013-12-18 10:44:36 +0000577 // Thus, we remove all ParenStates caused by fake parentheses that end
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000578 // at the r_brace. The net effect of this is that we don't indent
579 // relative to the l_brace, if the nested block is the last parameter of
580 // a function. For example, this formats:
581 //
582 // SomeFunction(a, [] {
583 // f(); // break
584 // });
585 //
586 // instead of:
587 // SomeFunction(a, [] {
Daniel Jasper5500f612013-11-25 11:08:59 +0000588 // f(); // break
589 // });
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000590 for (unsigned i = 0; i != Current.MatchingParen->FakeRParens; ++i)
591 State.Stack.pop_back();
Daniel Jasper015ed022013-09-13 09:20:45 +0000592 NewIndent = State.Stack.back().LastSpace + Style.IndentWidth;
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000593 ++NewIndentLevel;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000594 BreakBeforeParameter = true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000595 } else {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000596 NewIndent = State.Stack.back().LastSpace;
Daniel Jasperb8f61682013-10-22 15:45:58 +0000597 if (Current.opensBlockTypeList(Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000598 NewIndent += Style.IndentWidth;
Daniel Jasper5a611392013-12-19 21:41:37 +0000599 NewIndent = std::min(State.Column + 2, NewIndent);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000600 ++NewIndentLevel;
Daniel Jasperb8f61682013-10-22 15:45:58 +0000601 } else {
602 NewIndent += Style.ContinuationIndentWidth;
Daniel Jasper5a611392013-12-19 21:41:37 +0000603 NewIndent = std::min(State.Column + 1, NewIndent);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000604 }
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000605 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000606 const FormatToken *NextNoComment = Current.getNextNonComment();
Daniel Jasper015ed022013-09-13 09:20:45 +0000607 AvoidBinPacking = Current.BlockKind == BK_Block ||
Daniel Jasper1db6c382013-10-22 15:30:28 +0000608 Current.Type == TT_ArrayInitializerLSquare ||
Daniel Jasperb596fb22013-10-24 10:31:50 +0000609 Current.Type == TT_DictLiteral ||
Daniel Jasper015ed022013-09-13 09:20:45 +0000610 (NextNoComment &&
611 NextNoComment->Type == TT_DesignatedInitializerPeriod);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000612 } else {
Daniel Jasper6633ab82013-10-18 10:38:14 +0000613 NewIndent = Style.ContinuationIndentWidth +
614 std::max(State.Stack.back().LastSpace,
615 State.Stack.back().StartOfFunctionCall);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000616 AvoidBinPacking = !Style.BinPackParameters ||
617 (Style.ExperimentalAutoDetectBinPacking &&
618 (Current.PackingKind == PPK_OnePerLine ||
619 (!BinPackInconclusiveFunctions &&
620 Current.PackingKind == PPK_Inconclusive)));
Daniel Jasper1db6c382013-10-22 15:30:28 +0000621 // If this '[' opens an ObjC call, determine whether all parameters fit
622 // into one line and put one per line if they don't.
623 if (Current.Type == TT_ObjCMethodExpr &&
624 getLengthToMatchingParen(Current) + State.Column >
625 getColumnLimit(State))
626 BreakBeforeParameter = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000627 }
628
Daniel Jaspercc3114d2013-10-18 15:23:06 +0000629 bool NoLineBreak = State.Stack.back().NoLineBreak ||
630 (Current.Type == TT_TemplateOpener &&
631 State.Stack.back().ContainsUnwrappedBuilder);
632 State.Stack.push_back(ParenState(NewIndent, NewIndentLevel,
633 State.Stack.back().LastSpace,
634 AvoidBinPacking, NoLineBreak));
Daniel Jasper1db6c382013-10-22 15:30:28 +0000635 State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000636 ++State.ParenLevel;
637 }
638
Daniel Jasperde0328a2013-08-16 11:20:30 +0000639 // If we encounter a closing ), ], } or >, we can remove a level from our
640 // stacks.
Daniel Jasper96df37a2013-08-28 09:17:37 +0000641 if (State.Stack.size() > 1 &&
642 (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000643 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
Daniel Jasper96df37a2013-08-28 09:17:37 +0000644 State.NextToken->Type == TT_TemplateCloser)) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000645 State.Stack.pop_back();
646 --State.ParenLevel;
647 }
648 if (Current.is(tok::r_square)) {
649 // If this ends the array subscript expr, reset the corresponding value.
650 const FormatToken *NextNonComment = Current.getNextNonComment();
651 if (NextNonComment && NextNonComment->isNot(tok::l_square))
652 State.Stack.back().StartOfArraySubscripts = 0;
653 }
654
655 // Remove scopes created by fake parenthesis.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000656 if (Current.isNot(tok::r_brace) ||
657 (Current.MatchingParen && Current.MatchingParen->BlockKind != BK_Block)) {
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000658 // Don't remove FakeRParens attached to r_braces that surround nested blocks
659 // as they will have been removed early (see above).
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000660 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
661 unsigned VariablePos = State.Stack.back().VariablePos;
662 State.Stack.pop_back();
663 State.Stack.back().VariablePos = VariablePos;
664 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000665 }
666
667 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
668 State.StartOfStringLiteral = State.Column;
669 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
670 tok::string_literal)) {
671 State.StartOfStringLiteral = 0;
672 }
673
Alexander Kornienko39856b72013-09-10 09:38:25 +0000674 State.Column += Current.ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000675 State.NextToken = State.NextToken->Next;
Daniel Jasperb27c4b72013-08-27 11:09:05 +0000676 unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000677 if (State.Column > getColumnLimit(State)) {
678 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
679 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
680 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000681
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000682 // If the previous has a special role, let it consume tokens as appropriate.
683 // It is necessary to start at the previous token for the only implemented
684 // role (comma separated list). That way, the decision whether or not to break
685 // after the "{" is already done and both options are tried and evaluated.
686 // FIXME: This is ugly, find a better way.
687 if (Previous && Previous->Role)
688 Penalty += Previous->Role->format(State, this, DryRun);
689
690 return Penalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000691}
692
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000693unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
694 LineState &State) {
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000695 // Break before further function parameters on all levels.
696 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
697 State.Stack[i].BreakBeforeParameter = true;
698
Alexander Kornienko39856b72013-09-10 09:38:25 +0000699 unsigned ColumnsUsed = State.Column;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000700 // We can only affect layout of the first and the last line, so the penalty
701 // for all other lines is constant, and we ignore it.
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000702 State.Column = Current.LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000703
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000704 if (ColumnsUsed > getColumnLimit(State))
705 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000706 return 0;
707}
708
Alexander Kornienko81e32942013-09-16 20:20:49 +0000709static bool getRawStringLiteralPrefixPostfix(StringRef Text,
710 StringRef &Prefix,
711 StringRef &Postfix) {
712 if (Text.startswith(Prefix = "R\"") || Text.startswith(Prefix = "uR\"") ||
713 Text.startswith(Prefix = "UR\"") || Text.startswith(Prefix = "u8R\"") ||
714 Text.startswith(Prefix = "LR\"")) {
715 size_t ParenPos = Text.find('(');
716 if (ParenPos != StringRef::npos) {
717 StringRef Delimiter =
718 Text.substr(Prefix.size(), ParenPos - Prefix.size());
719 Prefix = Text.substr(0, ParenPos + 1);
720 Postfix = Text.substr(Text.size() - 2 - Delimiter.size());
721 return Postfix.front() == ')' && Postfix.back() == '"' &&
722 Postfix.substr(1).startswith(Delimiter);
723 }
724 }
725 return false;
726}
727
Daniel Jasperde0328a2013-08-16 11:20:30 +0000728unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
729 LineState &State,
730 bool DryRun) {
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000731 // Don't break multi-line tokens other than block comments. Instead, just
732 // update the state.
733 if (Current.Type != TT_BlockComment && Current.IsMultiline)
734 return addMultilineToken(Current, State);
735
Daniel Jasper98857842013-10-30 13:54:53 +0000736 // Don't break implicit string literals.
737 if (Current.Type == TT_ImplicitStringLiteral)
738 return 0;
739
Alexander Kornienko81e32942013-09-16 20:20:49 +0000740 if (!Current.isOneOf(tok::string_literal, tok::wide_string_literal,
741 tok::utf8_string_literal, tok::utf16_string_literal,
742 tok::utf32_string_literal, tok::comment))
Daniel Jasperf93551c2013-08-23 10:05:49 +0000743 return 0;
744
Daniel Jasperde0328a2013-08-16 11:20:30 +0000745 llvm::OwningPtr<BreakableToken> Token;
Alexander Kornienko39856b72013-09-10 09:38:25 +0000746 unsigned StartColumn = State.Column - Current.ColumnWidth;
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000747 unsigned ColumnLimit = getColumnLimit(State);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000748
Alexander Kornienko81e32942013-09-16 20:20:49 +0000749 if (Current.isOneOf(tok::string_literal, tok::wide_string_literal,
750 tok::utf8_string_literal, tok::utf16_string_literal,
751 tok::utf32_string_literal) &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000752 Current.Type != TT_ImplicitStringLiteral) {
Alexander Kornienko384b40b2013-10-11 21:43:05 +0000753 // Don't break string literals inside preprocessor directives (except for
754 // #define directives, as their contents are stored in separate lines and
755 // are not affected by this check).
756 // This way we avoid breaking code with line directives and unknown
757 // preprocessor directives that contain long string literals.
758 if (State.Line->Type == LT_PreprocessorDirective)
759 return 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000760 // Exempts unterminated string literals from line breaking. The user will
761 // likely want to terminate the string before any line breaking is done.
762 if (Current.IsUnterminatedLiteral)
763 return 0;
764
Alexander Kornienko81e32942013-09-16 20:20:49 +0000765 StringRef Text = Current.TokenText;
766 StringRef Prefix;
767 StringRef Postfix;
768 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
769 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
770 // reduce the overhead) for each FormatToken, which is a string, so that we
771 // don't run multiple checks here on the hot path.
772 if ((Text.endswith(Postfix = "\"") &&
773 (Text.startswith(Prefix = "\"") || Text.startswith(Prefix = "u\"") ||
774 Text.startswith(Prefix = "U\"") || Text.startswith(Prefix = "u8\"") ||
775 Text.startswith(Prefix = "L\""))) ||
776 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")")) ||
777 getRawStringLiteralPrefixPostfix(Text, Prefix, Postfix)) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000778 Token.reset(new BreakableStringLiteral(
779 Current, State.Line->Level, StartColumn, Prefix, Postfix,
780 State.Line->InPPDirective, Encoding, Style));
Alexander Kornienko81e32942013-09-16 20:20:49 +0000781 } else {
782 return 0;
783 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000784 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
785 Token.reset(new BreakableBlockComment(
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000786 Current, State.Line->Level, StartColumn, Current.OriginalColumn,
787 !Current.Previous, State.Line->InPPDirective, Encoding, Style));
Daniel Jasperde0328a2013-08-16 11:20:30 +0000788 } else if (Current.Type == TT_LineComment &&
789 (Current.Previous == NULL ||
790 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000791 Token.reset(new BreakableLineComment(Current, State.Line->Level,
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000792 StartColumn, /*InPPDirective=*/false,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000793 Encoding, Style));
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000794 // We don't insert backslashes when breaking line comments.
795 ColumnLimit = Style.ColumnLimit;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000796 } else {
797 return 0;
798 }
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000799 if (Current.UnbreakableTailLength >= ColumnLimit)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000800 return 0;
801
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000802 unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000803 bool BreakInserted = false;
804 unsigned Penalty = 0;
805 unsigned RemainingTokenColumns = 0;
806 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
807 LineIndex != EndIndex; ++LineIndex) {
808 if (!DryRun)
809 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
810 unsigned TailOffset = 0;
811 RemainingTokenColumns =
812 Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
813 while (RemainingTokenColumns > RemainingSpace) {
814 BreakableToken::Split Split =
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000815 Token->getSplit(LineIndex, TailOffset, ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000816 if (Split.first == StringRef::npos) {
817 // The last line's penalty is handled in addNextStateToQueue().
818 if (LineIndex < EndIndex - 1)
819 Penalty += Style.PenaltyExcessCharacter *
820 (RemainingTokenColumns - RemainingSpace);
821 break;
822 }
823 assert(Split.first != 0);
824 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
825 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
Alexander Kornienko875395f2013-11-12 17:50:13 +0000826
827 // We can remove extra whitespace instead of breaking the line.
828 if (RemainingTokenColumns + 1 - Split.second <= RemainingSpace) {
829 RemainingTokenColumns = 0;
830 if (!DryRun)
831 Token->replaceWhitespace(LineIndex, TailOffset, Split, Whitespaces);
832 break;
833 }
834
Daniel Jasperde0328a2013-08-16 11:20:30 +0000835 assert(NewRemainingTokenColumns < RemainingTokenColumns);
836 if (!DryRun)
837 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Daniel Jasper2739af32013-08-28 10:03:58 +0000838 Penalty += Current.SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000839 unsigned ColumnsUsed =
840 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000841 if (ColumnsUsed > ColumnLimit) {
842 Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000843 }
844 TailOffset += Split.first + Split.second;
845 RemainingTokenColumns = NewRemainingTokenColumns;
846 BreakInserted = true;
847 }
848 }
849
850 State.Column = RemainingTokenColumns;
851
852 if (BreakInserted) {
853 // If we break the token inside a parameter list, we need to break before
854 // the next parameter on all levels, so that the next parameter is clearly
855 // visible. Line comments already introduce a break.
856 if (Current.Type != TT_LineComment) {
857 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
858 State.Stack[i].BreakBeforeParameter = true;
859 }
860
Daniel Jasper2739af32013-08-28 10:03:58 +0000861 Penalty += Current.is(tok::string_literal) ? Style.PenaltyBreakString
862 : Style.PenaltyBreakComment;
863
Daniel Jasperde0328a2013-08-16 11:20:30 +0000864 State.Stack.back().LastSpace = StartColumn;
865 }
866 return Penalty;
867}
868
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000869unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000870 // In preprocessor directives reserve two chars for trailing " \"
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000871 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000872}
873
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000874bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
Daniel Jasperf438cb72013-08-23 11:57:34 +0000875 const FormatToken &Current = *State.NextToken;
876 if (!Current.is(tok::string_literal))
877 return false;
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000878 // We never consider raw string literals "multiline" for the purpose of
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000879 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
880 // (see TokenAnnotator::mustBreakBefore().
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000881 if (Current.TokenText.startswith("R\""))
882 return false;
Alexander Kornienko39856b72013-09-10 09:38:25 +0000883 if (Current.IsMultiline)
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000884 return true;
Daniel Jasperf438cb72013-08-23 11:57:34 +0000885 if (Current.getNextNonComment() &&
886 Current.getNextNonComment()->is(tok::string_literal))
887 return true; // Implicit concatenation.
Alexander Kornienko39856b72013-09-10 09:38:25 +0000888 if (State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
Daniel Jasperf438cb72013-08-23 11:57:34 +0000889 Style.ColumnLimit)
890 return true; // String will be split.
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000891 return false;
Daniel Jasperf438cb72013-08-23 11:57:34 +0000892}
893
Daniel Jasperde0328a2013-08-16 11:20:30 +0000894} // namespace format
895} // namespace clang