blob: 790485368917f9c5724c2d98ec88d3fb0bc1ce9c [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);
Daniel Jasperbbc87762013-05-29 12:07:31 +000088 IO.mapOptional("AlwaysBreakTemplateDeclarations",
89 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko56312022013-07-04 12:02:44 +000090 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
91 Style.AlwaysBreakBeforeMultilineStrings);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000092 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
93 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
94 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
95 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
96 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperc7bd68f2013-07-10 14:02:49 +000097 IO.mapOptional("ExperimentalAutoDetectBinPacking",
98 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000099 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
100 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
101 IO.mapOptional("ObjCSpaceBeforeProtocolList",
102 Style.ObjCSpaceBeforeProtocolList);
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000103 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
104 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000105 IO.mapOptional("PenaltyBreakFirstLessLess",
106 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000107 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
108 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
109 Style.PenaltyReturnTypeOnItsOwnLine);
110 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
111 IO.mapOptional("SpacesBeforeTrailingComments",
112 Style.SpacesBeforeTrailingComments);
Daniel Jasper1bee0732013-05-23 18:05:18 +0000113 IO.mapOptional("SpacesInBracedLists", Style.SpacesInBracedLists);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000114 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000115 IO.mapOptional("IndentWidth", Style.IndentWidth);
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000116 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimek44135b82013-05-13 12:51:40 +0000117 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimeka9a7f102013-06-21 17:25:42 +0000118 IO.mapOptional("IndentFunctionDeclarationAfterType",
119 Style.IndentFunctionDeclarationAfterType);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000120 }
121};
122}
123}
124
Daniel Jasperbac016b2012-12-03 18:12:45 +0000125namespace clang {
126namespace format {
127
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000128void setDefaultPenalties(FormatStyle &Style) {
129 Style.PenaltyBreakComment = 45;
Daniel Jasper9637dda2013-07-15 14:33:14 +0000130 Style.PenaltyBreakFirstLessLess = 120;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000131 Style.PenaltyBreakString = 1000;
132 Style.PenaltyExcessCharacter = 1000000;
133}
134
Daniel Jasperbac016b2012-12-03 18:12:45 +0000135FormatStyle getLLVMStyle() {
136 FormatStyle LLVMStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000137 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000138 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasperf1579602013-01-29 16:03:49 +0000139 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000140 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000141 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperbbc87762013-05-29 12:07:31 +0000142 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienko56312022013-07-04 12:02:44 +0000143 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000144 LLVMStyle.BinPackParameters = true;
145 LLVMStyle.ColumnLimit = 80;
146 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
147 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000148 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000149 LLVMStyle.IndentCaseLabels = false;
150 LLVMStyle.MaxEmptyLinesToKeep = 1;
Nico Weber5f500df2013-01-10 20:12:55 +0000151 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000152 LLVMStyle.PointerBindsToType = false;
153 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper2424eef2013-05-23 10:15:45 +0000154 LLVMStyle.SpacesInBracedLists = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000155 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000156 LLVMStyle.IndentWidth = 2;
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000157 LLVMStyle.UseTab = false;
Manuel Klimek44135b82013-05-13 12:51:40 +0000158 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Manuel Klimeka9a7f102013-06-21 17:25:42 +0000159 LLVMStyle.IndentFunctionDeclarationAfterType = false;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000160
161 setDefaultPenalties(LLVMStyle);
162 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
163
Daniel Jasperbac016b2012-12-03 18:12:45 +0000164 return LLVMStyle;
165}
166
167FormatStyle getGoogleStyle() {
168 FormatStyle GoogleStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000169 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000170 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000171 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000172 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper1bee0732013-05-23 18:05:18 +0000173 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Daniel Jasperbbc87762013-05-29 12:07:31 +0000174 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienko56312022013-07-04 12:02:44 +0000175 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000176 GoogleStyle.BinPackParameters = true;
177 GoogleStyle.ColumnLimit = 80;
178 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
179 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000180 GoogleStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000181 GoogleStyle.IndentCaseLabels = true;
182 GoogleStyle.MaxEmptyLinesToKeep = 1;
Nico Weber5f500df2013-01-10 20:12:55 +0000183 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000184 GoogleStyle.PointerBindsToType = true;
185 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper2424eef2013-05-23 10:15:45 +0000186 GoogleStyle.SpacesInBracedLists = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000187 GoogleStyle.Standard = FormatStyle::LS_Auto;
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000188 GoogleStyle.IndentWidth = 2;
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000189 GoogleStyle.UseTab = false;
Manuel Klimek44135b82013-05-13 12:51:40 +0000190 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Manuel Klimeka9a7f102013-06-21 17:25:42 +0000191 GoogleStyle.IndentFunctionDeclarationAfterType = true;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000192
193 setDefaultPenalties(GoogleStyle);
194 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
195
Daniel Jasperbac016b2012-12-03 18:12:45 +0000196 return GoogleStyle;
197}
198
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000199FormatStyle getChromiumStyle() {
200 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +0000201 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000202 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000203 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000204 ChromiumStyle.BinPackParameters = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000205 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
206 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000207 return ChromiumStyle;
208}
209
Alexander Kornienkofb594862013-05-06 14:11:27 +0000210FormatStyle getMozillaStyle() {
211 FormatStyle MozillaStyle = getLLVMStyle();
212 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
213 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
214 MozillaStyle.DerivePointerBinding = true;
215 MozillaStyle.IndentCaseLabels = true;
216 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
217 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
218 MozillaStyle.PointerBindsToType = true;
219 return MozillaStyle;
220}
221
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000222bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000223 if (Name.equals_lower("llvm"))
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000224 *Style = getLLVMStyle();
225 else if (Name.equals_lower("chromium"))
226 *Style = getChromiumStyle();
227 else if (Name.equals_lower("mozilla"))
228 *Style = getMozillaStyle();
229 else if (Name.equals_lower("google"))
230 *Style = getGoogleStyle();
231 else
232 return false;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000233
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000234 return true;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000235}
236
237llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienko107db3c2013-05-20 15:18:01 +0000238 if (Text.trim().empty())
239 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000240 llvm::yaml::Input Input(Text);
241 Input >> *Style;
242 return Input.error();
243}
244
245std::string configurationAsText(const FormatStyle &Style) {
246 std::string Text;
247 llvm::raw_string_ostream Stream(Text);
248 llvm::yaml::Output Output(Stream);
249 // We use the same mapping method for input and output, so we need a non-const
250 // reference here.
251 FormatStyle NonConstStyle = Style;
252 Output << NonConstStyle;
Alexander Kornienko2b6acb62013-05-13 12:56:35 +0000253 return Stream.str();
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000254}
255
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000256// Returns the length of everything up to the first possible line break after
257// the ), ], } or > matching \c Tok.
Manuel Klimekb3987012013-05-29 14:47:47 +0000258static unsigned getLengthToMatchingParen(const FormatToken &Tok) {
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000259 if (Tok.MatchingParen == NULL)
260 return 0;
Manuel Klimekb3987012013-05-29 14:47:47 +0000261 FormatToken *End = Tok.MatchingParen;
262 while (End->Next && !End->Next->CanBreakBefore) {
263 End = End->Next;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000264 }
265 return End->TotalLength - Tok.TotalLength + 1;
266}
267
Craig Topper83f81d72013-06-30 22:29:28 +0000268namespace {
269
Daniel Jasperbac016b2012-12-03 18:12:45 +0000270class UnwrappedLineFormatter {
271public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000272 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper995e8202013-01-14 13:08:07 +0000273 const AnnotatedLine &Line, unsigned FirstIndent,
Manuel Klimekb3987012013-05-29 14:47:47 +0000274 const FormatToken *RootToken,
Alexander Kornienko00895102013-06-05 14:09:10 +0000275 WhitespaceManager &Whitespaces,
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000276 encoding::Encoding Encoding,
277 bool BinPackInconclusiveFunctions)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000278 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000279 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000280 Whitespaces(Whitespaces), Count(0), Encoding(Encoding),
281 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000282
Manuel Klimekd4397b92013-01-04 23:34:14 +0000283 /// \brief Formats an \c UnwrappedLine.
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000284 void format(const AnnotatedLine *NextLine) {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000285 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000286 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000287 State.Column = FirstIndent;
Manuel Klimekb3987012013-05-29 14:47:47 +0000288 State.NextToken = RootToken;
Daniel Jasper2a409b62013-07-08 14:34:09 +0000289 State.Stack.push_back(ParenState(FirstIndent, FirstIndent,
290 /*AvoidBinPacking=*/false,
291 /*NoLineBreak=*/false));
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000292 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000293 State.ParenLevel = 0;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000294 State.StartOfStringLiteral = 0;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000295 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper07ca5472013-07-05 09:14:35 +0000296 State.LowestLevelOnLine = State.ParenLevel;
Daniel Jasper54b4e442013-05-22 05:27:42 +0000297 State.IgnoreStackForComparison = false;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000298
299 // The first token has already been indented and thus consumed.
Daniel Jasper0fde9502013-07-12 11:37:05 +0000300 moveStateToNextToken(State, /*DryRun=*/false, /*Newline=*/false);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000301
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000302 // If everything fits on a single line, just put it there.
Daniel Jaspera4d46212013-02-28 11:05:57 +0000303 unsigned ColumnLimit = Style.ColumnLimit;
304 if (NextLine && NextLine->InPPDirective &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000305 !NextLine->First->HasUnescapedNewline)
Daniel Jaspera4d46212013-02-28 11:05:57 +0000306 ColumnLimit = getColumnLimit();
307 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000308 while (State.NextToken != NULL) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000309 addTokenToState(false, false, State);
Daniel Jasper1321eb52012-12-18 21:05:13 +0000310 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000311 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000312
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000313 // If the ObjC method declaration does not fit on a line, we should format
314 // it with one arg per line.
315 if (Line.Type == LT_ObjCMethodDecl)
316 State.Stack.back().BreakBeforeParameter = true;
317
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000318 // Find best solution in solution space.
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000319 analyzeSolutionSpace(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000320 }
321
322private:
Manuel Klimekb3987012013-05-29 14:47:47 +0000323 void DebugTokenState(const FormatToken &FormatTok) {
324 const Token &Tok = FormatTok.Tok;
Alexander Kornienkodd256312013-05-10 11:56:10 +0000325 llvm::dbgs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000326 Tok.getLength());
Alexander Kornienkodd256312013-05-10 11:56:10 +0000327 llvm::dbgs();
Manuel Klimekca547db2013-01-16 14:55:28 +0000328 }
329
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000330 struct ParenState {
Daniel Jasperd399bff2013-02-05 09:41:21 +0000331 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000332 bool NoLineBreak)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000333 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
334 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000335 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000336 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
Daniel Jasper011c35d2013-07-12 11:19:37 +0000337 StartOfArraySubscripts(0), NestedNameSpecifierContinuation(0),
338 CallContinuation(0), VariablePos(0), ContainsLineBreak(false) {}
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000339
Daniel Jasperbac016b2012-12-03 18:12:45 +0000340 /// \brief The position to which a specific parenthesis level needs to be
341 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000342 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000343
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000344 /// \brief The position of the last space on each level.
345 ///
346 /// Used e.g. to break like:
347 /// functionCall(Parameter, otherCall(
348 /// OtherParameter));
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000349 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000350
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000351 /// \brief The position the first "<<" operator encountered on each level.
352 ///
353 /// Used to align "<<" operators. 0 if no such operator has been encountered
354 /// on a level.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000355 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000356
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000357 /// \brief Whether a newline needs to be inserted before the block's closing
358 /// brace.
359 ///
360 /// We only want to insert a newline before the closing brace if there also
361 /// was a newline after the beginning left brace.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000362 bool BreakBeforeClosingBrace;
363
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000364 /// \brief The column of a \c ? in a conditional expression;
365 unsigned QuestionColumn;
366
Daniel Jasperf343cab2013-01-31 14:59:26 +0000367 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
368 /// lines, in this context.
369 bool AvoidBinPacking;
370
371 /// \brief Break after the next comma (or all the commas in this context if
372 /// \c AvoidBinPacking is \c true).
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000373 bool BreakBeforeParameter;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000374
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000375 /// \brief Line breaking in this context would break a formatting rule.
376 bool NoLineBreak;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000377
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000378 /// \brief The position of the colon in an ObjC method declaration/call.
379 unsigned ColonPos;
Daniel Jasperc4615b72013-02-20 12:56:39 +0000380
Daniel Jasper24849712013-03-01 16:48:32 +0000381 /// \brief The start of the most recent function in a builder-type call.
382 unsigned StartOfFunctionCall;
383
Daniel Jasper011c35d2013-07-12 11:19:37 +0000384 /// \brief Contains the start of array subscript expressions, so that they
385 /// can be aligned.
386 unsigned StartOfArraySubscripts;
387
Daniel Jasper37911302013-04-02 14:33:13 +0000388 /// \brief If a nested name specifier was broken over multiple lines, this
389 /// contains the start column of the second line. Otherwise 0.
390 unsigned NestedNameSpecifierContinuation;
391
392 /// \brief If a call expression was broken over multiple lines, this
393 /// contains the start column of the second line. Otherwise 0.
394 unsigned CallContinuation;
395
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000396 /// \brief The column of the first variable name in a variable declaration.
397 ///
398 /// Used to align further variables if necessary.
399 unsigned VariablePos;
400
Daniel Jasper88cc5622013-07-08 14:25:23 +0000401 /// \brief \c true if this \c ParenState already contains a line-break.
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000402 ///
Daniel Jasper88cc5622013-07-08 14:25:23 +0000403 /// The first line break in a certain \c ParenState causes extra penalty so
404 /// that clang-format prefers similar breaks, i.e. breaks in the same
405 /// parenthesis.
406 bool ContainsLineBreak;
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000407
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000408 bool operator<(const ParenState &Other) const {
409 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000410 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000411 if (LastSpace != Other.LastSpace)
412 return LastSpace < Other.LastSpace;
413 if (FirstLessLess != Other.FirstLessLess)
414 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000415 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
416 return BreakBeforeClosingBrace;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000417 if (QuestionColumn != Other.QuestionColumn)
418 return QuestionColumn < Other.QuestionColumn;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000419 if (AvoidBinPacking != Other.AvoidBinPacking)
420 return AvoidBinPacking;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000421 if (BreakBeforeParameter != Other.BreakBeforeParameter)
422 return BreakBeforeParameter;
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000423 if (NoLineBreak != Other.NoLineBreak)
424 return NoLineBreak;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000425 if (ColonPos != Other.ColonPos)
426 return ColonPos < Other.ColonPos;
Daniel Jasper24849712013-03-01 16:48:32 +0000427 if (StartOfFunctionCall != Other.StartOfFunctionCall)
428 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasper011c35d2013-07-12 11:19:37 +0000429 if (StartOfArraySubscripts != Other.StartOfArraySubscripts)
430 return StartOfArraySubscripts < Other.StartOfArraySubscripts;
Daniel Jasper37911302013-04-02 14:33:13 +0000431 if (CallContinuation != Other.CallContinuation)
432 return CallContinuation < Other.CallContinuation;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000433 if (VariablePos != Other.VariablePos)
434 return VariablePos < Other.VariablePos;
Daniel Jasper88cc5622013-07-08 14:25:23 +0000435 if (ContainsLineBreak != Other.ContainsLineBreak)
436 return ContainsLineBreak < Other.ContainsLineBreak;
Daniel Jasperb3123142013-01-12 07:36:22 +0000437 return false;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000438 }
439 };
440
441 /// \brief The current state when indenting a unwrapped line.
442 ///
443 /// As the indenting tries different combinations this is copied by value.
444 struct LineState {
445 /// \brief The number of used columns in the current line.
446 unsigned Column;
447
448 /// \brief The token that needs to be next formatted.
Manuel Klimekb3987012013-05-29 14:47:47 +0000449 const FormatToken *NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000450
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000451 /// \brief \c true if this line contains a continued for-loop section.
452 bool LineContainsContinuedForLoopSection;
453
Daniel Jasper29f123b2013-02-08 15:28:42 +0000454 /// \brief The level of nesting inside (), [], <> and {}.
455 unsigned ParenLevel;
456
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000457 /// \brief The \c ParenLevel at the start of this line.
458 unsigned StartOfLineLevel;
459
Daniel Jasper07ca5472013-07-05 09:14:35 +0000460 /// \brief The lowest \c ParenLevel on the current line.
461 unsigned LowestLevelOnLine;
Daniel Jasper259a0382013-05-27 11:50:16 +0000462
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000463 /// \brief The start column of the string literal, if we're in a string
464 /// literal sequence, 0 otherwise.
465 unsigned StartOfStringLiteral;
466
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000467 /// \brief A stack keeping track of properties applying to parenthesis
468 /// levels.
469 std::vector<ParenState> Stack;
470
Daniel Jasper54b4e442013-05-22 05:27:42 +0000471 /// \brief Ignore the stack of \c ParenStates for state comparison.
472 ///
473 /// In long and deeply nested unwrapped lines, the current algorithm can
474 /// be insufficient for finding the best formatting with a reasonable amount
475 /// of time and memory. Setting this flag will effectively lead to the
476 /// algorithm not analyzing some combinations. However, these combinations
477 /// rarely contain the optimal solution: In short, accepting a higher
478 /// penalty early would need to lead to different values in the \c
479 /// ParenState stack (in an otherwise identical state) and these different
480 /// values would need to lead to a significant amount of avoided penalty
481 /// later.
482 ///
483 /// FIXME: Come up with a better algorithm instead.
484 bool IgnoreStackForComparison;
485
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000486 /// \brief Comparison operator to be able to used \c LineState in \c map.
487 bool operator<(const LineState &Other) const {
Daniel Jasperd7896702013-02-19 09:28:55 +0000488 if (NextToken != Other.NextToken)
489 return NextToken < Other.NextToken;
490 if (Column != Other.Column)
491 return Column < Other.Column;
Daniel Jasperd7896702013-02-19 09:28:55 +0000492 if (LineContainsContinuedForLoopSection !=
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000493 Other.LineContainsContinuedForLoopSection)
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000494 return LineContainsContinuedForLoopSection;
Daniel Jasperd7896702013-02-19 09:28:55 +0000495 if (ParenLevel != Other.ParenLevel)
496 return ParenLevel < Other.ParenLevel;
497 if (StartOfLineLevel != Other.StartOfLineLevel)
498 return StartOfLineLevel < Other.StartOfLineLevel;
Daniel Jasper07ca5472013-07-05 09:14:35 +0000499 if (LowestLevelOnLine != Other.LowestLevelOnLine)
500 return LowestLevelOnLine < Other.LowestLevelOnLine;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000501 if (StartOfStringLiteral != Other.StartOfStringLiteral)
502 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper54b4e442013-05-22 05:27:42 +0000503 if (IgnoreStackForComparison || Other.IgnoreStackForComparison)
504 return false;
Daniel Jasperd7896702013-02-19 09:28:55 +0000505 return Stack < Other.Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000506 }
507 };
508
Daniel Jasper20409152012-12-04 14:54:30 +0000509 /// \brief Appends the next token to \p State and updates information
510 /// necessary for indentation.
511 ///
Nico Weber1907c572013-06-26 02:42:46 +0000512 /// Puts the token on the current line if \p Newline is \c false and adds a
Daniel Jasper20409152012-12-04 14:54:30 +0000513 /// line break and necessary indentation otherwise.
514 ///
515 /// If \p DryRun is \c false, also creates and stores the required
516 /// \c Replacement.
Manuel Klimek8092a942013-02-20 10:15:13 +0000517 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000518 const FormatToken &Current = *State.NextToken;
519 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000520
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000521 // Extra penalty that needs to be added because of the way certain line
522 // breaks are chosen.
523 unsigned ExtraPenalty = 0;
524
Daniel Jasper92f9faf2013-03-20 15:58:10 +0000525 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Manuel Klimekad3094b2013-05-23 10:56:37 +0000526 // FIXME: Is this correct?
Manuel Klimekb3987012013-05-29 14:47:47 +0000527 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
528 State.NextToken->WhitespaceRange.getEnd()) -
529 SourceMgr.getSpellingColumnNumber(
530 State.NextToken->WhitespaceRange.getBegin());
Alexander Kornienko00895102013-06-05 14:09:10 +0000531 State.Column += WhitespaceLength + State.NextToken->CodePointCount;
Manuel Klimekb3987012013-05-29 14:47:47 +0000532 State.NextToken = State.NextToken->Next;
Manuel Klimek8092a942013-02-20 10:15:13 +0000533 return 0;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000534 }
535
Daniel Jasper3776ef32013-04-03 07:21:51 +0000536 // If we are continuing an expression, we want to indent an extra 4 spaces.
537 unsigned ContinuationIndent =
Daniel Jasper37911302013-04-02 14:33:13 +0000538 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000539 if (Newline) {
Daniel Jasper88cc5622013-07-08 14:25:23 +0000540 State.Stack.back().ContainsLineBreak = true;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000541 if (Current.is(tok::r_brace)) {
Daniel Jasper0de1c4d2013-07-09 09:06:29 +0000542 if (Current.BlockKind == BK_BracedInit)
543 State.Column = State.Stack[State.Stack.size() - 2].LastSpace;
544 else
Daniel Jasper15ec3a82013-07-11 21:27:40 +0000545 State.Column = FirstIndent;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000546 } else if (Current.is(tok::string_literal) &&
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000547 State.StartOfStringLiteral != 0) {
548 State.Column = State.StartOfStringLiteral;
Daniel Jasper66d19bd2013-02-18 11:59:17 +0000549 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000550 } else if (Current.is(tok::lessless) &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000551 State.Stack.back().FirstLessLess != 0) {
552 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasper5ad390d2013-05-28 11:30:49 +0000553 } else if (Current.isOneOf(tok::period, tok::arrow) &&
554 Current.Type != TT_DesignatedInitializerPeriod) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000555 if (State.Stack.back().CallContinuation == 0) {
556 State.Column = ContinuationIndent;
Daniel Jasper37911302013-04-02 14:33:13 +0000557 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000558 } else {
559 State.Column = State.Stack.back().CallContinuation;
560 }
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000561 } else if (Current.Type == TT_ConditionalExpr) {
562 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000563 } else if (Previous.is(tok::comma) &&
564 State.Stack.back().VariablePos != 0) {
565 State.Column = State.Stack.back().VariablePos;
Daniel Jasper3c08a812013-02-24 18:54:32 +0000566 } else if (Previous.ClosesTemplateDeclaration ||
Daniel Jasper6561f6a2013-07-09 07:43:55 +0000567 ((Current.Type == TT_StartOfName ||
568 Current.is(tok::kw_operator)) &&
569 State.ParenLevel == 0 &&
Manuel Klimeka9a7f102013-06-21 17:25:42 +0000570 (!Style.IndentFunctionDeclarationAfterType ||
571 Line.StartsDefinition))) {
Daniel Jasper37911302013-04-02 14:33:13 +0000572 State.Column = State.Stack.back().Indent;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000573 } else if (Current.Type == TT_ObjCSelectorName) {
Alexander Kornienko00895102013-06-05 14:09:10 +0000574 if (State.Stack.back().ColonPos > Current.CodePointCount) {
575 State.Column = State.Stack.back().ColonPos - Current.CodePointCount;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000576 } else {
577 State.Column = State.Stack.back().Indent;
Alexander Kornienko00895102013-06-05 14:09:10 +0000578 State.Stack.back().ColonPos = State.Column + Current.CodePointCount;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000579 }
Daniel Jasper011c35d2013-07-12 11:19:37 +0000580 } else if (Current.is(tok::l_square) &&
581 Current.Type != TT_ObjCMethodExpr) {
582 if (State.Stack.back().StartOfArraySubscripts != 0)
583 State.Column = State.Stack.back().StartOfArraySubscripts;
584 else
585 State.Column = ContinuationIndent;
Daniel Jasperb2f063a2013-05-08 10:00:18 +0000586 } else if (Current.Type == TT_StartOfName ||
587 Previous.isOneOf(tok::coloncolon, tok::equal) ||
Daniel Jasper37911302013-04-02 14:33:13 +0000588 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000589 State.Column = ContinuationIndent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000590 } else {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000591 State.Column = State.Stack.back().Indent;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000592 // Ensure that we fall back to indenting 4 spaces instead of just
593 // flushing continuations left.
Daniel Jasper37911302013-04-02 14:33:13 +0000594 if (State.Column == FirstIndent)
595 State.Column += 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000596 }
597
Daniel Jasper7878a7b2013-02-15 11:07:25 +0000598 if (Current.is(tok::question))
Daniel Jasper237d4c12013-02-23 21:01:55 +0000599 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper11e13802013-05-08 14:12:04 +0000600 if ((Previous.isOneOf(tok::comma, tok::semi) &&
601 !State.Stack.back().AvoidBinPacking) ||
602 Previous.Type == TT_BinaryOperator)
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000603 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper33f4b902013-05-15 09:35:08 +0000604 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
605 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000606
Manuel Klimek060143e2013-01-02 18:33:23 +0000607 if (!DryRun) {
Daniel Jasper1ef81d52013-02-26 13:10:34 +0000608 unsigned NewLines = 1;
Alexander Kornienkoe3f11972013-06-12 19:04:12 +0000609 if (Current.is(tok::comment))
Manuel Klimekb3987012013-05-29 14:47:47 +0000610 NewLines = std::max(
611 NewLines,
612 std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1));
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000613 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
614 State.Column, Line.InPPDirective);
Manuel Klimek060143e2013-01-02 18:33:23 +0000615 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000616
Daniel Jaspere1f9a8e2013-07-11 13:48:16 +0000617 if (!Current.isTrailingComment())
618 State.Stack.back().LastSpace = State.Column;
Daniel Jasper5ad390d2013-05-28 11:30:49 +0000619 if (Current.isOneOf(tok::arrow, tok::period) &&
620 Current.Type != TT_DesignatedInitializerPeriod)
Alexander Kornienko00895102013-06-05 14:09:10 +0000621 State.Stack.back().LastSpace += Current.CodePointCount;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000622 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper07ca5472013-07-05 09:14:35 +0000623 State.LowestLevelOnLine = State.ParenLevel;
Daniel Jasper237d4c12013-02-23 21:01:55 +0000624
625 // Any break on this level means that the parent level has been broken
626 // and we need to avoid bin packing there.
627 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
628 State.Stack[i].BreakBeforeParameter = true;
629 }
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000630 const FormatToken *TokenBefore = Current.getPreviousNonComment();
Daniel Jasper01218ff2013-04-15 22:36:37 +0000631 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
Daniel Jasper33f4b902013-05-15 09:35:08 +0000632 TokenBefore->Type != TT_TemplateCloser &&
Daniel Jasper11e13802013-05-08 14:12:04 +0000633 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000634 State.Stack.back().BreakBeforeParameter = true;
635
Daniel Jasper237d4c12013-02-23 21:01:55 +0000636 // If we break after {, we should also break before the corresponding }.
637 if (Previous.is(tok::l_brace))
638 State.Stack.back().BreakBeforeClosingBrace = true;
639
640 if (State.Stack.back().AvoidBinPacking) {
641 // If we are breaking after '(', '{', '<', this is not bin packing
642 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasperd741f022013-05-14 20:39:56 +0000643 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
644 Previous.Type == TT_BinaryOperator) ||
Daniel Jasper237d4c12013-02-23 21:01:55 +0000645 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
646 Line.MustBeDeclaration))
647 State.Stack.back().BreakBeforeParameter = true;
648 }
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000649
650 // Breaking before the first "<<" is generally not desirable.
651 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
652 ExtraPenalty += Style.PenaltyBreakFirstLessLess;
653
Daniel Jasperbac016b2012-12-03 18:12:45 +0000654 } else {
Daniel Jasper9c3e71a2013-02-25 15:59:54 +0000655 if (Current.is(tok::equal) &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000656 (RootToken->is(tok::kw_for) || State.ParenLevel == 0) &&
Daniel Jasperadc0f092013-04-05 09:38:50 +0000657 State.Stack.back().VariablePos == 0) {
658 State.Stack.back().VariablePos = State.Column;
659 // Move over * and & if they are bound to the variable name.
Manuel Klimekb3987012013-05-29 14:47:47 +0000660 const FormatToken *Tok = &Previous;
Alexander Kornienko00895102013-06-05 14:09:10 +0000661 while (Tok && State.Stack.back().VariablePos >= Tok->CodePointCount) {
662 State.Stack.back().VariablePos -= Tok->CodePointCount;
Daniel Jasperadc0f092013-04-05 09:38:50 +0000663 if (Tok->SpacesRequiredBefore != 0)
664 break;
Manuel Klimekb3987012013-05-29 14:47:47 +0000665 Tok = Tok->Previous;
Daniel Jasperadc0f092013-04-05 09:38:50 +0000666 }
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000667 if (Previous.PartOfMultiVariableDeclStmt)
668 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
669 }
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000670
Daniel Jasper729a7432013-02-11 12:36:37 +0000671 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper20409152012-12-04 14:54:30 +0000672
Daniel Jasperbac016b2012-12-03 18:12:45 +0000673 if (!DryRun)
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000674 Whitespaces.replaceWhitespace(Current, 0, Spaces,
675 State.Column + Spaces);
Daniel Jasper20409152012-12-04 14:54:30 +0000676
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000677 if (Current.Type == TT_ObjCSelectorName &&
678 State.Stack.back().ColonPos == 0) {
679 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienko00895102013-06-05 14:09:10 +0000680 State.Column + Spaces + Current.CodePointCount)
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000681 State.Stack.back().ColonPos =
682 State.Stack.back().Indent + Current.LongestObjCSelectorName;
683 else
684 State.Stack.back().ColonPos =
Alexander Kornienko00895102013-06-05 14:09:10 +0000685 State.Column + Spaces + Current.CodePointCount;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000686 }
687
Daniel Jasperac3223e2013-04-10 09:49:49 +0000688 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000689 Current.Type != TT_LineComment)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000690 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000691 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
692 State.Stack.back().AvoidBinPacking)
693 State.Stack.back().NoLineBreak = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000694
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000695 State.Column += Spaces;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000696 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jaspere438bac2013-01-23 20:41:06 +0000697 // Treat the condition inside an if as if it was a second function
698 // parameter, i.e. let nested calls have an indent of 4.
699 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperf9955d32013-03-20 12:37:50 +0000700 else if (Previous.is(tok::comma))
Daniel Jaspere438bac2013-01-23 20:41:06 +0000701 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000702 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper02b771e2013-01-28 13:31:35 +0000703 Previous.Type == TT_ConditionalExpr ||
704 Previous.Type == TT_CtorInitializerColon) &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000705 !(Previous.getPrecedence() == prec::Assignment &&
Daniel Jasper512843a2013-05-27 12:45:09 +0000706 Current.FakeLParens.empty()))
707 // Always indent relative to the RHS of the expression unless this is a
708 // simple assignment without binary expression on the RHS.
Daniel Jasperae8699b2013-01-28 09:35:24 +0000709 State.Stack.back().LastSpace = State.Column;
Daniel Jasper6cabab42013-02-14 08:42:54 +0000710 else if (Previous.Type == TT_InheritanceColon)
711 State.Stack.back().Indent = State.Column;
Daniel Jasperb1491792013-07-09 11:57:27 +0000712 else if (Previous.opensScope()) {
713 // If a function has multiple parameters (including a single parameter
Daniel Jasper2ca37412013-07-09 14:36:48 +0000714 // that is a binary expression) or a trailing call, indent all
Daniel Jasperb1491792013-07-09 11:57:27 +0000715 // parameters from the opening parenthesis. This avoids confusing
716 // indents like:
717 // OuterFunction(InnerFunctionCall(
718 // ParameterToInnerFunction),
719 // SecondParameterToOuterFunction);
720 bool HasMultipleParameters = !Current.FakeLParens.empty();
721 bool HasTrailingCall = false;
722 if (Previous.MatchingParen) {
723 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
724 if (Next && Next->isOneOf(tok::period, tok::arrow))
725 HasTrailingCall = true;
726 }
727 if (HasMultipleParameters || HasTrailingCall)
728 State.Stack.back().LastSpace = State.Column;
729 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000730 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000731
Daniel Jasper0fde9502013-07-12 11:37:05 +0000732 return moveStateToNextToken(State, DryRun, Newline) + ExtraPenalty;
Daniel Jasper20409152012-12-04 14:54:30 +0000733 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000734
Daniel Jasper20409152012-12-04 14:54:30 +0000735 /// \brief Mark the next token as consumed in \p State and modify its stacks
736 /// accordingly.
Daniel Jasper0fde9502013-07-12 11:37:05 +0000737 unsigned moveStateToNextToken(LineState &State, bool DryRun, bool Newline) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000738 const FormatToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000739 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000740
Daniel Jasper6cabab42013-02-14 08:42:54 +0000741 if (Current.Type == TT_InheritanceColon)
742 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000743 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
744 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasper011c35d2013-07-12 11:19:37 +0000745 if (Current.is(tok::l_square) &&
746 State.Stack.back().StartOfArraySubscripts == 0)
747 State.Stack.back().StartOfArraySubscripts = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000748 if (Current.is(tok::question))
749 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper07ca5472013-07-05 09:14:35 +0000750 if (!Current.opensScope() && !Current.closesScope())
751 State.LowestLevelOnLine =
752 std::min(State.LowestLevelOnLine, State.ParenLevel);
753 if (Current.isOneOf(tok::period, tok::arrow) &&
754 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
755 State.Stack.back().StartOfFunctionCall =
756 Current.LastInChainOfCalls ? 0
757 : State.Column + Current.CodePointCount;
Daniel Jasper7d812812013-02-21 15:00:29 +0000758 if (Current.Type == TT_CtorInitializerColon) {
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000759 // Indent 2 from the column, so:
760 // SomeClass::SomeClass()
761 // : First(...), ...
762 // Next(...)
763 // ^ line up here.
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000764 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper7d812812013-02-21 15:00:29 +0000765 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
766 State.Stack.back().AvoidBinPacking = true;
767 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000768 }
Daniel Jasper3776ef32013-04-03 07:21:51 +0000769
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000770 // If return returns a binary expression, align after it.
771 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
772 State.Stack.back().LastSpace = State.Column + 7;
773
Daniel Jasper3776ef32013-04-03 07:21:51 +0000774 // In ObjC method declaration we align on the ":" of parameters, but we need
775 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasper37911302013-04-02 14:33:13 +0000776 if (Current.Type == TT_ObjCMethodSpecifier)
777 State.Stack.back().Indent += 4;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000778
Daniel Jasper29f123b2013-02-08 15:28:42 +0000779 // Insert scopes created by fake parenthesis.
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000780 const FormatToken *Previous = Current.getPreviousNonComment();
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000781 // Don't add extra indentation for the first fake parenthesis after
782 // 'return', assignements or opening <({[. The indentation for these cases
783 // is special cased.
784 bool SkipFirstExtraIndent =
785 Current.is(tok::kw_return) ||
Daniel Jasperac3223e2013-04-10 09:49:49 +0000786 (Previous && (Previous->opensScope() ||
Manuel Klimekb3987012013-05-29 14:47:47 +0000787 Previous->getPrecedence() == prec::Assignment));
Craig Topper163fbf82013-07-08 03:55:09 +0000788 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000789 I = Current.FakeLParens.rbegin(),
790 E = Current.FakeLParens.rend();
791 I != E; ++I) {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000792 ParenState NewParenState = State.Stack.back();
Daniel Jasper88cc5622013-07-08 14:25:23 +0000793 NewParenState.ContainsLineBreak = false;
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000794 NewParenState.Indent =
795 std::max(std::max(State.Column, NewParenState.Indent),
796 State.Stack.back().LastSpace);
797
798 // Always indent conditional expressions. Never indent expression where
799 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
800 // prec::Assignment) as those have different indentation rules. Indent
801 // other expression, unless the indentation needs to be skipped.
802 if (*I == prec::Conditional ||
803 (!SkipFirstExtraIndent && *I > prec::Assignment))
804 NewParenState.Indent += 4;
Daniel Jasperac3223e2013-04-10 09:49:49 +0000805 if (Previous && !Previous->opensScope())
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000806 NewParenState.BreakBeforeParameter = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000807 State.Stack.push_back(NewParenState);
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000808 SkipFirstExtraIndent = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000809 }
810
Daniel Jaspercf225b62012-12-24 13:43:52 +0000811 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000812 // prepare for the following tokens.
Daniel Jasperac3223e2013-04-10 09:49:49 +0000813 if (Current.opensScope()) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000814 unsigned NewIndent;
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000815 unsigned LastSpace = State.Stack.back().LastSpace;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000816 bool AvoidBinPacking;
Manuel Klimek2851c162013-01-10 14:36:46 +0000817 if (Current.is(tok::l_brace)) {
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000818 NewIndent = Style.IndentWidth + LastSpace;
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000819 const FormatToken *NextNoComment = Current.getNextNonComment();
Daniel Jasper5ad390d2013-05-28 11:30:49 +0000820 AvoidBinPacking = NextNoComment &&
821 NextNoComment->Type == TT_DesignatedInitializerPeriod;
Manuel Klimek2851c162013-01-10 14:36:46 +0000822 } else {
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000823 NewIndent =
824 4 + std::max(LastSpace, State.Stack.back().StartOfFunctionCall);
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000825 AvoidBinPacking = !Style.BinPackParameters ||
826 (Style.ExperimentalAutoDetectBinPacking &&
827 (Current.PackingKind == PPK_OnePerLine ||
828 (!BinPackInconclusiveFunctions &&
829 Current.PackingKind == PPK_Inconclusive)));
Manuel Klimek2851c162013-01-10 14:36:46 +0000830 }
Daniel Jasperfca24bc2013-04-25 13:31:51 +0000831
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000832 State.Stack.push_back(ParenState(NewIndent, LastSpace, AvoidBinPacking,
833 State.Stack.back().NoLineBreak));
Daniel Jasper29f123b2013-02-08 15:28:42 +0000834 ++State.ParenLevel;
Daniel Jasper20409152012-12-04 14:54:30 +0000835 }
836
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000837 // If this '[' opens an ObjC call, determine whether all parameters fit into
838 // one line and put one per line if they don't.
839 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
840 Current.MatchingParen != NULL) {
841 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
842 State.Stack.back().BreakBeforeParameter = true;
843 }
844
Daniel Jaspercf225b62012-12-24 13:43:52 +0000845 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000846 // stacks.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000847 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Manuel Klimekb3987012013-05-29 14:47:47 +0000848 (Current.is(tok::r_brace) && State.NextToken != RootToken) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +0000849 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000850 State.Stack.pop_back();
Daniel Jasper29f123b2013-02-08 15:28:42 +0000851 --State.ParenLevel;
852 }
Daniel Jasper011c35d2013-07-12 11:19:37 +0000853 if (Current.is(tok::r_square)) {
854 // If this ends the array subscript expr, reset the corresponding value.
855 const FormatToken *NextNonComment = Current.getNextNonComment();
856 if (NextNonComment && NextNonComment->isNot(tok::l_square))
Daniel Jasper9637dda2013-07-15 14:33:14 +0000857 State.Stack.back().StartOfArraySubscripts = 0;
Daniel Jasper011c35d2013-07-12 11:19:37 +0000858 }
Daniel Jasper29f123b2013-02-08 15:28:42 +0000859
860 // Remove scopes created by fake parenthesis.
861 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasperabfc9c12013-04-04 19:31:00 +0000862 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000863 State.Stack.pop_back();
Daniel Jasperabfc9c12013-04-04 19:31:00 +0000864 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000865 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000866
Daniel Jasper27c7f542013-05-13 20:50:15 +0000867 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000868 State.StartOfStringLiteral = State.Column;
Daniel Jasper27c7f542013-05-13 20:50:15 +0000869 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
870 tok::string_literal)) {
Daniel Jasper9a2f8d02013-05-16 04:26:02 +0000871 State.StartOfStringLiteral = 0;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000872 }
873
Alexander Kornienko00895102013-06-05 14:09:10 +0000874 State.Column += Current.CodePointCount;
Manuel Klimek8092a942013-02-20 10:15:13 +0000875
Manuel Klimekb3987012013-05-29 14:47:47 +0000876 State.NextToken = State.NextToken->Next;
Manuel Klimek2851c162013-01-10 14:36:46 +0000877
Daniel Jasper0fde9502013-07-12 11:37:05 +0000878 if (!Newline && Style.AlwaysBreakBeforeMultilineStrings &&
879 Current.is(tok::string_literal))
880 return 0;
881
Manuel Klimek8092a942013-02-20 10:15:13 +0000882 return breakProtrudingToken(Current, State, DryRun);
883 }
884
885 /// \brief If the current token sticks out over the end of the line, break
886 /// it if possible.
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000887 ///
888 /// \returns An extra penalty if a token was broken, otherwise 0.
889 ///
Alexander Kornienkod446f732013-07-01 13:42:42 +0000890 /// The returned penalty will cover the cost of the additional line breaks and
891 /// column limit violation in all lines except for the last one. The penalty
892 /// for the column limit violation in the last line (and in single line
893 /// tokens) is handled in \c addNextStateToQueue.
Manuel Klimekb3987012013-05-29 14:47:47 +0000894 unsigned breakProtrudingToken(const FormatToken &Current, LineState &State,
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000895 bool DryRun) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000896 llvm::OwningPtr<BreakableToken> Token;
Alexander Kornienko00895102013-06-05 14:09:10 +0000897 unsigned StartColumn = State.Column - Current.CodePointCount;
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000898 unsigned OriginalStartColumn =
Manuel Klimekb3987012013-05-29 14:47:47 +0000899 SourceMgr.getSpellingColumnNumber(Current.getStartOfNonWhitespace()) -
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000900 1;
Manuel Klimekde008c02013-05-27 15:23:34 +0000901
Daniel Jasper5d5b4242013-05-16 12:59:13 +0000902 if (Current.is(tok::string_literal) &&
903 Current.Type != TT_ImplicitStringLiteral) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000904 // Only break up default narrow strings.
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000905 if (!Current.TokenText.startswith("\""))
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000906 return 0;
907
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000908 Token.reset(new BreakableStringLiteral(Current, StartColumn,
909 Line.InPPDirective, Encoding));
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000910 } else if (Current.Type == TT_BlockComment) {
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000911 Token.reset(new BreakableBlockComment(
Alexander Kornienko00895102013-06-05 14:09:10 +0000912 Style, Current, StartColumn, OriginalStartColumn, !Current.Previous,
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000913 Line.InPPDirective, Encoding));
Daniel Jasper7ff96ed2013-05-06 10:24:51 +0000914 } else if (Current.Type == TT_LineComment &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000915 (Current.Previous == NULL ||
916 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000917 Token.reset(new BreakableLineComment(Current, StartColumn,
918 Line.InPPDirective, Encoding));
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000919 } else {
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000920 return 0;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000921 }
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000922 if (Current.UnbreakableTailLength >= getColumnLimit())
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000923 return 0;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000924
Alexander Kornienkoc36c5c22013-06-19 19:50:11 +0000925 unsigned RemainingSpace = getColumnLimit() - Current.UnbreakableTailLength;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000926 bool BreakInserted = false;
927 unsigned Penalty = 0;
Alexander Kornienkoc36c5c22013-06-19 19:50:11 +0000928 unsigned RemainingTokenColumns = 0;
Manuel Klimekde008c02013-05-27 15:23:34 +0000929 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
930 LineIndex != EndIndex; ++LineIndex) {
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000931 if (!DryRun)
932 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000933 unsigned TailOffset = 0;
Alexander Kornienkoc36c5c22013-06-19 19:50:11 +0000934 RemainingTokenColumns = Token->getLineLengthAfterSplit(
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000935 LineIndex, TailOffset, StringRef::npos);
Alexander Kornienko00895102013-06-05 14:09:10 +0000936 while (RemainingTokenColumns > RemainingSpace) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000937 BreakableToken::Split Split =
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000938 Token->getSplit(LineIndex, TailOffset, getColumnLimit());
Alexander Kornienkod446f732013-07-01 13:42:42 +0000939 if (Split.first == StringRef::npos) {
940 // The last line's penalty is handled in addNextStateToQueue().
941 if (LineIndex < EndIndex - 1)
942 Penalty += Style.PenaltyExcessCharacter *
943 (RemainingTokenColumns - RemainingSpace);
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000944 break;
Alexander Kornienkod446f732013-07-01 13:42:42 +0000945 }
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000946 assert(Split.first != 0);
Alexander Kornienko00895102013-06-05 14:09:10 +0000947 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000948 LineIndex, TailOffset + Split.first + Split.second,
949 StringRef::npos);
Alexander Kornienko00895102013-06-05 14:09:10 +0000950 assert(NewRemainingTokenColumns < RemainingTokenColumns);
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000951 if (!DryRun)
952 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000953 Penalty += Current.is(tok::string_literal) ? Style.PenaltyBreakString
954 : Style.PenaltyBreakComment;
955 unsigned ColumnsUsed =
956 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
957 if (ColumnsUsed > getColumnLimit()) {
958 Penalty +=
959 Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit());
960 }
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000961 TailOffset += Split.first + Split.second;
Alexander Kornienko00895102013-06-05 14:09:10 +0000962 RemainingTokenColumns = NewRemainingTokenColumns;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000963 BreakInserted = true;
Manuel Klimek8092a942013-02-20 10:15:13 +0000964 }
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000965 }
966
Alexander Kornienkoc36c5c22013-06-19 19:50:11 +0000967 State.Column = RemainingTokenColumns;
968
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000969 if (BreakInserted) {
Alexander Kornienko22d0e292013-06-17 12:59:44 +0000970 // If we break the token inside a parameter list, we need to break before
971 // the next parameter on all levels, so that the next parameter is clearly
972 // visible. Line comments already introduce a break.
973 if (Current.Type != TT_LineComment) {
974 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
975 State.Stack[i].BreakBeforeParameter = true;
976 }
977
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000978 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek8092a942013-02-20 10:15:13 +0000979 }
Manuel Klimek8092a942013-02-20 10:15:13 +0000980 return Penalty;
981 }
982
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000983 unsigned getColumnLimit() {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000984 // In preprocessor directives reserve two chars for trailing " \"
985 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000986 }
987
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000988 /// \brief An edge in the solution space from \c Previous->State to \c State,
989 /// inserting a newline dependent on the \c NewLine.
990 struct StateNode {
991 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +0000992 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000993 LineState State;
994 bool NewLine;
995 StateNode *Previous;
996 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000997
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000998 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
999 ///
1000 /// In case of equal penalties, we want to prefer states that were inserted
1001 /// first. During state generation we make sure that we insert states first
1002 /// that break the line as late as possible.
1003 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1004
1005 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
1006 /// \c State has the given \c OrderedPenalty.
1007 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1008
1009 /// \brief The BFS queue type.
1010 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1011 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001012
1013 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +00001014 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001015 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1016 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1017 /// find the shortest path (the one with lowest penalty) from \p InitialState
1018 /// to a state where all tokens are placed.
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001019 void analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001020 std::set<LineState> Seen;
1021
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001022 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +00001023 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001024 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
1025 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1026 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001027
1028 // While not empty, take first element and follow edges.
1029 while (!Queue.empty()) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001030 unsigned Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +00001031 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001032 if (Node->State.NextToken == NULL) {
Alexander Kornienkodd256312013-05-10 11:56:10 +00001033 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001034 break;
Daniel Jasper01786732013-02-04 07:21:18 +00001035 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001036 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001037
Daniel Jasper54b4e442013-05-22 05:27:42 +00001038 // Cut off the analysis of certain solutions if the analysis gets too
1039 // complex. See description of IgnoreStackForComparison.
1040 if (Count > 10000)
1041 Node->State.IgnoreStackForComparison = true;
1042
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001043 if (!Seen.insert(Node->State).second)
1044 // State already examined with lower penalty.
1045 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001046
Nico Weber27268772013-06-26 00:30:14 +00001047 addNextStateToQueue(Penalty, Node, /*NewLine=*/false);
1048 addNextStateToQueue(Penalty, Node, /*NewLine=*/true);
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001049 }
1050
1051 if (Queue.empty())
1052 // We were unable to find a solution, do nothing.
1053 // FIXME: Add diagnostic?
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001054 return;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001055
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001056 // Reconstruct the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001057 reconstructPath(InitialState, Queue.top().second);
Alexander Kornienkodd256312013-05-10 11:56:10 +00001058 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1059 DEBUG(llvm::dbgs() << "---\n");
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001060 }
1061
1062 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek9c333b92013-05-29 15:10:11 +00001063 std::deque<StateNode *> Path;
1064 // We do not need a break before the initial token.
1065 while (Current->Previous) {
1066 Path.push_front(Current);
1067 Current = Current->Previous;
1068 }
1069 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1070 I != E; ++I) {
1071 DEBUG({
1072 if ((*I)->NewLine) {
1073 llvm::dbgs() << "Penalty for splitting before "
1074 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
1075 << (*I)->Previous->State.NextToken->SplitPenalty << "\n";
1076 }
1077 });
1078 addTokenToState((*I)->NewLine, false, State);
1079 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001080 }
1081
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001082 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001083 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001084 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001085 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001086 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1087 bool NewLine) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001088 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001089 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001090 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001091 return;
Daniel Jasper88cc5622013-07-08 14:25:23 +00001092 if (NewLine) {
1093 if (!PreviousNode->State.Stack.back().ContainsLineBreak)
1094 Penalty += 15;
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001095 Penalty += PreviousNode->State.NextToken->SplitPenalty;
Daniel Jasper88cc5622013-07-08 14:25:23 +00001096 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001097
1098 StateNode *Node = new (Allocator.Allocate())
1099 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek8092a942013-02-20 10:15:13 +00001100 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001101 if (Node->State.Column > getColumnLimit()) {
1102 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper01786732013-02-04 07:21:18 +00001103 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasperceb99ab2013-01-09 10:16:05 +00001104 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001105
1106 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
1107 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001108 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001109
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001110 /// \brief Returns \c true, if a line break after \p State is allowed.
1111 bool canBreak(const LineState &State) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001112 const FormatToken &Current = *State.NextToken;
1113 const FormatToken &Previous = *Current.Previous;
1114 assert(&Previous == Current.Previous);
Daniel Jasper399914b2013-05-17 09:35:01 +00001115 if (!Current.CanBreakBefore &&
1116 !(Current.is(tok::r_brace) &&
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001117 State.Stack.back().BreakBeforeClosingBrace))
1118 return false;
Daniel Jasper399914b2013-05-17 09:35:01 +00001119 // The opening "{" of a braced list has to be on the same line as the first
1120 // element if it is nested in another braced init list or function call.
1121 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001122 Previous.Previous &&
1123 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
Daniel Jasper399914b2013-05-17 09:35:01 +00001124 return false;
Daniel Jasper259a0382013-05-27 11:50:16 +00001125 // This prevents breaks like:
1126 // ...
1127 // SomeParameter, OtherParameter).DoSomething(
1128 // ...
1129 // As they hide "DoSomething" and are generally bad for readability.
Daniel Jasper07ca5472013-07-05 09:14:35 +00001130 if (Previous.opensScope() &&
1131 State.LowestLevelOnLine < State.StartOfLineLevel)
Daniel Jasper259a0382013-05-27 11:50:16 +00001132 return false;
Daniel Jasper001bf4e2013-04-22 07:59:53 +00001133 return !State.Stack.back().NoLineBreak;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001134 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001135
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001136 /// \brief Returns \c true, if a line break after \p State is mandatory.
1137 bool mustBreak(const LineState &State) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001138 const FormatToken &Current = *State.NextToken;
1139 const FormatToken &Previous = *Current.Previous;
Daniel Jasper11e13802013-05-08 14:12:04 +00001140 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001141 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001142 if (Current.is(tok::r_brace) && State.Stack.back().BreakBeforeClosingBrace)
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001143 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001144 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001145 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001146 if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) ||
1147 Current.Type == TT_ConditionalExpr) &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +00001148 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper11e13802013-05-08 14:12:04 +00001149 !Current.isTrailingComment() &&
1150 !Current.isOneOf(tok::r_paren, tok::r_brace))
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001151 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001152
1153 // If we need to break somewhere inside the LHS of a binary expression, we
Daniel Jasper6df7a2d2013-07-03 10:34:47 +00001154 // should also break after the operator. Otherwise, the formatting would
1155 // hide the operator precedence, e.g. in:
1156 // if (aaaaaaaaaaaaaa ==
1157 // bbbbbbbbbbbbbb && c) {..
1158 // For comparisons, we only apply this rule, if the LHS is a binary
1159 // expression itself as otherwise, the line breaks seem superfluous.
1160 // We need special cases for ">>" which we have split into two ">" while
1161 // lexing in order to make template parsing easier.
1162 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
1163 Previous.getPrecedence() == prec::Equality) &&
1164 Previous.Previous &&
1165 Previous.Previous->Type != TT_BinaryOperator; // For >>.
1166 bool LHSIsBinaryExpr =
1167 Previous.Previous && Previous.Previous->FakeRParens > 0;
Daniel Jasper11e13802013-05-08 14:12:04 +00001168 if (Previous.Type == TT_BinaryOperator &&
Daniel Jasper6df7a2d2013-07-03 10:34:47 +00001169 (!IsComparison || LHSIsBinaryExpr) &&
1170 Current.Type != TT_BinaryOperator && // For >>.
Daniel Jasper5ef8aac2013-06-03 08:42:05 +00001171 !Current.isTrailingComment() &&
Daniel Jasper11e13802013-05-08 14:12:04 +00001172 !Previous.isOneOf(tok::lessless, tok::question) &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001173 Previous.getPrecedence() != prec::Assignment &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +00001174 State.Stack.back().BreakBeforeParameter)
Daniel Jasper63d7ced2013-02-05 10:07:47 +00001175 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001176
Daniel Jaspera0740f52013-07-12 15:14:05 +00001177 // Same as above, but for the first "<<" operator.
1178 if (Current.is(tok::lessless) && State.Stack.back().BreakBeforeParameter &&
1179 State.Stack.back().FirstLessLess == 0)
1180 return true;
1181
Daniel Jasper11e13802013-05-08 14:12:04 +00001182 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1183 // out whether it is the first parameter. Clean this up.
1184 if (Current.Type == TT_ObjCSelectorName &&
1185 Current.LongestObjCSelectorName == 0 &&
1186 State.Stack.back().BreakBeforeParameter)
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001187 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001188 if ((Current.Type == TT_CtorInitializerColon ||
1189 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0)))
Daniel Jasper923ebef2013-03-14 13:45:21 +00001190 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001191
Daniel Jasper6561f6a2013-07-09 07:43:55 +00001192 if ((Current.Type == TT_StartOfName || Current.is(tok::kw_operator)) &&
1193 Line.MightBeFunctionDecl && State.Stack.back().BreakBeforeParameter &&
1194 State.ParenLevel == 0)
Daniel Jasper33f4b902013-05-15 09:35:08 +00001195 return true;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001196 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001197 }
1198
Daniel Jasper3af59ce2013-03-15 14:57:30 +00001199 // Returns the total number of columns required for the remaining tokens.
1200 unsigned getRemainingLength(const LineState &State) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001201 if (State.NextToken && State.NextToken->Previous)
1202 return Line.Last->TotalLength - State.NextToken->Previous->TotalLength;
Daniel Jasper3af59ce2013-03-15 14:57:30 +00001203 return 0;
1204 }
1205
Daniel Jasperbac016b2012-12-03 18:12:45 +00001206 FormatStyle Style;
1207 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +00001208 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001209 const unsigned FirstIndent;
Manuel Klimekb3987012013-05-29 14:47:47 +00001210 const FormatToken *RootToken;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001211 WhitespaceManager &Whitespaces;
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001212
1213 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1214 QueueType Queue;
1215 // Increasing count of \c StateNode items we have created. This is used
1216 // to create a deterministic order independent of the container.
1217 unsigned Count;
Alexander Kornienko00895102013-06-05 14:09:10 +00001218 encoding::Encoding Encoding;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001219 bool BinPackInconclusiveFunctions;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001220};
1221
Manuel Klimek96e888b2013-05-28 11:55:06 +00001222class FormatTokenLexer {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001223public:
Alexander Kornienko00895102013-06-05 14:09:10 +00001224 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr,
1225 encoding::Encoding Encoding)
Manuel Klimek96e888b2013-05-28 11:55:06 +00001226 : FormatTok(NULL), GreaterStashed(false), TrailingWhitespace(0), Lex(Lex),
Alexander Kornienko00895102013-06-05 14:09:10 +00001227 SourceMgr(SourceMgr), IdentTable(Lex.getLangOpts()),
1228 Encoding(Encoding) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001229 Lex.SetKeepWhitespaceMode(true);
1230 }
1231
Manuel Klimek96e888b2013-05-28 11:55:06 +00001232 ArrayRef<FormatToken *> lex() {
1233 assert(Tokens.empty());
1234 do {
1235 Tokens.push_back(getNextToken());
1236 } while (Tokens.back()->Tok.isNot(tok::eof));
1237 return Tokens;
1238 }
1239
1240 IdentifierTable &getIdentTable() { return IdentTable; }
1241
1242private:
1243 FormatToken *getNextToken() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001244 if (GreaterStashed) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001245 // Create a synthesized second '>' token.
1246 Token Greater = FormatTok->Tok;
1247 FormatTok = new (Allocator.Allocate()) FormatToken;
1248 FormatTok->Tok = Greater;
Manuel Klimekad3094b2013-05-23 10:56:37 +00001249 SourceLocation GreaterLocation =
Manuel Klimek96e888b2013-05-28 11:55:06 +00001250 FormatTok->Tok.getLocation().getLocWithOffset(1);
1251 FormatTok->WhitespaceRange =
1252 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001253 FormatTok->TokenText = ">";
Alexander Kornienko00895102013-06-05 14:09:10 +00001254 FormatTok->CodePointCount = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001255 GreaterStashed = false;
1256 return FormatTok;
1257 }
1258
Manuel Klimek96e888b2013-05-28 11:55:06 +00001259 FormatTok = new (Allocator.Allocate()) FormatToken;
1260 Lex.LexFromRawLexer(FormatTok->Tok);
1261 StringRef Text = rawTokenText(FormatTok->Tok);
Manuel Klimekde008c02013-05-27 15:23:34 +00001262 SourceLocation WhitespaceStart =
Manuel Klimek96e888b2013-05-28 11:55:06 +00001263 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Manuel Klimekad3094b2013-05-23 10:56:37 +00001264 if (SourceMgr.getFileOffset(WhitespaceStart) == 0)
Manuel Klimek96e888b2013-05-28 11:55:06 +00001265 FormatTok->IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001266
1267 // Consume and record whitespace until we find a significant token.
Manuel Klimekde008c02013-05-27 15:23:34 +00001268 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001269 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimeka28fc062013-02-11 12:33:24 +00001270 unsigned Newlines = Text.count('\n');
Daniel Jasper1eee6c42013-03-04 13:43:19 +00001271 if (Newlines > 0)
Manuel Klimek96e888b2013-05-28 11:55:06 +00001272 FormatTok->LastNewlineOffset = WhitespaceLength + Text.rfind('\n') + 1;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001273 FormatTok->NewlinesBefore += Newlines;
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001274 unsigned EscapedNewlines = Text.count("\\\n");
Manuel Klimek96e888b2013-05-28 11:55:06 +00001275 FormatTok->HasUnescapedNewline |= EscapedNewlines != Newlines;
1276 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001277
Manuel Klimek96e888b2013-05-28 11:55:06 +00001278 Lex.LexFromRawLexer(FormatTok->Tok);
1279 Text = rawTokenText(FormatTok->Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001280 }
Manuel Klimek95419382013-01-07 07:56:50 +00001281
Manuel Klimekd4397b92013-01-04 23:34:14 +00001282 // In case the token starts with escaped newlines, we want to
1283 // take them into account as whitespace - this pattern is quite frequent
1284 // in macro definitions.
1285 // FIXME: What do we want to do with other escaped spaces, and escaped
1286 // spaces or newlines in the middle of tokens?
1287 // FIXME: Add a more explicit test.
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001288 while (Text.size() > 1 && Text[0] == '\\' && Text[1] == '\n') {
Manuel Klimek96e888b2013-05-28 11:55:06 +00001289 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimekad3094b2013-05-23 10:56:37 +00001290 WhitespaceLength += 2;
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001291 Text = Text.substr(2);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001292 }
1293
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001294 TrailingWhitespace = 0;
1295 if (FormatTok->Tok.is(tok::comment)) {
1296 StringRef UntrimmedText = Text;
1297 Text = Text.rtrim();
1298 TrailingWhitespace = UntrimmedText.size() - Text.size();
1299 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001300 IdentifierInfo &Info = IdentTable.get(Text);
Manuel Klimek96e888b2013-05-28 11:55:06 +00001301 FormatTok->Tok.setIdentifierInfo(&Info);
1302 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001303 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek96e888b2013-05-28 11:55:06 +00001304 FormatTok->Tok.setKind(tok::greater);
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001305 Text = Text.substr(0, 1);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001306 GreaterStashed = true;
1307 }
1308
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001309 // Now FormatTok is the next non-whitespace token.
1310 FormatTok->TokenText = Text;
1311 FormatTok->CodePointCount = encoding::getCodePointCount(Text, Encoding);
Alexander Kornienko00895102013-06-05 14:09:10 +00001312
Manuel Klimek96e888b2013-05-28 11:55:06 +00001313 FormatTok->WhitespaceRange = SourceRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001314 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001315 return FormatTok;
1316 }
1317
Manuel Klimek96e888b2013-05-28 11:55:06 +00001318 FormatToken *FormatTok;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001319 bool GreaterStashed;
Manuel Klimekde008c02013-05-27 15:23:34 +00001320 unsigned TrailingWhitespace;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001321 Lexer &Lex;
1322 SourceManager &SourceMgr;
1323 IdentifierTable IdentTable;
Alexander Kornienko00895102013-06-05 14:09:10 +00001324 encoding::Encoding Encoding;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001325 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1326 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001327
1328 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +00001329 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001330 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1331 Tok.getLength());
1332 }
1333};
1334
Daniel Jasperbac016b2012-12-03 18:12:45 +00001335class Formatter : public UnwrappedLineConsumer {
1336public:
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001337 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001338 const std::vector<CharSourceRange> &Ranges)
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001339 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko00895102013-06-05 14:09:10 +00001340 Whitespaces(SourceMgr, Style), Ranges(Ranges),
1341 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasper9637dda2013-07-15 14:33:14 +00001342 DEBUG(llvm::dbgs() << "File encoding: "
1343 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1344 : "unknown")
1345 << "\n");
Alexander Kornienko00895102013-06-05 14:09:10 +00001346 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001347
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001348 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001349
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001350 tooling::Replacements format() {
Alexander Kornienko00895102013-06-05 14:09:10 +00001351 FormatTokenLexer Tokens(Lex, SourceMgr, Encoding);
Manuel Klimek96e888b2013-05-28 11:55:06 +00001352
1353 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek67d080d2013-04-12 14:13:36 +00001354 bool StructuralError = Parser.parse();
Alexander Kornienko00895102013-06-05 14:09:10 +00001355 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001356 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1357 Annotator.annotate(AnnotatedLines[i]);
1358 }
1359 deriveLocalStyle();
1360 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1361 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1362 }
Daniel Jasper5999f762013-04-09 17:46:55 +00001363
1364 // Adapt level to the next line if this is a comment.
1365 // FIXME: Can/should this be done in the UnwrappedLineParser?
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001366 const AnnotatedLine *NextNonCommentLine = NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +00001367 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001368 if (NextNonCommentLine && AnnotatedLines[i].First->is(tok::comment) &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001369 !AnnotatedLines[i].First->Next)
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001370 AnnotatedLines[i].Level = NextNonCommentLine->Level;
Daniel Jasper5999f762013-04-09 17:46:55 +00001371 else
Daniel Jasper2a409b62013-07-08 14:34:09 +00001372 NextNonCommentLine = AnnotatedLines[i].First->isNot(tok::r_brace)
1373 ? &AnnotatedLines[i]
1374 : NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +00001375 }
1376
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001377 std::vector<int> IndentForLevel;
1378 bool PreviousLineWasTouched = false;
Manuel Klimekb3987012013-05-29 14:47:47 +00001379 const FormatToken *PreviousLineLastToken = 0;
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001380 bool FormatPPDirective = false;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001381 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1382 E = AnnotatedLines.end();
1383 I != E; ++I) {
1384 const AnnotatedLine &TheLine = *I;
Manuel Klimekb3987012013-05-29 14:47:47 +00001385 const FormatToken *FirstTok = TheLine.First;
1386 int Offset = getIndentOffset(*TheLine.First);
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001387
1388 // Check whether this line is part of a formatted preprocessor directive.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001389 if (FirstTok->HasUnescapedNewline)
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001390 FormatPPDirective = false;
1391 if (!FormatPPDirective && TheLine.InPPDirective &&
1392 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
1393 FormatPPDirective = true;
1394
Daniel Jasper1fb8d882013-05-14 09:30:02 +00001395 // Determine indent and try to merge multiple unwrapped lines.
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001396 while (IndentForLevel.size() <= TheLine.Level)
1397 IndentForLevel.push_back(-1);
1398 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper1fb8d882013-05-14 09:30:02 +00001399 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
1400 if (static_cast<int>(Indent) + Offset >= 0)
1401 Indent += Offset;
1402 tryFitMultipleLinesInOne(Indent, I, E);
1403
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001404 bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0;
Manuel Klimekb3987012013-05-29 14:47:47 +00001405 if (TheLine.First->is(tok::eof)) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001406 if (PreviousLineWasTouched) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001407 unsigned NewLines = std::min(FirstTok->NewlinesBefore, 1u);
Manuel Klimekb3987012013-05-29 14:47:47 +00001408 Whitespaces.replaceWhitespace(*TheLine.First, NewLines, /*Indent*/ 0,
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001409 /*TargetColumn*/ 0);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001410 }
1411 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001412 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001413 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001414 if (FirstTok->WhitespaceRange.isValid() &&
Manuel Klimek67d080d2013-04-12 14:13:36 +00001415 // Insert a break even if there is a structural error in case where
1416 // we break apart a line consisting of multiple unwrapped lines.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001417 (FirstTok->NewlinesBefore == 0 || !StructuralError)) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001418 formatFirstToken(*TheLine.First, PreviousLineLastToken, Indent,
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001419 TheLine.InPPDirective);
Manuel Klimek67d080d2013-04-12 14:13:36 +00001420 } else {
1421 Indent = LevelIndent =
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001422 SourceMgr.getSpellingColumnNumber(FirstTok->Tok.getLocation()) -
1423 1;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001424 }
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001425 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001426 TheLine.First, Whitespaces, Encoding,
1427 BinPackInconclusiveFunctions);
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001428 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001429 IndentForLevel[TheLine.Level] = LevelIndent;
1430 PreviousLineWasTouched = true;
1431 } else {
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001432 // Format the first token if necessary, and notify the WhitespaceManager
1433 // about the unchanged whitespace.
Manuel Klimekb3987012013-05-29 14:47:47 +00001434 for (const FormatToken *Tok = TheLine.First; Tok != NULL;
1435 Tok = Tok->Next) {
1436 if (Tok == TheLine.First &&
1437 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
1438 unsigned LevelIndent =
1439 SourceMgr.getSpellingColumnNumber(Tok->Tok.getLocation()) - 1;
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001440 // Remove trailing whitespace of the previous line if it was
1441 // touched.
1442 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
1443 formatFirstToken(*Tok, PreviousLineLastToken, LevelIndent,
1444 TheLine.InPPDirective);
1445 } else {
Manuel Klimekb3987012013-05-29 14:47:47 +00001446 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001447 }
Daniel Jasper1fb8d882013-05-14 09:30:02 +00001448
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001449 if (static_cast<int>(LevelIndent) - Offset >= 0)
1450 LevelIndent -= Offset;
1451 if (Tok->isNot(tok::comment))
1452 IndentForLevel[TheLine.Level] = LevelIndent;
1453 } else {
Manuel Klimekb3987012013-05-29 14:47:47 +00001454 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001455 }
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001456 }
1457 // If we did not reformat this unwrapped line, the column at the end of
1458 // the last token is unchanged - thus, we can calculate the end of the
1459 // last token.
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001460 PreviousLineWasTouched = false;
1461 }
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001462 PreviousLineLastToken = I->Last;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001463 }
1464 return Whitespaces.generateReplacements();
1465 }
1466
1467private:
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001468 void deriveLocalStyle() {
1469 unsigned CountBoundToVariable = 0;
1470 unsigned CountBoundToType = 0;
1471 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001472 bool HasBinPackedFunction = false;
1473 bool HasOnePerLineFunction = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001474 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001475 if (!AnnotatedLines[i].First->Next)
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001476 continue;
Manuel Klimekb3987012013-05-29 14:47:47 +00001477 FormatToken *Tok = AnnotatedLines[i].First->Next;
1478 while (Tok->Next) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001479 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001480 bool SpacesBefore =
1481 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1482 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1483 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001484 if (SpacesBefore && !SpacesAfter)
1485 ++CountBoundToVariable;
1486 else if (!SpacesBefore && SpacesAfter)
1487 ++CountBoundToType;
1488 }
1489
Daniel Jasper29f123b2013-02-08 15:28:42 +00001490 if (Tok->Type == TT_TemplateCloser &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001491 Tok->Previous->Type == TT_TemplateCloser &&
1492 Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd())
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001493 HasCpp03IncompatibleFormat = true;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001494
1495 if (Tok->PackingKind == PPK_BinPacked)
1496 HasBinPackedFunction = true;
1497 if (Tok->PackingKind == PPK_OnePerLine)
1498 HasOnePerLineFunction = true;
1499
Manuel Klimekb3987012013-05-29 14:47:47 +00001500 Tok = Tok->Next;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001501 }
1502 }
1503 if (Style.DerivePointerBinding) {
1504 if (CountBoundToType > CountBoundToVariable)
1505 Style.PointerBindsToType = true;
1506 else if (CountBoundToType < CountBoundToVariable)
1507 Style.PointerBindsToType = false;
1508 }
1509 if (Style.Standard == FormatStyle::LS_Auto) {
1510 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1511 : FormatStyle::LS_Cpp03;
1512 }
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001513 BinPackInconclusiveFunctions =
1514 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001515 }
1516
Manuel Klimek547d5db2013-02-08 17:38:27 +00001517 /// \brief Get the indent of \p Level from \p IndentForLevel.
1518 ///
1519 /// \p IndentForLevel must contain the indent for the level \c l
1520 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1521 /// that level is unknown.
Daniel Jasperfc759082013-02-14 14:26:07 +00001522 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimek547d5db2013-02-08 17:38:27 +00001523 if (IndentForLevel[Level] != -1)
1524 return IndentForLevel[Level];
Manuel Klimek52635ff2013-02-08 19:53:32 +00001525 if (Level == 0)
1526 return 0;
Manuel Klimek07a64ec2013-05-13 08:42:42 +00001527 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimek547d5db2013-02-08 17:38:27 +00001528 }
1529
1530 /// \brief Get the offset of the line relatively to the level.
1531 ///
1532 /// For example, 'public:' labels in classes are offset by 1 or 2
1533 /// characters to the left from their level.
Manuel Klimekb3987012013-05-29 14:47:47 +00001534 int getIndentOffset(const FormatToken &RootToken) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001535 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimek547d5db2013-02-08 17:38:27 +00001536 return Style.AccessModifierOffset;
1537 return 0;
1538 }
1539
Manuel Klimek517e8942013-01-11 17:54:10 +00001540 /// \brief Tries to merge lines into one.
1541 ///
1542 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1543 /// if possible; note that \c I will be incremented when lines are merged.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001544 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +00001545 std::vector<AnnotatedLine>::iterator &I,
1546 std::vector<AnnotatedLine>::iterator E) {
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001547 // We can never merge stuff if there are trailing line comments.
1548 if (I->Last->Type == TT_LineComment)
1549 return;
1550
Daniel Jaspera4d46212013-02-28 11:05:57 +00001551 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001552 // If we already exceed the column limit, we set 'Limit' to 0. The different
1553 // tryMerge..() functions can then decide whether to still do merging.
1554 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001555
Daniel Jasper9c8c40e2013-01-21 14:18:28 +00001556 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001557 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001558
Daniel Jasper5be59ba2013-05-15 14:09:55 +00001559 if (I->Last->is(tok::l_brace)) {
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001560 tryMergeSimpleBlock(I, E, Limit);
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001561 } else if (Style.AllowShortIfStatementsOnASingleLine &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001562 I->First->is(tok::kw_if)) {
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001563 tryMergeSimpleControlStatement(I, E, Limit);
1564 } else if (Style.AllowShortLoopsOnASingleLine &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001565 I->First->isOneOf(tok::kw_for, tok::kw_while)) {
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001566 tryMergeSimpleControlStatement(I, E, Limit);
Manuel Klimekb3987012013-05-29 14:47:47 +00001567 } else if (I->InPPDirective &&
1568 (I->First->HasUnescapedNewline || I->First->IsFirst)) {
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001569 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001570 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001571 }
1572
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001573 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1574 std::vector<AnnotatedLine>::iterator E,
1575 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001576 if (Limit == 0)
1577 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001578 AnnotatedLine &Line = *I;
Manuel Klimekb3987012013-05-29 14:47:47 +00001579 if (!(I + 1)->InPPDirective || (I + 1)->First->HasUnescapedNewline)
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001580 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001581 if (I + 2 != E && (I + 2)->InPPDirective &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001582 !(I + 2)->First->HasUnescapedNewline)
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001583 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001584 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001585 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001586 join(Line, *(++I));
1587 }
1588
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001589 void tryMergeSimpleControlStatement(std::vector<AnnotatedLine>::iterator &I,
1590 std::vector<AnnotatedLine>::iterator E,
1591 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001592 if (Limit == 0)
1593 return;
Manuel Klimek4c128122013-01-18 14:46:43 +00001594 if ((I + 1)->InPPDirective != I->InPPDirective ||
Manuel Klimekb3987012013-05-29 14:47:47 +00001595 ((I + 1)->InPPDirective && (I + 1)->First->HasUnescapedNewline))
Manuel Klimek4c128122013-01-18 14:46:43 +00001596 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001597 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001598 if (Line.Last->isNot(tok::r_paren))
1599 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001600 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001601 return;
Manuel Klimekb3987012013-05-29 14:47:47 +00001602 if ((I + 1)->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
1603 tok::kw_while) ||
1604 (I + 1)->First->Type == TT_LineComment)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001605 return;
1606 // Only inline simple if's (no nested if or else).
Manuel Klimekb3987012013-05-29 14:47:47 +00001607 if (I + 2 != E && Line.First->is(tok::kw_if) &&
1608 (I + 2)->First->is(tok::kw_else))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001609 return;
1610 join(Line, *(++I));
1611 }
1612
1613 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001614 std::vector<AnnotatedLine>::iterator E,
1615 unsigned Limit) {
Daniel Jasper5be59ba2013-05-15 14:09:55 +00001616 // No merging if the brace already is on the next line.
1617 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
1618 return;
1619
Manuel Klimek517e8942013-01-11 17:54:10 +00001620 // First, check that the current line allows merging. This is the case if
1621 // we're not in a control flow statement and the last token is an opening
1622 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001623 AnnotatedLine &Line = *I;
Manuel Klimekb3987012013-05-29 14:47:47 +00001624 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1625 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001626 tok::kw_for,
Manuel Klimekb3987012013-05-29 14:47:47 +00001627 // This gets rid of all ObjC @ keywords and methods.
1628 tok::at, tok::minus, tok::plus))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001629 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001630
Manuel Klimekb3987012013-05-29 14:47:47 +00001631 FormatToken *Tok = (I + 1)->First;
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001632 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001633 (Tok->getNextNonComment() == NULL ||
1634 Tok->getNextNonComment()->is(tok::semi))) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001635 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jasper729a7432013-02-11 12:36:37 +00001636 Tok->SpacesRequiredBefore = 0;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001637 Tok->CanBreakBefore = true;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001638 join(Line, *(I + 1));
1639 I += 1;
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001640 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001641 // Check that we still have three lines and they fit into the limit.
1642 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1643 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001644 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001645
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001646 // Second, check that the next line does not contain any braces - if it
1647 // does, readability declines when putting it into a single line.
1648 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1649 return;
1650 do {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001651 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001652 return;
Manuel Klimekb3987012013-05-29 14:47:47 +00001653 Tok = Tok->Next;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001654 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001655
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001656 // Last, check that the third line contains a single closing brace.
Manuel Klimekb3987012013-05-29 14:47:47 +00001657 Tok = (I + 2)->First;
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001658 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001659 Tok->MustBreakBefore)
1660 return;
1661
1662 join(Line, *(I + 1));
1663 join(Line, *(I + 2));
1664 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +00001665 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001666 }
1667
1668 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1669 unsigned Limit) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001670 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1671 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001672 }
1673
Daniel Jasper995e8202013-01-14 13:08:07 +00001674 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001675 assert(!A.Last->Next);
1676 assert(!B.First->Previous);
1677 A.Last->Next = B.First;
1678 B.First->Previous = A.Last;
1679 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1680 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1681 Tok->TotalLength += LengthA;
1682 A.Last = Tok;
Daniel Jasper995e8202013-01-14 13:08:07 +00001683 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001684 }
1685
Daniel Jasper6f21a982013-03-13 07:49:51 +00001686 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf3023542013-03-07 20:50:00 +00001687 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1688 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1689 Ranges[i].getBegin()) &&
1690 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1691 Range.getBegin()))
1692 return true;
1693 }
1694 return false;
1695 }
1696
1697 bool touchesLine(const AnnotatedLine &TheLine) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001698 const FormatToken *First = TheLine.First;
1699 const FormatToken *Last = TheLine.Last;
Daniel Jasper84f5ddf2013-05-14 10:31:09 +00001700 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001701 First->WhitespaceRange.getBegin().getLocWithOffset(
1702 First->LastNewlineOffset),
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001703 Last->Tok.getLocation().getLocWithOffset(Last->TokenText.size() - 1));
Daniel Jasperf3023542013-03-07 20:50:00 +00001704 return touchesRanges(LineRange);
1705 }
1706
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001707 bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I,
1708 std::vector<AnnotatedLine>::iterator E) {
1709 for (; I != E; ++I) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001710 if (I->First->HasUnescapedNewline)
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001711 return false;
1712 if (touchesLine(*I))
1713 return true;
1714 }
1715 return false;
1716 }
1717
Daniel Jasperf3023542013-03-07 20:50:00 +00001718 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001719 const FormatToken *First = TheLine.First;
Daniel Jasperf3023542013-03-07 20:50:00 +00001720 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001721 First->WhitespaceRange.getBegin(),
1722 First->WhitespaceRange.getBegin().getLocWithOffset(
1723 First->LastNewlineOffset));
Daniel Jasperf3023542013-03-07 20:50:00 +00001724 return touchesRanges(LineRange);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001725 }
1726
1727 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +00001728 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001729 }
1730
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001731 /// \brief Add a new line and the required indent before the first Token
1732 /// of the \c UnwrappedLine if there was no structural parsing error.
1733 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimekb3987012013-05-29 14:47:47 +00001734 void formatFirstToken(const FormatToken &RootToken,
1735 const FormatToken *PreviousToken, unsigned Indent,
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001736 bool InPPDirective) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001737 unsigned Newlines =
Manuel Klimekb3987012013-05-29 14:47:47 +00001738 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Daniel Jasper15f33f02013-06-03 16:16:41 +00001739 // Remove empty lines before "}" where applicable.
1740 if (RootToken.is(tok::r_brace) &&
1741 (!RootToken.Next ||
1742 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1743 Newlines = std::min(Newlines, 1u);
Manuel Klimekb3987012013-05-29 14:47:47 +00001744 if (Newlines == 0 && !RootToken.IsFirst)
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001745 Newlines = 1;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001746
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001747 // Insert extra new line before access specifiers.
1748 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001749 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001750 ++Newlines;
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001751
Manuel Klimekb3987012013-05-29 14:47:47 +00001752 Whitespaces.replaceWhitespace(
1753 RootToken, Newlines, Indent, Indent,
1754 InPPDirective && !RootToken.HasUnescapedNewline);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001755 }
1756
Daniel Jasperbac016b2012-12-03 18:12:45 +00001757 FormatStyle Style;
1758 Lexer &Lex;
1759 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001760 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001761 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001762 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko00895102013-06-05 14:09:10 +00001763
1764 encoding::Encoding Encoding;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001765 bool BinPackInconclusiveFunctions;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001766};
1767
Craig Topper83f81d72013-06-30 22:29:28 +00001768} // end anonymous namespace
1769
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001770tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1771 SourceManager &SourceMgr,
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001772 std::vector<CharSourceRange> Ranges) {
1773 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001774 return formatter.format();
1775}
1776
Daniel Jasper8a999452013-05-16 10:40:07 +00001777tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1778 std::vector<tooling::Range> Ranges,
1779 StringRef FileName) {
1780 FileManager Files((FileSystemOptions()));
1781 DiagnosticsEngine Diagnostics(
1782 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1783 new DiagnosticOptions);
1784 SourceManager SourceMgr(Diagnostics, Files);
1785 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1786 const clang::FileEntry *Entry =
1787 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1788 SourceMgr.overrideFileContents(Entry, Buf);
1789 FileID ID =
1790 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001791 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1792 getFormattingLangOpts(Style.Standard));
Daniel Jasper8a999452013-05-16 10:40:07 +00001793 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1794 std::vector<CharSourceRange> CharRanges;
1795 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1796 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1797 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1798 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1799 }
1800 return reformat(Style, Lex, SourceMgr, CharRanges);
1801}
1802
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001803LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasper46ef8522013-01-10 13:08:12 +00001804 LangOptions LangOpts;
1805 LangOpts.CPlusPlus = 1;
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001806 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasperb64eca02013-03-22 10:01:29 +00001807 LangOpts.LineComment = 1;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001808 LangOpts.Bool = 1;
1809 LangOpts.ObjC1 = 1;
1810 LangOpts.ObjC2 = 1;
1811 return LangOpts;
1812}
1813
Daniel Jaspercd162382013-01-07 13:26:07 +00001814} // namespace format
1815} // namespace clang