blob: 872545660caaa3cf9e3ee5c2baf955549f6ebcfc [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),
Alexander Kornienkoce9161a2014-01-02 15:13:14 +000066 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
67 CommentPragmasRegex(Style.CommentPragmas) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +000068
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000069LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
Daniel Jasper1c5d9df2013-09-06 07:54:20 +000070 const AnnotatedLine *Line,
71 bool DryRun) {
Daniel Jasperde0328a2013-08-16 11:20:30 +000072 LineState State;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000073 State.FirstIndent = FirstIndent;
Daniel Jasperde0328a2013-08-16 11:20:30 +000074 State.Column = FirstIndent;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000075 State.Line = Line;
76 State.NextToken = Line->First;
Alexander Kornienkoe2e03872013-10-14 00:46:35 +000077 State.Stack.push_back(ParenState(FirstIndent, Line->Level, FirstIndent,
Daniel Jasperde0328a2013-08-16 11:20:30 +000078 /*AvoidBinPacking=*/false,
79 /*NoLineBreak=*/false));
80 State.LineContainsContinuedForLoopSection = false;
81 State.ParenLevel = 0;
82 State.StartOfStringLiteral = 0;
83 State.StartOfLineLevel = State.ParenLevel;
84 State.LowestLevelOnLine = State.ParenLevel;
85 State.IgnoreStackForComparison = false;
86
87 // The first token has already been indented and thus consumed.
Daniel Jasper1c5d9df2013-09-06 07:54:20 +000088 moveStateToNextToken(State, DryRun, /*Newline=*/false);
Daniel Jasperde0328a2013-08-16 11:20:30 +000089 return State;
90}
91
92bool ContinuationIndenter::canBreak(const LineState &State) {
93 const FormatToken &Current = *State.NextToken;
94 const FormatToken &Previous = *Current.Previous;
95 assert(&Previous == Current.Previous);
Daniel Jasper1db6c382013-10-22 15:30:28 +000096 if (!Current.CanBreakBefore && !(State.Stack.back().BreakBeforeClosingBrace &&
97 Current.closesBlockTypeList(Style)))
Daniel Jasperde0328a2013-08-16 11:20:30 +000098 return false;
99 // The opening "{" of a braced list has to be on the same line as the first
100 // element if it is nested in another braced init list or function call.
101 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
Daniel Jasperb596fb22013-10-24 10:31:50 +0000102 Previous.Type != TT_DictLiteral &&
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000103 Previous.BlockKind == BK_BracedInit && Previous.Previous &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000104 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
105 return false;
106 // This prevents breaks like:
107 // ...
108 // SomeParameter, OtherParameter).DoSomething(
109 // ...
110 // As they hide "DoSomething" and are generally bad for readability.
111 if (Previous.opensScope() && State.LowestLevelOnLine < State.StartOfLineLevel)
112 return false;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000113 if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
114 return false;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000115 return !State.Stack.back().NoLineBreak;
116}
117
118bool ContinuationIndenter::mustBreak(const LineState &State) {
119 const FormatToken &Current = *State.NextToken;
120 const FormatToken &Previous = *Current.Previous;
121 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
122 return true;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000123 if (State.Stack.back().BreakBeforeClosingBrace &&
124 Current.closesBlockTypeList(Style))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000125 return true;
126 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
127 return true;
Daniel Jasperec01cd62013-10-08 05:11:18 +0000128 if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
Daniel Jasper165b29e2013-11-08 00:57:11 +0000129 (Style.BreakBeforeTernaryOperators &&
130 (Current.is(tok::question) || (Current.Type == TT_ConditionalExpr &&
131 Previous.isNot(tok::question)))) ||
132 (!Style.BreakBeforeTernaryOperators &&
133 (Previous.is(tok::question) || Previous.Type == TT_ConditionalExpr))) &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000134 State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
135 !Current.isOneOf(tok::r_paren, tok::r_brace))
136 return true;
137 if (Style.AlwaysBreakBeforeMultilineStrings &&
Daniel Jasperf438cb72013-08-23 11:57:34 +0000138 State.Column > State.Stack.back().Indent && // Breaking saves columns.
Daniel Jasper27943052013-11-09 03:08:25 +0000139 !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) &&
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000140 Previous.Type != TT_InlineASMColon && nextIsMultilineString(State))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000141 return true;
Daniel Jasperb596fb22013-10-24 10:31:50 +0000142 if (((Previous.Type == TT_DictLiteral && Previous.is(tok::l_brace)) ||
Daniel Jasper1db6c382013-10-22 15:30:28 +0000143 Previous.Type == TT_ArrayInitializerLSquare) &&
Daniel Jasperd489dd32013-10-20 16:45:46 +0000144 getLengthToMatchingParen(Previous) + State.Column > getColumnLimit(State))
145 return true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000146
147 if (!Style.BreakBeforeBinaryOperators) {
148 // If we need to break somewhere inside the LHS of a binary expression, we
149 // should also break after the operator. Otherwise, the formatting would
150 // hide the operator precedence, e.g. in:
151 // if (aaaaaaaaaaaaaa ==
152 // bbbbbbbbbbbbbb && c) {..
153 // For comparisons, we only apply this rule, if the LHS is a binary
154 // expression itself as otherwise, the line breaks seem superfluous.
155 // We need special cases for ">>" which we have split into two ">" while
156 // lexing in order to make template parsing easier.
157 //
158 // FIXME: We'll need something similar for styles that break before binary
159 // operators.
160 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
161 Previous.getPrecedence() == prec::Equality) &&
162 Previous.Previous &&
163 Previous.Previous->Type != TT_BinaryOperator; // For >>.
164 bool LHSIsBinaryExpr =
Daniel Jasper562ecd42013-09-06 08:08:14 +0000165 Previous.Previous && Previous.Previous->EndsBinaryExpression;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000166 if (Previous.Type == TT_BinaryOperator &&
167 (!IsComparison || LHSIsBinaryExpr) &&
168 Current.Type != TT_BinaryOperator && // For >>.
169 !Current.isTrailingComment() &&
170 !Previous.isOneOf(tok::lessless, tok::question) &&
171 Previous.getPrecedence() != prec::Assignment &&
172 State.Stack.back().BreakBeforeParameter)
173 return true;
174 }
175
176 // Same as above, but for the first "<<" operator.
177 if (Current.is(tok::lessless) && State.Stack.back().BreakBeforeParameter &&
178 State.Stack.back().FirstLessLess == 0)
179 return true;
180
Daniel Jasperde0328a2013-08-16 11:20:30 +0000181 if (Current.Type == TT_ObjCSelectorName &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000182 State.Stack.back().ObjCSelectorNameFound &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000183 State.Stack.back().BreakBeforeParameter)
184 return true;
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000185 if (Current.Type == TT_CtorInitializerColon &&
186 (!Style.AllowShortFunctionsOnASingleLine ||
187 Style.BreakConstructorInitializersBeforeComma || Style.ColumnLimit != 0))
188 return true;
189 if (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0 &&
190 !Current.isTrailingComment())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000191 return true;
192
193 if ((Current.Type == TT_StartOfName || Current.is(tok::kw_operator)) &&
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000194 State.Line->MightBeFunctionDecl &&
195 State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000196 return true;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000197 if (startsSegmentOfBuilderTypeCall(Current) &&
Daniel Jasperf8151e92013-08-30 07:12:40 +0000198 (State.Stack.back().CallContinuation != 0 ||
199 (State.Stack.back().BreakBeforeParameter &&
200 State.Stack.back().ContainsUnwrappedBuilder)))
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000201 return true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000202 return false;
203}
204
205unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000206 bool DryRun,
207 unsigned ExtraSpaces) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000208 const FormatToken &Current = *State.NextToken;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000209
Daniel Jasper98857842013-10-30 13:54:53 +0000210 if (State.Stack.size() == 0 ||
211 (Current.Type == TT_ImplicitStringLiteral &&
212 (Current.Previous->Tok.getIdentifierInfo() == NULL ||
213 Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
214 tok::pp_not_keyword))) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000215 // FIXME: Is this correct?
216 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
217 State.NextToken->WhitespaceRange.getEnd()) -
218 SourceMgr.getSpellingColumnNumber(
219 State.NextToken->WhitespaceRange.getBegin());
Alexander Kornienko39856b72013-09-10 09:38:25 +0000220 State.Column += WhitespaceLength + State.NextToken->ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000221 State.NextToken = State.NextToken->Next;
222 return 0;
223 }
224
Alexander Kornienko1f803962013-10-01 14:41:18 +0000225 unsigned Penalty = 0;
226 if (Newline)
227 Penalty = addTokenOnNewLine(State, DryRun);
228 else
Daniel Jasper48437ce2013-11-20 14:54:39 +0000229 addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000230
231 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
232}
233
Daniel Jasper48437ce2013-11-20 14:54:39 +0000234void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
235 unsigned ExtraSpaces) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000236 FormatToken &Current = *State.NextToken;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000237 const FormatToken &Previous = *State.NextToken->Previous;
238 if (Current.is(tok::equal) &&
239 (State.Line->First->is(tok::kw_for) || State.ParenLevel == 0) &&
240 State.Stack.back().VariablePos == 0) {
241 State.Stack.back().VariablePos = State.Column;
242 // Move over * and & if they are bound to the variable name.
243 const FormatToken *Tok = &Previous;
244 while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
245 State.Stack.back().VariablePos -= Tok->ColumnWidth;
246 if (Tok->SpacesRequiredBefore != 0)
247 break;
248 Tok = Tok->Previous;
249 }
250 if (Previous.PartOfMultiVariableDeclStmt)
251 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
252 }
253
254 unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
255
256 if (!DryRun)
257 Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, /*IndentLevel=*/0,
258 Spaces, State.Column + Spaces);
259
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000260 if (Current.Type == TT_ObjCSelectorName &&
261 !State.Stack.back().ObjCSelectorNameFound) {
262 if (Current.LongestObjCSelectorName == 0)
263 State.Stack.back().AlignColons = false;
264 else if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
265 State.Column + Spaces + Current.ColumnWidth)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000266 State.Stack.back().ColonPos =
267 State.Stack.back().Indent + Current.LongestObjCSelectorName;
268 else
269 State.Stack.back().ColonPos = State.Column + Spaces + Current.ColumnWidth;
270 }
271
272 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper5a611392013-12-19 21:41:37 +0000273 (Current.Type != TT_LineComment || Previous.BlockKind == BK_BracedInit))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000274 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasperec01cd62013-10-08 05:11:18 +0000275 if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000276 State.Stack.back().NoLineBreak = true;
277 if (startsSegmentOfBuilderTypeCall(Current))
278 State.Stack.back().ContainsUnwrappedBuilder = true;
279
280 State.Column += Spaces;
281 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
282 // Treat the condition inside an if as if it was a second function
Daniel Jasper6633ab82013-10-18 10:38:14 +0000283 // parameter, i.e. let nested calls have a continuation indent.
Alexander Kornienko1f803962013-10-01 14:41:18 +0000284 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000285 else if (Current.isNot(tok::comment) &&
286 (Previous.is(tok::comma) ||
287 (Previous.is(tok::colon) && Previous.Type == TT_ObjCMethodExpr)))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000288 State.Stack.back().LastSpace = State.Column;
289 else if ((Previous.Type == TT_BinaryOperator ||
290 Previous.Type == TT_ConditionalExpr ||
291 Previous.Type == TT_UnaryOperator ||
292 Previous.Type == TT_CtorInitializerColon) &&
293 (Previous.getPrecedence() != prec::Assignment ||
294 Current.StartsBinaryExpression))
295 // Always indent relative to the RHS of the expression unless this is a
296 // simple assignment without binary expression on the RHS. Also indent
297 // relative to unary operators and the colons of constructor initializers.
298 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf9a5e402013-10-08 16:24:07 +0000299 else if (Previous.Type == TT_InheritanceColon) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000300 State.Stack.back().Indent = State.Column;
Daniel Jasperf9a5e402013-10-08 16:24:07 +0000301 State.Stack.back().LastSpace = State.Column;
302 } else if (Previous.opensScope()) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000303 // If a function has a trailing call, indent all parameters from the
304 // opening parenthesis. This avoids confusing indents like:
305 // OuterFunction(InnerFunctionCall( // break
306 // ParameterToInnerFunction)) // break
307 // .SecondInnerFunctionCall();
308 bool HasTrailingCall = false;
309 if (Previous.MatchingParen) {
310 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
311 HasTrailingCall = Next && Next->isMemberAccess();
312 }
313 if (HasTrailingCall &&
314 State.Stack[State.Stack.size() - 2].CallContinuation == 0)
315 State.Stack.back().LastSpace = State.Column;
316 }
317}
318
319unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
320 bool DryRun) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000321 FormatToken &Current = *State.NextToken;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000322 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasper6633ab82013-10-18 10:38:14 +0000323 // If we are continuing an expression, we want to use the continuation indent.
Daniel Jasperde0328a2013-08-16 11:20:30 +0000324 unsigned ContinuationIndent =
Daniel Jasper6633ab82013-10-18 10:38:14 +0000325 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
326 Style.ContinuationIndentWidth;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000327 // Extra penalty that needs to be added because of the way certain line
328 // breaks are chosen.
329 unsigned Penalty = 0;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000330
Alexander Kornienko1f803962013-10-01 14:41:18 +0000331 const FormatToken *PreviousNonComment =
332 State.NextToken->getPreviousNonComment();
333 // The first line break on any ParenLevel causes an extra penalty in order
334 // prefer similar line breaks.
335 if (!State.Stack.back().ContainsLineBreak)
336 Penalty += 15;
337 State.Stack.back().ContainsLineBreak = true;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000338
Alexander Kornienko1f803962013-10-01 14:41:18 +0000339 Penalty += State.NextToken->SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000340
Alexander Kornienko1f803962013-10-01 14:41:18 +0000341 // Breaking before the first "<<" is generally not desirable if the LHS is
Daniel Jasper48437ce2013-11-20 14:54:39 +0000342 // short. Also always add the penalty if the LHS is split over mutliple lines
343 // to avoid unncessary line breaks that just work around this penalty.
344 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0 &&
Daniel Jasper004177e2013-12-19 16:06:40 +0000345 (State.Column <= Style.ColumnLimit / 3 ||
Daniel Jasper48437ce2013-11-20 14:54:39 +0000346 State.Stack.back().BreakBeforeParameter))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000347 Penalty += Style.PenaltyBreakFirstLessLess;
348
349 if (Current.is(tok::l_brace) && Current.BlockKind == BK_Block) {
Daniel Jaspere40caf92013-11-29 08:46:20 +0000350 State.Column =
351 State.ParenLevel == 0 ? State.FirstIndent : State.Stack.back().Indent;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000352 } else if (Current.isOneOf(tok::r_brace, tok::r_square)) {
Daniel Jasper6b6e7c32013-11-07 14:02:28 +0000353 if (Current.closesBlockTypeList(Style) ||
354 (Current.MatchingParen &&
355 Current.MatchingParen->BlockKind == BK_BracedInit))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000356 State.Column = State.Stack[State.Stack.size() - 2].LastSpace;
357 else
Daniel Jasper015ed022013-09-13 09:20:45 +0000358 State.Column = State.FirstIndent;
Daniel Jasper04b6a082013-12-20 06:22:01 +0000359 } else if (Current.isStringLiteral() && State.StartOfStringLiteral != 0) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000360 State.Column = State.StartOfStringLiteral;
361 State.Stack.back().BreakBeforeParameter = true;
362 } else if (Current.is(tok::lessless) &&
363 State.Stack.back().FirstLessLess != 0) {
364 State.Column = State.Stack.back().FirstLessLess;
365 } else if (Current.isMemberAccess()) {
366 if (State.Stack.back().CallContinuation == 0) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000367 State.Column = ContinuationIndent;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000368 State.Stack.back().CallContinuation = State.Column;
369 } else {
370 State.Column = State.Stack.back().CallContinuation;
371 }
Daniel Jasper165b29e2013-11-08 00:57:11 +0000372 } else if (State.Stack.back().QuestionColumn != 0 &&
373 (Current.Type == TT_ConditionalExpr ||
374 Previous.Type == TT_ConditionalExpr)) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000375 State.Column = State.Stack.back().QuestionColumn;
376 } else if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0) {
377 State.Column = State.Stack.back().VariablePos;
378 } else if ((PreviousNonComment &&
379 PreviousNonComment->ClosesTemplateDeclaration) ||
380 ((Current.Type == TT_StartOfName ||
381 Current.is(tok::kw_operator)) &&
382 State.ParenLevel == 0 &&
383 (!Style.IndentFunctionDeclarationAfterType ||
384 State.Line->StartsDefinition))) {
Daniel Jasper298c3402013-11-22 07:48:15 +0000385 State.Column =
386 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000387 } else if (Current.Type == TT_ObjCSelectorName) {
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000388 if (!State.Stack.back().ObjCSelectorNameFound) {
389 if (Current.LongestObjCSelectorName == 0) {
390 State.Column = State.Stack.back().Indent;
391 State.Stack.back().AlignColons = false;
392 } else {
393 State.Stack.back().ColonPos =
394 State.Stack.back().Indent + Current.LongestObjCSelectorName;
395 State.Column = State.Stack.back().ColonPos - Current.ColumnWidth;
396 }
397 } else if (!State.Stack.back().AlignColons) {
398 State.Column = State.Stack.back().Indent;
Daniel Jasperb302f9a2013-11-08 02:08:01 +0000399 } else if (State.Stack.back().ColonPos > Current.ColumnWidth) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000400 State.Column = State.Stack.back().ColonPos - Current.ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000401 } else {
402 State.Column = State.Stack.back().Indent;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000403 State.Stack.back().ColonPos = State.Column + Current.ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000404 }
Daniel Jasper1db6c382013-10-22 15:30:28 +0000405 } else if (Current.Type == TT_ArraySubscriptLSquare) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000406 if (State.Stack.back().StartOfArraySubscripts != 0)
407 State.Column = State.Stack.back().StartOfArraySubscripts;
408 else
409 State.Column = ContinuationIndent;
410 } else if (Current.Type == TT_StartOfName ||
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000411 Previous.isOneOf(tok::coloncolon, tok::equal)) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000412 State.Column = ContinuationIndent;
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000413 } else if (PreviousNonComment &&
414 PreviousNonComment->Type == TT_ObjCMethodExpr) {
415 State.Column = ContinuationIndent;
416 // FIXME: This is hacky, find a better way. The problem is that in an ObjC
417 // method expression, the block should be aligned to the line starting it,
418 // e.g.:
419 // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
420 // ^(int *i) {
421 // // ...
422 // }];
423 // Thus, we set LastSpace of the next higher ParenLevel, to which we move
424 // when we consume all of the "}"'s FakeRParens at the "{".
Daniel Jasper9a26e772013-12-23 11:25:40 +0000425 if (State.Stack.size() > 1)
426 State.Stack[State.Stack.size() - 2].LastSpace = ContinuationIndent;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000427 } else if (Current.Type == TT_CtorInitializerColon) {
428 State.Column = State.FirstIndent + Style.ConstructorInitializerIndentWidth;
429 } else if (Current.Type == TT_CtorInitializerComma) {
430 State.Column = State.Stack.back().Indent;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000431 } else {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000432 State.Column = State.Stack.back().Indent;
Daniel Jasper6633ab82013-10-18 10:38:14 +0000433 // Ensure that we fall back to the continuation indent width instead of just
Alexander Kornienko1f803962013-10-01 14:41:18 +0000434 // flushing continuations left.
Daniel Jasper16fc7542013-10-30 14:04:10 +0000435 if (State.Column == State.FirstIndent &&
436 PreviousNonComment->isNot(tok::r_brace))
Daniel Jasper6633ab82013-10-18 10:38:14 +0000437 State.Column += Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000438 }
439
Alexander Kornienko1f803962013-10-01 14:41:18 +0000440 if ((Previous.isOneOf(tok::comma, tok::semi) &&
441 !State.Stack.back().AvoidBinPacking) ||
442 Previous.Type == TT_BinaryOperator)
443 State.Stack.back().BreakBeforeParameter = false;
444 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
445 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000446 if (Current.is(tok::question) ||
447 (PreviousNonComment && PreviousNonComment->is(tok::question)))
448 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000449
450 if (!DryRun) {
451 unsigned Newlines = 1;
452 if (Current.is(tok::comment))
453 Newlines = std::max(Newlines, std::min(Current.NewlinesBefore,
454 Style.MaxEmptyLinesToKeep + 1));
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000455 Whitespaces.replaceWhitespace(Current, Newlines,
456 State.Stack.back().IndentLevel, State.Column,
457 State.Column, State.Line->InPPDirective);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000458 }
459
460 if (!Current.isTrailingComment())
461 State.Stack.back().LastSpace = State.Column;
462 if (Current.isMemberAccess())
463 State.Stack.back().LastSpace += Current.ColumnWidth;
464 State.StartOfLineLevel = State.ParenLevel;
465 State.LowestLevelOnLine = State.ParenLevel;
466
467 // Any break on this level means that the parent level has been broken
468 // and we need to avoid bin packing there.
469 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
470 State.Stack[i].BreakBeforeParameter = true;
471 }
Daniel Jasper9e5ede02013-11-08 19:56:28 +0000472 if (PreviousNonComment &&
473 !PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
474 PreviousNonComment->Type != TT_TemplateCloser &&
475 PreviousNonComment->Type != TT_BinaryOperator &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000476 Current.Type != TT_BinaryOperator &&
Daniel Jasper9e5ede02013-11-08 19:56:28 +0000477 !PreviousNonComment->opensScope())
Alexander Kornienko1f803962013-10-01 14:41:18 +0000478 State.Stack.back().BreakBeforeParameter = true;
479
Daniel Jasper1db6c382013-10-22 15:30:28 +0000480 // If we break after { or the [ of an array initializer, we should also break
481 // before the corresponding } or ].
482 if (Previous.is(tok::l_brace) || Previous.Type == TT_ArrayInitializerLSquare)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000483 State.Stack.back().BreakBeforeClosingBrace = true;
484
485 if (State.Stack.back().AvoidBinPacking) {
486 // If we are breaking after '(', '{', '<', this is not bin packing
487 // unless AllowAllParametersOfDeclarationOnNextLine is false.
488 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
489 Previous.Type == TT_BinaryOperator) ||
490 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
491 State.Line->MustBeDeclaration))
492 State.Stack.back().BreakBeforeParameter = true;
493 }
494
495 return Penalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000496}
497
498unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
499 bool DryRun, bool Newline) {
500 const FormatToken &Current = *State.NextToken;
501 assert(State.Stack.size());
502
503 if (Current.Type == TT_InheritanceColon)
504 State.Stack.back().AvoidBinPacking = true;
505 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
506 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000507 if (Current.Type == TT_ArraySubscriptLSquare &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000508 State.Stack.back().StartOfArraySubscripts == 0)
509 State.Stack.back().StartOfArraySubscripts = State.Column;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000510 if ((Current.is(tok::question) && Style.BreakBeforeTernaryOperators) ||
511 (Current.getPreviousNonComment() && Current.isNot(tok::colon) &&
512 Current.getPreviousNonComment()->is(tok::question) &&
513 !Style.BreakBeforeTernaryOperators))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000514 State.Stack.back().QuestionColumn = State.Column;
515 if (!Current.opensScope() && !Current.closesScope())
516 State.LowestLevelOnLine =
517 std::min(State.LowestLevelOnLine, State.ParenLevel);
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000518 if (Current.isMemberAccess())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000519 State.Stack.back().StartOfFunctionCall =
Alexander Kornienko39856b72013-09-10 09:38:25 +0000520 Current.LastInChainOfCalls ? 0 : State.Column + Current.ColumnWidth;
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000521 if (Current.Type == TT_ObjCSelectorName)
522 State.Stack.back().ObjCSelectorNameFound = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000523 if (Current.Type == TT_CtorInitializerColon) {
524 // Indent 2 from the column, so:
525 // SomeClass::SomeClass()
526 // : First(...), ...
527 // Next(...)
528 // ^ line up here.
529 State.Stack.back().Indent =
530 State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
531 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
532 State.Stack.back().AvoidBinPacking = true;
533 State.Stack.back().BreakBeforeParameter = false;
534 }
535
Daniel Jasperde0328a2013-08-16 11:20:30 +0000536 // In ObjC method declaration we align on the ":" of parameters, but we need
Daniel Jasper6633ab82013-10-18 10:38:14 +0000537 // to ensure that we indent parameters on subsequent lines by at least our
538 // continuation indent width.
Daniel Jasperde0328a2013-08-16 11:20:30 +0000539 if (Current.Type == TT_ObjCMethodSpecifier)
Daniel Jasper6633ab82013-10-18 10:38:14 +0000540 State.Stack.back().Indent += Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000541
542 // Insert scopes created by fake parenthesis.
543 const FormatToken *Previous = Current.getPreviousNonComment();
544 // Don't add extra indentation for the first fake parenthesis after
545 // 'return', assignements or opening <({[. The indentation for these cases
546 // is special cased.
547 bool SkipFirstExtraIndent =
Daniel Jaspereabede62013-09-30 08:29:03 +0000548 (Previous && (Previous->opensScope() || Previous->is(tok::kw_return) ||
Daniel Jasperf48b5ab2013-11-07 19:23:49 +0000549 Previous->getPrecedence() == prec::Assignment ||
550 Previous->Type == TT_ObjCMethodExpr));
Daniel Jasperde0328a2013-08-16 11:20:30 +0000551 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
552 I = Current.FakeLParens.rbegin(),
553 E = Current.FakeLParens.rend();
554 I != E; ++I) {
555 ParenState NewParenState = State.Stack.back();
556 NewParenState.ContainsLineBreak = false;
Daniel Jaspereabede62013-09-30 08:29:03 +0000557
558 // Indent from 'LastSpace' unless this the fake parentheses encapsulating a
559 // builder type call after 'return'. If such a call is line-wrapped, we
560 // commonly just want to indent from the start of the line.
561 if (!Previous || Previous->isNot(tok::kw_return) || *I > 0)
562 NewParenState.Indent =
563 std::max(std::max(State.Column, NewParenState.Indent),
564 State.Stack.back().LastSpace);
565
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000566 // Do not indent relative to the fake parentheses inserted for "." or "->".
567 // This is a special case to make the following to statements consistent:
568 // OuterFunction(InnerFunctionCall( // break
569 // ParameterToInnerFunction));
570 // OuterFunction(SomeObject.InnerFunctionCall( // break
571 // ParameterToInnerFunction));
572 if (*I > prec::Unknown)
573 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
Daniel Jasper96964352013-12-18 10:44:36 +0000574 NewParenState.StartOfFunctionCall = State.Column;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000575
576 // Always indent conditional expressions. Never indent expression where
577 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
578 // prec::Assignment) as those have different indentation rules. Indent
579 // other expression, unless the indentation needs to be skipped.
580 if (*I == prec::Conditional ||
581 (!SkipFirstExtraIndent && *I > prec::Assignment &&
582 !Style.BreakBeforeBinaryOperators))
Daniel Jasper6633ab82013-10-18 10:38:14 +0000583 NewParenState.Indent += Style.ContinuationIndentWidth;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000584 if ((Previous && !Previous->opensScope()) || *I > prec::Comma)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000585 NewParenState.BreakBeforeParameter = false;
586 State.Stack.push_back(NewParenState);
587 SkipFirstExtraIndent = false;
588 }
589
590 // If we encounter an opening (, [, { or <, we add a level to our stacks to
591 // prepare for the following tokens.
592 if (Current.opensScope()) {
593 unsigned NewIndent;
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000594 unsigned NewIndentLevel = State.Stack.back().IndentLevel;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000595 bool AvoidBinPacking;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000596 bool BreakBeforeParameter = false;
597 if (Current.is(tok::l_brace) ||
598 Current.Type == TT_ArrayInitializerLSquare) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000599 if (Current.MatchingParen && Current.BlockKind == BK_Block) {
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000600 // If this is an l_brace starting a nested block, we pretend (wrt. to
601 // indentation) that we already consumed the corresponding r_brace.
Daniel Jasper96964352013-12-18 10:44:36 +0000602 // Thus, we remove all ParenStates caused by fake parentheses that end
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000603 // at the r_brace. The net effect of this is that we don't indent
604 // relative to the l_brace, if the nested block is the last parameter of
605 // a function. For example, this formats:
606 //
607 // SomeFunction(a, [] {
608 // f(); // break
609 // });
610 //
611 // instead of:
612 // SomeFunction(a, [] {
Daniel Jasper5500f612013-11-25 11:08:59 +0000613 // f(); // break
614 // });
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000615 for (unsigned i = 0; i != Current.MatchingParen->FakeRParens; ++i)
616 State.Stack.pop_back();
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000617 bool IsObjCBlock =
618 Previous &&
619 (Previous->is(tok::caret) ||
620 (Previous->is(tok::r_paren) && Previous->MatchingParen &&
621 Previous->MatchingParen->Previous &&
622 Previous->MatchingParen->Previous->is(tok::caret)));
623 // For some reason, ObjC blocks are indented like continuations.
624 NewIndent =
625 State.Stack.back().LastSpace +
626 (IsObjCBlock ? Style.ContinuationIndentWidth : Style.IndentWidth);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000627 ++NewIndentLevel;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000628 BreakBeforeParameter = true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000629 } else {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000630 NewIndent = State.Stack.back().LastSpace;
Daniel Jasperb8f61682013-10-22 15:45:58 +0000631 if (Current.opensBlockTypeList(Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000632 NewIndent += Style.IndentWidth;
Daniel Jasper5a611392013-12-19 21:41:37 +0000633 NewIndent = std::min(State.Column + 2, NewIndent);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000634 ++NewIndentLevel;
Daniel Jasperb8f61682013-10-22 15:45:58 +0000635 } else {
636 NewIndent += Style.ContinuationIndentWidth;
Daniel Jasper5a611392013-12-19 21:41:37 +0000637 NewIndent = std::min(State.Column + 1, NewIndent);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000638 }
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000639 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000640 const FormatToken *NextNoComment = Current.getNextNonComment();
Daniel Jasper015ed022013-09-13 09:20:45 +0000641 AvoidBinPacking = Current.BlockKind == BK_Block ||
Daniel Jasper1db6c382013-10-22 15:30:28 +0000642 Current.Type == TT_ArrayInitializerLSquare ||
Daniel Jasperb596fb22013-10-24 10:31:50 +0000643 Current.Type == TT_DictLiteral ||
Daniel Jasper015ed022013-09-13 09:20:45 +0000644 (NextNoComment &&
645 NextNoComment->Type == TT_DesignatedInitializerPeriod);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000646 } else {
Daniel Jasper6633ab82013-10-18 10:38:14 +0000647 NewIndent = Style.ContinuationIndentWidth +
648 std::max(State.Stack.back().LastSpace,
649 State.Stack.back().StartOfFunctionCall);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000650 AvoidBinPacking = !Style.BinPackParameters ||
651 (Style.ExperimentalAutoDetectBinPacking &&
652 (Current.PackingKind == PPK_OnePerLine ||
653 (!BinPackInconclusiveFunctions &&
654 Current.PackingKind == PPK_Inconclusive)));
Daniel Jasper1db6c382013-10-22 15:30:28 +0000655 // If this '[' opens an ObjC call, determine whether all parameters fit
656 // into one line and put one per line if they don't.
657 if (Current.Type == TT_ObjCMethodExpr &&
658 getLengthToMatchingParen(Current) + State.Column >
659 getColumnLimit(State))
660 BreakBeforeParameter = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000661 }
662
Daniel Jaspercc3114d2013-10-18 15:23:06 +0000663 bool NoLineBreak = State.Stack.back().NoLineBreak ||
664 (Current.Type == TT_TemplateOpener &&
665 State.Stack.back().ContainsUnwrappedBuilder);
666 State.Stack.push_back(ParenState(NewIndent, NewIndentLevel,
667 State.Stack.back().LastSpace,
668 AvoidBinPacking, NoLineBreak));
Daniel Jasper1db6c382013-10-22 15:30:28 +0000669 State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000670 ++State.ParenLevel;
671 }
672
Daniel Jasperde0328a2013-08-16 11:20:30 +0000673 // If we encounter a closing ), ], } or >, we can remove a level from our
674 // stacks.
Daniel Jasper96df37a2013-08-28 09:17:37 +0000675 if (State.Stack.size() > 1 &&
676 (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000677 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
Daniel Jasper96df37a2013-08-28 09:17:37 +0000678 State.NextToken->Type == TT_TemplateCloser)) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000679 State.Stack.pop_back();
680 --State.ParenLevel;
681 }
682 if (Current.is(tok::r_square)) {
683 // If this ends the array subscript expr, reset the corresponding value.
684 const FormatToken *NextNonComment = Current.getNextNonComment();
685 if (NextNonComment && NextNonComment->isNot(tok::l_square))
686 State.Stack.back().StartOfArraySubscripts = 0;
687 }
688
689 // Remove scopes created by fake parenthesis.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000690 if (Current.isNot(tok::r_brace) ||
691 (Current.MatchingParen && Current.MatchingParen->BlockKind != BK_Block)) {
Daniel Jasperf3a5d002013-09-05 10:48:50 +0000692 // Don't remove FakeRParens attached to r_braces that surround nested blocks
693 // as they will have been removed early (see above).
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000694 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
695 unsigned VariablePos = State.Stack.back().VariablePos;
696 State.Stack.pop_back();
697 State.Stack.back().VariablePos = VariablePos;
698 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000699 }
700
Daniel Jasper04b6a082013-12-20 06:22:01 +0000701 if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000702 State.StartOfStringLiteral = State.Column;
Daniel Jasper04b6a082013-12-20 06:22:01 +0000703 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
704 !Current.isStringLiteral()) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000705 State.StartOfStringLiteral = 0;
706 }
707
Alexander Kornienko39856b72013-09-10 09:38:25 +0000708 State.Column += Current.ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000709 State.NextToken = State.NextToken->Next;
Daniel Jasperb27c4b72013-08-27 11:09:05 +0000710 unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000711 if (State.Column > getColumnLimit(State)) {
712 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
713 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
714 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000715
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000716 // If the previous has a special role, let it consume tokens as appropriate.
717 // It is necessary to start at the previous token for the only implemented
718 // role (comma separated list). That way, the decision whether or not to break
719 // after the "{" is already done and both options are tried and evaluated.
720 // FIXME: This is ugly, find a better way.
721 if (Previous && Previous->Role)
722 Penalty += Previous->Role->format(State, this, DryRun);
723
724 return Penalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000725}
726
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000727unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
728 LineState &State) {
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000729 // Break before further function parameters on all levels.
730 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
731 State.Stack[i].BreakBeforeParameter = true;
732
Alexander Kornienko39856b72013-09-10 09:38:25 +0000733 unsigned ColumnsUsed = State.Column;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000734 // We can only affect layout of the first and the last line, so the penalty
735 // for all other lines is constant, and we ignore it.
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000736 State.Column = Current.LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000737
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000738 if (ColumnsUsed > getColumnLimit(State))
739 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000740 return 0;
741}
742
Alexander Kornienko81e32942013-09-16 20:20:49 +0000743static bool getRawStringLiteralPrefixPostfix(StringRef Text,
744 StringRef &Prefix,
745 StringRef &Postfix) {
746 if (Text.startswith(Prefix = "R\"") || Text.startswith(Prefix = "uR\"") ||
747 Text.startswith(Prefix = "UR\"") || Text.startswith(Prefix = "u8R\"") ||
748 Text.startswith(Prefix = "LR\"")) {
749 size_t ParenPos = Text.find('(');
750 if (ParenPos != StringRef::npos) {
751 StringRef Delimiter =
752 Text.substr(Prefix.size(), ParenPos - Prefix.size());
753 Prefix = Text.substr(0, ParenPos + 1);
754 Postfix = Text.substr(Text.size() - 2 - Delimiter.size());
755 return Postfix.front() == ')' && Postfix.back() == '"' &&
756 Postfix.substr(1).startswith(Delimiter);
757 }
758 }
759 return false;
760}
761
Daniel Jasperde0328a2013-08-16 11:20:30 +0000762unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
763 LineState &State,
764 bool DryRun) {
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000765 // Don't break multi-line tokens other than block comments. Instead, just
766 // update the state.
767 if (Current.Type != TT_BlockComment && Current.IsMultiline)
768 return addMultilineToken(Current, State);
769
Daniel Jasper98857842013-10-30 13:54:53 +0000770 // Don't break implicit string literals.
771 if (Current.Type == TT_ImplicitStringLiteral)
772 return 0;
773
Daniel Jasper04b6a082013-12-20 06:22:01 +0000774 if (!Current.isStringLiteral() && !Current.is(tok::comment))
Daniel Jasperf93551c2013-08-23 10:05:49 +0000775 return 0;
776
Daniel Jasperde0328a2013-08-16 11:20:30 +0000777 llvm::OwningPtr<BreakableToken> Token;
Alexander Kornienko39856b72013-09-10 09:38:25 +0000778 unsigned StartColumn = State.Column - Current.ColumnWidth;
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000779 unsigned ColumnLimit = getColumnLimit(State);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000780
Daniel Jasper04b6a082013-12-20 06:22:01 +0000781 if (Current.isStringLiteral()) {
Alexander Kornienko384b40b2013-10-11 21:43:05 +0000782 // Don't break string literals inside preprocessor directives (except for
783 // #define directives, as their contents are stored in separate lines and
784 // are not affected by this check).
785 // This way we avoid breaking code with line directives and unknown
786 // preprocessor directives that contain long string literals.
787 if (State.Line->Type == LT_PreprocessorDirective)
788 return 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000789 // Exempts unterminated string literals from line breaking. The user will
790 // likely want to terminate the string before any line breaking is done.
791 if (Current.IsUnterminatedLiteral)
792 return 0;
793
Alexander Kornienko81e32942013-09-16 20:20:49 +0000794 StringRef Text = Current.TokenText;
795 StringRef Prefix;
796 StringRef Postfix;
797 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
798 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
799 // reduce the overhead) for each FormatToken, which is a string, so that we
800 // don't run multiple checks here on the hot path.
801 if ((Text.endswith(Postfix = "\"") &&
802 (Text.startswith(Prefix = "\"") || Text.startswith(Prefix = "u\"") ||
803 Text.startswith(Prefix = "U\"") || Text.startswith(Prefix = "u8\"") ||
804 Text.startswith(Prefix = "L\""))) ||
805 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")")) ||
806 getRawStringLiteralPrefixPostfix(Text, Prefix, Postfix)) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000807 Token.reset(new BreakableStringLiteral(
808 Current, State.Line->Level, StartColumn, Prefix, Postfix,
809 State.Line->InPPDirective, Encoding, Style));
Alexander Kornienko81e32942013-09-16 20:20:49 +0000810 } else {
811 return 0;
812 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000813 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000814 if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
815 return 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000816 Token.reset(new BreakableBlockComment(
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000817 Current, State.Line->Level, StartColumn, Current.OriginalColumn,
818 !Current.Previous, State.Line->InPPDirective, Encoding, Style));
Daniel Jasperde0328a2013-08-16 11:20:30 +0000819 } else if (Current.Type == TT_LineComment &&
820 (Current.Previous == NULL ||
821 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000822 if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
823 return 0;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000824 Token.reset(new BreakableLineComment(Current, State.Line->Level,
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000825 StartColumn, /*InPPDirective=*/false,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000826 Encoding, Style));
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000827 // We don't insert backslashes when breaking line comments.
828 ColumnLimit = Style.ColumnLimit;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000829 } else {
830 return 0;
831 }
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000832 if (Current.UnbreakableTailLength >= ColumnLimit)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000833 return 0;
834
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000835 unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000836 bool BreakInserted = false;
837 unsigned Penalty = 0;
838 unsigned RemainingTokenColumns = 0;
839 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
840 LineIndex != EndIndex; ++LineIndex) {
841 if (!DryRun)
842 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
843 unsigned TailOffset = 0;
844 RemainingTokenColumns =
845 Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
846 while (RemainingTokenColumns > RemainingSpace) {
847 BreakableToken::Split Split =
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000848 Token->getSplit(LineIndex, TailOffset, ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000849 if (Split.first == StringRef::npos) {
850 // The last line's penalty is handled in addNextStateToQueue().
851 if (LineIndex < EndIndex - 1)
852 Penalty += Style.PenaltyExcessCharacter *
853 (RemainingTokenColumns - RemainingSpace);
854 break;
855 }
856 assert(Split.first != 0);
857 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
858 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
Alexander Kornienko875395f2013-11-12 17:50:13 +0000859
860 // We can remove extra whitespace instead of breaking the line.
861 if (RemainingTokenColumns + 1 - Split.second <= RemainingSpace) {
862 RemainingTokenColumns = 0;
863 if (!DryRun)
864 Token->replaceWhitespace(LineIndex, TailOffset, Split, Whitespaces);
865 break;
866 }
867
Daniel Jasperde0328a2013-08-16 11:20:30 +0000868 assert(NewRemainingTokenColumns < RemainingTokenColumns);
869 if (!DryRun)
870 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Daniel Jasper2739af32013-08-28 10:03:58 +0000871 Penalty += Current.SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000872 unsigned ColumnsUsed =
873 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000874 if (ColumnsUsed > ColumnLimit) {
875 Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000876 }
877 TailOffset += Split.first + Split.second;
878 RemainingTokenColumns = NewRemainingTokenColumns;
879 BreakInserted = true;
880 }
881 }
882
883 State.Column = RemainingTokenColumns;
884
885 if (BreakInserted) {
886 // If we break the token inside a parameter list, we need to break before
887 // the next parameter on all levels, so that the next parameter is clearly
888 // visible. Line comments already introduce a break.
889 if (Current.Type != TT_LineComment) {
890 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
891 State.Stack[i].BreakBeforeParameter = true;
892 }
893
Daniel Jasper04b6a082013-12-20 06:22:01 +0000894 Penalty += Current.isStringLiteral() ? Style.PenaltyBreakString
895 : Style.PenaltyBreakComment;
Daniel Jasper2739af32013-08-28 10:03:58 +0000896
Daniel Jasperde0328a2013-08-16 11:20:30 +0000897 State.Stack.back().LastSpace = StartColumn;
898 }
899 return Penalty;
900}
901
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000902unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000903 // In preprocessor directives reserve two chars for trailing " \"
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000904 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000905}
906
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000907bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
Daniel Jasperf438cb72013-08-23 11:57:34 +0000908 const FormatToken &Current = *State.NextToken;
Daniel Jasper04b6a082013-12-20 06:22:01 +0000909 if (!Current.isStringLiteral())
Daniel Jasperf438cb72013-08-23 11:57:34 +0000910 return false;
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000911 // We never consider raw string literals "multiline" for the purpose of
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000912 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
913 // (see TokenAnnotator::mustBreakBefore().
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000914 if (Current.TokenText.startswith("R\""))
915 return false;
Alexander Kornienko39856b72013-09-10 09:38:25 +0000916 if (Current.IsMultiline)
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000917 return true;
Daniel Jasperf438cb72013-08-23 11:57:34 +0000918 if (Current.getNextNonComment() &&
Daniel Jasper04b6a082013-12-20 06:22:01 +0000919 Current.getNextNonComment()->isStringLiteral())
Daniel Jasperf438cb72013-08-23 11:57:34 +0000920 return true; // Implicit concatenation.
Alexander Kornienko39856b72013-09-10 09:38:25 +0000921 if (State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
Daniel Jasperf438cb72013-08-23 11:57:34 +0000922 Style.ColumnLimit)
923 return true; // String will be split.
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000924 return false;
Daniel Jasperf438cb72013-08-23 11:57:34 +0000925}
926
Daniel Jasperde0328a2013-08-16 11:20:30 +0000927} // namespace format
928} // namespace clang