blob: 5a3dee6387075aef44ceaf52f0465dcb52574502 [file] [log] [blame]
Daniel Jasper6b2afe42013-08-16 11:20:30 +00001//===--- ContinuationIndenter.cpp - Format C++ code -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements the continuation indenter.
12///
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "format-formatter"
16
17#include "BreakableToken.h"
18#include "ContinuationIndenter.h"
19#include "WhitespaceManager.h"
20#include "clang/Basic/OperatorPrecedence.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Format/Format.h"
23#include "llvm/Support/Debug.h"
24#include <string>
25
26namespace clang {
27namespace format {
28
29// Returns the length of everything up to the first possible line break after
30// the ), ], } or > matching \c Tok.
31static unsigned getLengthToMatchingParen(const FormatToken &Tok) {
32 if (Tok.MatchingParen == NULL)
33 return 0;
34 FormatToken *End = Tok.MatchingParen;
35 while (End->Next && !End->Next->CanBreakBefore) {
36 End = End->Next;
37 }
38 return End->TotalLength - Tok.TotalLength + 1;
39}
40
Daniel Jasperd3fef0f2013-08-27 14:24:43 +000041// Returns \c true if \c Tok is the "." or "->" of a call and starts the next
42// segment of a builder type call.
43static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) {
44 return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope();
45}
46
Daniel Jasper19ccb122013-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 Jasper6b2afe42013-08-16 11:20:30 +000059ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,
60 SourceManager &SourceMgr,
Daniel Jasper6b2afe42013-08-16 11:20:30 +000061 WhitespaceManager &Whitespaces,
62 encoding::Encoding Encoding,
63 bool BinPackInconclusiveFunctions)
Daniel Jasper567dcf92013-09-05 09:29:45 +000064 : Style(Style), SourceMgr(SourceMgr), Whitespaces(Whitespaces),
65 Encoding(Encoding),
Stephen Hines651f13c2014-04-23 16:59:28 -070066 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
67 CommentPragmasRegex(Style.CommentPragmas) {}
Daniel Jasper6b2afe42013-08-16 11:20:30 +000068
Daniel Jasper567dcf92013-09-05 09:29:45 +000069LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
Daniel Jasperb77d7412013-09-06 07:54:20 +000070 const AnnotatedLine *Line,
71 bool DryRun) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +000072 LineState State;
Daniel Jasper567dcf92013-09-05 09:29:45 +000073 State.FirstIndent = FirstIndent;
Daniel Jasper6b2afe42013-08-16 11:20:30 +000074 State.Column = FirstIndent;
Daniel Jasper567dcf92013-09-05 09:29:45 +000075 State.Line = Line;
76 State.NextToken = Line->First;
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +000077 State.Stack.push_back(ParenState(FirstIndent, Line->Level, FirstIndent,
Daniel Jasper6b2afe42013-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 Jasperb77d7412013-09-06 07:54:20 +000088 moveStateToNextToken(State, DryRun, /*Newline=*/false);
Daniel Jasper6b2afe42013-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 Jaspera07aa662013-10-22 15:30:28 +000096 if (!Current.CanBreakBefore && !(State.Stack.back().BreakBeforeClosingBrace &&
97 Current.closesBlockTypeList(Style)))
Daniel Jasper6b2afe42013-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 Jasper3c6aea72013-10-24 10:31:50 +0000102 Previous.Type != TT_DictLiteral &&
Daniel Jasper567dcf92013-09-05 09:29:45 +0000103 Previous.BlockKind == BK_BracedInit && Previous.Previous &&
Daniel Jasper6b2afe42013-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.
Stephen Hines651f13c2014-04-23 16:59:28 -0700111 if (Previous.opensScope() && Previous.isNot(tok::l_brace) &&
112 State.LowestLevelOnLine < State.StartOfLineLevel)
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000113 return false;
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000114 if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
115 return false;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000116 return !State.Stack.back().NoLineBreak;
117}
118
119bool ContinuationIndenter::mustBreak(const LineState &State) {
120 const FormatToken &Current = *State.NextToken;
121 const FormatToken &Previous = *Current.Previous;
122 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
123 return true;
Daniel Jaspera07aa662013-10-22 15:30:28 +0000124 if (State.Stack.back().BreakBeforeClosingBrace &&
125 Current.closesBlockTypeList(Style))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000126 return true;
127 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
128 return true;
Daniel Jasper19ccb122013-10-08 05:11:18 +0000129 if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
Daniel Jasper1a896a52013-11-08 00:57:11 +0000130 (Style.BreakBeforeTernaryOperators &&
131 (Current.is(tok::question) || (Current.Type == TT_ConditionalExpr &&
132 Previous.isNot(tok::question)))) ||
133 (!Style.BreakBeforeTernaryOperators &&
134 (Previous.is(tok::question) || Previous.Type == TT_ConditionalExpr))) &&
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000135 State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
136 !Current.isOneOf(tok::r_paren, tok::r_brace))
137 return true;
138 if (Style.AlwaysBreakBeforeMultilineStrings &&
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000139 State.Column > State.Stack.back().Indent && // Breaking saves columns.
Daniel Jaspera7856d02013-11-09 03:08:25 +0000140 !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) &&
Stephen Hines651f13c2014-04-23 16:59:28 -0700141 Previous.Type != TT_InlineASMColon && nextIsMultilineString(State))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000142 return true;
Daniel Jasper3c6aea72013-10-24 10:31:50 +0000143 if (((Previous.Type == TT_DictLiteral && Previous.is(tok::l_brace)) ||
Daniel Jaspera07aa662013-10-22 15:30:28 +0000144 Previous.Type == TT_ArrayInitializerLSquare) &&
Daniel Jaspera53bbae2013-10-20 16:45:46 +0000145 getLengthToMatchingParen(Previous) + State.Column > getColumnLimit(State))
146 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -0700147 if (Current.Type == TT_CtorInitializerColon &&
148 (!Style.AllowShortFunctionsOnASingleLine ||
149 Style.BreakConstructorInitializersBeforeComma || Style.ColumnLimit != 0))
150 return true;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000151
Stephen Hines651f13c2014-04-23 16:59:28 -0700152 if (State.Column < getNewLineColumn(State))
153 return false;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000154 if (!Style.BreakBeforeBinaryOperators) {
155 // If we need to break somewhere inside the LHS of a binary expression, we
156 // should also break after the operator. Otherwise, the formatting would
157 // hide the operator precedence, e.g. in:
158 // if (aaaaaaaaaaaaaa ==
159 // bbbbbbbbbbbbbb && c) {..
160 // For comparisons, we only apply this rule, if the LHS is a binary
161 // expression itself as otherwise, the line breaks seem superfluous.
162 // We need special cases for ">>" which we have split into two ">" while
163 // lexing in order to make template parsing easier.
164 //
165 // FIXME: We'll need something similar for styles that break before binary
166 // operators.
167 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
168 Previous.getPrecedence() == prec::Equality) &&
169 Previous.Previous &&
170 Previous.Previous->Type != TT_BinaryOperator; // For >>.
171 bool LHSIsBinaryExpr =
Daniel Jasperdb4813a2013-09-06 08:08:14 +0000172 Previous.Previous && Previous.Previous->EndsBinaryExpression;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000173 if (Previous.Type == TT_BinaryOperator &&
174 (!IsComparison || LHSIsBinaryExpr) &&
175 Current.Type != TT_BinaryOperator && // For >>.
176 !Current.isTrailingComment() &&
177 !Previous.isOneOf(tok::lessless, tok::question) &&
178 Previous.getPrecedence() != prec::Assignment &&
179 State.Stack.back().BreakBeforeParameter)
180 return true;
181 }
182
183 // Same as above, but for the first "<<" operator.
Stephen Hines651f13c2014-04-23 16:59:28 -0700184 if (Current.is(tok::lessless) && Current.Type != TT_OverloadedOperator &&
185 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000186 State.Stack.back().FirstLessLess == 0)
187 return true;
188
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000189 if (Current.Type == TT_ObjCSelectorName &&
Stephen Hines651f13c2014-04-23 16:59:28 -0700190 State.Stack.back().ObjCSelectorNameFound &&
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000191 State.Stack.back().BreakBeforeParameter)
192 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -0700193 if (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0 &&
194 !Current.isTrailingComment())
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000195 return true;
196
197 if ((Current.Type == TT_StartOfName || Current.is(tok::kw_operator)) &&
Daniel Jasper567dcf92013-09-05 09:29:45 +0000198 State.Line->MightBeFunctionDecl &&
199 State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000200 return true;
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000201 if (startsSegmentOfBuilderTypeCall(Current) &&
Daniel Jaspereb331832013-08-30 07:12:40 +0000202 (State.Stack.back().CallContinuation != 0 ||
203 (State.Stack.back().BreakBeforeParameter &&
204 State.Stack.back().ContainsUnwrappedBuilder)))
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000205 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -0700206
207 // The following could be precomputed as they do not depend on the state.
208 // However, as they should take effect only if the UnwrappedLine does not fit
209 // into the ColumnLimit, they are checked here in the ContinuationIndenter.
210 if (Previous.BlockKind == BK_Block && Previous.is(tok::l_brace) &&
211 !Current.isOneOf(tok::r_brace, tok::comment))
212 return true;
213
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000214 return false;
215}
216
217unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000218 bool DryRun,
219 unsigned ExtraSpaces) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000220 const FormatToken &Current = *State.NextToken;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000221
Stephen Hines651f13c2014-04-23 16:59:28 -0700222 assert(!State.Stack.empty());
223 if ((Current.Type == TT_ImplicitStringLiteral &&
Daniel Jasper84379572013-10-30 13:54:53 +0000224 (Current.Previous->Tok.getIdentifierInfo() == NULL ||
225 Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
226 tok::pp_not_keyword))) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000227 // FIXME: Is this correct?
228 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
229 State.NextToken->WhitespaceRange.getEnd()) -
230 SourceMgr.getSpellingColumnNumber(
231 State.NextToken->WhitespaceRange.getBegin());
Stephen Hines651f13c2014-04-23 16:59:28 -0700232 State.Column += WhitespaceLength;
233 moveStateToNextToken(State, DryRun, /*Newline=*/false);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000234 return 0;
235 }
236
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000237 unsigned Penalty = 0;
238 if (Newline)
239 Penalty = addTokenOnNewLine(State, DryRun);
240 else
241 addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
242
243 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
244}
245
246void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
247 unsigned ExtraSpaces) {
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000248 FormatToken &Current = *State.NextToken;
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000249 const FormatToken &Previous = *State.NextToken->Previous;
250 if (Current.is(tok::equal) &&
251 (State.Line->First->is(tok::kw_for) || State.ParenLevel == 0) &&
252 State.Stack.back().VariablePos == 0) {
253 State.Stack.back().VariablePos = State.Column;
254 // Move over * and & if they are bound to the variable name.
255 const FormatToken *Tok = &Previous;
256 while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
257 State.Stack.back().VariablePos -= Tok->ColumnWidth;
258 if (Tok->SpacesRequiredBefore != 0)
259 break;
260 Tok = Tok->Previous;
261 }
262 if (Previous.PartOfMultiVariableDeclStmt)
263 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
264 }
265
266 unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
267
268 if (!DryRun)
269 Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, /*IndentLevel=*/0,
270 Spaces, State.Column + Spaces);
271
Stephen Hines651f13c2014-04-23 16:59:28 -0700272 if (Current.Type == TT_ObjCSelectorName &&
273 !State.Stack.back().ObjCSelectorNameFound) {
274 if (Current.LongestObjCSelectorName == 0)
275 State.Stack.back().AlignColons = false;
276 else if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
277 State.Column + Spaces + Current.ColumnWidth)
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000278 State.Stack.back().ColonPos =
279 State.Stack.back().Indent + Current.LongestObjCSelectorName;
280 else
281 State.Stack.back().ColonPos = State.Column + Spaces + Current.ColumnWidth;
282 }
283
284 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Stephen Hines651f13c2014-04-23 16:59:28 -0700285 (Current.Type != TT_LineComment || Previous.BlockKind == BK_BracedInit))
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000286 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper19ccb122013-10-08 05:11:18 +0000287 if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000288 State.Stack.back().NoLineBreak = true;
289 if (startsSegmentOfBuilderTypeCall(Current))
290 State.Stack.back().ContainsUnwrappedBuilder = true;
291
292 State.Column += Spaces;
293 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
294 // Treat the condition inside an if as if it was a second function
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000295 // parameter, i.e. let nested calls have a continuation indent.
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000296 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Stephen Hines651f13c2014-04-23 16:59:28 -0700297 else if (Current.isNot(tok::comment) &&
298 (Previous.is(tok::comma) ||
299 (Previous.is(tok::colon) && Previous.Type == TT_ObjCMethodExpr)))
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000300 State.Stack.back().LastSpace = State.Column;
301 else if ((Previous.Type == TT_BinaryOperator ||
302 Previous.Type == TT_ConditionalExpr ||
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000303 Previous.Type == TT_CtorInitializerColon) &&
304 (Previous.getPrecedence() != prec::Assignment ||
305 Current.StartsBinaryExpression))
306 // Always indent relative to the RHS of the expression unless this is a
307 // simple assignment without binary expression on the RHS. Also indent
308 // relative to unary operators and the colons of constructor initializers.
309 State.Stack.back().LastSpace = State.Column;
Daniel Jaspercea014b2013-10-08 16:24:07 +0000310 else if (Previous.Type == TT_InheritanceColon) {
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000311 State.Stack.back().Indent = State.Column;
Daniel Jaspercea014b2013-10-08 16:24:07 +0000312 State.Stack.back().LastSpace = State.Column;
313 } else if (Previous.opensScope()) {
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000314 // If a function has a trailing call, indent all parameters from the
315 // opening parenthesis. This avoids confusing indents like:
316 // OuterFunction(InnerFunctionCall( // break
317 // ParameterToInnerFunction)) // break
318 // .SecondInnerFunctionCall();
319 bool HasTrailingCall = false;
320 if (Previous.MatchingParen) {
321 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
322 HasTrailingCall = Next && Next->isMemberAccess();
323 }
324 if (HasTrailingCall &&
325 State.Stack[State.Stack.size() - 2].CallContinuation == 0)
326 State.Stack.back().LastSpace = State.Column;
327 }
328}
329
330unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
331 bool DryRun) {
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000332 FormatToken &Current = *State.NextToken;
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000333 const FormatToken &Previous = *State.NextToken->Previous;
Stephen Hines651f13c2014-04-23 16:59:28 -0700334
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000335 // Extra penalty that needs to be added because of the way certain line
336 // breaks are chosen.
337 unsigned Penalty = 0;
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000338
Stephen Hines651f13c2014-04-23 16:59:28 -0700339 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
340 const FormatToken *NextNonComment = Previous.getNextNonComment();
341 if (!NextNonComment)
342 NextNonComment = &Current;
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000343 // The first line break on any ParenLevel causes an extra penalty in order
344 // prefer similar line breaks.
345 if (!State.Stack.back().ContainsLineBreak)
346 Penalty += 15;
347 State.Stack.back().ContainsLineBreak = true;
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000348
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000349 Penalty += State.NextToken->SplitPenalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000350
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000351 // Breaking before the first "<<" is generally not desirable if the LHS is
Stephen Hines651f13c2014-04-23 16:59:28 -0700352 // short. Also always add the penalty if the LHS is split over mutliple lines
353 // to avoid unnecessary line breaks that just work around this penalty.
354 if (NextNonComment->is(tok::lessless) &&
355 State.Stack.back().FirstLessLess == 0 &&
356 (State.Column <= Style.ColumnLimit / 3 ||
357 State.Stack.back().BreakBeforeParameter))
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000358 Penalty += Style.PenaltyBreakFirstLessLess;
359
Stephen Hines651f13c2014-04-23 16:59:28 -0700360 State.Column = getNewLineColumn(State);
361 if (NextNonComment->isMemberAccess()) {
362 if (State.Stack.back().CallContinuation == 0)
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000363 State.Stack.back().CallContinuation = State.Column;
Stephen Hines651f13c2014-04-23 16:59:28 -0700364 } else if (NextNonComment->Type == TT_ObjCSelectorName) {
365 if (!State.Stack.back().ObjCSelectorNameFound) {
366 if (NextNonComment->LongestObjCSelectorName == 0) {
367 State.Stack.back().AlignColons = false;
368 } else {
369 State.Stack.back().ColonPos =
370 State.Stack.back().Indent + NextNonComment->LongestObjCSelectorName;
371 }
372 } else if (State.Stack.back().AlignColons &&
373 State.Stack.back().ColonPos <= NextNonComment->ColumnWidth) {
374 State.Stack.back().ColonPos = State.Column + NextNonComment->ColumnWidth;
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000375 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700376 } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
377 (PreviousNonComment->Type == TT_ObjCMethodExpr ||
378 PreviousNonComment->Type == TT_DictLiteral)) {
379 // FIXME: This is hacky, find a better way. The problem is that in an ObjC
380 // method expression, the block should be aligned to the line starting it,
381 // e.g.:
382 // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
383 // ^(int *i) {
384 // // ...
385 // }];
386 // Thus, we set LastSpace of the next higher ParenLevel, to which we move
387 // when we consume all of the "}"'s FakeRParens at the "{".
388 if (State.Stack.size() > 1)
389 State.Stack[State.Stack.size() - 2].LastSpace =
390 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
391 Style.ContinuationIndentWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000392 }
393
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000394 if ((Previous.isOneOf(tok::comma, tok::semi) &&
395 !State.Stack.back().AvoidBinPacking) ||
396 Previous.Type == TT_BinaryOperator)
397 State.Stack.back().BreakBeforeParameter = false;
398 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
399 State.Stack.back().BreakBeforeParameter = false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700400 if (NextNonComment->is(tok::question) ||
Daniel Jasper1a896a52013-11-08 00:57:11 +0000401 (PreviousNonComment && PreviousNonComment->is(tok::question)))
402 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000403
404 if (!DryRun) {
405 unsigned Newlines = 1;
406 if (Current.is(tok::comment))
407 Newlines = std::max(Newlines, std::min(Current.NewlinesBefore,
408 Style.MaxEmptyLinesToKeep + 1));
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000409 Whitespaces.replaceWhitespace(Current, Newlines,
410 State.Stack.back().IndentLevel, State.Column,
411 State.Column, State.Line->InPPDirective);
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000412 }
413
414 if (!Current.isTrailingComment())
415 State.Stack.back().LastSpace = State.Column;
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000416 State.StartOfLineLevel = State.ParenLevel;
417 State.LowestLevelOnLine = State.ParenLevel;
418
419 // Any break on this level means that the parent level has been broken
420 // and we need to avoid bin packing there.
421 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
422 State.Stack[i].BreakBeforeParameter = true;
423 }
Daniel Jasper8b156e22013-11-08 19:56:28 +0000424 if (PreviousNonComment &&
425 !PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
426 PreviousNonComment->Type != TT_TemplateCloser &&
427 PreviousNonComment->Type != TT_BinaryOperator &&
Stephen Hines651f13c2014-04-23 16:59:28 -0700428 Current.Type != TT_BinaryOperator &&
Daniel Jasper8b156e22013-11-08 19:56:28 +0000429 !PreviousNonComment->opensScope())
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000430 State.Stack.back().BreakBeforeParameter = true;
431
Daniel Jaspera07aa662013-10-22 15:30:28 +0000432 // If we break after { or the [ of an array initializer, we should also break
433 // before the corresponding } or ].
434 if (Previous.is(tok::l_brace) || Previous.Type == TT_ArrayInitializerLSquare)
Alexander Kornienkoe5321c42013-10-01 14:41:18 +0000435 State.Stack.back().BreakBeforeClosingBrace = true;
436
437 if (State.Stack.back().AvoidBinPacking) {
438 // If we are breaking after '(', '{', '<', this is not bin packing
439 // unless AllowAllParametersOfDeclarationOnNextLine is false.
440 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
441 Previous.Type == TT_BinaryOperator) ||
442 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
443 State.Line->MustBeDeclaration))
444 State.Stack.back().BreakBeforeParameter = true;
445 }
446
447 return Penalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000448}
449
Stephen Hines651f13c2014-04-23 16:59:28 -0700450unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
451 if (!State.NextToken || !State.NextToken->Previous)
452 return 0;
453 FormatToken &Current = *State.NextToken;
454 const FormatToken &Previous = *State.NextToken->Previous;
455 // If we are continuing an expression, we want to use the continuation indent.
456 unsigned ContinuationIndent =
457 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
458 Style.ContinuationIndentWidth;
459 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
460 const FormatToken *NextNonComment = Previous.getNextNonComment();
461 if (!NextNonComment)
462 NextNonComment = &Current;
463 if (NextNonComment->is(tok::l_brace) &&
464 NextNonComment->BlockKind == BK_Block)
465 return State.ParenLevel == 0 ? State.FirstIndent
466 : State.Stack.back().Indent;
467 if (Current.isOneOf(tok::r_brace, tok::r_square)) {
468 if (Current.closesBlockTypeList(Style) ||
469 (Current.MatchingParen &&
470 Current.MatchingParen->BlockKind == BK_BracedInit))
471 return State.Stack[State.Stack.size() - 2].LastSpace;
472 else
473 return State.FirstIndent;
474 }
475 if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
476 return State.StartOfStringLiteral;
477 if (NextNonComment->is(tok::lessless) &&
478 State.Stack.back().FirstLessLess != 0)
479 return State.Stack.back().FirstLessLess;
480 if (NextNonComment->isMemberAccess()) {
481 if (State.Stack.back().CallContinuation == 0) {
482 return ContinuationIndent;
483 } else {
484 return State.Stack.back().CallContinuation;
485 }
486 }
487 if (State.Stack.back().QuestionColumn != 0 &&
488 (NextNonComment->Type == TT_ConditionalExpr ||
489 Previous.Type == TT_ConditionalExpr))
490 return State.Stack.back().QuestionColumn;
491 if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0)
492 return State.Stack.back().VariablePos;
493 if ((PreviousNonComment && (PreviousNonComment->ClosesTemplateDeclaration ||
494 PreviousNonComment->Type == TT_AttributeParen)) ||
495 ((NextNonComment->Type == TT_StartOfName ||
496 NextNonComment->is(tok::kw_operator)) &&
497 State.ParenLevel == 0 && (!Style.IndentFunctionDeclarationAfterType ||
498 State.Line->StartsDefinition)))
499 return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
500 if (NextNonComment->Type == TT_ObjCSelectorName) {
501 if (!State.Stack.back().ObjCSelectorNameFound) {
502 if (NextNonComment->LongestObjCSelectorName == 0) {
503 return State.Stack.back().Indent;
504 } else {
505 return State.Stack.back().Indent +
506 NextNonComment->LongestObjCSelectorName -
507 NextNonComment->ColumnWidth;
508 }
509 } else if (!State.Stack.back().AlignColons) {
510 return State.Stack.back().Indent;
511 } else if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth) {
512 return State.Stack.back().ColonPos - NextNonComment->ColumnWidth;
513 } else {
514 return State.Stack.back().Indent;
515 }
516 }
517 if (NextNonComment->Type == TT_ArraySubscriptLSquare) {
518 if (State.Stack.back().StartOfArraySubscripts != 0)
519 return State.Stack.back().StartOfArraySubscripts;
520 else
521 return ContinuationIndent;
522 }
523 if (NextNonComment->Type == TT_StartOfName ||
524 Previous.isOneOf(tok::coloncolon, tok::equal)) {
525 return ContinuationIndent;
526 }
527 if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
528 (PreviousNonComment->Type == TT_ObjCMethodExpr ||
529 PreviousNonComment->Type == TT_DictLiteral))
530 return ContinuationIndent;
531 if (NextNonComment->Type == TT_CtorInitializerColon)
532 return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
533 if (NextNonComment->Type == TT_CtorInitializerComma)
534 return State.Stack.back().Indent;
535 if (State.Stack.back().Indent == State.FirstIndent && PreviousNonComment &&
536 PreviousNonComment->isNot(tok::r_brace))
537 // Ensure that we fall back to the continuation indent width instead of
538 // just flushing continuations left.
539 return State.Stack.back().Indent + Style.ContinuationIndentWidth;
540 return State.Stack.back().Indent;
541}
542
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000543unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
544 bool DryRun, bool Newline) {
545 const FormatToken &Current = *State.NextToken;
546 assert(State.Stack.size());
547
548 if (Current.Type == TT_InheritanceColon)
549 State.Stack.back().AvoidBinPacking = true;
Stephen Hines651f13c2014-04-23 16:59:28 -0700550 if (Current.is(tok::lessless) && Current.Type != TT_OverloadedOperator &&
551 State.Stack.back().FirstLessLess == 0)
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000552 State.Stack.back().FirstLessLess = State.Column;
Daniel Jaspera07aa662013-10-22 15:30:28 +0000553 if (Current.Type == TT_ArraySubscriptLSquare &&
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000554 State.Stack.back().StartOfArraySubscripts == 0)
555 State.Stack.back().StartOfArraySubscripts = State.Column;
Daniel Jasper1a896a52013-11-08 00:57:11 +0000556 if ((Current.is(tok::question) && Style.BreakBeforeTernaryOperators) ||
557 (Current.getPreviousNonComment() && Current.isNot(tok::colon) &&
558 Current.getPreviousNonComment()->is(tok::question) &&
559 !Style.BreakBeforeTernaryOperators))
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000560 State.Stack.back().QuestionColumn = State.Column;
561 if (!Current.opensScope() && !Current.closesScope())
562 State.LowestLevelOnLine =
563 std::min(State.LowestLevelOnLine, State.ParenLevel);
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000564 if (Current.isMemberAccess())
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000565 State.Stack.back().StartOfFunctionCall =
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000566 Current.LastInChainOfCalls ? 0 : State.Column + Current.ColumnWidth;
Stephen Hines651f13c2014-04-23 16:59:28 -0700567 if (Current.Type == TT_ObjCSelectorName)
568 State.Stack.back().ObjCSelectorNameFound = true;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000569 if (Current.Type == TT_CtorInitializerColon) {
570 // Indent 2 from the column, so:
571 // SomeClass::SomeClass()
572 // : First(...), ...
573 // Next(...)
574 // ^ line up here.
575 State.Stack.back().Indent =
576 State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
577 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
578 State.Stack.back().AvoidBinPacking = true;
579 State.Stack.back().BreakBeforeParameter = false;
580 }
581
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000582 // In ObjC method declaration we align on the ":" of parameters, but we need
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000583 // to ensure that we indent parameters on subsequent lines by at least our
584 // continuation indent width.
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000585 if (Current.Type == TT_ObjCMethodSpecifier)
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000586 State.Stack.back().Indent += Style.ContinuationIndentWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000587
588 // Insert scopes created by fake parenthesis.
589 const FormatToken *Previous = Current.getPreviousNonComment();
590 // Don't add extra indentation for the first fake parenthesis after
591 // 'return', assignements or opening <({[. The indentation for these cases
592 // is special cased.
593 bool SkipFirstExtraIndent =
Daniel Jasperf78bf4a2013-09-30 08:29:03 +0000594 (Previous && (Previous->opensScope() || Previous->is(tok::kw_return) ||
Daniel Jasper966e6d32013-11-07 19:23:49 +0000595 Previous->getPrecedence() == prec::Assignment ||
596 Previous->Type == TT_ObjCMethodExpr));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000597 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
598 I = Current.FakeLParens.rbegin(),
599 E = Current.FakeLParens.rend();
600 I != E; ++I) {
601 ParenState NewParenState = State.Stack.back();
602 NewParenState.ContainsLineBreak = false;
Daniel Jasperf78bf4a2013-09-30 08:29:03 +0000603
604 // Indent from 'LastSpace' unless this the fake parentheses encapsulating a
605 // builder type call after 'return'. If such a call is line-wrapped, we
606 // commonly just want to indent from the start of the line.
607 if (!Previous || Previous->isNot(tok::kw_return) || *I > 0)
608 NewParenState.Indent =
609 std::max(std::max(State.Column, NewParenState.Indent),
610 State.Stack.back().LastSpace);
611
Stephen Hines651f13c2014-04-23 16:59:28 -0700612 // Don't allow the RHS of an operator to be split over multiple lines unless
613 // there is a line-break right after the operator.
614 // Exclude relational operators, as there, it is always more desirable to
615 // have the LHS 'left' of the RHS.
616 // FIXME: Implement this for '<<' and BreakBeforeBinaryOperators.
617 if (!Newline && Previous && Previous->Type == TT_BinaryOperator &&
618 !Previous->isOneOf(tok::lessless, tok::question, tok::colon) &&
619 Previous->getPrecedence() > prec::Assignment &&
620 Previous->getPrecedence() != prec::Relational &&
621 !Style.BreakBeforeBinaryOperators)
622 NewParenState.NoLineBreak = true;
623
Daniel Jasper567dcf92013-09-05 09:29:45 +0000624 // Do not indent relative to the fake parentheses inserted for "." or "->".
625 // This is a special case to make the following to statements consistent:
626 // OuterFunction(InnerFunctionCall( // break
627 // ParameterToInnerFunction));
628 // OuterFunction(SomeObject.InnerFunctionCall( // break
629 // ParameterToInnerFunction));
630 if (*I > prec::Unknown)
631 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
Stephen Hines651f13c2014-04-23 16:59:28 -0700632 NewParenState.StartOfFunctionCall = State.Column;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000633
634 // Always indent conditional expressions. Never indent expression where
635 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
636 // prec::Assignment) as those have different indentation rules. Indent
637 // other expression, unless the indentation needs to be skipped.
638 if (*I == prec::Conditional ||
639 (!SkipFirstExtraIndent && *I > prec::Assignment &&
640 !Style.BreakBeforeBinaryOperators))
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000641 NewParenState.Indent += Style.ContinuationIndentWidth;
Daniel Jaspera07aa662013-10-22 15:30:28 +0000642 if ((Previous && !Previous->opensScope()) || *I > prec::Comma)
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000643 NewParenState.BreakBeforeParameter = false;
644 State.Stack.push_back(NewParenState);
645 SkipFirstExtraIndent = false;
646 }
647
648 // If we encounter an opening (, [, { or <, we add a level to our stacks to
649 // prepare for the following tokens.
650 if (Current.opensScope()) {
651 unsigned NewIndent;
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000652 unsigned NewIndentLevel = State.Stack.back().IndentLevel;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000653 bool AvoidBinPacking;
Daniel Jaspera07aa662013-10-22 15:30:28 +0000654 bool BreakBeforeParameter = false;
655 if (Current.is(tok::l_brace) ||
656 Current.Type == TT_ArrayInitializerLSquare) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000657 if (Current.MatchingParen && Current.BlockKind == BK_Block) {
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000658 // If this is an l_brace starting a nested block, we pretend (wrt. to
659 // indentation) that we already consumed the corresponding r_brace.
Stephen Hines651f13c2014-04-23 16:59:28 -0700660 // Thus, we remove all ParenStates caused by fake parentheses that end
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000661 // at the r_brace. The net effect of this is that we don't indent
662 // relative to the l_brace, if the nested block is the last parameter of
663 // a function. For example, this formats:
664 //
665 // SomeFunction(a, [] {
666 // f(); // break
667 // });
668 //
669 // instead of:
670 // SomeFunction(a, [] {
Stephen Hines651f13c2014-04-23 16:59:28 -0700671 // f(); // break
672 // });
673 for (unsigned i = 0; i != Current.MatchingParen->FakeRParens; ++i) {
674 assert(State.Stack.size() > 1);
675 if (State.Stack.size() == 1) {
676 // Do not pop the last element.
677 break;
678 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000679 State.Stack.pop_back();
Stephen Hines651f13c2014-04-23 16:59:28 -0700680 }
681 // For some reason, ObjC blocks are indented like continuations.
682 NewIndent =
683 State.Stack.back().LastSpace + (Current.Type == TT_ObjCBlockLBrace
684 ? Style.ContinuationIndentWidth
685 : Style.IndentWidth);
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000686 ++NewIndentLevel;
Daniel Jaspera07aa662013-10-22 15:30:28 +0000687 BreakBeforeParameter = true;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000688 } else {
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000689 NewIndent = State.Stack.back().LastSpace;
Daniel Jasperc9689432013-10-22 15:45:58 +0000690 if (Current.opensBlockTypeList(Style)) {
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000691 NewIndent += Style.IndentWidth;
Stephen Hines651f13c2014-04-23 16:59:28 -0700692 NewIndent = std::min(State.Column + 2, NewIndent);
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000693 ++NewIndentLevel;
Daniel Jasperc9689432013-10-22 15:45:58 +0000694 } else {
695 NewIndent += Style.ContinuationIndentWidth;
Stephen Hines651f13c2014-04-23 16:59:28 -0700696 NewIndent = std::min(State.Column + 1, NewIndent);
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000697 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000698 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000699 const FormatToken *NextNoComment = Current.getNextNonComment();
Daniel Jasper57981202013-09-13 09:20:45 +0000700 AvoidBinPacking = Current.BlockKind == BK_Block ||
Daniel Jaspera07aa662013-10-22 15:30:28 +0000701 Current.Type == TT_ArrayInitializerLSquare ||
Daniel Jasper3c6aea72013-10-24 10:31:50 +0000702 Current.Type == TT_DictLiteral ||
Daniel Jasper57981202013-09-13 09:20:45 +0000703 (NextNoComment &&
704 NextNoComment->Type == TT_DesignatedInitializerPeriod);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000705 } else {
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000706 NewIndent = Style.ContinuationIndentWidth +
707 std::max(State.Stack.back().LastSpace,
708 State.Stack.back().StartOfFunctionCall);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000709 AvoidBinPacking = !Style.BinPackParameters ||
710 (Style.ExperimentalAutoDetectBinPacking &&
711 (Current.PackingKind == PPK_OnePerLine ||
712 (!BinPackInconclusiveFunctions &&
713 Current.PackingKind == PPK_Inconclusive)));
Daniel Jaspera07aa662013-10-22 15:30:28 +0000714 // If this '[' opens an ObjC call, determine whether all parameters fit
715 // into one line and put one per line if they don't.
716 if (Current.Type == TT_ObjCMethodExpr &&
717 getLengthToMatchingParen(Current) + State.Column >
718 getColumnLimit(State))
719 BreakBeforeParameter = true;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000720 }
721
Daniel Jasper9b3cb442013-10-18 15:23:06 +0000722 bool NoLineBreak = State.Stack.back().NoLineBreak ||
723 (Current.Type == TT_TemplateOpener &&
724 State.Stack.back().ContainsUnwrappedBuilder);
725 State.Stack.push_back(ParenState(NewIndent, NewIndentLevel,
726 State.Stack.back().LastSpace,
727 AvoidBinPacking, NoLineBreak));
Daniel Jaspera07aa662013-10-22 15:30:28 +0000728 State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000729 ++State.ParenLevel;
730 }
731
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000732 // If we encounter a closing ), ], } or >, we can remove a level from our
733 // stacks.
Daniel Jasper7143a212013-08-28 09:17:37 +0000734 if (State.Stack.size() > 1 &&
735 (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper567dcf92013-09-05 09:29:45 +0000736 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
Daniel Jasper7143a212013-08-28 09:17:37 +0000737 State.NextToken->Type == TT_TemplateCloser)) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000738 State.Stack.pop_back();
739 --State.ParenLevel;
740 }
741 if (Current.is(tok::r_square)) {
742 // If this ends the array subscript expr, reset the corresponding value.
743 const FormatToken *NextNonComment = Current.getNextNonComment();
744 if (NextNonComment && NextNonComment->isNot(tok::l_square))
745 State.Stack.back().StartOfArraySubscripts = 0;
746 }
747
748 // Remove scopes created by fake parenthesis.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000749 if (Current.isNot(tok::r_brace) ||
750 (Current.MatchingParen && Current.MatchingParen->BlockKind != BK_Block)) {
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000751 // Don't remove FakeRParens attached to r_braces that surround nested blocks
752 // as they will have been removed early (see above).
Daniel Jasper567dcf92013-09-05 09:29:45 +0000753 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
754 unsigned VariablePos = State.Stack.back().VariablePos;
Stephen Hines651f13c2014-04-23 16:59:28 -0700755 assert(State.Stack.size() > 1);
756 if (State.Stack.size() == 1) {
757 // Do not pop the last element.
758 break;
759 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000760 State.Stack.pop_back();
761 State.Stack.back().VariablePos = VariablePos;
762 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000763 }
764
Stephen Hines651f13c2014-04-23 16:59:28 -0700765 if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000766 State.StartOfStringLiteral = State.Column;
Stephen Hines651f13c2014-04-23 16:59:28 -0700767 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
768 !Current.isStringLiteral()) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000769 State.StartOfStringLiteral = 0;
770 }
771
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000772 State.Column += Current.ColumnWidth;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000773 State.NextToken = State.NextToken->Next;
Daniel Jasperd489f8c2013-08-27 11:09:05 +0000774 unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000775 if (State.Column > getColumnLimit(State)) {
776 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
777 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
778 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000779
Stephen Hines651f13c2014-04-23 16:59:28 -0700780 if (Current.Role)
781 Current.Role->formatFromToken(State, this, DryRun);
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000782 // If the previous has a special role, let it consume tokens as appropriate.
783 // It is necessary to start at the previous token for the only implemented
784 // role (comma separated list). That way, the decision whether or not to break
785 // after the "{" is already done and both options are tried and evaluated.
786 // FIXME: This is ugly, find a better way.
787 if (Previous && Previous->Role)
Stephen Hines651f13c2014-04-23 16:59:28 -0700788 Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000789
790 return Penalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000791}
792
Alexander Kornienko6f6154c2013-09-10 12:29:48 +0000793unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
794 LineState &State) {
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000795 // Break before further function parameters on all levels.
796 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
797 State.Stack[i].BreakBeforeParameter = true;
798
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000799 unsigned ColumnsUsed = State.Column;
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000800 // We can only affect layout of the first and the last line, so the penalty
801 // for all other lines is constant, and we ignore it.
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000802 State.Column = Current.LastLineColumnWidth;
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000803
Daniel Jasper567dcf92013-09-05 09:29:45 +0000804 if (ColumnsUsed > getColumnLimit(State))
805 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000806 return 0;
807}
808
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000809static bool getRawStringLiteralPrefixPostfix(StringRef Text,
810 StringRef &Prefix,
811 StringRef &Postfix) {
812 if (Text.startswith(Prefix = "R\"") || Text.startswith(Prefix = "uR\"") ||
813 Text.startswith(Prefix = "UR\"") || Text.startswith(Prefix = "u8R\"") ||
814 Text.startswith(Prefix = "LR\"")) {
815 size_t ParenPos = Text.find('(');
816 if (ParenPos != StringRef::npos) {
817 StringRef Delimiter =
818 Text.substr(Prefix.size(), ParenPos - Prefix.size());
819 Prefix = Text.substr(0, ParenPos + 1);
820 Postfix = Text.substr(Text.size() - 2 - Delimiter.size());
821 return Postfix.front() == ')' && Postfix.back() == '"' &&
822 Postfix.substr(1).startswith(Delimiter);
823 }
824 }
825 return false;
826}
827
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000828unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
829 LineState &State,
830 bool DryRun) {
Alexander Kornienko6f6154c2013-09-10 12:29:48 +0000831 // Don't break multi-line tokens other than block comments. Instead, just
832 // update the state.
833 if (Current.Type != TT_BlockComment && Current.IsMultiline)
834 return addMultilineToken(Current, State);
835
Daniel Jasper84379572013-10-30 13:54:53 +0000836 // Don't break implicit string literals.
837 if (Current.Type == TT_ImplicitStringLiteral)
838 return 0;
839
Stephen Hines651f13c2014-04-23 16:59:28 -0700840 if (!Current.isStringLiteral() && !Current.is(tok::comment))
Daniel Jaspered51c022013-08-23 10:05:49 +0000841 return 0;
842
Stephen Hines651f13c2014-04-23 16:59:28 -0700843 std::unique_ptr<BreakableToken> Token;
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000844 unsigned StartColumn = State.Column - Current.ColumnWidth;
Alexander Kornienko5486a422013-11-12 17:30:49 +0000845 unsigned ColumnLimit = getColumnLimit(State);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000846
Stephen Hines651f13c2014-04-23 16:59:28 -0700847 if (Current.isStringLiteral()) {
Alexander Kornienkob18c2582013-10-11 21:43:05 +0000848 // Don't break string literals inside preprocessor directives (except for
849 // #define directives, as their contents are stored in separate lines and
850 // are not affected by this check).
851 // This way we avoid breaking code with line directives and unknown
852 // preprocessor directives that contain long string literals.
853 if (State.Line->Type == LT_PreprocessorDirective)
854 return 0;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000855 // Exempts unterminated string literals from line breaking. The user will
856 // likely want to terminate the string before any line breaking is done.
857 if (Current.IsUnterminatedLiteral)
858 return 0;
859
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000860 StringRef Text = Current.TokenText;
861 StringRef Prefix;
862 StringRef Postfix;
Stephen Hines651f13c2014-04-23 16:59:28 -0700863 bool IsNSStringLiteral = false;
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000864 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
865 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
866 // reduce the overhead) for each FormatToken, which is a string, so that we
867 // don't run multiple checks here on the hot path.
Stephen Hines651f13c2014-04-23 16:59:28 -0700868 if (Text.startswith("\"") && Current.Previous &&
869 Current.Previous->is(tok::at)) {
870 IsNSStringLiteral = true;
871 Prefix = "@\"";
872 }
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000873 if ((Text.endswith(Postfix = "\"") &&
Stephen Hines651f13c2014-04-23 16:59:28 -0700874 (IsNSStringLiteral || Text.startswith(Prefix = "\"") ||
875 Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
876 Text.startswith(Prefix = "u8\"") ||
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000877 Text.startswith(Prefix = "L\""))) ||
878 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")")) ||
879 getRawStringLiteralPrefixPostfix(Text, Prefix, Postfix)) {
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000880 Token.reset(new BreakableStringLiteral(
881 Current, State.Line->Level, StartColumn, Prefix, Postfix,
882 State.Line->InPPDirective, Encoding, Style));
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000883 } else {
884 return 0;
885 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000886 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700887 if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
888 return 0;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000889 Token.reset(new BreakableBlockComment(
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000890 Current, State.Line->Level, StartColumn, Current.OriginalColumn,
891 !Current.Previous, State.Line->InPPDirective, Encoding, Style));
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000892 } else if (Current.Type == TT_LineComment &&
893 (Current.Previous == NULL ||
894 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700895 if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
896 return 0;
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000897 Token.reset(new BreakableLineComment(Current, State.Line->Level,
Alexander Kornienko5486a422013-11-12 17:30:49 +0000898 StartColumn, /*InPPDirective=*/false,
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000899 Encoding, Style));
Alexander Kornienko5486a422013-11-12 17:30:49 +0000900 // We don't insert backslashes when breaking line comments.
901 ColumnLimit = Style.ColumnLimit;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000902 } else {
903 return 0;
904 }
Alexander Kornienko5486a422013-11-12 17:30:49 +0000905 if (Current.UnbreakableTailLength >= ColumnLimit)
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000906 return 0;
907
Alexander Kornienko5486a422013-11-12 17:30:49 +0000908 unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000909 bool BreakInserted = false;
910 unsigned Penalty = 0;
911 unsigned RemainingTokenColumns = 0;
912 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
913 LineIndex != EndIndex; ++LineIndex) {
914 if (!DryRun)
915 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
916 unsigned TailOffset = 0;
917 RemainingTokenColumns =
918 Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
919 while (RemainingTokenColumns > RemainingSpace) {
920 BreakableToken::Split Split =
Alexander Kornienko5486a422013-11-12 17:30:49 +0000921 Token->getSplit(LineIndex, TailOffset, ColumnLimit);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000922 if (Split.first == StringRef::npos) {
923 // The last line's penalty is handled in addNextStateToQueue().
924 if (LineIndex < EndIndex - 1)
925 Penalty += Style.PenaltyExcessCharacter *
926 (RemainingTokenColumns - RemainingSpace);
927 break;
928 }
929 assert(Split.first != 0);
930 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
931 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
Alexander Kornienkoa7462b82013-11-12 17:50:13 +0000932
933 // We can remove extra whitespace instead of breaking the line.
934 if (RemainingTokenColumns + 1 - Split.second <= RemainingSpace) {
935 RemainingTokenColumns = 0;
936 if (!DryRun)
937 Token->replaceWhitespace(LineIndex, TailOffset, Split, Whitespaces);
938 break;
939 }
940
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000941 assert(NewRemainingTokenColumns < RemainingTokenColumns);
942 if (!DryRun)
943 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Daniel Jasperf5461782013-08-28 10:03:58 +0000944 Penalty += Current.SplitPenalty;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000945 unsigned ColumnsUsed =
946 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
Alexander Kornienko5486a422013-11-12 17:30:49 +0000947 if (ColumnsUsed > ColumnLimit) {
948 Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000949 }
950 TailOffset += Split.first + Split.second;
951 RemainingTokenColumns = NewRemainingTokenColumns;
952 BreakInserted = true;
953 }
954 }
955
956 State.Column = RemainingTokenColumns;
957
958 if (BreakInserted) {
959 // If we break the token inside a parameter list, we need to break before
960 // the next parameter on all levels, so that the next parameter is clearly
961 // visible. Line comments already introduce a break.
962 if (Current.Type != TT_LineComment) {
963 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
964 State.Stack[i].BreakBeforeParameter = true;
965 }
966
Stephen Hines651f13c2014-04-23 16:59:28 -0700967 Penalty += Current.isStringLiteral() ? Style.PenaltyBreakString
968 : Style.PenaltyBreakComment;
Daniel Jasperf5461782013-08-28 10:03:58 +0000969
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000970 State.Stack.back().LastSpace = StartColumn;
971 }
972 return Penalty;
973}
974
Daniel Jasper567dcf92013-09-05 09:29:45 +0000975unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000976 // In preprocessor directives reserve two chars for trailing " \"
Daniel Jasper567dcf92013-09-05 09:29:45 +0000977 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000978}
979
Stephen Hines651f13c2014-04-23 16:59:28 -0700980bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000981 const FormatToken &Current = *State.NextToken;
Stephen Hines651f13c2014-04-23 16:59:28 -0700982 if (!Current.isStringLiteral())
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000983 return false;
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000984 // We never consider raw string literals "multiline" for the purpose of
Stephen Hines651f13c2014-04-23 16:59:28 -0700985 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
986 // (see TokenAnnotator::mustBreakBefore().
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000987 if (Current.TokenText.startswith("R\""))
988 return false;
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000989 if (Current.IsMultiline)
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000990 return true;
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000991 if (Current.getNextNonComment() &&
Stephen Hines651f13c2014-04-23 16:59:28 -0700992 Current.getNextNonComment()->isStringLiteral())
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000993 return true; // Implicit concatenation.
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000994 if (State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000995 Style.ColumnLimit)
996 return true; // String will be split.
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000997 return false;
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000998}
999
Daniel Jasper6b2afe42013-08-16 11:20:30 +00001000} // namespace format
1001} // namespace clang