blob: d4bf6ecfa915f6bdb4b426ac4d17c66d3e428de1 [file] [log] [blame]
Daniel Jasperde0328a2013-08-16 11:20:30 +00001//===--- ContinuationIndenter.cpp - Format C++ code -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements the continuation indenter.
12///
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "format-formatter"
16
17#include "BreakableToken.h"
18#include "ContinuationIndenter.h"
19#include "WhitespaceManager.h"
20#include "clang/Basic/OperatorPrecedence.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Format/Format.h"
23#include "llvm/Support/Debug.h"
24#include <string>
25
26namespace clang {
27namespace format {
28
29// Returns the length of everything up to the first possible line break after
30// the ), ], } or > matching \c Tok.
31static unsigned getLengthToMatchingParen(const FormatToken &Tok) {
32 if (Tok.MatchingParen == NULL)
33 return 0;
34 FormatToken *End = Tok.MatchingParen;
35 while (End->Next && !End->Next->CanBreakBefore) {
36 End = End->Next;
37 }
38 return End->TotalLength - Tok.TotalLength + 1;
39}
40
Daniel Jasper4c6e0052013-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 Jasperec01cd62013-10-08 05:11:18 +000047// Returns \c true if \c Current starts a new parameter.
48static bool startsNextParameter(const FormatToken &Current,
49 const FormatStyle &Style) {
50 const FormatToken &Previous = *Current.Previous;
51 if (Current.Type == TT_CtorInitializerComma &&
52 Style.BreakConstructorInitializersBeforeComma)
53 return true;
54 return Previous.is(tok::comma) && !Current.isTrailingComment() &&
55 (Previous.Type != TT_CtorInitializerComma ||
56 !Style.BreakConstructorInitializersBeforeComma);
57}
58
Daniel Jasperde0328a2013-08-16 11:20:30 +000059ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,
60 SourceManager &SourceMgr,
Daniel Jasperde0328a2013-08-16 11:20:30 +000061 WhitespaceManager &Whitespaces,
62 encoding::Encoding Encoding,
63 bool BinPackInconclusiveFunctions)
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000064 : Style(Style), SourceMgr(SourceMgr), Whitespaces(Whitespaces),
65 Encoding(Encoding),
Daniel Jasperde0328a2013-08-16 11:20:30 +000066 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions) {}
67
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000068LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
Daniel Jasper1c5d9df2013-09-06 07:54:20 +000069 const AnnotatedLine *Line,
70 bool DryRun) {
Daniel Jasperde0328a2013-08-16 11:20:30 +000071 LineState State;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000072 State.FirstIndent = FirstIndent;
Daniel Jasperde0328a2013-08-16 11:20:30 +000073 State.Column = FirstIndent;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000074 State.Line = Line;
75 State.NextToken = Line->First;
Alexander Kornienkoe2e03872013-10-14 00:46:35 +000076 State.Stack.push_back(ParenState(FirstIndent, Line->Level, FirstIndent,
Daniel Jasperde0328a2013-08-16 11:20:30 +000077 /*AvoidBinPacking=*/false,
78 /*NoLineBreak=*/false));
79 State.LineContainsContinuedForLoopSection = false;
80 State.ParenLevel = 0;
81 State.StartOfStringLiteral = 0;
82 State.StartOfLineLevel = State.ParenLevel;
83 State.LowestLevelOnLine = State.ParenLevel;
84 State.IgnoreStackForComparison = false;
85
86 // The first token has already been indented and thus consumed.
Daniel Jasper1c5d9df2013-09-06 07:54:20 +000087 moveStateToNextToken(State, DryRun, /*Newline=*/false);
Daniel Jasperde0328a2013-08-16 11:20:30 +000088 return State;
89}
90
91bool ContinuationIndenter::canBreak(const LineState &State) {
92 const FormatToken &Current = *State.NextToken;
93 const FormatToken &Previous = *Current.Previous;
94 assert(&Previous == Current.Previous);
Daniel Jasper1db6c382013-10-22 15:30:28 +000095 if (!Current.CanBreakBefore && !(State.Stack.back().BreakBeforeClosingBrace &&
96 Current.closesBlockTypeList(Style)))
Daniel Jasperde0328a2013-08-16 11:20:30 +000097 return false;
98 // The opening "{" of a braced list has to be on the same line as the first
99 // element if it is nested in another braced init list or function call.
100 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
Daniel Jasperb596fb22013-10-24 10:31:50 +0000101 Previous.Type != TT_DictLiteral &&
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000102 Previous.BlockKind == BK_BracedInit && Previous.Previous &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000103 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
104 return false;
105 // This prevents breaks like:
106 // ...
107 // SomeParameter, OtherParameter).DoSomething(
108 // ...
109 // As they hide "DoSomething" and are generally bad for readability.
110 if (Previous.opensScope() && State.LowestLevelOnLine < State.StartOfLineLevel)
111 return false;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000112 if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
113 return false;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000114 return !State.Stack.back().NoLineBreak;
115}
116
117bool ContinuationIndenter::mustBreak(const LineState &State) {
118 const FormatToken &Current = *State.NextToken;
119 const FormatToken &Previous = *Current.Previous;
120 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
121 return true;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000122 if (State.Stack.back().BreakBeforeClosingBrace &&
123 Current.closesBlockTypeList(Style))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000124 return true;
125 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
126 return true;
Daniel Jasperec01cd62013-10-08 05:11:18 +0000127 if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
Daniel Jasper165b29e2013-11-08 00:57:11 +0000128 (Style.BreakBeforeTernaryOperators &&
129 (Current.is(tok::question) || (Current.Type == TT_ConditionalExpr &&
130 Previous.isNot(tok::question)))) ||
131 (!Style.BreakBeforeTernaryOperators &&
132 (Previous.is(tok::question) || Previous.Type == TT_ConditionalExpr))) &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000133 State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
134 !Current.isOneOf(tok::r_paren, tok::r_brace))
135 return true;
136 if (Style.AlwaysBreakBeforeMultilineStrings &&
Daniel Jasperf438cb72013-08-23 11:57:34 +0000137 State.Column > State.Stack.back().Indent && // Breaking saves columns.
Daniel Jasper27943052013-11-09 03:08:25 +0000138 !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) &&
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000139 Previous.Type != TT_InlineASMColon && nextIsMultilineString(State))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000140 return true;
Daniel Jasperb596fb22013-10-24 10:31:50 +0000141 if (((Previous.Type == TT_DictLiteral && Previous.is(tok::l_brace)) ||
Daniel Jasper1db6c382013-10-22 15:30:28 +0000142 Previous.Type == TT_ArrayInitializerLSquare) &&
Daniel Jasperd489dd32013-10-20 16:45:46 +0000143 getLengthToMatchingParen(Previous) + State.Column > getColumnLimit(State))
144 return true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000145
146 if (!Style.BreakBeforeBinaryOperators) {
147 // If we need to break somewhere inside the LHS of a binary expression, we
148 // should also break after the operator. Otherwise, the formatting would
149 // hide the operator precedence, e.g. in:
150 // if (aaaaaaaaaaaaaa ==
151 // bbbbbbbbbbbbbb && c) {..
152 // For comparisons, we only apply this rule, if the LHS is a binary
153 // expression itself as otherwise, the line breaks seem superfluous.
154 // We need special cases for ">>" which we have split into two ">" while
155 // lexing in order to make template parsing easier.
156 //
157 // FIXME: We'll need something similar for styles that break before binary
158 // operators.
159 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
160 Previous.getPrecedence() == prec::Equality) &&
161 Previous.Previous &&
162 Previous.Previous->Type != TT_BinaryOperator; // For >>.
163 bool LHSIsBinaryExpr =
Daniel Jasper562ecd42013-09-06 08:08:14 +0000164 Previous.Previous && Previous.Previous->EndsBinaryExpression;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000165 if (Previous.Type == TT_BinaryOperator &&
166 (!IsComparison || LHSIsBinaryExpr) &&
167 Current.Type != TT_BinaryOperator && // For >>.
168 !Current.isTrailingComment() &&
169 !Previous.isOneOf(tok::lessless, tok::question) &&
170 Previous.getPrecedence() != prec::Assignment &&
171 State.Stack.back().BreakBeforeParameter)
172 return true;
173 }
174
175 // Same as above, but for the first "<<" operator.
176 if (Current.is(tok::lessless) && State.Stack.back().BreakBeforeParameter &&
177 State.Stack.back().FirstLessLess == 0)
178 return true;
179
Daniel Jasperde0328a2013-08-16 11:20:30 +0000180 if (Current.Type == TT_ObjCSelectorName &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000181 State.Stack.back().ObjCSelectorNameFound &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000182 State.Stack.back().BreakBeforeParameter)
183 return true;
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000184 if (Current.Type == TT_CtorInitializerColon &&
185 (!Style.AllowShortFunctionsOnASingleLine ||
186 Style.BreakConstructorInitializersBeforeComma || Style.ColumnLimit != 0))
187 return true;
188 if (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0 &&
189 !Current.isTrailingComment())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000190 return true;
191
192 if ((Current.Type == TT_StartOfName || Current.is(tok::kw_operator)) &&
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000193 State.Line->MightBeFunctionDecl &&
194 State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000195 return true;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000196 if (startsSegmentOfBuilderTypeCall(Current) &&
Daniel Jasperf8151e92013-08-30 07:12:40 +0000197 (State.Stack.back().CallContinuation != 0 ||
198 (State.Stack.back().BreakBeforeParameter &&
199 State.Stack.back().ContainsUnwrappedBuilder)))
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000200 return true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000201 return false;
202}
203
204unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000205 bool DryRun,
206 unsigned ExtraSpaces) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000207 const FormatToken &Current = *State.NextToken;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000208
Daniel Jasper98857842013-10-30 13:54:53 +0000209 if (State.Stack.size() == 0 ||
210 (Current.Type == TT_ImplicitStringLiteral &&
211 (Current.Previous->Tok.getIdentifierInfo() == NULL ||
212 Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
213 tok::pp_not_keyword))) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000214 // FIXME: Is this correct?
215 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
216 State.NextToken->WhitespaceRange.getEnd()) -
217 SourceMgr.getSpellingColumnNumber(
218 State.NextToken->WhitespaceRange.getBegin());
Alexander Kornienko39856b72013-09-10 09:38:25 +0000219 State.Column += WhitespaceLength + State.NextToken->ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000220 State.NextToken = State.NextToken->Next;
221 return 0;
222 }
223
Alexander Kornienko1f803962013-10-01 14:41:18 +0000224 unsigned Penalty = 0;
225 if (Newline)
226 Penalty = addTokenOnNewLine(State, DryRun);
227 else
Daniel Jasper48437ce2013-11-20 14:54:39 +0000228 addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000229
230 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
231}
232
Daniel Jasper48437ce2013-11-20 14:54:39 +0000233void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
234 unsigned ExtraSpaces) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000235 FormatToken &Current = *State.NextToken;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000236 const FormatToken &Previous = *State.NextToken->Previous;
237 if (Current.is(tok::equal) &&
238 (State.Line->First->is(tok::kw_for) || State.ParenLevel == 0) &&
239 State.Stack.back().VariablePos == 0) {
240 State.Stack.back().VariablePos = State.Column;
241 // Move over * and & if they are bound to the variable name.
242 const FormatToken *Tok = &Previous;
243 while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
244 State.Stack.back().VariablePos -= Tok->ColumnWidth;
245 if (Tok->SpacesRequiredBefore != 0)
246 break;
247 Tok = Tok->Previous;
248 }
249 if (Previous.PartOfMultiVariableDeclStmt)
250 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
251 }
252
253 unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
254
255 if (!DryRun)
256 Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, /*IndentLevel=*/0,
257 Spaces, State.Column + Spaces);
258
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000259 if (Current.Type == TT_ObjCSelectorName &&
260 !State.Stack.back().ObjCSelectorNameFound) {
261 if (Current.LongestObjCSelectorName == 0)
262 State.Stack.back().AlignColons = false;
263 else if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
264 State.Column + Spaces + Current.ColumnWidth)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000265 State.Stack.back().ColonPos =
266 State.Stack.back().Indent + Current.LongestObjCSelectorName;
267 else
268 State.Stack.back().ColonPos = State.Column + Spaces + Current.ColumnWidth;
269 }
270
271 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper5a611392013-12-19 21:41:37 +0000272 (Current.Type != TT_LineComment || Previous.BlockKind == BK_BracedInit))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000273 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasperec01cd62013-10-08 05:11:18 +0000274 if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000275 State.Stack.back().NoLineBreak = true;
276 if (startsSegmentOfBuilderTypeCall(Current))
277 State.Stack.back().ContainsUnwrappedBuilder = true;
278
279 State.Column += Spaces;
280 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
281 // Treat the condition inside an if as if it was a second function
Daniel Jasper6633ab82013-10-18 10:38:14 +0000282 // parameter, i.e. let nested calls have a continuation indent.
Alexander Kornienko1f803962013-10-01 14:41:18 +0000283 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000284 else if (Current.isNot(tok::comment) &&
285 (Previous.is(tok::comma) ||
286 (Previous.is(tok::colon) && Previous.Type == TT_ObjCMethodExpr)))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000287 State.Stack.back().LastSpace = State.Column;
288 else if ((Previous.Type == TT_BinaryOperator ||
289 Previous.Type == TT_ConditionalExpr ||
290 Previous.Type == TT_UnaryOperator ||
291 Previous.Type == TT_CtorInitializerColon) &&
292 (Previous.getPrecedence() != prec::Assignment ||
293 Current.StartsBinaryExpression))
294 // Always indent relative to the RHS of the expression unless this is a
295 // simple assignment without binary expression on the RHS. Also indent
296 // relative to unary operators and the colons of constructor initializers.
297 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf9a5e402013-10-08 16:24:07 +0000298 else if (Previous.Type == TT_InheritanceColon) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000299 State.Stack.back().Indent = State.Column;
Daniel Jasperf9a5e402013-10-08 16:24:07 +0000300 State.Stack.back().LastSpace = State.Column;
301 } else if (Previous.opensScope()) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000302 // If a function has a trailing call, indent all parameters from the
303 // opening parenthesis. This avoids confusing indents like:
304 // OuterFunction(InnerFunctionCall( // break
305 // ParameterToInnerFunction)) // break
306 // .SecondInnerFunctionCall();
307 bool HasTrailingCall = false;
308 if (Previous.MatchingParen) {
309 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
310 HasTrailingCall = Next && Next->isMemberAccess();
311 }
312 if (HasTrailingCall &&
313 State.Stack[State.Stack.size() - 2].CallContinuation == 0)
314 State.Stack.back().LastSpace = State.Column;
315 }
316}
317
318unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
319 bool DryRun) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000320 FormatToken &Current = *State.NextToken;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000321 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasper6633ab82013-10-18 10:38:14 +0000322 // If we are continuing an expression, we want to use the continuation indent.
Daniel Jasperde0328a2013-08-16 11:20:30 +0000323 unsigned ContinuationIndent =
Daniel Jasper6633ab82013-10-18 10:38:14 +0000324 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
325 Style.ContinuationIndentWidth;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000326 // Extra penalty that needs to be added because of the way certain line
327 // breaks are chosen.
328 unsigned Penalty = 0;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000329
Alexander Kornienko1f803962013-10-01 14:41:18 +0000330 const FormatToken *PreviousNonComment =
331 State.NextToken->getPreviousNonComment();
332 // The first line break on any ParenLevel causes an extra penalty in order
333 // prefer similar line breaks.
334 if (!State.Stack.back().ContainsLineBreak)
335 Penalty += 15;
336 State.Stack.back().ContainsLineBreak = true;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000337
Alexander Kornienko1f803962013-10-01 14:41:18 +0000338 Penalty += State.NextToken->SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000339
Alexander Kornienko1f803962013-10-01 14:41:18 +0000340 // Breaking before the first "<<" is generally not desirable if the LHS is
Daniel Jasper48437ce2013-11-20 14:54:39 +0000341 // short. Also always add the penalty if the LHS is split over mutliple lines
342 // to avoid unncessary line breaks that just work around this penalty.
343 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0 &&
Daniel Jasper004177e2013-12-19 16:06:40 +0000344 (State.Column <= Style.ColumnLimit / 3 ||
Daniel Jasper48437ce2013-11-20 14:54:39 +0000345 State.Stack.back().BreakBeforeParameter))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000346 Penalty += Style.PenaltyBreakFirstLessLess;
347
348 if (Current.is(tok::l_brace) && Current.BlockKind == BK_Block) {
Daniel Jaspere40caf92013-11-29 08:46:20 +0000349 State.Column =
350 State.ParenLevel == 0 ? State.FirstIndent : State.Stack.back().Indent;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000351 } else if (Current.isOneOf(tok::r_brace, tok::r_square)) {
Daniel Jasper6b6e7c32013-11-07 14:02:28 +0000352 if (Current.closesBlockTypeList(Style) ||
353 (Current.MatchingParen &&
354 Current.MatchingParen->BlockKind == BK_BracedInit))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000355 State.Column = State.Stack[State.Stack.size() - 2].LastSpace;
356 else
Daniel Jasper015ed022013-09-13 09:20:45 +0000357 State.Column = State.FirstIndent;
Daniel Jasper04b6a082013-12-20 06:22:01 +0000358 } else if (Current.isStringLiteral() && State.StartOfStringLiteral != 0) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000359 State.Column = State.StartOfStringLiteral;
360 State.Stack.back().BreakBeforeParameter = true;
361 } else if (Current.is(tok::lessless) &&
362 State.Stack.back().FirstLessLess != 0) {
363 State.Column = State.Stack.back().FirstLessLess;
364 } else if (Current.isMemberAccess()) {
365 if (State.Stack.back().CallContinuation == 0) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000366 State.Column = ContinuationIndent;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000367 State.Stack.back().CallContinuation = State.Column;
368 } else {
369 State.Column = State.Stack.back().CallContinuation;
370 }
Daniel Jasper165b29e2013-11-08 00:57:11 +0000371 } else if (State.Stack.back().QuestionColumn != 0 &&
372 (Current.Type == TT_ConditionalExpr ||
373 Previous.Type == TT_ConditionalExpr)) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000374 State.Column = State.Stack.back().QuestionColumn;
375 } else if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0) {
376 State.Column = State.Stack.back().VariablePos;
377 } else if ((PreviousNonComment &&
378 PreviousNonComment->ClosesTemplateDeclaration) ||
379 ((Current.Type == TT_StartOfName ||
380 Current.is(tok::kw_operator)) &&
381 State.ParenLevel == 0 &&
382 (!Style.IndentFunctionDeclarationAfterType ||
383 State.Line->StartsDefinition))) {
Daniel Jasper298c3402013-11-22 07:48:15 +0000384 State.Column =
385 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000386 } else if (Current.Type == TT_ObjCSelectorName) {
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000387 if (!State.Stack.back().ObjCSelectorNameFound) {
388 if (Current.LongestObjCSelectorName == 0) {
389 State.Column = State.Stack.back().Indent;
390 State.Stack.back().AlignColons = false;
391 } else {
392 State.Stack.back().ColonPos =
393 State.Stack.back().Indent + Current.LongestObjCSelectorName;
394 State.Column = State.Stack.back().ColonPos - Current.ColumnWidth;
395 }
396 } else if (!State.Stack.back().AlignColons) {
397 State.Column = State.Stack.back().Indent;
Daniel Jasperb302f9a2013-11-08 02:08:01 +0000398 } else if (State.Stack.back().ColonPos > Current.ColumnWidth) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000399 State.Column = State.Stack.back().ColonPos - Current.ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000400 } else {
401 State.Column = State.Stack.back().Indent;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000402 State.Stack.back().ColonPos = State.Column + Current.ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000403 }
Daniel Jasper1db6c382013-10-22 15:30:28 +0000404 } else if (Current.Type == TT_ArraySubscriptLSquare) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000405 if (State.Stack.back().StartOfArraySubscripts != 0)
406 State.Column = State.Stack.back().StartOfArraySubscripts;
407 else
408 State.Column = ContinuationIndent;
409 } else if (Current.Type == TT_StartOfName ||
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000410 Previous.isOneOf(tok::coloncolon, tok::equal)) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000411 State.Column = ContinuationIndent;
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000412 } else if (PreviousNonComment &&
413 PreviousNonComment->Type == TT_ObjCMethodExpr) {
414 State.Column = ContinuationIndent;
415 // FIXME: This is hacky, find a better way. The problem is that in an ObjC
416 // method expression, the block should be aligned to the line starting it,
417 // e.g.:
418 // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
419 // ^(int *i) {
420 // // ...
421 // }];
422 // Thus, we set LastSpace of the next higher ParenLevel, to which we move
423 // when we consume all of the "}"'s FakeRParens at the "{".
Daniel Jasper9a26e772013-12-23 11:25:40 +0000424 if (State.Stack.size() > 1)
425 State.Stack[State.Stack.size() - 2].LastSpace = ContinuationIndent;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000426 } else if (Current.Type == TT_CtorInitializerColon) {
427 State.Column = State.FirstIndent + Style.ConstructorInitializerIndentWidth;
428 } else if (Current.Type == TT_CtorInitializerComma) {
429 State.Column = State.Stack.back().Indent;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000430 } else {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000431 State.Column = State.Stack.back().Indent;
Daniel Jasper6633ab82013-10-18 10:38:14 +0000432 // Ensure that we fall back to the continuation indent width instead of just
Alexander Kornienko1f803962013-10-01 14:41:18 +0000433 // flushing continuations left.
Daniel Jasper16fc7542013-10-30 14:04:10 +0000434 if (State.Column == State.FirstIndent &&
435 PreviousNonComment->isNot(tok::r_brace))
Daniel Jasper6633ab82013-10-18 10:38:14 +0000436 State.Column += Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000437 }
438
Alexander Kornienko1f803962013-10-01 14:41:18 +0000439 if ((Previous.isOneOf(tok::comma, tok::semi) &&
440 !State.Stack.back().AvoidBinPacking) ||
441 Previous.Type == TT_BinaryOperator)
442 State.Stack.back().BreakBeforeParameter = false;
443 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
444 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000445 if (Current.is(tok::question) ||
446 (PreviousNonComment && PreviousNonComment->is(tok::question)))
447 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000448
449 if (!DryRun) {
450 unsigned Newlines = 1;
451 if (Current.is(tok::comment))
452 Newlines = std::max(Newlines, std::min(Current.NewlinesBefore,
453 Style.MaxEmptyLinesToKeep + 1));
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000454 Whitespaces.replaceWhitespace(Current, Newlines,
455 State.Stack.back().IndentLevel, State.Column,
456 State.Column, State.Line->InPPDirective);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000457 }
458
459 if (!Current.isTrailingComment())
460 State.Stack.back().LastSpace = State.Column;
461 if (Current.isMemberAccess())
462 State.Stack.back().LastSpace += Current.ColumnWidth;
463 State.StartOfLineLevel = State.ParenLevel;
464 State.LowestLevelOnLine = State.ParenLevel;
465
466 // Any break on this level means that the parent level has been broken
467 // and we need to avoid bin packing there.
468 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
469 State.Stack[i].BreakBeforeParameter = true;
470 }
Daniel Jasper9e5ede02013-11-08 19:56:28 +0000471 if (PreviousNonComment &&
472 !PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
473 PreviousNonComment->Type != TT_TemplateCloser &&
474 PreviousNonComment->Type != TT_BinaryOperator &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000475 Current.Type != TT_BinaryOperator &&
Daniel Jasper9e5ede02013-11-08 19:56:28 +0000476 !PreviousNonComment->opensScope())
Alexander Kornienko1f803962013-10-01 14:41:18 +0000477 State.Stack.back().BreakBeforeParameter = true;
478
Daniel Jasper1db6c382013-10-22 15:30:28 +0000479 // If we break after { or the [ of an array initializer, we should also break
480 // before the corresponding } or ].
481 if (Previous.is(tok::l_brace) || Previous.Type == TT_ArrayInitializerLSquare)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000482 State.Stack.back().BreakBeforeClosingBrace = true;
483
484 if (State.Stack.back().AvoidBinPacking) {
485 // If we are breaking after '(', '{', '<', this is not bin packing
486 // unless AllowAllParametersOfDeclarationOnNextLine is false.
487 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
488 Previous.Type == TT_BinaryOperator) ||
489 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
490 State.Line->MustBeDeclaration))
491 State.Stack.back().BreakBeforeParameter = true;
492 }
493
494 return Penalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000495}
496
497unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
498 bool DryRun, bool Newline) {
499 const FormatToken &Current = *State.NextToken;
500 assert(State.Stack.size());
501
502 if (Current.Type == TT_InheritanceColon)
503 State.Stack.back().AvoidBinPacking = true;
504 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
505 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000506 if (Current.Type == TT_ArraySubscriptLSquare &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000507 State.Stack.back().StartOfArraySubscripts == 0)
508 State.Stack.back().StartOfArraySubscripts = State.Column;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000509 if ((Current.is(tok::question) && Style.BreakBeforeTernaryOperators) ||
510 (Current.getPreviousNonComment() && Current.isNot(tok::colon) &&
511 Current.getPreviousNonComment()->is(tok::question) &&
512 !Style.BreakBeforeTernaryOperators))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000513 State.Stack.back().QuestionColumn = State.Column;
514 if (!Current.opensScope() && !Current.closesScope())
515 State.LowestLevelOnLine =
516 std::min(State.LowestLevelOnLine, State.ParenLevel);
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000517 if (Current.isMemberAccess())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000518 State.Stack.back().StartOfFunctionCall =
Alexander Kornienko39856b72013-09-10 09:38:25 +0000519 Current.LastInChainOfCalls ? 0 : State.Column + Current.ColumnWidth;
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000520 if (Current.Type == TT_ObjCSelectorName)
521 State.Stack.back().ObjCSelectorNameFound = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000522 if (Current.Type == TT_CtorInitializerColon) {
523 // Indent 2 from the column, so:
524 // SomeClass::SomeClass()
525 // : First(...), ...
526 // Next(...)
527 // ^ line up here.
528 State.Stack.back().Indent =
529 State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
530 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
531 State.Stack.back().AvoidBinPacking = true;
532 State.Stack.back().BreakBeforeParameter = false;
533 }
534
Daniel Jasperde0328a2013-08-16 11:20:30 +0000535 // In ObjC method declaration we align on the ":" of parameters, but we need
Daniel Jasper6633ab82013-10-18 10:38:14 +0000536 // to ensure that we indent parameters on subsequent lines by at least our
537 // continuation indent width.
Daniel Jasperde0328a2013-08-16 11:20:30 +0000538 if (Current.Type == TT_ObjCMethodSpecifier)
Daniel Jasper6633ab82013-10-18 10:38:14 +0000539 State.Stack.back().Indent += Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000540
541 // Insert scopes created by fake parenthesis.
542 const FormatToken *Previous = Current.getPreviousNonComment();
543 // Don't add extra indentation for the first fake parenthesis after
544 // 'return', assignements or opening <({[. The indentation for these cases
545 // is special cased.
546 bool SkipFirstExtraIndent =
Daniel Jaspereabede62013-09-30 08:29:03 +0000547 (Previous && (Previous->opensScope() || Previous->is(tok::kw_return) ||
Daniel Jasperf48b5ab2013-11-07 19:23:49 +0000548 Previous->getPrecedence() == prec::Assignment ||
549 Previous->Type == TT_ObjCMethodExpr));
Daniel Jasperde0328a2013-08-16 11:20:30 +0000550 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
551 I = Current.FakeLParens.rbegin(),
552 E = Current.FakeLParens.rend();
553 I != E; ++I) {
554 ParenState NewParenState = State.Stack.back();
555 NewParenState.ContainsLineBreak = false;
Daniel Jaspereabede62013-09-30 08:29:03 +0000556
557 // Indent from 'LastSpace' unless this the fake parentheses encapsulating a
558 // builder type call after 'return'. If such a call is line-wrapped, we
559 // commonly just want to indent from the start of the line.
560 if (!Previous || Previous->isNot(tok::kw_return) || *I > 0)
561 NewParenState.Indent =
562 std::max(std::max(State.Column, NewParenState.Indent),
563 State.Stack.back().LastSpace);
564
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000565 // Do not indent relative to the fake parentheses inserted for "." or "->".
566 // This is a special case to make the following to statements consistent:
567 // OuterFunction(InnerFunctionCall( // break
568 // ParameterToInnerFunction));
569 // OuterFunction(SomeObject.InnerFunctionCall( // break
570 // ParameterToInnerFunction));
571 if (*I > prec::Unknown)
572 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
Daniel Jasper96964352013-12-18 10:44:36 +0000573 NewParenState.StartOfFunctionCall = State.Column;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000574
575 // Always indent conditional expressions. Never indent expression where
576 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
577 // prec::Assignment) as those have different indentation rules. Indent
578 // other expression, unless the indentation needs to be skipped.
579 if (*I == prec::Conditional ||
580 (!SkipFirstExtraIndent && *I > prec::Assignment &&
581 !Style.BreakBeforeBinaryOperators))
Daniel Jasper6633ab82013-10-18 10:38:14 +0000582 NewParenState.Indent += Style.ContinuationIndentWidth;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000583 if ((Previous && !Previous->opensScope()) || *I > prec::Comma)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000584 NewParenState.BreakBeforeParameter = false;
585 State.Stack.push_back(NewParenState);
586 SkipFirstExtraIndent = false;
587 }
588
589 // If we encounter an opening (, [, { or <, we add a level to our stacks to
590 // prepare for the following tokens.
591 if (Current.opensScope()) {
592 unsigned NewIndent;
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000593 unsigned NewIndentLevel = State.Stack.back().IndentLevel;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000594 bool AvoidBinPacking;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000595 bool BreakBeforeParameter = false;
596 if (Current.is(tok::l_brace) ||
597 Current.Type == TT_ArrayInitializerLSquare) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000598 if (Current.MatchingParen && Current.BlockKind == BK_Block) {
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000599 // If this is an l_brace starting a nested block, we pretend (wrt. to
600 // indentation) that we already consumed the corresponding r_brace.
Daniel Jasper96964352013-12-18 10:44:36 +0000601 // Thus, we remove all ParenStates caused by fake parentheses that end
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000602 // at the r_brace. The net effect of this is that we don't indent
603 // relative to the l_brace, if the nested block is the last parameter of
604 // a function. For example, this formats:
605 //
606 // SomeFunction(a, [] {
607 // f(); // break
608 // });
609 //
610 // instead of:
611 // SomeFunction(a, [] {
Daniel Jasper5500f612013-11-25 11:08:59 +0000612 // f(); // break
613 // });
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000614 for (unsigned i = 0; i != Current.MatchingParen->FakeRParens; ++i)
615 State.Stack.pop_back();
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000616 bool IsObjCBlock =
617 Previous &&
618 (Previous->is(tok::caret) ||
619 (Previous->is(tok::r_paren) && Previous->MatchingParen &&
620 Previous->MatchingParen->Previous &&
621 Previous->MatchingParen->Previous->is(tok::caret)));
622 // For some reason, ObjC blocks are indented like continuations.
623 NewIndent =
624 State.Stack.back().LastSpace +
625 (IsObjCBlock ? Style.ContinuationIndentWidth : Style.IndentWidth);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000626 ++NewIndentLevel;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000627 BreakBeforeParameter = true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000628 } else {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000629 NewIndent = State.Stack.back().LastSpace;
Daniel Jasperb8f61682013-10-22 15:45:58 +0000630 if (Current.opensBlockTypeList(Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000631 NewIndent += Style.IndentWidth;
Daniel Jasper5a611392013-12-19 21:41:37 +0000632 NewIndent = std::min(State.Column + 2, NewIndent);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000633 ++NewIndentLevel;
Daniel Jasperb8f61682013-10-22 15:45:58 +0000634 } else {
635 NewIndent += Style.ContinuationIndentWidth;
Daniel Jasper5a611392013-12-19 21:41:37 +0000636 NewIndent = std::min(State.Column + 1, NewIndent);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000637 }
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000638 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000639 const FormatToken *NextNoComment = Current.getNextNonComment();
Daniel Jasper015ed022013-09-13 09:20:45 +0000640 AvoidBinPacking = Current.BlockKind == BK_Block ||
Daniel Jasper1db6c382013-10-22 15:30:28 +0000641 Current.Type == TT_ArrayInitializerLSquare ||
Daniel Jasperb596fb22013-10-24 10:31:50 +0000642 Current.Type == TT_DictLiteral ||
Daniel Jasper015ed022013-09-13 09:20:45 +0000643 (NextNoComment &&
644 NextNoComment->Type == TT_DesignatedInitializerPeriod);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000645 } else {
Daniel Jasper6633ab82013-10-18 10:38:14 +0000646 NewIndent = Style.ContinuationIndentWidth +
647 std::max(State.Stack.back().LastSpace,
648 State.Stack.back().StartOfFunctionCall);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000649 AvoidBinPacking = !Style.BinPackParameters ||
650 (Style.ExperimentalAutoDetectBinPacking &&
651 (Current.PackingKind == PPK_OnePerLine ||
652 (!BinPackInconclusiveFunctions &&
653 Current.PackingKind == PPK_Inconclusive)));
Daniel Jasper1db6c382013-10-22 15:30:28 +0000654 // If this '[' opens an ObjC call, determine whether all parameters fit
655 // into one line and put one per line if they don't.
656 if (Current.Type == TT_ObjCMethodExpr &&
657 getLengthToMatchingParen(Current) + State.Column >
658 getColumnLimit(State))
659 BreakBeforeParameter = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000660 }
661
Daniel Jaspercc3114d2013-10-18 15:23:06 +0000662 bool NoLineBreak = State.Stack.back().NoLineBreak ||
663 (Current.Type == TT_TemplateOpener &&
664 State.Stack.back().ContainsUnwrappedBuilder);
665 State.Stack.push_back(ParenState(NewIndent, NewIndentLevel,
666 State.Stack.back().LastSpace,
667 AvoidBinPacking, NoLineBreak));
Daniel Jasper1db6c382013-10-22 15:30:28 +0000668 State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000669 ++State.ParenLevel;
670 }
671
Daniel Jasperde0328a2013-08-16 11:20:30 +0000672 // If we encounter a closing ), ], } or >, we can remove a level from our
673 // stacks.
Daniel Jasper96df37a2013-08-28 09:17:37 +0000674 if (State.Stack.size() > 1 &&
675 (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000676 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
Daniel Jasper96df37a2013-08-28 09:17:37 +0000677 State.NextToken->Type == TT_TemplateCloser)) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000678 State.Stack.pop_back();
679 --State.ParenLevel;
680 }
681 if (Current.is(tok::r_square)) {
682 // If this ends the array subscript expr, reset the corresponding value.
683 const FormatToken *NextNonComment = Current.getNextNonComment();
684 if (NextNonComment && NextNonComment->isNot(tok::l_square))
685 State.Stack.back().StartOfArraySubscripts = 0;
686 }
687
688 // Remove scopes created by fake parenthesis.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000689 if (Current.isNot(tok::r_brace) ||
690 (Current.MatchingParen && Current.MatchingParen->BlockKind != BK_Block)) {
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000691 // Don't remove FakeRParens attached to r_braces that surround nested blocks
692 // as they will have been removed early (see above).
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000693 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
694 unsigned VariablePos = State.Stack.back().VariablePos;
695 State.Stack.pop_back();
696 State.Stack.back().VariablePos = VariablePos;
697 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000698 }
699
Daniel Jasper04b6a082013-12-20 06:22:01 +0000700 if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000701 State.StartOfStringLiteral = State.Column;
Daniel Jasper04b6a082013-12-20 06:22:01 +0000702 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
703 !Current.isStringLiteral()) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000704 State.StartOfStringLiteral = 0;
705 }
706
Alexander Kornienko39856b72013-09-10 09:38:25 +0000707 State.Column += Current.ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000708 State.NextToken = State.NextToken->Next;
Daniel Jasperb27c4b72013-08-27 11:09:05 +0000709 unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000710 if (State.Column > getColumnLimit(State)) {
711 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
712 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
713 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000714
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000715 // If the previous has a special role, let it consume tokens as appropriate.
716 // It is necessary to start at the previous token for the only implemented
717 // role (comma separated list). That way, the decision whether or not to break
718 // after the "{" is already done and both options are tried and evaluated.
719 // FIXME: This is ugly, find a better way.
720 if (Previous && Previous->Role)
721 Penalty += Previous->Role->format(State, this, DryRun);
722
723 return Penalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000724}
725
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000726unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
727 LineState &State) {
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000728 // Break before further function parameters on all levels.
729 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
730 State.Stack[i].BreakBeforeParameter = true;
731
Alexander Kornienko39856b72013-09-10 09:38:25 +0000732 unsigned ColumnsUsed = State.Column;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000733 // We can only affect layout of the first and the last line, so the penalty
734 // for all other lines is constant, and we ignore it.
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000735 State.Column = Current.LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000736
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000737 if (ColumnsUsed > getColumnLimit(State))
738 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000739 return 0;
740}
741
Alexander Kornienko81e32942013-09-16 20:20:49 +0000742static bool getRawStringLiteralPrefixPostfix(StringRef Text,
743 StringRef &Prefix,
744 StringRef &Postfix) {
745 if (Text.startswith(Prefix = "R\"") || Text.startswith(Prefix = "uR\"") ||
746 Text.startswith(Prefix = "UR\"") || Text.startswith(Prefix = "u8R\"") ||
747 Text.startswith(Prefix = "LR\"")) {
748 size_t ParenPos = Text.find('(');
749 if (ParenPos != StringRef::npos) {
750 StringRef Delimiter =
751 Text.substr(Prefix.size(), ParenPos - Prefix.size());
752 Prefix = Text.substr(0, ParenPos + 1);
753 Postfix = Text.substr(Text.size() - 2 - Delimiter.size());
754 return Postfix.front() == ')' && Postfix.back() == '"' &&
755 Postfix.substr(1).startswith(Delimiter);
756 }
757 }
758 return false;
759}
760
Daniel Jasperde0328a2013-08-16 11:20:30 +0000761unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
762 LineState &State,
763 bool DryRun) {
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000764 // Don't break multi-line tokens other than block comments. Instead, just
765 // update the state.
766 if (Current.Type != TT_BlockComment && Current.IsMultiline)
767 return addMultilineToken(Current, State);
768
Daniel Jasper98857842013-10-30 13:54:53 +0000769 // Don't break implicit string literals.
770 if (Current.Type == TT_ImplicitStringLiteral)
771 return 0;
772
Daniel Jasper04b6a082013-12-20 06:22:01 +0000773 if (!Current.isStringLiteral() && !Current.is(tok::comment))
Daniel Jasperf93551c2013-08-23 10:05:49 +0000774 return 0;
775
Daniel Jasperde0328a2013-08-16 11:20:30 +0000776 llvm::OwningPtr<BreakableToken> Token;
Alexander Kornienko39856b72013-09-10 09:38:25 +0000777 unsigned StartColumn = State.Column - Current.ColumnWidth;
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000778 unsigned ColumnLimit = getColumnLimit(State);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000779
Daniel Jasper04b6a082013-12-20 06:22:01 +0000780 if (Current.isStringLiteral()) {
Alexander Kornienko384b40b2013-10-11 21:43:05 +0000781 // Don't break string literals inside preprocessor directives (except for
782 // #define directives, as their contents are stored in separate lines and
783 // are not affected by this check).
784 // This way we avoid breaking code with line directives and unknown
785 // preprocessor directives that contain long string literals.
786 if (State.Line->Type == LT_PreprocessorDirective)
787 return 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000788 // Exempts unterminated string literals from line breaking. The user will
789 // likely want to terminate the string before any line breaking is done.
790 if (Current.IsUnterminatedLiteral)
791 return 0;
792
Alexander Kornienko81e32942013-09-16 20:20:49 +0000793 StringRef Text = Current.TokenText;
794 StringRef Prefix;
795 StringRef Postfix;
796 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
797 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
798 // reduce the overhead) for each FormatToken, which is a string, so that we
799 // don't run multiple checks here on the hot path.
800 if ((Text.endswith(Postfix = "\"") &&
801 (Text.startswith(Prefix = "\"") || Text.startswith(Prefix = "u\"") ||
802 Text.startswith(Prefix = "U\"") || Text.startswith(Prefix = "u8\"") ||
803 Text.startswith(Prefix = "L\""))) ||
804 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")")) ||
805 getRawStringLiteralPrefixPostfix(Text, Prefix, Postfix)) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000806 Token.reset(new BreakableStringLiteral(
807 Current, State.Line->Level, StartColumn, Prefix, Postfix,
808 State.Line->InPPDirective, Encoding, Style));
Alexander Kornienko81e32942013-09-16 20:20:49 +0000809 } else {
810 return 0;
811 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000812 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
813 Token.reset(new BreakableBlockComment(
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000814 Current, State.Line->Level, StartColumn, Current.OriginalColumn,
815 !Current.Previous, State.Line->InPPDirective, Encoding, Style));
Daniel Jasperde0328a2013-08-16 11:20:30 +0000816 } else if (Current.Type == TT_LineComment &&
817 (Current.Previous == NULL ||
818 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000819 Token.reset(new BreakableLineComment(Current, State.Line->Level,
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000820 StartColumn, /*InPPDirective=*/false,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000821 Encoding, Style));
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000822 // We don't insert backslashes when breaking line comments.
823 ColumnLimit = Style.ColumnLimit;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000824 } else {
825 return 0;
826 }
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000827 if (Current.UnbreakableTailLength >= ColumnLimit)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000828 return 0;
829
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000830 unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000831 bool BreakInserted = false;
832 unsigned Penalty = 0;
833 unsigned RemainingTokenColumns = 0;
834 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
835 LineIndex != EndIndex; ++LineIndex) {
836 if (!DryRun)
837 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
838 unsigned TailOffset = 0;
839 RemainingTokenColumns =
840 Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
841 while (RemainingTokenColumns > RemainingSpace) {
842 BreakableToken::Split Split =
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000843 Token->getSplit(LineIndex, TailOffset, ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000844 if (Split.first == StringRef::npos) {
845 // The last line's penalty is handled in addNextStateToQueue().
846 if (LineIndex < EndIndex - 1)
847 Penalty += Style.PenaltyExcessCharacter *
848 (RemainingTokenColumns - RemainingSpace);
849 break;
850 }
851 assert(Split.first != 0);
852 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
853 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
Alexander Kornienko875395f2013-11-12 17:50:13 +0000854
855 // We can remove extra whitespace instead of breaking the line.
856 if (RemainingTokenColumns + 1 - Split.second <= RemainingSpace) {
857 RemainingTokenColumns = 0;
858 if (!DryRun)
859 Token->replaceWhitespace(LineIndex, TailOffset, Split, Whitespaces);
860 break;
861 }
862
Daniel Jasperde0328a2013-08-16 11:20:30 +0000863 assert(NewRemainingTokenColumns < RemainingTokenColumns);
864 if (!DryRun)
865 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Daniel Jasper2739af32013-08-28 10:03:58 +0000866 Penalty += Current.SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000867 unsigned ColumnsUsed =
868 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000869 if (ColumnsUsed > ColumnLimit) {
870 Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000871 }
872 TailOffset += Split.first + Split.second;
873 RemainingTokenColumns = NewRemainingTokenColumns;
874 BreakInserted = true;
875 }
876 }
877
878 State.Column = RemainingTokenColumns;
879
880 if (BreakInserted) {
881 // If we break the token inside a parameter list, we need to break before
882 // the next parameter on all levels, so that the next parameter is clearly
883 // visible. Line comments already introduce a break.
884 if (Current.Type != TT_LineComment) {
885 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
886 State.Stack[i].BreakBeforeParameter = true;
887 }
888
Daniel Jasper04b6a082013-12-20 06:22:01 +0000889 Penalty += Current.isStringLiteral() ? Style.PenaltyBreakString
890 : Style.PenaltyBreakComment;
Daniel Jasper2739af32013-08-28 10:03:58 +0000891
Daniel Jasperde0328a2013-08-16 11:20:30 +0000892 State.Stack.back().LastSpace = StartColumn;
893 }
894 return Penalty;
895}
896
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000897unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000898 // In preprocessor directives reserve two chars for trailing " \"
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000899 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000900}
901
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000902bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
Daniel Jasperf438cb72013-08-23 11:57:34 +0000903 const FormatToken &Current = *State.NextToken;
Daniel Jasper04b6a082013-12-20 06:22:01 +0000904 if (!Current.isStringLiteral())
Daniel Jasperf438cb72013-08-23 11:57:34 +0000905 return false;
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000906 // We never consider raw string literals "multiline" for the purpose of
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000907 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
908 // (see TokenAnnotator::mustBreakBefore().
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000909 if (Current.TokenText.startswith("R\""))
910 return false;
Alexander Kornienko39856b72013-09-10 09:38:25 +0000911 if (Current.IsMultiline)
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000912 return true;
Daniel Jasperf438cb72013-08-23 11:57:34 +0000913 if (Current.getNextNonComment() &&
Daniel Jasper04b6a082013-12-20 06:22:01 +0000914 Current.getNextNonComment()->isStringLiteral())
Daniel Jasperf438cb72013-08-23 11:57:34 +0000915 return true; // Implicit concatenation.
Alexander Kornienko39856b72013-09-10 09:38:25 +0000916 if (State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
Daniel Jasperf438cb72013-08-23 11:57:34 +0000917 Style.ColumnLimit)
918 return true; // String will be split.
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000919 return false;
Daniel Jasperf438cb72013-08-23 11:57:34 +0000920}
921
Daniel Jasperde0328a2013-08-16 11:20:30 +0000922} // namespace format
923} // namespace clang