blob: 10295197240d104ee066d8176238c8d1fdc7226c [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 Jasperb27c4b72013-08-27 11:09:05 +000041// Returns \c true if \c Tok starts a binary expression.
42static bool startsBinaryExpression(const FormatToken &Tok) {
43 for (unsigned i = 0, e = Tok.FakeLParens.size(); i != e; ++i) {
44 if (Tok.FakeLParens[i] > prec::Unknown)
45 return true;
46 }
47 return false;
48}
49
Daniel Jasper4c6e0052013-08-27 14:24:43 +000050// Returns \c true if \c Tok is the "." or "->" of a call and starts the next
51// segment of a builder type call.
52static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) {
53 return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope();
54}
55
Daniel Jasperde0328a2013-08-16 11:20:30 +000056ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,
57 SourceManager &SourceMgr,
58 const AnnotatedLine &Line,
59 unsigned FirstIndent,
60 WhitespaceManager &Whitespaces,
61 encoding::Encoding Encoding,
62 bool BinPackInconclusiveFunctions)
63 : Style(Style), SourceMgr(SourceMgr), Line(Line), FirstIndent(FirstIndent),
64 Whitespaces(Whitespaces), Encoding(Encoding),
65 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions) {}
66
67LineState ContinuationIndenter::getInitialState() {
68 // Initialize state dependent on indent.
69 LineState State;
70 State.Column = FirstIndent;
71 State.NextToken = Line.First;
72 State.Stack.push_back(ParenState(FirstIndent, FirstIndent,
73 /*AvoidBinPacking=*/false,
74 /*NoLineBreak=*/false));
75 State.LineContainsContinuedForLoopSection = false;
76 State.ParenLevel = 0;
77 State.StartOfStringLiteral = 0;
78 State.StartOfLineLevel = State.ParenLevel;
79 State.LowestLevelOnLine = State.ParenLevel;
80 State.IgnoreStackForComparison = false;
81
82 // The first token has already been indented and thus consumed.
83 moveStateToNextToken(State, /*DryRun=*/false,
84 /*Newline=*/false);
85 return State;
86}
87
88bool ContinuationIndenter::canBreak(const LineState &State) {
89 const FormatToken &Current = *State.NextToken;
90 const FormatToken &Previous = *Current.Previous;
91 assert(&Previous == Current.Previous);
92 if (!Current.CanBreakBefore &&
93 !(Current.is(tok::r_brace) && State.Stack.back().BreakBeforeClosingBrace))
94 return false;
95 // The opening "{" of a braced list has to be on the same line as the first
96 // element if it is nested in another braced init list or function call.
97 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
98 Previous.Previous &&
99 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
100 return false;
101 // This prevents breaks like:
102 // ...
103 // SomeParameter, OtherParameter).DoSomething(
104 // ...
105 // As they hide "DoSomething" and are generally bad for readability.
106 if (Previous.opensScope() && State.LowestLevelOnLine < State.StartOfLineLevel)
107 return false;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000108 if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
109 return false;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000110 return !State.Stack.back().NoLineBreak;
111}
112
113bool ContinuationIndenter::mustBreak(const LineState &State) {
114 const FormatToken &Current = *State.NextToken;
115 const FormatToken &Previous = *Current.Previous;
116 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
117 return true;
118 if (!Style.Cpp11BracedListStyle && Current.is(tok::r_brace) &&
119 State.Stack.back().BreakBeforeClosingBrace)
120 return true;
121 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
122 return true;
123 if (Style.BreakConstructorInitializersBeforeComma) {
124 if (Previous.Type == TT_CtorInitializerComma)
125 return false;
126 if (Current.Type == TT_CtorInitializerComma)
127 return true;
128 }
129 if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) ||
130 (Current.Type == TT_ConditionalExpr &&
131 !(Current.is(tok::colon) && Previous.is(tok::question)))) &&
132 State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
133 !Current.isOneOf(tok::r_paren, tok::r_brace))
134 return true;
135 if (Style.AlwaysBreakBeforeMultilineStrings &&
Daniel Jasperf438cb72013-08-23 11:57:34 +0000136 State.Column > State.Stack.back().Indent && // Breaking saves columns.
137 Previous.isNot(tok::lessless) && Previous.Type != TT_InlineASMColon &&
138 NextIsMultilineString(State))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000139 return true;
140
141 if (!Style.BreakBeforeBinaryOperators) {
142 // If we need to break somewhere inside the LHS of a binary expression, we
143 // should also break after the operator. Otherwise, the formatting would
144 // hide the operator precedence, e.g. in:
145 // if (aaaaaaaaaaaaaa ==
146 // bbbbbbbbbbbbbb && c) {..
147 // For comparisons, we only apply this rule, if the LHS is a binary
148 // expression itself as otherwise, the line breaks seem superfluous.
149 // We need special cases for ">>" which we have split into two ">" while
150 // lexing in order to make template parsing easier.
151 //
152 // FIXME: We'll need something similar for styles that break before binary
153 // operators.
154 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
155 Previous.getPrecedence() == prec::Equality) &&
156 Previous.Previous &&
157 Previous.Previous->Type != TT_BinaryOperator; // For >>.
158 bool LHSIsBinaryExpr =
159 Previous.Previous && Previous.Previous->FakeRParens > 0;
160 if (Previous.Type == TT_BinaryOperator &&
161 (!IsComparison || LHSIsBinaryExpr) &&
162 Current.Type != TT_BinaryOperator && // For >>.
163 !Current.isTrailingComment() &&
164 !Previous.isOneOf(tok::lessless, tok::question) &&
165 Previous.getPrecedence() != prec::Assignment &&
166 State.Stack.back().BreakBeforeParameter)
167 return true;
168 }
169
170 // Same as above, but for the first "<<" operator.
171 if (Current.is(tok::lessless) && State.Stack.back().BreakBeforeParameter &&
172 State.Stack.back().FirstLessLess == 0)
173 return true;
174
175 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
176 // out whether it is the first parameter. Clean this up.
177 if (Current.Type == TT_ObjCSelectorName &&
178 Current.LongestObjCSelectorName == 0 &&
179 State.Stack.back().BreakBeforeParameter)
180 return true;
181 if ((Current.Type == TT_CtorInitializerColon ||
182 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0)))
183 return true;
184
185 if ((Current.Type == TT_StartOfName || Current.is(tok::kw_operator)) &&
186 Line.MightBeFunctionDecl && State.Stack.back().BreakBeforeParameter &&
187 State.ParenLevel == 0)
188 return true;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000189 if (startsSegmentOfBuilderTypeCall(Current) &&
Daniel Jasperf8151e92013-08-30 07:12:40 +0000190 (State.Stack.back().CallContinuation != 0 ||
191 (State.Stack.back().BreakBeforeParameter &&
192 State.Stack.back().ContainsUnwrappedBuilder)))
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000193 return true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000194 return false;
195}
196
197unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000198 bool DryRun,
199 unsigned ExtraSpaces) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000200 const FormatToken &Current = *State.NextToken;
201 const FormatToken &Previous = *State.NextToken->Previous;
202
203 // Extra penalty that needs to be added because of the way certain line
204 // breaks are chosen.
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000205 unsigned Penalty = 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000206
207 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
208 // FIXME: Is this correct?
209 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
210 State.NextToken->WhitespaceRange.getEnd()) -
211 SourceMgr.getSpellingColumnNumber(
212 State.NextToken->WhitespaceRange.getBegin());
213 State.Column += WhitespaceLength + State.NextToken->CodePointCount;
214 State.NextToken = State.NextToken->Next;
215 return 0;
216 }
217
218 // If we are continuing an expression, we want to indent an extra 4 spaces.
219 unsigned ContinuationIndent =
220 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
221 if (Newline) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000222 // The first line break on any ParenLevel causes an extra penalty in order
223 // prefer similar line breaks.
224 if (!State.Stack.back().ContainsLineBreak)
225 Penalty += 15;
226 State.Stack.back().ContainsLineBreak = true;
227
228 Penalty += State.NextToken->SplitPenalty;
229
Daniel Jasperde0328a2013-08-16 11:20:30 +0000230 // Breaking before the first "<<" is generally not desirable if the LHS is
231 // short.
232 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0 &&
233 State.Column <= Style.ColumnLimit / 2)
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000234 Penalty += Style.PenaltyBreakFirstLessLess;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000235
Daniel Jasperde0328a2013-08-16 11:20:30 +0000236 if (Current.is(tok::r_brace)) {
237 if (Current.BlockKind == BK_BracedInit)
238 State.Column = State.Stack[State.Stack.size() - 2].LastSpace;
239 else
240 State.Column = FirstIndent;
241 } else if (Current.is(tok::string_literal) &&
242 State.StartOfStringLiteral != 0) {
243 State.Column = State.StartOfStringLiteral;
244 State.Stack.back().BreakBeforeParameter = true;
245 } else if (Current.is(tok::lessless) &&
246 State.Stack.back().FirstLessLess != 0) {
247 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000248 } else if (Current.isMemberAccess()) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000249 if (State.Stack.back().CallContinuation == 0) {
250 State.Column = ContinuationIndent;
251 State.Stack.back().CallContinuation = State.Column;
252 } else {
253 State.Column = State.Stack.back().CallContinuation;
254 }
255 } else if (Current.Type == TT_ConditionalExpr) {
256 State.Column = State.Stack.back().QuestionColumn;
257 } else if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0) {
258 State.Column = State.Stack.back().VariablePos;
259 } else if (Previous.ClosesTemplateDeclaration ||
260 ((Current.Type == TT_StartOfName ||
261 Current.is(tok::kw_operator)) &&
262 State.ParenLevel == 0 &&
263 (!Style.IndentFunctionDeclarationAfterType ||
264 Line.StartsDefinition))) {
265 State.Column = State.Stack.back().Indent;
266 } else if (Current.Type == TT_ObjCSelectorName) {
267 if (State.Stack.back().ColonPos > Current.CodePointCount) {
268 State.Column = State.Stack.back().ColonPos - Current.CodePointCount;
269 } else {
270 State.Column = State.Stack.back().Indent;
271 State.Stack.back().ColonPos = State.Column + Current.CodePointCount;
272 }
273 } else if (Current.is(tok::l_square) && Current.Type != TT_ObjCMethodExpr) {
274 if (State.Stack.back().StartOfArraySubscripts != 0)
275 State.Column = State.Stack.back().StartOfArraySubscripts;
276 else
277 State.Column = ContinuationIndent;
278 } else if (Current.Type == TT_StartOfName ||
279 Previous.isOneOf(tok::coloncolon, tok::equal) ||
280 Previous.Type == TT_ObjCMethodExpr) {
281 State.Column = ContinuationIndent;
282 } else if (Current.Type == TT_CtorInitializerColon) {
283 State.Column = FirstIndent + Style.ConstructorInitializerIndentWidth;
284 } else if (Current.Type == TT_CtorInitializerComma) {
285 State.Column = State.Stack.back().Indent;
286 } else {
287 State.Column = State.Stack.back().Indent;
288 // Ensure that we fall back to indenting 4 spaces instead of just
289 // flushing continuations left.
290 if (State.Column == FirstIndent)
291 State.Column += 4;
292 }
293
294 if (Current.is(tok::question))
295 State.Stack.back().BreakBeforeParameter = true;
296 if ((Previous.isOneOf(tok::comma, tok::semi) &&
297 !State.Stack.back().AvoidBinPacking) ||
298 Previous.Type == TT_BinaryOperator)
299 State.Stack.back().BreakBeforeParameter = false;
300 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
301 State.Stack.back().BreakBeforeParameter = false;
302
303 if (!DryRun) {
304 unsigned NewLines = 1;
305 if (Current.is(tok::comment))
306 NewLines = std::max(NewLines, std::min(Current.NewlinesBefore,
307 Style.MaxEmptyLinesToKeep + 1));
308 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
309 State.Column, Line.InPPDirective);
310 }
311
312 if (!Current.isTrailingComment())
313 State.Stack.back().LastSpace = State.Column;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000314 if (Current.isMemberAccess())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000315 State.Stack.back().LastSpace += Current.CodePointCount;
316 State.StartOfLineLevel = State.ParenLevel;
317 State.LowestLevelOnLine = State.ParenLevel;
318
319 // Any break on this level means that the parent level has been broken
320 // and we need to avoid bin packing there.
321 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
322 State.Stack[i].BreakBeforeParameter = true;
323 }
324 const FormatToken *TokenBefore = Current.getPreviousNonComment();
325 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
326 TokenBefore->Type != TT_TemplateCloser &&
327 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
328 State.Stack.back().BreakBeforeParameter = true;
329
330 // If we break after {, we should also break before the corresponding }.
331 if (Previous.is(tok::l_brace))
332 State.Stack.back().BreakBeforeClosingBrace = true;
333
334 if (State.Stack.back().AvoidBinPacking) {
335 // If we are breaking after '(', '{', '<', this is not bin packing
336 // unless AllowAllParametersOfDeclarationOnNextLine is false.
337 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
338 Previous.Type == TT_BinaryOperator) ||
339 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
340 Line.MustBeDeclaration))
341 State.Stack.back().BreakBeforeParameter = true;
342 }
343
344 } else {
345 if (Current.is(tok::equal) &&
346 (Line.First->is(tok::kw_for) || State.ParenLevel == 0) &&
347 State.Stack.back().VariablePos == 0) {
348 State.Stack.back().VariablePos = State.Column;
349 // Move over * and & if they are bound to the variable name.
350 const FormatToken *Tok = &Previous;
351 while (Tok && State.Stack.back().VariablePos >= Tok->CodePointCount) {
352 State.Stack.back().VariablePos -= Tok->CodePointCount;
353 if (Tok->SpacesRequiredBefore != 0)
354 break;
355 Tok = Tok->Previous;
356 }
357 if (Previous.PartOfMultiVariableDeclStmt)
358 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
359 }
360
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000361 unsigned Spaces = State.NextToken->SpacesRequiredBefore + ExtraSpaces;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000362
363 if (!DryRun)
364 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column + Spaces);
365
366 if (Current.Type == TT_ObjCSelectorName &&
367 State.Stack.back().ColonPos == 0) {
368 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
369 State.Column + Spaces + Current.CodePointCount)
370 State.Stack.back().ColonPos =
371 State.Stack.back().Indent + Current.LongestObjCSelectorName;
372 else
373 State.Stack.back().ColonPos =
374 State.Column + Spaces + Current.CodePointCount;
375 }
376
377 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
378 Current.Type != TT_LineComment)
379 State.Stack.back().Indent = State.Column + Spaces;
380 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
381 State.Stack.back().AvoidBinPacking)
382 State.Stack.back().NoLineBreak = true;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000383 if (startsSegmentOfBuilderTypeCall(Current))
384 State.Stack.back().ContainsUnwrappedBuilder = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000385
386 State.Column += Spaces;
387 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
388 // Treat the condition inside an if as if it was a second function
389 // parameter, i.e. let nested calls have an indent of 4.
390 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
391 else if (Previous.is(tok::comma))
392 State.Stack.back().LastSpace = State.Column;
393 else if ((Previous.Type == TT_BinaryOperator ||
394 Previous.Type == TT_ConditionalExpr ||
Daniel Jasperf110e202013-08-21 08:39:01 +0000395 Previous.Type == TT_UnaryOperator ||
Daniel Jasperde0328a2013-08-16 11:20:30 +0000396 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasperb27c4b72013-08-27 11:09:05 +0000397 (Previous.getPrecedence() != prec::Assignment ||
398 startsBinaryExpression(Current)))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000399 // Always indent relative to the RHS of the expression unless this is a
Daniel Jasperf110e202013-08-21 08:39:01 +0000400 // simple assignment without binary expression on the RHS. Also indent
401 // relative to unary operators and the colons of constructor initializers.
Daniel Jasperde0328a2013-08-16 11:20:30 +0000402 State.Stack.back().LastSpace = State.Column;
403 else if (Previous.Type == TT_InheritanceColon)
404 State.Stack.back().Indent = State.Column;
405 else if (Previous.opensScope()) {
406 // If a function has multiple parameters (including a single parameter
407 // that is a binary expression) or a trailing call, indent all
408 // parameters from the opening parenthesis. This avoids confusing
409 // indents like:
410 // OuterFunction(InnerFunctionCall(
411 // ParameterToInnerFunction),
412 // SecondParameterToOuterFunction);
413 bool HasMultipleParameters = !Current.FakeLParens.empty();
414 bool HasTrailingCall = false;
415 if (Previous.MatchingParen) {
416 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000417 HasTrailingCall = Next && Next->isMemberAccess();
Daniel Jasperde0328a2013-08-16 11:20:30 +0000418 }
Daniel Jasperb27c4b72013-08-27 11:09:05 +0000419 if (HasMultipleParameters ||
420 (HasTrailingCall &&
421 State.Stack[State.Stack.size() - 2].CallContinuation == 0))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000422 State.Stack.back().LastSpace = State.Column;
423 }
424 }
425
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000426 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000427}
428
429unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
430 bool DryRun, bool Newline) {
431 const FormatToken &Current = *State.NextToken;
432 assert(State.Stack.size());
433
434 if (Current.Type == TT_InheritanceColon)
435 State.Stack.back().AvoidBinPacking = true;
436 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
437 State.Stack.back().FirstLessLess = State.Column;
438 if (Current.is(tok::l_square) &&
439 State.Stack.back().StartOfArraySubscripts == 0)
440 State.Stack.back().StartOfArraySubscripts = State.Column;
441 if (Current.is(tok::question))
442 State.Stack.back().QuestionColumn = State.Column;
443 if (!Current.opensScope() && !Current.closesScope())
444 State.LowestLevelOnLine =
445 std::min(State.LowestLevelOnLine, State.ParenLevel);
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000446 if (Current.isMemberAccess())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000447 State.Stack.back().StartOfFunctionCall =
448 Current.LastInChainOfCalls ? 0 : State.Column + Current.CodePointCount;
449 if (Current.Type == TT_CtorInitializerColon) {
450 // Indent 2 from the column, so:
451 // SomeClass::SomeClass()
452 // : First(...), ...
453 // Next(...)
454 // ^ line up here.
455 State.Stack.back().Indent =
456 State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
457 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
458 State.Stack.back().AvoidBinPacking = true;
459 State.Stack.back().BreakBeforeParameter = false;
460 }
461
462 // If return returns a binary expression, align after it.
463 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
464 State.Stack.back().LastSpace = State.Column + 7;
465
466 // In ObjC method declaration we align on the ":" of parameters, but we need
467 // to ensure that we indent parameters on subsequent lines by at least 4.
468 if (Current.Type == TT_ObjCMethodSpecifier)
469 State.Stack.back().Indent += 4;
470
471 // Insert scopes created by fake parenthesis.
472 const FormatToken *Previous = Current.getPreviousNonComment();
473 // Don't add extra indentation for the first fake parenthesis after
474 // 'return', assignements or opening <({[. The indentation for these cases
475 // is special cased.
476 bool SkipFirstExtraIndent =
477 Current.is(tok::kw_return) ||
478 (Previous && (Previous->opensScope() ||
479 Previous->getPrecedence() == prec::Assignment));
480 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
481 I = Current.FakeLParens.rbegin(),
482 E = Current.FakeLParens.rend();
483 I != E; ++I) {
484 ParenState NewParenState = State.Stack.back();
485 NewParenState.ContainsLineBreak = false;
486 NewParenState.Indent =
487 std::max(std::max(State.Column, NewParenState.Indent),
488 State.Stack.back().LastSpace);
489
490 // Always indent conditional expressions. Never indent expression where
491 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
492 // prec::Assignment) as those have different indentation rules. Indent
493 // other expression, unless the indentation needs to be skipped.
494 if (*I == prec::Conditional ||
495 (!SkipFirstExtraIndent && *I > prec::Assignment &&
496 !Style.BreakBeforeBinaryOperators))
497 NewParenState.Indent += 4;
498 if (Previous && !Previous->opensScope())
499 NewParenState.BreakBeforeParameter = false;
500 State.Stack.push_back(NewParenState);
501 SkipFirstExtraIndent = false;
502 }
503
504 // If we encounter an opening (, [, { or <, we add a level to our stacks to
505 // prepare for the following tokens.
506 if (Current.opensScope()) {
507 unsigned NewIndent;
508 unsigned LastSpace = State.Stack.back().LastSpace;
509 bool AvoidBinPacking;
510 if (Current.is(tok::l_brace)) {
511 NewIndent =
512 LastSpace + (Style.Cpp11BracedListStyle ? 4 : Style.IndentWidth);
513 const FormatToken *NextNoComment = Current.getNextNonComment();
514 AvoidBinPacking = NextNoComment &&
515 NextNoComment->Type == TT_DesignatedInitializerPeriod;
516 } else {
517 NewIndent =
518 4 + std::max(LastSpace, State.Stack.back().StartOfFunctionCall);
519 AvoidBinPacking = !Style.BinPackParameters ||
520 (Style.ExperimentalAutoDetectBinPacking &&
521 (Current.PackingKind == PPK_OnePerLine ||
522 (!BinPackInconclusiveFunctions &&
523 Current.PackingKind == PPK_Inconclusive)));
524 }
525
526 State.Stack.push_back(ParenState(NewIndent, LastSpace, AvoidBinPacking,
527 State.Stack.back().NoLineBreak));
528 ++State.ParenLevel;
529 }
530
531 // If this '[' opens an ObjC call, determine whether all parameters fit into
532 // one line and put one per line if they don't.
533 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
534 Current.MatchingParen != NULL) {
535 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
536 State.Stack.back().BreakBeforeParameter = true;
537 }
538
539 // If we encounter a closing ), ], } or >, we can remove a level from our
540 // stacks.
Daniel Jasper96df37a2013-08-28 09:17:37 +0000541 if (State.Stack.size() > 1 &&
542 (Current.isOneOf(tok::r_paren, tok::r_square) ||
543 (Current.is(tok::r_brace) && State.NextToken != Line.First) ||
544 State.NextToken->Type == TT_TemplateCloser)) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000545 State.Stack.pop_back();
546 --State.ParenLevel;
547 }
548 if (Current.is(tok::r_square)) {
549 // If this ends the array subscript expr, reset the corresponding value.
550 const FormatToken *NextNonComment = Current.getNextNonComment();
551 if (NextNonComment && NextNonComment->isNot(tok::l_square))
552 State.Stack.back().StartOfArraySubscripts = 0;
553 }
554
555 // Remove scopes created by fake parenthesis.
556 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
557 unsigned VariablePos = State.Stack.back().VariablePos;
558 State.Stack.pop_back();
559 State.Stack.back().VariablePos = VariablePos;
560 }
561
562 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
563 State.StartOfStringLiteral = State.Column;
564 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
565 tok::string_literal)) {
566 State.StartOfStringLiteral = 0;
567 }
568
569 State.Column += Current.CodePointCount;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000570 State.NextToken = State.NextToken->Next;
Daniel Jasperb27c4b72013-08-27 11:09:05 +0000571 unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000572
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000573 // If the previous has a special role, let it consume tokens as appropriate.
574 // It is necessary to start at the previous token for the only implemented
575 // role (comma separated list). That way, the decision whether or not to break
576 // after the "{" is already done and both options are tried and evaluated.
577 // FIXME: This is ugly, find a better way.
578 if (Previous && Previous->Role)
579 Penalty += Previous->Role->format(State, this, DryRun);
580
581 return Penalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000582}
583
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000584unsigned
585ContinuationIndenter::addMultilineStringLiteral(const FormatToken &Current,
586 LineState &State) {
587 StringRef Text = Current.TokenText;
588 // We can only affect layout of the first and the last line, so the penalty
589 // for all other lines is constant, and we ignore it.
590 size_t FirstLineBreak = Text.find('\n');
591 size_t LastLineBreak = Text.find_last_of('\n');
592 assert(FirstLineBreak != StringRef::npos);
593 unsigned StartColumn = State.Column - Current.CodePointCount;
594 State.Column =
595 encoding::getCodePointCount(Text.substr(LastLineBreak + 1), Encoding);
596
597 // Break before further function parameters on all levels.
598 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
599 State.Stack[i].BreakBeforeParameter = true;
600
601 unsigned ColumnsUsed =
602 StartColumn +
603 encoding::getCodePointCount(Text.substr(0, FirstLineBreak), Encoding);
604 if (ColumnsUsed > getColumnLimit())
605 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit());
606 return 0;
607}
608
Daniel Jasperde0328a2013-08-16 11:20:30 +0000609unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
610 LineState &State,
611 bool DryRun) {
Daniel Jasperf93551c2013-08-23 10:05:49 +0000612 if (!Current.isOneOf(tok::string_literal, tok::comment))
613 return 0;
614
Daniel Jasperde0328a2013-08-16 11:20:30 +0000615 llvm::OwningPtr<BreakableToken> Token;
616 unsigned StartColumn = State.Column - Current.CodePointCount;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000617
618 if (Current.is(tok::string_literal) &&
619 Current.Type != TT_ImplicitStringLiteral) {
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000620 // Don't break string literals with (in case of non-raw strings, escaped)
621 // newlines. As clang-format must not change the string's content, it is
622 // unlikely that we'll end up with a better format.
623 if (Current.IsMultiline)
624 return addMultilineStringLiteral(Current, State);
625
Daniel Jasperde0328a2013-08-16 11:20:30 +0000626 // Only break up default narrow strings.
627 if (!Current.TokenText.startswith("\""))
628 return 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000629 // Exempts unterminated string literals from line breaking. The user will
630 // likely want to terminate the string before any line breaking is done.
631 if (Current.IsUnterminatedLiteral)
632 return 0;
633
634 Token.reset(new BreakableStringLiteral(Current, StartColumn,
635 Line.InPPDirective, Encoding));
636 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000637 unsigned OriginalStartColumn =
638 SourceMgr.getSpellingColumnNumber(Current.getStartOfNonWhitespace()) -
639 1;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000640 Token.reset(new BreakableBlockComment(
641 Style, Current, StartColumn, OriginalStartColumn, !Current.Previous,
642 Line.InPPDirective, Encoding));
643 } else if (Current.Type == TT_LineComment &&
644 (Current.Previous == NULL ||
645 Current.Previous->Type != TT_ImplicitStringLiteral)) {
646 // Don't break line comments with escaped newlines. These look like
647 // separate line comments, but in fact contain a single line comment with
648 // multiple lines including leading whitespace and the '//' markers.
649 //
650 // FIXME: If we want to handle them correctly, we'll need to adjust
651 // leading whitespace in consecutive lines when changing indentation of
652 // the first line similar to what we do with block comments.
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000653 if (Current.IsMultiline) {
654 StringRef::size_type EscapedNewlinePos = Current.TokenText.find("\\\n");
655 assert(EscapedNewlinePos != StringRef::npos);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000656 State.Column =
657 StartColumn +
658 encoding::getCodePointCount(
659 Current.TokenText.substr(0, EscapedNewlinePos), Encoding) +
660 1;
661 return 0;
662 }
663
664 Token.reset(new BreakableLineComment(Current, StartColumn,
665 Line.InPPDirective, Encoding));
666 } else {
667 return 0;
668 }
669 if (Current.UnbreakableTailLength >= getColumnLimit())
670 return 0;
671
672 unsigned RemainingSpace = getColumnLimit() - Current.UnbreakableTailLength;
673 bool BreakInserted = false;
674 unsigned Penalty = 0;
675 unsigned RemainingTokenColumns = 0;
676 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
677 LineIndex != EndIndex; ++LineIndex) {
678 if (!DryRun)
679 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
680 unsigned TailOffset = 0;
681 RemainingTokenColumns =
682 Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
683 while (RemainingTokenColumns > RemainingSpace) {
684 BreakableToken::Split Split =
685 Token->getSplit(LineIndex, TailOffset, getColumnLimit());
686 if (Split.first == StringRef::npos) {
687 // The last line's penalty is handled in addNextStateToQueue().
688 if (LineIndex < EndIndex - 1)
689 Penalty += Style.PenaltyExcessCharacter *
690 (RemainingTokenColumns - RemainingSpace);
691 break;
692 }
693 assert(Split.first != 0);
694 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
695 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
696 assert(NewRemainingTokenColumns < RemainingTokenColumns);
697 if (!DryRun)
698 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Daniel Jasper2739af32013-08-28 10:03:58 +0000699 Penalty += Current.SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000700 unsigned ColumnsUsed =
701 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
702 if (ColumnsUsed > getColumnLimit()) {
703 Penalty +=
704 Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit());
705 }
706 TailOffset += Split.first + Split.second;
707 RemainingTokenColumns = NewRemainingTokenColumns;
708 BreakInserted = true;
709 }
710 }
711
712 State.Column = RemainingTokenColumns;
713
714 if (BreakInserted) {
715 // If we break the token inside a parameter list, we need to break before
716 // the next parameter on all levels, so that the next parameter is clearly
717 // visible. Line comments already introduce a break.
718 if (Current.Type != TT_LineComment) {
719 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
720 State.Stack[i].BreakBeforeParameter = true;
721 }
722
Daniel Jasper2739af32013-08-28 10:03:58 +0000723 Penalty += Current.is(tok::string_literal) ? Style.PenaltyBreakString
724 : Style.PenaltyBreakComment;
725
Daniel Jasperde0328a2013-08-16 11:20:30 +0000726 State.Stack.back().LastSpace = StartColumn;
727 }
728 return Penalty;
729}
730
731unsigned ContinuationIndenter::getColumnLimit() const {
732 // In preprocessor directives reserve two chars for trailing " \"
733 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
734}
735
Daniel Jasperf438cb72013-08-23 11:57:34 +0000736bool ContinuationIndenter::NextIsMultilineString(const LineState &State) {
737 const FormatToken &Current = *State.NextToken;
738 if (!Current.is(tok::string_literal))
739 return false;
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000740 // We never consider raw string literals "multiline" for the purpose of
741 // AlwaysBreakBeforeMultilineStrings implementation.
742 if (Current.TokenText.startswith("R\""))
743 return false;
744 if (Current.IsMultiline)
745 return true;
Daniel Jasperf438cb72013-08-23 11:57:34 +0000746 if (Current.getNextNonComment() &&
747 Current.getNextNonComment()->is(tok::string_literal))
748 return true; // Implicit concatenation.
749 if (State.Column + Current.CodePointCount + Current.UnbreakableTailLength >
750 Style.ColumnLimit)
751 return true; // String will be split.
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000752 return false;
Daniel Jasperf438cb72013-08-23 11:57:34 +0000753}
754
Daniel Jasperde0328a2013-08-16 11:20:30 +0000755} // namespace format
756} // namespace clang