blob: 4c93c7f548ceeba99a4561281169f4ff97129011 [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
Daniel Jasperde0328a2013-08-16 11:20:30 +000015#include "BreakableToken.h"
16#include "ContinuationIndenter.h"
17#include "WhitespaceManager.h"
18#include "clang/Basic/OperatorPrecedence.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Format/Format.h"
21#include "llvm/Support/Debug.h"
22#include <string>
23
Chandler Carruth10346662014-04-22 03:17:02 +000024#define DEBUG_TYPE "format-formatter"
25
Daniel Jasperde0328a2013-08-16 11:20:30 +000026namespace 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) {
Craig Topper2145bc02014-05-09 08:15:10 +000032 if (!Tok.MatchingParen)
Daniel Jasperde0328a2013-08-16 11:20:30 +000033 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;
Daniel Jasperde0328a2013-08-16 11:20:30 +000081 State.StartOfStringLiteral = 0;
Daniel Jasper05cd5862014-05-08 12:21:30 +000082 State.StartOfLineLevel = 0;
83 State.LowestLevelOnLine = 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +000084 State.IgnoreStackForComparison = false;
85
86 // The first token has already been indented and thus consumed.
Daniel Jasper1c5d9df2013-09-06 07:54:20 +000087 moveStateToNextToken(State, DryRun, /*Newline=*/false);
Daniel Jasperde0328a2013-08-16 11:20:30 +000088 return State;
89}
90
91bool ContinuationIndenter::canBreak(const LineState &State) {
92 const FormatToken &Current = *State.NextToken;
93 const FormatToken &Previous = *Current.Previous;
94 assert(&Previous == Current.Previous);
Daniel Jasper1db6c382013-10-22 15:30:28 +000095 if (!Current.CanBreakBefore && !(State.Stack.back().BreakBeforeClosingBrace &&
96 Current.closesBlockTypeList(Style)))
Daniel Jasperde0328a2013-08-16 11:20:30 +000097 return false;
98 // The opening "{" of a braced list has to be on the same line as the first
99 // element if it is nested in another braced init list or function call.
100 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000101 Previous.Type != TT_DictLiteral && Previous.BlockKind == BK_BracedInit &&
102 Previous.Previous &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000103 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
104 return false;
105 // This prevents breaks like:
106 // ...
107 // SomeParameter, OtherParameter).DoSomething(
108 // ...
109 // As they hide "DoSomething" and are generally bad for readability.
Daniel Jasper8f59ae52014-03-11 11:03:26 +0000110 if (Previous.opensScope() && Previous.isNot(tok::l_brace) &&
Daniel Jasperfcfac102014-07-15 09:00:34 +0000111 State.LowestLevelOnLine < State.StartOfLineLevel &&
112 State.LowestLevelOnLine < Current.NestingLevel)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000113 return false;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000114 if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
115 return false;
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000116
117 // Don't create a 'hanging' indent if there are multiple blocks in a single
118 // statement.
119 if (Style.Language == FormatStyle::LK_JavaScript &&
120 Previous.is(tok::l_brace) && State.Stack.size() > 1 &&
121 State.Stack[State.Stack.size() - 2].JSFunctionInlined &&
122 State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks)
123 return false;
124
Daniel Jasperde0328a2013-08-16 11:20:30 +0000125 return !State.Stack.back().NoLineBreak;
126}
127
128bool ContinuationIndenter::mustBreak(const LineState &State) {
129 const FormatToken &Current = *State.NextToken;
130 const FormatToken &Previous = *Current.Previous;
131 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
132 return true;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000133 if (State.Stack.back().BreakBeforeClosingBrace &&
134 Current.closesBlockTypeList(Style))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000135 return true;
136 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
137 return true;
Daniel Jasperec01cd62013-10-08 05:11:18 +0000138 if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
Daniel Jasper165b29e2013-11-08 00:57:11 +0000139 (Style.BreakBeforeTernaryOperators &&
140 (Current.is(tok::question) || (Current.Type == TT_ConditionalExpr &&
141 Previous.isNot(tok::question)))) ||
142 (!Style.BreakBeforeTernaryOperators &&
143 (Previous.is(tok::question) || Previous.Type == TT_ConditionalExpr))) &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000144 State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
145 !Current.isOneOf(tok::r_paren, tok::r_brace))
146 return true;
147 if (Style.AlwaysBreakBeforeMultilineStrings &&
Daniel Jasperf438cb72013-08-23 11:57:34 +0000148 State.Column > State.Stack.back().Indent && // Breaking saves columns.
Daniel Jasper27943052013-11-09 03:08:25 +0000149 !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) &&
Daniel Jasper3251fff2014-06-10 06:27:23 +0000150 Previous.Type != TT_InlineASMColon &&
151 Previous.Type != TT_ConditionalExpr && nextIsMultilineString(State))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000152 return true;
Daniel Jaspera382cbe2014-07-28 14:08:09 +0000153 if (Style.Language != FormatStyle::LK_Proto &&
154 ((Previous.Type == TT_DictLiteral && Previous.is(tok::l_brace)) ||
Daniel Jasper1db6c382013-10-22 15:30:28 +0000155 Previous.Type == TT_ArrayInitializerLSquare) &&
Daniel Jasperdb8804b2014-04-14 12:11:07 +0000156 Style.ColumnLimit > 0 &&
Daniel Jasperd489dd32013-10-20 16:45:46 +0000157 getLengthToMatchingParen(Previous) + State.Column > getColumnLimit(State))
158 return true;
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000159 if (Current.Type == TT_CtorInitializerColon &&
Daniel Jasperd74cf402014-04-08 12:46:38 +0000160 ((Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All) ||
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000161 Style.BreakConstructorInitializersBeforeComma || Style.ColumnLimit != 0))
162 return true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000163
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000164 if (State.Column < getNewLineColumn(State))
165 return false;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000166 if (!Style.BreakBeforeBinaryOperators) {
167 // If we need to break somewhere inside the LHS of a binary expression, we
168 // should also break after the operator. Otherwise, the formatting would
169 // hide the operator precedence, e.g. in:
170 // if (aaaaaaaaaaaaaa ==
171 // bbbbbbbbbbbbbb && c) {..
172 // For comparisons, we only apply this rule, if the LHS is a binary
173 // expression itself as otherwise, the line breaks seem superfluous.
174 // We need special cases for ">>" which we have split into two ">" while
175 // lexing in order to make template parsing easier.
176 //
177 // FIXME: We'll need something similar for styles that break before binary
178 // operators.
179 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
180 Previous.getPrecedence() == prec::Equality) &&
181 Previous.Previous &&
182 Previous.Previous->Type != TT_BinaryOperator; // For >>.
183 bool LHSIsBinaryExpr =
Daniel Jasper562ecd42013-09-06 08:08:14 +0000184 Previous.Previous && Previous.Previous->EndsBinaryExpression;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000185 if (Previous.Type == TT_BinaryOperator &&
186 (!IsComparison || LHSIsBinaryExpr) &&
187 Current.Type != TT_BinaryOperator && // For >>.
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000188 !Current.isTrailingComment() && !Previous.is(tok::lessless) &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000189 Previous.getPrecedence() != prec::Assignment &&
190 State.Stack.back().BreakBeforeParameter)
191 return true;
192 }
193
194 // Same as above, but for the first "<<" operator.
Alexander Kornienko86b2dfd2014-03-06 15:13:08 +0000195 if (Current.is(tok::lessless) && Current.Type != TT_OverloadedOperator &&
196 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000197 State.Stack.back().FirstLessLess == 0)
198 return true;
199
Daniel Jasper17062ff2014-06-10 14:44:02 +0000200 if (Current.Type == TT_SelectorName &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000201 State.Stack.back().ObjCSelectorNameFound &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000202 State.Stack.back().BreakBeforeParameter)
203 return true;
Daniel Jasper05cd5862014-05-08 12:21:30 +0000204 if (Previous.ClosesTemplateDeclaration && Current.NestingLevel == 0 &&
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000205 !Current.isTrailingComment())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000206 return true;
207
Daniel Jasper4355e7f2014-07-09 07:50:33 +0000208 // If the return type spans multiple lines, wrap before the function name.
209 if ((Current.Type == TT_FunctionDeclarationName ||
210 Current.is(tok::kw_operator)) &&
211 State.Stack.back().BreakBeforeParameter)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000212 return true;
Daniel Jasper4355e7f2014-07-09 07:50:33 +0000213
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000214 if (startsSegmentOfBuilderTypeCall(Current) &&
Daniel Jasperf8151e92013-08-30 07:12:40 +0000215 (State.Stack.back().CallContinuation != 0 ||
216 (State.Stack.back().BreakBeforeParameter &&
217 State.Stack.back().ContainsUnwrappedBuilder)))
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000218 return true;
Daniel Jasper96972812014-01-05 12:38:10 +0000219
220 // The following could be precomputed as they do not depend on the state.
221 // However, as they should take effect only if the UnwrappedLine does not fit
222 // into the ColumnLimit, they are checked here in the ContinuationIndenter.
Daniel Jasper35995672014-04-29 14:05:20 +0000223 if (Style.ColumnLimit != 0 && Previous.BlockKind == BK_Block &&
224 Previous.is(tok::l_brace) && !Current.isOneOf(tok::r_brace, tok::comment))
Daniel Jasper96972812014-01-05 12:38:10 +0000225 return true;
Daniel Jasper96972812014-01-05 12:38:10 +0000226
Daniel Jasperde0328a2013-08-16 11:20:30 +0000227 return false;
228}
229
230unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000231 bool DryRun,
232 unsigned ExtraSpaces) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000233 const FormatToken &Current = *State.NextToken;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000234
Manuel Klimek819788d2014-03-18 11:22:45 +0000235 assert(!State.Stack.empty());
236 if ((Current.Type == TT_ImplicitStringLiteral &&
Craig Topper2145bc02014-05-09 08:15:10 +0000237 (Current.Previous->Tok.getIdentifierInfo() == nullptr ||
Daniel Jasper98857842013-10-30 13:54:53 +0000238 Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
239 tok::pp_not_keyword))) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000240 // FIXME: Is this correct?
241 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
242 State.NextToken->WhitespaceRange.getEnd()) -
243 SourceMgr.getSpellingColumnNumber(
244 State.NextToken->WhitespaceRange.getBegin());
Daniel Jasperda353cd2014-03-12 08:24:47 +0000245 State.Column += WhitespaceLength;
Daniel Jasper240dfda2014-03-31 14:23:49 +0000246 moveStateToNextToken(State, DryRun, /*Newline=*/false);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000247 return 0;
248 }
249
Alexander Kornienko1f803962013-10-01 14:41:18 +0000250 unsigned Penalty = 0;
251 if (Newline)
252 Penalty = addTokenOnNewLine(State, DryRun);
253 else
Daniel Jasper48437ce2013-11-20 14:54:39 +0000254 addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000255
256 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
257}
258
Daniel Jasper48437ce2013-11-20 14:54:39 +0000259void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
260 unsigned ExtraSpaces) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000261 FormatToken &Current = *State.NextToken;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000262 const FormatToken &Previous = *State.NextToken->Previous;
263 if (Current.is(tok::equal) &&
Daniel Jasper05cd5862014-05-08 12:21:30 +0000264 (State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) &&
Alexander Kornienko1f803962013-10-01 14:41:18 +0000265 State.Stack.back().VariablePos == 0) {
266 State.Stack.back().VariablePos = State.Column;
267 // Move over * and & if they are bound to the variable name.
268 const FormatToken *Tok = &Previous;
269 while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
270 State.Stack.back().VariablePos -= Tok->ColumnWidth;
271 if (Tok->SpacesRequiredBefore != 0)
272 break;
273 Tok = Tok->Previous;
274 }
275 if (Previous.PartOfMultiVariableDeclStmt)
276 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
277 }
278
279 unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
280
281 if (!DryRun)
282 Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, /*IndentLevel=*/0,
283 Spaces, State.Column + Spaces);
284
Daniel Jasper17062ff2014-06-10 14:44:02 +0000285 if (Current.Type == TT_SelectorName &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000286 !State.Stack.back().ObjCSelectorNameFound) {
287 if (Current.LongestObjCSelectorName == 0)
288 State.Stack.back().AlignColons = false;
289 else if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
290 State.Column + Spaces + Current.ColumnWidth)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000291 State.Stack.back().ColonPos =
292 State.Stack.back().Indent + Current.LongestObjCSelectorName;
293 else
294 State.Stack.back().ColonPos = State.Column + Spaces + Current.ColumnWidth;
295 }
296
297 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper5a611392013-12-19 21:41:37 +0000298 (Current.Type != TT_LineComment || Previous.BlockKind == BK_BracedInit))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000299 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasperec01cd62013-10-08 05:11:18 +0000300 if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000301 State.Stack.back().NoLineBreak = true;
302 if (startsSegmentOfBuilderTypeCall(Current))
303 State.Stack.back().ContainsUnwrappedBuilder = true;
304
Daniel Jasperd6f17d82014-09-12 16:35:28 +0000305 if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&
306 (Previous.MatchingParen &&
307 (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10))) {
308 // If there is a function call with long parameters, break before trailing
309 // calls. This prevents things like:
310 // EXPECT_CALL(SomeLongParameter).Times(
311 // 2);
312 // We don't want to do this for short parameters as they can just be
313 // indexes.
314 State.Stack.back().NoLineBreak = true;
315 }
316
Alexander Kornienko1f803962013-10-01 14:41:18 +0000317 State.Column += Spaces;
Daniel Jasper8acf8222014-05-07 09:23:05 +0000318 if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&
319 Previous.Previous && Previous.Previous->isOneOf(tok::kw_if, tok::kw_for))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000320 // Treat the condition inside an if as if it was a second function
Daniel Jasper6633ab82013-10-18 10:38:14 +0000321 // parameter, i.e. let nested calls have a continuation indent.
Daniel Jasper8acf8222014-05-07 09:23:05 +0000322 State.Stack.back().LastSpace = State.Column;
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000323 else if (!Current.isOneOf(tok::comment, tok::caret) &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000324 (Previous.is(tok::comma) ||
325 (Previous.is(tok::colon) && Previous.Type == TT_ObjCMethodExpr)))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000326 State.Stack.back().LastSpace = State.Column;
327 else if ((Previous.Type == TT_BinaryOperator ||
328 Previous.Type == TT_ConditionalExpr ||
Alexander Kornienko1f803962013-10-01 14:41:18 +0000329 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper0e617842014-04-16 12:26:54 +0000330 ((Previous.getPrecedence() != prec::Assignment &&
331 (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||
332 !Previous.LastOperator)) ||
Alexander Kornienko1f803962013-10-01 14:41:18 +0000333 Current.StartsBinaryExpression))
334 // Always indent relative to the RHS of the expression unless this is a
335 // simple assignment without binary expression on the RHS. Also indent
336 // relative to unary operators and the colons of constructor initializers.
337 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf9a5e402013-10-08 16:24:07 +0000338 else if (Previous.Type == TT_InheritanceColon) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000339 State.Stack.back().Indent = State.Column;
Daniel Jasperf9a5e402013-10-08 16:24:07 +0000340 State.Stack.back().LastSpace = State.Column;
341 } else if (Previous.opensScope()) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000342 // If a function has a trailing call, indent all parameters from the
343 // opening parenthesis. This avoids confusing indents like:
344 // OuterFunction(InnerFunctionCall( // break
345 // ParameterToInnerFunction)) // break
346 // .SecondInnerFunctionCall();
347 bool HasTrailingCall = false;
348 if (Previous.MatchingParen) {
349 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
350 HasTrailingCall = Next && Next->isMemberAccess();
351 }
352 if (HasTrailingCall &&
353 State.Stack[State.Stack.size() - 2].CallContinuation == 0)
354 State.Stack.back().LastSpace = State.Column;
355 }
356}
357
358unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
359 bool DryRun) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000360 FormatToken &Current = *State.NextToken;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000361 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000362
Alexander Kornienko1f803962013-10-01 14:41:18 +0000363 // Extra penalty that needs to be added because of the way certain line
364 // breaks are chosen.
365 unsigned Penalty = 0;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000366
Daniel Jaspera0407742014-02-11 10:08:11 +0000367 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
368 const FormatToken *NextNonComment = Previous.getNextNonComment();
369 if (!NextNonComment)
370 NextNonComment = &Current;
Daniel Jasper05cd5862014-05-08 12:21:30 +0000371 // The first line break on any NestingLevel causes an extra penalty in order
Alexander Kornienko1f803962013-10-01 14:41:18 +0000372 // prefer similar line breaks.
373 if (!State.Stack.back().ContainsLineBreak)
374 Penalty += 15;
375 State.Stack.back().ContainsLineBreak = true;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000376
Alexander Kornienko1f803962013-10-01 14:41:18 +0000377 Penalty += State.NextToken->SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000378
Alexander Kornienko1f803962013-10-01 14:41:18 +0000379 // Breaking before the first "<<" is generally not desirable if the LHS is
Daniel Jasper48437ce2013-11-20 14:54:39 +0000380 // short. Also always add the penalty if the LHS is split over mutliple lines
Daniel Jasper2b7556e2014-04-03 12:00:27 +0000381 // to avoid unnecessary line breaks that just work around this penalty.
Daniel Jaspera0407742014-02-11 10:08:11 +0000382 if (NextNonComment->is(tok::lessless) &&
383 State.Stack.back().FirstLessLess == 0 &&
Daniel Jasper004177e2013-12-19 16:06:40 +0000384 (State.Column <= Style.ColumnLimit / 3 ||
Daniel Jasper48437ce2013-11-20 14:54:39 +0000385 State.Stack.back().BreakBeforeParameter))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000386 Penalty += Style.PenaltyBreakFirstLessLess;
387
Daniel Jasper9f388d02014-03-27 14:33:30 +0000388 State.Column = getNewLineColumn(State);
389 if (NextNonComment->isMemberAccess()) {
390 if (State.Stack.back().CallContinuation == 0)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000391 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper17062ff2014-06-10 14:44:02 +0000392 } else if (NextNonComment->Type == TT_SelectorName) {
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000393 if (!State.Stack.back().ObjCSelectorNameFound) {
Daniel Jaspera0407742014-02-11 10:08:11 +0000394 if (NextNonComment->LongestObjCSelectorName == 0) {
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000395 State.Stack.back().AlignColons = false;
396 } else {
397 State.Stack.back().ColonPos =
Daniel Jaspera0407742014-02-11 10:08:11 +0000398 State.Stack.back().Indent + NextNonComment->LongestObjCSelectorName;
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000399 }
Daniel Jasper9f388d02014-03-27 14:33:30 +0000400 } else if (State.Stack.back().AlignColons &&
401 State.Stack.back().ColonPos <= NextNonComment->ColumnWidth) {
Daniel Jaspera0407742014-02-11 10:08:11 +0000402 State.Stack.back().ColonPos = State.Column + NextNonComment->ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000403 }
Daniel Jasper1fd6f1f2014-03-17 14:32:47 +0000404 } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
405 (PreviousNonComment->Type == TT_ObjCMethodExpr ||
406 PreviousNonComment->Type == TT_DictLiteral)) {
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000407 // FIXME: This is hacky, find a better way. The problem is that in an ObjC
408 // method expression, the block should be aligned to the line starting it,
409 // e.g.:
410 // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
411 // ^(int *i) {
412 // // ...
413 // }];
Daniel Jasper05cd5862014-05-08 12:21:30 +0000414 // Thus, we set LastSpace of the next higher NestingLevel, to which we move
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000415 // when we consume all of the "}"'s FakeRParens at the "{".
Daniel Jasper9a26e772013-12-23 11:25:40 +0000416 if (State.Stack.size() > 1)
Daniel Jasper9f388d02014-03-27 14:33:30 +0000417 State.Stack[State.Stack.size() - 2].LastSpace =
418 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
419 Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000420 }
421
Alexander Kornienko1f803962013-10-01 14:41:18 +0000422 if ((Previous.isOneOf(tok::comma, tok::semi) &&
423 !State.Stack.back().AvoidBinPacking) ||
424 Previous.Type == TT_BinaryOperator)
425 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper05cd5862014-05-08 12:21:30 +0000426 if (Previous.Type == TT_TemplateCloser && Current.NestingLevel == 0)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000427 State.Stack.back().BreakBeforeParameter = false;
Daniel Jaspera0407742014-02-11 10:08:11 +0000428 if (NextNonComment->is(tok::question) ||
Daniel Jasper165b29e2013-11-08 00:57:11 +0000429 (PreviousNonComment && PreviousNonComment->is(tok::question)))
430 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000431
432 if (!DryRun) {
Daniel Jaspera69ca9b2014-06-04 12:40:57 +0000433 unsigned Newlines = std::max(
434 1u, std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1));
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000435 Whitespaces.replaceWhitespace(Current, Newlines,
436 State.Stack.back().IndentLevel, State.Column,
437 State.Column, State.Line->InPPDirective);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000438 }
439
440 if (!Current.isTrailingComment())
441 State.Stack.back().LastSpace = State.Column;
Daniel Jasper05cd5862014-05-08 12:21:30 +0000442 State.StartOfLineLevel = Current.NestingLevel;
443 State.LowestLevelOnLine = Current.NestingLevel;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000444
445 // Any break on this level means that the parent level has been broken
446 // and we need to avoid bin packing there.
Daniel Jasperb16b9692014-05-21 12:51:23 +0000447 bool JavaScriptFormat = Style.Language == FormatStyle::LK_JavaScript &&
448 Current.is(tok::r_brace) &&
449 State.Stack.size() > 1 &&
450 State.Stack[State.Stack.size() - 2].JSFunctionInlined;
451 if (!JavaScriptFormat) {
452 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
453 State.Stack[i].BreakBeforeParameter = true;
454 }
Alexander Kornienko1f803962013-10-01 14:41:18 +0000455 }
Daniel Jasperb16b9692014-05-21 12:51:23 +0000456
Daniel Jasper9e5ede02013-11-08 19:56:28 +0000457 if (PreviousNonComment &&
458 !PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
459 PreviousNonComment->Type != TT_TemplateCloser &&
460 PreviousNonComment->Type != TT_BinaryOperator &&
Daniel Jasperfab69ff2014-10-21 08:24:18 +0000461 PreviousNonComment->Type != TT_JavaAnnotation &&
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000462 Current.Type != TT_BinaryOperator && !PreviousNonComment->opensScope())
Alexander Kornienko1f803962013-10-01 14:41:18 +0000463 State.Stack.back().BreakBeforeParameter = true;
464
Daniel Jasper1db6c382013-10-22 15:30:28 +0000465 // If we break after { or the [ of an array initializer, we should also break
466 // before the corresponding } or ].
Daniel Jasper90818052014-06-10 10:42:26 +0000467 if (PreviousNonComment &&
468 (PreviousNonComment->is(tok::l_brace) ||
469 PreviousNonComment->Type == TT_ArrayInitializerLSquare))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000470 State.Stack.back().BreakBeforeClosingBrace = true;
471
472 if (State.Stack.back().AvoidBinPacking) {
473 // If we are breaking after '(', '{', '<', this is not bin packing
Daniel Jasper2a958322014-05-21 13:26:58 +0000474 // unless AllowAllParametersOfDeclarationOnNextLine is false or this is a
475 // dict/object literal.
Alexander Kornienko1f803962013-10-01 14:41:18 +0000476 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
477 Previous.Type == TT_BinaryOperator) ||
478 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
Daniel Jasper2a958322014-05-21 13:26:58 +0000479 State.Line->MustBeDeclaration) ||
480 Previous.Type == TT_DictLiteral)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000481 State.Stack.back().BreakBeforeParameter = true;
482 }
483
484 return Penalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000485}
486
Daniel Jasper9f388d02014-03-27 14:33:30 +0000487unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000488 if (!State.NextToken || !State.NextToken->Previous)
489 return 0;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000490 FormatToken &Current = *State.NextToken;
Daniel Jasper4281c5a2014-10-07 14:45:34 +0000491 const FormatToken &Previous = *Current.Previous;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000492 // If we are continuing an expression, we want to use the continuation indent.
493 unsigned ContinuationIndent =
494 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
495 Style.ContinuationIndentWidth;
496 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
497 const FormatToken *NextNonComment = Previous.getNextNonComment();
498 if (!NextNonComment)
499 NextNonComment = &Current;
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000500 if (NextNonComment->is(tok::l_brace) && NextNonComment->BlockKind == BK_Block)
Daniel Jasper05cd5862014-05-08 12:21:30 +0000501 return Current.NestingLevel == 0 ? State.FirstIndent
502 : State.Stack.back().Indent;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000503 if (Current.isOneOf(tok::r_brace, tok::r_square)) {
Daniel Jasperb16b9692014-05-21 12:51:23 +0000504 if (State.Stack.size() > 1 &&
505 State.Stack[State.Stack.size() - 2].JSFunctionInlined)
506 return State.FirstIndent;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000507 if (Current.closesBlockTypeList(Style) ||
508 (Current.MatchingParen &&
509 Current.MatchingParen->BlockKind == BK_BracedInit))
510 return State.Stack[State.Stack.size() - 2].LastSpace;
511 else
512 return State.FirstIndent;
513 }
Daniel Jasper783bac62014-04-15 09:54:30 +0000514 if (Current.is(tok::identifier) && Current.Next &&
515 Current.Next->Type == TT_DictLiteral)
516 return State.Stack.back().Indent;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000517 if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
518 return State.StartOfStringLiteral;
519 if (NextNonComment->is(tok::lessless) &&
520 State.Stack.back().FirstLessLess != 0)
521 return State.Stack.back().FirstLessLess;
522 if (NextNonComment->isMemberAccess()) {
523 if (State.Stack.back().CallContinuation == 0) {
524 return ContinuationIndent;
525 } else {
526 return State.Stack.back().CallContinuation;
527 }
528 }
529 if (State.Stack.back().QuestionColumn != 0 &&
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000530 ((NextNonComment->is(tok::colon) &&
531 NextNonComment->Type == TT_ConditionalExpr) ||
Daniel Jasper9f388d02014-03-27 14:33:30 +0000532 Previous.Type == TT_ConditionalExpr))
533 return State.Stack.back().QuestionColumn;
534 if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0)
535 return State.Stack.back().VariablePos;
536 if ((PreviousNonComment && (PreviousNonComment->ClosesTemplateDeclaration ||
Daniel Jasperfab69ff2014-10-21 08:24:18 +0000537 PreviousNonComment->Type == TT_AttributeParen ||
538 PreviousNonComment->Type == TT_JavaAnnotation)) ||
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000539 (!Style.IndentWrappedFunctionNames &&
540 (NextNonComment->is(tok::kw_operator) ||
541 NextNonComment->Type == TT_FunctionDeclarationName)))
Daniel Jasper9f388d02014-03-27 14:33:30 +0000542 return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
Daniel Jasper17062ff2014-06-10 14:44:02 +0000543 if (NextNonComment->Type == TT_SelectorName) {
Daniel Jasper9f388d02014-03-27 14:33:30 +0000544 if (!State.Stack.back().ObjCSelectorNameFound) {
545 if (NextNonComment->LongestObjCSelectorName == 0) {
546 return State.Stack.back().Indent;
547 } else {
548 return State.Stack.back().Indent +
549 NextNonComment->LongestObjCSelectorName -
550 NextNonComment->ColumnWidth;
551 }
552 } else if (!State.Stack.back().AlignColons) {
553 return State.Stack.back().Indent;
554 } else if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth) {
555 return State.Stack.back().ColonPos - NextNonComment->ColumnWidth;
556 } else {
557 return State.Stack.back().Indent;
558 }
559 }
560 if (NextNonComment->Type == TT_ArraySubscriptLSquare) {
561 if (State.Stack.back().StartOfArraySubscripts != 0)
562 return State.Stack.back().StartOfArraySubscripts;
563 else
564 return ContinuationIndent;
565 }
566 if (NextNonComment->Type == TT_StartOfName ||
567 Previous.isOneOf(tok::coloncolon, tok::equal)) {
568 return ContinuationIndent;
569 }
570 if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
571 (PreviousNonComment->Type == TT_ObjCMethodExpr ||
572 PreviousNonComment->Type == TT_DictLiteral))
573 return ContinuationIndent;
574 if (NextNonComment->Type == TT_CtorInitializerColon)
575 return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
576 if (NextNonComment->Type == TT_CtorInitializerComma)
577 return State.Stack.back().Indent;
Daniel Jasper316ab382014-08-06 13:14:58 +0000578 if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() &&
579 Current.isNot(tok::colon))
580 return ContinuationIndent;
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000581 if (State.Stack.back().Indent == State.FirstIndent && PreviousNonComment &&
Daniel Jasper9f388d02014-03-27 14:33:30 +0000582 PreviousNonComment->isNot(tok::r_brace))
583 // Ensure that we fall back to the continuation indent width instead of
584 // just flushing continuations left.
585 return State.Stack.back().Indent + Style.ContinuationIndentWidth;
586 return State.Stack.back().Indent;
587}
588
Daniel Jasperde0328a2013-08-16 11:20:30 +0000589unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
590 bool DryRun, bool Newline) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000591 assert(State.Stack.size());
Daniel Jasper60553be2014-05-26 13:10:39 +0000592 const FormatToken &Current = *State.NextToken;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000593
594 if (Current.Type == TT_InheritanceColon)
595 State.Stack.back().AvoidBinPacking = true;
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000596 if (Current.is(tok::lessless) && Current.Type != TT_OverloadedOperator) {
597 if (State.Stack.back().FirstLessLess == 0)
598 State.Stack.back().FirstLessLess = State.Column;
599 else
600 State.Stack.back().LastOperatorWrapped = Newline;
601 }
602 if ((Current.Type == TT_BinaryOperator && Current.isNot(tok::lessless)) ||
603 Current.Type == TT_ConditionalExpr)
604 State.Stack.back().LastOperatorWrapped = Newline;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000605 if (Current.Type == TT_ArraySubscriptLSquare &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000606 State.Stack.back().StartOfArraySubscripts == 0)
607 State.Stack.back().StartOfArraySubscripts = State.Column;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000608 if ((Current.is(tok::question) && Style.BreakBeforeTernaryOperators) ||
609 (Current.getPreviousNonComment() && Current.isNot(tok::colon) &&
610 Current.getPreviousNonComment()->is(tok::question) &&
611 !Style.BreakBeforeTernaryOperators))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000612 State.Stack.back().QuestionColumn = State.Column;
613 if (!Current.opensScope() && !Current.closesScope())
614 State.LowestLevelOnLine =
Daniel Jasper05cd5862014-05-08 12:21:30 +0000615 std::min(State.LowestLevelOnLine, Current.NestingLevel);
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000616 if (Current.isMemberAccess())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000617 State.Stack.back().StartOfFunctionCall =
Daniel Jasper0e617842014-04-16 12:26:54 +0000618 Current.LastOperator ? 0 : State.Column + Current.ColumnWidth;
Daniel Jasper17062ff2014-06-10 14:44:02 +0000619 if (Current.Type == TT_SelectorName)
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000620 State.Stack.back().ObjCSelectorNameFound = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000621 if (Current.Type == TT_CtorInitializerColon) {
622 // Indent 2 from the column, so:
623 // SomeClass::SomeClass()
624 // : First(...), ...
625 // Next(...)
626 // ^ line up here.
627 State.Stack.back().Indent =
628 State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
629 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
630 State.Stack.back().AvoidBinPacking = true;
631 State.Stack.back().BreakBeforeParameter = false;
632 }
633
Daniel Jasperde0328a2013-08-16 11:20:30 +0000634 // In ObjC method declaration we align on the ":" of parameters, but we need
Daniel Jasper6633ab82013-10-18 10:38:14 +0000635 // to ensure that we indent parameters on subsequent lines by at least our
636 // continuation indent width.
Daniel Jasperde0328a2013-08-16 11:20:30 +0000637 if (Current.Type == TT_ObjCMethodSpecifier)
Daniel Jasper6633ab82013-10-18 10:38:14 +0000638 State.Stack.back().Indent += Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000639
640 // Insert scopes created by fake parenthesis.
641 const FormatToken *Previous = Current.getPreviousNonComment();
Daniel Jasperb16b9692014-05-21 12:51:23 +0000642
643 // Add special behavior to support a format commonly used for JavaScript
644 // closures:
645 // SomeFunction(function() {
646 // foo();
647 // bar();
648 // }, a, b, c);
649 if (Style.Language == FormatStyle::LK_JavaScript) {
650 if (Current.isNot(tok::comment) && Previous && Previous->is(tok::l_brace) &&
651 State.Stack.size() > 1) {
652 if (State.Stack[State.Stack.size() - 2].JSFunctionInlined && Newline) {
653 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
654 State.Stack[i].NoLineBreak = true;
655 }
656 }
657 State.Stack[State.Stack.size() - 2].JSFunctionInlined = false;
658 }
659 if (Current.TokenText == "function")
Daniel Jasper90ebc982014-09-05 09:27:38 +0000660 State.Stack.back().JSFunctionInlined =
Daniel Jasper1779d432014-09-29 07:54:54 +0000661 !Newline && Previous && Previous->Type != TT_DictLiteral &&
662 // If the unnamed function is the only parameter to another function,
663 // we can likely inline it and come up with a good format.
664 (Previous->isNot(tok::l_paren) || Previous->ParameterCount > 1);
Daniel Jasperb16b9692014-05-21 12:51:23 +0000665 }
666
Daniel Jasper60553be2014-05-26 13:10:39 +0000667 moveStatePastFakeLParens(State, Newline);
668 moveStatePastScopeOpener(State, Newline);
669 moveStatePastScopeCloser(State);
670 moveStatePastFakeRParens(State);
671
672 if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) {
673 State.StartOfStringLiteral = State.Column;
674 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
675 !Current.isStringLiteral()) {
676 State.StartOfStringLiteral = 0;
677 }
678
679 State.Column += Current.ColumnWidth;
680 State.NextToken = State.NextToken->Next;
681 unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
682 if (State.Column > getColumnLimit(State)) {
683 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
684 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
685 }
686
687 if (Current.Role)
688 Current.Role->formatFromToken(State, this, DryRun);
689 // If the previous has a special role, let it consume tokens as appropriate.
690 // It is necessary to start at the previous token for the only implemented
691 // role (comma separated list). That way, the decision whether or not to break
692 // after the "{" is already done and both options are tried and evaluated.
693 // FIXME: This is ugly, find a better way.
694 if (Previous && Previous->Role)
695 Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
696
697 return Penalty;
698}
699
700void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
701 bool Newline) {
702 const FormatToken &Current = *State.NextToken;
703 const FormatToken *Previous = Current.getPreviousNonComment();
704
Daniel Jasperde0328a2013-08-16 11:20:30 +0000705 // Don't add extra indentation for the first fake parenthesis after
Dinesh Dwivedi0db806b2014-05-01 17:19:34 +0000706 // 'return', assignments or opening <({[. The indentation for these cases
Daniel Jasperde0328a2013-08-16 11:20:30 +0000707 // is special cased.
708 bool SkipFirstExtraIndent =
Daniel Jaspereabede62013-09-30 08:29:03 +0000709 (Previous && (Previous->opensScope() || Previous->is(tok::kw_return) ||
Daniel Jasperf48b5ab2013-11-07 19:23:49 +0000710 Previous->getPrecedence() == prec::Assignment ||
711 Previous->Type == TT_ObjCMethodExpr));
Daniel Jasperde0328a2013-08-16 11:20:30 +0000712 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
713 I = Current.FakeLParens.rbegin(),
714 E = Current.FakeLParens.rend();
715 I != E; ++I) {
716 ParenState NewParenState = State.Stack.back();
717 NewParenState.ContainsLineBreak = false;
Daniel Jaspereabede62013-09-30 08:29:03 +0000718
719 // Indent from 'LastSpace' unless this the fake parentheses encapsulating a
720 // builder type call after 'return'. If such a call is line-wrapped, we
721 // commonly just want to indent from the start of the line.
Daniel Jasper4281c5a2014-10-07 14:45:34 +0000722 if (!Current.isTrailingComment() &&
723 (!Previous || Previous->isNot(tok::kw_return) || *I > 0))
Daniel Jaspereabede62013-09-30 08:29:03 +0000724 NewParenState.Indent =
725 std::max(std::max(State.Column, NewParenState.Indent),
726 State.Stack.back().LastSpace);
727
Daniel Jasper5c332652014-04-03 12:00:33 +0000728 // Don't allow the RHS of an operator to be split over multiple lines unless
729 // there is a line-break right after the operator.
730 // Exclude relational operators, as there, it is always more desirable to
731 // have the LHS 'left' of the RHS.
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000732 if (Previous && Previous->getPrecedence() > prec::Assignment &&
733 (Previous->Type == TT_BinaryOperator ||
734 Previous->Type == TT_ConditionalExpr) &&
735 Previous->getPrecedence() != prec::Relational) {
736 bool BreakBeforeOperator = Previous->is(tok::lessless) ||
737 (Previous->Type == TT_BinaryOperator &&
738 Style.BreakBeforeBinaryOperators) ||
739 (Previous->Type == TT_ConditionalExpr &&
740 Style.BreakBeforeTernaryOperators);
741 if ((!Newline && !BreakBeforeOperator) ||
742 (!State.Stack.back().LastOperatorWrapped && BreakBeforeOperator))
743 NewParenState.NoLineBreak = true;
744 }
Daniel Jasper5c332652014-04-03 12:00:33 +0000745
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000746 // Do not indent relative to the fake parentheses inserted for "." or "->".
747 // This is a special case to make the following to statements consistent:
748 // OuterFunction(InnerFunctionCall( // break
749 // ParameterToInnerFunction));
750 // OuterFunction(SomeObject.InnerFunctionCall( // break
751 // ParameterToInnerFunction));
752 if (*I > prec::Unknown)
753 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
Daniel Jasper96964352013-12-18 10:44:36 +0000754 NewParenState.StartOfFunctionCall = State.Column;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000755
756 // Always indent conditional expressions. Never indent expression where
757 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
758 // prec::Assignment) as those have different indentation rules. Indent
759 // other expression, unless the indentation needs to be skipped.
760 if (*I == prec::Conditional ||
761 (!SkipFirstExtraIndent && *I > prec::Assignment &&
Daniel Jasper4281c5a2014-10-07 14:45:34 +0000762 !Current.isTrailingComment() && !Style.BreakBeforeBinaryOperators))
Daniel Jasper6633ab82013-10-18 10:38:14 +0000763 NewParenState.Indent += Style.ContinuationIndentWidth;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000764 if ((Previous && !Previous->opensScope()) || *I > prec::Comma)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000765 NewParenState.BreakBeforeParameter = false;
766 State.Stack.push_back(NewParenState);
767 SkipFirstExtraIndent = false;
768 }
Daniel Jasper60553be2014-05-26 13:10:39 +0000769}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000770
Daniel Jasper335ff262014-05-28 09:11:53 +0000771// Remove the fake r_parens after 'Tok'.
772static void consumeRParens(LineState& State, const FormatToken &Tok) {
773 for (unsigned i = 0, e = Tok.FakeRParens; i != e; ++i) {
774 unsigned VariablePos = State.Stack.back().VariablePos;
775 assert(State.Stack.size() > 1);
776 if (State.Stack.size() == 1) {
777 // Do not pop the last element.
778 break;
779 }
780 State.Stack.pop_back();
781 State.Stack.back().VariablePos = VariablePos;
782 }
783}
784
785// Returns whether 'Tok' opens or closes a scope requiring special handling
786// of the subsequent fake r_parens.
787//
788// For example, if this is an l_brace starting a nested block, we pretend (wrt.
789// to indentation) that we already consumed the corresponding r_brace. Thus, we
790// remove all ParenStates caused by fake parentheses that end at the r_brace.
791// The net effect of this is that we don't indent relative to the l_brace, if
792// the nested block is the last parameter of a function. This formats:
793//
794// SomeFunction(a, [] {
795// f(); // break
796// });
797//
798// instead of:
799// SomeFunction(a, [] {
800// f(); // break
801// });
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000802static bool fakeRParenSpecialCase(const LineState &State) {
803 const FormatToken &Tok = *State.NextToken;
Daniel Jasper335ff262014-05-28 09:11:53 +0000804 if (!Tok.MatchingParen)
805 return false;
806 const FormatToken *Left = &Tok;
807 if (Tok.isOneOf(tok::r_brace, tok::r_square))
808 Left = Tok.MatchingParen;
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000809 return !State.Stack.back().HasMultipleNestedBlocks &&
810 Left->isOneOf(tok::l_brace, tok::l_square) &&
Daniel Jasper335ff262014-05-28 09:11:53 +0000811 (Left->BlockKind == BK_Block ||
812 Left->Type == TT_ArrayInitializerLSquare ||
813 Left->Type == TT_DictLiteral);
814}
815
Daniel Jasper60553be2014-05-26 13:10:39 +0000816void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
Daniel Jasper335ff262014-05-28 09:11:53 +0000817 // Don't remove FakeRParens attached to r_braces that surround nested blocks
818 // as they will have been removed early (see above).
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000819 if (fakeRParenSpecialCase(State))
Daniel Jasper335ff262014-05-28 09:11:53 +0000820 return;
821
822 consumeRParens(State, *State.NextToken);
Daniel Jasper60553be2014-05-26 13:10:39 +0000823}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000824
Daniel Jasper60553be2014-05-26 13:10:39 +0000825void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
826 bool Newline) {
827 const FormatToken &Current = *State.NextToken;
828 if (!Current.opensScope())
829 return;
830
831 if (Current.MatchingParen && Current.BlockKind == BK_Block) {
832 moveStateToNewBlock(State);
833 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000834 }
835
Daniel Jasper60553be2014-05-26 13:10:39 +0000836 unsigned NewIndent;
837 unsigned NewIndentLevel = State.Stack.back().IndentLevel;
838 bool AvoidBinPacking;
839 bool BreakBeforeParameter = false;
840 if (Current.is(tok::l_brace) || Current.Type == TT_ArrayInitializerLSquare) {
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000841 if (fakeRParenSpecialCase(State))
Daniel Jasper335ff262014-05-28 09:11:53 +0000842 consumeRParens(State, *Current.MatchingParen);
843
Daniel Jasper60553be2014-05-26 13:10:39 +0000844 NewIndent = State.Stack.back().LastSpace;
845 if (Current.opensBlockTypeList(Style)) {
846 NewIndent += Style.IndentWidth;
847 NewIndent = std::min(State.Column + 2, NewIndent);
848 ++NewIndentLevel;
849 } else {
850 NewIndent += Style.ContinuationIndentWidth;
851 NewIndent = std::min(State.Column + 1, NewIndent);
852 }
853 const FormatToken *NextNoComment = Current.getNextNonComment();
854 AvoidBinPacking = Current.Type == TT_ArrayInitializerLSquare ||
855 Current.Type == TT_DictLiteral ||
856 Style.Language == FormatStyle::LK_Proto ||
857 !Style.BinPackParameters ||
858 (NextNoComment &&
859 NextNoComment->Type == TT_DesignatedInitializerPeriod);
860 } else {
861 NewIndent = Style.ContinuationIndentWidth +
862 std::max(State.Stack.back().LastSpace,
863 State.Stack.back().StartOfFunctionCall);
Daniel Jasper18210d72014-10-09 09:52:05 +0000864 AvoidBinPacking =
865 (State.Line->MustBeDeclaration && !Style.BinPackParameters) ||
866 (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||
867 (Style.ExperimentalAutoDetectBinPacking &&
868 (Current.PackingKind == PPK_OnePerLine ||
869 (!BinPackInconclusiveFunctions &&
870 Current.PackingKind == PPK_Inconclusive)));
Daniel Jasper60553be2014-05-26 13:10:39 +0000871 // If this '[' opens an ObjC call, determine whether all parameters fit
872 // into one line and put one per line if they don't.
873 if (Current.Type == TT_ObjCMethodExpr && Style.ColumnLimit != 0 &&
874 getLengthToMatchingParen(Current) + State.Column >
875 getColumnLimit(State))
876 BreakBeforeParameter = true;
877 }
Daniel Jaspera41aa532014-09-19 08:01:25 +0000878 bool NoLineBreak = State.Stack.back().NoLineBreak ||
879 (Current.Type == TT_TemplateOpener &&
880 State.Stack.back().ContainsUnwrappedBuilder);
Daniel Jasper60553be2014-05-26 13:10:39 +0000881 State.Stack.push_back(ParenState(NewIndent, NewIndentLevel,
882 State.Stack.back().LastSpace,
883 AvoidBinPacking, NoLineBreak));
884 State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000885 State.Stack.back().HasMultipleNestedBlocks = Current.BlockParameterCount > 1;
Daniel Jasper60553be2014-05-26 13:10:39 +0000886}
887
888void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
889 const FormatToken &Current = *State.NextToken;
890 if (!Current.closesScope())
891 return;
892
893 // If we encounter a closing ), ], } or >, we can remove a level from our
894 // stacks.
895 if (State.Stack.size() > 1 &&
896 (Current.isOneOf(tok::r_paren, tok::r_square) ||
897 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
Daniel Jasper335ff262014-05-28 09:11:53 +0000898 State.NextToken->Type == TT_TemplateCloser))
Daniel Jasper60553be2014-05-26 13:10:39 +0000899 State.Stack.pop_back();
Daniel Jasper335ff262014-05-28 09:11:53 +0000900
Daniel Jasper60553be2014-05-26 13:10:39 +0000901 if (Current.is(tok::r_square)) {
902 // If this ends the array subscript expr, reset the corresponding value.
903 const FormatToken *NextNonComment = Current.getNextNonComment();
904 if (NextNonComment && NextNonComment->isNot(tok::l_square))
905 State.Stack.back().StartOfArraySubscripts = 0;
906 }
907}
908
909void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
Daniel Jasper60553be2014-05-26 13:10:39 +0000910 // If we have already found more than one lambda introducers on this level, we
911 // opt out of this because similarity between the lambdas is more important.
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000912 if (fakeRParenSpecialCase(State))
Daniel Jasper335ff262014-05-28 09:11:53 +0000913 consumeRParens(State, *State.NextToken->MatchingParen);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000914
Daniel Jasper60553be2014-05-26 13:10:39 +0000915 // For some reason, ObjC blocks are indented like continuations.
916 unsigned NewIndent = State.Stack.back().LastSpace +
917 (State.NextToken->Type == TT_ObjCBlockLBrace
918 ? Style.ContinuationIndentWidth
919 : Style.IndentWidth);
920 State.Stack.push_back(ParenState(
921 NewIndent, /*NewIndentLevel=*/State.Stack.back().IndentLevel + 1,
922 State.Stack.back().LastSpace, /*AvoidBinPacking=*/true,
923 State.Stack.back().NoLineBreak));
924 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000925}
926
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000927unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
928 LineState &State) {
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000929 // Break before further function parameters on all levels.
930 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
931 State.Stack[i].BreakBeforeParameter = true;
932
Alexander Kornienko39856b72013-09-10 09:38:25 +0000933 unsigned ColumnsUsed = State.Column;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000934 // We can only affect layout of the first and the last line, so the penalty
935 // for all other lines is constant, and we ignore it.
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000936 State.Column = Current.LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000937
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000938 if (ColumnsUsed > getColumnLimit(State))
939 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000940 return 0;
941}
942
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000943static bool getRawStringLiteralPrefixPostfix(StringRef Text, StringRef &Prefix,
Alexander Kornienko81e32942013-09-16 20:20:49 +0000944 StringRef &Postfix) {
945 if (Text.startswith(Prefix = "R\"") || Text.startswith(Prefix = "uR\"") ||
946 Text.startswith(Prefix = "UR\"") || Text.startswith(Prefix = "u8R\"") ||
947 Text.startswith(Prefix = "LR\"")) {
948 size_t ParenPos = Text.find('(');
949 if (ParenPos != StringRef::npos) {
950 StringRef Delimiter =
951 Text.substr(Prefix.size(), ParenPos - Prefix.size());
952 Prefix = Text.substr(0, ParenPos + 1);
953 Postfix = Text.substr(Text.size() - 2 - Delimiter.size());
954 return Postfix.front() == ')' && Postfix.back() == '"' &&
955 Postfix.substr(1).startswith(Delimiter);
956 }
957 }
958 return false;
959}
960
Daniel Jasperde0328a2013-08-16 11:20:30 +0000961unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
962 LineState &State,
963 bool DryRun) {
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000964 // Don't break multi-line tokens other than block comments. Instead, just
965 // update the state.
966 if (Current.Type != TT_BlockComment && Current.IsMultiline)
967 return addMultilineToken(Current, State);
968
Daniel Jasper98857842013-10-30 13:54:53 +0000969 // Don't break implicit string literals.
970 if (Current.Type == TT_ImplicitStringLiteral)
971 return 0;
972
Daniel Jasper04b6a082013-12-20 06:22:01 +0000973 if (!Current.isStringLiteral() && !Current.is(tok::comment))
Daniel Jasperf93551c2013-08-23 10:05:49 +0000974 return 0;
975
Ahmed Charlesb8984322014-03-07 20:03:18 +0000976 std::unique_ptr<BreakableToken> Token;
Alexander Kornienko39856b72013-09-10 09:38:25 +0000977 unsigned StartColumn = State.Column - Current.ColumnWidth;
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000978 unsigned ColumnLimit = getColumnLimit(State);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000979
Daniel Jasper04b6a082013-12-20 06:22:01 +0000980 if (Current.isStringLiteral()) {
Alexander Kornienko384b40b2013-10-11 21:43:05 +0000981 // Don't break string literals inside preprocessor directives (except for
982 // #define directives, as their contents are stored in separate lines and
983 // are not affected by this check).
984 // This way we avoid breaking code with line directives and unknown
985 // preprocessor directives that contain long string literals.
986 if (State.Line->Type == LT_PreprocessorDirective)
987 return 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000988 // Exempts unterminated string literals from line breaking. The user will
989 // likely want to terminate the string before any line breaking is done.
990 if (Current.IsUnterminatedLiteral)
991 return 0;
992
Alexander Kornienko81e32942013-09-16 20:20:49 +0000993 StringRef Text = Current.TokenText;
994 StringRef Prefix;
995 StringRef Postfix;
Daniel Jasper174b0122014-01-09 14:18:12 +0000996 bool IsNSStringLiteral = false;
Alexander Kornienko81e32942013-09-16 20:20:49 +0000997 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
998 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
999 // reduce the overhead) for each FormatToken, which is a string, so that we
1000 // don't run multiple checks here on the hot path.
Daniel Jasper174b0122014-01-09 14:18:12 +00001001 if (Text.startswith("\"") && Current.Previous &&
1002 Current.Previous->is(tok::at)) {
1003 IsNSStringLiteral = true;
1004 Prefix = "@\"";
Daniel Jasper174b0122014-01-09 14:18:12 +00001005 }
Alexander Kornienko81e32942013-09-16 20:20:49 +00001006 if ((Text.endswith(Postfix = "\"") &&
Daniel Jasper174b0122014-01-09 14:18:12 +00001007 (IsNSStringLiteral || Text.startswith(Prefix = "\"") ||
1008 Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
1009 Text.startswith(Prefix = "u8\"") ||
Alexander Kornienko81e32942013-09-16 20:20:49 +00001010 Text.startswith(Prefix = "L\""))) ||
1011 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")")) ||
1012 getRawStringLiteralPrefixPostfix(Text, Prefix, Postfix)) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001013 Token.reset(new BreakableStringLiteral(
1014 Current, State.Line->Level, StartColumn, Prefix, Postfix,
1015 State.Line->InPPDirective, Encoding, Style));
Alexander Kornienko81e32942013-09-16 20:20:49 +00001016 } else {
1017 return 0;
1018 }
Daniel Jasperde0328a2013-08-16 11:20:30 +00001019 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
Alexander Kornienkoce9161a2014-01-02 15:13:14 +00001020 if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
1021 return 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001022 Token.reset(new BreakableBlockComment(
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001023 Current, State.Line->Level, StartColumn, Current.OriginalColumn,
1024 !Current.Previous, State.Line->InPPDirective, Encoding, Style));
Daniel Jasperde0328a2013-08-16 11:20:30 +00001025 } else if (Current.Type == TT_LineComment &&
Craig Topper2145bc02014-05-09 08:15:10 +00001026 (Current.Previous == nullptr ||
Daniel Jasperde0328a2013-08-16 11:20:30 +00001027 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienkoce9161a2014-01-02 15:13:14 +00001028 if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
1029 return 0;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001030 Token.reset(new BreakableLineComment(Current, State.Line->Level,
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001031 StartColumn, /*InPPDirective=*/false,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001032 Encoding, Style));
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001033 // We don't insert backslashes when breaking line comments.
1034 ColumnLimit = Style.ColumnLimit;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001035 } else {
1036 return 0;
1037 }
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001038 if (Current.UnbreakableTailLength >= ColumnLimit)
Daniel Jasperde0328a2013-08-16 11:20:30 +00001039 return 0;
1040
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001041 unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001042 bool BreakInserted = false;
1043 unsigned Penalty = 0;
1044 unsigned RemainingTokenColumns = 0;
1045 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
1046 LineIndex != EndIndex; ++LineIndex) {
1047 if (!DryRun)
1048 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
1049 unsigned TailOffset = 0;
1050 RemainingTokenColumns =
1051 Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
1052 while (RemainingTokenColumns > RemainingSpace) {
1053 BreakableToken::Split Split =
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001054 Token->getSplit(LineIndex, TailOffset, ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +00001055 if (Split.first == StringRef::npos) {
1056 // The last line's penalty is handled in addNextStateToQueue().
1057 if (LineIndex < EndIndex - 1)
1058 Penalty += Style.PenaltyExcessCharacter *
1059 (RemainingTokenColumns - RemainingSpace);
1060 break;
1061 }
1062 assert(Split.first != 0);
1063 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
1064 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
Alexander Kornienko875395f2013-11-12 17:50:13 +00001065
1066 // We can remove extra whitespace instead of breaking the line.
1067 if (RemainingTokenColumns + 1 - Split.second <= RemainingSpace) {
1068 RemainingTokenColumns = 0;
1069 if (!DryRun)
1070 Token->replaceWhitespace(LineIndex, TailOffset, Split, Whitespaces);
1071 break;
1072 }
1073
Alexander Kornienko64a42b82014-04-15 14:52:43 +00001074 // When breaking before a tab character, it may be moved by a few columns,
1075 // but will still be expanded to the next tab stop, so we don't save any
1076 // columns.
1077 if (NewRemainingTokenColumns == RemainingTokenColumns)
1078 break;
1079
Daniel Jasperde0328a2013-08-16 11:20:30 +00001080 assert(NewRemainingTokenColumns < RemainingTokenColumns);
1081 if (!DryRun)
1082 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Daniel Jasper2739af32013-08-28 10:03:58 +00001083 Penalty += Current.SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001084 unsigned ColumnsUsed =
1085 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001086 if (ColumnsUsed > ColumnLimit) {
1087 Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +00001088 }
1089 TailOffset += Split.first + Split.second;
1090 RemainingTokenColumns = NewRemainingTokenColumns;
1091 BreakInserted = true;
1092 }
1093 }
1094
1095 State.Column = RemainingTokenColumns;
1096
1097 if (BreakInserted) {
1098 // If we break the token inside a parameter list, we need to break before
1099 // the next parameter on all levels, so that the next parameter is clearly
1100 // visible. Line comments already introduce a break.
1101 if (Current.Type != TT_LineComment) {
1102 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1103 State.Stack[i].BreakBeforeParameter = true;
1104 }
1105
Daniel Jasper04b6a082013-12-20 06:22:01 +00001106 Penalty += Current.isStringLiteral() ? Style.PenaltyBreakString
1107 : Style.PenaltyBreakComment;
Daniel Jasper2739af32013-08-28 10:03:58 +00001108
Daniel Jasperde0328a2013-08-16 11:20:30 +00001109 State.Stack.back().LastSpace = StartColumn;
1110 }
1111 return Penalty;
1112}
1113
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001114unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001115 // In preprocessor directives reserve two chars for trailing " \"
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001116 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
Daniel Jasperde0328a2013-08-16 11:20:30 +00001117}
1118
Daniel Jasperc39b56f2013-12-16 07:23:08 +00001119bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
Daniel Jasperf438cb72013-08-23 11:57:34 +00001120 const FormatToken &Current = *State.NextToken;
Daniel Jasper9509f182014-05-05 08:08:07 +00001121 if (!Current.isStringLiteral() || Current.Type == TT_ImplicitStringLiteral)
Daniel Jasperf438cb72013-08-23 11:57:34 +00001122 return false;
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00001123 // We never consider raw string literals "multiline" for the purpose of
Daniel Jasperc39b56f2013-12-16 07:23:08 +00001124 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
1125 // (see TokenAnnotator::mustBreakBefore().
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00001126 if (Current.TokenText.startswith("R\""))
1127 return false;
Alexander Kornienko39856b72013-09-10 09:38:25 +00001128 if (Current.IsMultiline)
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00001129 return true;
Daniel Jasperf438cb72013-08-23 11:57:34 +00001130 if (Current.getNextNonComment() &&
Daniel Jasper04b6a082013-12-20 06:22:01 +00001131 Current.getNextNonComment()->isStringLiteral())
Daniel Jasperf438cb72013-08-23 11:57:34 +00001132 return true; // Implicit concatenation.
Alexander Kornienko39856b72013-09-10 09:38:25 +00001133 if (State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
Daniel Jasperf438cb72013-08-23 11:57:34 +00001134 Style.ColumnLimit)
1135 return true; // String will be split.
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00001136 return false;
Daniel Jasperf438cb72013-08-23 11:57:34 +00001137}
1138
Daniel Jasperde0328a2013-08-16 11:20:30 +00001139} // namespace format
1140} // namespace clang