blob: 6a5f8763d9b6d73b8385727bc2b53f2bc3f10174 [file] [log] [blame]
Daniel Jasper6b2afe42013-08-16 11:20:30 +00001//===--- ContinuationIndenter.cpp - Format C++ code -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements the continuation indenter.
12///
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "format-formatter"
16
17#include "BreakableToken.h"
18#include "ContinuationIndenter.h"
19#include "WhitespaceManager.h"
20#include "clang/Basic/OperatorPrecedence.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Format/Format.h"
23#include "llvm/Support/Debug.h"
24#include <string>
25
26namespace clang {
27namespace format {
28
29// Returns the length of everything up to the first possible line break after
30// the ), ], } or > matching \c Tok.
31static unsigned getLengthToMatchingParen(const FormatToken &Tok) {
32 if (Tok.MatchingParen == NULL)
33 return 0;
34 FormatToken *End = Tok.MatchingParen;
35 while (End->Next && !End->Next->CanBreakBefore) {
36 End = End->Next;
37 }
38 return End->TotalLength - Tok.TotalLength + 1;
39}
40
Daniel Jasperd3fef0f2013-08-27 14:24:43 +000041// Returns \c true if \c Tok is the "." or "->" of a call and starts the next
42// segment of a builder type call.
43static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) {
44 return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope();
45}
46
Daniel Jasper6b2afe42013-08-16 11:20:30 +000047ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,
48 SourceManager &SourceMgr,
Daniel Jasper6b2afe42013-08-16 11:20:30 +000049 WhitespaceManager &Whitespaces,
50 encoding::Encoding Encoding,
51 bool BinPackInconclusiveFunctions)
Daniel Jasper567dcf92013-09-05 09:29:45 +000052 : Style(Style), SourceMgr(SourceMgr), Whitespaces(Whitespaces),
53 Encoding(Encoding),
Daniel Jasper6b2afe42013-08-16 11:20:30 +000054 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions) {}
55
Daniel Jasper567dcf92013-09-05 09:29:45 +000056LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
Daniel Jasperb77d7412013-09-06 07:54:20 +000057 const AnnotatedLine *Line,
58 bool DryRun) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +000059 LineState State;
Daniel Jasper567dcf92013-09-05 09:29:45 +000060 State.FirstIndent = FirstIndent;
Daniel Jasper6b2afe42013-08-16 11:20:30 +000061 State.Column = FirstIndent;
Daniel Jasper567dcf92013-09-05 09:29:45 +000062 State.Line = Line;
63 State.NextToken = Line->First;
Daniel Jasper6b2afe42013-08-16 11:20:30 +000064 State.Stack.push_back(ParenState(FirstIndent, FirstIndent,
65 /*AvoidBinPacking=*/false,
66 /*NoLineBreak=*/false));
67 State.LineContainsContinuedForLoopSection = false;
68 State.ParenLevel = 0;
69 State.StartOfStringLiteral = 0;
70 State.StartOfLineLevel = State.ParenLevel;
71 State.LowestLevelOnLine = State.ParenLevel;
72 State.IgnoreStackForComparison = false;
73
74 // The first token has already been indented and thus consumed.
Daniel Jasperb77d7412013-09-06 07:54:20 +000075 moveStateToNextToken(State, DryRun, /*Newline=*/false);
Daniel Jasper6b2afe42013-08-16 11:20:30 +000076 return State;
77}
78
79bool ContinuationIndenter::canBreak(const LineState &State) {
80 const FormatToken &Current = *State.NextToken;
81 const FormatToken &Previous = *Current.Previous;
82 assert(&Previous == Current.Previous);
83 if (!Current.CanBreakBefore &&
84 !(Current.is(tok::r_brace) && State.Stack.back().BreakBeforeClosingBrace))
85 return false;
86 // The opening "{" of a braced list has to be on the same line as the first
87 // element if it is nested in another braced init list or function call.
88 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
Daniel Jasper567dcf92013-09-05 09:29:45 +000089 Previous.BlockKind == BK_BracedInit && Previous.Previous &&
Daniel Jasper6b2afe42013-08-16 11:20:30 +000090 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
91 return false;
92 // This prevents breaks like:
93 // ...
94 // SomeParameter, OtherParameter).DoSomething(
95 // ...
96 // As they hide "DoSomething" and are generally bad for readability.
97 if (Previous.opensScope() && State.LowestLevelOnLine < State.StartOfLineLevel)
98 return false;
Daniel Jasperd3fef0f2013-08-27 14:24:43 +000099 if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
100 return false;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000101 return !State.Stack.back().NoLineBreak;
102}
103
104bool ContinuationIndenter::mustBreak(const LineState &State) {
105 const FormatToken &Current = *State.NextToken;
106 const FormatToken &Previous = *Current.Previous;
107 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
108 return true;
Daniel Jasper57981202013-09-13 09:20:45 +0000109 if ((!Style.Cpp11BracedListStyle ||
110 (Current.MatchingParen &&
111 Current.MatchingParen->BlockKind == BK_Block)) &&
112 Current.is(tok::r_brace) && State.Stack.back().BreakBeforeClosingBrace)
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000113 return true;
114 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
115 return true;
116 if (Style.BreakConstructorInitializersBeforeComma) {
117 if (Previous.Type == TT_CtorInitializerComma)
118 return false;
119 if (Current.Type == TT_CtorInitializerComma)
120 return true;
121 }
122 if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) ||
123 (Current.Type == TT_ConditionalExpr &&
124 !(Current.is(tok::colon) && Previous.is(tok::question)))) &&
125 State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
126 !Current.isOneOf(tok::r_paren, tok::r_brace))
127 return true;
128 if (Style.AlwaysBreakBeforeMultilineStrings &&
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000129 State.Column > State.Stack.back().Indent && // Breaking saves columns.
130 Previous.isNot(tok::lessless) && Previous.Type != TT_InlineASMColon &&
131 NextIsMultilineString(State))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000132 return true;
133
134 if (!Style.BreakBeforeBinaryOperators) {
135 // If we need to break somewhere inside the LHS of a binary expression, we
136 // should also break after the operator. Otherwise, the formatting would
137 // hide the operator precedence, e.g. in:
138 // if (aaaaaaaaaaaaaa ==
139 // bbbbbbbbbbbbbb && c) {..
140 // For comparisons, we only apply this rule, if the LHS is a binary
141 // expression itself as otherwise, the line breaks seem superfluous.
142 // We need special cases for ">>" which we have split into two ">" while
143 // lexing in order to make template parsing easier.
144 //
145 // FIXME: We'll need something similar for styles that break before binary
146 // operators.
147 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
148 Previous.getPrecedence() == prec::Equality) &&
149 Previous.Previous &&
150 Previous.Previous->Type != TT_BinaryOperator; // For >>.
151 bool LHSIsBinaryExpr =
Daniel Jasperdb4813a2013-09-06 08:08:14 +0000152 Previous.Previous && Previous.Previous->EndsBinaryExpression;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000153 if (Previous.Type == TT_BinaryOperator &&
154 (!IsComparison || LHSIsBinaryExpr) &&
155 Current.Type != TT_BinaryOperator && // For >>.
156 !Current.isTrailingComment() &&
157 !Previous.isOneOf(tok::lessless, tok::question) &&
158 Previous.getPrecedence() != prec::Assignment &&
159 State.Stack.back().BreakBeforeParameter)
160 return true;
161 }
162
163 // Same as above, but for the first "<<" operator.
164 if (Current.is(tok::lessless) && State.Stack.back().BreakBeforeParameter &&
165 State.Stack.back().FirstLessLess == 0)
166 return true;
167
168 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
169 // out whether it is the first parameter. Clean this up.
170 if (Current.Type == TT_ObjCSelectorName &&
171 Current.LongestObjCSelectorName == 0 &&
172 State.Stack.back().BreakBeforeParameter)
173 return true;
174 if ((Current.Type == TT_CtorInitializerColon ||
175 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0)))
176 return true;
177
178 if ((Current.Type == TT_StartOfName || Current.is(tok::kw_operator)) &&
Daniel Jasper567dcf92013-09-05 09:29:45 +0000179 State.Line->MightBeFunctionDecl &&
180 State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000181 return true;
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000182 if (startsSegmentOfBuilderTypeCall(Current) &&
Daniel Jaspereb331832013-08-30 07:12:40 +0000183 (State.Stack.back().CallContinuation != 0 ||
184 (State.Stack.back().BreakBeforeParameter &&
185 State.Stack.back().ContainsUnwrappedBuilder)))
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000186 return true;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000187 return false;
188}
189
190unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000191 bool DryRun,
192 unsigned ExtraSpaces) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000193 const FormatToken &Current = *State.NextToken;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000194
195 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
196 // FIXME: Is this correct?
197 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
198 State.NextToken->WhitespaceRange.getEnd()) -
199 SourceMgr.getSpellingColumnNumber(
200 State.NextToken->WhitespaceRange.getBegin());
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000201 State.Column += WhitespaceLength + State.NextToken->ColumnWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000202 State.NextToken = State.NextToken->Next;
203 return 0;
204 }
205
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000206 unsigned Penalty = 0;
207 if (Newline)
208 Penalty = addTokenOnNewLine(State, DryRun);
209 else
210 addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
211
212 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
213}
214
215void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
216 unsigned ExtraSpaces) {
217 const FormatToken &Current = *State.NextToken;
218 const FormatToken &Previous = *State.NextToken->Previous;
219 if (Current.is(tok::equal) &&
220 (State.Line->First->is(tok::kw_for) || State.ParenLevel == 0) &&
221 State.Stack.back().VariablePos == 0) {
222 State.Stack.back().VariablePos = State.Column;
223 // Move over * and & if they are bound to the variable name.
224 const FormatToken *Tok = &Previous;
225 while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
226 State.Stack.back().VariablePos -= Tok->ColumnWidth;
227 if (Tok->SpacesRequiredBefore != 0)
228 break;
229 Tok = Tok->Previous;
230 }
231 if (Previous.PartOfMultiVariableDeclStmt)
232 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
233 }
234
235 unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
236
237 if (!DryRun)
238 Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, /*IndentLevel=*/0,
239 Spaces, State.Column + Spaces);
240
241 if (Current.Type == TT_ObjCSelectorName && State.Stack.back().ColonPos == 0) {
242 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
243 State.Column + Spaces + Current.ColumnWidth)
244 State.Stack.back().ColonPos =
245 State.Stack.back().Indent + Current.LongestObjCSelectorName;
246 else
247 State.Stack.back().ColonPos = State.Column + Spaces + Current.ColumnWidth;
248 }
249
250 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
251 Current.Type != TT_LineComment)
252 State.Stack.back().Indent = State.Column + Spaces;
253 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
254 State.Stack.back().AvoidBinPacking)
255 State.Stack.back().NoLineBreak = true;
256 if (startsSegmentOfBuilderTypeCall(Current))
257 State.Stack.back().ContainsUnwrappedBuilder = true;
258
259 State.Column += Spaces;
260 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
261 // Treat the condition inside an if as if it was a second function
262 // parameter, i.e. let nested calls have an indent of 4.
263 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
264 else if (Previous.is(tok::comma))
265 State.Stack.back().LastSpace = State.Column;
266 else if ((Previous.Type == TT_BinaryOperator ||
267 Previous.Type == TT_ConditionalExpr ||
268 Previous.Type == TT_UnaryOperator ||
269 Previous.Type == TT_CtorInitializerColon) &&
270 (Previous.getPrecedence() != prec::Assignment ||
271 Current.StartsBinaryExpression))
272 // Always indent relative to the RHS of the expression unless this is a
273 // simple assignment without binary expression on the RHS. Also indent
274 // relative to unary operators and the colons of constructor initializers.
275 State.Stack.back().LastSpace = State.Column;
276 else if (Previous.Type == TT_InheritanceColon)
277 State.Stack.back().Indent = State.Column;
278 else if (Previous.opensScope()) {
279 // If a function has a trailing call, indent all parameters from the
280 // opening parenthesis. This avoids confusing indents like:
281 // OuterFunction(InnerFunctionCall( // break
282 // ParameterToInnerFunction)) // break
283 // .SecondInnerFunctionCall();
284 bool HasTrailingCall = false;
285 if (Previous.MatchingParen) {
286 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
287 HasTrailingCall = Next && Next->isMemberAccess();
288 }
289 if (HasTrailingCall &&
290 State.Stack[State.Stack.size() - 2].CallContinuation == 0)
291 State.Stack.back().LastSpace = State.Column;
292 }
293}
294
295unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
296 bool DryRun) {
297 const FormatToken &Current = *State.NextToken;
298 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000299 // If we are continuing an expression, we want to indent an extra 4 spaces.
300 unsigned ContinuationIndent =
301 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000302 // Extra penalty that needs to be added because of the way certain line
303 // breaks are chosen.
304 unsigned Penalty = 0;
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000305
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000306 const FormatToken *PreviousNonComment =
307 State.NextToken->getPreviousNonComment();
308 // The first line break on any ParenLevel causes an extra penalty in order
309 // prefer similar line breaks.
310 if (!State.Stack.back().ContainsLineBreak)
311 Penalty += 15;
312 State.Stack.back().ContainsLineBreak = true;
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000313
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000314 Penalty += State.NextToken->SplitPenalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000315
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000316 // Breaking before the first "<<" is generally not desirable if the LHS is
317 // short.
318 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0 &&
319 State.Column <= Style.ColumnLimit / 2)
320 Penalty += Style.PenaltyBreakFirstLessLess;
321
322 if (Current.is(tok::l_brace) && Current.BlockKind == BK_Block) {
323 State.Column = State.FirstIndent;
324 } else if (Current.is(tok::r_brace)) {
325 if (Current.MatchingParen &&
326 (Current.MatchingParen->BlockKind == BK_BracedInit ||
327 !Current.MatchingParen->Children.empty()))
328 State.Column = State.Stack[State.Stack.size() - 2].LastSpace;
329 else
Daniel Jasper57981202013-09-13 09:20:45 +0000330 State.Column = State.FirstIndent;
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000331 } else if (Current.is(tok::string_literal) &&
332 State.StartOfStringLiteral != 0) {
333 State.Column = State.StartOfStringLiteral;
334 State.Stack.back().BreakBeforeParameter = true;
335 } else if (Current.is(tok::lessless) &&
336 State.Stack.back().FirstLessLess != 0) {
337 State.Column = State.Stack.back().FirstLessLess;
338 } else if (Current.isMemberAccess()) {
339 if (State.Stack.back().CallContinuation == 0) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000340 State.Column = ContinuationIndent;
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000341 State.Stack.back().CallContinuation = State.Column;
342 } else {
343 State.Column = State.Stack.back().CallContinuation;
344 }
345 } else if (Current.Type == TT_ConditionalExpr) {
346 State.Column = State.Stack.back().QuestionColumn;
347 } else if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0) {
348 State.Column = State.Stack.back().VariablePos;
349 } else if ((PreviousNonComment &&
350 PreviousNonComment->ClosesTemplateDeclaration) ||
351 ((Current.Type == TT_StartOfName ||
352 Current.is(tok::kw_operator)) &&
353 State.ParenLevel == 0 &&
354 (!Style.IndentFunctionDeclarationAfterType ||
355 State.Line->StartsDefinition))) {
356 State.Column = State.Stack.back().Indent;
357 } else if (Current.Type == TT_ObjCSelectorName) {
358 if (State.Stack.back().ColonPos > Current.ColumnWidth) {
359 State.Column = State.Stack.back().ColonPos - Current.ColumnWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000360 } else {
361 State.Column = State.Stack.back().Indent;
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000362 State.Stack.back().ColonPos = State.Column + Current.ColumnWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000363 }
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000364 } else if (Current.is(tok::l_square) && Current.Type != TT_ObjCMethodExpr &&
365 Current.Type != TT_LambdaLSquare) {
366 if (State.Stack.back().StartOfArraySubscripts != 0)
367 State.Column = State.Stack.back().StartOfArraySubscripts;
368 else
369 State.Column = ContinuationIndent;
370 } else if (Current.Type == TT_StartOfName ||
371 Previous.isOneOf(tok::coloncolon, tok::equal) ||
372 Previous.Type == TT_ObjCMethodExpr) {
373 State.Column = ContinuationIndent;
374 } else if (Current.Type == TT_CtorInitializerColon) {
375 State.Column = State.FirstIndent + Style.ConstructorInitializerIndentWidth;
376 } else if (Current.Type == TT_CtorInitializerComma) {
377 State.Column = State.Stack.back().Indent;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000378 } else {
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000379 State.Column = State.Stack.back().Indent;
380 // Ensure that we fall back to indenting 4 spaces instead of just
381 // flushing continuations left.
382 if (State.Column == State.FirstIndent)
383 State.Column += 4;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000384 }
385
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000386 if (Current.is(tok::question))
387 State.Stack.back().BreakBeforeParameter = true;
388 if ((Previous.isOneOf(tok::comma, tok::semi) &&
389 !State.Stack.back().AvoidBinPacking) ||
390 Previous.Type == TT_BinaryOperator)
391 State.Stack.back().BreakBeforeParameter = false;
392 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
393 State.Stack.back().BreakBeforeParameter = false;
394
395 if (!DryRun) {
396 unsigned Newlines = 1;
397 if (Current.is(tok::comment))
398 Newlines = std::max(Newlines, std::min(Current.NewlinesBefore,
399 Style.MaxEmptyLinesToKeep + 1));
400 Whitespaces.replaceWhitespace(Current, Newlines, State.Line->Level,
401 State.Column, State.Column,
402 State.Line->InPPDirective);
403 }
404
405 if (!Current.isTrailingComment())
406 State.Stack.back().LastSpace = State.Column;
407 if (Current.isMemberAccess())
408 State.Stack.back().LastSpace += Current.ColumnWidth;
409 State.StartOfLineLevel = State.ParenLevel;
410 State.LowestLevelOnLine = State.ParenLevel;
411
412 // Any break on this level means that the parent level has been broken
413 // and we need to avoid bin packing there.
414 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
415 State.Stack[i].BreakBeforeParameter = true;
416 }
417 const FormatToken *TokenBefore = Current.getPreviousNonComment();
418 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
419 TokenBefore->Type != TT_TemplateCloser &&
420 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
421 State.Stack.back().BreakBeforeParameter = true;
422
423 // If we break after {, we should also break before the corresponding }.
424 if (Previous.is(tok::l_brace))
425 State.Stack.back().BreakBeforeClosingBrace = true;
426
427 if (State.Stack.back().AvoidBinPacking) {
428 // If we are breaking after '(', '{', '<', this is not bin packing
429 // unless AllowAllParametersOfDeclarationOnNextLine is false.
430 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
431 Previous.Type == TT_BinaryOperator) ||
432 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
433 State.Line->MustBeDeclaration))
434 State.Stack.back().BreakBeforeParameter = true;
435 }
436
437 return Penalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000438}
439
440unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
441 bool DryRun, bool Newline) {
442 const FormatToken &Current = *State.NextToken;
443 assert(State.Stack.size());
444
445 if (Current.Type == TT_InheritanceColon)
446 State.Stack.back().AvoidBinPacking = true;
447 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
448 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000449 if (Current.is(tok::l_square) && Current.Type != TT_LambdaLSquare &&
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000450 State.Stack.back().StartOfArraySubscripts == 0)
451 State.Stack.back().StartOfArraySubscripts = State.Column;
452 if (Current.is(tok::question))
453 State.Stack.back().QuestionColumn = State.Column;
454 if (!Current.opensScope() && !Current.closesScope())
455 State.LowestLevelOnLine =
456 std::min(State.LowestLevelOnLine, State.ParenLevel);
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000457 if (Current.isMemberAccess())
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000458 State.Stack.back().StartOfFunctionCall =
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000459 Current.LastInChainOfCalls ? 0 : State.Column + Current.ColumnWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000460 if (Current.Type == TT_CtorInitializerColon) {
461 // Indent 2 from the column, so:
462 // SomeClass::SomeClass()
463 // : First(...), ...
464 // Next(...)
465 // ^ line up here.
466 State.Stack.back().Indent =
467 State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
468 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
469 State.Stack.back().AvoidBinPacking = true;
470 State.Stack.back().BreakBeforeParameter = false;
471 }
472
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000473 // In ObjC method declaration we align on the ":" of parameters, but we need
474 // to ensure that we indent parameters on subsequent lines by at least 4.
475 if (Current.Type == TT_ObjCMethodSpecifier)
476 State.Stack.back().Indent += 4;
477
478 // Insert scopes created by fake parenthesis.
479 const FormatToken *Previous = Current.getPreviousNonComment();
480 // Don't add extra indentation for the first fake parenthesis after
481 // 'return', assignements or opening <({[. The indentation for these cases
482 // is special cased.
483 bool SkipFirstExtraIndent =
Daniel Jasperf78bf4a2013-09-30 08:29:03 +0000484 (Previous && (Previous->opensScope() || Previous->is(tok::kw_return) ||
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000485 Previous->getPrecedence() == prec::Assignment));
486 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
487 I = Current.FakeLParens.rbegin(),
488 E = Current.FakeLParens.rend();
489 I != E; ++I) {
490 ParenState NewParenState = State.Stack.back();
491 NewParenState.ContainsLineBreak = false;
Daniel Jasperf78bf4a2013-09-30 08:29:03 +0000492
493 // Indent from 'LastSpace' unless this the fake parentheses encapsulating a
494 // builder type call after 'return'. If such a call is line-wrapped, we
495 // commonly just want to indent from the start of the line.
496 if (!Previous || Previous->isNot(tok::kw_return) || *I > 0)
497 NewParenState.Indent =
498 std::max(std::max(State.Column, NewParenState.Indent),
499 State.Stack.back().LastSpace);
500
Daniel Jasper567dcf92013-09-05 09:29:45 +0000501 // Do not indent relative to the fake parentheses inserted for "." or "->".
502 // This is a special case to make the following to statements consistent:
503 // OuterFunction(InnerFunctionCall( // break
504 // ParameterToInnerFunction));
505 // OuterFunction(SomeObject.InnerFunctionCall( // break
506 // ParameterToInnerFunction));
507 if (*I > prec::Unknown)
508 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000509
510 // Always indent conditional expressions. Never indent expression where
511 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
512 // prec::Assignment) as those have different indentation rules. Indent
513 // other expression, unless the indentation needs to be skipped.
514 if (*I == prec::Conditional ||
515 (!SkipFirstExtraIndent && *I > prec::Assignment &&
516 !Style.BreakBeforeBinaryOperators))
517 NewParenState.Indent += 4;
518 if (Previous && !Previous->opensScope())
519 NewParenState.BreakBeforeParameter = false;
520 State.Stack.push_back(NewParenState);
521 SkipFirstExtraIndent = false;
522 }
523
524 // If we encounter an opening (, [, { or <, we add a level to our stacks to
525 // prepare for the following tokens.
526 if (Current.opensScope()) {
527 unsigned NewIndent;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000528 bool AvoidBinPacking;
529 if (Current.is(tok::l_brace)) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000530 if (Current.MatchingParen && Current.BlockKind == BK_Block) {
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000531 // If this is an l_brace starting a nested block, we pretend (wrt. to
532 // indentation) that we already consumed the corresponding r_brace.
533 // Thus, we remove all ParenStates caused bake fake parentheses that end
534 // at the r_brace. The net effect of this is that we don't indent
535 // relative to the l_brace, if the nested block is the last parameter of
536 // a function. For example, this formats:
537 //
538 // SomeFunction(a, [] {
539 // f(); // break
540 // });
541 //
542 // instead of:
543 // SomeFunction(a, [] {
544 // f(); // break
545 // });
Daniel Jasper567dcf92013-09-05 09:29:45 +0000546 for (unsigned i = 0; i != Current.MatchingParen->FakeRParens; ++i)
547 State.Stack.pop_back();
Daniel Jasper57981202013-09-13 09:20:45 +0000548 NewIndent = State.Stack.back().LastSpace + Style.IndentWidth;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000549 } else {
550 NewIndent = State.Stack.back().LastSpace +
551 (Style.Cpp11BracedListStyle ? 4 : Style.IndentWidth);
552 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000553 const FormatToken *NextNoComment = Current.getNextNonComment();
Daniel Jasper57981202013-09-13 09:20:45 +0000554 AvoidBinPacking = Current.BlockKind == BK_Block ||
555 (NextNoComment &&
556 NextNoComment->Type == TT_DesignatedInitializerPeriod);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000557 } else {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000558 NewIndent = 4 + std::max(State.Stack.back().LastSpace,
559 State.Stack.back().StartOfFunctionCall);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000560 AvoidBinPacking = !Style.BinPackParameters ||
561 (Style.ExperimentalAutoDetectBinPacking &&
562 (Current.PackingKind == PPK_OnePerLine ||
563 (!BinPackInconclusiveFunctions &&
564 Current.PackingKind == PPK_Inconclusive)));
565 }
566
Daniel Jasper567dcf92013-09-05 09:29:45 +0000567 State.Stack.push_back(ParenState(NewIndent, State.Stack.back().LastSpace,
568 AvoidBinPacking,
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000569 State.Stack.back().NoLineBreak));
Daniel Jasper57981202013-09-13 09:20:45 +0000570 State.Stack.back().BreakBeforeParameter = Current.BlockKind == BK_Block;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000571 ++State.ParenLevel;
572 }
573
574 // If this '[' opens an ObjC call, determine whether all parameters fit into
575 // one line and put one per line if they don't.
576 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
577 Current.MatchingParen != NULL) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000578 if (getLengthToMatchingParen(Current) + State.Column >
579 getColumnLimit(State))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000580 State.Stack.back().BreakBeforeParameter = true;
581 }
582
583 // If we encounter a closing ), ], } or >, we can remove a level from our
584 // stacks.
Daniel Jasper7143a212013-08-28 09:17:37 +0000585 if (State.Stack.size() > 1 &&
586 (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper567dcf92013-09-05 09:29:45 +0000587 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
Daniel Jasper7143a212013-08-28 09:17:37 +0000588 State.NextToken->Type == TT_TemplateCloser)) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000589 State.Stack.pop_back();
590 --State.ParenLevel;
591 }
592 if (Current.is(tok::r_square)) {
593 // If this ends the array subscript expr, reset the corresponding value.
594 const FormatToken *NextNonComment = Current.getNextNonComment();
595 if (NextNonComment && NextNonComment->isNot(tok::l_square))
596 State.Stack.back().StartOfArraySubscripts = 0;
597 }
598
599 // Remove scopes created by fake parenthesis.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000600 if (Current.isNot(tok::r_brace) ||
601 (Current.MatchingParen && Current.MatchingParen->BlockKind != BK_Block)) {
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000602 // Don't remove FakeRParens attached to r_braces that surround nested blocks
603 // as they will have been removed early (see above).
Daniel Jasper567dcf92013-09-05 09:29:45 +0000604 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
605 unsigned VariablePos = State.Stack.back().VariablePos;
606 State.Stack.pop_back();
607 State.Stack.back().VariablePos = VariablePos;
608 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000609 }
610
611 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
612 State.StartOfStringLiteral = State.Column;
613 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
614 tok::string_literal)) {
615 State.StartOfStringLiteral = 0;
616 }
617
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000618 State.Column += Current.ColumnWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000619 State.NextToken = State.NextToken->Next;
Daniel Jasperd489f8c2013-08-27 11:09:05 +0000620 unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000621 if (State.Column > getColumnLimit(State)) {
622 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
623 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
624 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000625
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000626 // If the previous has a special role, let it consume tokens as appropriate.
627 // It is necessary to start at the previous token for the only implemented
628 // role (comma separated list). That way, the decision whether or not to break
629 // after the "{" is already done and both options are tried and evaluated.
630 // FIXME: This is ugly, find a better way.
631 if (Previous && Previous->Role)
632 Penalty += Previous->Role->format(State, this, DryRun);
633
634 return Penalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000635}
636
Alexander Kornienko6f6154c2013-09-10 12:29:48 +0000637unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
638 LineState &State) {
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000639 // Break before further function parameters on all levels.
640 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
641 State.Stack[i].BreakBeforeParameter = true;
642
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000643 unsigned ColumnsUsed = State.Column;
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000644 // We can only affect layout of the first and the last line, so the penalty
645 // for all other lines is constant, and we ignore it.
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000646 State.Column = Current.LastLineColumnWidth;
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000647
Daniel Jasper567dcf92013-09-05 09:29:45 +0000648 if (ColumnsUsed > getColumnLimit(State))
649 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000650 return 0;
651}
652
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000653static bool getRawStringLiteralPrefixPostfix(StringRef Text,
654 StringRef &Prefix,
655 StringRef &Postfix) {
656 if (Text.startswith(Prefix = "R\"") || Text.startswith(Prefix = "uR\"") ||
657 Text.startswith(Prefix = "UR\"") || Text.startswith(Prefix = "u8R\"") ||
658 Text.startswith(Prefix = "LR\"")) {
659 size_t ParenPos = Text.find('(');
660 if (ParenPos != StringRef::npos) {
661 StringRef Delimiter =
662 Text.substr(Prefix.size(), ParenPos - Prefix.size());
663 Prefix = Text.substr(0, ParenPos + 1);
664 Postfix = Text.substr(Text.size() - 2 - Delimiter.size());
665 return Postfix.front() == ')' && Postfix.back() == '"' &&
666 Postfix.substr(1).startswith(Delimiter);
667 }
668 }
669 return false;
670}
671
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000672unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
673 LineState &State,
674 bool DryRun) {
Alexander Kornienko6f6154c2013-09-10 12:29:48 +0000675 // Don't break multi-line tokens other than block comments. Instead, just
676 // update the state.
677 if (Current.Type != TT_BlockComment && Current.IsMultiline)
678 return addMultilineToken(Current, State);
679
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000680 if (!Current.isOneOf(tok::string_literal, tok::wide_string_literal,
681 tok::utf8_string_literal, tok::utf16_string_literal,
682 tok::utf32_string_literal, tok::comment))
Daniel Jaspered51c022013-08-23 10:05:49 +0000683 return 0;
684
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000685 llvm::OwningPtr<BreakableToken> Token;
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000686 unsigned StartColumn = State.Column - Current.ColumnWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000687
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000688 if (Current.isOneOf(tok::string_literal, tok::wide_string_literal,
689 tok::utf8_string_literal, tok::utf16_string_literal,
690 tok::utf32_string_literal) &&
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000691 Current.Type != TT_ImplicitStringLiteral) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000692 // Exempts unterminated string literals from line breaking. The user will
693 // likely want to terminate the string before any line breaking is done.
694 if (Current.IsUnterminatedLiteral)
695 return 0;
696
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000697 StringRef Text = Current.TokenText;
698 StringRef Prefix;
699 StringRef Postfix;
700 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
701 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
702 // reduce the overhead) for each FormatToken, which is a string, so that we
703 // don't run multiple checks here on the hot path.
704 if ((Text.endswith(Postfix = "\"") &&
705 (Text.startswith(Prefix = "\"") || Text.startswith(Prefix = "u\"") ||
706 Text.startswith(Prefix = "U\"") || Text.startswith(Prefix = "u8\"") ||
707 Text.startswith(Prefix = "L\""))) ||
708 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")")) ||
709 getRawStringLiteralPrefixPostfix(Text, Prefix, Postfix)) {
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000710 Token.reset(new BreakableStringLiteral(
711 Current, State.Line->Level, StartColumn, Prefix, Postfix,
712 State.Line->InPPDirective, Encoding, Style));
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000713 } else {
714 return 0;
715 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000716 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
717 Token.reset(new BreakableBlockComment(
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000718 Current, State.Line->Level, StartColumn, Current.OriginalColumn,
719 !Current.Previous, State.Line->InPPDirective, Encoding, Style));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000720 } else if (Current.Type == TT_LineComment &&
721 (Current.Previous == NULL ||
722 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000723 Token.reset(new BreakableLineComment(Current, State.Line->Level,
724 StartColumn, State.Line->InPPDirective,
725 Encoding, Style));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000726 } else {
727 return 0;
728 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000729 if (Current.UnbreakableTailLength >= getColumnLimit(State))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000730 return 0;
731
Daniel Jasper567dcf92013-09-05 09:29:45 +0000732 unsigned RemainingSpace =
733 getColumnLimit(State) - Current.UnbreakableTailLength;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000734 bool BreakInserted = false;
735 unsigned Penalty = 0;
736 unsigned RemainingTokenColumns = 0;
737 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
738 LineIndex != EndIndex; ++LineIndex) {
739 if (!DryRun)
740 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
741 unsigned TailOffset = 0;
742 RemainingTokenColumns =
743 Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
744 while (RemainingTokenColumns > RemainingSpace) {
745 BreakableToken::Split Split =
Daniel Jasper567dcf92013-09-05 09:29:45 +0000746 Token->getSplit(LineIndex, TailOffset, getColumnLimit(State));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000747 if (Split.first == StringRef::npos) {
748 // The last line's penalty is handled in addNextStateToQueue().
749 if (LineIndex < EndIndex - 1)
750 Penalty += Style.PenaltyExcessCharacter *
751 (RemainingTokenColumns - RemainingSpace);
752 break;
753 }
754 assert(Split.first != 0);
755 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
756 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
757 assert(NewRemainingTokenColumns < RemainingTokenColumns);
758 if (!DryRun)
759 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Daniel Jasperf5461782013-08-28 10:03:58 +0000760 Penalty += Current.SplitPenalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000761 unsigned ColumnsUsed =
762 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000763 if (ColumnsUsed > getColumnLimit(State)) {
764 Penalty += Style.PenaltyExcessCharacter *
765 (ColumnsUsed - getColumnLimit(State));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000766 }
767 TailOffset += Split.first + Split.second;
768 RemainingTokenColumns = NewRemainingTokenColumns;
769 BreakInserted = true;
770 }
771 }
772
773 State.Column = RemainingTokenColumns;
774
775 if (BreakInserted) {
776 // If we break the token inside a parameter list, we need to break before
777 // the next parameter on all levels, so that the next parameter is clearly
778 // visible. Line comments already introduce a break.
779 if (Current.Type != TT_LineComment) {
780 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
781 State.Stack[i].BreakBeforeParameter = true;
782 }
783
Daniel Jasperf5461782013-08-28 10:03:58 +0000784 Penalty += Current.is(tok::string_literal) ? Style.PenaltyBreakString
785 : Style.PenaltyBreakComment;
786
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000787 State.Stack.back().LastSpace = StartColumn;
788 }
789 return Penalty;
790}
791
Daniel Jasper567dcf92013-09-05 09:29:45 +0000792unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000793 // In preprocessor directives reserve two chars for trailing " \"
Daniel Jasper567dcf92013-09-05 09:29:45 +0000794 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000795}
796
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000797bool ContinuationIndenter::NextIsMultilineString(const LineState &State) {
798 const FormatToken &Current = *State.NextToken;
799 if (!Current.is(tok::string_literal))
800 return false;
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000801 // We never consider raw string literals "multiline" for the purpose of
802 // AlwaysBreakBeforeMultilineStrings implementation.
803 if (Current.TokenText.startswith("R\""))
804 return false;
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000805 if (Current.IsMultiline)
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000806 return true;
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000807 if (Current.getNextNonComment() &&
808 Current.getNextNonComment()->is(tok::string_literal))
809 return true; // Implicit concatenation.
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000810 if (State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000811 Style.ColumnLimit)
812 return true; // String will be split.
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000813 return false;
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000814}
815
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000816} // namespace format
817} // namespace clang