blob: 5f55e0daa06d2401156f2c86fc41a705d2e931b6 [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;
Daniel Jaspera98b7b02014-11-25 10:05:17 +000051 if (Current.is(TT_CtorInitializerComma) &&
Daniel Jasperec01cd62013-10-08 05:11:18 +000052 Style.BreakConstructorInitializersBeforeComma)
53 return true;
54 return Previous.is(tok::comma) && !Current.isTrailingComment() &&
Daniel Jaspera98b7b02014-11-25 10:05:17 +000055 (Previous.isNot(TT_CtorInitializerComma) ||
Daniel Jasperec01cd62013-10-08 05:11:18 +000056 !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 Jaspera98b7b02014-11-25 10:05:17 +0000102 Previous.isNot(TT_DictLiteral) && Previous.BlockKind == BK_BracedInit &&
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000103 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.
Daniel Jasper4b444492014-11-21 13:38:53 +0000120 if (Previous.is(tok::l_brace) && State.Stack.size() > 1 &&
121 State.Stack[State.Stack.size() - 2].NestedBlockInlined &&
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000122 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.
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000127 if (Current.is(TT_FunctionDeclarationName) &&
Daniel Jaspere068ac72014-10-27 17:13:59 +0000128 !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;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000137 if (Current.MustBreakBefore || Current.is(TT_InlineASMColon))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000138 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 &&
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000146 (Current.is(tok::question) ||
147 (Current.is(TT_ConditionalExpr) && Previous.isNot(tok::question)))) ||
Daniel Jasper165b29e2013-11-08 00:57:11 +0000148 (!Style.BreakBeforeTernaryOperators &&
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000149 (Previous.is(tok::question) || Previous.is(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 Jaspera98b7b02014-11-25 10:05:17 +0000156 !Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) &&
157 nextIsMultilineString(State))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000158 return true;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000159 if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) ||
160 Previous.is(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 Jaspera98b7b02014-11-25 10:05:17 +0000164 if (Current.is(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 Jasper8c6e9ef2014-12-02 09:46:56 +0000171 if (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000172 // 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.
Daniel Jasperde0328a2013-08-16 11:20:30 +0000181 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
182 Previous.getPrecedence() == prec::Equality) &&
183 Previous.Previous &&
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000184 Previous.Previous->isNot(TT_BinaryOperator); // For >>.
Daniel Jasperde0328a2013-08-16 11:20:30 +0000185 bool LHSIsBinaryExpr =
Daniel Jasper562ecd42013-09-06 08:08:14 +0000186 Previous.Previous && Previous.Previous->EndsBinaryExpression;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000187 if (Previous.is(TT_BinaryOperator) && (!IsComparison || LHSIsBinaryExpr) &&
188 Current.isNot(TT_BinaryOperator) && // For >>.
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000189 !Current.isTrailingComment() && !Previous.is(tok::lessless) &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000190 Previous.getPrecedence() != prec::Assignment &&
191 State.Stack.back().BreakBeforeParameter)
192 return true;
Daniel Jasper3219e432014-12-02 13:24:51 +0000193 } else {
194 if (Current.is(TT_BinaryOperator) && Previous.EndsBinaryExpression &&
195 State.Stack.back().BreakBeforeParameter)
196 return true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000197 }
198
Daniel Jasper3219e432014-12-02 13:24:51 +0000199
Daniel Jasperde0328a2013-08-16 11:20:30 +0000200 // Same as above, but for the first "<<" operator.
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000201 if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator) &&
Alexander Kornienko86b2dfd2014-03-06 15:13:08 +0000202 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000203 State.Stack.back().FirstLessLess == 0)
204 return true;
205
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000206 if (Current.is(TT_SelectorName) && State.Stack.back().ObjCSelectorNameFound &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000207 State.Stack.back().BreakBeforeParameter)
208 return true;
Daniel Jasper211e1322014-12-08 20:08:04 +0000209 if (Current.NestingLevel == 0 && !Current.isTrailingComment()) {
210 if (Previous.ClosesTemplateDeclaration)
211 return true;
212 if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren))
213 return true;
214 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000215
Daniel Jasper4355e7f2014-07-09 07:50:33 +0000216 // If the return type spans multiple lines, wrap before the function name.
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000217 if (Current.isOneOf(TT_FunctionDeclarationName ,tok::kw_operator) &&
Daniel Jasper4355e7f2014-07-09 07:50:33 +0000218 State.Stack.back().BreakBeforeParameter)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000219 return true;
Daniel Jasper4355e7f2014-07-09 07:50:33 +0000220
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000221 if (startsSegmentOfBuilderTypeCall(Current) &&
Daniel Jasperf8151e92013-08-30 07:12:40 +0000222 (State.Stack.back().CallContinuation != 0 ||
223 (State.Stack.back().BreakBeforeParameter &&
224 State.Stack.back().ContainsUnwrappedBuilder)))
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000225 return true;
Daniel Jasper96972812014-01-05 12:38:10 +0000226
227 // The following could be precomputed as they do not depend on the state.
228 // However, as they should take effect only if the UnwrappedLine does not fit
229 // into the ColumnLimit, they are checked here in the ContinuationIndenter.
Daniel Jasper35995672014-04-29 14:05:20 +0000230 if (Style.ColumnLimit != 0 && Previous.BlockKind == BK_Block &&
231 Previous.is(tok::l_brace) && !Current.isOneOf(tok::r_brace, tok::comment))
Daniel Jasper96972812014-01-05 12:38:10 +0000232 return true;
Daniel Jasper96972812014-01-05 12:38:10 +0000233
Daniel Jasperde0328a2013-08-16 11:20:30 +0000234 return false;
235}
236
237unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000238 bool DryRun,
239 unsigned ExtraSpaces) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000240 const FormatToken &Current = *State.NextToken;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000241
Manuel Klimek819788d2014-03-18 11:22:45 +0000242 assert(!State.Stack.empty());
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000243 if ((Current.is(TT_ImplicitStringLiteral) &&
Craig Topper2145bc02014-05-09 08:15:10 +0000244 (Current.Previous->Tok.getIdentifierInfo() == nullptr ||
Daniel Jasper98857842013-10-30 13:54:53 +0000245 Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
246 tok::pp_not_keyword))) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000247 // FIXME: Is this correct?
248 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
249 State.NextToken->WhitespaceRange.getEnd()) -
250 SourceMgr.getSpellingColumnNumber(
251 State.NextToken->WhitespaceRange.getBegin());
Daniel Jasperda353cd2014-03-12 08:24:47 +0000252 State.Column += WhitespaceLength;
Daniel Jasper240dfda2014-03-31 14:23:49 +0000253 moveStateToNextToken(State, DryRun, /*Newline=*/false);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000254 return 0;
255 }
256
Alexander Kornienko1f803962013-10-01 14:41:18 +0000257 unsigned Penalty = 0;
258 if (Newline)
259 Penalty = addTokenOnNewLine(State, DryRun);
260 else
Daniel Jasper48437ce2013-11-20 14:54:39 +0000261 addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000262
263 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
264}
265
Daniel Jasper48437ce2013-11-20 14:54:39 +0000266void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
267 unsigned ExtraSpaces) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000268 FormatToken &Current = *State.NextToken;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000269 const FormatToken &Previous = *State.NextToken->Previous;
270 if (Current.is(tok::equal) &&
Daniel Jasper05cd5862014-05-08 12:21:30 +0000271 (State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) &&
Alexander Kornienko1f803962013-10-01 14:41:18 +0000272 State.Stack.back().VariablePos == 0) {
273 State.Stack.back().VariablePos = State.Column;
274 // Move over * and & if they are bound to the variable name.
275 const FormatToken *Tok = &Previous;
276 while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
277 State.Stack.back().VariablePos -= Tok->ColumnWidth;
278 if (Tok->SpacesRequiredBefore != 0)
279 break;
280 Tok = Tok->Previous;
281 }
282 if (Previous.PartOfMultiVariableDeclStmt)
283 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
284 }
285
286 unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
287
288 if (!DryRun)
289 Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, /*IndentLevel=*/0,
290 Spaces, State.Column + Spaces);
291
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000292 if (Current.is(TT_SelectorName) &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000293 !State.Stack.back().ObjCSelectorNameFound) {
294 if (Current.LongestObjCSelectorName == 0)
295 State.Stack.back().AlignColons = false;
296 else if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
297 State.Column + Spaces + Current.ColumnWidth)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000298 State.Stack.back().ColonPos =
299 State.Stack.back().Indent + Current.LongestObjCSelectorName;
300 else
301 State.Stack.back().ColonPos = State.Column + Spaces + Current.ColumnWidth;
302 }
303
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000304 if (Style.AlignAfterOpenBracket && Previous.opensScope() &&
305 Previous.isNot(TT_ObjCMethodExpr) &&
306 (Current.isNot(TT_LineComment) || Previous.BlockKind == BK_BracedInit))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000307 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasperec01cd62013-10-08 05:11:18 +0000308 if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000309 State.Stack.back().NoLineBreak = true;
310 if (startsSegmentOfBuilderTypeCall(Current))
311 State.Stack.back().ContainsUnwrappedBuilder = true;
312
Daniel Jasperd6f17d82014-09-12 16:35:28 +0000313 if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&
314 (Previous.MatchingParen &&
315 (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10))) {
316 // If there is a function call with long parameters, break before trailing
317 // calls. This prevents things like:
318 // EXPECT_CALL(SomeLongParameter).Times(
319 // 2);
320 // We don't want to do this for short parameters as they can just be
321 // indexes.
322 State.Stack.back().NoLineBreak = true;
323 }
324
Alexander Kornienko1f803962013-10-01 14:41:18 +0000325 State.Column += Spaces;
Daniel Jasper8acf8222014-05-07 09:23:05 +0000326 if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&
327 Previous.Previous && Previous.Previous->isOneOf(tok::kw_if, tok::kw_for))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000328 // Treat the condition inside an if as if it was a second function
Daniel Jasper6633ab82013-10-18 10:38:14 +0000329 // parameter, i.e. let nested calls have a continuation indent.
Daniel Jasper8acf8222014-05-07 09:23:05 +0000330 State.Stack.back().LastSpace = State.Column;
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000331 else if (!Current.isOneOf(tok::comment, tok::caret) &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000332 (Previous.is(tok::comma) ||
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000333 (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr))))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000334 State.Stack.back().LastSpace = State.Column;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000335 else if ((Previous.isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
336 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 Jaspera98b7b02014-11-25 10:05:17 +0000345 else if (Previous.is(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 Jaspera98b7b02014-11-25 10:05:17 +0000399 } else if (NextNonComment->is(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) &&
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000412 PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000413 // FIXME: This is hacky, find a better way. The problem is that in an ObjC
414 // method expression, the block should be aligned to the line starting it,
415 // e.g.:
416 // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
417 // ^(int *i) {
418 // // ...
419 // }];
Daniel Jasper05cd5862014-05-08 12:21:30 +0000420 // Thus, we set LastSpace of the next higher NestingLevel, to which we move
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000421 // when we consume all of the "}"'s FakeRParens at the "{".
Daniel Jasper9a26e772013-12-23 11:25:40 +0000422 if (State.Stack.size() > 1)
Daniel Jasper9f388d02014-03-27 14:33:30 +0000423 State.Stack[State.Stack.size() - 2].LastSpace =
424 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
425 Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000426 }
427
Alexander Kornienko1f803962013-10-01 14:41:18 +0000428 if ((Previous.isOneOf(tok::comma, tok::semi) &&
429 !State.Stack.back().AvoidBinPacking) ||
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000430 Previous.is(TT_BinaryOperator))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000431 State.Stack.back().BreakBeforeParameter = false;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000432 if (Previous.isOneOf(TT_TemplateCloser, TT_JavaAnnotation) &&
Daniel Jasper39af6cd2014-11-03 02:27:28 +0000433 Current.NestingLevel == 0)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000434 State.Stack.back().BreakBeforeParameter = false;
Daniel Jaspera0407742014-02-11 10:08:11 +0000435 if (NextNonComment->is(tok::question) ||
Daniel Jasper165b29e2013-11-08 00:57:11 +0000436 (PreviousNonComment && PreviousNonComment->is(tok::question)))
437 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000438
439 if (!DryRun) {
Daniel Jaspera69ca9b2014-06-04 12:40:57 +0000440 unsigned Newlines = std::max(
441 1u, std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1));
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000442 Whitespaces.replaceWhitespace(Current, Newlines,
443 State.Stack.back().IndentLevel, State.Column,
444 State.Column, State.Line->InPPDirective);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000445 }
446
447 if (!Current.isTrailingComment())
448 State.Stack.back().LastSpace = State.Column;
Daniel Jasper05cd5862014-05-08 12:21:30 +0000449 State.StartOfLineLevel = Current.NestingLevel;
450 State.LowestLevelOnLine = Current.NestingLevel;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000451
452 // Any break on this level means that the parent level has been broken
453 // and we need to avoid bin packing there.
Daniel Jasper4b444492014-11-21 13:38:53 +0000454 bool NestedBlockSpecialCase =
455 Current.is(tok::r_brace) && State.Stack.size() > 1 &&
456 State.Stack[State.Stack.size() - 2].NestedBlockInlined;
457 if (!NestedBlockSpecialCase) {
Daniel Jasperb16b9692014-05-21 12:51:23 +0000458 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
459 State.Stack[i].BreakBeforeParameter = true;
460 }
Alexander Kornienko1f803962013-10-01 14:41:18 +0000461 }
Daniel Jasperb16b9692014-05-21 12:51:23 +0000462
Daniel Jasper9e5ede02013-11-08 19:56:28 +0000463 if (PreviousNonComment &&
464 !PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000465 (PreviousNonComment->isNot(TT_TemplateCloser) ||
Daniel Jasper6c0ee172014-11-14 13:14:45 +0000466 Current.NestingLevel != 0) &&
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000467 !PreviousNonComment->isOneOf(TT_BinaryOperator, TT_JavaAnnotation,
468 TT_LeadingJavaAnnotation) &&
469 Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope())
Alexander Kornienko1f803962013-10-01 14:41:18 +0000470 State.Stack.back().BreakBeforeParameter = true;
471
Daniel Jasper1db6c382013-10-22 15:30:28 +0000472 // If we break after { or the [ of an array initializer, we should also break
473 // before the corresponding } or ].
Daniel Jasper90818052014-06-10 10:42:26 +0000474 if (PreviousNonComment &&
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000475 (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000476 State.Stack.back().BreakBeforeClosingBrace = true;
477
478 if (State.Stack.back().AvoidBinPacking) {
479 // If we are breaking after '(', '{', '<', this is not bin packing
Daniel Jasper2a958322014-05-21 13:26:58 +0000480 // unless AllowAllParametersOfDeclarationOnNextLine is false or this is a
481 // dict/object literal.
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000482 if (!Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) ||
Alexander Kornienko1f803962013-10-01 14:41:18 +0000483 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
Daniel Jasper2a958322014-05-21 13:26:58 +0000484 State.Line->MustBeDeclaration) ||
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000485 Previous.is(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 Jasper50b4bd72014-11-02 19:16:41 +0000505
506 // Java specific bits.
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000507 if (Style.Language == FormatStyle::LK_Java &&
508 Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends))
Daniel Jasper50b4bd72014-11-02 19:16:41 +0000509 return std::max(State.Stack.back().LastSpace,
510 State.Stack.back().Indent + Style.ContinuationIndentWidth);
511
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000512 if (NextNonComment->is(tok::l_brace) && NextNonComment->BlockKind == BK_Block)
Daniel Jasper05cd5862014-05-08 12:21:30 +0000513 return Current.NestingLevel == 0 ? State.FirstIndent
514 : State.Stack.back().Indent;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000515 if (Current.isOneOf(tok::r_brace, tok::r_square)) {
Daniel Jasperb16b9692014-05-21 12:51:23 +0000516 if (State.Stack.size() > 1 &&
Daniel Jasper4b444492014-11-21 13:38:53 +0000517 State.Stack[State.Stack.size() - 2].NestedBlockInlined)
Daniel Jasperb16b9692014-05-21 12:51:23 +0000518 return State.FirstIndent;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000519 if (Current.closesBlockTypeList(Style) ||
520 (Current.MatchingParen &&
521 Current.MatchingParen->BlockKind == BK_BracedInit))
522 return State.Stack[State.Stack.size() - 2].LastSpace;
523 else
524 return State.FirstIndent;
525 }
Daniel Jasper783bac62014-04-15 09:54:30 +0000526 if (Current.is(tok::identifier) && Current.Next &&
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000527 Current.Next->is(TT_DictLiteral))
Daniel Jasper783bac62014-04-15 09:54:30 +0000528 return State.Stack.back().Indent;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000529 if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
530 return State.StartOfStringLiteral;
531 if (NextNonComment->is(tok::lessless) &&
532 State.Stack.back().FirstLessLess != 0)
533 return State.Stack.back().FirstLessLess;
534 if (NextNonComment->isMemberAccess()) {
535 if (State.Stack.back().CallContinuation == 0) {
536 return ContinuationIndent;
537 } else {
538 return State.Stack.back().CallContinuation;
539 }
540 }
541 if (State.Stack.back().QuestionColumn != 0 &&
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000542 ((NextNonComment->is(tok::colon) &&
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000543 NextNonComment->is(TT_ConditionalExpr)) ||
544 Previous.is(TT_ConditionalExpr)))
Daniel Jasper9f388d02014-03-27 14:33:30 +0000545 return State.Stack.back().QuestionColumn;
546 if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0)
547 return State.Stack.back().VariablePos;
Daniel Jaspere9ab42d2014-10-31 18:23:49 +0000548 if ((PreviousNonComment &&
549 (PreviousNonComment->ClosesTemplateDeclaration ||
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000550 PreviousNonComment->isOneOf(TT_AttributeParen, TT_JavaAnnotation,
551 TT_LeadingJavaAnnotation))) ||
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000552 (!Style.IndentWrappedFunctionNames &&
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000553 NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName)))
Daniel Jasper9f388d02014-03-27 14:33:30 +0000554 return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000555 if (NextNonComment->is(TT_SelectorName)) {
Daniel Jasper9f388d02014-03-27 14:33:30 +0000556 if (!State.Stack.back().ObjCSelectorNameFound) {
557 if (NextNonComment->LongestObjCSelectorName == 0) {
558 return State.Stack.back().Indent;
559 } else {
560 return State.Stack.back().Indent +
561 NextNonComment->LongestObjCSelectorName -
562 NextNonComment->ColumnWidth;
563 }
564 } else if (!State.Stack.back().AlignColons) {
565 return State.Stack.back().Indent;
566 } else if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth) {
567 return State.Stack.back().ColonPos - NextNonComment->ColumnWidth;
568 } else {
569 return State.Stack.back().Indent;
570 }
571 }
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000572 if (NextNonComment->is(TT_ArraySubscriptLSquare)) {
Daniel Jasper9f388d02014-03-27 14:33:30 +0000573 if (State.Stack.back().StartOfArraySubscripts != 0)
574 return State.Stack.back().StartOfArraySubscripts;
575 else
576 return ContinuationIndent;
577 }
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000578 if (NextNonComment->is(TT_StartOfName) ||
Daniel Jasper9f388d02014-03-27 14:33:30 +0000579 Previous.isOneOf(tok::coloncolon, tok::equal)) {
580 return ContinuationIndent;
581 }
582 if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000583 PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))
Daniel Jasper9f388d02014-03-27 14:33:30 +0000584 return ContinuationIndent;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000585 if (NextNonComment->is(TT_CtorInitializerColon))
Daniel Jasper9f388d02014-03-27 14:33:30 +0000586 return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000587 if (NextNonComment->is(TT_CtorInitializerComma))
Daniel Jasper9f388d02014-03-27 14:33:30 +0000588 return State.Stack.back().Indent;
Daniel Jasper316ab382014-08-06 13:14:58 +0000589 if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() &&
Daniel Jasper119ff532014-11-14 12:31:14 +0000590 !Current.isOneOf(tok::colon, tok::comment))
Daniel Jasper316ab382014-08-06 13:14:58 +0000591 return ContinuationIndent;
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000592 if (State.Stack.back().Indent == State.FirstIndent && PreviousNonComment &&
Daniel Jasper9f388d02014-03-27 14:33:30 +0000593 PreviousNonComment->isNot(tok::r_brace))
594 // Ensure that we fall back to the continuation indent width instead of
595 // just flushing continuations left.
596 return State.Stack.back().Indent + Style.ContinuationIndentWidth;
597 return State.Stack.back().Indent;
598}
599
Daniel Jasperde0328a2013-08-16 11:20:30 +0000600unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
601 bool DryRun, bool Newline) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000602 assert(State.Stack.size());
Daniel Jasper60553be2014-05-26 13:10:39 +0000603 const FormatToken &Current = *State.NextToken;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000604
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000605 if (Current.is(TT_InheritanceColon))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000606 State.Stack.back().AvoidBinPacking = true;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000607 if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) {
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000608 if (State.Stack.back().FirstLessLess == 0)
609 State.Stack.back().FirstLessLess = State.Column;
610 else
611 State.Stack.back().LastOperatorWrapped = Newline;
612 }
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000613 if ((Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless)) ||
614 Current.is(TT_ConditionalExpr))
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000615 State.Stack.back().LastOperatorWrapped = Newline;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000616 if (Current.is(TT_ArraySubscriptLSquare) &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000617 State.Stack.back().StartOfArraySubscripts == 0)
618 State.Stack.back().StartOfArraySubscripts = State.Column;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000619 if ((Current.is(tok::question) && Style.BreakBeforeTernaryOperators) ||
620 (Current.getPreviousNonComment() && Current.isNot(tok::colon) &&
621 Current.getPreviousNonComment()->is(tok::question) &&
622 !Style.BreakBeforeTernaryOperators))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000623 State.Stack.back().QuestionColumn = State.Column;
624 if (!Current.opensScope() && !Current.closesScope())
625 State.LowestLevelOnLine =
Daniel Jasper05cd5862014-05-08 12:21:30 +0000626 std::min(State.LowestLevelOnLine, Current.NestingLevel);
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000627 if (Current.isMemberAccess())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000628 State.Stack.back().StartOfFunctionCall =
Daniel Jasper0e617842014-04-16 12:26:54 +0000629 Current.LastOperator ? 0 : State.Column + Current.ColumnWidth;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000630 if (Current.is(TT_SelectorName))
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000631 State.Stack.back().ObjCSelectorNameFound = true;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000632 if (Current.is(TT_CtorInitializerColon)) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000633 // Indent 2 from the column, so:
634 // SomeClass::SomeClass()
635 // : First(...), ...
636 // Next(...)
637 // ^ line up here.
638 State.Stack.back().Indent =
639 State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
640 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
641 State.Stack.back().AvoidBinPacking = true;
642 State.Stack.back().BreakBeforeParameter = false;
643 }
644
Daniel Jasperde0328a2013-08-16 11:20:30 +0000645 // In ObjC method declaration we align on the ":" of parameters, but we need
Daniel Jasper6633ab82013-10-18 10:38:14 +0000646 // to ensure that we indent parameters on subsequent lines by at least our
647 // continuation indent width.
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000648 if (Current.is(TT_ObjCMethodSpecifier))
Daniel Jasper6633ab82013-10-18 10:38:14 +0000649 State.Stack.back().Indent += Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000650
651 // Insert scopes created by fake parenthesis.
652 const FormatToken *Previous = Current.getPreviousNonComment();
Daniel Jasperb16b9692014-05-21 12:51:23 +0000653
654 // Add special behavior to support a format commonly used for JavaScript
655 // closures:
656 // SomeFunction(function() {
657 // foo();
658 // bar();
659 // }, a, b, c);
Daniel Jasper4b444492014-11-21 13:38:53 +0000660 if (Current.isNot(tok::comment) && Previous && Previous->is(tok::l_brace) &&
661 State.Stack.size() > 1) {
662 if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline) {
663 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
664 State.Stack[i].NoLineBreak = true;
Daniel Jasperb16b9692014-05-21 12:51:23 +0000665 }
Daniel Jasperb16b9692014-05-21 12:51:23 +0000666 }
Daniel Jasper4b444492014-11-21 13:38:53 +0000667 State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;
668 }
669 if (Previous && (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) ||
670 Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr)) &&
671 !Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
672 State.Stack.back().NestedBlockInlined =
673 !Newline &&
674 (Previous->isNot(tok::l_paren) || Previous->ParameterCount > 1) && !Newline;
Daniel Jasperb16b9692014-05-21 12:51:23 +0000675 }
676
Daniel Jasper60553be2014-05-26 13:10:39 +0000677 moveStatePastFakeLParens(State, Newline);
678 moveStatePastScopeOpener(State, Newline);
679 moveStatePastScopeCloser(State);
680 moveStatePastFakeRParens(State);
681
682 if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) {
683 State.StartOfStringLiteral = State.Column;
684 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
685 !Current.isStringLiteral()) {
686 State.StartOfStringLiteral = 0;
687 }
688
689 State.Column += Current.ColumnWidth;
690 State.NextToken = State.NextToken->Next;
691 unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
692 if (State.Column > getColumnLimit(State)) {
693 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
694 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
695 }
696
697 if (Current.Role)
698 Current.Role->formatFromToken(State, this, DryRun);
699 // If the previous has a special role, let it consume tokens as appropriate.
700 // It is necessary to start at the previous token for the only implemented
701 // role (comma separated list). That way, the decision whether or not to break
702 // after the "{" is already done and both options are tried and evaluated.
703 // FIXME: This is ugly, find a better way.
704 if (Previous && Previous->Role)
705 Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
706
707 return Penalty;
708}
709
710void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
711 bool Newline) {
712 const FormatToken &Current = *State.NextToken;
713 const FormatToken *Previous = Current.getPreviousNonComment();
714
Daniel Jasperde0328a2013-08-16 11:20:30 +0000715 // Don't add extra indentation for the first fake parenthesis after
Dinesh Dwivedi0db806b2014-05-01 17:19:34 +0000716 // 'return', assignments or opening <({[. The indentation for these cases
Daniel Jasperde0328a2013-08-16 11:20:30 +0000717 // is special cased.
718 bool SkipFirstExtraIndent =
Daniel Jaspereabede62013-09-30 08:29:03 +0000719 (Previous && (Previous->opensScope() || Previous->is(tok::kw_return) ||
Daniel Jasper3219e432014-12-02 13:24:51 +0000720 (Previous->getPrecedence() == prec::Assignment &&
721 Style.AlignOperands) ||
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000722 Previous->is(TT_ObjCMethodExpr)));
Daniel Jasperde0328a2013-08-16 11:20:30 +0000723 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
724 I = Current.FakeLParens.rbegin(),
725 E = Current.FakeLParens.rend();
726 I != E; ++I) {
727 ParenState NewParenState = State.Stack.back();
728 NewParenState.ContainsLineBreak = false;
Daniel Jaspereabede62013-09-30 08:29:03 +0000729
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000730 // Indent from 'LastSpace' unless these are fake parentheses encapsulating
731 // a builder type call after 'return' or, if the alignment after opening
732 // brackets is disabled.
Daniel Jasper4281c5a2014-10-07 14:45:34 +0000733 if (!Current.isTrailingComment() &&
Daniel Jasper3219e432014-12-02 13:24:51 +0000734 (Style.AlignOperands || *I < prec::Assignment) &&
Daniel Jasper6cab6782014-11-20 09:54:49 +0000735 (!Previous || Previous->isNot(tok::kw_return) ||
736 (Style.Language != FormatStyle::LK_Java && *I > 0)) &&
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000737 (Style.AlignAfterOpenBracket || *I != prec::Comma ||
738 Current.NestingLevel == 0))
Daniel Jaspereabede62013-09-30 08:29:03 +0000739 NewParenState.Indent =
740 std::max(std::max(State.Column, NewParenState.Indent),
741 State.Stack.back().LastSpace);
742
Daniel Jasper5c332652014-04-03 12:00:33 +0000743 // Don't allow the RHS of an operator to be split over multiple lines unless
744 // there is a line-break right after the operator.
745 // Exclude relational operators, as there, it is always more desirable to
746 // have the LHS 'left' of the RHS.
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000747 if (Previous && Previous->getPrecedence() > prec::Assignment &&
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000748 Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000749 Previous->getPrecedence() != prec::Relational) {
Daniel Jasper8c6e9ef2014-12-02 09:46:56 +0000750 bool BreakBeforeOperator =
751 Previous->is(tok::lessless) ||
752 (Previous->is(TT_BinaryOperator) &&
753 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) ||
754 (Previous->is(TT_ConditionalExpr) &&
755 Style.BreakBeforeTernaryOperators);
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000756 if ((!Newline && !BreakBeforeOperator) ||
757 (!State.Stack.back().LastOperatorWrapped && BreakBeforeOperator))
758 NewParenState.NoLineBreak = true;
759 }
Daniel Jasper5c332652014-04-03 12:00:33 +0000760
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000761 // Do not indent relative to the fake parentheses inserted for "." or "->".
762 // This is a special case to make the following to statements consistent:
763 // OuterFunction(InnerFunctionCall( // break
764 // ParameterToInnerFunction));
765 // OuterFunction(SomeObject.InnerFunctionCall( // break
766 // ParameterToInnerFunction));
767 if (*I > prec::Unknown)
768 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
Daniel Jaspera536df42014-12-08 21:28:31 +0000769 if (*I != prec::Conditional)
770 NewParenState.StartOfFunctionCall = State.Column;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000771
772 // Always indent conditional expressions. Never indent expression where
773 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
774 // prec::Assignment) as those have different indentation rules. Indent
775 // other expression, unless the indentation needs to be skipped.
776 if (*I == prec::Conditional ||
777 (!SkipFirstExtraIndent && *I > prec::Assignment &&
Daniel Jasper8c6e9ef2014-12-02 09:46:56 +0000778 !Current.isTrailingComment()))
Daniel Jasper6633ab82013-10-18 10:38:14 +0000779 NewParenState.Indent += Style.ContinuationIndentWidth;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000780 if ((Previous && !Previous->opensScope()) || *I > prec::Comma)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000781 NewParenState.BreakBeforeParameter = false;
782 State.Stack.push_back(NewParenState);
783 SkipFirstExtraIndent = false;
784 }
Daniel Jasper60553be2014-05-26 13:10:39 +0000785}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000786
Daniel Jasper335ff262014-05-28 09:11:53 +0000787// Remove the fake r_parens after 'Tok'.
788static void consumeRParens(LineState& State, const FormatToken &Tok) {
789 for (unsigned i = 0, e = Tok.FakeRParens; i != e; ++i) {
790 unsigned VariablePos = State.Stack.back().VariablePos;
791 assert(State.Stack.size() > 1);
792 if (State.Stack.size() == 1) {
793 // Do not pop the last element.
794 break;
795 }
796 State.Stack.pop_back();
797 State.Stack.back().VariablePos = VariablePos;
798 }
799}
800
801// Returns whether 'Tok' opens or closes a scope requiring special handling
802// of the subsequent fake r_parens.
803//
804// For example, if this is an l_brace starting a nested block, we pretend (wrt.
805// to indentation) that we already consumed the corresponding r_brace. Thus, we
806// remove all ParenStates caused by fake parentheses that end at the r_brace.
807// The net effect of this is that we don't indent relative to the l_brace, if
808// the nested block is the last parameter of a function. This formats:
809//
810// SomeFunction(a, [] {
811// f(); // break
812// });
813//
814// instead of:
815// SomeFunction(a, [] {
816// f(); // break
817// });
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000818static bool fakeRParenSpecialCase(const LineState &State) {
819 const FormatToken &Tok = *State.NextToken;
Daniel Jasper335ff262014-05-28 09:11:53 +0000820 if (!Tok.MatchingParen)
821 return false;
822 const FormatToken *Left = &Tok;
823 if (Tok.isOneOf(tok::r_brace, tok::r_square))
824 Left = Tok.MatchingParen;
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000825 return !State.Stack.back().HasMultipleNestedBlocks &&
826 Left->isOneOf(tok::l_brace, tok::l_square) &&
Daniel Jasper335ff262014-05-28 09:11:53 +0000827 (Left->BlockKind == BK_Block ||
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000828 Left->isOneOf(TT_ArrayInitializerLSquare, TT_DictLiteral));
Daniel Jasper335ff262014-05-28 09:11:53 +0000829}
830
Daniel Jasper60553be2014-05-26 13:10:39 +0000831void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
Daniel Jasper335ff262014-05-28 09:11:53 +0000832 // Don't remove FakeRParens attached to r_braces that surround nested blocks
833 // as they will have been removed early (see above).
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000834 if (fakeRParenSpecialCase(State))
Daniel Jasper335ff262014-05-28 09:11:53 +0000835 return;
836
837 consumeRParens(State, *State.NextToken);
Daniel Jasper60553be2014-05-26 13:10:39 +0000838}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000839
Daniel Jasper60553be2014-05-26 13:10:39 +0000840void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
841 bool Newline) {
842 const FormatToken &Current = *State.NextToken;
843 if (!Current.opensScope())
844 return;
845
846 if (Current.MatchingParen && Current.BlockKind == BK_Block) {
847 moveStateToNewBlock(State);
848 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000849 }
850
Daniel Jasper60553be2014-05-26 13:10:39 +0000851 unsigned NewIndent;
852 unsigned NewIndentLevel = State.Stack.back().IndentLevel;
853 bool AvoidBinPacking;
854 bool BreakBeforeParameter = false;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000855 if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)) {
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000856 if (fakeRParenSpecialCase(State))
Daniel Jasper335ff262014-05-28 09:11:53 +0000857 consumeRParens(State, *Current.MatchingParen);
858
Daniel Jasper60553be2014-05-26 13:10:39 +0000859 NewIndent = State.Stack.back().LastSpace;
860 if (Current.opensBlockTypeList(Style)) {
861 NewIndent += Style.IndentWidth;
862 NewIndent = std::min(State.Column + 2, NewIndent);
863 ++NewIndentLevel;
864 } else {
865 NewIndent += Style.ContinuationIndentWidth;
866 NewIndent = std::min(State.Column + 1, NewIndent);
867 }
868 const FormatToken *NextNoComment = Current.getNextNonComment();
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000869 AvoidBinPacking =
870 Current.isOneOf(TT_ArrayInitializerLSquare, TT_DictLiteral) ||
871 Style.Language == FormatStyle::LK_Proto || !Style.BinPackParameters ||
872 (NextNoComment && NextNoComment->is(TT_DesignatedInitializerPeriod));
Daniel Jasper60553be2014-05-26 13:10:39 +0000873 } else {
874 NewIndent = Style.ContinuationIndentWidth +
875 std::max(State.Stack.back().LastSpace,
876 State.Stack.back().StartOfFunctionCall);
Daniel Jasper18210d72014-10-09 09:52:05 +0000877 AvoidBinPacking =
878 (State.Line->MustBeDeclaration && !Style.BinPackParameters) ||
879 (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||
880 (Style.ExperimentalAutoDetectBinPacking &&
881 (Current.PackingKind == PPK_OnePerLine ||
882 (!BinPackInconclusiveFunctions &&
883 Current.PackingKind == PPK_Inconclusive)));
Daniel Jasper60553be2014-05-26 13:10:39 +0000884 // If this '[' opens an ObjC call, determine whether all parameters fit
885 // into one line and put one per line if they don't.
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000886 if (Current.is(TT_ObjCMethodExpr) && Style.ColumnLimit != 0 &&
Daniel Jasper60553be2014-05-26 13:10:39 +0000887 getLengthToMatchingParen(Current) + State.Column >
888 getColumnLimit(State))
889 BreakBeforeParameter = true;
890 }
Daniel Jaspera41aa532014-09-19 08:01:25 +0000891 bool NoLineBreak = State.Stack.back().NoLineBreak ||
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000892 (Current.is(TT_TemplateOpener) &&
Daniel Jaspera41aa532014-09-19 08:01:25 +0000893 State.Stack.back().ContainsUnwrappedBuilder);
Daniel Jasper60553be2014-05-26 13:10:39 +0000894 State.Stack.push_back(ParenState(NewIndent, NewIndentLevel,
895 State.Stack.back().LastSpace,
896 AvoidBinPacking, NoLineBreak));
897 State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000898 State.Stack.back().HasMultipleNestedBlocks = Current.BlockParameterCount > 1;
Daniel Jasper60553be2014-05-26 13:10:39 +0000899}
900
901void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
902 const FormatToken &Current = *State.NextToken;
903 if (!Current.closesScope())
904 return;
905
906 // If we encounter a closing ), ], } or >, we can remove a level from our
907 // stacks.
908 if (State.Stack.size() > 1 &&
909 (Current.isOneOf(tok::r_paren, tok::r_square) ||
910 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000911 State.NextToken->is(TT_TemplateCloser)))
Daniel Jasper60553be2014-05-26 13:10:39 +0000912 State.Stack.pop_back();
Daniel Jasper335ff262014-05-28 09:11:53 +0000913
Daniel Jasper60553be2014-05-26 13:10:39 +0000914 if (Current.is(tok::r_square)) {
915 // If this ends the array subscript expr, reset the corresponding value.
916 const FormatToken *NextNonComment = Current.getNextNonComment();
917 if (NextNonComment && NextNonComment->isNot(tok::l_square))
918 State.Stack.back().StartOfArraySubscripts = 0;
919 }
920}
921
922void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
Daniel Jasper60553be2014-05-26 13:10:39 +0000923 // If we have already found more than one lambda introducers on this level, we
924 // opt out of this because similarity between the lambdas is more important.
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000925 if (fakeRParenSpecialCase(State))
Daniel Jasper335ff262014-05-28 09:11:53 +0000926 consumeRParens(State, *State.NextToken->MatchingParen);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000927
Daniel Jasper50d634b2014-10-28 16:53:38 +0000928 // ObjC block sometimes follow special indentation rules.
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000929 unsigned NewIndent =
930 State.Stack.back().LastSpace + (State.NextToken->is(TT_ObjCBlockLBrace)
931 ? Style.ObjCBlockIndentWidth
932 : Style.IndentWidth);
Daniel Jasper60553be2014-05-26 13:10:39 +0000933 State.Stack.push_back(ParenState(
934 NewIndent, /*NewIndentLevel=*/State.Stack.back().IndentLevel + 1,
935 State.Stack.back().LastSpace, /*AvoidBinPacking=*/true,
936 State.Stack.back().NoLineBreak));
937 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000938}
939
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000940unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
941 LineState &State) {
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000942 // Break before further function parameters on all levels.
943 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
944 State.Stack[i].BreakBeforeParameter = true;
945
Alexander Kornienko39856b72013-09-10 09:38:25 +0000946 unsigned ColumnsUsed = State.Column;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000947 // We can only affect layout of the first and the last line, so the penalty
948 // for all other lines is constant, and we ignore it.
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000949 State.Column = Current.LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000950
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000951 if (ColumnsUsed > getColumnLimit(State))
952 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000953 return 0;
954}
955
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000956static bool getRawStringLiteralPrefixPostfix(StringRef Text, StringRef &Prefix,
Alexander Kornienko81e32942013-09-16 20:20:49 +0000957 StringRef &Postfix) {
958 if (Text.startswith(Prefix = "R\"") || Text.startswith(Prefix = "uR\"") ||
959 Text.startswith(Prefix = "UR\"") || Text.startswith(Prefix = "u8R\"") ||
960 Text.startswith(Prefix = "LR\"")) {
961 size_t ParenPos = Text.find('(');
962 if (ParenPos != StringRef::npos) {
963 StringRef Delimiter =
964 Text.substr(Prefix.size(), ParenPos - Prefix.size());
965 Prefix = Text.substr(0, ParenPos + 1);
966 Postfix = Text.substr(Text.size() - 2 - Delimiter.size());
967 return Postfix.front() == ')' && Postfix.back() == '"' &&
968 Postfix.substr(1).startswith(Delimiter);
969 }
970 }
971 return false;
972}
973
Daniel Jasperde0328a2013-08-16 11:20:30 +0000974unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
975 LineState &State,
976 bool DryRun) {
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000977 // Don't break multi-line tokens other than block comments. Instead, just
978 // update the state.
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000979 if (Current.isNot(TT_BlockComment) && Current.IsMultiline)
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000980 return addMultilineToken(Current, State);
981
Daniel Jasper616de8642014-11-23 16:46:28 +0000982 // Don't break implicit string literals or import statements.
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000983 if (Current.is(TT_ImplicitStringLiteral) ||
Daniel Jasper616de8642014-11-23 16:46:28 +0000984 State.Line->Type == LT_ImportStatement)
Daniel Jasper98857842013-10-30 13:54:53 +0000985 return 0;
986
Daniel Jasper04b6a082013-12-20 06:22:01 +0000987 if (!Current.isStringLiteral() && !Current.is(tok::comment))
Daniel Jasperf93551c2013-08-23 10:05:49 +0000988 return 0;
989
Ahmed Charlesb8984322014-03-07 20:03:18 +0000990 std::unique_ptr<BreakableToken> Token;
Alexander Kornienko39856b72013-09-10 09:38:25 +0000991 unsigned StartColumn = State.Column - Current.ColumnWidth;
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +0000992 unsigned ColumnLimit = getColumnLimit(State);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000993
Daniel Jasper04b6a082013-12-20 06:22:01 +0000994 if (Current.isStringLiteral()) {
Alexander Kornienko384b40b2013-10-11 21:43:05 +0000995 // Don't break string literals inside preprocessor directives (except for
996 // #define directives, as their contents are stored in separate lines and
997 // are not affected by this check).
998 // This way we avoid breaking code with line directives and unknown
999 // preprocessor directives that contain long string literals.
1000 if (State.Line->Type == LT_PreprocessorDirective)
1001 return 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001002 // Exempts unterminated string literals from line breaking. The user will
1003 // likely want to terminate the string before any line breaking is done.
1004 if (Current.IsUnterminatedLiteral)
1005 return 0;
1006
Alexander Kornienko81e32942013-09-16 20:20:49 +00001007 StringRef Text = Current.TokenText;
1008 StringRef Prefix;
1009 StringRef Postfix;
Daniel Jasper174b0122014-01-09 14:18:12 +00001010 bool IsNSStringLiteral = false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001011 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
1012 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
1013 // reduce the overhead) for each FormatToken, which is a string, so that we
1014 // don't run multiple checks here on the hot path.
Daniel Jasper174b0122014-01-09 14:18:12 +00001015 if (Text.startswith("\"") && Current.Previous &&
1016 Current.Previous->is(tok::at)) {
1017 IsNSStringLiteral = true;
1018 Prefix = "@\"";
Daniel Jasper174b0122014-01-09 14:18:12 +00001019 }
Alexander Kornienko81e32942013-09-16 20:20:49 +00001020 if ((Text.endswith(Postfix = "\"") &&
Daniel Jasper174b0122014-01-09 14:18:12 +00001021 (IsNSStringLiteral || Text.startswith(Prefix = "\"") ||
1022 Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
1023 Text.startswith(Prefix = "u8\"") ||
Alexander Kornienko81e32942013-09-16 20:20:49 +00001024 Text.startswith(Prefix = "L\""))) ||
1025 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")")) ||
1026 getRawStringLiteralPrefixPostfix(Text, Prefix, Postfix)) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001027 Token.reset(new BreakableStringLiteral(
1028 Current, State.Line->Level, StartColumn, Prefix, Postfix,
1029 State.Line->InPPDirective, Encoding, Style));
Alexander Kornienko81e32942013-09-16 20:20:49 +00001030 } else {
1031 return 0;
1032 }
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001033 } else if (Current.is(TT_BlockComment) && Current.isTrailingComment()) {
Alexander Kornienkoce9161a2014-01-02 15:13:14 +00001034 if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
1035 return 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001036 Token.reset(new BreakableBlockComment(
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001037 Current, State.Line->Level, StartColumn, Current.OriginalColumn,
1038 !Current.Previous, State.Line->InPPDirective, Encoding, Style));
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001039 } else if (Current.is(TT_LineComment) &&
Craig Topper2145bc02014-05-09 08:15:10 +00001040 (Current.Previous == nullptr ||
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001041 Current.Previous->isNot(TT_ImplicitStringLiteral))) {
Alexander Kornienkoce9161a2014-01-02 15:13:14 +00001042 if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
1043 return 0;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001044 Token.reset(new BreakableLineComment(Current, State.Line->Level,
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001045 StartColumn, /*InPPDirective=*/false,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001046 Encoding, Style));
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001047 // We don't insert backslashes when breaking line comments.
1048 ColumnLimit = Style.ColumnLimit;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001049 } else {
1050 return 0;
1051 }
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001052 if (Current.UnbreakableTailLength >= ColumnLimit)
Daniel Jasperde0328a2013-08-16 11:20:30 +00001053 return 0;
1054
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001055 unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001056 bool BreakInserted = false;
1057 unsigned Penalty = 0;
1058 unsigned RemainingTokenColumns = 0;
1059 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
1060 LineIndex != EndIndex; ++LineIndex) {
1061 if (!DryRun)
1062 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
1063 unsigned TailOffset = 0;
1064 RemainingTokenColumns =
1065 Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
1066 while (RemainingTokenColumns > RemainingSpace) {
1067 BreakableToken::Split Split =
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001068 Token->getSplit(LineIndex, TailOffset, ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +00001069 if (Split.first == StringRef::npos) {
1070 // The last line's penalty is handled in addNextStateToQueue().
1071 if (LineIndex < EndIndex - 1)
1072 Penalty += Style.PenaltyExcessCharacter *
1073 (RemainingTokenColumns - RemainingSpace);
1074 break;
1075 }
1076 assert(Split.first != 0);
1077 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
1078 LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
Alexander Kornienko875395f2013-11-12 17:50:13 +00001079
1080 // We can remove extra whitespace instead of breaking the line.
1081 if (RemainingTokenColumns + 1 - Split.second <= RemainingSpace) {
1082 RemainingTokenColumns = 0;
1083 if (!DryRun)
1084 Token->replaceWhitespace(LineIndex, TailOffset, Split, Whitespaces);
1085 break;
1086 }
1087
Alexander Kornienko64a42b82014-04-15 14:52:43 +00001088 // When breaking before a tab character, it may be moved by a few columns,
1089 // but will still be expanded to the next tab stop, so we don't save any
1090 // columns.
1091 if (NewRemainingTokenColumns == RemainingTokenColumns)
1092 break;
1093
Daniel Jasperde0328a2013-08-16 11:20:30 +00001094 assert(NewRemainingTokenColumns < RemainingTokenColumns);
1095 if (!DryRun)
1096 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Daniel Jasper2739af32013-08-28 10:03:58 +00001097 Penalty += Current.SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001098 unsigned ColumnsUsed =
1099 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001100 if (ColumnsUsed > ColumnLimit) {
1101 Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit);
Daniel Jasperde0328a2013-08-16 11:20:30 +00001102 }
1103 TailOffset += Split.first + Split.second;
1104 RemainingTokenColumns = NewRemainingTokenColumns;
1105 BreakInserted = true;
1106 }
1107 }
1108
1109 State.Column = RemainingTokenColumns;
1110
1111 if (BreakInserted) {
1112 // If we break the token inside a parameter list, we need to break before
1113 // the next parameter on all levels, so that the next parameter is clearly
1114 // visible. Line comments already introduce a break.
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001115 if (Current.isNot(TT_LineComment)) {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001116 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1117 State.Stack[i].BreakBeforeParameter = true;
1118 }
1119
Daniel Jasper04b6a082013-12-20 06:22:01 +00001120 Penalty += Current.isStringLiteral() ? Style.PenaltyBreakString
1121 : Style.PenaltyBreakComment;
Daniel Jasper2739af32013-08-28 10:03:58 +00001122
Daniel Jasperde0328a2013-08-16 11:20:30 +00001123 State.Stack.back().LastSpace = StartColumn;
1124 }
1125 return Penalty;
1126}
1127
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001128unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001129 // In preprocessor directives reserve two chars for trailing " \"
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001130 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
Daniel Jasperde0328a2013-08-16 11:20:30 +00001131}
1132
Daniel Jasperc39b56f2013-12-16 07:23:08 +00001133bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
Daniel Jasperf438cb72013-08-23 11:57:34 +00001134 const FormatToken &Current = *State.NextToken;
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001135 if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral))
Daniel Jasperf438cb72013-08-23 11:57:34 +00001136 return false;
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00001137 // We never consider raw string literals "multiline" for the purpose of
Daniel Jasperc39b56f2013-12-16 07:23:08 +00001138 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
1139 // (see TokenAnnotator::mustBreakBefore().
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00001140 if (Current.TokenText.startswith("R\""))
1141 return false;
Alexander Kornienko39856b72013-09-10 09:38:25 +00001142 if (Current.IsMultiline)
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00001143 return true;
Daniel Jasperf438cb72013-08-23 11:57:34 +00001144 if (Current.getNextNonComment() &&
Daniel Jasper04b6a082013-12-20 06:22:01 +00001145 Current.getNextNonComment()->isStringLiteral())
Daniel Jasperf438cb72013-08-23 11:57:34 +00001146 return true; // Implicit concatenation.
Alexander Kornienko39856b72013-09-10 09:38:25 +00001147 if (State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
Daniel Jasperf438cb72013-08-23 11:57:34 +00001148 Style.ColumnLimit)
1149 return true; // String will be split.
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00001150 return false;
Daniel Jasperf438cb72013-08-23 11:57:34 +00001151}
1152
Daniel Jasperde0328a2013-08-16 11:20:30 +00001153} // namespace format
1154} // namespace clang