blob: a6fb40ece7a9ea9afbdde49f037c49469ffa267b [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 Jaspere068ac72014-10-27 17:13:59 +0000125 // Don't break after very short return types (e.g. "void") as that is often
126 // unexpected.
127 if (Current.Type == TT_FunctionDeclarationName &&
128 !Style.AlwaysBreakAfterDefinitionReturnType && State.Column < 6)
129 return false;
130
Daniel Jasperde0328a2013-08-16 11:20:30 +0000131 return !State.Stack.back().NoLineBreak;
132}
133
134bool ContinuationIndenter::mustBreak(const LineState &State) {
135 const FormatToken &Current = *State.NextToken;
136 const FormatToken &Previous = *Current.Previous;
137 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
138 return true;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000139 if (State.Stack.back().BreakBeforeClosingBrace &&
140 Current.closesBlockTypeList(Style))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000141 return true;
142 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
143 return true;
Daniel Jasperec01cd62013-10-08 05:11:18 +0000144 if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
Daniel Jasper165b29e2013-11-08 00:57:11 +0000145 (Style.BreakBeforeTernaryOperators &&
146 (Current.is(tok::question) || (Current.Type == TT_ConditionalExpr &&
147 Previous.isNot(tok::question)))) ||
148 (!Style.BreakBeforeTernaryOperators &&
149 (Previous.is(tok::question) || Previous.Type == TT_ConditionalExpr))) &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000150 State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
151 !Current.isOneOf(tok::r_paren, tok::r_brace))
152 return true;
153 if (Style.AlwaysBreakBeforeMultilineStrings &&
Daniel Jasperf438cb72013-08-23 11:57:34 +0000154 State.Column > State.Stack.back().Indent && // Breaking saves columns.
Daniel Jasper27943052013-11-09 03:08:25 +0000155 !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) &&
Daniel Jasper3251fff2014-06-10 06:27:23 +0000156 Previous.Type != TT_InlineASMColon &&
157 Previous.Type != TT_ConditionalExpr && nextIsMultilineString(State))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000158 return true;
Daniel Jasperce2fdb02014-10-27 13:25:59 +0000159 if (((Previous.Type == TT_DictLiteral && Previous.is(tok::l_brace)) ||
Daniel Jasper1db6c382013-10-22 15:30:28 +0000160 Previous.Type == TT_ArrayInitializerLSquare) &&
Daniel Jasperdb8804b2014-04-14 12:11:07 +0000161 Style.ColumnLimit > 0 &&
Daniel Jasperd489dd32013-10-20 16:45:46 +0000162 getLengthToMatchingParen(Previous) + State.Column > getColumnLimit(State))
163 return true;
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000164 if (Current.Type == TT_CtorInitializerColon &&
Daniel Jasperd74cf402014-04-08 12:46:38 +0000165 ((Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All) ||
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000166 Style.BreakConstructorInitializersBeforeComma || Style.ColumnLimit != 0))
167 return true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000168
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000169 if (State.Column < getNewLineColumn(State))
170 return false;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000171 if (!Style.BreakBeforeBinaryOperators) {
172 // If we need to break somewhere inside the LHS of a binary expression, we
173 // should also break after the operator. Otherwise, the formatting would
174 // hide the operator precedence, e.g. in:
175 // if (aaaaaaaaaaaaaa ==
176 // bbbbbbbbbbbbbb && c) {..
177 // For comparisons, we only apply this rule, if the LHS is a binary
178 // expression itself as otherwise, the line breaks seem superfluous.
179 // We need special cases for ">>" which we have split into two ">" while
180 // lexing in order to make template parsing easier.
181 //
182 // FIXME: We'll need something similar for styles that break before binary
183 // operators.
184 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
185 Previous.getPrecedence() == prec::Equality) &&
186 Previous.Previous &&
187 Previous.Previous->Type != TT_BinaryOperator; // For >>.
188 bool LHSIsBinaryExpr =
Daniel Jasper562ecd42013-09-06 08:08:14 +0000189 Previous.Previous && Previous.Previous->EndsBinaryExpression;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000190 if (Previous.Type == TT_BinaryOperator &&
191 (!IsComparison || LHSIsBinaryExpr) &&
192 Current.Type != TT_BinaryOperator && // For >>.
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000193 !Current.isTrailingComment() && !Previous.is(tok::lessless) &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000194 Previous.getPrecedence() != prec::Assignment &&
195 State.Stack.back().BreakBeforeParameter)
196 return true;
197 }
198
199 // Same as above, but for the first "<<" operator.
Alexander Kornienko86b2dfd2014-03-06 15:13:08 +0000200 if (Current.is(tok::lessless) && Current.Type != TT_OverloadedOperator &&
201 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000202 State.Stack.back().FirstLessLess == 0)
203 return true;
204
Daniel Jasper17062ff2014-06-10 14:44:02 +0000205 if (Current.Type == TT_SelectorName &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000206 State.Stack.back().ObjCSelectorNameFound &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000207 State.Stack.back().BreakBeforeParameter)
208 return true;
Daniel Jasper05cd5862014-05-08 12:21:30 +0000209 if (Previous.ClosesTemplateDeclaration && Current.NestingLevel == 0 &&
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000210 !Current.isTrailingComment())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000211 return true;
212
Daniel Jasper4355e7f2014-07-09 07:50:33 +0000213 // If the return type spans multiple lines, wrap before the function name.
214 if ((Current.Type == TT_FunctionDeclarationName ||
215 Current.is(tok::kw_operator)) &&
216 State.Stack.back().BreakBeforeParameter)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000217 return true;
Daniel Jasper4355e7f2014-07-09 07:50:33 +0000218
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000219 if (startsSegmentOfBuilderTypeCall(Current) &&
Daniel Jasperf8151e92013-08-30 07:12:40 +0000220 (State.Stack.back().CallContinuation != 0 ||
221 (State.Stack.back().BreakBeforeParameter &&
222 State.Stack.back().ContainsUnwrappedBuilder)))
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000223 return true;
Daniel Jasper96972812014-01-05 12:38:10 +0000224
225 // The following could be precomputed as they do not depend on the state.
226 // However, as they should take effect only if the UnwrappedLine does not fit
227 // into the ColumnLimit, they are checked here in the ContinuationIndenter.
Daniel Jasper35995672014-04-29 14:05:20 +0000228 if (Style.ColumnLimit != 0 && Previous.BlockKind == BK_Block &&
229 Previous.is(tok::l_brace) && !Current.isOneOf(tok::r_brace, tok::comment))
Daniel Jasper96972812014-01-05 12:38:10 +0000230 return true;
Daniel Jasper96972812014-01-05 12:38:10 +0000231
Daniel Jasperde0328a2013-08-16 11:20:30 +0000232 return false;
233}
234
235unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000236 bool DryRun,
237 unsigned ExtraSpaces) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000238 const FormatToken &Current = *State.NextToken;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000239
Manuel Klimek819788d2014-03-18 11:22:45 +0000240 assert(!State.Stack.empty());
241 if ((Current.Type == TT_ImplicitStringLiteral &&
Craig Topper2145bc02014-05-09 08:15:10 +0000242 (Current.Previous->Tok.getIdentifierInfo() == nullptr ||
Daniel Jasper98857842013-10-30 13:54:53 +0000243 Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
244 tok::pp_not_keyword))) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000245 // FIXME: Is this correct?
246 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
247 State.NextToken->WhitespaceRange.getEnd()) -
248 SourceMgr.getSpellingColumnNumber(
249 State.NextToken->WhitespaceRange.getBegin());
Daniel Jasperda353cd2014-03-12 08:24:47 +0000250 State.Column += WhitespaceLength;
Daniel Jasper240dfda2014-03-31 14:23:49 +0000251 moveStateToNextToken(State, DryRun, /*Newline=*/false);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000252 return 0;
253 }
254
Alexander Kornienko1f803962013-10-01 14:41:18 +0000255 unsigned Penalty = 0;
256 if (Newline)
257 Penalty = addTokenOnNewLine(State, DryRun);
258 else
Daniel Jasper48437ce2013-11-20 14:54:39 +0000259 addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000260
261 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
262}
263
Daniel Jasper48437ce2013-11-20 14:54:39 +0000264void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
265 unsigned ExtraSpaces) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000266 FormatToken &Current = *State.NextToken;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000267 const FormatToken &Previous = *State.NextToken->Previous;
268 if (Current.is(tok::equal) &&
Daniel Jasper05cd5862014-05-08 12:21:30 +0000269 (State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) &&
Alexander Kornienko1f803962013-10-01 14:41:18 +0000270 State.Stack.back().VariablePos == 0) {
271 State.Stack.back().VariablePos = State.Column;
272 // Move over * and & if they are bound to the variable name.
273 const FormatToken *Tok = &Previous;
274 while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
275 State.Stack.back().VariablePos -= Tok->ColumnWidth;
276 if (Tok->SpacesRequiredBefore != 0)
277 break;
278 Tok = Tok->Previous;
279 }
280 if (Previous.PartOfMultiVariableDeclStmt)
281 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
282 }
283
284 unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
285
286 if (!DryRun)
287 Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, /*IndentLevel=*/0,
288 Spaces, State.Column + Spaces);
289
Daniel Jasper17062ff2014-06-10 14:44:02 +0000290 if (Current.Type == TT_SelectorName &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000291 !State.Stack.back().ObjCSelectorNameFound) {
292 if (Current.LongestObjCSelectorName == 0)
293 State.Stack.back().AlignColons = false;
294 else if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
295 State.Column + Spaces + Current.ColumnWidth)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000296 State.Stack.back().ColonPos =
297 State.Stack.back().Indent + Current.LongestObjCSelectorName;
298 else
299 State.Stack.back().ColonPos = State.Column + Spaces + Current.ColumnWidth;
300 }
301
302 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper5a611392013-12-19 21:41:37 +0000303 (Current.Type != TT_LineComment || Previous.BlockKind == BK_BracedInit))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000304 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasperec01cd62013-10-08 05:11:18 +0000305 if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000306 State.Stack.back().NoLineBreak = true;
307 if (startsSegmentOfBuilderTypeCall(Current))
308 State.Stack.back().ContainsUnwrappedBuilder = true;
309
Daniel Jasperd6f17d82014-09-12 16:35:28 +0000310 if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&
311 (Previous.MatchingParen &&
312 (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10))) {
313 // If there is a function call with long parameters, break before trailing
314 // calls. This prevents things like:
315 // EXPECT_CALL(SomeLongParameter).Times(
316 // 2);
317 // We don't want to do this for short parameters as they can just be
318 // indexes.
319 State.Stack.back().NoLineBreak = true;
320 }
321
Alexander Kornienko1f803962013-10-01 14:41:18 +0000322 State.Column += Spaces;
Daniel Jasper8acf8222014-05-07 09:23:05 +0000323 if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&
324 Previous.Previous && Previous.Previous->isOneOf(tok::kw_if, tok::kw_for))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000325 // Treat the condition inside an if as if it was a second function
Daniel Jasper6633ab82013-10-18 10:38:14 +0000326 // parameter, i.e. let nested calls have a continuation indent.
Daniel Jasper8acf8222014-05-07 09:23:05 +0000327 State.Stack.back().LastSpace = State.Column;
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000328 else if (!Current.isOneOf(tok::comment, tok::caret) &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000329 (Previous.is(tok::comma) ||
330 (Previous.is(tok::colon) && Previous.Type == TT_ObjCMethodExpr)))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000331 State.Stack.back().LastSpace = State.Column;
332 else if ((Previous.Type == TT_BinaryOperator ||
333 Previous.Type == TT_ConditionalExpr ||
Alexander Kornienko1f803962013-10-01 14:41:18 +0000334 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper0e617842014-04-16 12:26:54 +0000335 ((Previous.getPrecedence() != prec::Assignment &&
336 (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||
337 !Previous.LastOperator)) ||
Alexander Kornienko1f803962013-10-01 14:41:18 +0000338 Current.StartsBinaryExpression))
339 // Always indent relative to the RHS of the expression unless this is a
340 // simple assignment without binary expression on the RHS. Also indent
341 // relative to unary operators and the colons of constructor initializers.
342 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf9a5e402013-10-08 16:24:07 +0000343 else if (Previous.Type == TT_InheritanceColon) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000344 State.Stack.back().Indent = State.Column;
Daniel Jasperf9a5e402013-10-08 16:24:07 +0000345 State.Stack.back().LastSpace = State.Column;
346 } else if (Previous.opensScope()) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000347 // If a function has a trailing call, indent all parameters from the
348 // opening parenthesis. This avoids confusing indents like:
349 // OuterFunction(InnerFunctionCall( // break
350 // ParameterToInnerFunction)) // break
351 // .SecondInnerFunctionCall();
352 bool HasTrailingCall = false;
353 if (Previous.MatchingParen) {
354 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
355 HasTrailingCall = Next && Next->isMemberAccess();
356 }
357 if (HasTrailingCall &&
358 State.Stack[State.Stack.size() - 2].CallContinuation == 0)
359 State.Stack.back().LastSpace = State.Column;
360 }
361}
362
363unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
364 bool DryRun) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000365 FormatToken &Current = *State.NextToken;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000366 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000367
Alexander Kornienko1f803962013-10-01 14:41:18 +0000368 // Extra penalty that needs to be added because of the way certain line
369 // breaks are chosen.
370 unsigned Penalty = 0;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000371
Daniel Jaspera0407742014-02-11 10:08:11 +0000372 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
373 const FormatToken *NextNonComment = Previous.getNextNonComment();
374 if (!NextNonComment)
375 NextNonComment = &Current;
Daniel Jasper05cd5862014-05-08 12:21:30 +0000376 // The first line break on any NestingLevel causes an extra penalty in order
Alexander Kornienko1f803962013-10-01 14:41:18 +0000377 // prefer similar line breaks.
378 if (!State.Stack.back().ContainsLineBreak)
379 Penalty += 15;
380 State.Stack.back().ContainsLineBreak = true;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000381
Alexander Kornienko1f803962013-10-01 14:41:18 +0000382 Penalty += State.NextToken->SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000383
Alexander Kornienko1f803962013-10-01 14:41:18 +0000384 // Breaking before the first "<<" is generally not desirable if the LHS is
Daniel Jasper48437ce2013-11-20 14:54:39 +0000385 // short. Also always add the penalty if the LHS is split over mutliple lines
Daniel Jasper2b7556e2014-04-03 12:00:27 +0000386 // to avoid unnecessary line breaks that just work around this penalty.
Daniel Jaspera0407742014-02-11 10:08:11 +0000387 if (NextNonComment->is(tok::lessless) &&
388 State.Stack.back().FirstLessLess == 0 &&
Daniel Jasper004177e2013-12-19 16:06:40 +0000389 (State.Column <= Style.ColumnLimit / 3 ||
Daniel Jasper48437ce2013-11-20 14:54:39 +0000390 State.Stack.back().BreakBeforeParameter))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000391 Penalty += Style.PenaltyBreakFirstLessLess;
392
Daniel Jasper9f388d02014-03-27 14:33:30 +0000393 State.Column = getNewLineColumn(State);
394 if (NextNonComment->isMemberAccess()) {
395 if (State.Stack.back().CallContinuation == 0)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000396 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper17062ff2014-06-10 14:44:02 +0000397 } else if (NextNonComment->Type == TT_SelectorName) {
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000398 if (!State.Stack.back().ObjCSelectorNameFound) {
Daniel Jaspera0407742014-02-11 10:08:11 +0000399 if (NextNonComment->LongestObjCSelectorName == 0) {
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000400 State.Stack.back().AlignColons = false;
401 } else {
402 State.Stack.back().ColonPos =
Daniel Jaspera0407742014-02-11 10:08:11 +0000403 State.Stack.back().Indent + NextNonComment->LongestObjCSelectorName;
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000404 }
Daniel Jasper9f388d02014-03-27 14:33:30 +0000405 } else if (State.Stack.back().AlignColons &&
406 State.Stack.back().ColonPos <= NextNonComment->ColumnWidth) {
Daniel Jaspera0407742014-02-11 10:08:11 +0000407 State.Stack.back().ColonPos = State.Column + NextNonComment->ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000408 }
Daniel Jasper1fd6f1f2014-03-17 14:32:47 +0000409 } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
410 (PreviousNonComment->Type == TT_ObjCMethodExpr ||
411 PreviousNonComment->Type == TT_DictLiteral)) {
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000412 // FIXME: This is hacky, find a better way. The problem is that in an ObjC
413 // method expression, the block should be aligned to the line starting it,
414 // e.g.:
415 // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
416 // ^(int *i) {
417 // // ...
418 // }];
Daniel Jasper05cd5862014-05-08 12:21:30 +0000419 // Thus, we set LastSpace of the next higher NestingLevel, to which we move
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000420 // when we consume all of the "}"'s FakeRParens at the "{".
Daniel Jasper9a26e772013-12-23 11:25:40 +0000421 if (State.Stack.size() > 1)
Daniel Jasper9f388d02014-03-27 14:33:30 +0000422 State.Stack[State.Stack.size() - 2].LastSpace =
423 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
424 Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000425 }
426
Alexander Kornienko1f803962013-10-01 14:41:18 +0000427 if ((Previous.isOneOf(tok::comma, tok::semi) &&
428 !State.Stack.back().AvoidBinPacking) ||
429 Previous.Type == TT_BinaryOperator)
430 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper05cd5862014-05-08 12:21:30 +0000431 if (Previous.Type == TT_TemplateCloser && Current.NestingLevel == 0)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000432 State.Stack.back().BreakBeforeParameter = false;
Daniel Jaspera0407742014-02-11 10:08:11 +0000433 if (NextNonComment->is(tok::question) ||
Daniel Jasper165b29e2013-11-08 00:57:11 +0000434 (PreviousNonComment && PreviousNonComment->is(tok::question)))
435 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000436
437 if (!DryRun) {
Daniel Jaspera69ca9b2014-06-04 12:40:57 +0000438 unsigned Newlines = std::max(
439 1u, std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1));
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000440 Whitespaces.replaceWhitespace(Current, Newlines,
441 State.Stack.back().IndentLevel, State.Column,
442 State.Column, State.Line->InPPDirective);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000443 }
444
445 if (!Current.isTrailingComment())
446 State.Stack.back().LastSpace = State.Column;
Daniel Jasper05cd5862014-05-08 12:21:30 +0000447 State.StartOfLineLevel = Current.NestingLevel;
448 State.LowestLevelOnLine = Current.NestingLevel;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000449
450 // Any break on this level means that the parent level has been broken
451 // and we need to avoid bin packing there.
Daniel Jasperb16b9692014-05-21 12:51:23 +0000452 bool JavaScriptFormat = Style.Language == FormatStyle::LK_JavaScript &&
453 Current.is(tok::r_brace) &&
454 State.Stack.size() > 1 &&
455 State.Stack[State.Stack.size() - 2].JSFunctionInlined;
456 if (!JavaScriptFormat) {
457 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
458 State.Stack[i].BreakBeforeParameter = true;
459 }
Alexander Kornienko1f803962013-10-01 14:41:18 +0000460 }
Daniel Jasperb16b9692014-05-21 12:51:23 +0000461
Daniel Jasper9e5ede02013-11-08 19:56:28 +0000462 if (PreviousNonComment &&
463 !PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
464 PreviousNonComment->Type != TT_TemplateCloser &&
465 PreviousNonComment->Type != TT_BinaryOperator &&
Daniel Jasperfab69ff2014-10-21 08:24:18 +0000466 PreviousNonComment->Type != TT_JavaAnnotation &&
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000467 Current.Type != TT_BinaryOperator && !PreviousNonComment->opensScope())
Alexander Kornienko1f803962013-10-01 14:41:18 +0000468 State.Stack.back().BreakBeforeParameter = true;
469
Daniel Jasper1db6c382013-10-22 15:30:28 +0000470 // If we break after { or the [ of an array initializer, we should also break
471 // before the corresponding } or ].
Daniel Jasper90818052014-06-10 10:42:26 +0000472 if (PreviousNonComment &&
473 (PreviousNonComment->is(tok::l_brace) ||
474 PreviousNonComment->Type == TT_ArrayInitializerLSquare))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000475 State.Stack.back().BreakBeforeClosingBrace = true;
476
477 if (State.Stack.back().AvoidBinPacking) {
478 // If we are breaking after '(', '{', '<', this is not bin packing
Daniel Jasper2a958322014-05-21 13:26:58 +0000479 // unless AllowAllParametersOfDeclarationOnNextLine is false or this is a
480 // dict/object literal.
Alexander Kornienko1f803962013-10-01 14:41:18 +0000481 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
482 Previous.Type == TT_BinaryOperator) ||
483 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
Daniel Jasper2a958322014-05-21 13:26:58 +0000484 State.Line->MustBeDeclaration) ||
485 Previous.Type == TT_DictLiteral)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000486 State.Stack.back().BreakBeforeParameter = true;
487 }
488
489 return Penalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000490}
491
Daniel Jasper9f388d02014-03-27 14:33:30 +0000492unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000493 if (!State.NextToken || !State.NextToken->Previous)
494 return 0;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000495 FormatToken &Current = *State.NextToken;
Daniel Jasper4281c5a2014-10-07 14:45:34 +0000496 const FormatToken &Previous = *Current.Previous;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000497 // If we are continuing an expression, we want to use the continuation indent.
498 unsigned ContinuationIndent =
499 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
500 Style.ContinuationIndentWidth;
501 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
502 const FormatToken *NextNonComment = Previous.getNextNonComment();
503 if (!NextNonComment)
504 NextNonComment = &Current;
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000505 if (NextNonComment->is(tok::l_brace) && NextNonComment->BlockKind == BK_Block)
Daniel Jasper05cd5862014-05-08 12:21:30 +0000506 return Current.NestingLevel == 0 ? State.FirstIndent
507 : State.Stack.back().Indent;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000508 if (Current.isOneOf(tok::r_brace, tok::r_square)) {
Daniel Jasperb16b9692014-05-21 12:51:23 +0000509 if (State.Stack.size() > 1 &&
510 State.Stack[State.Stack.size() - 2].JSFunctionInlined)
511 return State.FirstIndent;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000512 if (Current.closesBlockTypeList(Style) ||
513 (Current.MatchingParen &&
514 Current.MatchingParen->BlockKind == BK_BracedInit))
515 return State.Stack[State.Stack.size() - 2].LastSpace;
516 else
517 return State.FirstIndent;
518 }
Daniel Jasper783bac62014-04-15 09:54:30 +0000519 if (Current.is(tok::identifier) && Current.Next &&
520 Current.Next->Type == TT_DictLiteral)
521 return State.Stack.back().Indent;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000522 if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
523 return State.StartOfStringLiteral;
524 if (NextNonComment->is(tok::lessless) &&
525 State.Stack.back().FirstLessLess != 0)
526 return State.Stack.back().FirstLessLess;
527 if (NextNonComment->isMemberAccess()) {
528 if (State.Stack.back().CallContinuation == 0) {
529 return ContinuationIndent;
530 } else {
531 return State.Stack.back().CallContinuation;
532 }
533 }
534 if (State.Stack.back().QuestionColumn != 0 &&
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000535 ((NextNonComment->is(tok::colon) &&
536 NextNonComment->Type == TT_ConditionalExpr) ||
Daniel Jasper9f388d02014-03-27 14:33:30 +0000537 Previous.Type == TT_ConditionalExpr))
538 return State.Stack.back().QuestionColumn;
539 if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0)
540 return State.Stack.back().VariablePos;
541 if ((PreviousNonComment && (PreviousNonComment->ClosesTemplateDeclaration ||
Daniel Jasperfab69ff2014-10-21 08:24:18 +0000542 PreviousNonComment->Type == TT_AttributeParen ||
543 PreviousNonComment->Type == TT_JavaAnnotation)) ||
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000544 (!Style.IndentWrappedFunctionNames &&
545 (NextNonComment->is(tok::kw_operator) ||
546 NextNonComment->Type == TT_FunctionDeclarationName)))
Daniel Jasper9f388d02014-03-27 14:33:30 +0000547 return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
Daniel Jasper17062ff2014-06-10 14:44:02 +0000548 if (NextNonComment->Type == TT_SelectorName) {
Daniel Jasper9f388d02014-03-27 14:33:30 +0000549 if (!State.Stack.back().ObjCSelectorNameFound) {
550 if (NextNonComment->LongestObjCSelectorName == 0) {
551 return State.Stack.back().Indent;
552 } else {
553 return State.Stack.back().Indent +
554 NextNonComment->LongestObjCSelectorName -
555 NextNonComment->ColumnWidth;
556 }
557 } else if (!State.Stack.back().AlignColons) {
558 return State.Stack.back().Indent;
559 } else if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth) {
560 return State.Stack.back().ColonPos - NextNonComment->ColumnWidth;
561 } else {
562 return State.Stack.back().Indent;
563 }
564 }
565 if (NextNonComment->Type == TT_ArraySubscriptLSquare) {
566 if (State.Stack.back().StartOfArraySubscripts != 0)
567 return State.Stack.back().StartOfArraySubscripts;
568 else
569 return ContinuationIndent;
570 }
571 if (NextNonComment->Type == TT_StartOfName ||
572 Previous.isOneOf(tok::coloncolon, tok::equal)) {
573 return ContinuationIndent;
574 }
575 if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
576 (PreviousNonComment->Type == TT_ObjCMethodExpr ||
577 PreviousNonComment->Type == TT_DictLiteral))
578 return ContinuationIndent;
579 if (NextNonComment->Type == TT_CtorInitializerColon)
580 return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
581 if (NextNonComment->Type == TT_CtorInitializerComma)
582 return State.Stack.back().Indent;
Daniel Jasper316ab382014-08-06 13:14:58 +0000583 if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() &&
584 Current.isNot(tok::colon))
585 return ContinuationIndent;
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000586 if (State.Stack.back().Indent == State.FirstIndent && PreviousNonComment &&
Daniel Jasper9f388d02014-03-27 14:33:30 +0000587 PreviousNonComment->isNot(tok::r_brace))
588 // Ensure that we fall back to the continuation indent width instead of
589 // just flushing continuations left.
590 return State.Stack.back().Indent + Style.ContinuationIndentWidth;
591 return State.Stack.back().Indent;
592}
593
Daniel Jasperde0328a2013-08-16 11:20:30 +0000594unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
595 bool DryRun, bool Newline) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000596 assert(State.Stack.size());
Daniel Jasper60553be2014-05-26 13:10:39 +0000597 const FormatToken &Current = *State.NextToken;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000598
599 if (Current.Type == TT_InheritanceColon)
600 State.Stack.back().AvoidBinPacking = true;
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000601 if (Current.is(tok::lessless) && Current.Type != TT_OverloadedOperator) {
602 if (State.Stack.back().FirstLessLess == 0)
603 State.Stack.back().FirstLessLess = State.Column;
604 else
605 State.Stack.back().LastOperatorWrapped = Newline;
606 }
607 if ((Current.Type == TT_BinaryOperator && Current.isNot(tok::lessless)) ||
608 Current.Type == TT_ConditionalExpr)
609 State.Stack.back().LastOperatorWrapped = Newline;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000610 if (Current.Type == TT_ArraySubscriptLSquare &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000611 State.Stack.back().StartOfArraySubscripts == 0)
612 State.Stack.back().StartOfArraySubscripts = State.Column;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000613 if ((Current.is(tok::question) && Style.BreakBeforeTernaryOperators) ||
614 (Current.getPreviousNonComment() && Current.isNot(tok::colon) &&
615 Current.getPreviousNonComment()->is(tok::question) &&
616 !Style.BreakBeforeTernaryOperators))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000617 State.Stack.back().QuestionColumn = State.Column;
618 if (!Current.opensScope() && !Current.closesScope())
619 State.LowestLevelOnLine =
Daniel Jasper05cd5862014-05-08 12:21:30 +0000620 std::min(State.LowestLevelOnLine, Current.NestingLevel);
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000621 if (Current.isMemberAccess())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000622 State.Stack.back().StartOfFunctionCall =
Daniel Jasper0e617842014-04-16 12:26:54 +0000623 Current.LastOperator ? 0 : State.Column + Current.ColumnWidth;
Daniel Jasper17062ff2014-06-10 14:44:02 +0000624 if (Current.Type == TT_SelectorName)
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000625 State.Stack.back().ObjCSelectorNameFound = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000626 if (Current.Type == TT_CtorInitializerColon) {
627 // Indent 2 from the column, so:
628 // SomeClass::SomeClass()
629 // : First(...), ...
630 // Next(...)
631 // ^ line up here.
632 State.Stack.back().Indent =
633 State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
634 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
635 State.Stack.back().AvoidBinPacking = true;
636 State.Stack.back().BreakBeforeParameter = false;
637 }
638
Daniel Jasperde0328a2013-08-16 11:20:30 +0000639 // In ObjC method declaration we align on the ":" of parameters, but we need
Daniel Jasper6633ab82013-10-18 10:38:14 +0000640 // to ensure that we indent parameters on subsequent lines by at least our
641 // continuation indent width.
Daniel Jasperde0328a2013-08-16 11:20:30 +0000642 if (Current.Type == TT_ObjCMethodSpecifier)
Daniel Jasper6633ab82013-10-18 10:38:14 +0000643 State.Stack.back().Indent += Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000644
645 // Insert scopes created by fake parenthesis.
646 const FormatToken *Previous = Current.getPreviousNonComment();
Daniel Jasperb16b9692014-05-21 12:51:23 +0000647
648 // Add special behavior to support a format commonly used for JavaScript
649 // closures:
650 // SomeFunction(function() {
651 // foo();
652 // bar();
653 // }, a, b, c);
654 if (Style.Language == FormatStyle::LK_JavaScript) {
655 if (Current.isNot(tok::comment) && Previous && Previous->is(tok::l_brace) &&
656 State.Stack.size() > 1) {
657 if (State.Stack[State.Stack.size() - 2].JSFunctionInlined && Newline) {
658 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
659 State.Stack[i].NoLineBreak = true;
660 }
661 }
662 State.Stack[State.Stack.size() - 2].JSFunctionInlined = false;
663 }
664 if (Current.TokenText == "function")
Daniel Jasper90ebc982014-09-05 09:27:38 +0000665 State.Stack.back().JSFunctionInlined =
Daniel Jasper1779d432014-09-29 07:54:54 +0000666 !Newline && Previous && Previous->Type != TT_DictLiteral &&
667 // If the unnamed function is the only parameter to another function,
668 // we can likely inline it and come up with a good format.
669 (Previous->isNot(tok::l_paren) || Previous->ParameterCount > 1);
Daniel Jasperb16b9692014-05-21 12:51:23 +0000670 }
671
Daniel Jasper60553be2014-05-26 13:10:39 +0000672 moveStatePastFakeLParens(State, Newline);
673 moveStatePastScopeOpener(State, Newline);
674 moveStatePastScopeCloser(State);
675 moveStatePastFakeRParens(State);
676
677 if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) {
678 State.StartOfStringLiteral = State.Column;
679 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
680 !Current.isStringLiteral()) {
681 State.StartOfStringLiteral = 0;
682 }
683
684 State.Column += Current.ColumnWidth;
685 State.NextToken = State.NextToken->Next;
686 unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
687 if (State.Column > getColumnLimit(State)) {
688 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
689 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
690 }
691
692 if (Current.Role)
693 Current.Role->formatFromToken(State, this, DryRun);
694 // If the previous has a special role, let it consume tokens as appropriate.
695 // It is necessary to start at the previous token for the only implemented
696 // role (comma separated list). That way, the decision whether or not to break
697 // after the "{" is already done and both options are tried and evaluated.
698 // FIXME: This is ugly, find a better way.
699 if (Previous && Previous->Role)
700 Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
701
702 return Penalty;
703}
704
705void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
706 bool Newline) {
707 const FormatToken &Current = *State.NextToken;
708 const FormatToken *Previous = Current.getPreviousNonComment();
709
Daniel Jasperde0328a2013-08-16 11:20:30 +0000710 // Don't add extra indentation for the first fake parenthesis after
Dinesh Dwivedi0db806b2014-05-01 17:19:34 +0000711 // 'return', assignments or opening <({[. The indentation for these cases
Daniel Jasperde0328a2013-08-16 11:20:30 +0000712 // is special cased.
713 bool SkipFirstExtraIndent =
Daniel Jaspereabede62013-09-30 08:29:03 +0000714 (Previous && (Previous->opensScope() || Previous->is(tok::kw_return) ||
Daniel Jasperf48b5ab2013-11-07 19:23:49 +0000715 Previous->getPrecedence() == prec::Assignment ||
716 Previous->Type == TT_ObjCMethodExpr));
Daniel Jasperde0328a2013-08-16 11:20:30 +0000717 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
718 I = Current.FakeLParens.rbegin(),
719 E = Current.FakeLParens.rend();
720 I != E; ++I) {
721 ParenState NewParenState = State.Stack.back();
722 NewParenState.ContainsLineBreak = false;
Daniel Jaspereabede62013-09-30 08:29:03 +0000723
724 // Indent from 'LastSpace' unless this the fake parentheses encapsulating a
725 // builder type call after 'return'. If such a call is line-wrapped, we
726 // commonly just want to indent from the start of the line.
Daniel Jasper4281c5a2014-10-07 14:45:34 +0000727 if (!Current.isTrailingComment() &&
728 (!Previous || Previous->isNot(tok::kw_return) || *I > 0))
Daniel Jaspereabede62013-09-30 08:29:03 +0000729 NewParenState.Indent =
730 std::max(std::max(State.Column, NewParenState.Indent),
731 State.Stack.back().LastSpace);
732
Daniel Jasper5c332652014-04-03 12:00:33 +0000733 // Don't allow the RHS of an operator to be split over multiple lines unless
734 // there is a line-break right after the operator.
735 // Exclude relational operators, as there, it is always more desirable to
736 // have the LHS 'left' of the RHS.
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000737 if (Previous && Previous->getPrecedence() > prec::Assignment &&
738 (Previous->Type == TT_BinaryOperator ||
739 Previous->Type == TT_ConditionalExpr) &&
740 Previous->getPrecedence() != prec::Relational) {
741 bool BreakBeforeOperator = Previous->is(tok::lessless) ||
742 (Previous->Type == TT_BinaryOperator &&
743 Style.BreakBeforeBinaryOperators) ||
744 (Previous->Type == TT_ConditionalExpr &&
745 Style.BreakBeforeTernaryOperators);
746 if ((!Newline && !BreakBeforeOperator) ||
747 (!State.Stack.back().LastOperatorWrapped && BreakBeforeOperator))
748 NewParenState.NoLineBreak = true;
749 }
Daniel Jasper5c332652014-04-03 12:00:33 +0000750
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000751 // Do not indent relative to the fake parentheses inserted for "." or "->".
752 // This is a special case to make the following to statements consistent:
753 // OuterFunction(InnerFunctionCall( // break
754 // ParameterToInnerFunction));
755 // OuterFunction(SomeObject.InnerFunctionCall( // break
756 // ParameterToInnerFunction));
757 if (*I > prec::Unknown)
758 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
Daniel Jasper96964352013-12-18 10:44:36 +0000759 NewParenState.StartOfFunctionCall = State.Column;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000760
761 // Always indent conditional expressions. Never indent expression where
762 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
763 // prec::Assignment) as those have different indentation rules. Indent
764 // other expression, unless the indentation needs to be skipped.
765 if (*I == prec::Conditional ||
766 (!SkipFirstExtraIndent && *I > prec::Assignment &&
Daniel Jasper4281c5a2014-10-07 14:45:34 +0000767 !Current.isTrailingComment() && !Style.BreakBeforeBinaryOperators))
Daniel Jasper6633ab82013-10-18 10:38:14 +0000768 NewParenState.Indent += Style.ContinuationIndentWidth;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000769 if ((Previous && !Previous->opensScope()) || *I > prec::Comma)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000770 NewParenState.BreakBeforeParameter = false;
771 State.Stack.push_back(NewParenState);
772 SkipFirstExtraIndent = false;
773 }
Daniel Jasper60553be2014-05-26 13:10:39 +0000774}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000775
Daniel Jasper335ff262014-05-28 09:11:53 +0000776// Remove the fake r_parens after 'Tok'.
777static void consumeRParens(LineState& State, const FormatToken &Tok) {
778 for (unsigned i = 0, e = Tok.FakeRParens; i != e; ++i) {
779 unsigned VariablePos = State.Stack.back().VariablePos;
780 assert(State.Stack.size() > 1);
781 if (State.Stack.size() == 1) {
782 // Do not pop the last element.
783 break;
784 }
785 State.Stack.pop_back();
786 State.Stack.back().VariablePos = VariablePos;
787 }
788}
789
790// Returns whether 'Tok' opens or closes a scope requiring special handling
791// of the subsequent fake r_parens.
792//
793// For example, if this is an l_brace starting a nested block, we pretend (wrt.
794// to indentation) that we already consumed the corresponding r_brace. Thus, we
795// remove all ParenStates caused by fake parentheses that end at the r_brace.
796// The net effect of this is that we don't indent relative to the l_brace, if
797// the nested block is the last parameter of a function. This formats:
798//
799// SomeFunction(a, [] {
800// f(); // break
801// });
802//
803// instead of:
804// SomeFunction(a, [] {
805// f(); // break
806// });
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000807static bool fakeRParenSpecialCase(const LineState &State) {
808 const FormatToken &Tok = *State.NextToken;
Daniel Jasper335ff262014-05-28 09:11:53 +0000809 if (!Tok.MatchingParen)
810 return false;
811 const FormatToken *Left = &Tok;
812 if (Tok.isOneOf(tok::r_brace, tok::r_square))
813 Left = Tok.MatchingParen;
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000814 return !State.Stack.back().HasMultipleNestedBlocks &&
815 Left->isOneOf(tok::l_brace, tok::l_square) &&
Daniel Jasper335ff262014-05-28 09:11:53 +0000816 (Left->BlockKind == BK_Block ||
817 Left->Type == TT_ArrayInitializerLSquare ||
818 Left->Type == TT_DictLiteral);
819}
820
Daniel Jasper60553be2014-05-26 13:10:39 +0000821void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
Daniel Jasper335ff262014-05-28 09:11:53 +0000822 // Don't remove FakeRParens attached to r_braces that surround nested blocks
823 // as they will have been removed early (see above).
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000824 if (fakeRParenSpecialCase(State))
Daniel Jasper335ff262014-05-28 09:11:53 +0000825 return;
826
827 consumeRParens(State, *State.NextToken);
Daniel Jasper60553be2014-05-26 13:10:39 +0000828}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000829
Daniel Jasper60553be2014-05-26 13:10:39 +0000830void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
831 bool Newline) {
832 const FormatToken &Current = *State.NextToken;
833 if (!Current.opensScope())
834 return;
835
836 if (Current.MatchingParen && Current.BlockKind == BK_Block) {
837 moveStateToNewBlock(State);
838 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000839 }
840
Daniel Jasper60553be2014-05-26 13:10:39 +0000841 unsigned NewIndent;
842 unsigned NewIndentLevel = State.Stack.back().IndentLevel;
843 bool AvoidBinPacking;
844 bool BreakBeforeParameter = false;
845 if (Current.is(tok::l_brace) || Current.Type == TT_ArrayInitializerLSquare) {
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000846 if (fakeRParenSpecialCase(State))
Daniel Jasper335ff262014-05-28 09:11:53 +0000847 consumeRParens(State, *Current.MatchingParen);
848
Daniel Jasper60553be2014-05-26 13:10:39 +0000849 NewIndent = State.Stack.back().LastSpace;
850 if (Current.opensBlockTypeList(Style)) {
851 NewIndent += Style.IndentWidth;
852 NewIndent = std::min(State.Column + 2, NewIndent);
853 ++NewIndentLevel;
854 } else {
855 NewIndent += Style.ContinuationIndentWidth;
856 NewIndent = std::min(State.Column + 1, NewIndent);
857 }
858 const FormatToken *NextNoComment = Current.getNextNonComment();
859 AvoidBinPacking = Current.Type == TT_ArrayInitializerLSquare ||
860 Current.Type == TT_DictLiteral ||
861 Style.Language == FormatStyle::LK_Proto ||
862 !Style.BinPackParameters ||
863 (NextNoComment &&
864 NextNoComment->Type == TT_DesignatedInitializerPeriod);
865 } else {
866 NewIndent = Style.ContinuationIndentWidth +
867 std::max(State.Stack.back().LastSpace,
868 State.Stack.back().StartOfFunctionCall);
Daniel Jasper18210d72014-10-09 09:52:05 +0000869 AvoidBinPacking =
870 (State.Line->MustBeDeclaration && !Style.BinPackParameters) ||
871 (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||
872 (Style.ExperimentalAutoDetectBinPacking &&
873 (Current.PackingKind == PPK_OnePerLine ||
874 (!BinPackInconclusiveFunctions &&
875 Current.PackingKind == PPK_Inconclusive)));
Daniel Jasper60553be2014-05-26 13:10:39 +0000876 // If this '[' opens an ObjC call, determine whether all parameters fit
877 // into one line and put one per line if they don't.
878 if (Current.Type == TT_ObjCMethodExpr && Style.ColumnLimit != 0 &&
879 getLengthToMatchingParen(Current) + State.Column >
880 getColumnLimit(State))
881 BreakBeforeParameter = true;
882 }
Daniel Jaspera41aa532014-09-19 08:01:25 +0000883 bool NoLineBreak = State.Stack.back().NoLineBreak ||
884 (Current.Type == TT_TemplateOpener &&
885 State.Stack.back().ContainsUnwrappedBuilder);
Daniel Jasper60553be2014-05-26 13:10:39 +0000886 State.Stack.push_back(ParenState(NewIndent, NewIndentLevel,
887 State.Stack.back().LastSpace,
888 AvoidBinPacking, NoLineBreak));
889 State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000890 State.Stack.back().HasMultipleNestedBlocks = Current.BlockParameterCount > 1;
Daniel Jasper60553be2014-05-26 13:10:39 +0000891}
892
893void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
894 const FormatToken &Current = *State.NextToken;
895 if (!Current.closesScope())
896 return;
897
898 // If we encounter a closing ), ], } or >, we can remove a level from our
899 // stacks.
900 if (State.Stack.size() > 1 &&
901 (Current.isOneOf(tok::r_paren, tok::r_square) ||
902 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
Daniel Jasper335ff262014-05-28 09:11:53 +0000903 State.NextToken->Type == TT_TemplateCloser))
Daniel Jasper60553be2014-05-26 13:10:39 +0000904 State.Stack.pop_back();
Daniel Jasper335ff262014-05-28 09:11:53 +0000905
Daniel Jasper60553be2014-05-26 13:10:39 +0000906 if (Current.is(tok::r_square)) {
907 // If this ends the array subscript expr, reset the corresponding value.
908 const FormatToken *NextNonComment = Current.getNextNonComment();
909 if (NextNonComment && NextNonComment->isNot(tok::l_square))
910 State.Stack.back().StartOfArraySubscripts = 0;
911 }
912}
913
914void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
Daniel Jasper60553be2014-05-26 13:10:39 +0000915 // If we have already found more than one lambda introducers on this level, we
916 // opt out of this because similarity between the lambdas is more important.
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000917 if (fakeRParenSpecialCase(State))
Daniel Jasper335ff262014-05-28 09:11:53 +0000918 consumeRParens(State, *State.NextToken->MatchingParen);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000919
Daniel Jasper60553be2014-05-26 13:10:39 +0000920 // For some reason, ObjC blocks are indented like continuations.
921 unsigned NewIndent = State.Stack.back().LastSpace +
922 (State.NextToken->Type == TT_ObjCBlockLBrace
923 ? Style.ContinuationIndentWidth
924 : Style.IndentWidth);
925 State.Stack.push_back(ParenState(
926 NewIndent, /*NewIndentLevel=*/State.Stack.back().IndentLevel + 1,
927 State.Stack.back().LastSpace, /*AvoidBinPacking=*/true,
928 State.Stack.back().NoLineBreak));
929 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000930}
931
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000932unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
933 LineState &State) {
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000934 // Break before further function parameters on all levels.
935 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
936 State.Stack[i].BreakBeforeParameter = true;
937
Alexander Kornienko39856b72013-09-10 09:38:25 +0000938 unsigned ColumnsUsed = State.Column;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000939 // We can only affect layout of the first and the last line, so the penalty
940 // for all other lines is constant, and we ignore it.
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000941 State.Column = Current.LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000942
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000943 if (ColumnsUsed > getColumnLimit(State))
944 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000945 return 0;
946}
947
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000948static bool getRawStringLiteralPrefixPostfix(StringRef Text, StringRef &Prefix,
Alexander Kornienko81e32942013-09-16 20:20:49 +0000949 StringRef &Postfix) {
950 if (Text.startswith(Prefix = "R\"") || Text.startswith(Prefix = "uR\"") ||
951 Text.startswith(Prefix = "UR\"") || Text.startswith(Prefix = "u8R\"") ||
952 Text.startswith(Prefix = "LR\"")) {
953 size_t ParenPos = Text.find('(');
954 if (ParenPos != StringRef::npos) {
955 StringRef Delimiter =
956 Text.substr(Prefix.size(), ParenPos - Prefix.size());
957 Prefix = Text.substr(0, ParenPos + 1);
958 Postfix = Text.substr(Text.size() - 2 - Delimiter.size());
959 return Postfix.front() == ')' && Postfix.back() == '"' &&
960 Postfix.substr(1).startswith(Delimiter);
961 }
962 }
963 return false;
964}
965
Daniel Jasperde0328a2013-08-16 11:20:30 +0000966unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
967 LineState &State,
968 bool DryRun) {
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000969 // Don't break multi-line tokens other than block comments. Instead, just
970 // update the state.
971 if (Current.Type != TT_BlockComment && Current.IsMultiline)
972 return addMultilineToken(Current, State);
973
Daniel Jasper98857842013-10-30 13:54:53 +0000974 // Don't break implicit string literals.
975 if (Current.Type == TT_ImplicitStringLiteral)
976 return 0;
977
Daniel Jasper04b6a082013-12-20 06:22:01 +0000978 if (!Current.isStringLiteral() && !Current.is(tok::comment))
Daniel Jasperf93551c2013-08-23 10:05:49 +0000979 return 0;
980
Ahmed Charlesb8984322014-03-07 20:03:18 +0000981 std::unique_ptr<BreakableToken> Token;
Alexander Kornienko39856b72013-09-10 09:38:25 +0000982 unsigned StartColumn = State.Column - Current.ColumnWidth;
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000983 unsigned ColumnLimit = getColumnLimit(State);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000984
Daniel Jasper04b6a082013-12-20 06:22:01 +0000985 if (Current.isStringLiteral()) {
Alexander Kornienko384b40b2013-10-11 21:43:05 +0000986 // Don't break string literals inside preprocessor directives (except for
987 // #define directives, as their contents are stored in separate lines and
988 // are not affected by this check).
989 // This way we avoid breaking code with line directives and unknown
990 // preprocessor directives that contain long string literals.
991 if (State.Line->Type == LT_PreprocessorDirective)
992 return 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000993 // Exempts unterminated string literals from line breaking. The user will
994 // likely want to terminate the string before any line breaking is done.
995 if (Current.IsUnterminatedLiteral)
996 return 0;
997
Alexander Kornienko81e32942013-09-16 20:20:49 +0000998 StringRef Text = Current.TokenText;
999 StringRef Prefix;
1000 StringRef Postfix;
Daniel Jasper174b0122014-01-09 14:18:12 +00001001 bool IsNSStringLiteral = false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001002 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
1003 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
1004 // reduce the overhead) for each FormatToken, which is a string, so that we
1005 // don't run multiple checks here on the hot path.
Daniel Jasper174b0122014-01-09 14:18:12 +00001006 if (Text.startswith("\"") && Current.Previous &&
1007 Current.Previous->is(tok::at)) {
1008 IsNSStringLiteral = true;
1009 Prefix = "@\"";
Daniel Jasper174b0122014-01-09 14:18:12 +00001010 }
Alexander Kornienko81e32942013-09-16 20:20:49 +00001011 if ((Text.endswith(Postfix = "\"") &&
Daniel Jasper174b0122014-01-09 14:18:12 +00001012 (IsNSStringLiteral || Text.startswith(Prefix = "\"") ||
1013 Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
1014 Text.startswith(Prefix = "u8\"") ||
Alexander Kornienko81e32942013-09-16 20:20:49 +00001015 Text.startswith(Prefix = "L\""))) ||
1016 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")")) ||
1017 getRawStringLiteralPrefixPostfix(Text, Prefix, Postfix)) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001018 Token.reset(new BreakableStringLiteral(
1019 Current, State.Line->Level, StartColumn, Prefix, Postfix,
1020 State.Line->InPPDirective, Encoding, Style));
Alexander Kornienko81e32942013-09-16 20:20:49 +00001021 } else {
1022 return 0;
1023 }
Daniel Jasperde0328a2013-08-16 11:20:30 +00001024 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
Alexander Kornienkoce9161a2014-01-02 15:13:14 +00001025 if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
1026 return 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001027 Token.reset(new BreakableBlockComment(
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001028 Current, State.Line->Level, StartColumn, Current.OriginalColumn,
1029 !Current.Previous, State.Line->InPPDirective, Encoding, Style));
Daniel Jasperde0328a2013-08-16 11:20:30 +00001030 } else if (Current.Type == TT_LineComment &&
Craig Topper2145bc02014-05-09 08:15:10 +00001031 (Current.Previous == nullptr ||
Daniel Jasperde0328a2013-08-16 11:20:30 +00001032 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienkoce9161a2014-01-02 15:13:14 +00001033 if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
1034 return 0;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001035 Token.reset(new BreakableLineComment(Current, State.Line->Level,
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001036 StartColumn, /*InPPDirective=*/false,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001037 Encoding, Style));
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001038 // We don't insert backslashes when breaking line comments.
1039 ColumnLimit = Style.ColumnLimit;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001040 } else {
1041 return 0;
1042 }
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001043 if (Current.UnbreakableTailLength >= ColumnLimit)
Daniel Jasperde0328a2013-08-16 11:20:30 +00001044 return 0;
1045
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001046 unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001047 bool BreakInserted = false;
1048 unsigned Penalty = 0;
1049 unsigned RemainingTokenColumns = 0;
1050 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
1051 LineIndex != EndIndex; ++LineIndex) {
1052 if (!DryRun)
1053 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
1054 unsigned TailOffset = 0;
1055 RemainingTokenColumns =
1056 Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
1057 while (RemainingTokenColumns > RemainingSpace) {
1058 BreakableToken::Split Split =
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001059 Token->getSplit(LineIndex, TailOffset, ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +00001060 if (Split.first == StringRef::npos) {
1061 // The last line's penalty is handled in addNextStateToQueue().
1062 if (LineIndex < EndIndex - 1)
1063 Penalty += Style.PenaltyExcessCharacter *
1064 (RemainingTokenColumns - RemainingSpace);
1065 break;
1066 }
1067 assert(Split.first != 0);
1068 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
1069 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
Alexander Kornienko875395f2013-11-12 17:50:13 +00001070
1071 // We can remove extra whitespace instead of breaking the line.
1072 if (RemainingTokenColumns + 1 - Split.second <= RemainingSpace) {
1073 RemainingTokenColumns = 0;
1074 if (!DryRun)
1075 Token->replaceWhitespace(LineIndex, TailOffset, Split, Whitespaces);
1076 break;
1077 }
1078
Alexander Kornienko64a42b82014-04-15 14:52:43 +00001079 // When breaking before a tab character, it may be moved by a few columns,
1080 // but will still be expanded to the next tab stop, so we don't save any
1081 // columns.
1082 if (NewRemainingTokenColumns == RemainingTokenColumns)
1083 break;
1084
Daniel Jasperde0328a2013-08-16 11:20:30 +00001085 assert(NewRemainingTokenColumns < RemainingTokenColumns);
1086 if (!DryRun)
1087 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Daniel Jasper2739af32013-08-28 10:03:58 +00001088 Penalty += Current.SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001089 unsigned ColumnsUsed =
1090 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001091 if (ColumnsUsed > ColumnLimit) {
1092 Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +00001093 }
1094 TailOffset += Split.first + Split.second;
1095 RemainingTokenColumns = NewRemainingTokenColumns;
1096 BreakInserted = true;
1097 }
1098 }
1099
1100 State.Column = RemainingTokenColumns;
1101
1102 if (BreakInserted) {
1103 // If we break the token inside a parameter list, we need to break before
1104 // the next parameter on all levels, so that the next parameter is clearly
1105 // visible. Line comments already introduce a break.
1106 if (Current.Type != TT_LineComment) {
1107 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1108 State.Stack[i].BreakBeforeParameter = true;
1109 }
1110
Daniel Jasper04b6a082013-12-20 06:22:01 +00001111 Penalty += Current.isStringLiteral() ? Style.PenaltyBreakString
1112 : Style.PenaltyBreakComment;
Daniel Jasper2739af32013-08-28 10:03:58 +00001113
Daniel Jasperde0328a2013-08-16 11:20:30 +00001114 State.Stack.back().LastSpace = StartColumn;
1115 }
1116 return Penalty;
1117}
1118
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001119unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001120 // In preprocessor directives reserve two chars for trailing " \"
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001121 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
Daniel Jasperde0328a2013-08-16 11:20:30 +00001122}
1123
Daniel Jasperc39b56f2013-12-16 07:23:08 +00001124bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
Daniel Jasperf438cb72013-08-23 11:57:34 +00001125 const FormatToken &Current = *State.NextToken;
Daniel Jasper9509f182014-05-05 08:08:07 +00001126 if (!Current.isStringLiteral() || Current.Type == TT_ImplicitStringLiteral)
Daniel Jasperf438cb72013-08-23 11:57:34 +00001127 return false;
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00001128 // We never consider raw string literals "multiline" for the purpose of
Daniel Jasperc39b56f2013-12-16 07:23:08 +00001129 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
1130 // (see TokenAnnotator::mustBreakBefore().
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00001131 if (Current.TokenText.startswith("R\""))
1132 return false;
Alexander Kornienko39856b72013-09-10 09:38:25 +00001133 if (Current.IsMultiline)
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00001134 return true;
Daniel Jasperf438cb72013-08-23 11:57:34 +00001135 if (Current.getNextNonComment() &&
Daniel Jasper04b6a082013-12-20 06:22:01 +00001136 Current.getNextNonComment()->isStringLiteral())
Daniel Jasperf438cb72013-08-23 11:57:34 +00001137 return true; // Implicit concatenation.
Alexander Kornienko39856b72013-09-10 09:38:25 +00001138 if (State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
Daniel Jasperf438cb72013-08-23 11:57:34 +00001139 Style.ColumnLimit)
1140 return true; // String will be split.
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00001141 return false;
Daniel Jasperf438cb72013-08-23 11:57:34 +00001142}
1143
Daniel Jasperde0328a2013-08-16 11:20:30 +00001144} // namespace format
1145} // namespace clang