blob: 79244b199378c59ed4315900e099aae2b318b787 [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"
Edwin Vanef4e12c82013-09-30 13:31:48 +000030#include "llvm/Support/Path.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) {
Alexander Kornienko9321e872013-09-04 14:09:13 +000040 IO.enumCase(Value, "Cpp03", clang::format::FormatStyle::LS_Cpp03);
Manuel Klimek44135b82013-05-13 12:51:40 +000041 IO.enumCase(Value, "C++03", clang::format::FormatStyle::LS_Cpp03);
Alexander Kornienko9321e872013-09-04 14:09:13 +000042 IO.enumCase(Value, "Cpp11", clang::format::FormatStyle::LS_Cpp11);
Manuel Klimek44135b82013-05-13 12:51:40 +000043 IO.enumCase(Value, "C++11", clang::format::FormatStyle::LS_Cpp11);
44 IO.enumCase(Value, "Auto", clang::format::FormatStyle::LS_Auto);
45 }
46};
47
Daniel Jasper1fb8d882013-05-14 09:30:02 +000048template <>
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +000049struct ScalarEnumerationTraits<clang::format::FormatStyle::UseTabStyle> {
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +000050 static void enumeration(IO &IO,
51 clang::format::FormatStyle::UseTabStyle &Value) {
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +000052 IO.enumCase(Value, "Never", clang::format::FormatStyle::UT_Never);
53 IO.enumCase(Value, "false", clang::format::FormatStyle::UT_Never);
54 IO.enumCase(Value, "Always", clang::format::FormatStyle::UT_Always);
55 IO.enumCase(Value, "true", clang::format::FormatStyle::UT_Always);
56 IO.enumCase(Value, "ForIndentation",
57 clang::format::FormatStyle::UT_ForIndentation);
58 }
59};
60
61template <>
Manuel Klimek44135b82013-05-13 12:51:40 +000062struct ScalarEnumerationTraits<clang::format::FormatStyle::BraceBreakingStyle> {
63 static void
64 enumeration(IO &IO, clang::format::FormatStyle::BraceBreakingStyle &Value) {
65 IO.enumCase(Value, "Attach", clang::format::FormatStyle::BS_Attach);
66 IO.enumCase(Value, "Linux", clang::format::FormatStyle::BS_Linux);
67 IO.enumCase(Value, "Stroustrup", clang::format::FormatStyle::BS_Stroustrup);
Manuel Klimeke4907052013-08-02 21:31:59 +000068 IO.enumCase(Value, "Allman", clang::format::FormatStyle::BS_Allman);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000069 }
70};
71
Daniel Jaspereff18b92013-07-31 23:16:02 +000072template <>
73struct ScalarEnumerationTraits<
74 clang::format::FormatStyle::NamespaceIndentationKind> {
75 static void
76 enumeration(IO &IO,
77 clang::format::FormatStyle::NamespaceIndentationKind &Value) {
78 IO.enumCase(Value, "None", clang::format::FormatStyle::NI_None);
79 IO.enumCase(Value, "Inner", clang::format::FormatStyle::NI_Inner);
80 IO.enumCase(Value, "All", clang::format::FormatStyle::NI_All);
81 }
82};
83
Alexander Kornienkod71ec162013-05-07 15:32:14 +000084template <> struct MappingTraits<clang::format::FormatStyle> {
85 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
Alexander Kornienkodd256312013-05-10 11:56:10 +000086 if (IO.outputting()) {
Alexander Kornienko4e65c982013-09-02 16:39:23 +000087 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
88 "Mozilla", "WebKit" };
Alexander Kornienkodd256312013-05-10 11:56:10 +000089 ArrayRef<StringRef> Styles(StylesArray);
90 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
91 StringRef StyleName(Styles[i]);
Alexander Kornienko885f87b2013-05-19 00:53:30 +000092 clang::format::FormatStyle PredefinedStyle;
93 if (clang::format::getPredefinedStyle(StyleName, &PredefinedStyle) &&
94 Style == PredefinedStyle) {
Alexander Kornienkodd256312013-05-10 11:56:10 +000095 IO.mapOptional("# BasedOnStyle", StyleName);
96 break;
97 }
98 }
99 } else {
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000100 StringRef BasedOnStyle;
101 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000102 if (!BasedOnStyle.empty())
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000103 if (!clang::format::getPredefinedStyle(BasedOnStyle, &Style)) {
104 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
105 return;
106 }
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000107 }
108
109 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jasper6315fec2013-08-13 10:58:30 +0000110 IO.mapOptional("ConstructorInitializerIndentWidth",
111 Style.ConstructorInitializerIndentWidth);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000112 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000113 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000114 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
115 Style.AllowAllParametersOfDeclarationOnNextLine);
116 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
117 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000118 IO.mapOptional("AllowShortLoopsOnASingleLine",
119 Style.AllowShortLoopsOnASingleLine);
Daniel Jasperbbc87762013-05-29 12:07:31 +0000120 IO.mapOptional("AlwaysBreakTemplateDeclarations",
121 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko56312022013-07-04 12:02:44 +0000122 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
123 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000124 IO.mapOptional("BreakBeforeBinaryOperators",
125 Style.BreakBeforeBinaryOperators);
126 IO.mapOptional("BreakConstructorInitializersBeforeComma",
127 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000128 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
129 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
130 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
131 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
132 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000133 IO.mapOptional("ExperimentalAutoDetectBinPacking",
134 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000135 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
136 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspereff18b92013-07-31 23:16:02 +0000137 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000138 IO.mapOptional("ObjCSpaceBeforeProtocolList",
139 Style.ObjCSpaceBeforeProtocolList);
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000140 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
141 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000142 IO.mapOptional("PenaltyBreakFirstLessLess",
143 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000144 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
145 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
146 Style.PenaltyReturnTypeOnItsOwnLine);
147 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
148 IO.mapOptional("SpacesBeforeTrailingComments",
149 Style.SpacesBeforeTrailingComments);
Daniel Jasperb5dc3f42013-07-16 18:22:10 +0000150 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000151 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000152 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000153 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000154 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimek44135b82013-05-13 12:51:40 +0000155 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimeka9a7f102013-06-21 17:25:42 +0000156 IO.mapOptional("IndentFunctionDeclarationAfterType",
157 Style.IndentFunctionDeclarationAfterType);
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000158 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasper34f3d052013-08-21 08:39:01 +0000159 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000160 IO.mapOptional("SpacesInCStyleCastParentheses",
161 Style.SpacesInCStyleCastParentheses);
162 IO.mapOptional("SpaceAfterControlStatementKeyword",
163 Style.SpaceAfterControlStatementKeyword);
Daniel Jasper9b4de852013-09-25 15:15:02 +0000164 IO.mapOptional("SpaceBeforeAssignmentOperators",
165 Style.SpaceBeforeAssignmentOperators);
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000166 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000167 }
168};
169}
170}
171
Daniel Jasperbac016b2012-12-03 18:12:45 +0000172namespace clang {
173namespace format {
174
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000175void setDefaultPenalties(FormatStyle &Style) {
Daniel Jasperf5461782013-08-28 10:03:58 +0000176 Style.PenaltyBreakComment = 60;
Daniel Jasper9637dda2013-07-15 14:33:14 +0000177 Style.PenaltyBreakFirstLessLess = 120;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000178 Style.PenaltyBreakString = 1000;
179 Style.PenaltyExcessCharacter = 1000000;
180}
181
Daniel Jasperbac016b2012-12-03 18:12:45 +0000182FormatStyle getLLVMStyle() {
183 FormatStyle LLVMStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000184 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000185 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000186 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000187 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000188 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000189 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienko56312022013-07-04 12:02:44 +0000190 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000191 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000192 LLVMStyle.BinPackParameters = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000193 LLVMStyle.BreakBeforeBinaryOperators = false;
194 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
195 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000196 LLVMStyle.ColumnLimit = 80;
197 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6315fec2013-08-13 10:58:30 +0000198 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000199 LLVMStyle.Cpp11BracedListStyle = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000200 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000201 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000202 LLVMStyle.IndentCaseLabels = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000203 LLVMStyle.IndentFunctionDeclarationAfterType = false;
204 LLVMStyle.IndentWidth = 2;
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000205 LLVMStyle.TabWidth = 8;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000206 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000207 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Weber5f500df2013-01-10 20:12:55 +0000208 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000209 LLVMStyle.PointerBindsToType = false;
210 LLVMStyle.SpacesBeforeTrailingComments = 1;
211 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000212 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000213 LLVMStyle.SpacesInParentheses = false;
214 LLVMStyle.SpaceInEmptyParentheses = false;
215 LLVMStyle.SpacesInCStyleCastParentheses = false;
216 LLVMStyle.SpaceAfterControlStatementKeyword = true;
Daniel Jasper9b4de852013-09-25 15:15:02 +0000217 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000218 LLVMStyle.ContinuationIndentWidth = 4;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000219
220 setDefaultPenalties(LLVMStyle);
221 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
222
Daniel Jasperbac016b2012-12-03 18:12:45 +0000223 return LLVMStyle;
224}
225
226FormatStyle getGoogleStyle() {
227 FormatStyle GoogleStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000228 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000229 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000230 GoogleStyle.AlignTrailingComments = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000231 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000232 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper1bee0732013-05-23 18:05:18 +0000233 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko56312022013-07-04 12:02:44 +0000234 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000235 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000236 GoogleStyle.BinPackParameters = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000237 GoogleStyle.BreakBeforeBinaryOperators = false;
238 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
239 GoogleStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000240 GoogleStyle.ColumnLimit = 80;
241 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper6315fec2013-08-13 10:58:30 +0000242 GoogleStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000243 GoogleStyle.Cpp11BracedListStyle = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000244 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000245 GoogleStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000246 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000247 GoogleStyle.IndentFunctionDeclarationAfterType = true;
248 GoogleStyle.IndentWidth = 2;
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000249 GoogleStyle.TabWidth = 8;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000250 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000251 GoogleStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Weber5f500df2013-01-10 20:12:55 +0000252 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000253 GoogleStyle.PointerBindsToType = true;
254 GoogleStyle.SpacesBeforeTrailingComments = 2;
255 GoogleStyle.Standard = FormatStyle::LS_Auto;
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000256 GoogleStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000257 GoogleStyle.SpacesInParentheses = false;
258 GoogleStyle.SpaceInEmptyParentheses = false;
259 GoogleStyle.SpacesInCStyleCastParentheses = false;
260 GoogleStyle.SpaceAfterControlStatementKeyword = true;
Daniel Jasper9b4de852013-09-25 15:15:02 +0000261 GoogleStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000262 GoogleStyle.ContinuationIndentWidth = 4;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000263
264 setDefaultPenalties(GoogleStyle);
265 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
266
Daniel Jasperbac016b2012-12-03 18:12:45 +0000267 return GoogleStyle;
268}
269
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000270FormatStyle getChromiumStyle() {
271 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +0000272 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000273 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000274 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000275 ChromiumStyle.BinPackParameters = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000276 ChromiumStyle.DerivePointerBinding = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000277 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000278 return ChromiumStyle;
279}
280
Alexander Kornienkofb594862013-05-06 14:11:27 +0000281FormatStyle getMozillaStyle() {
282 FormatStyle MozillaStyle = getLLVMStyle();
283 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
284 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
285 MozillaStyle.DerivePointerBinding = true;
286 MozillaStyle.IndentCaseLabels = true;
287 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
288 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
289 MozillaStyle.PointerBindsToType = true;
290 return MozillaStyle;
291}
292
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000293FormatStyle getWebKitStyle() {
294 FormatStyle Style = getLLVMStyle();
Daniel Jaspereff18b92013-07-31 23:16:02 +0000295 Style.AccessModifierOffset = -4;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000296 Style.AlignTrailingComments = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000297 Style.BreakBeforeBinaryOperators = true;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000298 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000299 Style.BreakConstructorInitializersBeforeComma = true;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000300 Style.ColumnLimit = 0;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000301 Style.IndentWidth = 4;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000302 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000303 Style.PointerBindsToType = true;
304 return Style;
305}
306
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000307bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000308 if (Name.equals_lower("llvm"))
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000309 *Style = getLLVMStyle();
310 else if (Name.equals_lower("chromium"))
311 *Style = getChromiumStyle();
312 else if (Name.equals_lower("mozilla"))
313 *Style = getMozillaStyle();
314 else if (Name.equals_lower("google"))
315 *Style = getGoogleStyle();
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000316 else if (Name.equals_lower("webkit"))
317 *Style = getWebKitStyle();
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000318 else
319 return false;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000320
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000321 return true;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000322}
323
324llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienko107db3c2013-05-20 15:18:01 +0000325 if (Text.trim().empty())
326 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000327 llvm::yaml::Input Input(Text);
328 Input >> *Style;
329 return Input.error();
330}
331
332std::string configurationAsText(const FormatStyle &Style) {
333 std::string Text;
334 llvm::raw_string_ostream Stream(Text);
335 llvm::yaml::Output Output(Stream);
336 // We use the same mapping method for input and output, so we need a non-const
337 // reference here.
338 FormatStyle NonConstStyle = Style;
339 Output << NonConstStyle;
Alexander Kornienko2b6acb62013-05-13 12:56:35 +0000340 return Stream.str();
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000341}
342
Craig Topper83f81d72013-06-30 22:29:28 +0000343namespace {
344
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000345class NoColumnLimitFormatter {
346public:
Daniel Jasper34f3d052013-08-21 08:39:01 +0000347 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000348
349 /// \brief Formats the line starting at \p State, simply keeping all of the
350 /// input's line breaking decisions.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000351 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasperb77d7412013-09-06 07:54:20 +0000352 LineState State =
353 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000354 while (State.NextToken != NULL) {
355 bool Newline =
356 Indenter->mustBreak(State) ||
357 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
358 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
359 }
360 }
Daniel Jasper34f3d052013-08-21 08:39:01 +0000361
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000362private:
363 ContinuationIndenter *Indenter;
364};
365
Daniel Jasperbac016b2012-12-03 18:12:45 +0000366class UnwrappedLineFormatter {
367public:
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000368 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper567dcf92013-09-05 09:29:45 +0000369 WhitespaceManager *Whitespaces,
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000370 const FormatStyle &Style, const AnnotatedLine &Line)
Daniel Jasper567dcf92013-09-05 09:29:45 +0000371 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style), Line(Line),
372 Count(0) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000373
Daniel Jasper567dcf92013-09-05 09:29:45 +0000374 /// \brief Formats an \c UnwrappedLine and returns the penalty.
375 ///
376 /// If \p DryRun is \c false, directly applies the changes.
377 unsigned format(unsigned FirstIndent, bool DryRun = false) {
Daniel Jasperb77d7412013-09-06 07:54:20 +0000378 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000379
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000380 // If the ObjC method declaration does not fit on a line, we should format
381 // it with one arg per line.
382 if (Line.Type == LT_ObjCMethodDecl)
383 State.Stack.back().BreakBeforeParameter = true;
384
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000385 // Find best solution in solution space.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000386 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000387 }
388
389private:
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000390 /// \brief An edge in the solution space from \c Previous->State to \c State,
391 /// inserting a newline dependent on the \c NewLine.
392 struct StateNode {
393 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +0000394 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000395 LineState State;
396 bool NewLine;
397 StateNode *Previous;
398 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000399
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000400 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
401 ///
402 /// In case of equal penalties, we want to prefer states that were inserted
403 /// first. During state generation we make sure that we insert states first
404 /// that break the line as late as possible.
405 typedef std::pair<unsigned, unsigned> OrderedPenalty;
406
407 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
408 /// \c State has the given \c OrderedPenalty.
409 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
410
411 /// \brief The BFS queue type.
412 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
413 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000414
415 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000416 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000417 /// This implements a variant of Dijkstra's algorithm on the graph that spans
418 /// the solution space (\c LineStates are the nodes). The algorithm tries to
419 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper567dcf92013-09-05 09:29:45 +0000420 /// to a state where all tokens are placed. Returns the penalty.
421 ///
422 /// If \p DryRun is \c false, directly applies the changes.
423 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000424 std::set<LineState> Seen;
425
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000426 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +0000427 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000428 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
429 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
430 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000431
Daniel Jasper567dcf92013-09-05 09:29:45 +0000432 unsigned Penalty = 0;
433
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000434 // While not empty, take first element and follow edges.
435 while (!Queue.empty()) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000436 Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +0000437 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000438 if (Node->State.NextToken == NULL) {
Alexander Kornienkodd256312013-05-10 11:56:10 +0000439 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000440 break;
Daniel Jasper01786732013-02-04 07:21:18 +0000441 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000442 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000443
Daniel Jasper54b4e442013-05-22 05:27:42 +0000444 // Cut off the analysis of certain solutions if the analysis gets too
445 // complex. See description of IgnoreStackForComparison.
446 if (Count > 10000)
447 Node->State.IgnoreStackForComparison = true;
448
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000449 if (!Seen.insert(Node->State).second)
450 // State already examined with lower penalty.
451 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000452
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000453 FormatDecision LastFormat = Node->State.NextToken->Decision;
454 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
455 addNextStateToQueue(Penalty, Node, /*NewLine=*/false);
456 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
457 addNextStateToQueue(Penalty, Node, /*NewLine=*/true);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000458 }
459
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000460 if (Queue.empty()) {
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000461 // We were unable to find a solution, do nothing.
462 // FIXME: Add diagnostic?
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000463 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper567dcf92013-09-05 09:29:45 +0000464 return 0;
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000465 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000466
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000467 // Reconstruct the solution.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000468 if (!DryRun)
469 reconstructPath(InitialState, Queue.top().second);
470
Alexander Kornienkodd256312013-05-10 11:56:10 +0000471 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
472 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper567dcf92013-09-05 09:29:45 +0000473
474 return Penalty;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000475 }
476
477 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek9c333b92013-05-29 15:10:11 +0000478 std::deque<StateNode *> Path;
479 // We do not need a break before the initial token.
480 while (Current->Previous) {
481 Path.push_front(Current);
482 Current = Current->Previous;
483 }
484 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
485 I != E; ++I) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000486 unsigned Penalty = 0;
487 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
488 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
489
Manuel Klimek9c333b92013-05-29 15:10:11 +0000490 DEBUG({
491 if ((*I)->NewLine) {
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000492 llvm::dbgs() << "Penalty for placing "
Manuel Klimek9c333b92013-05-29 15:10:11 +0000493 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000494 << Penalty << "\n";
Manuel Klimek9c333b92013-05-29 15:10:11 +0000495 }
496 });
Manuel Klimek9c333b92013-05-29 15:10:11 +0000497 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000498 }
499
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000500 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000501 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000502 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000503 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000504 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
505 bool NewLine) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000506 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000507 return;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000508 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000509 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000510
511 StateNode *Node = new (Allocator.Allocate())
512 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000513 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
514 return;
515
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000516 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000517
518 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
519 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000520 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000521
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000522 /// \brief If the \p State's next token is an r_brace closing a nested block,
523 /// format the nested block before it.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000524 ///
525 /// Returns \c true if all children could be placed successfully and adapts
526 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
527 /// creates changes using \c Whitespaces.
528 ///
529 /// The crucial idea here is that children always get formatted upon
530 /// encountering the closing brace right after the nested block. Now, if we
531 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
532 /// \c false), the entire block has to be kept on the same line (which is only
533 /// possible if it fits on the line, only contains a single statement, etc.
534 ///
535 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
536 /// break after the "{", format all lines with correct indentation and the put
537 /// the closing "}" on yet another new line.
538 ///
539 /// This enables us to keep the simple structure of the
540 /// \c UnwrappedLineFormatter, where we only have two options for each token:
541 /// break or don't break.
542 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
543 unsigned &Penalty) {
Daniel Jasper15eef852013-10-20 17:28:32 +0000544 const FormatToken &Previous = *State.NextToken->Previous;
545 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
546 if (!LBrace || LBrace->isNot(tok::l_brace) ||
547 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasper1a925bc2013-09-05 10:48:50 +0000548 // The previous token does not open a block. Nothing to do. We don't
549 // assert so that we can simply call this function for all tokens.
Daniel Jasper2f0a0202013-09-06 08:54:24 +0000550 return true;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000551
552 if (NewLine) {
553 unsigned ParentIndent = State.Stack.back().Indent;
554 for (SmallVector<AnnotatedLine *, 1>::const_iterator
Daniel Jasper15eef852013-10-20 17:28:32 +0000555 I = Previous.Children.begin(),
556 E = Previous.Children.end();
Daniel Jasper567dcf92013-09-05 09:29:45 +0000557 I != E; ++I) {
558 unsigned Indent =
Daniel Jasper57981202013-09-13 09:20:45 +0000559 ParentIndent + ((*I)->Level - Line.Level - 1) * Style.IndentWidth;
Daniel Jasper14e25c02013-09-08 14:07:57 +0000560 if (!DryRun) {
561 unsigned Newlines = std::min((*I)->First->NewlinesBefore,
562 Style.MaxEmptyLinesToKeep + 1);
563 Newlines = std::max(1u, Newlines);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000564 Whitespaces->replaceWhitespace(
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000565 *(*I)->First, Newlines, (*I)->Level, /*Spaces=*/Indent,
Daniel Jasper567dcf92013-09-05 09:29:45 +0000566 /*StartOfTokenColumn=*/Indent, Line.InPPDirective);
Daniel Jasper14e25c02013-09-08 14:07:57 +0000567 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000568 UnwrappedLineFormatter Formatter(Indenter, Whitespaces, Style, **I);
569 Penalty += Formatter.format(Indent, DryRun);
570 }
571 return true;
572 }
573
Daniel Jasper15eef852013-10-20 17:28:32 +0000574 if (Previous.Children.size() > 1)
Daniel Jasper567dcf92013-09-05 09:29:45 +0000575 return false; // Cannot merge multiple statements into a single line.
576
577 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasper15eef852013-10-20 17:28:32 +0000578 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper567dcf92013-09-05 09:29:45 +0000579 return false;
580
581 if (!DryRun) {
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000582 Whitespaces->replaceWhitespace(
Daniel Jasper15eef852013-10-20 17:28:32 +0000583 *Previous.Children[0]->First,
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000584 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000585 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper14e25c02013-09-08 14:07:57 +0000586 UnwrappedLineFormatter Formatter(Indenter, Whitespaces, Style,
Daniel Jasper15eef852013-10-20 17:28:32 +0000587 *Previous.Children[0]);
Daniel Jasper14e25c02013-09-08 14:07:57 +0000588 Penalty += Formatter.format(State.Column + 1, DryRun);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000589 }
590
Daniel Jasper15eef852013-10-20 17:28:32 +0000591 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000592 return true;
593 }
594
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000595 ContinuationIndenter *Indenter;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000596 WhitespaceManager *Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000597 FormatStyle Style;
Daniel Jasper995e8202013-01-14 13:08:07 +0000598 const AnnotatedLine &Line;
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000599
600 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
601 QueueType Queue;
602 // Increasing count of \c StateNode items we have created. This is used
603 // to create a deterministic order independent of the container.
604 unsigned Count;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000605};
606
Manuel Klimek96e888b2013-05-28 11:55:06 +0000607class FormatTokenLexer {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000608public:
Manuel Klimekc41e8192013-08-29 15:21:40 +0000609 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienko00895102013-06-05 14:09:10 +0000610 encoding::Encoding Encoding)
Manuel Klimekc41e8192013-08-29 15:21:40 +0000611 : FormatTok(NULL), GreaterStashed(false), Column(0),
612 TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr), Style(Style),
613 IdentTable(getFormattingLangOpts()), Encoding(Encoding) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000614 Lex.SetKeepWhitespaceMode(true);
615 }
616
Manuel Klimek96e888b2013-05-28 11:55:06 +0000617 ArrayRef<FormatToken *> lex() {
618 assert(Tokens.empty());
619 do {
620 Tokens.push_back(getNextToken());
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000621 maybeJoinPreviousTokens();
Manuel Klimek96e888b2013-05-28 11:55:06 +0000622 } while (Tokens.back()->Tok.isNot(tok::eof));
623 return Tokens;
624 }
625
626 IdentifierTable &getIdentTable() { return IdentTable; }
627
628private:
Alexander Kornienko2c2f7292013-09-16 20:20:49 +0000629 void maybeJoinPreviousTokens() {
630 if (Tokens.size() < 4)
631 return;
632 FormatToken *Last = Tokens.back();
633 if (!Last->is(tok::r_paren))
634 return;
635
636 FormatToken *String = Tokens[Tokens.size() - 2];
637 if (!String->is(tok::string_literal) || String->IsMultiline)
638 return;
639
640 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
641 return;
642
643 FormatToken *Macro = Tokens[Tokens.size() - 4];
644 if (Macro->TokenText != "_T")
645 return;
646
647 const char *Start = Macro->TokenText.data();
648 const char *End = Last->TokenText.data() + Last->TokenText.size();
649 String->TokenText = StringRef(Start, End - Start);
650 String->IsFirst = Macro->IsFirst;
651 String->LastNewlineOffset = Macro->LastNewlineOffset;
652 String->WhitespaceRange = Macro->WhitespaceRange;
653 String->OriginalColumn = Macro->OriginalColumn;
654 String->ColumnWidth = encoding::columnWidthWithTabs(
655 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
656
657 Tokens.pop_back();
658 Tokens.pop_back();
659 Tokens.pop_back();
660 Tokens.back() = String;
661 }
662
Manuel Klimek96e888b2013-05-28 11:55:06 +0000663 FormatToken *getNextToken() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000664 if (GreaterStashed) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000665 // Create a synthesized second '>' token.
Manuel Klimekc41e8192013-08-29 15:21:40 +0000666 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000667 Token Greater = FormatTok->Tok;
668 FormatTok = new (Allocator.Allocate()) FormatToken;
669 FormatTok->Tok = Greater;
Manuel Klimekad3094b2013-05-23 10:56:37 +0000670 SourceLocation GreaterLocation =
Manuel Klimek96e888b2013-05-28 11:55:06 +0000671 FormatTok->Tok.getLocation().getLocWithOffset(1);
672 FormatTok->WhitespaceRange =
673 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000674 FormatTok->TokenText = ">";
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000675 FormatTok->ColumnWidth = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000676 GreaterStashed = false;
677 return FormatTok;
678 }
679
Manuel Klimek96e888b2013-05-28 11:55:06 +0000680 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper561211d2013-07-16 20:28:33 +0000681 readRawToken(*FormatTok);
Manuel Klimekde008c02013-05-27 15:23:34 +0000682 SourceLocation WhitespaceStart =
Manuel Klimek96e888b2013-05-28 11:55:06 +0000683 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Manuel Klimekad3094b2013-05-23 10:56:37 +0000684 if (SourceMgr.getFileOffset(WhitespaceStart) == 0)
Manuel Klimek96e888b2013-05-28 11:55:06 +0000685 FormatTok->IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000686
687 // Consume and record whitespace until we find a significant token.
Manuel Klimekde008c02013-05-27 15:23:34 +0000688 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek96e888b2013-05-28 11:55:06 +0000689 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000690 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
691 switch (FormatTok->TokenText[i]) {
692 case '\n':
693 ++FormatTok->NewlinesBefore;
694 // FIXME: This is technically incorrect, as it could also
695 // be a literal backslash at the end of the line.
Alexander Kornienko73d845c2013-09-11 12:25:57 +0000696 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
697 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
698 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimekc41e8192013-08-29 15:21:40 +0000699 FormatTok->HasUnescapedNewline = true;
700 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
701 Column = 0;
702 break;
Daniel Jasper1d82b1a2013-10-11 19:45:02 +0000703 case '\r':
704 case '\f':
705 case '\v':
706 Column = 0;
707 break;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000708 case ' ':
709 ++Column;
710 break;
711 case '\t':
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000712 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000713 break;
Daniel Jasper1d82b1a2013-10-11 19:45:02 +0000714 case '\\':
715 ++Column;
716 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
717 FormatTok->TokenText[i + 1] != '\n'))
718 FormatTok->Type = TT_ImplicitStringLiteral;
719 break;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000720 default:
Daniel Jasper1d82b1a2013-10-11 19:45:02 +0000721 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000722 ++Column;
723 break;
724 }
725 }
726
Daniel Jasper1d82b1a2013-10-11 19:45:02 +0000727 if (FormatTok->Type == TT_ImplicitStringLiteral)
728 break;
Manuel Klimek96e888b2013-05-28 11:55:06 +0000729 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000730
Daniel Jasper561211d2013-07-16 20:28:33 +0000731 readRawToken(*FormatTok);
Manuel Klimekd4397b92013-01-04 23:34:14 +0000732 }
Manuel Klimek95419382013-01-07 07:56:50 +0000733
Manuel Klimekd4397b92013-01-04 23:34:14 +0000734 // In case the token starts with escaped newlines, we want to
735 // take them into account as whitespace - this pattern is quite frequent
736 // in macro definitions.
Manuel Klimekd4397b92013-01-04 23:34:14 +0000737 // FIXME: Add a more explicit test.
Daniel Jasper561211d2013-07-16 20:28:33 +0000738 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
739 FormatTok->TokenText[1] == '\n') {
Manuel Klimek96e888b2013-05-28 11:55:06 +0000740 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimekad3094b2013-05-23 10:56:37 +0000741 WhitespaceLength += 2;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000742 Column = 0;
Daniel Jasper561211d2013-07-16 20:28:33 +0000743 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000744 }
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000745
746 FormatTok->WhitespaceRange = SourceRange(
747 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
748
Manuel Klimekc41e8192013-08-29 15:21:40 +0000749 FormatTok->OriginalColumn = Column;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000750
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000751 TrailingWhitespace = 0;
752 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000753 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper561211d2013-07-16 20:28:33 +0000754 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko51bb5d92013-09-06 17:24:54 +0000755 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper561211d2013-07-16 20:28:33 +0000756 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000757 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper561211d2013-07-16 20:28:33 +0000758 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek96e888b2013-05-28 11:55:06 +0000759 FormatTok->Tok.setIdentifierInfo(&Info);
760 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000761 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek96e888b2013-05-28 11:55:06 +0000762 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper561211d2013-07-16 20:28:33 +0000763 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000764 GreaterStashed = true;
765 }
766
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000767 // Now FormatTok is the next non-whitespace token.
Alexander Kornienko00895102013-06-05 14:09:10 +0000768
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000769 StringRef Text = FormatTok->TokenText;
770 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko6f6154c2013-09-10 12:29:48 +0000771 if (FirstNewlinePos == StringRef::npos) {
772 // FIXME: ColumnWidth actually depends on the start column, we need to
773 // take this into account when the token is moved.
774 FormatTok->ColumnWidth =
775 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
776 Column += FormatTok->ColumnWidth;
777 } else {
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000778 FormatTok->IsMultiline = true;
Alexander Kornienko6f6154c2013-09-10 12:29:48 +0000779 // FIXME: ColumnWidth actually depends on the start column, we need to
780 // take this into account when the token is moved.
781 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
782 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
783
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000784 // The last line of the token always starts in column 0.
785 // Thus, the length can be precomputed even in the presence of tabs.
786 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
787 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
788 Encoding);
Alexander Kornienko6f6154c2013-09-10 12:29:48 +0000789 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000790 }
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +0000791
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000792 return FormatTok;
793 }
794
Manuel Klimek96e888b2013-05-28 11:55:06 +0000795 FormatToken *FormatTok;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000796 bool GreaterStashed;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000797 unsigned Column;
Manuel Klimekde008c02013-05-27 15:23:34 +0000798 unsigned TrailingWhitespace;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000799 Lexer &Lex;
800 SourceManager &SourceMgr;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000801 FormatStyle &Style;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000802 IdentifierTable IdentTable;
Alexander Kornienko00895102013-06-05 14:09:10 +0000803 encoding::Encoding Encoding;
Manuel Klimek96e888b2013-05-28 11:55:06 +0000804 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
805 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000806
Daniel Jasper561211d2013-07-16 20:28:33 +0000807 void readRawToken(FormatToken &Tok) {
808 Lex.LexFromRawLexer(Tok.Tok);
809 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
810 Tok.Tok.getLength());
Daniel Jasper561211d2013-07-16 20:28:33 +0000811 // For formatting, treat unterminated string literals like normal string
812 // literals.
813 if (Tok.is(tok::unknown) && !Tok.TokenText.empty() &&
814 Tok.TokenText[0] == '"') {
815 Tok.Tok.setKind(tok::string_literal);
816 Tok.IsUnterminatedLiteral = true;
817 }
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000818 }
819};
820
Daniel Jasperbac016b2012-12-03 18:12:45 +0000821class Formatter : public UnwrappedLineConsumer {
822public:
Daniel Jaspercaf42a32013-05-15 08:14:19 +0000823 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000824 const std::vector<CharSourceRange> &Ranges)
Daniel Jaspercaf42a32013-05-15 08:14:19 +0000825 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko73d845c2013-09-11 12:25:57 +0000826 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000827 Ranges(Ranges), UnwrappedLines(1),
828 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasper9637dda2013-07-15 14:33:14 +0000829 DEBUG(llvm::dbgs() << "File encoding: "
830 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
831 : "unknown")
832 << "\n");
Alexander Kornienko00895102013-06-05 14:09:10 +0000833 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000834
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000835 tooling::Replacements format() {
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000836 tooling::Replacements Result;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000837 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek96e888b2013-05-28 11:55:06 +0000838
839 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek67d080d2013-04-12 14:13:36 +0000840 bool StructuralError = Parser.parse();
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000841 assert(UnwrappedLines.rbegin()->empty());
842 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
843 ++Run) {
844 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
845 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
846 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
847 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
848 }
849 tooling::Replacements RunResult =
850 format(AnnotatedLines, StructuralError, Tokens);
851 DEBUG({
852 llvm::dbgs() << "Replacements for run " << Run << ":\n";
853 for (tooling::Replacements::iterator I = RunResult.begin(),
854 E = RunResult.end();
855 I != E; ++I) {
856 llvm::dbgs() << I->toString() << "\n";
857 }
858 });
859 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
860 delete AnnotatedLines[i];
861 }
862 Result.insert(RunResult.begin(), RunResult.end());
863 Whitespaces.reset();
864 }
865 return Result;
866 }
867
868 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
869 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienko00895102013-06-05 14:09:10 +0000870 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000871 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000872 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000873 }
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000874 deriveLocalStyle(AnnotatedLines);
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000875 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000876 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000877 }
Daniel Jasper5999f762013-04-09 17:46:55 +0000878
Daniel Jasperb77d7412013-09-06 07:54:20 +0000879 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasper5999f762013-04-09 17:46:55 +0000880
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000881 std::vector<int> IndentForLevel;
882 bool PreviousLineWasTouched = false;
Daniel Jasper63cfb892013-10-06 11:40:08 +0000883 const AnnotatedLine *PreviousLine = NULL;
Daniel Jasper89b3a7f2013-05-10 13:00:49 +0000884 bool FormatPPDirective = false;
Daniel Jasperb77d7412013-09-06 07:54:20 +0000885 for (SmallVectorImpl<AnnotatedLine *>::iterator I = AnnotatedLines.begin(),
886 E = AnnotatedLines.end();
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000887 I != E; ++I) {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000888 const AnnotatedLine &TheLine = **I;
Manuel Klimekb3987012013-05-29 14:47:47 +0000889 const FormatToken *FirstTok = TheLine.First;
890 int Offset = getIndentOffset(*TheLine.First);
Daniel Jasper89b3a7f2013-05-10 13:00:49 +0000891
892 // Check whether this line is part of a formatted preprocessor directive.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000893 if (FirstTok->HasUnescapedNewline)
Daniel Jasper89b3a7f2013-05-10 13:00:49 +0000894 FormatPPDirective = false;
895 if (!FormatPPDirective && TheLine.InPPDirective &&
896 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
897 FormatPPDirective = true;
898
Daniel Jasper1fb8d882013-05-14 09:30:02 +0000899 // Determine indent and try to merge multiple unwrapped lines.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000900 while (IndentForLevel.size() <= TheLine.Level)
901 IndentForLevel.push_back(-1);
902 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper1fb8d882013-05-14 09:30:02 +0000903 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
904 if (static_cast<int>(Indent) + Offset >= 0)
905 Indent += Offset;
906 tryFitMultipleLinesInOne(Indent, I, E);
907
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000908 bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0;
Manuel Klimekb3987012013-05-29 14:47:47 +0000909 if (TheLine.First->is(tok::eof)) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000910 if (PreviousLineWasTouched) {
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000911 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
912 Whitespaces.replaceWhitespace(*TheLine.First, Newlines,
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000913 /*IndentLevel=*/0, /*Spaces=*/0,
914 /*TargetColumn=*/0);
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000915 }
916 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper89b3a7f2013-05-10 13:00:49 +0000917 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000918 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Daniel Jasper0baf33b2013-10-18 17:20:57 +0000919 if (FirstTok->WhitespaceRange.isValid()) {
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000920 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level, Indent,
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000921 TheLine.InPPDirective);
Manuel Klimek67d080d2013-04-12 14:13:36 +0000922 } else {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000923 Indent = LevelIndent = FirstTok->OriginalColumn;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000924 }
Daniel Jasper567dcf92013-09-05 09:29:45 +0000925 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000926 BinPackInconclusiveFunctions);
927
928 // If everything fits on a single line, just put it there.
929 unsigned ColumnLimit = Style.ColumnLimit;
Daniel Jasper567dcf92013-09-05 09:29:45 +0000930 AnnotatedLine *NextLine = *(I + 1);
931 if ((I + 1) != E && NextLine->InPPDirective &&
932 !NextLine->First->HasUnescapedNewline)
933 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000934
Daniel Jasper567dcf92013-09-05 09:29:45 +0000935 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
Daniel Jasperb77d7412013-09-06 07:54:20 +0000936 LineState State =
937 Indenter.getInitialState(Indent, &TheLine, /*DryRun=*/false);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000938 while (State.NextToken != NULL)
939 Indenter.addTokenToState(State, false, false);
940 } else if (Style.ColumnLimit == 0) {
941 NoColumnLimitFormatter Formatter(&Indenter);
Daniel Jasper567dcf92013-09-05 09:29:45 +0000942 Formatter.format(Indent, &TheLine);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000943 } else {
Daniel Jasper567dcf92013-09-05 09:29:45 +0000944 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style,
945 TheLine);
946 Formatter.format(Indent);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000947 }
948
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000949 IndentForLevel[TheLine.Level] = LevelIndent;
950 PreviousLineWasTouched = true;
951 } else {
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000952 // Format the first token if necessary, and notify the WhitespaceManager
953 // about the unchanged whitespace.
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000954 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000955 if (Tok == TheLine.First &&
956 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000957 unsigned LevelIndent = Tok->OriginalColumn;
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000958 // Remove trailing whitespace of the previous line if it was
959 // touched.
960 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000961 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000962 TheLine.InPPDirective);
963 } else {
Manuel Klimekb3987012013-05-29 14:47:47 +0000964 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000965 }
Daniel Jasper1fb8d882013-05-14 09:30:02 +0000966
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000967 if (static_cast<int>(LevelIndent) - Offset >= 0)
968 LevelIndent -= Offset;
969 if (Tok->isNot(tok::comment))
970 IndentForLevel[TheLine.Level] = LevelIndent;
971 } else {
Manuel Klimekb3987012013-05-29 14:47:47 +0000972 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000973 }
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000974 }
975 // If we did not reformat this unwrapped line, the column at the end of
976 // the last token is unchanged - thus, we can calculate the end of the
977 // last token.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000978 PreviousLineWasTouched = false;
979 }
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000980 for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
981 Tok->Finalized = true;
982 }
Daniel Jasper63cfb892013-10-06 11:40:08 +0000983 PreviousLine = *I;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000984 }
985 return Whitespaces.generateReplacements();
986 }
987
988private:
Alexander Kornienko73d845c2013-09-11 12:25:57 +0000989 static bool inputUsesCRLF(StringRef Text) {
990 return Text.count('\r') * 2 > Text.count('\n');
991 }
992
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000993 void
994 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000995 unsigned CountBoundToVariable = 0;
996 unsigned CountBoundToType = 0;
997 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000998 bool HasBinPackedFunction = false;
999 bool HasOnePerLineFunction = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001000 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001001 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001002 continue;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001003 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimekb3987012013-05-29 14:47:47 +00001004 while (Tok->Next) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001005 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001006 bool SpacesBefore =
1007 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1008 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1009 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001010 if (SpacesBefore && !SpacesAfter)
1011 ++CountBoundToVariable;
1012 else if (!SpacesBefore && SpacesAfter)
1013 ++CountBoundToType;
1014 }
1015
Daniel Jasper78a4e612013-10-12 05:16:06 +00001016 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1017 if (Tok->is(tok::coloncolon) &&
1018 Tok->Previous->Type == TT_TemplateOpener)
1019 HasCpp03IncompatibleFormat = true;
1020 if (Tok->Type == TT_TemplateCloser &&
1021 Tok->Previous->Type == TT_TemplateCloser)
1022 HasCpp03IncompatibleFormat = true;
1023 }
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001024
1025 if (Tok->PackingKind == PPK_BinPacked)
1026 HasBinPackedFunction = true;
1027 if (Tok->PackingKind == PPK_OnePerLine)
1028 HasOnePerLineFunction = true;
1029
Manuel Klimekb3987012013-05-29 14:47:47 +00001030 Tok = Tok->Next;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001031 }
1032 }
1033 if (Style.DerivePointerBinding) {
1034 if (CountBoundToType > CountBoundToVariable)
1035 Style.PointerBindsToType = true;
1036 else if (CountBoundToType < CountBoundToVariable)
1037 Style.PointerBindsToType = false;
1038 }
1039 if (Style.Standard == FormatStyle::LS_Auto) {
1040 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1041 : FormatStyle::LS_Cpp03;
1042 }
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001043 BinPackInconclusiveFunctions =
1044 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001045 }
1046
Manuel Klimek547d5db2013-02-08 17:38:27 +00001047 /// \brief Get the indent of \p Level from \p IndentForLevel.
1048 ///
1049 /// \p IndentForLevel must contain the indent for the level \c l
1050 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1051 /// that level is unknown.
Daniel Jasperfc759082013-02-14 14:26:07 +00001052 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimek547d5db2013-02-08 17:38:27 +00001053 if (IndentForLevel[Level] != -1)
1054 return IndentForLevel[Level];
Manuel Klimek52635ff2013-02-08 19:53:32 +00001055 if (Level == 0)
1056 return 0;
Manuel Klimek07a64ec2013-05-13 08:42:42 +00001057 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimek547d5db2013-02-08 17:38:27 +00001058 }
1059
1060 /// \brief Get the offset of the line relatively to the level.
1061 ///
1062 /// For example, 'public:' labels in classes are offset by 1 or 2
1063 /// characters to the left from their level.
Manuel Klimekb3987012013-05-29 14:47:47 +00001064 int getIndentOffset(const FormatToken &RootToken) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001065 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimek547d5db2013-02-08 17:38:27 +00001066 return Style.AccessModifierOffset;
1067 return 0;
1068 }
1069
Manuel Klimek517e8942013-01-11 17:54:10 +00001070 /// \brief Tries to merge lines into one.
1071 ///
1072 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1073 /// if possible; note that \c I will be incremented when lines are merged.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001074 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperb77d7412013-09-06 07:54:20 +00001075 SmallVectorImpl<AnnotatedLine *>::iterator &I,
1076 SmallVectorImpl<AnnotatedLine *>::iterator E) {
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001077 // We can never merge stuff if there are trailing line comments.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001078 AnnotatedLine *TheLine = *I;
1079 if (TheLine->Last->Type == TT_LineComment)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001080 return;
1081
Daniel Jaspere05dc6d2013-07-24 13:10:59 +00001082 if (Indent > Style.ColumnLimit)
1083 return;
1084
Daniel Jaspera4d46212013-02-28 11:05:57 +00001085 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001086 // If we already exceed the column limit, we set 'Limit' to 0. The different
1087 // tryMerge..() functions can then decide whether to still do merging.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001088 Limit = TheLine->Last->TotalLength > Limit
1089 ? 0
1090 : Limit - TheLine->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001091
Daniel Jasper567dcf92013-09-05 09:29:45 +00001092 if (I + 1 == E || (*(I + 1))->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001093 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001094
Daniel Jasper567dcf92013-09-05 09:29:45 +00001095 if (TheLine->Last->is(tok::l_brace)) {
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001096 tryMergeSimpleBlock(I, E, Limit);
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001097 } else if (Style.AllowShortIfStatementsOnASingleLine &&
Daniel Jasper567dcf92013-09-05 09:29:45 +00001098 TheLine->First->is(tok::kw_if)) {
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001099 tryMergeSimpleControlStatement(I, E, Limit);
1100 } else if (Style.AllowShortLoopsOnASingleLine &&
Daniel Jasper567dcf92013-09-05 09:29:45 +00001101 TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001102 tryMergeSimpleControlStatement(I, E, Limit);
Daniel Jasper567dcf92013-09-05 09:29:45 +00001103 } else if (TheLine->InPPDirective && (TheLine->First->HasUnescapedNewline ||
1104 TheLine->First->IsFirst)) {
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001105 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001106 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001107 }
1108
Daniel Jasperb77d7412013-09-06 07:54:20 +00001109 void tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::iterator &I,
1110 SmallVectorImpl<AnnotatedLine *>::iterator E,
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001111 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001112 if (Limit == 0)
1113 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001114 AnnotatedLine &Line = **I;
1115 if (!(*(I + 1))->InPPDirective || (*(I + 1))->First->HasUnescapedNewline)
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001116 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001117 if (I + 2 != E && (*(I + 2))->InPPDirective &&
1118 !(*(I + 2))->First->HasUnescapedNewline)
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001119 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001120 if (1 + (*(I + 1))->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001121 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001122 join(Line, **(++I));
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001123 }
1124
Daniel Jasperb77d7412013-09-06 07:54:20 +00001125 void
1126 tryMergeSimpleControlStatement(SmallVectorImpl<AnnotatedLine *>::iterator &I,
1127 SmallVectorImpl<AnnotatedLine *>::iterator E,
1128 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001129 if (Limit == 0)
1130 return;
Manuel Klimekd3a247c2013-08-07 19:20:45 +00001131 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman &&
Daniel Jasper567dcf92013-09-05 09:29:45 +00001132 (*(I + 1))->First->is(tok::l_brace))
Manuel Klimekd3a247c2013-08-07 19:20:45 +00001133 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001134 if ((*(I + 1))->InPPDirective != (*I)->InPPDirective ||
1135 ((*(I + 1))->InPPDirective && (*(I + 1))->First->HasUnescapedNewline))
Manuel Klimek4c128122013-01-18 14:46:43 +00001136 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001137 AnnotatedLine &Line = **I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001138 if (Line.Last->isNot(tok::r_paren))
1139 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001140 if (1 + (*(I + 1))->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001141 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001142 if ((*(I + 1))->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
1143 tok::kw_while) ||
1144 (*(I + 1))->First->Type == TT_LineComment)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001145 return;
1146 // Only inline simple if's (no nested if or else).
Manuel Klimekb3987012013-05-29 14:47:47 +00001147 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Daniel Jasper567dcf92013-09-05 09:29:45 +00001148 (*(I + 2))->First->is(tok::kw_else))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001149 return;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001150 join(Line, **(++I));
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001151 }
1152
Daniel Jasperb77d7412013-09-06 07:54:20 +00001153 void tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::iterator &I,
1154 SmallVectorImpl<AnnotatedLine *>::iterator E,
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001155 unsigned Limit) {
Daniel Jasper5be59ba2013-05-15 14:09:55 +00001156 // No merging if the brace already is on the next line.
1157 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
1158 return;
1159
Manuel Klimek517e8942013-01-11 17:54:10 +00001160 // First, check that the current line allows merging. This is the case if
1161 // we're not in a control flow statement and the last token is an opening
1162 // brace.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001163 AnnotatedLine &Line = **I;
Manuel Klimekb3987012013-05-29 14:47:47 +00001164 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1165 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001166 tok::kw_for,
Manuel Klimekb3987012013-05-29 14:47:47 +00001167 // This gets rid of all ObjC @ keywords and methods.
1168 tok::at, tok::minus, tok::plus))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001169 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001170
Daniel Jasper567dcf92013-09-05 09:29:45 +00001171 FormatToken *Tok = (*(I + 1))->First;
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001172 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001173 (Tok->getNextNonComment() == NULL ||
1174 Tok->getNextNonComment()->is(tok::semi))) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001175 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jasper729a7432013-02-11 12:36:37 +00001176 Tok->SpacesRequiredBefore = 0;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001177 Tok->CanBreakBefore = true;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001178 join(Line, **(I + 1));
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001179 I += 1;
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001180 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001181 // Check that we still have three lines and they fit into the limit.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001182 if (I + 2 == E || (*(I + 2))->Type == LT_Invalid ||
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001183 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001184 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001185
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001186 // Second, check that the next line does not contain any braces - if it
1187 // does, readability declines when putting it into a single line.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001188 if ((*(I + 1))->Last->Type == TT_LineComment || Tok->MustBreakBefore)
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001189 return;
1190 do {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001191 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001192 return;
Manuel Klimekb3987012013-05-29 14:47:47 +00001193 Tok = Tok->Next;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001194 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001195
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001196 // Last, check that the third line contains a single closing brace.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001197 Tok = (*(I + 2))->First;
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001198 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001199 Tok->MustBreakBefore)
1200 return;
1201
Daniel Jasper567dcf92013-09-05 09:29:45 +00001202 join(Line, **(I + 1));
1203 join(Line, **(I + 2));
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001204 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +00001205 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001206 }
1207
Daniel Jasperb77d7412013-09-06 07:54:20 +00001208 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::iterator I,
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001209 unsigned Limit) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001210 return 1 + (*(I + 1))->Last->TotalLength + 1 +
1211 (*(I + 2))->Last->TotalLength <=
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001212 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001213 }
1214
Daniel Jasper995e8202013-01-14 13:08:07 +00001215 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001216 assert(!A.Last->Next);
1217 assert(!B.First->Previous);
1218 A.Last->Next = B.First;
1219 B.First->Previous = A.Last;
1220 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1221 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1222 Tok->TotalLength += LengthA;
1223 A.Last = Tok;
Daniel Jasper995e8202013-01-14 13:08:07 +00001224 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001225 }
1226
Daniel Jasper6f21a982013-03-13 07:49:51 +00001227 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf3023542013-03-07 20:50:00 +00001228 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1229 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1230 Ranges[i].getBegin()) &&
1231 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1232 Range.getBegin()))
1233 return true;
1234 }
1235 return false;
1236 }
1237
1238 bool touchesLine(const AnnotatedLine &TheLine) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001239 const FormatToken *First = TheLine.First;
1240 const FormatToken *Last = TheLine.Last;
Daniel Jasper84f5ddf2013-05-14 10:31:09 +00001241 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001242 First->WhitespaceRange.getBegin().getLocWithOffset(
1243 First->LastNewlineOffset),
Alexander Kornienko2c2f7292013-09-16 20:20:49 +00001244 Last->getStartOfNonWhitespace().getLocWithOffset(
1245 Last->TokenText.size() - 1));
Daniel Jasperf3023542013-03-07 20:50:00 +00001246 return touchesRanges(LineRange);
1247 }
1248
Daniel Jasperb77d7412013-09-06 07:54:20 +00001249 bool touchesPPDirective(SmallVectorImpl<AnnotatedLine *>::iterator I,
1250 SmallVectorImpl<AnnotatedLine *>::iterator E) {
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001251 for (; I != E; ++I) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001252 if ((*I)->First->HasUnescapedNewline)
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001253 return false;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001254 if (touchesLine(**I))
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001255 return true;
1256 }
1257 return false;
1258 }
1259
Daniel Jasperf3023542013-03-07 20:50:00 +00001260 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001261 const FormatToken *First = TheLine.First;
Daniel Jasperf3023542013-03-07 20:50:00 +00001262 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001263 First->WhitespaceRange.getBegin(),
1264 First->WhitespaceRange.getBegin().getLocWithOffset(
1265 First->LastNewlineOffset));
Daniel Jasperf3023542013-03-07 20:50:00 +00001266 return touchesRanges(LineRange);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001267 }
1268
1269 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001270 assert(!UnwrappedLines.empty());
1271 UnwrappedLines.back().push_back(TheLine);
1272 }
1273
1274 virtual void finishRun() {
1275 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperbac016b2012-12-03 18:12:45 +00001276 }
1277
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001278 /// \brief Add a new line and the required indent before the first Token
1279 /// of the \c UnwrappedLine if there was no structural parsing error.
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001280 void formatFirstToken(FormatToken &RootToken,
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +00001281 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
1282 unsigned Indent, bool InPPDirective) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001283 unsigned Newlines =
Manuel Klimekb3987012013-05-29 14:47:47 +00001284 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Daniel Jasper15f33f02013-06-03 16:16:41 +00001285 // Remove empty lines before "}" where applicable.
1286 if (RootToken.is(tok::r_brace) &&
1287 (!RootToken.Next ||
1288 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1289 Newlines = std::min(Newlines, 1u);
Manuel Klimekb3987012013-05-29 14:47:47 +00001290 if (Newlines == 0 && !RootToken.IsFirst)
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001291 Newlines = 1;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001292
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001293 // Insert extra new line before access specifiers.
Daniel Jasper63cfb892013-10-06 11:40:08 +00001294 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001295 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001296 ++Newlines;
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001297
Daniel Jasper63cfb892013-10-06 11:40:08 +00001298 // Remove empty lines after access specifiers.
1299 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
1300 Newlines = std::min(1u, Newlines);
1301
Manuel Klimekb3987012013-05-29 14:47:47 +00001302 Whitespaces.replaceWhitespace(
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +00001303 RootToken, Newlines, IndentLevel, Indent, Indent,
Manuel Klimekb3987012013-05-29 14:47:47 +00001304 InPPDirective && !RootToken.HasUnescapedNewline);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001305 }
1306
Daniel Jasper567dcf92013-09-05 09:29:45 +00001307 unsigned getColumnLimit(bool InPPDirective) const {
1308 // In preprocessor directives reserve two chars for trailing " \"
1309 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1310 }
1311
Daniel Jasperbac016b2012-12-03 18:12:45 +00001312 FormatStyle Style;
1313 Lexer &Lex;
1314 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001315 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001316 std::vector<CharSourceRange> Ranges;
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001317 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienko00895102013-06-05 14:09:10 +00001318
1319 encoding::Encoding Encoding;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001320 bool BinPackInconclusiveFunctions;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001321};
1322
Craig Topper83f81d72013-06-30 22:29:28 +00001323} // end anonymous namespace
1324
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001325tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1326 SourceManager &SourceMgr,
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001327 std::vector<CharSourceRange> Ranges) {
1328 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001329 return formatter.format();
1330}
1331
Daniel Jasper8a999452013-05-16 10:40:07 +00001332tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1333 std::vector<tooling::Range> Ranges,
1334 StringRef FileName) {
1335 FileManager Files((FileSystemOptions()));
1336 DiagnosticsEngine Diagnostics(
1337 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1338 new DiagnosticOptions);
1339 SourceManager SourceMgr(Diagnostics, Files);
1340 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1341 const clang::FileEntry *Entry =
1342 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1343 SourceMgr.overrideFileContents(Entry, Buf);
1344 FileID ID =
1345 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001346 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1347 getFormattingLangOpts(Style.Standard));
Daniel Jasper8a999452013-05-16 10:40:07 +00001348 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1349 std::vector<CharSourceRange> CharRanges;
1350 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1351 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1352 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1353 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1354 }
1355 return reformat(Style, Lex, SourceMgr, CharRanges);
1356}
1357
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001358LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasper46ef8522013-01-10 13:08:12 +00001359 LangOptions LangOpts;
1360 LangOpts.CPlusPlus = 1;
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001361 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasperb64eca02013-03-22 10:01:29 +00001362 LangOpts.LineComment = 1;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001363 LangOpts.Bool = 1;
1364 LangOpts.ObjC1 = 1;
1365 LangOpts.ObjC2 = 1;
1366 return LangOpts;
1367}
1368
Edwin Vanef4e12c82013-09-30 13:31:48 +00001369const char *StyleOptionHelpDescription =
1370 "Coding style, currently supports:\n"
1371 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1372 "Use -style=file to load style configuration from\n"
1373 ".clang-format file located in one of the parent\n"
1374 "directories of the source file (or current\n"
1375 "directory for stdin).\n"
1376 "Use -style=\"{key: value, ...}\" to set specific\n"
1377 "parameters, e.g.:\n"
1378 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1379
1380FormatStyle getStyle(StringRef StyleName, StringRef FileName) {
1381 // Fallback style in case the rest of this function can't determine a style.
1382 StringRef FallbackStyle = "LLVM";
1383 FormatStyle Style;
1384 getPredefinedStyle(FallbackStyle, &Style);
1385
1386 if (StyleName.startswith("{")) {
1387 // Parse YAML/JSON style from the command line.
1388 if (llvm::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +00001389 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1390 << FallbackStyle << " style\n";
Edwin Vanef4e12c82013-09-30 13:31:48 +00001391 }
1392 return Style;
1393 }
1394
1395 if (!StyleName.equals_lower("file")) {
1396 if (!getPredefinedStyle(StyleName, &Style))
1397 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1398 << " style\n";
1399 return Style;
1400 }
1401
1402 SmallString<128> Path(FileName);
1403 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +00001404 for (StringRef Directory = Path; !Directory.empty();
Edwin Vanef4e12c82013-09-30 13:31:48 +00001405 Directory = llvm::sys::path::parent_path(Directory)) {
1406 if (!llvm::sys::fs::is_directory(Directory))
1407 continue;
1408 SmallString<128> ConfigFile(Directory);
1409
1410 llvm::sys::path::append(ConfigFile, ".clang-format");
1411 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1412 bool IsFile = false;
1413 // Ignore errors from is_regular_file: we only need to know if we can read
1414 // the file or not.
1415 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1416
1417 if (!IsFile) {
1418 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1419 ConfigFile = Directory;
1420 llvm::sys::path::append(ConfigFile, "_clang-format");
1421 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1422 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1423 }
1424
1425 if (IsFile) {
1426 OwningPtr<llvm::MemoryBuffer> Text;
1427 if (llvm::error_code ec = llvm::MemoryBuffer::getFile(ConfigFile, Text)) {
1428 llvm::errs() << ec.message() << "\n";
1429 continue;
1430 }
1431 if (llvm::error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
1432 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
1433 << "\n";
1434 continue;
1435 }
1436 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
1437 return Style;
1438 }
1439 }
1440 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
1441 << " style\n";
1442 return Style;
1443}
1444
Daniel Jaspercd162382013-01-07 13:26:07 +00001445} // namespace format
1446} // namespace clang