blob: 65b1a265e59b9a5d0acf0bf250f530b2d29dbb76 [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
Daniel Jaspereff18b92013-07-31 23:16:02 +000056template <>
57struct ScalarEnumerationTraits<
58 clang::format::FormatStyle::NamespaceIndentationKind> {
59 static void
60 enumeration(IO &IO,
61 clang::format::FormatStyle::NamespaceIndentationKind &Value) {
62 IO.enumCase(Value, "None", clang::format::FormatStyle::NI_None);
63 IO.enumCase(Value, "Inner", clang::format::FormatStyle::NI_Inner);
64 IO.enumCase(Value, "All", clang::format::FormatStyle::NI_All);
65 }
66};
67
Alexander Kornienkod71ec162013-05-07 15:32:14 +000068template <> struct MappingTraits<clang::format::FormatStyle> {
69 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
Alexander Kornienkodd256312013-05-10 11:56:10 +000070 if (IO.outputting()) {
71 StringRef StylesArray[] = { "LLVM", "Google", "Chromium", "Mozilla" };
72 ArrayRef<StringRef> Styles(StylesArray);
73 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
74 StringRef StyleName(Styles[i]);
Alexander Kornienko885f87b2013-05-19 00:53:30 +000075 clang::format::FormatStyle PredefinedStyle;
76 if (clang::format::getPredefinedStyle(StyleName, &PredefinedStyle) &&
77 Style == PredefinedStyle) {
Alexander Kornienkodd256312013-05-10 11:56:10 +000078 IO.mapOptional("# BasedOnStyle", StyleName);
79 break;
80 }
81 }
82 } else {
Alexander Kornienkod71ec162013-05-07 15:32:14 +000083 StringRef BasedOnStyle;
84 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000085 if (!BasedOnStyle.empty())
Alexander Kornienko885f87b2013-05-19 00:53:30 +000086 if (!clang::format::getPredefinedStyle(BasedOnStyle, &Style)) {
87 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
88 return;
89 }
Alexander Kornienkod71ec162013-05-07 15:32:14 +000090 }
91
92 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
93 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
94 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
95 Style.AllowAllParametersOfDeclarationOnNextLine);
96 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
97 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasperf11bbb92013-05-16 12:12:21 +000098 IO.mapOptional("AllowShortLoopsOnASingleLine",
99 Style.AllowShortLoopsOnASingleLine);
Daniel Jasperbbc87762013-05-29 12:07:31 +0000100 IO.mapOptional("AlwaysBreakTemplateDeclarations",
101 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko56312022013-07-04 12:02:44 +0000102 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
103 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000104 IO.mapOptional("BreakBeforeBinaryOperators",
105 Style.BreakBeforeBinaryOperators);
106 IO.mapOptional("BreakConstructorInitializersBeforeComma",
107 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000108 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
109 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
110 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
111 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
112 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000113 IO.mapOptional("ExperimentalAutoDetectBinPacking",
114 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000115 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
116 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspereff18b92013-07-31 23:16:02 +0000117 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000118 IO.mapOptional("ObjCSpaceBeforeProtocolList",
119 Style.ObjCSpaceBeforeProtocolList);
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000120 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
121 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000122 IO.mapOptional("PenaltyBreakFirstLessLess",
123 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000124 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
125 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
126 Style.PenaltyReturnTypeOnItsOwnLine);
127 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
128 IO.mapOptional("SpacesBeforeTrailingComments",
129 Style.SpacesBeforeTrailingComments);
Daniel Jasperb5dc3f42013-07-16 18:22:10 +0000130 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000131 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000132 IO.mapOptional("IndentWidth", Style.IndentWidth);
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000133 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimek44135b82013-05-13 12:51:40 +0000134 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimeka9a7f102013-06-21 17:25:42 +0000135 IO.mapOptional("IndentFunctionDeclarationAfterType",
136 Style.IndentFunctionDeclarationAfterType);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000137 }
138};
139}
140}
141
Daniel Jasperbac016b2012-12-03 18:12:45 +0000142namespace clang {
143namespace format {
144
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000145void setDefaultPenalties(FormatStyle &Style) {
146 Style.PenaltyBreakComment = 45;
Daniel Jasper9637dda2013-07-15 14:33:14 +0000147 Style.PenaltyBreakFirstLessLess = 120;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000148 Style.PenaltyBreakString = 1000;
149 Style.PenaltyExcessCharacter = 1000000;
150}
151
Daniel Jasperbac016b2012-12-03 18:12:45 +0000152FormatStyle getLLVMStyle() {
153 FormatStyle LLVMStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000154 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000155 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasperf1579602013-01-29 16:03:49 +0000156 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000157 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000158 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienko56312022013-07-04 12:02:44 +0000159 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000160 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000161 LLVMStyle.BinPackParameters = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000162 LLVMStyle.BreakBeforeBinaryOperators = false;
163 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
164 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000165 LLVMStyle.ColumnLimit = 80;
166 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000167 LLVMStyle.Cpp11BracedListStyle = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000168 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000169 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000170 LLVMStyle.IndentCaseLabels = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000171 LLVMStyle.IndentFunctionDeclarationAfterType = false;
172 LLVMStyle.IndentWidth = 2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000173 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000174 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Weber5f500df2013-01-10 20:12:55 +0000175 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000176 LLVMStyle.PointerBindsToType = false;
177 LLVMStyle.SpacesBeforeTrailingComments = 1;
178 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000179 LLVMStyle.UseTab = false;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000180
181 setDefaultPenalties(LLVMStyle);
182 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
183
Daniel Jasperbac016b2012-12-03 18:12:45 +0000184 return LLVMStyle;
185}
186
187FormatStyle getGoogleStyle() {
188 FormatStyle GoogleStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000189 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000190 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000191 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000192 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper1bee0732013-05-23 18:05:18 +0000193 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko56312022013-07-04 12:02:44 +0000194 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000195 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000196 GoogleStyle.BinPackParameters = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000197 GoogleStyle.BreakBeforeBinaryOperators = false;
198 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
199 GoogleStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000200 GoogleStyle.ColumnLimit = 80;
201 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000202 GoogleStyle.Cpp11BracedListStyle = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000203 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000204 GoogleStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000205 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000206 GoogleStyle.IndentFunctionDeclarationAfterType = true;
207 GoogleStyle.IndentWidth = 2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000208 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000209 GoogleStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Weber5f500df2013-01-10 20:12:55 +0000210 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000211 GoogleStyle.PointerBindsToType = true;
212 GoogleStyle.SpacesBeforeTrailingComments = 2;
213 GoogleStyle.Standard = FormatStyle::LS_Auto;
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000214 GoogleStyle.UseTab = false;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000215
216 setDefaultPenalties(GoogleStyle);
217 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
218
Daniel Jasperbac016b2012-12-03 18:12:45 +0000219 return GoogleStyle;
220}
221
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000222FormatStyle getChromiumStyle() {
223 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +0000224 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000225 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000226 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000227 ChromiumStyle.BinPackParameters = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000228 ChromiumStyle.DerivePointerBinding = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000229 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000230 return ChromiumStyle;
231}
232
Alexander Kornienkofb594862013-05-06 14:11:27 +0000233FormatStyle getMozillaStyle() {
234 FormatStyle MozillaStyle = getLLVMStyle();
235 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
236 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
237 MozillaStyle.DerivePointerBinding = true;
238 MozillaStyle.IndentCaseLabels = true;
239 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
240 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
241 MozillaStyle.PointerBindsToType = true;
242 return MozillaStyle;
243}
244
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000245FormatStyle getWebKitStyle() {
246 FormatStyle Style = getLLVMStyle();
Daniel Jaspereff18b92013-07-31 23:16:02 +0000247 Style.AccessModifierOffset = -4;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000248 Style.BreakBeforeBinaryOperators = true;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000249 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000250 Style.BreakConstructorInitializersBeforeComma = true;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000251 Style.ColumnLimit = 0;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000252 Style.IndentWidth = 4;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000253 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000254 Style.PointerBindsToType = true;
255 return Style;
256}
257
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000258bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000259 if (Name.equals_lower("llvm"))
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000260 *Style = getLLVMStyle();
261 else if (Name.equals_lower("chromium"))
262 *Style = getChromiumStyle();
263 else if (Name.equals_lower("mozilla"))
264 *Style = getMozillaStyle();
265 else if (Name.equals_lower("google"))
266 *Style = getGoogleStyle();
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000267 else if (Name.equals_lower("webkit"))
268 *Style = getWebKitStyle();
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000269 else
270 return false;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000271
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000272 return true;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000273}
274
275llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienko107db3c2013-05-20 15:18:01 +0000276 if (Text.trim().empty())
277 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000278 llvm::yaml::Input Input(Text);
279 Input >> *Style;
280 return Input.error();
281}
282
283std::string configurationAsText(const FormatStyle &Style) {
284 std::string Text;
285 llvm::raw_string_ostream Stream(Text);
286 llvm::yaml::Output Output(Stream);
287 // We use the same mapping method for input and output, so we need a non-const
288 // reference here.
289 FormatStyle NonConstStyle = Style;
290 Output << NonConstStyle;
Alexander Kornienko2b6acb62013-05-13 12:56:35 +0000291 return Stream.str();
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000292}
293
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000294// Returns the length of everything up to the first possible line break after
295// the ), ], } or > matching \c Tok.
Manuel Klimekb3987012013-05-29 14:47:47 +0000296static unsigned getLengthToMatchingParen(const FormatToken &Tok) {
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000297 if (Tok.MatchingParen == NULL)
298 return 0;
Manuel Klimekb3987012013-05-29 14:47:47 +0000299 FormatToken *End = Tok.MatchingParen;
300 while (End->Next && !End->Next->CanBreakBefore) {
301 End = End->Next;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000302 }
303 return End->TotalLength - Tok.TotalLength + 1;
304}
305
Craig Topper83f81d72013-06-30 22:29:28 +0000306namespace {
307
Daniel Jasperbac016b2012-12-03 18:12:45 +0000308class UnwrappedLineFormatter {
309public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000310 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper995e8202013-01-14 13:08:07 +0000311 const AnnotatedLine &Line, unsigned FirstIndent,
Manuel Klimekb3987012013-05-29 14:47:47 +0000312 const FormatToken *RootToken,
Alexander Kornienko00895102013-06-05 14:09:10 +0000313 WhitespaceManager &Whitespaces,
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000314 encoding::Encoding Encoding,
315 bool BinPackInconclusiveFunctions)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000316 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000317 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000318 Whitespaces(Whitespaces), Count(0), Encoding(Encoding),
319 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000320
Manuel Klimekd4397b92013-01-04 23:34:14 +0000321 /// \brief Formats an \c UnwrappedLine.
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000322 void format(const AnnotatedLine *NextLine) {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000323 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000324 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000325 State.Column = FirstIndent;
Manuel Klimekb3987012013-05-29 14:47:47 +0000326 State.NextToken = RootToken;
Daniel Jasper2a409b62013-07-08 14:34:09 +0000327 State.Stack.push_back(ParenState(FirstIndent, FirstIndent,
328 /*AvoidBinPacking=*/false,
329 /*NoLineBreak=*/false));
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000330 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000331 State.ParenLevel = 0;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000332 State.StartOfStringLiteral = 0;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000333 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper07ca5472013-07-05 09:14:35 +0000334 State.LowestLevelOnLine = State.ParenLevel;
Daniel Jasper54b4e442013-05-22 05:27:42 +0000335 State.IgnoreStackForComparison = false;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000336
337 // The first token has already been indented and thus consumed.
Daniel Jasper0fde9502013-07-12 11:37:05 +0000338 moveStateToNextToken(State, /*DryRun=*/false, /*Newline=*/false);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000339
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000340 if (Style.ColumnLimit == 0) {
341 formatWithoutColumnLimit(State);
342 return;
343 }
344
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000345 // If everything fits on a single line, just put it there.
Daniel Jaspera4d46212013-02-28 11:05:57 +0000346 unsigned ColumnLimit = Style.ColumnLimit;
347 if (NextLine && NextLine->InPPDirective &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000348 !NextLine->First->HasUnescapedNewline)
Daniel Jaspera4d46212013-02-28 11:05:57 +0000349 ColumnLimit = getColumnLimit();
350 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000351 while (State.NextToken != NULL) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000352 addTokenToState(false, false, State);
Daniel Jasper1321eb52012-12-18 21:05:13 +0000353 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000354 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000355
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000356 // If the ObjC method declaration does not fit on a line, we should format
357 // it with one arg per line.
358 if (Line.Type == LT_ObjCMethodDecl)
359 State.Stack.back().BreakBeforeParameter = true;
360
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000361 // Find best solution in solution space.
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000362 analyzeSolutionSpace(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000363 }
364
365private:
Manuel Klimekb3987012013-05-29 14:47:47 +0000366 void DebugTokenState(const FormatToken &FormatTok) {
367 const Token &Tok = FormatTok.Tok;
Alexander Kornienkodd256312013-05-10 11:56:10 +0000368 llvm::dbgs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000369 Tok.getLength());
Alexander Kornienkodd256312013-05-10 11:56:10 +0000370 llvm::dbgs();
Manuel Klimekca547db2013-01-16 14:55:28 +0000371 }
372
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000373 struct ParenState {
Daniel Jasperd399bff2013-02-05 09:41:21 +0000374 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000375 bool NoLineBreak)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000376 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
377 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000378 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000379 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
Daniel Jasper011c35d2013-07-12 11:19:37 +0000380 StartOfArraySubscripts(0), NestedNameSpecifierContinuation(0),
381 CallContinuation(0), VariablePos(0), ContainsLineBreak(false) {}
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000382
Daniel Jasperbac016b2012-12-03 18:12:45 +0000383 /// \brief The position to which a specific parenthesis level needs to be
384 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000385 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000386
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000387 /// \brief The position of the last space on each level.
388 ///
389 /// Used e.g. to break like:
390 /// functionCall(Parameter, otherCall(
391 /// OtherParameter));
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000392 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000393
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000394 /// \brief The position the first "<<" operator encountered on each level.
395 ///
396 /// Used to align "<<" operators. 0 if no such operator has been encountered
397 /// on a level.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000398 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000399
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000400 /// \brief Whether a newline needs to be inserted before the block's closing
401 /// brace.
402 ///
403 /// We only want to insert a newline before the closing brace if there also
404 /// was a newline after the beginning left brace.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000405 bool BreakBeforeClosingBrace;
406
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000407 /// \brief The column of a \c ? in a conditional expression;
408 unsigned QuestionColumn;
409
Daniel Jasperf343cab2013-01-31 14:59:26 +0000410 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
411 /// lines, in this context.
412 bool AvoidBinPacking;
413
414 /// \brief Break after the next comma (or all the commas in this context if
415 /// \c AvoidBinPacking is \c true).
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000416 bool BreakBeforeParameter;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000417
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000418 /// \brief Line breaking in this context would break a formatting rule.
419 bool NoLineBreak;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000420
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000421 /// \brief The position of the colon in an ObjC method declaration/call.
422 unsigned ColonPos;
Daniel Jasperc4615b72013-02-20 12:56:39 +0000423
Daniel Jasper24849712013-03-01 16:48:32 +0000424 /// \brief The start of the most recent function in a builder-type call.
425 unsigned StartOfFunctionCall;
426
Daniel Jasper011c35d2013-07-12 11:19:37 +0000427 /// \brief Contains the start of array subscript expressions, so that they
428 /// can be aligned.
429 unsigned StartOfArraySubscripts;
430
Daniel Jasper37911302013-04-02 14:33:13 +0000431 /// \brief If a nested name specifier was broken over multiple lines, this
432 /// contains the start column of the second line. Otherwise 0.
433 unsigned NestedNameSpecifierContinuation;
434
435 /// \brief If a call expression was broken over multiple lines, this
436 /// contains the start column of the second line. Otherwise 0.
437 unsigned CallContinuation;
438
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000439 /// \brief The column of the first variable name in a variable declaration.
440 ///
441 /// Used to align further variables if necessary.
442 unsigned VariablePos;
443
Daniel Jasper88cc5622013-07-08 14:25:23 +0000444 /// \brief \c true if this \c ParenState already contains a line-break.
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000445 ///
Daniel Jasper88cc5622013-07-08 14:25:23 +0000446 /// The first line break in a certain \c ParenState causes extra penalty so
447 /// that clang-format prefers similar breaks, i.e. breaks in the same
448 /// parenthesis.
449 bool ContainsLineBreak;
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000450
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000451 bool operator<(const ParenState &Other) const {
452 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000453 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000454 if (LastSpace != Other.LastSpace)
455 return LastSpace < Other.LastSpace;
456 if (FirstLessLess != Other.FirstLessLess)
457 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000458 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
459 return BreakBeforeClosingBrace;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000460 if (QuestionColumn != Other.QuestionColumn)
461 return QuestionColumn < Other.QuestionColumn;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000462 if (AvoidBinPacking != Other.AvoidBinPacking)
463 return AvoidBinPacking;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000464 if (BreakBeforeParameter != Other.BreakBeforeParameter)
465 return BreakBeforeParameter;
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000466 if (NoLineBreak != Other.NoLineBreak)
467 return NoLineBreak;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000468 if (ColonPos != Other.ColonPos)
469 return ColonPos < Other.ColonPos;
Daniel Jasper24849712013-03-01 16:48:32 +0000470 if (StartOfFunctionCall != Other.StartOfFunctionCall)
471 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasper011c35d2013-07-12 11:19:37 +0000472 if (StartOfArraySubscripts != Other.StartOfArraySubscripts)
473 return StartOfArraySubscripts < Other.StartOfArraySubscripts;
Daniel Jasper37911302013-04-02 14:33:13 +0000474 if (CallContinuation != Other.CallContinuation)
475 return CallContinuation < Other.CallContinuation;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000476 if (VariablePos != Other.VariablePos)
477 return VariablePos < Other.VariablePos;
Daniel Jasper88cc5622013-07-08 14:25:23 +0000478 if (ContainsLineBreak != Other.ContainsLineBreak)
479 return ContainsLineBreak < Other.ContainsLineBreak;
Daniel Jasperb3123142013-01-12 07:36:22 +0000480 return false;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000481 }
482 };
483
484 /// \brief The current state when indenting a unwrapped line.
485 ///
486 /// As the indenting tries different combinations this is copied by value.
487 struct LineState {
488 /// \brief The number of used columns in the current line.
489 unsigned Column;
490
491 /// \brief The token that needs to be next formatted.
Manuel Klimekb3987012013-05-29 14:47:47 +0000492 const FormatToken *NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000493
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000494 /// \brief \c true if this line contains a continued for-loop section.
495 bool LineContainsContinuedForLoopSection;
496
Daniel Jasper29f123b2013-02-08 15:28:42 +0000497 /// \brief The level of nesting inside (), [], <> and {}.
498 unsigned ParenLevel;
499
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000500 /// \brief The \c ParenLevel at the start of this line.
501 unsigned StartOfLineLevel;
502
Daniel Jasper07ca5472013-07-05 09:14:35 +0000503 /// \brief The lowest \c ParenLevel on the current line.
504 unsigned LowestLevelOnLine;
Daniel Jasper259a0382013-05-27 11:50:16 +0000505
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000506 /// \brief The start column of the string literal, if we're in a string
507 /// literal sequence, 0 otherwise.
508 unsigned StartOfStringLiteral;
509
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000510 /// \brief A stack keeping track of properties applying to parenthesis
511 /// levels.
512 std::vector<ParenState> Stack;
513
Daniel Jasper54b4e442013-05-22 05:27:42 +0000514 /// \brief Ignore the stack of \c ParenStates for state comparison.
515 ///
516 /// In long and deeply nested unwrapped lines, the current algorithm can
517 /// be insufficient for finding the best formatting with a reasonable amount
518 /// of time and memory. Setting this flag will effectively lead to the
519 /// algorithm not analyzing some combinations. However, these combinations
520 /// rarely contain the optimal solution: In short, accepting a higher
521 /// penalty early would need to lead to different values in the \c
522 /// ParenState stack (in an otherwise identical state) and these different
523 /// values would need to lead to a significant amount of avoided penalty
524 /// later.
525 ///
526 /// FIXME: Come up with a better algorithm instead.
527 bool IgnoreStackForComparison;
528
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000529 /// \brief Comparison operator to be able to used \c LineState in \c map.
530 bool operator<(const LineState &Other) const {
Daniel Jasperd7896702013-02-19 09:28:55 +0000531 if (NextToken != Other.NextToken)
532 return NextToken < Other.NextToken;
533 if (Column != Other.Column)
534 return Column < Other.Column;
Daniel Jasperd7896702013-02-19 09:28:55 +0000535 if (LineContainsContinuedForLoopSection !=
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000536 Other.LineContainsContinuedForLoopSection)
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000537 return LineContainsContinuedForLoopSection;
Daniel Jasperd7896702013-02-19 09:28:55 +0000538 if (ParenLevel != Other.ParenLevel)
539 return ParenLevel < Other.ParenLevel;
540 if (StartOfLineLevel != Other.StartOfLineLevel)
541 return StartOfLineLevel < Other.StartOfLineLevel;
Daniel Jasper07ca5472013-07-05 09:14:35 +0000542 if (LowestLevelOnLine != Other.LowestLevelOnLine)
543 return LowestLevelOnLine < Other.LowestLevelOnLine;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000544 if (StartOfStringLiteral != Other.StartOfStringLiteral)
545 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper54b4e442013-05-22 05:27:42 +0000546 if (IgnoreStackForComparison || Other.IgnoreStackForComparison)
547 return false;
Daniel Jasperd7896702013-02-19 09:28:55 +0000548 return Stack < Other.Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000549 }
550 };
551
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000552 /// \brief Formats the line starting at \p State, simply keeping all of the
553 /// input's line breaking decisions.
554 void formatWithoutColumnLimit(LineState &State) {
555 while (State.NextToken != NULL) {
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000556 bool Newline = mustBreak(State) ||
557 (canBreak(State) && State.NextToken->NewlinesBefore > 0);
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000558 addTokenToState(Newline, /*DryRun=*/false, State);
559 }
560 }
561
Daniel Jasper20409152012-12-04 14:54:30 +0000562 /// \brief Appends the next token to \p State and updates information
563 /// necessary for indentation.
564 ///
Nico Weber1907c572013-06-26 02:42:46 +0000565 /// Puts the token on the current line if \p Newline is \c false and adds a
Daniel Jasper20409152012-12-04 14:54:30 +0000566 /// line break and necessary indentation otherwise.
567 ///
568 /// If \p DryRun is \c false, also creates and stores the required
569 /// \c Replacement.
Manuel Klimek8092a942013-02-20 10:15:13 +0000570 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000571 const FormatToken &Current = *State.NextToken;
572 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000573
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000574 // Extra penalty that needs to be added because of the way certain line
575 // breaks are chosen.
576 unsigned ExtraPenalty = 0;
577
Daniel Jasper92f9faf2013-03-20 15:58:10 +0000578 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Manuel Klimekad3094b2013-05-23 10:56:37 +0000579 // FIXME: Is this correct?
Manuel Klimekb3987012013-05-29 14:47:47 +0000580 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
581 State.NextToken->WhitespaceRange.getEnd()) -
582 SourceMgr.getSpellingColumnNumber(
583 State.NextToken->WhitespaceRange.getBegin());
Alexander Kornienko00895102013-06-05 14:09:10 +0000584 State.Column += WhitespaceLength + State.NextToken->CodePointCount;
Manuel Klimekb3987012013-05-29 14:47:47 +0000585 State.NextToken = State.NextToken->Next;
Manuel Klimek8092a942013-02-20 10:15:13 +0000586 return 0;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000587 }
588
Daniel Jasper3776ef32013-04-03 07:21:51 +0000589 // If we are continuing an expression, we want to indent an extra 4 spaces.
590 unsigned ContinuationIndent =
Daniel Jasper37911302013-04-02 14:33:13 +0000591 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000592 if (Newline) {
Daniel Jasper88cc5622013-07-08 14:25:23 +0000593 State.Stack.back().ContainsLineBreak = true;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000594 if (Current.is(tok::r_brace)) {
Daniel Jasper0de1c4d2013-07-09 09:06:29 +0000595 if (Current.BlockKind == BK_BracedInit)
596 State.Column = State.Stack[State.Stack.size() - 2].LastSpace;
597 else
Daniel Jasper15ec3a82013-07-11 21:27:40 +0000598 State.Column = FirstIndent;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000599 } else if (Current.is(tok::string_literal) &&
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000600 State.StartOfStringLiteral != 0) {
601 State.Column = State.StartOfStringLiteral;
Daniel Jasper66d19bd2013-02-18 11:59:17 +0000602 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000603 } else if (Current.is(tok::lessless) &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000604 State.Stack.back().FirstLessLess != 0) {
605 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasper5ad390d2013-05-28 11:30:49 +0000606 } else if (Current.isOneOf(tok::period, tok::arrow) &&
607 Current.Type != TT_DesignatedInitializerPeriod) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000608 if (State.Stack.back().CallContinuation == 0) {
609 State.Column = ContinuationIndent;
Daniel Jasper37911302013-04-02 14:33:13 +0000610 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000611 } else {
612 State.Column = State.Stack.back().CallContinuation;
613 }
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000614 } else if (Current.Type == TT_ConditionalExpr) {
615 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000616 } else if (Previous.is(tok::comma) &&
617 State.Stack.back().VariablePos != 0) {
618 State.Column = State.Stack.back().VariablePos;
Daniel Jasper3c08a812013-02-24 18:54:32 +0000619 } else if (Previous.ClosesTemplateDeclaration ||
Daniel Jasper6561f6a2013-07-09 07:43:55 +0000620 ((Current.Type == TT_StartOfName ||
621 Current.is(tok::kw_operator)) &&
622 State.ParenLevel == 0 &&
Manuel Klimeka9a7f102013-06-21 17:25:42 +0000623 (!Style.IndentFunctionDeclarationAfterType ||
624 Line.StartsDefinition))) {
Daniel Jasper37911302013-04-02 14:33:13 +0000625 State.Column = State.Stack.back().Indent;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000626 } else if (Current.Type == TT_ObjCSelectorName) {
Alexander Kornienko00895102013-06-05 14:09:10 +0000627 if (State.Stack.back().ColonPos > Current.CodePointCount) {
628 State.Column = State.Stack.back().ColonPos - Current.CodePointCount;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000629 } else {
630 State.Column = State.Stack.back().Indent;
Alexander Kornienko00895102013-06-05 14:09:10 +0000631 State.Stack.back().ColonPos = State.Column + Current.CodePointCount;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000632 }
Daniel Jasper011c35d2013-07-12 11:19:37 +0000633 } else if (Current.is(tok::l_square) &&
634 Current.Type != TT_ObjCMethodExpr) {
635 if (State.Stack.back().StartOfArraySubscripts != 0)
636 State.Column = State.Stack.back().StartOfArraySubscripts;
637 else
638 State.Column = ContinuationIndent;
Daniel Jasperb2f063a2013-05-08 10:00:18 +0000639 } else if (Current.Type == TT_StartOfName ||
640 Previous.isOneOf(tok::coloncolon, tok::equal) ||
Daniel Jasper37911302013-04-02 14:33:13 +0000641 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000642 State.Column = ContinuationIndent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000643 } else {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000644 State.Column = State.Stack.back().Indent;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000645 // Ensure that we fall back to indenting 4 spaces instead of just
646 // flushing continuations left.
Daniel Jasper37911302013-04-02 14:33:13 +0000647 if (State.Column == FirstIndent)
648 State.Column += 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000649 }
650
Daniel Jasper7878a7b2013-02-15 11:07:25 +0000651 if (Current.is(tok::question))
Daniel Jasper237d4c12013-02-23 21:01:55 +0000652 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper11e13802013-05-08 14:12:04 +0000653 if ((Previous.isOneOf(tok::comma, tok::semi) &&
654 !State.Stack.back().AvoidBinPacking) ||
655 Previous.Type == TT_BinaryOperator)
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000656 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper33f4b902013-05-15 09:35:08 +0000657 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
658 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000659
Manuel Klimek060143e2013-01-02 18:33:23 +0000660 if (!DryRun) {
Daniel Jasper1ef81d52013-02-26 13:10:34 +0000661 unsigned NewLines = 1;
Alexander Kornienkoe3f11972013-06-12 19:04:12 +0000662 if (Current.is(tok::comment))
Manuel Klimekb3987012013-05-29 14:47:47 +0000663 NewLines = std::max(
664 NewLines,
665 std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1));
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000666 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
667 State.Column, Line.InPPDirective);
Manuel Klimek060143e2013-01-02 18:33:23 +0000668 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000669
Daniel Jaspere1f9a8e2013-07-11 13:48:16 +0000670 if (!Current.isTrailingComment())
671 State.Stack.back().LastSpace = State.Column;
Daniel Jasper5ad390d2013-05-28 11:30:49 +0000672 if (Current.isOneOf(tok::arrow, tok::period) &&
673 Current.Type != TT_DesignatedInitializerPeriod)
Alexander Kornienko00895102013-06-05 14:09:10 +0000674 State.Stack.back().LastSpace += Current.CodePointCount;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000675 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper07ca5472013-07-05 09:14:35 +0000676 State.LowestLevelOnLine = State.ParenLevel;
Daniel Jasper237d4c12013-02-23 21:01:55 +0000677
678 // Any break on this level means that the parent level has been broken
679 // and we need to avoid bin packing there.
680 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
681 State.Stack[i].BreakBeforeParameter = true;
682 }
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000683 const FormatToken *TokenBefore = Current.getPreviousNonComment();
Daniel Jasper01218ff2013-04-15 22:36:37 +0000684 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
Daniel Jasper33f4b902013-05-15 09:35:08 +0000685 TokenBefore->Type != TT_TemplateCloser &&
Daniel Jasper11e13802013-05-08 14:12:04 +0000686 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000687 State.Stack.back().BreakBeforeParameter = true;
688
Daniel Jasper237d4c12013-02-23 21:01:55 +0000689 // If we break after {, we should also break before the corresponding }.
690 if (Previous.is(tok::l_brace))
691 State.Stack.back().BreakBeforeClosingBrace = true;
692
693 if (State.Stack.back().AvoidBinPacking) {
694 // If we are breaking after '(', '{', '<', this is not bin packing
695 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasperd741f022013-05-14 20:39:56 +0000696 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
697 Previous.Type == TT_BinaryOperator) ||
Daniel Jasper237d4c12013-02-23 21:01:55 +0000698 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
699 Line.MustBeDeclaration))
700 State.Stack.back().BreakBeforeParameter = true;
701 }
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000702
703 // Breaking before the first "<<" is generally not desirable.
704 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
705 ExtraPenalty += Style.PenaltyBreakFirstLessLess;
706
Daniel Jasperbac016b2012-12-03 18:12:45 +0000707 } else {
Daniel Jasper9c3e71a2013-02-25 15:59:54 +0000708 if (Current.is(tok::equal) &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000709 (RootToken->is(tok::kw_for) || State.ParenLevel == 0) &&
Daniel Jasperadc0f092013-04-05 09:38:50 +0000710 State.Stack.back().VariablePos == 0) {
711 State.Stack.back().VariablePos = State.Column;
712 // Move over * and & if they are bound to the variable name.
Manuel Klimekb3987012013-05-29 14:47:47 +0000713 const FormatToken *Tok = &Previous;
Alexander Kornienko00895102013-06-05 14:09:10 +0000714 while (Tok && State.Stack.back().VariablePos >= Tok->CodePointCount) {
715 State.Stack.back().VariablePos -= Tok->CodePointCount;
Daniel Jasperadc0f092013-04-05 09:38:50 +0000716 if (Tok->SpacesRequiredBefore != 0)
717 break;
Manuel Klimekb3987012013-05-29 14:47:47 +0000718 Tok = Tok->Previous;
Daniel Jasperadc0f092013-04-05 09:38:50 +0000719 }
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000720 if (Previous.PartOfMultiVariableDeclStmt)
721 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
722 }
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000723
Daniel Jasper729a7432013-02-11 12:36:37 +0000724 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper20409152012-12-04 14:54:30 +0000725
Daniel Jasperbac016b2012-12-03 18:12:45 +0000726 if (!DryRun)
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000727 Whitespaces.replaceWhitespace(Current, 0, Spaces,
728 State.Column + Spaces);
Daniel Jasper20409152012-12-04 14:54:30 +0000729
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000730 if (Current.Type == TT_ObjCSelectorName &&
731 State.Stack.back().ColonPos == 0) {
732 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienko00895102013-06-05 14:09:10 +0000733 State.Column + Spaces + Current.CodePointCount)
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000734 State.Stack.back().ColonPos =
735 State.Stack.back().Indent + Current.LongestObjCSelectorName;
736 else
737 State.Stack.back().ColonPos =
Alexander Kornienko00895102013-06-05 14:09:10 +0000738 State.Column + Spaces + Current.CodePointCount;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000739 }
740
Daniel Jasperac3223e2013-04-10 09:49:49 +0000741 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000742 Current.Type != TT_LineComment)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000743 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000744 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
745 State.Stack.back().AvoidBinPacking)
746 State.Stack.back().NoLineBreak = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000747
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000748 State.Column += Spaces;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000749 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jaspere438bac2013-01-23 20:41:06 +0000750 // Treat the condition inside an if as if it was a second function
751 // parameter, i.e. let nested calls have an indent of 4.
752 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperf9955d32013-03-20 12:37:50 +0000753 else if (Previous.is(tok::comma))
Daniel Jaspere438bac2013-01-23 20:41:06 +0000754 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000755 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper02b771e2013-01-28 13:31:35 +0000756 Previous.Type == TT_ConditionalExpr ||
757 Previous.Type == TT_CtorInitializerColon) &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000758 !(Previous.getPrecedence() == prec::Assignment &&
Daniel Jasper512843a2013-05-27 12:45:09 +0000759 Current.FakeLParens.empty()))
760 // Always indent relative to the RHS of the expression unless this is a
761 // simple assignment without binary expression on the RHS.
Daniel Jasperae8699b2013-01-28 09:35:24 +0000762 State.Stack.back().LastSpace = State.Column;
Daniel Jasper6cabab42013-02-14 08:42:54 +0000763 else if (Previous.Type == TT_InheritanceColon)
764 State.Stack.back().Indent = State.Column;
Daniel Jasperb1491792013-07-09 11:57:27 +0000765 else if (Previous.opensScope()) {
766 // If a function has multiple parameters (including a single parameter
Daniel Jasper2ca37412013-07-09 14:36:48 +0000767 // that is a binary expression) or a trailing call, indent all
Daniel Jasperb1491792013-07-09 11:57:27 +0000768 // parameters from the opening parenthesis. This avoids confusing
769 // indents like:
770 // OuterFunction(InnerFunctionCall(
771 // ParameterToInnerFunction),
772 // SecondParameterToOuterFunction);
773 bool HasMultipleParameters = !Current.FakeLParens.empty();
774 bool HasTrailingCall = false;
775 if (Previous.MatchingParen) {
776 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
777 if (Next && Next->isOneOf(tok::period, tok::arrow))
778 HasTrailingCall = true;
779 }
780 if (HasMultipleParameters || HasTrailingCall)
781 State.Stack.back().LastSpace = State.Column;
782 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000783 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000784
Daniel Jasper0fde9502013-07-12 11:37:05 +0000785 return moveStateToNextToken(State, DryRun, Newline) + ExtraPenalty;
Daniel Jasper20409152012-12-04 14:54:30 +0000786 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000787
Daniel Jasper20409152012-12-04 14:54:30 +0000788 /// \brief Mark the next token as consumed in \p State and modify its stacks
789 /// accordingly.
Daniel Jasper0fde9502013-07-12 11:37:05 +0000790 unsigned moveStateToNextToken(LineState &State, bool DryRun, bool Newline) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000791 const FormatToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000792 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000793
Daniel Jasper6cabab42013-02-14 08:42:54 +0000794 if (Current.Type == TT_InheritanceColon)
795 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000796 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
797 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasper011c35d2013-07-12 11:19:37 +0000798 if (Current.is(tok::l_square) &&
799 State.Stack.back().StartOfArraySubscripts == 0)
800 State.Stack.back().StartOfArraySubscripts = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000801 if (Current.is(tok::question))
802 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper07ca5472013-07-05 09:14:35 +0000803 if (!Current.opensScope() && !Current.closesScope())
804 State.LowestLevelOnLine =
805 std::min(State.LowestLevelOnLine, State.ParenLevel);
806 if (Current.isOneOf(tok::period, tok::arrow) &&
807 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
808 State.Stack.back().StartOfFunctionCall =
809 Current.LastInChainOfCalls ? 0
810 : State.Column + Current.CodePointCount;
Daniel Jasper7d812812013-02-21 15:00:29 +0000811 if (Current.Type == TT_CtorInitializerColon) {
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000812 // Indent 2 from the column, so:
813 // SomeClass::SomeClass()
814 // : First(...), ...
815 // Next(...)
816 // ^ line up here.
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000817 if (!Style.BreakConstructorInitializersBeforeComma)
818 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper7d812812013-02-21 15:00:29 +0000819 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
820 State.Stack.back().AvoidBinPacking = true;
821 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000822 }
Daniel Jasper3776ef32013-04-03 07:21:51 +0000823
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000824 // If return returns a binary expression, align after it.
825 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
826 State.Stack.back().LastSpace = State.Column + 7;
827
Daniel Jasper3776ef32013-04-03 07:21:51 +0000828 // In ObjC method declaration we align on the ":" of parameters, but we need
829 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasper37911302013-04-02 14:33:13 +0000830 if (Current.Type == TT_ObjCMethodSpecifier)
831 State.Stack.back().Indent += 4;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000832
Daniel Jasper29f123b2013-02-08 15:28:42 +0000833 // Insert scopes created by fake parenthesis.
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000834 const FormatToken *Previous = Current.getPreviousNonComment();
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000835 // Don't add extra indentation for the first fake parenthesis after
836 // 'return', assignements or opening <({[. The indentation for these cases
837 // is special cased.
838 bool SkipFirstExtraIndent =
839 Current.is(tok::kw_return) ||
Daniel Jasperac3223e2013-04-10 09:49:49 +0000840 (Previous && (Previous->opensScope() ||
Manuel Klimekb3987012013-05-29 14:47:47 +0000841 Previous->getPrecedence() == prec::Assignment));
Craig Topper163fbf82013-07-08 03:55:09 +0000842 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000843 I = Current.FakeLParens.rbegin(),
844 E = Current.FakeLParens.rend();
845 I != E; ++I) {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000846 ParenState NewParenState = State.Stack.back();
Daniel Jasper88cc5622013-07-08 14:25:23 +0000847 NewParenState.ContainsLineBreak = false;
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000848 NewParenState.Indent =
849 std::max(std::max(State.Column, NewParenState.Indent),
850 State.Stack.back().LastSpace);
851
852 // Always indent conditional expressions. Never indent expression where
853 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
854 // prec::Assignment) as those have different indentation rules. Indent
855 // other expression, unless the indentation needs to be skipped.
856 if (*I == prec::Conditional ||
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000857 (!SkipFirstExtraIndent && *I > prec::Assignment &&
858 !Style.BreakBeforeBinaryOperators))
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000859 NewParenState.Indent += 4;
Daniel Jasperac3223e2013-04-10 09:49:49 +0000860 if (Previous && !Previous->opensScope())
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000861 NewParenState.BreakBeforeParameter = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000862 State.Stack.push_back(NewParenState);
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000863 SkipFirstExtraIndent = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000864 }
865
Daniel Jaspercf225b62012-12-24 13:43:52 +0000866 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000867 // prepare for the following tokens.
Daniel Jasperac3223e2013-04-10 09:49:49 +0000868 if (Current.opensScope()) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000869 unsigned NewIndent;
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000870 unsigned LastSpace = State.Stack.back().LastSpace;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000871 bool AvoidBinPacking;
Manuel Klimek2851c162013-01-10 14:36:46 +0000872 if (Current.is(tok::l_brace)) {
Daniel Jasperb5dc3f42013-07-16 18:22:10 +0000873 NewIndent =
874 LastSpace + (Style.Cpp11BracedListStyle ? 4 : Style.IndentWidth);
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000875 const FormatToken *NextNoComment = Current.getNextNonComment();
Daniel Jasper5ad390d2013-05-28 11:30:49 +0000876 AvoidBinPacking = NextNoComment &&
877 NextNoComment->Type == TT_DesignatedInitializerPeriod;
Manuel Klimek2851c162013-01-10 14:36:46 +0000878 } else {
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000879 NewIndent =
880 4 + std::max(LastSpace, State.Stack.back().StartOfFunctionCall);
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000881 AvoidBinPacking = !Style.BinPackParameters ||
882 (Style.ExperimentalAutoDetectBinPacking &&
883 (Current.PackingKind == PPK_OnePerLine ||
884 (!BinPackInconclusiveFunctions &&
885 Current.PackingKind == PPK_Inconclusive)));
Manuel Klimek2851c162013-01-10 14:36:46 +0000886 }
Daniel Jasperfca24bc2013-04-25 13:31:51 +0000887
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000888 State.Stack.push_back(ParenState(NewIndent, LastSpace, AvoidBinPacking,
889 State.Stack.back().NoLineBreak));
Daniel Jasper29f123b2013-02-08 15:28:42 +0000890 ++State.ParenLevel;
Daniel Jasper20409152012-12-04 14:54:30 +0000891 }
892
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000893 // If this '[' opens an ObjC call, determine whether all parameters fit into
894 // one line and put one per line if they don't.
895 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
896 Current.MatchingParen != NULL) {
897 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
898 State.Stack.back().BreakBeforeParameter = true;
899 }
900
Daniel Jaspercf225b62012-12-24 13:43:52 +0000901 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000902 // stacks.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000903 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Manuel Klimekb3987012013-05-29 14:47:47 +0000904 (Current.is(tok::r_brace) && State.NextToken != RootToken) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +0000905 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000906 State.Stack.pop_back();
Daniel Jasper29f123b2013-02-08 15:28:42 +0000907 --State.ParenLevel;
908 }
Daniel Jasper011c35d2013-07-12 11:19:37 +0000909 if (Current.is(tok::r_square)) {
910 // If this ends the array subscript expr, reset the corresponding value.
911 const FormatToken *NextNonComment = Current.getNextNonComment();
912 if (NextNonComment && NextNonComment->isNot(tok::l_square))
Daniel Jasper9637dda2013-07-15 14:33:14 +0000913 State.Stack.back().StartOfArraySubscripts = 0;
Daniel Jasper011c35d2013-07-12 11:19:37 +0000914 }
Daniel Jasper29f123b2013-02-08 15:28:42 +0000915
916 // Remove scopes created by fake parenthesis.
917 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasperabfc9c12013-04-04 19:31:00 +0000918 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000919 State.Stack.pop_back();
Daniel Jasperabfc9c12013-04-04 19:31:00 +0000920 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000921 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000922
Daniel Jasper27c7f542013-05-13 20:50:15 +0000923 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000924 State.StartOfStringLiteral = State.Column;
Daniel Jasper27c7f542013-05-13 20:50:15 +0000925 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
926 tok::string_literal)) {
Daniel Jasper9a2f8d02013-05-16 04:26:02 +0000927 State.StartOfStringLiteral = 0;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000928 }
929
Alexander Kornienko00895102013-06-05 14:09:10 +0000930 State.Column += Current.CodePointCount;
Manuel Klimek8092a942013-02-20 10:15:13 +0000931
Manuel Klimekb3987012013-05-29 14:47:47 +0000932 State.NextToken = State.NextToken->Next;
Manuel Klimek2851c162013-01-10 14:36:46 +0000933
Daniel Jasper0fde9502013-07-12 11:37:05 +0000934 if (!Newline && Style.AlwaysBreakBeforeMultilineStrings &&
935 Current.is(tok::string_literal))
936 return 0;
937
Manuel Klimek8092a942013-02-20 10:15:13 +0000938 return breakProtrudingToken(Current, State, DryRun);
939 }
940
941 /// \brief If the current token sticks out over the end of the line, break
942 /// it if possible.
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000943 ///
944 /// \returns An extra penalty if a token was broken, otherwise 0.
945 ///
Alexander Kornienkod446f732013-07-01 13:42:42 +0000946 /// The returned penalty will cover the cost of the additional line breaks and
947 /// column limit violation in all lines except for the last one. The penalty
948 /// for the column limit violation in the last line (and in single line
949 /// tokens) is handled in \c addNextStateToQueue.
Manuel Klimekb3987012013-05-29 14:47:47 +0000950 unsigned breakProtrudingToken(const FormatToken &Current, LineState &State,
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000951 bool DryRun) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000952 llvm::OwningPtr<BreakableToken> Token;
Alexander Kornienko00895102013-06-05 14:09:10 +0000953 unsigned StartColumn = State.Column - Current.CodePointCount;
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000954 unsigned OriginalStartColumn =
Manuel Klimekb3987012013-05-29 14:47:47 +0000955 SourceMgr.getSpellingColumnNumber(Current.getStartOfNonWhitespace()) -
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000956 1;
Manuel Klimekde008c02013-05-27 15:23:34 +0000957
Daniel Jasper5d5b4242013-05-16 12:59:13 +0000958 if (Current.is(tok::string_literal) &&
959 Current.Type != TT_ImplicitStringLiteral) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000960 // Only break up default narrow strings.
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000961 if (!Current.TokenText.startswith("\""))
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000962 return 0;
Alexander Kornienko10c26b22013-07-16 21:06:13 +0000963 // Don't break string literals with escaped newlines. As clang-format must
964 // not change the string's content, it is unlikely that we'll end up with
965 // a better format.
966 if (Current.TokenText.find("\\\n") != StringRef::npos)
967 return 0;
Daniel Jasper561211d2013-07-16 20:28:33 +0000968 // Exempts unterminated string literals from line breaking. The user will
969 // likely want to terminate the string before any line breaking is done.
970 if (Current.IsUnterminatedLiteral)
971 return 0;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000972
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000973 Token.reset(new BreakableStringLiteral(Current, StartColumn,
974 Line.InPPDirective, Encoding));
Alexander Kornienkob4b4a522013-07-16 23:47:22 +0000975 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000976 Token.reset(new BreakableBlockComment(
Alexander Kornienko00895102013-06-05 14:09:10 +0000977 Style, Current, StartColumn, OriginalStartColumn, !Current.Previous,
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000978 Line.InPPDirective, Encoding));
Daniel Jasper7ff96ed2013-05-06 10:24:51 +0000979 } else if (Current.Type == TT_LineComment &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000980 (Current.Previous == NULL ||
981 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko10c26b22013-07-16 21:06:13 +0000982 // Don't break line comments with escaped newlines. These look like
983 // separate line comments, but in fact contain a single line comment with
984 // multiple lines including leading whitespace and the '//' markers.
985 //
986 // FIXME: If we want to handle them correctly, we'll need to adjust
987 // leading whitespace in consecutive lines when changing indentation of
988 // the first line similar to what we do with block comments.
989 StringRef::size_type EscapedNewlinePos = Current.TokenText.find("\\\n");
990 if (EscapedNewlinePos != StringRef::npos) {
991 State.Column =
992 StartColumn +
993 encoding::getCodePointCount(
994 Current.TokenText.substr(0, EscapedNewlinePos), Encoding) +
995 1;
996 return 0;
997 }
998
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000999 Token.reset(new BreakableLineComment(Current, StartColumn,
1000 Line.InPPDirective, Encoding));
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001001 } else {
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001002 return 0;
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001003 }
Alexander Kornienko16a0ec62013-06-14 11:46:10 +00001004 if (Current.UnbreakableTailLength >= getColumnLimit())
Manuel Klimek2a9805d2013-05-14 09:04:24 +00001005 return 0;
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001006
Alexander Kornienkoc36c5c22013-06-19 19:50:11 +00001007 unsigned RemainingSpace = getColumnLimit() - Current.UnbreakableTailLength;
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001008 bool BreakInserted = false;
1009 unsigned Penalty = 0;
Alexander Kornienkoc36c5c22013-06-19 19:50:11 +00001010 unsigned RemainingTokenColumns = 0;
Manuel Klimekde008c02013-05-27 15:23:34 +00001011 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
1012 LineIndex != EndIndex; ++LineIndex) {
Alexander Kornienko16a0ec62013-06-14 11:46:10 +00001013 if (!DryRun)
1014 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001015 unsigned TailOffset = 0;
Alexander Kornienkoc36c5c22013-06-19 19:50:11 +00001016 RemainingTokenColumns = Token->getLineLengthAfterSplit(
Alexander Kornienko2785b9a2013-06-07 16:02:52 +00001017 LineIndex, TailOffset, StringRef::npos);
Alexander Kornienko00895102013-06-05 14:09:10 +00001018 while (RemainingTokenColumns > RemainingSpace) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001019 BreakableToken::Split Split =
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001020 Token->getSplit(LineIndex, TailOffset, getColumnLimit());
Alexander Kornienkod446f732013-07-01 13:42:42 +00001021 if (Split.first == StringRef::npos) {
1022 // The last line's penalty is handled in addNextStateToQueue().
1023 if (LineIndex < EndIndex - 1)
1024 Penalty += Style.PenaltyExcessCharacter *
1025 (RemainingTokenColumns - RemainingSpace);
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001026 break;
Alexander Kornienkod446f732013-07-01 13:42:42 +00001027 }
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001028 assert(Split.first != 0);
Alexander Kornienko00895102013-06-05 14:09:10 +00001029 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
Alexander Kornienko2785b9a2013-06-07 16:02:52 +00001030 LineIndex, TailOffset + Split.first + Split.second,
1031 StringRef::npos);
Alexander Kornienko00895102013-06-05 14:09:10 +00001032 assert(NewRemainingTokenColumns < RemainingTokenColumns);
Alexander Kornienko16a0ec62013-06-14 11:46:10 +00001033 if (!DryRun)
1034 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Alexander Kornienko2785b9a2013-06-07 16:02:52 +00001035 Penalty += Current.is(tok::string_literal) ? Style.PenaltyBreakString
1036 : Style.PenaltyBreakComment;
1037 unsigned ColumnsUsed =
1038 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
1039 if (ColumnsUsed > getColumnLimit()) {
1040 Penalty +=
1041 Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit());
1042 }
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001043 TailOffset += Split.first + Split.second;
Alexander Kornienko00895102013-06-05 14:09:10 +00001044 RemainingTokenColumns = NewRemainingTokenColumns;
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001045 BreakInserted = true;
Manuel Klimek8092a942013-02-20 10:15:13 +00001046 }
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001047 }
1048
Alexander Kornienkoc36c5c22013-06-19 19:50:11 +00001049 State.Column = RemainingTokenColumns;
1050
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001051 if (BreakInserted) {
Alexander Kornienko22d0e292013-06-17 12:59:44 +00001052 // If we break the token inside a parameter list, we need to break before
1053 // the next parameter on all levels, so that the next parameter is clearly
1054 // visible. Line comments already introduce a break.
1055 if (Current.Type != TT_LineComment) {
1056 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1057 State.Stack[i].BreakBeforeParameter = true;
1058 }
1059
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001060 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek8092a942013-02-20 10:15:13 +00001061 }
Manuel Klimek8092a942013-02-20 10:15:13 +00001062 return Penalty;
1063 }
1064
Daniel Jasperceb99ab2013-01-09 10:16:05 +00001065 unsigned getColumnLimit() {
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001066 // In preprocessor directives reserve two chars for trailing " \"
1067 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasperceb99ab2013-01-09 10:16:05 +00001068 }
1069
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001070 /// \brief An edge in the solution space from \c Previous->State to \c State,
1071 /// inserting a newline dependent on the \c NewLine.
1072 struct StateNode {
1073 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +00001074 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001075 LineState State;
1076 bool NewLine;
1077 StateNode *Previous;
1078 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001079
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001080 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
1081 ///
1082 /// In case of equal penalties, we want to prefer states that were inserted
1083 /// first. During state generation we make sure that we insert states first
1084 /// that break the line as late as possible.
1085 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1086
1087 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
1088 /// \c State has the given \c OrderedPenalty.
1089 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1090
1091 /// \brief The BFS queue type.
1092 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1093 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001094
1095 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +00001096 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001097 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1098 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1099 /// find the shortest path (the one with lowest penalty) from \p InitialState
1100 /// to a state where all tokens are placed.
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001101 void analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001102 std::set<LineState> Seen;
1103
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001104 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +00001105 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001106 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
1107 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1108 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001109
1110 // While not empty, take first element and follow edges.
1111 while (!Queue.empty()) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001112 unsigned Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +00001113 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001114 if (Node->State.NextToken == NULL) {
Alexander Kornienkodd256312013-05-10 11:56:10 +00001115 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001116 break;
Daniel Jasper01786732013-02-04 07:21:18 +00001117 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001118 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001119
Daniel Jasper54b4e442013-05-22 05:27:42 +00001120 // Cut off the analysis of certain solutions if the analysis gets too
1121 // complex. See description of IgnoreStackForComparison.
1122 if (Count > 10000)
1123 Node->State.IgnoreStackForComparison = true;
1124
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001125 if (!Seen.insert(Node->State).second)
1126 // State already examined with lower penalty.
1127 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001128
Nico Weber27268772013-06-26 00:30:14 +00001129 addNextStateToQueue(Penalty, Node, /*NewLine=*/false);
1130 addNextStateToQueue(Penalty, Node, /*NewLine=*/true);
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001131 }
1132
1133 if (Queue.empty())
1134 // We were unable to find a solution, do nothing.
1135 // FIXME: Add diagnostic?
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001136 return;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001137
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001138 // Reconstruct the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001139 reconstructPath(InitialState, Queue.top().second);
Alexander Kornienkodd256312013-05-10 11:56:10 +00001140 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1141 DEBUG(llvm::dbgs() << "---\n");
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001142 }
1143
1144 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek9c333b92013-05-29 15:10:11 +00001145 std::deque<StateNode *> Path;
1146 // We do not need a break before the initial token.
1147 while (Current->Previous) {
1148 Path.push_front(Current);
1149 Current = Current->Previous;
1150 }
1151 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1152 I != E; ++I) {
1153 DEBUG({
1154 if ((*I)->NewLine) {
1155 llvm::dbgs() << "Penalty for splitting before "
1156 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
1157 << (*I)->Previous->State.NextToken->SplitPenalty << "\n";
1158 }
1159 });
1160 addTokenToState((*I)->NewLine, false, State);
1161 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001162 }
1163
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001164 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001165 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001166 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001167 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001168 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1169 bool NewLine) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001170 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001171 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001172 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001173 return;
Daniel Jasper88cc5622013-07-08 14:25:23 +00001174 if (NewLine) {
1175 if (!PreviousNode->State.Stack.back().ContainsLineBreak)
1176 Penalty += 15;
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001177 Penalty += PreviousNode->State.NextToken->SplitPenalty;
Daniel Jasper88cc5622013-07-08 14:25:23 +00001178 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001179
1180 StateNode *Node = new (Allocator.Allocate())
1181 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek8092a942013-02-20 10:15:13 +00001182 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001183 if (Node->State.Column > getColumnLimit()) {
1184 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper01786732013-02-04 07:21:18 +00001185 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasperceb99ab2013-01-09 10:16:05 +00001186 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001187
1188 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
1189 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001190 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001191
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001192 /// \brief Returns \c true, if a line break after \p State is allowed.
1193 bool canBreak(const LineState &State) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001194 const FormatToken &Current = *State.NextToken;
1195 const FormatToken &Previous = *Current.Previous;
1196 assert(&Previous == Current.Previous);
Daniel Jasper399914b2013-05-17 09:35:01 +00001197 if (!Current.CanBreakBefore &&
1198 !(Current.is(tok::r_brace) &&
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001199 State.Stack.back().BreakBeforeClosingBrace))
1200 return false;
Daniel Jasper399914b2013-05-17 09:35:01 +00001201 // The opening "{" of a braced list has to be on the same line as the first
1202 // element if it is nested in another braced init list or function call.
1203 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001204 Previous.Previous &&
1205 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
Daniel Jasper399914b2013-05-17 09:35:01 +00001206 return false;
Daniel Jasper259a0382013-05-27 11:50:16 +00001207 // This prevents breaks like:
1208 // ...
1209 // SomeParameter, OtherParameter).DoSomething(
1210 // ...
1211 // As they hide "DoSomething" and are generally bad for readability.
Daniel Jasper07ca5472013-07-05 09:14:35 +00001212 if (Previous.opensScope() &&
1213 State.LowestLevelOnLine < State.StartOfLineLevel)
Daniel Jasper259a0382013-05-27 11:50:16 +00001214 return false;
Daniel Jasper001bf4e2013-04-22 07:59:53 +00001215 return !State.Stack.back().NoLineBreak;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001216 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001217
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001218 /// \brief Returns \c true, if a line break after \p State is mandatory.
1219 bool mustBreak(const LineState &State) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001220 const FormatToken &Current = *State.NextToken;
1221 const FormatToken &Previous = *Current.Previous;
Daniel Jasper11e13802013-05-08 14:12:04 +00001222 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001223 return true;
Daniel Jasperb5dc3f42013-07-16 18:22:10 +00001224 if (!Style.Cpp11BracedListStyle && Current.is(tok::r_brace) &&
1225 State.Stack.back().BreakBeforeClosingBrace)
1226 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001227 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001228 return true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +00001229 if (Style.BreakConstructorInitializersBeforeComma) {
1230 if (Previous.Type == TT_CtorInitializerComma)
1231 return false;
1232 if (Current.Type == TT_CtorInitializerComma)
1233 return true;
1234 }
Daniel Jasper11e13802013-05-08 14:12:04 +00001235 if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) ||
1236 Current.Type == TT_ConditionalExpr) &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +00001237 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper11e13802013-05-08 14:12:04 +00001238 !Current.isTrailingComment() &&
1239 !Current.isOneOf(tok::r_paren, tok::r_brace))
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001240 return true;
Daniel Jasper215c57f2013-07-17 15:38:19 +00001241 if (Style.AlwaysBreakBeforeMultilineStrings &&
1242 State.Column > State.Stack.back().Indent &&
1243 Current.is(tok::string_literal) && Previous.isNot(tok::lessless) &&
1244 Previous.Type != TT_InlineASMColon &&
1245 ((Current.getNextNonComment() &&
1246 Current.getNextNonComment()->is(tok::string_literal)) ||
1247 (Current.TokenText.find("\\\n") != StringRef::npos)))
1248 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001249
Daniel Jaspere8b10d32013-07-26 16:56:36 +00001250 if (!Style.BreakBeforeBinaryOperators) {
1251 // If we need to break somewhere inside the LHS of a binary expression, we
1252 // should also break after the operator. Otherwise, the formatting would
1253 // hide the operator precedence, e.g. in:
1254 // if (aaaaaaaaaaaaaa ==
1255 // bbbbbbbbbbbbbb && c) {..
1256 // For comparisons, we only apply this rule, if the LHS is a binary
1257 // expression itself as otherwise, the line breaks seem superfluous.
1258 // We need special cases for ">>" which we have split into two ">" while
1259 // lexing in order to make template parsing easier.
1260 //
1261 // FIXME: We'll need something similar for styles that break before binary
1262 // operators.
1263 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
1264 Previous.getPrecedence() == prec::Equality) &&
1265 Previous.Previous && Previous.Previous->Type !=
1266 TT_BinaryOperator; // For >>.
1267 bool LHSIsBinaryExpr =
1268 Previous.Previous && Previous.Previous->FakeRParens > 0;
1269 if (Previous.Type == TT_BinaryOperator &&
1270 (!IsComparison || LHSIsBinaryExpr) &&
1271 Current.Type != TT_BinaryOperator && // For >>.
1272 !Current.isTrailingComment() &&
1273 !Previous.isOneOf(tok::lessless, tok::question) &&
1274 Previous.getPrecedence() != prec::Assignment &&
1275 State.Stack.back().BreakBeforeParameter)
1276 return true;
1277 }
Daniel Jasper11e13802013-05-08 14:12:04 +00001278
Daniel Jaspera0740f52013-07-12 15:14:05 +00001279 // Same as above, but for the first "<<" operator.
1280 if (Current.is(tok::lessless) && State.Stack.back().BreakBeforeParameter &&
1281 State.Stack.back().FirstLessLess == 0)
1282 return true;
1283
Daniel Jasper11e13802013-05-08 14:12:04 +00001284 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1285 // out whether it is the first parameter. Clean this up.
1286 if (Current.Type == TT_ObjCSelectorName &&
1287 Current.LongestObjCSelectorName == 0 &&
1288 State.Stack.back().BreakBeforeParameter)
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001289 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001290 if ((Current.Type == TT_CtorInitializerColon ||
1291 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0)))
Daniel Jasper923ebef2013-03-14 13:45:21 +00001292 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001293
Daniel Jasper6561f6a2013-07-09 07:43:55 +00001294 if ((Current.Type == TT_StartOfName || Current.is(tok::kw_operator)) &&
1295 Line.MightBeFunctionDecl && State.Stack.back().BreakBeforeParameter &&
1296 State.ParenLevel == 0)
Daniel Jasper33f4b902013-05-15 09:35:08 +00001297 return true;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001298 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001299 }
1300
Daniel Jasper3af59ce2013-03-15 14:57:30 +00001301 // Returns the total number of columns required for the remaining tokens.
1302 unsigned getRemainingLength(const LineState &State) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001303 if (State.NextToken && State.NextToken->Previous)
1304 return Line.Last->TotalLength - State.NextToken->Previous->TotalLength;
Daniel Jasper3af59ce2013-03-15 14:57:30 +00001305 return 0;
1306 }
1307
Daniel Jasperbac016b2012-12-03 18:12:45 +00001308 FormatStyle Style;
1309 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +00001310 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001311 const unsigned FirstIndent;
Manuel Klimekb3987012013-05-29 14:47:47 +00001312 const FormatToken *RootToken;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001313 WhitespaceManager &Whitespaces;
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001314
1315 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1316 QueueType Queue;
1317 // Increasing count of \c StateNode items we have created. This is used
1318 // to create a deterministic order independent of the container.
1319 unsigned Count;
Alexander Kornienko00895102013-06-05 14:09:10 +00001320 encoding::Encoding Encoding;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001321 bool BinPackInconclusiveFunctions;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001322};
1323
Manuel Klimek96e888b2013-05-28 11:55:06 +00001324class FormatTokenLexer {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001325public:
Alexander Kornienko00895102013-06-05 14:09:10 +00001326 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr,
1327 encoding::Encoding Encoding)
Manuel Klimek96e888b2013-05-28 11:55:06 +00001328 : FormatTok(NULL), GreaterStashed(false), TrailingWhitespace(0), Lex(Lex),
Alexander Kornienko00895102013-06-05 14:09:10 +00001329 SourceMgr(SourceMgr), IdentTable(Lex.getLangOpts()),
1330 Encoding(Encoding) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001331 Lex.SetKeepWhitespaceMode(true);
1332 }
1333
Manuel Klimek96e888b2013-05-28 11:55:06 +00001334 ArrayRef<FormatToken *> lex() {
1335 assert(Tokens.empty());
1336 do {
1337 Tokens.push_back(getNextToken());
1338 } while (Tokens.back()->Tok.isNot(tok::eof));
1339 return Tokens;
1340 }
1341
1342 IdentifierTable &getIdentTable() { return IdentTable; }
1343
1344private:
1345 FormatToken *getNextToken() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001346 if (GreaterStashed) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001347 // Create a synthesized second '>' token.
1348 Token Greater = FormatTok->Tok;
1349 FormatTok = new (Allocator.Allocate()) FormatToken;
1350 FormatTok->Tok = Greater;
Manuel Klimekad3094b2013-05-23 10:56:37 +00001351 SourceLocation GreaterLocation =
Manuel Klimek96e888b2013-05-28 11:55:06 +00001352 FormatTok->Tok.getLocation().getLocWithOffset(1);
1353 FormatTok->WhitespaceRange =
1354 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001355 FormatTok->TokenText = ">";
Alexander Kornienko00895102013-06-05 14:09:10 +00001356 FormatTok->CodePointCount = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001357 GreaterStashed = false;
1358 return FormatTok;
1359 }
1360
Manuel Klimek96e888b2013-05-28 11:55:06 +00001361 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper561211d2013-07-16 20:28:33 +00001362 readRawToken(*FormatTok);
Manuel Klimekde008c02013-05-27 15:23:34 +00001363 SourceLocation WhitespaceStart =
Manuel Klimek96e888b2013-05-28 11:55:06 +00001364 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Manuel Klimekad3094b2013-05-23 10:56:37 +00001365 if (SourceMgr.getFileOffset(WhitespaceStart) == 0)
Manuel Klimek96e888b2013-05-28 11:55:06 +00001366 FormatTok->IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001367
1368 // Consume and record whitespace until we find a significant token.
Manuel Klimekde008c02013-05-27 15:23:34 +00001369 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001370 while (FormatTok->Tok.is(tok::unknown)) {
Daniel Jasper561211d2013-07-16 20:28:33 +00001371 unsigned Newlines = FormatTok->TokenText.count('\n');
Daniel Jasper1eee6c42013-03-04 13:43:19 +00001372 if (Newlines > 0)
Daniel Jasper561211d2013-07-16 20:28:33 +00001373 FormatTok->LastNewlineOffset =
1374 WhitespaceLength + FormatTok->TokenText.rfind('\n') + 1;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001375 FormatTok->NewlinesBefore += Newlines;
Daniel Jasper561211d2013-07-16 20:28:33 +00001376 unsigned EscapedNewlines = FormatTok->TokenText.count("\\\n");
Manuel Klimek96e888b2013-05-28 11:55:06 +00001377 FormatTok->HasUnescapedNewline |= EscapedNewlines != Newlines;
1378 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001379
Daniel Jasper561211d2013-07-16 20:28:33 +00001380 readRawToken(*FormatTok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001381 }
Manuel Klimek95419382013-01-07 07:56:50 +00001382
Manuel Klimekd4397b92013-01-04 23:34:14 +00001383 // In case the token starts with escaped newlines, we want to
1384 // take them into account as whitespace - this pattern is quite frequent
1385 // in macro definitions.
1386 // FIXME: What do we want to do with other escaped spaces, and escaped
1387 // spaces or newlines in the middle of tokens?
1388 // FIXME: Add a more explicit test.
Daniel Jasper561211d2013-07-16 20:28:33 +00001389 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1390 FormatTok->TokenText[1] == '\n') {
Manuel Klimek96e888b2013-05-28 11:55:06 +00001391 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimekad3094b2013-05-23 10:56:37 +00001392 WhitespaceLength += 2;
Daniel Jasper561211d2013-07-16 20:28:33 +00001393 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001394 }
1395
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001396 TrailingWhitespace = 0;
1397 if (FormatTok->Tok.is(tok::comment)) {
Daniel Jasper561211d2013-07-16 20:28:33 +00001398 StringRef UntrimmedText = FormatTok->TokenText;
1399 FormatTok->TokenText = FormatTok->TokenText.rtrim();
1400 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001401 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper561211d2013-07-16 20:28:33 +00001402 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek96e888b2013-05-28 11:55:06 +00001403 FormatTok->Tok.setIdentifierInfo(&Info);
1404 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001405 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek96e888b2013-05-28 11:55:06 +00001406 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper561211d2013-07-16 20:28:33 +00001407 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001408 GreaterStashed = true;
1409 }
1410
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001411 // Now FormatTok is the next non-whitespace token.
Daniel Jasper561211d2013-07-16 20:28:33 +00001412 FormatTok->CodePointCount =
1413 encoding::getCodePointCount(FormatTok->TokenText, Encoding);
Alexander Kornienko00895102013-06-05 14:09:10 +00001414
Manuel Klimek96e888b2013-05-28 11:55:06 +00001415 FormatTok->WhitespaceRange = SourceRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001416 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001417 return FormatTok;
1418 }
1419
Manuel Klimek96e888b2013-05-28 11:55:06 +00001420 FormatToken *FormatTok;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001421 bool GreaterStashed;
Manuel Klimekde008c02013-05-27 15:23:34 +00001422 unsigned TrailingWhitespace;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001423 Lexer &Lex;
1424 SourceManager &SourceMgr;
1425 IdentifierTable IdentTable;
Alexander Kornienko00895102013-06-05 14:09:10 +00001426 encoding::Encoding Encoding;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001427 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1428 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001429
Daniel Jasper561211d2013-07-16 20:28:33 +00001430 void readRawToken(FormatToken &Tok) {
1431 Lex.LexFromRawLexer(Tok.Tok);
1432 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1433 Tok.Tok.getLength());
1434
1435 // For formatting, treat unterminated string literals like normal string
1436 // literals.
1437 if (Tok.is(tok::unknown) && !Tok.TokenText.empty() &&
1438 Tok.TokenText[0] == '"') {
1439 Tok.Tok.setKind(tok::string_literal);
1440 Tok.IsUnterminatedLiteral = true;
1441 }
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001442 }
1443};
1444
Daniel Jasperbac016b2012-12-03 18:12:45 +00001445class Formatter : public UnwrappedLineConsumer {
1446public:
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001447 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001448 const std::vector<CharSourceRange> &Ranges)
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001449 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko00895102013-06-05 14:09:10 +00001450 Whitespaces(SourceMgr, Style), Ranges(Ranges),
1451 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasper9637dda2013-07-15 14:33:14 +00001452 DEBUG(llvm::dbgs() << "File encoding: "
1453 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1454 : "unknown")
1455 << "\n");
Alexander Kornienko00895102013-06-05 14:09:10 +00001456 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001457
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001458 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001459
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001460 tooling::Replacements format() {
Alexander Kornienko00895102013-06-05 14:09:10 +00001461 FormatTokenLexer Tokens(Lex, SourceMgr, Encoding);
Manuel Klimek96e888b2013-05-28 11:55:06 +00001462
1463 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek67d080d2013-04-12 14:13:36 +00001464 bool StructuralError = Parser.parse();
Alexander Kornienko00895102013-06-05 14:09:10 +00001465 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001466 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1467 Annotator.annotate(AnnotatedLines[i]);
1468 }
1469 deriveLocalStyle();
1470 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1471 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1472 }
Daniel Jasper5999f762013-04-09 17:46:55 +00001473
1474 // Adapt level to the next line if this is a comment.
1475 // FIXME: Can/should this be done in the UnwrappedLineParser?
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001476 const AnnotatedLine *NextNonCommentLine = NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +00001477 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001478 if (NextNonCommentLine && AnnotatedLines[i].First->is(tok::comment) &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001479 !AnnotatedLines[i].First->Next)
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001480 AnnotatedLines[i].Level = NextNonCommentLine->Level;
Daniel Jasper5999f762013-04-09 17:46:55 +00001481 else
Daniel Jasper2a409b62013-07-08 14:34:09 +00001482 NextNonCommentLine = AnnotatedLines[i].First->isNot(tok::r_brace)
1483 ? &AnnotatedLines[i]
1484 : NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +00001485 }
1486
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001487 std::vector<int> IndentForLevel;
1488 bool PreviousLineWasTouched = false;
Manuel Klimekb3987012013-05-29 14:47:47 +00001489 const FormatToken *PreviousLineLastToken = 0;
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001490 bool FormatPPDirective = false;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001491 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1492 E = AnnotatedLines.end();
1493 I != E; ++I) {
1494 const AnnotatedLine &TheLine = *I;
Manuel Klimekb3987012013-05-29 14:47:47 +00001495 const FormatToken *FirstTok = TheLine.First;
1496 int Offset = getIndentOffset(*TheLine.First);
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001497
1498 // Check whether this line is part of a formatted preprocessor directive.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001499 if (FirstTok->HasUnescapedNewline)
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001500 FormatPPDirective = false;
1501 if (!FormatPPDirective && TheLine.InPPDirective &&
1502 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
1503 FormatPPDirective = true;
1504
Daniel Jasper1fb8d882013-05-14 09:30:02 +00001505 // Determine indent and try to merge multiple unwrapped lines.
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001506 while (IndentForLevel.size() <= TheLine.Level)
1507 IndentForLevel.push_back(-1);
1508 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper1fb8d882013-05-14 09:30:02 +00001509 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
1510 if (static_cast<int>(Indent) + Offset >= 0)
1511 Indent += Offset;
1512 tryFitMultipleLinesInOne(Indent, I, E);
1513
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001514 bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0;
Manuel Klimekb3987012013-05-29 14:47:47 +00001515 if (TheLine.First->is(tok::eof)) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001516 if (PreviousLineWasTouched) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001517 unsigned NewLines = std::min(FirstTok->NewlinesBefore, 1u);
Manuel Klimekb3987012013-05-29 14:47:47 +00001518 Whitespaces.replaceWhitespace(*TheLine.First, NewLines, /*Indent*/ 0,
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001519 /*TargetColumn*/ 0);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001520 }
1521 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001522 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001523 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001524 if (FirstTok->WhitespaceRange.isValid() &&
Manuel Klimek67d080d2013-04-12 14:13:36 +00001525 // Insert a break even if there is a structural error in case where
1526 // we break apart a line consisting of multiple unwrapped lines.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001527 (FirstTok->NewlinesBefore == 0 || !StructuralError)) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001528 formatFirstToken(*TheLine.First, PreviousLineLastToken, Indent,
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001529 TheLine.InPPDirective);
Manuel Klimek67d080d2013-04-12 14:13:36 +00001530 } else {
1531 Indent = LevelIndent =
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001532 SourceMgr.getSpellingColumnNumber(FirstTok->Tok.getLocation()) -
1533 1;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001534 }
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001535 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001536 TheLine.First, Whitespaces, Encoding,
1537 BinPackInconclusiveFunctions);
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001538 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001539 IndentForLevel[TheLine.Level] = LevelIndent;
1540 PreviousLineWasTouched = true;
1541 } else {
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001542 // Format the first token if necessary, and notify the WhitespaceManager
1543 // about the unchanged whitespace.
Manuel Klimekb3987012013-05-29 14:47:47 +00001544 for (const FormatToken *Tok = TheLine.First; Tok != NULL;
1545 Tok = Tok->Next) {
1546 if (Tok == TheLine.First &&
1547 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
1548 unsigned LevelIndent =
1549 SourceMgr.getSpellingColumnNumber(Tok->Tok.getLocation()) - 1;
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001550 // Remove trailing whitespace of the previous line if it was
1551 // touched.
1552 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
1553 formatFirstToken(*Tok, PreviousLineLastToken, LevelIndent,
1554 TheLine.InPPDirective);
1555 } else {
Manuel Klimekb3987012013-05-29 14:47:47 +00001556 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001557 }
Daniel Jasper1fb8d882013-05-14 09:30:02 +00001558
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001559 if (static_cast<int>(LevelIndent) - Offset >= 0)
1560 LevelIndent -= Offset;
1561 if (Tok->isNot(tok::comment))
1562 IndentForLevel[TheLine.Level] = LevelIndent;
1563 } else {
Manuel Klimekb3987012013-05-29 14:47:47 +00001564 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001565 }
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001566 }
1567 // If we did not reformat this unwrapped line, the column at the end of
1568 // the last token is unchanged - thus, we can calculate the end of the
1569 // last token.
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001570 PreviousLineWasTouched = false;
1571 }
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001572 PreviousLineLastToken = I->Last;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001573 }
1574 return Whitespaces.generateReplacements();
1575 }
1576
1577private:
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001578 void deriveLocalStyle() {
1579 unsigned CountBoundToVariable = 0;
1580 unsigned CountBoundToType = 0;
1581 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001582 bool HasBinPackedFunction = false;
1583 bool HasOnePerLineFunction = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001584 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001585 if (!AnnotatedLines[i].First->Next)
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001586 continue;
Manuel Klimekb3987012013-05-29 14:47:47 +00001587 FormatToken *Tok = AnnotatedLines[i].First->Next;
1588 while (Tok->Next) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001589 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001590 bool SpacesBefore =
1591 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1592 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1593 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001594 if (SpacesBefore && !SpacesAfter)
1595 ++CountBoundToVariable;
1596 else if (!SpacesBefore && SpacesAfter)
1597 ++CountBoundToType;
1598 }
1599
Daniel Jasper29f123b2013-02-08 15:28:42 +00001600 if (Tok->Type == TT_TemplateCloser &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001601 Tok->Previous->Type == TT_TemplateCloser &&
1602 Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd())
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001603 HasCpp03IncompatibleFormat = true;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001604
1605 if (Tok->PackingKind == PPK_BinPacked)
1606 HasBinPackedFunction = true;
1607 if (Tok->PackingKind == PPK_OnePerLine)
1608 HasOnePerLineFunction = true;
1609
Manuel Klimekb3987012013-05-29 14:47:47 +00001610 Tok = Tok->Next;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001611 }
1612 }
1613 if (Style.DerivePointerBinding) {
1614 if (CountBoundToType > CountBoundToVariable)
1615 Style.PointerBindsToType = true;
1616 else if (CountBoundToType < CountBoundToVariable)
1617 Style.PointerBindsToType = false;
1618 }
1619 if (Style.Standard == FormatStyle::LS_Auto) {
1620 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1621 : FormatStyle::LS_Cpp03;
1622 }
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001623 BinPackInconclusiveFunctions =
1624 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001625 }
1626
Manuel Klimek547d5db2013-02-08 17:38:27 +00001627 /// \brief Get the indent of \p Level from \p IndentForLevel.
1628 ///
1629 /// \p IndentForLevel must contain the indent for the level \c l
1630 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1631 /// that level is unknown.
Daniel Jasperfc759082013-02-14 14:26:07 +00001632 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimek547d5db2013-02-08 17:38:27 +00001633 if (IndentForLevel[Level] != -1)
1634 return IndentForLevel[Level];
Manuel Klimek52635ff2013-02-08 19:53:32 +00001635 if (Level == 0)
1636 return 0;
Manuel Klimek07a64ec2013-05-13 08:42:42 +00001637 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimek547d5db2013-02-08 17:38:27 +00001638 }
1639
1640 /// \brief Get the offset of the line relatively to the level.
1641 ///
1642 /// For example, 'public:' labels in classes are offset by 1 or 2
1643 /// characters to the left from their level.
Manuel Klimekb3987012013-05-29 14:47:47 +00001644 int getIndentOffset(const FormatToken &RootToken) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001645 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimek547d5db2013-02-08 17:38:27 +00001646 return Style.AccessModifierOffset;
1647 return 0;
1648 }
1649
Manuel Klimek517e8942013-01-11 17:54:10 +00001650 /// \brief Tries to merge lines into one.
1651 ///
1652 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1653 /// if possible; note that \c I will be incremented when lines are merged.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001654 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +00001655 std::vector<AnnotatedLine>::iterator &I,
1656 std::vector<AnnotatedLine>::iterator E) {
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001657 // We can never merge stuff if there are trailing line comments.
1658 if (I->Last->Type == TT_LineComment)
1659 return;
1660
Daniel Jaspere05dc6d2013-07-24 13:10:59 +00001661 if (Indent > Style.ColumnLimit)
1662 return;
1663
Daniel Jaspera4d46212013-02-28 11:05:57 +00001664 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001665 // If we already exceed the column limit, we set 'Limit' to 0. The different
1666 // tryMerge..() functions can then decide whether to still do merging.
1667 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001668
Daniel Jasper9c8c40e2013-01-21 14:18:28 +00001669 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001670 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001671
Daniel Jasper5be59ba2013-05-15 14:09:55 +00001672 if (I->Last->is(tok::l_brace)) {
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001673 tryMergeSimpleBlock(I, E, Limit);
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001674 } else if (Style.AllowShortIfStatementsOnASingleLine &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001675 I->First->is(tok::kw_if)) {
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001676 tryMergeSimpleControlStatement(I, E, Limit);
1677 } else if (Style.AllowShortLoopsOnASingleLine &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001678 I->First->isOneOf(tok::kw_for, tok::kw_while)) {
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001679 tryMergeSimpleControlStatement(I, E, Limit);
Manuel Klimekb3987012013-05-29 14:47:47 +00001680 } else if (I->InPPDirective &&
1681 (I->First->HasUnescapedNewline || I->First->IsFirst)) {
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001682 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001683 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001684 }
1685
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001686 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1687 std::vector<AnnotatedLine>::iterator E,
1688 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001689 if (Limit == 0)
1690 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001691 AnnotatedLine &Line = *I;
Manuel Klimekb3987012013-05-29 14:47:47 +00001692 if (!(I + 1)->InPPDirective || (I + 1)->First->HasUnescapedNewline)
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001693 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001694 if (I + 2 != E && (I + 2)->InPPDirective &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001695 !(I + 2)->First->HasUnescapedNewline)
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001696 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001697 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001698 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001699 join(Line, *(++I));
1700 }
1701
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001702 void tryMergeSimpleControlStatement(std::vector<AnnotatedLine>::iterator &I,
1703 std::vector<AnnotatedLine>::iterator E,
1704 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001705 if (Limit == 0)
1706 return;
Manuel Klimek4c128122013-01-18 14:46:43 +00001707 if ((I + 1)->InPPDirective != I->InPPDirective ||
Manuel Klimekb3987012013-05-29 14:47:47 +00001708 ((I + 1)->InPPDirective && (I + 1)->First->HasUnescapedNewline))
Manuel Klimek4c128122013-01-18 14:46:43 +00001709 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001710 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001711 if (Line.Last->isNot(tok::r_paren))
1712 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001713 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001714 return;
Manuel Klimekb3987012013-05-29 14:47:47 +00001715 if ((I + 1)->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
1716 tok::kw_while) ||
1717 (I + 1)->First->Type == TT_LineComment)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001718 return;
1719 // Only inline simple if's (no nested if or else).
Manuel Klimekb3987012013-05-29 14:47:47 +00001720 if (I + 2 != E && Line.First->is(tok::kw_if) &&
1721 (I + 2)->First->is(tok::kw_else))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001722 return;
1723 join(Line, *(++I));
1724 }
1725
1726 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001727 std::vector<AnnotatedLine>::iterator E,
1728 unsigned Limit) {
Daniel Jasper5be59ba2013-05-15 14:09:55 +00001729 // No merging if the brace already is on the next line.
1730 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
1731 return;
1732
Manuel Klimek517e8942013-01-11 17:54:10 +00001733 // First, check that the current line allows merging. This is the case if
1734 // we're not in a control flow statement and the last token is an opening
1735 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001736 AnnotatedLine &Line = *I;
Manuel Klimekb3987012013-05-29 14:47:47 +00001737 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1738 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001739 tok::kw_for,
Manuel Klimekb3987012013-05-29 14:47:47 +00001740 // This gets rid of all ObjC @ keywords and methods.
1741 tok::at, tok::minus, tok::plus))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001742 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001743
Manuel Klimekb3987012013-05-29 14:47:47 +00001744 FormatToken *Tok = (I + 1)->First;
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001745 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001746 (Tok->getNextNonComment() == NULL ||
1747 Tok->getNextNonComment()->is(tok::semi))) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001748 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jasper729a7432013-02-11 12:36:37 +00001749 Tok->SpacesRequiredBefore = 0;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001750 Tok->CanBreakBefore = true;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001751 join(Line, *(I + 1));
1752 I += 1;
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001753 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001754 // Check that we still have three lines and they fit into the limit.
1755 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1756 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001757 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001758
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001759 // Second, check that the next line does not contain any braces - if it
1760 // does, readability declines when putting it into a single line.
1761 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1762 return;
1763 do {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001764 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001765 return;
Manuel Klimekb3987012013-05-29 14:47:47 +00001766 Tok = Tok->Next;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001767 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001768
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001769 // Last, check that the third line contains a single closing brace.
Manuel Klimekb3987012013-05-29 14:47:47 +00001770 Tok = (I + 2)->First;
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001771 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001772 Tok->MustBreakBefore)
1773 return;
1774
1775 join(Line, *(I + 1));
1776 join(Line, *(I + 2));
1777 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +00001778 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001779 }
1780
1781 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1782 unsigned Limit) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001783 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1784 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001785 }
1786
Daniel Jasper995e8202013-01-14 13:08:07 +00001787 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001788 assert(!A.Last->Next);
1789 assert(!B.First->Previous);
1790 A.Last->Next = B.First;
1791 B.First->Previous = A.Last;
1792 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1793 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1794 Tok->TotalLength += LengthA;
1795 A.Last = Tok;
Daniel Jasper995e8202013-01-14 13:08:07 +00001796 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001797 }
1798
Daniel Jasper6f21a982013-03-13 07:49:51 +00001799 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf3023542013-03-07 20:50:00 +00001800 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1801 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1802 Ranges[i].getBegin()) &&
1803 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1804 Range.getBegin()))
1805 return true;
1806 }
1807 return false;
1808 }
1809
1810 bool touchesLine(const AnnotatedLine &TheLine) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001811 const FormatToken *First = TheLine.First;
1812 const FormatToken *Last = TheLine.Last;
Daniel Jasper84f5ddf2013-05-14 10:31:09 +00001813 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001814 First->WhitespaceRange.getBegin().getLocWithOffset(
1815 First->LastNewlineOffset),
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001816 Last->Tok.getLocation().getLocWithOffset(Last->TokenText.size() - 1));
Daniel Jasperf3023542013-03-07 20:50:00 +00001817 return touchesRanges(LineRange);
1818 }
1819
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001820 bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I,
1821 std::vector<AnnotatedLine>::iterator E) {
1822 for (; I != E; ++I) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001823 if (I->First->HasUnescapedNewline)
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001824 return false;
1825 if (touchesLine(*I))
1826 return true;
1827 }
1828 return false;
1829 }
1830
Daniel Jasperf3023542013-03-07 20:50:00 +00001831 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001832 const FormatToken *First = TheLine.First;
Daniel Jasperf3023542013-03-07 20:50:00 +00001833 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001834 First->WhitespaceRange.getBegin(),
1835 First->WhitespaceRange.getBegin().getLocWithOffset(
1836 First->LastNewlineOffset));
Daniel Jasperf3023542013-03-07 20:50:00 +00001837 return touchesRanges(LineRange);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001838 }
1839
1840 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +00001841 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001842 }
1843
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001844 /// \brief Add a new line and the required indent before the first Token
1845 /// of the \c UnwrappedLine if there was no structural parsing error.
1846 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimekb3987012013-05-29 14:47:47 +00001847 void formatFirstToken(const FormatToken &RootToken,
1848 const FormatToken *PreviousToken, unsigned Indent,
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001849 bool InPPDirective) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001850 unsigned Newlines =
Manuel Klimekb3987012013-05-29 14:47:47 +00001851 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Daniel Jasper15f33f02013-06-03 16:16:41 +00001852 // Remove empty lines before "}" where applicable.
1853 if (RootToken.is(tok::r_brace) &&
1854 (!RootToken.Next ||
1855 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1856 Newlines = std::min(Newlines, 1u);
Manuel Klimekb3987012013-05-29 14:47:47 +00001857 if (Newlines == 0 && !RootToken.IsFirst)
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001858 Newlines = 1;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001859
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001860 // Insert extra new line before access specifiers.
1861 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001862 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001863 ++Newlines;
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001864
Manuel Klimekb3987012013-05-29 14:47:47 +00001865 Whitespaces.replaceWhitespace(
1866 RootToken, Newlines, Indent, Indent,
1867 InPPDirective && !RootToken.HasUnescapedNewline);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001868 }
1869
Daniel Jasperbac016b2012-12-03 18:12:45 +00001870 FormatStyle Style;
1871 Lexer &Lex;
1872 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001873 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001874 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001875 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko00895102013-06-05 14:09:10 +00001876
1877 encoding::Encoding Encoding;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001878 bool BinPackInconclusiveFunctions;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001879};
1880
Craig Topper83f81d72013-06-30 22:29:28 +00001881} // end anonymous namespace
1882
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001883tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1884 SourceManager &SourceMgr,
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001885 std::vector<CharSourceRange> Ranges) {
1886 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001887 return formatter.format();
1888}
1889
Daniel Jasper8a999452013-05-16 10:40:07 +00001890tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1891 std::vector<tooling::Range> Ranges,
1892 StringRef FileName) {
1893 FileManager Files((FileSystemOptions()));
1894 DiagnosticsEngine Diagnostics(
1895 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1896 new DiagnosticOptions);
1897 SourceManager SourceMgr(Diagnostics, Files);
1898 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1899 const clang::FileEntry *Entry =
1900 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1901 SourceMgr.overrideFileContents(Entry, Buf);
1902 FileID ID =
1903 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001904 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1905 getFormattingLangOpts(Style.Standard));
Daniel Jasper8a999452013-05-16 10:40:07 +00001906 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1907 std::vector<CharSourceRange> CharRanges;
1908 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1909 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1910 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1911 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1912 }
1913 return reformat(Style, Lex, SourceMgr, CharRanges);
1914}
1915
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001916LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasper46ef8522013-01-10 13:08:12 +00001917 LangOptions LangOpts;
1918 LangOpts.CPlusPlus = 1;
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001919 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasperb64eca02013-03-22 10:01:29 +00001920 LangOpts.LineComment = 1;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001921 LangOpts.Bool = 1;
1922 LangOpts.ObjC1 = 1;
1923 LangOpts.ObjC2 = 1;
1924 return LangOpts;
1925}
1926
Daniel Jaspercd162382013-01-07 13:26:07 +00001927} // namespace format
1928} // namespace clang