blob: b8c40cf2633c2089117903ed388df60cbe37d7ef [file] [log] [blame]
Daniel Jasperbac016b2012-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 Jasperbac016b2012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimekca547db2013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Alexander Kornienko70ce7882013-04-15 14:28:00 +000018#include "BreakableToken.h"
Daniel Jasper32d28ee2013-01-29 21:01:14 +000019#include "TokenAnnotator.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienko70ce7882013-04-15 14:28:00 +000021#include "WhitespaceManager.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000022#include "clang/Basic/Diagnostic.h"
Daniel Jasper675d2e32012-12-21 10:20:02 +000023#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000025#include "clang/Format/Format.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000026#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000027#include "clang/Lex/Lexer.h"
Alexander Kornienko5262dd92013-03-27 11:52:18 +000028#include "llvm/ADT/STLExtras.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000029#include "llvm/Support/Allocator.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000030#include "llvm/Support/Debug.h"
Alexander Kornienkod71ec162013-05-07 15:32:14 +000031#include "llvm/Support/YAMLTraits.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000032#include <queue>
Daniel Jasper8822d3a2012-12-04 13:02:32 +000033#include <string>
34
Alexander Kornienkod71ec162013-05-07 15:32:14 +000035namespace llvm {
36namespace yaml {
37template <>
38struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> {
Manuel Klimek44135b82013-05-13 12:51:40 +000039 static void enumeration(IO &IO,
40 clang::format::FormatStyle::LanguageStandard &Value) {
41 IO.enumCase(Value, "C++03", clang::format::FormatStyle::LS_Cpp03);
42 IO.enumCase(Value, "C++11", clang::format::FormatStyle::LS_Cpp11);
43 IO.enumCase(Value, "Auto", clang::format::FormatStyle::LS_Auto);
44 }
45};
46
47template<>
48struct ScalarEnumerationTraits<clang::format::FormatStyle::BraceBreakingStyle> {
49 static void
50 enumeration(IO &IO, clang::format::FormatStyle::BraceBreakingStyle &Value) {
51 IO.enumCase(Value, "Attach", clang::format::FormatStyle::BS_Attach);
52 IO.enumCase(Value, "Linux", clang::format::FormatStyle::BS_Linux);
53 IO.enumCase(Value, "Stroustrup", clang::format::FormatStyle::BS_Stroustrup);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000054 }
55};
56
57template <> struct MappingTraits<clang::format::FormatStyle> {
58 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
Alexander Kornienkodd256312013-05-10 11:56:10 +000059 if (IO.outputting()) {
60 StringRef StylesArray[] = { "LLVM", "Google", "Chromium", "Mozilla" };
61 ArrayRef<StringRef> Styles(StylesArray);
62 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
63 StringRef StyleName(Styles[i]);
64 if (Style == clang::format::getPredefinedStyle(StyleName)) {
65 IO.mapOptional("# BasedOnStyle", StyleName);
66 break;
67 }
68 }
69 } else {
Alexander Kornienkod71ec162013-05-07 15:32:14 +000070 StringRef BasedOnStyle;
71 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000072 if (!BasedOnStyle.empty())
73 Style = clang::format::getPredefinedStyle(BasedOnStyle);
74 }
75
76 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
77 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
78 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
79 Style.AllowAllParametersOfDeclarationOnNextLine);
80 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
81 Style.AllowShortIfStatementsOnASingleLine);
82 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
83 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
84 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
85 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
86 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
87 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
88 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
89 IO.mapOptional("ObjCSpaceBeforeProtocolList",
90 Style.ObjCSpaceBeforeProtocolList);
91 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
92 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
93 Style.PenaltyReturnTypeOnItsOwnLine);
94 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
95 IO.mapOptional("SpacesBeforeTrailingComments",
96 Style.SpacesBeforeTrailingComments);
97 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek07a64ec2013-05-13 08:42:42 +000098 IO.mapOptional("IndentWidth", Style.IndentWidth);
Manuel Klimek7c9a93e2013-05-13 09:22:11 +000099 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimek44135b82013-05-13 12:51:40 +0000100 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000101 }
102};
103}
104}
105
Daniel Jasperbac016b2012-12-03 18:12:45 +0000106namespace clang {
107namespace format {
108
Daniel Jasperbac016b2012-12-03 18:12:45 +0000109FormatStyle getLLVMStyle() {
110 FormatStyle LLVMStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000111 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000112 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasperf1579602013-01-29 16:03:49 +0000113 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000114 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000115 LLVMStyle.BinPackParameters = true;
116 LLVMStyle.ColumnLimit = 80;
117 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
118 LLVMStyle.DerivePointerBinding = false;
119 LLVMStyle.IndentCaseLabels = false;
120 LLVMStyle.MaxEmptyLinesToKeep = 1;
Nico Weber5f500df2013-01-10 20:12:55 +0000121 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper01786732013-02-04 07:21:18 +0000122 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper1407bee2013-04-11 14:29:13 +0000123 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 75;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000124 LLVMStyle.PointerBindsToType = false;
125 LLVMStyle.SpacesBeforeTrailingComments = 1;
126 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000127 LLVMStyle.IndentWidth = 2;
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000128 LLVMStyle.UseTab = false;
Manuel Klimek44135b82013-05-13 12:51:40 +0000129 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000130 return LLVMStyle;
131}
132
133FormatStyle getGoogleStyle() {
134 FormatStyle GoogleStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000135 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000136 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000137 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000138 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000139 GoogleStyle.BinPackParameters = true;
140 GoogleStyle.ColumnLimit = 80;
141 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
142 GoogleStyle.DerivePointerBinding = true;
143 GoogleStyle.IndentCaseLabels = true;
144 GoogleStyle.MaxEmptyLinesToKeep = 1;
Nico Weber5f500df2013-01-10 20:12:55 +0000145 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper01786732013-02-04 07:21:18 +0000146 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper1407bee2013-04-11 14:29:13 +0000147 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000148 GoogleStyle.PointerBindsToType = true;
149 GoogleStyle.SpacesBeforeTrailingComments = 2;
150 GoogleStyle.Standard = FormatStyle::LS_Auto;
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000151 GoogleStyle.IndentWidth = 2;
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000152 GoogleStyle.UseTab = false;
Manuel Klimek44135b82013-05-13 12:51:40 +0000153 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000154 return GoogleStyle;
155}
156
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000157FormatStyle getChromiumStyle() {
158 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +0000159 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000160 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000161 ChromiumStyle.BinPackParameters = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000162 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
163 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000164 return ChromiumStyle;
165}
166
Alexander Kornienkofb594862013-05-06 14:11:27 +0000167FormatStyle getMozillaStyle() {
168 FormatStyle MozillaStyle = getLLVMStyle();
169 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
170 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
171 MozillaStyle.DerivePointerBinding = true;
172 MozillaStyle.IndentCaseLabels = true;
173 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
174 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
175 MozillaStyle.PointerBindsToType = true;
176 return MozillaStyle;
177}
178
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000179FormatStyle getPredefinedStyle(StringRef Name) {
180 if (Name.equals_lower("llvm"))
181 return getLLVMStyle();
182 if (Name.equals_lower("chromium"))
183 return getChromiumStyle();
184 if (Name.equals_lower("mozilla"))
185 return getMozillaStyle();
186 if (Name.equals_lower("google"))
187 return getGoogleStyle();
188
189 llvm::errs() << "Unknown style " << Name << ", using Google style.\n";
190 return getGoogleStyle();
191}
192
193llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
194 llvm::yaml::Input Input(Text);
195 Input >> *Style;
196 return Input.error();
197}
198
199std::string configurationAsText(const FormatStyle &Style) {
200 std::string Text;
201 llvm::raw_string_ostream Stream(Text);
202 llvm::yaml::Output Output(Stream);
203 // We use the same mapping method for input and output, so we need a non-const
204 // reference here.
205 FormatStyle NonConstStyle = Style;
206 Output << NonConstStyle;
Alexander Kornienkoaf640322013-05-13 12:41:08 +0000207 Stream.flush();
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000208 return Text;
209}
210
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000211// Returns the length of everything up to the first possible line break after
212// the ), ], } or > matching \c Tok.
213static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
214 if (Tok.MatchingParen == NULL)
215 return 0;
216 AnnotatedToken *End = Tok.MatchingParen;
217 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
218 End = &End->Children[0];
219 }
220 return End->TotalLength - Tok.TotalLength + 1;
221}
222
Daniel Jasperbac016b2012-12-03 18:12:45 +0000223class UnwrappedLineFormatter {
224public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000225 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper995e8202013-01-14 13:08:07 +0000226 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000227 const AnnotatedToken &RootToken,
Manuel Klimek67d080d2013-04-12 14:13:36 +0000228 WhitespaceManager &Whitespaces)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000229 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000230 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasperf11a7052013-02-21 21:33:55 +0000231 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000232
Manuel Klimekd4397b92013-01-04 23:34:14 +0000233 /// \brief Formats an \c UnwrappedLine.
234 ///
235 /// \returns The column after the last token in the last line of the
236 /// \c UnwrappedLine.
Daniel Jaspera4d46212013-02-28 11:05:57 +0000237 unsigned format(const AnnotatedLine *NextLine) {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000238 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000239 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000240 State.Column = FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000241 State.NextToken = &RootToken;
Daniel Jasper6f21a982013-03-13 07:49:51 +0000242 State.Stack.push_back(
Daniel Jasper37911302013-04-02 14:33:13 +0000243 ParenState(FirstIndent, FirstIndent, !Style.BinPackParameters,
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000244 /*NoLineBreak=*/ false));
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000245 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000246 State.ParenLevel = 0;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000247 State.StartOfStringLiteral = 0;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000248 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000249
250 // The first token has already been indented and thus consumed.
Manuel Klimek8092a942013-02-20 10:15:13 +0000251 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000252
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000253 // If everything fits on a single line, just put it there.
Daniel Jaspera4d46212013-02-28 11:05:57 +0000254 unsigned ColumnLimit = Style.ColumnLimit;
255 if (NextLine && NextLine->InPPDirective &&
256 !NextLine->First.FormatTok.HasUnescapedNewline)
257 ColumnLimit = getColumnLimit();
258 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000259 while (State.NextToken != NULL) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000260 addTokenToState(false, false, State);
Daniel Jasper1321eb52012-12-18 21:05:13 +0000261 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000262 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000263 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000264
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000265 // If the ObjC method declaration does not fit on a line, we should format
266 // it with one arg per line.
267 if (Line.Type == LT_ObjCMethodDecl)
268 State.Stack.back().BreakBeforeParameter = true;
269
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000270 // Find best solution in solution space.
271 return analyzeSolutionSpace(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000272 }
273
274private:
Manuel Klimekca547db2013-01-16 14:55:28 +0000275 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
276 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Alexander Kornienkodd256312013-05-10 11:56:10 +0000277 llvm::dbgs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000278 Tok.getLength());
Alexander Kornienkodd256312013-05-10 11:56:10 +0000279 llvm::dbgs();
Manuel Klimekca547db2013-01-16 14:55:28 +0000280 }
281
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000282 struct ParenState {
Daniel Jasperd399bff2013-02-05 09:41:21 +0000283 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000284 bool NoLineBreak)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000285 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
286 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000287 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000288 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
289 NestedNameSpecifierContinuation(0), CallContinuation(0),
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000290 VariablePos(0), ForFakeParenthesis(false) {}
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000291
Daniel Jasperbac016b2012-12-03 18:12:45 +0000292 /// \brief The position to which a specific parenthesis level needs to be
293 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000294 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000295
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000296 /// \brief The position of the last space on each level.
297 ///
298 /// Used e.g. to break like:
299 /// functionCall(Parameter, otherCall(
300 /// OtherParameter));
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000301 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000302
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000303 /// \brief The position the first "<<" operator encountered on each level.
304 ///
305 /// Used to align "<<" operators. 0 if no such operator has been encountered
306 /// on a level.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000307 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000308
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000309 /// \brief Whether a newline needs to be inserted before the block's closing
310 /// brace.
311 ///
312 /// We only want to insert a newline before the closing brace if there also
313 /// was a newline after the beginning left brace.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000314 bool BreakBeforeClosingBrace;
315
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000316 /// \brief The column of a \c ? in a conditional expression;
317 unsigned QuestionColumn;
318
Daniel Jasperf343cab2013-01-31 14:59:26 +0000319 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
320 /// lines, in this context.
321 bool AvoidBinPacking;
322
323 /// \brief Break after the next comma (or all the commas in this context if
324 /// \c AvoidBinPacking is \c true).
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000325 bool BreakBeforeParameter;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000326
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000327 /// \brief Line breaking in this context would break a formatting rule.
328 bool NoLineBreak;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000329
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000330 /// \brief The position of the colon in an ObjC method declaration/call.
331 unsigned ColonPos;
Daniel Jasperc4615b72013-02-20 12:56:39 +0000332
Daniel Jasper24849712013-03-01 16:48:32 +0000333 /// \brief The start of the most recent function in a builder-type call.
334 unsigned StartOfFunctionCall;
335
Daniel Jasper37911302013-04-02 14:33:13 +0000336 /// \brief If a nested name specifier was broken over multiple lines, this
337 /// contains the start column of the second line. Otherwise 0.
338 unsigned NestedNameSpecifierContinuation;
339
340 /// \brief If a call expression was broken over multiple lines, this
341 /// contains the start column of the second line. Otherwise 0.
342 unsigned CallContinuation;
343
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000344 /// \brief The column of the first variable name in a variable declaration.
345 ///
346 /// Used to align further variables if necessary.
347 unsigned VariablePos;
348
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000349 /// \brief \c true if this \c ParenState was created for a fake parenthesis.
350 ///
351 /// Does not need to be considered for memoization / the comparison function
352 /// as otherwise identical states will have the same fake/non-fake
353 /// \c ParenStates.
354 bool ForFakeParenthesis;
355
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000356 bool operator<(const ParenState &Other) const {
357 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000358 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000359 if (LastSpace != Other.LastSpace)
360 return LastSpace < Other.LastSpace;
361 if (FirstLessLess != Other.FirstLessLess)
362 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000363 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
364 return BreakBeforeClosingBrace;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000365 if (QuestionColumn != Other.QuestionColumn)
366 return QuestionColumn < Other.QuestionColumn;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000367 if (AvoidBinPacking != Other.AvoidBinPacking)
368 return AvoidBinPacking;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000369 if (BreakBeforeParameter != Other.BreakBeforeParameter)
370 return BreakBeforeParameter;
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000371 if (NoLineBreak != Other.NoLineBreak)
372 return NoLineBreak;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000373 if (ColonPos != Other.ColonPos)
374 return ColonPos < Other.ColonPos;
Daniel Jasper24849712013-03-01 16:48:32 +0000375 if (StartOfFunctionCall != Other.StartOfFunctionCall)
376 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasper37911302013-04-02 14:33:13 +0000377 if (CallContinuation != Other.CallContinuation)
378 return CallContinuation < Other.CallContinuation;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000379 if (VariablePos != Other.VariablePos)
380 return VariablePos < Other.VariablePos;
Daniel Jasperb3123142013-01-12 07:36:22 +0000381 return false;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000382 }
383 };
384
385 /// \brief The current state when indenting a unwrapped line.
386 ///
387 /// As the indenting tries different combinations this is copied by value.
388 struct LineState {
389 /// \brief The number of used columns in the current line.
390 unsigned Column;
391
392 /// \brief The token that needs to be next formatted.
393 const AnnotatedToken *NextToken;
394
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000395 /// \brief \c true if this line contains a continued for-loop section.
396 bool LineContainsContinuedForLoopSection;
397
Daniel Jasper29f123b2013-02-08 15:28:42 +0000398 /// \brief The level of nesting inside (), [], <> and {}.
399 unsigned ParenLevel;
400
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000401 /// \brief The \c ParenLevel at the start of this line.
402 unsigned StartOfLineLevel;
403
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000404 /// \brief The start column of the string literal, if we're in a string
405 /// literal sequence, 0 otherwise.
406 unsigned StartOfStringLiteral;
407
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000408 /// \brief A stack keeping track of properties applying to parenthesis
409 /// levels.
410 std::vector<ParenState> Stack;
411
412 /// \brief Comparison operator to be able to used \c LineState in \c map.
413 bool operator<(const LineState &Other) const {
Daniel Jasperd7896702013-02-19 09:28:55 +0000414 if (NextToken != Other.NextToken)
415 return NextToken < Other.NextToken;
416 if (Column != Other.Column)
417 return Column < Other.Column;
Daniel Jasperd7896702013-02-19 09:28:55 +0000418 if (LineContainsContinuedForLoopSection !=
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000419 Other.LineContainsContinuedForLoopSection)
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000420 return LineContainsContinuedForLoopSection;
Daniel Jasperd7896702013-02-19 09:28:55 +0000421 if (ParenLevel != Other.ParenLevel)
422 return ParenLevel < Other.ParenLevel;
423 if (StartOfLineLevel != Other.StartOfLineLevel)
424 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000425 if (StartOfStringLiteral != Other.StartOfStringLiteral)
426 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasperd7896702013-02-19 09:28:55 +0000427 return Stack < Other.Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000428 }
429 };
430
Daniel Jasper20409152012-12-04 14:54:30 +0000431 /// \brief Appends the next token to \p State and updates information
432 /// necessary for indentation.
433 ///
434 /// Puts the token on the current line if \p Newline is \c true and adds a
435 /// line break and necessary indentation otherwise.
436 ///
437 /// If \p DryRun is \c false, also creates and stores the required
438 /// \c Replacement.
Manuel Klimek8092a942013-02-20 10:15:13 +0000439 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000440 const AnnotatedToken &Current = *State.NextToken;
441 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000442
Daniel Jasper92f9faf2013-03-20 15:58:10 +0000443 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000444 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
445 State.NextToken->FormatTok.TokenLength;
446 if (State.NextToken->Children.empty())
447 State.NextToken = NULL;
448 else
449 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek8092a942013-02-20 10:15:13 +0000450 return 0;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000451 }
452
Daniel Jasper3776ef32013-04-03 07:21:51 +0000453 // If we are continuing an expression, we want to indent an extra 4 spaces.
454 unsigned ContinuationIndent =
Daniel Jasper37911302013-04-02 14:33:13 +0000455 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000456 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000457 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000458 if (Current.is(tok::r_brace)) {
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000459 State.Column = Line.Level * Style.IndentWidth;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000460 } else if (Current.is(tok::string_literal) &&
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000461 State.StartOfStringLiteral != 0) {
462 State.Column = State.StartOfStringLiteral;
Daniel Jasper66d19bd2013-02-18 11:59:17 +0000463 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000464 } else if (Current.is(tok::lessless) &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000465 State.Stack.back().FirstLessLess != 0) {
466 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasper37911302013-04-02 14:33:13 +0000467 } else if (Current.isOneOf(tok::period, tok::arrow)) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000468 if (State.Stack.back().CallContinuation == 0) {
469 State.Column = ContinuationIndent;
Daniel Jasper37911302013-04-02 14:33:13 +0000470 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000471 } else {
472 State.Column = State.Stack.back().CallContinuation;
473 }
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000474 } else if (Current.Type == TT_ConditionalExpr) {
475 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000476 } else if (Previous.is(tok::comma) &&
477 State.Stack.back().VariablePos != 0) {
478 State.Column = State.Stack.back().VariablePos;
Daniel Jasper3c08a812013-02-24 18:54:32 +0000479 } else if (Previous.ClosesTemplateDeclaration ||
Daniel Jasper53e72cd2013-05-06 08:27:33 +0000480 (Current.Type == TT_StartOfName && State.ParenLevel == 0 &&
481 Line.StartsDefinition)) {
Daniel Jasper37911302013-04-02 14:33:13 +0000482 State.Column = State.Stack.back().Indent;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000483 } else if (Current.Type == TT_ObjCSelectorName) {
484 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
485 State.Column =
486 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
487 } else {
488 State.Column = State.Stack.back().Indent;
489 State.Stack.back().ColonPos =
490 State.Column + Current.FormatTok.TokenLength;
491 }
Daniel Jasperb2f063a2013-05-08 10:00:18 +0000492 } else if (Current.Type == TT_StartOfName ||
493 Previous.isOneOf(tok::coloncolon, tok::equal) ||
Daniel Jasper37911302013-04-02 14:33:13 +0000494 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000495 State.Column = ContinuationIndent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000496 } else {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000497 State.Column = State.Stack.back().Indent;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000498 // Ensure that we fall back to indenting 4 spaces instead of just
499 // flushing continuations left.
Daniel Jasper37911302013-04-02 14:33:13 +0000500 if (State.Column == FirstIndent)
501 State.Column += 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000502 }
503
Daniel Jasper7878a7b2013-02-15 11:07:25 +0000504 if (Current.is(tok::question))
Daniel Jasper237d4c12013-02-23 21:01:55 +0000505 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper11e13802013-05-08 14:12:04 +0000506 if ((Previous.isOneOf(tok::comma, tok::semi) &&
507 !State.Stack.back().AvoidBinPacking) ||
508 Previous.Type == TT_BinaryOperator)
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000509 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000510
Manuel Klimek060143e2013-01-02 18:33:23 +0000511 if (!DryRun) {
Daniel Jasper1ef81d52013-02-26 13:10:34 +0000512 unsigned NewLines = 1;
513 if (Current.Type == TT_LineComment)
514 NewLines =
515 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
516 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimek060143e2013-01-02 18:33:23 +0000517 if (!Line.InPPDirective)
Daniel Jasperc4615b72013-02-20 12:56:39 +0000518 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Alexander Kornienko052685c2013-03-19 17:41:36 +0000519 WhitespaceStartColumn);
Manuel Klimek060143e2013-01-02 18:33:23 +0000520 else
Daniel Jasperc4615b72013-02-20 12:56:39 +0000521 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Alexander Kornienko052685c2013-03-19 17:41:36 +0000522 WhitespaceStartColumn);
Manuel Klimek060143e2013-01-02 18:33:23 +0000523 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000524
Daniel Jasper29f123b2013-02-08 15:28:42 +0000525 State.Stack.back().LastSpace = State.Column;
Daniel Jasper04abbb22013-05-10 13:37:16 +0000526 if (Current.isOneOf(tok::arrow, tok::period))
527 State.Stack.back().LastSpace += Current.FormatTok.TokenLength;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000528 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper237d4c12013-02-23 21:01:55 +0000529
530 // Any break on this level means that the parent level has been broken
531 // and we need to avoid bin packing there.
532 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
533 State.Stack[i].BreakBeforeParameter = true;
534 }
Daniel Jasper01218ff2013-04-15 22:36:37 +0000535 const AnnotatedToken *TokenBefore = Current.getPreviousNoneComment();
536 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
Daniel Jasper11e13802013-05-08 14:12:04 +0000537 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000538 State.Stack.back().BreakBeforeParameter = true;
539
Daniel Jasper237d4c12013-02-23 21:01:55 +0000540 // If we break after {, we should also break before the corresponding }.
541 if (Previous.is(tok::l_brace))
542 State.Stack.back().BreakBeforeClosingBrace = true;
543
544 if (State.Stack.back().AvoidBinPacking) {
545 // If we are breaking after '(', '{', '<', this is not bin packing
546 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper3c08a812013-02-24 18:54:32 +0000547 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jasper237d4c12013-02-23 21:01:55 +0000548 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
549 Line.MustBeDeclaration))
550 State.Stack.back().BreakBeforeParameter = true;
551 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000552 } else {
Daniel Jasper9c3e71a2013-02-25 15:59:54 +0000553 if (Current.is(tok::equal) &&
Daniel Jasperadc0f092013-04-05 09:38:50 +0000554 (RootToken.is(tok::kw_for) || State.ParenLevel == 0) &&
555 State.Stack.back().VariablePos == 0) {
556 State.Stack.back().VariablePos = State.Column;
557 // Move over * and & if they are bound to the variable name.
558 const AnnotatedToken *Tok = &Previous;
559 while (Tok &&
560 State.Stack.back().VariablePos >= Tok->FormatTok.TokenLength) {
561 State.Stack.back().VariablePos -= Tok->FormatTok.TokenLength;
562 if (Tok->SpacesRequiredBefore != 0)
563 break;
564 Tok = Tok->Parent;
565 }
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000566 if (Previous.PartOfMultiVariableDeclStmt)
567 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
568 }
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000569
Daniel Jasper729a7432013-02-11 12:36:37 +0000570 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper20409152012-12-04 14:54:30 +0000571
Daniel Jasperbac016b2012-12-03 18:12:45 +0000572 if (!DryRun)
Alexander Kornienko052685c2013-03-19 17:41:36 +0000573 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column);
Daniel Jasper20409152012-12-04 14:54:30 +0000574
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000575 if (Current.Type == TT_ObjCSelectorName &&
576 State.Stack.back().ColonPos == 0) {
577 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000578 State.Column + Spaces + Current.FormatTok.TokenLength)
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000579 State.Stack.back().ColonPos =
580 State.Stack.back().Indent + Current.LongestObjCSelectorName;
581 else
582 State.Stack.back().ColonPos =
Daniel Jasper9e9e6e02013-02-06 16:00:26 +0000583 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000584 }
585
Daniel Jasperac3223e2013-04-10 09:49:49 +0000586 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000587 Current.Type != TT_LineComment)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000588 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000589 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
590 State.Stack.back().AvoidBinPacking)
591 State.Stack.back().NoLineBreak = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000592
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000593 State.Column += Spaces;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000594 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jaspere438bac2013-01-23 20:41:06 +0000595 // Treat the condition inside an if as if it was a second function
596 // parameter, i.e. let nested calls have an indent of 4.
597 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperf9955d32013-03-20 12:37:50 +0000598 else if (Previous.is(tok::comma))
Daniel Jaspere438bac2013-01-23 20:41:06 +0000599 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000600 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper02b771e2013-01-28 13:31:35 +0000601 Previous.Type == TT_ConditionalExpr ||
602 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasperae8699b2013-01-28 09:35:24 +0000603 getPrecedence(Previous) != prec::Assignment)
604 State.Stack.back().LastSpace = State.Column;
Daniel Jasper6cabab42013-02-14 08:42:54 +0000605 else if (Previous.Type == TT_InheritanceColon)
606 State.Stack.back().Indent = State.Column;
Daniel Jasper11e13802013-05-08 14:12:04 +0000607 else if (Previous.opensScope() && !Current.FakeLParens.empty())
608 // If this function has multiple parameters or a binary expression
609 // parameter, indent nested calls from the start of the first parameter.
Daniel Jasper986e17f2013-01-28 07:35:34 +0000610 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000611 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000612
Manuel Klimek8092a942013-02-20 10:15:13 +0000613 return moveStateToNextToken(State, DryRun);
Daniel Jasper20409152012-12-04 14:54:30 +0000614 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000615
Daniel Jasper20409152012-12-04 14:54:30 +0000616 /// \brief Mark the next token as consumed in \p State and modify its stacks
617 /// accordingly.
Manuel Klimek8092a942013-02-20 10:15:13 +0000618 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000619 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000620 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000621
Daniel Jasper6cabab42013-02-14 08:42:54 +0000622 if (Current.Type == TT_InheritanceColon)
623 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000624 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
625 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000626 if (Current.is(tok::question))
627 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000628 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasper24849712013-03-01 16:48:32 +0000629 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
630 State.Stack.back().StartOfFunctionCall =
Daniel Jasper04abbb22013-05-10 13:37:16 +0000631 Current.LastInChainOfCalls ? 0 : State.Column +
632 Current.FormatTok.TokenLength;
Daniel Jasper7d812812013-02-21 15:00:29 +0000633 if (Current.Type == TT_CtorInitializerColon) {
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000634 // Indent 2 from the column, so:
635 // SomeClass::SomeClass()
636 // : First(...), ...
637 // Next(...)
638 // ^ line up here.
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000639 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper7d812812013-02-21 15:00:29 +0000640 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
641 State.Stack.back().AvoidBinPacking = true;
642 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000643 }
Daniel Jasper3776ef32013-04-03 07:21:51 +0000644
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000645 // If return returns a binary expression, align after it.
646 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
647 State.Stack.back().LastSpace = State.Column + 7;
648
Daniel Jasper3776ef32013-04-03 07:21:51 +0000649 // In ObjC method declaration we align on the ":" of parameters, but we need
650 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasper37911302013-04-02 14:33:13 +0000651 if (Current.Type == TT_ObjCMethodSpecifier)
652 State.Stack.back().Indent += 4;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000653
Daniel Jasper29f123b2013-02-08 15:28:42 +0000654 // Insert scopes created by fake parenthesis.
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000655 const AnnotatedToken *Previous = Current.getPreviousNoneComment();
656 // Don't add extra indentation for the first fake parenthesis after
657 // 'return', assignements or opening <({[. The indentation for these cases
658 // is special cased.
659 bool SkipFirstExtraIndent =
660 Current.is(tok::kw_return) ||
Daniel Jasperac3223e2013-04-10 09:49:49 +0000661 (Previous && (Previous->opensScope() ||
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000662 getPrecedence(*Previous) == prec::Assignment));
663 for (SmallVector<prec::Level, 4>::const_reverse_iterator
664 I = Current.FakeLParens.rbegin(),
665 E = Current.FakeLParens.rend();
666 I != E; ++I) {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000667 ParenState NewParenState = State.Stack.back();
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000668 NewParenState.ForFakeParenthesis = true;
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000669 NewParenState.Indent =
670 std::max(std::max(State.Column, NewParenState.Indent),
671 State.Stack.back().LastSpace);
672
673 // Always indent conditional expressions. Never indent expression where
674 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
675 // prec::Assignment) as those have different indentation rules. Indent
676 // other expression, unless the indentation needs to be skipped.
677 if (*I == prec::Conditional ||
678 (!SkipFirstExtraIndent && *I > prec::Assignment))
679 NewParenState.Indent += 4;
Daniel Jasperac3223e2013-04-10 09:49:49 +0000680 if (Previous && !Previous->opensScope())
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000681 NewParenState.BreakBeforeParameter = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000682 State.Stack.push_back(NewParenState);
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000683 SkipFirstExtraIndent = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000684 }
685
Daniel Jaspercf225b62012-12-24 13:43:52 +0000686 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000687 // prepare for the following tokens.
Daniel Jasperac3223e2013-04-10 09:49:49 +0000688 if (Current.opensScope()) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000689 unsigned NewIndent;
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000690 unsigned LastSpace = State.Stack.back().LastSpace;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000691 bool AvoidBinPacking;
Manuel Klimek2851c162013-01-10 14:36:46 +0000692 if (Current.is(tok::l_brace)) {
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000693 NewIndent = Style.IndentWidth + LastSpace;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000694 AvoidBinPacking = false;
Manuel Klimek2851c162013-01-10 14:36:46 +0000695 } else {
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000696 NewIndent =
697 4 + std::max(LastSpace, State.Stack.back().StartOfFunctionCall);
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000698 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek2851c162013-01-10 14:36:46 +0000699 }
Daniel Jasperfca24bc2013-04-25 13:31:51 +0000700
701 if (Current.NoMoreTokensOnLevel && Current.FakeLParens.empty()) {
702 // This parenthesis was the last token possibly making use of Indent and
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000703 // LastSpace of the next higher ParenLevel. Thus, erase them to achieve
Daniel Jasperfca24bc2013-04-25 13:31:51 +0000704 // better memoization results.
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000705 for (unsigned i = State.Stack.size() - 1; i > 0; --i) {
706 State.Stack[i].Indent = 0;
707 State.Stack[i].LastSpace = 0;
708 if (!State.Stack[i].ForFakeParenthesis)
709 break;
710 }
Daniel Jasperfca24bc2013-04-25 13:31:51 +0000711 }
712
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000713 State.Stack.push_back(ParenState(NewIndent, LastSpace, AvoidBinPacking,
714 State.Stack.back().NoLineBreak));
Daniel Jasper29f123b2013-02-08 15:28:42 +0000715 ++State.ParenLevel;
Daniel Jasper20409152012-12-04 14:54:30 +0000716 }
717
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000718 // If this '[' opens an ObjC call, determine whether all parameters fit into
719 // one line and put one per line if they don't.
720 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
721 Current.MatchingParen != NULL) {
722 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
723 State.Stack.back().BreakBeforeParameter = true;
724 }
725
Daniel Jaspercf225b62012-12-24 13:43:52 +0000726 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000727 // stacks.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000728 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +0000729 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
730 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000731 State.Stack.pop_back();
Daniel Jasper29f123b2013-02-08 15:28:42 +0000732 --State.ParenLevel;
733 }
734
735 // Remove scopes created by fake parenthesis.
736 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasperabfc9c12013-04-04 19:31:00 +0000737 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000738 State.Stack.pop_back();
Daniel Jasperabfc9c12013-04-04 19:31:00 +0000739 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000740 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000741
Manuel Klimeke9a62262013-02-20 15:32:58 +0000742 if (Current.is(tok::string_literal)) {
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000743 State.StartOfStringLiteral = State.Column;
744 } else if (Current.isNot(tok::comment)) {
745 State.StartOfStringLiteral = 0;
746 }
747
Manuel Klimek8092a942013-02-20 10:15:13 +0000748 State.Column += Current.FormatTok.TokenLength;
749
Daniel Jasper26f7e782013-01-08 14:56:18 +0000750 if (State.NextToken->Children.empty())
751 State.NextToken = NULL;
752 else
753 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek2851c162013-01-10 14:36:46 +0000754
Manuel Klimek8092a942013-02-20 10:15:13 +0000755 return breakProtrudingToken(Current, State, DryRun);
756 }
757
758 /// \brief If the current token sticks out over the end of the line, break
759 /// it if possible.
760 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
761 bool DryRun) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000762 llvm::OwningPtr<BreakableToken> Token;
Manuel Klimek8092a942013-02-20 10:15:13 +0000763 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000764 if (Current.is(tok::string_literal)) {
765 // Only break up default narrow strings.
Alexander Kornienko919398b2013-04-17 17:34:05 +0000766 const char *LiteralData = SourceMgr.getCharacterData(
767 Current.FormatTok.getStartOfNonWhitespace());
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000768 if (!LiteralData || *LiteralData != '"')
769 return 0;
770
Alexander Kornienko919398b2013-04-17 17:34:05 +0000771 Token.reset(new BreakableStringLiteral(SourceMgr, Current.FormatTok,
772 StartColumn));
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000773 } else if (Current.Type == TT_BlockComment) {
774 BreakableBlockComment *BBC =
775 new BreakableBlockComment(SourceMgr, Current, StartColumn);
776 if (!DryRun)
777 BBC->alignLines(Whitespaces);
778 Token.reset(BBC);
Daniel Jasper7ff96ed2013-05-06 10:24:51 +0000779 } else if (Current.Type == TT_LineComment &&
780 (Current.Parent == NULL ||
781 Current.Parent->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko919398b2013-04-17 17:34:05 +0000782 Token.reset(new BreakableLineComment(SourceMgr, Current, StartColumn));
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000783 } else {
784 return 0;
785 }
786
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000787 bool BreakInserted = false;
788 unsigned Penalty = 0;
789 for (unsigned LineIndex = 0; LineIndex < Token->getLineCount();
790 ++LineIndex) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000791 unsigned TailOffset = 0;
792 unsigned RemainingLength =
793 Token->getLineLengthAfterSplit(LineIndex, TailOffset);
794 while (RemainingLength > getColumnLimit()) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000795 BreakableToken::Split Split =
796 Token->getSplit(LineIndex, TailOffset, getColumnLimit());
797 if (Split.first == StringRef::npos)
798 break;
799 assert(Split.first != 0);
Alexander Kornienko919398b2013-04-17 17:34:05 +0000800 unsigned NewRemainingLength = Token->getLineLengthAfterSplit(
801 LineIndex, TailOffset + Split.first + Split.second);
802 if (NewRemainingLength >= RemainingLength)
803 break;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000804 if (!DryRun) {
805 Token->insertBreak(LineIndex, TailOffset, Split, Line.InPPDirective,
806 Whitespaces);
807 }
808 TailOffset += Split.first + Split.second;
Alexander Kornienkoe2657dd2013-04-15 15:47:34 +0000809 RemainingLength = NewRemainingLength;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000810 Penalty += Style.PenaltyExcessCharacter;
811 BreakInserted = true;
Manuel Klimek8092a942013-02-20 10:15:13 +0000812 }
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000813 State.Column = RemainingLength;
814 if (!DryRun) {
815 Token->trimLine(LineIndex, TailOffset, Line.InPPDirective, Whitespaces);
816 }
817 }
818
819 if (BreakInserted) {
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000820 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
821 State.Stack[i].BreakBeforeParameter = true;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000822 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek8092a942013-02-20 10:15:13 +0000823 }
Manuel Klimek8092a942013-02-20 10:15:13 +0000824 return Penalty;
825 }
826
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000827 unsigned getColumnLimit() {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000828 // In preprocessor directives reserve two chars for trailing " \"
829 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000830 }
831
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000832 /// \brief An edge in the solution space from \c Previous->State to \c State,
833 /// inserting a newline dependent on the \c NewLine.
834 struct StateNode {
835 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +0000836 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000837 LineState State;
838 bool NewLine;
839 StateNode *Previous;
840 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000841
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000842 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
843 ///
844 /// In case of equal penalties, we want to prefer states that were inserted
845 /// first. During state generation we make sure that we insert states first
846 /// that break the line as late as possible.
847 typedef std::pair<unsigned, unsigned> OrderedPenalty;
848
849 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
850 /// \c State has the given \c OrderedPenalty.
851 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
852
853 /// \brief The BFS queue type.
854 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
855 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000856
857 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000858 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000859 /// This implements a variant of Dijkstra's algorithm on the graph that spans
860 /// the solution space (\c LineStates are the nodes). The algorithm tries to
861 /// find the shortest path (the one with lowest penalty) from \p InitialState
862 /// to a state where all tokens are placed.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000863 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000864 std::set<LineState> Seen;
865
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000866 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +0000867 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000868 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
869 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
870 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000871
872 // While not empty, take first element and follow edges.
873 while (!Queue.empty()) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000874 unsigned Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +0000875 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000876 if (Node->State.NextToken == NULL) {
Alexander Kornienkodd256312013-05-10 11:56:10 +0000877 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000878 break;
Daniel Jasper01786732013-02-04 07:21:18 +0000879 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000880 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000881
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000882 if (!Seen.insert(Node->State).second)
883 // State already examined with lower penalty.
884 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000885
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000886 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
887 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000888 }
889
890 if (Queue.empty())
891 // We were unable to find a solution, do nothing.
892 // FIXME: Add diagnostic?
Daniel Jasperbac016b2012-12-03 18:12:45 +0000893 return 0;
894
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000895 // Reconstruct the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000896 reconstructPath(InitialState, Queue.top().second);
Alexander Kornienkodd256312013-05-10 11:56:10 +0000897 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
898 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasperbac016b2012-12-03 18:12:45 +0000899
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000900 // Return the column after the last token of the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000901 return Queue.top().second->State.Column;
902 }
903
904 void reconstructPath(LineState &State, StateNode *Current) {
905 // FIXME: This recursive implementation limits the possible number
906 // of tokens per line if compiled into a binary with small stack space.
907 // To become more independent of stack frame limitations we would need
908 // to also change the TokenAnnotator.
909 if (Current->Previous == NULL)
910 return;
911 reconstructPath(State, Current->Previous);
912 DEBUG({
913 if (Current->NewLine) {
Alexander Kornienkodd256312013-05-10 11:56:10 +0000914 llvm::dbgs()
Daniel Jaspera03ab102013-02-13 20:33:44 +0000915 << "Penalty for splitting before "
916 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
917 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000918 }
919 });
920 addTokenToState(Current->NewLine, false, State);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000921 }
922
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000923 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000924 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000925 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000926 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000927 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
928 bool NewLine) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000929 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000930 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000931 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000932 return;
Daniel Jasperae8699b2013-01-28 09:35:24 +0000933 if (NewLine)
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000934 Penalty += PreviousNode->State.NextToken->SplitPenalty;
935
936 StateNode *Node = new (Allocator.Allocate())
937 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek8092a942013-02-20 10:15:13 +0000938 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000939 if (Node->State.Column > getColumnLimit()) {
940 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper01786732013-02-04 07:21:18 +0000941 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000942 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000943
944 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
945 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000946 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000947
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000948 /// \brief Returns \c true, if a line break after \p State is allowed.
949 bool canBreak(const LineState &State) {
950 if (!State.NextToken->CanBreakBefore &&
951 !(State.NextToken->is(tok::r_brace) &&
952 State.Stack.back().BreakBeforeClosingBrace))
953 return false;
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000954 return !State.Stack.back().NoLineBreak;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000955 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000956
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000957 /// \brief Returns \c true, if a line break after \p State is mandatory.
958 bool mustBreak(const LineState &State) {
Daniel Jasper11e13802013-05-08 14:12:04 +0000959 const AnnotatedToken &Current = *State.NextToken;
960 const AnnotatedToken &Previous = *Current.Parent;
961 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000962 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +0000963 if (Current.is(tok::r_brace) && State.Stack.back().BreakBeforeClosingBrace)
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000964 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +0000965 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000966 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +0000967 if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) ||
968 Current.Type == TT_ConditionalExpr) &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000969 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper11e13802013-05-08 14:12:04 +0000970 !Current.isTrailingComment() &&
971 !Current.isOneOf(tok::r_paren, tok::r_brace))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000972 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +0000973
974 // If we need to break somewhere inside the LHS of a binary expression, we
975 // should also break after the operator.
976 if (Previous.Type == TT_BinaryOperator &&
977 !Previous.isOneOf(tok::lessless, tok::question) &&
978 getPrecedence(Previous) != prec::Assignment &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000979 State.Stack.back().BreakBeforeParameter)
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000980 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +0000981
982 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
983 // out whether it is the first parameter. Clean this up.
984 if (Current.Type == TT_ObjCSelectorName &&
985 Current.LongestObjCSelectorName == 0 &&
986 State.Stack.back().BreakBeforeParameter)
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000987 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +0000988 if ((Current.Type == TT_CtorInitializerColon ||
989 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0)))
Daniel Jasper923ebef2013-03-14 13:45:21 +0000990 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +0000991
Daniel Jasper3af59ce2013-03-15 14:57:30 +0000992 // This prevents breaks like:
993 // ...
994 // SomeParameter, OtherParameter).DoSomething(
995 // ...
996 // As they hide "DoSomething" and generally bad for readability.
Daniel Jasper11e13802013-05-08 14:12:04 +0000997 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasper3af59ce2013-03-15 14:57:30 +0000998 getRemainingLength(State) + State.Column > getColumnLimit() &&
999 State.ParenLevel < State.StartOfLineLevel)
1000 return true;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001001 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001002 }
1003
Daniel Jasper3af59ce2013-03-15 14:57:30 +00001004 // Returns the total number of columns required for the remaining tokens.
1005 unsigned getRemainingLength(const LineState &State) {
1006 if (State.NextToken && State.NextToken->Parent)
1007 return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
1008 return 0;
1009 }
1010
Daniel Jasperbac016b2012-12-03 18:12:45 +00001011 FormatStyle Style;
1012 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +00001013 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001014 const unsigned FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001015 const AnnotatedToken &RootToken;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001016 WhitespaceManager &Whitespaces;
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001017
1018 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1019 QueueType Queue;
1020 // Increasing count of \c StateNode items we have created. This is used
1021 // to create a deterministic order independent of the container.
1022 unsigned Count;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001023};
1024
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001025class LexerBasedFormatTokenSource : public FormatTokenSource {
1026public:
1027 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +00001028 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001029 IdentTable(Lex.getLangOpts()) {
1030 Lex.SetKeepWhitespaceMode(true);
1031 }
1032
1033 virtual FormatToken getNextToken() {
1034 if (GreaterStashed) {
1035 FormatTok.NewlinesBefore = 0;
1036 FormatTok.WhiteSpaceStart =
1037 FormatTok.Tok.getLocation().getLocWithOffset(1);
1038 FormatTok.WhiteSpaceLength = 0;
1039 GreaterStashed = false;
1040 return FormatTok;
1041 }
1042
1043 FormatTok = FormatToken();
1044 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001045 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001046 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +00001047 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1048 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001049
1050 // Consume and record whitespace until we find a significant token.
1051 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka28fc062013-02-11 12:33:24 +00001052 unsigned Newlines = Text.count('\n');
Daniel Jasper1eee6c42013-03-04 13:43:19 +00001053 if (Newlines > 0)
1054 FormatTok.LastNewlineOffset =
1055 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
Manuel Klimeka28fc062013-02-11 12:33:24 +00001056 unsigned EscapedNewlines = Text.count("\\\n");
1057 FormatTok.NewlinesBefore += Newlines;
1058 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001059 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1060
1061 if (FormatTok.Tok.is(tok::eof))
1062 return FormatTok;
1063 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001064 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001065 }
Manuel Klimek95419382013-01-07 07:56:50 +00001066
1067 // Now FormatTok is the next non-whitespace token.
1068 FormatTok.TokenLength = Text.size();
1069
Alexander Kornienko919398b2013-04-17 17:34:05 +00001070 if (FormatTok.Tok.is(tok::comment)) {
1071 FormatTok.TrailingWhiteSpaceLength = Text.size() - Text.rtrim().size();
1072 FormatTok.TokenLength -= FormatTok.TrailingWhiteSpaceLength;
1073 }
1074
Manuel Klimekd4397b92013-01-04 23:34:14 +00001075 // In case the token starts with escaped newlines, we want to
1076 // take them into account as whitespace - this pattern is quite frequent
1077 // in macro definitions.
1078 // FIXME: What do we want to do with other escaped spaces, and escaped
1079 // spaces or newlines in the middle of tokens?
1080 // FIXME: Add a more explicit test.
1081 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +00001082 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek86721d22013-01-22 16:31:55 +00001083 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimekd4397b92013-01-04 23:34:14 +00001084 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +00001085 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +00001086 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001087 }
1088
1089 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001090 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001091 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001092 FormatTok.Tok.setKind(Info.getTokenID());
1093 }
1094
1095 if (FormatTok.Tok.is(tok::greatergreater)) {
1096 FormatTok.Tok.setKind(tok::greater);
Daniel Jasperb6f02f32013-02-28 10:06:05 +00001097 FormatTok.TokenLength = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001098 GreaterStashed = true;
1099 }
1100
1101 return FormatTok;
1102 }
1103
Nico Weberc2e6d2a2013-02-11 15:32:15 +00001104 IdentifierTable &getIdentTable() { return IdentTable; }
1105
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001106private:
1107 FormatToken FormatTok;
1108 bool GreaterStashed;
1109 Lexer &Lex;
1110 SourceManager &SourceMgr;
1111 IdentifierTable IdentTable;
1112
1113 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +00001114 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001115 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1116 Tok.getLength());
1117 }
1118};
1119
Daniel Jasperbac016b2012-12-03 18:12:45 +00001120class Formatter : public UnwrappedLineConsumer {
1121public:
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001122 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1123 SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001124 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001125 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko052685c2013-03-19 17:41:36 +00001126 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +00001127
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001128 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001129
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001130 tooling::Replacements format() {
1131 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
1132 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Manuel Klimek67d080d2013-04-12 14:13:36 +00001133 bool StructuralError = Parser.parse();
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001134 unsigned PreviousEndOfLineColumn = 0;
1135 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1136 Tokens.getIdentTable().get("in"));
1137 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1138 Annotator.annotate(AnnotatedLines[i]);
1139 }
1140 deriveLocalStyle();
1141 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1142 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1143 }
Daniel Jasper5999f762013-04-09 17:46:55 +00001144
1145 // Adapt level to the next line if this is a comment.
1146 // FIXME: Can/should this be done in the UnwrappedLineParser?
Daniel Jasper1407bee2013-04-11 14:29:13 +00001147 const AnnotatedLine *NextNoneCommentLine = NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +00001148 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
1149 if (NextNoneCommentLine && AnnotatedLines[i].First.is(tok::comment) &&
1150 AnnotatedLines[i].First.Children.empty())
1151 AnnotatedLines[i].Level = NextNoneCommentLine->Level;
1152 else
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001153 NextNoneCommentLine =
1154 AnnotatedLines[i].First.isNot(tok::r_brace) ? &AnnotatedLines[i]
1155 : NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +00001156 }
1157
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001158 std::vector<int> IndentForLevel;
1159 bool PreviousLineWasTouched = false;
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001160 const AnnotatedToken *PreviousLineLastToken = 0;
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001161 bool FormatPPDirective = false;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001162 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1163 E = AnnotatedLines.end();
1164 I != E; ++I) {
1165 const AnnotatedLine &TheLine = *I;
1166 const FormatToken &FirstTok = TheLine.First.FormatTok;
1167 int Offset = getIndentOffset(TheLine.First);
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001168
1169 // Check whether this line is part of a formatted preprocessor directive.
1170 if (FirstTok.HasUnescapedNewline)
1171 FormatPPDirective = false;
1172 if (!FormatPPDirective && TheLine.InPPDirective &&
1173 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
1174 FormatPPDirective = true;
1175
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001176 while (IndentForLevel.size() <= TheLine.Level)
1177 IndentForLevel.push_back(-1);
1178 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasperf9955d32013-03-20 12:37:50 +00001179 bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001180 if (TheLine.First.is(tok::eof)) {
1181 if (PreviousLineWasTouched) {
1182 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1183 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
Alexander Kornienko052685c2013-03-19 17:41:36 +00001184 /*WhitespaceStartColumn*/ 0);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001185 }
1186 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001187 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001188 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
1189 unsigned Indent = LevelIndent;
1190 if (static_cast<int>(Indent) + Offset >= 0)
1191 Indent += Offset;
Manuel Klimek67d080d2013-04-12 14:13:36 +00001192 if (FirstTok.WhiteSpaceStart.isValid() &&
1193 // Insert a break even if there is a structural error in case where
1194 // we break apart a line consisting of multiple unwrapped lines.
1195 (FirstTok.NewlinesBefore == 0 || !StructuralError)) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001196 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1197 TheLine.InPPDirective, PreviousEndOfLineColumn);
Manuel Klimek67d080d2013-04-12 14:13:36 +00001198 } else {
1199 Indent = LevelIndent =
1200 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001201 }
1202 tryFitMultipleLinesInOne(Indent, I, E);
1203 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Manuel Klimek67d080d2013-04-12 14:13:36 +00001204 TheLine.First, Whitespaces);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001205 PreviousEndOfLineColumn =
1206 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1207 IndentForLevel[TheLine.Level] = LevelIndent;
1208 PreviousLineWasTouched = true;
1209 } else {
1210 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
1211 unsigned Indent =
1212 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
1213 unsigned LevelIndent = Indent;
1214 if (static_cast<int>(LevelIndent) - Offset >= 0)
1215 LevelIndent -= Offset;
Daniel Jasper83a90e52013-03-20 14:31:47 +00001216 if (TheLine.First.isNot(tok::comment))
1217 IndentForLevel[TheLine.Level] = LevelIndent;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001218
1219 // Remove trailing whitespace of the previous line if it was touched.
1220 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001221 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1222 TheLine.InPPDirective, PreviousEndOfLineColumn);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001223 }
1224 // If we did not reformat this unwrapped line, the column at the end of
1225 // the last token is unchanged - thus, we can calculate the end of the
1226 // last token.
1227 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1228 PreviousEndOfLineColumn =
1229 SourceMgr.getSpellingColumnNumber(LastLoc) +
1230 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1231 PreviousLineWasTouched = false;
Daniel Jasperc363dbb2013-03-22 16:25:51 +00001232 if (TheLine.Last->is(tok::comment))
Daniel Jasper11e13802013-05-08 14:12:04 +00001233 Whitespaces.addUntouchableComment(
1234 SourceMgr.getSpellingColumnNumber(
1235 TheLine.Last->FormatTok.Tok.getLocation()) -
1236 1);
Daniel Jasperaf849762013-04-24 06:33:59 +00001237 else
1238 Whitespaces.alignComments();
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001239 }
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001240 PreviousLineLastToken = I->Last;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001241 }
1242 return Whitespaces.generateReplacements();
1243 }
1244
1245private:
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001246 void deriveLocalStyle() {
1247 unsigned CountBoundToVariable = 0;
1248 unsigned CountBoundToType = 0;
1249 bool HasCpp03IncompatibleFormat = false;
1250 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1251 if (AnnotatedLines[i].First.Children.empty())
1252 continue;
1253 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1254 while (!Tok->Children.empty()) {
1255 if (Tok->Type == TT_PointerOrReference) {
1256 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1257 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1258 if (SpacesBefore && !SpacesAfter)
1259 ++CountBoundToVariable;
1260 else if (!SpacesBefore && SpacesAfter)
1261 ++CountBoundToType;
1262 }
1263
Daniel Jasper29f123b2013-02-08 15:28:42 +00001264 if (Tok->Type == TT_TemplateCloser &&
1265 Tok->Parent->Type == TT_TemplateCloser &&
1266 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001267 HasCpp03IncompatibleFormat = true;
1268 Tok = &Tok->Children[0];
1269 }
1270 }
1271 if (Style.DerivePointerBinding) {
1272 if (CountBoundToType > CountBoundToVariable)
1273 Style.PointerBindsToType = true;
1274 else if (CountBoundToType < CountBoundToVariable)
1275 Style.PointerBindsToType = false;
1276 }
1277 if (Style.Standard == FormatStyle::LS_Auto) {
1278 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1279 : FormatStyle::LS_Cpp03;
1280 }
1281 }
1282
Manuel Klimek547d5db2013-02-08 17:38:27 +00001283 /// \brief Get the indent of \p Level from \p IndentForLevel.
1284 ///
1285 /// \p IndentForLevel must contain the indent for the level \c l
1286 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1287 /// that level is unknown.
Daniel Jasperfc759082013-02-14 14:26:07 +00001288 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimek547d5db2013-02-08 17:38:27 +00001289 if (IndentForLevel[Level] != -1)
1290 return IndentForLevel[Level];
Manuel Klimek52635ff2013-02-08 19:53:32 +00001291 if (Level == 0)
1292 return 0;
Manuel Klimek07a64ec2013-05-13 08:42:42 +00001293 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimek547d5db2013-02-08 17:38:27 +00001294 }
1295
1296 /// \brief Get the offset of the line relatively to the level.
1297 ///
1298 /// For example, 'public:' labels in classes are offset by 1 or 2
1299 /// characters to the left from their level.
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001300 int getIndentOffset(const AnnotatedToken &RootToken) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001301 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimek547d5db2013-02-08 17:38:27 +00001302 return Style.AccessModifierOffset;
1303 return 0;
1304 }
1305
Manuel Klimek517e8942013-01-11 17:54:10 +00001306 /// \brief Tries to merge lines into one.
1307 ///
1308 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1309 /// if possible; note that \c I will be incremented when lines are merged.
1310 ///
1311 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001312 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +00001313 std::vector<AnnotatedLine>::iterator &I,
1314 std::vector<AnnotatedLine>::iterator E) {
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001315 // We can never merge stuff if there are trailing line comments.
1316 if (I->Last->Type == TT_LineComment)
1317 return;
1318
Daniel Jaspera4d46212013-02-28 11:05:57 +00001319 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001320 // If we already exceed the column limit, we set 'Limit' to 0. The different
1321 // tryMerge..() functions can then decide whether to still do merging.
1322 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001323
Daniel Jasper9c8c40e2013-01-21 14:18:28 +00001324 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001325 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001326
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001327 if (I->Last->is(tok::l_brace)) {
1328 tryMergeSimpleBlock(I, E, Limit);
1329 } else if (I->First.is(tok::kw_if)) {
1330 tryMergeSimpleIf(I, E, Limit);
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001331 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1332 I->First.FormatTok.IsFirst)) {
1333 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001334 }
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001335 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001336 }
1337
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001338 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1339 std::vector<AnnotatedLine>::iterator E,
1340 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001341 if (Limit == 0)
1342 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001343 AnnotatedLine &Line = *I;
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001344 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1345 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001346 if (I + 2 != E && (I + 2)->InPPDirective &&
1347 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1348 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001349 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001350 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001351 join(Line, *(++I));
1352 }
1353
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001354 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1355 std::vector<AnnotatedLine>::iterator E,
1356 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001357 if (Limit == 0)
1358 return;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +00001359 if (!Style.AllowShortIfStatementsOnASingleLine)
1360 return;
Manuel Klimek4c128122013-01-18 14:46:43 +00001361 if ((I + 1)->InPPDirective != I->InPPDirective ||
1362 ((I + 1)->InPPDirective &&
1363 (I + 1)->First.FormatTok.HasUnescapedNewline))
1364 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001365 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001366 if (Line.Last->isNot(tok::r_paren))
1367 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001368 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001369 return;
1370 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1371 return;
1372 // Only inline simple if's (no nested if or else).
1373 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1374 return;
1375 join(Line, *(++I));
1376 }
1377
1378 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001379 std::vector<AnnotatedLine>::iterator E,
1380 unsigned Limit) {
Manuel Klimek517e8942013-01-11 17:54:10 +00001381 // First, check that the current line allows merging. This is the case if
1382 // we're not in a control flow statement and the last token is an opening
1383 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001384 AnnotatedLine &Line = *I;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001385 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1386 tok::kw_else, tok::kw_try, tok::kw_catch,
1387 tok::kw_for,
1388 // This gets rid of all ObjC @ keywords and methods.
1389 tok::at, tok::minus, tok::plus))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001390 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001391
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001392 AnnotatedToken *Tok = &(I + 1)->First;
1393 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasperf11a7052013-02-21 21:33:55 +00001394 !Tok->MustBreakBefore) {
1395 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jasper729a7432013-02-11 12:36:37 +00001396 Tok->SpacesRequiredBefore = 0;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001397 Tok->CanBreakBefore = true;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001398 join(Line, *(I + 1));
1399 I += 1;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001400 } else if (Limit != 0) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001401 // Check that we still have three lines and they fit into the limit.
1402 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1403 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001404 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001405
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001406 // Second, check that the next line does not contain any braces - if it
1407 // does, readability declines when putting it into a single line.
1408 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1409 return;
1410 do {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001411 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001412 return;
1413 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1414 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001415
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001416 // Last, check that the third line contains a single closing brace.
1417 Tok = &(I + 2)->First;
1418 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1419 Tok->MustBreakBefore)
1420 return;
1421
1422 join(Line, *(I + 1));
1423 join(Line, *(I + 2));
1424 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +00001425 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001426 }
1427
1428 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1429 unsigned Limit) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001430 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1431 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001432 }
1433
Daniel Jasper995e8202013-01-14 13:08:07 +00001434 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001435 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasper995e8202013-01-14 13:08:07 +00001436 A.Last->Children.push_back(B.First);
1437 while (!A.Last->Children.empty()) {
1438 A.Last->Children[0].Parent = A.Last;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001439 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasper995e8202013-01-14 13:08:07 +00001440 A.Last = &A.Last->Children[0];
1441 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001442 }
1443
Daniel Jasper6f21a982013-03-13 07:49:51 +00001444 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf3023542013-03-07 20:50:00 +00001445 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1446 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1447 Ranges[i].getBegin()) &&
1448 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1449 Range.getBegin()))
1450 return true;
1451 }
1452 return false;
1453 }
1454
1455 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001456 const FormatToken *First = &TheLine.First.FormatTok;
1457 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jaspercd162382013-01-07 13:26:07 +00001458 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper1eee6c42013-03-04 13:43:19 +00001459 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
1460 Last->Tok.getLocation());
Daniel Jasperf3023542013-03-07 20:50:00 +00001461 return touchesRanges(LineRange);
1462 }
1463
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001464 bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I,
1465 std::vector<AnnotatedLine>::iterator E) {
1466 for (; I != E; ++I) {
1467 if (I->First.FormatTok.HasUnescapedNewline)
1468 return false;
1469 if (touchesLine(*I))
1470 return true;
1471 }
1472 return false;
1473 }
1474
Daniel Jasperf3023542013-03-07 20:50:00 +00001475 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1476 const FormatToken *First = &TheLine.First.FormatTok;
1477 CharSourceRange LineRange = CharSourceRange::getCharRange(
1478 First->WhiteSpaceStart,
1479 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1480 return touchesRanges(LineRange);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001481 }
1482
1483 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +00001484 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001485 }
1486
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001487 /// \brief Add a new line and the required indent before the first Token
1488 /// of the \c UnwrappedLine if there was no structural parsing error.
1489 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001490 void formatFirstToken(const AnnotatedToken &RootToken,
1491 const AnnotatedToken *PreviousToken, unsigned Indent,
Manuel Klimek547d5db2013-02-08 17:38:27 +00001492 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001493 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001494
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001495 unsigned Newlines =
1496 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001497 if (Newlines == 0 && !Tok.IsFirst)
1498 Newlines = 1;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001499
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001500 if (!InPPDirective || Tok.HasUnescapedNewline) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001501 // Insert extra new line before access specifiers.
1502 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
1503 RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1)
1504 ++Newlines;
1505
Alexander Kornienko052685c2013-03-19 17:41:36 +00001506 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001507 } else {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001508 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
Alexander Kornienko052685c2013-03-19 17:41:36 +00001509 PreviousEndOfLineColumn);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001510 }
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001511 }
1512
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001513 DiagnosticsEngine &Diag;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001514 FormatStyle Style;
1515 Lexer &Lex;
1516 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001517 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001518 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001519 std::vector<AnnotatedLine> AnnotatedLines;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001520};
1521
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001522tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1523 SourceManager &SourceMgr,
1524 std::vector<CharSourceRange> Ranges,
1525 DiagnosticConsumer *DiagClient) {
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001526 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001527 OwningPtr<DiagnosticConsumer> DiagPrinter;
1528 if (DiagClient == 0) {
1529 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1530 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1531 DiagClient = DiagPrinter.get();
1532 }
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001533 DiagnosticsEngine Diagnostics(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001534 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001535 DiagClient, false);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001536 Diagnostics.setSourceManager(&SourceMgr);
1537 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001538 return formatter.format();
1539}
1540
Daniel Jasper46ef8522013-01-10 13:08:12 +00001541LangOptions getFormattingLangOpts() {
1542 LangOptions LangOpts;
1543 LangOpts.CPlusPlus = 1;
1544 LangOpts.CPlusPlus11 = 1;
Daniel Jasperb64eca02013-03-22 10:01:29 +00001545 LangOpts.LineComment = 1;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001546 LangOpts.Bool = 1;
1547 LangOpts.ObjC1 = 1;
1548 LangOpts.ObjC2 = 1;
1549 return LangOpts;
1550}
1551
Daniel Jaspercd162382013-01-07 13:26:07 +00001552} // namespace format
1553} // namespace clang