blob: 6472a1f10d0d00b525b3a5826a537202e3e3bd93 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.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 functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
Daniel Jasperf7935112012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimek24998102013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000018#include "BreakableToken.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000019#include "TokenAnnotator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000021#include "WhitespaceManager.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000022#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000023#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000024#include "clang/Format/Format.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000026#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000027#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Alexander Kornienkod6538332013-05-07 15:32:14 +000029#include "llvm/Support/YAMLTraits.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000030#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000031#include <string>
32
Alexander Kornienkod6538332013-05-07 15:32:14 +000033namespace llvm {
34namespace yaml {
35template <>
36struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +000037 static void enumeration(IO &IO,
38 clang::format::FormatStyle::LanguageStandard &Value) {
39 IO.enumCase(Value, "C++03", clang::format::FormatStyle::LS_Cpp03);
40 IO.enumCase(Value, "C++11", clang::format::FormatStyle::LS_Cpp11);
41 IO.enumCase(Value, "Auto", clang::format::FormatStyle::LS_Auto);
42 }
43};
44
Daniel Jasper12f9d8e2013-05-14 09:30:02 +000045template <>
Manuel Klimeka8eb9142013-05-13 12:51:40 +000046struct ScalarEnumerationTraits<clang::format::FormatStyle::BraceBreakingStyle> {
47 static void
48 enumeration(IO &IO, clang::format::FormatStyle::BraceBreakingStyle &Value) {
49 IO.enumCase(Value, "Attach", clang::format::FormatStyle::BS_Attach);
50 IO.enumCase(Value, "Linux", clang::format::FormatStyle::BS_Linux);
51 IO.enumCase(Value, "Stroustrup", clang::format::FormatStyle::BS_Stroustrup);
Alexander Kornienkod6538332013-05-07 15:32:14 +000052 }
53};
54
55template <> struct MappingTraits<clang::format::FormatStyle> {
56 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
Alexander Kornienko49149672013-05-10 11:56:10 +000057 if (IO.outputting()) {
58 StringRef StylesArray[] = { "LLVM", "Google", "Chromium", "Mozilla" };
59 ArrayRef<StringRef> Styles(StylesArray);
60 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
61 StringRef StyleName(Styles[i]);
62 if (Style == clang::format::getPredefinedStyle(StyleName)) {
63 IO.mapOptional("# BasedOnStyle", StyleName);
64 break;
65 }
66 }
67 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +000068 StringRef BasedOnStyle;
69 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +000070 if (!BasedOnStyle.empty())
71 Style = clang::format::getPredefinedStyle(BasedOnStyle);
72 }
73
74 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
75 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
76 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
77 Style.AllowAllParametersOfDeclarationOnNextLine);
78 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
79 Style.AllowShortIfStatementsOnASingleLine);
80 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
81 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
82 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
83 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
84 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
85 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
86 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
87 IO.mapOptional("ObjCSpaceBeforeProtocolList",
88 Style.ObjCSpaceBeforeProtocolList);
89 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
90 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
91 Style.PenaltyReturnTypeOnItsOwnLine);
92 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
93 IO.mapOptional("SpacesBeforeTrailingComments",
94 Style.SpacesBeforeTrailingComments);
95 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +000096 IO.mapOptional("IndentWidth", Style.IndentWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +000097 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +000098 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Alexander Kornienkod6538332013-05-07 15:32:14 +000099 }
100};
101}
102}
103
Daniel Jasperf7935112012-12-03 18:12:45 +0000104namespace clang {
105namespace format {
106
Daniel Jasperf7935112012-12-03 18:12:45 +0000107FormatStyle getLLVMStyle() {
108 FormatStyle LLVMStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000109 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000110 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000111 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000112 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000113 LLVMStyle.BinPackParameters = true;
114 LLVMStyle.ColumnLimit = 80;
115 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
116 LLVMStyle.DerivePointerBinding = false;
117 LLVMStyle.IndentCaseLabels = false;
118 LLVMStyle.MaxEmptyLinesToKeep = 1;
Nico Webera6087752013-01-10 20:12:55 +0000119 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000120 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper6728fc12013-04-11 14:29:13 +0000121 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 75;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000122 LLVMStyle.PointerBindsToType = false;
123 LLVMStyle.SpacesBeforeTrailingComments = 1;
124 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Manuel Klimek13b97d82013-05-13 08:42:42 +0000125 LLVMStyle.IndentWidth = 2;
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000126 LLVMStyle.UseTab = false;
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000127 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasperf7935112012-12-03 18:12:45 +0000128 return LLVMStyle;
129}
130
131FormatStyle getGoogleStyle() {
132 FormatStyle GoogleStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000133 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000134 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000135 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000136 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000137 GoogleStyle.BinPackParameters = true;
138 GoogleStyle.ColumnLimit = 80;
139 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
140 GoogleStyle.DerivePointerBinding = true;
141 GoogleStyle.IndentCaseLabels = true;
142 GoogleStyle.MaxEmptyLinesToKeep = 1;
Nico Webera6087752013-01-10 20:12:55 +0000143 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000144 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper6728fc12013-04-11 14:29:13 +0000145 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000146 GoogleStyle.PointerBindsToType = true;
147 GoogleStyle.SpacesBeforeTrailingComments = 2;
148 GoogleStyle.Standard = FormatStyle::LS_Auto;
Manuel Klimek13b97d82013-05-13 08:42:42 +0000149 GoogleStyle.IndentWidth = 2;
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000150 GoogleStyle.UseTab = false;
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000151 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasperf7935112012-12-03 18:12:45 +0000152 return GoogleStyle;
153}
154
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000155FormatStyle getChromiumStyle() {
156 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +0000157 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000158 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000159 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000160 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
161 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000162 return ChromiumStyle;
163}
164
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000165FormatStyle getMozillaStyle() {
166 FormatStyle MozillaStyle = getLLVMStyle();
167 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
168 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
169 MozillaStyle.DerivePointerBinding = true;
170 MozillaStyle.IndentCaseLabels = true;
171 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
172 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
173 MozillaStyle.PointerBindsToType = true;
174 return MozillaStyle;
175}
176
Alexander Kornienkod6538332013-05-07 15:32:14 +0000177FormatStyle getPredefinedStyle(StringRef Name) {
178 if (Name.equals_lower("llvm"))
179 return getLLVMStyle();
180 if (Name.equals_lower("chromium"))
181 return getChromiumStyle();
182 if (Name.equals_lower("mozilla"))
183 return getMozillaStyle();
184 if (Name.equals_lower("google"))
185 return getGoogleStyle();
186
187 llvm::errs() << "Unknown style " << Name << ", using Google style.\n";
188 return getGoogleStyle();
189}
190
191llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
192 llvm::yaml::Input Input(Text);
193 Input >> *Style;
194 return Input.error();
195}
196
197std::string configurationAsText(const FormatStyle &Style) {
198 std::string Text;
199 llvm::raw_string_ostream Stream(Text);
200 llvm::yaml::Output Output(Stream);
201 // We use the same mapping method for input and output, so we need a non-const
202 // reference here.
203 FormatStyle NonConstStyle = Style;
204 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000205 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000206}
207
Daniel Jasperacc33662013-02-08 08:22:00 +0000208// Returns the length of everything up to the first possible line break after
209// the ), ], } or > matching \c Tok.
210static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
211 if (Tok.MatchingParen == NULL)
212 return 0;
213 AnnotatedToken *End = Tok.MatchingParen;
214 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
215 End = &End->Children[0];
216 }
217 return End->TotalLength - Tok.TotalLength + 1;
218}
219
Daniel Jasperf7935112012-12-03 18:12:45 +0000220class UnwrappedLineFormatter {
221public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000222 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000223 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000224 const AnnotatedToken &RootToken,
Manuel Klimek1a18c402013-04-12 14:13:36 +0000225 WhitespaceManager &Whitespaces)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000226 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000227 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000228 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000229
Manuel Klimek1abf7892013-01-04 23:34:14 +0000230 /// \brief Formats an \c UnwrappedLine.
231 ///
232 /// \returns The column after the last token in the last line of the
233 /// \c UnwrappedLine.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000234 unsigned format(const AnnotatedLine *NextLine) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000235 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000236 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000237 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000238 State.NextToken = &RootToken;
Daniel Jasper97b89482013-03-13 07:49:51 +0000239 State.Stack.push_back(
Daniel Jasperc238c872013-04-02 14:33:13 +0000240 ParenState(FirstIndent, FirstIndent, !Style.BinPackParameters,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000241 /*NoLineBreak=*/ false));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000242 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000243 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000244 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000245 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000246
247 // The first token has already been indented and thus consumed.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000248 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000249
Daniel Jasper4b866272013-02-01 11:00:45 +0000250 // If everything fits on a single line, just put it there.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000251 unsigned ColumnLimit = Style.ColumnLimit;
252 if (NextLine && NextLine->InPPDirective &&
253 !NextLine->First.FormatTok.HasUnescapedNewline)
254 ColumnLimit = getColumnLimit();
255 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000256 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000257 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000258 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000259 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000260 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000261
Daniel Jasperacc33662013-02-08 08:22:00 +0000262 // If the ObjC method declaration does not fit on a line, we should format
263 // it with one arg per line.
264 if (Line.Type == LT_ObjCMethodDecl)
265 State.Stack.back().BreakBeforeParameter = true;
266
Daniel Jasper4b866272013-02-01 11:00:45 +0000267 // Find best solution in solution space.
268 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000269 }
270
271private:
Manuel Klimek24998102013-01-16 14:55:28 +0000272 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
273 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Alexander Kornienko49149672013-05-10 11:56:10 +0000274 llvm::dbgs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000275 Tok.getLength());
Alexander Kornienko49149672013-05-10 11:56:10 +0000276 llvm::dbgs();
Manuel Klimek24998102013-01-16 14:55:28 +0000277 }
278
Daniel Jasper337816e2013-01-11 10:22:12 +0000279 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000280 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000281 bool NoLineBreak)
Daniel Jasper400adc62013-02-08 15:28:42 +0000282 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
283 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000284 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000285 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
286 NestedNameSpecifierContinuation(0), CallContinuation(0),
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000287 VariablePos(0), ForFakeParenthesis(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000288
Daniel Jasperf7935112012-12-03 18:12:45 +0000289 /// \brief The position to which a specific parenthesis level needs to be
290 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000291 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000292
Daniel Jaspere9de2602012-12-06 09:56:08 +0000293 /// \brief The position of the last space on each level.
294 ///
295 /// Used e.g. to break like:
296 /// functionCall(Parameter, otherCall(
297 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000298 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000299
Daniel Jaspere9de2602012-12-06 09:56:08 +0000300 /// \brief The position the first "<<" operator encountered on each level.
301 ///
302 /// Used to align "<<" operators. 0 if no such operator has been encountered
303 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000304 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000305
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000306 /// \brief Whether a newline needs to be inserted before the block's closing
307 /// brace.
308 ///
309 /// We only want to insert a newline before the closing brace if there also
310 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000311 bool BreakBeforeClosingBrace;
312
Daniel Jasperca6623b2013-01-28 12:45:14 +0000313 /// \brief The column of a \c ? in a conditional expression;
314 unsigned QuestionColumn;
315
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000316 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
317 /// lines, in this context.
318 bool AvoidBinPacking;
319
320 /// \brief Break after the next comma (or all the commas in this context if
321 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000322 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000323
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000324 /// \brief Line breaking in this context would break a formatting rule.
325 bool NoLineBreak;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000326
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000327 /// \brief The position of the colon in an ObjC method declaration/call.
328 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000329
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000330 /// \brief The start of the most recent function in a builder-type call.
331 unsigned StartOfFunctionCall;
332
Daniel Jasperc238c872013-04-02 14:33:13 +0000333 /// \brief If a nested name specifier was broken over multiple lines, this
334 /// contains the start column of the second line. Otherwise 0.
335 unsigned NestedNameSpecifierContinuation;
336
337 /// \brief If a call expression was broken over multiple lines, this
338 /// contains the start column of the second line. Otherwise 0.
339 unsigned CallContinuation;
340
Daniel Jaspera628c982013-04-03 13:36:17 +0000341 /// \brief The column of the first variable name in a variable declaration.
342 ///
343 /// Used to align further variables if necessary.
344 unsigned VariablePos;
345
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000346 /// \brief \c true if this \c ParenState was created for a fake parenthesis.
347 ///
348 /// Does not need to be considered for memoization / the comparison function
349 /// as otherwise identical states will have the same fake/non-fake
350 /// \c ParenStates.
351 bool ForFakeParenthesis;
352
Daniel Jasper337816e2013-01-11 10:22:12 +0000353 bool operator<(const ParenState &Other) const {
354 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000355 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000356 if (LastSpace != Other.LastSpace)
357 return LastSpace < Other.LastSpace;
358 if (FirstLessLess != Other.FirstLessLess)
359 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000360 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
361 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000362 if (QuestionColumn != Other.QuestionColumn)
363 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000364 if (AvoidBinPacking != Other.AvoidBinPacking)
365 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000366 if (BreakBeforeParameter != Other.BreakBeforeParameter)
367 return BreakBeforeParameter;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000368 if (NoLineBreak != Other.NoLineBreak)
369 return NoLineBreak;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000370 if (ColonPos != Other.ColonPos)
371 return ColonPos < Other.ColonPos;
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000372 if (StartOfFunctionCall != Other.StartOfFunctionCall)
373 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasperc238c872013-04-02 14:33:13 +0000374 if (CallContinuation != Other.CallContinuation)
375 return CallContinuation < Other.CallContinuation;
Daniel Jaspera628c982013-04-03 13:36:17 +0000376 if (VariablePos != Other.VariablePos)
377 return VariablePos < Other.VariablePos;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000378 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000379 }
380 };
381
382 /// \brief The current state when indenting a unwrapped line.
383 ///
384 /// As the indenting tries different combinations this is copied by value.
385 struct LineState {
386 /// \brief The number of used columns in the current line.
387 unsigned Column;
388
389 /// \brief The token that needs to be next formatted.
390 const AnnotatedToken *NextToken;
391
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000392 /// \brief \c true if this line contains a continued for-loop section.
393 bool LineContainsContinuedForLoopSection;
394
Daniel Jasper400adc62013-02-08 15:28:42 +0000395 /// \brief The level of nesting inside (), [], <> and {}.
396 unsigned ParenLevel;
397
Daniel Jasper40c36c52013-02-18 11:05:07 +0000398 /// \brief The \c ParenLevel at the start of this line.
399 unsigned StartOfLineLevel;
400
Manuel Klimek02f640a2013-02-20 15:25:48 +0000401 /// \brief The start column of the string literal, if we're in a string
402 /// literal sequence, 0 otherwise.
403 unsigned StartOfStringLiteral;
404
Daniel Jasper337816e2013-01-11 10:22:12 +0000405 /// \brief A stack keeping track of properties applying to parenthesis
406 /// levels.
407 std::vector<ParenState> Stack;
408
409 /// \brief Comparison operator to be able to used \c LineState in \c map.
410 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000411 if (NextToken != Other.NextToken)
412 return NextToken < Other.NextToken;
413 if (Column != Other.Column)
414 return Column < Other.Column;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000415 if (LineContainsContinuedForLoopSection !=
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000416 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000417 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000418 if (ParenLevel != Other.ParenLevel)
419 return ParenLevel < Other.ParenLevel;
420 if (StartOfLineLevel != Other.StartOfLineLevel)
421 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000422 if (StartOfStringLiteral != Other.StartOfStringLiteral)
423 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000424 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000425 }
426 };
427
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000428 /// \brief Appends the next token to \p State and updates information
429 /// necessary for indentation.
430 ///
431 /// Puts the token on the current line if \p Newline is \c true and adds a
432 /// line break and necessary indentation otherwise.
433 ///
434 /// If \p DryRun is \c false, also creates and stores the required
435 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000436 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000437 const AnnotatedToken &Current = *State.NextToken;
438 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000439
Daniel Jasper291f9362013-03-20 15:58:10 +0000440 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000441 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
442 State.NextToken->FormatTok.TokenLength;
443 if (State.NextToken->Children.empty())
444 State.NextToken = NULL;
445 else
446 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek1998ea22013-02-20 10:15:13 +0000447 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000448 }
449
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000450 // If we are continuing an expression, we want to indent an extra 4 spaces.
451 unsigned ContinuationIndent =
Daniel Jasperc238c872013-04-02 14:33:13 +0000452 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperf7935112012-12-03 18:12:45 +0000453 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000454 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000455 if (Current.is(tok::r_brace)) {
Manuel Klimek13b97d82013-05-13 08:42:42 +0000456 State.Column = Line.Level * Style.IndentWidth;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000457 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000458 State.StartOfStringLiteral != 0) {
459 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000460 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000461 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000462 State.Stack.back().FirstLessLess != 0) {
463 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasperc238c872013-04-02 14:33:13 +0000464 } else if (Current.isOneOf(tok::period, tok::arrow)) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000465 if (State.Stack.back().CallContinuation == 0) {
466 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000467 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000468 } else {
469 State.Column = State.Stack.back().CallContinuation;
470 }
Daniel Jasperca6623b2013-01-28 12:45:14 +0000471 } else if (Current.Type == TT_ConditionalExpr) {
472 State.Column = State.Stack.back().QuestionColumn;
Daniel Jaspera628c982013-04-03 13:36:17 +0000473 } else if (Previous.is(tok::comma) &&
474 State.Stack.back().VariablePos != 0) {
475 State.Column = State.Stack.back().VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000476 } else if (Previous.ClosesTemplateDeclaration ||
Daniel Jasper8e357692013-05-06 08:27:33 +0000477 (Current.Type == TT_StartOfName && State.ParenLevel == 0 &&
478 Line.StartsDefinition)) {
Daniel Jasperc238c872013-04-02 14:33:13 +0000479 State.Column = State.Stack.back().Indent;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000480 } else if (Current.Type == TT_ObjCSelectorName) {
481 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
482 State.Column =
483 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
484 } else {
485 State.Column = State.Stack.back().Indent;
486 State.Stack.back().ColonPos =
487 State.Column + Current.FormatTok.TokenLength;
488 }
Daniel Jasper0f0234e2013-05-08 10:00:18 +0000489 } else if (Current.Type == TT_StartOfName ||
490 Previous.isOneOf(tok::coloncolon, tok::equal) ||
Daniel Jasperc238c872013-04-02 14:33:13 +0000491 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000492 State.Column = ContinuationIndent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000493 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000494 State.Column = State.Stack.back().Indent;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000495 // Ensure that we fall back to indenting 4 spaces instead of just
496 // flushing continuations left.
Daniel Jasperc238c872013-04-02 14:33:13 +0000497 if (State.Column == FirstIndent)
498 State.Column += 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000499 }
500
Daniel Jasper54a86022013-02-15 11:07:25 +0000501 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000502 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000503 if ((Previous.isOneOf(tok::comma, tok::semi) &&
504 !State.Stack.back().AvoidBinPacking) ||
505 Previous.Type == TT_BinaryOperator)
Daniel Jasperacc33662013-02-08 08:22:00 +0000506 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000507
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000508 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000509 unsigned NewLines = 1;
510 if (Current.Type == TT_LineComment)
511 NewLines =
512 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
513 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000514 if (!Line.InPPDirective)
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000515 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000516 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000517 else
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000518 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000519 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000520 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000521
Daniel Jasper400adc62013-02-08 15:28:42 +0000522 State.Stack.back().LastSpace = State.Column;
Daniel Jasper66e4f832013-05-10 13:37:16 +0000523 if (Current.isOneOf(tok::arrow, tok::period))
524 State.Stack.back().LastSpace += Current.FormatTok.TokenLength;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000525 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000526
527 // Any break on this level means that the parent level has been broken
528 // and we need to avoid bin packing there.
529 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
530 State.Stack[i].BreakBeforeParameter = true;
531 }
Daniel Jasper1b8e76f2013-04-15 22:36:37 +0000532 const AnnotatedToken *TokenBefore = Current.getPreviousNoneComment();
533 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
Daniel Jasperd69fc772013-05-08 14:12:04 +0000534 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000535 State.Stack.back().BreakBeforeParameter = true;
536
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000537 // If we break after {, we should also break before the corresponding }.
538 if (Previous.is(tok::l_brace))
539 State.Stack.back().BreakBeforeClosingBrace = true;
540
541 if (State.Stack.back().AvoidBinPacking) {
542 // If we are breaking after '(', '{', '<', this is not bin packing
543 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper571f1af2013-05-14 20:39:56 +0000544 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
545 Previous.Type == TT_BinaryOperator) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000546 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
547 Line.MustBeDeclaration))
548 State.Stack.back().BreakBeforeParameter = true;
549 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000550 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000551 if (Current.is(tok::equal) &&
Daniel Jasper31c96b92013-04-05 09:38:50 +0000552 (RootToken.is(tok::kw_for) || State.ParenLevel == 0) &&
553 State.Stack.back().VariablePos == 0) {
554 State.Stack.back().VariablePos = State.Column;
555 // Move over * and & if they are bound to the variable name.
556 const AnnotatedToken *Tok = &Previous;
557 while (Tok &&
558 State.Stack.back().VariablePos >= Tok->FormatTok.TokenLength) {
559 State.Stack.back().VariablePos -= Tok->FormatTok.TokenLength;
560 if (Tok->SpacesRequiredBefore != 0)
561 break;
562 Tok = Tok->Parent;
563 }
Daniel Jaspera628c982013-04-03 13:36:17 +0000564 if (Previous.PartOfMultiVariableDeclStmt)
565 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
566 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000567
Daniel Jaspereef30492013-02-11 12:36:37 +0000568 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000569
Daniel Jasperf7935112012-12-03 18:12:45 +0000570 if (!DryRun)
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000571 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000572
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000573 if (Current.Type == TT_ObjCSelectorName &&
574 State.Stack.back().ColonPos == 0) {
575 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000576 State.Column + Spaces + Current.FormatTok.TokenLength)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000577 State.Stack.back().ColonPos =
578 State.Stack.back().Indent + Current.LongestObjCSelectorName;
579 else
580 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000581 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000582 }
583
Daniel Jasperc04baae2013-04-10 09:49:49 +0000584 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper6bee6822013-04-08 20:33:42 +0000585 Current.Type != TT_LineComment)
Daniel Jasper400adc62013-02-08 15:28:42 +0000586 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000587 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
588 State.Stack.back().AvoidBinPacking)
589 State.Stack.back().NoLineBreak = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000590
Daniel Jaspere9de2602012-12-06 09:56:08 +0000591 State.Column += Spaces;
Daniel Jaspera628c982013-04-03 13:36:17 +0000592 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jasper39e27382013-01-23 20:41:06 +0000593 // Treat the condition inside an if as if it was a second function
594 // parameter, i.e. let nested calls have an indent of 4.
595 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000596 else if (Previous.is(tok::comma))
Daniel Jasper39e27382013-01-23 20:41:06 +0000597 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000598 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000599 Previous.Type == TT_ConditionalExpr ||
600 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000601 getPrecedence(Previous) != prec::Assignment)
602 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000603 else if (Previous.Type == TT_InheritanceColon)
604 State.Stack.back().Indent = State.Column;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000605 else if (Previous.opensScope() && !Current.FakeLParens.empty())
606 // If this function has multiple parameters or a binary expression
607 // parameter, indent nested calls from the start of the first parameter.
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000608 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000609 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000610
Manuel Klimek1998ea22013-02-20 10:15:13 +0000611 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000612 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000613
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000614 /// \brief Mark the next token as consumed in \p State and modify its stacks
615 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000616 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000617 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000618 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000619
Daniel Jaspereead02b2013-02-14 08:42:54 +0000620 if (Current.Type == TT_InheritanceColon)
621 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000622 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
623 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000624 if (Current.is(tok::question))
625 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000626 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000627 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
628 State.Stack.back().StartOfFunctionCall =
Daniel Jasper66e4f832013-05-10 13:37:16 +0000629 Current.LastInChainOfCalls ? 0 : State.Column +
630 Current.FormatTok.TokenLength;
Daniel Jasper37905f72013-02-21 15:00:29 +0000631 if (Current.Type == TT_CtorInitializerColon) {
Manuel Klimek13b97d82013-05-13 08:42:42 +0000632 // Indent 2 from the column, so:
633 // SomeClass::SomeClass()
634 // : First(...), ...
635 // Next(...)
636 // ^ line up here.
Daniel Jasper6bee6822013-04-08 20:33:42 +0000637 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper37905f72013-02-21 15:00:29 +0000638 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
639 State.Stack.back().AvoidBinPacking = true;
640 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000641 }
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000642
Daniel Jasper6bee6822013-04-08 20:33:42 +0000643 // If return returns a binary expression, align after it.
644 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
645 State.Stack.back().LastSpace = State.Column + 7;
646
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000647 // In ObjC method declaration we align on the ":" of parameters, but we need
648 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasperc238c872013-04-02 14:33:13 +0000649 if (Current.Type == TT_ObjCMethodSpecifier)
650 State.Stack.back().Indent += 4;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000651
Daniel Jasper400adc62013-02-08 15:28:42 +0000652 // Insert scopes created by fake parenthesis.
Daniel Jasper6bee6822013-04-08 20:33:42 +0000653 const AnnotatedToken *Previous = Current.getPreviousNoneComment();
654 // Don't add extra indentation for the first fake parenthesis after
655 // 'return', assignements or opening <({[. The indentation for these cases
656 // is special cased.
657 bool SkipFirstExtraIndent =
658 Current.is(tok::kw_return) ||
Daniel Jasperc04baae2013-04-10 09:49:49 +0000659 (Previous && (Previous->opensScope() ||
Daniel Jasper6bee6822013-04-08 20:33:42 +0000660 getPrecedence(*Previous) == prec::Assignment));
661 for (SmallVector<prec::Level, 4>::const_reverse_iterator
662 I = Current.FakeLParens.rbegin(),
663 E = Current.FakeLParens.rend();
664 I != E; ++I) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000665 ParenState NewParenState = State.Stack.back();
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000666 NewParenState.ForFakeParenthesis = true;
Daniel Jasper6bee6822013-04-08 20:33:42 +0000667 NewParenState.Indent =
668 std::max(std::max(State.Column, NewParenState.Indent),
669 State.Stack.back().LastSpace);
670
671 // Always indent conditional expressions. Never indent expression where
672 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
673 // prec::Assignment) as those have different indentation rules. Indent
674 // other expression, unless the indentation needs to be skipped.
675 if (*I == prec::Conditional ||
676 (!SkipFirstExtraIndent && *I > prec::Assignment))
677 NewParenState.Indent += 4;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000678 if (Previous && !Previous->opensScope())
Daniel Jasper6bee6822013-04-08 20:33:42 +0000679 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000680 State.Stack.push_back(NewParenState);
Daniel Jasper6bee6822013-04-08 20:33:42 +0000681 SkipFirstExtraIndent = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000682 }
683
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000684 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000685 // prepare for the following tokens.
Daniel Jasperc04baae2013-04-10 09:49:49 +0000686 if (Current.opensScope()) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000687 unsigned NewIndent;
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000688 unsigned LastSpace = State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000689 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000690 if (Current.is(tok::l_brace)) {
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000691 NewIndent = Style.IndentWidth + LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000692 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000693 } else {
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000694 NewIndent =
695 4 + std::max(LastSpace, State.Stack.back().StartOfFunctionCall);
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000696 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000697 }
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000698
699 if (Current.NoMoreTokensOnLevel && Current.FakeLParens.empty()) {
700 // This parenthesis was the last token possibly making use of Indent and
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000701 // LastSpace of the next higher ParenLevel. Thus, erase them to achieve
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000702 // better memoization results.
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000703 for (unsigned i = State.Stack.size() - 1; i > 0; --i) {
704 State.Stack[i].Indent = 0;
705 State.Stack[i].LastSpace = 0;
706 if (!State.Stack[i].ForFakeParenthesis)
707 break;
708 }
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000709 }
710
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000711 State.Stack.push_back(ParenState(NewIndent, LastSpace, AvoidBinPacking,
712 State.Stack.back().NoLineBreak));
Daniel Jasper400adc62013-02-08 15:28:42 +0000713 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000714 }
715
Daniel Jasperacc33662013-02-08 08:22:00 +0000716 // If this '[' opens an ObjC call, determine whether all parameters fit into
717 // one line and put one per line if they don't.
718 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
719 Current.MatchingParen != NULL) {
720 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
721 State.Stack.back().BreakBeforeParameter = true;
722 }
723
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000724 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000725 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000726 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000727 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
728 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000729 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000730 --State.ParenLevel;
731 }
732
733 // Remove scopes created by fake parenthesis.
734 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasper6daabe32013-04-04 19:31:00 +0000735 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper400adc62013-02-08 15:28:42 +0000736 State.Stack.pop_back();
Daniel Jasper6daabe32013-04-04 19:31:00 +0000737 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000738 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000739
Daniel Jasper47a04442013-05-13 20:50:15 +0000740 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000741 State.StartOfStringLiteral = State.Column;
Daniel Jasper47a04442013-05-13 20:50:15 +0000742 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
743 tok::string_literal)) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000744 }
745
Manuel Klimek1998ea22013-02-20 10:15:13 +0000746 State.Column += Current.FormatTok.TokenLength;
747
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000748 if (State.NextToken->Children.empty())
749 State.NextToken = NULL;
750 else
751 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000752
Manuel Klimek1998ea22013-02-20 10:15:13 +0000753 return breakProtrudingToken(Current, State, DryRun);
754 }
755
756 /// \brief If the current token sticks out over the end of the line, break
757 /// it if possible.
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000758 ///
759 /// \returns An extra penalty if a token was broken, otherwise 0.
760 ///
761 /// Note that the penalty of the token protruding the allowed line length is
762 /// already handled in \c addNextStateToQueue; the returned penalty will only
763 /// cover the cost of the additional line breaks.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000764 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000765 bool DryRun,
766 unsigned UnbreakableTailLength = 0) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000767 llvm::OwningPtr<BreakableToken> Token;
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000768 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength -
769 UnbreakableTailLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000770 if (Current.is(tok::string_literal)) {
771 // Only break up default narrow strings.
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000772 const char *LiteralData = SourceMgr.getCharacterData(
773 Current.FormatTok.getStartOfNonWhitespace());
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000774 if (!LiteralData || *LiteralData != '"')
775 return 0;
776
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000777 Token.reset(new BreakableStringLiteral(SourceMgr, Current.FormatTok,
778 StartColumn));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000779 } else if (Current.Type == TT_BlockComment) {
780 BreakableBlockComment *BBC =
781 new BreakableBlockComment(SourceMgr, Current, StartColumn);
782 if (!DryRun)
783 BBC->alignLines(Whitespaces);
784 Token.reset(BBC);
Daniel Jasper4a4be012013-05-06 10:24:51 +0000785 } else if (Current.Type == TT_LineComment &&
786 (Current.Parent == NULL ||
787 Current.Parent->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000788 Token.reset(new BreakableLineComment(SourceMgr, Current, StartColumn));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000789 } else {
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000790 // If a token that we cannot breaks protrudes, it means we were unable to
791 // break a sequence of tokens due to disallowed breaks between the tokens.
792 // Thus, we recursively search backwards to try to find a breakable token.
793 if (State.Column <= getColumnLimit() ||
794 Current.CanBreakBefore || !Current.Parent)
795 return 0;
796 return breakProtrudingToken(
797 *Current.Parent, State, DryRun,
798 UnbreakableTailLength + Current.FormatTok.TokenLength);
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000799 }
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000800 if (UnbreakableTailLength >= getColumnLimit())
801 return 0;
802 unsigned RemainingSpace = getColumnLimit() - UnbreakableTailLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000803
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000804 bool BreakInserted = false;
805 unsigned Penalty = 0;
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000806 unsigned PositionAfterLastLineInToken = 0;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000807 for (unsigned LineIndex = 0; LineIndex < Token->getLineCount();
808 ++LineIndex) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000809 unsigned TailOffset = 0;
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000810 unsigned RemainingTokenLength =
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000811 Token->getLineLengthAfterSplit(LineIndex, TailOffset);
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000812 while (RemainingTokenLength > RemainingSpace) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000813 BreakableToken::Split Split =
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000814 Token->getSplit(LineIndex, TailOffset, RemainingSpace);
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000815 if (Split.first == StringRef::npos)
816 break;
817 assert(Split.first != 0);
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000818 unsigned NewRemainingTokenLength = Token->getLineLengthAfterSplit(
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000819 LineIndex, TailOffset + Split.first + Split.second);
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000820 if (NewRemainingTokenLength >= RemainingTokenLength)
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000821 break;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000822 if (!DryRun) {
823 Token->insertBreak(LineIndex, TailOffset, Split, Line.InPPDirective,
824 Whitespaces);
825 }
826 TailOffset += Split.first + Split.second;
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000827 RemainingTokenLength = NewRemainingTokenLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000828 Penalty += Style.PenaltyExcessCharacter;
829 BreakInserted = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000830 }
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000831 PositionAfterLastLineInToken = RemainingTokenLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000832 if (!DryRun) {
833 Token->trimLine(LineIndex, TailOffset, Line.InPPDirective, Whitespaces);
834 }
835 }
836
837 if (BreakInserted) {
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000838 State.Column = PositionAfterLastLineInToken + UnbreakableTailLength;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000839 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
840 State.Stack[i].BreakBeforeParameter = true;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000841 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000842 }
Manuel Klimek1998ea22013-02-20 10:15:13 +0000843 return Penalty;
844 }
845
Daniel Jasper2df93312013-01-09 10:16:05 +0000846 unsigned getColumnLimit() {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000847 // In preprocessor directives reserve two chars for trailing " \"
848 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasper2df93312013-01-09 10:16:05 +0000849 }
850
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000851 /// \brief An edge in the solution space from \c Previous->State to \c State,
852 /// inserting a newline dependent on the \c NewLine.
853 struct StateNode {
854 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000855 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000856 LineState State;
857 bool NewLine;
858 StateNode *Previous;
859 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000860
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000861 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
862 ///
863 /// In case of equal penalties, we want to prefer states that were inserted
864 /// first. During state generation we make sure that we insert states first
865 /// that break the line as late as possible.
866 typedef std::pair<unsigned, unsigned> OrderedPenalty;
867
868 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
869 /// \c State has the given \c OrderedPenalty.
870 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
871
872 /// \brief The BFS queue type.
873 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
874 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000875
876 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000877 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000878 /// This implements a variant of Dijkstra's algorithm on the graph that spans
879 /// the solution space (\c LineStates are the nodes). The algorithm tries to
880 /// find the shortest path (the one with lowest penalty) from \p InitialState
881 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000882 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000883 std::set<LineState> Seen;
884
Daniel Jasper4b866272013-02-01 11:00:45 +0000885 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000886 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000887 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
888 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
889 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000890
891 // While not empty, take first element and follow edges.
892 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000893 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000894 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000895 if (Node->State.NextToken == NULL) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000896 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000897 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000898 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000899 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000900
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000901 if (!Seen.insert(Node->State).second)
902 // State already examined with lower penalty.
903 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000904
Manuel Klimekaf491072013-02-13 10:54:19 +0000905 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
906 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +0000907 }
908
909 if (Queue.empty())
910 // We were unable to find a solution, do nothing.
911 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000912 return 0;
913
Daniel Jasper4b866272013-02-01 11:00:45 +0000914 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000915 reconstructPath(InitialState, Queue.top().second);
Alexander Kornienko49149672013-05-10 11:56:10 +0000916 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
917 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000918
Daniel Jasper4b866272013-02-01 11:00:45 +0000919 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000920 return Queue.top().second->State.Column;
921 }
922
923 void reconstructPath(LineState &State, StateNode *Current) {
924 // FIXME: This recursive implementation limits the possible number
925 // of tokens per line if compiled into a binary with small stack space.
926 // To become more independent of stack frame limitations we would need
927 // to also change the TokenAnnotator.
928 if (Current->Previous == NULL)
929 return;
930 reconstructPath(State, Current->Previous);
931 DEBUG({
932 if (Current->NewLine) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000933 llvm::dbgs()
Daniel Jasperb9caeac2013-02-13 20:33:44 +0000934 << "Penalty for splitting before "
935 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
936 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000937 }
938 });
939 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +0000940 }
941
Manuel Klimekaf491072013-02-13 10:54:19 +0000942 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000943 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000944 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000945 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000946 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
947 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000948 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000949 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000950 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000951 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000952 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000953 Penalty += PreviousNode->State.NextToken->SplitPenalty;
954
955 StateNode *Node = new (Allocator.Allocate())
956 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000957 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000958 if (Node->State.Column > getColumnLimit()) {
959 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000960 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000961 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000962
963 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
964 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000965 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000966
Daniel Jasper4b866272013-02-01 11:00:45 +0000967 /// \brief Returns \c true, if a line break after \p State is allowed.
968 bool canBreak(const LineState &State) {
969 if (!State.NextToken->CanBreakBefore &&
970 !(State.NextToken->is(tok::r_brace) &&
971 State.Stack.back().BreakBeforeClosingBrace))
972 return false;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000973 return !State.Stack.back().NoLineBreak;
Daniel Jasper4b866272013-02-01 11:00:45 +0000974 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000975
Daniel Jasper4b866272013-02-01 11:00:45 +0000976 /// \brief Returns \c true, if a line break after \p State is mandatory.
977 bool mustBreak(const LineState &State) {
Daniel Jasperd69fc772013-05-08 14:12:04 +0000978 const AnnotatedToken &Current = *State.NextToken;
979 const AnnotatedToken &Previous = *Current.Parent;
980 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
Daniel Jasper4b866272013-02-01 11:00:45 +0000981 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000982 if (Current.is(tok::r_brace) && State.Stack.back().BreakBeforeClosingBrace)
Daniel Jasper4b866272013-02-01 11:00:45 +0000983 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000984 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
Daniel Jasper4b866272013-02-01 11:00:45 +0000985 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000986 if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) ||
987 Current.Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000988 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperd69fc772013-05-08 14:12:04 +0000989 !Current.isTrailingComment() &&
990 !Current.isOneOf(tok::r_paren, tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +0000991 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000992
993 // If we need to break somewhere inside the LHS of a binary expression, we
994 // should also break after the operator.
995 if (Previous.Type == TT_BinaryOperator &&
996 !Previous.isOneOf(tok::lessless, tok::question) &&
997 getPrecedence(Previous) != prec::Assignment &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000998 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000999 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001000
1001 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1002 // out whether it is the first parameter. Clean this up.
1003 if (Current.Type == TT_ObjCSelectorName &&
1004 Current.LongestObjCSelectorName == 0 &&
1005 State.Stack.back().BreakBeforeParameter)
Daniel Jasper4b866272013-02-01 11:00:45 +00001006 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001007 if ((Current.Type == TT_CtorInitializerColon ||
1008 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0)))
Daniel Jasper40aacf42013-03-14 13:45:21 +00001009 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001010
Daniel Jasper9b334242013-03-15 14:57:30 +00001011 // This prevents breaks like:
1012 // ...
1013 // SomeParameter, OtherParameter).DoSomething(
1014 // ...
1015 // As they hide "DoSomething" and generally bad for readability.
Daniel Jasperd69fc772013-05-08 14:12:04 +00001016 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasper9b334242013-03-15 14:57:30 +00001017 getRemainingLength(State) + State.Column > getColumnLimit() &&
1018 State.ParenLevel < State.StartOfLineLevel)
1019 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +00001020 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001021 }
1022
Daniel Jasper9b334242013-03-15 14:57:30 +00001023 // Returns the total number of columns required for the remaining tokens.
1024 unsigned getRemainingLength(const LineState &State) {
1025 if (State.NextToken && State.NextToken->Parent)
1026 return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
1027 return 0;
1028 }
1029
Daniel Jasperf7935112012-12-03 18:12:45 +00001030 FormatStyle Style;
1031 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001032 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001033 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001034 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001035 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +00001036
1037 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1038 QueueType Queue;
1039 // Increasing count of \c StateNode items we have created. This is used
1040 // to create a deterministic order independent of the container.
1041 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +00001042};
1043
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001044class LexerBasedFormatTokenSource : public FormatTokenSource {
1045public:
1046 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001047 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001048 IdentTable(Lex.getLangOpts()) {
1049 Lex.SetKeepWhitespaceMode(true);
1050 }
1051
1052 virtual FormatToken getNextToken() {
1053 if (GreaterStashed) {
1054 FormatTok.NewlinesBefore = 0;
1055 FormatTok.WhiteSpaceStart =
1056 FormatTok.Tok.getLocation().getLocWithOffset(1);
1057 FormatTok.WhiteSpaceLength = 0;
1058 GreaterStashed = false;
1059 return FormatTok;
1060 }
1061
1062 FormatTok = FormatToken();
1063 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001064 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001065 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001066 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1067 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001068
1069 // Consume and record whitespace until we find a significant token.
1070 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +00001071 unsigned Newlines = Text.count('\n');
Daniel Jasper973c9422013-03-04 13:43:19 +00001072 if (Newlines > 0)
1073 FormatTok.LastNewlineOffset =
1074 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
Manuel Klimek0c137952013-02-11 12:33:24 +00001075 unsigned EscapedNewlines = Text.count("\\\n");
1076 FormatTok.NewlinesBefore += Newlines;
1077 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001078 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1079
1080 if (FormatTok.Tok.is(tok::eof))
1081 return FormatTok;
1082 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001083 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001084 }
Manuel Klimekef920692013-01-07 07:56:50 +00001085
1086 // Now FormatTok is the next non-whitespace token.
1087 FormatTok.TokenLength = Text.size();
1088
Alexander Kornienko9e90b622013-04-17 17:34:05 +00001089 if (FormatTok.Tok.is(tok::comment)) {
1090 FormatTok.TrailingWhiteSpaceLength = Text.size() - Text.rtrim().size();
1091 FormatTok.TokenLength -= FormatTok.TrailingWhiteSpaceLength;
1092 }
1093
Manuel Klimek1abf7892013-01-04 23:34:14 +00001094 // In case the token starts with escaped newlines, we want to
1095 // take them into account as whitespace - this pattern is quite frequent
1096 // in macro definitions.
1097 // FIXME: What do we want to do with other escaped spaces, and escaped
1098 // spaces or newlines in the middle of tokens?
1099 // FIXME: Add a more explicit test.
1100 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001101 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001102 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001103 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001104 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001105 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001106 }
1107
1108 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001109 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001110 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001111 FormatTok.Tok.setKind(Info.getTokenID());
1112 }
1113
1114 if (FormatTok.Tok.is(tok::greatergreater)) {
1115 FormatTok.Tok.setKind(tok::greater);
Daniel Jasper57d4a582013-02-28 10:06:05 +00001116 FormatTok.TokenLength = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001117 GreaterStashed = true;
1118 }
1119
1120 return FormatTok;
1121 }
1122
Nico Weber29f9dea2013-02-11 15:32:15 +00001123 IdentifierTable &getIdentTable() { return IdentTable; }
1124
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001125private:
1126 FormatToken FormatTok;
1127 bool GreaterStashed;
1128 Lexer &Lex;
1129 SourceManager &SourceMgr;
1130 IdentifierTable IdentTable;
1131
1132 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001133 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001134 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1135 Tok.getLength());
1136 }
1137};
1138
Daniel Jasperf7935112012-12-03 18:12:45 +00001139class Formatter : public UnwrappedLineConsumer {
1140public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001141 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001142 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001143 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001144 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001145
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001146 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001147
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001148 tooling::Replacements format() {
1149 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001150 UnwrappedLineParser Parser(Style, Tokens, *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001151 bool StructuralError = Parser.parse();
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001152 unsigned PreviousEndOfLineColumn = 0;
1153 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1154 Tokens.getIdentTable().get("in"));
1155 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1156 Annotator.annotate(AnnotatedLines[i]);
1157 }
1158 deriveLocalStyle();
1159 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1160 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1161 }
Daniel Jasperb67cc422013-04-09 17:46:55 +00001162
1163 // Adapt level to the next line if this is a comment.
1164 // FIXME: Can/should this be done in the UnwrappedLineParser?
Daniel Jasper6728fc12013-04-11 14:29:13 +00001165 const AnnotatedLine *NextNoneCommentLine = NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001166 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
1167 if (NextNoneCommentLine && AnnotatedLines[i].First.is(tok::comment) &&
1168 AnnotatedLines[i].First.Children.empty())
1169 AnnotatedLines[i].Level = NextNoneCommentLine->Level;
1170 else
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001171 NextNoneCommentLine =
1172 AnnotatedLines[i].First.isNot(tok::r_brace) ? &AnnotatedLines[i]
1173 : NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001174 }
1175
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001176 std::vector<int> IndentForLevel;
1177 bool PreviousLineWasTouched = false;
Alexander Kornienkofd433362013-03-27 17:08:02 +00001178 const AnnotatedToken *PreviousLineLastToken = 0;
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001179 bool FormatPPDirective = false;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001180 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1181 E = AnnotatedLines.end();
1182 I != E; ++I) {
1183 const AnnotatedLine &TheLine = *I;
1184 const FormatToken &FirstTok = TheLine.First.FormatTok;
1185 int Offset = getIndentOffset(TheLine.First);
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001186
1187 // Check whether this line is part of a formatted preprocessor directive.
1188 if (FirstTok.HasUnescapedNewline)
1189 FormatPPDirective = false;
1190 if (!FormatPPDirective && TheLine.InPPDirective &&
1191 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
1192 FormatPPDirective = true;
1193
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001194 // Determine indent and try to merge multiple unwrapped lines.
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001195 while (IndentForLevel.size() <= TheLine.Level)
1196 IndentForLevel.push_back(-1);
1197 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001198 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
1199 if (static_cast<int>(Indent) + Offset >= 0)
1200 Indent += Offset;
1201 tryFitMultipleLinesInOne(Indent, I, E);
1202
Daniel Jasperd1ae3582013-03-20 12:37:50 +00001203 bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001204 if (TheLine.First.is(tok::eof)) {
1205 if (PreviousLineWasTouched) {
1206 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1207 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001208 /*WhitespaceStartColumn*/ 0);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001209 }
1210 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001211 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001212 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001213 if (FirstTok.WhiteSpaceStart.isValid() &&
1214 // Insert a break even if there is a structural error in case where
1215 // we break apart a line consisting of multiple unwrapped lines.
1216 (FirstTok.NewlinesBefore == 0 || !StructuralError)) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001217 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1218 TheLine.InPPDirective, PreviousEndOfLineColumn);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001219 } else {
1220 Indent = LevelIndent =
1221 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001222 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001223 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Manuel Klimek1a18c402013-04-12 14:13:36 +00001224 TheLine.First, Whitespaces);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001225 PreviousEndOfLineColumn =
1226 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1227 IndentForLevel[TheLine.Level] = LevelIndent;
1228 PreviousLineWasTouched = true;
1229 } else {
1230 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001231 unsigned LevelIndent =
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001232 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001233 // Remove trailing whitespace of the previous line if it was touched.
1234 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
1235 formatFirstToken(TheLine.First, PreviousLineLastToken, LevelIndent,
1236 TheLine.InPPDirective, PreviousEndOfLineColumn);
1237
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001238 if (static_cast<int>(LevelIndent) - Offset >= 0)
1239 LevelIndent -= Offset;
Daniel Jasper66dc2ec2013-03-20 14:31:47 +00001240 if (TheLine.First.isNot(tok::comment))
1241 IndentForLevel[TheLine.Level] = LevelIndent;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001242 }
1243 // If we did not reformat this unwrapped line, the column at the end of
1244 // the last token is unchanged - thus, we can calculate the end of the
1245 // last token.
1246 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1247 PreviousEndOfLineColumn =
1248 SourceMgr.getSpellingColumnNumber(LastLoc) +
1249 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1250 PreviousLineWasTouched = false;
Daniel Jasperbc0fa392013-03-22 16:25:51 +00001251 if (TheLine.Last->is(tok::comment))
Daniel Jasperd69fc772013-05-08 14:12:04 +00001252 Whitespaces.addUntouchableComment(
1253 SourceMgr.getSpellingColumnNumber(
1254 TheLine.Last->FormatTok.Tok.getLocation()) -
1255 1);
Daniel Jasper770eb7c2013-04-24 06:33:59 +00001256 else
1257 Whitespaces.alignComments();
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001258 }
Alexander Kornienkofd433362013-03-27 17:08:02 +00001259 PreviousLineLastToken = I->Last;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001260 }
1261 return Whitespaces.generateReplacements();
1262 }
1263
1264private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001265 void deriveLocalStyle() {
1266 unsigned CountBoundToVariable = 0;
1267 unsigned CountBoundToType = 0;
1268 bool HasCpp03IncompatibleFormat = false;
1269 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1270 if (AnnotatedLines[i].First.Children.empty())
1271 continue;
1272 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1273 while (!Tok->Children.empty()) {
1274 if (Tok->Type == TT_PointerOrReference) {
1275 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1276 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1277 if (SpacesBefore && !SpacesAfter)
1278 ++CountBoundToVariable;
1279 else if (!SpacesBefore && SpacesAfter)
1280 ++CountBoundToType;
1281 }
1282
Daniel Jasper400adc62013-02-08 15:28:42 +00001283 if (Tok->Type == TT_TemplateCloser &&
1284 Tok->Parent->Type == TT_TemplateCloser &&
1285 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001286 HasCpp03IncompatibleFormat = true;
1287 Tok = &Tok->Children[0];
1288 }
1289 }
1290 if (Style.DerivePointerBinding) {
1291 if (CountBoundToType > CountBoundToVariable)
1292 Style.PointerBindsToType = true;
1293 else if (CountBoundToType < CountBoundToVariable)
1294 Style.PointerBindsToType = false;
1295 }
1296 if (Style.Standard == FormatStyle::LS_Auto) {
1297 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1298 : FormatStyle::LS_Cpp03;
1299 }
1300 }
1301
Manuel Klimekb95f5452013-02-08 17:38:27 +00001302 /// \brief Get the indent of \p Level from \p IndentForLevel.
1303 ///
1304 /// \p IndentForLevel must contain the indent for the level \c l
1305 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1306 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001307 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001308 if (IndentForLevel[Level] != -1)
1309 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001310 if (Level == 0)
1311 return 0;
Manuel Klimek13b97d82013-05-13 08:42:42 +00001312 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001313 }
1314
1315 /// \brief Get the offset of the line relatively to the level.
1316 ///
1317 /// For example, 'public:' labels in classes are offset by 1 or 2
1318 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001319 int getIndentOffset(const AnnotatedToken &RootToken) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001320 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimekb95f5452013-02-08 17:38:27 +00001321 return Style.AccessModifierOffset;
1322 return 0;
1323 }
1324
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001325 /// \brief Tries to merge lines into one.
1326 ///
1327 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1328 /// if possible; note that \c I will be incremented when lines are merged.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001329 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001330 std::vector<AnnotatedLine>::iterator &I,
1331 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001332 // We can never merge stuff if there are trailing line comments.
1333 if (I->Last->Type == TT_LineComment)
1334 return;
1335
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001336 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001337 // If we already exceed the column limit, we set 'Limit' to 0. The different
1338 // tryMerge..() functions can then decide whether to still do merging.
1339 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001340
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001341 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001342 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001343
Daniel Jasper25837aa2013-01-14 14:14:23 +00001344 if (I->Last->is(tok::l_brace)) {
1345 tryMergeSimpleBlock(I, E, Limit);
1346 } else if (I->First.is(tok::kw_if)) {
1347 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001348 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1349 I->First.FormatTok.IsFirst)) {
1350 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001351 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001352 }
1353
Daniel Jasper39825ea2013-01-14 15:40:57 +00001354 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1355 std::vector<AnnotatedLine>::iterator E,
1356 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001357 if (Limit == 0)
1358 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001359 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001360 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1361 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001362 if (I + 2 != E && (I + 2)->InPPDirective &&
1363 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1364 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001365 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001366 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001367 join(Line, *(++I));
1368 }
1369
Daniel Jasper25837aa2013-01-14 14:14:23 +00001370 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1371 std::vector<AnnotatedLine>::iterator E,
1372 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001373 if (Limit == 0)
1374 return;
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001375 if (!Style.AllowShortIfStatementsOnASingleLine)
1376 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001377 if ((I + 1)->InPPDirective != I->InPPDirective ||
1378 ((I + 1)->InPPDirective &&
1379 (I + 1)->First.FormatTok.HasUnescapedNewline))
1380 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001381 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001382 if (Line.Last->isNot(tok::r_paren))
1383 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001384 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001385 return;
1386 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1387 return;
1388 // Only inline simple if's (no nested if or else).
1389 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1390 return;
1391 join(Line, *(++I));
1392 }
1393
1394 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001395 std::vector<AnnotatedLine>::iterator E,
1396 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001397 // First, check that the current line allows merging. This is the case if
1398 // we're not in a control flow statement and the last token is an opening
1399 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001400 AnnotatedLine &Line = *I;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001401 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1402 tok::kw_else, tok::kw_try, tok::kw_catch,
1403 tok::kw_for,
1404 // This gets rid of all ObjC @ keywords and methods.
1405 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001406 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001407
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001408 AnnotatedToken *Tok = &(I + 1)->First;
1409 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001410 !Tok->MustBreakBefore) {
1411 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001412 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001413 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001414 join(Line, *(I + 1));
1415 I += 1;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001416 } else if (Limit != 0) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001417 // Check that we still have three lines and they fit into the limit.
1418 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1419 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001420 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001421
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001422 // Second, check that the next line does not contain any braces - if it
1423 // does, readability declines when putting it into a single line.
1424 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1425 return;
1426 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001427 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001428 return;
1429 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1430 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001431
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001432 // Last, check that the third line contains a single closing brace.
1433 Tok = &(I + 2)->First;
1434 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1435 Tok->MustBreakBefore)
1436 return;
1437
1438 join(Line, *(I + 1));
1439 join(Line, *(I + 2));
1440 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001441 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001442 }
1443
1444 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1445 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001446 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1447 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001448 }
1449
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001450 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001451 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001452 A.Last->Children.push_back(B.First);
1453 while (!A.Last->Children.empty()) {
1454 A.Last->Children[0].Parent = A.Last;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001455 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001456 A.Last = &A.Last->Children[0];
1457 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001458 }
1459
Daniel Jasper97b89482013-03-13 07:49:51 +00001460 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001461 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1462 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1463 Ranges[i].getBegin()) &&
1464 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1465 Range.getBegin()))
1466 return true;
1467 }
1468 return false;
1469 }
1470
1471 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001472 const FormatToken *First = &TheLine.First.FormatTok;
1473 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jaspercdd06622013-05-14 10:31:09 +00001474 CharSourceRange LineRange = CharSourceRange::getCharRange(
Daniel Jasper973c9422013-03-04 13:43:19 +00001475 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
Daniel Jaspercdd06622013-05-14 10:31:09 +00001476 Last->Tok.getLocation().getLocWithOffset(Last->TokenLength - 1));
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001477 return touchesRanges(LineRange);
1478 }
1479
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001480 bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I,
1481 std::vector<AnnotatedLine>::iterator E) {
1482 for (; I != E; ++I) {
1483 if (I->First.FormatTok.HasUnescapedNewline)
1484 return false;
1485 if (touchesLine(*I))
1486 return true;
1487 }
1488 return false;
1489 }
1490
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001491 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1492 const FormatToken *First = &TheLine.First.FormatTok;
1493 CharSourceRange LineRange = CharSourceRange::getCharRange(
1494 First->WhiteSpaceStart,
1495 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1496 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001497 }
1498
1499 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001500 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001501 }
1502
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001503 /// \brief Add a new line and the required indent before the first Token
1504 /// of the \c UnwrappedLine if there was no structural parsing error.
1505 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkofd433362013-03-27 17:08:02 +00001506 void formatFirstToken(const AnnotatedToken &RootToken,
1507 const AnnotatedToken *PreviousToken, unsigned Indent,
Manuel Klimekb95f5452013-02-08 17:38:27 +00001508 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001509 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001510
Daniel Jasperbbc84152013-01-29 11:27:30 +00001511 unsigned Newlines =
1512 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001513 if (Newlines == 0 && !Tok.IsFirst)
1514 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001515
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001516 if (!InPPDirective || Tok.HasUnescapedNewline) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001517 // Insert extra new line before access specifiers.
1518 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
1519 RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1)
1520 ++Newlines;
1521
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001522 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001523 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001524 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001525 PreviousEndOfLineColumn);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001526 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001527 }
1528
Daniel Jasperf7935112012-12-03 18:12:45 +00001529 FormatStyle Style;
1530 Lexer &Lex;
1531 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001532 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001533 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001534 std::vector<AnnotatedLine> AnnotatedLines;
Daniel Jasperf7935112012-12-03 18:12:45 +00001535};
1536
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001537tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1538 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001539 std::vector<CharSourceRange> Ranges) {
1540 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001541 return formatter.format();
1542}
1543
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001544LangOptions getFormattingLangOpts() {
1545 LangOptions LangOpts;
1546 LangOpts.CPlusPlus = 1;
1547 LangOpts.CPlusPlus11 = 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001548 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001549 LangOpts.Bool = 1;
1550 LangOpts.ObjC1 = 1;
1551 LangOpts.ObjC2 = 1;
1552 return LangOpts;
1553}
1554
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001555} // namespace format
1556} // namespace clang