blob: 40d9d2f7d292ff17daab973ba983f5191f5bbe6b [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 Jasper00e0f432013-09-06 21:46:41 +0000228 if (Current.MatchingParen &&
229 (Current.MatchingParen->BlockKind == BK_BracedInit ||
230 !Current.MatchingParen->Children.empty()))
231 State.Column = State.Stack[State.Stack.size() - 2].LastSpace;
232 else
233 State.Column = State.FirstIndent;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000234 } else if (Current.is(tok::string_literal) &&
235 State.StartOfStringLiteral != 0) {
236 State.Column = State.StartOfStringLiteral;
237 State.Stack.back().BreakBeforeParameter = true;
238 } else if (Current.is(tok::lessless) &&
239 State.Stack.back().FirstLessLess != 0) {
240 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000241 } else if (Current.isMemberAccess()) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000242 if (State.Stack.back().CallContinuation == 0) {
243 State.Column = ContinuationIndent;
244 State.Stack.back().CallContinuation = State.Column;
245 } else {
246 State.Column = State.Stack.back().CallContinuation;
247 }
248 } else if (Current.Type == TT_ConditionalExpr) {
249 State.Column = State.Stack.back().QuestionColumn;
250 } else if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0) {
251 State.Column = State.Stack.back().VariablePos;
252 } else if (Previous.ClosesTemplateDeclaration ||
253 ((Current.Type == TT_StartOfName ||
254 Current.is(tok::kw_operator)) &&
255 State.ParenLevel == 0 &&
256 (!Style.IndentFunctionDeclarationAfterType ||
Daniel Jasper567dcf92013-09-05 09:29:45 +0000257 State.Line->StartsDefinition))) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000258 State.Column = State.Stack.back().Indent;
259 } else if (Current.Type == TT_ObjCSelectorName) {
260 if (State.Stack.back().ColonPos > Current.CodePointCount) {
261 State.Column = State.Stack.back().ColonPos - Current.CodePointCount;
262 } else {
263 State.Column = State.Stack.back().Indent;
264 State.Stack.back().ColonPos = State.Column + Current.CodePointCount;
265 }
Daniel Jasperac2c9742013-09-05 10:04:31 +0000266 } else if (Current.is(tok::l_square) && Current.Type != TT_ObjCMethodExpr &&
267 Current.Type != TT_LambdaLSquare) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000268 if (State.Stack.back().StartOfArraySubscripts != 0)
269 State.Column = State.Stack.back().StartOfArraySubscripts;
270 else
271 State.Column = ContinuationIndent;
272 } else if (Current.Type == TT_StartOfName ||
273 Previous.isOneOf(tok::coloncolon, tok::equal) ||
274 Previous.Type == TT_ObjCMethodExpr) {
275 State.Column = ContinuationIndent;
276 } else if (Current.Type == TT_CtorInitializerColon) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000277 State.Column =
278 State.FirstIndent + Style.ConstructorInitializerIndentWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000279 } else if (Current.Type == TT_CtorInitializerComma) {
280 State.Column = State.Stack.back().Indent;
281 } else {
282 State.Column = State.Stack.back().Indent;
283 // Ensure that we fall back to indenting 4 spaces instead of just
284 // flushing continuations left.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000285 if (State.Column == State.FirstIndent)
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000286 State.Column += 4;
287 }
288
289 if (Current.is(tok::question))
290 State.Stack.back().BreakBeforeParameter = true;
291 if ((Previous.isOneOf(tok::comma, tok::semi) &&
292 !State.Stack.back().AvoidBinPacking) ||
293 Previous.Type == TT_BinaryOperator)
294 State.Stack.back().BreakBeforeParameter = false;
295 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
296 State.Stack.back().BreakBeforeParameter = false;
297
298 if (!DryRun) {
299 unsigned NewLines = 1;
300 if (Current.is(tok::comment))
301 NewLines = std::max(NewLines, std::min(Current.NewlinesBefore,
302 Style.MaxEmptyLinesToKeep + 1));
303 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Daniel Jasper567dcf92013-09-05 09:29:45 +0000304 State.Column, State.Line->InPPDirective);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000305 }
306
307 if (!Current.isTrailingComment())
308 State.Stack.back().LastSpace = State.Column;
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000309 if (Current.isMemberAccess())
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000310 State.Stack.back().LastSpace += Current.CodePointCount;
311 State.StartOfLineLevel = State.ParenLevel;
312 State.LowestLevelOnLine = State.ParenLevel;
313
314 // Any break on this level means that the parent level has been broken
315 // and we need to avoid bin packing there.
316 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
317 State.Stack[i].BreakBeforeParameter = true;
318 }
319 const FormatToken *TokenBefore = Current.getPreviousNonComment();
320 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
321 TokenBefore->Type != TT_TemplateCloser &&
322 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
323 State.Stack.back().BreakBeforeParameter = true;
324
325 // If we break after {, we should also break before the corresponding }.
326 if (Previous.is(tok::l_brace))
327 State.Stack.back().BreakBeforeClosingBrace = true;
328
329 if (State.Stack.back().AvoidBinPacking) {
330 // If we are breaking after '(', '{', '<', this is not bin packing
331 // unless AllowAllParametersOfDeclarationOnNextLine is false.
332 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
333 Previous.Type == TT_BinaryOperator) ||
334 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
Daniel Jasper567dcf92013-09-05 09:29:45 +0000335 State.Line->MustBeDeclaration))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000336 State.Stack.back().BreakBeforeParameter = true;
337 }
338
339 } else {
340 if (Current.is(tok::equal) &&
Daniel Jasper567dcf92013-09-05 09:29:45 +0000341 (State.Line->First->is(tok::kw_for) || State.ParenLevel == 0) &&
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000342 State.Stack.back().VariablePos == 0) {
343 State.Stack.back().VariablePos = State.Column;
344 // Move over * and & if they are bound to the variable name.
345 const FormatToken *Tok = &Previous;
346 while (Tok && State.Stack.back().VariablePos >= Tok->CodePointCount) {
347 State.Stack.back().VariablePos -= Tok->CodePointCount;
348 if (Tok->SpacesRequiredBefore != 0)
349 break;
350 Tok = Tok->Previous;
351 }
352 if (Previous.PartOfMultiVariableDeclStmt)
353 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
354 }
355
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000356 unsigned Spaces = State.NextToken->SpacesRequiredBefore + ExtraSpaces;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000357
358 if (!DryRun)
359 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column + Spaces);
360
361 if (Current.Type == TT_ObjCSelectorName &&
362 State.Stack.back().ColonPos == 0) {
363 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
364 State.Column + Spaces + Current.CodePointCount)
365 State.Stack.back().ColonPos =
366 State.Stack.back().Indent + Current.LongestObjCSelectorName;
367 else
368 State.Stack.back().ColonPos =
369 State.Column + Spaces + Current.CodePointCount;
370 }
371
372 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
373 Current.Type != TT_LineComment)
374 State.Stack.back().Indent = State.Column + Spaces;
375 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
376 State.Stack.back().AvoidBinPacking)
377 State.Stack.back().NoLineBreak = true;
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000378 if (startsSegmentOfBuilderTypeCall(Current))
379 State.Stack.back().ContainsUnwrappedBuilder = true;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000380
381 State.Column += Spaces;
382 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
383 // Treat the condition inside an if as if it was a second function
384 // parameter, i.e. let nested calls have an indent of 4.
385 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
386 else if (Previous.is(tok::comma))
387 State.Stack.back().LastSpace = State.Column;
388 else if ((Previous.Type == TT_BinaryOperator ||
389 Previous.Type == TT_ConditionalExpr ||
Daniel Jasper34f3d052013-08-21 08:39:01 +0000390 Previous.Type == TT_UnaryOperator ||
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000391 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasperd489f8c2013-08-27 11:09:05 +0000392 (Previous.getPrecedence() != prec::Assignment ||
Daniel Jasperdb4813a2013-09-06 08:08:14 +0000393 Current.StartsBinaryExpression))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000394 // Always indent relative to the RHS of the expression unless this is a
Daniel Jasper34f3d052013-08-21 08:39:01 +0000395 // simple assignment without binary expression on the RHS. Also indent
396 // relative to unary operators and the colons of constructor initializers.
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000397 State.Stack.back().LastSpace = State.Column;
398 else if (Previous.Type == TT_InheritanceColon)
399 State.Stack.back().Indent = State.Column;
400 else if (Previous.opensScope()) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000401 // If a function has a trailing call, indent all parameters from the
402 // opening parenthesis. This avoids confusing indents like:
403 // OuterFunction(InnerFunctionCall( // break
404 // ParameterToInnerFunction)) // break
405 // .SecondInnerFunctionCall();
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000406 bool HasTrailingCall = false;
407 if (Previous.MatchingParen) {
408 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000409 HasTrailingCall = Next && Next->isMemberAccess();
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000410 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000411 if (HasTrailingCall &&
412 State.Stack[State.Stack.size() - 2].CallContinuation == 0)
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000413 State.Stack.back().LastSpace = State.Column;
414 }
415 }
416
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000417 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000418}
419
420unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
421 bool DryRun, bool Newline) {
422 const FormatToken &Current = *State.NextToken;
423 assert(State.Stack.size());
424
425 if (Current.Type == TT_InheritanceColon)
426 State.Stack.back().AvoidBinPacking = true;
427 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
428 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000429 if (Current.is(tok::l_square) && Current.Type != TT_LambdaLSquare &&
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000430 State.Stack.back().StartOfArraySubscripts == 0)
431 State.Stack.back().StartOfArraySubscripts = State.Column;
432 if (Current.is(tok::question))
433 State.Stack.back().QuestionColumn = State.Column;
434 if (!Current.opensScope() && !Current.closesScope())
435 State.LowestLevelOnLine =
436 std::min(State.LowestLevelOnLine, State.ParenLevel);
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000437 if (Current.isMemberAccess())
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000438 State.Stack.back().StartOfFunctionCall =
439 Current.LastInChainOfCalls ? 0 : State.Column + Current.CodePointCount;
440 if (Current.Type == TT_CtorInitializerColon) {
441 // Indent 2 from the column, so:
442 // SomeClass::SomeClass()
443 // : First(...), ...
444 // Next(...)
445 // ^ line up here.
446 State.Stack.back().Indent =
447 State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
448 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
449 State.Stack.back().AvoidBinPacking = true;
450 State.Stack.back().BreakBeforeParameter = false;
451 }
452
453 // If return returns a binary expression, align after it.
Daniel Jasperdb4813a2013-09-06 08:08:14 +0000454 if (Current.is(tok::kw_return) && Current.StartsBinaryExpression)
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000455 State.Stack.back().LastSpace = State.Column + 7;
456
457 // In ObjC method declaration we align on the ":" of parameters, but we need
458 // to ensure that we indent parameters on subsequent lines by at least 4.
459 if (Current.Type == TT_ObjCMethodSpecifier)
460 State.Stack.back().Indent += 4;
461
462 // Insert scopes created by fake parenthesis.
463 const FormatToken *Previous = Current.getPreviousNonComment();
464 // Don't add extra indentation for the first fake parenthesis after
465 // 'return', assignements or opening <({[. The indentation for these cases
466 // is special cased.
467 bool SkipFirstExtraIndent =
468 Current.is(tok::kw_return) ||
469 (Previous && (Previous->opensScope() ||
470 Previous->getPrecedence() == prec::Assignment));
471 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
472 I = Current.FakeLParens.rbegin(),
473 E = Current.FakeLParens.rend();
474 I != E; ++I) {
475 ParenState NewParenState = State.Stack.back();
476 NewParenState.ContainsLineBreak = false;
477 NewParenState.Indent =
478 std::max(std::max(State.Column, NewParenState.Indent),
479 State.Stack.back().LastSpace);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000480 // Do not indent relative to the fake parentheses inserted for "." or "->".
481 // This is a special case to make the following to statements consistent:
482 // OuterFunction(InnerFunctionCall( // break
483 // ParameterToInnerFunction));
484 // OuterFunction(SomeObject.InnerFunctionCall( // break
485 // ParameterToInnerFunction));
486 if (*I > prec::Unknown)
487 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000488
489 // Always indent conditional expressions. Never indent expression where
490 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
491 // prec::Assignment) as those have different indentation rules. Indent
492 // other expression, unless the indentation needs to be skipped.
493 if (*I == prec::Conditional ||
494 (!SkipFirstExtraIndent && *I > prec::Assignment &&
495 !Style.BreakBeforeBinaryOperators))
496 NewParenState.Indent += 4;
497 if (Previous && !Previous->opensScope())
498 NewParenState.BreakBeforeParameter = false;
499 State.Stack.push_back(NewParenState);
500 SkipFirstExtraIndent = false;
501 }
502
503 // If we encounter an opening (, [, { or <, we add a level to our stacks to
504 // prepare for the following tokens.
505 if (Current.opensScope()) {
506 unsigned NewIndent;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000507 bool AvoidBinPacking;
508 if (Current.is(tok::l_brace)) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000509 if (Current.MatchingParen && Current.BlockKind == BK_Block) {
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000510 // If this is an l_brace starting a nested block, we pretend (wrt. to
511 // indentation) that we already consumed the corresponding r_brace.
512 // Thus, we remove all ParenStates caused bake fake parentheses that end
513 // at the r_brace. The net effect of this is that we don't indent
514 // relative to the l_brace, if the nested block is the last parameter of
515 // a function. For example, this formats:
516 //
517 // SomeFunction(a, [] {
518 // f(); // break
519 // });
520 //
521 // instead of:
522 // SomeFunction(a, [] {
523 // f(); // break
524 // });
Daniel Jasper567dcf92013-09-05 09:29:45 +0000525 for (unsigned i = 0; i != Current.MatchingParen->FakeRParens; ++i)
526 State.Stack.pop_back();
527 NewIndent = State.Stack.back().LastSpace;
528 } else {
529 NewIndent = State.Stack.back().LastSpace +
530 (Style.Cpp11BracedListStyle ? 4 : Style.IndentWidth);
531 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000532 const FormatToken *NextNoComment = Current.getNextNonComment();
533 AvoidBinPacking = NextNoComment &&
534 NextNoComment->Type == TT_DesignatedInitializerPeriod;
535 } else {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000536 NewIndent = 4 + std::max(State.Stack.back().LastSpace,
537 State.Stack.back().StartOfFunctionCall);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000538 AvoidBinPacking = !Style.BinPackParameters ||
539 (Style.ExperimentalAutoDetectBinPacking &&
540 (Current.PackingKind == PPK_OnePerLine ||
541 (!BinPackInconclusiveFunctions &&
542 Current.PackingKind == PPK_Inconclusive)));
543 }
544
Daniel Jasper567dcf92013-09-05 09:29:45 +0000545 State.Stack.push_back(ParenState(NewIndent, State.Stack.back().LastSpace,
546 AvoidBinPacking,
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000547 State.Stack.back().NoLineBreak));
548 ++State.ParenLevel;
549 }
550
551 // If this '[' opens an ObjC call, determine whether all parameters fit into
552 // one line and put one per line if they don't.
553 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
554 Current.MatchingParen != NULL) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000555 if (getLengthToMatchingParen(Current) + State.Column >
556 getColumnLimit(State))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000557 State.Stack.back().BreakBeforeParameter = true;
558 }
559
560 // If we encounter a closing ), ], } or >, we can remove a level from our
561 // stacks.
Daniel Jasper7143a212013-08-28 09:17:37 +0000562 if (State.Stack.size() > 1 &&
563 (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper567dcf92013-09-05 09:29:45 +0000564 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
Daniel Jasper7143a212013-08-28 09:17:37 +0000565 State.NextToken->Type == TT_TemplateCloser)) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000566 State.Stack.pop_back();
567 --State.ParenLevel;
568 }
569 if (Current.is(tok::r_square)) {
570 // If this ends the array subscript expr, reset the corresponding value.
571 const FormatToken *NextNonComment = Current.getNextNonComment();
572 if (NextNonComment && NextNonComment->isNot(tok::l_square))
573 State.Stack.back().StartOfArraySubscripts = 0;
574 }
575
576 // Remove scopes created by fake parenthesis.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000577 if (Current.isNot(tok::r_brace) ||
578 (Current.MatchingParen && Current.MatchingParen->BlockKind != BK_Block)) {
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000579 // Don't remove FakeRParens attached to r_braces that surround nested blocks
580 // as they will have been removed early (see above).
Daniel Jasper567dcf92013-09-05 09:29:45 +0000581 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
582 unsigned VariablePos = State.Stack.back().VariablePos;
583 State.Stack.pop_back();
584 State.Stack.back().VariablePos = VariablePos;
585 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000586 }
587
588 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
589 State.StartOfStringLiteral = State.Column;
590 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
591 tok::string_literal)) {
592 State.StartOfStringLiteral = 0;
593 }
594
595 State.Column += Current.CodePointCount;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000596 State.NextToken = State.NextToken->Next;
Daniel Jasperd489f8c2013-08-27 11:09:05 +0000597 unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000598 if (State.Column > getColumnLimit(State)) {
599 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
600 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
601 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000602
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000603 // If the previous has a special role, let it consume tokens as appropriate.
604 // It is necessary to start at the previous token for the only implemented
605 // role (comma separated list). That way, the decision whether or not to break
606 // after the "{" is already done and both options are tried and evaluated.
607 // FIXME: This is ugly, find a better way.
608 if (Previous && Previous->Role)
609 Penalty += Previous->Role->format(State, this, DryRun);
610
611 return Penalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000612}
613
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000614unsigned
615ContinuationIndenter::addMultilineStringLiteral(const FormatToken &Current,
616 LineState &State) {
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000617 // Break before further function parameters on all levels.
618 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
619 State.Stack[i].BreakBeforeParameter = true;
620
621 unsigned ColumnsUsed =
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000622 State.Column - Current.CodePointCount + Current.FirstLineColumnWidth;
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000623 // We can only affect layout of the first and the last line, so the penalty
624 // for all other lines is constant, and we ignore it.
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000625 State.Column = Current.LastLineColumnWidth;
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000626
Daniel Jasper567dcf92013-09-05 09:29:45 +0000627 if (ColumnsUsed > getColumnLimit(State))
628 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000629 return 0;
630}
631
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000632unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
633 LineState &State,
634 bool DryRun) {
Daniel Jaspered51c022013-08-23 10:05:49 +0000635 if (!Current.isOneOf(tok::string_literal, tok::comment))
636 return 0;
637
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000638 llvm::OwningPtr<BreakableToken> Token;
639 unsigned StartColumn = State.Column - Current.CodePointCount;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000640
641 if (Current.is(tok::string_literal) &&
642 Current.Type != TT_ImplicitStringLiteral) {
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000643 // Don't break string literals with (in case of non-raw strings, escaped)
644 // newlines. As clang-format must not change the string's content, it is
645 // unlikely that we'll end up with a better format.
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000646 if (Current.isMultiline())
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000647 return addMultilineStringLiteral(Current, State);
648
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000649 // Only break up default narrow strings.
650 if (!Current.TokenText.startswith("\""))
651 return 0;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000652 // Exempts unterminated string literals from line breaking. The user will
653 // likely want to terminate the string before any line breaking is done.
654 if (Current.IsUnterminatedLiteral)
655 return 0;
656
Daniel Jasper567dcf92013-09-05 09:29:45 +0000657 Token.reset(new BreakableStringLiteral(
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000658 Current, StartColumn, State.Line->InPPDirective, Encoding, Style));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000659 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000660 unsigned OriginalStartColumn =
661 SourceMgr.getSpellingColumnNumber(Current.getStartOfNonWhitespace()) -
662 1;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000663 Token.reset(new BreakableBlockComment(
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000664 Current, StartColumn, OriginalStartColumn, !Current.Previous,
665 State.Line->InPPDirective, Encoding, Style));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000666 } else if (Current.Type == TT_LineComment &&
667 (Current.Previous == NULL ||
668 Current.Previous->Type != TT_ImplicitStringLiteral)) {
669 // Don't break line comments with escaped newlines. These look like
670 // separate line comments, but in fact contain a single line comment with
671 // multiple lines including leading whitespace and the '//' markers.
672 //
673 // FIXME: If we want to handle them correctly, we'll need to adjust
674 // leading whitespace in consecutive lines when changing indentation of
675 // the first line similar to what we do with block comments.
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000676 if (Current.isMultiline()) {
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000677 State.Column = StartColumn + Current.FirstLineColumnWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000678 return 0;
679 }
680
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000681 Token.reset(new BreakableLineComment(
682 Current, StartColumn, State.Line->InPPDirective, Encoding, Style));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000683 } else {
684 return 0;
685 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000686 if (Current.UnbreakableTailLength >= getColumnLimit(State))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000687 return 0;
688
Daniel Jasper567dcf92013-09-05 09:29:45 +0000689 unsigned RemainingSpace =
690 getColumnLimit(State) - Current.UnbreakableTailLength;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000691 bool BreakInserted = false;
692 unsigned Penalty = 0;
693 unsigned RemainingTokenColumns = 0;
694 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
695 LineIndex != EndIndex; ++LineIndex) {
696 if (!DryRun)
697 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
698 unsigned TailOffset = 0;
699 RemainingTokenColumns =
700 Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
701 while (RemainingTokenColumns > RemainingSpace) {
702 BreakableToken::Split Split =
Daniel Jasper567dcf92013-09-05 09:29:45 +0000703 Token->getSplit(LineIndex, TailOffset, getColumnLimit(State));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000704 if (Split.first == StringRef::npos) {
705 // The last line's penalty is handled in addNextStateToQueue().
706 if (LineIndex < EndIndex - 1)
707 Penalty += Style.PenaltyExcessCharacter *
708 (RemainingTokenColumns - RemainingSpace);
709 break;
710 }
711 assert(Split.first != 0);
712 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
713 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
714 assert(NewRemainingTokenColumns < RemainingTokenColumns);
715 if (!DryRun)
716 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Daniel Jasperf5461782013-08-28 10:03:58 +0000717 Penalty += Current.SplitPenalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000718 unsigned ColumnsUsed =
719 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000720 if (ColumnsUsed > getColumnLimit(State)) {
721 Penalty += Style.PenaltyExcessCharacter *
722 (ColumnsUsed - getColumnLimit(State));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000723 }
724 TailOffset += Split.first + Split.second;
725 RemainingTokenColumns = NewRemainingTokenColumns;
726 BreakInserted = true;
727 }
728 }
729
730 State.Column = RemainingTokenColumns;
731
732 if (BreakInserted) {
733 // If we break the token inside a parameter list, we need to break before
734 // the next parameter on all levels, so that the next parameter is clearly
735 // visible. Line comments already introduce a break.
736 if (Current.Type != TT_LineComment) {
737 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
738 State.Stack[i].BreakBeforeParameter = true;
739 }
740
Daniel Jasperf5461782013-08-28 10:03:58 +0000741 Penalty += Current.is(tok::string_literal) ? Style.PenaltyBreakString
742 : Style.PenaltyBreakComment;
743
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000744 State.Stack.back().LastSpace = StartColumn;
745 }
746 return Penalty;
747}
748
Daniel Jasper567dcf92013-09-05 09:29:45 +0000749unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000750 // In preprocessor directives reserve two chars for trailing " \"
Daniel Jasper567dcf92013-09-05 09:29:45 +0000751 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000752}
753
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000754bool ContinuationIndenter::NextIsMultilineString(const LineState &State) {
755 const FormatToken &Current = *State.NextToken;
756 if (!Current.is(tok::string_literal))
757 return false;
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000758 // We never consider raw string literals "multiline" for the purpose of
759 // AlwaysBreakBeforeMultilineStrings implementation.
760 if (Current.TokenText.startswith("R\""))
761 return false;
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000762 if (Current.isMultiline())
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000763 return true;
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000764 if (Current.getNextNonComment() &&
765 Current.getNextNonComment()->is(tok::string_literal))
766 return true; // Implicit concatenation.
767 if (State.Column + Current.CodePointCount + Current.UnbreakableTailLength >
768 Style.ColumnLimit)
769 return true; // String will be split.
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000770 return false;
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000771}
772
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000773} // namespace format
774} // namespace clang