blob: 7d0e102d630278857a23af598b7113fde8863273 [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);
44 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
45 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
46 }
47};
48
49template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
50 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
51 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
52 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
53 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
54 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
55 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
56 }
57};
58
59template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
60 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
61 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
62 IO.enumCase(Value, "false", FormatStyle::UT_Never);
63 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
64 IO.enumCase(Value, "true", FormatStyle::UT_Always);
65 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
66 }
67};
68
Stephen Hines6bcf27b2014-05-29 04:14:42 -070069template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
70 static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
71 IO.enumCase(Value, "None", FormatStyle::SFS_None);
72 IO.enumCase(Value, "false", FormatStyle::SFS_None);
73 IO.enumCase(Value, "All", FormatStyle::SFS_All);
74 IO.enumCase(Value, "true", FormatStyle::SFS_All);
75 IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
76 }
77};
78
Stephen Hines651f13c2014-04-23 16:59:28 -070079template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
80 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
81 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
82 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
83 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
84 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
85 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
86 }
87};
88
Alexander Kornienkod71ec162013-05-07 15:32:14 +000089template <>
Stephen Hines651f13c2014-04-23 16:59:28 -070090struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Manuel Klimek44135b82013-05-13 12:51:40 +000091 static void enumeration(IO &IO,
Stephen Hines651f13c2014-04-23 16:59:28 -070092 FormatStyle::NamespaceIndentationKind &Value) {
93 IO.enumCase(Value, "None", FormatStyle::NI_None);
94 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
95 IO.enumCase(Value, "All", FormatStyle::NI_All);
Manuel Klimek44135b82013-05-13 12:51:40 +000096 }
97};
98
Daniel Jasper1fb8d882013-05-14 09:30:02 +000099template <>
Stephen Hines651f13c2014-04-23 16:59:28 -0700100struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +0000101 static void enumeration(IO &IO,
Stephen Hines651f13c2014-04-23 16:59:28 -0700102 FormatStyle::SpaceBeforeParensOptions &Value) {
103 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
104 IO.enumCase(Value, "ControlStatements",
105 FormatStyle::SBPO_ControlStatements);
106 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
107
108 // For backward compatibility.
109 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
110 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000111 }
112};
113
Stephen Hines651f13c2014-04-23 16:59:28 -0700114template <> struct MappingTraits<FormatStyle> {
115 static void mapping(IO &IO, FormatStyle &Style) {
116 // When reading, read the language first, we need it for getPredefinedStyle.
117 IO.mapOptional("Language", Style.Language);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000118
Alexander Kornienkodd256312013-05-10 11:56:10 +0000119 if (IO.outputting()) {
Alexander Kornienko4e65c982013-09-02 16:39:23 +0000120 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
Stephen Hines651f13c2014-04-23 16:59:28 -0700121 "Mozilla", "WebKit", "GNU" };
Alexander Kornienkodd256312013-05-10 11:56:10 +0000122 ArrayRef<StringRef> Styles(StylesArray);
123 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
124 StringRef StyleName(Styles[i]);
Stephen Hines651f13c2014-04-23 16:59:28 -0700125 FormatStyle PredefinedStyle;
126 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000127 Style == PredefinedStyle) {
Alexander Kornienkodd256312013-05-10 11:56:10 +0000128 IO.mapOptional("# BasedOnStyle", StyleName);
129 break;
130 }
131 }
132 } else {
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000133 StringRef BasedOnStyle;
134 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Stephen Hines651f13c2014-04-23 16:59:28 -0700135 if (!BasedOnStyle.empty()) {
136 FormatStyle::LanguageKind OldLanguage = Style.Language;
137 FormatStyle::LanguageKind Language =
138 ((FormatStyle *)IO.getContext())->Language;
139 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000140 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
141 return;
142 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700143 Style.Language = OldLanguage;
144 }
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000145 }
146
147 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jasper6315fec2013-08-13 10:58:30 +0000148 IO.mapOptional("ConstructorInitializerIndentWidth",
149 Style.ConstructorInitializerIndentWidth);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000150 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000151 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000152 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
153 Style.AllowAllParametersOfDeclarationOnNextLine);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700154 IO.mapOptional("AllowShortBlocksOnASingleLine",
155 Style.AllowShortBlocksOnASingleLine);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000156 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
157 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000158 IO.mapOptional("AllowShortLoopsOnASingleLine",
159 Style.AllowShortLoopsOnASingleLine);
Stephen Hines651f13c2014-04-23 16:59:28 -0700160 IO.mapOptional("AllowShortFunctionsOnASingleLine",
161 Style.AllowShortFunctionsOnASingleLine);
Daniel Jasperbbc87762013-05-29 12:07:31 +0000162 IO.mapOptional("AlwaysBreakTemplateDeclarations",
163 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko56312022013-07-04 12:02:44 +0000164 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
165 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000166 IO.mapOptional("BreakBeforeBinaryOperators",
167 Style.BreakBeforeBinaryOperators);
Daniel Jasper1a896a52013-11-08 00:57:11 +0000168 IO.mapOptional("BreakBeforeTernaryOperators",
169 Style.BreakBeforeTernaryOperators);
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000170 IO.mapOptional("BreakConstructorInitializersBeforeComma",
171 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000172 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
173 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
174 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
175 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
176 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000177 IO.mapOptional("ExperimentalAutoDetectBinPacking",
178 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000179 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
180 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Stephen Hines651f13c2014-04-23 16:59:28 -0700181 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
182 Style.KeepEmptyLinesAtTheStartOfBlocks);
Daniel Jaspereff18b92013-07-31 23:16:02 +0000183 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Stephen Hines651f13c2014-04-23 16:59:28 -0700184 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000185 IO.mapOptional("ObjCSpaceBeforeProtocolList",
186 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper47066e42013-10-25 14:29:37 +0000187 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
188 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000189 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
190 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000191 IO.mapOptional("PenaltyBreakFirstLessLess",
192 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000193 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
194 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
195 Style.PenaltyReturnTypeOnItsOwnLine);
196 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
197 IO.mapOptional("SpacesBeforeTrailingComments",
198 Style.SpacesBeforeTrailingComments);
Daniel Jasperb5dc3f42013-07-16 18:22:10 +0000199 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000200 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000201 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000202 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000203 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimek44135b82013-05-13 12:51:40 +0000204 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimeka9a7f102013-06-21 17:25:42 +0000205 IO.mapOptional("IndentFunctionDeclarationAfterType",
206 Style.IndentFunctionDeclarationAfterType);
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000207 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperd8ee5c12013-10-29 14:52:02 +0000208 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasper34f3d052013-08-21 08:39:01 +0000209 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000210 IO.mapOptional("SpacesInCStyleCastParentheses",
211 Style.SpacesInCStyleCastParentheses);
Stephen Hines651f13c2014-04-23 16:59:28 -0700212 IO.mapOptional("SpacesInContainerLiterals",
213 Style.SpacesInContainerLiterals);
Daniel Jasper9b4de852013-09-25 15:15:02 +0000214 IO.mapOptional("SpaceBeforeAssignmentOperators",
215 Style.SpaceBeforeAssignmentOperators);
Daniel Jasperc2827ec2013-10-18 10:38:14 +0000216 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Stephen Hines651f13c2014-04-23 16:59:28 -0700217 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700218 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Stephen Hines651f13c2014-04-23 16:59:28 -0700219
220 // For backward compatibility.
221 if (!IO.outputting()) {
222 IO.mapOptional("SpaceAfterControlStatementKeyword",
223 Style.SpaceBeforeParens);
224 }
225 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700226 IO.mapOptional("DisableFormat", Style.DisableFormat);
Stephen Hines651f13c2014-04-23 16:59:28 -0700227 }
228};
229
230// Allows to read vector<FormatStyle> while keeping default values.
231// IO.getContext() should contain a pointer to the FormatStyle structure, that
232// will be used to get default values for missing keys.
233// If the first element has no Language specified, it will be treated as the
234// default one for the following elements.
235template <> struct DocumentListTraits<std::vector<FormatStyle> > {
236 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
237 return Seq.size();
238 }
239 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
240 size_t Index) {
241 if (Index >= Seq.size()) {
242 assert(Index == Seq.size());
243 FormatStyle Template;
244 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
245 Template = Seq[0];
246 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700247 Template = *((const FormatStyle *)IO.getContext());
Stephen Hines651f13c2014-04-23 16:59:28 -0700248 Template.Language = FormatStyle::LK_None;
249 }
250 Seq.resize(Index + 1, Template);
251 }
252 return Seq[Index];
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000253 }
254};
255}
256}
257
Daniel Jasperbac016b2012-12-03 18:12:45 +0000258namespace clang {
259namespace format {
260
Daniel Jasperbac016b2012-12-03 18:12:45 +0000261FormatStyle getLLVMStyle() {
262 FormatStyle LLVMStyle;
Stephen Hines651f13c2014-04-23 16:59:28 -0700263 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000264 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000265 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000266 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000267 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700268 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
269 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000270 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000271 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienko56312022013-07-04 12:02:44 +0000272 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000273 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000274 LLVMStyle.BinPackParameters = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000275 LLVMStyle.BreakBeforeBinaryOperators = false;
Daniel Jasper1a896a52013-11-08 00:57:11 +0000276 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000277 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
278 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000279 LLVMStyle.ColumnLimit = 80;
Stephen Hines651f13c2014-04-23 16:59:28 -0700280 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkofb594862013-05-06 14:11:27 +0000281 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6315fec2013-08-13 10:58:30 +0000282 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Stephen Hines651f13c2014-04-23 16:59:28 -0700283 LLVMStyle.ContinuationIndentWidth = 4;
284 LLVMStyle.Cpp11BracedListStyle = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000285 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000286 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700287 LLVMStyle.ForEachMacros.push_back("foreach");
288 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
289 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Alexander Kornienkofb594862013-05-06 14:11:27 +0000290 LLVMStyle.IndentCaseLabels = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000291 LLVMStyle.IndentFunctionDeclarationAfterType = false;
292 LLVMStyle.IndentWidth = 2;
Alexander Kornienko0b62cc32013-09-05 14:08:34 +0000293 LLVMStyle.TabWidth = 8;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000294 LLVMStyle.MaxEmptyLinesToKeep = 1;
Stephen Hines651f13c2014-04-23 16:59:28 -0700295 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000296 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Stephen Hines651f13c2014-04-23 16:59:28 -0700297 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Weber5f500df2013-01-10 20:12:55 +0000298 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000299 LLVMStyle.PointerBindsToType = false;
300 LLVMStyle.SpacesBeforeTrailingComments = 1;
Stephen Hines651f13c2014-04-23 16:59:28 -0700301 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +0000302 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000303 LLVMStyle.SpacesInParentheses = false;
304 LLVMStyle.SpaceInEmptyParentheses = false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700305 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000306 LLVMStyle.SpacesInCStyleCastParentheses = false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700307 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasper9b4de852013-09-25 15:15:02 +0000308 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperd8ee5c12013-10-29 14:52:02 +0000309 LLVMStyle.SpacesInAngles = false;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000310
Stephen Hines651f13c2014-04-23 16:59:28 -0700311 LLVMStyle.PenaltyBreakComment = 300;
312 LLVMStyle.PenaltyBreakFirstLessLess = 120;
313 LLVMStyle.PenaltyBreakString = 1000;
314 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000315 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper47066e42013-10-25 14:29:37 +0000316 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000317
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700318 LLVMStyle.DisableFormat = false;
319
Daniel Jasperbac016b2012-12-03 18:12:45 +0000320 return LLVMStyle;
321}
322
Stephen Hines651f13c2014-04-23 16:59:28 -0700323FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
324 FormatStyle GoogleStyle = getLLVMStyle();
325 GoogleStyle.Language = Language;
326
Daniel Jasperbac016b2012-12-03 18:12:45 +0000327 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000328 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000329 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper1bee0732013-05-23 18:05:18 +0000330 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko56312022013-07-04 12:02:44 +0000331 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000332 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000333 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
334 GoogleStyle.DerivePointerBinding = true;
335 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000336 GoogleStyle.IndentFunctionDeclarationAfterType = true;
Stephen Hines651f13c2014-04-23 16:59:28 -0700337 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
338 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Weber5f500df2013-01-10 20:12:55 +0000339 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000340 GoogleStyle.PointerBindsToType = true;
341 GoogleStyle.SpacesBeforeTrailingComments = 2;
342 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000343
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000344 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper47066e42013-10-25 14:29:37 +0000345 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000346
Stephen Hines651f13c2014-04-23 16:59:28 -0700347 if (Language == FormatStyle::LK_JavaScript) {
348 GoogleStyle.BreakBeforeTernaryOperators = false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700349 GoogleStyle.MaxEmptyLinesToKeep = 3;
Stephen Hines651f13c2014-04-23 16:59:28 -0700350 GoogleStyle.SpacesInContainerLiterals = false;
351 } else if (Language == FormatStyle::LK_Proto) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700352 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
353 GoogleStyle.SpacesInContainerLiterals = false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700354 }
355
Daniel Jasperbac016b2012-12-03 18:12:45 +0000356 return GoogleStyle;
357}
358
Stephen Hines651f13c2014-04-23 16:59:28 -0700359FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
360 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Daniel Jasperf1579602013-01-29 16:03:49 +0000361 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700362 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000363 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000364 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000365 ChromiumStyle.BinPackParameters = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000366 ChromiumStyle.DerivePointerBinding = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000367 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000368 return ChromiumStyle;
369}
370
Alexander Kornienkofb594862013-05-06 14:11:27 +0000371FormatStyle getMozillaStyle() {
372 FormatStyle MozillaStyle = getLLVMStyle();
373 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700374 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000375 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
376 MozillaStyle.DerivePointerBinding = true;
377 MozillaStyle.IndentCaseLabels = true;
Stephen Hines651f13c2014-04-23 16:59:28 -0700378 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000379 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
380 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
381 MozillaStyle.PointerBindsToType = true;
Stephen Hines651f13c2014-04-23 16:59:28 -0700382 MozillaStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000383 return MozillaStyle;
384}
385
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000386FormatStyle getWebKitStyle() {
387 FormatStyle Style = getLLVMStyle();
Daniel Jaspereff18b92013-07-31 23:16:02 +0000388 Style.AccessModifierOffset = -4;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000389 Style.AlignTrailingComments = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000390 Style.BreakBeforeBinaryOperators = true;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000391 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000392 Style.BreakConstructorInitializersBeforeComma = true;
Stephen Hines651f13c2014-04-23 16:59:28 -0700393 Style.Cpp11BracedListStyle = false;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000394 Style.ColumnLimit = 0;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000395 Style.IndentWidth = 4;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000396 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Stephen Hines651f13c2014-04-23 16:59:28 -0700397 Style.ObjCSpaceAfterProperty = true;
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000398 Style.PointerBindsToType = true;
Stephen Hines651f13c2014-04-23 16:59:28 -0700399 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000400 return Style;
401}
402
Stephen Hines651f13c2014-04-23 16:59:28 -0700403FormatStyle getGNUStyle() {
404 FormatStyle Style = getLLVMStyle();
405 Style.BreakBeforeBinaryOperators = true;
406 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
407 Style.BreakBeforeTernaryOperators = true;
408 Style.Cpp11BracedListStyle = false;
409 Style.ColumnLimit = 79;
410 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
411 Style.Standard = FormatStyle::LS_Cpp03;
412 return Style;
413}
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000414
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700415FormatStyle getNoStyle() {
416 FormatStyle NoStyle = getLLVMStyle();
417 NoStyle.DisableFormat = true;
418 return NoStyle;
419}
420
Stephen Hines651f13c2014-04-23 16:59:28 -0700421bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
422 FormatStyle *Style) {
423 if (Name.equals_lower("llvm")) {
424 *Style = getLLVMStyle();
425 } else if (Name.equals_lower("chromium")) {
426 *Style = getChromiumStyle(Language);
427 } else if (Name.equals_lower("mozilla")) {
428 *Style = getMozillaStyle();
429 } else if (Name.equals_lower("google")) {
430 *Style = getGoogleStyle(Language);
431 } else if (Name.equals_lower("webkit")) {
432 *Style = getWebKitStyle();
433 } else if (Name.equals_lower("gnu")) {
434 *Style = getGNUStyle();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700435 } else if (Name.equals_lower("none")) {
436 *Style = getNoStyle();
Stephen Hines651f13c2014-04-23 16:59:28 -0700437 } else {
438 return false;
439 }
440
441 Style->Language = Language;
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000442 return true;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000443}
444
445llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700446 assert(Style);
447 FormatStyle::LanguageKind Language = Style->Language;
448 assert(Language != FormatStyle::LK_None);
Alexander Kornienko107db3c2013-05-20 15:18:01 +0000449 if (Text.trim().empty())
450 return llvm::make_error_code(llvm::errc::invalid_argument);
Stephen Hines651f13c2014-04-23 16:59:28 -0700451
452 std::vector<FormatStyle> Styles;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000453 llvm::yaml::Input Input(Text);
Stephen Hines651f13c2014-04-23 16:59:28 -0700454 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
455 // values for the fields, keys for which are missing from the configuration.
456 // Mapping also uses the context to get the language to find the correct
457 // base style.
458 Input.setContext(Style);
459 Input >> Styles;
460 if (Input.error())
461 return Input.error();
462
463 for (unsigned i = 0; i < Styles.size(); ++i) {
464 // Ensures that only the first configuration can skip the Language option.
465 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
466 return llvm::make_error_code(llvm::errc::invalid_argument);
467 // Ensure that each language is configured at most once.
468 for (unsigned j = 0; j < i; ++j) {
469 if (Styles[i].Language == Styles[j].Language) {
470 DEBUG(llvm::dbgs()
471 << "Duplicate languages in the config file on positions " << j
472 << " and " << i << "\n");
473 return llvm::make_error_code(llvm::errc::invalid_argument);
474 }
475 }
476 }
477 // Look for a suitable configuration starting from the end, so we can
478 // find the configuration for the specific language first, and the default
479 // configuration (which can only be at slot 0) after it.
480 for (int i = Styles.size() - 1; i >= 0; --i) {
481 if (Styles[i].Language == Language ||
482 Styles[i].Language == FormatStyle::LK_None) {
483 *Style = Styles[i];
484 Style->Language = Language;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700485 return llvm::error_code::success();
Stephen Hines651f13c2014-04-23 16:59:28 -0700486 }
487 }
488 return llvm::make_error_code(llvm::errc::not_supported);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000489}
490
491std::string configurationAsText(const FormatStyle &Style) {
492 std::string Text;
493 llvm::raw_string_ostream Stream(Text);
494 llvm::yaml::Output Output(Stream);
495 // We use the same mapping method for input and output, so we need a non-const
496 // reference here.
497 FormatStyle NonConstStyle = Style;
498 Output << NonConstStyle;
Alexander Kornienko2b6acb62013-05-13 12:56:35 +0000499 return Stream.str();
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000500}
501
Craig Topper83f81d72013-06-30 22:29:28 +0000502namespace {
503
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000504class NoColumnLimitFormatter {
505public:
Daniel Jasper34f3d052013-08-21 08:39:01 +0000506 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000507
508 /// \brief Formats the line starting at \p State, simply keeping all of the
509 /// input's line breaking decisions.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000510 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasperb77d7412013-09-06 07:54:20 +0000511 LineState State =
512 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700513 while (State.NextToken) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000514 bool Newline =
515 Indenter->mustBreak(State) ||
516 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
517 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
518 }
519 }
Daniel Jasper34f3d052013-08-21 08:39:01 +0000520
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000521private:
522 ContinuationIndenter *Indenter;
523};
524
Daniel Jasper4281d732013-11-06 23:12:09 +0000525class LineJoiner {
526public:
527 LineJoiner(const FormatStyle &Style) : Style(Style) {}
528
529 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
530 unsigned
531 tryFitMultipleLinesInOne(unsigned Indent,
Stephen Hines651f13c2014-04-23 16:59:28 -0700532 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper4281d732013-11-06 23:12:09 +0000533 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
534 // We can never merge stuff if there are trailing line comments.
Stephen Hines651f13c2014-04-23 16:59:28 -0700535 const AnnotatedLine *TheLine = *I;
Daniel Jasper4281d732013-11-06 23:12:09 +0000536 if (TheLine->Last->Type == TT_LineComment)
537 return 0;
538
Stephen Hines651f13c2014-04-23 16:59:28 -0700539 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
Daniel Jasper4281d732013-11-06 23:12:09 +0000540 return 0;
541
Daniel Jasperc2e03292013-11-08 17:33:27 +0000542 unsigned Limit =
543 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper4281d732013-11-06 23:12:09 +0000544 // If we already exceed the column limit, we set 'Limit' to 0. The different
545 // tryMerge..() functions can then decide whether to still do merging.
546 Limit = TheLine->Last->TotalLength > Limit
547 ? 0
548 : Limit - TheLine->Last->TotalLength;
549
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700550 if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
Daniel Jasper4281d732013-11-06 23:12:09 +0000551 return 0;
552
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700553 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
554 // If necessary, change to something smarter.
555 bool MergeShortFunctions =
556 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
557 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
558 TheLine->Level != 0);
559
Stephen Hines651f13c2014-04-23 16:59:28 -0700560 if (TheLine->Last->Type == TT_FunctionLBrace &&
561 TheLine->First != TheLine->Last) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700562 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
Stephen Hines651f13c2014-04-23 16:59:28 -0700563 }
Daniel Jasper4281d732013-11-06 23:12:09 +0000564 if (TheLine->Last->is(tok::l_brace)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700565 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
566 ? tryMergeSimpleBlock(I, E, Limit)
567 : 0;
568 }
569 if (I[1]->First->Type == TT_FunctionLBrace &&
570 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
571 // Check for Limit <= 2 to account for the " {".
572 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
573 return 0;
574 Limit -= 2;
575
576 unsigned MergedLines = 0;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700577 if (MergeShortFunctions) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700578 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
579 // If we managed to merge the block, count the function header, which is
580 // on a separate line.
581 if (MergedLines > 0)
582 ++MergedLines;
583 }
584 return MergedLines;
585 }
586 if (TheLine->First->is(tok::kw_if)) {
587 return Style.AllowShortIfStatementsOnASingleLine
588 ? tryMergeSimpleControlStatement(I, E, Limit)
589 : 0;
590 }
591 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
592 return Style.AllowShortLoopsOnASingleLine
593 ? tryMergeSimpleControlStatement(I, E, Limit)
594 : 0;
595 }
596 if (TheLine->InPPDirective &&
597 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper4281d732013-11-06 23:12:09 +0000598 return tryMergeSimplePPDirective(I, E, Limit);
599 }
600 return 0;
601 }
602
603private:
604 unsigned
Stephen Hines651f13c2014-04-23 16:59:28 -0700605 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper4281d732013-11-06 23:12:09 +0000606 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
607 unsigned Limit) {
608 if (Limit == 0)
609 return 0;
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000610 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper4281d732013-11-06 23:12:09 +0000611 return 0;
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000612 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper4281d732013-11-06 23:12:09 +0000613 return 0;
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000614 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper4281d732013-11-06 23:12:09 +0000615 return 0;
616 return 1;
617 }
618
619 unsigned tryMergeSimpleControlStatement(
Stephen Hines651f13c2014-04-23 16:59:28 -0700620 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper4281d732013-11-06 23:12:09 +0000621 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
622 if (Limit == 0)
623 return 0;
Stephen Hines651f13c2014-04-23 16:59:28 -0700624 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
625 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700626 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
Daniel Jasper4281d732013-11-06 23:12:09 +0000627 return 0;
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000628 if (I[1]->InPPDirective != (*I)->InPPDirective ||
629 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper4281d732013-11-06 23:12:09 +0000630 return 0;
Stephen Hines651f13c2014-04-23 16:59:28 -0700631 Limit = limitConsideringMacros(I + 1, E, Limit);
Daniel Jasper4281d732013-11-06 23:12:09 +0000632 AnnotatedLine &Line = **I;
633 if (Line.Last->isNot(tok::r_paren))
634 return 0;
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000635 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper4281d732013-11-06 23:12:09 +0000636 return 0;
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000637 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Stephen Hines651f13c2014-04-23 16:59:28 -0700638 tok::kw_while) ||
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000639 I[1]->First->Type == TT_LineComment)
Daniel Jasper4281d732013-11-06 23:12:09 +0000640 return 0;
641 // Only inline simple if's (no nested if or else).
642 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000643 I[2]->First->is(tok::kw_else))
Daniel Jasper4281d732013-11-06 23:12:09 +0000644 return 0;
645 return 1;
646 }
647
648 unsigned
Stephen Hines651f13c2014-04-23 16:59:28 -0700649 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper4281d732013-11-06 23:12:09 +0000650 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
651 unsigned Limit) {
Daniel Jasper4281d732013-11-06 23:12:09 +0000652 AnnotatedLine &Line = **I;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700653
654 // Don't merge ObjC @ keywords and methods.
655 if (Line.First->isOneOf(tok::at, tok::minus, tok::plus))
Daniel Jasper4281d732013-11-06 23:12:09 +0000656 return 0;
657
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700658 // Check that the current line allows merging. This depends on whether we
659 // are in a control flow statements as well as several style flags.
660 if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
661 return 0;
662 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
663 tok::kw_catch, tok::kw_for, tok::r_brace)) {
664 if (!Style.AllowShortBlocksOnASingleLine)
665 return 0;
666 if (!Style.AllowShortIfStatementsOnASingleLine &&
667 Line.First->is(tok::kw_if))
668 return 0;
669 if (!Style.AllowShortLoopsOnASingleLine &&
670 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
671 return 0;
672 // FIXME: Consider an option to allow short exception handling clauses on
673 // a single line.
674 if (Line.First->isOneOf(tok::kw_try, tok::kw_catch))
675 return 0;
676 }
677
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000678 FormatToken *Tok = I[1]->First;
Daniel Jasper4281d732013-11-06 23:12:09 +0000679 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700680 (Tok->getNextNonComment() == nullptr ||
Daniel Jasper4281d732013-11-06 23:12:09 +0000681 Tok->getNextNonComment()->is(tok::semi))) {
682 // We merge empty blocks even if the line exceeds the column limit.
683 Tok->SpacesRequiredBefore = 0;
684 Tok->CanBreakBefore = true;
685 return 1;
686 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700687 // We don't merge short records.
688 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
689 return 0;
690
Daniel Jasper4281d732013-11-06 23:12:09 +0000691 // Check that we still have three lines and they fit into the limit.
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000692 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper4281d732013-11-06 23:12:09 +0000693 return 0;
Stephen Hines651f13c2014-04-23 16:59:28 -0700694 Limit = limitConsideringMacros(I + 2, E, Limit);
Daniel Jasper4281d732013-11-06 23:12:09 +0000695
696 if (!nextTwoLinesFitInto(I, Limit))
697 return 0;
698
699 // Second, check that the next line does not contain any braces - if it
700 // does, readability declines when putting it into a single line.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700701 if (I[1]->Last->Type == TT_LineComment)
Daniel Jasper4281d732013-11-06 23:12:09 +0000702 return 0;
703 do {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700704 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
Daniel Jasper4281d732013-11-06 23:12:09 +0000705 return 0;
706 Tok = Tok->Next;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700707 } while (Tok);
Daniel Jasper4281d732013-11-06 23:12:09 +0000708
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700709 // Last, check that the third line starts with a closing brace.
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000710 Tok = I[2]->First;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700711 if (Tok->isNot(tok::r_brace))
Daniel Jasper4281d732013-11-06 23:12:09 +0000712 return 0;
713
714 return 2;
715 }
716 return 0;
717 }
718
Stephen Hines651f13c2014-04-23 16:59:28 -0700719 /// Returns the modified column limit for \p I if it is inside a macro and
720 /// needs a trailing '\'.
721 unsigned
722 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
723 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
724 unsigned Limit) {
725 if (I[0]->InPPDirective && I + 1 != E &&
726 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
727 return Limit < 2 ? 0 : Limit - 2;
728 }
729 return Limit;
730 }
731
Daniel Jasper4281d732013-11-06 23:12:09 +0000732 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
733 unsigned Limit) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700734 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
735 return false;
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000736 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper4281d732013-11-06 23:12:09 +0000737 }
738
Stephen Hines651f13c2014-04-23 16:59:28 -0700739 bool containsMustBreak(const AnnotatedLine *Line) {
740 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
741 if (Tok->MustBreakBefore)
742 return true;
743 }
744 return false;
745 }
746
Daniel Jasper4281d732013-11-06 23:12:09 +0000747 const FormatStyle &Style;
748};
749
Daniel Jasperbac016b2012-12-03 18:12:45 +0000750class UnwrappedLineFormatter {
751public:
Stephen Hines651f13c2014-04-23 16:59:28 -0700752 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper567dcf92013-09-05 09:29:45 +0000753 WhitespaceManager *Whitespaces,
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000754 const FormatStyle &Style)
Stephen Hines651f13c2014-04-23 16:59:28 -0700755 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
756 Joiner(Style) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000757
Daniel Jasper4281d732013-11-06 23:12:09 +0000758 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Stephen Hines651f13c2014-04-23 16:59:28 -0700759 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700760 // Try to look up already computed penalty in DryRun-mode.
761 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
762 &Lines, AdditionalIndent);
763 auto CacheIt = PenaltyCache.find(CacheKey);
764 if (DryRun && CacheIt != PenaltyCache.end())
765 return CacheIt->second;
766
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000767 assert(!Lines.empty());
768 unsigned Penalty = 0;
769 std::vector<int> IndentForLevel;
770 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
771 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700772 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper4281d732013-11-06 23:12:09 +0000773 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
774 E = Lines.end();
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000775 I != E; ++I) {
776 const AnnotatedLine &TheLine = **I;
777 const FormatToken *FirstTok = TheLine.First;
778 int Offset = getIndentOffset(*FirstTok);
779
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000780 // Determine indent and try to merge multiple unwrapped lines.
Stephen Hines651f13c2014-04-23 16:59:28 -0700781 unsigned Indent;
782 if (TheLine.InPPDirective) {
783 Indent = TheLine.Level * Style.IndentWidth;
784 } else {
785 while (IndentForLevel.size() <= TheLine.Level)
786 IndentForLevel.push_back(-1);
787 IndentForLevel.resize(TheLine.Level + 1);
788 Indent = getIndent(IndentForLevel, TheLine.Level);
789 }
790 unsigned LevelIndent = Indent;
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000791 if (static_cast<int>(Indent) + Offset >= 0)
792 Indent += Offset;
Stephen Hines651f13c2014-04-23 16:59:28 -0700793
794 // Merge multiple lines if possible.
Daniel Jasper4281d732013-11-06 23:12:09 +0000795 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
Stephen Hines651f13c2014-04-23 16:59:28 -0700796 if (MergedLines > 0 && Style.ColumnLimit == 0) {
797 // Disallow line merging if there is a break at the start of one of the
798 // input lines.
799 for (unsigned i = 0; i < MergedLines; ++i) {
800 if (I[i + 1]->First->NewlinesBefore > 0)
801 MergedLines = 0;
802 }
803 }
Daniel Jasper4281d732013-11-06 23:12:09 +0000804 if (!DryRun) {
805 for (unsigned i = 0; i < MergedLines; ++i) {
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000806 join(*I[i], *I[i + 1]);
Daniel Jasper4281d732013-11-06 23:12:09 +0000807 }
808 }
809 I += MergedLines;
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000810
Stephen Hines651f13c2014-04-23 16:59:28 -0700811 bool FixIndentation =
812 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000813 if (TheLine.First->is(tok::eof)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700814 if (PreviousLine && PreviousLine->Affected && !DryRun) {
815 // Remove the file's trailing whitespace.
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000816 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
817 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
818 /*IndentLevel=*/0, /*Spaces=*/0,
819 /*TargetColumn=*/0);
820 }
821 } else if (TheLine.Type != LT_Invalid &&
Stephen Hines651f13c2014-04-23 16:59:28 -0700822 (TheLine.Affected || FixIndentation)) {
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000823 if (FirstTok->WhitespaceRange.isValid()) {
824 if (!DryRun)
825 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
826 Indent, TheLine.InPPDirective);
827 } else {
828 Indent = LevelIndent = FirstTok->OriginalColumn;
829 }
830
831 // If everything fits on a single line, just put it there.
832 unsigned ColumnLimit = Style.ColumnLimit;
833 if (I + 1 != E) {
Bill Wendlingb2ea6952013-11-19 18:42:00 +0000834 AnnotatedLine *NextLine = I[1];
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000835 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
836 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
837 }
838
839 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
840 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700841 while (State.NextToken) {
842 formatChildren(State, /*Newline=*/false, /*DryRun=*/false, Penalty);
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000843 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700844 }
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000845 } else if (Style.ColumnLimit == 0) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700846 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000847 NoColumnLimitFormatter Formatter(Indenter);
848 if (!DryRun)
849 Formatter.format(Indent, &TheLine);
850 } else {
851 Penalty += format(TheLine, Indent, DryRun);
852 }
853
Stephen Hines651f13c2014-04-23 16:59:28 -0700854 if (!TheLine.InPPDirective)
855 IndentForLevel[TheLine.Level] = LevelIndent;
856 } else if (TheLine.ChildrenAffected) {
857 format(TheLine.Children, DryRun);
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000858 } else {
859 // Format the first token if necessary, and notify the WhitespaceManager
860 // about the unchanged whitespace.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700861 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000862 if (Tok == TheLine.First &&
863 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
864 unsigned LevelIndent = Tok->OriginalColumn;
865 if (!DryRun) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700866 // Remove trailing whitespace of the previous line.
867 if ((PreviousLine && PreviousLine->Affected) ||
868 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000869 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
870 TheLine.InPPDirective);
871 } else {
872 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
873 }
874 }
875
876 if (static_cast<int>(LevelIndent) - Offset >= 0)
877 LevelIndent -= Offset;
Stephen Hines651f13c2014-04-23 16:59:28 -0700878 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000879 IndentForLevel[TheLine.Level] = LevelIndent;
880 } else if (!DryRun) {
881 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
882 }
883 }
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000884 }
885 if (!DryRun) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700886 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000887 Tok->Finalized = true;
888 }
889 }
890 PreviousLine = *I;
891 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700892 PenaltyCache[CacheKey] = Penalty;
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000893 return Penalty;
894 }
895
896private:
897 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000898 ///
899 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000900 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
901 bool DryRun) {
Daniel Jasperb77d7412013-09-06 07:54:20 +0000902 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000903
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000904 // If the ObjC method declaration does not fit on a line, we should format
905 // it with one arg per line.
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000906 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000907 State.Stack.back().BreakBeforeParameter = true;
908
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000909 // Find best solution in solution space.
Daniel Jasper567dcf92013-09-05 09:29:45 +0000910 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000911 }
912
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000913 /// \brief An edge in the solution space from \c Previous->State to \c State,
914 /// inserting a newline dependent on the \c NewLine.
915 struct StateNode {
916 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +0000917 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000918 LineState State;
919 bool NewLine;
920 StateNode *Previous;
921 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000922
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000923 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
924 ///
925 /// In case of equal penalties, we want to prefer states that were inserted
926 /// first. During state generation we make sure that we insert states first
927 /// that break the line as late as possible.
928 typedef std::pair<unsigned, unsigned> OrderedPenalty;
929
930 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
931 /// \c State has the given \c OrderedPenalty.
932 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
933
934 /// \brief The BFS queue type.
935 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
936 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000937
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000938 /// \brief Get the offset of the line relatively to the level.
939 ///
940 /// For example, 'public:' labels in classes are offset by 1 or 2
941 /// characters to the left from their level.
942 int getIndentOffset(const FormatToken &RootToken) {
943 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
944 return Style.AccessModifierOffset;
945 return 0;
946 }
947
948 /// \brief Add a new line and the required indent before the first Token
949 /// of the \c UnwrappedLine if there was no structural parsing error.
950 void formatFirstToken(FormatToken &RootToken,
951 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
952 unsigned Indent, bool InPPDirective) {
953 unsigned Newlines =
954 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
955 // Remove empty lines before "}" where applicable.
956 if (RootToken.is(tok::r_brace) &&
957 (!RootToken.Next ||
958 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
959 Newlines = std::min(Newlines, 1u);
960 if (Newlines == 0 && !RootToken.IsFirst)
961 Newlines = 1;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700962 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
963 Newlines = 0;
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000964
Stephen Hines651f13c2014-04-23 16:59:28 -0700965 // Remove empty lines after "{".
966 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
967 PreviousLine->Last->is(tok::l_brace) &&
968 PreviousLine->First->isNot(tok::kw_namespace))
969 Newlines = 1;
970
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000971 // Insert extra new line before access specifiers.
972 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
973 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
974 ++Newlines;
975
976 // Remove empty lines after access specifiers.
977 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
978 Newlines = std::min(1u, Newlines);
979
Stephen Hines651f13c2014-04-23 16:59:28 -0700980 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
981 Indent, InPPDirective &&
982 !RootToken.HasUnescapedNewline);
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000983 }
984
985 /// \brief Get the indent of \p Level from \p IndentForLevel.
986 ///
987 /// \p IndentForLevel must contain the indent for the level \c l
988 /// at \p IndentForLevel[l], or a value < 0 if the indent for
989 /// that level is unknown.
990 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
991 if (IndentForLevel[Level] != -1)
992 return IndentForLevel[Level];
993 if (Level == 0)
994 return 0;
995 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
996 }
997
Daniel Jasper2a80ad62013-11-05 19:10:03 +0000998 void join(AnnotatedLine &A, const AnnotatedLine &B) {
999 assert(!A.Last->Next);
1000 assert(!B.First->Previous);
Stephen Hines651f13c2014-04-23 16:59:28 -07001001 if (B.Affected)
1002 A.Affected = true;
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001003 A.Last->Next = B.First;
1004 B.First->Previous = A.Last;
Daniel Jasperc2e03292013-11-08 17:33:27 +00001005 B.First->CanBreakBefore = true;
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001006 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1007 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1008 Tok->TotalLength += LengthA;
1009 A.Last = Tok;
1010 }
1011 }
1012
1013 unsigned getColumnLimit(bool InPPDirective) const {
1014 // In preprocessor directives reserve two chars for trailing " \"
1015 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1016 }
1017
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001018 struct CompareLineStatePointers {
1019 bool operator()(LineState *obj1, LineState *obj2) const {
1020 return *obj1 < *obj2;
1021 }
1022 };
1023
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001024 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +00001025 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001026 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1027 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1028 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper567dcf92013-09-05 09:29:45 +00001029 /// to a state where all tokens are placed. Returns the penalty.
1030 ///
1031 /// If \p DryRun is \c false, directly applies the changes.
1032 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001033 std::set<LineState *, CompareLineStatePointers> Seen;
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001034
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001035 // Increasing count of \c StateNode items we have created. This is used to
1036 // create a deterministic order independent of the container.
1037 unsigned Count = 0;
1038 QueueType Queue;
1039
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001040 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +00001041 StateNode *Node =
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001042 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001043 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1044 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001045
Daniel Jasper567dcf92013-09-05 09:29:45 +00001046 unsigned Penalty = 0;
1047
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001048 // While not empty, take first element and follow edges.
1049 while (!Queue.empty()) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001050 Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +00001051 StateNode *Node = Queue.top().second;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001052 if (!Node->State.NextToken) {
Alexander Kornienkodd256312013-05-10 11:56:10 +00001053 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001054 break;
Daniel Jasper01786732013-02-04 07:21:18 +00001055 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001056 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001057
Daniel Jasper54b4e442013-05-22 05:27:42 +00001058 // Cut off the analysis of certain solutions if the analysis gets too
1059 // complex. See description of IgnoreStackForComparison.
1060 if (Count > 10000)
1061 Node->State.IgnoreStackForComparison = true;
1062
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001063 if (!Seen.insert(&Node->State).second)
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001064 // State already examined with lower penalty.
1065 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001066
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001067 FormatDecision LastFormat = Node->State.NextToken->Decision;
1068 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001069 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001070 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001071 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001072 }
1073
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001074 if (Queue.empty()) {
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001075 // We were unable to find a solution, do nothing.
1076 // FIXME: Add diagnostic?
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001077 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper567dcf92013-09-05 09:29:45 +00001078 return 0;
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001079 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001080
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001081 // Reconstruct the solution.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001082 if (!DryRun)
1083 reconstructPath(InitialState, Queue.top().second);
1084
Alexander Kornienkodd256312013-05-10 11:56:10 +00001085 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1086 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper567dcf92013-09-05 09:29:45 +00001087
1088 return Penalty;
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001089 }
1090
1091 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek9c333b92013-05-29 15:10:11 +00001092 std::deque<StateNode *> Path;
1093 // We do not need a break before the initial token.
1094 while (Current->Previous) {
1095 Path.push_front(Current);
1096 Current = Current->Previous;
1097 }
1098 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1099 I != E; ++I) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001100 unsigned Penalty = 0;
1101 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1102 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1103
Manuel Klimek9c333b92013-05-29 15:10:11 +00001104 DEBUG({
1105 if ((*I)->NewLine) {
Daniel Jasperd4a03db2013-08-22 15:00:41 +00001106 llvm::dbgs() << "Penalty for placing "
Manuel Klimek9c333b92013-05-29 15:10:11 +00001107 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasperd4a03db2013-08-22 15:00:41 +00001108 << Penalty << "\n";
Manuel Klimek9c333b92013-05-29 15:10:11 +00001109 }
1110 });
Manuel Klimek9c333b92013-05-29 15:10:11 +00001111 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001112 }
1113
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001114 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001115 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001116 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001117 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001118 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001119 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +00001120 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001121 return;
Daniel Jasper6b2afe42013-08-16 11:20:30 +00001122 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001123 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001124
1125 StateNode *Node = new (Allocator.Allocate())
1126 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper567dcf92013-09-05 09:29:45 +00001127 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1128 return;
1129
Daniel Jasper6b2afe42013-08-16 11:20:30 +00001130 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001131
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001132 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1133 ++(*Count);
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001134 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001135
Daniel Jasper1a925bc2013-09-05 10:48:50 +00001136 /// \brief If the \p State's next token is an r_brace closing a nested block,
1137 /// format the nested block before it.
Daniel Jasper567dcf92013-09-05 09:29:45 +00001138 ///
1139 /// Returns \c true if all children could be placed successfully and adapts
1140 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1141 /// creates changes using \c Whitespaces.
1142 ///
1143 /// The crucial idea here is that children always get formatted upon
1144 /// encountering the closing brace right after the nested block. Now, if we
1145 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1146 /// \c false), the entire block has to be kept on the same line (which is only
1147 /// possible if it fits on the line, only contains a single statement, etc.
1148 ///
1149 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1150 /// break after the "{", format all lines with correct indentation and the put
1151 /// the closing "}" on yet another new line.
1152 ///
1153 /// This enables us to keep the simple structure of the
1154 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1155 /// break or don't break.
1156 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1157 unsigned &Penalty) {
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001158 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasper15eef852013-10-20 17:28:32 +00001159 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1160 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1161 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasper1a925bc2013-09-05 10:48:50 +00001162 // The previous token does not open a block. Nothing to do. We don't
1163 // assert so that we can simply call this function for all tokens.
Daniel Jasper2f0a0202013-09-06 08:54:24 +00001164 return true;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001165
1166 if (NewLine) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001167 int AdditionalIndent = 0;
1168 if (State.Stack.size() < 2 ||
1169 !State.Stack[State.Stack.size() - 2].JSFunctionInlined) {
1170 AdditionalIndent = State.Stack.back().Indent -
1171 Previous.Children[0]->Level * Style.IndentWidth;
1172 }
1173
Stephen Hines651f13c2014-04-23 16:59:28 -07001174 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1175 /*FixBadIndentation=*/true);
Daniel Jasper567dcf92013-09-05 09:29:45 +00001176 return true;
1177 }
1178
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001179 // Cannot merge multiple statements into a single line.
Daniel Jasper15eef852013-10-20 17:28:32 +00001180 if (Previous.Children.size() > 1)
Stephen Hines651f13c2014-04-23 16:59:28 -07001181 return false;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001182
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001183 // Cannot merge into one line if this line ends on a comment.
1184 if (Previous.is(tok::comment))
1185 return false;
1186
Daniel Jasper567dcf92013-09-05 09:29:45 +00001187 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasper15eef852013-10-20 17:28:32 +00001188 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper567dcf92013-09-05 09:29:45 +00001189 return false;
1190
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001191 // If the child line exceeds the column limit, we wouldn't want to merge it.
1192 // We add +2 for the trailing " }".
1193 if (Style.ColumnLimit > 0 &&
1194 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
1195 Style.ColumnLimit)
1196 return false;
1197
Daniel Jasper567dcf92013-09-05 09:29:45 +00001198 if (!DryRun) {
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +00001199 Whitespaces->replaceWhitespace(
Daniel Jasper15eef852013-10-20 17:28:32 +00001200 *Previous.Children[0]->First,
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +00001201 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3d9ffcf2013-09-27 16:14:22 +00001202 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper567dcf92013-09-05 09:29:45 +00001203 }
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001204 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper567dcf92013-09-05 09:29:45 +00001205
Daniel Jasper15eef852013-10-20 17:28:32 +00001206 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001207 return true;
1208 }
1209
Daniel Jasper6b2afe42013-08-16 11:20:30 +00001210 ContinuationIndenter *Indenter;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001211 WhitespaceManager *Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001212 FormatStyle Style;
Daniel Jasper4281d732013-11-06 23:12:09 +00001213 LineJoiner Joiner;
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001214
1215 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001216
1217 // Cache to store the penalty of formatting a vector of AnnotatedLines
1218 // starting from a specific additional offset. Improves performance if there
1219 // are many nested blocks.
1220 std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
1221 unsigned> PenaltyCache;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001222};
1223
Manuel Klimek96e888b2013-05-28 11:55:06 +00001224class FormatTokenLexer {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001225public:
Manuel Klimekc41e8192013-08-29 15:21:40 +00001226 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienko00895102013-06-05 14:09:10 +00001227 encoding::Encoding Encoding)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001228 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
1229 Column(0), TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr),
1230 Style(Style), IdentTable(getFormattingLangOpts()), Encoding(Encoding),
1231 FirstInLineIndex(0) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001232 Lex.SetKeepWhitespaceMode(true);
Stephen Hines651f13c2014-04-23 16:59:28 -07001233
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001234 for (const std::string &ForEachMacro : Style.ForEachMacros)
Stephen Hines651f13c2014-04-23 16:59:28 -07001235 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1236 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001237 }
1238
Manuel Klimek96e888b2013-05-28 11:55:06 +00001239 ArrayRef<FormatToken *> lex() {
1240 assert(Tokens.empty());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001241 assert(FirstInLineIndex == 0);
Manuel Klimek96e888b2013-05-28 11:55:06 +00001242 do {
1243 Tokens.push_back(getNextToken());
Stephen Hines651f13c2014-04-23 16:59:28 -07001244 tryMergePreviousTokens();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001245 if (Tokens.back()->NewlinesBefore > 0)
1246 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001247 } while (Tokens.back()->Tok.isNot(tok::eof));
1248 return Tokens;
1249 }
1250
1251 IdentifierTable &getIdentTable() { return IdentTable; }
1252
1253private:
Stephen Hines651f13c2014-04-23 16:59:28 -07001254 void tryMergePreviousTokens() {
1255 if (tryMerge_TMacro())
Alexander Kornienko2c2f7292013-09-16 20:20:49 +00001256 return;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001257 if (tryMergeConflictMarkers())
1258 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07001259
1260 if (Style.Language == FormatStyle::LK_JavaScript) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001261 if (tryMergeEscapeSequence())
1262 return;
1263 if (tryMergeJSRegexLiteral())
1264 return;
1265
Stephen Hines651f13c2014-04-23 16:59:28 -07001266 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1267 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1268 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1269 tok::greaterequal };
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001270 static tok::TokenKind JSRightArrow[] = { tok::equal, tok::greater };
Stephen Hines651f13c2014-04-23 16:59:28 -07001271 // FIXME: We probably need to change token type to mimic operator with the
1272 // correct priority.
1273 if (tryMergeTokens(JSIdentity))
1274 return;
1275 if (tryMergeTokens(JSNotIdentity))
1276 return;
1277 if (tryMergeTokens(JSShiftEqual))
1278 return;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001279 if (tryMergeTokens(JSRightArrow))
1280 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07001281 }
1282 }
1283
1284 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1285 if (Tokens.size() < Kinds.size())
1286 return false;
1287
1288 SmallVectorImpl<FormatToken *>::const_iterator First =
1289 Tokens.end() - Kinds.size();
1290 if (!First[0]->is(Kinds[0]))
1291 return false;
1292 unsigned AddLength = 0;
1293 for (unsigned i = 1; i < Kinds.size(); ++i) {
1294 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1295 First[i]->WhitespaceRange.getEnd())
1296 return false;
1297 AddLength += First[i]->TokenText.size();
1298 }
1299 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1300 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1301 First[0]->TokenText.size() + AddLength);
1302 First[0]->ColumnWidth += AddLength;
1303 return true;
1304 }
1305
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001306 // Tries to merge an escape sequence, i.e. a "\\" and the following
1307 // character. Use e.g. inside JavaScript regex literals.
1308 bool tryMergeEscapeSequence() {
1309 if (Tokens.size() < 2)
1310 return false;
1311 FormatToken *Previous = Tokens[Tokens.size() - 2];
1312 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\" ||
1313 Tokens.back()->NewlinesBefore != 0)
1314 return false;
1315 Previous->ColumnWidth += Tokens.back()->ColumnWidth;
1316 StringRef Text = Previous->TokenText;
1317 Previous->TokenText =
1318 StringRef(Text.data(), Text.size() + Tokens.back()->TokenText.size());
1319 Tokens.resize(Tokens.size() - 1);
1320 return true;
1321 }
1322
1323 // Try to determine whether the current token ends a JavaScript regex literal.
1324 // We heuristically assume that this is a regex literal if we find two
1325 // unescaped slashes on a line and the token before the first slash is one of
1326 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
1327 // a division.
1328 bool tryMergeJSRegexLiteral() {
1329 if (Tokens.size() < 2 || Tokens.back()->isNot(tok::slash) ||
1330 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
1331 Tokens[Tokens.size() - 2]->TokenText == "\\"))
1332 return false;
1333 unsigned TokenCount = 0;
1334 unsigned LastColumn = Tokens.back()->OriginalColumn;
1335 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
1336 ++TokenCount;
1337 if (I[0]->is(tok::slash) && I + 1 != E &&
1338 (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
1339 tok::exclaim, tok::l_square, tok::colon, tok::comma,
1340 tok::question, tok::kw_return) ||
1341 I[1]->isBinaryOperator())) {
1342 Tokens.resize(Tokens.size() - TokenCount);
1343 Tokens.back()->Tok.setKind(tok::unknown);
1344 Tokens.back()->Type = TT_RegexLiteral;
1345 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
1346 return true;
1347 }
1348
1349 // There can't be a newline inside a regex literal.
1350 if (I[0]->NewlinesBefore > 0)
1351 return false;
1352 }
1353 return false;
1354 }
1355
Stephen Hines651f13c2014-04-23 16:59:28 -07001356 bool tryMerge_TMacro() {
1357 if (Tokens.size() < 4)
1358 return false;
Alexander Kornienko2c2f7292013-09-16 20:20:49 +00001359 FormatToken *Last = Tokens.back();
1360 if (!Last->is(tok::r_paren))
Stephen Hines651f13c2014-04-23 16:59:28 -07001361 return false;
Alexander Kornienko2c2f7292013-09-16 20:20:49 +00001362
1363 FormatToken *String = Tokens[Tokens.size() - 2];
1364 if (!String->is(tok::string_literal) || String->IsMultiline)
Stephen Hines651f13c2014-04-23 16:59:28 -07001365 return false;
Alexander Kornienko2c2f7292013-09-16 20:20:49 +00001366
1367 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Stephen Hines651f13c2014-04-23 16:59:28 -07001368 return false;
Alexander Kornienko2c2f7292013-09-16 20:20:49 +00001369
1370 FormatToken *Macro = Tokens[Tokens.size() - 4];
1371 if (Macro->TokenText != "_T")
Stephen Hines651f13c2014-04-23 16:59:28 -07001372 return false;
Alexander Kornienko2c2f7292013-09-16 20:20:49 +00001373
1374 const char *Start = Macro->TokenText.data();
1375 const char *End = Last->TokenText.data() + Last->TokenText.size();
1376 String->TokenText = StringRef(Start, End - Start);
1377 String->IsFirst = Macro->IsFirst;
1378 String->LastNewlineOffset = Macro->LastNewlineOffset;
1379 String->WhitespaceRange = Macro->WhitespaceRange;
1380 String->OriginalColumn = Macro->OriginalColumn;
1381 String->ColumnWidth = encoding::columnWidthWithTabs(
1382 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1383
1384 Tokens.pop_back();
1385 Tokens.pop_back();
1386 Tokens.pop_back();
1387 Tokens.back() = String;
Stephen Hines651f13c2014-04-23 16:59:28 -07001388 return true;
Alexander Kornienko2c2f7292013-09-16 20:20:49 +00001389 }
1390
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001391 bool tryMergeConflictMarkers() {
1392 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1393 return false;
1394
1395 // Conflict lines look like:
1396 // <marker> <text from the vcs>
1397 // For example:
1398 // >>>>>>> /file/in/file/system at revision 1234
1399 //
1400 // We merge all tokens in a line that starts with a conflict marker
1401 // into a single token with a special token type that the unwrapped line
1402 // parser will use to correctly rebuild the underlying code.
1403
1404 FileID ID;
1405 // Get the position of the first token in the line.
1406 unsigned FirstInLineOffset;
1407 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1408 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1409 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1410 // Calculate the offset of the start of the current line.
1411 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1412 if (LineOffset == StringRef::npos) {
1413 LineOffset = 0;
1414 } else {
1415 ++LineOffset;
1416 }
1417
1418 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1419 StringRef LineStart;
1420 if (FirstSpace == StringRef::npos) {
1421 LineStart = Buffer.substr(LineOffset);
1422 } else {
1423 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1424 }
1425
1426 TokenType Type = TT_Unknown;
1427 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1428 Type = TT_ConflictStart;
1429 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1430 LineStart == "====") {
1431 Type = TT_ConflictAlternative;
1432 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1433 Type = TT_ConflictEnd;
1434 }
1435
1436 if (Type != TT_Unknown) {
1437 FormatToken *Next = Tokens.back();
1438
1439 Tokens.resize(FirstInLineIndex + 1);
1440 // We do not need to build a complete token here, as we will skip it
1441 // during parsing anyway (as we must not touch whitespace around conflict
1442 // markers).
1443 Tokens.back()->Type = Type;
1444 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1445
1446 Tokens.push_back(Next);
1447 return true;
1448 }
1449
1450 return false;
1451 }
1452
Manuel Klimek96e888b2013-05-28 11:55:06 +00001453 FormatToken *getNextToken() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001454 if (GreaterStashed) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001455 // Create a synthesized second '>' token.
Manuel Klimekc41e8192013-08-29 15:21:40 +00001456 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001457 Token Greater = FormatTok->Tok;
1458 FormatTok = new (Allocator.Allocate()) FormatToken;
1459 FormatTok->Tok = Greater;
Manuel Klimekad3094b2013-05-23 10:56:37 +00001460 SourceLocation GreaterLocation =
Manuel Klimek96e888b2013-05-28 11:55:06 +00001461 FormatTok->Tok.getLocation().getLocWithOffset(1);
1462 FormatTok->WhitespaceRange =
1463 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001464 FormatTok->TokenText = ">";
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001465 FormatTok->ColumnWidth = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001466 GreaterStashed = false;
1467 return FormatTok;
1468 }
1469
Manuel Klimek96e888b2013-05-28 11:55:06 +00001470 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper561211d2013-07-16 20:28:33 +00001471 readRawToken(*FormatTok);
Manuel Klimekde008c02013-05-27 15:23:34 +00001472 SourceLocation WhitespaceStart =
Manuel Klimek96e888b2013-05-28 11:55:06 +00001473 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienkoa9f28092013-11-13 14:04:17 +00001474 FormatTok->IsFirst = IsFirstToken;
1475 IsFirstToken = false;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001476
1477 // Consume and record whitespace until we find a significant token.
Manuel Klimekde008c02013-05-27 15:23:34 +00001478 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001479 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +00001480 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1481 switch (FormatTok->TokenText[i]) {
1482 case '\n':
1483 ++FormatTok->NewlinesBefore;
1484 // FIXME: This is technically incorrect, as it could also
1485 // be a literal backslash at the end of the line.
Alexander Kornienko73d845c2013-09-11 12:25:57 +00001486 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1487 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1488 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimekc41e8192013-08-29 15:21:40 +00001489 FormatTok->HasUnescapedNewline = true;
1490 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1491 Column = 0;
1492 break;
Daniel Jasper1d82b1a2013-10-11 19:45:02 +00001493 case '\r':
1494 case '\f':
1495 case '\v':
1496 Column = 0;
1497 break;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001498 case ' ':
1499 ++Column;
1500 break;
1501 case '\t':
Alexander Kornienko0b62cc32013-09-05 14:08:34 +00001502 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001503 break;
Daniel Jasper1d82b1a2013-10-11 19:45:02 +00001504 case '\\':
1505 ++Column;
1506 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1507 FormatTok->TokenText[i + 1] != '\n'))
1508 FormatTok->Type = TT_ImplicitStringLiteral;
1509 break;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001510 default:
Daniel Jasper1d82b1a2013-10-11 19:45:02 +00001511 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001512 ++Column;
1513 break;
1514 }
1515 }
1516
Daniel Jasper1d82b1a2013-10-11 19:45:02 +00001517 if (FormatTok->Type == TT_ImplicitStringLiteral)
1518 break;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001519 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001520
Daniel Jasper561211d2013-07-16 20:28:33 +00001521 readRawToken(*FormatTok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001522 }
Manuel Klimek95419382013-01-07 07:56:50 +00001523
Manuel Klimekd4397b92013-01-04 23:34:14 +00001524 // In case the token starts with escaped newlines, we want to
1525 // take them into account as whitespace - this pattern is quite frequent
1526 // in macro definitions.
Manuel Klimekd4397b92013-01-04 23:34:14 +00001527 // FIXME: Add a more explicit test.
Daniel Jasper561211d2013-07-16 20:28:33 +00001528 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1529 FormatTok->TokenText[1] == '\n') {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001530 ++FormatTok->NewlinesBefore;
Manuel Klimekad3094b2013-05-23 10:56:37 +00001531 WhitespaceLength += 2;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001532 Column = 0;
Daniel Jasper561211d2013-07-16 20:28:33 +00001533 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001534 }
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001535
1536 FormatTok->WhitespaceRange = SourceRange(
1537 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1538
Manuel Klimekc41e8192013-08-29 15:21:40 +00001539 FormatTok->OriginalColumn = Column;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001540
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001541 TrailingWhitespace = 0;
1542 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +00001543 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper561211d2013-07-16 20:28:33 +00001544 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko51bb5d92013-09-06 17:24:54 +00001545 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper561211d2013-07-16 20:28:33 +00001546 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001547 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper561211d2013-07-16 20:28:33 +00001548 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek96e888b2013-05-28 11:55:06 +00001549 FormatTok->Tok.setIdentifierInfo(&Info);
1550 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001551 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek96e888b2013-05-28 11:55:06 +00001552 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper561211d2013-07-16 20:28:33 +00001553 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001554 GreaterStashed = true;
1555 }
1556
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001557 // Now FormatTok is the next non-whitespace token.
Alexander Kornienko00895102013-06-05 14:09:10 +00001558
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001559 StringRef Text = FormatTok->TokenText;
1560 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko6f6154c2013-09-10 12:29:48 +00001561 if (FirstNewlinePos == StringRef::npos) {
1562 // FIXME: ColumnWidth actually depends on the start column, we need to
1563 // take this into account when the token is moved.
1564 FormatTok->ColumnWidth =
1565 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1566 Column += FormatTok->ColumnWidth;
1567 } else {
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001568 FormatTok->IsMultiline = true;
Alexander Kornienko6f6154c2013-09-10 12:29:48 +00001569 // FIXME: ColumnWidth actually depends on the start column, we need to
1570 // take this into account when the token is moved.
1571 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1572 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1573
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001574 // The last line of the token always starts in column 0.
1575 // Thus, the length can be precomputed even in the presence of tabs.
1576 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1577 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1578 Encoding);
Alexander Kornienko6f6154c2013-09-10 12:29:48 +00001579 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko4b762a92013-09-02 13:58:14 +00001580 }
Alexander Kornienko83a7dcd2013-09-10 09:38:25 +00001581
Stephen Hines651f13c2014-04-23 16:59:28 -07001582 FormatTok->IsForEachMacro =
1583 std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1584 FormatTok->Tok.getIdentifierInfo());
1585
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001586 return FormatTok;
1587 }
1588
Manuel Klimek96e888b2013-05-28 11:55:06 +00001589 FormatToken *FormatTok;
Alexander Kornienkoa9f28092013-11-13 14:04:17 +00001590 bool IsFirstToken;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001591 bool GreaterStashed;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001592 unsigned Column;
Manuel Klimekde008c02013-05-27 15:23:34 +00001593 unsigned TrailingWhitespace;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001594 Lexer &Lex;
1595 SourceManager &SourceMgr;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001596 FormatStyle &Style;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001597 IdentifierTable IdentTable;
Alexander Kornienko00895102013-06-05 14:09:10 +00001598 encoding::Encoding Encoding;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001599 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001600 // Index (in 'Tokens') of the last token that starts a new line.
1601 unsigned FirstInLineIndex;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001602 SmallVector<FormatToken *, 16> Tokens;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001603 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001604
Daniel Jasper561211d2013-07-16 20:28:33 +00001605 void readRawToken(FormatToken &Tok) {
1606 Lex.LexFromRawLexer(Tok.Tok);
1607 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1608 Tok.Tok.getLength());
Daniel Jasper561211d2013-07-16 20:28:33 +00001609 // For formatting, treat unterminated string literals like normal string
1610 // literals.
Stephen Hines651f13c2014-04-23 16:59:28 -07001611 if (Tok.is(tok::unknown)) {
1612 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1613 Tok.Tok.setKind(tok::string_literal);
1614 Tok.IsUnterminatedLiteral = true;
1615 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1616 Tok.TokenText == "''") {
1617 Tok.Tok.setKind(tok::char_constant);
1618 }
Daniel Jasper561211d2013-07-16 20:28:33 +00001619 }
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001620 }
1621};
1622
Stephen Hines651f13c2014-04-23 16:59:28 -07001623static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1624 switch (Language) {
1625 case FormatStyle::LK_Cpp:
1626 return "C++";
1627 case FormatStyle::LK_JavaScript:
1628 return "JavaScript";
1629 case FormatStyle::LK_Proto:
1630 return "Proto";
1631 default:
1632 return "Unknown";
1633 }
1634}
1635
Daniel Jasperbac016b2012-12-03 18:12:45 +00001636class Formatter : public UnwrappedLineConsumer {
1637public:
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001638 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001639 const std::vector<CharSourceRange> &Ranges)
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001640 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko73d845c2013-09-11 12:25:57 +00001641 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001642 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001643 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasper9637dda2013-07-15 14:33:14 +00001644 DEBUG(llvm::dbgs() << "File encoding: "
1645 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1646 : "unknown")
1647 << "\n");
Stephen Hines651f13c2014-04-23 16:59:28 -07001648 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1649 << "\n");
Alexander Kornienko00895102013-06-05 14:09:10 +00001650 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001651
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001652 tooling::Replacements format() {
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001653 tooling::Replacements Result;
Manuel Klimekc41e8192013-08-29 15:21:40 +00001654 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek96e888b2013-05-28 11:55:06 +00001655
1656 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek67d080d2013-04-12 14:13:36 +00001657 bool StructuralError = Parser.parse();
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001658 assert(UnwrappedLines.rbegin()->empty());
1659 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1660 ++Run) {
1661 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1662 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1663 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1664 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1665 }
1666 tooling::Replacements RunResult =
1667 format(AnnotatedLines, StructuralError, Tokens);
1668 DEBUG({
1669 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1670 for (tooling::Replacements::iterator I = RunResult.begin(),
1671 E = RunResult.end();
1672 I != E; ++I) {
1673 llvm::dbgs() << I->toString() << "\n";
1674 }
1675 });
1676 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1677 delete AnnotatedLines[i];
1678 }
1679 Result.insert(RunResult.begin(), RunResult.end());
1680 Whitespaces.reset();
1681 }
1682 return Result;
1683 }
1684
1685 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1686 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienko00895102013-06-05 14:09:10 +00001687 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001688 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001689 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001690 }
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001691 deriveLocalStyle(AnnotatedLines);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001692 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001693 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001694 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001695 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasper5999f762013-04-09 17:46:55 +00001696
Daniel Jasperb77d7412013-09-06 07:54:20 +00001697 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001698 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1699 BinPackInconclusiveFunctions);
Stephen Hines651f13c2014-04-23 16:59:28 -07001700 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001701 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001702 return Whitespaces.generateReplacements();
1703 }
1704
1705private:
Stephen Hines651f13c2014-04-23 16:59:28 -07001706 // Determines which lines are affected by the SourceRanges given as input.
1707 // Returns \c true if at least one line between I and E or one of their
1708 // children is affected.
1709 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1710 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1711 bool SomeLineAffected = false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001712 const AnnotatedLine *PreviousLine = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07001713 while (I != E) {
1714 AnnotatedLine *Line = *I;
1715 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1716
1717 // If a line is part of a preprocessor directive, it needs to be formatted
1718 // if any token within the directive is affected.
1719 if (Line->InPPDirective) {
1720 FormatToken *Last = Line->Last;
1721 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1722 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1723 Last = (*PPEnd)->Last;
1724 ++PPEnd;
1725 }
1726
1727 if (affectsTokenRange(*Line->First, *Last,
1728 /*IncludeLeadingNewlines=*/false)) {
1729 SomeLineAffected = true;
1730 markAllAsAffected(I, PPEnd);
1731 }
1732 I = PPEnd;
1733 continue;
1734 }
1735
1736 if (nonPPLineAffected(Line, PreviousLine))
1737 SomeLineAffected = true;
1738
1739 PreviousLine = Line;
1740 ++I;
1741 }
1742 return SomeLineAffected;
1743 }
1744
1745 // Determines whether 'Line' is affected by the SourceRanges given as input.
1746 // Returns \c true if line or one if its children is affected.
1747 bool nonPPLineAffected(AnnotatedLine *Line,
1748 const AnnotatedLine *PreviousLine) {
1749 bool SomeLineAffected = false;
1750 Line->ChildrenAffected =
1751 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1752 if (Line->ChildrenAffected)
1753 SomeLineAffected = true;
1754
1755 // Stores whether one of the line's tokens is directly affected.
1756 bool SomeTokenAffected = false;
1757 // Stores whether we need to look at the leading newlines of the next token
1758 // in order to determine whether it was affected.
1759 bool IncludeLeadingNewlines = false;
1760
1761 // Stores whether the first child line of any of this line's tokens is
1762 // affected.
1763 bool SomeFirstChildAffected = false;
1764
1765 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1766 // Determine whether 'Tok' was affected.
1767 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1768 SomeTokenAffected = true;
1769
1770 // Determine whether the first child of 'Tok' was affected.
1771 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1772 SomeFirstChildAffected = true;
1773
1774 IncludeLeadingNewlines = Tok->Children.empty();
1775 }
1776
1777 // Was this line moved, i.e. has it previously been on the same line as an
1778 // affected line?
1779 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1780 Line->First->NewlinesBefore == 0;
1781
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001782 bool IsContinuedComment =
1783 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1784 Line->First->NewlinesBefore < 2 && PreviousLine &&
1785 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Stephen Hines651f13c2014-04-23 16:59:28 -07001786
1787 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1788 IsContinuedComment) {
1789 Line->Affected = true;
1790 SomeLineAffected = true;
1791 }
1792 return SomeLineAffected;
1793 }
1794
1795 // Marks all lines between I and E as well as all their children as affected.
1796 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1797 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1798 while (I != E) {
1799 (*I)->Affected = true;
1800 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1801 ++I;
1802 }
1803 }
1804
1805 // Returns true if the range from 'First' to 'Last' intersects with one of the
1806 // input ranges.
1807 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1808 bool IncludeLeadingNewlines) {
1809 SourceLocation Start = First.WhitespaceRange.getBegin();
1810 if (!IncludeLeadingNewlines)
1811 Start = Start.getLocWithOffset(First.LastNewlineOffset);
1812 SourceLocation End = Last.getStartOfNonWhitespace();
1813 if (Last.TokenText.size() > 0)
1814 End = End.getLocWithOffset(Last.TokenText.size() - 1);
1815 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1816 return affectsCharSourceRange(Range);
1817 }
1818
1819 // Returns true if one of the input ranges intersect the leading empty lines
1820 // before 'Tok'.
1821 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1822 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1823 Tok.WhitespaceRange.getBegin(),
1824 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1825 return affectsCharSourceRange(EmptyLineRange);
1826 }
1827
1828 // Returns true if 'Range' intersects with one of the input ranges.
1829 bool affectsCharSourceRange(const CharSourceRange &Range) {
1830 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1831 E = Ranges.end();
1832 I != E; ++I) {
1833 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1834 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1835 return true;
1836 }
1837 return false;
1838 }
1839
Alexander Kornienko73d845c2013-09-11 12:25:57 +00001840 static bool inputUsesCRLF(StringRef Text) {
1841 return Text.count('\r') * 2 > Text.count('\n');
1842 }
1843
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001844 void
1845 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001846 unsigned CountBoundToVariable = 0;
1847 unsigned CountBoundToType = 0;
1848 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001849 bool HasBinPackedFunction = false;
1850 bool HasOnePerLineFunction = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001851 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper567dcf92013-09-05 09:29:45 +00001852 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001853 continue;
Daniel Jasper567dcf92013-09-05 09:29:45 +00001854 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimekb3987012013-05-29 14:47:47 +00001855 while (Tok->Next) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001856 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001857 bool SpacesBefore =
1858 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1859 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1860 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001861 if (SpacesBefore && !SpacesAfter)
1862 ++CountBoundToVariable;
1863 else if (!SpacesBefore && SpacesAfter)
1864 ++CountBoundToType;
1865 }
1866
Daniel Jasper78a4e612013-10-12 05:16:06 +00001867 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1868 if (Tok->is(tok::coloncolon) &&
1869 Tok->Previous->Type == TT_TemplateOpener)
1870 HasCpp03IncompatibleFormat = true;
1871 if (Tok->Type == TT_TemplateCloser &&
1872 Tok->Previous->Type == TT_TemplateCloser)
1873 HasCpp03IncompatibleFormat = true;
1874 }
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001875
1876 if (Tok->PackingKind == PPK_BinPacked)
1877 HasBinPackedFunction = true;
1878 if (Tok->PackingKind == PPK_OnePerLine)
1879 HasOnePerLineFunction = true;
1880
Manuel Klimekb3987012013-05-29 14:47:47 +00001881 Tok = Tok->Next;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001882 }
1883 }
1884 if (Style.DerivePointerBinding) {
1885 if (CountBoundToType > CountBoundToVariable)
1886 Style.PointerBindsToType = true;
1887 else if (CountBoundToType < CountBoundToVariable)
1888 Style.PointerBindsToType = false;
1889 }
1890 if (Style.Standard == FormatStyle::LS_Auto) {
1891 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1892 : FormatStyle::LS_Cpp03;
1893 }
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001894 BinPackInconclusiveFunctions =
1895 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001896 }
1897
Stephen Hines651f13c2014-04-23 16:59:28 -07001898 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001899 assert(!UnwrappedLines.empty());
1900 UnwrappedLines.back().push_back(TheLine);
1901 }
1902
Stephen Hines651f13c2014-04-23 16:59:28 -07001903 void finishRun() override {
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001904 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperbac016b2012-12-03 18:12:45 +00001905 }
1906
1907 FormatStyle Style;
1908 Lexer &Lex;
1909 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001910 WhitespaceManager Whitespaces;
Daniel Jasper2a80ad62013-11-05 19:10:03 +00001911 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimekae76f7f2013-10-11 21:25:45 +00001912 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienko00895102013-06-05 14:09:10 +00001913
1914 encoding::Encoding Encoding;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001915 bool BinPackInconclusiveFunctions;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001916};
1917
Craig Topper83f81d72013-06-30 22:29:28 +00001918} // end anonymous namespace
1919
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001920tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1921 SourceManager &SourceMgr,
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001922 std::vector<CharSourceRange> Ranges) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001923 if (Style.DisableFormat) {
1924 tooling::Replacements EmptyResult;
1925 return EmptyResult;
1926 }
1927
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001928 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001929 return formatter.format();
1930}
1931
Daniel Jasper8a999452013-05-16 10:40:07 +00001932tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1933 std::vector<tooling::Range> Ranges,
1934 StringRef FileName) {
1935 FileManager Files((FileSystemOptions()));
1936 DiagnosticsEngine Diagnostics(
1937 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1938 new DiagnosticOptions);
1939 SourceManager SourceMgr(Diagnostics, Files);
1940 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1941 const clang::FileEntry *Entry =
1942 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1943 SourceMgr.overrideFileContents(Entry, Buf);
1944 FileID ID =
1945 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001946 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1947 getFormattingLangOpts(Style.Standard));
Daniel Jasper8a999452013-05-16 10:40:07 +00001948 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1949 std::vector<CharSourceRange> CharRanges;
1950 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1951 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1952 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1953 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1954 }
1955 return reformat(Style, Lex, SourceMgr, CharRanges);
1956}
1957
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001958LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasper46ef8522013-01-10 13:08:12 +00001959 LangOptions LangOpts;
1960 LangOpts.CPlusPlus = 1;
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001961 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001962 LangOpts.CPlusPlus1y = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasperb64eca02013-03-22 10:01:29 +00001963 LangOpts.LineComment = 1;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001964 LangOpts.CXXOperatorNames = 1;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001965 LangOpts.Bool = 1;
1966 LangOpts.ObjC1 = 1;
1967 LangOpts.ObjC2 = 1;
1968 return LangOpts;
1969}
1970
Edwin Vanef4e12c82013-09-30 13:31:48 +00001971const char *StyleOptionHelpDescription =
1972 "Coding style, currently supports:\n"
1973 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1974 "Use -style=file to load style configuration from\n"
1975 ".clang-format file located in one of the parent\n"
1976 "directories of the source file (or current\n"
1977 "directory for stdin).\n"
1978 "Use -style=\"{key: value, ...}\" to set specific\n"
1979 "parameters, e.g.:\n"
1980 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1981
Stephen Hines651f13c2014-04-23 16:59:28 -07001982static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
1983 if (FileName.endswith_lower(".js")) {
1984 return FormatStyle::LK_JavaScript;
1985 } else if (FileName.endswith_lower(".proto") ||
1986 FileName.endswith_lower(".protodevel")) {
1987 return FormatStyle::LK_Proto;
1988 }
1989 return FormatStyle::LK_Cpp;
1990}
1991
1992FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1993 StringRef FallbackStyle) {
1994 FormatStyle Style = getLLVMStyle();
1995 Style.Language = getLanguageByFileName(FileName);
1996 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
1997 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1998 << "\" using LLVM style\n";
1999 return Style;
2000 }
Edwin Vanef4e12c82013-09-30 13:31:48 +00002001
2002 if (StyleName.startswith("{")) {
2003 // Parse YAML/JSON style from the command line.
2004 if (llvm::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +00002005 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
2006 << FallbackStyle << " style\n";
Edwin Vanef4e12c82013-09-30 13:31:48 +00002007 }
2008 return Style;
2009 }
2010
2011 if (!StyleName.equals_lower("file")) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002012 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vanef4e12c82013-09-30 13:31:48 +00002013 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
2014 << " style\n";
2015 return Style;
2016 }
2017
Stephen Hines651f13c2014-04-23 16:59:28 -07002018 // Look for .clang-format/_clang-format file in the file's parent directories.
2019 SmallString<128> UnsuitableConfigFiles;
Edwin Vanef4e12c82013-09-30 13:31:48 +00002020 SmallString<128> Path(FileName);
2021 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkof0fc89c2013-10-14 00:46:35 +00002022 for (StringRef Directory = Path; !Directory.empty();
Edwin Vanef4e12c82013-09-30 13:31:48 +00002023 Directory = llvm::sys::path::parent_path(Directory)) {
2024 if (!llvm::sys::fs::is_directory(Directory))
2025 continue;
2026 SmallString<128> ConfigFile(Directory);
2027
2028 llvm::sys::path::append(ConfigFile, ".clang-format");
2029 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2030 bool IsFile = false;
2031 // Ignore errors from is_regular_file: we only need to know if we can read
2032 // the file or not.
2033 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2034
2035 if (!IsFile) {
2036 // Try _clang-format too, since dotfiles are not commonly used on Windows.
2037 ConfigFile = Directory;
2038 llvm::sys::path::append(ConfigFile, "_clang-format");
2039 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2040 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2041 }
2042
2043 if (IsFile) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002044 std::unique_ptr<llvm::MemoryBuffer> Text;
Rafael Espindola28ce23a2013-10-25 19:00:49 +00002045 if (llvm::error_code ec =
2046 llvm::MemoryBuffer::getFile(ConfigFile.c_str(), Text)) {
Edwin Vanef4e12c82013-09-30 13:31:48 +00002047 llvm::errs() << ec.message() << "\n";
Stephen Hines651f13c2014-04-23 16:59:28 -07002048 break;
Edwin Vanef4e12c82013-09-30 13:31:48 +00002049 }
2050 if (llvm::error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002051 if (ec == llvm::errc::not_supported) {
2052 if (!UnsuitableConfigFiles.empty())
2053 UnsuitableConfigFiles.append(", ");
2054 UnsuitableConfigFiles.append(ConfigFile);
2055 continue;
2056 }
Edwin Vanef4e12c82013-09-30 13:31:48 +00002057 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2058 << "\n";
Stephen Hines651f13c2014-04-23 16:59:28 -07002059 break;
Edwin Vanef4e12c82013-09-30 13:31:48 +00002060 }
2061 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2062 return Style;
2063 }
2064 }
2065 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
2066 << " style\n";
Stephen Hines651f13c2014-04-23 16:59:28 -07002067 if (!UnsuitableConfigFiles.empty()) {
2068 llvm::errs() << "Configuration file(s) do(es) not support "
2069 << getLanguageName(Style.Language) << ": "
2070 << UnsuitableConfigFiles << "\n";
2071 }
Edwin Vanef4e12c82013-09-30 13:31:48 +00002072 return Style;
2073}
2074
Daniel Jaspercd162382013-01-07 13:26:07 +00002075} // namespace format
2076} // namespace clang