blob: 0dd47fe4a99b18365eb6e21f4e5a0c7c95c2fe43 [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);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000105 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
106 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
107 Style.PenaltyReturnTypeOnItsOwnLine);
108 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
109 IO.mapOptional("SpacesBeforeTrailingComments",
110 Style.SpacesBeforeTrailingComments);
Daniel Jasper1bee0732013-05-23 18:05:18 +0000111 IO.mapOptional("SpacesInBracedLists", Style.SpacesInBracedLists);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000112 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000113 IO.mapOptional("IndentWidth", Style.IndentWidth);
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000114 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimek44135b82013-05-13 12:51:40 +0000115 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimeka9a7f102013-06-21 17:25:42 +0000116 IO.mapOptional("IndentFunctionDeclarationAfterType",
117 Style.IndentFunctionDeclarationAfterType);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000118 }
119};
120}
121}
122
Daniel Jasperbac016b2012-12-03 18:12:45 +0000123namespace clang {
124namespace format {
125
Daniel Jasperbac016b2012-12-03 18:12:45 +0000126FormatStyle getLLVMStyle() {
127 FormatStyle LLVMStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000128 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000129 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasperf1579602013-01-29 16:03:49 +0000130 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000131 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000132 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperbbc87762013-05-29 12:07:31 +0000133 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienko56312022013-07-04 12:02:44 +0000134 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000135 LLVMStyle.BinPackParameters = true;
136 LLVMStyle.ColumnLimit = 80;
137 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
138 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000139 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000140 LLVMStyle.IndentCaseLabels = false;
141 LLVMStyle.MaxEmptyLinesToKeep = 1;
Nico Weber5f500df2013-01-10 20:12:55 +0000142 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000143 LLVMStyle.PenaltyBreakComment = 45;
144 LLVMStyle.PenaltyBreakString = 1000;
Daniel Jasper01786732013-02-04 07:21:18 +0000145 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper88cc5622013-07-08 14:25:23 +0000146 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000147 LLVMStyle.PointerBindsToType = false;
148 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper2424eef2013-05-23 10:15:45 +0000149 LLVMStyle.SpacesInBracedLists = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000150 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000151 LLVMStyle.IndentWidth = 2;
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000152 LLVMStyle.UseTab = false;
Manuel Klimek44135b82013-05-13 12:51:40 +0000153 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Manuel Klimeka9a7f102013-06-21 17:25:42 +0000154 LLVMStyle.IndentFunctionDeclarationAfterType = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000155 return LLVMStyle;
156}
157
158FormatStyle getGoogleStyle() {
159 FormatStyle GoogleStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000160 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000161 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000162 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000163 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper1bee0732013-05-23 18:05:18 +0000164 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Daniel Jasperbbc87762013-05-29 12:07:31 +0000165 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienko56312022013-07-04 12:02:44 +0000166 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000167 GoogleStyle.BinPackParameters = true;
168 GoogleStyle.ColumnLimit = 80;
169 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
170 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000171 GoogleStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000172 GoogleStyle.IndentCaseLabels = true;
173 GoogleStyle.MaxEmptyLinesToKeep = 1;
Nico Weber5f500df2013-01-10 20:12:55 +0000174 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000175 GoogleStyle.PenaltyBreakComment = 45;
176 GoogleStyle.PenaltyBreakString = 1000;
Daniel Jasper01786732013-02-04 07:21:18 +0000177 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper1407bee2013-04-11 14:29:13 +0000178 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000179 GoogleStyle.PointerBindsToType = true;
180 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper2424eef2013-05-23 10:15:45 +0000181 GoogleStyle.SpacesInBracedLists = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000182 GoogleStyle.Standard = FormatStyle::LS_Auto;
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000183 GoogleStyle.IndentWidth = 2;
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000184 GoogleStyle.UseTab = false;
Manuel Klimek44135b82013-05-13 12:51:40 +0000185 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Manuel Klimeka9a7f102013-06-21 17:25:42 +0000186 GoogleStyle.IndentFunctionDeclarationAfterType = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000187 return GoogleStyle;
188}
189
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000190FormatStyle getChromiumStyle() {
191 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +0000192 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000193 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000194 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000195 ChromiumStyle.BinPackParameters = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000196 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
197 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000198 return ChromiumStyle;
199}
200
Alexander Kornienkofb594862013-05-06 14:11:27 +0000201FormatStyle getMozillaStyle() {
202 FormatStyle MozillaStyle = getLLVMStyle();
203 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
204 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
205 MozillaStyle.DerivePointerBinding = true;
206 MozillaStyle.IndentCaseLabels = true;
207 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
208 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
209 MozillaStyle.PointerBindsToType = true;
210 return MozillaStyle;
211}
212
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000213bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000214 if (Name.equals_lower("llvm"))
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000215 *Style = getLLVMStyle();
216 else if (Name.equals_lower("chromium"))
217 *Style = getChromiumStyle();
218 else if (Name.equals_lower("mozilla"))
219 *Style = getMozillaStyle();
220 else if (Name.equals_lower("google"))
221 *Style = getGoogleStyle();
222 else
223 return false;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000224
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000225 return true;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000226}
227
228llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienko107db3c2013-05-20 15:18:01 +0000229 if (Text.trim().empty())
230 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000231 llvm::yaml::Input Input(Text);
232 Input >> *Style;
233 return Input.error();
234}
235
236std::string configurationAsText(const FormatStyle &Style) {
237 std::string Text;
238 llvm::raw_string_ostream Stream(Text);
239 llvm::yaml::Output Output(Stream);
240 // We use the same mapping method for input and output, so we need a non-const
241 // reference here.
242 FormatStyle NonConstStyle = Style;
243 Output << NonConstStyle;
Alexander Kornienko2b6acb62013-05-13 12:56:35 +0000244 return Stream.str();
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000245}
246
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000247// Returns the length of everything up to the first possible line break after
248// the ), ], } or > matching \c Tok.
Manuel Klimekb3987012013-05-29 14:47:47 +0000249static unsigned getLengthToMatchingParen(const FormatToken &Tok) {
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000250 if (Tok.MatchingParen == NULL)
251 return 0;
Manuel Klimekb3987012013-05-29 14:47:47 +0000252 FormatToken *End = Tok.MatchingParen;
253 while (End->Next && !End->Next->CanBreakBefore) {
254 End = End->Next;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000255 }
256 return End->TotalLength - Tok.TotalLength + 1;
257}
258
Craig Topper83f81d72013-06-30 22:29:28 +0000259namespace {
260
Daniel Jasperbac016b2012-12-03 18:12:45 +0000261class UnwrappedLineFormatter {
262public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000263 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper995e8202013-01-14 13:08:07 +0000264 const AnnotatedLine &Line, unsigned FirstIndent,
Manuel Klimekb3987012013-05-29 14:47:47 +0000265 const FormatToken *RootToken,
Alexander Kornienko00895102013-06-05 14:09:10 +0000266 WhitespaceManager &Whitespaces,
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000267 encoding::Encoding Encoding,
268 bool BinPackInconclusiveFunctions)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000269 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000270 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000271 Whitespaces(Whitespaces), Count(0), Encoding(Encoding),
272 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000273
Manuel Klimekd4397b92013-01-04 23:34:14 +0000274 /// \brief Formats an \c UnwrappedLine.
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000275 void format(const AnnotatedLine *NextLine) {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000276 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000277 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000278 State.Column = FirstIndent;
Manuel Klimekb3987012013-05-29 14:47:47 +0000279 State.NextToken = RootToken;
Daniel Jasper2a409b62013-07-08 14:34:09 +0000280 State.Stack.push_back(ParenState(FirstIndent, FirstIndent,
281 /*AvoidBinPacking=*/false,
282 /*NoLineBreak=*/false));
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000283 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000284 State.ParenLevel = 0;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000285 State.StartOfStringLiteral = 0;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000286 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper07ca5472013-07-05 09:14:35 +0000287 State.LowestLevelOnLine = State.ParenLevel;
Daniel Jasper54b4e442013-05-22 05:27:42 +0000288 State.IgnoreStackForComparison = false;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000289
290 // The first token has already been indented and thus consumed.
Nico Weber27268772013-06-26 00:30:14 +0000291 moveStateToNextToken(State, /*DryRun=*/false);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000292
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000293 // If everything fits on a single line, just put it there.
Daniel Jaspera4d46212013-02-28 11:05:57 +0000294 unsigned ColumnLimit = Style.ColumnLimit;
295 if (NextLine && NextLine->InPPDirective &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000296 !NextLine->First->HasUnescapedNewline)
Daniel Jaspera4d46212013-02-28 11:05:57 +0000297 ColumnLimit = getColumnLimit();
298 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000299 while (State.NextToken != NULL) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000300 addTokenToState(false, false, State);
Daniel Jasper1321eb52012-12-18 21:05:13 +0000301 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000302 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000303
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000304 // If the ObjC method declaration does not fit on a line, we should format
305 // it with one arg per line.
306 if (Line.Type == LT_ObjCMethodDecl)
307 State.Stack.back().BreakBeforeParameter = true;
308
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000309 // Find best solution in solution space.
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000310 analyzeSolutionSpace(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000311 }
312
313private:
Manuel Klimekb3987012013-05-29 14:47:47 +0000314 void DebugTokenState(const FormatToken &FormatTok) {
315 const Token &Tok = FormatTok.Tok;
Alexander Kornienkodd256312013-05-10 11:56:10 +0000316 llvm::dbgs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000317 Tok.getLength());
Alexander Kornienkodd256312013-05-10 11:56:10 +0000318 llvm::dbgs();
Manuel Klimekca547db2013-01-16 14:55:28 +0000319 }
320
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000321 struct ParenState {
Daniel Jasperd399bff2013-02-05 09:41:21 +0000322 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000323 bool NoLineBreak)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000324 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
325 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000326 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000327 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
328 NestedNameSpecifierContinuation(0), CallContinuation(0),
Daniel Jasper88cc5622013-07-08 14:25:23 +0000329 VariablePos(0), ContainsLineBreak(false) {}
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000330
Daniel Jasperbac016b2012-12-03 18:12:45 +0000331 /// \brief The position to which a specific parenthesis level needs to be
332 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000333 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000334
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000335 /// \brief The position of the last space on each level.
336 ///
337 /// Used e.g. to break like:
338 /// functionCall(Parameter, otherCall(
339 /// OtherParameter));
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000340 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000341
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000342 /// \brief The position the first "<<" operator encountered on each level.
343 ///
344 /// Used to align "<<" operators. 0 if no such operator has been encountered
345 /// on a level.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000346 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000347
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000348 /// \brief Whether a newline needs to be inserted before the block's closing
349 /// brace.
350 ///
351 /// We only want to insert a newline before the closing brace if there also
352 /// was a newline after the beginning left brace.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000353 bool BreakBeforeClosingBrace;
354
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000355 /// \brief The column of a \c ? in a conditional expression;
356 unsigned QuestionColumn;
357
Daniel Jasperf343cab2013-01-31 14:59:26 +0000358 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
359 /// lines, in this context.
360 bool AvoidBinPacking;
361
362 /// \brief Break after the next comma (or all the commas in this context if
363 /// \c AvoidBinPacking is \c true).
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000364 bool BreakBeforeParameter;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000365
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000366 /// \brief Line breaking in this context would break a formatting rule.
367 bool NoLineBreak;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000368
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000369 /// \brief The position of the colon in an ObjC method declaration/call.
370 unsigned ColonPos;
Daniel Jasperc4615b72013-02-20 12:56:39 +0000371
Daniel Jasper24849712013-03-01 16:48:32 +0000372 /// \brief The start of the most recent function in a builder-type call.
373 unsigned StartOfFunctionCall;
374
Daniel Jasper37911302013-04-02 14:33:13 +0000375 /// \brief If a nested name specifier was broken over multiple lines, this
376 /// contains the start column of the second line. Otherwise 0.
377 unsigned NestedNameSpecifierContinuation;
378
379 /// \brief If a call expression was broken over multiple lines, this
380 /// contains the start column of the second line. Otherwise 0.
381 unsigned CallContinuation;
382
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000383 /// \brief The column of the first variable name in a variable declaration.
384 ///
385 /// Used to align further variables if necessary.
386 unsigned VariablePos;
387
Daniel Jasper88cc5622013-07-08 14:25:23 +0000388 /// \brief \c true if this \c ParenState already contains a line-break.
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000389 ///
Daniel Jasper88cc5622013-07-08 14:25:23 +0000390 /// The first line break in a certain \c ParenState causes extra penalty so
391 /// that clang-format prefers similar breaks, i.e. breaks in the same
392 /// parenthesis.
393 bool ContainsLineBreak;
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000394
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000395 bool operator<(const ParenState &Other) const {
396 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000397 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000398 if (LastSpace != Other.LastSpace)
399 return LastSpace < Other.LastSpace;
400 if (FirstLessLess != Other.FirstLessLess)
401 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000402 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
403 return BreakBeforeClosingBrace;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000404 if (QuestionColumn != Other.QuestionColumn)
405 return QuestionColumn < Other.QuestionColumn;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000406 if (AvoidBinPacking != Other.AvoidBinPacking)
407 return AvoidBinPacking;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000408 if (BreakBeforeParameter != Other.BreakBeforeParameter)
409 return BreakBeforeParameter;
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000410 if (NoLineBreak != Other.NoLineBreak)
411 return NoLineBreak;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000412 if (ColonPos != Other.ColonPos)
413 return ColonPos < Other.ColonPos;
Daniel Jasper24849712013-03-01 16:48:32 +0000414 if (StartOfFunctionCall != Other.StartOfFunctionCall)
415 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasper37911302013-04-02 14:33:13 +0000416 if (CallContinuation != Other.CallContinuation)
417 return CallContinuation < Other.CallContinuation;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000418 if (VariablePos != Other.VariablePos)
419 return VariablePos < Other.VariablePos;
Daniel Jasper88cc5622013-07-08 14:25:23 +0000420 if (ContainsLineBreak != Other.ContainsLineBreak)
421 return ContainsLineBreak < Other.ContainsLineBreak;
Daniel Jasperb3123142013-01-12 07:36:22 +0000422 return false;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000423 }
424 };
425
426 /// \brief The current state when indenting a unwrapped line.
427 ///
428 /// As the indenting tries different combinations this is copied by value.
429 struct LineState {
430 /// \brief The number of used columns in the current line.
431 unsigned Column;
432
433 /// \brief The token that needs to be next formatted.
Manuel Klimekb3987012013-05-29 14:47:47 +0000434 const FormatToken *NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000435
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000436 /// \brief \c true if this line contains a continued for-loop section.
437 bool LineContainsContinuedForLoopSection;
438
Daniel Jasper29f123b2013-02-08 15:28:42 +0000439 /// \brief The level of nesting inside (), [], <> and {}.
440 unsigned ParenLevel;
441
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000442 /// \brief The \c ParenLevel at the start of this line.
443 unsigned StartOfLineLevel;
444
Daniel Jasper07ca5472013-07-05 09:14:35 +0000445 /// \brief The lowest \c ParenLevel on the current line.
446 unsigned LowestLevelOnLine;
Daniel Jasper259a0382013-05-27 11:50:16 +0000447
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000448 /// \brief The start column of the string literal, if we're in a string
449 /// literal sequence, 0 otherwise.
450 unsigned StartOfStringLiteral;
451
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000452 /// \brief A stack keeping track of properties applying to parenthesis
453 /// levels.
454 std::vector<ParenState> Stack;
455
Daniel Jasper54b4e442013-05-22 05:27:42 +0000456 /// \brief Ignore the stack of \c ParenStates for state comparison.
457 ///
458 /// In long and deeply nested unwrapped lines, the current algorithm can
459 /// be insufficient for finding the best formatting with a reasonable amount
460 /// of time and memory. Setting this flag will effectively lead to the
461 /// algorithm not analyzing some combinations. However, these combinations
462 /// rarely contain the optimal solution: In short, accepting a higher
463 /// penalty early would need to lead to different values in the \c
464 /// ParenState stack (in an otherwise identical state) and these different
465 /// values would need to lead to a significant amount of avoided penalty
466 /// later.
467 ///
468 /// FIXME: Come up with a better algorithm instead.
469 bool IgnoreStackForComparison;
470
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000471 /// \brief Comparison operator to be able to used \c LineState in \c map.
472 bool operator<(const LineState &Other) const {
Daniel Jasperd7896702013-02-19 09:28:55 +0000473 if (NextToken != Other.NextToken)
474 return NextToken < Other.NextToken;
475 if (Column != Other.Column)
476 return Column < Other.Column;
Daniel Jasperd7896702013-02-19 09:28:55 +0000477 if (LineContainsContinuedForLoopSection !=
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000478 Other.LineContainsContinuedForLoopSection)
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000479 return LineContainsContinuedForLoopSection;
Daniel Jasperd7896702013-02-19 09:28:55 +0000480 if (ParenLevel != Other.ParenLevel)
481 return ParenLevel < Other.ParenLevel;
482 if (StartOfLineLevel != Other.StartOfLineLevel)
483 return StartOfLineLevel < Other.StartOfLineLevel;
Daniel Jasper07ca5472013-07-05 09:14:35 +0000484 if (LowestLevelOnLine != Other.LowestLevelOnLine)
485 return LowestLevelOnLine < Other.LowestLevelOnLine;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000486 if (StartOfStringLiteral != Other.StartOfStringLiteral)
487 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper54b4e442013-05-22 05:27:42 +0000488 if (IgnoreStackForComparison || Other.IgnoreStackForComparison)
489 return false;
Daniel Jasperd7896702013-02-19 09:28:55 +0000490 return Stack < Other.Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000491 }
492 };
493
Daniel Jasper20409152012-12-04 14:54:30 +0000494 /// \brief Appends the next token to \p State and updates information
495 /// necessary for indentation.
496 ///
Nico Weber1907c572013-06-26 02:42:46 +0000497 /// Puts the token on the current line if \p Newline is \c false and adds a
Daniel Jasper20409152012-12-04 14:54:30 +0000498 /// line break and necessary indentation otherwise.
499 ///
500 /// If \p DryRun is \c false, also creates and stores the required
501 /// \c Replacement.
Manuel Klimek8092a942013-02-20 10:15:13 +0000502 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000503 const FormatToken &Current = *State.NextToken;
504 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000505
Daniel Jasper92f9faf2013-03-20 15:58:10 +0000506 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Manuel Klimekad3094b2013-05-23 10:56:37 +0000507 // FIXME: Is this correct?
Manuel Klimekb3987012013-05-29 14:47:47 +0000508 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
509 State.NextToken->WhitespaceRange.getEnd()) -
510 SourceMgr.getSpellingColumnNumber(
511 State.NextToken->WhitespaceRange.getBegin());
Alexander Kornienko00895102013-06-05 14:09:10 +0000512 State.Column += WhitespaceLength + State.NextToken->CodePointCount;
Manuel Klimekb3987012013-05-29 14:47:47 +0000513 State.NextToken = State.NextToken->Next;
Manuel Klimek8092a942013-02-20 10:15:13 +0000514 return 0;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000515 }
516
Daniel Jasper3776ef32013-04-03 07:21:51 +0000517 // If we are continuing an expression, we want to indent an extra 4 spaces.
518 unsigned ContinuationIndent =
Daniel Jasper37911302013-04-02 14:33:13 +0000519 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000520 if (Newline) {
Daniel Jasper88cc5622013-07-08 14:25:23 +0000521 State.Stack.back().ContainsLineBreak = true;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000522 if (Current.is(tok::r_brace)) {
Daniel Jasper0de1c4d2013-07-09 09:06:29 +0000523 if (Current.BlockKind == BK_BracedInit)
524 State.Column = State.Stack[State.Stack.size() - 2].LastSpace;
525 else
526 State.Column = Line.Level * Style.IndentWidth;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000527 } else if (Current.is(tok::string_literal) &&
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000528 State.StartOfStringLiteral != 0) {
529 State.Column = State.StartOfStringLiteral;
Daniel Jasper66d19bd2013-02-18 11:59:17 +0000530 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000531 } else if (Current.is(tok::lessless) &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000532 State.Stack.back().FirstLessLess != 0) {
533 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasper5ad390d2013-05-28 11:30:49 +0000534 } else if (Current.isOneOf(tok::period, tok::arrow) &&
535 Current.Type != TT_DesignatedInitializerPeriod) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000536 if (State.Stack.back().CallContinuation == 0) {
537 State.Column = ContinuationIndent;
Daniel Jasper37911302013-04-02 14:33:13 +0000538 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000539 } else {
540 State.Column = State.Stack.back().CallContinuation;
541 }
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000542 } else if (Current.Type == TT_ConditionalExpr) {
543 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000544 } else if (Previous.is(tok::comma) &&
545 State.Stack.back().VariablePos != 0) {
546 State.Column = State.Stack.back().VariablePos;
Daniel Jasper3c08a812013-02-24 18:54:32 +0000547 } else if (Previous.ClosesTemplateDeclaration ||
Daniel Jasper6561f6a2013-07-09 07:43:55 +0000548 ((Current.Type == TT_StartOfName ||
549 Current.is(tok::kw_operator)) &&
550 State.ParenLevel == 0 &&
Manuel Klimeka9a7f102013-06-21 17:25:42 +0000551 (!Style.IndentFunctionDeclarationAfterType ||
552 Line.StartsDefinition))) {
Daniel Jasper37911302013-04-02 14:33:13 +0000553 State.Column = State.Stack.back().Indent;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000554 } else if (Current.Type == TT_ObjCSelectorName) {
Alexander Kornienko00895102013-06-05 14:09:10 +0000555 if (State.Stack.back().ColonPos > Current.CodePointCount) {
556 State.Column = State.Stack.back().ColonPos - Current.CodePointCount;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000557 } else {
558 State.Column = State.Stack.back().Indent;
Alexander Kornienko00895102013-06-05 14:09:10 +0000559 State.Stack.back().ColonPos = State.Column + Current.CodePointCount;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000560 }
Daniel Jasperb2f063a2013-05-08 10:00:18 +0000561 } else if (Current.Type == TT_StartOfName ||
562 Previous.isOneOf(tok::coloncolon, tok::equal) ||
Daniel Jasper37911302013-04-02 14:33:13 +0000563 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000564 State.Column = ContinuationIndent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000565 } else {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000566 State.Column = State.Stack.back().Indent;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000567 // Ensure that we fall back to indenting 4 spaces instead of just
568 // flushing continuations left.
Daniel Jasper37911302013-04-02 14:33:13 +0000569 if (State.Column == FirstIndent)
570 State.Column += 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000571 }
572
Daniel Jasper7878a7b2013-02-15 11:07:25 +0000573 if (Current.is(tok::question))
Daniel Jasper237d4c12013-02-23 21:01:55 +0000574 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper11e13802013-05-08 14:12:04 +0000575 if ((Previous.isOneOf(tok::comma, tok::semi) &&
576 !State.Stack.back().AvoidBinPacking) ||
577 Previous.Type == TT_BinaryOperator)
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000578 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper33f4b902013-05-15 09:35:08 +0000579 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
580 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000581
Manuel Klimek060143e2013-01-02 18:33:23 +0000582 if (!DryRun) {
Daniel Jasper1ef81d52013-02-26 13:10:34 +0000583 unsigned NewLines = 1;
Alexander Kornienkoe3f11972013-06-12 19:04:12 +0000584 if (Current.is(tok::comment))
Manuel Klimekb3987012013-05-29 14:47:47 +0000585 NewLines = std::max(
586 NewLines,
587 std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1));
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000588 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
589 State.Column, Line.InPPDirective);
Manuel Klimek060143e2013-01-02 18:33:23 +0000590 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000591
Daniel Jaspere1f9a8e2013-07-11 13:48:16 +0000592 if (!Current.isTrailingComment())
593 State.Stack.back().LastSpace = State.Column;
Daniel Jasper5ad390d2013-05-28 11:30:49 +0000594 if (Current.isOneOf(tok::arrow, tok::period) &&
595 Current.Type != TT_DesignatedInitializerPeriod)
Alexander Kornienko00895102013-06-05 14:09:10 +0000596 State.Stack.back().LastSpace += Current.CodePointCount;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000597 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper07ca5472013-07-05 09:14:35 +0000598 State.LowestLevelOnLine = State.ParenLevel;
Daniel Jasper237d4c12013-02-23 21:01:55 +0000599
600 // Any break on this level means that the parent level has been broken
601 // and we need to avoid bin packing there.
602 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
603 State.Stack[i].BreakBeforeParameter = true;
604 }
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000605 const FormatToken *TokenBefore = Current.getPreviousNonComment();
Daniel Jasper01218ff2013-04-15 22:36:37 +0000606 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
Daniel Jasper33f4b902013-05-15 09:35:08 +0000607 TokenBefore->Type != TT_TemplateCloser &&
Daniel Jasper11e13802013-05-08 14:12:04 +0000608 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000609 State.Stack.back().BreakBeforeParameter = true;
610
Daniel Jasper237d4c12013-02-23 21:01:55 +0000611 // If we break after {, we should also break before the corresponding }.
612 if (Previous.is(tok::l_brace))
613 State.Stack.back().BreakBeforeClosingBrace = true;
614
615 if (State.Stack.back().AvoidBinPacking) {
616 // If we are breaking after '(', '{', '<', this is not bin packing
617 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasperd741f022013-05-14 20:39:56 +0000618 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
619 Previous.Type == TT_BinaryOperator) ||
Daniel Jasper237d4c12013-02-23 21:01:55 +0000620 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
621 Line.MustBeDeclaration))
622 State.Stack.back().BreakBeforeParameter = true;
623 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000624 } else {
Daniel Jasper9c3e71a2013-02-25 15:59:54 +0000625 if (Current.is(tok::equal) &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000626 (RootToken->is(tok::kw_for) || State.ParenLevel == 0) &&
Daniel Jasperadc0f092013-04-05 09:38:50 +0000627 State.Stack.back().VariablePos == 0) {
628 State.Stack.back().VariablePos = State.Column;
629 // Move over * and & if they are bound to the variable name.
Manuel Klimekb3987012013-05-29 14:47:47 +0000630 const FormatToken *Tok = &Previous;
Alexander Kornienko00895102013-06-05 14:09:10 +0000631 while (Tok && State.Stack.back().VariablePos >= Tok->CodePointCount) {
632 State.Stack.back().VariablePos -= Tok->CodePointCount;
Daniel Jasperadc0f092013-04-05 09:38:50 +0000633 if (Tok->SpacesRequiredBefore != 0)
634 break;
Manuel Klimekb3987012013-05-29 14:47:47 +0000635 Tok = Tok->Previous;
Daniel Jasperadc0f092013-04-05 09:38:50 +0000636 }
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000637 if (Previous.PartOfMultiVariableDeclStmt)
638 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
639 }
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000640
Daniel Jasper729a7432013-02-11 12:36:37 +0000641 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper20409152012-12-04 14:54:30 +0000642
Daniel Jasperbac016b2012-12-03 18:12:45 +0000643 if (!DryRun)
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000644 Whitespaces.replaceWhitespace(Current, 0, Spaces,
645 State.Column + Spaces);
Daniel Jasper20409152012-12-04 14:54:30 +0000646
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000647 if (Current.Type == TT_ObjCSelectorName &&
648 State.Stack.back().ColonPos == 0) {
649 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienko00895102013-06-05 14:09:10 +0000650 State.Column + Spaces + Current.CodePointCount)
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000651 State.Stack.back().ColonPos =
652 State.Stack.back().Indent + Current.LongestObjCSelectorName;
653 else
654 State.Stack.back().ColonPos =
Alexander Kornienko00895102013-06-05 14:09:10 +0000655 State.Column + Spaces + Current.CodePointCount;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000656 }
657
Daniel Jasperac3223e2013-04-10 09:49:49 +0000658 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000659 Current.Type != TT_LineComment)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000660 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000661 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
662 State.Stack.back().AvoidBinPacking)
663 State.Stack.back().NoLineBreak = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000664
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000665 State.Column += Spaces;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000666 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jaspere438bac2013-01-23 20:41:06 +0000667 // Treat the condition inside an if as if it was a second function
668 // parameter, i.e. let nested calls have an indent of 4.
669 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperf9955d32013-03-20 12:37:50 +0000670 else if (Previous.is(tok::comma))
Daniel Jaspere438bac2013-01-23 20:41:06 +0000671 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000672 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper02b771e2013-01-28 13:31:35 +0000673 Previous.Type == TT_ConditionalExpr ||
674 Previous.Type == TT_CtorInitializerColon) &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000675 !(Previous.getPrecedence() == prec::Assignment &&
Daniel Jasper512843a2013-05-27 12:45:09 +0000676 Current.FakeLParens.empty()))
677 // Always indent relative to the RHS of the expression unless this is a
678 // simple assignment without binary expression on the RHS.
Daniel Jasperae8699b2013-01-28 09:35:24 +0000679 State.Stack.back().LastSpace = State.Column;
Daniel Jasper6cabab42013-02-14 08:42:54 +0000680 else if (Previous.Type == TT_InheritanceColon)
681 State.Stack.back().Indent = State.Column;
Daniel Jasperb1491792013-07-09 11:57:27 +0000682 else if (Previous.opensScope()) {
683 // If a function has multiple parameters (including a single parameter
Daniel Jasper2ca37412013-07-09 14:36:48 +0000684 // that is a binary expression) or a trailing call, indent all
Daniel Jasperb1491792013-07-09 11:57:27 +0000685 // parameters from the opening parenthesis. This avoids confusing
686 // indents like:
687 // OuterFunction(InnerFunctionCall(
688 // ParameterToInnerFunction),
689 // SecondParameterToOuterFunction);
690 bool HasMultipleParameters = !Current.FakeLParens.empty();
691 bool HasTrailingCall = false;
692 if (Previous.MatchingParen) {
693 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
694 if (Next && Next->isOneOf(tok::period, tok::arrow))
695 HasTrailingCall = true;
696 }
697 if (HasMultipleParameters || HasTrailingCall)
698 State.Stack.back().LastSpace = State.Column;
699 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000700 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000701
Manuel Klimek8092a942013-02-20 10:15:13 +0000702 return moveStateToNextToken(State, DryRun);
Daniel Jasper20409152012-12-04 14:54:30 +0000703 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000704
Daniel Jasper20409152012-12-04 14:54:30 +0000705 /// \brief Mark the next token as consumed in \p State and modify its stacks
706 /// accordingly.
Manuel Klimek8092a942013-02-20 10:15:13 +0000707 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000708 const FormatToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000709 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000710
Daniel Jasper6cabab42013-02-14 08:42:54 +0000711 if (Current.Type == TT_InheritanceColon)
712 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000713 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
714 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000715 if (Current.is(tok::question))
716 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper07ca5472013-07-05 09:14:35 +0000717 if (!Current.opensScope() && !Current.closesScope())
718 State.LowestLevelOnLine =
719 std::min(State.LowestLevelOnLine, State.ParenLevel);
720 if (Current.isOneOf(tok::period, tok::arrow) &&
721 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
722 State.Stack.back().StartOfFunctionCall =
723 Current.LastInChainOfCalls ? 0
724 : State.Column + Current.CodePointCount;
Daniel Jasper7d812812013-02-21 15:00:29 +0000725 if (Current.Type == TT_CtorInitializerColon) {
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000726 // Indent 2 from the column, so:
727 // SomeClass::SomeClass()
728 // : First(...), ...
729 // Next(...)
730 // ^ line up here.
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000731 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper7d812812013-02-21 15:00:29 +0000732 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
733 State.Stack.back().AvoidBinPacking = true;
734 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000735 }
Daniel Jasper3776ef32013-04-03 07:21:51 +0000736
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000737 // If return returns a binary expression, align after it.
738 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
739 State.Stack.back().LastSpace = State.Column + 7;
740
Daniel Jasper3776ef32013-04-03 07:21:51 +0000741 // In ObjC method declaration we align on the ":" of parameters, but we need
742 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasper37911302013-04-02 14:33:13 +0000743 if (Current.Type == TT_ObjCMethodSpecifier)
744 State.Stack.back().Indent += 4;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000745
Daniel Jasper29f123b2013-02-08 15:28:42 +0000746 // Insert scopes created by fake parenthesis.
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000747 const FormatToken *Previous = Current.getPreviousNonComment();
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000748 // Don't add extra indentation for the first fake parenthesis after
749 // 'return', assignements or opening <({[. The indentation for these cases
750 // is special cased.
751 bool SkipFirstExtraIndent =
752 Current.is(tok::kw_return) ||
Daniel Jasperac3223e2013-04-10 09:49:49 +0000753 (Previous && (Previous->opensScope() ||
Manuel Klimekb3987012013-05-29 14:47:47 +0000754 Previous->getPrecedence() == prec::Assignment));
Craig Topper163fbf82013-07-08 03:55:09 +0000755 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000756 I = Current.FakeLParens.rbegin(),
757 E = Current.FakeLParens.rend();
758 I != E; ++I) {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000759 ParenState NewParenState = State.Stack.back();
Daniel Jasper88cc5622013-07-08 14:25:23 +0000760 NewParenState.ContainsLineBreak = false;
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000761 NewParenState.Indent =
762 std::max(std::max(State.Column, NewParenState.Indent),
763 State.Stack.back().LastSpace);
764
765 // Always indent conditional expressions. Never indent expression where
766 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
767 // prec::Assignment) as those have different indentation rules. Indent
768 // other expression, unless the indentation needs to be skipped.
769 if (*I == prec::Conditional ||
770 (!SkipFirstExtraIndent && *I > prec::Assignment))
771 NewParenState.Indent += 4;
Daniel Jasperac3223e2013-04-10 09:49:49 +0000772 if (Previous && !Previous->opensScope())
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000773 NewParenState.BreakBeforeParameter = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000774 State.Stack.push_back(NewParenState);
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000775 SkipFirstExtraIndent = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000776 }
777
Daniel Jaspercf225b62012-12-24 13:43:52 +0000778 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000779 // prepare for the following tokens.
Daniel Jasperac3223e2013-04-10 09:49:49 +0000780 if (Current.opensScope()) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000781 unsigned NewIndent;
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000782 unsigned LastSpace = State.Stack.back().LastSpace;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000783 bool AvoidBinPacking;
Manuel Klimek2851c162013-01-10 14:36:46 +0000784 if (Current.is(tok::l_brace)) {
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000785 NewIndent = Style.IndentWidth + LastSpace;
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000786 const FormatToken *NextNoComment = Current.getNextNonComment();
Daniel Jasper5ad390d2013-05-28 11:30:49 +0000787 AvoidBinPacking = NextNoComment &&
788 NextNoComment->Type == TT_DesignatedInitializerPeriod;
Manuel Klimek2851c162013-01-10 14:36:46 +0000789 } else {
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000790 NewIndent =
791 4 + std::max(LastSpace, State.Stack.back().StartOfFunctionCall);
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000792 AvoidBinPacking = !Style.BinPackParameters ||
793 (Style.ExperimentalAutoDetectBinPacking &&
794 (Current.PackingKind == PPK_OnePerLine ||
795 (!BinPackInconclusiveFunctions &&
796 Current.PackingKind == PPK_Inconclusive)));
Manuel Klimek2851c162013-01-10 14:36:46 +0000797 }
Daniel Jasperfca24bc2013-04-25 13:31:51 +0000798
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000799 State.Stack.push_back(ParenState(NewIndent, LastSpace, AvoidBinPacking,
800 State.Stack.back().NoLineBreak));
Daniel Jasper29f123b2013-02-08 15:28:42 +0000801 ++State.ParenLevel;
Daniel Jasper20409152012-12-04 14:54:30 +0000802 }
803
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000804 // If this '[' opens an ObjC call, determine whether all parameters fit into
805 // one line and put one per line if they don't.
806 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
807 Current.MatchingParen != NULL) {
808 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
809 State.Stack.back().BreakBeforeParameter = true;
810 }
811
Daniel Jaspercf225b62012-12-24 13:43:52 +0000812 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000813 // stacks.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000814 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Manuel Klimekb3987012013-05-29 14:47:47 +0000815 (Current.is(tok::r_brace) && State.NextToken != RootToken) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +0000816 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000817 State.Stack.pop_back();
Daniel Jasper29f123b2013-02-08 15:28:42 +0000818 --State.ParenLevel;
819 }
820
821 // Remove scopes created by fake parenthesis.
822 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasperabfc9c12013-04-04 19:31:00 +0000823 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000824 State.Stack.pop_back();
Daniel Jasperabfc9c12013-04-04 19:31:00 +0000825 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000826 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000827
Daniel Jasper27c7f542013-05-13 20:50:15 +0000828 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000829 State.StartOfStringLiteral = State.Column;
Daniel Jasper27c7f542013-05-13 20:50:15 +0000830 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
831 tok::string_literal)) {
Daniel Jasper9a2f8d02013-05-16 04:26:02 +0000832 State.StartOfStringLiteral = 0;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000833 }
834
Alexander Kornienko00895102013-06-05 14:09:10 +0000835 State.Column += Current.CodePointCount;
Manuel Klimek8092a942013-02-20 10:15:13 +0000836
Manuel Klimekb3987012013-05-29 14:47:47 +0000837 State.NextToken = State.NextToken->Next;
Manuel Klimek2851c162013-01-10 14:36:46 +0000838
Manuel Klimek8092a942013-02-20 10:15:13 +0000839 return breakProtrudingToken(Current, State, DryRun);
840 }
841
842 /// \brief If the current token sticks out over the end of the line, break
843 /// it if possible.
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000844 ///
845 /// \returns An extra penalty if a token was broken, otherwise 0.
846 ///
Alexander Kornienkod446f732013-07-01 13:42:42 +0000847 /// The returned penalty will cover the cost of the additional line breaks and
848 /// column limit violation in all lines except for the last one. The penalty
849 /// for the column limit violation in the last line (and in single line
850 /// tokens) is handled in \c addNextStateToQueue.
Manuel Klimekb3987012013-05-29 14:47:47 +0000851 unsigned breakProtrudingToken(const FormatToken &Current, LineState &State,
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000852 bool DryRun) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000853 llvm::OwningPtr<BreakableToken> Token;
Alexander Kornienko00895102013-06-05 14:09:10 +0000854 unsigned StartColumn = State.Column - Current.CodePointCount;
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000855 unsigned OriginalStartColumn =
Manuel Klimekb3987012013-05-29 14:47:47 +0000856 SourceMgr.getSpellingColumnNumber(Current.getStartOfNonWhitespace()) -
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000857 1;
Manuel Klimekde008c02013-05-27 15:23:34 +0000858
Daniel Jasper5d5b4242013-05-16 12:59:13 +0000859 if (Current.is(tok::string_literal) &&
860 Current.Type != TT_ImplicitStringLiteral) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000861 // Only break up default narrow strings.
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000862 if (!Current.TokenText.startswith("\""))
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000863 return 0;
864
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000865 Token.reset(new BreakableStringLiteral(Current, StartColumn,
866 Line.InPPDirective, Encoding));
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000867 } else if (Current.Type == TT_BlockComment) {
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000868 Token.reset(new BreakableBlockComment(
Alexander Kornienko00895102013-06-05 14:09:10 +0000869 Style, Current, StartColumn, OriginalStartColumn, !Current.Previous,
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000870 Line.InPPDirective, Encoding));
Daniel Jasper7ff96ed2013-05-06 10:24:51 +0000871 } else if (Current.Type == TT_LineComment &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000872 (Current.Previous == NULL ||
873 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000874 Token.reset(new BreakableLineComment(Current, StartColumn,
875 Line.InPPDirective, Encoding));
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000876 } else {
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000877 return 0;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000878 }
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000879 if (Current.UnbreakableTailLength >= getColumnLimit())
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000880 return 0;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000881
Alexander Kornienkoc36c5c22013-06-19 19:50:11 +0000882 unsigned RemainingSpace = getColumnLimit() - Current.UnbreakableTailLength;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000883 bool BreakInserted = false;
884 unsigned Penalty = 0;
Alexander Kornienkoc36c5c22013-06-19 19:50:11 +0000885 unsigned RemainingTokenColumns = 0;
Manuel Klimekde008c02013-05-27 15:23:34 +0000886 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
887 LineIndex != EndIndex; ++LineIndex) {
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000888 if (!DryRun)
889 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000890 unsigned TailOffset = 0;
Alexander Kornienkoc36c5c22013-06-19 19:50:11 +0000891 RemainingTokenColumns = Token->getLineLengthAfterSplit(
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000892 LineIndex, TailOffset, StringRef::npos);
Alexander Kornienko00895102013-06-05 14:09:10 +0000893 while (RemainingTokenColumns > RemainingSpace) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000894 BreakableToken::Split Split =
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000895 Token->getSplit(LineIndex, TailOffset, getColumnLimit());
Alexander Kornienkod446f732013-07-01 13:42:42 +0000896 if (Split.first == StringRef::npos) {
897 // The last line's penalty is handled in addNextStateToQueue().
898 if (LineIndex < EndIndex - 1)
899 Penalty += Style.PenaltyExcessCharacter *
900 (RemainingTokenColumns - RemainingSpace);
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000901 break;
Alexander Kornienkod446f732013-07-01 13:42:42 +0000902 }
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000903 assert(Split.first != 0);
Alexander Kornienko00895102013-06-05 14:09:10 +0000904 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000905 LineIndex, TailOffset + Split.first + Split.second,
906 StringRef::npos);
Alexander Kornienko00895102013-06-05 14:09:10 +0000907 assert(NewRemainingTokenColumns < RemainingTokenColumns);
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000908 if (!DryRun)
909 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000910 Penalty += Current.is(tok::string_literal) ? Style.PenaltyBreakString
911 : Style.PenaltyBreakComment;
912 unsigned ColumnsUsed =
913 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
914 if (ColumnsUsed > getColumnLimit()) {
915 Penalty +=
916 Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit());
917 }
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000918 TailOffset += Split.first + Split.second;
Alexander Kornienko00895102013-06-05 14:09:10 +0000919 RemainingTokenColumns = NewRemainingTokenColumns;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000920 BreakInserted = true;
Manuel Klimek8092a942013-02-20 10:15:13 +0000921 }
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000922 }
923
Alexander Kornienkoc36c5c22013-06-19 19:50:11 +0000924 State.Column = RemainingTokenColumns;
925
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000926 if (BreakInserted) {
Alexander Kornienko22d0e292013-06-17 12:59:44 +0000927 // If we break the token inside a parameter list, we need to break before
928 // the next parameter on all levels, so that the next parameter is clearly
929 // visible. Line comments already introduce a break.
930 if (Current.Type != TT_LineComment) {
931 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
932 State.Stack[i].BreakBeforeParameter = true;
933 }
934
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000935 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek8092a942013-02-20 10:15:13 +0000936 }
Manuel Klimek8092a942013-02-20 10:15:13 +0000937 return Penalty;
938 }
939
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000940 unsigned getColumnLimit() {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000941 // In preprocessor directives reserve two chars for trailing " \"
942 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000943 }
944
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000945 /// \brief An edge in the solution space from \c Previous->State to \c State,
946 /// inserting a newline dependent on the \c NewLine.
947 struct StateNode {
948 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +0000949 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000950 LineState State;
951 bool NewLine;
952 StateNode *Previous;
953 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000954
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000955 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
956 ///
957 /// In case of equal penalties, we want to prefer states that were inserted
958 /// first. During state generation we make sure that we insert states first
959 /// that break the line as late as possible.
960 typedef std::pair<unsigned, unsigned> OrderedPenalty;
961
962 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
963 /// \c State has the given \c OrderedPenalty.
964 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
965
966 /// \brief The BFS queue type.
967 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
968 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000969
970 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000971 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000972 /// This implements a variant of Dijkstra's algorithm on the graph that spans
973 /// the solution space (\c LineStates are the nodes). The algorithm tries to
974 /// find the shortest path (the one with lowest penalty) from \p InitialState
975 /// to a state where all tokens are placed.
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000976 void analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000977 std::set<LineState> Seen;
978
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000979 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +0000980 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000981 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
982 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
983 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000984
985 // While not empty, take first element and follow edges.
986 while (!Queue.empty()) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000987 unsigned Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +0000988 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000989 if (Node->State.NextToken == NULL) {
Alexander Kornienkodd256312013-05-10 11:56:10 +0000990 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000991 break;
Daniel Jasper01786732013-02-04 07:21:18 +0000992 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000993 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000994
Daniel Jasper54b4e442013-05-22 05:27:42 +0000995 // Cut off the analysis of certain solutions if the analysis gets too
996 // complex. See description of IgnoreStackForComparison.
997 if (Count > 10000)
998 Node->State.IgnoreStackForComparison = true;
999
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001000 if (!Seen.insert(Node->State).second)
1001 // State already examined with lower penalty.
1002 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001003
Nico Weber27268772013-06-26 00:30:14 +00001004 addNextStateToQueue(Penalty, Node, /*NewLine=*/false);
1005 addNextStateToQueue(Penalty, Node, /*NewLine=*/true);
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001006 }
1007
1008 if (Queue.empty())
1009 // We were unable to find a solution, do nothing.
1010 // FIXME: Add diagnostic?
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001011 return;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001012
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001013 // Reconstruct the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001014 reconstructPath(InitialState, Queue.top().second);
Alexander Kornienkodd256312013-05-10 11:56:10 +00001015 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1016 DEBUG(llvm::dbgs() << "---\n");
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001017 }
1018
1019 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek9c333b92013-05-29 15:10:11 +00001020 std::deque<StateNode *> Path;
1021 // We do not need a break before the initial token.
1022 while (Current->Previous) {
1023 Path.push_front(Current);
1024 Current = Current->Previous;
1025 }
1026 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1027 I != E; ++I) {
1028 DEBUG({
1029 if ((*I)->NewLine) {
1030 llvm::dbgs() << "Penalty for splitting before "
1031 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
1032 << (*I)->Previous->State.NextToken->SplitPenalty << "\n";
1033 }
1034 });
1035 addTokenToState((*I)->NewLine, false, State);
1036 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001037 }
1038
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001039 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001040 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001041 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001042 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001043 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1044 bool NewLine) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001045 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001046 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001047 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001048 return;
Daniel Jasper88cc5622013-07-08 14:25:23 +00001049 if (NewLine) {
1050 if (!PreviousNode->State.Stack.back().ContainsLineBreak)
1051 Penalty += 15;
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001052 Penalty += PreviousNode->State.NextToken->SplitPenalty;
Daniel Jasper88cc5622013-07-08 14:25:23 +00001053 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001054
1055 StateNode *Node = new (Allocator.Allocate())
1056 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek8092a942013-02-20 10:15:13 +00001057 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001058 if (Node->State.Column > getColumnLimit()) {
1059 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper01786732013-02-04 07:21:18 +00001060 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasperceb99ab2013-01-09 10:16:05 +00001061 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001062
1063 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
1064 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001065 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001066
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001067 /// \brief Returns \c true, if a line break after \p State is allowed.
1068 bool canBreak(const LineState &State) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001069 const FormatToken &Current = *State.NextToken;
1070 const FormatToken &Previous = *Current.Previous;
1071 assert(&Previous == Current.Previous);
Daniel Jasper399914b2013-05-17 09:35:01 +00001072 if (!Current.CanBreakBefore &&
1073 !(Current.is(tok::r_brace) &&
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001074 State.Stack.back().BreakBeforeClosingBrace))
1075 return false;
Daniel Jasper399914b2013-05-17 09:35:01 +00001076 // The opening "{" of a braced list has to be on the same line as the first
1077 // element if it is nested in another braced init list or function call.
1078 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001079 Previous.Previous &&
1080 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
Daniel Jasper399914b2013-05-17 09:35:01 +00001081 return false;
Daniel Jasper259a0382013-05-27 11:50:16 +00001082 // This prevents breaks like:
1083 // ...
1084 // SomeParameter, OtherParameter).DoSomething(
1085 // ...
1086 // As they hide "DoSomething" and are generally bad for readability.
Daniel Jasper07ca5472013-07-05 09:14:35 +00001087 if (Previous.opensScope() &&
1088 State.LowestLevelOnLine < State.StartOfLineLevel)
Daniel Jasper259a0382013-05-27 11:50:16 +00001089 return false;
Daniel Jasper001bf4e2013-04-22 07:59:53 +00001090 return !State.Stack.back().NoLineBreak;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001091 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001092
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001093 /// \brief Returns \c true, if a line break after \p State is mandatory.
1094 bool mustBreak(const LineState &State) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001095 const FormatToken &Current = *State.NextToken;
1096 const FormatToken &Previous = *Current.Previous;
Daniel Jasper11e13802013-05-08 14:12:04 +00001097 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001098 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001099 if (Current.is(tok::r_brace) && State.Stack.back().BreakBeforeClosingBrace)
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001100 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001101 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001102 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001103 if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) ||
1104 Current.Type == TT_ConditionalExpr) &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +00001105 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper11e13802013-05-08 14:12:04 +00001106 !Current.isTrailingComment() &&
1107 !Current.isOneOf(tok::r_paren, tok::r_brace))
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001108 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001109
1110 // If we need to break somewhere inside the LHS of a binary expression, we
Daniel Jasper6df7a2d2013-07-03 10:34:47 +00001111 // should also break after the operator. Otherwise, the formatting would
1112 // hide the operator precedence, e.g. in:
1113 // if (aaaaaaaaaaaaaa ==
1114 // bbbbbbbbbbbbbb && c) {..
1115 // For comparisons, we only apply this rule, if the LHS is a binary
1116 // expression itself as otherwise, the line breaks seem superfluous.
1117 // We need special cases for ">>" which we have split into two ">" while
1118 // lexing in order to make template parsing easier.
1119 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
1120 Previous.getPrecedence() == prec::Equality) &&
1121 Previous.Previous &&
1122 Previous.Previous->Type != TT_BinaryOperator; // For >>.
1123 bool LHSIsBinaryExpr =
1124 Previous.Previous && Previous.Previous->FakeRParens > 0;
Daniel Jasper11e13802013-05-08 14:12:04 +00001125 if (Previous.Type == TT_BinaryOperator &&
Daniel Jasper6df7a2d2013-07-03 10:34:47 +00001126 (!IsComparison || LHSIsBinaryExpr) &&
1127 Current.Type != TT_BinaryOperator && // For >>.
Daniel Jasper5ef8aac2013-06-03 08:42:05 +00001128 !Current.isTrailingComment() &&
Daniel Jasper11e13802013-05-08 14:12:04 +00001129 !Previous.isOneOf(tok::lessless, tok::question) &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001130 Previous.getPrecedence() != prec::Assignment &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +00001131 State.Stack.back().BreakBeforeParameter)
Daniel Jasper63d7ced2013-02-05 10:07:47 +00001132 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001133
1134 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1135 // out whether it is the first parameter. Clean this up.
1136 if (Current.Type == TT_ObjCSelectorName &&
1137 Current.LongestObjCSelectorName == 0 &&
1138 State.Stack.back().BreakBeforeParameter)
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001139 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001140 if ((Current.Type == TT_CtorInitializerColon ||
1141 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0)))
Daniel Jasper923ebef2013-03-14 13:45:21 +00001142 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001143
Daniel Jasper6561f6a2013-07-09 07:43:55 +00001144 if ((Current.Type == TT_StartOfName || Current.is(tok::kw_operator)) &&
1145 Line.MightBeFunctionDecl && State.Stack.back().BreakBeforeParameter &&
1146 State.ParenLevel == 0)
Daniel Jasper33f4b902013-05-15 09:35:08 +00001147 return true;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001148 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001149 }
1150
Daniel Jasper3af59ce2013-03-15 14:57:30 +00001151 // Returns the total number of columns required for the remaining tokens.
1152 unsigned getRemainingLength(const LineState &State) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001153 if (State.NextToken && State.NextToken->Previous)
1154 return Line.Last->TotalLength - State.NextToken->Previous->TotalLength;
Daniel Jasper3af59ce2013-03-15 14:57:30 +00001155 return 0;
1156 }
1157
Daniel Jasperbac016b2012-12-03 18:12:45 +00001158 FormatStyle Style;
1159 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +00001160 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001161 const unsigned FirstIndent;
Manuel Klimekb3987012013-05-29 14:47:47 +00001162 const FormatToken *RootToken;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001163 WhitespaceManager &Whitespaces;
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001164
1165 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1166 QueueType Queue;
1167 // Increasing count of \c StateNode items we have created. This is used
1168 // to create a deterministic order independent of the container.
1169 unsigned Count;
Alexander Kornienko00895102013-06-05 14:09:10 +00001170 encoding::Encoding Encoding;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001171 bool BinPackInconclusiveFunctions;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001172};
1173
Manuel Klimek96e888b2013-05-28 11:55:06 +00001174class FormatTokenLexer {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001175public:
Alexander Kornienko00895102013-06-05 14:09:10 +00001176 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr,
1177 encoding::Encoding Encoding)
Manuel Klimek96e888b2013-05-28 11:55:06 +00001178 : FormatTok(NULL), GreaterStashed(false), TrailingWhitespace(0), Lex(Lex),
Alexander Kornienko00895102013-06-05 14:09:10 +00001179 SourceMgr(SourceMgr), IdentTable(Lex.getLangOpts()),
1180 Encoding(Encoding) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001181 Lex.SetKeepWhitespaceMode(true);
1182 }
1183
Manuel Klimek96e888b2013-05-28 11:55:06 +00001184 ArrayRef<FormatToken *> lex() {
1185 assert(Tokens.empty());
1186 do {
1187 Tokens.push_back(getNextToken());
1188 } while (Tokens.back()->Tok.isNot(tok::eof));
1189 return Tokens;
1190 }
1191
1192 IdentifierTable &getIdentTable() { return IdentTable; }
1193
1194private:
1195 FormatToken *getNextToken() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001196 if (GreaterStashed) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001197 // Create a synthesized second '>' token.
1198 Token Greater = FormatTok->Tok;
1199 FormatTok = new (Allocator.Allocate()) FormatToken;
1200 FormatTok->Tok = Greater;
Manuel Klimekad3094b2013-05-23 10:56:37 +00001201 SourceLocation GreaterLocation =
Manuel Klimek96e888b2013-05-28 11:55:06 +00001202 FormatTok->Tok.getLocation().getLocWithOffset(1);
1203 FormatTok->WhitespaceRange =
1204 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001205 FormatTok->TokenText = ">";
Alexander Kornienko00895102013-06-05 14:09:10 +00001206 FormatTok->CodePointCount = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001207 GreaterStashed = false;
1208 return FormatTok;
1209 }
1210
Manuel Klimek96e888b2013-05-28 11:55:06 +00001211 FormatTok = new (Allocator.Allocate()) FormatToken;
1212 Lex.LexFromRawLexer(FormatTok->Tok);
1213 StringRef Text = rawTokenText(FormatTok->Tok);
Manuel Klimekde008c02013-05-27 15:23:34 +00001214 SourceLocation WhitespaceStart =
Manuel Klimek96e888b2013-05-28 11:55:06 +00001215 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Manuel Klimekad3094b2013-05-23 10:56:37 +00001216 if (SourceMgr.getFileOffset(WhitespaceStart) == 0)
Manuel Klimek96e888b2013-05-28 11:55:06 +00001217 FormatTok->IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001218
1219 // Consume and record whitespace until we find a significant token.
Manuel Klimekde008c02013-05-27 15:23:34 +00001220 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001221 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimeka28fc062013-02-11 12:33:24 +00001222 unsigned Newlines = Text.count('\n');
Daniel Jasper1eee6c42013-03-04 13:43:19 +00001223 if (Newlines > 0)
Manuel Klimek96e888b2013-05-28 11:55:06 +00001224 FormatTok->LastNewlineOffset = WhitespaceLength + Text.rfind('\n') + 1;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001225 FormatTok->NewlinesBefore += Newlines;
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001226 unsigned EscapedNewlines = Text.count("\\\n");
Manuel Klimek96e888b2013-05-28 11:55:06 +00001227 FormatTok->HasUnescapedNewline |= EscapedNewlines != Newlines;
1228 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001229
Manuel Klimek96e888b2013-05-28 11:55:06 +00001230 Lex.LexFromRawLexer(FormatTok->Tok);
1231 Text = rawTokenText(FormatTok->Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001232 }
Manuel Klimek95419382013-01-07 07:56:50 +00001233
Manuel Klimekd4397b92013-01-04 23:34:14 +00001234 // In case the token starts with escaped newlines, we want to
1235 // take them into account as whitespace - this pattern is quite frequent
1236 // in macro definitions.
1237 // FIXME: What do we want to do with other escaped spaces, and escaped
1238 // spaces or newlines in the middle of tokens?
1239 // FIXME: Add a more explicit test.
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001240 while (Text.size() > 1 && Text[0] == '\\' && Text[1] == '\n') {
Manuel Klimek96e888b2013-05-28 11:55:06 +00001241 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimekad3094b2013-05-23 10:56:37 +00001242 WhitespaceLength += 2;
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001243 Text = Text.substr(2);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001244 }
1245
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001246 TrailingWhitespace = 0;
1247 if (FormatTok->Tok.is(tok::comment)) {
1248 StringRef UntrimmedText = Text;
1249 Text = Text.rtrim();
1250 TrailingWhitespace = UntrimmedText.size() - Text.size();
1251 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001252 IdentifierInfo &Info = IdentTable.get(Text);
Manuel Klimek96e888b2013-05-28 11:55:06 +00001253 FormatTok->Tok.setIdentifierInfo(&Info);
1254 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001255 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek96e888b2013-05-28 11:55:06 +00001256 FormatTok->Tok.setKind(tok::greater);
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001257 Text = Text.substr(0, 1);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001258 GreaterStashed = true;
1259 }
1260
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001261 // Now FormatTok is the next non-whitespace token.
1262 FormatTok->TokenText = Text;
1263 FormatTok->CodePointCount = encoding::getCodePointCount(Text, Encoding);
Alexander Kornienko00895102013-06-05 14:09:10 +00001264
Manuel Klimek96e888b2013-05-28 11:55:06 +00001265 FormatTok->WhitespaceRange = SourceRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001266 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001267 return FormatTok;
1268 }
1269
Manuel Klimek96e888b2013-05-28 11:55:06 +00001270 FormatToken *FormatTok;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001271 bool GreaterStashed;
Manuel Klimekde008c02013-05-27 15:23:34 +00001272 unsigned TrailingWhitespace;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001273 Lexer &Lex;
1274 SourceManager &SourceMgr;
1275 IdentifierTable IdentTable;
Alexander Kornienko00895102013-06-05 14:09:10 +00001276 encoding::Encoding Encoding;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001277 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1278 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001279
1280 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +00001281 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001282 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1283 Tok.getLength());
1284 }
1285};
1286
Daniel Jasperbac016b2012-12-03 18:12:45 +00001287class Formatter : public UnwrappedLineConsumer {
1288public:
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001289 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001290 const std::vector<CharSourceRange> &Ranges)
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001291 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko00895102013-06-05 14:09:10 +00001292 Whitespaces(SourceMgr, Style), Ranges(Ranges),
1293 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
1294 DEBUG(llvm::dbgs()
1295 << "File encoding: "
1296 << (Encoding == encoding::Encoding_UTF8 ? "UTF8" : "unknown")
1297 << "\n");
1298 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001299
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001300 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001301
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001302 tooling::Replacements format() {
Alexander Kornienko00895102013-06-05 14:09:10 +00001303 FormatTokenLexer Tokens(Lex, SourceMgr, Encoding);
Manuel Klimek96e888b2013-05-28 11:55:06 +00001304
1305 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek67d080d2013-04-12 14:13:36 +00001306 bool StructuralError = Parser.parse();
Alexander Kornienko00895102013-06-05 14:09:10 +00001307 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001308 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1309 Annotator.annotate(AnnotatedLines[i]);
1310 }
1311 deriveLocalStyle();
1312 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1313 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1314 }
Daniel Jasper5999f762013-04-09 17:46:55 +00001315
1316 // Adapt level to the next line if this is a comment.
1317 // FIXME: Can/should this be done in the UnwrappedLineParser?
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001318 const AnnotatedLine *NextNonCommentLine = NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +00001319 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001320 if (NextNonCommentLine && AnnotatedLines[i].First->is(tok::comment) &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001321 !AnnotatedLines[i].First->Next)
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001322 AnnotatedLines[i].Level = NextNonCommentLine->Level;
Daniel Jasper5999f762013-04-09 17:46:55 +00001323 else
Daniel Jasper2a409b62013-07-08 14:34:09 +00001324 NextNonCommentLine = AnnotatedLines[i].First->isNot(tok::r_brace)
1325 ? &AnnotatedLines[i]
1326 : NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +00001327 }
1328
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001329 std::vector<int> IndentForLevel;
1330 bool PreviousLineWasTouched = false;
Manuel Klimekb3987012013-05-29 14:47:47 +00001331 const FormatToken *PreviousLineLastToken = 0;
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001332 bool FormatPPDirective = false;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001333 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1334 E = AnnotatedLines.end();
1335 I != E; ++I) {
1336 const AnnotatedLine &TheLine = *I;
Manuel Klimekb3987012013-05-29 14:47:47 +00001337 const FormatToken *FirstTok = TheLine.First;
1338 int Offset = getIndentOffset(*TheLine.First);
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001339
1340 // Check whether this line is part of a formatted preprocessor directive.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001341 if (FirstTok->HasUnescapedNewline)
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001342 FormatPPDirective = false;
1343 if (!FormatPPDirective && TheLine.InPPDirective &&
1344 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
1345 FormatPPDirective = true;
1346
Daniel Jasper1fb8d882013-05-14 09:30:02 +00001347 // Determine indent and try to merge multiple unwrapped lines.
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001348 while (IndentForLevel.size() <= TheLine.Level)
1349 IndentForLevel.push_back(-1);
1350 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper1fb8d882013-05-14 09:30:02 +00001351 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
1352 if (static_cast<int>(Indent) + Offset >= 0)
1353 Indent += Offset;
1354 tryFitMultipleLinesInOne(Indent, I, E);
1355
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001356 bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0;
Manuel Klimekb3987012013-05-29 14:47:47 +00001357 if (TheLine.First->is(tok::eof)) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001358 if (PreviousLineWasTouched) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001359 unsigned NewLines = std::min(FirstTok->NewlinesBefore, 1u);
Manuel Klimekb3987012013-05-29 14:47:47 +00001360 Whitespaces.replaceWhitespace(*TheLine.First, NewLines, /*Indent*/ 0,
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001361 /*TargetColumn*/ 0);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001362 }
1363 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001364 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001365 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001366 if (FirstTok->WhitespaceRange.isValid() &&
Manuel Klimek67d080d2013-04-12 14:13:36 +00001367 // Insert a break even if there is a structural error in case where
1368 // we break apart a line consisting of multiple unwrapped lines.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001369 (FirstTok->NewlinesBefore == 0 || !StructuralError)) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001370 formatFirstToken(*TheLine.First, PreviousLineLastToken, Indent,
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001371 TheLine.InPPDirective);
Manuel Klimek67d080d2013-04-12 14:13:36 +00001372 } else {
1373 Indent = LevelIndent =
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001374 SourceMgr.getSpellingColumnNumber(FirstTok->Tok.getLocation()) -
1375 1;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001376 }
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001377 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001378 TheLine.First, Whitespaces, Encoding,
1379 BinPackInconclusiveFunctions);
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001380 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001381 IndentForLevel[TheLine.Level] = LevelIndent;
1382 PreviousLineWasTouched = true;
1383 } else {
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001384 // Format the first token if necessary, and notify the WhitespaceManager
1385 // about the unchanged whitespace.
Manuel Klimekb3987012013-05-29 14:47:47 +00001386 for (const FormatToken *Tok = TheLine.First; Tok != NULL;
1387 Tok = Tok->Next) {
1388 if (Tok == TheLine.First &&
1389 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
1390 unsigned LevelIndent =
1391 SourceMgr.getSpellingColumnNumber(Tok->Tok.getLocation()) - 1;
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001392 // Remove trailing whitespace of the previous line if it was
1393 // touched.
1394 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
1395 formatFirstToken(*Tok, PreviousLineLastToken, LevelIndent,
1396 TheLine.InPPDirective);
1397 } else {
Manuel Klimekb3987012013-05-29 14:47:47 +00001398 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001399 }
Daniel Jasper1fb8d882013-05-14 09:30:02 +00001400
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001401 if (static_cast<int>(LevelIndent) - Offset >= 0)
1402 LevelIndent -= Offset;
1403 if (Tok->isNot(tok::comment))
1404 IndentForLevel[TheLine.Level] = LevelIndent;
1405 } else {
Manuel Klimekb3987012013-05-29 14:47:47 +00001406 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001407 }
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001408 }
1409 // If we did not reformat this unwrapped line, the column at the end of
1410 // the last token is unchanged - thus, we can calculate the end of the
1411 // last token.
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001412 PreviousLineWasTouched = false;
1413 }
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001414 PreviousLineLastToken = I->Last;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001415 }
1416 return Whitespaces.generateReplacements();
1417 }
1418
1419private:
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001420 void deriveLocalStyle() {
1421 unsigned CountBoundToVariable = 0;
1422 unsigned CountBoundToType = 0;
1423 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001424 bool HasBinPackedFunction = false;
1425 bool HasOnePerLineFunction = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001426 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001427 if (!AnnotatedLines[i].First->Next)
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001428 continue;
Manuel Klimekb3987012013-05-29 14:47:47 +00001429 FormatToken *Tok = AnnotatedLines[i].First->Next;
1430 while (Tok->Next) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001431 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001432 bool SpacesBefore =
1433 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1434 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1435 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001436 if (SpacesBefore && !SpacesAfter)
1437 ++CountBoundToVariable;
1438 else if (!SpacesBefore && SpacesAfter)
1439 ++CountBoundToType;
1440 }
1441
Daniel Jasper29f123b2013-02-08 15:28:42 +00001442 if (Tok->Type == TT_TemplateCloser &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001443 Tok->Previous->Type == TT_TemplateCloser &&
1444 Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd())
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001445 HasCpp03IncompatibleFormat = true;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001446
1447 if (Tok->PackingKind == PPK_BinPacked)
1448 HasBinPackedFunction = true;
1449 if (Tok->PackingKind == PPK_OnePerLine)
1450 HasOnePerLineFunction = true;
1451
Manuel Klimekb3987012013-05-29 14:47:47 +00001452 Tok = Tok->Next;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001453 }
1454 }
1455 if (Style.DerivePointerBinding) {
1456 if (CountBoundToType > CountBoundToVariable)
1457 Style.PointerBindsToType = true;
1458 else if (CountBoundToType < CountBoundToVariable)
1459 Style.PointerBindsToType = false;
1460 }
1461 if (Style.Standard == FormatStyle::LS_Auto) {
1462 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1463 : FormatStyle::LS_Cpp03;
1464 }
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001465 BinPackInconclusiveFunctions =
1466 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001467 }
1468
Manuel Klimek547d5db2013-02-08 17:38:27 +00001469 /// \brief Get the indent of \p Level from \p IndentForLevel.
1470 ///
1471 /// \p IndentForLevel must contain the indent for the level \c l
1472 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1473 /// that level is unknown.
Daniel Jasperfc759082013-02-14 14:26:07 +00001474 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimek547d5db2013-02-08 17:38:27 +00001475 if (IndentForLevel[Level] != -1)
1476 return IndentForLevel[Level];
Manuel Klimek52635ff2013-02-08 19:53:32 +00001477 if (Level == 0)
1478 return 0;
Manuel Klimek07a64ec2013-05-13 08:42:42 +00001479 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimek547d5db2013-02-08 17:38:27 +00001480 }
1481
1482 /// \brief Get the offset of the line relatively to the level.
1483 ///
1484 /// For example, 'public:' labels in classes are offset by 1 or 2
1485 /// characters to the left from their level.
Manuel Klimekb3987012013-05-29 14:47:47 +00001486 int getIndentOffset(const FormatToken &RootToken) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001487 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimek547d5db2013-02-08 17:38:27 +00001488 return Style.AccessModifierOffset;
1489 return 0;
1490 }
1491
Manuel Klimek517e8942013-01-11 17:54:10 +00001492 /// \brief Tries to merge lines into one.
1493 ///
1494 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1495 /// if possible; note that \c I will be incremented when lines are merged.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001496 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +00001497 std::vector<AnnotatedLine>::iterator &I,
1498 std::vector<AnnotatedLine>::iterator E) {
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001499 // We can never merge stuff if there are trailing line comments.
1500 if (I->Last->Type == TT_LineComment)
1501 return;
1502
Daniel Jaspera4d46212013-02-28 11:05:57 +00001503 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001504 // If we already exceed the column limit, we set 'Limit' to 0. The different
1505 // tryMerge..() functions can then decide whether to still do merging.
1506 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001507
Daniel Jasper9c8c40e2013-01-21 14:18:28 +00001508 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001509 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001510
Daniel Jasper5be59ba2013-05-15 14:09:55 +00001511 if (I->Last->is(tok::l_brace)) {
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001512 tryMergeSimpleBlock(I, E, Limit);
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001513 } else if (Style.AllowShortIfStatementsOnASingleLine &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001514 I->First->is(tok::kw_if)) {
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001515 tryMergeSimpleControlStatement(I, E, Limit);
1516 } else if (Style.AllowShortLoopsOnASingleLine &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001517 I->First->isOneOf(tok::kw_for, tok::kw_while)) {
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001518 tryMergeSimpleControlStatement(I, E, Limit);
Manuel Klimekb3987012013-05-29 14:47:47 +00001519 } else if (I->InPPDirective &&
1520 (I->First->HasUnescapedNewline || I->First->IsFirst)) {
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001521 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001522 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001523 }
1524
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001525 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1526 std::vector<AnnotatedLine>::iterator E,
1527 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001528 if (Limit == 0)
1529 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001530 AnnotatedLine &Line = *I;
Manuel Klimekb3987012013-05-29 14:47:47 +00001531 if (!(I + 1)->InPPDirective || (I + 1)->First->HasUnescapedNewline)
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001532 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001533 if (I + 2 != E && (I + 2)->InPPDirective &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001534 !(I + 2)->First->HasUnescapedNewline)
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001535 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001536 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001537 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001538 join(Line, *(++I));
1539 }
1540
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001541 void tryMergeSimpleControlStatement(std::vector<AnnotatedLine>::iterator &I,
1542 std::vector<AnnotatedLine>::iterator E,
1543 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001544 if (Limit == 0)
1545 return;
Manuel Klimek4c128122013-01-18 14:46:43 +00001546 if ((I + 1)->InPPDirective != I->InPPDirective ||
Manuel Klimekb3987012013-05-29 14:47:47 +00001547 ((I + 1)->InPPDirective && (I + 1)->First->HasUnescapedNewline))
Manuel Klimek4c128122013-01-18 14:46:43 +00001548 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001549 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001550 if (Line.Last->isNot(tok::r_paren))
1551 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001552 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001553 return;
Manuel Klimekb3987012013-05-29 14:47:47 +00001554 if ((I + 1)->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
1555 tok::kw_while) ||
1556 (I + 1)->First->Type == TT_LineComment)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001557 return;
1558 // Only inline simple if's (no nested if or else).
Manuel Klimekb3987012013-05-29 14:47:47 +00001559 if (I + 2 != E && Line.First->is(tok::kw_if) &&
1560 (I + 2)->First->is(tok::kw_else))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001561 return;
1562 join(Line, *(++I));
1563 }
1564
1565 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001566 std::vector<AnnotatedLine>::iterator E,
1567 unsigned Limit) {
Daniel Jasper5be59ba2013-05-15 14:09:55 +00001568 // No merging if the brace already is on the next line.
1569 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
1570 return;
1571
Manuel Klimek517e8942013-01-11 17:54:10 +00001572 // First, check that the current line allows merging. This is the case if
1573 // we're not in a control flow statement and the last token is an opening
1574 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001575 AnnotatedLine &Line = *I;
Manuel Klimekb3987012013-05-29 14:47:47 +00001576 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1577 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001578 tok::kw_for,
Manuel Klimekb3987012013-05-29 14:47:47 +00001579 // This gets rid of all ObjC @ keywords and methods.
1580 tok::at, tok::minus, tok::plus))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001581 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001582
Manuel Klimekb3987012013-05-29 14:47:47 +00001583 FormatToken *Tok = (I + 1)->First;
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001584 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001585 (Tok->getNextNonComment() == NULL ||
1586 Tok->getNextNonComment()->is(tok::semi))) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001587 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jasper729a7432013-02-11 12:36:37 +00001588 Tok->SpacesRequiredBefore = 0;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001589 Tok->CanBreakBefore = true;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001590 join(Line, *(I + 1));
1591 I += 1;
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001592 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001593 // Check that we still have three lines and they fit into the limit.
1594 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1595 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001596 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001597
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001598 // Second, check that the next line does not contain any braces - if it
1599 // does, readability declines when putting it into a single line.
1600 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1601 return;
1602 do {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001603 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001604 return;
Manuel Klimekb3987012013-05-29 14:47:47 +00001605 Tok = Tok->Next;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001606 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001607
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001608 // Last, check that the third line contains a single closing brace.
Manuel Klimekb3987012013-05-29 14:47:47 +00001609 Tok = (I + 2)->First;
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001610 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001611 Tok->MustBreakBefore)
1612 return;
1613
1614 join(Line, *(I + 1));
1615 join(Line, *(I + 2));
1616 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +00001617 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001618 }
1619
1620 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1621 unsigned Limit) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001622 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1623 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001624 }
1625
Daniel Jasper995e8202013-01-14 13:08:07 +00001626 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001627 assert(!A.Last->Next);
1628 assert(!B.First->Previous);
1629 A.Last->Next = B.First;
1630 B.First->Previous = A.Last;
1631 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1632 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1633 Tok->TotalLength += LengthA;
1634 A.Last = Tok;
Daniel Jasper995e8202013-01-14 13:08:07 +00001635 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001636 }
1637
Daniel Jasper6f21a982013-03-13 07:49:51 +00001638 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf3023542013-03-07 20:50:00 +00001639 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1640 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1641 Ranges[i].getBegin()) &&
1642 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1643 Range.getBegin()))
1644 return true;
1645 }
1646 return false;
1647 }
1648
1649 bool touchesLine(const AnnotatedLine &TheLine) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001650 const FormatToken *First = TheLine.First;
1651 const FormatToken *Last = TheLine.Last;
Daniel Jasper84f5ddf2013-05-14 10:31:09 +00001652 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001653 First->WhitespaceRange.getBegin().getLocWithOffset(
1654 First->LastNewlineOffset),
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001655 Last->Tok.getLocation().getLocWithOffset(Last->TokenText.size() - 1));
Daniel Jasperf3023542013-03-07 20:50:00 +00001656 return touchesRanges(LineRange);
1657 }
1658
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001659 bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I,
1660 std::vector<AnnotatedLine>::iterator E) {
1661 for (; I != E; ++I) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001662 if (I->First->HasUnescapedNewline)
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001663 return false;
1664 if (touchesLine(*I))
1665 return true;
1666 }
1667 return false;
1668 }
1669
Daniel Jasperf3023542013-03-07 20:50:00 +00001670 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001671 const FormatToken *First = TheLine.First;
Daniel Jasperf3023542013-03-07 20:50:00 +00001672 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001673 First->WhitespaceRange.getBegin(),
1674 First->WhitespaceRange.getBegin().getLocWithOffset(
1675 First->LastNewlineOffset));
Daniel Jasperf3023542013-03-07 20:50:00 +00001676 return touchesRanges(LineRange);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001677 }
1678
1679 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +00001680 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001681 }
1682
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001683 /// \brief Add a new line and the required indent before the first Token
1684 /// of the \c UnwrappedLine if there was no structural parsing error.
1685 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimekb3987012013-05-29 14:47:47 +00001686 void formatFirstToken(const FormatToken &RootToken,
1687 const FormatToken *PreviousToken, unsigned Indent,
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001688 bool InPPDirective) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001689 unsigned Newlines =
Manuel Klimekb3987012013-05-29 14:47:47 +00001690 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Daniel Jasper15f33f02013-06-03 16:16:41 +00001691 // Remove empty lines before "}" where applicable.
1692 if (RootToken.is(tok::r_brace) &&
1693 (!RootToken.Next ||
1694 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1695 Newlines = std::min(Newlines, 1u);
Manuel Klimekb3987012013-05-29 14:47:47 +00001696 if (Newlines == 0 && !RootToken.IsFirst)
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001697 Newlines = 1;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001698
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001699 // Insert extra new line before access specifiers.
1700 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001701 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001702 ++Newlines;
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001703
Manuel Klimekb3987012013-05-29 14:47:47 +00001704 Whitespaces.replaceWhitespace(
1705 RootToken, Newlines, Indent, Indent,
1706 InPPDirective && !RootToken.HasUnescapedNewline);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001707 }
1708
Daniel Jasperbac016b2012-12-03 18:12:45 +00001709 FormatStyle Style;
1710 Lexer &Lex;
1711 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001712 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001713 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001714 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko00895102013-06-05 14:09:10 +00001715
1716 encoding::Encoding Encoding;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001717 bool BinPackInconclusiveFunctions;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001718};
1719
Craig Topper83f81d72013-06-30 22:29:28 +00001720} // end anonymous namespace
1721
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001722tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1723 SourceManager &SourceMgr,
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001724 std::vector<CharSourceRange> Ranges) {
1725 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001726 return formatter.format();
1727}
1728
Daniel Jasper8a999452013-05-16 10:40:07 +00001729tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1730 std::vector<tooling::Range> Ranges,
1731 StringRef FileName) {
1732 FileManager Files((FileSystemOptions()));
1733 DiagnosticsEngine Diagnostics(
1734 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1735 new DiagnosticOptions);
1736 SourceManager SourceMgr(Diagnostics, Files);
1737 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1738 const clang::FileEntry *Entry =
1739 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1740 SourceMgr.overrideFileContents(Entry, Buf);
1741 FileID ID =
1742 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001743 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1744 getFormattingLangOpts(Style.Standard));
Daniel Jasper8a999452013-05-16 10:40:07 +00001745 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1746 std::vector<CharSourceRange> CharRanges;
1747 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1748 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1749 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1750 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1751 }
1752 return reformat(Style, Lex, SourceMgr, CharRanges);
1753}
1754
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001755LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasper46ef8522013-01-10 13:08:12 +00001756 LangOptions LangOpts;
1757 LangOpts.CPlusPlus = 1;
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001758 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasperb64eca02013-03-22 10:01:29 +00001759 LangOpts.LineComment = 1;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001760 LangOpts.Bool = 1;
1761 LangOpts.ObjC1 = 1;
1762 LangOpts.ObjC2 = 1;
1763 return LangOpts;
1764}
1765
Daniel Jaspercd162382013-01-07 13:26:07 +00001766} // namespace format
1767} // namespace clang