blob: 3a0802a4609f8ed4d80591cf4ea5629179b7895a [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
Daniel Jasper6b2afe42013-08-16 11:20:30 +000018#include "ContinuationIndenter.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"
Chandler Carruthb99083e2013-01-02 10:28:36 +000023#include "clang/Basic/SourceManager.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000024#include "clang/Format/Format.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Alexander Kornienko5262dd92013-03-27 11:52:18 +000026#include "llvm/ADT/STLExtras.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000027#include "llvm/Support/Allocator.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Alexander Kornienkod71ec162013-05-07 15:32:14 +000029#include "llvm/Support/YAMLTraits.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000030#include <queue>
Daniel Jasper8822d3a2012-12-04 13:02:32 +000031#include <string>
32
Alexander Kornienkod71ec162013-05-07 15:32:14 +000033namespace llvm {
34namespace yaml {
35template <>
36struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> {
Manuel Klimek44135b82013-05-13 12:51:40 +000037 static void enumeration(IO &IO,
38 clang::format::FormatStyle::LanguageStandard &Value) {
Alexander Kornienko9321e872013-09-04 14:09:13 +000039 IO.enumCase(Value, "Cpp03", clang::format::FormatStyle::LS_Cpp03);
Manuel Klimek44135b82013-05-13 12:51:40 +000040 IO.enumCase(Value, "C++03", clang::format::FormatStyle::LS_Cpp03);
Alexander Kornienko9321e872013-09-04 14:09:13 +000041 IO.enumCase(Value, "Cpp11", clang::format::FormatStyle::LS_Cpp11);
Manuel Klimek44135b82013-05-13 12:51:40 +000042 IO.enumCase(Value, "C++11", clang::format::FormatStyle::LS_Cpp11);
43 IO.enumCase(Value, "Auto", clang::format::FormatStyle::LS_Auto);
44 }
45};
46
Daniel Jasper1fb8d882013-05-14 09:30:02 +000047template <>
Manuel Klimek44135b82013-05-13 12:51:40 +000048struct ScalarEnumerationTraits<clang::format::FormatStyle::BraceBreakingStyle> {
49 static void
50 enumeration(IO &IO, clang::format::FormatStyle::BraceBreakingStyle &Value) {
51 IO.enumCase(Value, "Attach", clang::format::FormatStyle::BS_Attach);
52 IO.enumCase(Value, "Linux", clang::format::FormatStyle::BS_Linux);
53 IO.enumCase(Value, "Stroustrup", clang::format::FormatStyle::BS_Stroustrup);
Manuel Klimeke4907052013-08-02 21:31:59 +000054 IO.enumCase(Value, "Allman", clang::format::FormatStyle::BS_Allman);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000055 }
56};
57
Daniel Jaspereff18b92013-07-31 23:16:02 +000058template <>
59struct ScalarEnumerationTraits<
60 clang::format::FormatStyle::NamespaceIndentationKind> {
61 static void
62 enumeration(IO &IO,
63 clang::format::FormatStyle::NamespaceIndentationKind &Value) {
64 IO.enumCase(Value, "None", clang::format::FormatStyle::NI_None);
65 IO.enumCase(Value, "Inner", clang::format::FormatStyle::NI_Inner);
66 IO.enumCase(Value, "All", clang::format::FormatStyle::NI_All);
67 }
68};
69
Alexander Kornienkod71ec162013-05-07 15:32:14 +000070template <> struct MappingTraits<clang::format::FormatStyle> {
71 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
Alexander Kornienkodd256312013-05-10 11:56:10 +000072 if (IO.outputting()) {
Alexander Kornienko4e65c982013-09-02 16:39:23 +000073 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
74 "Mozilla", "WebKit" };
Alexander Kornienkodd256312013-05-10 11:56:10 +000075 ArrayRef<StringRef> Styles(StylesArray);
76 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
77 StringRef StyleName(Styles[i]);
Alexander Kornienko885f87b2013-05-19 00:53:30 +000078 clang::format::FormatStyle PredefinedStyle;
79 if (clang::format::getPredefinedStyle(StyleName, &PredefinedStyle) &&
80 Style == PredefinedStyle) {
Alexander Kornienkodd256312013-05-10 11:56:10 +000081 IO.mapOptional("# BasedOnStyle", StyleName);
82 break;
83 }
84 }
85 } else {
Alexander Kornienkod71ec162013-05-07 15:32:14 +000086 StringRef BasedOnStyle;
87 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000088 if (!BasedOnStyle.empty())
Alexander Kornienko885f87b2013-05-19 00:53:30 +000089 if (!clang::format::getPredefinedStyle(BasedOnStyle, &Style)) {
90 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
91 return;
92 }
Alexander Kornienkod71ec162013-05-07 15:32:14 +000093 }
94
95 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jasper6315fec2013-08-13 10:58:30 +000096 IO.mapOptional("ConstructorInitializerIndentWidth",
97 Style.ConstructorInitializerIndentWidth);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000098 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper893ea8d2013-07-31 23:55:15 +000099 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000100 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
101 Style.AllowAllParametersOfDeclarationOnNextLine);
102 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
103 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000104 IO.mapOptional("AllowShortLoopsOnASingleLine",
105 Style.AllowShortLoopsOnASingleLine);
Daniel Jasperbbc87762013-05-29 12:07:31 +0000106 IO.mapOptional("AlwaysBreakTemplateDeclarations",
107 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko56312022013-07-04 12:02:44 +0000108 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
109 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000110 IO.mapOptional("BreakBeforeBinaryOperators",
111 Style.BreakBeforeBinaryOperators);
112 IO.mapOptional("BreakConstructorInitializersBeforeComma",
113 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000114 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
115 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
116 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
117 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
118 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000119 IO.mapOptional("ExperimentalAutoDetectBinPacking",
120 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000121 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
122 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspereff18b92013-07-31 23:16:02 +0000123 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000124 IO.mapOptional("ObjCSpaceBeforeProtocolList",
125 Style.ObjCSpaceBeforeProtocolList);
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000126 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
127 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000128 IO.mapOptional("PenaltyBreakFirstLessLess",
129 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000130 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
131 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
132 Style.PenaltyReturnTypeOnItsOwnLine);
133 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
134 IO.mapOptional("SpacesBeforeTrailingComments",
135 Style.SpacesBeforeTrailingComments);
Daniel Jasperb5dc3f42013-07-16 18:22:10 +0000136 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000137 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000138 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000139 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000140 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimek44135b82013-05-13 12:51:40 +0000141 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimeka9a7f102013-06-21 17:25:42 +0000142 IO.mapOptional("IndentFunctionDeclarationAfterType",
143 Style.IndentFunctionDeclarationAfterType);
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000144 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasper34f3d052013-08-21 08:39:01 +0000145 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000146 IO.mapOptional("SpacesInCStyleCastParentheses",
147 Style.SpacesInCStyleCastParentheses);
148 IO.mapOptional("SpaceAfterControlStatementKeyword",
149 Style.SpaceAfterControlStatementKeyword);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000150 }
151};
152}
153}
154
Daniel Jasperbac016b2012-12-03 18:12:45 +0000155namespace clang {
156namespace format {
157
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000158void setDefaultPenalties(FormatStyle &Style) {
Daniel Jasperf5461782013-08-28 10:03:58 +0000159 Style.PenaltyBreakComment = 60;
Daniel Jasper9637dda2013-07-15 14:33:14 +0000160 Style.PenaltyBreakFirstLessLess = 120;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000161 Style.PenaltyBreakString = 1000;
162 Style.PenaltyExcessCharacter = 1000000;
163}
164
Daniel Jasperbac016b2012-12-03 18:12:45 +0000165FormatStyle getLLVMStyle() {
166 FormatStyle LLVMStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000167 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000168 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000169 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000170 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000171 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000172 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienko56312022013-07-04 12:02:44 +0000173 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000174 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000175 LLVMStyle.BinPackParameters = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000176 LLVMStyle.BreakBeforeBinaryOperators = false;
177 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
178 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000179 LLVMStyle.ColumnLimit = 80;
180 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6315fec2013-08-13 10:58:30 +0000181 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000182 LLVMStyle.Cpp11BracedListStyle = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000183 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000184 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000185 LLVMStyle.IndentCaseLabels = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000186 LLVMStyle.IndentFunctionDeclarationAfterType = false;
187 LLVMStyle.IndentWidth = 2;
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000188 LLVMStyle.TabWidth = 8;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000189 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000190 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Weber5f500df2013-01-10 20:12:55 +0000191 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000192 LLVMStyle.PointerBindsToType = false;
193 LLVMStyle.SpacesBeforeTrailingComments = 1;
194 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000195 LLVMStyle.UseTab = false;
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000196 LLVMStyle.SpacesInParentheses = false;
197 LLVMStyle.SpaceInEmptyParentheses = false;
198 LLVMStyle.SpacesInCStyleCastParentheses = false;
199 LLVMStyle.SpaceAfterControlStatementKeyword = true;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000200
201 setDefaultPenalties(LLVMStyle);
202 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
203
Daniel Jasperbac016b2012-12-03 18:12:45 +0000204 return LLVMStyle;
205}
206
207FormatStyle getGoogleStyle() {
208 FormatStyle GoogleStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000209 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000210 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000211 GoogleStyle.AlignTrailingComments = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000212 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000213 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper1bee0732013-05-23 18:05:18 +0000214 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko56312022013-07-04 12:02:44 +0000215 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000216 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000217 GoogleStyle.BinPackParameters = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000218 GoogleStyle.BreakBeforeBinaryOperators = false;
219 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
220 GoogleStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000221 GoogleStyle.ColumnLimit = 80;
222 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper6315fec2013-08-13 10:58:30 +0000223 GoogleStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000224 GoogleStyle.Cpp11BracedListStyle = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000225 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000226 GoogleStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000227 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000228 GoogleStyle.IndentFunctionDeclarationAfterType = true;
229 GoogleStyle.IndentWidth = 2;
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000230 GoogleStyle.TabWidth = 8;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000231 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000232 GoogleStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Weber5f500df2013-01-10 20:12:55 +0000233 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000234 GoogleStyle.PointerBindsToType = true;
235 GoogleStyle.SpacesBeforeTrailingComments = 2;
236 GoogleStyle.Standard = FormatStyle::LS_Auto;
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000237 GoogleStyle.UseTab = false;
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000238 GoogleStyle.SpacesInParentheses = false;
239 GoogleStyle.SpaceInEmptyParentheses = false;
240 GoogleStyle.SpacesInCStyleCastParentheses = false;
241 GoogleStyle.SpaceAfterControlStatementKeyword = true;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000242
243 setDefaultPenalties(GoogleStyle);
244 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
245
Daniel Jasperbac016b2012-12-03 18:12:45 +0000246 return GoogleStyle;
247}
248
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000249FormatStyle getChromiumStyle() {
250 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +0000251 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000252 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000253 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000254 ChromiumStyle.BinPackParameters = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000255 ChromiumStyle.DerivePointerBinding = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000256 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000257 return ChromiumStyle;
258}
259
Alexander Kornienkofb594862013-05-06 14:11:27 +0000260FormatStyle getMozillaStyle() {
261 FormatStyle MozillaStyle = getLLVMStyle();
262 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
263 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
264 MozillaStyle.DerivePointerBinding = true;
265 MozillaStyle.IndentCaseLabels = true;
266 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
267 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
268 MozillaStyle.PointerBindsToType = true;
269 return MozillaStyle;
270}
271
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000272FormatStyle getWebKitStyle() {
273 FormatStyle Style = getLLVMStyle();
Daniel Jaspereff18b92013-07-31 23:16:02 +0000274 Style.AccessModifierOffset = -4;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000275 Style.AlignTrailingComments = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000276 Style.BreakBeforeBinaryOperators = true;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000277 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000278 Style.BreakConstructorInitializersBeforeComma = true;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000279 Style.ColumnLimit = 0;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000280 Style.IndentWidth = 4;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000281 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000282 Style.PointerBindsToType = true;
283 return Style;
284}
285
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000286bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000287 if (Name.equals_lower("llvm"))
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000288 *Style = getLLVMStyle();
289 else if (Name.equals_lower("chromium"))
290 *Style = getChromiumStyle();
291 else if (Name.equals_lower("mozilla"))
292 *Style = getMozillaStyle();
293 else if (Name.equals_lower("google"))
294 *Style = getGoogleStyle();
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000295 else if (Name.equals_lower("webkit"))
296 *Style = getWebKitStyle();
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000297 else
298 return false;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000299
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000300 return true;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000301}
302
303llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienko107db3c2013-05-20 15:18:01 +0000304 if (Text.trim().empty())
305 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000306 llvm::yaml::Input Input(Text);
307 Input >> *Style;
308 return Input.error();
309}
310
311std::string configurationAsText(const FormatStyle &Style) {
312 std::string Text;
313 llvm::raw_string_ostream Stream(Text);
314 llvm::yaml::Output Output(Stream);
315 // We use the same mapping method for input and output, so we need a non-const
316 // reference here.
317 FormatStyle NonConstStyle = Style;
318 Output << NonConstStyle;
Alexander Kornienko2b6acb62013-05-13 12:56:35 +0000319 return Stream.str();
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000320}
321
Craig Topper83f81d72013-06-30 22:29:28 +0000322namespace {
323
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000324class NoColumnLimitFormatter {
325public:
Daniel Jasper34f3d052013-08-21 08:39:01 +0000326 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000327
328 /// \brief Formats the line starting at \p State, simply keeping all of the
329 /// input's line breaking decisions.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000330 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasperb77d7412013-09-06 07:54:20 +0000331 LineState State =
332 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000333 while (State.NextToken != NULL) {
334 bool Newline =
335 Indenter->mustBreak(State) ||
336 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
337 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
338 }
339 }
Daniel Jasper34f3d052013-08-21 08:39:01 +0000340
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000341private:
342 ContinuationIndenter *Indenter;
343};
344
Daniel Jasperbac016b2012-12-03 18:12:45 +0000345class UnwrappedLineFormatter {
346public:
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000347 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper567dcf92013-09-05 09:29:45 +0000348 WhitespaceManager *Whitespaces,
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000349 const FormatStyle &Style, const AnnotatedLine &Line)
Daniel Jasper567dcf92013-09-05 09:29:45 +0000350 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style), Line(Line),
351 Count(0) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000352
Daniel Jasper567dcf92013-09-05 09:29:45 +0000353 /// \brief Formats an \c UnwrappedLine and returns the penalty.
354 ///
355 /// If \p DryRun is \c false, directly applies the changes.
356 unsigned format(unsigned FirstIndent, bool DryRun = false) {
Daniel Jasperb77d7412013-09-06 07:54:20 +0000357 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000358
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000359 // If the ObjC method declaration does not fit on a line, we should format
360 // it with one arg per line.
361 if (Line.Type == LT_ObjCMethodDecl)
362 State.Stack.back().BreakBeforeParameter = true;
363
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000364 // Find best solution in solution space.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000365 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000366 }
367
368private:
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000369 /// \brief An edge in the solution space from \c Previous->State to \c State,
370 /// inserting a newline dependent on the \c NewLine.
371 struct StateNode {
372 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +0000373 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000374 LineState State;
375 bool NewLine;
376 StateNode *Previous;
377 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000378
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000379 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
380 ///
381 /// In case of equal penalties, we want to prefer states that were inserted
382 /// first. During state generation we make sure that we insert states first
383 /// that break the line as late as possible.
384 typedef std::pair<unsigned, unsigned> OrderedPenalty;
385
386 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
387 /// \c State has the given \c OrderedPenalty.
388 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
389
390 /// \brief The BFS queue type.
391 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
392 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000393
394 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000395 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000396 /// This implements a variant of Dijkstra's algorithm on the graph that spans
397 /// the solution space (\c LineStates are the nodes). The algorithm tries to
398 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper567dcf92013-09-05 09:29:45 +0000399 /// to a state where all tokens are placed. Returns the penalty.
400 ///
401 /// If \p DryRun is \c false, directly applies the changes.
402 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000403 std::set<LineState> Seen;
404
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000405 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +0000406 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000407 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
408 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
409 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000410
Daniel Jasper567dcf92013-09-05 09:29:45 +0000411 unsigned Penalty = 0;
412
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000413 // While not empty, take first element and follow edges.
414 while (!Queue.empty()) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000415 Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +0000416 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000417 if (Node->State.NextToken == NULL) {
Alexander Kornienkodd256312013-05-10 11:56:10 +0000418 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000419 break;
Daniel Jasper01786732013-02-04 07:21:18 +0000420 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000421 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000422
Daniel Jasper54b4e442013-05-22 05:27:42 +0000423 // Cut off the analysis of certain solutions if the analysis gets too
424 // complex. See description of IgnoreStackForComparison.
425 if (Count > 10000)
426 Node->State.IgnoreStackForComparison = true;
427
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000428 if (!Seen.insert(Node->State).second)
429 // State already examined with lower penalty.
430 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000431
Nico Weber27268772013-06-26 00:30:14 +0000432 addNextStateToQueue(Penalty, Node, /*NewLine=*/false);
433 addNextStateToQueue(Penalty, Node, /*NewLine=*/true);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000434 }
435
436 if (Queue.empty())
437 // We were unable to find a solution, do nothing.
438 // FIXME: Add diagnostic?
Daniel Jasper567dcf92013-09-05 09:29:45 +0000439 return 0;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000440
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000441 // Reconstruct the solution.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000442 if (!DryRun)
443 reconstructPath(InitialState, Queue.top().second);
444
Alexander Kornienkodd256312013-05-10 11:56:10 +0000445 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
446 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper567dcf92013-09-05 09:29:45 +0000447
448 return Penalty;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000449 }
450
451 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek9c333b92013-05-29 15:10:11 +0000452 std::deque<StateNode *> Path;
453 // We do not need a break before the initial token.
454 while (Current->Previous) {
455 Path.push_front(Current);
456 Current = Current->Previous;
457 }
458 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
459 I != E; ++I) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000460 unsigned Penalty = 0;
461 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
462 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
463
Manuel Klimek9c333b92013-05-29 15:10:11 +0000464 DEBUG({
465 if ((*I)->NewLine) {
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000466 llvm::dbgs() << "Penalty for placing "
Manuel Klimek9c333b92013-05-29 15:10:11 +0000467 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000468 << Penalty << "\n";
Manuel Klimek9c333b92013-05-29 15:10:11 +0000469 }
470 });
Manuel Klimek9c333b92013-05-29 15:10:11 +0000471 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000472 }
473
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000474 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000475 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000476 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000477 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000478 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
479 bool NewLine) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000480 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000481 return;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000482 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000483 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000484
485 StateNode *Node = new (Allocator.Allocate())
486 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000487 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
488 return;
489
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000490 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000491
492 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
493 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000494 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000495
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000496 /// \brief If the \p State's next token is an r_brace closing a nested block,
497 /// format the nested block before it.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000498 ///
499 /// Returns \c true if all children could be placed successfully and adapts
500 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
501 /// creates changes using \c Whitespaces.
502 ///
503 /// The crucial idea here is that children always get formatted upon
504 /// encountering the closing brace right after the nested block. Now, if we
505 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
506 /// \c false), the entire block has to be kept on the same line (which is only
507 /// possible if it fits on the line, only contains a single statement, etc.
508 ///
509 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
510 /// break after the "{", format all lines with correct indentation and the put
511 /// the closing "}" on yet another new line.
512 ///
513 /// This enables us to keep the simple structure of the
514 /// \c UnwrappedLineFormatter, where we only have two options for each token:
515 /// break or don't break.
516 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
517 unsigned &Penalty) {
518 const FormatToken &LBrace = *State.NextToken->Previous;
519 if (LBrace.isNot(tok::l_brace) || LBrace.BlockKind != BK_Block ||
520 LBrace.Children.size() == 0)
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000521 // The previous token does not open a block. Nothing to do. We don't
522 // assert so that we can simply call this function for all tokens.
Daniel Jasper2f0a0202013-09-06 08:54:24 +0000523 return true;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000524
525 if (NewLine) {
526 unsigned ParentIndent = State.Stack.back().Indent;
527 for (SmallVector<AnnotatedLine *, 1>::const_iterator
528 I = LBrace.Children.begin(),
529 E = LBrace.Children.end();
530 I != E; ++I) {
531 unsigned Indent =
532 ParentIndent + ((*I)->Level - Line.Level) * Style.IndentWidth;
Daniel Jasper14e25c02013-09-08 14:07:57 +0000533 if (!DryRun) {
534 unsigned Newlines = std::min((*I)->First->NewlinesBefore,
535 Style.MaxEmptyLinesToKeep + 1);
536 Newlines = std::max(1u, Newlines);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000537 Whitespaces->replaceWhitespace(
Daniel Jasper14e25c02013-09-08 14:07:57 +0000538 *(*I)->First, Newlines, /*Spaces=*/Indent,
Daniel Jasper567dcf92013-09-05 09:29:45 +0000539 /*StartOfTokenColumn=*/Indent, Line.InPPDirective);
Daniel Jasper14e25c02013-09-08 14:07:57 +0000540 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000541 UnwrappedLineFormatter Formatter(Indenter, Whitespaces, Style, **I);
542 Penalty += Formatter.format(Indent, DryRun);
543 }
544 return true;
545 }
546
547 if (LBrace.Children.size() > 1)
548 return false; // Cannot merge multiple statements into a single line.
549
550 // We can't put the closing "}" on a line with a trailing comment.
551 if (LBrace.Children[0]->Last->isTrailingComment())
552 return false;
553
554 if (!DryRun) {
555 Whitespaces->replaceWhitespace(*LBrace.Children[0]->First,
556 /*Newlines=*/0, /*Spaces=*/1,
557 /*StartOfTokenColumn=*/State.Column,
558 State.Line->InPPDirective);
Daniel Jasper14e25c02013-09-08 14:07:57 +0000559 UnwrappedLineFormatter Formatter(Indenter, Whitespaces, Style,
560 *LBrace.Children[0]);
561 Penalty += Formatter.format(State.Column + 1, DryRun);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000562 }
563
564 State.Column += 1 + LBrace.Children[0]->Last->TotalLength;
565 return true;
566 }
567
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000568 ContinuationIndenter *Indenter;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000569 WhitespaceManager *Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000570 FormatStyle Style;
Daniel Jasper995e8202013-01-14 13:08:07 +0000571 const AnnotatedLine &Line;
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000572
573 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
574 QueueType Queue;
575 // Increasing count of \c StateNode items we have created. This is used
576 // to create a deterministic order independent of the container.
577 unsigned Count;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000578};
579
Manuel Klimek96e888b2013-05-28 11:55:06 +0000580class FormatTokenLexer {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000581public:
Manuel Klimekc41e8192013-08-29 15:21:40 +0000582 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienko00895102013-06-05 14:09:10 +0000583 encoding::Encoding Encoding)
Manuel Klimekc41e8192013-08-29 15:21:40 +0000584 : FormatTok(NULL), GreaterStashed(false), Column(0),
585 TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr), Style(Style),
586 IdentTable(getFormattingLangOpts()), Encoding(Encoding) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000587 Lex.SetKeepWhitespaceMode(true);
588 }
589
Manuel Klimek96e888b2013-05-28 11:55:06 +0000590 ArrayRef<FormatToken *> lex() {
591 assert(Tokens.empty());
592 do {
593 Tokens.push_back(getNextToken());
594 } while (Tokens.back()->Tok.isNot(tok::eof));
595 return Tokens;
596 }
597
598 IdentifierTable &getIdentTable() { return IdentTable; }
599
600private:
601 FormatToken *getNextToken() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000602 if (GreaterStashed) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000603 // Create a synthesized second '>' token.
Manuel Klimekc41e8192013-08-29 15:21:40 +0000604 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000605 Token Greater = FormatTok->Tok;
606 FormatTok = new (Allocator.Allocate()) FormatToken;
607 FormatTok->Tok = Greater;
Manuel Klimekad3094b2013-05-23 10:56:37 +0000608 SourceLocation GreaterLocation =
Manuel Klimek96e888b2013-05-28 11:55:06 +0000609 FormatTok->Tok.getLocation().getLocWithOffset(1);
610 FormatTok->WhitespaceRange =
611 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000612 FormatTok->TokenText = ">";
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000613 FormatTok->ColumnWidth = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000614 GreaterStashed = false;
615 return FormatTok;
616 }
617
Manuel Klimek96e888b2013-05-28 11:55:06 +0000618 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper561211d2013-07-16 20:28:33 +0000619 readRawToken(*FormatTok);
Manuel Klimekde008c02013-05-27 15:23:34 +0000620 SourceLocation WhitespaceStart =
Manuel Klimek96e888b2013-05-28 11:55:06 +0000621 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Manuel Klimekad3094b2013-05-23 10:56:37 +0000622 if (SourceMgr.getFileOffset(WhitespaceStart) == 0)
Manuel Klimek96e888b2013-05-28 11:55:06 +0000623 FormatTok->IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000624
625 // Consume and record whitespace until we find a significant token.
Manuel Klimekde008c02013-05-27 15:23:34 +0000626 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek96e888b2013-05-28 11:55:06 +0000627 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000628 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
629 switch (FormatTok->TokenText[i]) {
630 case '\n':
631 ++FormatTok->NewlinesBefore;
632 // FIXME: This is technically incorrect, as it could also
633 // be a literal backslash at the end of the line.
Daniel Jasper2f0a0202013-09-06 08:54:24 +0000634 if (i == 0 || FormatTok->TokenText[i - 1] != '\\')
Manuel Klimekc41e8192013-08-29 15:21:40 +0000635 FormatTok->HasUnescapedNewline = true;
636 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
637 Column = 0;
638 break;
639 case ' ':
640 ++Column;
641 break;
642 case '\t':
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000643 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000644 break;
645 default:
646 ++Column;
647 break;
648 }
649 }
650
Manuel Klimek96e888b2013-05-28 11:55:06 +0000651 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000652
Daniel Jasper561211d2013-07-16 20:28:33 +0000653 readRawToken(*FormatTok);
Manuel Klimekd4397b92013-01-04 23:34:14 +0000654 }
Manuel Klimek95419382013-01-07 07:56:50 +0000655
Manuel Klimekd4397b92013-01-04 23:34:14 +0000656 // In case the token starts with escaped newlines, we want to
657 // take them into account as whitespace - this pattern is quite frequent
658 // in macro definitions.
659 // FIXME: What do we want to do with other escaped spaces, and escaped
660 // spaces or newlines in the middle of tokens?
661 // FIXME: Add a more explicit test.
Daniel Jasper561211d2013-07-16 20:28:33 +0000662 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
663 FormatTok->TokenText[1] == '\n') {
Manuel Klimek96e888b2013-05-28 11:55:06 +0000664 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimekad3094b2013-05-23 10:56:37 +0000665 WhitespaceLength += 2;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000666 Column = 0;
Daniel Jasper561211d2013-07-16 20:28:33 +0000667 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000668 }
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000669
670 FormatTok->WhitespaceRange = SourceRange(
671 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
672
Manuel Klimekc41e8192013-08-29 15:21:40 +0000673 FormatTok->OriginalColumn = Column;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000674
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000675 TrailingWhitespace = 0;
676 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000677 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper561211d2013-07-16 20:28:33 +0000678 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko51bb5d92013-09-06 17:24:54 +0000679 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper561211d2013-07-16 20:28:33 +0000680 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000681 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper561211d2013-07-16 20:28:33 +0000682 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek96e888b2013-05-28 11:55:06 +0000683 FormatTok->Tok.setIdentifierInfo(&Info);
684 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000685 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek96e888b2013-05-28 11:55:06 +0000686 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper561211d2013-07-16 20:28:33 +0000687 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000688 GreaterStashed = true;
689 }
690
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000691 // Now FormatTok is the next non-whitespace token.
Alexander Kornienko00895102013-06-05 14:09:10 +0000692
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000693 StringRef Text = FormatTok->TokenText;
694 size_t FirstNewlinePos = Text.find('\n');
695 if (FirstNewlinePos != StringRef::npos) {
696 FormatTok->IsMultiline = true;
697 // The last line of the token always starts in column 0.
698 // Thus, the length can be precomputed even in the presence of tabs.
699 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
700 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
701 Encoding);
702 Text = Text.substr(0, FirstNewlinePos);
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000703 }
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000704
705 // FIXME: ColumnWidth actually depends on the start column, we need to
706 // take this into account when the token is moved.
707 FormatTok->ColumnWidth =
708 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
709
710 // FIXME: For multi-line tokens this should be LastLineColumnWidth.
711 // For line comments this should probably be zero. But before changing,
712 // we need good tests for this.
713 Column += FormatTok->ColumnWidth;
714
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000715 return FormatTok;
716 }
717
Manuel Klimek96e888b2013-05-28 11:55:06 +0000718 FormatToken *FormatTok;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000719 bool GreaterStashed;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000720 unsigned Column;
Manuel Klimekde008c02013-05-27 15:23:34 +0000721 unsigned TrailingWhitespace;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000722 Lexer &Lex;
723 SourceManager &SourceMgr;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000724 FormatStyle &Style;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000725 IdentifierTable IdentTable;
Alexander Kornienko00895102013-06-05 14:09:10 +0000726 encoding::Encoding Encoding;
Manuel Klimek96e888b2013-05-28 11:55:06 +0000727 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
728 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000729
Daniel Jasper561211d2013-07-16 20:28:33 +0000730 void readRawToken(FormatToken &Tok) {
731 Lex.LexFromRawLexer(Tok.Tok);
732 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
733 Tok.Tok.getLength());
Daniel Jasper561211d2013-07-16 20:28:33 +0000734 // For formatting, treat unterminated string literals like normal string
735 // literals.
736 if (Tok.is(tok::unknown) && !Tok.TokenText.empty() &&
737 Tok.TokenText[0] == '"') {
738 Tok.Tok.setKind(tok::string_literal);
739 Tok.IsUnterminatedLiteral = true;
740 }
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000741 }
742};
743
Daniel Jasperbac016b2012-12-03 18:12:45 +0000744class Formatter : public UnwrappedLineConsumer {
745public:
Daniel Jaspercaf42a32013-05-15 08:14:19 +0000746 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000747 const std::vector<CharSourceRange> &Ranges)
Daniel Jaspercaf42a32013-05-15 08:14:19 +0000748 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko00895102013-06-05 14:09:10 +0000749 Whitespaces(SourceMgr, Style), Ranges(Ranges),
750 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasper9637dda2013-07-15 14:33:14 +0000751 DEBUG(llvm::dbgs() << "File encoding: "
752 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
753 : "unknown")
754 << "\n");
Alexander Kornienko00895102013-06-05 14:09:10 +0000755 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000756
Daniel Jasper567dcf92013-09-05 09:29:45 +0000757 virtual ~Formatter() {
758 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
759 delete AnnotatedLines[i];
760 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000761 }
Daniel Jasperaccb0b02012-12-04 21:05:31 +0000762
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000763 tooling::Replacements format() {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000764 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek96e888b2013-05-28 11:55:06 +0000765
766 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek67d080d2013-04-12 14:13:36 +0000767 bool StructuralError = Parser.parse();
Alexander Kornienko00895102013-06-05 14:09:10 +0000768 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000769 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000770 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000771 }
772 deriveLocalStyle();
773 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000774 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000775 }
Daniel Jasper5999f762013-04-09 17:46:55 +0000776
Daniel Jasperb77d7412013-09-06 07:54:20 +0000777 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasper5999f762013-04-09 17:46:55 +0000778
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000779 std::vector<int> IndentForLevel;
780 bool PreviousLineWasTouched = false;
Manuel Klimekb3987012013-05-29 14:47:47 +0000781 const FormatToken *PreviousLineLastToken = 0;
Daniel Jasper89b3a7f2013-05-10 13:00:49 +0000782 bool FormatPPDirective = false;
Daniel Jasperb77d7412013-09-06 07:54:20 +0000783 for (SmallVectorImpl<AnnotatedLine *>::iterator I = AnnotatedLines.begin(),
784 E = AnnotatedLines.end();
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000785 I != E; ++I) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000786 const AnnotatedLine &TheLine = **I;
Manuel Klimekb3987012013-05-29 14:47:47 +0000787 const FormatToken *FirstTok = TheLine.First;
788 int Offset = getIndentOffset(*TheLine.First);
Daniel Jasper89b3a7f2013-05-10 13:00:49 +0000789
790 // Check whether this line is part of a formatted preprocessor directive.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000791 if (FirstTok->HasUnescapedNewline)
Daniel Jasper89b3a7f2013-05-10 13:00:49 +0000792 FormatPPDirective = false;
793 if (!FormatPPDirective && TheLine.InPPDirective &&
794 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
795 FormatPPDirective = true;
796
Daniel Jasper1fb8d882013-05-14 09:30:02 +0000797 // Determine indent and try to merge multiple unwrapped lines.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000798 while (IndentForLevel.size() <= TheLine.Level)
799 IndentForLevel.push_back(-1);
800 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper1fb8d882013-05-14 09:30:02 +0000801 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
802 if (static_cast<int>(Indent) + Offset >= 0)
803 Indent += Offset;
804 tryFitMultipleLinesInOne(Indent, I, E);
805
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000806 bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0;
Manuel Klimekb3987012013-05-29 14:47:47 +0000807 if (TheLine.First->is(tok::eof)) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000808 if (PreviousLineWasTouched) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000809 unsigned NewLines = std::min(FirstTok->NewlinesBefore, 1u);
Manuel Klimekb3987012013-05-29 14:47:47 +0000810 Whitespaces.replaceWhitespace(*TheLine.First, NewLines, /*Indent*/ 0,
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000811 /*TargetColumn*/ 0);
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000812 }
813 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper89b3a7f2013-05-10 13:00:49 +0000814 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000815 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000816 if (FirstTok->WhitespaceRange.isValid() &&
Manuel Klimek67d080d2013-04-12 14:13:36 +0000817 // Insert a break even if there is a structural error in case where
818 // we break apart a line consisting of multiple unwrapped lines.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000819 (FirstTok->NewlinesBefore == 0 || !StructuralError)) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000820 formatFirstToken(*TheLine.First, PreviousLineLastToken, Indent,
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000821 TheLine.InPPDirective);
Manuel Klimek67d080d2013-04-12 14:13:36 +0000822 } else {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000823 Indent = LevelIndent = FirstTok->OriginalColumn;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000824 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000825 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000826 BinPackInconclusiveFunctions);
827
828 // If everything fits on a single line, just put it there.
829 unsigned ColumnLimit = Style.ColumnLimit;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000830 AnnotatedLine *NextLine = *(I + 1);
831 if ((I + 1) != E && NextLine->InPPDirective &&
832 !NextLine->First->HasUnescapedNewline)
833 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000834
Daniel Jasper567dcf92013-09-05 09:29:45 +0000835 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
Daniel Jasperb77d7412013-09-06 07:54:20 +0000836 LineState State =
837 Indenter.getInitialState(Indent, &TheLine, /*DryRun=*/false);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000838 while (State.NextToken != NULL)
839 Indenter.addTokenToState(State, false, false);
840 } else if (Style.ColumnLimit == 0) {
841 NoColumnLimitFormatter Formatter(&Indenter);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000842 Formatter.format(Indent, &TheLine);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000843 } else {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000844 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style,
845 TheLine);
846 Formatter.format(Indent);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000847 }
848
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000849 IndentForLevel[TheLine.Level] = LevelIndent;
850 PreviousLineWasTouched = true;
851 } else {
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000852 // Format the first token if necessary, and notify the WhitespaceManager
853 // about the unchanged whitespace.
Manuel Klimekb3987012013-05-29 14:47:47 +0000854 for (const FormatToken *Tok = TheLine.First; Tok != NULL;
855 Tok = Tok->Next) {
856 if (Tok == TheLine.First &&
857 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000858 unsigned LevelIndent = Tok->OriginalColumn;
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000859 // Remove trailing whitespace of the previous line if it was
860 // touched.
861 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
862 formatFirstToken(*Tok, PreviousLineLastToken, LevelIndent,
863 TheLine.InPPDirective);
864 } else {
Manuel Klimekb3987012013-05-29 14:47:47 +0000865 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000866 }
Daniel Jasper1fb8d882013-05-14 09:30:02 +0000867
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000868 if (static_cast<int>(LevelIndent) - Offset >= 0)
869 LevelIndent -= Offset;
870 if (Tok->isNot(tok::comment))
871 IndentForLevel[TheLine.Level] = LevelIndent;
872 } else {
Manuel Klimekb3987012013-05-29 14:47:47 +0000873 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000874 }
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000875 }
876 // If we did not reformat this unwrapped line, the column at the end of
877 // the last token is unchanged - thus, we can calculate the end of the
878 // last token.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000879 PreviousLineWasTouched = false;
880 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000881 PreviousLineLastToken = TheLine.Last;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000882 }
883 return Whitespaces.generateReplacements();
884 }
885
886private:
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000887 void deriveLocalStyle() {
888 unsigned CountBoundToVariable = 0;
889 unsigned CountBoundToType = 0;
890 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000891 bool HasBinPackedFunction = false;
892 bool HasOnePerLineFunction = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000893 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000894 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000895 continue;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000896 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimekb3987012013-05-29 14:47:47 +0000897 while (Tok->Next) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000898 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000899 bool SpacesBefore =
900 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
901 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
902 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000903 if (SpacesBefore && !SpacesAfter)
904 ++CountBoundToVariable;
905 else if (!SpacesBefore && SpacesAfter)
906 ++CountBoundToType;
907 }
908
Daniel Jasper29f123b2013-02-08 15:28:42 +0000909 if (Tok->Type == TT_TemplateCloser &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000910 Tok->Previous->Type == TT_TemplateCloser &&
911 Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd())
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000912 HasCpp03IncompatibleFormat = true;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000913
914 if (Tok->PackingKind == PPK_BinPacked)
915 HasBinPackedFunction = true;
916 if (Tok->PackingKind == PPK_OnePerLine)
917 HasOnePerLineFunction = true;
918
Manuel Klimekb3987012013-05-29 14:47:47 +0000919 Tok = Tok->Next;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000920 }
921 }
922 if (Style.DerivePointerBinding) {
923 if (CountBoundToType > CountBoundToVariable)
924 Style.PointerBindsToType = true;
925 else if (CountBoundToType < CountBoundToVariable)
926 Style.PointerBindsToType = false;
927 }
928 if (Style.Standard == FormatStyle::LS_Auto) {
929 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
930 : FormatStyle::LS_Cpp03;
931 }
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000932 BinPackInconclusiveFunctions =
933 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000934 }
935
Manuel Klimek547d5db2013-02-08 17:38:27 +0000936 /// \brief Get the indent of \p Level from \p IndentForLevel.
937 ///
938 /// \p IndentForLevel must contain the indent for the level \c l
939 /// at \p IndentForLevel[l], or a value < 0 if the indent for
940 /// that level is unknown.
Daniel Jasperfc759082013-02-14 14:26:07 +0000941 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimek547d5db2013-02-08 17:38:27 +0000942 if (IndentForLevel[Level] != -1)
943 return IndentForLevel[Level];
Manuel Klimek52635ff2013-02-08 19:53:32 +0000944 if (Level == 0)
945 return 0;
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000946 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimek547d5db2013-02-08 17:38:27 +0000947 }
948
949 /// \brief Get the offset of the line relatively to the level.
950 ///
951 /// For example, 'public:' labels in classes are offset by 1 or 2
952 /// characters to the left from their level.
Manuel Klimekb3987012013-05-29 14:47:47 +0000953 int getIndentOffset(const FormatToken &RootToken) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +0000954 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimek547d5db2013-02-08 17:38:27 +0000955 return Style.AccessModifierOffset;
956 return 0;
957 }
958
Manuel Klimek517e8942013-01-11 17:54:10 +0000959 /// \brief Tries to merge lines into one.
960 ///
961 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
962 /// if possible; note that \c I will be incremented when lines are merged.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000963 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperb77d7412013-09-06 07:54:20 +0000964 SmallVectorImpl<AnnotatedLine *>::iterator &I,
965 SmallVectorImpl<AnnotatedLine *>::iterator E) {
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000966 // We can never merge stuff if there are trailing line comments.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000967 AnnotatedLine *TheLine = *I;
968 if (TheLine->Last->Type == TT_LineComment)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000969 return;
970
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000971 if (Indent > Style.ColumnLimit)
972 return;
973
Daniel Jaspera4d46212013-02-28 11:05:57 +0000974 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasperf11a7052013-02-21 21:33:55 +0000975 // If we already exceed the column limit, we set 'Limit' to 0. The different
976 // tryMerge..() functions can then decide whether to still do merging.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000977 Limit = TheLine->Last->TotalLength > Limit
978 ? 0
979 : Limit - TheLine->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +0000980
Daniel Jasper567dcf92013-09-05 09:29:45 +0000981 if (I + 1 == E || (*(I + 1))->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000982 return;
Manuel Klimek517e8942013-01-11 17:54:10 +0000983
Daniel Jasper567dcf92013-09-05 09:29:45 +0000984 if (TheLine->Last->is(tok::l_brace)) {
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000985 tryMergeSimpleBlock(I, E, Limit);
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000986 } else if (Style.AllowShortIfStatementsOnASingleLine &&
Daniel Jasper567dcf92013-09-05 09:29:45 +0000987 TheLine->First->is(tok::kw_if)) {
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000988 tryMergeSimpleControlStatement(I, E, Limit);
989 } else if (Style.AllowShortLoopsOnASingleLine &&
Daniel Jasper567dcf92013-09-05 09:29:45 +0000990 TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000991 tryMergeSimpleControlStatement(I, E, Limit);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000992 } else if (TheLine->InPPDirective && (TheLine->First->HasUnescapedNewline ||
993 TheLine->First->IsFirst)) {
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000994 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000995 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000996 }
997
Daniel Jasperb77d7412013-09-06 07:54:20 +0000998 void tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::iterator &I,
999 SmallVectorImpl<AnnotatedLine *>::iterator E,
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001000 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001001 if (Limit == 0)
1002 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001003 AnnotatedLine &Line = **I;
1004 if (!(*(I + 1))->InPPDirective || (*(I + 1))->First->HasUnescapedNewline)
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001005 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001006 if (I + 2 != E && (*(I + 2))->InPPDirective &&
1007 !(*(I + 2))->First->HasUnescapedNewline)
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001008 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001009 if (1 + (*(I + 1))->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001010 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001011 join(Line, **(++I));
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001012 }
1013
Daniel Jasperb77d7412013-09-06 07:54:20 +00001014 void
1015 tryMergeSimpleControlStatement(SmallVectorImpl<AnnotatedLine *>::iterator &I,
1016 SmallVectorImpl<AnnotatedLine *>::iterator E,
1017 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001018 if (Limit == 0)
1019 return;
Manuel Klimekd3a247c2013-08-07 19:20:45 +00001020 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman &&
Daniel Jasper567dcf92013-09-05 09:29:45 +00001021 (*(I + 1))->First->is(tok::l_brace))
Manuel Klimekd3a247c2013-08-07 19:20:45 +00001022 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001023 if ((*(I + 1))->InPPDirective != (*I)->InPPDirective ||
1024 ((*(I + 1))->InPPDirective && (*(I + 1))->First->HasUnescapedNewline))
Manuel Klimek4c128122013-01-18 14:46:43 +00001025 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001026 AnnotatedLine &Line = **I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001027 if (Line.Last->isNot(tok::r_paren))
1028 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001029 if (1 + (*(I + 1))->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001030 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001031 if ((*(I + 1))->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
1032 tok::kw_while) ||
1033 (*(I + 1))->First->Type == TT_LineComment)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001034 return;
1035 // Only inline simple if's (no nested if or else).
Manuel Klimekb3987012013-05-29 14:47:47 +00001036 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Daniel Jasper567dcf92013-09-05 09:29:45 +00001037 (*(I + 2))->First->is(tok::kw_else))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001038 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001039 join(Line, **(++I));
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001040 }
1041
Daniel Jasperb77d7412013-09-06 07:54:20 +00001042 void tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::iterator &I,
1043 SmallVectorImpl<AnnotatedLine *>::iterator E,
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001044 unsigned Limit) {
Daniel Jasper5be59ba2013-05-15 14:09:55 +00001045 // No merging if the brace already is on the next line.
1046 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
1047 return;
1048
Manuel Klimek517e8942013-01-11 17:54:10 +00001049 // First, check that the current line allows merging. This is the case if
1050 // we're not in a control flow statement and the last token is an opening
1051 // brace.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001052 AnnotatedLine &Line = **I;
Manuel Klimekb3987012013-05-29 14:47:47 +00001053 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1054 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001055 tok::kw_for,
Manuel Klimekb3987012013-05-29 14:47:47 +00001056 // This gets rid of all ObjC @ keywords and methods.
1057 tok::at, tok::minus, tok::plus))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001058 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001059
Daniel Jasper567dcf92013-09-05 09:29:45 +00001060 FormatToken *Tok = (*(I + 1))->First;
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001061 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001062 (Tok->getNextNonComment() == NULL ||
1063 Tok->getNextNonComment()->is(tok::semi))) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001064 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jasper729a7432013-02-11 12:36:37 +00001065 Tok->SpacesRequiredBefore = 0;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001066 Tok->CanBreakBefore = true;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001067 join(Line, **(I + 1));
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001068 I += 1;
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001069 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001070 // Check that we still have three lines and they fit into the limit.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001071 if (I + 2 == E || (*(I + 2))->Type == LT_Invalid ||
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001072 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001073 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001074
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001075 // Second, check that the next line does not contain any braces - if it
1076 // does, readability declines when putting it into a single line.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001077 if ((*(I + 1))->Last->Type == TT_LineComment || Tok->MustBreakBefore)
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001078 return;
1079 do {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001080 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001081 return;
Manuel Klimekb3987012013-05-29 14:47:47 +00001082 Tok = Tok->Next;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001083 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001084
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001085 // Last, check that the third line contains a single closing brace.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001086 Tok = (*(I + 2))->First;
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001087 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001088 Tok->MustBreakBefore)
1089 return;
1090
Daniel Jasper567dcf92013-09-05 09:29:45 +00001091 join(Line, **(I + 1));
1092 join(Line, **(I + 2));
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001093 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +00001094 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001095 }
1096
Daniel Jasperb77d7412013-09-06 07:54:20 +00001097 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::iterator I,
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001098 unsigned Limit) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001099 return 1 + (*(I + 1))->Last->TotalLength + 1 +
1100 (*(I + 2))->Last->TotalLength <=
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001101 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001102 }
1103
Daniel Jasper995e8202013-01-14 13:08:07 +00001104 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001105 assert(!A.Last->Next);
1106 assert(!B.First->Previous);
1107 A.Last->Next = B.First;
1108 B.First->Previous = A.Last;
1109 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1110 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1111 Tok->TotalLength += LengthA;
1112 A.Last = Tok;
Daniel Jasper995e8202013-01-14 13:08:07 +00001113 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001114 }
1115
Daniel Jasper6f21a982013-03-13 07:49:51 +00001116 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf3023542013-03-07 20:50:00 +00001117 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1118 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1119 Ranges[i].getBegin()) &&
1120 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1121 Range.getBegin()))
1122 return true;
1123 }
1124 return false;
1125 }
1126
1127 bool touchesLine(const AnnotatedLine &TheLine) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001128 const FormatToken *First = TheLine.First;
1129 const FormatToken *Last = TheLine.Last;
Daniel Jasper84f5ddf2013-05-14 10:31:09 +00001130 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001131 First->WhitespaceRange.getBegin().getLocWithOffset(
1132 First->LastNewlineOffset),
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001133 Last->Tok.getLocation().getLocWithOffset(Last->TokenText.size() - 1));
Daniel Jasperf3023542013-03-07 20:50:00 +00001134 return touchesRanges(LineRange);
1135 }
1136
Daniel Jasperb77d7412013-09-06 07:54:20 +00001137 bool touchesPPDirective(SmallVectorImpl<AnnotatedLine *>::iterator I,
1138 SmallVectorImpl<AnnotatedLine *>::iterator E) {
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001139 for (; I != E; ++I) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001140 if ((*I)->First->HasUnescapedNewline)
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001141 return false;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001142 if (touchesLine(**I))
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001143 return true;
1144 }
1145 return false;
1146 }
1147
Daniel Jasperf3023542013-03-07 20:50:00 +00001148 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001149 const FormatToken *First = TheLine.First;
Daniel Jasperf3023542013-03-07 20:50:00 +00001150 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001151 First->WhitespaceRange.getBegin(),
1152 First->WhitespaceRange.getBegin().getLocWithOffset(
1153 First->LastNewlineOffset));
Daniel Jasperf3023542013-03-07 20:50:00 +00001154 return touchesRanges(LineRange);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001155 }
1156
1157 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001158 AnnotatedLines.push_back(new AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001159 }
1160
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001161 /// \brief Add a new line and the required indent before the first Token
1162 /// of the \c UnwrappedLine if there was no structural parsing error.
1163 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimekb3987012013-05-29 14:47:47 +00001164 void formatFirstToken(const FormatToken &RootToken,
1165 const FormatToken *PreviousToken, unsigned Indent,
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001166 bool InPPDirective) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001167 unsigned Newlines =
Manuel Klimekb3987012013-05-29 14:47:47 +00001168 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Daniel Jasper15f33f02013-06-03 16:16:41 +00001169 // Remove empty lines before "}" where applicable.
1170 if (RootToken.is(tok::r_brace) &&
1171 (!RootToken.Next ||
1172 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1173 Newlines = std::min(Newlines, 1u);
Manuel Klimekb3987012013-05-29 14:47:47 +00001174 if (Newlines == 0 && !RootToken.IsFirst)
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001175 Newlines = 1;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001176
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001177 // Insert extra new line before access specifiers.
1178 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001179 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001180 ++Newlines;
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001181
Manuel Klimekb3987012013-05-29 14:47:47 +00001182 Whitespaces.replaceWhitespace(
1183 RootToken, Newlines, Indent, Indent,
1184 InPPDirective && !RootToken.HasUnescapedNewline);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001185 }
1186
Daniel Jasper567dcf92013-09-05 09:29:45 +00001187 unsigned getColumnLimit(bool InPPDirective) const {
1188 // In preprocessor directives reserve two chars for trailing " \"
1189 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1190 }
1191
Daniel Jasperbac016b2012-12-03 18:12:45 +00001192 FormatStyle Style;
1193 Lexer &Lex;
1194 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001195 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001196 std::vector<CharSourceRange> Ranges;
Daniel Jasperb77d7412013-09-06 07:54:20 +00001197 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
Alexander Kornienko00895102013-06-05 14:09:10 +00001198
1199 encoding::Encoding Encoding;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001200 bool BinPackInconclusiveFunctions;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001201};
1202
Craig Topper83f81d72013-06-30 22:29:28 +00001203} // end anonymous namespace
1204
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001205tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1206 SourceManager &SourceMgr,
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001207 std::vector<CharSourceRange> Ranges) {
1208 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001209 return formatter.format();
1210}
1211
Daniel Jasper8a999452013-05-16 10:40:07 +00001212tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1213 std::vector<tooling::Range> Ranges,
1214 StringRef FileName) {
1215 FileManager Files((FileSystemOptions()));
1216 DiagnosticsEngine Diagnostics(
1217 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1218 new DiagnosticOptions);
1219 SourceManager SourceMgr(Diagnostics, Files);
1220 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1221 const clang::FileEntry *Entry =
1222 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1223 SourceMgr.overrideFileContents(Entry, Buf);
1224 FileID ID =
1225 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001226 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1227 getFormattingLangOpts(Style.Standard));
Daniel Jasper8a999452013-05-16 10:40:07 +00001228 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1229 std::vector<CharSourceRange> CharRanges;
1230 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1231 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1232 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1233 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1234 }
1235 return reformat(Style, Lex, SourceMgr, CharRanges);
1236}
1237
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001238LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasper46ef8522013-01-10 13:08:12 +00001239 LangOptions LangOpts;
1240 LangOpts.CPlusPlus = 1;
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001241 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasperb64eca02013-03-22 10:01:29 +00001242 LangOpts.LineComment = 1;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001243 LangOpts.Bool = 1;
1244 LangOpts.ObjC1 = 1;
1245 LangOpts.ObjC2 = 1;
1246 return LangOpts;
1247}
1248
Daniel Jaspercd162382013-01-07 13:26:07 +00001249} // namespace format
1250} // namespace clang