blob: 12cfd48f5b38dfaf3bc9965eac13861743a905b8 [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;
109 if (!Style.Cpp11BracedListStyle && Current.is(tok::r_brace) &&
110 State.Stack.back().BreakBeforeClosingBrace)
111 return true;
112 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
113 return true;
114 if (Style.BreakConstructorInitializersBeforeComma) {
115 if (Previous.Type == TT_CtorInitializerComma)
116 return false;
117 if (Current.Type == TT_CtorInitializerComma)
118 return true;
119 }
120 if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) ||
121 (Current.Type == TT_ConditionalExpr &&
122 !(Current.is(tok::colon) && Previous.is(tok::question)))) &&
123 State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
124 !Current.isOneOf(tok::r_paren, tok::r_brace))
125 return true;
126 if (Style.AlwaysBreakBeforeMultilineStrings &&
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000127 State.Column > State.Stack.back().Indent && // Breaking saves columns.
128 Previous.isNot(tok::lessless) && Previous.Type != TT_InlineASMColon &&
129 NextIsMultilineString(State))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000130 return true;
131
132 if (!Style.BreakBeforeBinaryOperators) {
133 // If we need to break somewhere inside the LHS of a binary expression, we
134 // should also break after the operator. Otherwise, the formatting would
135 // hide the operator precedence, e.g. in:
136 // if (aaaaaaaaaaaaaa ==
137 // bbbbbbbbbbbbbb && c) {..
138 // For comparisons, we only apply this rule, if the LHS is a binary
139 // expression itself as otherwise, the line breaks seem superfluous.
140 // We need special cases for ">>" which we have split into two ">" while
141 // lexing in order to make template parsing easier.
142 //
143 // FIXME: We'll need something similar for styles that break before binary
144 // operators.
145 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
146 Previous.getPrecedence() == prec::Equality) &&
147 Previous.Previous &&
148 Previous.Previous->Type != TT_BinaryOperator; // For >>.
149 bool LHSIsBinaryExpr =
Daniel Jasperdb4813a2013-09-06 08:08:14 +0000150 Previous.Previous && Previous.Previous->EndsBinaryExpression;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000151 if (Previous.Type == TT_BinaryOperator &&
152 (!IsComparison || LHSIsBinaryExpr) &&
153 Current.Type != TT_BinaryOperator && // For >>.
154 !Current.isTrailingComment() &&
155 !Previous.isOneOf(tok::lessless, tok::question) &&
156 Previous.getPrecedence() != prec::Assignment &&
157 State.Stack.back().BreakBeforeParameter)
158 return true;
159 }
160
161 // Same as above, but for the first "<<" operator.
162 if (Current.is(tok::lessless) && State.Stack.back().BreakBeforeParameter &&
163 State.Stack.back().FirstLessLess == 0)
164 return true;
165
166 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
167 // out whether it is the first parameter. Clean this up.
168 if (Current.Type == TT_ObjCSelectorName &&
169 Current.LongestObjCSelectorName == 0 &&
170 State.Stack.back().BreakBeforeParameter)
171 return true;
172 if ((Current.Type == TT_CtorInitializerColon ||
173 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0)))
174 return true;
175
176 if ((Current.Type == TT_StartOfName || Current.is(tok::kw_operator)) &&
Daniel Jasper567dcf92013-09-05 09:29:45 +0000177 State.Line->MightBeFunctionDecl &&
178 State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000179 return true;
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000180 if (startsSegmentOfBuilderTypeCall(Current) &&
Daniel Jaspereb331832013-08-30 07:12:40 +0000181 (State.Stack.back().CallContinuation != 0 ||
182 (State.Stack.back().BreakBeforeParameter &&
183 State.Stack.back().ContainsUnwrappedBuilder)))
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000184 return true;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000185 return false;
186}
187
188unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000189 bool DryRun,
190 unsigned ExtraSpaces) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000191 const FormatToken &Current = *State.NextToken;
192 const FormatToken &Previous = *State.NextToken->Previous;
193
194 // Extra penalty that needs to be added because of the way certain line
195 // breaks are chosen.
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000196 unsigned Penalty = 0;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000197
198 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
199 // FIXME: Is this correct?
200 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
201 State.NextToken->WhitespaceRange.getEnd()) -
202 SourceMgr.getSpellingColumnNumber(
203 State.NextToken->WhitespaceRange.getBegin());
204 State.Column += WhitespaceLength + State.NextToken->CodePointCount;
205 State.NextToken = State.NextToken->Next;
206 return 0;
207 }
208
209 // If we are continuing an expression, we want to indent an extra 4 spaces.
210 unsigned ContinuationIndent =
211 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
212 if (Newline) {
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000213 // The first line break on any ParenLevel causes an extra penalty in order
214 // prefer similar line breaks.
215 if (!State.Stack.back().ContainsLineBreak)
216 Penalty += 15;
217 State.Stack.back().ContainsLineBreak = true;
218
219 Penalty += State.NextToken->SplitPenalty;
220
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000221 // Breaking before the first "<<" is generally not desirable if the LHS is
222 // short.
223 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0 &&
224 State.Column <= Style.ColumnLimit / 2)
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000225 Penalty += Style.PenaltyBreakFirstLessLess;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000226
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000227 if (Current.is(tok::r_brace)) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000228 State.Column = State.Stack[State.Stack.size() - 2].LastSpace;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000229 } else if (Current.is(tok::string_literal) &&
230 State.StartOfStringLiteral != 0) {
231 State.Column = State.StartOfStringLiteral;
232 State.Stack.back().BreakBeforeParameter = true;
233 } else if (Current.is(tok::lessless) &&
234 State.Stack.back().FirstLessLess != 0) {
235 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000236 } else if (Current.isMemberAccess()) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000237 if (State.Stack.back().CallContinuation == 0) {
238 State.Column = ContinuationIndent;
239 State.Stack.back().CallContinuation = State.Column;
240 } else {
241 State.Column = State.Stack.back().CallContinuation;
242 }
243 } else if (Current.Type == TT_ConditionalExpr) {
244 State.Column = State.Stack.back().QuestionColumn;
245 } else if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0) {
246 State.Column = State.Stack.back().VariablePos;
247 } else if (Previous.ClosesTemplateDeclaration ||
248 ((Current.Type == TT_StartOfName ||
249 Current.is(tok::kw_operator)) &&
250 State.ParenLevel == 0 &&
251 (!Style.IndentFunctionDeclarationAfterType ||
Daniel Jasper567dcf92013-09-05 09:29:45 +0000252 State.Line->StartsDefinition))) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000253 State.Column = State.Stack.back().Indent;
254 } else if (Current.Type == TT_ObjCSelectorName) {
255 if (State.Stack.back().ColonPos > Current.CodePointCount) {
256 State.Column = State.Stack.back().ColonPos - Current.CodePointCount;
257 } else {
258 State.Column = State.Stack.back().Indent;
259 State.Stack.back().ColonPos = State.Column + Current.CodePointCount;
260 }
Daniel Jasperac2c9742013-09-05 10:04:31 +0000261 } else if (Current.is(tok::l_square) && Current.Type != TT_ObjCMethodExpr &&
262 Current.Type != TT_LambdaLSquare) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000263 if (State.Stack.back().StartOfArraySubscripts != 0)
264 State.Column = State.Stack.back().StartOfArraySubscripts;
265 else
266 State.Column = ContinuationIndent;
267 } else if (Current.Type == TT_StartOfName ||
268 Previous.isOneOf(tok::coloncolon, tok::equal) ||
269 Previous.Type == TT_ObjCMethodExpr) {
270 State.Column = ContinuationIndent;
271 } else if (Current.Type == TT_CtorInitializerColon) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000272 State.Column =
273 State.FirstIndent + Style.ConstructorInitializerIndentWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000274 } else if (Current.Type == TT_CtorInitializerComma) {
275 State.Column = State.Stack.back().Indent;
276 } else {
277 State.Column = State.Stack.back().Indent;
278 // Ensure that we fall back to indenting 4 spaces instead of just
279 // flushing continuations left.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000280 if (State.Column == State.FirstIndent)
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000281 State.Column += 4;
282 }
283
284 if (Current.is(tok::question))
285 State.Stack.back().BreakBeforeParameter = true;
286 if ((Previous.isOneOf(tok::comma, tok::semi) &&
287 !State.Stack.back().AvoidBinPacking) ||
288 Previous.Type == TT_BinaryOperator)
289 State.Stack.back().BreakBeforeParameter = false;
290 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
291 State.Stack.back().BreakBeforeParameter = false;
292
293 if (!DryRun) {
294 unsigned NewLines = 1;
295 if (Current.is(tok::comment))
296 NewLines = std::max(NewLines, std::min(Current.NewlinesBefore,
297 Style.MaxEmptyLinesToKeep + 1));
298 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Daniel Jasper567dcf92013-09-05 09:29:45 +0000299 State.Column, State.Line->InPPDirective);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000300 }
301
302 if (!Current.isTrailingComment())
303 State.Stack.back().LastSpace = State.Column;
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000304 if (Current.isMemberAccess())
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000305 State.Stack.back().LastSpace += Current.CodePointCount;
306 State.StartOfLineLevel = State.ParenLevel;
307 State.LowestLevelOnLine = State.ParenLevel;
308
309 // Any break on this level means that the parent level has been broken
310 // and we need to avoid bin packing there.
311 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
312 State.Stack[i].BreakBeforeParameter = true;
313 }
314 const FormatToken *TokenBefore = Current.getPreviousNonComment();
315 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
316 TokenBefore->Type != TT_TemplateCloser &&
317 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
318 State.Stack.back().BreakBeforeParameter = true;
319
320 // If we break after {, we should also break before the corresponding }.
321 if (Previous.is(tok::l_brace))
322 State.Stack.back().BreakBeforeClosingBrace = true;
323
324 if (State.Stack.back().AvoidBinPacking) {
325 // If we are breaking after '(', '{', '<', this is not bin packing
326 // unless AllowAllParametersOfDeclarationOnNextLine is false.
327 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
328 Previous.Type == TT_BinaryOperator) ||
329 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
Daniel Jasper567dcf92013-09-05 09:29:45 +0000330 State.Line->MustBeDeclaration))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000331 State.Stack.back().BreakBeforeParameter = true;
332 }
333
334 } else {
335 if (Current.is(tok::equal) &&
Daniel Jasper567dcf92013-09-05 09:29:45 +0000336 (State.Line->First->is(tok::kw_for) || State.ParenLevel == 0) &&
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000337 State.Stack.back().VariablePos == 0) {
338 State.Stack.back().VariablePos = State.Column;
339 // Move over * and & if they are bound to the variable name.
340 const FormatToken *Tok = &Previous;
341 while (Tok && State.Stack.back().VariablePos >= Tok->CodePointCount) {
342 State.Stack.back().VariablePos -= Tok->CodePointCount;
343 if (Tok->SpacesRequiredBefore != 0)
344 break;
345 Tok = Tok->Previous;
346 }
347 if (Previous.PartOfMultiVariableDeclStmt)
348 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
349 }
350
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000351 unsigned Spaces = State.NextToken->SpacesRequiredBefore + ExtraSpaces;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000352
353 if (!DryRun)
354 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column + Spaces);
355
356 if (Current.Type == TT_ObjCSelectorName &&
357 State.Stack.back().ColonPos == 0) {
358 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
359 State.Column + Spaces + Current.CodePointCount)
360 State.Stack.back().ColonPos =
361 State.Stack.back().Indent + Current.LongestObjCSelectorName;
362 else
363 State.Stack.back().ColonPos =
364 State.Column + Spaces + Current.CodePointCount;
365 }
366
367 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
368 Current.Type != TT_LineComment)
369 State.Stack.back().Indent = State.Column + Spaces;
370 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
371 State.Stack.back().AvoidBinPacking)
372 State.Stack.back().NoLineBreak = true;
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000373 if (startsSegmentOfBuilderTypeCall(Current))
374 State.Stack.back().ContainsUnwrappedBuilder = true;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000375
376 State.Column += Spaces;
377 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
378 // Treat the condition inside an if as if it was a second function
379 // parameter, i.e. let nested calls have an indent of 4.
380 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
381 else if (Previous.is(tok::comma))
382 State.Stack.back().LastSpace = State.Column;
383 else if ((Previous.Type == TT_BinaryOperator ||
384 Previous.Type == TT_ConditionalExpr ||
Daniel Jasper34f3d052013-08-21 08:39:01 +0000385 Previous.Type == TT_UnaryOperator ||
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000386 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasperd489f8c2013-08-27 11:09:05 +0000387 (Previous.getPrecedence() != prec::Assignment ||
Daniel Jasperdb4813a2013-09-06 08:08:14 +0000388 Current.StartsBinaryExpression))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000389 // Always indent relative to the RHS of the expression unless this is a
Daniel Jasper34f3d052013-08-21 08:39:01 +0000390 // simple assignment without binary expression on the RHS. Also indent
391 // relative to unary operators and the colons of constructor initializers.
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000392 State.Stack.back().LastSpace = State.Column;
393 else if (Previous.Type == TT_InheritanceColon)
394 State.Stack.back().Indent = State.Column;
395 else if (Previous.opensScope()) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000396 // If a function has a trailing call, indent all parameters from the
397 // opening parenthesis. This avoids confusing indents like:
398 // OuterFunction(InnerFunctionCall( // break
399 // ParameterToInnerFunction)) // break
400 // .SecondInnerFunctionCall();
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000401 bool HasTrailingCall = false;
402 if (Previous.MatchingParen) {
403 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000404 HasTrailingCall = Next && Next->isMemberAccess();
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000405 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000406 if (HasTrailingCall &&
407 State.Stack[State.Stack.size() - 2].CallContinuation == 0)
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000408 State.Stack.back().LastSpace = State.Column;
409 }
410 }
411
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000412 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000413}
414
415unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
416 bool DryRun, bool Newline) {
417 const FormatToken &Current = *State.NextToken;
418 assert(State.Stack.size());
419
420 if (Current.Type == TT_InheritanceColon)
421 State.Stack.back().AvoidBinPacking = true;
422 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
423 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000424 if (Current.is(tok::l_square) && Current.Type != TT_LambdaLSquare &&
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000425 State.Stack.back().StartOfArraySubscripts == 0)
426 State.Stack.back().StartOfArraySubscripts = State.Column;
427 if (Current.is(tok::question))
428 State.Stack.back().QuestionColumn = State.Column;
429 if (!Current.opensScope() && !Current.closesScope())
430 State.LowestLevelOnLine =
431 std::min(State.LowestLevelOnLine, State.ParenLevel);
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000432 if (Current.isMemberAccess())
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000433 State.Stack.back().StartOfFunctionCall =
434 Current.LastInChainOfCalls ? 0 : State.Column + Current.CodePointCount;
435 if (Current.Type == TT_CtorInitializerColon) {
436 // Indent 2 from the column, so:
437 // SomeClass::SomeClass()
438 // : First(...), ...
439 // Next(...)
440 // ^ line up here.
441 State.Stack.back().Indent =
442 State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
443 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
444 State.Stack.back().AvoidBinPacking = true;
445 State.Stack.back().BreakBeforeParameter = false;
446 }
447
448 // If return returns a binary expression, align after it.
Daniel Jasperdb4813a2013-09-06 08:08:14 +0000449 if (Current.is(tok::kw_return) && Current.StartsBinaryExpression)
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000450 State.Stack.back().LastSpace = State.Column + 7;
451
452 // In ObjC method declaration we align on the ":" of parameters, but we need
453 // to ensure that we indent parameters on subsequent lines by at least 4.
454 if (Current.Type == TT_ObjCMethodSpecifier)
455 State.Stack.back().Indent += 4;
456
457 // Insert scopes created by fake parenthesis.
458 const FormatToken *Previous = Current.getPreviousNonComment();
459 // Don't add extra indentation for the first fake parenthesis after
460 // 'return', assignements or opening <({[. The indentation for these cases
461 // is special cased.
462 bool SkipFirstExtraIndent =
463 Current.is(tok::kw_return) ||
464 (Previous && (Previous->opensScope() ||
465 Previous->getPrecedence() == prec::Assignment));
466 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
467 I = Current.FakeLParens.rbegin(),
468 E = Current.FakeLParens.rend();
469 I != E; ++I) {
470 ParenState NewParenState = State.Stack.back();
471 NewParenState.ContainsLineBreak = false;
472 NewParenState.Indent =
473 std::max(std::max(State.Column, NewParenState.Indent),
474 State.Stack.back().LastSpace);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000475 // Do not indent relative to the fake parentheses inserted for "." or "->".
476 // This is a special case to make the following to statements consistent:
477 // OuterFunction(InnerFunctionCall( // break
478 // ParameterToInnerFunction));
479 // OuterFunction(SomeObject.InnerFunctionCall( // break
480 // ParameterToInnerFunction));
481 if (*I > prec::Unknown)
482 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000483
484 // Always indent conditional expressions. Never indent expression where
485 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
486 // prec::Assignment) as those have different indentation rules. Indent
487 // other expression, unless the indentation needs to be skipped.
488 if (*I == prec::Conditional ||
489 (!SkipFirstExtraIndent && *I > prec::Assignment &&
490 !Style.BreakBeforeBinaryOperators))
491 NewParenState.Indent += 4;
492 if (Previous && !Previous->opensScope())
493 NewParenState.BreakBeforeParameter = false;
494 State.Stack.push_back(NewParenState);
495 SkipFirstExtraIndent = false;
496 }
497
498 // If we encounter an opening (, [, { or <, we add a level to our stacks to
499 // prepare for the following tokens.
500 if (Current.opensScope()) {
501 unsigned NewIndent;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000502 bool AvoidBinPacking;
503 if (Current.is(tok::l_brace)) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000504 if (Current.MatchingParen && Current.BlockKind == BK_Block) {
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000505 // If this is an l_brace starting a nested block, we pretend (wrt. to
506 // indentation) that we already consumed the corresponding r_brace.
507 // Thus, we remove all ParenStates caused bake fake parentheses that end
508 // at the r_brace. The net effect of this is that we don't indent
509 // relative to the l_brace, if the nested block is the last parameter of
510 // a function. For example, this formats:
511 //
512 // SomeFunction(a, [] {
513 // f(); // break
514 // });
515 //
516 // instead of:
517 // SomeFunction(a, [] {
518 // f(); // break
519 // });
Daniel Jasper567dcf92013-09-05 09:29:45 +0000520 for (unsigned i = 0; i != Current.MatchingParen->FakeRParens; ++i)
521 State.Stack.pop_back();
522 NewIndent = State.Stack.back().LastSpace;
523 } else {
524 NewIndent = State.Stack.back().LastSpace +
525 (Style.Cpp11BracedListStyle ? 4 : Style.IndentWidth);
526 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000527 const FormatToken *NextNoComment = Current.getNextNonComment();
528 AvoidBinPacking = NextNoComment &&
529 NextNoComment->Type == TT_DesignatedInitializerPeriod;
530 } else {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000531 NewIndent = 4 + std::max(State.Stack.back().LastSpace,
532 State.Stack.back().StartOfFunctionCall);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000533 AvoidBinPacking = !Style.BinPackParameters ||
534 (Style.ExperimentalAutoDetectBinPacking &&
535 (Current.PackingKind == PPK_OnePerLine ||
536 (!BinPackInconclusiveFunctions &&
537 Current.PackingKind == PPK_Inconclusive)));
538 }
539
Daniel Jasper567dcf92013-09-05 09:29:45 +0000540 State.Stack.push_back(ParenState(NewIndent, State.Stack.back().LastSpace,
541 AvoidBinPacking,
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000542 State.Stack.back().NoLineBreak));
543 ++State.ParenLevel;
544 }
545
546 // If this '[' opens an ObjC call, determine whether all parameters fit into
547 // one line and put one per line if they don't.
548 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
549 Current.MatchingParen != NULL) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000550 if (getLengthToMatchingParen(Current) + State.Column >
551 getColumnLimit(State))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000552 State.Stack.back().BreakBeforeParameter = true;
553 }
554
555 // If we encounter a closing ), ], } or >, we can remove a level from our
556 // stacks.
Daniel Jasper7143a212013-08-28 09:17:37 +0000557 if (State.Stack.size() > 1 &&
558 (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper567dcf92013-09-05 09:29:45 +0000559 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
Daniel Jasper7143a212013-08-28 09:17:37 +0000560 State.NextToken->Type == TT_TemplateCloser)) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000561 State.Stack.pop_back();
562 --State.ParenLevel;
563 }
564 if (Current.is(tok::r_square)) {
565 // If this ends the array subscript expr, reset the corresponding value.
566 const FormatToken *NextNonComment = Current.getNextNonComment();
567 if (NextNonComment && NextNonComment->isNot(tok::l_square))
568 State.Stack.back().StartOfArraySubscripts = 0;
569 }
570
571 // Remove scopes created by fake parenthesis.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000572 if (Current.isNot(tok::r_brace) ||
573 (Current.MatchingParen && Current.MatchingParen->BlockKind != BK_Block)) {
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000574 // Don't remove FakeRParens attached to r_braces that surround nested blocks
575 // as they will have been removed early (see above).
Daniel Jasper567dcf92013-09-05 09:29:45 +0000576 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
577 unsigned VariablePos = State.Stack.back().VariablePos;
578 State.Stack.pop_back();
579 State.Stack.back().VariablePos = VariablePos;
580 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000581 }
582
583 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
584 State.StartOfStringLiteral = State.Column;
585 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
586 tok::string_literal)) {
587 State.StartOfStringLiteral = 0;
588 }
589
590 State.Column += Current.CodePointCount;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000591 State.NextToken = State.NextToken->Next;
Daniel Jasperd489f8c2013-08-27 11:09:05 +0000592 unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000593 if (State.Column > getColumnLimit(State)) {
594 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
595 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
596 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000597
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000598 // If the previous has a special role, let it consume tokens as appropriate.
599 // It is necessary to start at the previous token for the only implemented
600 // role (comma separated list). That way, the decision whether or not to break
601 // after the "{" is already done and both options are tried and evaluated.
602 // FIXME: This is ugly, find a better way.
603 if (Previous && Previous->Role)
604 Penalty += Previous->Role->format(State, this, DryRun);
605
606 return Penalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000607}
608
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000609unsigned
610ContinuationIndenter::addMultilineStringLiteral(const FormatToken &Current,
611 LineState &State) {
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000612 // Break before further function parameters on all levels.
613 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
614 State.Stack[i].BreakBeforeParameter = true;
615
616 unsigned ColumnsUsed =
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000617 State.Column - Current.CodePointCount + Current.FirstLineColumnWidth;
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000618 // We can only affect layout of the first and the last line, so the penalty
619 // for all other lines is constant, and we ignore it.
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000620 State.Column = Current.LastLineColumnWidth;
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000621
Daniel Jasper567dcf92013-09-05 09:29:45 +0000622 if (ColumnsUsed > getColumnLimit(State))
623 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000624 return 0;
625}
626
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000627unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
628 LineState &State,
629 bool DryRun) {
Daniel Jaspered51c022013-08-23 10:05:49 +0000630 if (!Current.isOneOf(tok::string_literal, tok::comment))
631 return 0;
632
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000633 llvm::OwningPtr<BreakableToken> Token;
634 unsigned StartColumn = State.Column - Current.CodePointCount;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000635
636 if (Current.is(tok::string_literal) &&
637 Current.Type != TT_ImplicitStringLiteral) {
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000638 // Don't break string literals with (in case of non-raw strings, escaped)
639 // newlines. As clang-format must not change the string's content, it is
640 // unlikely that we'll end up with a better format.
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000641 if (Current.isMultiline())
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000642 return addMultilineStringLiteral(Current, State);
643
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000644 // Only break up default narrow strings.
645 if (!Current.TokenText.startswith("\""))
646 return 0;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000647 // Exempts unterminated string literals from line breaking. The user will
648 // likely want to terminate the string before any line breaking is done.
649 if (Current.IsUnterminatedLiteral)
650 return 0;
651
Daniel Jasper567dcf92013-09-05 09:29:45 +0000652 Token.reset(new BreakableStringLiteral(
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000653 Current, StartColumn, State.Line->InPPDirective, Encoding, Style));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000654 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000655 unsigned OriginalStartColumn =
656 SourceMgr.getSpellingColumnNumber(Current.getStartOfNonWhitespace()) -
657 1;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000658 Token.reset(new BreakableBlockComment(
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000659 Current, StartColumn, OriginalStartColumn, !Current.Previous,
660 State.Line->InPPDirective, Encoding, Style));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000661 } else if (Current.Type == TT_LineComment &&
662 (Current.Previous == NULL ||
663 Current.Previous->Type != TT_ImplicitStringLiteral)) {
664 // Don't break line comments with escaped newlines. These look like
665 // separate line comments, but in fact contain a single line comment with
666 // multiple lines including leading whitespace and the '//' markers.
667 //
668 // FIXME: If we want to handle them correctly, we'll need to adjust
669 // leading whitespace in consecutive lines when changing indentation of
670 // the first line similar to what we do with block comments.
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000671 if (Current.isMultiline()) {
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000672 State.Column = StartColumn + Current.FirstLineColumnWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000673 return 0;
674 }
675
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000676 Token.reset(new BreakableLineComment(
677 Current, StartColumn, State.Line->InPPDirective, Encoding, Style));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000678 } else {
679 return 0;
680 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000681 if (Current.UnbreakableTailLength >= getColumnLimit(State))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000682 return 0;
683
Daniel Jasper567dcf92013-09-05 09:29:45 +0000684 unsigned RemainingSpace =
685 getColumnLimit(State) - Current.UnbreakableTailLength;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000686 bool BreakInserted = false;
687 unsigned Penalty = 0;
688 unsigned RemainingTokenColumns = 0;
689 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
690 LineIndex != EndIndex; ++LineIndex) {
691 if (!DryRun)
692 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
693 unsigned TailOffset = 0;
694 RemainingTokenColumns =
695 Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
696 while (RemainingTokenColumns > RemainingSpace) {
697 BreakableToken::Split Split =
Daniel Jasper567dcf92013-09-05 09:29:45 +0000698 Token->getSplit(LineIndex, TailOffset, getColumnLimit(State));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000699 if (Split.first == StringRef::npos) {
700 // The last line's penalty is handled in addNextStateToQueue().
701 if (LineIndex < EndIndex - 1)
702 Penalty += Style.PenaltyExcessCharacter *
703 (RemainingTokenColumns - RemainingSpace);
704 break;
705 }
706 assert(Split.first != 0);
707 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
708 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
709 assert(NewRemainingTokenColumns < RemainingTokenColumns);
710 if (!DryRun)
711 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Daniel Jasperf5461782013-08-28 10:03:58 +0000712 Penalty += Current.SplitPenalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000713 unsigned ColumnsUsed =
714 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000715 if (ColumnsUsed > getColumnLimit(State)) {
716 Penalty += Style.PenaltyExcessCharacter *
717 (ColumnsUsed - getColumnLimit(State));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000718 }
719 TailOffset += Split.first + Split.second;
720 RemainingTokenColumns = NewRemainingTokenColumns;
721 BreakInserted = true;
722 }
723 }
724
725 State.Column = RemainingTokenColumns;
726
727 if (BreakInserted) {
728 // If we break the token inside a parameter list, we need to break before
729 // the next parameter on all levels, so that the next parameter is clearly
730 // visible. Line comments already introduce a break.
731 if (Current.Type != TT_LineComment) {
732 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
733 State.Stack[i].BreakBeforeParameter = true;
734 }
735
Daniel Jasperf5461782013-08-28 10:03:58 +0000736 Penalty += Current.is(tok::string_literal) ? Style.PenaltyBreakString
737 : Style.PenaltyBreakComment;
738
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000739 State.Stack.back().LastSpace = StartColumn;
740 }
741 return Penalty;
742}
743
Daniel Jasper567dcf92013-09-05 09:29:45 +0000744unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000745 // In preprocessor directives reserve two chars for trailing " \"
Daniel Jasper567dcf92013-09-05 09:29:45 +0000746 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000747}
748
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000749bool ContinuationIndenter::NextIsMultilineString(const LineState &State) {
750 const FormatToken &Current = *State.NextToken;
751 if (!Current.is(tok::string_literal))
752 return false;
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000753 // We never consider raw string literals "multiline" for the purpose of
754 // AlwaysBreakBeforeMultilineStrings implementation.
755 if (Current.TokenText.startswith("R\""))
756 return false;
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000757 if (Current.isMultiline())
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000758 return true;
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000759 if (Current.getNextNonComment() &&
760 Current.getNextNonComment()->is(tok::string_literal))
761 return true; // Implicit concatenation.
762 if (State.Column + Current.CodePointCount + Current.UnbreakableTailLength >
763 Style.ColumnLimit)
764 return true; // String will be split.
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000765 return false;
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000766}
767
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000768} // namespace format
769} // namespace clang