blob: 6027f5fd61257f75609cf11e45cf1a84fcbb67e6 [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 "ContinuationIndenter.h"
Manuel Klimek89628f62017-09-20 09:51:03 +000016#include "BreakableToken.h"
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +000017#include "FormatInternal.h"
Daniel Jasperde0328a2013-08-16 11:20:30 +000018#include "WhitespaceManager.h"
19#include "clang/Basic/OperatorPrecedence.h"
20#include "clang/Basic/SourceManager.h"
21#include "clang/Format/Format.h"
22#include "llvm/Support/Debug.h"
Daniel Jasperde0328a2013-08-16 11:20:30 +000023
Krasimir Georgiev91834222017-01-25 13:58:58 +000024#define DEBUG_TYPE "format-indenter"
Chandler Carruth10346662014-04-22 03:17:02 +000025
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 Jasper801cdb22016-01-05 13:03:59 +000041static unsigned getLengthToNextOperator(const FormatToken &Tok) {
42 if (!Tok.NextOperator)
43 return 0;
44 return Tok.NextOperator->TotalLength - Tok.TotalLength;
45}
46
Daniel Jasper4c6e0052013-08-27 14:24:43 +000047// Returns \c true if \c Tok is the "." or "->" of a call and starts the next
48// segment of a builder type call.
49static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) {
50 return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope();
51}
52
Daniel Jasperec01cd62013-10-08 05:11:18 +000053// Returns \c true if \c Current starts a new parameter.
54static bool startsNextParameter(const FormatToken &Current,
55 const FormatStyle &Style) {
56 const FormatToken &Previous = *Current.Previous;
Daniel Jaspera98b7b02014-11-25 10:05:17 +000057 if (Current.is(TT_CtorInitializerComma) &&
Francois Ferranda6b6d512017-05-24 11:36:58 +000058 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
Daniel Jasperec01cd62013-10-08 05:11:18 +000059 return true;
Krasimir Georgievff747be2017-06-27 13:43:07 +000060 if (Style.Language == FormatStyle::LK_Proto && Current.is(TT_SelectorName))
61 return true;
Daniel Jasperec01cd62013-10-08 05:11:18 +000062 return Previous.is(tok::comma) && !Current.isTrailingComment() &&
Andi-Bogdan Postelnicu0ef8ee12017-03-10 15:10:37 +000063 ((Previous.isNot(TT_CtorInitializerComma) ||
Francois Ferranda6b6d512017-05-24 11:36:58 +000064 Style.BreakConstructorInitializers !=
65 FormatStyle::BCIS_BeforeComma) &&
Andi-Bogdan Postelnicu0ef8ee12017-03-10 15:10:37 +000066 (Previous.isNot(TT_InheritanceComma) ||
Francois Ferranda6b6d512017-05-24 11:36:58 +000067 !Style.BreakBeforeInheritanceComma));
Daniel Jasperec01cd62013-10-08 05:11:18 +000068}
69
Krasimir Georgiev26b144c2017-07-03 15:05:14 +000070static bool opensProtoMessageField(const FormatToken &LessTok,
71 const FormatStyle &Style) {
72 if (LessTok.isNot(tok::less))
73 return false;
74 return Style.Language == FormatStyle::LK_TextProto ||
75 (Style.Language == FormatStyle::LK_Proto &&
76 (LessTok.NestingLevel > 0 ||
77 (LessTok.Previous && LessTok.Previous->is(tok::equal))));
78}
79
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +000080// Returns the delimiter of a raw string literal, or None if TokenText is not
81// the text of a raw string literal. The delimiter could be the empty string.
82// For example, the delimiter of R"deli(cont)deli" is deli.
83static llvm::Optional<StringRef> getRawStringDelimiter(StringRef TokenText) {
84 if (TokenText.size() < 5 // The smallest raw string possible is 'R"()"'.
85 || !TokenText.startswith("R\"") || !TokenText.endswith("\""))
86 return None;
87
88 // A raw string starts with 'R"<delimiter>(' and delimiter is ascii and has
89 // size at most 16 by the standard, so the first '(' must be among the first
90 // 19 bytes.
91 size_t LParenPos = TokenText.substr(0, 19).find_first_of('(');
92 if (LParenPos == StringRef::npos)
93 return None;
94 StringRef Delimiter = TokenText.substr(2, LParenPos - 2);
95
96 // Check that the string ends in ')Delimiter"'.
97 size_t RParenPos = TokenText.size() - Delimiter.size() - 2;
98 if (TokenText[RParenPos] != ')')
99 return None;
100 if (!TokenText.substr(RParenPos + 1).startswith(Delimiter))
101 return None;
102 return Delimiter;
103}
104
Krasimir Georgiev412ed092018-01-19 16:18:47 +0000105// Returns the canonical delimiter for \p Language, or the empty string if no
106// canonical delimiter is specified.
107static StringRef
108getCanonicalRawStringDelimiter(const FormatStyle &Style,
109 FormatStyle::LanguageKind Language) {
110 for (const auto &Format : Style.RawStringFormats) {
111 if (Format.Language == Language)
112 return StringRef(Format.CanonicalDelimiter);
113 }
114 return "";
115}
116
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000117RawStringFormatStyleManager::RawStringFormatStyleManager(
118 const FormatStyle &CodeStyle) {
119 for (const auto &RawStringFormat : CodeStyle.RawStringFormats) {
Krasimir Georgiev2537e222018-01-17 16:17:26 +0000120 llvm::Optional<FormatStyle> LanguageStyle =
121 CodeStyle.GetLanguageStyle(RawStringFormat.Language);
122 if (!LanguageStyle) {
123 FormatStyle PredefinedStyle;
124 if (!getPredefinedStyle(RawStringFormat.BasedOnStyle,
125 RawStringFormat.Language, &PredefinedStyle)) {
126 PredefinedStyle = getLLVMStyle();
127 PredefinedStyle.Language = RawStringFormat.Language;
Krasimir Georgiev4527f132018-01-17 12:24:59 +0000128 }
Krasimir Georgiev2537e222018-01-17 16:17:26 +0000129 LanguageStyle = PredefinedStyle;
130 }
131 LanguageStyle->ColumnLimit = CodeStyle.ColumnLimit;
132 for (StringRef Delimiter : RawStringFormat.Delimiters) {
Krasimir Georgiev4527f132018-01-17 12:24:59 +0000133 DelimiterStyle.insert({Delimiter, *LanguageStyle});
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000134 }
Krasimir Georgiev2537e222018-01-17 16:17:26 +0000135 for (StringRef EnclosingFunction : RawStringFormat.EnclosingFunctions) {
136 EnclosingFunctionStyle.insert({EnclosingFunction, *LanguageStyle});
137 }
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000138 }
139}
140
141llvm::Optional<FormatStyle>
Krasimir Georgiev2537e222018-01-17 16:17:26 +0000142RawStringFormatStyleManager::getDelimiterStyle(StringRef Delimiter) const {
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000143 auto It = DelimiterStyle.find(Delimiter);
144 if (It == DelimiterStyle.end())
145 return None;
146 return It->second;
147}
148
Krasimir Georgiev2537e222018-01-17 16:17:26 +0000149llvm::Optional<FormatStyle>
150RawStringFormatStyleManager::getEnclosingFunctionStyle(
151 StringRef EnclosingFunction) const {
152 auto It = EnclosingFunctionStyle.find(EnclosingFunction);
153 if (It == EnclosingFunctionStyle.end())
154 return None;
155 return It->second;
156}
157
Daniel Jasperde0328a2013-08-16 11:20:30 +0000158ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000159 const AdditionalKeywords &Keywords,
Eric Liu635423e2016-04-28 07:52:03 +0000160 const SourceManager &SourceMgr,
Daniel Jasperde0328a2013-08-16 11:20:30 +0000161 WhitespaceManager &Whitespaces,
162 encoding::Encoding Encoding,
163 bool BinPackInconclusiveFunctions)
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000164 : Style(Style), Keywords(Keywords), SourceMgr(SourceMgr),
165 Whitespaces(Whitespaces), Encoding(Encoding),
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000166 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000167 CommentPragmasRegex(Style.CommentPragmas), RawStringFormats(Style) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000168
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000169LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000170 unsigned FirstStartColumn,
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000171 const AnnotatedLine *Line,
172 bool DryRun) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000173 LineState State;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000174 State.FirstIndent = FirstIndent;
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000175 if (FirstStartColumn && Line->First->NewlinesBefore == 0)
176 State.Column = FirstStartColumn;
177 else
178 State.Column = FirstIndent;
Krasimir Georgievad47c902017-08-30 14:34:57 +0000179 // With preprocessor directive indentation, the line starts on column 0
180 // since it's indented after the hash, but FirstIndent is set to the
181 // preprocessor indent.
182 if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash &&
183 (Line->Type == LT_PreprocessorDirective ||
184 Line->Type == LT_ImportStatement))
185 State.Column = 0;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000186 State.Line = Line;
187 State.NextToken = Line->First;
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000188 State.Stack.push_back(ParenState(FirstIndent, FirstIndent,
Daniel Jasperde0328a2013-08-16 11:20:30 +0000189 /*AvoidBinPacking=*/false,
190 /*NoLineBreak=*/false));
191 State.LineContainsContinuedForLoopSection = false;
Krasimir Georgiev35599fd2017-10-16 09:08:53 +0000192 State.NoContinuation = false;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000193 State.StartOfStringLiteral = 0;
Daniel Jasper05cd5862014-05-08 12:21:30 +0000194 State.StartOfLineLevel = 0;
195 State.LowestLevelOnLine = 0;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000196 State.IgnoreStackForComparison = false;
197
Krasimir Georgiev26b144c2017-07-03 15:05:14 +0000198 if (Style.Language == FormatStyle::LK_TextProto) {
199 // We need this in order to deal with the bin packing of text fields at
200 // global scope.
201 State.Stack.back().AvoidBinPacking = true;
202 State.Stack.back().BreakBeforeParameter = true;
Krasimir Georgievc8b461b2018-02-12 15:49:09 +0000203 State.Stack.back().AlignColons = false;
Krasimir Georgiev26b144c2017-07-03 15:05:14 +0000204 }
205
Daniel Jasperde0328a2013-08-16 11:20:30 +0000206 // The first token has already been indented and thus consumed.
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000207 moveStateToNextToken(State, DryRun, /*Newline=*/false);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000208 return State;
209}
210
211bool ContinuationIndenter::canBreak(const LineState &State) {
212 const FormatToken &Current = *State.NextToken;
213 const FormatToken &Previous = *Current.Previous;
214 assert(&Previous == Current.Previous);
Manuel Klimek89628f62017-09-20 09:51:03 +0000215 if (!Current.CanBreakBefore && !(State.Stack.back().BreakBeforeClosingBrace &&
216 Current.closesBlockOrBlockTypeList(Style)))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000217 return false;
218 // The opening "{" of a braced list has to be on the same line as the first
219 // element if it is nested in another braced init list or function call.
220 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000221 Previous.isNot(TT_DictLiteral) && Previous.BlockKind == BK_BracedInit &&
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000222 Previous.Previous &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000223 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
224 return false;
225 // This prevents breaks like:
226 // ...
227 // SomeParameter, OtherParameter).DoSomething(
228 // ...
229 // As they hide "DoSomething" and are generally bad for readability.
Daniel Jasper8f59ae52014-03-11 11:03:26 +0000230 if (Previous.opensScope() && Previous.isNot(tok::l_brace) &&
Daniel Jasperfcfac102014-07-15 09:00:34 +0000231 State.LowestLevelOnLine < State.StartOfLineLevel &&
232 State.LowestLevelOnLine < Current.NestingLevel)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000233 return false;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000234 if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
235 return false;
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000236
237 // Don't create a 'hanging' indent if there are multiple blocks in a single
238 // statement.
Daniel Jasper4b444492014-11-21 13:38:53 +0000239 if (Previous.is(tok::l_brace) && State.Stack.size() > 1 &&
240 State.Stack[State.Stack.size() - 2].NestedBlockInlined &&
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000241 State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks)
242 return false;
243
Daniel Jaspere068ac72014-10-27 17:13:59 +0000244 // Don't break after very short return types (e.g. "void") as that is often
245 // unexpected.
Zachary Turner448592e2015-12-18 22:20:15 +0000246 if (Current.is(TT_FunctionDeclarationName) && State.Column < 6) {
247 if (Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None)
248 return false;
249 }
Daniel Jaspere068ac72014-10-27 17:13:59 +0000250
Daniel Jasper240527c2017-01-16 13:13:15 +0000251 // If binary operators are moved to the next line (including commas for some
252 // styles of constructor initializers), that's always ok.
253 if (!Current.isOneOf(TT_BinaryOperator, tok::comma) &&
254 State.Stack.back().NoLineBreakInOperand)
255 return false;
256
Daniel Jasperde0328a2013-08-16 11:20:30 +0000257 return !State.Stack.back().NoLineBreak;
258}
259
260bool ContinuationIndenter::mustBreak(const LineState &State) {
261 const FormatToken &Current = *State.NextToken;
262 const FormatToken &Previous = *Current.Previous;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000263 if (Current.MustBreakBefore || Current.is(TT_InlineASMColon))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000264 return true;
Daniel Jasper1db6c382013-10-22 15:30:28 +0000265 if (State.Stack.back().BreakBeforeClosingBrace &&
Daniel Jasperbd73bcf2015-10-27 13:42:08 +0000266 Current.closesBlockOrBlockTypeList(Style))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000267 return true;
268 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
269 return true;
Jacek Olesiakfb7f5c02018-02-07 10:35:08 +0000270 if (Style.Language == FormatStyle::LK_ObjC &&
271 Current.ObjCSelectorNameParts > 1 &&
272 Current.startsSequence(TT_SelectorName, tok::colon, tok::caret)) {
273 return true;
274 }
Daniel Jasperec01cd62013-10-08 05:11:18 +0000275 if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
Daniel Jasper00693b082016-01-09 15:56:47 +0000276 (Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) &&
Daniel Jasper1dbc2102017-03-31 13:30:24 +0000277 Style.isCpp() &&
Daniel Jasper06ca0fc2016-01-11 11:01:05 +0000278 // FIXME: This is a temporary workaround for the case where clang-format
279 // sets BreakBeforeParameter to avoid bin packing and this creates a
280 // completely unnecessary line break after a template type that isn't
281 // line-wrapped.
282 (Previous.NestingLevel == 1 || Style.BinPackParameters)) ||
Daniel Jasper3e0dcc22015-05-27 05:37:40 +0000283 (Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&
284 Previous.isNot(tok::question)) ||
Daniel Jasper165b29e2013-11-08 00:57:11 +0000285 (!Style.BreakBeforeTernaryOperators &&
Daniel Jasper3e0dcc22015-05-27 05:37:40 +0000286 Previous.is(TT_ConditionalExpr))) &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000287 State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
288 !Current.isOneOf(tok::r_paren, tok::r_brace))
289 return true;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000290 if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) ||
Daniel Jasperccff4d12016-01-04 07:27:33 +0000291 (Previous.is(TT_ArrayInitializerLSquare) &&
Krasimir Georgiev26b144c2017-07-03 15:05:14 +0000292 Previous.ParameterCount > 1) ||
293 opensProtoMessageField(Previous, Style)) &&
Daniel Jasperdb8804b2014-04-14 12:11:07 +0000294 Style.ColumnLimit > 0 &&
Daniel Jasper199d0c92015-06-02 15:14:21 +0000295 getLengthToMatchingParen(Previous) + State.Column - 1 >
296 getColumnLimit(State))
Daniel Jasperd489dd32013-10-20 16:45:46 +0000297 return true;
Francois Ferranda6b6d512017-05-24 11:36:58 +0000298
299 const FormatToken &BreakConstructorInitializersToken =
300 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon
301 ? Previous
302 : Current;
303 if (BreakConstructorInitializersToken.is(TT_CtorInitializerColon) &&
304 (State.Column + State.Line->Last->TotalLength - Previous.TotalLength >
Daniel Jasper7b259cd2015-08-27 11:59:31 +0000305 getColumnLimit(State) ||
306 State.Stack.back().BreakBeforeParameter) &&
Francois Ferranda6b6d512017-05-24 11:36:58 +0000307 (Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All ||
308 Style.BreakConstructorInitializers != FormatStyle::BCIS_BeforeColon ||
309 Style.ColumnLimit != 0))
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000310 return true;
Francois Ferranda6b6d512017-05-24 11:36:58 +0000311
Daniel Jasperfd36f0b2016-11-12 07:38:22 +0000312 if (Current.is(TT_ObjCMethodExpr) && !Previous.is(TT_SelectorName) &&
313 State.Line->startsWith(TT_ObjCMethodSpecifier))
314 return true;
Daniel Jasper2746a302015-05-06 13:13:03 +0000315 if (Current.is(TT_SelectorName) && State.Stack.back().ObjCSelectorNameFound &&
316 State.Stack.back().BreakBeforeParameter)
317 return true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000318
Daniel Jasper2aaedd32015-06-18 09:12:47 +0000319 unsigned NewLineColumn = getNewLineColumn(State);
Daniel Jaspera3cd21642016-01-14 13:36:46 +0000320 if (Current.isMemberAccess() && Style.ColumnLimit != 0 &&
Daniel Jasper28024562016-01-11 11:00:58 +0000321 State.Column + getLengthToNextOperator(Current) > Style.ColumnLimit &&
322 (State.Column > NewLineColumn ||
323 Current.NestingLevel < State.StartOfLineLevel))
324 return true;
325
Daniel Jaspere61f9f92017-01-13 23:18:16 +0000326 if (startsSegmentOfBuilderTypeCall(Current) &&
327 (State.Stack.back().CallContinuation != 0 ||
Daniel Jasper51c868e2017-01-30 07:08:40 +0000328 State.Stack.back().BreakBeforeParameter) &&
329 // JavaScript is treated different here as there is a frequent pattern:
330 // SomeFunction(function() {
331 // ...
332 // }.bind(...));
333 // FIXME: We should find a more generic solution to this problem.
Martin Probstb2f06ea2017-05-29 07:50:52 +0000334 !(State.Column <= NewLineColumn &&
Daniel Jasper51c868e2017-01-30 07:08:40 +0000335 Style.Language == FormatStyle::LK_JavaScript))
Daniel Jaspere61f9f92017-01-13 23:18:16 +0000336 return true;
337
Daniel Jasper411af722016-01-05 16:10:39 +0000338 if (State.Column <= NewLineColumn)
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000339 return false;
Daniel Jasper173504e2015-05-10 21:15:07 +0000340
Daniel Jasper2aaedd32015-06-18 09:12:47 +0000341 if (Style.AlwaysBreakBeforeMultilineStrings &&
Daniel Jasper1bf729c2015-06-18 16:05:17 +0000342 (NewLineColumn == State.FirstIndent + Style.ContinuationIndentWidth ||
Daniel Jasper9fb676a2015-06-19 10:32:28 +0000343 Previous.is(tok::comma) || Current.NestingLevel < 2) &&
Daniel Jasper2aaedd32015-06-18 09:12:47 +0000344 !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) &&
345 !Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) &&
346 nextIsMultilineString(State))
347 return true;
348
Daniel Jasper173504e2015-05-10 21:15:07 +0000349 // Using CanBreakBefore here and below takes care of the decision whether the
350 // current style uses wrapping before or after operators for the given
351 // operator.
352 if (Previous.is(TT_BinaryOperator) && Current.CanBreakBefore) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000353 // If we need to break somewhere inside the LHS of a binary expression, we
354 // should also break after the operator. Otherwise, the formatting would
355 // hide the operator precedence, e.g. in:
356 // if (aaaaaaaaaaaaaa ==
357 // bbbbbbbbbbbbbb && c) {..
358 // For comparisons, we only apply this rule, if the LHS is a binary
359 // expression itself as otherwise, the line breaks seem superfluous.
360 // We need special cases for ">>" which we have split into two ">" while
361 // lexing in order to make template parsing easier.
Daniel Jasperde0328a2013-08-16 11:20:30 +0000362 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
Richard Smithc70f1d62017-12-14 15:16:18 +0000363 Previous.getPrecedence() == prec::Equality ||
364 Previous.getPrecedence() == prec::Spaceship) &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000365 Previous.Previous &&
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000366 Previous.Previous->isNot(TT_BinaryOperator); // For >>.
Daniel Jasperde0328a2013-08-16 11:20:30 +0000367 bool LHSIsBinaryExpr =
Daniel Jasper562ecd42013-09-06 08:08:14 +0000368 Previous.Previous && Previous.Previous->EndsBinaryExpression;
Daniel Jasper173504e2015-05-10 21:15:07 +0000369 if ((!IsComparison || LHSIsBinaryExpr) && !Current.isTrailingComment() &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000370 Previous.getPrecedence() != prec::Assignment &&
371 State.Stack.back().BreakBeforeParameter)
372 return true;
Daniel Jasper173504e2015-05-10 21:15:07 +0000373 } else if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore &&
374 State.Stack.back().BreakBeforeParameter) {
375 return true;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000376 }
377
378 // Same as above, but for the first "<<" operator.
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000379 if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator) &&
Alexander Kornienko86b2dfd2014-03-06 15:13:08 +0000380 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000381 State.Stack.back().FirstLessLess == 0)
382 return true;
383
Daniel Jasper211e1322014-12-08 20:08:04 +0000384 if (Current.NestingLevel == 0 && !Current.isTrailingComment()) {
Daniel Jasperf090f032015-05-18 09:47:22 +0000385 // Always break after "template <...>" and leading annotations. This is only
386 // for cases where the entire line does not fit on a single line as a
387 // different LineFormatter would be used otherwise.
Daniel Jasper211e1322014-12-08 20:08:04 +0000388 if (Previous.ClosesTemplateDeclaration)
389 return true;
Daniel Jasper47bbda02015-05-18 13:47:23 +0000390 if (Previous.is(TT_FunctionAnnotationRParen))
Daniel Jasperf090f032015-05-18 09:47:22 +0000391 return true;
Nico Weberbeb03932015-01-09 23:25:06 +0000392 if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) &&
393 Current.isNot(TT_LeadingJavaAnnotation))
Daniel Jasper211e1322014-12-08 20:08:04 +0000394 return true;
395 }
Daniel Jasperde0328a2013-08-16 11:20:30 +0000396
Daniel Jasper4355e7f2014-07-09 07:50:33 +0000397 // If the return type spans multiple lines, wrap before the function name.
Birunthan Mohanathas525579d2015-07-15 19:11:58 +0000398 if ((Current.is(TT_FunctionDeclarationName) ||
399 (Current.is(tok::kw_operator) && !Previous.is(tok::coloncolon))) &&
Daniel Jasper0c9772e2016-02-05 14:17:16 +0000400 !Previous.is(tok::kw_template) && State.Stack.back().BreakBeforeParameter)
Daniel Jasperde0328a2013-08-16 11:20:30 +0000401 return true;
Daniel Jasper4355e7f2014-07-09 07:50:33 +0000402
Daniel Jasper96972812014-01-05 12:38:10 +0000403 // The following could be precomputed as they do not depend on the state.
404 // However, as they should take effect only if the UnwrappedLine does not fit
405 // into the ColumnLimit, they are checked here in the ContinuationIndenter.
Daniel Jasper35995672014-04-29 14:05:20 +0000406 if (Style.ColumnLimit != 0 && Previous.BlockKind == BK_Block &&
407 Previous.is(tok::l_brace) && !Current.isOneOf(tok::r_brace, tok::comment))
Daniel Jasper96972812014-01-05 12:38:10 +0000408 return true;
Daniel Jasper96972812014-01-05 12:38:10 +0000409
Daniel Jasper0a589412016-01-05 13:06:27 +0000410 if (Current.is(tok::lessless) &&
411 ((Previous.is(tok::identifier) && Previous.TokenText == "endl") ||
412 (Previous.Tok.isLiteral() && (Previous.TokenText.endswith("\\n\"") ||
413 Previous.TokenText == "\'\\n\'"))))
Daniel Jasper69963122015-02-17 10:05:15 +0000414 return true;
415
Krasimir Georgiev35599fd2017-10-16 09:08:53 +0000416 if (Previous.is(TT_BlockComment) && Previous.IsMultiline)
417 return true;
418
419 if (State.NoContinuation)
420 return true;
421
Daniel Jasperde0328a2013-08-16 11:20:30 +0000422 return false;
423}
424
425unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000426 bool DryRun,
427 unsigned ExtraSpaces) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000428 const FormatToken &Current = *State.NextToken;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000429
Manuel Klimek819788d2014-03-18 11:22:45 +0000430 assert(!State.Stack.empty());
Krasimir Georgiev35599fd2017-10-16 09:08:53 +0000431 State.NoContinuation = false;
432
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000433 if ((Current.is(TT_ImplicitStringLiteral) &&
Craig Topper2145bc02014-05-09 08:15:10 +0000434 (Current.Previous->Tok.getIdentifierInfo() == nullptr ||
Daniel Jasper98857842013-10-30 13:54:53 +0000435 Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
436 tok::pp_not_keyword))) {
Daniel Jasper30526e72015-01-31 07:05:46 +0000437 unsigned EndColumn =
438 SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getEnd());
439 if (Current.LastNewlineOffset != 0) {
440 // If there is a newline within this token, the final column will solely
441 // determined by the current end column.
442 State.Column = EndColumn;
443 } else {
444 unsigned StartColumn =
445 SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getBegin());
446 assert(EndColumn >= StartColumn);
447 State.Column += EndColumn - StartColumn;
448 }
Daniel Jasper240dfda2014-03-31 14:23:49 +0000449 moveStateToNextToken(State, DryRun, /*Newline=*/false);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000450 return 0;
451 }
452
Alexander Kornienko1f803962013-10-01 14:41:18 +0000453 unsigned Penalty = 0;
454 if (Newline)
455 Penalty = addTokenOnNewLine(State, DryRun);
456 else
Daniel Jasper48437ce2013-11-20 14:54:39 +0000457 addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000458
459 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
460}
461
Daniel Jasper48437ce2013-11-20 14:54:39 +0000462void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
463 unsigned ExtraSpaces) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000464 FormatToken &Current = *State.NextToken;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000465 const FormatToken &Previous = *State.NextToken->Previous;
466 if (Current.is(tok::equal) &&
Daniel Jasper05cd5862014-05-08 12:21:30 +0000467 (State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) &&
Alexander Kornienko1f803962013-10-01 14:41:18 +0000468 State.Stack.back().VariablePos == 0) {
469 State.Stack.back().VariablePos = State.Column;
470 // Move over * and & if they are bound to the variable name.
471 const FormatToken *Tok = &Previous;
472 while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
473 State.Stack.back().VariablePos -= Tok->ColumnWidth;
474 if (Tok->SpacesRequiredBefore != 0)
475 break;
476 Tok = Tok->Previous;
477 }
478 if (Previous.PartOfMultiVariableDeclStmt)
479 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
480 }
481
482 unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
483
Krasimir Georgievad47c902017-08-30 14:34:57 +0000484 // Indent preprocessor directives after the hash if required.
485 int PPColumnCorrection = 0;
486 if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash &&
487 Previous.is(tok::hash) && State.FirstIndent > 0 &&
488 (State.Line->Type == LT_PreprocessorDirective ||
489 State.Line->Type == LT_ImportStatement)) {
490 Spaces += State.FirstIndent;
491
492 // For preprocessor indent with tabs, State.Column will be 1 because of the
493 // hash. This causes second-level indents onward to have an extra space
494 // after the tabs. We avoid this misalignment by subtracting 1 from the
495 // column value passed to replaceWhitespace().
496 if (Style.UseTab != FormatStyle::UT_Never)
497 PPColumnCorrection = -1;
498 }
499
Alexander Kornienko1f803962013-10-01 14:41:18 +0000500 if (!DryRun)
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000501 Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, Spaces,
Krasimir Georgievad47c902017-08-30 14:34:57 +0000502 State.Column + Spaces + PPColumnCorrection);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000503
Andi-Bogdan Postelnicu0ef8ee12017-03-10 15:10:37 +0000504 // If "BreakBeforeInheritanceComma" mode, don't break within the inheritance
505 // declaration unless there is multiple inheritance.
506 if (Style.BreakBeforeInheritanceComma && Current.is(TT_InheritanceColon))
507 State.Stack.back().NoLineBreak = true;
508
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000509 if (Current.is(TT_SelectorName) &&
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000510 !State.Stack.back().ObjCSelectorNameFound) {
Daniel Jasper06a26952016-01-04 07:29:07 +0000511 unsigned MinIndent =
512 std::max(State.FirstIndent + Style.ContinuationIndentWidth,
513 State.Stack.back().Indent);
514 unsigned FirstColonPos = State.Column + Spaces + Current.ColumnWidth;
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000515 if (Current.LongestObjCSelectorName == 0)
516 State.Stack.back().AlignColons = false;
Daniel Jasper06a26952016-01-04 07:29:07 +0000517 else if (MinIndent + Current.LongestObjCSelectorName > FirstColonPos)
518 State.Stack.back().ColonPos = MinIndent + Current.LongestObjCSelectorName;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000519 else
Daniel Jasper06a26952016-01-04 07:29:07 +0000520 State.Stack.back().ColonPos = FirstColonPos;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000521 }
522
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000523 // In "AlwaysBreak" mode, enforce wrapping directly after the parenthesis by
524 // disallowing any further line breaks if there is no line break after the
525 // opening parenthesis. Don't break if it doesn't conserve columns.
526 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_AlwaysBreak &&
Daniel Jasperb618a982016-02-02 10:28:11 +0000527 Previous.isOneOf(tok::l_paren, TT_TemplateOpener, tok::l_square) &&
528 State.Column > getNewLineColumn(State) &&
Manuel Klimek89628f62017-09-20 09:51:03 +0000529 (!Previous.Previous || !Previous.Previous->isOneOf(
530 tok::kw_for, tok::kw_while, tok::kw_switch)) &&
Daniel Jasper710f8492016-03-17 12:00:22 +0000531 // Don't do this for simple (no expressions) one-argument function calls
532 // as that feels like needlessly wasting whitespace, e.g.:
533 //
534 // caaaaaaaaaaaall(
535 // caaaaaaaaaaaall(
536 // caaaaaaaaaaaall(
537 // caaaaaaaaaaaaaaaaaaaaaaall(aaaaaaaaaaaaaa, aaaaaaaaa))));
538 Current.FakeLParens.size() > 0 &&
539 Current.FakeLParens.back() > prec::Unknown)
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000540 State.Stack.back().NoLineBreak = true;
Daniel Jasper98e0b122017-02-20 14:51:16 +0000541 if (Previous.is(TT_TemplateString) && Previous.opensScope())
542 State.Stack.back().NoLineBreak = true;
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000543
544 if (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign &&
545 Previous.opensScope() && Previous.isNot(TT_ObjCMethodExpr) &&
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000546 (Current.isNot(TT_LineComment) || Previous.BlockKind == BK_BracedInit))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000547 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasperec01cd62013-10-08 05:11:18 +0000548 if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000549 State.Stack.back().NoLineBreak = true;
Daniel Jasper775954b2015-04-24 10:08:09 +0000550 if (startsSegmentOfBuilderTypeCall(Current) &&
551 State.Column > getNewLineColumn(State))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000552 State.Stack.back().ContainsUnwrappedBuilder = true;
553
Daniel Jasper6f2b88a2015-06-05 13:18:09 +0000554 if (Current.is(TT_LambdaArrow) && Style.Language == FormatStyle::LK_Java)
Daniel Jasper05cd9292015-03-26 18:46:28 +0000555 State.Stack.back().NoLineBreak = true;
Daniel Jasperd6f17d82014-09-12 16:35:28 +0000556 if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&
557 (Previous.MatchingParen &&
Daniel Jasper98e0b122017-02-20 14:51:16 +0000558 (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10)))
Daniel Jasperd6f17d82014-09-12 16:35:28 +0000559 // If there is a function call with long parameters, break before trailing
560 // calls. This prevents things like:
561 // EXPECT_CALL(SomeLongParameter).Times(
562 // 2);
563 // We don't want to do this for short parameters as they can just be
564 // indexes.
565 State.Stack.back().NoLineBreak = true;
Daniel Jasperd6f17d82014-09-12 16:35:28 +0000566
Daniel Jasper240527c2017-01-16 13:13:15 +0000567 // Don't allow the RHS of an operator to be split over multiple lines unless
568 // there is a line-break right after the operator.
569 // Exclude relational operators, as there, it is always more desirable to
570 // have the LHS 'left' of the RHS.
571 const FormatToken *P = Current.getPreviousNonComment();
572 if (!Current.is(tok::comment) && P &&
573 (P->isOneOf(TT_BinaryOperator, tok::comma) ||
574 (P->is(TT_ConditionalExpr) && P->is(tok::colon))) &&
575 !P->isOneOf(TT_OverloadedOperator, TT_CtorInitializerComma) &&
576 P->getPrecedence() != prec::Assignment &&
Richard Smithc70f1d62017-12-14 15:16:18 +0000577 P->getPrecedence() != prec::Relational &&
578 P->getPrecedence() != prec::Spaceship) {
Daniel Jasper240527c2017-01-16 13:13:15 +0000579 bool BreakBeforeOperator =
Daniel Jasperb1270392017-02-01 23:27:37 +0000580 P->MustBreakBefore || P->is(tok::lessless) ||
Daniel Jasper240527c2017-01-16 13:13:15 +0000581 (P->is(TT_BinaryOperator) &&
582 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) ||
583 (P->is(TT_ConditionalExpr) && Style.BreakBeforeTernaryOperators);
Daniel Jasper21f7dea2017-02-01 09:23:39 +0000584 // Don't do this if there are only two operands. In these cases, there is
585 // always a nice vertical separation between them and the extra line break
586 // does not help.
587 bool HasTwoOperands =
588 P->OperatorIndex == 0 && !P->NextOperator && !P->is(TT_ConditionalExpr);
Daniel Jasperc3aa05c2017-02-02 08:30:21 +0000589 if ((!BreakBeforeOperator && !(HasTwoOperands && Style.AlignOperands)) ||
Daniel Jasper240527c2017-01-16 13:13:15 +0000590 (!State.Stack.back().LastOperatorWrapped && BreakBeforeOperator))
591 State.Stack.back().NoLineBreakInOperand = true;
592 }
593
Alexander Kornienko1f803962013-10-01 14:41:18 +0000594 State.Column += Spaces;
Daniel Jasper8acf8222014-05-07 09:23:05 +0000595 if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&
Daniel Jasper11a0ac62014-12-12 09:40:58 +0000596 Previous.Previous &&
Daniel Jasper6a7d5a72017-06-19 07:40:49 +0000597 (Previous.Previous->isOneOf(tok::kw_if, tok::kw_for) ||
598 Previous.Previous->endsSequence(tok::kw_constexpr, tok::kw_if))) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000599 // Treat the condition inside an if as if it was a second function
Daniel Jasper6633ab82013-10-18 10:38:14 +0000600 // parameter, i.e. let nested calls have a continuation indent.
Daniel Jasper8acf8222014-05-07 09:23:05 +0000601 State.Stack.back().LastSpace = State.Column;
Daniel Jasper11a0ac62014-12-12 09:40:58 +0000602 State.Stack.back().NestedBlockIndent = State.Column;
603 } else if (!Current.isOneOf(tok::comment, tok::caret) &&
Daniel Jasper804a2762016-01-09 15:56:40 +0000604 ((Previous.is(tok::comma) &&
605 !Previous.is(TT_OverloadedOperator)) ||
Daniel Jasper11a0ac62014-12-12 09:40:58 +0000606 (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000607 State.Stack.back().LastSpace = State.Column;
Francois Ferranda6b6d512017-05-24 11:36:58 +0000608 } else if (Previous.is(TT_CtorInitializerColon) &&
609 Style.BreakConstructorInitializers ==
610 FormatStyle::BCIS_AfterColon) {
611 State.Stack.back().Indent = State.Column;
612 State.Stack.back().LastSpace = State.Column;
Daniel Jasper11a0ac62014-12-12 09:40:58 +0000613 } else if ((Previous.isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
614 TT_CtorInitializerColon)) &&
615 ((Previous.getPrecedence() != prec::Assignment &&
616 (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||
Daniel Jasper00492f92016-01-05 13:03:50 +0000617 Previous.NextOperator)) ||
Daniel Jasper11a0ac62014-12-12 09:40:58 +0000618 Current.StartsBinaryExpression)) {
Daniel Jasper602a7272016-02-11 13:15:14 +0000619 // Indent relative to the RHS of the expression unless this is a simple
620 // assignment without binary expression on the RHS. Also indent relative to
621 // unary operators and the colons of constructor initializers.
Alexander Kornienko1f803962013-10-01 14:41:18 +0000622 State.Stack.back().LastSpace = State.Column;
Daniel Jasper11a0ac62014-12-12 09:40:58 +0000623 } else if (Previous.is(TT_InheritanceColon)) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000624 State.Stack.back().Indent = State.Column;
Daniel Jasperf9a5e402013-10-08 16:24:07 +0000625 State.Stack.back().LastSpace = State.Column;
626 } else if (Previous.opensScope()) {
Alexander Kornienko1f803962013-10-01 14:41:18 +0000627 // If a function has a trailing call, indent all parameters from the
628 // opening parenthesis. This avoids confusing indents like:
629 // OuterFunction(InnerFunctionCall( // break
630 // ParameterToInnerFunction)) // break
631 // .SecondInnerFunctionCall();
632 bool HasTrailingCall = false;
633 if (Previous.MatchingParen) {
634 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
635 HasTrailingCall = Next && Next->isMemberAccess();
636 }
Daniel Jasperd97d5d52015-02-17 09:58:03 +0000637 if (HasTrailingCall && State.Stack.size() > 1 &&
Alexander Kornienko1f803962013-10-01 14:41:18 +0000638 State.Stack[State.Stack.size() - 2].CallContinuation == 0)
639 State.Stack.back().LastSpace = State.Column;
640 }
641}
642
643unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
644 bool DryRun) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000645 FormatToken &Current = *State.NextToken;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000646 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000647
Alexander Kornienko1f803962013-10-01 14:41:18 +0000648 // Extra penalty that needs to be added because of the way certain line
649 // breaks are chosen.
650 unsigned Penalty = 0;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000651
Daniel Jaspera0407742014-02-11 10:08:11 +0000652 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
653 const FormatToken *NextNonComment = Previous.getNextNonComment();
654 if (!NextNonComment)
655 NextNonComment = &Current;
Daniel Jasper05cd5862014-05-08 12:21:30 +0000656 // The first line break on any NestingLevel causes an extra penalty in order
Alexander Kornienko1f803962013-10-01 14:41:18 +0000657 // prefer similar line breaks.
658 if (!State.Stack.back().ContainsLineBreak)
659 Penalty += 15;
660 State.Stack.back().ContainsLineBreak = true;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000661
Alexander Kornienko1f803962013-10-01 14:41:18 +0000662 Penalty += State.NextToken->SplitPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000663
Alexander Kornienko1f803962013-10-01 14:41:18 +0000664 // Breaking before the first "<<" is generally not desirable if the LHS is
Daniel Jasper7aacf462016-12-19 11:14:23 +0000665 // short. Also always add the penalty if the LHS is split over multiple lines
Daniel Jasper2b7556e2014-04-03 12:00:27 +0000666 // to avoid unnecessary line breaks that just work around this penalty.
Daniel Jaspera0407742014-02-11 10:08:11 +0000667 if (NextNonComment->is(tok::lessless) &&
668 State.Stack.back().FirstLessLess == 0 &&
Daniel Jasper004177e2013-12-19 16:06:40 +0000669 (State.Column <= Style.ColumnLimit / 3 ||
Daniel Jasper48437ce2013-11-20 14:54:39 +0000670 State.Stack.back().BreakBeforeParameter))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000671 Penalty += Style.PenaltyBreakFirstLessLess;
672
Daniel Jasper9f388d02014-03-27 14:33:30 +0000673 State.Column = getNewLineColumn(State);
Daniel Jaspered3f3952015-06-18 12:32:59 +0000674
675 // Indent nested blocks relative to this column, unless in a very specific
676 // JavaScript special case where:
677 //
678 // var loooooong_name =
679 // function() {
680 // // code
681 // }
682 //
Daniel Jasper87448c52016-06-13 07:48:45 +0000683 // is common and should be formatted like a free-standing function. The same
684 // goes for wrapping before the lambda return type arrow.
685 if (!Current.is(TT_LambdaArrow) &&
686 (Style.Language != FormatStyle::LK_JavaScript ||
687 Current.NestingLevel != 0 || !PreviousNonComment ||
688 !PreviousNonComment->is(tok::equal) ||
689 !Current.isOneOf(Keywords.kw_async, Keywords.kw_function)))
Daniel Jaspered3f3952015-06-18 12:32:59 +0000690 State.Stack.back().NestedBlockIndent = State.Column;
691
Daniel Jasper9f388d02014-03-27 14:33:30 +0000692 if (NextNonComment->isMemberAccess()) {
693 if (State.Stack.back().CallContinuation == 0)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000694 State.Stack.back().CallContinuation = State.Column;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000695 } else if (NextNonComment->is(TT_SelectorName)) {
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000696 if (!State.Stack.back().ObjCSelectorNameFound) {
Daniel Jaspera0407742014-02-11 10:08:11 +0000697 if (NextNonComment->LongestObjCSelectorName == 0) {
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000698 State.Stack.back().AlignColons = false;
699 } else {
700 State.Stack.back().ColonPos =
Daniel Jaspera2a4d9c2015-05-13 09:38:25 +0000701 (Style.IndentWrappedFunctionNames
702 ? std::max(State.Stack.back().Indent,
703 State.FirstIndent + Style.ContinuationIndentWidth)
704 : State.Stack.back().Indent) +
Francois Ferrand38d80132018-02-09 15:41:56 +0000705 std::max(NextNonComment->LongestObjCSelectorName,
706 NextNonComment->ColumnWidth);
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000707 }
Daniel Jasper9f388d02014-03-27 14:33:30 +0000708 } else if (State.Stack.back().AlignColons &&
709 State.Stack.back().ColonPos <= NextNonComment->ColumnWidth) {
Daniel Jaspera0407742014-02-11 10:08:11 +0000710 State.Stack.back().ColonPos = State.Column + NextNonComment->ColumnWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000711 }
Daniel Jasper1fd6f1f2014-03-17 14:32:47 +0000712 } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000713 PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000714 // FIXME: This is hacky, find a better way. The problem is that in an ObjC
715 // method expression, the block should be aligned to the line starting it,
716 // e.g.:
717 // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
718 // ^(int *i) {
719 // // ...
720 // }];
Daniel Jasper05cd5862014-05-08 12:21:30 +0000721 // Thus, we set LastSpace of the next higher NestingLevel, to which we move
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000722 // when we consume all of the "}"'s FakeRParens at the "{".
Daniel Jasper9a26e772013-12-23 11:25:40 +0000723 if (State.Stack.size() > 1)
Daniel Jasper9f388d02014-03-27 14:33:30 +0000724 State.Stack[State.Stack.size() - 2].LastSpace =
725 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
726 Style.ContinuationIndentWidth;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000727 }
728
Daniel Jasper35e41222016-11-29 09:40:01 +0000729 if ((PreviousNonComment &&
730 PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
Alexander Kornienko1f803962013-10-01 14:41:18 +0000731 !State.Stack.back().AvoidBinPacking) ||
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000732 Previous.is(TT_BinaryOperator))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000733 State.Stack.back().BreakBeforeParameter = false;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000734 if (Previous.isOneOf(TT_TemplateCloser, TT_JavaAnnotation) &&
Daniel Jasper39af6cd2014-11-03 02:27:28 +0000735 Current.NestingLevel == 0)
Alexander Kornienko1f803962013-10-01 14:41:18 +0000736 State.Stack.back().BreakBeforeParameter = false;
Daniel Jaspera0407742014-02-11 10:08:11 +0000737 if (NextNonComment->is(tok::question) ||
Daniel Jasper165b29e2013-11-08 00:57:11 +0000738 (PreviousNonComment && PreviousNonComment->is(tok::question)))
739 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper5962fa82015-06-03 09:26:03 +0000740 if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore)
741 State.Stack.back().BreakBeforeParameter = false;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000742
743 if (!DryRun) {
Martin Probsta004b3f2017-11-17 18:06:33 +0000744 unsigned MaxEmptyLinesToKeep = Style.MaxEmptyLinesToKeep + 1;
745 if (Current.is(tok::r_brace) && Current.MatchingParen &&
746 // Only strip trailing empty lines for l_braces that have children, i.e.
747 // for function expressions (lambdas, arrows, etc).
748 !Current.MatchingParen->Children.empty()) {
749 // lambdas and arrow functions are expressions, thus their r_brace is not
750 // on its own line, and thus not covered by UnwrappedLineFormatter's logic
751 // about removing empty lines on closing blocks. Special case them here.
752 MaxEmptyLinesToKeep = 1;
753 }
Daniel Jaspera69ca9b2014-06-04 12:40:57 +0000754 unsigned Newlines = std::max(
Martin Probsta004b3f2017-11-17 18:06:33 +0000755 1u, std::min(Current.NewlinesBefore, MaxEmptyLinesToKeep));
Krasimir Georgieva1c30932017-05-19 10:34:57 +0000756 bool ContinuePPDirective =
757 State.Line->InPPDirective && State.Line->Type != LT_ImportStatement;
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000758 Whitespaces.replaceWhitespace(Current, Newlines, State.Column, State.Column,
Krasimir Georgieva1c30932017-05-19 10:34:57 +0000759 ContinuePPDirective);
Alexander Kornienko1f803962013-10-01 14:41:18 +0000760 }
761
762 if (!Current.isTrailingComment())
763 State.Stack.back().LastSpace = State.Column;
Daniel Jasper602a7272016-02-11 13:15:14 +0000764 if (Current.is(tok::lessless))
765 // If we are breaking before a "<<", we always want to indent relative to
766 // RHS. This is necessary only for "<<", as we special-case it and don't
767 // always indent relative to the RHS.
768 State.Stack.back().LastSpace += 3; // 3 -> width of "<< ".
769
Daniel Jasper05cd5862014-05-08 12:21:30 +0000770 State.StartOfLineLevel = Current.NestingLevel;
771 State.LowestLevelOnLine = Current.NestingLevel;
Alexander Kornienko1f803962013-10-01 14:41:18 +0000772
773 // Any break on this level means that the parent level has been broken
774 // and we need to avoid bin packing there.
Daniel Jasper4b444492014-11-21 13:38:53 +0000775 bool NestedBlockSpecialCase =
Daniel Jasper1dbc2102017-03-31 13:30:24 +0000776 !Style.isCpp() && Current.is(tok::r_brace) && State.Stack.size() > 1 &&
Daniel Jasper4b444492014-11-21 13:38:53 +0000777 State.Stack[State.Stack.size() - 2].NestedBlockInlined;
Daniel Jasper1699eca2015-06-01 09:56:32 +0000778 if (!NestedBlockSpecialCase)
779 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
Daniel Jasperb16b9692014-05-21 12:51:23 +0000780 State.Stack[i].BreakBeforeParameter = true;
Daniel Jasperb16b9692014-05-21 12:51:23 +0000781
Daniel Jasper9e5ede02013-11-08 19:56:28 +0000782 if (PreviousNonComment &&
Francois Ferranda6b6d512017-05-24 11:36:58 +0000783 !PreviousNonComment->isOneOf(tok::comma, tok::colon, tok::semi) &&
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000784 (PreviousNonComment->isNot(TT_TemplateCloser) ||
Daniel Jasper6c0ee172014-11-14 13:14:45 +0000785 Current.NestingLevel != 0) &&
Daniel Jasper47bbda02015-05-18 13:47:23 +0000786 !PreviousNonComment->isOneOf(
787 TT_BinaryOperator, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
788 TT_LeadingJavaAnnotation) &&
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000789 Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope())
Alexander Kornienko1f803962013-10-01 14:41:18 +0000790 State.Stack.back().BreakBeforeParameter = true;
791
Daniel Jasper1db6c382013-10-22 15:30:28 +0000792 // If we break after { or the [ of an array initializer, we should also break
793 // before the corresponding } or ].
Daniel Jasper90818052014-06-10 10:42:26 +0000794 if (PreviousNonComment &&
Daniel Jasper98e0b122017-02-20 14:51:16 +0000795 (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
Martin Probstc10d97f2017-08-29 08:30:07 +0000796 opensProtoMessageField(*PreviousNonComment, Style)))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000797 State.Stack.back().BreakBeforeClosingBrace = true;
798
799 if (State.Stack.back().AvoidBinPacking) {
800 // If we are breaking after '(', '{', '<', this is not bin packing
Daniel Jasper2a958322014-05-21 13:26:58 +0000801 // unless AllowAllParametersOfDeclarationOnNextLine is false or this is a
802 // dict/object literal.
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000803 if (!Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) ||
Alexander Kornienko1f803962013-10-01 14:41:18 +0000804 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
Daniel Jasper2a958322014-05-21 13:26:58 +0000805 State.Line->MustBeDeclaration) ||
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000806 Previous.is(TT_DictLiteral))
Alexander Kornienko1f803962013-10-01 14:41:18 +0000807 State.Stack.back().BreakBeforeParameter = true;
808 }
809
810 return Penalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000811}
812
Daniel Jasper9f388d02014-03-27 14:33:30 +0000813unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000814 if (!State.NextToken || !State.NextToken->Previous)
815 return 0;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000816 FormatToken &Current = *State.NextToken;
Daniel Jasper4281c5a2014-10-07 14:45:34 +0000817 const FormatToken &Previous = *Current.Previous;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000818 // If we are continuing an expression, we want to use the continuation indent.
819 unsigned ContinuationIndent =
820 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
821 Style.ContinuationIndentWidth;
822 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
823 const FormatToken *NextNonComment = Previous.getNextNonComment();
824 if (!NextNonComment)
825 NextNonComment = &Current;
Daniel Jasper50b4bd72014-11-02 19:16:41 +0000826
827 // Java specific bits.
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000828 if (Style.Language == FormatStyle::LK_Java &&
829 Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends))
Daniel Jasper50b4bd72014-11-02 19:16:41 +0000830 return std::max(State.Stack.back().LastSpace,
831 State.Stack.back().Indent + Style.ContinuationIndentWidth);
832
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000833 if (NextNonComment->is(tok::l_brace) && NextNonComment->BlockKind == BK_Block)
Daniel Jasper05cd5862014-05-08 12:21:30 +0000834 return Current.NestingLevel == 0 ? State.FirstIndent
835 : State.Stack.back().Indent;
Krasimir Georgievff747be2017-06-27 13:43:07 +0000836 if ((Current.isOneOf(tok::r_brace, tok::r_square) ||
Krasimir Georgiev26b144c2017-07-03 15:05:14 +0000837 (Current.is(tok::greater) &&
838 (Style.Language == FormatStyle::LK_Proto ||
839 Style.Language == FormatStyle::LK_TextProto))) &&
Krasimir Georgievff747be2017-06-27 13:43:07 +0000840 State.Stack.size() > 1) {
Daniel Jasperbd73bcf2015-10-27 13:42:08 +0000841 if (Current.closesBlockOrBlockTypeList(Style))
Daniel Jasper11a0ac62014-12-12 09:40:58 +0000842 return State.Stack[State.Stack.size() - 2].NestedBlockIndent;
843 if (Current.MatchingParen &&
844 Current.MatchingParen->BlockKind == BK_BracedInit)
Daniel Jasper9f388d02014-03-27 14:33:30 +0000845 return State.Stack[State.Stack.size() - 2].LastSpace;
Daniel Jasper24a14772014-12-10 17:24:34 +0000846 return State.FirstIndent;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000847 }
Martin Probstb2f06ea2017-05-29 07:50:52 +0000848 // Indent a closing parenthesis at the previous level if followed by a semi or
849 // opening brace. This allows indentations such as:
850 // foo(
851 // a,
852 // );
853 // function foo(
854 // a,
855 // ) {
856 // code(); //
857 // }
858 if (Current.is(tok::r_paren) && State.Stack.size() > 1 &&
859 (!Current.Next || Current.Next->isOneOf(tok::semi, tok::l_brace)))
Martin Probst2c1cdae2017-05-15 11:15:29 +0000860 return State.Stack[State.Stack.size() - 2].LastSpace;
Daniel Jasper98e0b122017-02-20 14:51:16 +0000861 if (NextNonComment->is(TT_TemplateString) && NextNonComment->closesScope())
862 return State.Stack[State.Stack.size() - 2].LastSpace;
Daniel Jasper783bac62014-04-15 09:54:30 +0000863 if (Current.is(tok::identifier) && Current.Next &&
Krasimir Georgievddb19242017-08-03 14:17:29 +0000864 (Current.Next->is(TT_DictLiteral) ||
865 ((Style.Language == FormatStyle::LK_Proto ||
866 Style.Language == FormatStyle::LK_TextProto) &&
Krasimir Georgieva79d62d2018-02-06 11:34:34 +0000867 Current.Next->isOneOf(tok::less, tok::l_brace))))
Daniel Jasper783bac62014-04-15 09:54:30 +0000868 return State.Stack.back().Indent;
Daniel Jasper09285532015-05-17 08:13:23 +0000869 if (NextNonComment->is(TT_ObjCStringLiteral) &&
870 State.StartOfStringLiteral != 0)
871 return State.StartOfStringLiteral - 1;
Alexander Kornienkod4fa2e62017-04-11 09:55:00 +0000872 if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
873 return State.StartOfStringLiteral;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000874 if (NextNonComment->is(tok::lessless) &&
875 State.Stack.back().FirstLessLess != 0)
876 return State.Stack.back().FirstLessLess;
877 if (NextNonComment->isMemberAccess()) {
Daniel Jasper24a14772014-12-10 17:24:34 +0000878 if (State.Stack.back().CallContinuation == 0)
Daniel Jasper9f388d02014-03-27 14:33:30 +0000879 return ContinuationIndent;
Daniel Jasper24a14772014-12-10 17:24:34 +0000880 return State.Stack.back().CallContinuation;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000881 }
882 if (State.Stack.back().QuestionColumn != 0 &&
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000883 ((NextNonComment->is(tok::colon) &&
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000884 NextNonComment->is(TT_ConditionalExpr)) ||
885 Previous.is(TT_ConditionalExpr)))
Daniel Jasper9f388d02014-03-27 14:33:30 +0000886 return State.Stack.back().QuestionColumn;
887 if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0)
888 return State.Stack.back().VariablePos;
Daniel Jaspere9ab42d2014-10-31 18:23:49 +0000889 if ((PreviousNonComment &&
890 (PreviousNonComment->ClosesTemplateDeclaration ||
Daniel Jasper47bbda02015-05-18 13:47:23 +0000891 PreviousNonComment->isOneOf(
Ben Hamiltonb060ad82018-03-12 15:42:38 +0000892 TT_AttributeParen, TT_AttributeSquare, TT_FunctionAnnotationRParen,
893 TT_JavaAnnotation, TT_LeadingJavaAnnotation))) ||
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000894 (!Style.IndentWrappedFunctionNames &&
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000895 NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName)))
Daniel Jasper9f388d02014-03-27 14:33:30 +0000896 return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000897 if (NextNonComment->is(TT_SelectorName)) {
Daniel Jasper9f388d02014-03-27 14:33:30 +0000898 if (!State.Stack.back().ObjCSelectorNameFound) {
Daniel Jasper24a14772014-12-10 17:24:34 +0000899 if (NextNonComment->LongestObjCSelectorName == 0)
Daniel Jasper9f388d02014-03-27 14:33:30 +0000900 return State.Stack.back().Indent;
Daniel Jaspera2a4d9c2015-05-13 09:38:25 +0000901 return (Style.IndentWrappedFunctionNames
902 ? std::max(State.Stack.back().Indent,
903 State.FirstIndent + Style.ContinuationIndentWidth)
904 : State.Stack.back().Indent) +
Francois Ferrand38d80132018-02-09 15:41:56 +0000905 std::max(NextNonComment->LongestObjCSelectorName,
906 NextNonComment->ColumnWidth) -
Daniel Jasper24a14772014-12-10 17:24:34 +0000907 NextNonComment->ColumnWidth;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000908 }
Daniel Jasper24a14772014-12-10 17:24:34 +0000909 if (!State.Stack.back().AlignColons)
910 return State.Stack.back().Indent;
911 if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth)
912 return State.Stack.back().ColonPos - NextNonComment->ColumnWidth;
913 return State.Stack.back().Indent;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000914 }
Daniel Jasperfd36f0b2016-11-12 07:38:22 +0000915 if (NextNonComment->is(tok::colon) && NextNonComment->is(TT_ObjCMethodExpr))
916 return State.Stack.back().ColonPos;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000917 if (NextNonComment->is(TT_ArraySubscriptLSquare)) {
Daniel Jasper9f388d02014-03-27 14:33:30 +0000918 if (State.Stack.back().StartOfArraySubscripts != 0)
919 return State.Stack.back().StartOfArraySubscripts;
Daniel Jasper24a14772014-12-10 17:24:34 +0000920 return ContinuationIndent;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000921 }
Daniel Jasper9c950132015-05-07 14:19:59 +0000922
923 // This ensure that we correctly format ObjC methods calls without inputs,
924 // i.e. where the last element isn't selector like: [callee method];
925 if (NextNonComment->is(tok::identifier) && NextNonComment->FakeRParens == 0 &&
926 NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr))
Daniel Jaspereb536682015-05-06 12:48:06 +0000927 return State.Stack.back().Indent;
Daniel Jasper9c950132015-05-07 14:19:59 +0000928
Daniel Jasperb754a742015-03-12 15:04:53 +0000929 if (NextNonComment->isOneOf(TT_StartOfName, TT_PointerOrReference) ||
Daniel Jasperb2328b12015-07-06 14:07:51 +0000930 Previous.isOneOf(tok::coloncolon, tok::equal, TT_JsTypeColon))
Daniel Jasper9f388d02014-03-27 14:33:30 +0000931 return ContinuationIndent;
Daniel Jasper9f388d02014-03-27 14:33:30 +0000932 if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000933 PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))
Daniel Jasper9f388d02014-03-27 14:33:30 +0000934 return ContinuationIndent;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000935 if (NextNonComment->is(TT_CtorInitializerComma))
Daniel Jasper9f388d02014-03-27 14:33:30 +0000936 return State.Stack.back().Indent;
Francois Ferranda6b6d512017-05-24 11:36:58 +0000937 if (PreviousNonComment && PreviousNonComment->is(TT_CtorInitializerColon) &&
938 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon)
939 return State.Stack.back().Indent;
Andi-Bogdan Postelnicu0ef8ee12017-03-10 15:10:37 +0000940 if (NextNonComment->isOneOf(TT_CtorInitializerColon, TT_InheritanceColon,
941 TT_InheritanceComma))
942 return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
Daniel Jasper316ab382014-08-06 13:14:58 +0000943 if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() &&
Daniel Jasper119ff532014-11-14 12:31:14 +0000944 !Current.isOneOf(tok::colon, tok::comment))
Daniel Jasper316ab382014-08-06 13:14:58 +0000945 return ContinuationIndent;
Krasimir Georgiev4e2906482018-02-13 10:20:39 +0000946 if (Current.is(TT_ProtoExtensionLSquare))
947 return State.Stack.back().Indent;
Daniel Jasper5d2587d2014-03-27 16:14:13 +0000948 if (State.Stack.back().Indent == State.FirstIndent && PreviousNonComment &&
Daniel Jasper9f388d02014-03-27 14:33:30 +0000949 PreviousNonComment->isNot(tok::r_brace))
950 // Ensure that we fall back to the continuation indent width instead of
951 // just flushing continuations left.
952 return State.Stack.back().Indent + Style.ContinuationIndentWidth;
953 return State.Stack.back().Indent;
954}
955
Daniel Jasperde0328a2013-08-16 11:20:30 +0000956unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
957 bool DryRun, bool Newline) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000958 assert(State.Stack.size());
Daniel Jasper60553be2014-05-26 13:10:39 +0000959 const FormatToken &Current = *State.NextToken;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000960
Daniel Jasper240527c2017-01-16 13:13:15 +0000961 if (Current.isOneOf(tok::comma, TT_BinaryOperator))
962 State.Stack.back().NoLineBreakInOperand = false;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000963 if (Current.is(TT_InheritanceColon))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000964 State.Stack.back().AvoidBinPacking = true;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000965 if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) {
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000966 if (State.Stack.back().FirstLessLess == 0)
967 State.Stack.back().FirstLessLess = State.Column;
968 else
969 State.Stack.back().LastOperatorWrapped = Newline;
970 }
Daniel Jasper240527c2017-01-16 13:13:15 +0000971 if (Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless))
972 State.Stack.back().LastOperatorWrapped = Newline;
973 if (Current.is(TT_ConditionalExpr) && Current.Previous &&
974 !Current.Previous->is(TT_ConditionalExpr))
Daniel Jasperc0d606a2014-04-14 11:08:45 +0000975 State.Stack.back().LastOperatorWrapped = Newline;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000976 if (Current.is(TT_ArraySubscriptLSquare) &&
Daniel Jasperde0328a2013-08-16 11:20:30 +0000977 State.Stack.back().StartOfArraySubscripts == 0)
978 State.Stack.back().StartOfArraySubscripts = State.Column;
Daniel Jasper45860fa2016-02-03 17:27:10 +0000979 if (Style.BreakBeforeTernaryOperators && Current.is(tok::question))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000980 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper45860fa2016-02-03 17:27:10 +0000981 if (!Style.BreakBeforeTernaryOperators && Current.isNot(tok::colon)) {
982 const FormatToken *Previous = Current.Previous;
983 while (Previous && Previous->isTrailingComment())
984 Previous = Previous->Previous;
985 if (Previous && Previous->is(tok::question))
986 State.Stack.back().QuestionColumn = State.Column;
987 }
Daniel Jaspercab46172017-04-24 14:28:49 +0000988 if (!Current.opensScope() && !Current.closesScope() &&
989 !Current.is(TT_PointerOrReference))
Daniel Jasperde0328a2013-08-16 11:20:30 +0000990 State.LowestLevelOnLine =
Daniel Jasper05cd5862014-05-08 12:21:30 +0000991 std::min(State.LowestLevelOnLine, Current.NestingLevel);
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000992 if (Current.isMemberAccess())
Daniel Jasperde0328a2013-08-16 11:20:30 +0000993 State.Stack.back().StartOfFunctionCall =
Daniel Jasper00492f92016-01-05 13:03:50 +0000994 !Current.NextOperator ? 0 : State.Column;
Daniel Jasper3c44c222015-07-16 22:58:24 +0000995 if (Current.is(TT_SelectorName)) {
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000996 State.Stack.back().ObjCSelectorNameFound = true;
Daniel Jasper3c44c222015-07-16 22:58:24 +0000997 if (Style.IndentWrappedFunctionNames) {
998 State.Stack.back().Indent =
999 State.FirstIndent + Style.ContinuationIndentWidth;
1000 }
1001 }
Francois Ferranda6b6d512017-05-24 11:36:58 +00001002 if (Current.is(TT_CtorInitializerColon) &&
1003 Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon) {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001004 // Indent 2 from the column, so:
1005 // SomeClass::SomeClass()
1006 // : First(...), ...
1007 // Next(...)
1008 // ^ line up here.
1009 State.Stack.back().Indent =
Manuel Klimek89628f62017-09-20 09:51:03 +00001010 State.Column +
1011 (Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma
1012 ? 0
1013 : 2);
Daniel Jasperd6a1cab2015-01-12 10:23:24 +00001014 State.Stack.back().NestedBlockIndent = State.Stack.back().Indent;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001015 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
1016 State.Stack.back().AvoidBinPacking = true;
1017 State.Stack.back().BreakBeforeParameter = false;
1018 }
Francois Ferranda6b6d512017-05-24 11:36:58 +00001019 if (Current.is(TT_CtorInitializerColon) &&
1020 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) {
1021 State.Stack.back().Indent =
1022 State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1023 State.Stack.back().NestedBlockIndent = State.Stack.back().Indent;
1024 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
Manuel Klimek89628f62017-09-20 09:51:03 +00001025 State.Stack.back().AvoidBinPacking = true;
Francois Ferranda6b6d512017-05-24 11:36:58 +00001026 }
Andi-Bogdan Postelnicu0ef8ee12017-03-10 15:10:37 +00001027 if (Current.is(TT_InheritanceColon))
1028 State.Stack.back().Indent =
1029 State.FirstIndent + Style.ContinuationIndentWidth;
Daniel Jasperc4144ea2015-05-13 16:09:21 +00001030 if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline)
1031 State.Stack.back().NestedBlockIndent =
1032 State.Column + Current.ColumnWidth + 1;
Daniel Jasperd9b319e2017-02-20 12:43:48 +00001033 if (Current.isOneOf(TT_LambdaLSquare, TT_LambdaArrow))
1034 State.Stack.back().LastSpace = State.Column;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001035
Daniel Jasperde0328a2013-08-16 11:20:30 +00001036 // Insert scopes created by fake parenthesis.
1037 const FormatToken *Previous = Current.getPreviousNonComment();
Daniel Jasperb16b9692014-05-21 12:51:23 +00001038
1039 // Add special behavior to support a format commonly used for JavaScript
1040 // closures:
1041 // SomeFunction(function() {
1042 // foo();
1043 // bar();
1044 // }, a, b, c);
Daniel Jasperb2ad4d42015-06-15 09:23:17 +00001045 if (Current.isNot(tok::comment) && Previous &&
1046 Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
Daniel Jasperccff4d12016-01-04 07:27:33 +00001047 !Previous->is(TT_DictLiteral) && State.Stack.size() > 1) {
Daniel Jasper1699eca2015-06-01 09:56:32 +00001048 if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline)
1049 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
Daniel Jasper4b444492014-11-21 13:38:53 +00001050 State.Stack[i].NoLineBreak = true;
Daniel Jasper4b444492014-11-21 13:38:53 +00001051 State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;
1052 }
Manuel Klimek89628f62017-09-20 09:51:03 +00001053 if (Previous &&
1054 (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) ||
1055 Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr)) &&
Daniel Jasper4b444492014-11-21 13:38:53 +00001056 !Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
1057 State.Stack.back().NestedBlockInlined =
1058 !Newline &&
Daniel Jasper11a0ac62014-12-12 09:40:58 +00001059 (Previous->isNot(tok::l_paren) || Previous->ParameterCount > 1);
Daniel Jasperb16b9692014-05-21 12:51:23 +00001060 }
1061
Daniel Jasper60553be2014-05-26 13:10:39 +00001062 moveStatePastFakeLParens(State, Newline);
Daniel Jasper60553be2014-05-26 13:10:39 +00001063 moveStatePastScopeCloser(State);
Manuel Klimek45ab5592017-11-14 09:19:53 +00001064 bool AllowBreak = !State.Stack.back().NoLineBreak &&
1065 !State.Stack.back().NoLineBreakInOperand;
Daniel Jasperc06f6da2017-02-03 14:32:38 +00001066 moveStatePastScopeOpener(State, Newline);
Daniel Jasper60553be2014-05-26 13:10:39 +00001067 moveStatePastFakeRParens(State);
1068
Daniel Jasper09285532015-05-17 08:13:23 +00001069 if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0)
1070 State.StartOfStringLiteral = State.Column + 1;
Alexander Kornienkod4fa2e62017-04-11 09:55:00 +00001071 else if (Current.isStringLiteral() && State.StartOfStringLiteral == 0)
1072 State.StartOfStringLiteral = State.Column;
Daniel Jasper09285532015-05-17 08:13:23 +00001073 else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001074 !Current.isStringLiteral())
Daniel Jasper60553be2014-05-26 13:10:39 +00001075 State.StartOfStringLiteral = 0;
Daniel Jasper60553be2014-05-26 13:10:39 +00001076
1077 State.Column += Current.ColumnWidth;
1078 State.NextToken = State.NextToken->Next;
Manuel Klimek45ab5592017-11-14 09:19:53 +00001079
1080 unsigned Penalty =
1081 handleEndOfLine(Current, State, DryRun, AllowBreak);
Daniel Jasper60553be2014-05-26 13:10:39 +00001082
1083 if (Current.Role)
1084 Current.Role->formatFromToken(State, this, DryRun);
1085 // If the previous has a special role, let it consume tokens as appropriate.
1086 // It is necessary to start at the previous token for the only implemented
1087 // role (comma separated list). That way, the decision whether or not to break
1088 // after the "{" is already done and both options are tried and evaluated.
1089 // FIXME: This is ugly, find a better way.
1090 if (Previous && Previous->Role)
1091 Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
1092
1093 return Penalty;
1094}
1095
1096void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
1097 bool Newline) {
1098 const FormatToken &Current = *State.NextToken;
1099 const FormatToken *Previous = Current.getPreviousNonComment();
1100
Daniel Jasperde0328a2013-08-16 11:20:30 +00001101 // Don't add extra indentation for the first fake parenthesis after
Dinesh Dwivedi0db806b2014-05-01 17:19:34 +00001102 // 'return', assignments or opening <({[. The indentation for these cases
Daniel Jasperde0328a2013-08-16 11:20:30 +00001103 // is special cased.
1104 bool SkipFirstExtraIndent =
Daniel Jasper98f8ae32015-03-06 10:57:12 +00001105 (Previous && (Previous->opensScope() ||
1106 Previous->isOneOf(tok::semi, tok::kw_return) ||
Daniel Jasper3219e432014-12-02 13:24:51 +00001107 (Previous->getPrecedence() == prec::Assignment &&
1108 Style.AlignOperands) ||
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001109 Previous->is(TT_ObjCMethodExpr)));
Daniel Jasperde0328a2013-08-16 11:20:30 +00001110 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
1111 I = Current.FakeLParens.rbegin(),
1112 E = Current.FakeLParens.rend();
1113 I != E; ++I) {
1114 ParenState NewParenState = State.Stack.back();
1115 NewParenState.ContainsLineBreak = false;
Daniel Jasper04bbda92017-03-16 07:54:11 +00001116 NewParenState.LastOperatorWrapped = true;
Daniel Jasper240527c2017-01-16 13:13:15 +00001117 NewParenState.NoLineBreak =
1118 NewParenState.NoLineBreak || State.Stack.back().NoLineBreakInOperand;
Daniel Jaspereabede62013-09-30 08:29:03 +00001119
Daniel Jasper988e7e42017-05-08 15:07:52 +00001120 // Don't propagate AvoidBinPacking into subexpressions of arg/param lists.
1121 if (*I > prec::Comma)
1122 NewParenState.AvoidBinPacking = false;
1123
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +00001124 // Indent from 'LastSpace' unless these are fake parentheses encapsulating
1125 // a builder type call after 'return' or, if the alignment after opening
1126 // brackets is disabled.
Daniel Jasper4281c5a2014-10-07 14:45:34 +00001127 if (!Current.isTrailingComment() &&
Daniel Jasper3219e432014-12-02 13:24:51 +00001128 (Style.AlignOperands || *I < prec::Assignment) &&
Daniel Jasper6cab6782014-11-20 09:54:49 +00001129 (!Previous || Previous->isNot(tok::kw_return) ||
1130 (Style.Language != FormatStyle::LK_Java && *I > 0)) &&
Daniel Jasper6501f7e2015-10-27 12:38:37 +00001131 (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign ||
1132 *I != prec::Comma || Current.NestingLevel == 0))
Daniel Jaspereabede62013-09-30 08:29:03 +00001133 NewParenState.Indent =
1134 std::max(std::max(State.Column, NewParenState.Indent),
1135 State.Stack.back().LastSpace);
1136
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001137 // Do not indent relative to the fake parentheses inserted for "." or "->".
1138 // This is a special case to make the following to statements consistent:
1139 // OuterFunction(InnerFunctionCall( // break
1140 // ParameterToInnerFunction));
1141 // OuterFunction(SomeObject.InnerFunctionCall( // break
1142 // ParameterToInnerFunction));
1143 if (*I > prec::Unknown)
1144 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
Daniel Jasper2a9f7202016-02-08 09:52:54 +00001145 if (*I != prec::Conditional && !Current.is(TT_UnaryOperator) &&
1146 Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
Daniel Jaspera536df42014-12-08 21:28:31 +00001147 NewParenState.StartOfFunctionCall = State.Column;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001148
1149 // Always indent conditional expressions. Never indent expression where
1150 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
1151 // prec::Assignment) as those have different indentation rules. Indent
1152 // other expression, unless the indentation needs to be skipped.
1153 if (*I == prec::Conditional ||
1154 (!SkipFirstExtraIndent && *I > prec::Assignment &&
Daniel Jasper8c6e9ef2014-12-02 09:46:56 +00001155 !Current.isTrailingComment()))
Daniel Jasper6633ab82013-10-18 10:38:14 +00001156 NewParenState.Indent += Style.ContinuationIndentWidth;
Daniel Jasper7bec87c2016-01-07 18:11:54 +00001157 if ((Previous && !Previous->opensScope()) || *I != prec::Comma)
Daniel Jasperde0328a2013-08-16 11:20:30 +00001158 NewParenState.BreakBeforeParameter = false;
1159 State.Stack.push_back(NewParenState);
1160 SkipFirstExtraIndent = false;
1161 }
Daniel Jasper60553be2014-05-26 13:10:39 +00001162}
Daniel Jasperde0328a2013-08-16 11:20:30 +00001163
Daniel Jasper11a0ac62014-12-12 09:40:58 +00001164void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
1165 for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) {
Daniel Jasper335ff262014-05-28 09:11:53 +00001166 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper335ff262014-05-28 09:11:53 +00001167 if (State.Stack.size() == 1) {
1168 // Do not pop the last element.
1169 break;
1170 }
1171 State.Stack.pop_back();
1172 State.Stack.back().VariablePos = VariablePos;
1173 }
1174}
1175
Daniel Jasper60553be2014-05-26 13:10:39 +00001176void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
1177 bool Newline) {
1178 const FormatToken &Current = *State.NextToken;
1179 if (!Current.opensScope())
1180 return;
1181
1182 if (Current.MatchingParen && Current.BlockKind == BK_Block) {
1183 moveStateToNewBlock(State);
1184 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001185 }
1186
Daniel Jasper60553be2014-05-26 13:10:39 +00001187 unsigned NewIndent;
Daniel Jasperde7ca752015-05-04 07:39:00 +00001188 unsigned LastSpace = State.Stack.back().LastSpace;
Daniel Jasper60553be2014-05-26 13:10:39 +00001189 bool AvoidBinPacking;
1190 bool BreakBeforeParameter = false;
Daniel Jasperea40cee2015-07-14 11:26:14 +00001191 unsigned NestedBlockIndent = std::max(State.Stack.back().StartOfFunctionCall,
1192 State.Stack.back().NestedBlockIndent);
Krasimir Georgievff747be2017-06-27 13:43:07 +00001193 if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001194 opensProtoMessageField(Current, Style)) {
Daniel Jasperbd73bcf2015-10-27 13:42:08 +00001195 if (Current.opensBlockOrBlockTypeList(Style)) {
Martin Probst38423272017-06-06 12:38:29 +00001196 NewIndent = Style.IndentWidth +
1197 std::min(State.Column, State.Stack.back().NestedBlockIndent);
Daniel Jasper60553be2014-05-26 13:10:39 +00001198 } else {
Daniel Jasper11a0ac62014-12-12 09:40:58 +00001199 NewIndent = State.Stack.back().LastSpace + Style.ContinuationIndentWidth;
Daniel Jasper60553be2014-05-26 13:10:39 +00001200 }
1201 const FormatToken *NextNoComment = Current.getNextNonComment();
Daniel Jasper50780ce2016-01-13 16:41:34 +00001202 bool EndsInComma = Current.MatchingParen &&
1203 Current.MatchingParen->Previous &&
1204 Current.MatchingParen->Previous->is(tok::comma);
Manuel Klimek89628f62017-09-20 09:51:03 +00001205 AvoidBinPacking = EndsInComma || Current.is(TT_DictLiteral) ||
1206 Style.Language == FormatStyle::LK_Proto ||
1207 Style.Language == FormatStyle::LK_TextProto ||
1208 !Style.BinPackArguments ||
1209 (NextNoComment &&
1210 NextNoComment->isOneOf(TT_DesignatedInitializerPeriod,
1211 TT_DesignatedInitializerLSquare));
Francois Ferrandd2130f52017-06-30 20:00:02 +00001212 BreakBeforeParameter = EndsInComma;
Daniel Jasperea40cee2015-07-14 11:26:14 +00001213 if (Current.ParameterCount > 1)
1214 NestedBlockIndent = std::max(NestedBlockIndent, State.Column + 1);
Daniel Jasper60553be2014-05-26 13:10:39 +00001215 } else {
1216 NewIndent = Style.ContinuationIndentWidth +
1217 std::max(State.Stack.back().LastSpace,
1218 State.Stack.back().StartOfFunctionCall);
Daniel Jasperde7ca752015-05-04 07:39:00 +00001219
1220 // Ensure that different different brackets force relative alignment, e.g.:
1221 // void SomeFunction(vector< // break
1222 // int> v);
1223 // FIXME: We likely want to do this for more combinations of brackets.
Daniel Jasper3f119412017-01-31 14:39:33 +00001224 if (Current.is(tok::less) && Current.ParentBracket == tok::l_paren) {
Daniel Jasperde7ca752015-05-04 07:39:00 +00001225 NewIndent = std::max(NewIndent, State.Stack.back().Indent);
1226 LastSpace = std::max(LastSpace, State.Stack.back().Indent);
1227 }
1228
Martin Probst2c1cdae2017-05-15 11:15:29 +00001229 bool EndsInComma =
1230 Current.MatchingParen &&
1231 Current.MatchingParen->getPreviousNonComment() &&
1232 Current.MatchingParen->getPreviousNonComment()->is(tok::comma);
1233
Ben Hamilton4dc658c2018-02-02 20:15:14 +00001234 // If ObjCBinPackProtocolList is unspecified, fall back to BinPackParameters
1235 // for backwards compatibility.
1236 bool ObjCBinPackProtocolList =
1237 (Style.ObjCBinPackProtocolList == FormatStyle::BPS_Auto &&
1238 Style.BinPackParameters) ||
1239 Style.ObjCBinPackProtocolList == FormatStyle::BPS_Always;
1240
1241 bool BinPackDeclaration =
1242 (State.Line->Type != LT_ObjCDecl && Style.BinPackParameters) ||
1243 (State.Line->Type == LT_ObjCDecl && ObjCBinPackProtocolList);
1244
Daniel Jasper18210d72014-10-09 09:52:05 +00001245 AvoidBinPacking =
Martin Probst2c1cdae2017-05-15 11:15:29 +00001246 (Style.Language == FormatStyle::LK_JavaScript && EndsInComma) ||
Ben Hamilton4dc658c2018-02-02 20:15:14 +00001247 (State.Line->MustBeDeclaration && !BinPackDeclaration) ||
Daniel Jasper18210d72014-10-09 09:52:05 +00001248 (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||
1249 (Style.ExperimentalAutoDetectBinPacking &&
1250 (Current.PackingKind == PPK_OnePerLine ||
1251 (!BinPackInconclusiveFunctions &&
1252 Current.PackingKind == PPK_Inconclusive)));
Martin Probst2c1cdae2017-05-15 11:15:29 +00001253
Daniel Jasper289afc02015-04-23 09:23:17 +00001254 if (Current.is(TT_ObjCMethodExpr) && Current.MatchingParen) {
1255 if (Style.ColumnLimit) {
1256 // If this '[' opens an ObjC call, determine whether all parameters fit
1257 // into one line and put one per line if they don't.
1258 if (getLengthToMatchingParen(Current) + State.Column >
Daniel Jasper60553be2014-05-26 13:10:39 +00001259 getColumnLimit(State))
Daniel Jasper289afc02015-04-23 09:23:17 +00001260 BreakBeforeParameter = true;
1261 } else {
1262 // For ColumnLimit = 0, we have to figure out whether there is or has to
1263 // be a line break within this call.
1264 for (const FormatToken *Tok = &Current;
1265 Tok && Tok != Current.MatchingParen; Tok = Tok->Next) {
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001266 if (Tok->MustBreakBefore ||
Daniel Jasper289afc02015-04-23 09:23:17 +00001267 (Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) {
1268 BreakBeforeParameter = true;
1269 break;
1270 }
1271 }
1272 }
1273 }
Martin Probst2c1cdae2017-05-15 11:15:29 +00001274
1275 if (Style.Language == FormatStyle::LK_JavaScript && EndsInComma)
1276 BreakBeforeParameter = true;
Daniel Jasper60553be2014-05-26 13:10:39 +00001277 }
Daniel Jasperbd73bcf2015-10-27 13:42:08 +00001278 // Generally inherit NoLineBreak from the current scope to nested scope.
1279 // However, don't do this for non-empty nested blocks, dict literals and
1280 // array literals as these follow different indentation rules.
1281 bool NoLineBreak =
1282 Current.Children.empty() &&
1283 !Current.isOneOf(TT_DictLiteral, TT_ArrayInitializerLSquare) &&
1284 (State.Stack.back().NoLineBreak ||
Daniel Jasper240527c2017-01-16 13:13:15 +00001285 State.Stack.back().NoLineBreakInOperand ||
Daniel Jasperbd73bcf2015-10-27 13:42:08 +00001286 (Current.is(TT_TemplateOpener) &&
Daniel Jasper240527c2017-01-16 13:13:15 +00001287 State.Stack.back().ContainsUnwrappedBuilder));
Daniel Jasper7d42f3f2017-01-31 11:25:01 +00001288 State.Stack.push_back(
1289 ParenState(NewIndent, LastSpace, AvoidBinPacking, NoLineBreak));
Daniel Jasper11a0ac62014-12-12 09:40:58 +00001290 State.Stack.back().NestedBlockIndent = NestedBlockIndent;
Daniel Jasper60553be2014-05-26 13:10:39 +00001291 State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
Daniel Jasper114a2bc2014-06-03 12:02:45 +00001292 State.Stack.back().HasMultipleNestedBlocks = Current.BlockParameterCount > 1;
Ben Hamilton09051f22018-02-08 16:07:25 +00001293 State.Stack.back().IsInsideObjCArrayLiteral =
1294 Current.is(TT_ArrayInitializerLSquare) && Current.Previous &&
1295 Current.Previous->is(tok::at);
Daniel Jasper60553be2014-05-26 13:10:39 +00001296}
1297
1298void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
1299 const FormatToken &Current = *State.NextToken;
1300 if (!Current.closesScope())
1301 return;
1302
1303 // If we encounter a closing ), ], } or >, we can remove a level from our
1304 // stacks.
1305 if (State.Stack.size() > 1 &&
Daniel Jasperc06f6da2017-02-03 14:32:38 +00001306 (Current.isOneOf(tok::r_paren, tok::r_square, TT_TemplateString) ||
Daniel Jasper60553be2014-05-26 13:10:39 +00001307 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
Krasimir Georgieva79d62d2018-02-06 11:34:34 +00001308 State.NextToken->is(TT_TemplateCloser) ||
1309 (Current.is(tok::greater) && Current.is(TT_DictLiteral))))
Daniel Jasper60553be2014-05-26 13:10:39 +00001310 State.Stack.pop_back();
Daniel Jasper335ff262014-05-28 09:11:53 +00001311
Daniel Jasper60553be2014-05-26 13:10:39 +00001312 if (Current.is(tok::r_square)) {
1313 // If this ends the array subscript expr, reset the corresponding value.
1314 const FormatToken *NextNonComment = Current.getNextNonComment();
1315 if (NextNonComment && NextNonComment->isNot(tok::l_square))
1316 State.Stack.back().StartOfArraySubscripts = 0;
1317 }
1318}
1319
1320void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
Daniel Jasper11a0ac62014-12-12 09:40:58 +00001321 unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
Daniel Jasper50d634b2014-10-28 16:53:38 +00001322 // ObjC block sometimes follow special indentation rules.
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001323 unsigned NewIndent =
Daniel Jasper11a0ac62014-12-12 09:40:58 +00001324 NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace)
1325 ? Style.ObjCBlockIndentWidth
1326 : Style.IndentWidth);
Daniel Jasper7d42f3f2017-01-31 11:25:01 +00001327 State.Stack.push_back(ParenState(NewIndent, State.Stack.back().LastSpace,
1328 /*AvoidBinPacking=*/true,
1329 /*NoLineBreak=*/false));
Daniel Jasper11a0ac62014-12-12 09:40:58 +00001330 State.Stack.back().NestedBlockIndent = NestedBlockIndent;
Daniel Jasper60553be2014-05-26 13:10:39 +00001331 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001332}
1333
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001334static unsigned getLastLineEndColumn(StringRef Text, unsigned StartColumn,
1335 unsigned TabWidth,
1336 encoding::Encoding Encoding) {
1337 size_t LastNewlinePos = Text.find_last_of("\n");
1338 if (LastNewlinePos == StringRef::npos) {
1339 return StartColumn +
1340 encoding::columnWidthWithTabs(Text, StartColumn, TabWidth, Encoding);
1341 } else {
1342 return encoding::columnWidthWithTabs(Text.substr(LastNewlinePos),
1343 /*StartColumn=*/0, TabWidth, Encoding);
1344 }
1345}
1346
1347unsigned ContinuationIndenter::reformatRawStringLiteral(
Manuel Klimek45ab5592017-11-14 09:19:53 +00001348 const FormatToken &Current, LineState &State,
1349 const FormatStyle &RawStringStyle, bool DryRun) {
1350 unsigned StartColumn = State.Column - Current.ColumnWidth;
Krasimir Georgiev412ed092018-01-19 16:18:47 +00001351 StringRef OldDelimiter = *getRawStringDelimiter(Current.TokenText);
1352 StringRef NewDelimiter =
1353 getCanonicalRawStringDelimiter(Style, RawStringStyle.Language);
1354 if (NewDelimiter.empty() || OldDelimiter.empty())
1355 NewDelimiter = OldDelimiter;
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001356 // The text of a raw string is between the leading 'R"delimiter(' and the
1357 // trailing 'delimiter)"'.
Krasimir Georgiev412ed092018-01-19 16:18:47 +00001358 unsigned OldPrefixSize = 3 + OldDelimiter.size();
1359 unsigned OldSuffixSize = 2 + OldDelimiter.size();
1360 // We create a virtual text environment which expects a null-terminated
1361 // string, so we cannot use StringRef.
1362 std::string RawText =
1363 Current.TokenText.substr(OldPrefixSize).drop_back(OldSuffixSize);
1364 if (NewDelimiter != OldDelimiter) {
1365 // Don't update to the canonical delimiter 'deli' if ')deli"' occurs in the
1366 // raw string.
1367 std::string CanonicalDelimiterSuffix = (")" + NewDelimiter + "\"").str();
1368 if (StringRef(RawText).contains(CanonicalDelimiterSuffix))
1369 NewDelimiter = OldDelimiter;
1370 }
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001371
Krasimir Georgiev412ed092018-01-19 16:18:47 +00001372 unsigned NewPrefixSize = 3 + NewDelimiter.size();
1373 unsigned NewSuffixSize = 2 + NewDelimiter.size();
1374
1375 // The first start column is the column the raw text starts after formatting.
1376 unsigned FirstStartColumn = StartColumn + NewPrefixSize;
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001377
1378 // The next start column is the intended indentation a line break inside
1379 // the raw string at level 0. It is determined by the following rules:
1380 // - if the content starts on newline, it is one level more than the current
1381 // indent, and
1382 // - if the content does not start on a newline, it is the first start
1383 // column.
1384 // These rules have the advantage that the formatted content both does not
1385 // violate the rectangle rule and visually flows within the surrounding
1386 // source.
Krasimir Georgiev412ed092018-01-19 16:18:47 +00001387 bool ContentStartsOnNewline = Current.TokenText[OldPrefixSize] == '\n';
Krasimir Georgieva71f6262018-03-08 11:29:27 +00001388 unsigned NextStartColumn =
1389 ContentStartsOnNewline
1390 ? State.Stack.back().NestedBlockIndent + Style.IndentWidth
1391 : FirstStartColumn;
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001392
1393 // The last start column is the column the raw string suffix starts if it is
1394 // put on a newline.
1395 // The last start column is the intended indentation of the raw string postfix
1396 // if it is put on a newline. It is determined by the following rules:
1397 // - if the raw string prefix starts on a newline, it is the column where
1398 // that raw string prefix starts, and
1399 // - if the raw string prefix does not start on a newline, it is the current
1400 // indent.
1401 unsigned LastStartColumn = Current.NewlinesBefore
Krasimir Georgiev412ed092018-01-19 16:18:47 +00001402 ? FirstStartColumn - NewPrefixSize
Krasimir Georgieva71f6262018-03-08 11:29:27 +00001403 : State.Stack.back().NestedBlockIndent;
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001404
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001405 std::pair<tooling::Replacements, unsigned> Fixes = internal::reformat(
1406 RawStringStyle, RawText, {tooling::Range(0, RawText.size())},
1407 FirstStartColumn, NextStartColumn, LastStartColumn, "<stdin>",
Krasimir Georgiev0fcb5802017-11-09 13:19:14 +00001408 /*Status=*/nullptr);
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001409
1410 auto NewCode = applyAllReplacements(RawText, Fixes.first);
1411 tooling::Replacements NoFixes;
1412 if (!NewCode) {
1413 State.Column += Current.ColumnWidth;
1414 return 0;
1415 }
1416 if (!DryRun) {
Krasimir Georgiev412ed092018-01-19 16:18:47 +00001417 if (NewDelimiter != OldDelimiter) {
1418 // In 'R"delimiter(...', the delimiter starts 2 characters after the start
1419 // of the token.
1420 SourceLocation PrefixDelimiterStart =
1421 Current.Tok.getLocation().getLocWithOffset(2);
1422 auto PrefixErr = Whitespaces.addReplacement(tooling::Replacement(
1423 SourceMgr, PrefixDelimiterStart, OldDelimiter.size(), NewDelimiter));
1424 if (PrefixErr) {
1425 llvm::errs()
1426 << "Failed to update the prefix delimiter of a raw string: "
1427 << llvm::toString(std::move(PrefixErr)) << "\n";
1428 }
1429 // In 'R"delimiter(...)delimiter"', the suffix delimiter starts at
1430 // position length - 1 - |delimiter|.
1431 SourceLocation SuffixDelimiterStart =
1432 Current.Tok.getLocation().getLocWithOffset(Current.TokenText.size() -
1433 1 - OldDelimiter.size());
1434 auto SuffixErr = Whitespaces.addReplacement(tooling::Replacement(
1435 SourceMgr, SuffixDelimiterStart, OldDelimiter.size(), NewDelimiter));
1436 if (SuffixErr) {
1437 llvm::errs()
1438 << "Failed to update the suffix delimiter of a raw string: "
1439 << llvm::toString(std::move(SuffixErr)) << "\n";
1440 }
1441 }
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001442 SourceLocation OriginLoc =
Krasimir Georgiev412ed092018-01-19 16:18:47 +00001443 Current.Tok.getLocation().getLocWithOffset(OldPrefixSize);
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001444 for (const tooling::Replacement &Fix : Fixes.first) {
1445 auto Err = Whitespaces.addReplacement(tooling::Replacement(
1446 SourceMgr, OriginLoc.getLocWithOffset(Fix.getOffset()),
1447 Fix.getLength(), Fix.getReplacementText()));
1448 if (Err) {
1449 llvm::errs() << "Failed to reformat raw string: "
1450 << llvm::toString(std::move(Err)) << "\n";
1451 }
1452 }
1453 }
1454 unsigned RawLastLineEndColumn = getLastLineEndColumn(
1455 *NewCode, FirstStartColumn, Style.TabWidth, Encoding);
Krasimir Georgiev412ed092018-01-19 16:18:47 +00001456 State.Column = RawLastLineEndColumn + NewSuffixSize;
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001457 return Fixes.second;
1458}
1459
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001460unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
1461 LineState &State) {
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00001462 // Break before further function parameters on all levels.
1463 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1464 State.Stack[i].BreakBeforeParameter = true;
1465
Alexander Kornienko39856b72013-09-10 09:38:25 +00001466 unsigned ColumnsUsed = State.Column;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001467 // We can only affect layout of the first and the last line, so the penalty
1468 // for all other lines is constant, and we ignore it.
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001469 State.Column = Current.LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001470
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001471 if (ColumnsUsed > getColumnLimit(State))
1472 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00001473 return 0;
1474}
1475
Manuel Klimek45ab5592017-11-14 09:19:53 +00001476unsigned ContinuationIndenter::handleEndOfLine(const FormatToken &Current,
1477 LineState &State, bool DryRun,
1478 bool AllowBreak) {
1479 unsigned Penalty = 0;
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001480 // Compute the raw string style to use in case this is a raw string literal
1481 // that can be reformatted.
Manuel Klimek45ab5592017-11-14 09:19:53 +00001482 auto RawStringStyle = getRawStringStyle(Current, State);
Daniel Jasperdd0c4e12018-03-12 10:11:30 +00001483 if (RawStringStyle && !Current.Finalized) {
Manuel Klimek45ab5592017-11-14 09:19:53 +00001484 Penalty = reformatRawStringLiteral(Current, State, *RawStringStyle, DryRun);
1485 } else if (Current.IsMultiline && Current.isNot(TT_BlockComment)) {
1486 // Don't break multi-line tokens other than block comments and raw string
1487 // literals. Instead, just update the state.
1488 Penalty = addMultilineToken(Current, State);
1489 } else if (State.Line->Type != LT_ImportStatement) {
1490 // We generally don't break import statements.
Manuel Klimek0b58c322017-12-01 13:28:08 +00001491 LineState OriginalState = State;
1492
1493 // Whether we force the reflowing algorithm to stay strictly within the
1494 // column limit.
1495 bool Strict = false;
1496 // Whether the first non-strict attempt at reflowing did intentionally
1497 // exceed the column limit.
1498 bool Exceeded = false;
1499 std::tie(Penalty, Exceeded) = breakProtrudingToken(
1500 Current, State, AllowBreak, /*DryRun=*/true, Strict);
1501 if (Exceeded) {
1502 // If non-strict reflowing exceeds the column limit, try whether strict
1503 // reflowing leads to an overall lower penalty.
1504 LineState StrictState = OriginalState;
1505 unsigned StrictPenalty =
1506 breakProtrudingToken(Current, StrictState, AllowBreak,
1507 /*DryRun=*/true, /*Strict=*/true)
1508 .first;
1509 Strict = StrictPenalty <= Penalty;
1510 if (Strict) {
1511 Penalty = StrictPenalty;
1512 State = StrictState;
1513 }
1514 }
1515 if (!DryRun) {
1516 // If we're not in dry-run mode, apply the changes with the decision on
1517 // strictness made above.
1518 breakProtrudingToken(Current, OriginalState, AllowBreak, /*DryRun=*/false,
1519 Strict);
1520 }
Manuel Klimek45ab5592017-11-14 09:19:53 +00001521 }
1522 if (State.Column > getColumnLimit(State)) {
1523 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
1524 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
1525 }
1526 return Penalty;
1527}
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001528
Krasimir Georgiev2537e222018-01-17 16:17:26 +00001529// Returns the enclosing function name of a token, or the empty string if not
1530// found.
1531static StringRef getEnclosingFunctionName(const FormatToken &Current) {
1532 // Look for: 'function(' or 'function<templates>(' before Current.
1533 auto Tok = Current.getPreviousNonComment();
1534 if (!Tok || !Tok->is(tok::l_paren))
1535 return "";
1536 Tok = Tok->getPreviousNonComment();
1537 if (!Tok)
1538 return "";
1539 if (Tok->is(TT_TemplateCloser)) {
1540 Tok = Tok->MatchingParen;
1541 if (Tok)
1542 Tok = Tok->getPreviousNonComment();
1543 }
1544 if (!Tok || !Tok->is(tok::identifier))
1545 return "";
1546 return Tok->TokenText;
1547}
1548
Manuel Klimek45ab5592017-11-14 09:19:53 +00001549llvm::Optional<FormatStyle>
1550ContinuationIndenter::getRawStringStyle(const FormatToken &Current,
1551 const LineState &State) {
1552 if (!Current.isStringLiteral())
1553 return None;
1554 auto Delimiter = getRawStringDelimiter(Current.TokenText);
1555 if (!Delimiter)
1556 return None;
Krasimir Georgiev2537e222018-01-17 16:17:26 +00001557 auto RawStringStyle = RawStringFormats.getDelimiterStyle(*Delimiter);
1558 if (!RawStringStyle)
1559 RawStringStyle = RawStringFormats.getEnclosingFunctionStyle(
1560 getEnclosingFunctionName(Current));
Manuel Klimek45ab5592017-11-14 09:19:53 +00001561 if (!RawStringStyle)
1562 return None;
1563 RawStringStyle->ColumnLimit = getColumnLimit(State);
1564 return RawStringStyle;
1565}
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001566
Manuel Klimek45ab5592017-11-14 09:19:53 +00001567std::unique_ptr<BreakableToken> ContinuationIndenter::createBreakableToken(
1568 const FormatToken &Current, LineState &State, bool AllowBreak) {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001569 unsigned StartColumn = State.Column - Current.ColumnWidth;
Daniel Jasper04b6a082013-12-20 06:22:01 +00001570 if (Current.isStringLiteral()) {
Daniel Jasper428f0b12015-01-04 09:11:17 +00001571 // FIXME: String literal breaking is currently disabled for Java and JS, as
1572 // it requires strings to be merged using "+" which we don't support.
1573 if (Style.Language == FormatStyle::LK_Java ||
Daniel Jaspere1a7b762016-02-01 11:21:02 +00001574 Style.Language == FormatStyle::LK_JavaScript ||
Manuel Klimek45ab5592017-11-14 09:19:53 +00001575 !Style.BreakStringLiterals ||
1576 !AllowBreak)
1577 return nullptr;
Daniel Jasper428f0b12015-01-04 09:11:17 +00001578
Alexander Kornienko384b40b2013-10-11 21:43:05 +00001579 // Don't break string literals inside preprocessor directives (except for
1580 // #define directives, as their contents are stored in separate lines and
1581 // are not affected by this check).
1582 // This way we avoid breaking code with line directives and unknown
1583 // preprocessor directives that contain long string literals.
1584 if (State.Line->Type == LT_PreprocessorDirective)
Manuel Klimek45ab5592017-11-14 09:19:53 +00001585 return nullptr;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001586 // Exempts unterminated string literals from line breaking. The user will
1587 // likely want to terminate the string before any line breaking is done.
1588 if (Current.IsUnterminatedLiteral)
Manuel Klimek45ab5592017-11-14 09:19:53 +00001589 return nullptr;
Ben Hamilton09051f22018-02-08 16:07:25 +00001590 // Don't break string literals inside Objective-C array literals (doing so
1591 // raises the warning -Wobjc-string-concatenation).
1592 if (State.Stack.back().IsInsideObjCArrayLiteral) {
1593 return nullptr;
1594 }
Daniel Jasperde0328a2013-08-16 11:20:30 +00001595
Alexander Kornienko81e32942013-09-16 20:20:49 +00001596 StringRef Text = Current.TokenText;
1597 StringRef Prefix;
1598 StringRef Postfix;
1599 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
1600 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
1601 // reduce the overhead) for each FormatToken, which is a string, so that we
1602 // don't run multiple checks here on the hot path.
1603 if ((Text.endswith(Postfix = "\"") &&
Alexander Kornienkod4fa2e62017-04-11 09:55:00 +00001604 (Text.startswith(Prefix = "@\"") || Text.startswith(Prefix = "\"") ||
Daniel Jasper174b0122014-01-09 14:18:12 +00001605 Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
1606 Text.startswith(Prefix = "u8\"") ||
Alexander Kornienko81e32942013-09-16 20:20:49 +00001607 Text.startswith(Prefix = "L\""))) ||
Alexander Kornienko732b6bd2014-12-14 20:47:11 +00001608 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) {
Krasimir Georgiev55c23a12018-01-23 11:26:19 +00001609 // We need this to address the case where there is an unbreakable tail
1610 // only if certain other formatting decisions have been taken. The
1611 // UnbreakableTailLength of Current is an overapproximation is that case
1612 // and we need to be correct here.
1613 unsigned UnbreakableTailLength = (State.NextToken && canBreak(State))
1614 ? 0
1615 : Current.UnbreakableTailLength;
Manuel Klimek45ab5592017-11-14 09:19:53 +00001616 return llvm::make_unique<BreakableStringLiteral>(
Krasimir Georgiev55c23a12018-01-23 11:26:19 +00001617 Current, StartColumn, Prefix, Postfix, UnbreakableTailLength,
1618 State.Line->InPPDirective, Encoding, Style);
Alexander Kornienko81e32942013-09-16 20:20:49 +00001619 }
Daniel Jasperacadc8e2016-06-08 09:45:08 +00001620 } else if (Current.is(TT_BlockComment)) {
Krasimir Georgiev35599fd2017-10-16 09:08:53 +00001621 if (!Style.ReflowComments ||
Krasimir Georgiev91834222017-01-25 13:58:58 +00001622 // If a comment token switches formatting, like
1623 // /* clang-format on */, we don't want to break it further,
1624 // but we may still want to adjust its indentation.
Manuel Klimek45ab5592017-11-14 09:19:53 +00001625 switchesFormatting(Current)) {
1626 return nullptr;
1627 }
1628 return llvm::make_unique<BreakableBlockComment>(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +00001629 Current, StartColumn, Current.OriginalColumn, !Current.Previous,
Manuel Klimek45ab5592017-11-14 09:19:53 +00001630 State.Line->InPPDirective, Encoding, Style);
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001631 } else if (Current.is(TT_LineComment) &&
Craig Topper2145bc02014-05-09 08:15:10 +00001632 (Current.Previous == nullptr ||
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001633 Current.Previous->isNot(TT_ImplicitStringLiteral))) {
Daniel Jaspera0a50392015-12-01 13:28:53 +00001634 if (!Style.ReflowComments ||
Krasimir Georgiev91834222017-01-25 13:58:58 +00001635 CommentPragmasRegex.match(Current.TokenText.substr(2)) ||
1636 switchesFormatting(Current))
Manuel Klimek45ab5592017-11-14 09:19:53 +00001637 return nullptr;
1638 return llvm::make_unique<BreakableLineCommentSection>(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +00001639 Current, StartColumn, Current.OriginalColumn, !Current.Previous,
Manuel Klimek45ab5592017-11-14 09:19:53 +00001640 /*InPPDirective=*/false, Encoding, Style);
1641 }
1642 return nullptr;
1643}
1644
Manuel Klimek0b58c322017-12-01 13:28:08 +00001645std::pair<unsigned, bool>
1646ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
1647 LineState &State, bool AllowBreak,
1648 bool DryRun, bool Strict) {
Manuel Klimek93699f42017-11-29 14:29:43 +00001649 std::unique_ptr<const BreakableToken> Token =
Manuel Klimek45ab5592017-11-14 09:19:53 +00001650 createBreakableToken(Current, State, AllowBreak);
1651 if (!Token)
Manuel Klimek0b58c322017-12-01 13:28:08 +00001652 return {0, false};
Manuel Klimek93699f42017-11-29 14:29:43 +00001653 assert(Token->getLineCount() > 0);
Manuel Klimek45ab5592017-11-14 09:19:53 +00001654 unsigned ColumnLimit = getColumnLimit(State);
Manuel Klimek45ab5592017-11-14 09:19:53 +00001655 if (Current.is(TT_LineComment)) {
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001656 // We don't insert backslashes when breaking line comments.
1657 ColumnLimit = Style.ColumnLimit;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001658 }
Alexander Kornienko3abbb8a2013-11-12 17:30:49 +00001659 if (Current.UnbreakableTailLength >= ColumnLimit)
Manuel Klimek0b58c322017-12-01 13:28:08 +00001660 return {0, false};
Manuel Klimek93699f42017-11-29 14:29:43 +00001661 // ColumnWidth was already accounted into State.Column before calling
1662 // breakProtrudingToken.
1663 unsigned StartColumn = State.Column - Current.ColumnWidth;
Manuel Klimek77866142017-11-17 11:17:15 +00001664 unsigned NewBreakPenalty = Current.isStringLiteral()
1665 ? Style.PenaltyBreakString
1666 : Style.PenaltyBreakComment;
Manuel Klimek0b58c322017-12-01 13:28:08 +00001667 // Stores whether we intentionally decide to let a line exceed the column
1668 // limit.
1669 bool Exceeded = false;
Manuel Klimek93699f42017-11-29 14:29:43 +00001670 // Stores whether we introduce a break anywhere in the token.
Manuel Klimek77866142017-11-17 11:17:15 +00001671 bool BreakInserted = Token->introducesBreakBeforeToken();
1672 // Store whether we inserted a new line break at the end of the previous
1673 // logical line.
1674 bool NewBreakBefore = false;
Krasimir Georgiev91834222017-01-25 13:58:58 +00001675 // We use a conservative reflowing strategy. Reflow starts after a line is
1676 // broken or the corresponding whitespace compressed. Reflow ends as soon as a
1677 // line that doesn't get reflown with the previous line is reached.
Manuel Klimek93699f42017-11-29 14:29:43 +00001678 bool Reflow = false;
1679 // Keep track of where we are in the token:
1680 // Where we are in the content of the current logical line.
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +00001681 unsigned TailOffset = 0;
Manuel Klimek93699f42017-11-29 14:29:43 +00001682 // The column number we're currently at.
1683 unsigned ContentStartColumn =
1684 Token->getContentStartColumn(0, /*Break=*/false);
1685 // The number of columns left in the current logical line after TailOffset.
1686 unsigned RemainingTokenColumns =
1687 Token->getRemainingLength(0, TailOffset, ContentStartColumn);
1688 // Adapt the start of the token, for example indent.
1689 if (!DryRun)
1690 Token->adaptStartOfLine(0, Whitespaces);
1691
1692 unsigned Penalty = 0;
Manuel Klimek77866142017-11-17 11:17:15 +00001693 DEBUG(llvm::dbgs() << "Breaking protruding token at column " << StartColumn
1694 << ".\n");
Daniel Jasperde0328a2013-08-16 11:20:30 +00001695 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
1696 LineIndex != EndIndex; ++LineIndex) {
Manuel Klimek93699f42017-11-29 14:29:43 +00001697 DEBUG(llvm::dbgs() << " Line: " << LineIndex << " (Reflow: " << Reflow
1698 << ")\n");
Manuel Klimek77866142017-11-17 11:17:15 +00001699 NewBreakBefore = false;
Manuel Klimek93699f42017-11-29 14:29:43 +00001700 // If we did reflow the previous line, we'll try reflowing again. Otherwise
1701 // we'll start reflowing if the current line is broken or whitespace is
1702 // compressed.
1703 bool TryReflow = Reflow;
1704 // Break the current token until we can fit the rest of the line.
1705 while (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {
1706 DEBUG(llvm::dbgs() << " Over limit, need: "
1707 << (ContentStartColumn + RemainingTokenColumns)
1708 << ", space: " << ColumnLimit
1709 << ", reflown prefix: " << ContentStartColumn
1710 << ", offset in line: " << TailOffset << "\n");
1711 // If the current token doesn't fit, find the latest possible split in the
1712 // current line so that breaking at it will be under the column limit.
1713 // FIXME: Use the earliest possible split while reflowing to correctly
1714 // compress whitespace within a line.
1715 BreakableToken::Split Split =
1716 Token->getSplit(LineIndex, TailOffset, ColumnLimit,
1717 ContentStartColumn, CommentPragmasRegex);
Daniel Jasperde0328a2013-08-16 11:20:30 +00001718 if (Split.first == StringRef::npos) {
Manuel Klimek93699f42017-11-29 14:29:43 +00001719 // No break opportunity - update the penalty and continue with the next
1720 // logical line.
Daniel Jasperde0328a2013-08-16 11:20:30 +00001721 if (LineIndex < EndIndex - 1)
Manuel Klimek93699f42017-11-29 14:29:43 +00001722 // The last line's penalty is handled in addNextStateToQueue().
Daniel Jasperde0328a2013-08-16 11:20:30 +00001723 Penalty += Style.PenaltyExcessCharacter *
Manuel Klimek93699f42017-11-29 14:29:43 +00001724 (ContentStartColumn + RemainingTokenColumns - ColumnLimit);
Manuel Klimek77866142017-11-17 11:17:15 +00001725 DEBUG(llvm::dbgs() << " No break opportunity.\n");
Daniel Jasperde0328a2013-08-16 11:20:30 +00001726 break;
1727 }
1728 assert(Split.first != 0);
Alexander Kornienko875395f2013-11-12 17:50:13 +00001729
Manuel Klimek93699f42017-11-29 14:29:43 +00001730 if (Token->supportsReflow()) {
1731 // Check whether the next natural split point after the current one can
1732 // still fit the line, either because we can compress away whitespace,
1733 // or because the penalty the excess characters introduce is lower than
1734 // the break penalty.
1735 // We only do this for tokens that support reflowing, and thus allow us
1736 // to change the whitespace arbitrarily (e.g. comments).
1737 // Other tokens, like string literals, can be broken on arbitrary
1738 // positions.
1739
1740 // First, compute the columns from TailOffset to the next possible split
1741 // position.
1742 // For example:
1743 // ColumnLimit: |
1744 // // Some text that breaks
1745 // ^ tail offset
1746 // ^-- split
1747 // ^-------- to split columns
1748 // ^--- next split
1749 // ^--------------- to next split columns
1750 unsigned ToSplitColumns = Token->getRangeLength(
1751 LineIndex, TailOffset, Split.first, ContentStartColumn);
1752 DEBUG(llvm::dbgs() << " ToSplit: " << ToSplitColumns << "\n");
1753
1754 BreakableToken::Split NextSplit = Token->getSplit(
1755 LineIndex, TailOffset + Split.first + Split.second, ColumnLimit,
1756 ContentStartColumn + ToSplitColumns + 1, CommentPragmasRegex);
1757 // Compute the columns necessary to fit the next non-breakable sequence
1758 // into the current line.
1759 unsigned ToNextSplitColumns = 0;
1760 if (NextSplit.first == StringRef::npos) {
1761 ToNextSplitColumns = Token->getRemainingLength(LineIndex, TailOffset,
1762 ContentStartColumn);
1763 } else {
1764 ToNextSplitColumns = Token->getRangeLength(
1765 LineIndex, TailOffset,
1766 Split.first + Split.second + NextSplit.first, ContentStartColumn);
1767 }
1768 // Compress the whitespace between the break and the start of the next
1769 // unbreakable sequence.
1770 ToNextSplitColumns =
1771 Token->getLengthAfterCompression(ToNextSplitColumns, Split);
1772 DEBUG(llvm::dbgs() << " ContentStartColumn: " << ContentStartColumn
1773 << "\n");
1774 DEBUG(llvm::dbgs() << " ToNextSplit: " << ToNextSplitColumns << "\n");
1775 // If the whitespace compression makes us fit, continue on the current
1776 // line.
1777 bool ContinueOnLine =
1778 ContentStartColumn + ToNextSplitColumns <= ColumnLimit;
1779 unsigned ExcessCharactersPenalty = 0;
Manuel Klimek0b58c322017-12-01 13:28:08 +00001780 if (!ContinueOnLine && !Strict) {
Manuel Klimek93699f42017-11-29 14:29:43 +00001781 // Similarly, if the excess characters' penalty is lower than the
1782 // penalty of introducing a new break, continue on the current line.
1783 ExcessCharactersPenalty =
1784 (ContentStartColumn + ToNextSplitColumns - ColumnLimit) *
1785 Style.PenaltyExcessCharacter;
1786 DEBUG(llvm::dbgs()
1787 << " Penalty excess: " << ExcessCharactersPenalty
1788 << "\n break : " << NewBreakPenalty << "\n");
Manuel Klimek0b58c322017-12-01 13:28:08 +00001789 if (ExcessCharactersPenalty < NewBreakPenalty) {
1790 Exceeded = true;
Manuel Klimek93699f42017-11-29 14:29:43 +00001791 ContinueOnLine = true;
Manuel Klimek0b58c322017-12-01 13:28:08 +00001792 }
Manuel Klimek93699f42017-11-29 14:29:43 +00001793 }
1794 if (ContinueOnLine) {
1795 DEBUG(llvm::dbgs() << " Continuing on line...\n");
1796 // The current line fits after compressing the whitespace - reflow
1797 // the next line into it if possible.
1798 TryReflow = true;
1799 if (!DryRun)
1800 Token->compressWhitespace(LineIndex, TailOffset, Split,
1801 Whitespaces);
1802 // When we continue on the same line, leave one space between content.
1803 ContentStartColumn += ToSplitColumns + 1;
1804 Penalty += ExcessCharactersPenalty;
1805 TailOffset += Split.first + Split.second;
1806 RemainingTokenColumns = Token->getRemainingLength(
1807 LineIndex, TailOffset, ContentStartColumn);
1808 continue;
1809 }
Manuel Klimek77866142017-11-17 11:17:15 +00001810 }
Manuel Klimek93699f42017-11-29 14:29:43 +00001811 DEBUG(llvm::dbgs() << " Breaking...\n");
1812 ContentStartColumn =
1813 Token->getContentStartColumn(LineIndex, /*Break=*/true);
1814 unsigned NewRemainingTokenColumns = Token->getRemainingLength(
1815 LineIndex, TailOffset + Split.first + Split.second,
1816 ContentStartColumn);
Krasimir Georgiev91834222017-01-25 13:58:58 +00001817
Alexander Kornienko64a42b82014-04-15 14:52:43 +00001818 // When breaking before a tab character, it may be moved by a few columns,
1819 // but will still be expanded to the next tab stop, so we don't save any
1820 // columns.
Manuel Klimek93699f42017-11-29 14:29:43 +00001821 if (NewRemainingTokenColumns == RemainingTokenColumns) {
Manuel Klimek77866142017-11-17 11:17:15 +00001822 // FIXME: Do we need to adjust the penalty?
Alexander Kornienko64a42b82014-04-15 14:52:43 +00001823 break;
Manuel Klimek93699f42017-11-29 14:29:43 +00001824 }
Daniel Jasperde0328a2013-08-16 11:20:30 +00001825 assert(NewRemainingTokenColumns < RemainingTokenColumns);
Manuel Klimek77866142017-11-17 11:17:15 +00001826
Manuel Klimek93699f42017-11-29 14:29:43 +00001827 DEBUG(llvm::dbgs() << " Breaking at: " << TailOffset + Split.first
1828 << ", " << Split.second << "\n");
Daniel Jasperde0328a2013-08-16 11:20:30 +00001829 if (!DryRun)
1830 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Manuel Klimek77866142017-11-17 11:17:15 +00001831
Manuel Klimek93699f42017-11-29 14:29:43 +00001832 Penalty += NewBreakPenalty;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001833 TailOffset += Split.first + Split.second;
1834 RemainingTokenColumns = NewRemainingTokenColumns;
1835 BreakInserted = true;
Manuel Klimek77866142017-11-17 11:17:15 +00001836 NewBreakBefore = true;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001837 }
Manuel Klimek93699f42017-11-29 14:29:43 +00001838 // In case there's another line, prepare the state for the start of the next
1839 // line.
1840 if (LineIndex + 1 != EndIndex) {
1841 unsigned NextLineIndex = LineIndex + 1;
1842 if (NewBreakBefore)
1843 // After breaking a line, try to reflow the next line into the current
1844 // one once RemainingTokenColumns fits.
1845 TryReflow = true;
1846 if (TryReflow) {
1847 // We decided that we want to try reflowing the next line into the
1848 // current one.
1849 // We will now adjust the state as if the reflow is successful (in
1850 // preparation for the next line), and see whether that works. If we
1851 // decide that we cannot reflow, we will later reset the state to the
1852 // start of the next line.
1853 Reflow = false;
1854 // As we did not continue breaking the line, RemainingTokenColumns is
1855 // known to fit after ContentStartColumn. Adapt ContentStartColumn to
1856 // the position at which we want to format the next line if we do
1857 // actually reflow.
1858 // When we reflow, we need to add a space between the end of the current
1859 // line and the next line's start column.
1860 ContentStartColumn += RemainingTokenColumns + 1;
1861 // Get the split that we need to reflow next logical line into the end
1862 // of the current one; the split will include any leading whitespace of
1863 // the next logical line.
1864 BreakableToken::Split SplitBeforeNext =
1865 Token->getReflowSplit(NextLineIndex, CommentPragmasRegex);
1866 DEBUG(llvm::dbgs() << " Size of reflown text: " << ContentStartColumn
1867 << "\n Potential reflow split: ");
1868 if (SplitBeforeNext.first != StringRef::npos) {
1869 DEBUG(llvm::dbgs() << SplitBeforeNext.first << ", "
1870 << SplitBeforeNext.second << "\n");
1871 TailOffset = SplitBeforeNext.first + SplitBeforeNext.second;
1872 // If the rest of the next line fits into the current line below the
1873 // column limit, we can safely reflow.
1874 RemainingTokenColumns = Token->getRemainingLength(
1875 NextLineIndex, TailOffset, ContentStartColumn);
1876 Reflow = true;
1877 if (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {
1878 DEBUG(llvm::dbgs() << " Over limit after reflow, need: "
1879 << (ContentStartColumn + RemainingTokenColumns)
1880 << ", space: " << ColumnLimit
1881 << ", reflown prefix: " << ContentStartColumn
1882 << ", offset in line: " << TailOffset << "\n");
1883 // If the whole next line does not fit, try to find a point in
1884 // the next line at which we can break so that attaching the part
1885 // of the next line to that break point onto the current line is
1886 // below the column limit.
1887 BreakableToken::Split Split =
1888 Token->getSplit(NextLineIndex, TailOffset, ColumnLimit,
1889 ContentStartColumn, CommentPragmasRegex);
1890 if (Split.first == StringRef::npos) {
1891 DEBUG(llvm::dbgs() << " Did not find later break\n");
1892 Reflow = false;
1893 } else {
1894 // Check whether the first split point gets us below the column
1895 // limit. Note that we will execute this split below as part of
1896 // the normal token breaking and reflow logic within the line.
1897 unsigned ToSplitColumns = Token->getRangeLength(
1898 NextLineIndex, TailOffset, Split.first, ContentStartColumn);
1899 if (ContentStartColumn + ToSplitColumns > ColumnLimit) {
1900 DEBUG(llvm::dbgs() << " Next split protrudes, need: "
1901 << (ContentStartColumn + ToSplitColumns)
1902 << ", space: " << ColumnLimit);
1903 unsigned ExcessCharactersPenalty =
1904 (ContentStartColumn + ToSplitColumns - ColumnLimit) *
1905 Style.PenaltyExcessCharacter;
1906 if (NewBreakPenalty < ExcessCharactersPenalty) {
1907 Reflow = false;
1908 }
1909 }
1910 }
1911 }
1912 } else {
1913 DEBUG(llvm::dbgs() << "not found.\n");
1914 }
1915 }
1916 if (!Reflow) {
1917 // If we didn't reflow into the next line, the only space to consider is
1918 // the next logical line. Reset our state to match the start of the next
1919 // line.
1920 TailOffset = 0;
1921 ContentStartColumn =
1922 Token->getContentStartColumn(NextLineIndex, /*Break=*/false);
1923 RemainingTokenColumns = Token->getRemainingLength(
1924 NextLineIndex, TailOffset, ContentStartColumn);
1925 // Adapt the start of the token, for example indent.
1926 if (!DryRun)
1927 Token->adaptStartOfLine(NextLineIndex, Whitespaces);
1928 } else {
1929 // If we found a reflow split and have added a new break before the next
1930 // line, we are going to remove the line break at the start of the next
1931 // logical line. For example, here we'll add a new line break after
1932 // 'text', and subsequently delete the line break between 'that' and
1933 // 'reflows'.
1934 // // some text that
1935 // // reflows
1936 // ->
1937 // // some text
1938 // // that reflows
1939 // When adding the line break, we also added the penalty for it, so we
1940 // need to subtract that penalty again when we remove the line break due
1941 // to reflowing.
1942 if (NewBreakBefore) {
1943 assert(Penalty >= NewBreakPenalty);
1944 Penalty -= NewBreakPenalty;
1945 }
1946 if (!DryRun)
1947 Token->reflow(NextLineIndex, Whitespaces);
1948 }
1949 }
Daniel Jasperde0328a2013-08-16 11:20:30 +00001950 }
1951
Krasimir Georgiev3b865342017-08-09 09:42:32 +00001952 BreakableToken::Split SplitAfterLastLine =
Manuel Klimek93699f42017-11-29 14:29:43 +00001953 Token->getSplitAfterLastLine(TailOffset);
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +00001954 if (SplitAfterLastLine.first != StringRef::npos) {
Manuel Klimek77866142017-11-17 11:17:15 +00001955 DEBUG(llvm::dbgs() << "Replacing whitespace after last line.\n");
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +00001956 if (!DryRun)
1957 Token->replaceWhitespaceAfterLastLine(TailOffset, SplitAfterLastLine,
1958 Whitespaces);
Manuel Klimek93699f42017-11-29 14:29:43 +00001959 ContentStartColumn =
1960 Token->getContentStartColumn(Token->getLineCount() - 1, /*Break=*/true);
1961 RemainingTokenColumns = Token->getRemainingLength(
1962 Token->getLineCount() - 1,
1963 TailOffset + SplitAfterLastLine.first + SplitAfterLastLine.second,
1964 ContentStartColumn);
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +00001965 }
1966
Manuel Klimek93699f42017-11-29 14:29:43 +00001967 State.Column = ContentStartColumn + RemainingTokenColumns -
1968 Current.UnbreakableTailLength;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001969
1970 if (BreakInserted) {
1971 // If we break the token inside a parameter list, we need to break before
1972 // the next parameter on all levels, so that the next parameter is clearly
1973 // visible. Line comments already introduce a break.
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001974 if (Current.isNot(TT_LineComment)) {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001975 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1976 State.Stack[i].BreakBeforeParameter = true;
1977 }
1978
Krasimir Georgiev35599fd2017-10-16 09:08:53 +00001979 if (Current.is(TT_BlockComment))
1980 State.NoContinuation = true;
1981
Daniel Jasperde0328a2013-08-16 11:20:30 +00001982 State.Stack.back().LastSpace = StartColumn;
1983 }
Krasimir Georgiev91834222017-01-25 13:58:58 +00001984
1985 Token->updateNextToken(State);
1986
Manuel Klimek0b58c322017-12-01 13:28:08 +00001987 return {Penalty, Exceeded};
Daniel Jasperde0328a2013-08-16 11:20:30 +00001988}
1989
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001990unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001991 // In preprocessor directives reserve two chars for trailing " \"
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001992 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
Daniel Jasperde0328a2013-08-16 11:20:30 +00001993}
1994
Daniel Jasperc39b56f2013-12-16 07:23:08 +00001995bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
Daniel Jasperf438cb72013-08-23 11:57:34 +00001996 const FormatToken &Current = *State.NextToken;
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001997 if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral))
Daniel Jasperf438cb72013-08-23 11:57:34 +00001998 return false;
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00001999 // We never consider raw string literals "multiline" for the purpose of
Daniel Jasperc39b56f2013-12-16 07:23:08 +00002000 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
2001 // (see TokenAnnotator::mustBreakBefore().
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00002002 if (Current.TokenText.startswith("R\""))
2003 return false;
Alexander Kornienko39856b72013-09-10 09:38:25 +00002004 if (Current.IsMultiline)
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00002005 return true;
Daniel Jasperf438cb72013-08-23 11:57:34 +00002006 if (Current.getNextNonComment() &&
Daniel Jasper04b6a082013-12-20 06:22:01 +00002007 Current.getNextNonComment()->isStringLiteral())
Daniel Jasperf438cb72013-08-23 11:57:34 +00002008 return true; // Implicit concatenation.
Krasimir Georgiev374e6de2018-02-08 10:47:12 +00002009 if (Style.ColumnLimit != 0 && Style.BreakStringLiterals &&
Daniel Jasper6fd5d642015-01-20 12:59:20 +00002010 State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
2011 Style.ColumnLimit)
Daniel Jasperf438cb72013-08-23 11:57:34 +00002012 return true; // String will be split.
Alexander Kornienkod7b837e2013-08-29 17:32:57 +00002013 return false;
Daniel Jasperf438cb72013-08-23 11:57:34 +00002014}
2015
Daniel Jasperde0328a2013-08-16 11:20:30 +00002016} // namespace format
2017} // namespace clang