blob: 5b2f222bfc5679481fd4600bdf3f21eaf2be6472 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
Daniel Jasperf7935112012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Daniel Jasperde0328a2013-08-16 11:20:30 +000016#include "ContinuationIndenter.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000017#include "TokenAnnotator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "UnwrappedLineParser.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000019#include "WhitespaceManager.h"
Daniel Jasperec04c0d2013-05-16 10:40:07 +000020#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000021#include "clang/Basic/DiagnosticOptions.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000023#include "clang/Format/Format.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000024#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000025#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000026#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000027#include "llvm/Support/Debug.h"
Edwin Vaned544aa72013-09-30 13:31:48 +000028#include "llvm/Support/Path.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000029#include "llvm/Support/YAMLTraits.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000030#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000031#include <string>
32
Chandler Carruth10346662014-04-22 03:17:02 +000033#define DEBUG_TYPE "format-formatter"
34
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000035using clang::format::FormatStyle;
36
Daniel Jaspere1e43192014-04-01 12:55:11 +000037LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
38
Alexander Kornienkod6538332013-05-07 15:32:14 +000039namespace llvm {
40namespace yaml {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000041template <> 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);
Daniel Jasper7052ce62014-01-19 09:04:08 +000045 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000046 }
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
Daniel Jasperd74cf402014-04-08 12:46:38 +000069template <> 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
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000079template <> 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);
Alexander Kornienko3a33f022013-12-12 09:49:52 +000085 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000086 }
87};
88
Alexander Kornienkod6538332013-05-07 15:32:14 +000089template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000090struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +000091 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000092 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);
Alexander Kornienkocabdd732013-11-29 15:19:43 +000096 }
97};
98
99template <>
Daniel Jasper553d4872014-06-17 12:40:34 +0000100struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
101 static void enumeration(IO &IO,
102 FormatStyle::PointerAlignmentStyle &Value) {
103 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
104 IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
105 IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
106
Alp Toker958027b2014-07-14 19:42:55 +0000107 // For backward compatibility.
Daniel Jasper553d4872014-06-17 12:40:34 +0000108 IO.enumCase(Value, "true", FormatStyle::PAS_Left);
109 IO.enumCase(Value, "false", FormatStyle::PAS_Right);
110 }
111};
112
113template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000114struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000115 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000116 FormatStyle::SpaceBeforeParensOptions &Value) {
117 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000118 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000119 FormatStyle::SBPO_ControlStatements);
120 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000121
122 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000123 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
124 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000125 }
126};
127
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000128template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000129 static void mapping(IO &IO, FormatStyle &Style) {
130 // When reading, read the language first, we need it for getPredefinedStyle.
131 IO.mapOptional("Language", Style.Language);
132
Alexander Kornienko49149672013-05-10 11:56:10 +0000133 if (IO.outputting()) {
Alexander Kornienkoe3648fb2013-09-02 16:39:23 +0000134 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000135 "Mozilla", "WebKit", "GNU" };
Alexander Kornienko49149672013-05-10 11:56:10 +0000136 ArrayRef<StringRef> Styles(StylesArray);
137 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
138 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000139 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000140 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000141 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000142 IO.mapOptional("# BasedOnStyle", StyleName);
143 break;
144 }
145 }
146 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000147 StringRef BasedOnStyle;
148 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000149 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000150 FormatStyle::LanguageKind OldLanguage = Style.Language;
151 FormatStyle::LanguageKind Language =
152 ((FormatStyle *)IO.getContext())->Language;
153 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000154 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
155 return;
156 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000157 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000158 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000159 }
160
161 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000162 IO.mapOptional("ConstructorInitializerIndentWidth",
163 Style.ConstructorInitializerIndentWidth);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000164 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000165 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000166 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
167 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000168 IO.mapOptional("AllowShortBlocksOnASingleLine",
169 Style.AllowShortBlocksOnASingleLine);
Daniel Jasperb87899b2014-09-10 13:11:45 +0000170 IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
171 Style.AllowShortCaseLabelsOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000172 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
173 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000174 IO.mapOptional("AllowShortLoopsOnASingleLine",
175 Style.AllowShortLoopsOnASingleLine);
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000176 IO.mapOptional("AllowShortFunctionsOnASingleLine",
177 Style.AllowShortFunctionsOnASingleLine);
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000178 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
179 Style.AlwaysBreakAfterDefinitionReturnType);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000180 IO.mapOptional("AlwaysBreakTemplateDeclarations",
181 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko58611712013-07-04 12:02:44 +0000182 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
183 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000184 IO.mapOptional("BreakBeforeBinaryOperators",
185 Style.BreakBeforeBinaryOperators);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000186 IO.mapOptional("BreakBeforeTernaryOperators",
187 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000188 IO.mapOptional("BreakConstructorInitializersBeforeComma",
189 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000190 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
191 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
192 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
193 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000194 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000195 IO.mapOptional("ExperimentalAutoDetectBinPacking",
196 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000197 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000198 IO.mapOptional("IndentWrappedFunctionNames",
199 Style.IndentWrappedFunctionNames);
200 IO.mapOptional("IndentFunctionDeclarationAfterType",
201 Style.IndentWrappedFunctionNames);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000202 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000203 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
204 Style.KeepEmptyLinesAtTheStartOfBlocks);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000205 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000206 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000207 IO.mapOptional("ObjCSpaceBeforeProtocolList",
208 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000209 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
210 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000211 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
212 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000213 IO.mapOptional("PenaltyBreakFirstLessLess",
214 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000215 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
216 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
217 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000218 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000219 IO.mapOptional("SpacesBeforeTrailingComments",
220 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000221 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000222 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000223 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000224 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000225 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000226 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000227 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperad981f82014-08-26 11:41:14 +0000228 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000229 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasperf110e202013-08-21 08:39:01 +0000230 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000231 IO.mapOptional("SpacesInCStyleCastParentheses",
232 Style.SpacesInCStyleCastParentheses);
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000233 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000234 IO.mapOptional("SpacesInContainerLiterals",
235 Style.SpacesInContainerLiterals);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000236 IO.mapOptional("SpaceBeforeAssignmentOperators",
237 Style.SpaceBeforeAssignmentOperators);
Daniel Jasper6633ab82013-10-18 10:38:14 +0000238 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000239 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000240 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000241
242 // For backward compatibility.
243 if (!IO.outputting()) {
244 IO.mapOptional("SpaceAfterControlStatementKeyword",
245 Style.SpaceBeforeParens);
Daniel Jasper553d4872014-06-17 12:40:34 +0000246 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
247 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000248 }
249 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000250 IO.mapOptional("DisableFormat", Style.DisableFormat);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000251 }
252};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000253
254// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000255// IO.getContext() should contain a pointer to the FormatStyle structure, that
256// will be used to get default values for missing keys.
257// If the first element has no Language specified, it will be treated as the
258// default one for the following elements.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000259template <> struct DocumentListTraits<std::vector<FormatStyle> > {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000260 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
261 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000262 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000263 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000264 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000265 if (Index >= Seq.size()) {
266 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000267 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000268 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000269 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000270 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000271 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000272 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000273 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000274 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000275 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000276 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000277 }
278};
Alexander Kornienkod6538332013-05-07 15:32:14 +0000279}
280}
281
Daniel Jasperf7935112012-12-03 18:12:45 +0000282namespace clang {
283namespace format {
284
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000285const std::error_category &getParseCategory() {
Rafael Espindolad0136702014-06-12 02:50:04 +0000286 static ParseErrorCategory C;
287 return C;
288}
289std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000290 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000291}
292
293const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
294 return "clang-format.parse_error";
295}
296
297std::string ParseErrorCategory::message(int EV) const {
298 switch (static_cast<ParseError>(EV)) {
299 case ParseError::Success:
300 return "Success";
301 case ParseError::Error:
302 return "Invalid argument";
303 case ParseError::Unsuitable:
304 return "Unsuitable";
305 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000306 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000307}
308
Daniel Jasperf7935112012-12-03 18:12:45 +0000309FormatStyle getLLVMStyle() {
310 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000311 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000312 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000313 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000314 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000315 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000316 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000317 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000318 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000319 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000320 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000321 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000322 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000323 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000324 LLVMStyle.BinPackParameters = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000325 LLVMStyle.BreakBeforeBinaryOperators = false;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000326 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000327 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
328 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000329 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000330 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000331 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000332 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000333 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000334 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000335 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000336 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000337 LLVMStyle.ForEachMacros.push_back("foreach");
338 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
339 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000340 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000341 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000342 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000343 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000344 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000345 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000346 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000347 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000348 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000349 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000350 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000351 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000352 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000353 LLVMStyle.SpacesInParentheses = false;
Daniel Jasperad981f82014-08-26 11:41:14 +0000354 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000355 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000356 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000357 LLVMStyle.SpacesInCStyleCastParentheses = false;
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000358 LLVMStyle.SpaceAfterCStyleCast = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000359 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000360 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000361 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000362
Daniel Jasper19a541e2013-12-19 16:45:34 +0000363 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000364 LLVMStyle.PenaltyBreakFirstLessLess = 120;
365 LLVMStyle.PenaltyBreakString = 1000;
366 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000367 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000368 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000369
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000370 LLVMStyle.DisableFormat = false;
371
Daniel Jasperf7935112012-12-03 18:12:45 +0000372 return LLVMStyle;
373}
374
Nico Weber514ecc82014-02-02 20:50:45 +0000375FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000376 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000377 GoogleStyle.Language = Language;
378
Daniel Jasperf7935112012-12-03 18:12:45 +0000379 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000380 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000381 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000382 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000383 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000384 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000385 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000386 GoogleStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000387 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000388 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000389 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000390 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000391 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000392 GoogleStyle.SpacesBeforeTrailingComments = 2;
393 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000394
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000395 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000396 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000397
Nico Weber514ecc82014-02-02 20:50:45 +0000398 if (Language == FormatStyle::LK_JavaScript) {
399 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000400 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000401 GoogleStyle.SpacesInContainerLiterals = false;
402 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000403 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000404 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000405 }
406
Daniel Jasperf7935112012-12-03 18:12:45 +0000407 return GoogleStyle;
408}
409
Nico Weber514ecc82014-02-02 20:50:45 +0000410FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
411 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Daniel Jasperf7db4332013-01-29 16:03:49 +0000412 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000413 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000414 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000415 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000416 ChromiumStyle.BinPackParameters = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000417 ChromiumStyle.DerivePointerAlignment = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000418 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000419 return ChromiumStyle;
420}
421
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000422FormatStyle getMozillaStyle() {
423 FormatStyle MozillaStyle = getLLVMStyle();
424 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000425 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000426 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000427 MozillaStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000428 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000429 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000430 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
431 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000432 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000433 MozillaStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000434 return MozillaStyle;
435}
436
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000437FormatStyle getWebKitStyle() {
438 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000439 Style.AccessModifierOffset = -4;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000440 Style.AlignTrailingComments = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000441 Style.BreakBeforeBinaryOperators = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000442 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000443 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000444 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000445 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000446 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000447 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000448 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000449 Style.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000450 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000451 return Style;
452}
453
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000454FormatStyle getGNUStyle() {
455 FormatStyle Style = getLLVMStyle();
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000456 Style.AlwaysBreakAfterDefinitionReturnType = true;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000457 Style.BreakBeforeBinaryOperators = true;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000458 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000459 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000460 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000461 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000462 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000463 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000464 return Style;
465}
466
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000467FormatStyle getNoStyle() {
468 FormatStyle NoStyle = getLLVMStyle();
469 NoStyle.DisableFormat = true;
470 return NoStyle;
471}
472
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000473bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
474 FormatStyle *Style) {
475 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000476 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000477 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000478 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000479 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000480 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000481 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000482 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000483 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000484 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000485 } else if (Name.equals_lower("gnu")) {
486 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000487 } else if (Name.equals_lower("none")) {
488 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000489 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000490 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000491 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000492
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000493 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000494 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000495}
496
Rafael Espindolac0809172014-06-12 14:02:15 +0000497std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000498 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000499 FormatStyle::LanguageKind Language = Style->Language;
500 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000501 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000502 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000503
504 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000505 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000506 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
507 // values for the fields, keys for which are missing from the configuration.
508 // Mapping also uses the context to get the language to find the correct
509 // base style.
510 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000511 Input >> Styles;
512 if (Input.error())
513 return Input.error();
514
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000515 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000516 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000517 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000518 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000519 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000520 for (unsigned j = 0; j < i; ++j) {
521 if (Styles[i].Language == Styles[j].Language) {
522 DEBUG(llvm::dbgs()
523 << "Duplicate languages in the config file on positions " << j
524 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000525 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000526 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000527 }
528 }
529 // Look for a suitable configuration starting from the end, so we can
530 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000531 // configuration (which can only be at slot 0) after it.
532 for (int i = Styles.size() - 1; i >= 0; --i) {
533 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000534 Styles[i].Language == FormatStyle::LK_None) {
535 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000536 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000537 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000538 }
539 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000540 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000541}
542
543std::string configurationAsText(const FormatStyle &Style) {
544 std::string Text;
545 llvm::raw_string_ostream Stream(Text);
546 llvm::yaml::Output Output(Stream);
547 // We use the same mapping method for input and output, so we need a non-const
548 // reference here.
549 FormatStyle NonConstStyle = Style;
550 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000551 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000552}
553
Craig Topperaf35e852013-06-30 22:29:28 +0000554namespace {
555
Daniel Jasperde0328a2013-08-16 11:20:30 +0000556class NoColumnLimitFormatter {
557public:
Daniel Jasperf110e202013-08-21 08:39:01 +0000558 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000559
560 /// \brief Formats the line starting at \p State, simply keeping all of the
561 /// input's line breaking decisions.
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000562 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000563 LineState State =
564 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Craig Topper2145bc02014-05-09 08:15:10 +0000565 while (State.NextToken) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000566 bool Newline =
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000567 Indenter->mustBreak(State) ||
Daniel Jasperde0328a2013-08-16 11:20:30 +0000568 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
569 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
570 }
571 }
Daniel Jasperf110e202013-08-21 08:39:01 +0000572
Daniel Jasperde0328a2013-08-16 11:20:30 +0000573private:
574 ContinuationIndenter *Indenter;
575};
576
Daniel Jasper56f8b432013-11-06 23:12:09 +0000577class LineJoiner {
578public:
579 LineJoiner(const FormatStyle &Style) : Style(Style) {}
580
581 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
582 unsigned
583 tryFitMultipleLinesInOne(unsigned Indent,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000584 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000585 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
586 // We can never merge stuff if there are trailing line comments.
Daniel Jasper234379f2013-12-24 13:31:25 +0000587 const AnnotatedLine *TheLine = *I;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000588 if (TheLine->Last->Type == TT_LineComment)
589 return 0;
590
Alexander Kornienkoecc232d2013-12-04 13:25:26 +0000591 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
592 return 0;
593
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000594 unsigned Limit =
595 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000596 // If we already exceed the column limit, we set 'Limit' to 0. The different
597 // tryMerge..() functions can then decide whether to still do merging.
598 Limit = TheLine->Last->TotalLength > Limit
599 ? 0
600 : Limit - TheLine->Last->TotalLength;
601
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000602 if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000603 return 0;
604
Daniel Jasperd74cf402014-04-08 12:46:38 +0000605 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
606 // If necessary, change to something smarter.
607 bool MergeShortFunctions =
608 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
609 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
610 TheLine->Level != 0);
611
Daniel Jasper234379f2013-12-24 13:31:25 +0000612 if (TheLine->Last->Type == TT_FunctionLBrace &&
613 TheLine->First != TheLine->Last) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000614 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000615 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000616 if (TheLine->Last->is(tok::l_brace)) {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000617 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000618 ? tryMergeSimpleBlock(I, E, Limit)
619 : 0;
620 }
621 if (I[1]->First->Type == TT_FunctionLBrace &&
622 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
Alp Tokerba5b4dc2013-12-30 02:06:29 +0000623 // Check for Limit <= 2 to account for the " {".
Daniel Jasper234379f2013-12-24 13:31:25 +0000624 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
625 return 0;
626 Limit -= 2;
627
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000628 unsigned MergedLines = 0;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000629 if (MergeShortFunctions) {
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000630 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
631 // If we managed to merge the block, count the function header, which is
632 // on a separate line.
633 if (MergedLines > 0)
634 ++MergedLines;
635 }
636 return MergedLines;
637 }
638 if (TheLine->First->is(tok::kw_if)) {
639 return Style.AllowShortIfStatementsOnASingleLine
640 ? tryMergeSimpleControlStatement(I, E, Limit)
641 : 0;
642 }
643 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
644 return Style.AllowShortLoopsOnASingleLine
645 ? tryMergeSimpleControlStatement(I, E, Limit)
646 : 0;
647 }
Daniel Jasperb87899b2014-09-10 13:11:45 +0000648 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
649 return Style.AllowShortCaseLabelsOnASingleLine
650 ? tryMergeShortCaseLabels(I, E, Limit)
651 : 0;
652 }
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000653 if (TheLine->InPPDirective &&
654 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000655 return tryMergeSimplePPDirective(I, E, Limit);
656 }
657 return 0;
658 }
659
660private:
661 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000662 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000663 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
664 unsigned Limit) {
665 if (Limit == 0)
666 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000667 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000668 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000669 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000670 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000671 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000672 return 0;
673 return 1;
674 }
675
676 unsigned tryMergeSimpleControlStatement(
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000677 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000678 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
679 if (Limit == 0)
680 return 0;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000681 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
682 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
Daniel Jasper17605d32014-05-14 09:33:35 +0000683 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000684 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000685 if (I[1]->InPPDirective != (*I)->InPPDirective ||
686 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000687 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000688 Limit = limitConsideringMacros(I + 1, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000689 AnnotatedLine &Line = **I;
690 if (Line.Last->isNot(tok::r_paren))
691 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000692 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000693 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000694 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000695 tok::kw_while) ||
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000696 I[1]->First->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000697 return 0;
698 // Only inline simple if's (no nested if or else).
699 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000700 I[2]->First->is(tok::kw_else))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000701 return 0;
702 return 1;
703 }
704
Daniel Jasperb87899b2014-09-10 13:11:45 +0000705 unsigned tryMergeShortCaseLabels(
706 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
707 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
708 if (Limit == 0 || I + 1 == E ||
709 I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
710 return 0;
711 unsigned NumStmts = 0;
712 unsigned Length = 0;
713 for (; NumStmts < 3; ++NumStmts) {
714 if (I + 1 + NumStmts == E)
715 break;
716 const AnnotatedLine *Line = I[1 + NumStmts];
717 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
718 break;
719 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
720 tok::kw_while))
721 return 0;
722 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
723 }
724 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
725 return 0;
726 return NumStmts;
727 }
728
Daniel Jasper56f8b432013-11-06 23:12:09 +0000729 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000730 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000731 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
732 unsigned Limit) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000733 AnnotatedLine &Line = **I;
Daniel Jasper17605d32014-05-14 09:33:35 +0000734
735 // Don't merge ObjC @ keywords and methods.
736 if (Line.First->isOneOf(tok::at, tok::minus, tok::plus))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000737 return 0;
738
Daniel Jasper17605d32014-05-14 09:33:35 +0000739 // Check that the current line allows merging. This depends on whether we
740 // are in a control flow statements as well as several style flags.
741 if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
742 return 0;
743 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
744 tok::kw_catch, tok::kw_for, tok::r_brace)) {
745 if (!Style.AllowShortBlocksOnASingleLine)
746 return 0;
747 if (!Style.AllowShortIfStatementsOnASingleLine &&
748 Line.First->is(tok::kw_if))
749 return 0;
750 if (!Style.AllowShortLoopsOnASingleLine &&
751 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
752 return 0;
753 // FIXME: Consider an option to allow short exception handling clauses on
754 // a single line.
755 if (Line.First->isOneOf(tok::kw_try, tok::kw_catch))
756 return 0;
757 }
758
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000759 FormatToken *Tok = I[1]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000760 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Craig Topper2145bc02014-05-09 08:15:10 +0000761 (Tok->getNextNonComment() == nullptr ||
Daniel Jasper56f8b432013-11-06 23:12:09 +0000762 Tok->getNextNonComment()->is(tok::semi))) {
763 // We merge empty blocks even if the line exceeds the column limit.
764 Tok->SpacesRequiredBefore = 0;
765 Tok->CanBreakBefore = true;
766 return 1;
767 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Daniel Jasper79dffb42014-05-07 09:48:30 +0000768 // We don't merge short records.
769 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
770 return 0;
771
Daniel Jasper56f8b432013-11-06 23:12:09 +0000772 // Check that we still have three lines and they fit into the limit.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000773 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000774 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000775 Limit = limitConsideringMacros(I + 2, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000776
777 if (!nextTwoLinesFitInto(I, Limit))
778 return 0;
779
780 // Second, check that the next line does not contain any braces - if it
781 // does, readability declines when putting it into a single line.
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000782 if (I[1]->Last->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000783 return 0;
784 do {
Daniel Jasperbd630732014-05-22 13:25:26 +0000785 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000786 return 0;
787 Tok = Tok->Next;
Craig Topper2145bc02014-05-09 08:15:10 +0000788 } while (Tok);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000789
Daniel Jasper79dffb42014-05-07 09:48:30 +0000790 // Last, check that the third line starts with a closing brace.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000791 Tok = I[2]->First;
Daniel Jasper79dffb42014-05-07 09:48:30 +0000792 if (Tok->isNot(tok::r_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000793 return 0;
794
795 return 2;
796 }
797 return 0;
798 }
799
Daniel Jasper64989962014-02-07 13:45:27 +0000800 /// Returns the modified column limit for \p I if it is inside a macro and
801 /// needs a trailing '\'.
802 unsigned
Daniel Jaspera0407742014-02-11 10:08:11 +0000803 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper64989962014-02-07 13:45:27 +0000804 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
805 unsigned Limit) {
806 if (I[0]->InPPDirective && I + 1 != E &&
807 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
808 return Limit < 2 ? 0 : Limit - 2;
809 }
810 return Limit;
811 }
812
Daniel Jasper56f8b432013-11-06 23:12:09 +0000813 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
814 unsigned Limit) {
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000815 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
816 return false;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000817 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000818 }
819
Daniel Jasper234379f2013-12-24 13:31:25 +0000820 bool containsMustBreak(const AnnotatedLine *Line) {
821 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
822 if (Tok->MustBreakBefore)
823 return true;
824 }
825 return false;
826 }
827
Daniel Jasper56f8b432013-11-06 23:12:09 +0000828 const FormatStyle &Style;
829};
830
Daniel Jasperf7935112012-12-03 18:12:45 +0000831class UnwrappedLineFormatter {
832public:
Daniel Jasper5500f612013-11-25 11:08:59 +0000833 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000834 WhitespaceManager *Whitespaces,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000835 const FormatStyle &Style)
Daniel Jasper5500f612013-11-25 11:08:59 +0000836 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
837 Joiner(Style) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000838
Daniel Jasper56f8b432013-11-06 23:12:09 +0000839 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper9c199562013-11-28 15:58:55 +0000840 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Daniel Jasperc359ad02014-04-15 08:13:47 +0000841 // Try to look up already computed penalty in DryRun-mode.
NAKAMURA Takumi22059522014-04-15 23:29:04 +0000842 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
843 &Lines, AdditionalIndent);
Daniel Jasperc359ad02014-04-15 08:13:47 +0000844 auto CacheIt = PenaltyCache.find(CacheKey);
845 if (DryRun && CacheIt != PenaltyCache.end())
846 return CacheIt->second;
847
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000848 assert(!Lines.empty());
849 unsigned Penalty = 0;
850 std::vector<int> IndentForLevel;
851 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
852 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Craig Topper2145bc02014-05-09 08:15:10 +0000853 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000854 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
855 E = Lines.end();
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000856 I != E; ++I) {
857 const AnnotatedLine &TheLine = **I;
858 const FormatToken *FirstTok = TheLine.First;
859 int Offset = getIndentOffset(*FirstTok);
860
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000861 // Determine indent and try to merge multiple unwrapped lines.
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000862 unsigned Indent;
863 if (TheLine.InPPDirective) {
864 Indent = TheLine.Level * Style.IndentWidth;
865 } else {
866 while (IndentForLevel.size() <= TheLine.Level)
867 IndentForLevel.push_back(-1);
868 IndentForLevel.resize(TheLine.Level + 1);
869 Indent = getIndent(IndentForLevel, TheLine.Level);
870 }
871 unsigned LevelIndent = Indent;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000872 if (static_cast<int>(Indent) + Offset >= 0)
873 Indent += Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000874
875 // Merge multiple lines if possible.
Daniel Jasper56f8b432013-11-06 23:12:09 +0000876 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
Alexander Kornienko31e95542013-12-04 12:21:08 +0000877 if (MergedLines > 0 && Style.ColumnLimit == 0) {
878 // Disallow line merging if there is a break at the start of one of the
879 // input lines.
880 for (unsigned i = 0; i < MergedLines; ++i) {
881 if (I[i + 1]->First->NewlinesBefore > 0)
882 MergedLines = 0;
883 }
884 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000885 if (!DryRun) {
886 for (unsigned i = 0; i < MergedLines; ++i) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000887 join(*I[i], *I[i + 1]);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000888 }
889 }
890 I += MergedLines;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000891
Daniel Jasper9c199562013-11-28 15:58:55 +0000892 bool FixIndentation =
893 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000894 if (TheLine.First->is(tok::eof)) {
Daniel Jasper5500f612013-11-25 11:08:59 +0000895 if (PreviousLine && PreviousLine->Affected && !DryRun) {
896 // Remove the file's trailing whitespace.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000897 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
898 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
899 /*IndentLevel=*/0, /*Spaces=*/0,
900 /*TargetColumn=*/0);
901 }
Daniel Jasper9c199562013-11-28 15:58:55 +0000902 } else if (TheLine.Type != LT_Invalid &&
903 (TheLine.Affected || FixIndentation)) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000904 if (FirstTok->WhitespaceRange.isValid()) {
905 if (!DryRun)
906 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
907 Indent, TheLine.InPPDirective);
908 } else {
909 Indent = LevelIndent = FirstTok->OriginalColumn;
910 }
911
912 // If everything fits on a single line, just put it there.
913 unsigned ColumnLimit = Style.ColumnLimit;
914 if (I + 1 != E) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000915 AnnotatedLine *NextLine = I[1];
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000916 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
917 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
918 }
919
920 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
921 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000922 while (State.NextToken) {
923 formatChildren(State, /*Newline=*/false, /*DryRun=*/false, Penalty);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000924 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000925 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000926 } else if (Style.ColumnLimit == 0) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000927 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000928 NoColumnLimitFormatter Formatter(Indenter);
929 if (!DryRun)
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000930 Formatter.format(Indent, &TheLine);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000931 } else {
932 Penalty += format(TheLine, Indent, DryRun);
933 }
934
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000935 if (!TheLine.InPPDirective)
936 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper9c199562013-11-28 15:58:55 +0000937 } else if (TheLine.ChildrenAffected) {
938 format(TheLine.Children, DryRun);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000939 } else {
940 // Format the first token if necessary, and notify the WhitespaceManager
941 // about the unchanged whitespace.
Craig Topper2145bc02014-05-09 08:15:10 +0000942 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000943 if (Tok == TheLine.First &&
944 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
945 unsigned LevelIndent = Tok->OriginalColumn;
946 if (!DryRun) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000947 // Remove trailing whitespace of the previous line.
Daniel Jasper5500f612013-11-25 11:08:59 +0000948 if ((PreviousLine && PreviousLine->Affected) ||
949 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000950 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
951 TheLine.InPPDirective);
952 } else {
953 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
954 }
955 }
956
957 if (static_cast<int>(LevelIndent) - Offset >= 0)
958 LevelIndent -= Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000959 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000960 IndentForLevel[TheLine.Level] = LevelIndent;
961 } else if (!DryRun) {
962 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
963 }
964 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000965 }
966 if (!DryRun) {
Craig Topper2145bc02014-05-09 08:15:10 +0000967 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000968 Tok->Finalized = true;
969 }
970 }
971 PreviousLine = *I;
972 }
Daniel Jasperc359ad02014-04-15 08:13:47 +0000973 PenaltyCache[CacheKey] = Penalty;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000974 return Penalty;
975 }
976
977private:
978 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000979 ///
980 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000981 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
982 bool DryRun) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000983 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +0000984
Daniel Jasperacc33662013-02-08 08:22:00 +0000985 // If the ObjC method declaration does not fit on a line, we should format
986 // it with one arg per line.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000987 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperacc33662013-02-08 08:22:00 +0000988 State.Stack.back().BreakBeforeParameter = true;
989
Daniel Jasper4b866272013-02-01 11:00:45 +0000990 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000991 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +0000992 }
993
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000994 /// \brief An edge in the solution space from \c Previous->State to \c State,
995 /// inserting a newline dependent on the \c NewLine.
996 struct StateNode {
997 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000998 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000999 LineState State;
1000 bool NewLine;
1001 StateNode *Previous;
1002 };
Daniel Jasper4b866272013-02-01 11:00:45 +00001003
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001004 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
1005 ///
1006 /// In case of equal penalties, we want to prefer states that were inserted
1007 /// first. During state generation we make sure that we insert states first
1008 /// that break the line as late as possible.
1009 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1010
1011 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
1012 /// \c State has the given \c OrderedPenalty.
1013 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1014
1015 /// \brief The BFS queue type.
1016 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1017 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +00001018
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001019 /// \brief Get the offset of the line relatively to the level.
1020 ///
1021 /// For example, 'public:' labels in classes are offset by 1 or 2
1022 /// characters to the left from their level.
1023 int getIndentOffset(const FormatToken &RootToken) {
1024 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
1025 return Style.AccessModifierOffset;
1026 return 0;
1027 }
1028
1029 /// \brief Add a new line and the required indent before the first Token
1030 /// of the \c UnwrappedLine if there was no structural parsing error.
1031 void formatFirstToken(FormatToken &RootToken,
1032 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
1033 unsigned Indent, bool InPPDirective) {
1034 unsigned Newlines =
1035 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1036 // Remove empty lines before "}" where applicable.
1037 if (RootToken.is(tok::r_brace) &&
1038 (!RootToken.Next ||
1039 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1040 Newlines = std::min(Newlines, 1u);
1041 if (Newlines == 0 && !RootToken.IsFirst)
1042 Newlines = 1;
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001043 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1044 Newlines = 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001045
Daniel Jasper11164bd2014-03-21 12:58:53 +00001046 // Remove empty lines after "{".
Daniel Jaspera26fc5c2014-03-21 13:43:14 +00001047 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1048 PreviousLine->Last->is(tok::l_brace) &&
Daniel Jasper01b35482014-03-21 13:03:33 +00001049 PreviousLine->First->isNot(tok::kw_namespace))
Daniel Jasper11164bd2014-03-21 12:58:53 +00001050 Newlines = 1;
1051
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001052 // Insert extra new line before access specifiers.
1053 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1054 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1055 ++Newlines;
1056
1057 // Remove empty lines after access specifiers.
1058 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
1059 Newlines = std::min(1u, Newlines);
1060
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001061 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
1062 Indent, InPPDirective &&
1063 !RootToken.HasUnescapedNewline);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001064 }
1065
1066 /// \brief Get the indent of \p Level from \p IndentForLevel.
1067 ///
1068 /// \p IndentForLevel must contain the indent for the level \c l
1069 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1070 /// that level is unknown.
1071 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
1072 if (IndentForLevel[Level] != -1)
1073 return IndentForLevel[Level];
1074 if (Level == 0)
1075 return 0;
1076 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
1077 }
1078
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001079 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1080 assert(!A.Last->Next);
1081 assert(!B.First->Previous);
Daniel Jasper5500f612013-11-25 11:08:59 +00001082 if (B.Affected)
1083 A.Affected = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001084 A.Last->Next = B.First;
1085 B.First->Previous = A.Last;
Daniel Jasper98fb6e12013-11-08 17:33:27 +00001086 B.First->CanBreakBefore = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001087 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1088 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1089 Tok->TotalLength += LengthA;
1090 A.Last = Tok;
1091 }
1092 }
1093
1094 unsigned getColumnLimit(bool InPPDirective) const {
1095 // In preprocessor directives reserve two chars for trailing " \"
1096 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1097 }
1098
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001099 struct CompareLineStatePointers {
1100 bool operator()(LineState *obj1, LineState *obj2) const {
1101 return *obj1 < *obj2;
1102 }
1103 };
1104
Daniel Jasper4b866272013-02-01 11:00:45 +00001105 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +00001106 ///
Daniel Jasper4b866272013-02-01 11:00:45 +00001107 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1108 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1109 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001110 /// to a state where all tokens are placed. Returns the penalty.
1111 ///
1112 /// If \p DryRun is \c false, directly applies the changes.
1113 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001114 std::set<LineState *, CompareLineStatePointers> Seen;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001115
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001116 // Increasing count of \c StateNode items we have created. This is used to
1117 // create a deterministic order independent of the container.
1118 unsigned Count = 0;
1119 QueueType Queue;
1120
Daniel Jasper4b866272013-02-01 11:00:45 +00001121 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001122 StateNode *Node =
Craig Topper2145bc02014-05-09 08:15:10 +00001123 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001124 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1125 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001126
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001127 unsigned Penalty = 0;
1128
Daniel Jasper4b866272013-02-01 11:00:45 +00001129 // While not empty, take first element and follow edges.
1130 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001131 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001132 StateNode *Node = Queue.top().second;
Craig Topper2145bc02014-05-09 08:15:10 +00001133 if (!Node->State.NextToken) {
Alexander Kornienko49149672013-05-10 11:56:10 +00001134 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001135 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001136 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001137 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001138
Daniel Jasperf8114cf2013-05-22 05:27:42 +00001139 // Cut off the analysis of certain solutions if the analysis gets too
1140 // complex. See description of IgnoreStackForComparison.
1141 if (Count > 10000)
1142 Node->State.IgnoreStackForComparison = true;
1143
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001144 if (!Seen.insert(&Node->State).second)
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001145 // State already examined with lower penalty.
1146 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001147
Manuel Klimek71814b42013-10-11 21:25:45 +00001148 FormatDecision LastFormat = Node->State.NextToken->Decision;
1149 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001150 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimek71814b42013-10-11 21:25:45 +00001151 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001152 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper4b866272013-02-01 11:00:45 +00001153 }
1154
Manuel Klimek71814b42013-10-11 21:25:45 +00001155 if (Queue.empty()) {
Daniel Jasper4b866272013-02-01 11:00:45 +00001156 // We were unable to find a solution, do nothing.
1157 // FIXME: Add diagnostic?
Manuel Klimek71814b42013-10-11 21:25:45 +00001158 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001159 return 0;
Manuel Klimek71814b42013-10-11 21:25:45 +00001160 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001161
Daniel Jasper4b866272013-02-01 11:00:45 +00001162 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001163 if (!DryRun)
1164 reconstructPath(InitialState, Queue.top().second);
1165
Alexander Kornienko49149672013-05-10 11:56:10 +00001166 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1167 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001168
1169 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001170 }
1171
1172 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001173 std::deque<StateNode *> Path;
1174 // We do not need a break before the initial token.
1175 while (Current->Previous) {
1176 Path.push_front(Current);
1177 Current = Current->Previous;
1178 }
1179 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1180 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001181 unsigned Penalty = 0;
1182 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1183 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1184
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001185 DEBUG({
1186 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001187 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001188 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001189 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001190 }
1191 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001192 }
Daniel Jasper4b866272013-02-01 11:00:45 +00001193 }
1194
Manuel Klimekaf491072013-02-13 10:54:19 +00001195 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001196 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001197 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001198 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001199 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001200 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001201 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001202 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001203 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001204 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001205
1206 StateNode *Node = new (Allocator.Allocate())
1207 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001208 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1209 return;
1210
Daniel Jasperde0328a2013-08-16 11:20:30 +00001211 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001212
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001213 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1214 ++(*Count);
Daniel Jasper4b866272013-02-01 11:00:45 +00001215 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001216
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001217 /// \brief If the \p State's next token is an r_brace closing a nested block,
1218 /// format the nested block before it.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001219 ///
1220 /// Returns \c true if all children could be placed successfully and adapts
1221 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1222 /// creates changes using \c Whitespaces.
1223 ///
1224 /// The crucial idea here is that children always get formatted upon
1225 /// encountering the closing brace right after the nested block. Now, if we
1226 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1227 /// \c false), the entire block has to be kept on the same line (which is only
1228 /// possible if it fits on the line, only contains a single statement, etc.
1229 ///
1230 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1231 /// break after the "{", format all lines with correct indentation and the put
1232 /// the closing "}" on yet another new line.
1233 ///
1234 /// This enables us to keep the simple structure of the
1235 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1236 /// break or don't break.
1237 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1238 unsigned &Penalty) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001239 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001240 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1241 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1242 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001243 // The previous token does not open a block. Nothing to do. We don't
1244 // assert so that we can simply call this function for all tokens.
Daniel Jasper36c28ce2013-09-06 08:54:24 +00001245 return true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001246
1247 if (NewLine) {
Daniel Jasper58cb2ed2014-06-06 13:49:04 +00001248 int AdditionalIndent =
1249 State.FirstIndent - State.Line->Level * Style.IndentWidth;
Daniel Jasperb16b9692014-05-21 12:51:23 +00001250 if (State.Stack.size() < 2 ||
1251 !State.Stack[State.Stack.size() - 2].JSFunctionInlined) {
1252 AdditionalIndent = State.Stack.back().Indent -
1253 Previous.Children[0]->Level * Style.IndentWidth;
1254 }
1255
Daniel Jasper9c199562013-11-28 15:58:55 +00001256 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1257 /*FixBadIndentation=*/true);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001258 return true;
1259 }
1260
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001261 // Cannot merge multiple statements into a single line.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001262 if (Previous.Children.size() > 1)
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001263 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001264
Daniel Jasper21397a32014-04-09 12:21:48 +00001265 // Cannot merge into one line if this line ends on a comment.
1266 if (Previous.is(tok::comment))
1267 return false;
1268
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001269 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001270 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001271 return false;
1272
Daniel Jasper98583d52014-04-15 08:28:06 +00001273 // If the child line exceeds the column limit, we wouldn't want to merge it.
1274 // We add +2 for the trailing " }".
1275 if (Style.ColumnLimit > 0 &&
1276 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
1277 Style.ColumnLimit)
1278 return false;
1279
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001280 if (!DryRun) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001281 Whitespaces->replaceWhitespace(
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001282 *Previous.Children[0]->First,
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001283 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001284 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001285 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001286 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001287
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001288 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001289 return true;
1290 }
1291
Daniel Jasperde0328a2013-08-16 11:20:30 +00001292 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001293 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001294 FormatStyle Style;
Daniel Jasper56f8b432013-11-06 23:12:09 +00001295 LineJoiner Joiner;
Manuel Klimekaf491072013-02-13 10:54:19 +00001296
1297 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperc359ad02014-04-15 08:13:47 +00001298
1299 // Cache to store the penalty of formatting a vector of AnnotatedLines
1300 // starting from a specific additional offset. Improves performance if there
1301 // are many nested blocks.
1302 std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
1303 unsigned> PenaltyCache;
Daniel Jasperf7935112012-12-03 18:12:45 +00001304};
1305
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001306class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001307public:
Daniel Jasper23376252014-09-09 14:37:39 +00001308 FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001309 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +00001310 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
Daniel Jasper23376252014-09-09 14:37:39 +00001311 Column(0), TrailingWhitespace(0),
1312 SourceMgr(SourceMgr), ID(ID), Style(Style),
1313 IdentTable(getFormattingLangOpts(Style)), Encoding(Encoding),
1314 FirstInLineIndex(0), FormattingDisabled(false) {
1315 Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
1316 getFormattingLangOpts(Style)));
1317 Lex->SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +00001318
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001319 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +00001320 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1321 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001322 }
1323
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001324 ArrayRef<FormatToken *> lex() {
1325 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +00001326 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001327 do {
1328 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001329 tryMergePreviousTokens();
Manuel Klimek68b03042014-04-14 09:14:11 +00001330 if (Tokens.back()->NewlinesBefore > 0)
1331 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001332 } while (Tokens.back()->Tok.isNot(tok::eof));
1333 return Tokens;
1334 }
1335
1336 IdentifierTable &getIdentTable() { return IdentTable; }
1337
1338private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001339 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001340 if (tryMerge_TMacro())
1341 return;
Manuel Klimek68b03042014-04-14 09:14:11 +00001342 if (tryMergeConflictMarkers())
1343 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001344
1345 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001346 if (tryMergeJSRegexLiteral())
1347 return;
Daniel Jasper23376252014-09-09 14:37:39 +00001348 if (tryMergeEscapeSequence())
1349 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001350
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001351 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1352 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1353 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1354 tok::greaterequal };
Daniel Jasper78214392014-05-19 07:27:02 +00001355 static tok::TokenKind JSRightArrow[] = { tok::equal, tok::greater };
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001356 // FIXME: We probably need to change token type to mimic operator with the
1357 // correct priority.
1358 if (tryMergeTokens(JSIdentity))
1359 return;
1360 if (tryMergeTokens(JSNotIdentity))
1361 return;
1362 if (tryMergeTokens(JSShiftEqual))
1363 return;
Daniel Jasper78214392014-05-19 07:27:02 +00001364 if (tryMergeTokens(JSRightArrow))
1365 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001366 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001367 }
1368
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001369 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1370 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001371 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001372
1373 SmallVectorImpl<FormatToken *>::const_iterator First =
1374 Tokens.end() - Kinds.size();
1375 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001376 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001377 unsigned AddLength = 0;
1378 for (unsigned i = 1; i < Kinds.size(); ++i) {
1379 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1380 First[i]->WhitespaceRange.getEnd())
1381 return false;
1382 AddLength += First[i]->TokenText.size();
1383 }
1384 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1385 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1386 First[0]->TokenText.size() + AddLength);
1387 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001388 return true;
1389 }
1390
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001391 // Tries to merge an escape sequence, i.e. a "\\" and the following
Alp Tokerc3f36af2014-05-15 01:35:53 +00001392 // character. Use e.g. inside JavaScript regex literals.
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001393 bool tryMergeEscapeSequence() {
1394 if (Tokens.size() < 2)
1395 return false;
1396 FormatToken *Previous = Tokens[Tokens.size() - 2];
1397 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\" ||
1398 Tokens.back()->NewlinesBefore != 0)
1399 return false;
1400 Previous->ColumnWidth += Tokens.back()->ColumnWidth;
1401 StringRef Text = Previous->TokenText;
1402 Previous->TokenText =
1403 StringRef(Text.data(), Text.size() + Tokens.back()->TokenText.size());
1404 Tokens.resize(Tokens.size() - 1);
1405 return true;
1406 }
1407
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001408 // Try to determine whether the current token ends a JavaScript regex literal.
1409 // We heuristically assume that this is a regex literal if we find two
1410 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +00001411 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
1412 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001413 bool tryMergeJSRegexLiteral() {
Daniel Jasper23376252014-09-09 14:37:39 +00001414 if (Tokens.size() < 2)
1415 return false;
1416 // If a regex literal ends in "\//", this gets represented by an unknown
1417 // token "\" and a comment.
1418 bool MightEndWithEscapedSlash =
1419 Tokens.back()->is(tok::comment) &&
1420 Tokens.back()->TokenText.startswith("//") &&
1421 Tokens[Tokens.size() - 2]->TokenText == "\\";
1422 if (!MightEndWithEscapedSlash &&
1423 (Tokens.back()->isNot(tok::slash) ||
1424 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
1425 Tokens[Tokens.size() - 2]->TokenText == "\\")))
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001426 return false;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001427 unsigned TokenCount = 0;
1428 unsigned LastColumn = Tokens.back()->OriginalColumn;
1429 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
1430 ++TokenCount;
1431 if (I[0]->is(tok::slash) && I + 1 != E &&
1432 (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
1433 tok::exclaim, tok::l_square, tok::colon, tok::comma,
1434 tok::question, tok::kw_return) ||
1435 I[1]->isBinaryOperator())) {
Daniel Jasper23376252014-09-09 14:37:39 +00001436 if (MightEndWithEscapedSlash) {
1437 StringRef Buffer = SourceMgr.getBufferData(ID);
1438 // This regex literal ends in '\//'. Skip past the '//' of the last
1439 // token and re-start lexing from there.
1440 int offset =
1441 SourceMgr.getFileOffset(Tokens.back()->Tok.getLocation()) + 2;
1442 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1443 getFormattingLangOpts(Style), Buffer.begin(),
1444 Buffer.begin() + offset, Buffer.end()));
1445 Lex->SetKeepWhitespaceMode(true);
1446 }
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001447 Tokens.resize(Tokens.size() - TokenCount);
1448 Tokens.back()->Tok.setKind(tok::unknown);
1449 Tokens.back()->Type = TT_RegexLiteral;
1450 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
1451 return true;
1452 }
1453
1454 // There can't be a newline inside a regex literal.
1455 if (I[0]->NewlinesBefore > 0)
1456 return false;
1457 }
1458 return false;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001459 }
1460
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001461 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001462 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001463 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001464 FormatToken *Last = Tokens.back();
1465 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001466 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001467
1468 FormatToken *String = Tokens[Tokens.size() - 2];
1469 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001470 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001471
1472 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001473 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001474
1475 FormatToken *Macro = Tokens[Tokens.size() - 4];
1476 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001477 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001478
1479 const char *Start = Macro->TokenText.data();
1480 const char *End = Last->TokenText.data() + Last->TokenText.size();
1481 String->TokenText = StringRef(Start, End - Start);
1482 String->IsFirst = Macro->IsFirst;
1483 String->LastNewlineOffset = Macro->LastNewlineOffset;
1484 String->WhitespaceRange = Macro->WhitespaceRange;
1485 String->OriginalColumn = Macro->OriginalColumn;
1486 String->ColumnWidth = encoding::columnWidthWithTabs(
1487 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1488
1489 Tokens.pop_back();
1490 Tokens.pop_back();
1491 Tokens.pop_back();
1492 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001493 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001494 }
1495
Manuel Klimek68b03042014-04-14 09:14:11 +00001496 bool tryMergeConflictMarkers() {
1497 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1498 return false;
1499
1500 // Conflict lines look like:
1501 // <marker> <text from the vcs>
1502 // For example:
1503 // >>>>>>> /file/in/file/system at revision 1234
1504 //
1505 // We merge all tokens in a line that starts with a conflict marker
1506 // into a single token with a special token type that the unwrapped line
1507 // parser will use to correctly rebuild the underlying code.
1508
1509 FileID ID;
1510 // Get the position of the first token in the line.
1511 unsigned FirstInLineOffset;
1512 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1513 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1514 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1515 // Calculate the offset of the start of the current line.
1516 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1517 if (LineOffset == StringRef::npos) {
1518 LineOffset = 0;
1519 } else {
1520 ++LineOffset;
1521 }
1522
1523 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1524 StringRef LineStart;
1525 if (FirstSpace == StringRef::npos) {
1526 LineStart = Buffer.substr(LineOffset);
1527 } else {
1528 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1529 }
1530
1531 TokenType Type = TT_Unknown;
1532 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1533 Type = TT_ConflictStart;
1534 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1535 LineStart == "====") {
1536 Type = TT_ConflictAlternative;
1537 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1538 Type = TT_ConflictEnd;
1539 }
1540
1541 if (Type != TT_Unknown) {
1542 FormatToken *Next = Tokens.back();
1543
1544 Tokens.resize(FirstInLineIndex + 1);
1545 // We do not need to build a complete token here, as we will skip it
1546 // during parsing anyway (as we must not touch whitespace around conflict
1547 // markers).
1548 Tokens.back()->Type = Type;
1549 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1550
1551 Tokens.push_back(Next);
1552 return true;
1553 }
1554
1555 return false;
1556 }
1557
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001558 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001559 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001560 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +00001561 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001562 Token Greater = FormatTok->Tok;
1563 FormatTok = new (Allocator.Allocate()) FormatToken;
1564 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001565 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001566 FormatTok->Tok.getLocation().getLocWithOffset(1);
1567 FormatTok->WhitespaceRange =
1568 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001569 FormatTok->TokenText = ">";
Alexander Kornienko39856b72013-09-10 09:38:25 +00001570 FormatTok->ColumnWidth = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001571 GreaterStashed = false;
1572 return FormatTok;
1573 }
1574
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001575 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001576 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001577 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001578 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001579 FormatTok->IsFirst = IsFirstToken;
1580 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001581
1582 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001583 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001584 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001585 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1586 switch (FormatTok->TokenText[i]) {
1587 case '\n':
1588 ++FormatTok->NewlinesBefore;
1589 // FIXME: This is technically incorrect, as it could also
1590 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001591 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1592 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1593 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +00001594 FormatTok->HasUnescapedNewline = true;
1595 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1596 Column = 0;
1597 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001598 case '\r':
1599 case '\f':
1600 case '\v':
1601 Column = 0;
1602 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001603 case ' ':
1604 ++Column;
1605 break;
1606 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001607 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001608 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001609 case '\\':
1610 ++Column;
1611 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1612 FormatTok->TokenText[i + 1] != '\n'))
1613 FormatTok->Type = TT_ImplicitStringLiteral;
1614 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001615 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001616 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001617 ++Column;
1618 break;
1619 }
1620 }
1621
Daniel Jasper877615c2013-10-11 19:45:02 +00001622 if (FormatTok->Type == TT_ImplicitStringLiteral)
1623 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001624 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001625
Daniel Jasper8369aa52013-07-16 20:28:33 +00001626 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001627 }
Manuel Klimekef920692013-01-07 07:56:50 +00001628
Manuel Klimek1abf7892013-01-04 23:34:14 +00001629 // In case the token starts with escaped newlines, we want to
1630 // take them into account as whitespace - this pattern is quite frequent
1631 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001632 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001633 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1634 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001635 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001636 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001637 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001638 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001639 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001640
1641 FormatTok->WhitespaceRange = SourceRange(
1642 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1643
Manuel Klimek31c85922013-08-29 15:21:40 +00001644 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001645
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001646 TrailingWhitespace = 0;
1647 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001648 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001649 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001650 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001651 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001652 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001653 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001654 FormatTok->Tok.setIdentifierInfo(&Info);
1655 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001656 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001657 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001658 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001659 GreaterStashed = true;
1660 }
1661
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001662 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001663
Alexander Kornienko39856b72013-09-10 09:38:25 +00001664 StringRef Text = FormatTok->TokenText;
1665 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001666 if (FirstNewlinePos == StringRef::npos) {
1667 // FIXME: ColumnWidth actually depends on the start column, we need to
1668 // take this into account when the token is moved.
1669 FormatTok->ColumnWidth =
1670 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1671 Column += FormatTok->ColumnWidth;
1672 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001673 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001674 // FIXME: ColumnWidth actually depends on the start column, we need to
1675 // take this into account when the token is moved.
1676 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1677 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1678
Alexander Kornienko39856b72013-09-10 09:38:25 +00001679 // The last line of the token always starts in column 0.
1680 // Thus, the length can be precomputed even in the presence of tabs.
1681 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1682 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1683 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001684 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001685 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001686
Daniel Jaspere1e43192014-04-01 12:55:11 +00001687 FormatTok->IsForEachMacro =
1688 std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1689 FormatTok->Tok.getIdentifierInfo());
1690
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001691 return FormatTok;
1692 }
1693
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001694 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001695 bool IsFirstToken;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001696 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001697 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001698 unsigned TrailingWhitespace;
Daniel Jasper23376252014-09-09 14:37:39 +00001699 std::unique_ptr<Lexer> Lex;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001700 SourceManager &SourceMgr;
Daniel Jasper23376252014-09-09 14:37:39 +00001701 FileID ID;
Manuel Klimek31c85922013-08-29 15:21:40 +00001702 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001703 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001704 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001705 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001706 // Index (in 'Tokens') of the last token that starts a new line.
1707 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001708 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001709 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001710
NAKAMURA Takumi7160c4d2014-08-06 16:53:13 +00001711 bool FormattingDisabled;
Daniel Jasper471894432014-08-06 13:40:26 +00001712
Daniel Jasper8369aa52013-07-16 20:28:33 +00001713 void readRawToken(FormatToken &Tok) {
Daniel Jasper23376252014-09-09 14:37:39 +00001714 Lex->LexFromRawLexer(Tok.Tok);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001715 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1716 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001717 // For formatting, treat unterminated string literals like normal string
1718 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001719 if (Tok.is(tok::unknown)) {
1720 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1721 Tok.Tok.setKind(tok::string_literal);
1722 Tok.IsUnterminatedLiteral = true;
1723 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1724 Tok.TokenText == "''") {
1725 Tok.Tok.setKind(tok::char_constant);
1726 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001727 }
Daniel Jasper471894432014-08-06 13:40:26 +00001728 if (Tok.is(tok::comment) && Tok.TokenText == "// clang-format on")
1729 FormattingDisabled = false;
1730 Tok.Finalized = FormattingDisabled;
1731 if (Tok.is(tok::comment) && Tok.TokenText == "// clang-format off")
1732 FormattingDisabled = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001733 }
1734};
1735
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001736static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1737 switch (Language) {
1738 case FormatStyle::LK_Cpp:
1739 return "C++";
1740 case FormatStyle::LK_JavaScript:
1741 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001742 case FormatStyle::LK_Proto:
1743 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001744 default:
1745 return "Unknown";
1746 }
1747}
1748
Daniel Jasperf7935112012-12-03 18:12:45 +00001749class Formatter : public UnwrappedLineConsumer {
1750public:
Daniel Jasper23376252014-09-09 14:37:39 +00001751 Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
Daniel Jasperf7935112012-12-03 18:12:45 +00001752 const std::vector<CharSourceRange> &Ranges)
Daniel Jasper23376252014-09-09 14:37:39 +00001753 : Style(Style), ID(ID), SourceMgr(SourceMgr),
1754 Whitespaces(SourceMgr, Style,
1755 inputUsesCRLF(SourceMgr.getBufferData(ID))),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001756 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Daniel Jasper23376252014-09-09 14:37:39 +00001757 Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001758 DEBUG(llvm::dbgs() << "File encoding: "
1759 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1760 : "unknown")
1761 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001762 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1763 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001764 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001765
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001766 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001767 tooling::Replacements Result;
Daniel Jasper23376252014-09-09 14:37:39 +00001768 FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001769
1770 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001771 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001772 assert(UnwrappedLines.rbegin()->empty());
1773 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1774 ++Run) {
1775 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1776 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1777 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1778 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1779 }
1780 tooling::Replacements RunResult =
1781 format(AnnotatedLines, StructuralError, Tokens);
1782 DEBUG({
1783 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1784 for (tooling::Replacements::iterator I = RunResult.begin(),
1785 E = RunResult.end();
1786 I != E; ++I) {
1787 llvm::dbgs() << I->toString() << "\n";
1788 }
1789 });
1790 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1791 delete AnnotatedLines[i];
1792 }
1793 Result.insert(RunResult.begin(), RunResult.end());
1794 Whitespaces.reset();
1795 }
1796 return Result;
1797 }
1798
1799 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1800 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001801 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001802 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001803 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001804 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001805 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001806 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001807 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001808 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001809 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001810
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001811 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001812 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1813 BinPackInconclusiveFunctions);
Daniel Jasper5500f612013-11-25 11:08:59 +00001814 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001815 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001816 return Whitespaces.generateReplacements();
1817 }
1818
1819private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001820 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001821 // Returns \c true if at least one line between I and E or one of their
1822 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001823 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1824 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1825 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001826 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001827 while (I != E) {
1828 AnnotatedLine *Line = *I;
1829 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1830
1831 // If a line is part of a preprocessor directive, it needs to be formatted
1832 // if any token within the directive is affected.
1833 if (Line->InPPDirective) {
1834 FormatToken *Last = Line->Last;
1835 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1836 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1837 Last = (*PPEnd)->Last;
1838 ++PPEnd;
1839 }
1840
1841 if (affectsTokenRange(*Line->First, *Last,
1842 /*IncludeLeadingNewlines=*/false)) {
1843 SomeLineAffected = true;
1844 markAllAsAffected(I, PPEnd);
1845 }
1846 I = PPEnd;
1847 continue;
1848 }
1849
Daniel Jasper38c82402013-11-29 09:27:43 +00001850 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001851 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001852
Daniel Jasper38c82402013-11-29 09:27:43 +00001853 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001854 ++I;
1855 }
1856 return SomeLineAffected;
1857 }
1858
Daniel Jasper9c199562013-11-28 15:58:55 +00001859 // Determines whether 'Line' is affected by the SourceRanges given as input.
1860 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001861 bool nonPPLineAffected(AnnotatedLine *Line,
1862 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001863 bool SomeLineAffected = false;
1864 Line->ChildrenAffected =
1865 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1866 if (Line->ChildrenAffected)
1867 SomeLineAffected = true;
1868
1869 // Stores whether one of the line's tokens is directly affected.
1870 bool SomeTokenAffected = false;
1871 // Stores whether we need to look at the leading newlines of the next token
1872 // in order to determine whether it was affected.
1873 bool IncludeLeadingNewlines = false;
1874
1875 // Stores whether the first child line of any of this line's tokens is
1876 // affected.
1877 bool SomeFirstChildAffected = false;
1878
1879 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1880 // Determine whether 'Tok' was affected.
1881 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1882 SomeTokenAffected = true;
1883
1884 // Determine whether the first child of 'Tok' was affected.
1885 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1886 SomeFirstChildAffected = true;
1887
1888 IncludeLeadingNewlines = Tok->Children.empty();
1889 }
1890
1891 // Was this line moved, i.e. has it previously been on the same line as an
1892 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001893 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1894 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001895
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001896 bool IsContinuedComment =
1897 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1898 Line->First->NewlinesBefore < 2 && PreviousLine &&
1899 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001900
1901 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1902 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001903 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001904 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001905 }
1906 return SomeLineAffected;
1907 }
1908
Daniel Jasper5500f612013-11-25 11:08:59 +00001909 // Marks all lines between I and E as well as all their children as affected.
1910 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1911 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1912 while (I != E) {
1913 (*I)->Affected = true;
1914 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1915 ++I;
1916 }
1917 }
1918
1919 // Returns true if the range from 'First' to 'Last' intersects with one of the
1920 // input ranges.
1921 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1922 bool IncludeLeadingNewlines) {
1923 SourceLocation Start = First.WhitespaceRange.getBegin();
1924 if (!IncludeLeadingNewlines)
1925 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001926 SourceLocation End = Last.getStartOfNonWhitespace();
1927 if (Last.TokenText.size() > 0)
1928 End = End.getLocWithOffset(Last.TokenText.size() - 1);
Daniel Jasper5500f612013-11-25 11:08:59 +00001929 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1930 return affectsCharSourceRange(Range);
1931 }
1932
1933 // Returns true if one of the input ranges intersect the leading empty lines
1934 // before 'Tok'.
1935 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1936 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1937 Tok.WhitespaceRange.getBegin(),
1938 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1939 return affectsCharSourceRange(EmptyLineRange);
1940 }
1941
1942 // Returns true if 'Range' intersects with one of the input ranges.
1943 bool affectsCharSourceRange(const CharSourceRange &Range) {
1944 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1945 E = Ranges.end();
1946 I != E; ++I) {
1947 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1948 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1949 return true;
1950 }
1951 return false;
1952 }
1953
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001954 static bool inputUsesCRLF(StringRef Text) {
1955 return Text.count('\r') * 2 > Text.count('\n');
1956 }
1957
Manuel Klimek71814b42013-10-11 21:25:45 +00001958 void
1959 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001960 unsigned CountBoundToVariable = 0;
1961 unsigned CountBoundToType = 0;
1962 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001963 bool HasBinPackedFunction = false;
1964 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001965 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001966 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001967 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001968 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001969 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001970 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001971 bool SpacesBefore =
1972 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1973 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1974 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001975 if (SpacesBefore && !SpacesAfter)
1976 ++CountBoundToVariable;
1977 else if (!SpacesBefore && SpacesAfter)
1978 ++CountBoundToType;
1979 }
1980
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001981 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1982 if (Tok->is(tok::coloncolon) &&
1983 Tok->Previous->Type == TT_TemplateOpener)
1984 HasCpp03IncompatibleFormat = true;
1985 if (Tok->Type == TT_TemplateCloser &&
1986 Tok->Previous->Type == TT_TemplateCloser)
1987 HasCpp03IncompatibleFormat = true;
1988 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001989
1990 if (Tok->PackingKind == PPK_BinPacked)
1991 HasBinPackedFunction = true;
1992 if (Tok->PackingKind == PPK_OnePerLine)
1993 HasOnePerLineFunction = true;
1994
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001995 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001996 }
1997 }
Daniel Jasper553d4872014-06-17 12:40:34 +00001998 if (Style.DerivePointerAlignment) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001999 if (CountBoundToType > CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00002000 Style.PointerAlignment = FormatStyle::PAS_Left;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002001 else if (CountBoundToType < CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00002002 Style.PointerAlignment = FormatStyle::PAS_Right;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002003 }
2004 if (Style.Standard == FormatStyle::LS_Auto) {
2005 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
2006 : FormatStyle::LS_Cpp03;
2007 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002008 BinPackInconclusiveFunctions =
2009 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002010 }
2011
Craig Topperfb6b25b2014-03-15 04:29:04 +00002012 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00002013 assert(!UnwrappedLines.empty());
2014 UnwrappedLines.back().push_back(TheLine);
2015 }
2016
Craig Topperfb6b25b2014-03-15 04:29:04 +00002017 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00002018 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00002019 }
2020
2021 FormatStyle Style;
Daniel Jasper23376252014-09-09 14:37:39 +00002022 FileID ID;
Daniel Jasperf7935112012-12-03 18:12:45 +00002023 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00002024 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00002025 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00002026 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00002027
2028 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002029 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00002030};
2031
Craig Topperaf35e852013-06-30 22:29:28 +00002032} // end anonymous namespace
2033
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00002034tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
2035 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00002036 std::vector<CharSourceRange> Ranges) {
Daniel Jasper23376252014-09-09 14:37:39 +00002037 if (Style.DisableFormat)
2038 return tooling::Replacements();
2039 return reformat(Style, SourceMgr,
2040 SourceMgr.getFileID(Lex.getSourceLocation()), Ranges);
2041}
Daniel Jasperc64b09a2014-05-22 15:12:22 +00002042
Daniel Jasper23376252014-09-09 14:37:39 +00002043tooling::Replacements reformat(const FormatStyle &Style,
2044 SourceManager &SourceMgr, FileID ID,
2045 std::vector<CharSourceRange> Ranges) {
2046 if (Style.DisableFormat)
2047 return tooling::Replacements();
2048 Formatter formatter(Style, SourceMgr, ID, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00002049 return formatter.format();
2050}
2051
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002052tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
2053 std::vector<tooling::Range> Ranges,
2054 StringRef FileName) {
Daniel Jasper23376252014-09-09 14:37:39 +00002055 if (Style.DisableFormat)
2056 return tooling::Replacements();
2057
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002058 FileManager Files((FileSystemOptions()));
2059 DiagnosticsEngine Diagnostics(
2060 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2061 new DiagnosticOptions);
2062 SourceManager SourceMgr(Diagnostics, Files);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00002063 std::unique_ptr<llvm::MemoryBuffer> Buf =
2064 llvm::MemoryBuffer::getMemBuffer(Code, FileName);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002065 const clang::FileEntry *Entry =
2066 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
David Blaikie49cc3182014-08-27 20:54:45 +00002067 SourceMgr.overrideFileContents(Entry, std::move(Buf));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002068 FileID ID =
2069 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002070 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
2071 std::vector<CharSourceRange> CharRanges;
2072 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
2073 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
2074 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
2075 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
2076 }
Daniel Jasper23376252014-09-09 14:37:39 +00002077 return reformat(Style, SourceMgr, ID, CharRanges);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002078}
2079
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002080LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002081 LangOptions LangOpts;
2082 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002083 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2084 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00002085 LangOpts.LineComment = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002086 LangOpts.CXXOperatorNames =
2087 Style.Language != FormatStyle::LK_JavaScript ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002088 LangOpts.Bool = 1;
2089 LangOpts.ObjC1 = 1;
2090 LangOpts.ObjC2 = 1;
2091 return LangOpts;
2092}
2093
Edwin Vaned544aa72013-09-30 13:31:48 +00002094const char *StyleOptionHelpDescription =
2095 "Coding style, currently supports:\n"
2096 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
2097 "Use -style=file to load style configuration from\n"
2098 ".clang-format file located in one of the parent\n"
2099 "directories of the source file (or current\n"
2100 "directory for stdin).\n"
2101 "Use -style=\"{key: value, ...}\" to set specific\n"
2102 "parameters, e.g.:\n"
2103 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
2104
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002105static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002106 if (FileName.endswith_lower(".js")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002107 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00002108 } else if (FileName.endswith_lower(".proto") ||
2109 FileName.endswith_lower(".protodevel")) {
2110 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002111 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002112 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002113}
2114
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002115FormatStyle getStyle(StringRef StyleName, StringRef FileName,
2116 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002117 FormatStyle Style = getLLVMStyle();
2118 Style.Language = getLanguageByFileName(FileName);
2119 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002120 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
2121 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002122 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002123 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002124
2125 if (StyleName.startswith("{")) {
2126 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00002127 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002128 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
2129 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00002130 }
2131 return Style;
2132 }
2133
2134 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002135 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00002136 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
2137 << " style\n";
2138 return Style;
2139 }
2140
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002141 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002142 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00002143 SmallString<128> Path(FileName);
2144 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002145 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00002146 Directory = llvm::sys::path::parent_path(Directory)) {
2147 if (!llvm::sys::fs::is_directory(Directory))
2148 continue;
2149 SmallString<128> ConfigFile(Directory);
2150
2151 llvm::sys::path::append(ConfigFile, ".clang-format");
2152 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2153 bool IsFile = false;
2154 // Ignore errors from is_regular_file: we only need to know if we can read
2155 // the file or not.
2156 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2157
2158 if (!IsFile) {
2159 // Try _clang-format too, since dotfiles are not commonly used on Windows.
2160 ConfigFile = Directory;
2161 llvm::sys::path::append(ConfigFile, "_clang-format");
2162 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2163 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2164 }
2165
2166 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002167 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
2168 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
2169 if (std::error_code EC = Text.getError()) {
2170 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002171 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002172 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002173 if (std::error_code ec =
2174 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00002175 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002176 if (!UnsuitableConfigFiles.empty())
2177 UnsuitableConfigFiles.append(", ");
2178 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002179 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002180 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002181 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2182 << "\n";
2183 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002184 }
2185 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2186 return Style;
2187 }
2188 }
2189 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
2190 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002191 if (!UnsuitableConfigFiles.empty()) {
2192 llvm::errs() << "Configuration file(s) do(es) not support "
2193 << getLanguageName(Style.Language) << ": "
2194 << UnsuitableConfigFiles << "\n";
2195 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002196 return Style;
2197}
2198
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002199} // namespace format
2200} // namespace clang