blob: 729ca97aabe7b8d556f24aea16a72a8c32684504 [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
Daniel Jasper6b2afe42013-08-16 11:20:30 +000016#include "ContinuationIndenter.h"
Daniel Jasper32d28ee2013-01-29 21:01:14 +000017#include "TokenAnnotator.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "UnwrappedLineParser.h"
Alexander Kornienko70ce7882013-04-15 14:28:00 +000019#include "WhitespaceManager.h"
Daniel Jasper8a999452013-05-16 10:40:07 +000020#include "clang/Basic/Diagnostic.h"
Stephen Hines6bcf27b2014-05-29 04:14:42 -070021#include "clang/Basic/DiagnosticOptions.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000023#include "clang/Format/Format.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000024#include "clang/Lex/Lexer.h"
Alexander Kornienko5262dd92013-03-27 11:52:18 +000025#include "llvm/ADT/STLExtras.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000026#include "llvm/Support/Allocator.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000027#include "llvm/Support/Debug.h"
Edwin Vanef4e12c82013-09-30 13:31:48 +000028#include "llvm/Support/Path.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070029#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
Stephen Hines6bcf27b2014-05-29 04:14:42 -070033#define DEBUG_TYPE "format-formatter"
34
Stephen Hines651f13c2014-04-23 16:59:28 -070035using clang::format::FormatStyle;
36
37LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
38
Alexander Kornienkod71ec162013-05-07 15:32:14 +000039namespace llvm {
40namespace yaml {
Stephen Hines651f13c2014-04-23 16:59:28 -070041template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
42 static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
43 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
Stephen Hines176edba2014-12-01 14:53:08 -080044 IO.enumCase(Value, "Java", FormatStyle::LK_Java);
Stephen Hines651f13c2014-04-23 16:59:28 -070045 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
46 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
47 }
48};
49
50template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
51 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
52 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
53 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
54 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
55 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
56 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
57 }
58};
59
60template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
61 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
62 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
63 IO.enumCase(Value, "false", FormatStyle::UT_Never);
64 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
65 IO.enumCase(Value, "true", FormatStyle::UT_Always);
66 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
67 }
68};
69
Stephen Hines6bcf27b2014-05-29 04:14:42 -070070template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
71 static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
72 IO.enumCase(Value, "None", FormatStyle::SFS_None);
73 IO.enumCase(Value, "false", FormatStyle::SFS_None);
74 IO.enumCase(Value, "All", FormatStyle::SFS_All);
75 IO.enumCase(Value, "true", FormatStyle::SFS_All);
76 IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
77 }
78};
79
Stephen Hines176edba2014-12-01 14:53:08 -080080template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
81 static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
82 IO.enumCase(Value, "All", FormatStyle::BOS_All);
83 IO.enumCase(Value, "true", FormatStyle::BOS_All);
84 IO.enumCase(Value, "None", FormatStyle::BOS_None);
85 IO.enumCase(Value, "false", FormatStyle::BOS_None);
86 IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
87 }
88};
89
Stephen Hines651f13c2014-04-23 16:59:28 -070090template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
91 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
92 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
93 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
94 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
95 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
96 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
97 }
98};
99
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000100template <>
Stephen Hines651f13c2014-04-23 16:59:28 -0700101struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Manuel Klimek44135b82013-05-13 12:51:40 +0000102 static void enumeration(IO &IO,
Stephen Hines651f13c2014-04-23 16:59:28 -0700103 FormatStyle::NamespaceIndentationKind &Value) {
104 IO.enumCase(Value, "None", FormatStyle::NI_None);
105 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
106 IO.enumCase(Value, "All", FormatStyle::NI_All);
Manuel Klimek44135b82013-05-13 12:51:40 +0000107 }
108};
109
Daniel Jasper1fb8d882013-05-14 09:30:02 +0000110template <>
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700111struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
112 static void enumeration(IO &IO,
113 FormatStyle::PointerAlignmentStyle &Value) {
114 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
115 IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
116 IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
117
Stephen Hines176edba2014-12-01 14:53:08 -0800118 // For backward compatibility.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700119 IO.enumCase(Value, "true", FormatStyle::PAS_Left);
120 IO.enumCase(Value, "false", FormatStyle::PAS_Right);
121 }
122};
123
124template <>
Stephen Hines651f13c2014-04-23 16:59:28 -0700125struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000126 static void enumeration(IO &IO,
Stephen Hines651f13c2014-04-23 16:59:28 -0700127 FormatStyle::SpaceBeforeParensOptions &Value) {
128 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
129 IO.enumCase(Value, "ControlStatements",
130 FormatStyle::SBPO_ControlStatements);
131 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
132
133 // For backward compatibility.
134 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
135 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000136 }
137};
138
Stephen Hines651f13c2014-04-23 16:59:28 -0700139template <> struct MappingTraits<FormatStyle> {
140 static void mapping(IO &IO, FormatStyle &Style) {
141 // When reading, read the language first, we need it for getPredefinedStyle.
142 IO.mapOptional("Language", Style.Language);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000143
Alexander Kornienkodd256312013-05-10 11:56:10 +0000144 if (IO.outputting()) {
Alexander Kornienko4e65c982013-09-02 16:39:23 +0000145 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
Stephen Hines651f13c2014-04-23 16:59:28 -0700146 "Mozilla", "WebKit", "GNU" };
Alexander Kornienkodd256312013-05-10 11:56:10 +0000147 ArrayRef<StringRef> Styles(StylesArray);
148 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
149 StringRef StyleName(Styles[i]);
Stephen Hines651f13c2014-04-23 16:59:28 -0700150 FormatStyle PredefinedStyle;
151 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000152 Style == PredefinedStyle) {
Alexander Kornienkodd256312013-05-10 11:56:10 +0000153 IO.mapOptional("# BasedOnStyle", StyleName);
154 break;
155 }
156 }
157 } else {
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000158 StringRef BasedOnStyle;
159 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Stephen Hines651f13c2014-04-23 16:59:28 -0700160 if (!BasedOnStyle.empty()) {
161 FormatStyle::LanguageKind OldLanguage = Style.Language;
162 FormatStyle::LanguageKind Language =
163 ((FormatStyle *)IO.getContext())->Language;
164 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000165 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
166 return;
167 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700168 Style.Language = OldLanguage;
169 }
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000170 }
171
172 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Stephen Hines176edba2014-12-01 14:53:08 -0800173 IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000174 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000175 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000176 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
177 Style.AllowAllParametersOfDeclarationOnNextLine);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700178 IO.mapOptional("AllowShortBlocksOnASingleLine",
179 Style.AllowShortBlocksOnASingleLine);
Stephen Hines176edba2014-12-01 14:53:08 -0800180 IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
181 Style.AllowShortCaseLabelsOnASingleLine);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000182 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
183 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000184 IO.mapOptional("AllowShortLoopsOnASingleLine",
185 Style.AllowShortLoopsOnASingleLine);
Stephen Hines651f13c2014-04-23 16:59:28 -0700186 IO.mapOptional("AllowShortFunctionsOnASingleLine",
187 Style.AllowShortFunctionsOnASingleLine);
Stephen Hines176edba2014-12-01 14:53:08 -0800188 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
189 Style.AlwaysBreakAfterDefinitionReturnType);
Daniel Jasperbbc87762013-05-29 12:07:31 +0000190 IO.mapOptional("AlwaysBreakTemplateDeclarations",
191 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko56312022013-07-04 12:02:44 +0000192 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
193 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000194 IO.mapOptional("BreakBeforeBinaryOperators",
195 Style.BreakBeforeBinaryOperators);
Daniel Jasper1a896a52013-11-08 00:57:11 +0000196 IO.mapOptional("BreakBeforeTernaryOperators",
197 Style.BreakBeforeTernaryOperators);
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000198 IO.mapOptional("BreakConstructorInitializersBeforeComma",
199 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000200 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
Stephen Hines176edba2014-12-01 14:53:08 -0800201 IO.mapOptional("BinPackArguments", Style.BinPackArguments);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000202 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
203 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
204 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Stephen Hines176edba2014-12-01 14:53:08 -0800205 IO.mapOptional("ConstructorInitializerIndentWidth",
206 Style.ConstructorInitializerIndentWidth);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700207 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000208 IO.mapOptional("ExperimentalAutoDetectBinPacking",
209 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000210 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700211 IO.mapOptional("IndentWrappedFunctionNames",
212 Style.IndentWrappedFunctionNames);
213 IO.mapOptional("IndentFunctionDeclarationAfterType",
214 Style.IndentWrappedFunctionNames);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000215 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Stephen Hines651f13c2014-04-23 16:59:28 -0700216 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
217 Style.KeepEmptyLinesAtTheStartOfBlocks);
Daniel Jaspereff18b92013-07-31 23:16:02 +0000218 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Stephen Hines176edba2014-12-01 14:53:08 -0800219 IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
Stephen Hines651f13c2014-04-23 16:59:28 -0700220 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000221 IO.mapOptional("ObjCSpaceBeforeProtocolList",
222 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper47066e42013-10-25 14:29:37 +0000223 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
224 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000225 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
226 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000227 IO.mapOptional("PenaltyBreakFirstLessLess",
228 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000229 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
230 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
231 Style.PenaltyReturnTypeOnItsOwnLine);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700232 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000233 IO.mapOptional("SpacesBeforeTrailingComments",
234 Style.SpacesBeforeTrailingComments);
Daniel Jasperb5dc3f42013-07-16 18:22:10 +0000235 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000236 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000237 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000238 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000239 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimek44135b82013-05-13 12:51:40 +0000240 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000241 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Stephen Hines176edba2014-12-01 14:53:08 -0800242 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
Daniel Jasperd8ee5c12013-10-29 14:52:02 +0000243 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasper34f3d052013-08-21 08:39:01 +0000244 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000245 IO.mapOptional("SpacesInCStyleCastParentheses",
246 Style.SpacesInCStyleCastParentheses);
Stephen Hines176edba2014-12-01 14:53:08 -0800247 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
Stephen Hines651f13c2014-04-23 16:59:28 -0700248 IO.mapOptional("SpacesInContainerLiterals",
249 Style.SpacesInContainerLiterals);
Daniel Jasper9b4de852013-09-25 15:15:02 +0000250 IO.mapOptional("SpaceBeforeAssignmentOperators",
251 Style.SpaceBeforeAssignmentOperators);
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000252 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Stephen Hines651f13c2014-04-23 16:59:28 -0700253 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700254 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Stephen Hines651f13c2014-04-23 16:59:28 -0700255
256 // For backward compatibility.
257 if (!IO.outputting()) {
258 IO.mapOptional("SpaceAfterControlStatementKeyword",
259 Style.SpaceBeforeParens);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700260 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
261 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
Stephen Hines651f13c2014-04-23 16:59:28 -0700262 }
263 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700264 IO.mapOptional("DisableFormat", Style.DisableFormat);
Stephen Hines651f13c2014-04-23 16:59:28 -0700265 }
266};
267
268// Allows to read vector<FormatStyle> while keeping default values.
269// IO.getContext() should contain a pointer to the FormatStyle structure, that
270// will be used to get default values for missing keys.
271// If the first element has no Language specified, it will be treated as the
272// default one for the following elements.
273template <> struct DocumentListTraits<std::vector<FormatStyle> > {
274 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
275 return Seq.size();
276 }
277 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
278 size_t Index) {
279 if (Index >= Seq.size()) {
280 assert(Index == Seq.size());
281 FormatStyle Template;
282 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
283 Template = Seq[0];
284 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700285 Template = *((const FormatStyle *)IO.getContext());
Stephen Hines651f13c2014-04-23 16:59:28 -0700286 Template.Language = FormatStyle::LK_None;
287 }
288 Seq.resize(Index + 1, Template);
289 }
290 return Seq[Index];
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000291 }
292};
293}
294}
295
Daniel Jasperbac016b2012-12-03 18:12:45 +0000296namespace clang {
297namespace format {
298
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700299const std::error_category &getParseCategory() {
300 static ParseErrorCategory C;
301 return C;
302}
303std::error_code make_error_code(ParseError e) {
304 return std::error_code(static_cast<int>(e), getParseCategory());
305}
306
307const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
308 return "clang-format.parse_error";
309}
310
311std::string ParseErrorCategory::message(int EV) const {
312 switch (static_cast<ParseError>(EV)) {
313 case ParseError::Success:
314 return "Success";
315 case ParseError::Error:
316 return "Invalid argument";
317 case ParseError::Unsuitable:
318 return "Unsuitable";
319 }
320 llvm_unreachable("unexpected parse error");
321}
322
Daniel Jasperbac016b2012-12-03 18:12:45 +0000323FormatStyle getLLVMStyle() {
324 FormatStyle LLVMStyle;
Stephen Hines651f13c2014-04-23 16:59:28 -0700325 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000326 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000327 LLVMStyle.AlignEscapedNewlinesLeft = false;
Stephen Hines176edba2014-12-01 14:53:08 -0800328 LLVMStyle.AlignAfterOpenBracket = true;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000329 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000330 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700331 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
332 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Stephen Hines176edba2014-12-01 14:53:08 -0800333 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000334 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000335 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Stephen Hines176edba2014-12-01 14:53:08 -0800336 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = false;
Alexander Kornienko56312022013-07-04 12:02:44 +0000337 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000338 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000339 LLVMStyle.BinPackParameters = true;
Stephen Hines176edba2014-12-01 14:53:08 -0800340 LLVMStyle.BinPackArguments = true;
341 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
Daniel Jasper1a896a52013-11-08 00:57:11 +0000342 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000343 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
344 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000345 LLVMStyle.ColumnLimit = 80;
Stephen Hines651f13c2014-04-23 16:59:28 -0700346 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkofb594862013-05-06 14:11:27 +0000347 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6315fec2013-08-13 10:58:30 +0000348 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Stephen Hines651f13c2014-04-23 16:59:28 -0700349 LLVMStyle.ContinuationIndentWidth = 4;
350 LLVMStyle.Cpp11BracedListStyle = true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700351 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000352 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700353 LLVMStyle.ForEachMacros.push_back("foreach");
354 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
355 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Alexander Kornienkofb594862013-05-06 14:11:27 +0000356 LLVMStyle.IndentCaseLabels = false;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700357 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000358 LLVMStyle.IndentWidth = 2;
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000359 LLVMStyle.TabWidth = 8;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000360 LLVMStyle.MaxEmptyLinesToKeep = 1;
Stephen Hines651f13c2014-04-23 16:59:28 -0700361 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000362 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Stephen Hines176edba2014-12-01 14:53:08 -0800363 LLVMStyle.ObjCBlockIndentWidth = 2;
Stephen Hines651f13c2014-04-23 16:59:28 -0700364 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Weber5f500df2013-01-10 20:12:55 +0000365 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700366 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000367 LLVMStyle.SpacesBeforeTrailingComments = 1;
Stephen Hines651f13c2014-04-23 16:59:28 -0700368 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000369 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000370 LLVMStyle.SpacesInParentheses = false;
Stephen Hines176edba2014-12-01 14:53:08 -0800371 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000372 LLVMStyle.SpaceInEmptyParentheses = false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700373 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000374 LLVMStyle.SpacesInCStyleCastParentheses = false;
Stephen Hines176edba2014-12-01 14:53:08 -0800375 LLVMStyle.SpaceAfterCStyleCast = false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700376 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasper9b4de852013-09-25 15:15:02 +0000377 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperd8ee5c12013-10-29 14:52:02 +0000378 LLVMStyle.SpacesInAngles = false;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000379
Stephen Hines651f13c2014-04-23 16:59:28 -0700380 LLVMStyle.PenaltyBreakComment = 300;
381 LLVMStyle.PenaltyBreakFirstLessLess = 120;
382 LLVMStyle.PenaltyBreakString = 1000;
383 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000384 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper47066e42013-10-25 14:29:37 +0000385 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000386
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700387 LLVMStyle.DisableFormat = false;
388
Daniel Jasperbac016b2012-12-03 18:12:45 +0000389 return LLVMStyle;
390}
391
Stephen Hines651f13c2014-04-23 16:59:28 -0700392FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
393 FormatStyle GoogleStyle = getLLVMStyle();
394 GoogleStyle.Language = Language;
395
Daniel Jasperbac016b2012-12-03 18:12:45 +0000396 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000397 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000398 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper1bee0732013-05-23 18:05:18 +0000399 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko56312022013-07-04 12:02:44 +0000400 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000401 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000402 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700403 GoogleStyle.DerivePointerAlignment = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000404 GoogleStyle.IndentCaseLabels = true;
Stephen Hines651f13c2014-04-23 16:59:28 -0700405 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
406 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Weber5f500df2013-01-10 20:12:55 +0000407 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700408 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000409 GoogleStyle.SpacesBeforeTrailingComments = 2;
410 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000411
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000412 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper47066e42013-10-25 14:29:37 +0000413 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000414
Stephen Hines176edba2014-12-01 14:53:08 -0800415 if (Language == FormatStyle::LK_Java) {
416 GoogleStyle.AlignAfterOpenBracket = false;
417 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
418 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
419 GoogleStyle.ColumnLimit = 100;
420 GoogleStyle.SpaceAfterCStyleCast = true;
421 GoogleStyle.SpacesBeforeTrailingComments = 1;
422 } else if (Language == FormatStyle::LK_JavaScript) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700423 GoogleStyle.BreakBeforeTernaryOperators = false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700424 GoogleStyle.MaxEmptyLinesToKeep = 3;
Stephen Hines651f13c2014-04-23 16:59:28 -0700425 GoogleStyle.SpacesInContainerLiterals = false;
Stephen Hines176edba2014-12-01 14:53:08 -0800426 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Stephen Hines651f13c2014-04-23 16:59:28 -0700427 } else if (Language == FormatStyle::LK_Proto) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700428 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
429 GoogleStyle.SpacesInContainerLiterals = false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700430 }
431
Daniel Jasperbac016b2012-12-03 18:12:45 +0000432 return GoogleStyle;
433}
434
Stephen Hines651f13c2014-04-23 16:59:28 -0700435FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
436 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Daniel Jasperf1579602013-01-29 16:03:49 +0000437 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700438 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000439 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000440 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000441 ChromiumStyle.BinPackParameters = false;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700442 ChromiumStyle.DerivePointerAlignment = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000443 return ChromiumStyle;
444}
445
Alexander Kornienkofb594862013-05-06 14:11:27 +0000446FormatStyle getMozillaStyle() {
447 FormatStyle MozillaStyle = getLLVMStyle();
448 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700449 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000450 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700451 MozillaStyle.DerivePointerAlignment = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000452 MozillaStyle.IndentCaseLabels = true;
Stephen Hines651f13c2014-04-23 16:59:28 -0700453 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000454 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
455 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700456 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Stephen Hines651f13c2014-04-23 16:59:28 -0700457 MozillaStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000458 return MozillaStyle;
459}
460
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000461FormatStyle getWebKitStyle() {
462 FormatStyle Style = getLLVMStyle();
Daniel Jaspereff18b92013-07-31 23:16:02 +0000463 Style.AccessModifierOffset = -4;
Stephen Hines176edba2014-12-01 14:53:08 -0800464 Style.AlignAfterOpenBracket = false;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000465 Style.AlignTrailingComments = false;
Stephen Hines176edba2014-12-01 14:53:08 -0800466 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000467 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000468 Style.BreakConstructorInitializersBeforeComma = true;
Stephen Hines651f13c2014-04-23 16:59:28 -0700469 Style.Cpp11BracedListStyle = false;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000470 Style.ColumnLimit = 0;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000471 Style.IndentWidth = 4;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000472 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Stephen Hines176edba2014-12-01 14:53:08 -0800473 Style.ObjCBlockIndentWidth = 4;
Stephen Hines651f13c2014-04-23 16:59:28 -0700474 Style.ObjCSpaceAfterProperty = true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700475 Style.PointerAlignment = FormatStyle::PAS_Left;
Stephen Hines651f13c2014-04-23 16:59:28 -0700476 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000477 return Style;
478}
479
Stephen Hines651f13c2014-04-23 16:59:28 -0700480FormatStyle getGNUStyle() {
481 FormatStyle Style = getLLVMStyle();
Stephen Hines176edba2014-12-01 14:53:08 -0800482 Style.AlwaysBreakAfterDefinitionReturnType = true;
483 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Stephen Hines651f13c2014-04-23 16:59:28 -0700484 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
485 Style.BreakBeforeTernaryOperators = true;
486 Style.Cpp11BracedListStyle = false;
487 Style.ColumnLimit = 79;
488 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
489 Style.Standard = FormatStyle::LS_Cpp03;
490 return Style;
491}
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000492
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700493FormatStyle getNoStyle() {
494 FormatStyle NoStyle = getLLVMStyle();
495 NoStyle.DisableFormat = true;
496 return NoStyle;
497}
498
Stephen Hines651f13c2014-04-23 16:59:28 -0700499bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
500 FormatStyle *Style) {
501 if (Name.equals_lower("llvm")) {
502 *Style = getLLVMStyle();
503 } else if (Name.equals_lower("chromium")) {
504 *Style = getChromiumStyle(Language);
505 } else if (Name.equals_lower("mozilla")) {
506 *Style = getMozillaStyle();
507 } else if (Name.equals_lower("google")) {
508 *Style = getGoogleStyle(Language);
509 } else if (Name.equals_lower("webkit")) {
510 *Style = getWebKitStyle();
511 } else if (Name.equals_lower("gnu")) {
512 *Style = getGNUStyle();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700513 } else if (Name.equals_lower("none")) {
514 *Style = getNoStyle();
Stephen Hines651f13c2014-04-23 16:59:28 -0700515 } else {
516 return false;
517 }
518
519 Style->Language = Language;
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000520 return true;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000521}
522
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700523std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700524 assert(Style);
525 FormatStyle::LanguageKind Language = Style->Language;
526 assert(Language != FormatStyle::LK_None);
Alexander Kornienko107db3c2013-05-20 15:18:01 +0000527 if (Text.trim().empty())
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700528 return make_error_code(ParseError::Error);
Stephen Hines651f13c2014-04-23 16:59:28 -0700529
530 std::vector<FormatStyle> Styles;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000531 llvm::yaml::Input Input(Text);
Stephen Hines651f13c2014-04-23 16:59:28 -0700532 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
533 // values for the fields, keys for which are missing from the configuration.
534 // Mapping also uses the context to get the language to find the correct
535 // base style.
536 Input.setContext(Style);
537 Input >> Styles;
538 if (Input.error())
539 return Input.error();
540
541 for (unsigned i = 0; i < Styles.size(); ++i) {
542 // Ensures that only the first configuration can skip the Language option.
543 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700544 return make_error_code(ParseError::Error);
Stephen Hines651f13c2014-04-23 16:59:28 -0700545 // Ensure that each language is configured at most once.
546 for (unsigned j = 0; j < i; ++j) {
547 if (Styles[i].Language == Styles[j].Language) {
548 DEBUG(llvm::dbgs()
549 << "Duplicate languages in the config file on positions " << j
550 << " and " << i << "\n");
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700551 return make_error_code(ParseError::Error);
Stephen Hines651f13c2014-04-23 16:59:28 -0700552 }
553 }
554 }
555 // Look for a suitable configuration starting from the end, so we can
556 // find the configuration for the specific language first, and the default
557 // configuration (which can only be at slot 0) after it.
558 for (int i = Styles.size() - 1; i >= 0; --i) {
559 if (Styles[i].Language == Language ||
560 Styles[i].Language == FormatStyle::LK_None) {
561 *Style = Styles[i];
562 Style->Language = Language;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700563 return make_error_code(ParseError::Success);
Stephen Hines651f13c2014-04-23 16:59:28 -0700564 }
565 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700566 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000567}
568
569std::string configurationAsText(const FormatStyle &Style) {
570 std::string Text;
571 llvm::raw_string_ostream Stream(Text);
572 llvm::yaml::Output Output(Stream);
573 // We use the same mapping method for input and output, so we need a non-const
574 // reference here.
575 FormatStyle NonConstStyle = Style;
576 Output << NonConstStyle;
Alexander Kornienko2b6acb62013-05-13 12:56:35 +0000577 return Stream.str();
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000578}
579
Craig Topper83f81d72013-06-30 22:29:28 +0000580namespace {
581
Stephen Hines176edba2014-12-01 14:53:08 -0800582bool startsExternCBlock(const AnnotatedLine &Line) {
583 const FormatToken *Next = Line.First->getNextNonComment();
584 const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr;
585 return Line.First->is(tok::kw_extern) && Next && Next->isStringLiteral() &&
586 NextNext && NextNext->is(tok::l_brace);
587}
588
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000589class NoColumnLimitFormatter {
590public:
Daniel Jasper34f3d052013-08-21 08:39:01 +0000591 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000592
593 /// \brief Formats the line starting at \p State, simply keeping all of the
594 /// input's line breaking decisions.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000595 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasperb77d7412013-09-06 07:54:20 +0000596 LineState State =
597 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700598 while (State.NextToken) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000599 bool Newline =
600 Indenter->mustBreak(State) ||
601 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
602 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
603 }
604 }
Daniel Jasper34f3d052013-08-21 08:39:01 +0000605
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000606private:
607 ContinuationIndenter *Indenter;
608};
609
Daniel Jasper4281d732013-11-06 23:12:09 +0000610class LineJoiner {
611public:
612 LineJoiner(const FormatStyle &Style) : Style(Style) {}
613
614 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
615 unsigned
616 tryFitMultipleLinesInOne(unsigned Indent,
Stephen Hines651f13c2014-04-23 16:59:28 -0700617 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper4281d732013-11-06 23:12:09 +0000618 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
619 // We can never merge stuff if there are trailing line comments.
Stephen Hines651f13c2014-04-23 16:59:28 -0700620 const AnnotatedLine *TheLine = *I;
Daniel Jasper4281d732013-11-06 23:12:09 +0000621 if (TheLine->Last->Type == TT_LineComment)
622 return 0;
623
Stephen Hines651f13c2014-04-23 16:59:28 -0700624 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
Daniel Jasper4281d732013-11-06 23:12:09 +0000625 return 0;
626
Daniel Jasperc2e03292013-11-08 17:33:27 +0000627 unsigned Limit =
628 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper4281d732013-11-06 23:12:09 +0000629 // If we already exceed the column limit, we set 'Limit' to 0. The different
630 // tryMerge..() functions can then decide whether to still do merging.
631 Limit = TheLine->Last->TotalLength > Limit
632 ? 0
633 : Limit - TheLine->Last->TotalLength;
634
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700635 if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
Daniel Jasper4281d732013-11-06 23:12:09 +0000636 return 0;
637
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700638 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
639 // If necessary, change to something smarter.
640 bool MergeShortFunctions =
641 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
642 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
643 TheLine->Level != 0);
644
Stephen Hines651f13c2014-04-23 16:59:28 -0700645 if (TheLine->Last->Type == TT_FunctionLBrace &&
646 TheLine->First != TheLine->Last) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700647 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
Stephen Hines651f13c2014-04-23 16:59:28 -0700648 }
Daniel Jasper4281d732013-11-06 23:12:09 +0000649 if (TheLine->Last->is(tok::l_brace)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700650 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
651 ? tryMergeSimpleBlock(I, E, Limit)
652 : 0;
653 }
654 if (I[1]->First->Type == TT_FunctionLBrace &&
655 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
656 // Check for Limit <= 2 to account for the " {".
657 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
658 return 0;
659 Limit -= 2;
660
661 unsigned MergedLines = 0;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700662 if (MergeShortFunctions) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700663 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
664 // If we managed to merge the block, count the function header, which is
665 // on a separate line.
666 if (MergedLines > 0)
667 ++MergedLines;
668 }
669 return MergedLines;
670 }
671 if (TheLine->First->is(tok::kw_if)) {
672 return Style.AllowShortIfStatementsOnASingleLine
673 ? tryMergeSimpleControlStatement(I, E, Limit)
674 : 0;
675 }
676 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
677 return Style.AllowShortLoopsOnASingleLine
678 ? tryMergeSimpleControlStatement(I, E, Limit)
679 : 0;
680 }
Stephen Hines176edba2014-12-01 14:53:08 -0800681 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
682 return Style.AllowShortCaseLabelsOnASingleLine
683 ? tryMergeShortCaseLabels(I, E, Limit)
684 : 0;
685 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700686 if (TheLine->InPPDirective &&
687 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper4281d732013-11-06 23:12:09 +0000688 return tryMergeSimplePPDirective(I, E, Limit);
689 }
690 return 0;
691 }
692
693private:
694 unsigned
Stephen Hines651f13c2014-04-23 16:59:28 -0700695 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper4281d732013-11-06 23:12:09 +0000696 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
697 unsigned Limit) {
698 if (Limit == 0)
699 return 0;
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000700 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper4281d732013-11-06 23:12:09 +0000701 return 0;
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000702 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper4281d732013-11-06 23:12:09 +0000703 return 0;
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000704 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper4281d732013-11-06 23:12:09 +0000705 return 0;
706 return 1;
707 }
708
709 unsigned tryMergeSimpleControlStatement(
Stephen Hines651f13c2014-04-23 16:59:28 -0700710 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper4281d732013-11-06 23:12:09 +0000711 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
712 if (Limit == 0)
713 return 0;
Stephen Hines651f13c2014-04-23 16:59:28 -0700714 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
715 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700716 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
Daniel Jasper4281d732013-11-06 23:12:09 +0000717 return 0;
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000718 if (I[1]->InPPDirective != (*I)->InPPDirective ||
719 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper4281d732013-11-06 23:12:09 +0000720 return 0;
Stephen Hines651f13c2014-04-23 16:59:28 -0700721 Limit = limitConsideringMacros(I + 1, E, Limit);
Daniel Jasper4281d732013-11-06 23:12:09 +0000722 AnnotatedLine &Line = **I;
723 if (Line.Last->isNot(tok::r_paren))
724 return 0;
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000725 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper4281d732013-11-06 23:12:09 +0000726 return 0;
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000727 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Stephen Hines651f13c2014-04-23 16:59:28 -0700728 tok::kw_while) ||
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000729 I[1]->First->Type == TT_LineComment)
Daniel Jasper4281d732013-11-06 23:12:09 +0000730 return 0;
731 // Only inline simple if's (no nested if or else).
732 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000733 I[2]->First->is(tok::kw_else))
Daniel Jasper4281d732013-11-06 23:12:09 +0000734 return 0;
735 return 1;
736 }
737
Stephen Hines176edba2014-12-01 14:53:08 -0800738 unsigned tryMergeShortCaseLabels(
739 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
740 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
741 if (Limit == 0 || I + 1 == E ||
742 I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
743 return 0;
744 unsigned NumStmts = 0;
745 unsigned Length = 0;
746 for (; NumStmts < 3; ++NumStmts) {
747 if (I + 1 + NumStmts == E)
748 break;
749 const AnnotatedLine *Line = I[1 + NumStmts];
750 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
751 break;
752 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
753 tok::kw_while))
754 return 0;
755 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
756 }
757 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
758 return 0;
759 return NumStmts;
760 }
761
Daniel Jasper4281d732013-11-06 23:12:09 +0000762 unsigned
Stephen Hines651f13c2014-04-23 16:59:28 -0700763 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper4281d732013-11-06 23:12:09 +0000764 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
765 unsigned Limit) {
Daniel Jasper4281d732013-11-06 23:12:09 +0000766 AnnotatedLine &Line = **I;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700767
768 // Don't merge ObjC @ keywords and methods.
769 if (Line.First->isOneOf(tok::at, tok::minus, tok::plus))
Daniel Jasper4281d732013-11-06 23:12:09 +0000770 return 0;
771
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700772 // Check that the current line allows merging. This depends on whether we
773 // are in a control flow statements as well as several style flags.
774 if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
775 return 0;
776 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
777 tok::kw_catch, tok::kw_for, tok::r_brace)) {
778 if (!Style.AllowShortBlocksOnASingleLine)
779 return 0;
780 if (!Style.AllowShortIfStatementsOnASingleLine &&
781 Line.First->is(tok::kw_if))
782 return 0;
783 if (!Style.AllowShortLoopsOnASingleLine &&
784 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
785 return 0;
786 // FIXME: Consider an option to allow short exception handling clauses on
787 // a single line.
788 if (Line.First->isOneOf(tok::kw_try, tok::kw_catch))
789 return 0;
790 }
791
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000792 FormatToken *Tok = I[1]->First;
Daniel Jasper4281d732013-11-06 23:12:09 +0000793 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700794 (Tok->getNextNonComment() == nullptr ||
Daniel Jasper4281d732013-11-06 23:12:09 +0000795 Tok->getNextNonComment()->is(tok::semi))) {
796 // We merge empty blocks even if the line exceeds the column limit.
797 Tok->SpacesRequiredBefore = 0;
798 Tok->CanBreakBefore = true;
799 return 1;
Stephen Hines176edba2014-12-01 14:53:08 -0800800 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace) &&
801 !startsExternCBlock(Line)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700802 // We don't merge short records.
803 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
804 return 0;
805
Daniel Jasper4281d732013-11-06 23:12:09 +0000806 // Check that we still have three lines and they fit into the limit.
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000807 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper4281d732013-11-06 23:12:09 +0000808 return 0;
Stephen Hines651f13c2014-04-23 16:59:28 -0700809 Limit = limitConsideringMacros(I + 2, E, Limit);
Daniel Jasper4281d732013-11-06 23:12:09 +0000810
811 if (!nextTwoLinesFitInto(I, Limit))
812 return 0;
813
814 // Second, check that the next line does not contain any braces - if it
815 // does, readability declines when putting it into a single line.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700816 if (I[1]->Last->Type == TT_LineComment)
Daniel Jasper4281d732013-11-06 23:12:09 +0000817 return 0;
818 do {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700819 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
Daniel Jasper4281d732013-11-06 23:12:09 +0000820 return 0;
821 Tok = Tok->Next;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700822 } while (Tok);
Daniel Jasper4281d732013-11-06 23:12:09 +0000823
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700824 // Last, check that the third line starts with a closing brace.
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000825 Tok = I[2]->First;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700826 if (Tok->isNot(tok::r_brace))
Daniel Jasper4281d732013-11-06 23:12:09 +0000827 return 0;
828
829 return 2;
830 }
831 return 0;
832 }
833
Stephen Hines651f13c2014-04-23 16:59:28 -0700834 /// Returns the modified column limit for \p I if it is inside a macro and
835 /// needs a trailing '\'.
836 unsigned
837 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
838 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
839 unsigned Limit) {
840 if (I[0]->InPPDirective && I + 1 != E &&
841 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
842 return Limit < 2 ? 0 : Limit - 2;
843 }
844 return Limit;
845 }
846
Daniel Jasper4281d732013-11-06 23:12:09 +0000847 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
848 unsigned Limit) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700849 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
850 return false;
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000851 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper4281d732013-11-06 23:12:09 +0000852 }
853
Stephen Hines651f13c2014-04-23 16:59:28 -0700854 bool containsMustBreak(const AnnotatedLine *Line) {
855 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
856 if (Tok->MustBreakBefore)
857 return true;
858 }
859 return false;
860 }
861
Daniel Jasper4281d732013-11-06 23:12:09 +0000862 const FormatStyle &Style;
863};
864
Daniel Jasperbac016b2012-12-03 18:12:45 +0000865class UnwrappedLineFormatter {
866public:
Stephen Hines651f13c2014-04-23 16:59:28 -0700867 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper567dcf92013-09-05 09:29:45 +0000868 WhitespaceManager *Whitespaces,
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000869 const FormatStyle &Style)
Stephen Hines651f13c2014-04-23 16:59:28 -0700870 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
871 Joiner(Style) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000872
Daniel Jasper4281d732013-11-06 23:12:09 +0000873 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Stephen Hines651f13c2014-04-23 16:59:28 -0700874 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700875 // Try to look up already computed penalty in DryRun-mode.
876 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
877 &Lines, AdditionalIndent);
878 auto CacheIt = PenaltyCache.find(CacheKey);
879 if (DryRun && CacheIt != PenaltyCache.end())
880 return CacheIt->second;
881
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000882 assert(!Lines.empty());
883 unsigned Penalty = 0;
884 std::vector<int> IndentForLevel;
885 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
886 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700887 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper4281d732013-11-06 23:12:09 +0000888 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
889 E = Lines.end();
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000890 I != E; ++I) {
891 const AnnotatedLine &TheLine = **I;
892 const FormatToken *FirstTok = TheLine.First;
893 int Offset = getIndentOffset(*FirstTok);
894
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000895 // Determine indent and try to merge multiple unwrapped lines.
Stephen Hines651f13c2014-04-23 16:59:28 -0700896 unsigned Indent;
897 if (TheLine.InPPDirective) {
898 Indent = TheLine.Level * Style.IndentWidth;
899 } else {
900 while (IndentForLevel.size() <= TheLine.Level)
901 IndentForLevel.push_back(-1);
902 IndentForLevel.resize(TheLine.Level + 1);
903 Indent = getIndent(IndentForLevel, TheLine.Level);
904 }
905 unsigned LevelIndent = Indent;
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000906 if (static_cast<int>(Indent) + Offset >= 0)
907 Indent += Offset;
Stephen Hines651f13c2014-04-23 16:59:28 -0700908
909 // Merge multiple lines if possible.
Daniel Jasper4281d732013-11-06 23:12:09 +0000910 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
Stephen Hines651f13c2014-04-23 16:59:28 -0700911 if (MergedLines > 0 && Style.ColumnLimit == 0) {
912 // Disallow line merging if there is a break at the start of one of the
913 // input lines.
914 for (unsigned i = 0; i < MergedLines; ++i) {
915 if (I[i + 1]->First->NewlinesBefore > 0)
916 MergedLines = 0;
917 }
918 }
Daniel Jasper4281d732013-11-06 23:12:09 +0000919 if (!DryRun) {
920 for (unsigned i = 0; i < MergedLines; ++i) {
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000921 join(*I[i], *I[i + 1]);
Daniel Jasper4281d732013-11-06 23:12:09 +0000922 }
923 }
924 I += MergedLines;
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000925
Stephen Hines651f13c2014-04-23 16:59:28 -0700926 bool FixIndentation =
927 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000928 if (TheLine.First->is(tok::eof)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700929 if (PreviousLine && PreviousLine->Affected && !DryRun) {
930 // Remove the file's trailing whitespace.
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000931 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
932 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
933 /*IndentLevel=*/0, /*Spaces=*/0,
934 /*TargetColumn=*/0);
935 }
936 } else if (TheLine.Type != LT_Invalid &&
Stephen Hines651f13c2014-04-23 16:59:28 -0700937 (TheLine.Affected || FixIndentation)) {
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000938 if (FirstTok->WhitespaceRange.isValid()) {
939 if (!DryRun)
940 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
941 Indent, TheLine.InPPDirective);
942 } else {
943 Indent = LevelIndent = FirstTok->OriginalColumn;
944 }
945
946 // If everything fits on a single line, just put it there.
947 unsigned ColumnLimit = Style.ColumnLimit;
948 if (I + 1 != E) {
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000949 AnnotatedLine *NextLine = I[1];
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000950 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
951 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
952 }
953
954 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
955 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700956 while (State.NextToken) {
957 formatChildren(State, /*Newline=*/false, /*DryRun=*/false, Penalty);
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000958 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700959 }
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000960 } else if (Style.ColumnLimit == 0) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700961 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000962 NoColumnLimitFormatter Formatter(Indenter);
963 if (!DryRun)
964 Formatter.format(Indent, &TheLine);
965 } else {
966 Penalty += format(TheLine, Indent, DryRun);
967 }
968
Stephen Hines651f13c2014-04-23 16:59:28 -0700969 if (!TheLine.InPPDirective)
970 IndentForLevel[TheLine.Level] = LevelIndent;
971 } else if (TheLine.ChildrenAffected) {
972 format(TheLine.Children, DryRun);
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000973 } else {
974 // Format the first token if necessary, and notify the WhitespaceManager
975 // about the unchanged whitespace.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700976 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000977 if (Tok == TheLine.First &&
978 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
979 unsigned LevelIndent = Tok->OriginalColumn;
980 if (!DryRun) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700981 // Remove trailing whitespace of the previous line.
982 if ((PreviousLine && PreviousLine->Affected) ||
983 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000984 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
985 TheLine.InPPDirective);
986 } else {
987 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
988 }
989 }
990
991 if (static_cast<int>(LevelIndent) - Offset >= 0)
992 LevelIndent -= Offset;
Stephen Hines651f13c2014-04-23 16:59:28 -0700993 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000994 IndentForLevel[TheLine.Level] = LevelIndent;
995 } else if (!DryRun) {
996 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
997 }
998 }
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000999 }
1000 if (!DryRun) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001001 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001002 Tok->Finalized = true;
1003 }
1004 }
1005 PreviousLine = *I;
1006 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001007 PenaltyCache[CacheKey] = Penalty;
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001008 return Penalty;
1009 }
1010
1011private:
1012 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001013 ///
1014 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001015 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
1016 bool DryRun) {
Daniel Jasperb77d7412013-09-06 07:54:20 +00001017 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001018
Daniel Jasperce3d1a62013-02-08 08:22:00 +00001019 // If the ObjC method declaration does not fit on a line, we should format
1020 // it with one arg per line.
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001021 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperce3d1a62013-02-08 08:22:00 +00001022 State.Stack.back().BreakBeforeParameter = true;
1023
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001024 // Find best solution in solution space.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001025 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001026 }
1027
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001028 /// \brief An edge in the solution space from \c Previous->State to \c State,
1029 /// inserting a newline dependent on the \c NewLine.
1030 struct StateNode {
1031 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +00001032 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001033 LineState State;
1034 bool NewLine;
1035 StateNode *Previous;
1036 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001037
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001038 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
1039 ///
1040 /// In case of equal penalties, we want to prefer states that were inserted
1041 /// first. During state generation we make sure that we insert states first
1042 /// that break the line as late as possible.
1043 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1044
1045 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
1046 /// \c State has the given \c OrderedPenalty.
1047 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1048
1049 /// \brief The BFS queue type.
1050 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1051 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001052
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001053 /// \brief Get the offset of the line relatively to the level.
1054 ///
1055 /// For example, 'public:' labels in classes are offset by 1 or 2
1056 /// characters to the left from their level.
1057 int getIndentOffset(const FormatToken &RootToken) {
Stephen Hines176edba2014-12-01 14:53:08 -08001058 if (Style.Language == FormatStyle::LK_Java)
1059 return 0;
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001060 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
1061 return Style.AccessModifierOffset;
1062 return 0;
1063 }
1064
1065 /// \brief Add a new line and the required indent before the first Token
1066 /// of the \c UnwrappedLine if there was no structural parsing error.
1067 void formatFirstToken(FormatToken &RootToken,
1068 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
1069 unsigned Indent, bool InPPDirective) {
1070 unsigned Newlines =
1071 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1072 // Remove empty lines before "}" where applicable.
1073 if (RootToken.is(tok::r_brace) &&
1074 (!RootToken.Next ||
1075 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1076 Newlines = std::min(Newlines, 1u);
1077 if (Newlines == 0 && !RootToken.IsFirst)
1078 Newlines = 1;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001079 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1080 Newlines = 0;
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001081
Stephen Hines651f13c2014-04-23 16:59:28 -07001082 // Remove empty lines after "{".
1083 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1084 PreviousLine->Last->is(tok::l_brace) &&
Stephen Hines176edba2014-12-01 14:53:08 -08001085 PreviousLine->First->isNot(tok::kw_namespace) &&
1086 !startsExternCBlock(*PreviousLine))
Stephen Hines651f13c2014-04-23 16:59:28 -07001087 Newlines = 1;
1088
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001089 // Insert extra new line before access specifiers.
1090 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1091 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1092 ++Newlines;
1093
1094 // Remove empty lines after access specifiers.
1095 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
1096 Newlines = std::min(1u, Newlines);
1097
Stephen Hines651f13c2014-04-23 16:59:28 -07001098 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
1099 Indent, InPPDirective &&
1100 !RootToken.HasUnescapedNewline);
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001101 }
1102
1103 /// \brief Get the indent of \p Level from \p IndentForLevel.
1104 ///
1105 /// \p IndentForLevel must contain the indent for the level \c l
1106 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1107 /// that level is unknown.
Stephen Hines176edba2014-12-01 14:53:08 -08001108 unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) {
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001109 if (IndentForLevel[Level] != -1)
1110 return IndentForLevel[Level];
1111 if (Level == 0)
1112 return 0;
1113 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
1114 }
1115
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001116 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1117 assert(!A.Last->Next);
1118 assert(!B.First->Previous);
Stephen Hines651f13c2014-04-23 16:59:28 -07001119 if (B.Affected)
1120 A.Affected = true;
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001121 A.Last->Next = B.First;
1122 B.First->Previous = A.Last;
Daniel Jasperc2e03292013-11-08 17:33:27 +00001123 B.First->CanBreakBefore = true;
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001124 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1125 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1126 Tok->TotalLength += LengthA;
1127 A.Last = Tok;
1128 }
1129 }
1130
1131 unsigned getColumnLimit(bool InPPDirective) const {
1132 // In preprocessor directives reserve two chars for trailing " \"
1133 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1134 }
1135
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001136 struct CompareLineStatePointers {
1137 bool operator()(LineState *obj1, LineState *obj2) const {
1138 return *obj1 < *obj2;
1139 }
1140 };
1141
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001142 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +00001143 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001144 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1145 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1146 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper567dcf92013-09-05 09:29:45 +00001147 /// to a state where all tokens are placed. Returns the penalty.
1148 ///
1149 /// If \p DryRun is \c false, directly applies the changes.
1150 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001151 std::set<LineState *, CompareLineStatePointers> Seen;
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001152
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001153 // Increasing count of \c StateNode items we have created. This is used to
1154 // create a deterministic order independent of the container.
1155 unsigned Count = 0;
1156 QueueType Queue;
1157
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001158 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +00001159 StateNode *Node =
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001160 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001161 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1162 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001163
Daniel Jasper567dcf92013-09-05 09:29:45 +00001164 unsigned Penalty = 0;
1165
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001166 // While not empty, take first element and follow edges.
1167 while (!Queue.empty()) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001168 Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +00001169 StateNode *Node = Queue.top().second;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001170 if (!Node->State.NextToken) {
Alexander Kornienkodd256312013-05-10 11:56:10 +00001171 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001172 break;
Daniel Jasper01786732013-02-04 07:21:18 +00001173 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001174 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001175
Daniel Jasper54b4e442013-05-22 05:27:42 +00001176 // Cut off the analysis of certain solutions if the analysis gets too
1177 // complex. See description of IgnoreStackForComparison.
1178 if (Count > 10000)
1179 Node->State.IgnoreStackForComparison = true;
1180
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001181 if (!Seen.insert(&Node->State).second)
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001182 // State already examined with lower penalty.
1183 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001184
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001185 FormatDecision LastFormat = Node->State.NextToken->Decision;
1186 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001187 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001188 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001189 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001190 }
1191
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001192 if (Queue.empty()) {
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001193 // We were unable to find a solution, do nothing.
1194 // FIXME: Add diagnostic?
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001195 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper567dcf92013-09-05 09:29:45 +00001196 return 0;
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001197 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001198
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001199 // Reconstruct the solution.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001200 if (!DryRun)
1201 reconstructPath(InitialState, Queue.top().second);
1202
Alexander Kornienkodd256312013-05-10 11:56:10 +00001203 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1204 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper567dcf92013-09-05 09:29:45 +00001205
1206 return Penalty;
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001207 }
1208
1209 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek9c333b92013-05-29 15:10:11 +00001210 std::deque<StateNode *> Path;
1211 // We do not need a break before the initial token.
1212 while (Current->Previous) {
1213 Path.push_front(Current);
1214 Current = Current->Previous;
1215 }
1216 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1217 I != E; ++I) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001218 unsigned Penalty = 0;
1219 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1220 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1221
Manuel Klimek9c333b92013-05-29 15:10:11 +00001222 DEBUG({
1223 if ((*I)->NewLine) {
Daniel Jasperd4a03db2013-08-22 15:00:41 +00001224 llvm::dbgs() << "Penalty for placing "
Manuel Klimek9c333b92013-05-29 15:10:11 +00001225 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasperd4a03db2013-08-22 15:00:41 +00001226 << Penalty << "\n";
Manuel Klimek9c333b92013-05-29 15:10:11 +00001227 }
1228 });
Manuel Klimek9c333b92013-05-29 15:10:11 +00001229 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001230 }
1231
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001232 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001233 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001234 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001235 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001236 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001237 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +00001238 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001239 return;
Daniel Jasper6b2afe42013-08-16 11:20:30 +00001240 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001241 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001242
1243 StateNode *Node = new (Allocator.Allocate())
1244 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper567dcf92013-09-05 09:29:45 +00001245 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1246 return;
1247
Daniel Jasper6b2afe42013-08-16 11:20:30 +00001248 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001249
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001250 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1251 ++(*Count);
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001252 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001253
Daniel Jasper1a925bc2013-09-05 10:48:50 +00001254 /// \brief If the \p State's next token is an r_brace closing a nested block,
1255 /// format the nested block before it.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001256 ///
1257 /// Returns \c true if all children could be placed successfully and adapts
1258 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1259 /// creates changes using \c Whitespaces.
1260 ///
1261 /// The crucial idea here is that children always get formatted upon
1262 /// encountering the closing brace right after the nested block. Now, if we
1263 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1264 /// \c false), the entire block has to be kept on the same line (which is only
1265 /// possible if it fits on the line, only contains a single statement, etc.
1266 ///
1267 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1268 /// break after the "{", format all lines with correct indentation and the put
1269 /// the closing "}" on yet another new line.
1270 ///
1271 /// This enables us to keep the simple structure of the
1272 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1273 /// break or don't break.
1274 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1275 unsigned &Penalty) {
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001276 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasper15eef852013-10-20 17:28:32 +00001277 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1278 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1279 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasper1a925bc2013-09-05 10:48:50 +00001280 // The previous token does not open a block. Nothing to do. We don't
1281 // assert so that we can simply call this function for all tokens.
Daniel Jasper2f0a0202013-09-06 08:54:24 +00001282 return true;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001283
1284 if (NewLine) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001285 int AdditionalIndent =
1286 State.FirstIndent - State.Line->Level * Style.IndentWidth;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001287 if (State.Stack.size() < 2 ||
1288 !State.Stack[State.Stack.size() - 2].JSFunctionInlined) {
1289 AdditionalIndent = State.Stack.back().Indent -
1290 Previous.Children[0]->Level * Style.IndentWidth;
1291 }
1292
Stephen Hines651f13c2014-04-23 16:59:28 -07001293 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1294 /*FixBadIndentation=*/true);
Daniel Jasper567dcf92013-09-05 09:29:45 +00001295 return true;
1296 }
1297
Stephen Hines176edba2014-12-01 14:53:08 -08001298 if (Previous.Children[0]->First->MustBreakBefore)
1299 return false;
1300
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001301 // Cannot merge multiple statements into a single line.
Daniel Jasper15eef852013-10-20 17:28:32 +00001302 if (Previous.Children.size() > 1)
Stephen Hines651f13c2014-04-23 16:59:28 -07001303 return false;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001304
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001305 // Cannot merge into one line if this line ends on a comment.
1306 if (Previous.is(tok::comment))
1307 return false;
1308
Daniel Jasper567dcf92013-09-05 09:29:45 +00001309 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasper15eef852013-10-20 17:28:32 +00001310 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper567dcf92013-09-05 09:29:45 +00001311 return false;
1312
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001313 // If the child line exceeds the column limit, we wouldn't want to merge it.
1314 // We add +2 for the trailing " }".
1315 if (Style.ColumnLimit > 0 &&
1316 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
1317 Style.ColumnLimit)
1318 return false;
1319
Daniel Jasper567dcf92013-09-05 09:29:45 +00001320 if (!DryRun) {
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +00001321 Whitespaces->replaceWhitespace(
Daniel Jasper15eef852013-10-20 17:28:32 +00001322 *Previous.Children[0]->First,
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +00001323 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +00001324 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper567dcf92013-09-05 09:29:45 +00001325 }
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001326 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper567dcf92013-09-05 09:29:45 +00001327
Daniel Jasper15eef852013-10-20 17:28:32 +00001328 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001329 return true;
1330 }
1331
Daniel Jasper6b2afe42013-08-16 11:20:30 +00001332 ContinuationIndenter *Indenter;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001333 WhitespaceManager *Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001334 FormatStyle Style;
Daniel Jasper4281d732013-11-06 23:12:09 +00001335 LineJoiner Joiner;
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001336
1337 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001338
1339 // Cache to store the penalty of formatting a vector of AnnotatedLines
1340 // starting from a specific additional offset. Improves performance if there
1341 // are many nested blocks.
1342 std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
1343 unsigned> PenaltyCache;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001344};
1345
Manuel Klimek96e888b2013-05-28 11:55:06 +00001346class FormatTokenLexer {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001347public:
Stephen Hines176edba2014-12-01 14:53:08 -08001348 FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
Alexander Kornienko00895102013-06-05 14:09:10 +00001349 encoding::Encoding Encoding)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001350 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
Stephen Hines176edba2014-12-01 14:53:08 -08001351 Column(0), TrailingWhitespace(0), SourceMgr(SourceMgr), ID(ID),
1352 Style(Style), IdentTable(getFormattingLangOpts(Style)),
1353 Keywords(IdentTable), Encoding(Encoding), FirstInLineIndex(0),
1354 FormattingDisabled(false) {
1355 Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
1356 getFormattingLangOpts(Style)));
1357 Lex->SetKeepWhitespaceMode(true);
Stephen Hines651f13c2014-04-23 16:59:28 -07001358
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001359 for (const std::string &ForEachMacro : Style.ForEachMacros)
Stephen Hines651f13c2014-04-23 16:59:28 -07001360 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1361 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001362 }
1363
Manuel Klimek96e888b2013-05-28 11:55:06 +00001364 ArrayRef<FormatToken *> lex() {
1365 assert(Tokens.empty());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001366 assert(FirstInLineIndex == 0);
Manuel Klimek96e888b2013-05-28 11:55:06 +00001367 do {
1368 Tokens.push_back(getNextToken());
Stephen Hines651f13c2014-04-23 16:59:28 -07001369 tryMergePreviousTokens();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001370 if (Tokens.back()->NewlinesBefore > 0)
1371 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001372 } while (Tokens.back()->Tok.isNot(tok::eof));
1373 return Tokens;
1374 }
1375
Stephen Hines176edba2014-12-01 14:53:08 -08001376 const AdditionalKeywords &getKeywords() { return Keywords; }
Manuel Klimek96e888b2013-05-28 11:55:06 +00001377
1378private:
Stephen Hines651f13c2014-04-23 16:59:28 -07001379 void tryMergePreviousTokens() {
1380 if (tryMerge_TMacro())
Alexander Kornienko2c2f7292013-09-16 20:20:49 +00001381 return;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001382 if (tryMergeConflictMarkers())
1383 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07001384
1385 if (Style.Language == FormatStyle::LK_JavaScript) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001386 if (tryMergeJSRegexLiteral())
1387 return;
Stephen Hines176edba2014-12-01 14:53:08 -08001388 if (tryMergeEscapeSequence())
1389 return;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001390
Stephen Hines651f13c2014-04-23 16:59:28 -07001391 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1392 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1393 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1394 tok::greaterequal };
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001395 static tok::TokenKind JSRightArrow[] = { tok::equal, tok::greater };
Stephen Hines651f13c2014-04-23 16:59:28 -07001396 // FIXME: We probably need to change token type to mimic operator with the
1397 // correct priority.
1398 if (tryMergeTokens(JSIdentity))
1399 return;
1400 if (tryMergeTokens(JSNotIdentity))
1401 return;
1402 if (tryMergeTokens(JSShiftEqual))
1403 return;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001404 if (tryMergeTokens(JSRightArrow))
1405 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07001406 }
1407 }
1408
1409 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1410 if (Tokens.size() < Kinds.size())
1411 return false;
1412
1413 SmallVectorImpl<FormatToken *>::const_iterator First =
1414 Tokens.end() - Kinds.size();
1415 if (!First[0]->is(Kinds[0]))
1416 return false;
1417 unsigned AddLength = 0;
1418 for (unsigned i = 1; i < Kinds.size(); ++i) {
1419 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1420 First[i]->WhitespaceRange.getEnd())
1421 return false;
1422 AddLength += First[i]->TokenText.size();
1423 }
1424 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1425 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1426 First[0]->TokenText.size() + AddLength);
1427 First[0]->ColumnWidth += AddLength;
1428 return true;
1429 }
1430
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001431 // Tries to merge an escape sequence, i.e. a "\\" and the following
1432 // character. Use e.g. inside JavaScript regex literals.
1433 bool tryMergeEscapeSequence() {
1434 if (Tokens.size() < 2)
1435 return false;
1436 FormatToken *Previous = Tokens[Tokens.size() - 2];
Stephen Hines176edba2014-12-01 14:53:08 -08001437 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\")
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001438 return false;
Stephen Hines176edba2014-12-01 14:53:08 -08001439 ++Previous->ColumnWidth;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001440 StringRef Text = Previous->TokenText;
Stephen Hines176edba2014-12-01 14:53:08 -08001441 Previous->TokenText = StringRef(Text.data(), Text.size() + 1);
1442 resetLexer(SourceMgr.getFileOffset(Tokens.back()->Tok.getLocation()) + 1);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001443 Tokens.resize(Tokens.size() - 1);
Stephen Hines176edba2014-12-01 14:53:08 -08001444 Column = Previous->OriginalColumn + Previous->ColumnWidth;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001445 return true;
1446 }
1447
1448 // Try to determine whether the current token ends a JavaScript regex literal.
1449 // We heuristically assume that this is a regex literal if we find two
1450 // unescaped slashes on a line and the token before the first slash is one of
1451 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
1452 // a division.
1453 bool tryMergeJSRegexLiteral() {
Stephen Hines176edba2014-12-01 14:53:08 -08001454 if (Tokens.size() < 2)
1455 return false;
1456 // If a regex literal ends in "\//", this gets represented by an unknown
1457 // token "\" and a comment.
1458 bool MightEndWithEscapedSlash =
1459 Tokens.back()->is(tok::comment) &&
1460 Tokens.back()->TokenText.startswith("//") &&
1461 Tokens[Tokens.size() - 2]->TokenText == "\\";
1462 if (!MightEndWithEscapedSlash &&
1463 (Tokens.back()->isNot(tok::slash) ||
1464 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
1465 Tokens[Tokens.size() - 2]->TokenText == "\\")))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001466 return false;
1467 unsigned TokenCount = 0;
1468 unsigned LastColumn = Tokens.back()->OriginalColumn;
1469 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
1470 ++TokenCount;
1471 if (I[0]->is(tok::slash) && I + 1 != E &&
1472 (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
1473 tok::exclaim, tok::l_square, tok::colon, tok::comma,
1474 tok::question, tok::kw_return) ||
1475 I[1]->isBinaryOperator())) {
Stephen Hines176edba2014-12-01 14:53:08 -08001476 if (MightEndWithEscapedSlash) {
1477 // This regex literal ends in '\//'. Skip past the '//' of the last
1478 // token and re-start lexing from there.
1479 SourceLocation Loc = Tokens.back()->Tok.getLocation();
1480 resetLexer(SourceMgr.getFileOffset(Loc) + 2);
1481 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001482 Tokens.resize(Tokens.size() - TokenCount);
1483 Tokens.back()->Tok.setKind(tok::unknown);
1484 Tokens.back()->Type = TT_RegexLiteral;
1485 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
1486 return true;
1487 }
1488
1489 // There can't be a newline inside a regex literal.
1490 if (I[0]->NewlinesBefore > 0)
1491 return false;
1492 }
1493 return false;
1494 }
1495
Stephen Hines651f13c2014-04-23 16:59:28 -07001496 bool tryMerge_TMacro() {
1497 if (Tokens.size() < 4)
1498 return false;
Alexander Kornienko2c2f7292013-09-16 20:20:49 +00001499 FormatToken *Last = Tokens.back();
1500 if (!Last->is(tok::r_paren))
Stephen Hines651f13c2014-04-23 16:59:28 -07001501 return false;
Alexander Kornienko2c2f7292013-09-16 20:20:49 +00001502
1503 FormatToken *String = Tokens[Tokens.size() - 2];
1504 if (!String->is(tok::string_literal) || String->IsMultiline)
Stephen Hines651f13c2014-04-23 16:59:28 -07001505 return false;
Alexander Kornienko2c2f7292013-09-16 20:20:49 +00001506
1507 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Stephen Hines651f13c2014-04-23 16:59:28 -07001508 return false;
Alexander Kornienko2c2f7292013-09-16 20:20:49 +00001509
1510 FormatToken *Macro = Tokens[Tokens.size() - 4];
1511 if (Macro->TokenText != "_T")
Stephen Hines651f13c2014-04-23 16:59:28 -07001512 return false;
Alexander Kornienko2c2f7292013-09-16 20:20:49 +00001513
1514 const char *Start = Macro->TokenText.data();
1515 const char *End = Last->TokenText.data() + Last->TokenText.size();
1516 String->TokenText = StringRef(Start, End - Start);
1517 String->IsFirst = Macro->IsFirst;
1518 String->LastNewlineOffset = Macro->LastNewlineOffset;
1519 String->WhitespaceRange = Macro->WhitespaceRange;
1520 String->OriginalColumn = Macro->OriginalColumn;
1521 String->ColumnWidth = encoding::columnWidthWithTabs(
1522 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1523
1524 Tokens.pop_back();
1525 Tokens.pop_back();
1526 Tokens.pop_back();
1527 Tokens.back() = String;
Stephen Hines651f13c2014-04-23 16:59:28 -07001528 return true;
Alexander Kornienko2c2f7292013-09-16 20:20:49 +00001529 }
1530
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001531 bool tryMergeConflictMarkers() {
1532 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1533 return false;
1534
1535 // Conflict lines look like:
1536 // <marker> <text from the vcs>
1537 // For example:
1538 // >>>>>>> /file/in/file/system at revision 1234
1539 //
1540 // We merge all tokens in a line that starts with a conflict marker
1541 // into a single token with a special token type that the unwrapped line
1542 // parser will use to correctly rebuild the underlying code.
1543
1544 FileID ID;
1545 // Get the position of the first token in the line.
1546 unsigned FirstInLineOffset;
1547 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1548 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1549 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1550 // Calculate the offset of the start of the current line.
1551 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1552 if (LineOffset == StringRef::npos) {
1553 LineOffset = 0;
1554 } else {
1555 ++LineOffset;
1556 }
1557
1558 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1559 StringRef LineStart;
1560 if (FirstSpace == StringRef::npos) {
1561 LineStart = Buffer.substr(LineOffset);
1562 } else {
1563 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1564 }
1565
1566 TokenType Type = TT_Unknown;
1567 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1568 Type = TT_ConflictStart;
1569 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1570 LineStart == "====") {
1571 Type = TT_ConflictAlternative;
1572 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1573 Type = TT_ConflictEnd;
1574 }
1575
1576 if (Type != TT_Unknown) {
1577 FormatToken *Next = Tokens.back();
1578
1579 Tokens.resize(FirstInLineIndex + 1);
1580 // We do not need to build a complete token here, as we will skip it
1581 // during parsing anyway (as we must not touch whitespace around conflict
1582 // markers).
1583 Tokens.back()->Type = Type;
1584 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1585
1586 Tokens.push_back(Next);
1587 return true;
1588 }
1589
1590 return false;
1591 }
1592
Manuel Klimek96e888b2013-05-28 11:55:06 +00001593 FormatToken *getNextToken() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001594 if (GreaterStashed) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001595 // Create a synthesized second '>' token.
Manuel Klimekc41e8192013-08-29 15:21:40 +00001596 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001597 Token Greater = FormatTok->Tok;
1598 FormatTok = new (Allocator.Allocate()) FormatToken;
1599 FormatTok->Tok = Greater;
Manuel Klimekad3094b2013-05-23 10:56:37 +00001600 SourceLocation GreaterLocation =
Manuel Klimek96e888b2013-05-28 11:55:06 +00001601 FormatTok->Tok.getLocation().getLocWithOffset(1);
1602 FormatTok->WhitespaceRange =
1603 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001604 FormatTok->TokenText = ">";
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001605 FormatTok->ColumnWidth = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001606 GreaterStashed = false;
1607 return FormatTok;
1608 }
1609
Manuel Klimek96e888b2013-05-28 11:55:06 +00001610 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper561211d2013-07-16 20:28:33 +00001611 readRawToken(*FormatTok);
Manuel Klimekde008c02013-05-27 15:23:34 +00001612 SourceLocation WhitespaceStart =
Manuel Klimek96e888b2013-05-28 11:55:06 +00001613 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienkoa9f28092013-11-13 14:04:17 +00001614 FormatTok->IsFirst = IsFirstToken;
1615 IsFirstToken = false;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001616
1617 // Consume and record whitespace until we find a significant token.
Manuel Klimekde008c02013-05-27 15:23:34 +00001618 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001619 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +00001620 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1621 switch (FormatTok->TokenText[i]) {
1622 case '\n':
1623 ++FormatTok->NewlinesBefore;
1624 // FIXME: This is technically incorrect, as it could also
1625 // be a literal backslash at the end of the line.
Alexander Kornienko73d845c2013-09-11 12:25:57 +00001626 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1627 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1628 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimekc41e8192013-08-29 15:21:40 +00001629 FormatTok->HasUnescapedNewline = true;
1630 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1631 Column = 0;
1632 break;
Daniel Jasper1d82b1a2013-10-11 19:45:02 +00001633 case '\r':
1634 case '\f':
1635 case '\v':
1636 Column = 0;
1637 break;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001638 case ' ':
1639 ++Column;
1640 break;
1641 case '\t':
Alexander Kornienko0b62cc32013-09-05 14:08:34 +00001642 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001643 break;
Daniel Jasper1d82b1a2013-10-11 19:45:02 +00001644 case '\\':
1645 ++Column;
1646 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1647 FormatTok->TokenText[i + 1] != '\n'))
1648 FormatTok->Type = TT_ImplicitStringLiteral;
1649 break;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001650 default:
Daniel Jasper1d82b1a2013-10-11 19:45:02 +00001651 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001652 ++Column;
1653 break;
1654 }
1655 }
1656
Daniel Jasper1d82b1a2013-10-11 19:45:02 +00001657 if (FormatTok->Type == TT_ImplicitStringLiteral)
1658 break;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001659 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001660
Daniel Jasper561211d2013-07-16 20:28:33 +00001661 readRawToken(*FormatTok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001662 }
Manuel Klimek95419382013-01-07 07:56:50 +00001663
Manuel Klimekd4397b92013-01-04 23:34:14 +00001664 // In case the token starts with escaped newlines, we want to
1665 // take them into account as whitespace - this pattern is quite frequent
1666 // in macro definitions.
Manuel Klimekd4397b92013-01-04 23:34:14 +00001667 // FIXME: Add a more explicit test.
Daniel Jasper561211d2013-07-16 20:28:33 +00001668 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1669 FormatTok->TokenText[1] == '\n') {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001670 ++FormatTok->NewlinesBefore;
Manuel Klimekad3094b2013-05-23 10:56:37 +00001671 WhitespaceLength += 2;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001672 Column = 0;
Daniel Jasper561211d2013-07-16 20:28:33 +00001673 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001674 }
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001675
1676 FormatTok->WhitespaceRange = SourceRange(
1677 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1678
Manuel Klimekc41e8192013-08-29 15:21:40 +00001679 FormatTok->OriginalColumn = Column;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001680
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001681 TrailingWhitespace = 0;
1682 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +00001683 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper561211d2013-07-16 20:28:33 +00001684 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko51bb5d92013-09-06 17:24:54 +00001685 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper561211d2013-07-16 20:28:33 +00001686 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001687 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper561211d2013-07-16 20:28:33 +00001688 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek96e888b2013-05-28 11:55:06 +00001689 FormatTok->Tok.setIdentifierInfo(&Info);
1690 FormatTok->Tok.setKind(Info.getTokenID());
Stephen Hines176edba2014-12-01 14:53:08 -08001691 if (Style.Language == FormatStyle::LK_Java &&
1692 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete)) {
1693 FormatTok->Tok.setKind(tok::identifier);
1694 FormatTok->Tok.setIdentifierInfo(nullptr);
1695 }
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001696 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek96e888b2013-05-28 11:55:06 +00001697 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper561211d2013-07-16 20:28:33 +00001698 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001699 GreaterStashed = true;
1700 }
1701
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001702 // Now FormatTok is the next non-whitespace token.
Alexander Kornienko00895102013-06-05 14:09:10 +00001703
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001704 StringRef Text = FormatTok->TokenText;
1705 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko6f6154c2013-09-10 12:29:48 +00001706 if (FirstNewlinePos == StringRef::npos) {
1707 // FIXME: ColumnWidth actually depends on the start column, we need to
1708 // take this into account when the token is moved.
1709 FormatTok->ColumnWidth =
1710 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1711 Column += FormatTok->ColumnWidth;
1712 } else {
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001713 FormatTok->IsMultiline = true;
Alexander Kornienko6f6154c2013-09-10 12:29:48 +00001714 // FIXME: ColumnWidth actually depends on the start column, we need to
1715 // take this into account when the token is moved.
1716 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1717 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1718
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001719 // The last line of the token always starts in column 0.
1720 // Thus, the length can be precomputed even in the presence of tabs.
1721 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1722 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1723 Encoding);
Alexander Kornienko6f6154c2013-09-10 12:29:48 +00001724 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko4b762a92013-09-02 13:58:14 +00001725 }
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001726
Stephen Hines651f13c2014-04-23 16:59:28 -07001727 FormatTok->IsForEachMacro =
1728 std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1729 FormatTok->Tok.getIdentifierInfo());
1730
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001731 return FormatTok;
1732 }
1733
Manuel Klimek96e888b2013-05-28 11:55:06 +00001734 FormatToken *FormatTok;
Alexander Kornienkoa9f28092013-11-13 14:04:17 +00001735 bool IsFirstToken;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001736 bool GreaterStashed;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001737 unsigned Column;
Manuel Klimekde008c02013-05-27 15:23:34 +00001738 unsigned TrailingWhitespace;
Stephen Hines176edba2014-12-01 14:53:08 -08001739 std::unique_ptr<Lexer> Lex;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001740 SourceManager &SourceMgr;
Stephen Hines176edba2014-12-01 14:53:08 -08001741 FileID ID;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001742 FormatStyle &Style;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001743 IdentifierTable IdentTable;
Stephen Hines176edba2014-12-01 14:53:08 -08001744 AdditionalKeywords Keywords;
Alexander Kornienko00895102013-06-05 14:09:10 +00001745 encoding::Encoding Encoding;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001746 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001747 // Index (in 'Tokens') of the last token that starts a new line.
1748 unsigned FirstInLineIndex;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001749 SmallVector<FormatToken *, 16> Tokens;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001750 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001751
Stephen Hines176edba2014-12-01 14:53:08 -08001752 bool FormattingDisabled;
1753
Daniel Jasper561211d2013-07-16 20:28:33 +00001754 void readRawToken(FormatToken &Tok) {
Stephen Hines176edba2014-12-01 14:53:08 -08001755 Lex->LexFromRawLexer(Tok.Tok);
Daniel Jasper561211d2013-07-16 20:28:33 +00001756 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1757 Tok.Tok.getLength());
Daniel Jasper561211d2013-07-16 20:28:33 +00001758 // For formatting, treat unterminated string literals like normal string
1759 // literals.
Stephen Hines651f13c2014-04-23 16:59:28 -07001760 if (Tok.is(tok::unknown)) {
1761 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1762 Tok.Tok.setKind(tok::string_literal);
1763 Tok.IsUnterminatedLiteral = true;
1764 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1765 Tok.TokenText == "''") {
1766 Tok.Tok.setKind(tok::char_constant);
1767 }
Daniel Jasper561211d2013-07-16 20:28:33 +00001768 }
Stephen Hines176edba2014-12-01 14:53:08 -08001769
1770 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1771 Tok.TokenText == "/* clang-format on */")) {
1772 FormattingDisabled = false;
1773 }
1774
1775 Tok.Finalized = FormattingDisabled;
1776
1777 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1778 Tok.TokenText == "/* clang-format off */")) {
1779 FormattingDisabled = true;
1780 }
1781 }
1782
1783 void resetLexer(unsigned Offset) {
1784 StringRef Buffer = SourceMgr.getBufferData(ID);
1785 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1786 getFormattingLangOpts(Style), Buffer.begin(),
1787 Buffer.begin() + Offset, Buffer.end()));
1788 Lex->SetKeepWhitespaceMode(true);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001789 }
1790};
1791
Stephen Hines651f13c2014-04-23 16:59:28 -07001792static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1793 switch (Language) {
1794 case FormatStyle::LK_Cpp:
1795 return "C++";
Stephen Hines176edba2014-12-01 14:53:08 -08001796 case FormatStyle::LK_Java:
1797 return "Java";
Stephen Hines651f13c2014-04-23 16:59:28 -07001798 case FormatStyle::LK_JavaScript:
1799 return "JavaScript";
1800 case FormatStyle::LK_Proto:
1801 return "Proto";
1802 default:
1803 return "Unknown";
1804 }
1805}
1806
Daniel Jasperbac016b2012-12-03 18:12:45 +00001807class Formatter : public UnwrappedLineConsumer {
1808public:
Stephen Hines176edba2014-12-01 14:53:08 -08001809 Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
1810 ArrayRef<CharSourceRange> Ranges)
1811 : Style(Style), ID(ID), SourceMgr(SourceMgr),
1812 Whitespaces(SourceMgr, Style,
1813 inputUsesCRLF(SourceMgr.getBufferData(ID))),
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001814 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Stephen Hines176edba2014-12-01 14:53:08 -08001815 Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
Daniel Jasper9637dda2013-07-15 14:33:14 +00001816 DEBUG(llvm::dbgs() << "File encoding: "
1817 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1818 : "unknown")
1819 << "\n");
Stephen Hines651f13c2014-04-23 16:59:28 -07001820 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1821 << "\n");
Alexander Kornienko00895102013-06-05 14:09:10 +00001822 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001823
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001824 tooling::Replacements format() {
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001825 tooling::Replacements Result;
Stephen Hines176edba2014-12-01 14:53:08 -08001826 FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
Manuel Klimek96e888b2013-05-28 11:55:06 +00001827
Stephen Hines176edba2014-12-01 14:53:08 -08001828 UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
1829 *this);
Manuel Klimek67d080d2013-04-12 14:13:36 +00001830 bool StructuralError = Parser.parse();
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001831 assert(UnwrappedLines.rbegin()->empty());
1832 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1833 ++Run) {
1834 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1835 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1836 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1837 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1838 }
1839 tooling::Replacements RunResult =
1840 format(AnnotatedLines, StructuralError, Tokens);
1841 DEBUG({
1842 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1843 for (tooling::Replacements::iterator I = RunResult.begin(),
1844 E = RunResult.end();
1845 I != E; ++I) {
1846 llvm::dbgs() << I->toString() << "\n";
1847 }
1848 });
1849 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1850 delete AnnotatedLines[i];
1851 }
1852 Result.insert(RunResult.begin(), RunResult.end());
1853 Whitespaces.reset();
1854 }
1855 return Result;
1856 }
1857
1858 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1859 bool StructuralError, FormatTokenLexer &Tokens) {
Stephen Hines176edba2014-12-01 14:53:08 -08001860 TokenAnnotator Annotator(Style, Tokens.getKeywords());
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001861 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001862 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001863 }
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001864 deriveLocalStyle(AnnotatedLines);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001865 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001866 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001867 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001868 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasper5999f762013-04-09 17:46:55 +00001869
Daniel Jasperb77d7412013-09-06 07:54:20 +00001870 Annotator.setCommentLineLevels(AnnotatedLines);
Stephen Hines176edba2014-12-01 14:53:08 -08001871 ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
1872 Whitespaces, Encoding,
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001873 BinPackInconclusiveFunctions);
Stephen Hines651f13c2014-04-23 16:59:28 -07001874 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001875 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001876 return Whitespaces.generateReplacements();
1877 }
1878
1879private:
Stephen Hines651f13c2014-04-23 16:59:28 -07001880 // Determines which lines are affected by the SourceRanges given as input.
1881 // Returns \c true if at least one line between I and E or one of their
1882 // children is affected.
1883 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1884 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1885 bool SomeLineAffected = false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001886 const AnnotatedLine *PreviousLine = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07001887 while (I != E) {
1888 AnnotatedLine *Line = *I;
1889 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1890
1891 // If a line is part of a preprocessor directive, it needs to be formatted
1892 // if any token within the directive is affected.
1893 if (Line->InPPDirective) {
1894 FormatToken *Last = Line->Last;
1895 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1896 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1897 Last = (*PPEnd)->Last;
1898 ++PPEnd;
1899 }
1900
1901 if (affectsTokenRange(*Line->First, *Last,
1902 /*IncludeLeadingNewlines=*/false)) {
1903 SomeLineAffected = true;
1904 markAllAsAffected(I, PPEnd);
1905 }
1906 I = PPEnd;
1907 continue;
1908 }
1909
1910 if (nonPPLineAffected(Line, PreviousLine))
1911 SomeLineAffected = true;
1912
1913 PreviousLine = Line;
1914 ++I;
1915 }
1916 return SomeLineAffected;
1917 }
1918
1919 // Determines whether 'Line' is affected by the SourceRanges given as input.
1920 // Returns \c true if line or one if its children is affected.
1921 bool nonPPLineAffected(AnnotatedLine *Line,
1922 const AnnotatedLine *PreviousLine) {
1923 bool SomeLineAffected = false;
1924 Line->ChildrenAffected =
1925 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1926 if (Line->ChildrenAffected)
1927 SomeLineAffected = true;
1928
1929 // Stores whether one of the line's tokens is directly affected.
1930 bool SomeTokenAffected = false;
1931 // Stores whether we need to look at the leading newlines of the next token
1932 // in order to determine whether it was affected.
1933 bool IncludeLeadingNewlines = false;
1934
1935 // Stores whether the first child line of any of this line's tokens is
1936 // affected.
1937 bool SomeFirstChildAffected = false;
1938
1939 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1940 // Determine whether 'Tok' was affected.
1941 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1942 SomeTokenAffected = true;
1943
1944 // Determine whether the first child of 'Tok' was affected.
1945 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1946 SomeFirstChildAffected = true;
1947
1948 IncludeLeadingNewlines = Tok->Children.empty();
1949 }
1950
1951 // Was this line moved, i.e. has it previously been on the same line as an
1952 // affected line?
1953 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1954 Line->First->NewlinesBefore == 0;
1955
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001956 bool IsContinuedComment =
1957 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1958 Line->First->NewlinesBefore < 2 && PreviousLine &&
1959 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Stephen Hines651f13c2014-04-23 16:59:28 -07001960
1961 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1962 IsContinuedComment) {
1963 Line->Affected = true;
1964 SomeLineAffected = true;
1965 }
1966 return SomeLineAffected;
1967 }
1968
1969 // Marks all lines between I and E as well as all their children as affected.
1970 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1971 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1972 while (I != E) {
1973 (*I)->Affected = true;
1974 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1975 ++I;
1976 }
1977 }
1978
1979 // Returns true if the range from 'First' to 'Last' intersects with one of the
1980 // input ranges.
1981 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1982 bool IncludeLeadingNewlines) {
1983 SourceLocation Start = First.WhitespaceRange.getBegin();
1984 if (!IncludeLeadingNewlines)
1985 Start = Start.getLocWithOffset(First.LastNewlineOffset);
1986 SourceLocation End = Last.getStartOfNonWhitespace();
Stephen Hines176edba2014-12-01 14:53:08 -08001987 End = End.getLocWithOffset(Last.TokenText.size());
Stephen Hines651f13c2014-04-23 16:59:28 -07001988 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1989 return affectsCharSourceRange(Range);
1990 }
1991
1992 // Returns true if one of the input ranges intersect the leading empty lines
1993 // before 'Tok'.
1994 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1995 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1996 Tok.WhitespaceRange.getBegin(),
1997 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1998 return affectsCharSourceRange(EmptyLineRange);
1999 }
2000
2001 // Returns true if 'Range' intersects with one of the input ranges.
2002 bool affectsCharSourceRange(const CharSourceRange &Range) {
2003 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
2004 E = Ranges.end();
2005 I != E; ++I) {
2006 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
2007 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
2008 return true;
2009 }
2010 return false;
2011 }
2012
Alexander Kornienko73d845c2013-09-11 12:25:57 +00002013 static bool inputUsesCRLF(StringRef Text) {
2014 return Text.count('\r') * 2 > Text.count('\n');
2015 }
2016
Manuel Klimekae76f7f2013-10-11 21:25:45 +00002017 void
2018 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +00002019 unsigned CountBoundToVariable = 0;
2020 unsigned CountBoundToType = 0;
2021 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00002022 bool HasBinPackedFunction = false;
2023 bool HasOnePerLineFunction = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00002024 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00002025 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper8ff690a2013-02-06 14:22:40 +00002026 continue;
Daniel Jasper567dcf92013-09-05 09:29:45 +00002027 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimekb3987012013-05-29 14:47:47 +00002028 while (Tok->Next) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +00002029 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimekb3987012013-05-29 14:47:47 +00002030 bool SpacesBefore =
2031 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
2032 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
2033 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper8ff690a2013-02-06 14:22:40 +00002034 if (SpacesBefore && !SpacesAfter)
2035 ++CountBoundToVariable;
2036 else if (!SpacesBefore && SpacesAfter)
2037 ++CountBoundToType;
2038 }
2039
Daniel Jasper78a4e612013-10-12 05:16:06 +00002040 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
2041 if (Tok->is(tok::coloncolon) &&
2042 Tok->Previous->Type == TT_TemplateOpener)
2043 HasCpp03IncompatibleFormat = true;
2044 if (Tok->Type == TT_TemplateCloser &&
2045 Tok->Previous->Type == TT_TemplateCloser)
2046 HasCpp03IncompatibleFormat = true;
2047 }
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00002048
2049 if (Tok->PackingKind == PPK_BinPacked)
2050 HasBinPackedFunction = true;
2051 if (Tok->PackingKind == PPK_OnePerLine)
2052 HasOnePerLineFunction = true;
2053
Manuel Klimekb3987012013-05-29 14:47:47 +00002054 Tok = Tok->Next;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00002055 }
2056 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002057 if (Style.DerivePointerAlignment) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +00002058 if (CountBoundToType > CountBoundToVariable)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002059 Style.PointerAlignment = FormatStyle::PAS_Left;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00002060 else if (CountBoundToType < CountBoundToVariable)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002061 Style.PointerAlignment = FormatStyle::PAS_Right;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00002062 }
2063 if (Style.Standard == FormatStyle::LS_Auto) {
2064 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
2065 : FormatStyle::LS_Cpp03;
2066 }
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00002067 BinPackInconclusiveFunctions =
2068 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00002069 }
2070
Stephen Hines651f13c2014-04-23 16:59:28 -07002071 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimekae76f7f2013-10-11 21:25:45 +00002072 assert(!UnwrappedLines.empty());
2073 UnwrappedLines.back().push_back(TheLine);
2074 }
2075
Stephen Hines651f13c2014-04-23 16:59:28 -07002076 void finishRun() override {
Manuel Klimekae76f7f2013-10-11 21:25:45 +00002077 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperbac016b2012-12-03 18:12:45 +00002078 }
2079
2080 FormatStyle Style;
Stephen Hines176edba2014-12-01 14:53:08 -08002081 FileID ID;
Daniel Jasperbac016b2012-12-03 18:12:45 +00002082 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00002083 WhitespaceManager Whitespaces;
Daniel Jasper2a80ad62013-11-05 19:10:03 +00002084 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimekae76f7f2013-10-11 21:25:45 +00002085 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienko00895102013-06-05 14:09:10 +00002086
2087 encoding::Encoding Encoding;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00002088 bool BinPackInconclusiveFunctions;
Daniel Jasperbac016b2012-12-03 18:12:45 +00002089};
2090
Craig Topper83f81d72013-06-30 22:29:28 +00002091} // end anonymous namespace
2092
Alexander Kornienko70ce7882013-04-15 14:28:00 +00002093tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
2094 SourceManager &SourceMgr,
Stephen Hines176edba2014-12-01 14:53:08 -08002095 ArrayRef<CharSourceRange> Ranges) {
2096 if (Style.DisableFormat)
2097 return tooling::Replacements();
2098 return reformat(Style, SourceMgr,
2099 SourceMgr.getFileID(Lex.getSourceLocation()), Ranges);
2100}
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002101
Stephen Hines176edba2014-12-01 14:53:08 -08002102tooling::Replacements reformat(const FormatStyle &Style,
2103 SourceManager &SourceMgr, FileID ID,
2104 ArrayRef<CharSourceRange> Ranges) {
2105 if (Style.DisableFormat)
2106 return tooling::Replacements();
2107 Formatter formatter(Style, SourceMgr, ID, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00002108 return formatter.format();
2109}
2110
Daniel Jasper8a999452013-05-16 10:40:07 +00002111tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
Stephen Hines176edba2014-12-01 14:53:08 -08002112 ArrayRef<tooling::Range> Ranges,
Daniel Jasper8a999452013-05-16 10:40:07 +00002113 StringRef FileName) {
Stephen Hines176edba2014-12-01 14:53:08 -08002114 if (Style.DisableFormat)
2115 return tooling::Replacements();
2116
Daniel Jasper8a999452013-05-16 10:40:07 +00002117 FileManager Files((FileSystemOptions()));
2118 DiagnosticsEngine Diagnostics(
2119 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2120 new DiagnosticOptions);
2121 SourceManager SourceMgr(Diagnostics, Files);
Stephen Hines176edba2014-12-01 14:53:08 -08002122 std::unique_ptr<llvm::MemoryBuffer> Buf =
2123 llvm::MemoryBuffer::getMemBuffer(Code, FileName);
Daniel Jasper8a999452013-05-16 10:40:07 +00002124 const clang::FileEntry *Entry =
2125 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
Stephen Hines176edba2014-12-01 14:53:08 -08002126 SourceMgr.overrideFileContents(Entry, std::move(Buf));
Daniel Jasper8a999452013-05-16 10:40:07 +00002127 FileID ID =
2128 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Daniel Jasper8a999452013-05-16 10:40:07 +00002129 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
2130 std::vector<CharSourceRange> CharRanges;
Stephen Hines176edba2014-12-01 14:53:08 -08002131 for (const tooling::Range &Range : Ranges) {
2132 SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
2133 SourceLocation End = Start.getLocWithOffset(Range.getLength());
Daniel Jasper8a999452013-05-16 10:40:07 +00002134 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
2135 }
Stephen Hines176edba2014-12-01 14:53:08 -08002136 return reformat(Style, SourceMgr, ID, CharRanges);
Daniel Jasper8a999452013-05-16 10:40:07 +00002137}
2138
Stephen Hines176edba2014-12-01 14:53:08 -08002139LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasper46ef8522013-01-10 13:08:12 +00002140 LangOptions LangOpts;
2141 LangOpts.CPlusPlus = 1;
Stephen Hines176edba2014-12-01 14:53:08 -08002142 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2143 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasperb64eca02013-03-22 10:01:29 +00002144 LangOpts.LineComment = 1;
Stephen Hines176edba2014-12-01 14:53:08 -08002145 bool AlternativeOperators = Style.Language != FormatStyle::LK_JavaScript &&
2146 Style.Language != FormatStyle::LK_Java;
2147 LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
Daniel Jasper46ef8522013-01-10 13:08:12 +00002148 LangOpts.Bool = 1;
2149 LangOpts.ObjC1 = 1;
2150 LangOpts.ObjC2 = 1;
2151 return LangOpts;
2152}
2153
Edwin Vanef4e12c82013-09-30 13:31:48 +00002154const char *StyleOptionHelpDescription =
2155 "Coding style, currently supports:\n"
2156 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
2157 "Use -style=file to load style configuration from\n"
2158 ".clang-format file located in one of the parent\n"
2159 "directories of the source file (or current\n"
2160 "directory for stdin).\n"
2161 "Use -style=\"{key: value, ...}\" to set specific\n"
2162 "parameters, e.g.:\n"
2163 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
2164
Stephen Hines651f13c2014-04-23 16:59:28 -07002165static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Stephen Hines176edba2014-12-01 14:53:08 -08002166 if (FileName.endswith(".java")) {
2167 return FormatStyle::LK_Java;
2168 } else if (FileName.endswith_lower(".js")) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002169 return FormatStyle::LK_JavaScript;
2170 } else if (FileName.endswith_lower(".proto") ||
2171 FileName.endswith_lower(".protodevel")) {
2172 return FormatStyle::LK_Proto;
2173 }
2174 return FormatStyle::LK_Cpp;
2175}
2176
2177FormatStyle getStyle(StringRef StyleName, StringRef FileName,
2178 StringRef FallbackStyle) {
2179 FormatStyle Style = getLLVMStyle();
2180 Style.Language = getLanguageByFileName(FileName);
2181 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
2182 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
2183 << "\" using LLVM style\n";
2184 return Style;
2185 }
Edwin Vanef4e12c82013-09-30 13:31:48 +00002186
2187 if (StyleName.startswith("{")) {
2188 // Parse YAML/JSON style from the command line.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002189 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +00002190 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
2191 << FallbackStyle << " style\n";
Edwin Vanef4e12c82013-09-30 13:31:48 +00002192 }
2193 return Style;
2194 }
2195
2196 if (!StyleName.equals_lower("file")) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002197 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vanef4e12c82013-09-30 13:31:48 +00002198 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
2199 << " style\n";
2200 return Style;
2201 }
2202
Stephen Hines651f13c2014-04-23 16:59:28 -07002203 // Look for .clang-format/_clang-format file in the file's parent directories.
2204 SmallString<128> UnsuitableConfigFiles;
Edwin Vanef4e12c82013-09-30 13:31:48 +00002205 SmallString<128> Path(FileName);
2206 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +00002207 for (StringRef Directory = Path; !Directory.empty();
Edwin Vanef4e12c82013-09-30 13:31:48 +00002208 Directory = llvm::sys::path::parent_path(Directory)) {
2209 if (!llvm::sys::fs::is_directory(Directory))
2210 continue;
2211 SmallString<128> ConfigFile(Directory);
2212
2213 llvm::sys::path::append(ConfigFile, ".clang-format");
2214 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2215 bool IsFile = false;
2216 // Ignore errors from is_regular_file: we only need to know if we can read
2217 // the file or not.
2218 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2219
2220 if (!IsFile) {
2221 // Try _clang-format too, since dotfiles are not commonly used on Windows.
2222 ConfigFile = Directory;
2223 llvm::sys::path::append(ConfigFile, "_clang-format");
2224 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2225 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2226 }
2227
2228 if (IsFile) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002229 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
2230 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
2231 if (std::error_code EC = Text.getError()) {
2232 llvm::errs() << EC.message() << "\n";
Stephen Hines651f13c2014-04-23 16:59:28 -07002233 break;
Edwin Vanef4e12c82013-09-30 13:31:48 +00002234 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002235 if (std::error_code ec =
2236 parseConfiguration(Text.get()->getBuffer(), &Style)) {
2237 if (ec == ParseError::Unsuitable) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002238 if (!UnsuitableConfigFiles.empty())
2239 UnsuitableConfigFiles.append(", ");
2240 UnsuitableConfigFiles.append(ConfigFile);
2241 continue;
2242 }
Edwin Vanef4e12c82013-09-30 13:31:48 +00002243 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2244 << "\n";
Stephen Hines651f13c2014-04-23 16:59:28 -07002245 break;
Edwin Vanef4e12c82013-09-30 13:31:48 +00002246 }
2247 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2248 return Style;
2249 }
2250 }
2251 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
2252 << " style\n";
Stephen Hines651f13c2014-04-23 16:59:28 -07002253 if (!UnsuitableConfigFiles.empty()) {
2254 llvm::errs() << "Configuration file(s) do(es) not support "
2255 << getLanguageName(Style.Language) << ": "
2256 << UnsuitableConfigFiles << "\n";
2257 }
Edwin Vanef4e12c82013-09-30 13:31:48 +00002258 return Style;
2259}
2260
Daniel Jaspercd162382013-01-07 13:26:07 +00002261} // namespace format
2262} // namespace clang