blob: c126249ef8672fc8ed39090da70fd3e546140cbc [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"
Daniel Jasper8a999452013-05-16 10:40:07 +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"
Daniel Jasperbac016b2012-12-03 18:12:45 +000026#include "clang/Lex/Lexer.h"
Alexander Kornienko5262dd92013-03-27 11:52:18 +000027#include "llvm/ADT/STLExtras.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000028#include "llvm/Support/Allocator.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000029#include "llvm/Support/Debug.h"
Alexander Kornienkod71ec162013-05-07 15:32:14 +000030#include "llvm/Support/YAMLTraits.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000031#include <queue>
Daniel Jasper8822d3a2012-12-04 13:02:32 +000032#include <string>
33
Alexander Kornienkod71ec162013-05-07 15:32:14 +000034namespace llvm {
35namespace yaml {
36template <>
37struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> {
Manuel Klimek44135b82013-05-13 12:51:40 +000038 static void enumeration(IO &IO,
39 clang::format::FormatStyle::LanguageStandard &Value) {
40 IO.enumCase(Value, "C++03", clang::format::FormatStyle::LS_Cpp03);
41 IO.enumCase(Value, "C++11", clang::format::FormatStyle::LS_Cpp11);
42 IO.enumCase(Value, "Auto", clang::format::FormatStyle::LS_Auto);
43 }
44};
45
Daniel Jasper1fb8d882013-05-14 09:30:02 +000046template <>
Manuel Klimek44135b82013-05-13 12:51:40 +000047struct ScalarEnumerationTraits<clang::format::FormatStyle::BraceBreakingStyle> {
48 static void
49 enumeration(IO &IO, clang::format::FormatStyle::BraceBreakingStyle &Value) {
50 IO.enumCase(Value, "Attach", clang::format::FormatStyle::BS_Attach);
51 IO.enumCase(Value, "Linux", clang::format::FormatStyle::BS_Linux);
52 IO.enumCase(Value, "Stroustrup", clang::format::FormatStyle::BS_Stroustrup);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000053 }
54};
55
56template <> struct MappingTraits<clang::format::FormatStyle> {
57 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
Alexander Kornienkodd256312013-05-10 11:56:10 +000058 if (IO.outputting()) {
59 StringRef StylesArray[] = { "LLVM", "Google", "Chromium", "Mozilla" };
60 ArrayRef<StringRef> Styles(StylesArray);
61 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
62 StringRef StyleName(Styles[i]);
Alexander Kornienko885f87b2013-05-19 00:53:30 +000063 clang::format::FormatStyle PredefinedStyle;
64 if (clang::format::getPredefinedStyle(StyleName, &PredefinedStyle) &&
65 Style == PredefinedStyle) {
Alexander Kornienkodd256312013-05-10 11:56:10 +000066 IO.mapOptional("# BasedOnStyle", StyleName);
67 break;
68 }
69 }
70 } else {
Alexander Kornienkod71ec162013-05-07 15:32:14 +000071 StringRef BasedOnStyle;
72 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000073 if (!BasedOnStyle.empty())
Alexander Kornienko885f87b2013-05-19 00:53:30 +000074 if (!clang::format::getPredefinedStyle(BasedOnStyle, &Style)) {
75 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
76 return;
77 }
Alexander Kornienkod71ec162013-05-07 15:32:14 +000078 }
79
80 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
81 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
82 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
83 Style.AllowAllParametersOfDeclarationOnNextLine);
84 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
85 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasperf11bbb92013-05-16 12:12:21 +000086 IO.mapOptional("AllowShortLoopsOnASingleLine",
87 Style.AllowShortLoopsOnASingleLine);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000088 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
89 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
90 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
91 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
92 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
93 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
94 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
95 IO.mapOptional("ObjCSpaceBeforeProtocolList",
96 Style.ObjCSpaceBeforeProtocolList);
97 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
98 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
99 Style.PenaltyReturnTypeOnItsOwnLine);
100 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
101 IO.mapOptional("SpacesBeforeTrailingComments",
102 Style.SpacesBeforeTrailingComments);
Daniel Jasper1bee0732013-05-23 18:05:18 +0000103 IO.mapOptional("SpacesInBracedLists", Style.SpacesInBracedLists);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000104 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000105 IO.mapOptional("IndentWidth", Style.IndentWidth);
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000106 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimek44135b82013-05-13 12:51:40 +0000107 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000108 }
109};
110}
111}
112
Daniel Jasperbac016b2012-12-03 18:12:45 +0000113namespace clang {
114namespace format {
115
Daniel Jasperbac016b2012-12-03 18:12:45 +0000116FormatStyle getLLVMStyle() {
117 FormatStyle LLVMStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000118 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000119 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasperf1579602013-01-29 16:03:49 +0000120 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000121 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000122 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000123 LLVMStyle.BinPackParameters = true;
124 LLVMStyle.ColumnLimit = 80;
125 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
126 LLVMStyle.DerivePointerBinding = false;
127 LLVMStyle.IndentCaseLabels = false;
128 LLVMStyle.MaxEmptyLinesToKeep = 1;
Nico Weber5f500df2013-01-10 20:12:55 +0000129 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper01786732013-02-04 07:21:18 +0000130 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper1407bee2013-04-11 14:29:13 +0000131 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 75;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000132 LLVMStyle.PointerBindsToType = false;
133 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper2424eef2013-05-23 10:15:45 +0000134 LLVMStyle.SpacesInBracedLists = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000135 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000136 LLVMStyle.IndentWidth = 2;
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000137 LLVMStyle.UseTab = false;
Manuel Klimek44135b82013-05-13 12:51:40 +0000138 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000139 return LLVMStyle;
140}
141
142FormatStyle getGoogleStyle() {
143 FormatStyle GoogleStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000144 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000145 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000146 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000147 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper1bee0732013-05-23 18:05:18 +0000148 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000149 GoogleStyle.BinPackParameters = true;
150 GoogleStyle.ColumnLimit = 80;
151 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
152 GoogleStyle.DerivePointerBinding = true;
153 GoogleStyle.IndentCaseLabels = true;
154 GoogleStyle.MaxEmptyLinesToKeep = 1;
Nico Weber5f500df2013-01-10 20:12:55 +0000155 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper01786732013-02-04 07:21:18 +0000156 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper1407bee2013-04-11 14:29:13 +0000157 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000158 GoogleStyle.PointerBindsToType = true;
159 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper2424eef2013-05-23 10:15:45 +0000160 GoogleStyle.SpacesInBracedLists = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000161 GoogleStyle.Standard = FormatStyle::LS_Auto;
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000162 GoogleStyle.IndentWidth = 2;
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000163 GoogleStyle.UseTab = false;
Manuel Klimek44135b82013-05-13 12:51:40 +0000164 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000165 return GoogleStyle;
166}
167
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000168FormatStyle getChromiumStyle() {
169 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +0000170 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000171 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000172 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000173 ChromiumStyle.BinPackParameters = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000174 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
175 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000176 return ChromiumStyle;
177}
178
Alexander Kornienkofb594862013-05-06 14:11:27 +0000179FormatStyle getMozillaStyle() {
180 FormatStyle MozillaStyle = getLLVMStyle();
181 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
182 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
183 MozillaStyle.DerivePointerBinding = true;
184 MozillaStyle.IndentCaseLabels = true;
185 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
186 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
187 MozillaStyle.PointerBindsToType = true;
188 return MozillaStyle;
189}
190
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000191bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000192 if (Name.equals_lower("llvm"))
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000193 *Style = getLLVMStyle();
194 else if (Name.equals_lower("chromium"))
195 *Style = getChromiumStyle();
196 else if (Name.equals_lower("mozilla"))
197 *Style = getMozillaStyle();
198 else if (Name.equals_lower("google"))
199 *Style = getGoogleStyle();
200 else
201 return false;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000202
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000203 return true;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000204}
205
206llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienko107db3c2013-05-20 15:18:01 +0000207 if (Text.trim().empty())
208 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000209 llvm::yaml::Input Input(Text);
210 Input >> *Style;
211 return Input.error();
212}
213
214std::string configurationAsText(const FormatStyle &Style) {
215 std::string Text;
216 llvm::raw_string_ostream Stream(Text);
217 llvm::yaml::Output Output(Stream);
218 // We use the same mapping method for input and output, so we need a non-const
219 // reference here.
220 FormatStyle NonConstStyle = Style;
221 Output << NonConstStyle;
Alexander Kornienko2b6acb62013-05-13 12:56:35 +0000222 return Stream.str();
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000223}
224
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000225// Returns the length of everything up to the first possible line break after
226// the ), ], } or > matching \c Tok.
227static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
228 if (Tok.MatchingParen == NULL)
229 return 0;
230 AnnotatedToken *End = Tok.MatchingParen;
231 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
232 End = &End->Children[0];
233 }
234 return End->TotalLength - Tok.TotalLength + 1;
235}
236
Daniel Jasperbac016b2012-12-03 18:12:45 +0000237class UnwrappedLineFormatter {
238public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000239 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper995e8202013-01-14 13:08:07 +0000240 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000241 const AnnotatedToken &RootToken,
Manuel Klimek67d080d2013-04-12 14:13:36 +0000242 WhitespaceManager &Whitespaces)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000243 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000244 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasperf11a7052013-02-21 21:33:55 +0000245 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000246
Manuel Klimekd4397b92013-01-04 23:34:14 +0000247 /// \brief Formats an \c UnwrappedLine.
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000248 void format(const AnnotatedLine *NextLine) {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000249 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000250 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000251 State.Column = FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000252 State.NextToken = &RootToken;
Daniel Jasper6f21a982013-03-13 07:49:51 +0000253 State.Stack.push_back(
Daniel Jasper24e19e42013-05-22 08:55:55 +0000254 ParenState(FirstIndent, FirstIndent, /*AvoidBinPacking=*/ false,
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000255 /*NoLineBreak=*/ false));
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000256 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000257 State.ParenLevel = 0;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000258 State.StartOfStringLiteral = 0;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000259 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper259a0382013-05-27 11:50:16 +0000260 State.LowestLevelOnLine = State.ParenLevel;
Daniel Jasper54b4e442013-05-22 05:27:42 +0000261 State.IgnoreStackForComparison = false;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000262
263 // The first token has already been indented and thus consumed.
Manuel Klimek8092a942013-02-20 10:15:13 +0000264 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000265
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000266 // If everything fits on a single line, just put it there.
Daniel Jaspera4d46212013-02-28 11:05:57 +0000267 unsigned ColumnLimit = Style.ColumnLimit;
268 if (NextLine && NextLine->InPPDirective &&
269 !NextLine->First.FormatTok.HasUnescapedNewline)
270 ColumnLimit = getColumnLimit();
271 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000272 while (State.NextToken != NULL) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000273 addTokenToState(false, false, State);
Daniel Jasper1321eb52012-12-18 21:05:13 +0000274 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000275 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000276
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000277 // If the ObjC method declaration does not fit on a line, we should format
278 // it with one arg per line.
279 if (Line.Type == LT_ObjCMethodDecl)
280 State.Stack.back().BreakBeforeParameter = true;
281
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000282 // Find best solution in solution space.
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000283 analyzeSolutionSpace(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000284 }
285
286private:
Manuel Klimekca547db2013-01-16 14:55:28 +0000287 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
288 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Alexander Kornienkodd256312013-05-10 11:56:10 +0000289 llvm::dbgs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000290 Tok.getLength());
Alexander Kornienkodd256312013-05-10 11:56:10 +0000291 llvm::dbgs();
Manuel Klimekca547db2013-01-16 14:55:28 +0000292 }
293
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000294 struct ParenState {
Daniel Jasperd399bff2013-02-05 09:41:21 +0000295 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000296 bool NoLineBreak)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000297 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
298 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000299 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000300 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
301 NestedNameSpecifierContinuation(0), CallContinuation(0),
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000302 VariablePos(0), ForFakeParenthesis(false) {}
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000303
Daniel Jasperbac016b2012-12-03 18:12:45 +0000304 /// \brief The position to which a specific parenthesis level needs to be
305 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000306 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000307
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000308 /// \brief The position of the last space on each level.
309 ///
310 /// Used e.g. to break like:
311 /// functionCall(Parameter, otherCall(
312 /// OtherParameter));
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000313 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000314
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000315 /// \brief The position the first "<<" operator encountered on each level.
316 ///
317 /// Used to align "<<" operators. 0 if no such operator has been encountered
318 /// on a level.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000319 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000320
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000321 /// \brief Whether a newline needs to be inserted before the block's closing
322 /// brace.
323 ///
324 /// We only want to insert a newline before the closing brace if there also
325 /// was a newline after the beginning left brace.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000326 bool BreakBeforeClosingBrace;
327
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000328 /// \brief The column of a \c ? in a conditional expression;
329 unsigned QuestionColumn;
330
Daniel Jasperf343cab2013-01-31 14:59:26 +0000331 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
332 /// lines, in this context.
333 bool AvoidBinPacking;
334
335 /// \brief Break after the next comma (or all the commas in this context if
336 /// \c AvoidBinPacking is \c true).
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000337 bool BreakBeforeParameter;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000338
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000339 /// \brief Line breaking in this context would break a formatting rule.
340 bool NoLineBreak;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000341
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000342 /// \brief The position of the colon in an ObjC method declaration/call.
343 unsigned ColonPos;
Daniel Jasperc4615b72013-02-20 12:56:39 +0000344
Daniel Jasper24849712013-03-01 16:48:32 +0000345 /// \brief The start of the most recent function in a builder-type call.
346 unsigned StartOfFunctionCall;
347
Daniel Jasper37911302013-04-02 14:33:13 +0000348 /// \brief If a nested name specifier was broken over multiple lines, this
349 /// contains the start column of the second line. Otherwise 0.
350 unsigned NestedNameSpecifierContinuation;
351
352 /// \brief If a call expression was broken over multiple lines, this
353 /// contains the start column of the second line. Otherwise 0.
354 unsigned CallContinuation;
355
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000356 /// \brief The column of the first variable name in a variable declaration.
357 ///
358 /// Used to align further variables if necessary.
359 unsigned VariablePos;
360
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000361 /// \brief \c true if this \c ParenState was created for a fake parenthesis.
362 ///
363 /// Does not need to be considered for memoization / the comparison function
364 /// as otherwise identical states will have the same fake/non-fake
365 /// \c ParenStates.
366 bool ForFakeParenthesis;
367
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000368 bool operator<(const ParenState &Other) const {
369 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000370 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000371 if (LastSpace != Other.LastSpace)
372 return LastSpace < Other.LastSpace;
373 if (FirstLessLess != Other.FirstLessLess)
374 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000375 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
376 return BreakBeforeClosingBrace;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000377 if (QuestionColumn != Other.QuestionColumn)
378 return QuestionColumn < Other.QuestionColumn;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000379 if (AvoidBinPacking != Other.AvoidBinPacking)
380 return AvoidBinPacking;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000381 if (BreakBeforeParameter != Other.BreakBeforeParameter)
382 return BreakBeforeParameter;
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000383 if (NoLineBreak != Other.NoLineBreak)
384 return NoLineBreak;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000385 if (ColonPos != Other.ColonPos)
386 return ColonPos < Other.ColonPos;
Daniel Jasper24849712013-03-01 16:48:32 +0000387 if (StartOfFunctionCall != Other.StartOfFunctionCall)
388 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasper37911302013-04-02 14:33:13 +0000389 if (CallContinuation != Other.CallContinuation)
390 return CallContinuation < Other.CallContinuation;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000391 if (VariablePos != Other.VariablePos)
392 return VariablePos < Other.VariablePos;
Daniel Jasperb3123142013-01-12 07:36:22 +0000393 return false;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000394 }
395 };
396
397 /// \brief The current state when indenting a unwrapped line.
398 ///
399 /// As the indenting tries different combinations this is copied by value.
400 struct LineState {
401 /// \brief The number of used columns in the current line.
402 unsigned Column;
403
404 /// \brief The token that needs to be next formatted.
405 const AnnotatedToken *NextToken;
406
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000407 /// \brief \c true if this line contains a continued for-loop section.
408 bool LineContainsContinuedForLoopSection;
409
Daniel Jasper29f123b2013-02-08 15:28:42 +0000410 /// \brief The level of nesting inside (), [], <> and {}.
411 unsigned ParenLevel;
412
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000413 /// \brief The \c ParenLevel at the start of this line.
414 unsigned StartOfLineLevel;
415
Daniel Jasper259a0382013-05-27 11:50:16 +0000416 /// \brief The lowest \c ParenLevel on the current line.
417 unsigned LowestLevelOnLine;
418
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000419 /// \brief The start column of the string literal, if we're in a string
420 /// literal sequence, 0 otherwise.
421 unsigned StartOfStringLiteral;
422
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000423 /// \brief A stack keeping track of properties applying to parenthesis
424 /// levels.
425 std::vector<ParenState> Stack;
426
Daniel Jasper54b4e442013-05-22 05:27:42 +0000427 /// \brief Ignore the stack of \c ParenStates for state comparison.
428 ///
429 /// In long and deeply nested unwrapped lines, the current algorithm can
430 /// be insufficient for finding the best formatting with a reasonable amount
431 /// of time and memory. Setting this flag will effectively lead to the
432 /// algorithm not analyzing some combinations. However, these combinations
433 /// rarely contain the optimal solution: In short, accepting a higher
434 /// penalty early would need to lead to different values in the \c
435 /// ParenState stack (in an otherwise identical state) and these different
436 /// values would need to lead to a significant amount of avoided penalty
437 /// later.
438 ///
439 /// FIXME: Come up with a better algorithm instead.
440 bool IgnoreStackForComparison;
441
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000442 /// \brief Comparison operator to be able to used \c LineState in \c map.
443 bool operator<(const LineState &Other) const {
Daniel Jasperd7896702013-02-19 09:28:55 +0000444 if (NextToken != Other.NextToken)
445 return NextToken < Other.NextToken;
446 if (Column != Other.Column)
447 return Column < Other.Column;
Daniel Jasperd7896702013-02-19 09:28:55 +0000448 if (LineContainsContinuedForLoopSection !=
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000449 Other.LineContainsContinuedForLoopSection)
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000450 return LineContainsContinuedForLoopSection;
Daniel Jasperd7896702013-02-19 09:28:55 +0000451 if (ParenLevel != Other.ParenLevel)
452 return ParenLevel < Other.ParenLevel;
453 if (StartOfLineLevel != Other.StartOfLineLevel)
454 return StartOfLineLevel < Other.StartOfLineLevel;
Daniel Jasper259a0382013-05-27 11:50:16 +0000455 if (LowestLevelOnLine != Other.LowestLevelOnLine)
456 return LowestLevelOnLine < Other.LowestLevelOnLine;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000457 if (StartOfStringLiteral != Other.StartOfStringLiteral)
458 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper54b4e442013-05-22 05:27:42 +0000459 if (IgnoreStackForComparison || Other.IgnoreStackForComparison)
460 return false;
Daniel Jasperd7896702013-02-19 09:28:55 +0000461 return Stack < Other.Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000462 }
463 };
464
Daniel Jasper20409152012-12-04 14:54:30 +0000465 /// \brief Appends the next token to \p State and updates information
466 /// necessary for indentation.
467 ///
468 /// Puts the token on the current line if \p Newline is \c true and adds a
469 /// line break and necessary indentation otherwise.
470 ///
471 /// If \p DryRun is \c false, also creates and stores the required
472 /// \c Replacement.
Manuel Klimek8092a942013-02-20 10:15:13 +0000473 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000474 const AnnotatedToken &Current = *State.NextToken;
475 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000476
Daniel Jasper92f9faf2013-03-20 15:58:10 +0000477 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Manuel Klimekad3094b2013-05-23 10:56:37 +0000478 // FIXME: Is this correct?
479 int WhitespaceLength =
480 SourceMgr.getSpellingColumnNumber(
481 State.NextToken->FormatTok.WhitespaceRange.getEnd()) -
482 SourceMgr.getSpellingColumnNumber(
483 State.NextToken->FormatTok.WhitespaceRange.getBegin());
484 State.Column += WhitespaceLength + State.NextToken->FormatTok.TokenLength;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000485 if (State.NextToken->Children.empty())
486 State.NextToken = NULL;
487 else
488 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek8092a942013-02-20 10:15:13 +0000489 return 0;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000490 }
491
Daniel Jasper3776ef32013-04-03 07:21:51 +0000492 // If we are continuing an expression, we want to indent an extra 4 spaces.
493 unsigned ContinuationIndent =
Daniel Jasper37911302013-04-02 14:33:13 +0000494 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000495 if (Newline) {
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000496 if (Current.is(tok::r_brace)) {
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000497 State.Column = Line.Level * Style.IndentWidth;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000498 } else if (Current.is(tok::string_literal) &&
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000499 State.StartOfStringLiteral != 0) {
500 State.Column = State.StartOfStringLiteral;
Daniel Jasper66d19bd2013-02-18 11:59:17 +0000501 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000502 } else if (Current.is(tok::lessless) &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000503 State.Stack.back().FirstLessLess != 0) {
504 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasper5ad390d2013-05-28 11:30:49 +0000505 } else if (Current.isOneOf(tok::period, tok::arrow) &&
506 Current.Type != TT_DesignatedInitializerPeriod) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000507 if (State.Stack.back().CallContinuation == 0) {
508 State.Column = ContinuationIndent;
Daniel Jasper37911302013-04-02 14:33:13 +0000509 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000510 } else {
511 State.Column = State.Stack.back().CallContinuation;
512 }
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000513 } else if (Current.Type == TT_ConditionalExpr) {
514 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000515 } else if (Previous.is(tok::comma) &&
516 State.Stack.back().VariablePos != 0) {
517 State.Column = State.Stack.back().VariablePos;
Daniel Jasper3c08a812013-02-24 18:54:32 +0000518 } else if (Previous.ClosesTemplateDeclaration ||
Daniel Jasper53e72cd2013-05-06 08:27:33 +0000519 (Current.Type == TT_StartOfName && State.ParenLevel == 0 &&
520 Line.StartsDefinition)) {
Daniel Jasper37911302013-04-02 14:33:13 +0000521 State.Column = State.Stack.back().Indent;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000522 } else if (Current.Type == TT_ObjCSelectorName) {
523 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
524 State.Column =
525 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
526 } else {
527 State.Column = State.Stack.back().Indent;
528 State.Stack.back().ColonPos =
529 State.Column + Current.FormatTok.TokenLength;
530 }
Daniel Jasperb2f063a2013-05-08 10:00:18 +0000531 } else if (Current.Type == TT_StartOfName ||
532 Previous.isOneOf(tok::coloncolon, tok::equal) ||
Daniel Jasper37911302013-04-02 14:33:13 +0000533 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000534 State.Column = ContinuationIndent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000535 } else {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000536 State.Column = State.Stack.back().Indent;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000537 // Ensure that we fall back to indenting 4 spaces instead of just
538 // flushing continuations left.
Daniel Jasper37911302013-04-02 14:33:13 +0000539 if (State.Column == FirstIndent)
540 State.Column += 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000541 }
542
Daniel Jasper7878a7b2013-02-15 11:07:25 +0000543 if (Current.is(tok::question))
Daniel Jasper237d4c12013-02-23 21:01:55 +0000544 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper11e13802013-05-08 14:12:04 +0000545 if ((Previous.isOneOf(tok::comma, tok::semi) &&
546 !State.Stack.back().AvoidBinPacking) ||
547 Previous.Type == TT_BinaryOperator)
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000548 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper33f4b902013-05-15 09:35:08 +0000549 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
550 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000551
Manuel Klimek060143e2013-01-02 18:33:23 +0000552 if (!DryRun) {
Daniel Jasper1ef81d52013-02-26 13:10:34 +0000553 unsigned NewLines = 1;
554 if (Current.Type == TT_LineComment)
555 NewLines =
556 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
557 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000558 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
559 State.Column, Line.InPPDirective);
Manuel Klimek060143e2013-01-02 18:33:23 +0000560 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000561
Daniel Jasper29f123b2013-02-08 15:28:42 +0000562 State.Stack.back().LastSpace = State.Column;
Daniel Jasper5ad390d2013-05-28 11:30:49 +0000563 if (Current.isOneOf(tok::arrow, tok::period) &&
564 Current.Type != TT_DesignatedInitializerPeriod)
Daniel Jasper04abbb22013-05-10 13:37:16 +0000565 State.Stack.back().LastSpace += Current.FormatTok.TokenLength;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000566 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper259a0382013-05-27 11:50:16 +0000567 State.LowestLevelOnLine = State.ParenLevel;
Daniel Jasper237d4c12013-02-23 21:01:55 +0000568
569 // Any break on this level means that the parent level has been broken
570 // and we need to avoid bin packing there.
571 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
572 State.Stack[i].BreakBeforeParameter = true;
573 }
Daniel Jasper01218ff2013-04-15 22:36:37 +0000574 const AnnotatedToken *TokenBefore = Current.getPreviousNoneComment();
575 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
Daniel Jasper33f4b902013-05-15 09:35:08 +0000576 TokenBefore->Type != TT_TemplateCloser &&
Daniel Jasper11e13802013-05-08 14:12:04 +0000577 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000578 State.Stack.back().BreakBeforeParameter = true;
579
Daniel Jasper237d4c12013-02-23 21:01:55 +0000580 // If we break after {, we should also break before the corresponding }.
581 if (Previous.is(tok::l_brace))
582 State.Stack.back().BreakBeforeClosingBrace = true;
583
584 if (State.Stack.back().AvoidBinPacking) {
585 // If we are breaking after '(', '{', '<', this is not bin packing
586 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasperd741f022013-05-14 20:39:56 +0000587 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
588 Previous.Type == TT_BinaryOperator) ||
Daniel Jasper237d4c12013-02-23 21:01:55 +0000589 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
590 Line.MustBeDeclaration))
591 State.Stack.back().BreakBeforeParameter = true;
592 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000593 } else {
Daniel Jasper9c3e71a2013-02-25 15:59:54 +0000594 if (Current.is(tok::equal) &&
Daniel Jasperadc0f092013-04-05 09:38:50 +0000595 (RootToken.is(tok::kw_for) || State.ParenLevel == 0) &&
596 State.Stack.back().VariablePos == 0) {
597 State.Stack.back().VariablePos = State.Column;
598 // Move over * and & if they are bound to the variable name.
599 const AnnotatedToken *Tok = &Previous;
600 while (Tok &&
601 State.Stack.back().VariablePos >= Tok->FormatTok.TokenLength) {
602 State.Stack.back().VariablePos -= Tok->FormatTok.TokenLength;
603 if (Tok->SpacesRequiredBefore != 0)
604 break;
605 Tok = Tok->Parent;
606 }
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000607 if (Previous.PartOfMultiVariableDeclStmt)
608 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
609 }
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000610
Daniel Jasper729a7432013-02-11 12:36:37 +0000611 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper20409152012-12-04 14:54:30 +0000612
Daniel Jasperbac016b2012-12-03 18:12:45 +0000613 if (!DryRun)
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000614 Whitespaces.replaceWhitespace(Current, 0, Spaces,
615 State.Column + Spaces);
Daniel Jasper20409152012-12-04 14:54:30 +0000616
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000617 if (Current.Type == TT_ObjCSelectorName &&
618 State.Stack.back().ColonPos == 0) {
619 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000620 State.Column + Spaces + Current.FormatTok.TokenLength)
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000621 State.Stack.back().ColonPos =
622 State.Stack.back().Indent + Current.LongestObjCSelectorName;
623 else
624 State.Stack.back().ColonPos =
Daniel Jasper9e9e6e02013-02-06 16:00:26 +0000625 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000626 }
627
Daniel Jasperac3223e2013-04-10 09:49:49 +0000628 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000629 Current.Type != TT_LineComment)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000630 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000631 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
632 State.Stack.back().AvoidBinPacking)
633 State.Stack.back().NoLineBreak = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000634
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000635 State.Column += Spaces;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000636 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jaspere438bac2013-01-23 20:41:06 +0000637 // Treat the condition inside an if as if it was a second function
638 // parameter, i.e. let nested calls have an indent of 4.
639 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperf9955d32013-03-20 12:37:50 +0000640 else if (Previous.is(tok::comma))
Daniel Jaspere438bac2013-01-23 20:41:06 +0000641 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000642 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper02b771e2013-01-28 13:31:35 +0000643 Previous.Type == TT_ConditionalExpr ||
644 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper512843a2013-05-27 12:45:09 +0000645 !(getPrecedence(Previous) == prec::Assignment &&
646 Current.FakeLParens.empty()))
647 // Always indent relative to the RHS of the expression unless this is a
648 // simple assignment without binary expression on the RHS.
Daniel Jasperae8699b2013-01-28 09:35:24 +0000649 State.Stack.back().LastSpace = State.Column;
Daniel Jasper6cabab42013-02-14 08:42:54 +0000650 else if (Previous.Type == TT_InheritanceColon)
651 State.Stack.back().Indent = State.Column;
Daniel Jasper11e13802013-05-08 14:12:04 +0000652 else if (Previous.opensScope() && !Current.FakeLParens.empty())
653 // If this function has multiple parameters or a binary expression
654 // parameter, indent nested calls from the start of the first parameter.
Daniel Jasper986e17f2013-01-28 07:35:34 +0000655 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000656 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000657
Manuel Klimek8092a942013-02-20 10:15:13 +0000658 return moveStateToNextToken(State, DryRun);
Daniel Jasper20409152012-12-04 14:54:30 +0000659 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000660
Daniel Jasper20409152012-12-04 14:54:30 +0000661 /// \brief Mark the next token as consumed in \p State and modify its stacks
662 /// accordingly.
Manuel Klimek8092a942013-02-20 10:15:13 +0000663 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000664 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000665 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000666
Daniel Jasper6cabab42013-02-14 08:42:54 +0000667 if (Current.Type == TT_InheritanceColon)
668 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000669 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
670 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000671 if (Current.is(tok::question))
672 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000673 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasper24849712013-03-01 16:48:32 +0000674 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
675 State.Stack.back().StartOfFunctionCall =
Daniel Jasper04abbb22013-05-10 13:37:16 +0000676 Current.LastInChainOfCalls ? 0 : State.Column +
677 Current.FormatTok.TokenLength;
Daniel Jasper7d812812013-02-21 15:00:29 +0000678 if (Current.Type == TT_CtorInitializerColon) {
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000679 // Indent 2 from the column, so:
680 // SomeClass::SomeClass()
681 // : First(...), ...
682 // Next(...)
683 // ^ line up here.
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000684 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper7d812812013-02-21 15:00:29 +0000685 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
686 State.Stack.back().AvoidBinPacking = true;
687 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000688 }
Daniel Jasper3776ef32013-04-03 07:21:51 +0000689
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000690 // If return returns a binary expression, align after it.
691 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
692 State.Stack.back().LastSpace = State.Column + 7;
693
Daniel Jasper3776ef32013-04-03 07:21:51 +0000694 // In ObjC method declaration we align on the ":" of parameters, but we need
695 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasper37911302013-04-02 14:33:13 +0000696 if (Current.Type == TT_ObjCMethodSpecifier)
697 State.Stack.back().Indent += 4;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000698
Daniel Jasper29f123b2013-02-08 15:28:42 +0000699 // Insert scopes created by fake parenthesis.
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000700 const AnnotatedToken *Previous = Current.getPreviousNoneComment();
701 // Don't add extra indentation for the first fake parenthesis after
702 // 'return', assignements or opening <({[. The indentation for these cases
703 // is special cased.
704 bool SkipFirstExtraIndent =
705 Current.is(tok::kw_return) ||
Daniel Jasperac3223e2013-04-10 09:49:49 +0000706 (Previous && (Previous->opensScope() ||
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000707 getPrecedence(*Previous) == prec::Assignment));
708 for (SmallVector<prec::Level, 4>::const_reverse_iterator
709 I = Current.FakeLParens.rbegin(),
710 E = Current.FakeLParens.rend();
711 I != E; ++I) {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000712 ParenState NewParenState = State.Stack.back();
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000713 NewParenState.ForFakeParenthesis = true;
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000714 NewParenState.Indent =
715 std::max(std::max(State.Column, NewParenState.Indent),
716 State.Stack.back().LastSpace);
717
718 // Always indent conditional expressions. Never indent expression where
719 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
720 // prec::Assignment) as those have different indentation rules. Indent
721 // other expression, unless the indentation needs to be skipped.
722 if (*I == prec::Conditional ||
723 (!SkipFirstExtraIndent && *I > prec::Assignment))
724 NewParenState.Indent += 4;
Daniel Jasperac3223e2013-04-10 09:49:49 +0000725 if (Previous && !Previous->opensScope())
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000726 NewParenState.BreakBeforeParameter = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000727 State.Stack.push_back(NewParenState);
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000728 SkipFirstExtraIndent = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000729 }
730
Daniel Jaspercf225b62012-12-24 13:43:52 +0000731 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000732 // prepare for the following tokens.
Daniel Jasperac3223e2013-04-10 09:49:49 +0000733 if (Current.opensScope()) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000734 unsigned NewIndent;
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000735 unsigned LastSpace = State.Stack.back().LastSpace;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000736 bool AvoidBinPacking;
Manuel Klimek2851c162013-01-10 14:36:46 +0000737 if (Current.is(tok::l_brace)) {
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000738 NewIndent = Style.IndentWidth + LastSpace;
Daniel Jasper5ad390d2013-05-28 11:30:49 +0000739 const AnnotatedToken *NextNoComment = Current.getNextNoneComment();
740 AvoidBinPacking = NextNoComment &&
741 NextNoComment->Type == TT_DesignatedInitializerPeriod;
Manuel Klimek2851c162013-01-10 14:36:46 +0000742 } else {
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000743 NewIndent =
744 4 + std::max(LastSpace, State.Stack.back().StartOfFunctionCall);
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000745 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek2851c162013-01-10 14:36:46 +0000746 }
Daniel Jasperfca24bc2013-04-25 13:31:51 +0000747
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000748 State.Stack.push_back(ParenState(NewIndent, LastSpace, AvoidBinPacking,
749 State.Stack.back().NoLineBreak));
Daniel Jasper29f123b2013-02-08 15:28:42 +0000750 ++State.ParenLevel;
Daniel Jasper20409152012-12-04 14:54:30 +0000751 }
752
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000753 // If this '[' opens an ObjC call, determine whether all parameters fit into
754 // one line and put one per line if they don't.
755 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
756 Current.MatchingParen != NULL) {
757 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
758 State.Stack.back().BreakBeforeParameter = true;
759 }
760
Daniel Jaspercf225b62012-12-24 13:43:52 +0000761 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000762 // stacks.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000763 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +0000764 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
765 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000766 State.Stack.pop_back();
Daniel Jasper29f123b2013-02-08 15:28:42 +0000767 --State.ParenLevel;
768 }
Daniel Jasper259a0382013-05-27 11:50:16 +0000769 State.LowestLevelOnLine =
770 std::min(State.LowestLevelOnLine, State.ParenLevel);
Daniel Jasper29f123b2013-02-08 15:28:42 +0000771
772 // Remove scopes created by fake parenthesis.
773 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasperabfc9c12013-04-04 19:31:00 +0000774 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000775 State.Stack.pop_back();
Daniel Jasperabfc9c12013-04-04 19:31:00 +0000776 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000777 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000778
Daniel Jasper27c7f542013-05-13 20:50:15 +0000779 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000780 State.StartOfStringLiteral = State.Column;
Daniel Jasper27c7f542013-05-13 20:50:15 +0000781 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
782 tok::string_literal)) {
Daniel Jasper9a2f8d02013-05-16 04:26:02 +0000783 State.StartOfStringLiteral = 0;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000784 }
785
Manuel Klimek8092a942013-02-20 10:15:13 +0000786 State.Column += Current.FormatTok.TokenLength;
787
Daniel Jasper26f7e782013-01-08 14:56:18 +0000788 if (State.NextToken->Children.empty())
789 State.NextToken = NULL;
790 else
791 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek2851c162013-01-10 14:36:46 +0000792
Manuel Klimek8092a942013-02-20 10:15:13 +0000793 return breakProtrudingToken(Current, State, DryRun);
794 }
795
796 /// \brief If the current token sticks out over the end of the line, break
797 /// it if possible.
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000798 ///
799 /// \returns An extra penalty if a token was broken, otherwise 0.
800 ///
801 /// Note that the penalty of the token protruding the allowed line length is
802 /// already handled in \c addNextStateToQueue; the returned penalty will only
803 /// cover the cost of the additional line breaks.
Manuel Klimek8092a942013-02-20 10:15:13 +0000804 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000805 bool DryRun) {
806 unsigned UnbreakableTailLength = Current.UnbreakableTailLength;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000807 llvm::OwningPtr<BreakableToken> Token;
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000808 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
Manuel Klimekde008c02013-05-27 15:23:34 +0000809 unsigned OriginalStartColumn = SourceMgr.getSpellingColumnNumber(
810 Current.FormatTok.getStartOfNonWhitespace()) - 1;
811
Daniel Jasper5d5b4242013-05-16 12:59:13 +0000812 if (Current.is(tok::string_literal) &&
813 Current.Type != TT_ImplicitStringLiteral) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000814 // Only break up default narrow strings.
Alexander Kornienko919398b2013-04-17 17:34:05 +0000815 const char *LiteralData = SourceMgr.getCharacterData(
816 Current.FormatTok.getStartOfNonWhitespace());
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000817 if (!LiteralData || *LiteralData != '"')
818 return 0;
819
Manuel Klimekde008c02013-05-27 15:23:34 +0000820 Token.reset(new BreakableStringLiteral(Current.FormatTok, StartColumn));
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000821 } else if (Current.Type == TT_BlockComment) {
822 BreakableBlockComment *BBC =
Manuel Klimekde008c02013-05-27 15:23:34 +0000823 new BreakableBlockComment(Style, Current.FormatTok, StartColumn,
824 OriginalStartColumn, !Current.Parent);
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000825 Token.reset(BBC);
Daniel Jasper7ff96ed2013-05-06 10:24:51 +0000826 } else if (Current.Type == TT_LineComment &&
827 (Current.Parent == NULL ||
828 Current.Parent->Type != TT_ImplicitStringLiteral)) {
Manuel Klimekde008c02013-05-27 15:23:34 +0000829 Token.reset(new BreakableLineComment(Current.FormatTok, StartColumn));
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000830 } else {
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000831 return 0;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000832 }
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000833 if (UnbreakableTailLength >= getColumnLimit())
834 return 0;
835 unsigned RemainingSpace = getColumnLimit() - UnbreakableTailLength;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000836
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000837 bool BreakInserted = false;
838 unsigned Penalty = 0;
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000839 unsigned PositionAfterLastLineInToken = 0;
Manuel Klimekde008c02013-05-27 15:23:34 +0000840 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
841 LineIndex != EndIndex; ++LineIndex) {
842 if (!DryRun) {
843 Token->replaceWhitespaceBefore(LineIndex, Line.InPPDirective,
844 Whitespaces);
845 }
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000846 unsigned TailOffset = 0;
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000847 unsigned RemainingTokenLength =
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000848 Token->getLineLengthAfterSplit(LineIndex, TailOffset);
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000849 while (RemainingTokenLength > RemainingSpace) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000850 BreakableToken::Split Split =
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000851 Token->getSplit(LineIndex, TailOffset, getColumnLimit());
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000852 if (Split.first == StringRef::npos)
853 break;
854 assert(Split.first != 0);
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000855 unsigned NewRemainingTokenLength = Token->getLineLengthAfterSplit(
Alexander Kornienko919398b2013-04-17 17:34:05 +0000856 LineIndex, TailOffset + Split.first + Split.second);
Manuel Klimekde008c02013-05-27 15:23:34 +0000857 assert(NewRemainingTokenLength < RemainingTokenLength);
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000858 if (!DryRun) {
859 Token->insertBreak(LineIndex, TailOffset, Split, Line.InPPDirective,
860 Whitespaces);
861 }
862 TailOffset += Split.first + Split.second;
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000863 RemainingTokenLength = NewRemainingTokenLength;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000864 Penalty += Style.PenaltyExcessCharacter;
865 BreakInserted = true;
Manuel Klimek8092a942013-02-20 10:15:13 +0000866 }
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000867 PositionAfterLastLineInToken = RemainingTokenLength;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000868 }
869
870 if (BreakInserted) {
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000871 State.Column = PositionAfterLastLineInToken;
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000872 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
873 State.Stack[i].BreakBeforeParameter = true;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000874 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek8092a942013-02-20 10:15:13 +0000875 }
Manuel Klimek8092a942013-02-20 10:15:13 +0000876 return Penalty;
877 }
878
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000879 unsigned getColumnLimit() {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000880 // In preprocessor directives reserve two chars for trailing " \"
881 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000882 }
883
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000884 /// \brief An edge in the solution space from \c Previous->State to \c State,
885 /// inserting a newline dependent on the \c NewLine.
886 struct StateNode {
887 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +0000888 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000889 LineState State;
890 bool NewLine;
891 StateNode *Previous;
892 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000893
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000894 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
895 ///
896 /// In case of equal penalties, we want to prefer states that were inserted
897 /// first. During state generation we make sure that we insert states first
898 /// that break the line as late as possible.
899 typedef std::pair<unsigned, unsigned> OrderedPenalty;
900
901 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
902 /// \c State has the given \c OrderedPenalty.
903 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
904
905 /// \brief The BFS queue type.
906 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
907 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000908
909 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000910 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000911 /// This implements a variant of Dijkstra's algorithm on the graph that spans
912 /// the solution space (\c LineStates are the nodes). The algorithm tries to
913 /// find the shortest path (the one with lowest penalty) from \p InitialState
914 /// to a state where all tokens are placed.
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000915 void analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000916 std::set<LineState> Seen;
917
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000918 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +0000919 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000920 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
921 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
922 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000923
924 // While not empty, take first element and follow edges.
925 while (!Queue.empty()) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000926 unsigned Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +0000927 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000928 if (Node->State.NextToken == NULL) {
Alexander Kornienkodd256312013-05-10 11:56:10 +0000929 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000930 break;
Daniel Jasper01786732013-02-04 07:21:18 +0000931 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000932 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000933
Daniel Jasper54b4e442013-05-22 05:27:42 +0000934 // Cut off the analysis of certain solutions if the analysis gets too
935 // complex. See description of IgnoreStackForComparison.
936 if (Count > 10000)
937 Node->State.IgnoreStackForComparison = true;
938
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000939 if (!Seen.insert(Node->State).second)
940 // State already examined with lower penalty.
941 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000942
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000943 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
944 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000945 }
946
947 if (Queue.empty())
948 // We were unable to find a solution, do nothing.
949 // FIXME: Add diagnostic?
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000950 return;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000951
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000952 // Reconstruct the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000953 reconstructPath(InitialState, Queue.top().second);
Alexander Kornienkodd256312013-05-10 11:56:10 +0000954 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
955 DEBUG(llvm::dbgs() << "---\n");
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000956 }
957
958 void reconstructPath(LineState &State, StateNode *Current) {
959 // FIXME: This recursive implementation limits the possible number
960 // of tokens per line if compiled into a binary with small stack space.
961 // To become more independent of stack frame limitations we would need
962 // to also change the TokenAnnotator.
963 if (Current->Previous == NULL)
964 return;
965 reconstructPath(State, Current->Previous);
966 DEBUG({
967 if (Current->NewLine) {
Alexander Kornienkodd256312013-05-10 11:56:10 +0000968 llvm::dbgs()
Daniel Jaspera03ab102013-02-13 20:33:44 +0000969 << "Penalty for splitting before "
970 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
971 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000972 }
973 });
974 addTokenToState(Current->NewLine, false, State);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000975 }
976
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000977 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000978 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000979 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000980 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000981 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
982 bool NewLine) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000983 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000984 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000985 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000986 return;
Daniel Jasperae8699b2013-01-28 09:35:24 +0000987 if (NewLine)
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000988 Penalty += PreviousNode->State.NextToken->SplitPenalty;
989
990 StateNode *Node = new (Allocator.Allocate())
991 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek8092a942013-02-20 10:15:13 +0000992 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000993 if (Node->State.Column > getColumnLimit()) {
994 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper01786732013-02-04 07:21:18 +0000995 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000996 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000997
998 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
999 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001000 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001001
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001002 /// \brief Returns \c true, if a line break after \p State is allowed.
1003 bool canBreak(const LineState &State) {
Daniel Jasper399914b2013-05-17 09:35:01 +00001004 const AnnotatedToken &Current = *State.NextToken;
1005 const AnnotatedToken &Previous = *Current.Parent;
1006 if (!Current.CanBreakBefore &&
1007 !(Current.is(tok::r_brace) &&
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001008 State.Stack.back().BreakBeforeClosingBrace))
1009 return false;
Daniel Jasper399914b2013-05-17 09:35:01 +00001010 // The opening "{" of a braced list has to be on the same line as the first
1011 // element if it is nested in another braced init list or function call.
1012 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
1013 Previous.Parent &&
1014 Previous.Parent->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
1015 return false;
Daniel Jasper259a0382013-05-27 11:50:16 +00001016 // This prevents breaks like:
1017 // ...
1018 // SomeParameter, OtherParameter).DoSomething(
1019 // ...
1020 // As they hide "DoSomething" and are generally bad for readability.
1021 if (Previous.opensScope() &&
1022 State.LowestLevelOnLine < State.StartOfLineLevel)
1023 return false;
Daniel Jasper001bf4e2013-04-22 07:59:53 +00001024 return !State.Stack.back().NoLineBreak;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001025 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001026
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001027 /// \brief Returns \c true, if a line break after \p State is mandatory.
1028 bool mustBreak(const LineState &State) {
Daniel Jasper11e13802013-05-08 14:12:04 +00001029 const AnnotatedToken &Current = *State.NextToken;
1030 const AnnotatedToken &Previous = *Current.Parent;
1031 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001032 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001033 if (Current.is(tok::r_brace) && State.Stack.back().BreakBeforeClosingBrace)
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001034 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001035 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001036 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001037 if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) ||
1038 Current.Type == TT_ConditionalExpr) &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +00001039 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper11e13802013-05-08 14:12:04 +00001040 !Current.isTrailingComment() &&
1041 !Current.isOneOf(tok::r_paren, tok::r_brace))
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001042 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001043
1044 // If we need to break somewhere inside the LHS of a binary expression, we
1045 // should also break after the operator.
1046 if (Previous.Type == TT_BinaryOperator &&
Daniel Jasper69c43712013-05-28 07:42:44 +00001047 Current.Type != TT_BinaryOperator && // Special case for ">>".
Daniel Jasper11e13802013-05-08 14:12:04 +00001048 !Previous.isOneOf(tok::lessless, tok::question) &&
1049 getPrecedence(Previous) != prec::Assignment &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +00001050 State.Stack.back().BreakBeforeParameter)
Daniel Jasper63d7ced2013-02-05 10:07:47 +00001051 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001052
1053 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1054 // out whether it is the first parameter. Clean this up.
1055 if (Current.Type == TT_ObjCSelectorName &&
1056 Current.LongestObjCSelectorName == 0 &&
1057 State.Stack.back().BreakBeforeParameter)
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001058 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001059 if ((Current.Type == TT_CtorInitializerColon ||
1060 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0)))
Daniel Jasper923ebef2013-03-14 13:45:21 +00001061 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001062
Daniel Jasper33f4b902013-05-15 09:35:08 +00001063 if (Current.Type == TT_StartOfName && Line.MightBeFunctionDecl &&
1064 State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
1065 return true;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001066 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001067 }
1068
Daniel Jasper3af59ce2013-03-15 14:57:30 +00001069 // Returns the total number of columns required for the remaining tokens.
1070 unsigned getRemainingLength(const LineState &State) {
1071 if (State.NextToken && State.NextToken->Parent)
1072 return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
1073 return 0;
1074 }
1075
Daniel Jasperbac016b2012-12-03 18:12:45 +00001076 FormatStyle Style;
1077 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +00001078 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001079 const unsigned FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001080 const AnnotatedToken &RootToken;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001081 WhitespaceManager &Whitespaces;
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001082
1083 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1084 QueueType Queue;
1085 // Increasing count of \c StateNode items we have created. This is used
1086 // to create a deterministic order independent of the container.
1087 unsigned Count;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001088};
1089
Manuel Klimek96e888b2013-05-28 11:55:06 +00001090class FormatTokenLexer {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001091public:
Manuel Klimek96e888b2013-05-28 11:55:06 +00001092 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr)
1093 : FormatTok(NULL), GreaterStashed(false), TrailingWhitespace(0), Lex(Lex),
Manuel Klimekde008c02013-05-27 15:23:34 +00001094 SourceMgr(SourceMgr), IdentTable(Lex.getLangOpts()) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001095 Lex.SetKeepWhitespaceMode(true);
1096 }
1097
Manuel Klimek96e888b2013-05-28 11:55:06 +00001098 ArrayRef<FormatToken *> lex() {
1099 assert(Tokens.empty());
1100 do {
1101 Tokens.push_back(getNextToken());
1102 } while (Tokens.back()->Tok.isNot(tok::eof));
1103 return Tokens;
1104 }
1105
1106 IdentifierTable &getIdentTable() { return IdentTable; }
1107
1108private:
1109 FormatToken *getNextToken() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001110 if (GreaterStashed) {
Manuel Klimek96e888b2013-05-28 11:55:06 +00001111 FormatTok = new (Allocator.Allocate()) FormatToken(*FormatTok);
1112 FormatTok->NewlinesBefore = 0;
Manuel Klimekad3094b2013-05-23 10:56:37 +00001113 SourceLocation GreaterLocation =
Manuel Klimek96e888b2013-05-28 11:55:06 +00001114 FormatTok->Tok.getLocation().getLocWithOffset(1);
1115 FormatTok->WhitespaceRange =
1116 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001117 GreaterStashed = false;
1118 return FormatTok;
1119 }
1120
Manuel Klimek96e888b2013-05-28 11:55:06 +00001121 FormatTok = new (Allocator.Allocate()) FormatToken;
1122 Lex.LexFromRawLexer(FormatTok->Tok);
1123 StringRef Text = rawTokenText(FormatTok->Tok);
Manuel Klimekde008c02013-05-27 15:23:34 +00001124 SourceLocation WhitespaceStart =
Manuel Klimek96e888b2013-05-28 11:55:06 +00001125 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Manuel Klimekad3094b2013-05-23 10:56:37 +00001126 if (SourceMgr.getFileOffset(WhitespaceStart) == 0)
Manuel Klimek96e888b2013-05-28 11:55:06 +00001127 FormatTok->IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001128
1129 // Consume and record whitespace until we find a significant token.
Manuel Klimekde008c02013-05-27 15:23:34 +00001130 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001131 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimeka28fc062013-02-11 12:33:24 +00001132 unsigned Newlines = Text.count('\n');
Daniel Jasper1eee6c42013-03-04 13:43:19 +00001133 if (Newlines > 0)
Manuel Klimek96e888b2013-05-28 11:55:06 +00001134 FormatTok->LastNewlineOffset = WhitespaceLength + Text.rfind('\n') + 1;
Manuel Klimeka28fc062013-02-11 12:33:24 +00001135 unsigned EscapedNewlines = Text.count("\\\n");
Manuel Klimek96e888b2013-05-28 11:55:06 +00001136 FormatTok->NewlinesBefore += Newlines;
1137 FormatTok->HasUnescapedNewline |= EscapedNewlines != Newlines;
1138 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001139
Manuel Klimek96e888b2013-05-28 11:55:06 +00001140 if (FormatTok->Tok.is(tok::eof)) {
1141 FormatTok->WhitespaceRange =
Manuel Klimekad3094b2013-05-23 10:56:37 +00001142 SourceRange(WhitespaceStart,
1143 WhitespaceStart.getLocWithOffset(WhitespaceLength));
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001144 return FormatTok;
Manuel Klimekad3094b2013-05-23 10:56:37 +00001145 }
Manuel Klimek96e888b2013-05-28 11:55:06 +00001146 Lex.LexFromRawLexer(FormatTok->Tok);
1147 Text = rawTokenText(FormatTok->Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001148 }
Manuel Klimek95419382013-01-07 07:56:50 +00001149
1150 // Now FormatTok is the next non-whitespace token.
Manuel Klimek96e888b2013-05-28 11:55:06 +00001151 FormatTok->TokenLength = Text.size();
Manuel Klimek95419382013-01-07 07:56:50 +00001152
Manuel Klimekde008c02013-05-27 15:23:34 +00001153 TrailingWhitespace = 0;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001154 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimekde008c02013-05-27 15:23:34 +00001155 TrailingWhitespace = Text.size() - Text.rtrim().size();
Manuel Klimek96e888b2013-05-28 11:55:06 +00001156 FormatTok->TokenLength -= TrailingWhitespace;
Alexander Kornienko919398b2013-04-17 17:34:05 +00001157 }
1158
Manuel Klimekd4397b92013-01-04 23:34:14 +00001159 // In case the token starts with escaped newlines, we want to
1160 // take them into account as whitespace - this pattern is quite frequent
1161 // in macro definitions.
1162 // FIXME: What do we want to do with other escaped spaces, and escaped
1163 // spaces or newlines in the middle of tokens?
1164 // FIXME: Add a more explicit test.
1165 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +00001166 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek96e888b2013-05-28 11:55:06 +00001167 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimekad3094b2013-05-23 10:56:37 +00001168 WhitespaceLength += 2;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001169 FormatTok->TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +00001170 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001171 }
1172
Manuel Klimek96e888b2013-05-28 11:55:06 +00001173 if (FormatTok->Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001174 IdentifierInfo &Info = IdentTable.get(Text);
Manuel Klimek96e888b2013-05-28 11:55:06 +00001175 FormatTok->Tok.setIdentifierInfo(&Info);
1176 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001177 }
1178
Manuel Klimek96e888b2013-05-28 11:55:06 +00001179 if (FormatTok->Tok.is(tok::greatergreater)) {
1180 FormatTok->Tok.setKind(tok::greater);
1181 FormatTok->TokenLength = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001182 GreaterStashed = true;
1183 }
1184
Manuel Klimek96e888b2013-05-28 11:55:06 +00001185 FormatTok->WhitespaceRange = SourceRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001186 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
Manuel Klimek96e888b2013-05-28 11:55:06 +00001187 FormatTok->TokenText = StringRef(
1188 SourceMgr.getCharacterData(FormatTok->getStartOfNonWhitespace()),
1189 FormatTok->TokenLength);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001190 return FormatTok;
1191 }
1192
Manuel Klimek96e888b2013-05-28 11:55:06 +00001193 FormatToken *FormatTok;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001194 bool GreaterStashed;
Manuel Klimekde008c02013-05-27 15:23:34 +00001195 unsigned TrailingWhitespace;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001196 Lexer &Lex;
1197 SourceManager &SourceMgr;
1198 IdentifierTable IdentTable;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001199 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1200 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001201
1202 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +00001203 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001204 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1205 Tok.getLength());
1206 }
1207};
1208
Daniel Jasperbac016b2012-12-03 18:12:45 +00001209class Formatter : public UnwrappedLineConsumer {
1210public:
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001211 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001212 const std::vector<CharSourceRange> &Ranges)
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001213 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko052685c2013-03-19 17:41:36 +00001214 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +00001215
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001216 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001217
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001218 tooling::Replacements format() {
Manuel Klimek96e888b2013-05-28 11:55:06 +00001219 FormatTokenLexer Tokens(Lex, SourceMgr);
1220
1221 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek67d080d2013-04-12 14:13:36 +00001222 bool StructuralError = Parser.parse();
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001223 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1224 Tokens.getIdentTable().get("in"));
1225 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1226 Annotator.annotate(AnnotatedLines[i]);
1227 }
1228 deriveLocalStyle();
1229 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1230 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1231 }
Daniel Jasper5999f762013-04-09 17:46:55 +00001232
1233 // Adapt level to the next line if this is a comment.
1234 // FIXME: Can/should this be done in the UnwrappedLineParser?
Daniel Jasper1407bee2013-04-11 14:29:13 +00001235 const AnnotatedLine *NextNoneCommentLine = NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +00001236 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
1237 if (NextNoneCommentLine && AnnotatedLines[i].First.is(tok::comment) &&
1238 AnnotatedLines[i].First.Children.empty())
1239 AnnotatedLines[i].Level = NextNoneCommentLine->Level;
1240 else
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001241 NextNoneCommentLine =
1242 AnnotatedLines[i].First.isNot(tok::r_brace) ? &AnnotatedLines[i]
1243 : NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +00001244 }
1245
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001246 std::vector<int> IndentForLevel;
1247 bool PreviousLineWasTouched = false;
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001248 const AnnotatedToken *PreviousLineLastToken = 0;
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001249 bool FormatPPDirective = false;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001250 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1251 E = AnnotatedLines.end();
1252 I != E; ++I) {
1253 const AnnotatedLine &TheLine = *I;
1254 const FormatToken &FirstTok = TheLine.First.FormatTok;
1255 int Offset = getIndentOffset(TheLine.First);
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001256
1257 // Check whether this line is part of a formatted preprocessor directive.
1258 if (FirstTok.HasUnescapedNewline)
1259 FormatPPDirective = false;
1260 if (!FormatPPDirective && TheLine.InPPDirective &&
1261 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
1262 FormatPPDirective = true;
1263
Daniel Jasper1fb8d882013-05-14 09:30:02 +00001264 // Determine indent and try to merge multiple unwrapped lines.
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001265 while (IndentForLevel.size() <= TheLine.Level)
1266 IndentForLevel.push_back(-1);
1267 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper1fb8d882013-05-14 09:30:02 +00001268 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
1269 if (static_cast<int>(Indent) + Offset >= 0)
1270 Indent += Offset;
1271 tryFitMultipleLinesInOne(Indent, I, E);
1272
Daniel Jasperf9955d32013-03-20 12:37:50 +00001273 bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001274 if (TheLine.First.is(tok::eof)) {
1275 if (PreviousLineWasTouched) {
1276 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1277 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001278 /*TargetColumn*/ 0);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001279 }
1280 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001281 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001282 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimekad3094b2013-05-23 10:56:37 +00001283 if (FirstTok.WhitespaceRange.isValid() &&
Manuel Klimek67d080d2013-04-12 14:13:36 +00001284 // Insert a break even if there is a structural error in case where
1285 // we break apart a line consisting of multiple unwrapped lines.
1286 (FirstTok.NewlinesBefore == 0 || !StructuralError)) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001287 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001288 TheLine.InPPDirective);
Manuel Klimek67d080d2013-04-12 14:13:36 +00001289 } else {
1290 Indent = LevelIndent =
1291 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001292 }
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001293 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Manuel Klimek67d080d2013-04-12 14:13:36 +00001294 TheLine.First, Whitespaces);
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001295 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001296 IndentForLevel[TheLine.Level] = LevelIndent;
1297 PreviousLineWasTouched = true;
1298 } else {
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001299 // Format the first token if necessary, and notify the WhitespaceManager
1300 // about the unchanged whitespace.
1301 for (const AnnotatedToken *Tok = &TheLine.First; Tok != NULL;
1302 Tok = Tok->Children.empty() ? NULL : &Tok->Children[0]) {
1303 if (Tok == &TheLine.First &&
1304 (Tok->FormatTok.NewlinesBefore > 0 || Tok->FormatTok.IsFirst)) {
1305 unsigned LevelIndent = SourceMgr.getSpellingColumnNumber(
1306 Tok->FormatTok.Tok.getLocation()) -
1307 1;
1308 // Remove trailing whitespace of the previous line if it was
1309 // touched.
1310 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
1311 formatFirstToken(*Tok, PreviousLineLastToken, LevelIndent,
1312 TheLine.InPPDirective);
1313 } else {
1314 Whitespaces.addUntouchableToken(Tok->FormatTok,
1315 TheLine.InPPDirective);
1316 }
Daniel Jasper1fb8d882013-05-14 09:30:02 +00001317
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001318 if (static_cast<int>(LevelIndent) - Offset >= 0)
1319 LevelIndent -= Offset;
1320 if (Tok->isNot(tok::comment))
1321 IndentForLevel[TheLine.Level] = LevelIndent;
1322 } else {
1323 Whitespaces.addUntouchableToken(Tok->FormatTok,
1324 TheLine.InPPDirective);
1325 }
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001326 }
1327 // If we did not reformat this unwrapped line, the column at the end of
1328 // the last token is unchanged - thus, we can calculate the end of the
1329 // last token.
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001330 PreviousLineWasTouched = false;
1331 }
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001332 PreviousLineLastToken = I->Last;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001333 }
1334 return Whitespaces.generateReplacements();
1335 }
1336
1337private:
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001338 void deriveLocalStyle() {
1339 unsigned CountBoundToVariable = 0;
1340 unsigned CountBoundToType = 0;
1341 bool HasCpp03IncompatibleFormat = false;
1342 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1343 if (AnnotatedLines[i].First.Children.empty())
1344 continue;
1345 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1346 while (!Tok->Children.empty()) {
1347 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimekad3094b2013-05-23 10:56:37 +00001348 bool SpacesBefore = Tok->FormatTok.WhitespaceRange.getBegin() !=
1349 Tok->FormatTok.WhitespaceRange.getEnd();
1350 bool SpacesAfter =
1351 Tok->Children[0].FormatTok.WhitespaceRange.getBegin() !=
1352 Tok->Children[0].FormatTok.WhitespaceRange.getEnd();
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001353 if (SpacesBefore && !SpacesAfter)
1354 ++CountBoundToVariable;
1355 else if (!SpacesBefore && SpacesAfter)
1356 ++CountBoundToType;
1357 }
1358
Daniel Jasper29f123b2013-02-08 15:28:42 +00001359 if (Tok->Type == TT_TemplateCloser &&
1360 Tok->Parent->Type == TT_TemplateCloser &&
Manuel Klimekad3094b2013-05-23 10:56:37 +00001361 Tok->FormatTok.WhitespaceRange.getBegin() ==
1362 Tok->FormatTok.WhitespaceRange.getEnd())
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001363 HasCpp03IncompatibleFormat = true;
1364 Tok = &Tok->Children[0];
1365 }
1366 }
1367 if (Style.DerivePointerBinding) {
1368 if (CountBoundToType > CountBoundToVariable)
1369 Style.PointerBindsToType = true;
1370 else if (CountBoundToType < CountBoundToVariable)
1371 Style.PointerBindsToType = false;
1372 }
1373 if (Style.Standard == FormatStyle::LS_Auto) {
1374 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1375 : FormatStyle::LS_Cpp03;
1376 }
1377 }
1378
Manuel Klimek547d5db2013-02-08 17:38:27 +00001379 /// \brief Get the indent of \p Level from \p IndentForLevel.
1380 ///
1381 /// \p IndentForLevel must contain the indent for the level \c l
1382 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1383 /// that level is unknown.
Daniel Jasperfc759082013-02-14 14:26:07 +00001384 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimek547d5db2013-02-08 17:38:27 +00001385 if (IndentForLevel[Level] != -1)
1386 return IndentForLevel[Level];
Manuel Klimek52635ff2013-02-08 19:53:32 +00001387 if (Level == 0)
1388 return 0;
Manuel Klimek07a64ec2013-05-13 08:42:42 +00001389 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimek547d5db2013-02-08 17:38:27 +00001390 }
1391
1392 /// \brief Get the offset of the line relatively to the level.
1393 ///
1394 /// For example, 'public:' labels in classes are offset by 1 or 2
1395 /// characters to the left from their level.
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001396 int getIndentOffset(const AnnotatedToken &RootToken) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001397 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimek547d5db2013-02-08 17:38:27 +00001398 return Style.AccessModifierOffset;
1399 return 0;
1400 }
1401
Manuel Klimek517e8942013-01-11 17:54:10 +00001402 /// \brief Tries to merge lines into one.
1403 ///
1404 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1405 /// if possible; note that \c I will be incremented when lines are merged.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001406 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +00001407 std::vector<AnnotatedLine>::iterator &I,
1408 std::vector<AnnotatedLine>::iterator E) {
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001409 // We can never merge stuff if there are trailing line comments.
1410 if (I->Last->Type == TT_LineComment)
1411 return;
1412
Daniel Jaspera4d46212013-02-28 11:05:57 +00001413 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001414 // If we already exceed the column limit, we set 'Limit' to 0. The different
1415 // tryMerge..() functions can then decide whether to still do merging.
1416 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001417
Daniel Jasper9c8c40e2013-01-21 14:18:28 +00001418 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001419 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001420
Daniel Jasper5be59ba2013-05-15 14:09:55 +00001421 if (I->Last->is(tok::l_brace)) {
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001422 tryMergeSimpleBlock(I, E, Limit);
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001423 } else if (Style.AllowShortIfStatementsOnASingleLine &&
1424 I->First.is(tok::kw_if)) {
1425 tryMergeSimpleControlStatement(I, E, Limit);
1426 } else if (Style.AllowShortLoopsOnASingleLine &&
1427 I->First.isOneOf(tok::kw_for, tok::kw_while)) {
1428 tryMergeSimpleControlStatement(I, E, Limit);
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001429 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1430 I->First.FormatTok.IsFirst)) {
1431 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001432 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001433 }
1434
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001435 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1436 std::vector<AnnotatedLine>::iterator E,
1437 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001438 if (Limit == 0)
1439 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001440 AnnotatedLine &Line = *I;
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001441 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1442 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001443 if (I + 2 != E && (I + 2)->InPPDirective &&
1444 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1445 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001446 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001447 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001448 join(Line, *(++I));
1449 }
1450
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001451 void tryMergeSimpleControlStatement(std::vector<AnnotatedLine>::iterator &I,
1452 std::vector<AnnotatedLine>::iterator E,
1453 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001454 if (Limit == 0)
1455 return;
Manuel Klimek4c128122013-01-18 14:46:43 +00001456 if ((I + 1)->InPPDirective != I->InPPDirective ||
1457 ((I + 1)->InPPDirective &&
1458 (I + 1)->First.FormatTok.HasUnescapedNewline))
1459 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001460 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001461 if (Line.Last->isNot(tok::r_paren))
1462 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001463 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001464 return;
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001465 if ((I + 1)->First.isOneOf(tok::semi, tok::kw_if, tok::kw_for,
1466 tok::kw_while) ||
1467 (I + 1)->First.Type == TT_LineComment)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001468 return;
1469 // Only inline simple if's (no nested if or else).
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001470 if (I + 2 != E && Line.First.is(tok::kw_if) &&
1471 (I + 2)->First.is(tok::kw_else))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001472 return;
1473 join(Line, *(++I));
1474 }
1475
1476 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001477 std::vector<AnnotatedLine>::iterator E,
1478 unsigned Limit) {
Daniel Jasper5be59ba2013-05-15 14:09:55 +00001479 // No merging if the brace already is on the next line.
1480 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
1481 return;
1482
Manuel Klimek517e8942013-01-11 17:54:10 +00001483 // First, check that the current line allows merging. This is the case if
1484 // we're not in a control flow statement and the last token is an opening
1485 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001486 AnnotatedLine &Line = *I;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001487 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1488 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jasper5be59ba2013-05-15 14:09:55 +00001489 tok::kw_for, tok::kw_namespace,
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001490 // This gets rid of all ObjC @ keywords and methods.
1491 tok::at, tok::minus, tok::plus))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001492 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001493
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001494 AnnotatedToken *Tok = &(I + 1)->First;
Daniel Jasper058f6f82013-05-16 10:17:39 +00001495 if (Tok->getNextNoneComment() == NULL && Tok->is(tok::r_brace) &&
Daniel Jasperf11a7052013-02-21 21:33:55 +00001496 !Tok->MustBreakBefore) {
1497 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jasper729a7432013-02-11 12:36:37 +00001498 Tok->SpacesRequiredBefore = 0;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001499 Tok->CanBreakBefore = true;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001500 join(Line, *(I + 1));
1501 I += 1;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001502 } else if (Limit != 0) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001503 // Check that we still have three lines and they fit into the limit.
1504 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1505 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001506 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001507
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001508 // Second, check that the next line does not contain any braces - if it
1509 // does, readability declines when putting it into a single line.
1510 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1511 return;
1512 do {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001513 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001514 return;
1515 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1516 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001517
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001518 // Last, check that the third line contains a single closing brace.
1519 Tok = &(I + 2)->First;
Daniel Jasper058f6f82013-05-16 10:17:39 +00001520 if (Tok->getNextNoneComment() != NULL || Tok->isNot(tok::r_brace) ||
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001521 Tok->MustBreakBefore)
1522 return;
1523
1524 join(Line, *(I + 1));
1525 join(Line, *(I + 2));
1526 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +00001527 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001528 }
1529
1530 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1531 unsigned Limit) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001532 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1533 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001534 }
1535
Daniel Jasper995e8202013-01-14 13:08:07 +00001536 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001537 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasper995e8202013-01-14 13:08:07 +00001538 A.Last->Children.push_back(B.First);
1539 while (!A.Last->Children.empty()) {
1540 A.Last->Children[0].Parent = A.Last;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001541 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasper995e8202013-01-14 13:08:07 +00001542 A.Last = &A.Last->Children[0];
1543 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001544 }
1545
Daniel Jasper6f21a982013-03-13 07:49:51 +00001546 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf3023542013-03-07 20:50:00 +00001547 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1548 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1549 Ranges[i].getBegin()) &&
1550 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1551 Range.getBegin()))
1552 return true;
1553 }
1554 return false;
1555 }
1556
1557 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001558 const FormatToken *First = &TheLine.First.FormatTok;
1559 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper84f5ddf2013-05-14 10:31:09 +00001560 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001561 First->WhitespaceRange.getBegin().getLocWithOffset(
1562 First->LastNewlineOffset),
Daniel Jasper84f5ddf2013-05-14 10:31:09 +00001563 Last->Tok.getLocation().getLocWithOffset(Last->TokenLength - 1));
Daniel Jasperf3023542013-03-07 20:50:00 +00001564 return touchesRanges(LineRange);
1565 }
1566
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001567 bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I,
1568 std::vector<AnnotatedLine>::iterator E) {
1569 for (; I != E; ++I) {
1570 if (I->First.FormatTok.HasUnescapedNewline)
1571 return false;
1572 if (touchesLine(*I))
1573 return true;
1574 }
1575 return false;
1576 }
1577
Daniel Jasperf3023542013-03-07 20:50:00 +00001578 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1579 const FormatToken *First = &TheLine.First.FormatTok;
1580 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001581 First->WhitespaceRange.getBegin(),
1582 First->WhitespaceRange.getBegin().getLocWithOffset(
1583 First->LastNewlineOffset));
Daniel Jasperf3023542013-03-07 20:50:00 +00001584 return touchesRanges(LineRange);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001585 }
1586
1587 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +00001588 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001589 }
1590
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001591 /// \brief Add a new line and the required indent before the first Token
1592 /// of the \c UnwrappedLine if there was no structural parsing error.
1593 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001594 void formatFirstToken(const AnnotatedToken &RootToken,
1595 const AnnotatedToken *PreviousToken, unsigned Indent,
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001596 bool InPPDirective) {
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001597 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001598
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001599 unsigned Newlines =
1600 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001601 if (Newlines == 0 && !Tok.IsFirst)
1602 Newlines = 1;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001603
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001604 // Insert extra new line before access specifiers.
1605 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
1606 RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1)
1607 ++Newlines;
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001608
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001609 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, Indent,
1610 InPPDirective && !Tok.HasUnescapedNewline);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001611 }
1612
Daniel Jasperbac016b2012-12-03 18:12:45 +00001613 FormatStyle Style;
1614 Lexer &Lex;
1615 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001616 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001617 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001618 std::vector<AnnotatedLine> AnnotatedLines;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001619};
1620
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001621tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1622 SourceManager &SourceMgr,
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001623 std::vector<CharSourceRange> Ranges) {
1624 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001625 return formatter.format();
1626}
1627
Daniel Jasper8a999452013-05-16 10:40:07 +00001628tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1629 std::vector<tooling::Range> Ranges,
1630 StringRef FileName) {
1631 FileManager Files((FileSystemOptions()));
1632 DiagnosticsEngine Diagnostics(
1633 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1634 new DiagnosticOptions);
1635 SourceManager SourceMgr(Diagnostics, Files);
1636 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1637 const clang::FileEntry *Entry =
1638 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1639 SourceMgr.overrideFileContents(Entry, Buf);
1640 FileID ID =
1641 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
1642 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr, getFormattingLangOpts());
1643 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1644 std::vector<CharSourceRange> CharRanges;
1645 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1646 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1647 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1648 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1649 }
1650 return reformat(Style, Lex, SourceMgr, CharRanges);
1651}
1652
Daniel Jasper46ef8522013-01-10 13:08:12 +00001653LangOptions getFormattingLangOpts() {
1654 LangOptions LangOpts;
1655 LangOpts.CPlusPlus = 1;
1656 LangOpts.CPlusPlus11 = 1;
Daniel Jasperb64eca02013-03-22 10:01:29 +00001657 LangOpts.LineComment = 1;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001658 LangOpts.Bool = 1;
1659 LangOpts.ObjC1 = 1;
1660 LangOpts.ObjC2 = 1;
1661 return LangOpts;
1662}
1663
Daniel Jaspercd162382013-01-07 13:26:07 +00001664} // namespace format
1665} // namespace clang