blob: 89960003bce66c6718118e03c983f5b6f42d0821 [file] [log] [blame]
Daniel Jasperbac016b2012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
Daniel Jasperbac016b2012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimekca547db2013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Daniel Jasper6b2afe42013-08-16 11:20:30 +000018#include "ContinuationIndenter.h"
Daniel Jasper32d28ee2013-01-29 21:01:14 +000019#include "TokenAnnotator.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienko70ce7882013-04-15 14:28:00 +000021#include "WhitespaceManager.h"
Daniel Jasper8a999452013-05-16 10:40:07 +000022#include "clang/Basic/Diagnostic.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000023#include "clang/Basic/SourceManager.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000024#include "clang/Format/Format.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Alexander Kornienko5262dd92013-03-27 11:52:18 +000026#include "llvm/ADT/STLExtras.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000027#include "llvm/Support/Allocator.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Alexander Kornienkod71ec162013-05-07 15:32:14 +000029#include "llvm/Support/YAMLTraits.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000030#include <queue>
Daniel Jasper8822d3a2012-12-04 13:02:32 +000031#include <string>
32
Alexander Kornienkod71ec162013-05-07 15:32:14 +000033namespace llvm {
34namespace yaml {
35template <>
36struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> {
Manuel Klimek44135b82013-05-13 12:51:40 +000037 static void enumeration(IO &IO,
38 clang::format::FormatStyle::LanguageStandard &Value) {
Alexander Kornienko9321e872013-09-04 14:09:13 +000039 IO.enumCase(Value, "Cpp03", clang::format::FormatStyle::LS_Cpp03);
Manuel Klimek44135b82013-05-13 12:51:40 +000040 IO.enumCase(Value, "C++03", clang::format::FormatStyle::LS_Cpp03);
Alexander Kornienko9321e872013-09-04 14:09:13 +000041 IO.enumCase(Value, "Cpp11", clang::format::FormatStyle::LS_Cpp11);
Manuel Klimek44135b82013-05-13 12:51:40 +000042 IO.enumCase(Value, "C++11", clang::format::FormatStyle::LS_Cpp11);
43 IO.enumCase(Value, "Auto", clang::format::FormatStyle::LS_Auto);
44 }
45};
46
Daniel Jasper1fb8d882013-05-14 09:30:02 +000047template <>
Manuel Klimek44135b82013-05-13 12:51:40 +000048struct ScalarEnumerationTraits<clang::format::FormatStyle::BraceBreakingStyle> {
49 static void
50 enumeration(IO &IO, clang::format::FormatStyle::BraceBreakingStyle &Value) {
51 IO.enumCase(Value, "Attach", clang::format::FormatStyle::BS_Attach);
52 IO.enumCase(Value, "Linux", clang::format::FormatStyle::BS_Linux);
53 IO.enumCase(Value, "Stroustrup", clang::format::FormatStyle::BS_Stroustrup);
Manuel Klimeke4907052013-08-02 21:31:59 +000054 IO.enumCase(Value, "Allman", clang::format::FormatStyle::BS_Allman);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000055 }
56};
57
Daniel Jaspereff18b92013-07-31 23:16:02 +000058template <>
59struct ScalarEnumerationTraits<
60 clang::format::FormatStyle::NamespaceIndentationKind> {
61 static void
62 enumeration(IO &IO,
63 clang::format::FormatStyle::NamespaceIndentationKind &Value) {
64 IO.enumCase(Value, "None", clang::format::FormatStyle::NI_None);
65 IO.enumCase(Value, "Inner", clang::format::FormatStyle::NI_Inner);
66 IO.enumCase(Value, "All", clang::format::FormatStyle::NI_All);
67 }
68};
69
Alexander Kornienkod71ec162013-05-07 15:32:14 +000070template <> struct MappingTraits<clang::format::FormatStyle> {
71 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
Alexander Kornienkodd256312013-05-10 11:56:10 +000072 if (IO.outputting()) {
Alexander Kornienko4e65c982013-09-02 16:39:23 +000073 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
74 "Mozilla", "WebKit" };
Alexander Kornienkodd256312013-05-10 11:56:10 +000075 ArrayRef<StringRef> Styles(StylesArray);
76 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
77 StringRef StyleName(Styles[i]);
Alexander Kornienko885f87b2013-05-19 00:53:30 +000078 clang::format::FormatStyle PredefinedStyle;
79 if (clang::format::getPredefinedStyle(StyleName, &PredefinedStyle) &&
80 Style == PredefinedStyle) {
Alexander Kornienkodd256312013-05-10 11:56:10 +000081 IO.mapOptional("# BasedOnStyle", StyleName);
82 break;
83 }
84 }
85 } else {
Alexander Kornienkod71ec162013-05-07 15:32:14 +000086 StringRef BasedOnStyle;
87 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000088 if (!BasedOnStyle.empty())
Alexander Kornienko885f87b2013-05-19 00:53:30 +000089 if (!clang::format::getPredefinedStyle(BasedOnStyle, &Style)) {
90 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
91 return;
92 }
Alexander Kornienkod71ec162013-05-07 15:32:14 +000093 }
94
95 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jasper6315fec2013-08-13 10:58:30 +000096 IO.mapOptional("ConstructorInitializerIndentWidth",
97 Style.ConstructorInitializerIndentWidth);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000098 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper893ea8d2013-07-31 23:55:15 +000099 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000100 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
101 Style.AllowAllParametersOfDeclarationOnNextLine);
102 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
103 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000104 IO.mapOptional("AllowShortLoopsOnASingleLine",
105 Style.AllowShortLoopsOnASingleLine);
Daniel Jasperbbc87762013-05-29 12:07:31 +0000106 IO.mapOptional("AlwaysBreakTemplateDeclarations",
107 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko56312022013-07-04 12:02:44 +0000108 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
109 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000110 IO.mapOptional("BreakBeforeBinaryOperators",
111 Style.BreakBeforeBinaryOperators);
112 IO.mapOptional("BreakConstructorInitializersBeforeComma",
113 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000114 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
115 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
116 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
117 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
118 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000119 IO.mapOptional("ExperimentalAutoDetectBinPacking",
120 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000121 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
122 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspereff18b92013-07-31 23:16:02 +0000123 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000124 IO.mapOptional("ObjCSpaceBeforeProtocolList",
125 Style.ObjCSpaceBeforeProtocolList);
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000126 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
127 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000128 IO.mapOptional("PenaltyBreakFirstLessLess",
129 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000130 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
131 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
132 Style.PenaltyReturnTypeOnItsOwnLine);
133 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
134 IO.mapOptional("SpacesBeforeTrailingComments",
135 Style.SpacesBeforeTrailingComments);
Daniel Jasperb5dc3f42013-07-16 18:22:10 +0000136 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000137 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000138 IO.mapOptional("IndentWidth", Style.IndentWidth);
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000139 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimek44135b82013-05-13 12:51:40 +0000140 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimeka9a7f102013-06-21 17:25:42 +0000141 IO.mapOptional("IndentFunctionDeclarationAfterType",
142 Style.IndentFunctionDeclarationAfterType);
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000143 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasper34f3d052013-08-21 08:39:01 +0000144 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000145 IO.mapOptional("SpacesInCStyleCastParentheses",
146 Style.SpacesInCStyleCastParentheses);
147 IO.mapOptional("SpaceAfterControlStatementKeyword",
148 Style.SpaceAfterControlStatementKeyword);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000149 }
150};
151}
152}
153
Daniel Jasperbac016b2012-12-03 18:12:45 +0000154namespace clang {
155namespace format {
156
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000157void setDefaultPenalties(FormatStyle &Style) {
Daniel Jasperf5461782013-08-28 10:03:58 +0000158 Style.PenaltyBreakComment = 60;
Daniel Jasper9637dda2013-07-15 14:33:14 +0000159 Style.PenaltyBreakFirstLessLess = 120;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000160 Style.PenaltyBreakString = 1000;
161 Style.PenaltyExcessCharacter = 1000000;
162}
163
Daniel Jasperbac016b2012-12-03 18:12:45 +0000164FormatStyle getLLVMStyle() {
165 FormatStyle LLVMStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000166 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000167 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000168 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000169 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000170 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000171 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienko56312022013-07-04 12:02:44 +0000172 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000173 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000174 LLVMStyle.BinPackParameters = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000175 LLVMStyle.BreakBeforeBinaryOperators = false;
176 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
177 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000178 LLVMStyle.ColumnLimit = 80;
179 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6315fec2013-08-13 10:58:30 +0000180 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000181 LLVMStyle.Cpp11BracedListStyle = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000182 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000183 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000184 LLVMStyle.IndentCaseLabels = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000185 LLVMStyle.IndentFunctionDeclarationAfterType = false;
186 LLVMStyle.IndentWidth = 2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000187 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000188 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Weber5f500df2013-01-10 20:12:55 +0000189 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000190 LLVMStyle.PointerBindsToType = false;
191 LLVMStyle.SpacesBeforeTrailingComments = 1;
192 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000193 LLVMStyle.UseTab = false;
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000194 LLVMStyle.SpacesInParentheses = false;
195 LLVMStyle.SpaceInEmptyParentheses = false;
196 LLVMStyle.SpacesInCStyleCastParentheses = false;
197 LLVMStyle.SpaceAfterControlStatementKeyword = true;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000198
199 setDefaultPenalties(LLVMStyle);
200 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
201
Daniel Jasperbac016b2012-12-03 18:12:45 +0000202 return LLVMStyle;
203}
204
205FormatStyle getGoogleStyle() {
206 FormatStyle GoogleStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000207 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000208 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000209 GoogleStyle.AlignTrailingComments = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000210 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000211 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper1bee0732013-05-23 18:05:18 +0000212 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko56312022013-07-04 12:02:44 +0000213 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000214 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000215 GoogleStyle.BinPackParameters = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000216 GoogleStyle.BreakBeforeBinaryOperators = false;
217 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
218 GoogleStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000219 GoogleStyle.ColumnLimit = 80;
220 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper6315fec2013-08-13 10:58:30 +0000221 GoogleStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000222 GoogleStyle.Cpp11BracedListStyle = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000223 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000224 GoogleStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000225 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000226 GoogleStyle.IndentFunctionDeclarationAfterType = true;
227 GoogleStyle.IndentWidth = 2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000228 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000229 GoogleStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Weber5f500df2013-01-10 20:12:55 +0000230 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000231 GoogleStyle.PointerBindsToType = true;
232 GoogleStyle.SpacesBeforeTrailingComments = 2;
233 GoogleStyle.Standard = FormatStyle::LS_Auto;
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000234 GoogleStyle.UseTab = false;
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000235 GoogleStyle.SpacesInParentheses = false;
236 GoogleStyle.SpaceInEmptyParentheses = false;
237 GoogleStyle.SpacesInCStyleCastParentheses = false;
238 GoogleStyle.SpaceAfterControlStatementKeyword = true;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000239
240 setDefaultPenalties(GoogleStyle);
241 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
242
Daniel Jasperbac016b2012-12-03 18:12:45 +0000243 return GoogleStyle;
244}
245
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000246FormatStyle getChromiumStyle() {
247 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +0000248 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000249 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000250 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000251 ChromiumStyle.BinPackParameters = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000252 ChromiumStyle.DerivePointerBinding = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000253 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000254 return ChromiumStyle;
255}
256
Alexander Kornienkofb594862013-05-06 14:11:27 +0000257FormatStyle getMozillaStyle() {
258 FormatStyle MozillaStyle = getLLVMStyle();
259 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
260 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
261 MozillaStyle.DerivePointerBinding = true;
262 MozillaStyle.IndentCaseLabels = true;
263 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
264 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
265 MozillaStyle.PointerBindsToType = true;
266 return MozillaStyle;
267}
268
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000269FormatStyle getWebKitStyle() {
270 FormatStyle Style = getLLVMStyle();
Daniel Jaspereff18b92013-07-31 23:16:02 +0000271 Style.AccessModifierOffset = -4;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000272 Style.AlignTrailingComments = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000273 Style.BreakBeforeBinaryOperators = true;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000274 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000275 Style.BreakConstructorInitializersBeforeComma = true;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000276 Style.ColumnLimit = 0;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000277 Style.IndentWidth = 4;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000278 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000279 Style.PointerBindsToType = true;
280 return Style;
281}
282
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000283bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000284 if (Name.equals_lower("llvm"))
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000285 *Style = getLLVMStyle();
286 else if (Name.equals_lower("chromium"))
287 *Style = getChromiumStyle();
288 else if (Name.equals_lower("mozilla"))
289 *Style = getMozillaStyle();
290 else if (Name.equals_lower("google"))
291 *Style = getGoogleStyle();
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000292 else if (Name.equals_lower("webkit"))
293 *Style = getWebKitStyle();
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000294 else
295 return false;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000296
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000297 return true;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000298}
299
300llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienko107db3c2013-05-20 15:18:01 +0000301 if (Text.trim().empty())
302 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000303 llvm::yaml::Input Input(Text);
304 Input >> *Style;
305 return Input.error();
306}
307
308std::string configurationAsText(const FormatStyle &Style) {
309 std::string Text;
310 llvm::raw_string_ostream Stream(Text);
311 llvm::yaml::Output Output(Stream);
312 // We use the same mapping method for input and output, so we need a non-const
313 // reference here.
314 FormatStyle NonConstStyle = Style;
315 Output << NonConstStyle;
Alexander Kornienko2b6acb62013-05-13 12:56:35 +0000316 return Stream.str();
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000317}
318
Craig Topper83f81d72013-06-30 22:29:28 +0000319namespace {
320
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000321class NoColumnLimitFormatter {
322public:
Daniel Jasper34f3d052013-08-21 08:39:01 +0000323 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000324
325 /// \brief Formats the line starting at \p State, simply keeping all of the
326 /// input's line breaking decisions.
327 void format() {
328 LineState State = Indenter->getInitialState();
329 while (State.NextToken != NULL) {
330 bool Newline =
331 Indenter->mustBreak(State) ||
332 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
333 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
334 }
335 }
Daniel Jasper34f3d052013-08-21 08:39:01 +0000336
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000337private:
338 ContinuationIndenter *Indenter;
339};
340
Daniel Jasperbac016b2012-12-03 18:12:45 +0000341class UnwrappedLineFormatter {
342public:
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000343 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
344 const FormatStyle &Style, const AnnotatedLine &Line)
345 : Indenter(Indenter), Style(Style), Line(Line), Count(0) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000346
Manuel Klimekd4397b92013-01-04 23:34:14 +0000347 /// \brief Formats an \c UnwrappedLine.
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000348 void format() {
349 LineState State = Indenter->getInitialState();
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000350
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000351 // If the ObjC method declaration does not fit on a line, we should format
352 // it with one arg per line.
353 if (Line.Type == LT_ObjCMethodDecl)
354 State.Stack.back().BreakBeforeParameter = true;
355
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000356 // Find best solution in solution space.
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000357 analyzeSolutionSpace(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000358 }
359
360private:
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000361 /// \brief An edge in the solution space from \c Previous->State to \c State,
362 /// inserting a newline dependent on the \c NewLine.
363 struct StateNode {
364 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +0000365 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000366 LineState State;
367 bool NewLine;
368 StateNode *Previous;
369 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000370
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000371 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
372 ///
373 /// In case of equal penalties, we want to prefer states that were inserted
374 /// first. During state generation we make sure that we insert states first
375 /// that break the line as late as possible.
376 typedef std::pair<unsigned, unsigned> OrderedPenalty;
377
378 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
379 /// \c State has the given \c OrderedPenalty.
380 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
381
382 /// \brief The BFS queue type.
383 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
384 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000385
386 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000387 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000388 /// This implements a variant of Dijkstra's algorithm on the graph that spans
389 /// the solution space (\c LineStates are the nodes). The algorithm tries to
390 /// find the shortest path (the one with lowest penalty) from \p InitialState
391 /// to a state where all tokens are placed.
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000392 void analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000393 std::set<LineState> Seen;
394
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000395 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +0000396 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000397 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
398 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
399 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000400
401 // While not empty, take first element and follow edges.
402 while (!Queue.empty()) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000403 unsigned Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +0000404 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000405 if (Node->State.NextToken == NULL) {
Alexander Kornienkodd256312013-05-10 11:56:10 +0000406 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000407 break;
Daniel Jasper01786732013-02-04 07:21:18 +0000408 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000409 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000410
Daniel Jasper54b4e442013-05-22 05:27:42 +0000411 // Cut off the analysis of certain solutions if the analysis gets too
412 // complex. See description of IgnoreStackForComparison.
413 if (Count > 10000)
414 Node->State.IgnoreStackForComparison = true;
415
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000416 if (!Seen.insert(Node->State).second)
417 // State already examined with lower penalty.
418 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000419
Nico Weber27268772013-06-26 00:30:14 +0000420 addNextStateToQueue(Penalty, Node, /*NewLine=*/false);
421 addNextStateToQueue(Penalty, Node, /*NewLine=*/true);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000422 }
423
424 if (Queue.empty())
425 // We were unable to find a solution, do nothing.
426 // FIXME: Add diagnostic?
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000427 return;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000428
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000429 // Reconstruct the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000430 reconstructPath(InitialState, Queue.top().second);
Alexander Kornienkodd256312013-05-10 11:56:10 +0000431 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
432 DEBUG(llvm::dbgs() << "---\n");
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000433 }
434
435 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek9c333b92013-05-29 15:10:11 +0000436 std::deque<StateNode *> Path;
437 // We do not need a break before the initial token.
438 while (Current->Previous) {
439 Path.push_front(Current);
440 Current = Current->Previous;
441 }
442 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
443 I != E; ++I) {
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000444 unsigned Penalty = Indenter->addTokenToState(State, (*I)->NewLine, false);
Daniel Jasper259118e2013-08-22 16:11:46 +0000445 (void)Penalty;
Manuel Klimek9c333b92013-05-29 15:10:11 +0000446 DEBUG({
447 if ((*I)->NewLine) {
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000448 llvm::dbgs() << "Penalty for placing "
Manuel Klimek9c333b92013-05-29 15:10:11 +0000449 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000450 << Penalty << "\n";
Manuel Klimek9c333b92013-05-29 15:10:11 +0000451 }
452 });
Manuel Klimek9c333b92013-05-29 15:10:11 +0000453 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000454 }
455
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000456 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000457 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000458 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000459 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000460 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
461 bool NewLine) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000462 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000463 return;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000464 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000465 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000466
467 StateNode *Node = new (Allocator.Allocate())
468 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000469 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
470 if (Node->State.Column > Indenter->getColumnLimit()) {
471 unsigned ExcessCharacters =
472 Node->State.Column - Indenter->getColumnLimit();
Daniel Jasper01786732013-02-04 07:21:18 +0000473 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000474 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000475
476 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
477 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000478 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000479
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000480 ContinuationIndenter *Indenter;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000481 FormatStyle Style;
Daniel Jasper995e8202013-01-14 13:08:07 +0000482 const AnnotatedLine &Line;
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000483
484 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
485 QueueType Queue;
486 // Increasing count of \c StateNode items we have created. This is used
487 // to create a deterministic order independent of the container.
488 unsigned Count;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000489};
490
Manuel Klimek96e888b2013-05-28 11:55:06 +0000491class FormatTokenLexer {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000492public:
Manuel Klimekc41e8192013-08-29 15:21:40 +0000493 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienko00895102013-06-05 14:09:10 +0000494 encoding::Encoding Encoding)
Manuel Klimekc41e8192013-08-29 15:21:40 +0000495 : FormatTok(NULL), GreaterStashed(false), Column(0),
496 TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr), Style(Style),
497 IdentTable(getFormattingLangOpts()), Encoding(Encoding) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000498 Lex.SetKeepWhitespaceMode(true);
499 }
500
Manuel Klimek96e888b2013-05-28 11:55:06 +0000501 ArrayRef<FormatToken *> lex() {
502 assert(Tokens.empty());
503 do {
504 Tokens.push_back(getNextToken());
505 } while (Tokens.back()->Tok.isNot(tok::eof));
506 return Tokens;
507 }
508
509 IdentifierTable &getIdentTable() { return IdentTable; }
510
511private:
512 FormatToken *getNextToken() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000513 if (GreaterStashed) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000514 // Create a synthesized second '>' token.
Manuel Klimekc41e8192013-08-29 15:21:40 +0000515 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000516 Token Greater = FormatTok->Tok;
517 FormatTok = new (Allocator.Allocate()) FormatToken;
518 FormatTok->Tok = Greater;
Manuel Klimekad3094b2013-05-23 10:56:37 +0000519 SourceLocation GreaterLocation =
Manuel Klimek96e888b2013-05-28 11:55:06 +0000520 FormatTok->Tok.getLocation().getLocWithOffset(1);
521 FormatTok->WhitespaceRange =
522 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000523 FormatTok->TokenText = ">";
Alexander Kornienko00895102013-06-05 14:09:10 +0000524 FormatTok->CodePointCount = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000525 GreaterStashed = false;
526 return FormatTok;
527 }
528
Manuel Klimek96e888b2013-05-28 11:55:06 +0000529 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper561211d2013-07-16 20:28:33 +0000530 readRawToken(*FormatTok);
Manuel Klimekde008c02013-05-27 15:23:34 +0000531 SourceLocation WhitespaceStart =
Manuel Klimek96e888b2013-05-28 11:55:06 +0000532 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Manuel Klimekad3094b2013-05-23 10:56:37 +0000533 if (SourceMgr.getFileOffset(WhitespaceStart) == 0)
Manuel Klimek96e888b2013-05-28 11:55:06 +0000534 FormatTok->IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000535
536 // Consume and record whitespace until we find a significant token.
Manuel Klimekde008c02013-05-27 15:23:34 +0000537 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek96e888b2013-05-28 11:55:06 +0000538 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000539 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
540 switch (FormatTok->TokenText[i]) {
541 case '\n':
542 ++FormatTok->NewlinesBefore;
543 // FIXME: This is technically incorrect, as it could also
544 // be a literal backslash at the end of the line.
545 if (i == 0 || FormatTok->TokenText[i-1] != '\\')
546 FormatTok->HasUnescapedNewline = true;
547 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
548 Column = 0;
549 break;
550 case ' ':
551 ++Column;
552 break;
553 case '\t':
554 Column += Style.IndentWidth - Column % Style.IndentWidth;
555 break;
556 default:
557 ++Column;
558 break;
559 }
560 }
561
Manuel Klimek96e888b2013-05-28 11:55:06 +0000562 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000563
Daniel Jasper561211d2013-07-16 20:28:33 +0000564 readRawToken(*FormatTok);
Manuel Klimekd4397b92013-01-04 23:34:14 +0000565 }
Manuel Klimek95419382013-01-07 07:56:50 +0000566
Manuel Klimekd4397b92013-01-04 23:34:14 +0000567 // In case the token starts with escaped newlines, we want to
568 // take them into account as whitespace - this pattern is quite frequent
569 // in macro definitions.
570 // FIXME: What do we want to do with other escaped spaces, and escaped
571 // spaces or newlines in the middle of tokens?
572 // FIXME: Add a more explicit test.
Daniel Jasper561211d2013-07-16 20:28:33 +0000573 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
574 FormatTok->TokenText[1] == '\n') {
Manuel Klimek96e888b2013-05-28 11:55:06 +0000575 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimekad3094b2013-05-23 10:56:37 +0000576 WhitespaceLength += 2;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000577 Column = 0;
Daniel Jasper561211d2013-07-16 20:28:33 +0000578 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000579 }
Manuel Klimekc41e8192013-08-29 15:21:40 +0000580 FormatTok->OriginalColumn = Column;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000581
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000582 TrailingWhitespace = 0;
583 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000584 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper561211d2013-07-16 20:28:33 +0000585 StringRef UntrimmedText = FormatTok->TokenText;
586 FormatTok->TokenText = FormatTok->TokenText.rtrim();
587 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000588 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper561211d2013-07-16 20:28:33 +0000589 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek96e888b2013-05-28 11:55:06 +0000590 FormatTok->Tok.setIdentifierInfo(&Info);
591 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000592 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek96e888b2013-05-28 11:55:06 +0000593 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper561211d2013-07-16 20:28:33 +0000594 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000595 GreaterStashed = true;
596 }
597
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000598 // Now FormatTok is the next non-whitespace token.
Daniel Jasper561211d2013-07-16 20:28:33 +0000599 FormatTok->CodePointCount =
600 encoding::getCodePointCount(FormatTok->TokenText, Encoding);
Alexander Kornienko00895102013-06-05 14:09:10 +0000601
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000602 if (FormatTok->isOneOf(tok::string_literal, tok::comment)) {
603 StringRef Text = FormatTok->TokenText;
604 size_t FirstNewlinePos = Text.find('\n');
605 if (FirstNewlinePos != StringRef::npos) {
606 FormatTok->CodePointsInFirstLine = encoding::getCodePointCount(
607 Text.substr(0, FirstNewlinePos), Encoding);
608 FormatTok->CodePointsInLastLine = encoding::getCodePointCount(
609 Text.substr(Text.find_last_of('\n') + 1), Encoding);
610 }
611 }
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000612 // FIXME: Add the CodePointCount to Column.
Manuel Klimek96e888b2013-05-28 11:55:06 +0000613 FormatTok->WhitespaceRange = SourceRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +0000614 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000615 return FormatTok;
616 }
617
Manuel Klimek96e888b2013-05-28 11:55:06 +0000618 FormatToken *FormatTok;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000619 bool GreaterStashed;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000620 unsigned Column;
Manuel Klimekde008c02013-05-27 15:23:34 +0000621 unsigned TrailingWhitespace;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000622 Lexer &Lex;
623 SourceManager &SourceMgr;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000624 FormatStyle &Style;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000625 IdentifierTable IdentTable;
Alexander Kornienko00895102013-06-05 14:09:10 +0000626 encoding::Encoding Encoding;
Manuel Klimek96e888b2013-05-28 11:55:06 +0000627 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
628 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000629
Daniel Jasper561211d2013-07-16 20:28:33 +0000630 void readRawToken(FormatToken &Tok) {
631 Lex.LexFromRawLexer(Tok.Tok);
632 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
633 Tok.Tok.getLength());
Daniel Jasper561211d2013-07-16 20:28:33 +0000634 // For formatting, treat unterminated string literals like normal string
635 // literals.
636 if (Tok.is(tok::unknown) && !Tok.TokenText.empty() &&
637 Tok.TokenText[0] == '"') {
638 Tok.Tok.setKind(tok::string_literal);
639 Tok.IsUnterminatedLiteral = true;
640 }
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000641 }
642};
643
Daniel Jasperbac016b2012-12-03 18:12:45 +0000644class Formatter : public UnwrappedLineConsumer {
645public:
Daniel Jaspercaf42a32013-05-15 08:14:19 +0000646 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000647 const std::vector<CharSourceRange> &Ranges)
Daniel Jaspercaf42a32013-05-15 08:14:19 +0000648 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko00895102013-06-05 14:09:10 +0000649 Whitespaces(SourceMgr, Style), Ranges(Ranges),
650 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasper9637dda2013-07-15 14:33:14 +0000651 DEBUG(llvm::dbgs() << "File encoding: "
652 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
653 : "unknown")
654 << "\n");
Alexander Kornienko00895102013-06-05 14:09:10 +0000655 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000656
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000657 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +0000658
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000659 tooling::Replacements format() {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000660 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek96e888b2013-05-28 11:55:06 +0000661
662 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek67d080d2013-04-12 14:13:36 +0000663 bool StructuralError = Parser.parse();
Alexander Kornienko00895102013-06-05 14:09:10 +0000664 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000665 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
666 Annotator.annotate(AnnotatedLines[i]);
667 }
668 deriveLocalStyle();
669 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
670 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
671 }
Daniel Jasper5999f762013-04-09 17:46:55 +0000672
673 // Adapt level to the next line if this is a comment.
674 // FIXME: Can/should this be done in the UnwrappedLineParser?
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000675 const AnnotatedLine *NextNonCommentLine = NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +0000676 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000677 if (NextNonCommentLine && AnnotatedLines[i].First->is(tok::comment) &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000678 !AnnotatedLines[i].First->Next)
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000679 AnnotatedLines[i].Level = NextNonCommentLine->Level;
Daniel Jasper5999f762013-04-09 17:46:55 +0000680 else
Daniel Jasper2a409b62013-07-08 14:34:09 +0000681 NextNonCommentLine = AnnotatedLines[i].First->isNot(tok::r_brace)
682 ? &AnnotatedLines[i]
683 : NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +0000684 }
685
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000686 std::vector<int> IndentForLevel;
687 bool PreviousLineWasTouched = false;
Manuel Klimekb3987012013-05-29 14:47:47 +0000688 const FormatToken *PreviousLineLastToken = 0;
Daniel Jasper89b3a7f2013-05-10 13:00:49 +0000689 bool FormatPPDirective = false;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000690 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
691 E = AnnotatedLines.end();
692 I != E; ++I) {
693 const AnnotatedLine &TheLine = *I;
Manuel Klimekb3987012013-05-29 14:47:47 +0000694 const FormatToken *FirstTok = TheLine.First;
695 int Offset = getIndentOffset(*TheLine.First);
Daniel Jasper89b3a7f2013-05-10 13:00:49 +0000696
697 // Check whether this line is part of a formatted preprocessor directive.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000698 if (FirstTok->HasUnescapedNewline)
Daniel Jasper89b3a7f2013-05-10 13:00:49 +0000699 FormatPPDirective = false;
700 if (!FormatPPDirective && TheLine.InPPDirective &&
701 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
702 FormatPPDirective = true;
703
Daniel Jasper1fb8d882013-05-14 09:30:02 +0000704 // Determine indent and try to merge multiple unwrapped lines.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000705 while (IndentForLevel.size() <= TheLine.Level)
706 IndentForLevel.push_back(-1);
707 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper1fb8d882013-05-14 09:30:02 +0000708 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
709 if (static_cast<int>(Indent) + Offset >= 0)
710 Indent += Offset;
711 tryFitMultipleLinesInOne(Indent, I, E);
712
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000713 bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0;
Manuel Klimekb3987012013-05-29 14:47:47 +0000714 if (TheLine.First->is(tok::eof)) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000715 if (PreviousLineWasTouched) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000716 unsigned NewLines = std::min(FirstTok->NewlinesBefore, 1u);
Manuel Klimekb3987012013-05-29 14:47:47 +0000717 Whitespaces.replaceWhitespace(*TheLine.First, NewLines, /*Indent*/ 0,
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000718 /*TargetColumn*/ 0);
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000719 }
720 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper89b3a7f2013-05-10 13:00:49 +0000721 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000722 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000723 if (FirstTok->WhitespaceRange.isValid() &&
Manuel Klimek67d080d2013-04-12 14:13:36 +0000724 // Insert a break even if there is a structural error in case where
725 // we break apart a line consisting of multiple unwrapped lines.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000726 (FirstTok->NewlinesBefore == 0 || !StructuralError)) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000727 formatFirstToken(*TheLine.First, PreviousLineLastToken, Indent,
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000728 TheLine.InPPDirective);
Manuel Klimek67d080d2013-04-12 14:13:36 +0000729 } else {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000730 Indent = LevelIndent = FirstTok->OriginalColumn;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000731 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000732 ContinuationIndenter Indenter(Style, SourceMgr, TheLine, Indent,
733 Whitespaces, Encoding,
734 BinPackInconclusiveFunctions);
735
736 // If everything fits on a single line, just put it there.
737 unsigned ColumnLimit = Style.ColumnLimit;
738 if ((I + 1) != E && (I + 1)->InPPDirective &&
739 !(I + 1)->First->HasUnescapedNewline)
740 ColumnLimit = Indenter.getColumnLimit();
741
742 if (I->Last->TotalLength + Indent <= ColumnLimit) {
743 LineState State = Indenter.getInitialState();
744 while (State.NextToken != NULL)
745 Indenter.addTokenToState(State, false, false);
746 } else if (Style.ColumnLimit == 0) {
747 NoColumnLimitFormatter Formatter(&Indenter);
748 Formatter.format();
749 } else {
750 UnwrappedLineFormatter Formatter(&Indenter, Style, TheLine);
751 Formatter.format();
752 }
753
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000754 IndentForLevel[TheLine.Level] = LevelIndent;
755 PreviousLineWasTouched = true;
756 } else {
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000757 // Format the first token if necessary, and notify the WhitespaceManager
758 // about the unchanged whitespace.
Manuel Klimekb3987012013-05-29 14:47:47 +0000759 for (const FormatToken *Tok = TheLine.First; Tok != NULL;
760 Tok = Tok->Next) {
761 if (Tok == TheLine.First &&
762 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000763 unsigned LevelIndent = Tok->OriginalColumn;
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000764 // Remove trailing whitespace of the previous line if it was
765 // touched.
766 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
767 formatFirstToken(*Tok, PreviousLineLastToken, LevelIndent,
768 TheLine.InPPDirective);
769 } else {
Manuel Klimekb3987012013-05-29 14:47:47 +0000770 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000771 }
Daniel Jasper1fb8d882013-05-14 09:30:02 +0000772
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000773 if (static_cast<int>(LevelIndent) - Offset >= 0)
774 LevelIndent -= Offset;
775 if (Tok->isNot(tok::comment))
776 IndentForLevel[TheLine.Level] = LevelIndent;
777 } else {
Manuel Klimekb3987012013-05-29 14:47:47 +0000778 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000779 }
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000780 }
781 // If we did not reformat this unwrapped line, the column at the end of
782 // the last token is unchanged - thus, we can calculate the end of the
783 // last token.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000784 PreviousLineWasTouched = false;
785 }
Alexander Kornienko94b748f2013-03-27 17:08:02 +0000786 PreviousLineLastToken = I->Last;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000787 }
788 return Whitespaces.generateReplacements();
789 }
790
791private:
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000792 void deriveLocalStyle() {
793 unsigned CountBoundToVariable = 0;
794 unsigned CountBoundToType = 0;
795 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000796 bool HasBinPackedFunction = false;
797 bool HasOnePerLineFunction = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000798 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000799 if (!AnnotatedLines[i].First->Next)
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000800 continue;
Manuel Klimekb3987012013-05-29 14:47:47 +0000801 FormatToken *Tok = AnnotatedLines[i].First->Next;
802 while (Tok->Next) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000803 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000804 bool SpacesBefore =
805 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
806 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
807 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000808 if (SpacesBefore && !SpacesAfter)
809 ++CountBoundToVariable;
810 else if (!SpacesBefore && SpacesAfter)
811 ++CountBoundToType;
812 }
813
Daniel Jasper29f123b2013-02-08 15:28:42 +0000814 if (Tok->Type == TT_TemplateCloser &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000815 Tok->Previous->Type == TT_TemplateCloser &&
816 Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd())
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000817 HasCpp03IncompatibleFormat = true;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000818
819 if (Tok->PackingKind == PPK_BinPacked)
820 HasBinPackedFunction = true;
821 if (Tok->PackingKind == PPK_OnePerLine)
822 HasOnePerLineFunction = true;
823
Manuel Klimekb3987012013-05-29 14:47:47 +0000824 Tok = Tok->Next;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000825 }
826 }
827 if (Style.DerivePointerBinding) {
828 if (CountBoundToType > CountBoundToVariable)
829 Style.PointerBindsToType = true;
830 else if (CountBoundToType < CountBoundToVariable)
831 Style.PointerBindsToType = false;
832 }
833 if (Style.Standard == FormatStyle::LS_Auto) {
834 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
835 : FormatStyle::LS_Cpp03;
836 }
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000837 BinPackInconclusiveFunctions =
838 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000839 }
840
Manuel Klimek547d5db2013-02-08 17:38:27 +0000841 /// \brief Get the indent of \p Level from \p IndentForLevel.
842 ///
843 /// \p IndentForLevel must contain the indent for the level \c l
844 /// at \p IndentForLevel[l], or a value < 0 if the indent for
845 /// that level is unknown.
Daniel Jasperfc759082013-02-14 14:26:07 +0000846 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimek547d5db2013-02-08 17:38:27 +0000847 if (IndentForLevel[Level] != -1)
848 return IndentForLevel[Level];
Manuel Klimek52635ff2013-02-08 19:53:32 +0000849 if (Level == 0)
850 return 0;
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000851 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimek547d5db2013-02-08 17:38:27 +0000852 }
853
854 /// \brief Get the offset of the line relatively to the level.
855 ///
856 /// For example, 'public:' labels in classes are offset by 1 or 2
857 /// characters to the left from their level.
Manuel Klimekb3987012013-05-29 14:47:47 +0000858 int getIndentOffset(const FormatToken &RootToken) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +0000859 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimek547d5db2013-02-08 17:38:27 +0000860 return Style.AccessModifierOffset;
861 return 0;
862 }
863
Manuel Klimek517e8942013-01-11 17:54:10 +0000864 /// \brief Tries to merge lines into one.
865 ///
866 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
867 /// if possible; note that \c I will be incremented when lines are merged.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000868 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +0000869 std::vector<AnnotatedLine>::iterator &I,
870 std::vector<AnnotatedLine>::iterator E) {
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000871 // We can never merge stuff if there are trailing line comments.
872 if (I->Last->Type == TT_LineComment)
873 return;
874
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000875 if (Indent > Style.ColumnLimit)
876 return;
877
Daniel Jaspera4d46212013-02-28 11:05:57 +0000878 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasperf11a7052013-02-21 21:33:55 +0000879 // If we already exceed the column limit, we set 'Limit' to 0. The different
880 // tryMerge..() functions can then decide whether to still do merging.
881 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +0000882
Daniel Jasper9c8c40e2013-01-21 14:18:28 +0000883 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000884 return;
Manuel Klimek517e8942013-01-11 17:54:10 +0000885
Daniel Jasper5be59ba2013-05-15 14:09:55 +0000886 if (I->Last->is(tok::l_brace)) {
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000887 tryMergeSimpleBlock(I, E, Limit);
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000888 } else if (Style.AllowShortIfStatementsOnASingleLine &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000889 I->First->is(tok::kw_if)) {
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000890 tryMergeSimpleControlStatement(I, E, Limit);
891 } else if (Style.AllowShortLoopsOnASingleLine &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000892 I->First->isOneOf(tok::kw_for, tok::kw_while)) {
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000893 tryMergeSimpleControlStatement(I, E, Limit);
Manuel Klimekb3987012013-05-29 14:47:47 +0000894 } else if (I->InPPDirective &&
895 (I->First->HasUnescapedNewline || I->First->IsFirst)) {
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000896 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000897 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000898 }
899
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000900 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
901 std::vector<AnnotatedLine>::iterator E,
902 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +0000903 if (Limit == 0)
904 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000905 AnnotatedLine &Line = *I;
Manuel Klimekb3987012013-05-29 14:47:47 +0000906 if (!(I + 1)->InPPDirective || (I + 1)->First->HasUnescapedNewline)
Daniel Jasper2b9c10b2013-01-14 15:52:06 +0000907 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000908 if (I + 2 != E && (I + 2)->InPPDirective &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000909 !(I + 2)->First->HasUnescapedNewline)
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000910 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000911 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000912 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000913 join(Line, *(++I));
914 }
915
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000916 void tryMergeSimpleControlStatement(std::vector<AnnotatedLine>::iterator &I,
917 std::vector<AnnotatedLine>::iterator E,
918 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +0000919 if (Limit == 0)
920 return;
Manuel Klimekd3a247c2013-08-07 19:20:45 +0000921 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman &&
922 (I + 1)->First->is(tok::l_brace))
923 return;
Manuel Klimek4c128122013-01-18 14:46:43 +0000924 if ((I + 1)->InPPDirective != I->InPPDirective ||
Manuel Klimekb3987012013-05-29 14:47:47 +0000925 ((I + 1)->InPPDirective && (I + 1)->First->HasUnescapedNewline))
Manuel Klimek4c128122013-01-18 14:46:43 +0000926 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000927 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +0000928 if (Line.Last->isNot(tok::r_paren))
929 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000930 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000931 return;
Manuel Klimekb3987012013-05-29 14:47:47 +0000932 if ((I + 1)->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
933 tok::kw_while) ||
934 (I + 1)->First->Type == TT_LineComment)
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000935 return;
936 // Only inline simple if's (no nested if or else).
Manuel Klimekb3987012013-05-29 14:47:47 +0000937 if (I + 2 != E && Line.First->is(tok::kw_if) &&
938 (I + 2)->First->is(tok::kw_else))
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000939 return;
940 join(Line, *(++I));
941 }
942
943 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000944 std::vector<AnnotatedLine>::iterator E,
945 unsigned Limit) {
Daniel Jasper5be59ba2013-05-15 14:09:55 +0000946 // No merging if the brace already is on the next line.
947 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
948 return;
949
Manuel Klimek517e8942013-01-11 17:54:10 +0000950 // First, check that the current line allows merging. This is the case if
951 // we're not in a control flow statement and the last token is an opening
952 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000953 AnnotatedLine &Line = *I;
Manuel Klimekb3987012013-05-29 14:47:47 +0000954 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
955 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jasper8893b8a2013-05-31 14:56:20 +0000956 tok::kw_for,
Manuel Klimekb3987012013-05-29 14:47:47 +0000957 // This gets rid of all ObjC @ keywords and methods.
958 tok::at, tok::minus, tok::plus))
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000959 return;
Manuel Klimek517e8942013-01-11 17:54:10 +0000960
Manuel Klimekb3987012013-05-29 14:47:47 +0000961 FormatToken *Tok = (I + 1)->First;
Daniel Jasper8893b8a2013-05-31 14:56:20 +0000962 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000963 (Tok->getNextNonComment() == NULL ||
964 Tok->getNextNonComment()->is(tok::semi))) {
Daniel Jasperf11a7052013-02-21 21:33:55 +0000965 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jasper729a7432013-02-11 12:36:37 +0000966 Tok->SpacesRequiredBefore = 0;
Daniel Jasperf11a7052013-02-21 21:33:55 +0000967 Tok->CanBreakBefore = true;
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000968 join(Line, *(I + 1));
969 I += 1;
Daniel Jasper8893b8a2013-05-31 14:56:20 +0000970 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000971 // Check that we still have three lines and they fit into the limit.
972 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
973 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000974 return;
Manuel Klimek517e8942013-01-11 17:54:10 +0000975
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000976 // Second, check that the next line does not contain any braces - if it
977 // does, readability declines when putting it into a single line.
978 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
979 return;
980 do {
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000981 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000982 return;
Manuel Klimekb3987012013-05-29 14:47:47 +0000983 Tok = Tok->Next;
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000984 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +0000985
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000986 // Last, check that the third line contains a single closing brace.
Manuel Klimekb3987012013-05-29 14:47:47 +0000987 Tok = (I + 2)->First;
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000988 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000989 Tok->MustBreakBefore)
990 return;
991
992 join(Line, *(I + 1));
993 join(Line, *(I + 2));
994 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +0000995 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000996 }
997
998 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
999 unsigned Limit) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001000 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1001 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001002 }
1003
Daniel Jasper995e8202013-01-14 13:08:07 +00001004 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001005 assert(!A.Last->Next);
1006 assert(!B.First->Previous);
1007 A.Last->Next = B.First;
1008 B.First->Previous = A.Last;
1009 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1010 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1011 Tok->TotalLength += LengthA;
1012 A.Last = Tok;
Daniel Jasper995e8202013-01-14 13:08:07 +00001013 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001014 }
1015
Daniel Jasper6f21a982013-03-13 07:49:51 +00001016 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf3023542013-03-07 20:50:00 +00001017 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1018 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1019 Ranges[i].getBegin()) &&
1020 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1021 Range.getBegin()))
1022 return true;
1023 }
1024 return false;
1025 }
1026
1027 bool touchesLine(const AnnotatedLine &TheLine) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001028 const FormatToken *First = TheLine.First;
1029 const FormatToken *Last = TheLine.Last;
Daniel Jasper84f5ddf2013-05-14 10:31:09 +00001030 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001031 First->WhitespaceRange.getBegin().getLocWithOffset(
1032 First->LastNewlineOffset),
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001033 Last->Tok.getLocation().getLocWithOffset(Last->TokenText.size() - 1));
Daniel Jasperf3023542013-03-07 20:50:00 +00001034 return touchesRanges(LineRange);
1035 }
1036
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001037 bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I,
1038 std::vector<AnnotatedLine>::iterator E) {
1039 for (; I != E; ++I) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001040 if (I->First->HasUnescapedNewline)
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001041 return false;
1042 if (touchesLine(*I))
1043 return true;
1044 }
1045 return false;
1046 }
1047
Daniel Jasperf3023542013-03-07 20:50:00 +00001048 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001049 const FormatToken *First = TheLine.First;
Daniel Jasperf3023542013-03-07 20:50:00 +00001050 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001051 First->WhitespaceRange.getBegin(),
1052 First->WhitespaceRange.getBegin().getLocWithOffset(
1053 First->LastNewlineOffset));
Daniel Jasperf3023542013-03-07 20:50:00 +00001054 return touchesRanges(LineRange);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001055 }
1056
1057 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +00001058 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001059 }
1060
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001061 /// \brief Add a new line and the required indent before the first Token
1062 /// of the \c UnwrappedLine if there was no structural parsing error.
1063 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimekb3987012013-05-29 14:47:47 +00001064 void formatFirstToken(const FormatToken &RootToken,
1065 const FormatToken *PreviousToken, unsigned Indent,
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001066 bool InPPDirective) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001067 unsigned Newlines =
Manuel Klimekb3987012013-05-29 14:47:47 +00001068 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Daniel Jasper15f33f02013-06-03 16:16:41 +00001069 // Remove empty lines before "}" where applicable.
1070 if (RootToken.is(tok::r_brace) &&
1071 (!RootToken.Next ||
1072 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1073 Newlines = std::min(Newlines, 1u);
Manuel Klimekb3987012013-05-29 14:47:47 +00001074 if (Newlines == 0 && !RootToken.IsFirst)
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001075 Newlines = 1;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001076
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001077 // Insert extra new line before access specifiers.
1078 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001079 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001080 ++Newlines;
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001081
Manuel Klimekb3987012013-05-29 14:47:47 +00001082 Whitespaces.replaceWhitespace(
1083 RootToken, Newlines, Indent, Indent,
1084 InPPDirective && !RootToken.HasUnescapedNewline);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001085 }
1086
Daniel Jasperbac016b2012-12-03 18:12:45 +00001087 FormatStyle Style;
1088 Lexer &Lex;
1089 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001090 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001091 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001092 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko00895102013-06-05 14:09:10 +00001093
1094 encoding::Encoding Encoding;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001095 bool BinPackInconclusiveFunctions;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001096};
1097
Craig Topper83f81d72013-06-30 22:29:28 +00001098} // end anonymous namespace
1099
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001100tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1101 SourceManager &SourceMgr,
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001102 std::vector<CharSourceRange> Ranges) {
1103 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001104 return formatter.format();
1105}
1106
Daniel Jasper8a999452013-05-16 10:40:07 +00001107tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1108 std::vector<tooling::Range> Ranges,
1109 StringRef FileName) {
1110 FileManager Files((FileSystemOptions()));
1111 DiagnosticsEngine Diagnostics(
1112 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1113 new DiagnosticOptions);
1114 SourceManager SourceMgr(Diagnostics, Files);
1115 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1116 const clang::FileEntry *Entry =
1117 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1118 SourceMgr.overrideFileContents(Entry, Buf);
1119 FileID ID =
1120 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001121 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1122 getFormattingLangOpts(Style.Standard));
Daniel Jasper8a999452013-05-16 10:40:07 +00001123 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1124 std::vector<CharSourceRange> CharRanges;
1125 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1126 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1127 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1128 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1129 }
1130 return reformat(Style, Lex, SourceMgr, CharRanges);
1131}
1132
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001133LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasper46ef8522013-01-10 13:08:12 +00001134 LangOptions LangOpts;
1135 LangOpts.CPlusPlus = 1;
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001136 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasperb64eca02013-03-22 10:01:29 +00001137 LangOpts.LineComment = 1;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001138 LangOpts.Bool = 1;
1139 LangOpts.ObjC1 = 1;
1140 LangOpts.ObjC2 = 1;
1141 return LangOpts;
1142}
1143
Daniel Jaspercd162382013-01-07 13:26:07 +00001144} // namespace format
1145} // namespace clang