blob: f9219cbaf75314a280376227cf77910bec5a5b3f [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 Jasperd489f8c2013-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 Jasperd3fef0f2013-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 Jasper6b2afe42013-08-16 11:20:30 +000056ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,
57 SourceManager &SourceMgr,
Daniel Jasper6b2afe42013-08-16 11:20:30 +000058 WhitespaceManager &Whitespaces,
59 encoding::Encoding Encoding,
60 bool BinPackInconclusiveFunctions)
Daniel Jasper567dcf92013-09-05 09:29:45 +000061 : Style(Style), SourceMgr(SourceMgr), Whitespaces(Whitespaces),
62 Encoding(Encoding),
Daniel Jasper6b2afe42013-08-16 11:20:30 +000063 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions) {}
64
Daniel Jasper567dcf92013-09-05 09:29:45 +000065LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
66 const AnnotatedLine *Line) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +000067 LineState State;
Daniel Jasper567dcf92013-09-05 09:29:45 +000068 State.FirstIndent = FirstIndent;
Daniel Jasper6b2afe42013-08-16 11:20:30 +000069 State.Column = FirstIndent;
Daniel Jasper567dcf92013-09-05 09:29:45 +000070 State.Line = Line;
71 State.NextToken = Line->First;
Daniel Jasper6b2afe42013-08-16 11:20:30 +000072 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) &&
Daniel Jasper567dcf92013-09-05 09:29:45 +000098 Previous.BlockKind == BK_BracedInit && Previous.Previous &&
Daniel Jasper6b2afe42013-08-16 11:20:30 +000099 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 Jasperd3fef0f2013-08-27 14:24:43 +0000108 if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
109 return false;
Daniel Jasper6b2afe42013-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 Jasper4df1ff92013-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 Jasper6b2afe42013-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)) &&
Daniel Jasper567dcf92013-09-05 09:29:45 +0000186 State.Line->MightBeFunctionDecl &&
187 State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000188 return true;
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000189 if (startsSegmentOfBuilderTypeCall(Current) &&
Daniel Jaspereb331832013-08-30 07:12:40 +0000190 (State.Stack.back().CallContinuation != 0 ||
191 (State.Stack.back().BreakBeforeParameter &&
192 State.Stack.back().ContainsUnwrappedBuilder)))
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000193 return true;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000194 return false;
195}
196
197unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000198 bool DryRun,
199 unsigned ExtraSpaces) {
Daniel Jasper6b2afe42013-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 Jasperd4a03db2013-08-22 15:00:41 +0000205 unsigned Penalty = 0;
Daniel Jasper6b2afe42013-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 Jasperd4a03db2013-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 Jasper6b2afe42013-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 Jasperd4a03db2013-08-22 15:00:41 +0000234 Penalty += Style.PenaltyBreakFirstLessLess;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000235
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000236 if (Current.is(tok::r_brace)) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000237 State.Column = State.Stack[State.Stack.size() - 2].LastSpace;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000238 } else if (Current.is(tok::string_literal) &&
239 State.StartOfStringLiteral != 0) {
240 State.Column = State.StartOfStringLiteral;
241 State.Stack.back().BreakBeforeParameter = true;
242 } else if (Current.is(tok::lessless) &&
243 State.Stack.back().FirstLessLess != 0) {
244 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000245 } else if (Current.isMemberAccess()) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000246 if (State.Stack.back().CallContinuation == 0) {
247 State.Column = ContinuationIndent;
248 State.Stack.back().CallContinuation = State.Column;
249 } else {
250 State.Column = State.Stack.back().CallContinuation;
251 }
252 } else if (Current.Type == TT_ConditionalExpr) {
253 State.Column = State.Stack.back().QuestionColumn;
254 } else if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0) {
255 State.Column = State.Stack.back().VariablePos;
256 } else if (Previous.ClosesTemplateDeclaration ||
257 ((Current.Type == TT_StartOfName ||
258 Current.is(tok::kw_operator)) &&
259 State.ParenLevel == 0 &&
260 (!Style.IndentFunctionDeclarationAfterType ||
Daniel Jasper567dcf92013-09-05 09:29:45 +0000261 State.Line->StartsDefinition))) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000262 State.Column = State.Stack.back().Indent;
263 } else if (Current.Type == TT_ObjCSelectorName) {
264 if (State.Stack.back().ColonPos > Current.CodePointCount) {
265 State.Column = State.Stack.back().ColonPos - Current.CodePointCount;
266 } else {
267 State.Column = State.Stack.back().Indent;
268 State.Stack.back().ColonPos = State.Column + Current.CodePointCount;
269 }
270 } else if (Current.is(tok::l_square) && Current.Type != TT_ObjCMethodExpr) {
271 if (State.Stack.back().StartOfArraySubscripts != 0)
272 State.Column = State.Stack.back().StartOfArraySubscripts;
273 else
274 State.Column = ContinuationIndent;
275 } else if (Current.Type == TT_StartOfName ||
276 Previous.isOneOf(tok::coloncolon, tok::equal) ||
277 Previous.Type == TT_ObjCMethodExpr) {
278 State.Column = ContinuationIndent;
279 } else if (Current.Type == TT_CtorInitializerColon) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000280 State.Column =
281 State.FirstIndent + Style.ConstructorInitializerIndentWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000282 } else if (Current.Type == TT_CtorInitializerComma) {
283 State.Column = State.Stack.back().Indent;
284 } else {
285 State.Column = State.Stack.back().Indent;
286 // Ensure that we fall back to indenting 4 spaces instead of just
287 // flushing continuations left.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000288 if (State.Column == State.FirstIndent)
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000289 State.Column += 4;
290 }
291
292 if (Current.is(tok::question))
293 State.Stack.back().BreakBeforeParameter = true;
294 if ((Previous.isOneOf(tok::comma, tok::semi) &&
295 !State.Stack.back().AvoidBinPacking) ||
296 Previous.Type == TT_BinaryOperator)
297 State.Stack.back().BreakBeforeParameter = false;
298 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
299 State.Stack.back().BreakBeforeParameter = false;
300
301 if (!DryRun) {
302 unsigned NewLines = 1;
303 if (Current.is(tok::comment))
304 NewLines = std::max(NewLines, std::min(Current.NewlinesBefore,
305 Style.MaxEmptyLinesToKeep + 1));
306 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Daniel Jasper567dcf92013-09-05 09:29:45 +0000307 State.Column, State.Line->InPPDirective);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000308 }
309
310 if (!Current.isTrailingComment())
311 State.Stack.back().LastSpace = State.Column;
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000312 if (Current.isMemberAccess())
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000313 State.Stack.back().LastSpace += Current.CodePointCount;
314 State.StartOfLineLevel = State.ParenLevel;
315 State.LowestLevelOnLine = State.ParenLevel;
316
317 // Any break on this level means that the parent level has been broken
318 // and we need to avoid bin packing there.
319 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
320 State.Stack[i].BreakBeforeParameter = true;
321 }
322 const FormatToken *TokenBefore = Current.getPreviousNonComment();
323 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
324 TokenBefore->Type != TT_TemplateCloser &&
325 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
326 State.Stack.back().BreakBeforeParameter = true;
327
328 // If we break after {, we should also break before the corresponding }.
329 if (Previous.is(tok::l_brace))
330 State.Stack.back().BreakBeforeClosingBrace = true;
331
332 if (State.Stack.back().AvoidBinPacking) {
333 // If we are breaking after '(', '{', '<', this is not bin packing
334 // unless AllowAllParametersOfDeclarationOnNextLine is false.
335 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
336 Previous.Type == TT_BinaryOperator) ||
337 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
Daniel Jasper567dcf92013-09-05 09:29:45 +0000338 State.Line->MustBeDeclaration))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000339 State.Stack.back().BreakBeforeParameter = true;
340 }
341
342 } else {
343 if (Current.is(tok::equal) &&
Daniel Jasper567dcf92013-09-05 09:29:45 +0000344 (State.Line->First->is(tok::kw_for) || State.ParenLevel == 0) &&
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000345 State.Stack.back().VariablePos == 0) {
346 State.Stack.back().VariablePos = State.Column;
347 // Move over * and & if they are bound to the variable name.
348 const FormatToken *Tok = &Previous;
349 while (Tok && State.Stack.back().VariablePos >= Tok->CodePointCount) {
350 State.Stack.back().VariablePos -= Tok->CodePointCount;
351 if (Tok->SpacesRequiredBefore != 0)
352 break;
353 Tok = Tok->Previous;
354 }
355 if (Previous.PartOfMultiVariableDeclStmt)
356 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
357 }
358
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000359 unsigned Spaces = State.NextToken->SpacesRequiredBefore + ExtraSpaces;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000360
361 if (!DryRun)
362 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column + Spaces);
363
364 if (Current.Type == TT_ObjCSelectorName &&
365 State.Stack.back().ColonPos == 0) {
366 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
367 State.Column + Spaces + Current.CodePointCount)
368 State.Stack.back().ColonPos =
369 State.Stack.back().Indent + Current.LongestObjCSelectorName;
370 else
371 State.Stack.back().ColonPos =
372 State.Column + Spaces + Current.CodePointCount;
373 }
374
375 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
376 Current.Type != TT_LineComment)
377 State.Stack.back().Indent = State.Column + Spaces;
378 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
379 State.Stack.back().AvoidBinPacking)
380 State.Stack.back().NoLineBreak = true;
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000381 if (startsSegmentOfBuilderTypeCall(Current))
382 State.Stack.back().ContainsUnwrappedBuilder = true;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000383
384 State.Column += Spaces;
385 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
386 // Treat the condition inside an if as if it was a second function
387 // parameter, i.e. let nested calls have an indent of 4.
388 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
389 else if (Previous.is(tok::comma))
390 State.Stack.back().LastSpace = State.Column;
391 else if ((Previous.Type == TT_BinaryOperator ||
392 Previous.Type == TT_ConditionalExpr ||
Daniel Jasper34f3d052013-08-21 08:39:01 +0000393 Previous.Type == TT_UnaryOperator ||
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000394 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasperd489f8c2013-08-27 11:09:05 +0000395 (Previous.getPrecedence() != prec::Assignment ||
396 startsBinaryExpression(Current)))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000397 // Always indent relative to the RHS of the expression unless this is a
Daniel Jasper34f3d052013-08-21 08:39:01 +0000398 // simple assignment without binary expression on the RHS. Also indent
399 // relative to unary operators and the colons of constructor initializers.
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000400 State.Stack.back().LastSpace = State.Column;
401 else if (Previous.Type == TT_InheritanceColon)
402 State.Stack.back().Indent = State.Column;
403 else if (Previous.opensScope()) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000404 // If a function has a trailing call, indent all parameters from the
405 // opening parenthesis. This avoids confusing indents like:
406 // OuterFunction(InnerFunctionCall( // break
407 // ParameterToInnerFunction)) // break
408 // .SecondInnerFunctionCall();
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000409 bool HasTrailingCall = false;
410 if (Previous.MatchingParen) {
411 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000412 HasTrailingCall = Next && Next->isMemberAccess();
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000413 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000414 if (HasTrailingCall &&
415 State.Stack[State.Stack.size() - 2].CallContinuation == 0)
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000416 State.Stack.back().LastSpace = State.Column;
417 }
418 }
419
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000420 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000421}
422
423unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
424 bool DryRun, bool Newline) {
425 const FormatToken &Current = *State.NextToken;
426 assert(State.Stack.size());
427
428 if (Current.Type == TT_InheritanceColon)
429 State.Stack.back().AvoidBinPacking = true;
430 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
431 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000432 if (Current.is(tok::l_square) && Current.Type != TT_LambdaLSquare &&
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000433 State.Stack.back().StartOfArraySubscripts == 0)
434 State.Stack.back().StartOfArraySubscripts = State.Column;
435 if (Current.is(tok::question))
436 State.Stack.back().QuestionColumn = State.Column;
437 if (!Current.opensScope() && !Current.closesScope())
438 State.LowestLevelOnLine =
439 std::min(State.LowestLevelOnLine, State.ParenLevel);
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000440 if (Current.isMemberAccess())
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000441 State.Stack.back().StartOfFunctionCall =
442 Current.LastInChainOfCalls ? 0 : State.Column + Current.CodePointCount;
443 if (Current.Type == TT_CtorInitializerColon) {
444 // Indent 2 from the column, so:
445 // SomeClass::SomeClass()
446 // : First(...), ...
447 // Next(...)
448 // ^ line up here.
449 State.Stack.back().Indent =
450 State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
451 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
452 State.Stack.back().AvoidBinPacking = true;
453 State.Stack.back().BreakBeforeParameter = false;
454 }
455
456 // If return returns a binary expression, align after it.
Daniel Jasper29082452013-08-30 07:27:13 +0000457 if (Current.is(tok::kw_return) && startsBinaryExpression(Current))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000458 State.Stack.back().LastSpace = State.Column + 7;
459
460 // In ObjC method declaration we align on the ":" of parameters, but we need
461 // to ensure that we indent parameters on subsequent lines by at least 4.
462 if (Current.Type == TT_ObjCMethodSpecifier)
463 State.Stack.back().Indent += 4;
464
465 // Insert scopes created by fake parenthesis.
466 const FormatToken *Previous = Current.getPreviousNonComment();
467 // Don't add extra indentation for the first fake parenthesis after
468 // 'return', assignements or opening <({[. The indentation for these cases
469 // is special cased.
470 bool SkipFirstExtraIndent =
471 Current.is(tok::kw_return) ||
472 (Previous && (Previous->opensScope() ||
473 Previous->getPrecedence() == prec::Assignment));
474 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
475 I = Current.FakeLParens.rbegin(),
476 E = Current.FakeLParens.rend();
477 I != E; ++I) {
478 ParenState NewParenState = State.Stack.back();
479 NewParenState.ContainsLineBreak = false;
480 NewParenState.Indent =
481 std::max(std::max(State.Column, NewParenState.Indent),
482 State.Stack.back().LastSpace);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000483 // Do not indent relative to the fake parentheses inserted for "." or "->".
484 // This is a special case to make the following to statements consistent:
485 // OuterFunction(InnerFunctionCall( // break
486 // ParameterToInnerFunction));
487 // OuterFunction(SomeObject.InnerFunctionCall( // break
488 // ParameterToInnerFunction));
489 if (*I > prec::Unknown)
490 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000491
492 // Always indent conditional expressions. Never indent expression where
493 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
494 // prec::Assignment) as those have different indentation rules. Indent
495 // other expression, unless the indentation needs to be skipped.
496 if (*I == prec::Conditional ||
497 (!SkipFirstExtraIndent && *I > prec::Assignment &&
498 !Style.BreakBeforeBinaryOperators))
499 NewParenState.Indent += 4;
500 if (Previous && !Previous->opensScope())
501 NewParenState.BreakBeforeParameter = false;
502 State.Stack.push_back(NewParenState);
503 SkipFirstExtraIndent = false;
504 }
505
506 // If we encounter an opening (, [, { or <, we add a level to our stacks to
507 // prepare for the following tokens.
508 if (Current.opensScope()) {
509 unsigned NewIndent;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000510 bool AvoidBinPacking;
511 if (Current.is(tok::l_brace)) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000512 if (Current.MatchingParen && Current.BlockKind == BK_Block) {
513 for (unsigned i = 0; i != Current.MatchingParen->FakeRParens; ++i)
514 State.Stack.pop_back();
515 NewIndent = State.Stack.back().LastSpace;
516 } else {
517 NewIndent = State.Stack.back().LastSpace +
518 (Style.Cpp11BracedListStyle ? 4 : Style.IndentWidth);
519 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000520 const FormatToken *NextNoComment = Current.getNextNonComment();
521 AvoidBinPacking = NextNoComment &&
522 NextNoComment->Type == TT_DesignatedInitializerPeriod;
523 } else {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000524 NewIndent = 4 + std::max(State.Stack.back().LastSpace,
525 State.Stack.back().StartOfFunctionCall);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000526 AvoidBinPacking = !Style.BinPackParameters ||
527 (Style.ExperimentalAutoDetectBinPacking &&
528 (Current.PackingKind == PPK_OnePerLine ||
529 (!BinPackInconclusiveFunctions &&
530 Current.PackingKind == PPK_Inconclusive)));
531 }
532
Daniel Jasper567dcf92013-09-05 09:29:45 +0000533 State.Stack.push_back(ParenState(NewIndent, State.Stack.back().LastSpace,
534 AvoidBinPacking,
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000535 State.Stack.back().NoLineBreak));
536 ++State.ParenLevel;
537 }
538
539 // If this '[' opens an ObjC call, determine whether all parameters fit into
540 // one line and put one per line if they don't.
541 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
542 Current.MatchingParen != NULL) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000543 if (getLengthToMatchingParen(Current) + State.Column >
544 getColumnLimit(State))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000545 State.Stack.back().BreakBeforeParameter = true;
546 }
547
548 // If we encounter a closing ), ], } or >, we can remove a level from our
549 // stacks.
Daniel Jasper7143a212013-08-28 09:17:37 +0000550 if (State.Stack.size() > 1 &&
551 (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper567dcf92013-09-05 09:29:45 +0000552 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
Daniel Jasper7143a212013-08-28 09:17:37 +0000553 State.NextToken->Type == TT_TemplateCloser)) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000554 State.Stack.pop_back();
555 --State.ParenLevel;
556 }
557 if (Current.is(tok::r_square)) {
558 // If this ends the array subscript expr, reset the corresponding value.
559 const FormatToken *NextNonComment = Current.getNextNonComment();
560 if (NextNonComment && NextNonComment->isNot(tok::l_square))
561 State.Stack.back().StartOfArraySubscripts = 0;
562 }
563
564 // Remove scopes created by fake parenthesis.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000565 if (Current.isNot(tok::r_brace) ||
566 (Current.MatchingParen && Current.MatchingParen->BlockKind != BK_Block)) {
567 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
568 unsigned VariablePos = State.Stack.back().VariablePos;
569 State.Stack.pop_back();
570 State.Stack.back().VariablePos = VariablePos;
571 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000572 }
573
574 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
575 State.StartOfStringLiteral = State.Column;
576 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
577 tok::string_literal)) {
578 State.StartOfStringLiteral = 0;
579 }
580
581 State.Column += Current.CodePointCount;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000582 State.NextToken = State.NextToken->Next;
Daniel Jasperd489f8c2013-08-27 11:09:05 +0000583 unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000584 if (State.Column > getColumnLimit(State)) {
585 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
586 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
587 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000588
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000589 // If the previous has a special role, let it consume tokens as appropriate.
590 // It is necessary to start at the previous token for the only implemented
591 // role (comma separated list). That way, the decision whether or not to break
592 // after the "{" is already done and both options are tried and evaluated.
593 // FIXME: This is ugly, find a better way.
594 if (Previous && Previous->Role)
595 Penalty += Previous->Role->format(State, this, DryRun);
596
597 return Penalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000598}
599
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000600unsigned
601ContinuationIndenter::addMultilineStringLiteral(const FormatToken &Current,
602 LineState &State) {
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000603 // Break before further function parameters on all levels.
604 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
605 State.Stack[i].BreakBeforeParameter = true;
606
607 unsigned ColumnsUsed =
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000608 State.Column - Current.CodePointCount + Current.CodePointsInFirstLine;
609 // We can only affect layout of the first and the last line, so the penalty
610 // for all other lines is constant, and we ignore it.
611 State.Column = Current.CodePointsInLastLine;
612
Daniel Jasper567dcf92013-09-05 09:29:45 +0000613 if (ColumnsUsed > getColumnLimit(State))
614 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000615 return 0;
616}
617
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000618unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
619 LineState &State,
620 bool DryRun) {
Daniel Jaspered51c022013-08-23 10:05:49 +0000621 if (!Current.isOneOf(tok::string_literal, tok::comment))
622 return 0;
623
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000624 llvm::OwningPtr<BreakableToken> Token;
625 unsigned StartColumn = State.Column - Current.CodePointCount;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000626
627 if (Current.is(tok::string_literal) &&
628 Current.Type != TT_ImplicitStringLiteral) {
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000629 // Don't break string literals with (in case of non-raw strings, escaped)
630 // newlines. As clang-format must not change the string's content, it is
631 // unlikely that we'll end up with a better format.
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000632 if (Current.isMultiline())
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000633 return addMultilineStringLiteral(Current, State);
634
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000635 // Only break up default narrow strings.
636 if (!Current.TokenText.startswith("\""))
637 return 0;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000638 // Exempts unterminated string literals from line breaking. The user will
639 // likely want to terminate the string before any line breaking is done.
640 if (Current.IsUnterminatedLiteral)
641 return 0;
642
Daniel Jasper567dcf92013-09-05 09:29:45 +0000643 Token.reset(new BreakableStringLiteral(
644 Current, StartColumn, State.Line->InPPDirective, Encoding));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000645 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000646 unsigned OriginalStartColumn =
647 SourceMgr.getSpellingColumnNumber(Current.getStartOfNonWhitespace()) -
648 1;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000649 Token.reset(new BreakableBlockComment(
650 Style, Current, StartColumn, OriginalStartColumn, !Current.Previous,
Daniel Jasper567dcf92013-09-05 09:29:45 +0000651 State.Line->InPPDirective, Encoding));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000652 } else if (Current.Type == TT_LineComment &&
653 (Current.Previous == NULL ||
654 Current.Previous->Type != TT_ImplicitStringLiteral)) {
655 // Don't break line comments with escaped newlines. These look like
656 // separate line comments, but in fact contain a single line comment with
657 // multiple lines including leading whitespace and the '//' markers.
658 //
659 // FIXME: If we want to handle them correctly, we'll need to adjust
660 // leading whitespace in consecutive lines when changing indentation of
661 // the first line similar to what we do with block comments.
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000662 if (Current.isMultiline()) {
663 State.Column = StartColumn + Current.CodePointsInFirstLine;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000664 return 0;
665 }
666
667 Token.reset(new BreakableLineComment(Current, StartColumn,
Daniel Jasper567dcf92013-09-05 09:29:45 +0000668 State.Line->InPPDirective, Encoding));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000669 } else {
670 return 0;
671 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000672 if (Current.UnbreakableTailLength >= getColumnLimit(State))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000673 return 0;
674
Daniel Jasper567dcf92013-09-05 09:29:45 +0000675 unsigned RemainingSpace =
676 getColumnLimit(State) - Current.UnbreakableTailLength;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000677 bool BreakInserted = false;
678 unsigned Penalty = 0;
679 unsigned RemainingTokenColumns = 0;
680 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
681 LineIndex != EndIndex; ++LineIndex) {
682 if (!DryRun)
683 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
684 unsigned TailOffset = 0;
685 RemainingTokenColumns =
686 Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
687 while (RemainingTokenColumns > RemainingSpace) {
688 BreakableToken::Split Split =
Daniel Jasper567dcf92013-09-05 09:29:45 +0000689 Token->getSplit(LineIndex, TailOffset, getColumnLimit(State));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000690 if (Split.first == StringRef::npos) {
691 // The last line's penalty is handled in addNextStateToQueue().
692 if (LineIndex < EndIndex - 1)
693 Penalty += Style.PenaltyExcessCharacter *
694 (RemainingTokenColumns - RemainingSpace);
695 break;
696 }
697 assert(Split.first != 0);
698 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
699 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
700 assert(NewRemainingTokenColumns < RemainingTokenColumns);
701 if (!DryRun)
702 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Daniel Jasperf5461782013-08-28 10:03:58 +0000703 Penalty += Current.SplitPenalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000704 unsigned ColumnsUsed =
705 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000706 if (ColumnsUsed > getColumnLimit(State)) {
707 Penalty += Style.PenaltyExcessCharacter *
708 (ColumnsUsed - getColumnLimit(State));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000709 }
710 TailOffset += Split.first + Split.second;
711 RemainingTokenColumns = NewRemainingTokenColumns;
712 BreakInserted = true;
713 }
714 }
715
716 State.Column = RemainingTokenColumns;
717
718 if (BreakInserted) {
719 // If we break the token inside a parameter list, we need to break before
720 // the next parameter on all levels, so that the next parameter is clearly
721 // visible. Line comments already introduce a break.
722 if (Current.Type != TT_LineComment) {
723 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
724 State.Stack[i].BreakBeforeParameter = true;
725 }
726
Daniel Jasperf5461782013-08-28 10:03:58 +0000727 Penalty += Current.is(tok::string_literal) ? Style.PenaltyBreakString
728 : Style.PenaltyBreakComment;
729
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000730 State.Stack.back().LastSpace = StartColumn;
731 }
732 return Penalty;
733}
734
Daniel Jasper567dcf92013-09-05 09:29:45 +0000735unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000736 // In preprocessor directives reserve two chars for trailing " \"
Daniel Jasper567dcf92013-09-05 09:29:45 +0000737 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000738}
739
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000740bool ContinuationIndenter::NextIsMultilineString(const LineState &State) {
741 const FormatToken &Current = *State.NextToken;
742 if (!Current.is(tok::string_literal))
743 return false;
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000744 // We never consider raw string literals "multiline" for the purpose of
745 // AlwaysBreakBeforeMultilineStrings implementation.
746 if (Current.TokenText.startswith("R\""))
747 return false;
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000748 if (Current.isMultiline())
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000749 return true;
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000750 if (Current.getNextNonComment() &&
751 Current.getNextNonComment()->is(tok::string_literal))
752 return true; // Implicit concatenation.
753 if (State.Column + Current.CodePointCount + Current.UnbreakableTailLength >
754 Style.ColumnLimit)
755 return true; // String will be split.
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000756 return false;
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000757}
758
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000759} // namespace format
760} // namespace clang