blob: 24680ae76ca845f493aab1d65e2c6260249cbc35 [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,
Daniel Jasperd0ec0d62014-11-04 12:41:02 +000060 const AdditionalKeywords &Keywords,
Daniel Jasperde0328a2013-08-16 11:20:30 +000061 SourceManager &SourceMgr,
Daniel Jasperde0328a2013-08-16 11:20:30 +000062 WhitespaceManager &Whitespaces,
63 encoding::Encoding Encoding,
64 bool BinPackInconclusiveFunctions)
Daniel Jasperd0ec0d62014-11-04 12:41:02 +000065 : Style(Style), Keywords(Keywords), SourceMgr(SourceMgr),
66 Whitespaces(Whitespaces), Encoding(Encoding),
Alexander Kornienkoce9161a2014-01-02 15:13:14 +000067 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
68 CommentPragmasRegex(Style.CommentPragmas) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +000069
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000070LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
Daniel Jasper1c5d9df2013-09-06 07:54:20 +000071 const AnnotatedLine *Line,
72 bool DryRun) {
Daniel Jasperde0328a2013-08-16 11:20:30 +000073 LineState State;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000074 State.FirstIndent = FirstIndent;
Daniel Jasperde0328a2013-08-16 11:20:30 +000075 State.Column = FirstIndent;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000076 State.Line = Line;
77 State.NextToken = Line->First;
Alexander Kornienkoe2e03872013-10-14 00:46:35 +000078 State.Stack.push_back(ParenState(FirstIndent, Line->Level, FirstIndent,
Daniel Jasperde0328a2013-08-16 11:20:30 +000079 /*AvoidBinPacking=*/false,
80 /*NoLineBreak=*/false));
81 State.LineContainsContinuedForLoopSection = false;
Daniel Jasperde0328a2013-08-16 11:20:30 +000082 State.StartOfStringLiteral = 0;
Daniel Jasper05cd5862014-05-08 12:21:30 +000083 State.StartOfLineLevel = 0;
84 State.LowestLevelOnLine = 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +000085 State.IgnoreStackForComparison = false;
86
87 // The first token has already been indented and thus consumed.
Daniel Jasper1c5d9df2013-09-06 07:54:20 +000088 moveStateToNextToken(State, DryRun, /*Newline=*/false);
Daniel Jasperde0328a2013-08-16 11:20:30 +000089 return State;
90}
91
92bool ContinuationIndenter::canBreak(const LineState &State) {
93 const FormatToken &Current = *State.NextToken;
94 const FormatToken &Previous = *Current.Previous;
95 assert(&Previous == Current.Previous);
Daniel Jasper1db6c382013-10-22 15:30:28 +000096 if (!Current.CanBreakBefore && !(State.Stack.back().BreakBeforeClosingBrace &&
97 Current.closesBlockTypeList(Style)))
Daniel Jasperde0328a2013-08-16 11:20:30 +000098 return false;
99 // The opening "{" of a braced list has to be on the same line as the first
100 // element if it is nested in another braced init list or function call.
101 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000102 Previous.Type != TT_DictLiteral && Previous.BlockKind == BK_BracedInit &&
103 Previous.Previous &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000104 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
105 return false;
106 // This prevents breaks like:
107 // ...
108 // SomeParameter, OtherParameter).DoSomething(
109 // ...
110 // As they hide "DoSomething" and are generally bad for readability.
Daniel Jasper8f59ae52014-03-11 11:03:26 +0000111 if (Previous.opensScope() && Previous.isNot(tok::l_brace) &&
Daniel Jasperfcfac102014-07-15 09:00:34 +0000112 State.LowestLevelOnLine < State.StartOfLineLevel &&
113 State.LowestLevelOnLine < Current.NestingLevel)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000114 return false;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000115 if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
116 return false;
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000117
118 // Don't create a 'hanging' indent if there are multiple blocks in a single
119 // statement.
120 if (Style.Language == FormatStyle::LK_JavaScript &&
121 Previous.is(tok::l_brace) && State.Stack.size() > 1 &&
122 State.Stack[State.Stack.size() - 2].JSFunctionInlined &&
123 State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks)
124 return false;
125
Daniel Jaspere068ac72014-10-27 17:13:59 +0000126 // Don't break after very short return types (e.g. "void") as that is often
127 // unexpected.
128 if (Current.Type == TT_FunctionDeclarationName &&
129 !Style.AlwaysBreakAfterDefinitionReturnType && State.Column < 6)
130 return false;
131
Daniel Jasperde0328a2013-08-16 11:20:30 +0000132 return !State.Stack.back().NoLineBreak;
133}
134
135bool ContinuationIndenter::mustBreak(const LineState &State) {
136 const FormatToken &Current = *State.NextToken;
137 const FormatToken &Previous = *Current.Previous;
138 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
139 return true;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000140 if (State.Stack.back().BreakBeforeClosingBrace &&
141 Current.closesBlockTypeList(Style))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000142 return true;
143 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
144 return true;
Daniel Jasperec01cd62013-10-08 05:11:18 +0000145 if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
Daniel Jasper165b29e2013-11-08 00:57:11 +0000146 (Style.BreakBeforeTernaryOperators &&
147 (Current.is(tok::question) || (Current.Type == TT_ConditionalExpr &&
148 Previous.isNot(tok::question)))) ||
149 (!Style.BreakBeforeTernaryOperators &&
150 (Previous.is(tok::question) || Previous.Type == TT_ConditionalExpr))) &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000151 State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
152 !Current.isOneOf(tok::r_paren, tok::r_brace))
153 return true;
154 if (Style.AlwaysBreakBeforeMultilineStrings &&
Daniel Jasperf438cb72013-08-23 11:57:34 +0000155 State.Column > State.Stack.back().Indent && // Breaking saves columns.
Daniel Jasper27943052013-11-09 03:08:25 +0000156 !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) &&
Daniel Jasper3251fff2014-06-10 06:27:23 +0000157 Previous.Type != TT_InlineASMColon &&
158 Previous.Type != TT_ConditionalExpr && nextIsMultilineString(State))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000159 return true;
Daniel Jasperce2fdb02014-10-27 13:25:59 +0000160 if (((Previous.Type == TT_DictLiteral && Previous.is(tok::l_brace)) ||
Daniel Jasper1db6c382013-10-22 15:30:28 +0000161 Previous.Type == TT_ArrayInitializerLSquare) &&
Daniel Jasperdb8804b2014-04-14 12:11:07 +0000162 Style.ColumnLimit > 0 &&
Daniel Jasperd489dd32013-10-20 16:45:46 +0000163 getLengthToMatchingParen(Previous) + State.Column > getColumnLimit(State))
164 return true;
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000165 if (Current.Type == TT_CtorInitializerColon &&
Daniel Jasperd74cf402014-04-08 12:46:38 +0000166 ((Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All) ||
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000167 Style.BreakConstructorInitializersBeforeComma || Style.ColumnLimit != 0))
168 return true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000169
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000170 if (State.Column < getNewLineColumn(State))
171 return false;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000172 if (!Style.BreakBeforeBinaryOperators) {
173 // If we need to break somewhere inside the LHS of a binary expression, we
174 // should also break after the operator. Otherwise, the formatting would
175 // hide the operator precedence, e.g. in:
176 // if (aaaaaaaaaaaaaa ==
177 // bbbbbbbbbbbbbb && c) {..
178 // For comparisons, we only apply this rule, if the LHS is a binary
179 // expression itself as otherwise, the line breaks seem superfluous.
180 // We need special cases for ">>" which we have split into two ">" while
181 // lexing in order to make template parsing easier.
182 //
183 // FIXME: We'll need something similar for styles that break before binary
184 // operators.
185 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
186 Previous.getPrecedence() == prec::Equality) &&
187 Previous.Previous &&
188 Previous.Previous->Type != TT_BinaryOperator; // For >>.
189 bool LHSIsBinaryExpr =
Daniel Jasper562ecd42013-09-06 08:08:14 +0000190 Previous.Previous && Previous.Previous->EndsBinaryExpression;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000191 if (Previous.Type == TT_BinaryOperator &&
192 (!IsComparison || LHSIsBinaryExpr) &&
193 Current.Type != TT_BinaryOperator && // For >>.
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000194 !Current.isTrailingComment() && !Previous.is(tok::lessless) &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000195 Previous.getPrecedence() != prec::Assignment &&
196 State.Stack.back().BreakBeforeParameter)
197 return true;
198 }
199
200 // Same as above, but for the first "<<" operator.
Alexander Kornienko86b2dfd2014-03-06 15:13:08 +0000201 if (Current.is(tok::lessless) && Current.Type != TT_OverloadedOperator &&
202 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000203 State.Stack.back().FirstLessLess == 0)
204 return true;
205
Daniel Jasper17062ff2014-06-10 14:44:02 +0000206 if (Current.Type == TT_SelectorName &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000207 State.Stack.back().ObjCSelectorNameFound &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000208 State.Stack.back().BreakBeforeParameter)
209 return true;
Daniel Jasper05cd5862014-05-08 12:21:30 +0000210 if (Previous.ClosesTemplateDeclaration && Current.NestingLevel == 0 &&
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000211 !Current.isTrailingComment())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000212 return true;
213
Daniel Jasper4355e7f2014-07-09 07:50:33 +0000214 // If the return type spans multiple lines, wrap before the function name.
215 if ((Current.Type == TT_FunctionDeclarationName ||
216 Current.is(tok::kw_operator)) &&
217 State.Stack.back().BreakBeforeParameter)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000218 return true;
Daniel Jasper4355e7f2014-07-09 07:50:33 +0000219
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000220 if (startsSegmentOfBuilderTypeCall(Current) &&
Daniel Jasperf8151e92013-08-30 07:12:40 +0000221 (State.Stack.back().CallContinuation != 0 ||
222 (State.Stack.back().BreakBeforeParameter &&
223 State.Stack.back().ContainsUnwrappedBuilder)))
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000224 return true;
Daniel Jasper96972812014-01-05 12:38:10 +0000225
226 // The following could be precomputed as they do not depend on the state.
227 // However, as they should take effect only if the UnwrappedLine does not fit
228 // into the ColumnLimit, they are checked here in the ContinuationIndenter.
Daniel Jasper35995672014-04-29 14:05:20 +0000229 if (Style.ColumnLimit != 0 && Previous.BlockKind == BK_Block &&
230 Previous.is(tok::l_brace) && !Current.isOneOf(tok::r_brace, tok::comment))
Daniel Jasper96972812014-01-05 12:38:10 +0000231 return true;
Daniel Jasper96972812014-01-05 12:38:10 +0000232
Daniel Jasperde0328a2013-08-16 11:20:30 +0000233 return false;
234}
235
236unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000237 bool DryRun,
238 unsigned ExtraSpaces) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000239 const FormatToken &Current = *State.NextToken;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000240
Manuel Klimek819788d2014-03-18 11:22:45 +0000241 assert(!State.Stack.empty());
242 if ((Current.Type == TT_ImplicitStringLiteral &&
Craig Topper2145bc02014-05-09 08:15:10 +0000243 (Current.Previous->Tok.getIdentifierInfo() == nullptr ||
Daniel Jasper98857842013-10-30 13:54:53 +0000244 Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
245 tok::pp_not_keyword))) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000246 // FIXME: Is this correct?
247 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
248 State.NextToken->WhitespaceRange.getEnd()) -
249 SourceMgr.getSpellingColumnNumber(
250 State.NextToken->WhitespaceRange.getBegin());
Daniel Jasperda353cd2014-03-12 08:24:47 +0000251 State.Column += WhitespaceLength;
Daniel Jasper240dfda2014-03-31 14:23:49 +0000252 moveStateToNextToken(State, DryRun, /*Newline=*/false);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000253 return 0;
254 }
255
Alexander Kornienko1f803962013-10-01 14:41:18 +0000256 unsigned Penalty = 0;
257 if (Newline)
258 Penalty = addTokenOnNewLine(State, DryRun);
259 else
Daniel Jasper48437ce2013-11-20 14:54:39 +0000260 addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000261
262 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
263}
264
Daniel Jasper48437ce2013-11-20 14:54:39 +0000265void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
266 unsigned ExtraSpaces) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000267 FormatToken &Current = *State.NextToken;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000268 const FormatToken &Previous = *State.NextToken->Previous;
269 if (Current.is(tok::equal) &&
Daniel Jasper05cd5862014-05-08 12:21:30 +0000270 (State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) &&
Alexander Kornienko1f803962013-10-01 14:41:18 +0000271 State.Stack.back().VariablePos == 0) {
272 State.Stack.back().VariablePos = State.Column;
273 // Move over * and & if they are bound to the variable name.
274 const FormatToken *Tok = &Previous;
275 while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
276 State.Stack.back().VariablePos -= Tok->ColumnWidth;
277 if (Tok->SpacesRequiredBefore != 0)
278 break;
279 Tok = Tok->Previous;
280 }
281 if (Previous.PartOfMultiVariableDeclStmt)
282 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
283 }
284
285 unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
286
287 if (!DryRun)
288 Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, /*IndentLevel=*/0,
289 Spaces, State.Column + Spaces);
290
Daniel Jasper17062ff2014-06-10 14:44:02 +0000291 if (Current.Type == TT_SelectorName &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000292 !State.Stack.back().ObjCSelectorNameFound) {
293 if (Current.LongestObjCSelectorName == 0)
294 State.Stack.back().AlignColons = false;
295 else if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
296 State.Column + Spaces + Current.ColumnWidth)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000297 State.Stack.back().ColonPos =
298 State.Stack.back().Indent + Current.LongestObjCSelectorName;
299 else
300 State.Stack.back().ColonPos = State.Column + Spaces + Current.ColumnWidth;
301 }
302
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000303 if (Style.AlignAfterOpenBracket &&
304 Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper5a611392013-12-19 21:41:37 +0000305 (Current.Type != TT_LineComment || Previous.BlockKind == BK_BracedInit))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000306 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasperec01cd62013-10-08 05:11:18 +0000307 if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000308 State.Stack.back().NoLineBreak = true;
309 if (startsSegmentOfBuilderTypeCall(Current))
310 State.Stack.back().ContainsUnwrappedBuilder = true;
311
Daniel Jasperd6f17d82014-09-12 16:35:28 +0000312 if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&
313 (Previous.MatchingParen &&
314 (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10))) {
315 // If there is a function call with long parameters, break before trailing
316 // calls. This prevents things like:
317 // EXPECT_CALL(SomeLongParameter).Times(
318 // 2);
319 // We don't want to do this for short parameters as they can just be
320 // indexes.
321 State.Stack.back().NoLineBreak = true;
322 }
323
Alexander Kornienko1f803962013-10-01 14:41:18 +0000324 State.Column += Spaces;
Daniel Jasper8acf8222014-05-07 09:23:05 +0000325 if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&
326 Previous.Previous && Previous.Previous->isOneOf(tok::kw_if, tok::kw_for))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000327 // Treat the condition inside an if as if it was a second function
Daniel Jasper6633ab82013-10-18 10:38:14 +0000328 // parameter, i.e. let nested calls have a continuation indent.
Daniel Jasper8acf8222014-05-07 09:23:05 +0000329 State.Stack.back().LastSpace = State.Column;
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000330 else if (!Current.isOneOf(tok::comment, tok::caret) &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000331 (Previous.is(tok::comma) ||
332 (Previous.is(tok::colon) && Previous.Type == TT_ObjCMethodExpr)))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000333 State.Stack.back().LastSpace = State.Column;
334 else if ((Previous.Type == TT_BinaryOperator ||
335 Previous.Type == TT_ConditionalExpr ||
Alexander Kornienko1f803962013-10-01 14:41:18 +0000336 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper0e617842014-04-16 12:26:54 +0000337 ((Previous.getPrecedence() != prec::Assignment &&
338 (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||
339 !Previous.LastOperator)) ||
Alexander Kornienko1f803962013-10-01 14:41:18 +0000340 Current.StartsBinaryExpression))
341 // Always indent relative to the RHS of the expression unless this is a
342 // simple assignment without binary expression on the RHS. Also indent
343 // relative to unary operators and the colons of constructor initializers.
344 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf9a5e402013-10-08 16:24:07 +0000345 else if (Previous.Type == TT_InheritanceColon) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000346 State.Stack.back().Indent = State.Column;
Daniel Jasperf9a5e402013-10-08 16:24:07 +0000347 State.Stack.back().LastSpace = State.Column;
348 } else if (Previous.opensScope()) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000349 // If a function has a trailing call, indent all parameters from the
350 // opening parenthesis. This avoids confusing indents like:
351 // OuterFunction(InnerFunctionCall( // break
352 // ParameterToInnerFunction)) // break
353 // .SecondInnerFunctionCall();
354 bool HasTrailingCall = false;
355 if (Previous.MatchingParen) {
356 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
357 HasTrailingCall = Next && Next->isMemberAccess();
358 }
359 if (HasTrailingCall &&
360 State.Stack[State.Stack.size() - 2].CallContinuation == 0)
361 State.Stack.back().LastSpace = State.Column;
362 }
363}
364
365unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
366 bool DryRun) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000367 FormatToken &Current = *State.NextToken;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000368 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000369
Alexander Kornienko1f803962013-10-01 14:41:18 +0000370 // Extra penalty that needs to be added because of the way certain line
371 // breaks are chosen.
372 unsigned Penalty = 0;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000373
Daniel Jaspera0407742014-02-11 10:08:11 +0000374 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
375 const FormatToken *NextNonComment = Previous.getNextNonComment();
376 if (!NextNonComment)
377 NextNonComment = &Current;
Daniel Jasper05cd5862014-05-08 12:21:30 +0000378 // The first line break on any NestingLevel causes an extra penalty in order
Alexander Kornienko1f803962013-10-01 14:41:18 +0000379 // prefer similar line breaks.
380 if (!State.Stack.back().ContainsLineBreak)
381 Penalty += 15;
382 State.Stack.back().ContainsLineBreak = true;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000383
Alexander Kornienko1f803962013-10-01 14:41:18 +0000384 Penalty += State.NextToken->SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000385
Alexander Kornienko1f803962013-10-01 14:41:18 +0000386 // Breaking before the first "<<" is generally not desirable if the LHS is
Daniel Jasper48437ce2013-11-20 14:54:39 +0000387 // short. Also always add the penalty if the LHS is split over mutliple lines
Daniel Jasper2b7556e2014-04-03 12:00:27 +0000388 // to avoid unnecessary line breaks that just work around this penalty.
Daniel Jaspera0407742014-02-11 10:08:11 +0000389 if (NextNonComment->is(tok::lessless) &&
390 State.Stack.back().FirstLessLess == 0 &&
Daniel Jasper004177e2013-12-19 16:06:40 +0000391 (State.Column <= Style.ColumnLimit / 3 ||
Daniel Jasper48437ce2013-11-20 14:54:39 +0000392 State.Stack.back().BreakBeforeParameter))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000393 Penalty += Style.PenaltyBreakFirstLessLess;
394
Daniel Jasper9f388d02014-03-27 14:33:30 +0000395 State.Column = getNewLineColumn(State);
396 if (NextNonComment->isMemberAccess()) {
397 if (State.Stack.back().CallContinuation == 0)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000398 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper17062ff2014-06-10 14:44:02 +0000399 } else if (NextNonComment->Type == TT_SelectorName) {
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000400 if (!State.Stack.back().ObjCSelectorNameFound) {
Daniel Jaspera0407742014-02-11 10:08:11 +0000401 if (NextNonComment->LongestObjCSelectorName == 0) {
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000402 State.Stack.back().AlignColons = false;
403 } else {
404 State.Stack.back().ColonPos =
Daniel Jaspera0407742014-02-11 10:08:11 +0000405 State.Stack.back().Indent + NextNonComment->LongestObjCSelectorName;
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000406 }
Daniel Jasper9f388d02014-03-27 14:33:30 +0000407 } else if (State.Stack.back().AlignColons &&
408 State.Stack.back().ColonPos <= NextNonComment->ColumnWidth) {
Daniel Jaspera0407742014-02-11 10:08:11 +0000409 State.Stack.back().ColonPos = State.Column + NextNonComment->ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000410 }
Daniel Jasper1fd6f1f2014-03-17 14:32:47 +0000411 } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
412 (PreviousNonComment->Type == TT_ObjCMethodExpr ||
413 PreviousNonComment->Type == TT_DictLiteral)) {
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000414 // FIXME: This is hacky, find a better way. The problem is that in an ObjC
415 // method expression, the block should be aligned to the line starting it,
416 // e.g.:
417 // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
418 // ^(int *i) {
419 // // ...
420 // }];
Daniel Jasper05cd5862014-05-08 12:21:30 +0000421 // Thus, we set LastSpace of the next higher NestingLevel, to which we move
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000422 // when we consume all of the "}"'s FakeRParens at the "{".
Daniel Jasper9a26e772013-12-23 11:25:40 +0000423 if (State.Stack.size() > 1)
Daniel Jasper9f388d02014-03-27 14:33:30 +0000424 State.Stack[State.Stack.size() - 2].LastSpace =
425 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
426 Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000427 }
428
Alexander Kornienko1f803962013-10-01 14:41:18 +0000429 if ((Previous.isOneOf(tok::comma, tok::semi) &&
430 !State.Stack.back().AvoidBinPacking) ||
431 Previous.Type == TT_BinaryOperator)
432 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper39af6cd2014-11-03 02:27:28 +0000433 if ((Previous.Type == TT_TemplateCloser ||
434 Previous.Type == TT_JavaAnnotation) &&
435 Current.NestingLevel == 0)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000436 State.Stack.back().BreakBeforeParameter = false;
Daniel Jaspera0407742014-02-11 10:08:11 +0000437 if (NextNonComment->is(tok::question) ||
Daniel Jasper165b29e2013-11-08 00:57:11 +0000438 (PreviousNonComment && PreviousNonComment->is(tok::question)))
439 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000440
441 if (!DryRun) {
Daniel Jaspera69ca9b2014-06-04 12:40:57 +0000442 unsigned Newlines = std::max(
443 1u, std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1));
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000444 Whitespaces.replaceWhitespace(Current, Newlines,
445 State.Stack.back().IndentLevel, State.Column,
446 State.Column, State.Line->InPPDirective);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000447 }
448
449 if (!Current.isTrailingComment())
450 State.Stack.back().LastSpace = State.Column;
Daniel Jasper05cd5862014-05-08 12:21:30 +0000451 State.StartOfLineLevel = Current.NestingLevel;
452 State.LowestLevelOnLine = Current.NestingLevel;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000453
454 // Any break on this level means that the parent level has been broken
455 // and we need to avoid bin packing there.
Daniel Jasperb16b9692014-05-21 12:51:23 +0000456 bool JavaScriptFormat = Style.Language == FormatStyle::LK_JavaScript &&
457 Current.is(tok::r_brace) &&
458 State.Stack.size() > 1 &&
459 State.Stack[State.Stack.size() - 2].JSFunctionInlined;
460 if (!JavaScriptFormat) {
461 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
462 State.Stack[i].BreakBeforeParameter = true;
463 }
Alexander Kornienko1f803962013-10-01 14:41:18 +0000464 }
Daniel Jasperb16b9692014-05-21 12:51:23 +0000465
Daniel Jasper9e5ede02013-11-08 19:56:28 +0000466 if (PreviousNonComment &&
467 !PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
Daniel Jasper6c0ee172014-11-14 13:14:45 +0000468 (PreviousNonComment->Type != TT_TemplateCloser ||
469 Current.NestingLevel != 0) &&
Daniel Jasper9e5ede02013-11-08 19:56:28 +0000470 PreviousNonComment->Type != TT_BinaryOperator &&
Daniel Jasperfab69ff2014-10-21 08:24:18 +0000471 PreviousNonComment->Type != TT_JavaAnnotation &&
Daniel Jaspere9ab42d2014-10-31 18:23:49 +0000472 PreviousNonComment->Type != TT_LeadingJavaAnnotation &&
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000473 Current.Type != TT_BinaryOperator && !PreviousNonComment->opensScope())
Alexander Kornienko1f803962013-10-01 14:41:18 +0000474 State.Stack.back().BreakBeforeParameter = true;
475
Daniel Jasper1db6c382013-10-22 15:30:28 +0000476 // If we break after { or the [ of an array initializer, we should also break
477 // before the corresponding } or ].
Daniel Jasper90818052014-06-10 10:42:26 +0000478 if (PreviousNonComment &&
479 (PreviousNonComment->is(tok::l_brace) ||
480 PreviousNonComment->Type == TT_ArrayInitializerLSquare))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000481 State.Stack.back().BreakBeforeClosingBrace = true;
482
483 if (State.Stack.back().AvoidBinPacking) {
484 // If we are breaking after '(', '{', '<', this is not bin packing
Daniel Jasper2a958322014-05-21 13:26:58 +0000485 // unless AllowAllParametersOfDeclarationOnNextLine is false or this is a
486 // dict/object literal.
Alexander Kornienko1f803962013-10-01 14:41:18 +0000487 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
488 Previous.Type == TT_BinaryOperator) ||
489 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
Daniel Jasper2a958322014-05-21 13:26:58 +0000490 State.Line->MustBeDeclaration) ||
491 Previous.Type == TT_DictLiteral)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000492 State.Stack.back().BreakBeforeParameter = true;
493 }
494
495 return Penalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000496}
497
Daniel Jasper9f388d02014-03-27 14:33:30 +0000498unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000499 if (!State.NextToken || !State.NextToken->Previous)
500 return 0;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000501 FormatToken &Current = *State.NextToken;
Daniel Jasper4281c5a2014-10-07 14:45:34 +0000502 const FormatToken &Previous = *Current.Previous;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000503 // If we are continuing an expression, we want to use the continuation indent.
504 unsigned ContinuationIndent =
505 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
506 Style.ContinuationIndentWidth;
507 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
508 const FormatToken *NextNonComment = Previous.getNextNonComment();
509 if (!NextNonComment)
510 NextNonComment = &Current;
Daniel Jasper50b4bd72014-11-02 19:16:41 +0000511
512 // Java specific bits.
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000513 if (Style.Language == FormatStyle::LK_Java &&
514 Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends))
Daniel Jasper50b4bd72014-11-02 19:16:41 +0000515 return std::max(State.Stack.back().LastSpace,
516 State.Stack.back().Indent + Style.ContinuationIndentWidth);
517
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000518 if (NextNonComment->is(tok::l_brace) && NextNonComment->BlockKind == BK_Block)
Daniel Jasper05cd5862014-05-08 12:21:30 +0000519 return Current.NestingLevel == 0 ? State.FirstIndent
520 : State.Stack.back().Indent;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000521 if (Current.isOneOf(tok::r_brace, tok::r_square)) {
Daniel Jasperb16b9692014-05-21 12:51:23 +0000522 if (State.Stack.size() > 1 &&
523 State.Stack[State.Stack.size() - 2].JSFunctionInlined)
524 return State.FirstIndent;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000525 if (Current.closesBlockTypeList(Style) ||
526 (Current.MatchingParen &&
527 Current.MatchingParen->BlockKind == BK_BracedInit))
528 return State.Stack[State.Stack.size() - 2].LastSpace;
529 else
530 return State.FirstIndent;
531 }
Daniel Jasper783bac62014-04-15 09:54:30 +0000532 if (Current.is(tok::identifier) && Current.Next &&
533 Current.Next->Type == TT_DictLiteral)
534 return State.Stack.back().Indent;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000535 if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
536 return State.StartOfStringLiteral;
537 if (NextNonComment->is(tok::lessless) &&
538 State.Stack.back().FirstLessLess != 0)
539 return State.Stack.back().FirstLessLess;
540 if (NextNonComment->isMemberAccess()) {
541 if (State.Stack.back().CallContinuation == 0) {
542 return ContinuationIndent;
543 } else {
544 return State.Stack.back().CallContinuation;
545 }
546 }
547 if (State.Stack.back().QuestionColumn != 0 &&
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000548 ((NextNonComment->is(tok::colon) &&
549 NextNonComment->Type == TT_ConditionalExpr) ||
Daniel Jasper9f388d02014-03-27 14:33:30 +0000550 Previous.Type == TT_ConditionalExpr))
551 return State.Stack.back().QuestionColumn;
552 if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0)
553 return State.Stack.back().VariablePos;
Daniel Jaspere9ab42d2014-10-31 18:23:49 +0000554 if ((PreviousNonComment &&
555 (PreviousNonComment->ClosesTemplateDeclaration ||
556 PreviousNonComment->Type == TT_AttributeParen ||
557 PreviousNonComment->Type == TT_JavaAnnotation ||
558 PreviousNonComment->Type == TT_LeadingJavaAnnotation)) ||
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000559 (!Style.IndentWrappedFunctionNames &&
560 (NextNonComment->is(tok::kw_operator) ||
561 NextNonComment->Type == TT_FunctionDeclarationName)))
Daniel Jasper9f388d02014-03-27 14:33:30 +0000562 return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
Daniel Jasper17062ff2014-06-10 14:44:02 +0000563 if (NextNonComment->Type == TT_SelectorName) {
Daniel Jasper9f388d02014-03-27 14:33:30 +0000564 if (!State.Stack.back().ObjCSelectorNameFound) {
565 if (NextNonComment->LongestObjCSelectorName == 0) {
566 return State.Stack.back().Indent;
567 } else {
568 return State.Stack.back().Indent +
569 NextNonComment->LongestObjCSelectorName -
570 NextNonComment->ColumnWidth;
571 }
572 } else if (!State.Stack.back().AlignColons) {
573 return State.Stack.back().Indent;
574 } else if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth) {
575 return State.Stack.back().ColonPos - NextNonComment->ColumnWidth;
576 } else {
577 return State.Stack.back().Indent;
578 }
579 }
580 if (NextNonComment->Type == TT_ArraySubscriptLSquare) {
581 if (State.Stack.back().StartOfArraySubscripts != 0)
582 return State.Stack.back().StartOfArraySubscripts;
583 else
584 return ContinuationIndent;
585 }
586 if (NextNonComment->Type == TT_StartOfName ||
587 Previous.isOneOf(tok::coloncolon, tok::equal)) {
588 return ContinuationIndent;
589 }
590 if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
591 (PreviousNonComment->Type == TT_ObjCMethodExpr ||
592 PreviousNonComment->Type == TT_DictLiteral))
593 return ContinuationIndent;
594 if (NextNonComment->Type == TT_CtorInitializerColon)
595 return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
596 if (NextNonComment->Type == TT_CtorInitializerComma)
597 return State.Stack.back().Indent;
Daniel Jasper316ab382014-08-06 13:14:58 +0000598 if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() &&
Daniel Jasper119ff532014-11-14 12:31:14 +0000599 !Current.isOneOf(tok::colon, tok::comment))
Daniel Jasper316ab382014-08-06 13:14:58 +0000600 return ContinuationIndent;
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000601 if (State.Stack.back().Indent == State.FirstIndent && PreviousNonComment &&
Daniel Jasper9f388d02014-03-27 14:33:30 +0000602 PreviousNonComment->isNot(tok::r_brace))
603 // Ensure that we fall back to the continuation indent width instead of
604 // just flushing continuations left.
605 return State.Stack.back().Indent + Style.ContinuationIndentWidth;
606 return State.Stack.back().Indent;
607}
608
Daniel Jasperde0328a2013-08-16 11:20:30 +0000609unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
610 bool DryRun, bool Newline) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000611 assert(State.Stack.size());
Daniel Jasper60553be2014-05-26 13:10:39 +0000612 const FormatToken &Current = *State.NextToken;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000613
614 if (Current.Type == TT_InheritanceColon)
615 State.Stack.back().AvoidBinPacking = true;
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000616 if (Current.is(tok::lessless) && Current.Type != TT_OverloadedOperator) {
617 if (State.Stack.back().FirstLessLess == 0)
618 State.Stack.back().FirstLessLess = State.Column;
619 else
620 State.Stack.back().LastOperatorWrapped = Newline;
621 }
622 if ((Current.Type == TT_BinaryOperator && Current.isNot(tok::lessless)) ||
623 Current.Type == TT_ConditionalExpr)
624 State.Stack.back().LastOperatorWrapped = Newline;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000625 if (Current.Type == TT_ArraySubscriptLSquare &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000626 State.Stack.back().StartOfArraySubscripts == 0)
627 State.Stack.back().StartOfArraySubscripts = State.Column;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000628 if ((Current.is(tok::question) && Style.BreakBeforeTernaryOperators) ||
629 (Current.getPreviousNonComment() && Current.isNot(tok::colon) &&
630 Current.getPreviousNonComment()->is(tok::question) &&
631 !Style.BreakBeforeTernaryOperators))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000632 State.Stack.back().QuestionColumn = State.Column;
633 if (!Current.opensScope() && !Current.closesScope())
634 State.LowestLevelOnLine =
Daniel Jasper05cd5862014-05-08 12:21:30 +0000635 std::min(State.LowestLevelOnLine, Current.NestingLevel);
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000636 if (Current.isMemberAccess())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000637 State.Stack.back().StartOfFunctionCall =
Daniel Jasper0e617842014-04-16 12:26:54 +0000638 Current.LastOperator ? 0 : State.Column + Current.ColumnWidth;
Daniel Jasper17062ff2014-06-10 14:44:02 +0000639 if (Current.Type == TT_SelectorName)
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000640 State.Stack.back().ObjCSelectorNameFound = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000641 if (Current.Type == TT_CtorInitializerColon) {
642 // Indent 2 from the column, so:
643 // SomeClass::SomeClass()
644 // : First(...), ...
645 // Next(...)
646 // ^ line up here.
647 State.Stack.back().Indent =
648 State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
649 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
650 State.Stack.back().AvoidBinPacking = true;
651 State.Stack.back().BreakBeforeParameter = false;
652 }
653
Daniel Jasperde0328a2013-08-16 11:20:30 +0000654 // In ObjC method declaration we align on the ":" of parameters, but we need
Daniel Jasper6633ab82013-10-18 10:38:14 +0000655 // to ensure that we indent parameters on subsequent lines by at least our
656 // continuation indent width.
Daniel Jasperde0328a2013-08-16 11:20:30 +0000657 if (Current.Type == TT_ObjCMethodSpecifier)
Daniel Jasper6633ab82013-10-18 10:38:14 +0000658 State.Stack.back().Indent += Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000659
660 // Insert scopes created by fake parenthesis.
661 const FormatToken *Previous = Current.getPreviousNonComment();
Daniel Jasperb16b9692014-05-21 12:51:23 +0000662
663 // Add special behavior to support a format commonly used for JavaScript
664 // closures:
665 // SomeFunction(function() {
666 // foo();
667 // bar();
668 // }, a, b, c);
669 if (Style.Language == FormatStyle::LK_JavaScript) {
670 if (Current.isNot(tok::comment) && Previous && Previous->is(tok::l_brace) &&
671 State.Stack.size() > 1) {
672 if (State.Stack[State.Stack.size() - 2].JSFunctionInlined && Newline) {
673 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
674 State.Stack[i].NoLineBreak = true;
675 }
676 }
677 State.Stack[State.Stack.size() - 2].JSFunctionInlined = false;
678 }
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000679 if (Current.is(Keywords.kw_function))
Daniel Jasper90ebc982014-09-05 09:27:38 +0000680 State.Stack.back().JSFunctionInlined =
Daniel Jasper1779d432014-09-29 07:54:54 +0000681 !Newline && Previous && Previous->Type != TT_DictLiteral &&
682 // If the unnamed function is the only parameter to another function,
683 // we can likely inline it and come up with a good format.
684 (Previous->isNot(tok::l_paren) || Previous->ParameterCount > 1);
Daniel Jasperb16b9692014-05-21 12:51:23 +0000685 }
686
Daniel Jasper60553be2014-05-26 13:10:39 +0000687 moveStatePastFakeLParens(State, Newline);
688 moveStatePastScopeOpener(State, Newline);
689 moveStatePastScopeCloser(State);
690 moveStatePastFakeRParens(State);
691
692 if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) {
693 State.StartOfStringLiteral = State.Column;
694 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
695 !Current.isStringLiteral()) {
696 State.StartOfStringLiteral = 0;
697 }
698
699 State.Column += Current.ColumnWidth;
700 State.NextToken = State.NextToken->Next;
701 unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
702 if (State.Column > getColumnLimit(State)) {
703 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
704 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
705 }
706
707 if (Current.Role)
708 Current.Role->formatFromToken(State, this, DryRun);
709 // If the previous has a special role, let it consume tokens as appropriate.
710 // It is necessary to start at the previous token for the only implemented
711 // role (comma separated list). That way, the decision whether or not to break
712 // after the "{" is already done and both options are tried and evaluated.
713 // FIXME: This is ugly, find a better way.
714 if (Previous && Previous->Role)
715 Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
716
717 return Penalty;
718}
719
720void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
721 bool Newline) {
722 const FormatToken &Current = *State.NextToken;
723 const FormatToken *Previous = Current.getPreviousNonComment();
724
Daniel Jasperde0328a2013-08-16 11:20:30 +0000725 // Don't add extra indentation for the first fake parenthesis after
Dinesh Dwivedi0db806b2014-05-01 17:19:34 +0000726 // 'return', assignments or opening <({[. The indentation for these cases
Daniel Jasperde0328a2013-08-16 11:20:30 +0000727 // is special cased.
728 bool SkipFirstExtraIndent =
Daniel Jaspereabede62013-09-30 08:29:03 +0000729 (Previous && (Previous->opensScope() || Previous->is(tok::kw_return) ||
Daniel Jasperf48b5ab2013-11-07 19:23:49 +0000730 Previous->getPrecedence() == prec::Assignment ||
731 Previous->Type == TT_ObjCMethodExpr));
Daniel Jasperde0328a2013-08-16 11:20:30 +0000732 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
733 I = Current.FakeLParens.rbegin(),
734 E = Current.FakeLParens.rend();
735 I != E; ++I) {
736 ParenState NewParenState = State.Stack.back();
737 NewParenState.ContainsLineBreak = false;
Daniel Jaspereabede62013-09-30 08:29:03 +0000738
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000739 // Indent from 'LastSpace' unless these are fake parentheses encapsulating
740 // a builder type call after 'return' or, if the alignment after opening
741 // brackets is disabled.
Daniel Jasper4281c5a2014-10-07 14:45:34 +0000742 if (!Current.isTrailingComment() &&
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000743 (!Previous || Previous->isNot(tok::kw_return) || *I > 0) &&
744 (Style.AlignAfterOpenBracket || *I != prec::Comma ||
745 Current.NestingLevel == 0))
Daniel Jaspereabede62013-09-30 08:29:03 +0000746 NewParenState.Indent =
747 std::max(std::max(State.Column, NewParenState.Indent),
748 State.Stack.back().LastSpace);
749
Daniel Jasper5c332652014-04-03 12:00:33 +0000750 // Don't allow the RHS of an operator to be split over multiple lines unless
751 // there is a line-break right after the operator.
752 // Exclude relational operators, as there, it is always more desirable to
753 // have the LHS 'left' of the RHS.
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000754 if (Previous && Previous->getPrecedence() > prec::Assignment &&
755 (Previous->Type == TT_BinaryOperator ||
756 Previous->Type == TT_ConditionalExpr) &&
757 Previous->getPrecedence() != prec::Relational) {
758 bool BreakBeforeOperator = Previous->is(tok::lessless) ||
759 (Previous->Type == TT_BinaryOperator &&
760 Style.BreakBeforeBinaryOperators) ||
761 (Previous->Type == TT_ConditionalExpr &&
762 Style.BreakBeforeTernaryOperators);
763 if ((!Newline && !BreakBeforeOperator) ||
764 (!State.Stack.back().LastOperatorWrapped && BreakBeforeOperator))
765 NewParenState.NoLineBreak = true;
766 }
Daniel Jasper5c332652014-04-03 12:00:33 +0000767
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000768 // Do not indent relative to the fake parentheses inserted for "." or "->".
769 // This is a special case to make the following to statements consistent:
770 // OuterFunction(InnerFunctionCall( // break
771 // ParameterToInnerFunction));
772 // OuterFunction(SomeObject.InnerFunctionCall( // break
773 // ParameterToInnerFunction));
774 if (*I > prec::Unknown)
775 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
Daniel Jasper96964352013-12-18 10:44:36 +0000776 NewParenState.StartOfFunctionCall = State.Column;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000777
778 // Always indent conditional expressions. Never indent expression where
779 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
780 // prec::Assignment) as those have different indentation rules. Indent
781 // other expression, unless the indentation needs to be skipped.
782 if (*I == prec::Conditional ||
783 (!SkipFirstExtraIndent && *I > prec::Assignment &&
Daniel Jasper4281c5a2014-10-07 14:45:34 +0000784 !Current.isTrailingComment() && !Style.BreakBeforeBinaryOperators))
Daniel Jasper6633ab82013-10-18 10:38:14 +0000785 NewParenState.Indent += Style.ContinuationIndentWidth;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000786 if ((Previous && !Previous->opensScope()) || *I > prec::Comma)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000787 NewParenState.BreakBeforeParameter = false;
788 State.Stack.push_back(NewParenState);
789 SkipFirstExtraIndent = false;
790 }
Daniel Jasper60553be2014-05-26 13:10:39 +0000791}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000792
Daniel Jasper335ff262014-05-28 09:11:53 +0000793// Remove the fake r_parens after 'Tok'.
794static void consumeRParens(LineState& State, const FormatToken &Tok) {
795 for (unsigned i = 0, e = Tok.FakeRParens; i != e; ++i) {
796 unsigned VariablePos = State.Stack.back().VariablePos;
797 assert(State.Stack.size() > 1);
798 if (State.Stack.size() == 1) {
799 // Do not pop the last element.
800 break;
801 }
802 State.Stack.pop_back();
803 State.Stack.back().VariablePos = VariablePos;
804 }
805}
806
807// Returns whether 'Tok' opens or closes a scope requiring special handling
808// of the subsequent fake r_parens.
809//
810// For example, if this is an l_brace starting a nested block, we pretend (wrt.
811// to indentation) that we already consumed the corresponding r_brace. Thus, we
812// remove all ParenStates caused by fake parentheses that end at the r_brace.
813// The net effect of this is that we don't indent relative to the l_brace, if
814// the nested block is the last parameter of a function. This formats:
815//
816// SomeFunction(a, [] {
817// f(); // break
818// });
819//
820// instead of:
821// SomeFunction(a, [] {
822// f(); // break
823// });
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000824static bool fakeRParenSpecialCase(const LineState &State) {
825 const FormatToken &Tok = *State.NextToken;
Daniel Jasper335ff262014-05-28 09:11:53 +0000826 if (!Tok.MatchingParen)
827 return false;
828 const FormatToken *Left = &Tok;
829 if (Tok.isOneOf(tok::r_brace, tok::r_square))
830 Left = Tok.MatchingParen;
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000831 return !State.Stack.back().HasMultipleNestedBlocks &&
832 Left->isOneOf(tok::l_brace, tok::l_square) &&
Daniel Jasper335ff262014-05-28 09:11:53 +0000833 (Left->BlockKind == BK_Block ||
834 Left->Type == TT_ArrayInitializerLSquare ||
835 Left->Type == TT_DictLiteral);
836}
837
Daniel Jasper60553be2014-05-26 13:10:39 +0000838void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
Daniel Jasper335ff262014-05-28 09:11:53 +0000839 // Don't remove FakeRParens attached to r_braces that surround nested blocks
840 // as they will have been removed early (see above).
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000841 if (fakeRParenSpecialCase(State))
Daniel Jasper335ff262014-05-28 09:11:53 +0000842 return;
843
844 consumeRParens(State, *State.NextToken);
Daniel Jasper60553be2014-05-26 13:10:39 +0000845}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000846
Daniel Jasper60553be2014-05-26 13:10:39 +0000847void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
848 bool Newline) {
849 const FormatToken &Current = *State.NextToken;
850 if (!Current.opensScope())
851 return;
852
853 if (Current.MatchingParen && Current.BlockKind == BK_Block) {
854 moveStateToNewBlock(State);
855 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000856 }
857
Daniel Jasper60553be2014-05-26 13:10:39 +0000858 unsigned NewIndent;
859 unsigned NewIndentLevel = State.Stack.back().IndentLevel;
860 bool AvoidBinPacking;
861 bool BreakBeforeParameter = false;
862 if (Current.is(tok::l_brace) || Current.Type == TT_ArrayInitializerLSquare) {
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000863 if (fakeRParenSpecialCase(State))
Daniel Jasper335ff262014-05-28 09:11:53 +0000864 consumeRParens(State, *Current.MatchingParen);
865
Daniel Jasper60553be2014-05-26 13:10:39 +0000866 NewIndent = State.Stack.back().LastSpace;
867 if (Current.opensBlockTypeList(Style)) {
868 NewIndent += Style.IndentWidth;
869 NewIndent = std::min(State.Column + 2, NewIndent);
870 ++NewIndentLevel;
871 } else {
872 NewIndent += Style.ContinuationIndentWidth;
873 NewIndent = std::min(State.Column + 1, NewIndent);
874 }
875 const FormatToken *NextNoComment = Current.getNextNonComment();
876 AvoidBinPacking = Current.Type == TT_ArrayInitializerLSquare ||
877 Current.Type == TT_DictLiteral ||
878 Style.Language == FormatStyle::LK_Proto ||
879 !Style.BinPackParameters ||
880 (NextNoComment &&
881 NextNoComment->Type == TT_DesignatedInitializerPeriod);
882 } else {
883 NewIndent = Style.ContinuationIndentWidth +
884 std::max(State.Stack.back().LastSpace,
885 State.Stack.back().StartOfFunctionCall);
Daniel Jasper18210d72014-10-09 09:52:05 +0000886 AvoidBinPacking =
887 (State.Line->MustBeDeclaration && !Style.BinPackParameters) ||
888 (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||
889 (Style.ExperimentalAutoDetectBinPacking &&
890 (Current.PackingKind == PPK_OnePerLine ||
891 (!BinPackInconclusiveFunctions &&
892 Current.PackingKind == PPK_Inconclusive)));
Daniel Jasper60553be2014-05-26 13:10:39 +0000893 // If this '[' opens an ObjC call, determine whether all parameters fit
894 // into one line and put one per line if they don't.
895 if (Current.Type == TT_ObjCMethodExpr && Style.ColumnLimit != 0 &&
896 getLengthToMatchingParen(Current) + State.Column >
897 getColumnLimit(State))
898 BreakBeforeParameter = true;
899 }
Daniel Jaspera41aa532014-09-19 08:01:25 +0000900 bool NoLineBreak = State.Stack.back().NoLineBreak ||
901 (Current.Type == TT_TemplateOpener &&
902 State.Stack.back().ContainsUnwrappedBuilder);
Daniel Jasper60553be2014-05-26 13:10:39 +0000903 State.Stack.push_back(ParenState(NewIndent, NewIndentLevel,
904 State.Stack.back().LastSpace,
905 AvoidBinPacking, NoLineBreak));
906 State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000907 State.Stack.back().HasMultipleNestedBlocks = Current.BlockParameterCount > 1;
Daniel Jasper60553be2014-05-26 13:10:39 +0000908}
909
910void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
911 const FormatToken &Current = *State.NextToken;
912 if (!Current.closesScope())
913 return;
914
915 // If we encounter a closing ), ], } or >, we can remove a level from our
916 // stacks.
917 if (State.Stack.size() > 1 &&
918 (Current.isOneOf(tok::r_paren, tok::r_square) ||
919 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
Daniel Jasper335ff262014-05-28 09:11:53 +0000920 State.NextToken->Type == TT_TemplateCloser))
Daniel Jasper60553be2014-05-26 13:10:39 +0000921 State.Stack.pop_back();
Daniel Jasper335ff262014-05-28 09:11:53 +0000922
Daniel Jasper60553be2014-05-26 13:10:39 +0000923 if (Current.is(tok::r_square)) {
924 // If this ends the array subscript expr, reset the corresponding value.
925 const FormatToken *NextNonComment = Current.getNextNonComment();
926 if (NextNonComment && NextNonComment->isNot(tok::l_square))
927 State.Stack.back().StartOfArraySubscripts = 0;
928 }
929}
930
931void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
Daniel Jasper60553be2014-05-26 13:10:39 +0000932 // If we have already found more than one lambda introducers on this level, we
933 // opt out of this because similarity between the lambdas is more important.
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000934 if (fakeRParenSpecialCase(State))
Daniel Jasper335ff262014-05-28 09:11:53 +0000935 consumeRParens(State, *State.NextToken->MatchingParen);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000936
Daniel Jasper50d634b2014-10-28 16:53:38 +0000937 // ObjC block sometimes follow special indentation rules.
Daniel Jasper60553be2014-05-26 13:10:39 +0000938 unsigned NewIndent = State.Stack.back().LastSpace +
939 (State.NextToken->Type == TT_ObjCBlockLBrace
Daniel Jasper50d634b2014-10-28 16:53:38 +0000940 ? Style.ObjCBlockIndentWidth
Daniel Jasper60553be2014-05-26 13:10:39 +0000941 : Style.IndentWidth);
942 State.Stack.push_back(ParenState(
943 NewIndent, /*NewIndentLevel=*/State.Stack.back().IndentLevel + 1,
944 State.Stack.back().LastSpace, /*AvoidBinPacking=*/true,
945 State.Stack.back().NoLineBreak));
946 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000947}
948
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000949unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
950 LineState &State) {
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000951 // Break before further function parameters on all levels.
952 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
953 State.Stack[i].BreakBeforeParameter = true;
954
Alexander Kornienko39856b72013-09-10 09:38:25 +0000955 unsigned ColumnsUsed = State.Column;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000956 // We can only affect layout of the first and the last line, so the penalty
957 // for all other lines is constant, and we ignore it.
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000958 State.Column = Current.LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000959
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000960 if (ColumnsUsed > getColumnLimit(State))
961 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000962 return 0;
963}
964
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000965static bool getRawStringLiteralPrefixPostfix(StringRef Text, StringRef &Prefix,
Alexander Kornienko81e32942013-09-16 20:20:49 +0000966 StringRef &Postfix) {
967 if (Text.startswith(Prefix = "R\"") || Text.startswith(Prefix = "uR\"") ||
968 Text.startswith(Prefix = "UR\"") || Text.startswith(Prefix = "u8R\"") ||
969 Text.startswith(Prefix = "LR\"")) {
970 size_t ParenPos = Text.find('(');
971 if (ParenPos != StringRef::npos) {
972 StringRef Delimiter =
973 Text.substr(Prefix.size(), ParenPos - Prefix.size());
974 Prefix = Text.substr(0, ParenPos + 1);
975 Postfix = Text.substr(Text.size() - 2 - Delimiter.size());
976 return Postfix.front() == ')' && Postfix.back() == '"' &&
977 Postfix.substr(1).startswith(Delimiter);
978 }
979 }
980 return false;
981}
982
Daniel Jasperde0328a2013-08-16 11:20:30 +0000983unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
984 LineState &State,
985 bool DryRun) {
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000986 // Don't break multi-line tokens other than block comments. Instead, just
987 // update the state.
988 if (Current.Type != TT_BlockComment && Current.IsMultiline)
989 return addMultilineToken(Current, State);
990
Daniel Jasper98857842013-10-30 13:54:53 +0000991 // Don't break implicit string literals.
992 if (Current.Type == TT_ImplicitStringLiteral)
993 return 0;
994
Daniel Jasper04b6a082013-12-20 06:22:01 +0000995 if (!Current.isStringLiteral() && !Current.is(tok::comment))
Daniel Jasperf93551c2013-08-23 10:05:49 +0000996 return 0;
997
Ahmed Charlesb8984322014-03-07 20:03:18 +0000998 std::unique_ptr<BreakableToken> Token;
Alexander Kornienko39856b72013-09-10 09:38:25 +0000999 unsigned StartColumn = State.Column - Current.ColumnWidth;
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001000 unsigned ColumnLimit = getColumnLimit(State);
Daniel Jasperde0328a2013-08-16 11:20:30 +00001001
Daniel Jasper04b6a082013-12-20 06:22:01 +00001002 if (Current.isStringLiteral()) {
Alexander Kornienko384b40b2013-10-11 21:43:05 +00001003 // Don't break string literals inside preprocessor directives (except for
1004 // #define directives, as their contents are stored in separate lines and
1005 // are not affected by this check).
1006 // This way we avoid breaking code with line directives and unknown
1007 // preprocessor directives that contain long string literals.
1008 if (State.Line->Type == LT_PreprocessorDirective)
1009 return 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001010 // Exempts unterminated string literals from line breaking. The user will
1011 // likely want to terminate the string before any line breaking is done.
1012 if (Current.IsUnterminatedLiteral)
1013 return 0;
1014
Alexander Kornienko81e32942013-09-16 20:20:49 +00001015 StringRef Text = Current.TokenText;
1016 StringRef Prefix;
1017 StringRef Postfix;
Daniel Jasper174b0122014-01-09 14:18:12 +00001018 bool IsNSStringLiteral = false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001019 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
1020 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
1021 // reduce the overhead) for each FormatToken, which is a string, so that we
1022 // don't run multiple checks here on the hot path.
Daniel Jasper174b0122014-01-09 14:18:12 +00001023 if (Text.startswith("\"") && Current.Previous &&
1024 Current.Previous->is(tok::at)) {
1025 IsNSStringLiteral = true;
1026 Prefix = "@\"";
Daniel Jasper174b0122014-01-09 14:18:12 +00001027 }
Alexander Kornienko81e32942013-09-16 20:20:49 +00001028 if ((Text.endswith(Postfix = "\"") &&
Daniel Jasper174b0122014-01-09 14:18:12 +00001029 (IsNSStringLiteral || Text.startswith(Prefix = "\"") ||
1030 Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
1031 Text.startswith(Prefix = "u8\"") ||
Alexander Kornienko81e32942013-09-16 20:20:49 +00001032 Text.startswith(Prefix = "L\""))) ||
1033 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")")) ||
1034 getRawStringLiteralPrefixPostfix(Text, Prefix, Postfix)) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001035 Token.reset(new BreakableStringLiteral(
1036 Current, State.Line->Level, StartColumn, Prefix, Postfix,
1037 State.Line->InPPDirective, Encoding, Style));
Alexander Kornienko81e32942013-09-16 20:20:49 +00001038 } else {
1039 return 0;
1040 }
Daniel Jasperde0328a2013-08-16 11:20:30 +00001041 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
Alexander Kornienkoce9161a2014-01-02 15:13:14 +00001042 if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
1043 return 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001044 Token.reset(new BreakableBlockComment(
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001045 Current, State.Line->Level, StartColumn, Current.OriginalColumn,
1046 !Current.Previous, State.Line->InPPDirective, Encoding, Style));
Daniel Jasperde0328a2013-08-16 11:20:30 +00001047 } else if (Current.Type == TT_LineComment &&
Craig Topper2145bc02014-05-09 08:15:10 +00001048 (Current.Previous == nullptr ||
Daniel Jasperde0328a2013-08-16 11:20:30 +00001049 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienkoce9161a2014-01-02 15:13:14 +00001050 if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
1051 return 0;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001052 Token.reset(new BreakableLineComment(Current, State.Line->Level,
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001053 StartColumn, /*InPPDirective=*/false,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001054 Encoding, Style));
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001055 // We don't insert backslashes when breaking line comments.
1056 ColumnLimit = Style.ColumnLimit;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001057 } else {
1058 return 0;
1059 }
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001060 if (Current.UnbreakableTailLength >= ColumnLimit)
Daniel Jasperde0328a2013-08-16 11:20:30 +00001061 return 0;
1062
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001063 unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001064 bool BreakInserted = false;
1065 unsigned Penalty = 0;
1066 unsigned RemainingTokenColumns = 0;
1067 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
1068 LineIndex != EndIndex; ++LineIndex) {
1069 if (!DryRun)
1070 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
1071 unsigned TailOffset = 0;
1072 RemainingTokenColumns =
1073 Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
1074 while (RemainingTokenColumns > RemainingSpace) {
1075 BreakableToken::Split Split =
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001076 Token->getSplit(LineIndex, TailOffset, ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +00001077 if (Split.first == StringRef::npos) {
1078 // The last line's penalty is handled in addNextStateToQueue().
1079 if (LineIndex < EndIndex - 1)
1080 Penalty += Style.PenaltyExcessCharacter *
1081 (RemainingTokenColumns - RemainingSpace);
1082 break;
1083 }
1084 assert(Split.first != 0);
1085 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
1086 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
Alexander Kornienko875395f2013-11-12 17:50:13 +00001087
1088 // We can remove extra whitespace instead of breaking the line.
1089 if (RemainingTokenColumns + 1 - Split.second <= RemainingSpace) {
1090 RemainingTokenColumns = 0;
1091 if (!DryRun)
1092 Token->replaceWhitespace(LineIndex, TailOffset, Split, Whitespaces);
1093 break;
1094 }
1095
Alexander Kornienko64a42b82014-04-15 14:52:43 +00001096 // When breaking before a tab character, it may be moved by a few columns,
1097 // but will still be expanded to the next tab stop, so we don't save any
1098 // columns.
1099 if (NewRemainingTokenColumns == RemainingTokenColumns)
1100 break;
1101
Daniel Jasperde0328a2013-08-16 11:20:30 +00001102 assert(NewRemainingTokenColumns < RemainingTokenColumns);
1103 if (!DryRun)
1104 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Daniel Jasper2739af32013-08-28 10:03:58 +00001105 Penalty += Current.SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001106 unsigned ColumnsUsed =
1107 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001108 if (ColumnsUsed > ColumnLimit) {
1109 Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +00001110 }
1111 TailOffset += Split.first + Split.second;
1112 RemainingTokenColumns = NewRemainingTokenColumns;
1113 BreakInserted = true;
1114 }
1115 }
1116
1117 State.Column = RemainingTokenColumns;
1118
1119 if (BreakInserted) {
1120 // If we break the token inside a parameter list, we need to break before
1121 // the next parameter on all levels, so that the next parameter is clearly
1122 // visible. Line comments already introduce a break.
1123 if (Current.Type != TT_LineComment) {
1124 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1125 State.Stack[i].BreakBeforeParameter = true;
1126 }
1127
Daniel Jasper04b6a082013-12-20 06:22:01 +00001128 Penalty += Current.isStringLiteral() ? Style.PenaltyBreakString
1129 : Style.PenaltyBreakComment;
Daniel Jasper2739af32013-08-28 10:03:58 +00001130
Daniel Jasperde0328a2013-08-16 11:20:30 +00001131 State.Stack.back().LastSpace = StartColumn;
1132 }
1133 return Penalty;
1134}
1135
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001136unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001137 // In preprocessor directives reserve two chars for trailing " \"
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001138 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
Daniel Jasperde0328a2013-08-16 11:20:30 +00001139}
1140
Daniel Jasperc39b56f2013-12-16 07:23:08 +00001141bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
Daniel Jasperf438cb72013-08-23 11:57:34 +00001142 const FormatToken &Current = *State.NextToken;
Daniel Jasper9509f182014-05-05 08:08:07 +00001143 if (!Current.isStringLiteral() || Current.Type == TT_ImplicitStringLiteral)
Daniel Jasperf438cb72013-08-23 11:57:34 +00001144 return false;
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00001145 // We never consider raw string literals "multiline" for the purpose of
Daniel Jasperc39b56f2013-12-16 07:23:08 +00001146 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
1147 // (see TokenAnnotator::mustBreakBefore().
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00001148 if (Current.TokenText.startswith("R\""))
1149 return false;
Alexander Kornienko39856b72013-09-10 09:38:25 +00001150 if (Current.IsMultiline)
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00001151 return true;
Daniel Jasperf438cb72013-08-23 11:57:34 +00001152 if (Current.getNextNonComment() &&
Daniel Jasper04b6a082013-12-20 06:22:01 +00001153 Current.getNextNonComment()->isStringLiteral())
Daniel Jasperf438cb72013-08-23 11:57:34 +00001154 return true; // Implicit concatenation.
Alexander Kornienko39856b72013-09-10 09:38:25 +00001155 if (State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
Daniel Jasperf438cb72013-08-23 11:57:34 +00001156 Style.ColumnLimit)
1157 return true; // String will be split.
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00001158 return false;
Daniel Jasperf438cb72013-08-23 11:57:34 +00001159}
1160
Daniel Jasperde0328a2013-08-16 11:20:30 +00001161} // namespace format
1162} // namespace clang