blob: d408b3862b1efc5b48d49789a90b143039f1195b [file] [log] [blame]
Daniel Jasperf7935112012-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 Jasperf7935112012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimek24998102013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Daniel Jasperde0328a2013-08-16 11:20:30 +000018#include "ContinuationIndenter.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000019#include "TokenAnnotator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000021#include "WhitespaceManager.h"
Daniel Jasperec04c0d2013-05-16 10:40:07 +000022#include "clang/Basic/Diagnostic.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000023#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000024#include "clang/Format/Format.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000026#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000027#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Alexander Kornienkod6538332013-05-07 15:32:14 +000029#include "llvm/Support/YAMLTraits.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000030#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000031#include <string>
32
Alexander Kornienkod6538332013-05-07 15:32:14 +000033namespace llvm {
34namespace yaml {
35template <>
36struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +000037 static void enumeration(IO &IO,
38 clang::format::FormatStyle::LanguageStandard &Value) {
Alexander Kornienkob40cfe42013-09-04 14:09:13 +000039 IO.enumCase(Value, "Cpp03", clang::format::FormatStyle::LS_Cpp03);
Manuel Klimeka8eb9142013-05-13 12:51:40 +000040 IO.enumCase(Value, "C++03", clang::format::FormatStyle::LS_Cpp03);
Alexander Kornienkob40cfe42013-09-04 14:09:13 +000041 IO.enumCase(Value, "Cpp11", clang::format::FormatStyle::LS_Cpp11);
Manuel Klimeka8eb9142013-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 Jasper12f9d8e2013-05-14 09:30:02 +000047template <>
Manuel Klimeka8eb9142013-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 Klimekd3ed59a2013-08-02 21:31:59 +000054 IO.enumCase(Value, "Allman", clang::format::FormatStyle::BS_Allman);
Alexander Kornienkod6538332013-05-07 15:32:14 +000055 }
56};
57
Daniel Jasper65ee3472013-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 Kornienkod6538332013-05-07 15:32:14 +000070template <> struct MappingTraits<clang::format::FormatStyle> {
71 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
Alexander Kornienko49149672013-05-10 11:56:10 +000072 if (IO.outputting()) {
Alexander Kornienkoe3648fb2013-09-02 16:39:23 +000073 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
74 "Mozilla", "WebKit" };
Alexander Kornienko49149672013-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 Kornienko006b5c82013-05-19 00:53:30 +000078 clang::format::FormatStyle PredefinedStyle;
79 if (clang::format::getPredefinedStyle(StyleName, &PredefinedStyle) &&
80 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +000081 IO.mapOptional("# BasedOnStyle", StyleName);
82 break;
83 }
84 }
85 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +000086 StringRef BasedOnStyle;
87 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +000088 if (!BasedOnStyle.empty())
Alexander Kornienko006b5c82013-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 Kornienkod6538332013-05-07 15:32:14 +000093 }
94
95 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jaspercdaffa42013-08-13 10:58:30 +000096 IO.mapOptional("ConstructorInitializerIndentWidth",
97 Style.ConstructorInitializerIndentWidth);
Alexander Kornienkod6538332013-05-07 15:32:14 +000098 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper552f4a72013-07-31 23:55:15 +000099 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000100 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
101 Style.AllowAllParametersOfDeclarationOnNextLine);
102 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
103 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000104 IO.mapOptional("AllowShortLoopsOnASingleLine",
105 Style.AllowShortLoopsOnASingleLine);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000106 IO.mapOptional("AlwaysBreakTemplateDeclarations",
107 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko58611712013-07-04 12:02:44 +0000108 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
109 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000110 IO.mapOptional("BreakBeforeBinaryOperators",
111 Style.BreakBeforeBinaryOperators);
112 IO.mapOptional("BreakConstructorInitializersBeforeComma",
113 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-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 Jasperb10cbc42013-07-10 14:02:49 +0000119 IO.mapOptional("ExperimentalAutoDetectBinPacking",
120 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000121 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
122 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000123 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000124 IO.mapOptional("ObjCSpaceBeforeProtocolList",
125 Style.ObjCSpaceBeforeProtocolList);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000126 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
127 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000128 IO.mapOptional("PenaltyBreakFirstLessLess",
129 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-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 Jasper6ab54682013-07-16 18:22:10 +0000136 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000137 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000138 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000139 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000140 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000141 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimek836c2862013-06-21 17:25:42 +0000142 IO.mapOptional("IndentFunctionDeclarationAfterType",
143 Style.IndentFunctionDeclarationAfterType);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000144 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperf110e202013-08-21 08:39:01 +0000145 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000146 IO.mapOptional("SpacesInCStyleCastParentheses",
147 Style.SpacesInCStyleCastParentheses);
148 IO.mapOptional("SpaceAfterControlStatementKeyword",
149 Style.SpaceAfterControlStatementKeyword);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000150 }
151};
152}
153}
154
Daniel Jasperf7935112012-12-03 18:12:45 +0000155namespace clang {
156namespace format {
157
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000158void setDefaultPenalties(FormatStyle &Style) {
Daniel Jasper2739af32013-08-28 10:03:58 +0000159 Style.PenaltyBreakComment = 60;
Daniel Jasperfa21c072013-07-15 14:33:14 +0000160 Style.PenaltyBreakFirstLessLess = 120;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000161 Style.PenaltyBreakString = 1000;
162 Style.PenaltyExcessCharacter = 1000000;
163}
164
Daniel Jasperf7935112012-12-03 18:12:45 +0000165FormatStyle getLLVMStyle() {
166 FormatStyle LLVMStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000167 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000168 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000169 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000170 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000171 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000172 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000173 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000174 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000175 LLVMStyle.BinPackParameters = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000176 LLVMStyle.BreakBeforeBinaryOperators = false;
177 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
178 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000179 LLVMStyle.ColumnLimit = 80;
180 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000181 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000182 LLVMStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000183 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000184 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000185 LLVMStyle.IndentCaseLabels = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000186 LLVMStyle.IndentFunctionDeclarationAfterType = false;
187 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000188 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000189 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000190 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Webera6087752013-01-10 20:12:55 +0000191 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000192 LLVMStyle.PointerBindsToType = false;
193 LLVMStyle.SpacesBeforeTrailingComments = 1;
194 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000195 LLVMStyle.UseTab = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000196 LLVMStyle.SpacesInParentheses = false;
197 LLVMStyle.SpaceInEmptyParentheses = false;
198 LLVMStyle.SpacesInCStyleCastParentheses = false;
199 LLVMStyle.SpaceAfterControlStatementKeyword = true;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000200
201 setDefaultPenalties(LLVMStyle);
202 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
203
Daniel Jasperf7935112012-12-03 18:12:45 +0000204 return LLVMStyle;
205}
206
207FormatStyle getGoogleStyle() {
208 FormatStyle GoogleStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000209 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000210 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000211 GoogleStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000212 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000213 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000214 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000215 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000216 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000217 GoogleStyle.BinPackParameters = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000218 GoogleStyle.BreakBeforeBinaryOperators = false;
219 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
220 GoogleStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000221 GoogleStyle.ColumnLimit = 80;
222 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000223 GoogleStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000224 GoogleStyle.Cpp11BracedListStyle = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000225 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000226 GoogleStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000227 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000228 GoogleStyle.IndentFunctionDeclarationAfterType = true;
229 GoogleStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000230 GoogleStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000231 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000232 GoogleStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Webera6087752013-01-10 20:12:55 +0000233 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000234 GoogleStyle.PointerBindsToType = true;
235 GoogleStyle.SpacesBeforeTrailingComments = 2;
236 GoogleStyle.Standard = FormatStyle::LS_Auto;
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000237 GoogleStyle.UseTab = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000238 GoogleStyle.SpacesInParentheses = false;
239 GoogleStyle.SpaceInEmptyParentheses = false;
240 GoogleStyle.SpacesInCStyleCastParentheses = false;
241 GoogleStyle.SpaceAfterControlStatementKeyword = true;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000242
243 setDefaultPenalties(GoogleStyle);
244 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
245
Daniel Jasperf7935112012-12-03 18:12:45 +0000246 return GoogleStyle;
247}
248
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000249FormatStyle getChromiumStyle() {
250 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +0000251 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000252 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000253 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000254 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000255 ChromiumStyle.DerivePointerBinding = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000256 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000257 return ChromiumStyle;
258}
259
Alexander Kornienkoc8602662013-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 Jasperffefb3d2013-07-24 13:10:59 +0000272FormatStyle getWebKitStyle() {
273 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000274 Style.AccessModifierOffset = -4;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000275 Style.AlignTrailingComments = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000276 Style.BreakBeforeBinaryOperators = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000277 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000278 Style.BreakConstructorInitializersBeforeComma = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000279 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000280 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000281 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000282 Style.PointerBindsToType = true;
283 return Style;
284}
285
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000286bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000287 if (Name.equals_lower("llvm"))
Alexander Kornienko006b5c82013-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 Jasperffefb3d2013-07-24 13:10:59 +0000295 else if (Name.equals_lower("webkit"))
296 *Style = getWebKitStyle();
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000297 else
298 return false;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000299
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000300 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000301}
302
303llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienko06e00332013-05-20 15:18:01 +0000304 if (Text.trim().empty())
305 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkod6538332013-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 Kornienko9a38ec22013-05-13 12:56:35 +0000319 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000320}
321
Craig Topperaf35e852013-06-30 22:29:28 +0000322namespace {
323
Daniel Jasperde0328a2013-08-16 11:20:30 +0000324class NoColumnLimitFormatter {
325public:
Daniel Jasperf110e202013-08-21 08:39:01 +0000326 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasperde0328a2013-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 Jasper9fe0e8d2013-09-05 09:29:45 +0000330 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000331 LineState State =
332 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Daniel Jasperde0328a2013-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 Jasperf110e202013-08-21 08:39:01 +0000340
Daniel Jasperde0328a2013-08-16 11:20:30 +0000341private:
342 ContinuationIndenter *Indenter;
343};
344
Daniel Jasperf7935112012-12-03 18:12:45 +0000345class UnwrappedLineFormatter {
346public:
Daniel Jasperde0328a2013-08-16 11:20:30 +0000347 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000348 WhitespaceManager *Whitespaces,
Daniel Jasperde0328a2013-08-16 11:20:30 +0000349 const FormatStyle &Style, const AnnotatedLine &Line)
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000350 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style), Line(Line),
351 Count(0) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000352
Daniel Jasper9fe0e8d2013-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 Jasper1c5d9df2013-09-06 07:54:20 +0000357 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +0000358
Daniel Jasperacc33662013-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 Jasper4b866272013-02-01 11:00:45 +0000364 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000365 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +0000366 }
367
368private:
Manuel Klimek2ef908e2013-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 Jasper12ef4e52013-02-21 21:33:55 +0000373 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000374 LineState State;
375 bool NewLine;
376 StateNode *Previous;
377 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000378
Manuel Klimek2ef908e2013-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 Jasper4b866272013-02-01 11:00:45 +0000393
394 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000395 ///
Daniel Jasper4b866272013-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 Jasper9fe0e8d2013-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 Klimek2ef908e2013-02-13 10:46:36 +0000403 std::set<LineState> Seen;
404
Daniel Jasper4b866272013-02-01 11:00:45 +0000405 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000406 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000407 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
408 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
409 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000410
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000411 unsigned Penalty = 0;
412
Daniel Jasper4b866272013-02-01 11:00:45 +0000413 // While not empty, take first element and follow edges.
414 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000415 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000416 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000417 if (Node->State.NextToken == NULL) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000418 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000419 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000420 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000421 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000422
Daniel Jasperf8114cf2013-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 Klimek2ef908e2013-02-13 10:46:36 +0000428 if (!Seen.insert(Node->State).second)
429 // State already examined with lower penalty.
430 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000431
Nico Weber9096fc02013-06-26 00:30:14 +0000432 addNextStateToQueue(Penalty, Node, /*NewLine=*/false);
433 addNextStateToQueue(Penalty, Node, /*NewLine=*/true);
Daniel Jasper4b866272013-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 Jasper9fe0e8d2013-09-05 09:29:45 +0000439 return 0;
Daniel Jasperf7935112012-12-03 18:12:45 +0000440
Daniel Jasper4b866272013-02-01 11:00:45 +0000441 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000442 if (!DryRun)
443 reconstructPath(InitialState, Queue.top().second);
444
Alexander Kornienko49149672013-05-10 11:56:10 +0000445 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
446 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000447
448 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000449 }
450
451 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-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 Jasper9fe0e8d2013-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 Klimek4c5c28b2013-05-29 15:10:11 +0000464 DEBUG({
465 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000466 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000467 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000468 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000469 }
470 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +0000471 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000472 }
473
Manuel Klimekaf491072013-02-13 10:54:19 +0000474 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000475 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000476 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000477 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000478 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
479 bool NewLine) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000480 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000481 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000482 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000483 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000484
485 StateNode *Node = new (Allocator.Allocate())
486 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000487 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
488 return;
489
Daniel Jasperde0328a2013-08-16 11:20:30 +0000490 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000491
492 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
493 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000494 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000495
Daniel Jasperf3a5d002013-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 Jasper9fe0e8d2013-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 Jasperf3a5d002013-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 Jasper36c28ce2013-09-06 08:54:24 +0000523 return true;
Daniel Jasper9fe0e8d2013-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;
533 if (!DryRun)
534 Whitespaces->replaceWhitespace(
535 *(*I)->First, /*Newlines=*/1, /*Spaces=*/Indent,
536 /*StartOfTokenColumn=*/Indent, Line.InPPDirective);
537 UnwrappedLineFormatter Formatter(Indenter, Whitespaces, Style, **I);
538 Penalty += Formatter.format(Indent, DryRun);
539 }
540 return true;
541 }
542
543 if (LBrace.Children.size() > 1)
544 return false; // Cannot merge multiple statements into a single line.
545
546 // We can't put the closing "}" on a line with a trailing comment.
547 if (LBrace.Children[0]->Last->isTrailingComment())
548 return false;
549
550 if (!DryRun) {
551 Whitespaces->replaceWhitespace(*LBrace.Children[0]->First,
552 /*Newlines=*/0, /*Spaces=*/1,
553 /*StartOfTokenColumn=*/State.Column,
554 State.Line->InPPDirective);
555 }
556
557 State.Column += 1 + LBrace.Children[0]->Last->TotalLength;
558 return true;
559 }
560
Daniel Jasperde0328a2013-08-16 11:20:30 +0000561 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000562 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000563 FormatStyle Style;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000564 const AnnotatedLine &Line;
Manuel Klimekaf491072013-02-13 10:54:19 +0000565
566 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
567 QueueType Queue;
568 // Increasing count of \c StateNode items we have created. This is used
569 // to create a deterministic order independent of the container.
570 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +0000571};
572
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000573class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000574public:
Manuel Klimek31c85922013-08-29 15:21:40 +0000575 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000576 encoding::Encoding Encoding)
Manuel Klimek31c85922013-08-29 15:21:40 +0000577 : FormatTok(NULL), GreaterStashed(false), Column(0),
578 TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr), Style(Style),
579 IdentTable(getFormattingLangOpts()), Encoding(Encoding) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000580 Lex.SetKeepWhitespaceMode(true);
581 }
582
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000583 ArrayRef<FormatToken *> lex() {
584 assert(Tokens.empty());
585 do {
586 Tokens.push_back(getNextToken());
587 } while (Tokens.back()->Tok.isNot(tok::eof));
588 return Tokens;
589 }
590
591 IdentifierTable &getIdentTable() { return IdentTable; }
592
593private:
594 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000595 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +0000596 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +0000597 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +0000598 Token Greater = FormatTok->Tok;
599 FormatTok = new (Allocator.Allocate()) FormatToken;
600 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +0000601 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000602 FormatTok->Tok.getLocation().getLocWithOffset(1);
603 FormatTok->WhitespaceRange =
604 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +0000605 FormatTok->TokenText = ">";
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000606 FormatTok->CodePointCount = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000607 GreaterStashed = false;
608 return FormatTok;
609 }
610
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000611 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +0000612 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +0000613 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000614 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Manuel Klimek5c24cca2013-05-23 10:56:37 +0000615 if (SourceMgr.getFileOffset(WhitespaceStart) == 0)
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000616 FormatTok->IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000617
618 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +0000619 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000620 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +0000621 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
622 switch (FormatTok->TokenText[i]) {
623 case '\n':
624 ++FormatTok->NewlinesBefore;
625 // FIXME: This is technically incorrect, as it could also
626 // be a literal backslash at the end of the line.
Daniel Jasper36c28ce2013-09-06 08:54:24 +0000627 if (i == 0 || FormatTok->TokenText[i - 1] != '\\')
Manuel Klimek31c85922013-08-29 15:21:40 +0000628 FormatTok->HasUnescapedNewline = true;
629 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
630 Column = 0;
631 break;
632 case ' ':
633 ++Column;
634 break;
635 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000636 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +0000637 break;
638 default:
639 ++Column;
640 break;
641 }
642 }
643
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000644 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000645
Daniel Jasper8369aa52013-07-16 20:28:33 +0000646 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000647 }
Manuel Klimekef920692013-01-07 07:56:50 +0000648
Manuel Klimek1abf7892013-01-04 23:34:14 +0000649 // In case the token starts with escaped newlines, we want to
650 // take them into account as whitespace - this pattern is quite frequent
651 // in macro definitions.
652 // FIXME: What do we want to do with other escaped spaces, and escaped
653 // spaces or newlines in the middle of tokens?
654 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +0000655 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
656 FormatTok->TokenText[1] == '\n') {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000657 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimek5c24cca2013-05-23 10:56:37 +0000658 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +0000659 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +0000660 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000661 }
Manuel Klimek31c85922013-08-29 15:21:40 +0000662 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000663
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +0000664 TrailingWhitespace = 0;
665 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +0000666 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +0000667 StringRef UntrimmedText = FormatTok->TokenText;
668 FormatTok->TokenText = FormatTok->TokenText.rtrim();
669 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +0000670 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +0000671 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000672 FormatTok->Tok.setIdentifierInfo(&Info);
673 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +0000674 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000675 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +0000676 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000677 GreaterStashed = true;
678 }
679
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +0000680 // Now FormatTok is the next non-whitespace token.
Daniel Jasper8369aa52013-07-16 20:28:33 +0000681 FormatTok->CodePointCount =
682 encoding::getCodePointCount(FormatTok->TokenText, Encoding);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000683
Alexander Kornienko632abb92013-09-02 13:58:14 +0000684 if (FormatTok->isOneOf(tok::string_literal, tok::comment)) {
685 StringRef Text = FormatTok->TokenText;
686 size_t FirstNewlinePos = Text.find('\n');
687 if (FirstNewlinePos != StringRef::npos) {
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000688 // FIXME: Handle embedded tabs.
689 FormatTok->FirstLineColumnWidth = encoding::columnWidthWithTabs(
690 Text.substr(0, FirstNewlinePos), 0, Style.TabWidth, Encoding);
691 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
692 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
693 Encoding);
Alexander Kornienko632abb92013-09-02 13:58:14 +0000694 }
695 }
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000696 // FIXME: Add the CodePointCount to Column.
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000697 FormatTok->WhitespaceRange = SourceRange(
Manuel Klimek5c24cca2013-05-23 10:56:37 +0000698 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000699 return FormatTok;
700 }
701
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000702 FormatToken *FormatTok;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000703 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +0000704 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +0000705 unsigned TrailingWhitespace;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000706 Lexer &Lex;
707 SourceManager &SourceMgr;
Manuel Klimek31c85922013-08-29 15:21:40 +0000708 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000709 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000710 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000711 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
712 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000713
Daniel Jasper8369aa52013-07-16 20:28:33 +0000714 void readRawToken(FormatToken &Tok) {
715 Lex.LexFromRawLexer(Tok.Tok);
716 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
717 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +0000718 // For formatting, treat unterminated string literals like normal string
719 // literals.
720 if (Tok.is(tok::unknown) && !Tok.TokenText.empty() &&
721 Tok.TokenText[0] == '"') {
722 Tok.Tok.setKind(tok::string_literal);
723 Tok.IsUnterminatedLiteral = true;
724 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000725 }
726};
727
Daniel Jasperf7935112012-12-03 18:12:45 +0000728class Formatter : public UnwrappedLineConsumer {
729public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +0000730 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +0000731 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +0000732 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000733 Whitespaces(SourceMgr, Style), Ranges(Ranges),
734 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasperfa21c072013-07-15 14:33:14 +0000735 DEBUG(llvm::dbgs() << "File encoding: "
736 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
737 : "unknown")
738 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000739 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000740
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000741 virtual ~Formatter() {
742 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
743 delete AnnotatedLines[i];
744 }
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000745 }
Daniel Jasper61bd3a12012-12-04 21:05:31 +0000746
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000747 tooling::Replacements format() {
Manuel Klimek31c85922013-08-29 15:21:40 +0000748 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000749
750 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +0000751 bool StructuralError = Parser.parse();
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000752 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000753 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000754 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000755 }
756 deriveLocalStyle();
757 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000758 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000759 }
Daniel Jasperb67cc422013-04-09 17:46:55 +0000760
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000761 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperb67cc422013-04-09 17:46:55 +0000762
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000763 std::vector<int> IndentForLevel;
764 bool PreviousLineWasTouched = false;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000765 const FormatToken *PreviousLineLastToken = 0;
Daniel Jasper1cb530f2013-05-10 13:00:49 +0000766 bool FormatPPDirective = false;
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000767 for (SmallVectorImpl<AnnotatedLine *>::iterator I = AnnotatedLines.begin(),
768 E = AnnotatedLines.end();
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000769 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000770 const AnnotatedLine &TheLine = **I;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000771 const FormatToken *FirstTok = TheLine.First;
772 int Offset = getIndentOffset(*TheLine.First);
Daniel Jasper1cb530f2013-05-10 13:00:49 +0000773
774 // Check whether this line is part of a formatted preprocessor directive.
Manuel Klimek591ab5a2013-05-28 13:42:28 +0000775 if (FirstTok->HasUnescapedNewline)
Daniel Jasper1cb530f2013-05-10 13:00:49 +0000776 FormatPPDirective = false;
777 if (!FormatPPDirective && TheLine.InPPDirective &&
778 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
779 FormatPPDirective = true;
780
Daniel Jasper12f9d8e2013-05-14 09:30:02 +0000781 // Determine indent and try to merge multiple unwrapped lines.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000782 while (IndentForLevel.size() <= TheLine.Level)
783 IndentForLevel.push_back(-1);
784 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper12f9d8e2013-05-14 09:30:02 +0000785 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
786 if (static_cast<int>(Indent) + Offset >= 0)
787 Indent += Offset;
788 tryFitMultipleLinesInOne(Indent, I, E);
789
Manuel Klimek591ab5a2013-05-28 13:42:28 +0000790 bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000791 if (TheLine.First->is(tok::eof)) {
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000792 if (PreviousLineWasTouched) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +0000793 unsigned NewLines = std::min(FirstTok->NewlinesBefore, 1u);
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000794 Whitespaces.replaceWhitespace(*TheLine.First, NewLines, /*Indent*/ 0,
Manuel Klimek4fe43002013-05-22 12:51:29 +0000795 /*TargetColumn*/ 0);
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000796 }
797 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper1cb530f2013-05-10 13:00:49 +0000798 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000799 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimek591ab5a2013-05-28 13:42:28 +0000800 if (FirstTok->WhitespaceRange.isValid() &&
Manuel Klimek1a18c402013-04-12 14:13:36 +0000801 // Insert a break even if there is a structural error in case where
802 // we break apart a line consisting of multiple unwrapped lines.
Manuel Klimek591ab5a2013-05-28 13:42:28 +0000803 (FirstTok->NewlinesBefore == 0 || !StructuralError)) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000804 formatFirstToken(*TheLine.First, PreviousLineLastToken, Indent,
Manuel Klimek4fe43002013-05-22 12:51:29 +0000805 TheLine.InPPDirective);
Manuel Klimek1a18c402013-04-12 14:13:36 +0000806 } else {
Manuel Klimek31c85922013-08-29 15:21:40 +0000807 Indent = LevelIndent = FirstTok->OriginalColumn;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000808 }
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000809 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
Daniel Jasperde0328a2013-08-16 11:20:30 +0000810 BinPackInconclusiveFunctions);
811
812 // If everything fits on a single line, just put it there.
813 unsigned ColumnLimit = Style.ColumnLimit;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000814 AnnotatedLine *NextLine = *(I + 1);
815 if ((I + 1) != E && NextLine->InPPDirective &&
816 !NextLine->First->HasUnescapedNewline)
817 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000818
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000819 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000820 LineState State =
821 Indenter.getInitialState(Indent, &TheLine, /*DryRun=*/false);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000822 while (State.NextToken != NULL)
823 Indenter.addTokenToState(State, false, false);
824 } else if (Style.ColumnLimit == 0) {
825 NoColumnLimitFormatter Formatter(&Indenter);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000826 Formatter.format(Indent, &TheLine);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000827 } else {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000828 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style,
829 TheLine);
830 Formatter.format(Indent);
Daniel Jasperde0328a2013-08-16 11:20:30 +0000831 }
832
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000833 IndentForLevel[TheLine.Level] = LevelIndent;
834 PreviousLineWasTouched = true;
835 } else {
Manuel Klimek4fe43002013-05-22 12:51:29 +0000836 // Format the first token if necessary, and notify the WhitespaceManager
837 // about the unchanged whitespace.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000838 for (const FormatToken *Tok = TheLine.First; Tok != NULL;
839 Tok = Tok->Next) {
840 if (Tok == TheLine.First &&
841 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
Manuel Klimek31c85922013-08-29 15:21:40 +0000842 unsigned LevelIndent = Tok->OriginalColumn;
Manuel Klimek4fe43002013-05-22 12:51:29 +0000843 // Remove trailing whitespace of the previous line if it was
844 // touched.
845 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
846 formatFirstToken(*Tok, PreviousLineLastToken, LevelIndent,
847 TheLine.InPPDirective);
848 } else {
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000849 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimek4fe43002013-05-22 12:51:29 +0000850 }
Daniel Jasper12f9d8e2013-05-14 09:30:02 +0000851
Manuel Klimek4fe43002013-05-22 12:51:29 +0000852 if (static_cast<int>(LevelIndent) - Offset >= 0)
853 LevelIndent -= Offset;
854 if (Tok->isNot(tok::comment))
855 IndentForLevel[TheLine.Level] = LevelIndent;
856 } else {
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000857 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimek4fe43002013-05-22 12:51:29 +0000858 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000859 }
860 // If we did not reformat this unwrapped line, the column at the end of
861 // the last token is unchanged - thus, we can calculate the end of the
862 // last token.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000863 PreviousLineWasTouched = false;
864 }
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000865 PreviousLineLastToken = TheLine.Last;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000866 }
867 return Whitespaces.generateReplacements();
868 }
869
870private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000871 void deriveLocalStyle() {
872 unsigned CountBoundToVariable = 0;
873 unsigned CountBoundToType = 0;
874 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000875 bool HasBinPackedFunction = false;
876 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000877 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000878 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000879 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000880 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000881 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000882 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000883 bool SpacesBefore =
884 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
885 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
886 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000887 if (SpacesBefore && !SpacesAfter)
888 ++CountBoundToVariable;
889 else if (!SpacesBefore && SpacesAfter)
890 ++CountBoundToType;
891 }
892
Daniel Jasper400adc62013-02-08 15:28:42 +0000893 if (Tok->Type == TT_TemplateCloser &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000894 Tok->Previous->Type == TT_TemplateCloser &&
895 Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd())
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000896 HasCpp03IncompatibleFormat = true;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000897
898 if (Tok->PackingKind == PPK_BinPacked)
899 HasBinPackedFunction = true;
900 if (Tok->PackingKind == PPK_OnePerLine)
901 HasOnePerLineFunction = true;
902
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000903 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000904 }
905 }
906 if (Style.DerivePointerBinding) {
907 if (CountBoundToType > CountBoundToVariable)
908 Style.PointerBindsToType = true;
909 else if (CountBoundToType < CountBoundToVariable)
910 Style.PointerBindsToType = false;
911 }
912 if (Style.Standard == FormatStyle::LS_Auto) {
913 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
914 : FormatStyle::LS_Cpp03;
915 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000916 BinPackInconclusiveFunctions =
917 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000918 }
919
Manuel Klimekb95f5452013-02-08 17:38:27 +0000920 /// \brief Get the indent of \p Level from \p IndentForLevel.
921 ///
922 /// \p IndentForLevel must contain the indent for the level \c l
923 /// at \p IndentForLevel[l], or a value < 0 if the indent for
924 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000925 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +0000926 if (IndentForLevel[Level] != -1)
927 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +0000928 if (Level == 0)
929 return 0;
Manuel Klimek13b97d82013-05-13 08:42:42 +0000930 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimekb95f5452013-02-08 17:38:27 +0000931 }
932
933 /// \brief Get the offset of the line relatively to the level.
934 ///
935 /// For example, 'public:' labels in classes are offset by 1 or 2
936 /// characters to the left from their level.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000937 int getIndentOffset(const FormatToken &RootToken) {
Alexander Kornienkofd433362013-03-27 17:08:02 +0000938 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimekb95f5452013-02-08 17:38:27 +0000939 return Style.AccessModifierOffset;
940 return 0;
941 }
942
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000943 /// \brief Tries to merge lines into one.
944 ///
945 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
946 /// if possible; note that \c I will be incremented when lines are merged.
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000947 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000948 SmallVectorImpl<AnnotatedLine *>::iterator &I,
949 SmallVectorImpl<AnnotatedLine *>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000950 // We can never merge stuff if there are trailing line comments.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000951 AnnotatedLine *TheLine = *I;
952 if (TheLine->Last->Type == TT_LineComment)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000953 return;
954
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000955 if (Indent > Style.ColumnLimit)
956 return;
957
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000958 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000959 // If we already exceed the column limit, we set 'Limit' to 0. The different
960 // tryMerge..() functions can then decide whether to still do merging.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000961 Limit = TheLine->Last->TotalLength > Limit
962 ? 0
963 : Limit - TheLine->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +0000964
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000965 if (I + 1 == E || (*(I + 1))->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000966 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000967
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000968 if (TheLine->Last->is(tok::l_brace)) {
Daniel Jasper25837aa2013-01-14 14:14:23 +0000969 tryMergeSimpleBlock(I, E, Limit);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000970 } else if (Style.AllowShortIfStatementsOnASingleLine &&
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000971 TheLine->First->is(tok::kw_if)) {
Daniel Jasper3a685df2013-05-16 12:12:21 +0000972 tryMergeSimpleControlStatement(I, E, Limit);
973 } else if (Style.AllowShortLoopsOnASingleLine &&
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000974 TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
Daniel Jasper3a685df2013-05-16 12:12:21 +0000975 tryMergeSimpleControlStatement(I, E, Limit);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000976 } else if (TheLine->InPPDirective && (TheLine->First->HasUnescapedNewline ||
977 TheLine->First->IsFirst)) {
Daniel Jasper39825ea2013-01-14 15:40:57 +0000978 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +0000979 }
Daniel Jasper25837aa2013-01-14 14:14:23 +0000980 }
981
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000982 void tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::iterator &I,
983 SmallVectorImpl<AnnotatedLine *>::iterator E,
Daniel Jasper39825ea2013-01-14 15:40:57 +0000984 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000985 if (Limit == 0)
986 return;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000987 AnnotatedLine &Line = **I;
988 if (!(*(I + 1))->InPPDirective || (*(I + 1))->First->HasUnescapedNewline)
Daniel Jasper2ab0d012013-01-14 15:52:06 +0000989 return;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000990 if (I + 2 != E && (*(I + 2))->InPPDirective &&
991 !(*(I + 2))->First->HasUnescapedNewline)
Daniel Jasper39825ea2013-01-14 15:40:57 +0000992 return;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000993 if (1 + (*(I + 1))->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000994 return;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000995 join(Line, **(++I));
Daniel Jasper39825ea2013-01-14 15:40:57 +0000996 }
997
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000998 void
999 tryMergeSimpleControlStatement(SmallVectorImpl<AnnotatedLine *>::iterator &I,
1000 SmallVectorImpl<AnnotatedLine *>::iterator E,
1001 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001002 if (Limit == 0)
1003 return;
Manuel Klimeka027f302013-08-07 19:20:45 +00001004 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman &&
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001005 (*(I + 1))->First->is(tok::l_brace))
Manuel Klimeka027f302013-08-07 19:20:45 +00001006 return;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001007 if ((*(I + 1))->InPPDirective != (*I)->InPPDirective ||
1008 ((*(I + 1))->InPPDirective && (*(I + 1))->First->HasUnescapedNewline))
Manuel Klimekda087612013-01-18 14:46:43 +00001009 return;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001010 AnnotatedLine &Line = **I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001011 if (Line.Last->isNot(tok::r_paren))
1012 return;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001013 if (1 + (*(I + 1))->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001014 return;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001015 if ((*(I + 1))->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
1016 tok::kw_while) ||
1017 (*(I + 1))->First->Type == TT_LineComment)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001018 return;
1019 // Only inline simple if's (no nested if or else).
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001020 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001021 (*(I + 2))->First->is(tok::kw_else))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001022 return;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001023 join(Line, **(++I));
Daniel Jasper25837aa2013-01-14 14:14:23 +00001024 }
1025
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001026 void tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::iterator &I,
1027 SmallVectorImpl<AnnotatedLine *>::iterator E,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001028 unsigned Limit) {
Daniel Jasperabca58c2013-05-15 14:09:55 +00001029 // No merging if the brace already is on the next line.
1030 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
1031 return;
1032
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001033 // First, check that the current line allows merging. This is the case if
1034 // we're not in a control flow statement and the last token is an opening
1035 // brace.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001036 AnnotatedLine &Line = **I;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001037 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1038 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jaspera9eb2aa2013-05-31 14:56:20 +00001039 tok::kw_for,
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001040 // This gets rid of all ObjC @ keywords and methods.
1041 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001042 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001043
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001044 FormatToken *Tok = (*(I + 1))->First;
Daniel Jaspera9eb2aa2013-05-31 14:56:20 +00001045 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Alexander Kornienko1efe0a02013-07-04 14:47:51 +00001046 (Tok->getNextNonComment() == NULL ||
1047 Tok->getNextNonComment()->is(tok::semi))) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001048 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001049 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001050 Tok->CanBreakBefore = true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001051 join(Line, **(I + 1));
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001052 I += 1;
Daniel Jaspera9eb2aa2013-05-31 14:56:20 +00001053 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001054 // Check that we still have three lines and they fit into the limit.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001055 if (I + 2 == E || (*(I + 2))->Type == LT_Invalid ||
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001056 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001057 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001058
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001059 // Second, check that the next line does not contain any braces - if it
1060 // does, readability declines when putting it into a single line.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001061 if ((*(I + 1))->Last->Type == TT_LineComment || Tok->MustBreakBefore)
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001062 return;
1063 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001064 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001065 return;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001066 Tok = Tok->Next;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001067 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001068
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001069 // Last, check that the third line contains a single closing brace.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001070 Tok = (*(I + 2))->First;
Alexander Kornienko1efe0a02013-07-04 14:47:51 +00001071 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001072 Tok->MustBreakBefore)
1073 return;
1074
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001075 join(Line, **(I + 1));
1076 join(Line, **(I + 2));
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001077 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001078 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001079 }
1080
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001081 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::iterator I,
Daniel Jasper25837aa2013-01-14 14:14:23 +00001082 unsigned Limit) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001083 return 1 + (*(I + 1))->Last->TotalLength + 1 +
1084 (*(I + 2))->Last->TotalLength <=
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001085 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001086 }
1087
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001088 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001089 assert(!A.Last->Next);
1090 assert(!B.First->Previous);
1091 A.Last->Next = B.First;
1092 B.First->Previous = A.Last;
1093 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1094 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1095 Tok->TotalLength += LengthA;
1096 A.Last = Tok;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001097 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001098 }
1099
Daniel Jasper97b89482013-03-13 07:49:51 +00001100 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001101 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1102 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1103 Ranges[i].getBegin()) &&
1104 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1105 Range.getBegin()))
1106 return true;
1107 }
1108 return false;
1109 }
1110
1111 bool touchesLine(const AnnotatedLine &TheLine) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001112 const FormatToken *First = TheLine.First;
1113 const FormatToken *Last = TheLine.Last;
Daniel Jaspercdd06622013-05-14 10:31:09 +00001114 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001115 First->WhitespaceRange.getBegin().getLocWithOffset(
1116 First->LastNewlineOffset),
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001117 Last->Tok.getLocation().getLocWithOffset(Last->TokenText.size() - 1));
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001118 return touchesRanges(LineRange);
1119 }
1120
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001121 bool touchesPPDirective(SmallVectorImpl<AnnotatedLine *>::iterator I,
1122 SmallVectorImpl<AnnotatedLine *>::iterator E) {
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001123 for (; I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001124 if ((*I)->First->HasUnescapedNewline)
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001125 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001126 if (touchesLine(**I))
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001127 return true;
1128 }
1129 return false;
1130 }
1131
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001132 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001133 const FormatToken *First = TheLine.First;
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001134 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001135 First->WhitespaceRange.getBegin(),
1136 First->WhitespaceRange.getBegin().getLocWithOffset(
1137 First->LastNewlineOffset));
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001138 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001139 }
1140
1141 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001142 AnnotatedLines.push_back(new AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001143 }
1144
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001145 /// \brief Add a new line and the required indent before the first Token
1146 /// of the \c UnwrappedLine if there was no structural parsing error.
1147 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001148 void formatFirstToken(const FormatToken &RootToken,
1149 const FormatToken *PreviousToken, unsigned Indent,
Manuel Klimek4fe43002013-05-22 12:51:29 +00001150 bool InPPDirective) {
Daniel Jasperbbc84152013-01-29 11:27:30 +00001151 unsigned Newlines =
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001152 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Daniel Jasper1027c6e2013-06-03 16:16:41 +00001153 // Remove empty lines before "}" where applicable.
1154 if (RootToken.is(tok::r_brace) &&
1155 (!RootToken.Next ||
1156 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1157 Newlines = std::min(Newlines, 1u);
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001158 if (Newlines == 0 && !RootToken.IsFirst)
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001159 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001160
Manuel Klimek4fe43002013-05-22 12:51:29 +00001161 // Insert extra new line before access specifiers.
1162 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001163 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
Manuel Klimek4fe43002013-05-22 12:51:29 +00001164 ++Newlines;
Alexander Kornienkofd433362013-03-27 17:08:02 +00001165
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001166 Whitespaces.replaceWhitespace(
1167 RootToken, Newlines, Indent, Indent,
1168 InPPDirective && !RootToken.HasUnescapedNewline);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001169 }
1170
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001171 unsigned getColumnLimit(bool InPPDirective) const {
1172 // In preprocessor directives reserve two chars for trailing " \"
1173 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1174 }
1175
Daniel Jasperf7935112012-12-03 18:12:45 +00001176 FormatStyle Style;
1177 Lexer &Lex;
1178 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001179 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001180 std::vector<CharSourceRange> Ranges;
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001181 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001182
1183 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001184 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001185};
1186
Craig Topperaf35e852013-06-30 22:29:28 +00001187} // end anonymous namespace
1188
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001189tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1190 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001191 std::vector<CharSourceRange> Ranges) {
1192 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001193 return formatter.format();
1194}
1195
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001196tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1197 std::vector<tooling::Range> Ranges,
1198 StringRef FileName) {
1199 FileManager Files((FileSystemOptions()));
1200 DiagnosticsEngine Diagnostics(
1201 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1202 new DiagnosticOptions);
1203 SourceManager SourceMgr(Diagnostics, Files);
1204 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1205 const clang::FileEntry *Entry =
1206 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1207 SourceMgr.overrideFileContents(Entry, Buf);
1208 FileID ID =
1209 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienko1e808872013-06-28 12:51:24 +00001210 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1211 getFormattingLangOpts(Style.Standard));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001212 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1213 std::vector<CharSourceRange> CharRanges;
1214 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1215 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1216 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1217 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1218 }
1219 return reformat(Style, Lex, SourceMgr, CharRanges);
1220}
1221
Alexander Kornienko1e808872013-06-28 12:51:24 +00001222LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001223 LangOptions LangOpts;
1224 LangOpts.CPlusPlus = 1;
Alexander Kornienko1e808872013-06-28 12:51:24 +00001225 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001226 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001227 LangOpts.Bool = 1;
1228 LangOpts.ObjC1 = 1;
1229 LangOpts.ObjC2 = 1;
1230 return LangOpts;
1231}
1232
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001233} // namespace format
1234} // namespace clang