blob: c7bcc670ac7b1d83045d35a8f170e65c38b2a2e3 [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);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000170 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
171 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000172 IO.mapOptional("AllowShortLoopsOnASingleLine",
173 Style.AllowShortLoopsOnASingleLine);
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000174 IO.mapOptional("AllowShortFunctionsOnASingleLine",
175 Style.AllowShortFunctionsOnASingleLine);
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000176 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
177 Style.AlwaysBreakAfterDefinitionReturnType);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000178 IO.mapOptional("AlwaysBreakTemplateDeclarations",
179 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko58611712013-07-04 12:02:44 +0000180 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
181 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000182 IO.mapOptional("BreakBeforeBinaryOperators",
183 Style.BreakBeforeBinaryOperators);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000184 IO.mapOptional("BreakBeforeTernaryOperators",
185 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000186 IO.mapOptional("BreakConstructorInitializersBeforeComma",
187 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000188 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
189 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
190 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
191 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000192 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000193 IO.mapOptional("ExperimentalAutoDetectBinPacking",
194 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000195 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000196 IO.mapOptional("IndentWrappedFunctionNames",
197 Style.IndentWrappedFunctionNames);
198 IO.mapOptional("IndentFunctionDeclarationAfterType",
199 Style.IndentWrappedFunctionNames);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000200 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000201 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
202 Style.KeepEmptyLinesAtTheStartOfBlocks);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000203 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000204 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000205 IO.mapOptional("ObjCSpaceBeforeProtocolList",
206 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000207 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
208 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000209 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
210 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000211 IO.mapOptional("PenaltyBreakFirstLessLess",
212 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000213 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
214 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
215 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000216 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000217 IO.mapOptional("SpacesBeforeTrailingComments",
218 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000219 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000220 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000221 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000222 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000223 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000224 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000225 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperad981f82014-08-26 11:41:14 +0000226 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000227 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasperf110e202013-08-21 08:39:01 +0000228 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000229 IO.mapOptional("SpacesInCStyleCastParentheses",
230 Style.SpacesInCStyleCastParentheses);
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000231 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000232 IO.mapOptional("SpacesInContainerLiterals",
233 Style.SpacesInContainerLiterals);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000234 IO.mapOptional("SpaceBeforeAssignmentOperators",
235 Style.SpaceBeforeAssignmentOperators);
Daniel Jasper6633ab82013-10-18 10:38:14 +0000236 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000237 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000238 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000239
240 // For backward compatibility.
241 if (!IO.outputting()) {
242 IO.mapOptional("SpaceAfterControlStatementKeyword",
243 Style.SpaceBeforeParens);
Daniel Jasper553d4872014-06-17 12:40:34 +0000244 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
245 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000246 }
247 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000248 IO.mapOptional("DisableFormat", Style.DisableFormat);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000249 }
250};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000251
252// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000253// IO.getContext() should contain a pointer to the FormatStyle structure, that
254// will be used to get default values for missing keys.
255// If the first element has no Language specified, it will be treated as the
256// default one for the following elements.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000257template <> struct DocumentListTraits<std::vector<FormatStyle> > {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000258 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
259 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000260 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000261 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000262 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000263 if (Index >= Seq.size()) {
264 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000265 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000266 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000267 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000268 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000269 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000270 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000271 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000272 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000273 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000274 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000275 }
276};
Alexander Kornienkod6538332013-05-07 15:32:14 +0000277}
278}
279
Daniel Jasperf7935112012-12-03 18:12:45 +0000280namespace clang {
281namespace format {
282
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000283const std::error_category &getParseCategory() {
Rafael Espindolad0136702014-06-12 02:50:04 +0000284 static ParseErrorCategory C;
285 return C;
286}
287std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000288 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000289}
290
291const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
292 return "clang-format.parse_error";
293}
294
295std::string ParseErrorCategory::message(int EV) const {
296 switch (static_cast<ParseError>(EV)) {
297 case ParseError::Success:
298 return "Success";
299 case ParseError::Error:
300 return "Invalid argument";
301 case ParseError::Unsuitable:
302 return "Unsuitable";
303 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000304 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000305}
306
Daniel Jasperf7935112012-12-03 18:12:45 +0000307FormatStyle getLLVMStyle() {
308 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000309 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000310 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000311 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000312 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000313 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000314 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000315 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000316 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000317 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000318 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000319 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000320 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000321 LLVMStyle.BinPackParameters = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000322 LLVMStyle.BreakBeforeBinaryOperators = false;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000323 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000324 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
325 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000326 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000327 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000328 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000329 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000330 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000331 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000332 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000333 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000334 LLVMStyle.ForEachMacros.push_back("foreach");
335 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
336 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000337 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000338 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000339 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000340 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000341 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000342 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000343 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000344 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000345 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000346 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000347 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000348 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000349 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000350 LLVMStyle.SpacesInParentheses = false;
Daniel Jasperad981f82014-08-26 11:41:14 +0000351 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000352 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000353 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000354 LLVMStyle.SpacesInCStyleCastParentheses = false;
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000355 LLVMStyle.SpaceAfterCStyleCast = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000356 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000357 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000358 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000359
Daniel Jasper19a541e2013-12-19 16:45:34 +0000360 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000361 LLVMStyle.PenaltyBreakFirstLessLess = 120;
362 LLVMStyle.PenaltyBreakString = 1000;
363 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000364 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000365 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000366
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000367 LLVMStyle.DisableFormat = false;
368
Daniel Jasperf7935112012-12-03 18:12:45 +0000369 return LLVMStyle;
370}
371
Nico Weber514ecc82014-02-02 20:50:45 +0000372FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000373 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000374 GoogleStyle.Language = Language;
375
Daniel Jasperf7935112012-12-03 18:12:45 +0000376 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000377 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000378 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000379 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000380 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000381 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000382 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000383 GoogleStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000384 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000385 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000386 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000387 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000388 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000389 GoogleStyle.SpacesBeforeTrailingComments = 2;
390 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000391
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000392 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000393 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000394
Nico Weber514ecc82014-02-02 20:50:45 +0000395 if (Language == FormatStyle::LK_JavaScript) {
396 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000397 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000398 GoogleStyle.SpacesInContainerLiterals = false;
399 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000400 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000401 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000402 }
403
Daniel Jasperf7935112012-12-03 18:12:45 +0000404 return GoogleStyle;
405}
406
Nico Weber514ecc82014-02-02 20:50:45 +0000407FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
408 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Daniel Jasperf7db4332013-01-29 16:03:49 +0000409 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000410 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000411 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000412 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000413 ChromiumStyle.BinPackParameters = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000414 ChromiumStyle.DerivePointerAlignment = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000415 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000416 return ChromiumStyle;
417}
418
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000419FormatStyle getMozillaStyle() {
420 FormatStyle MozillaStyle = getLLVMStyle();
421 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000422 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000423 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000424 MozillaStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000425 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000426 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000427 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
428 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000429 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000430 MozillaStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000431 return MozillaStyle;
432}
433
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000434FormatStyle getWebKitStyle() {
435 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000436 Style.AccessModifierOffset = -4;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000437 Style.AlignTrailingComments = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000438 Style.BreakBeforeBinaryOperators = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000439 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000440 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000441 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000442 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000443 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000444 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000445 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000446 Style.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000447 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000448 return Style;
449}
450
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000451FormatStyle getGNUStyle() {
452 FormatStyle Style = getLLVMStyle();
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000453 Style.AlwaysBreakAfterDefinitionReturnType = true;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000454 Style.BreakBeforeBinaryOperators = true;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000455 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000456 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000457 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000458 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000459 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000460 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000461 return Style;
462}
463
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000464FormatStyle getNoStyle() {
465 FormatStyle NoStyle = getLLVMStyle();
466 NoStyle.DisableFormat = true;
467 return NoStyle;
468}
469
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000470bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
471 FormatStyle *Style) {
472 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000473 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000474 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000475 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000476 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000477 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000478 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000479 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000480 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000481 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000482 } else if (Name.equals_lower("gnu")) {
483 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000484 } else if (Name.equals_lower("none")) {
485 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000486 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000487 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000488 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000489
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000490 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000491 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000492}
493
Rafael Espindolac0809172014-06-12 14:02:15 +0000494std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000495 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000496 FormatStyle::LanguageKind Language = Style->Language;
497 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000498 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000499 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000500
501 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000502 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000503 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
504 // values for the fields, keys for which are missing from the configuration.
505 // Mapping also uses the context to get the language to find the correct
506 // base style.
507 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000508 Input >> Styles;
509 if (Input.error())
510 return Input.error();
511
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000512 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000513 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000514 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000515 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000516 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000517 for (unsigned j = 0; j < i; ++j) {
518 if (Styles[i].Language == Styles[j].Language) {
519 DEBUG(llvm::dbgs()
520 << "Duplicate languages in the config file on positions " << j
521 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000522 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000523 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000524 }
525 }
526 // Look for a suitable configuration starting from the end, so we can
527 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000528 // configuration (which can only be at slot 0) after it.
529 for (int i = Styles.size() - 1; i >= 0; --i) {
530 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000531 Styles[i].Language == FormatStyle::LK_None) {
532 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000533 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000534 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000535 }
536 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000537 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000538}
539
540std::string configurationAsText(const FormatStyle &Style) {
541 std::string Text;
542 llvm::raw_string_ostream Stream(Text);
543 llvm::yaml::Output Output(Stream);
544 // We use the same mapping method for input and output, so we need a non-const
545 // reference here.
546 FormatStyle NonConstStyle = Style;
547 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000548 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000549}
550
Craig Topperaf35e852013-06-30 22:29:28 +0000551namespace {
552
Daniel Jasperde0328a2013-08-16 11:20:30 +0000553class NoColumnLimitFormatter {
554public:
Daniel Jasperf110e202013-08-21 08:39:01 +0000555 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000556
557 /// \brief Formats the line starting at \p State, simply keeping all of the
558 /// input's line breaking decisions.
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000559 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000560 LineState State =
561 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Craig Topper2145bc02014-05-09 08:15:10 +0000562 while (State.NextToken) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000563 bool Newline =
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000564 Indenter->mustBreak(State) ||
Daniel Jasperde0328a2013-08-16 11:20:30 +0000565 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
566 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
567 }
568 }
Daniel Jasperf110e202013-08-21 08:39:01 +0000569
Daniel Jasperde0328a2013-08-16 11:20:30 +0000570private:
571 ContinuationIndenter *Indenter;
572};
573
Daniel Jasper56f8b432013-11-06 23:12:09 +0000574class LineJoiner {
575public:
576 LineJoiner(const FormatStyle &Style) : Style(Style) {}
577
578 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
579 unsigned
580 tryFitMultipleLinesInOne(unsigned Indent,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000581 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000582 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
583 // We can never merge stuff if there are trailing line comments.
Daniel Jasper234379f2013-12-24 13:31:25 +0000584 const AnnotatedLine *TheLine = *I;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000585 if (TheLine->Last->Type == TT_LineComment)
586 return 0;
587
Alexander Kornienkoecc232d2013-12-04 13:25:26 +0000588 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
589 return 0;
590
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000591 unsigned Limit =
592 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000593 // If we already exceed the column limit, we set 'Limit' to 0. The different
594 // tryMerge..() functions can then decide whether to still do merging.
595 Limit = TheLine->Last->TotalLength > Limit
596 ? 0
597 : Limit - TheLine->Last->TotalLength;
598
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000599 if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000600 return 0;
601
Daniel Jasperd74cf402014-04-08 12:46:38 +0000602 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
603 // If necessary, change to something smarter.
604 bool MergeShortFunctions =
605 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
606 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
607 TheLine->Level != 0);
608
Daniel Jasper234379f2013-12-24 13:31:25 +0000609 if (TheLine->Last->Type == TT_FunctionLBrace &&
610 TheLine->First != TheLine->Last) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000611 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000612 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000613 if (TheLine->Last->is(tok::l_brace)) {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000614 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000615 ? tryMergeSimpleBlock(I, E, Limit)
616 : 0;
617 }
618 if (I[1]->First->Type == TT_FunctionLBrace &&
619 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
Alp Tokerba5b4dc2013-12-30 02:06:29 +0000620 // Check for Limit <= 2 to account for the " {".
Daniel Jasper234379f2013-12-24 13:31:25 +0000621 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
622 return 0;
623 Limit -= 2;
624
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000625 unsigned MergedLines = 0;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000626 if (MergeShortFunctions) {
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000627 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
628 // If we managed to merge the block, count the function header, which is
629 // on a separate line.
630 if (MergedLines > 0)
631 ++MergedLines;
632 }
633 return MergedLines;
634 }
635 if (TheLine->First->is(tok::kw_if)) {
636 return Style.AllowShortIfStatementsOnASingleLine
637 ? tryMergeSimpleControlStatement(I, E, Limit)
638 : 0;
639 }
640 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
641 return Style.AllowShortLoopsOnASingleLine
642 ? tryMergeSimpleControlStatement(I, E, Limit)
643 : 0;
644 }
645 if (TheLine->InPPDirective &&
646 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000647 return tryMergeSimplePPDirective(I, E, Limit);
648 }
649 return 0;
650 }
651
652private:
653 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000654 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000655 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
656 unsigned Limit) {
657 if (Limit == 0)
658 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000659 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000660 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000661 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000662 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000663 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000664 return 0;
665 return 1;
666 }
667
668 unsigned tryMergeSimpleControlStatement(
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000669 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000670 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
671 if (Limit == 0)
672 return 0;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000673 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
674 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
Daniel Jasper17605d32014-05-14 09:33:35 +0000675 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000676 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000677 if (I[1]->InPPDirective != (*I)->InPPDirective ||
678 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000679 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000680 Limit = limitConsideringMacros(I + 1, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000681 AnnotatedLine &Line = **I;
682 if (Line.Last->isNot(tok::r_paren))
683 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000684 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000685 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000686 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000687 tok::kw_while) ||
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000688 I[1]->First->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000689 return 0;
690 // Only inline simple if's (no nested if or else).
691 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000692 I[2]->First->is(tok::kw_else))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000693 return 0;
694 return 1;
695 }
696
697 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000698 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000699 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
700 unsigned Limit) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000701 AnnotatedLine &Line = **I;
Daniel Jasper17605d32014-05-14 09:33:35 +0000702
703 // Don't merge ObjC @ keywords and methods.
704 if (Line.First->isOneOf(tok::at, tok::minus, tok::plus))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000705 return 0;
706
Daniel Jasper17605d32014-05-14 09:33:35 +0000707 // Check that the current line allows merging. This depends on whether we
708 // are in a control flow statements as well as several style flags.
709 if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
710 return 0;
711 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
712 tok::kw_catch, tok::kw_for, tok::r_brace)) {
713 if (!Style.AllowShortBlocksOnASingleLine)
714 return 0;
715 if (!Style.AllowShortIfStatementsOnASingleLine &&
716 Line.First->is(tok::kw_if))
717 return 0;
718 if (!Style.AllowShortLoopsOnASingleLine &&
719 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
720 return 0;
721 // FIXME: Consider an option to allow short exception handling clauses on
722 // a single line.
723 if (Line.First->isOneOf(tok::kw_try, tok::kw_catch))
724 return 0;
725 }
726
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000727 FormatToken *Tok = I[1]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000728 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Craig Topper2145bc02014-05-09 08:15:10 +0000729 (Tok->getNextNonComment() == nullptr ||
Daniel Jasper56f8b432013-11-06 23:12:09 +0000730 Tok->getNextNonComment()->is(tok::semi))) {
731 // We merge empty blocks even if the line exceeds the column limit.
732 Tok->SpacesRequiredBefore = 0;
733 Tok->CanBreakBefore = true;
734 return 1;
735 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Daniel Jasper79dffb42014-05-07 09:48:30 +0000736 // We don't merge short records.
737 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
738 return 0;
739
Daniel Jasper56f8b432013-11-06 23:12:09 +0000740 // Check that we still have three lines and they fit into the limit.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000741 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000742 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000743 Limit = limitConsideringMacros(I + 2, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000744
745 if (!nextTwoLinesFitInto(I, Limit))
746 return 0;
747
748 // Second, check that the next line does not contain any braces - if it
749 // does, readability declines when putting it into a single line.
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000750 if (I[1]->Last->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000751 return 0;
752 do {
Daniel Jasperbd630732014-05-22 13:25:26 +0000753 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000754 return 0;
755 Tok = Tok->Next;
Craig Topper2145bc02014-05-09 08:15:10 +0000756 } while (Tok);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000757
Daniel Jasper79dffb42014-05-07 09:48:30 +0000758 // Last, check that the third line starts with a closing brace.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000759 Tok = I[2]->First;
Daniel Jasper79dffb42014-05-07 09:48:30 +0000760 if (Tok->isNot(tok::r_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000761 return 0;
762
763 return 2;
764 }
765 return 0;
766 }
767
Daniel Jasper64989962014-02-07 13:45:27 +0000768 /// Returns the modified column limit for \p I if it is inside a macro and
769 /// needs a trailing '\'.
770 unsigned
Daniel Jaspera0407742014-02-11 10:08:11 +0000771 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper64989962014-02-07 13:45:27 +0000772 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
773 unsigned Limit) {
774 if (I[0]->InPPDirective && I + 1 != E &&
775 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
776 return Limit < 2 ? 0 : Limit - 2;
777 }
778 return Limit;
779 }
780
Daniel Jasper56f8b432013-11-06 23:12:09 +0000781 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
782 unsigned Limit) {
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000783 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
784 return false;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000785 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000786 }
787
Daniel Jasper234379f2013-12-24 13:31:25 +0000788 bool containsMustBreak(const AnnotatedLine *Line) {
789 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
790 if (Tok->MustBreakBefore)
791 return true;
792 }
793 return false;
794 }
795
Daniel Jasper56f8b432013-11-06 23:12:09 +0000796 const FormatStyle &Style;
797};
798
Daniel Jasperf7935112012-12-03 18:12:45 +0000799class UnwrappedLineFormatter {
800public:
Daniel Jasper5500f612013-11-25 11:08:59 +0000801 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000802 WhitespaceManager *Whitespaces,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000803 const FormatStyle &Style)
Daniel Jasper5500f612013-11-25 11:08:59 +0000804 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
805 Joiner(Style) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000806
Daniel Jasper56f8b432013-11-06 23:12:09 +0000807 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper9c199562013-11-28 15:58:55 +0000808 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Daniel Jasperc359ad02014-04-15 08:13:47 +0000809 // Try to look up already computed penalty in DryRun-mode.
NAKAMURA Takumi22059522014-04-15 23:29:04 +0000810 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
811 &Lines, AdditionalIndent);
Daniel Jasperc359ad02014-04-15 08:13:47 +0000812 auto CacheIt = PenaltyCache.find(CacheKey);
813 if (DryRun && CacheIt != PenaltyCache.end())
814 return CacheIt->second;
815
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000816 assert(!Lines.empty());
817 unsigned Penalty = 0;
818 std::vector<int> IndentForLevel;
819 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
820 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Craig Topper2145bc02014-05-09 08:15:10 +0000821 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000822 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
823 E = Lines.end();
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000824 I != E; ++I) {
825 const AnnotatedLine &TheLine = **I;
826 const FormatToken *FirstTok = TheLine.First;
827 int Offset = getIndentOffset(*FirstTok);
828
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000829 // Determine indent and try to merge multiple unwrapped lines.
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000830 unsigned Indent;
831 if (TheLine.InPPDirective) {
832 Indent = TheLine.Level * Style.IndentWidth;
833 } else {
834 while (IndentForLevel.size() <= TheLine.Level)
835 IndentForLevel.push_back(-1);
836 IndentForLevel.resize(TheLine.Level + 1);
837 Indent = getIndent(IndentForLevel, TheLine.Level);
838 }
839 unsigned LevelIndent = Indent;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000840 if (static_cast<int>(Indent) + Offset >= 0)
841 Indent += Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000842
843 // Merge multiple lines if possible.
Daniel Jasper56f8b432013-11-06 23:12:09 +0000844 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
Alexander Kornienko31e95542013-12-04 12:21:08 +0000845 if (MergedLines > 0 && Style.ColumnLimit == 0) {
846 // Disallow line merging if there is a break at the start of one of the
847 // input lines.
848 for (unsigned i = 0; i < MergedLines; ++i) {
849 if (I[i + 1]->First->NewlinesBefore > 0)
850 MergedLines = 0;
851 }
852 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000853 if (!DryRun) {
854 for (unsigned i = 0; i < MergedLines; ++i) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000855 join(*I[i], *I[i + 1]);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000856 }
857 }
858 I += MergedLines;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000859
Daniel Jasper9c199562013-11-28 15:58:55 +0000860 bool FixIndentation =
861 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000862 if (TheLine.First->is(tok::eof)) {
Daniel Jasper5500f612013-11-25 11:08:59 +0000863 if (PreviousLine && PreviousLine->Affected && !DryRun) {
864 // Remove the file's trailing whitespace.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000865 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
866 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
867 /*IndentLevel=*/0, /*Spaces=*/0,
868 /*TargetColumn=*/0);
869 }
Daniel Jasper9c199562013-11-28 15:58:55 +0000870 } else if (TheLine.Type != LT_Invalid &&
871 (TheLine.Affected || FixIndentation)) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000872 if (FirstTok->WhitespaceRange.isValid()) {
873 if (!DryRun)
874 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
875 Indent, TheLine.InPPDirective);
876 } else {
877 Indent = LevelIndent = FirstTok->OriginalColumn;
878 }
879
880 // If everything fits on a single line, just put it there.
881 unsigned ColumnLimit = Style.ColumnLimit;
882 if (I + 1 != E) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000883 AnnotatedLine *NextLine = I[1];
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000884 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
885 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
886 }
887
888 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
889 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000890 while (State.NextToken) {
891 formatChildren(State, /*Newline=*/false, /*DryRun=*/false, Penalty);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000892 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000893 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000894 } else if (Style.ColumnLimit == 0) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000895 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000896 NoColumnLimitFormatter Formatter(Indenter);
897 if (!DryRun)
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000898 Formatter.format(Indent, &TheLine);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000899 } else {
900 Penalty += format(TheLine, Indent, DryRun);
901 }
902
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000903 if (!TheLine.InPPDirective)
904 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper9c199562013-11-28 15:58:55 +0000905 } else if (TheLine.ChildrenAffected) {
906 format(TheLine.Children, DryRun);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000907 } else {
908 // Format the first token if necessary, and notify the WhitespaceManager
909 // about the unchanged whitespace.
Craig Topper2145bc02014-05-09 08:15:10 +0000910 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000911 if (Tok == TheLine.First &&
912 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
913 unsigned LevelIndent = Tok->OriginalColumn;
914 if (!DryRun) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000915 // Remove trailing whitespace of the previous line.
Daniel Jasper5500f612013-11-25 11:08:59 +0000916 if ((PreviousLine && PreviousLine->Affected) ||
917 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000918 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
919 TheLine.InPPDirective);
920 } else {
921 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
922 }
923 }
924
925 if (static_cast<int>(LevelIndent) - Offset >= 0)
926 LevelIndent -= Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000927 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000928 IndentForLevel[TheLine.Level] = LevelIndent;
929 } else if (!DryRun) {
930 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
931 }
932 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000933 }
934 if (!DryRun) {
Craig Topper2145bc02014-05-09 08:15:10 +0000935 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000936 Tok->Finalized = true;
937 }
938 }
939 PreviousLine = *I;
940 }
Daniel Jasperc359ad02014-04-15 08:13:47 +0000941 PenaltyCache[CacheKey] = Penalty;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000942 return Penalty;
943 }
944
945private:
946 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000947 ///
948 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000949 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
950 bool DryRun) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000951 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +0000952
Daniel Jasperacc33662013-02-08 08:22:00 +0000953 // If the ObjC method declaration does not fit on a line, we should format
954 // it with one arg per line.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000955 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperacc33662013-02-08 08:22:00 +0000956 State.Stack.back().BreakBeforeParameter = true;
957
Daniel Jasper4b866272013-02-01 11:00:45 +0000958 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000959 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +0000960 }
961
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000962 /// \brief An edge in the solution space from \c Previous->State to \c State,
963 /// inserting a newline dependent on the \c NewLine.
964 struct StateNode {
965 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000966 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000967 LineState State;
968 bool NewLine;
969 StateNode *Previous;
970 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000971
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000972 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
973 ///
974 /// In case of equal penalties, we want to prefer states that were inserted
975 /// first. During state generation we make sure that we insert states first
976 /// that break the line as late as possible.
977 typedef std::pair<unsigned, unsigned> OrderedPenalty;
978
979 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
980 /// \c State has the given \c OrderedPenalty.
981 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
982
983 /// \brief The BFS queue type.
984 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
985 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000986
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000987 /// \brief Get the offset of the line relatively to the level.
988 ///
989 /// For example, 'public:' labels in classes are offset by 1 or 2
990 /// characters to the left from their level.
991 int getIndentOffset(const FormatToken &RootToken) {
992 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
993 return Style.AccessModifierOffset;
994 return 0;
995 }
996
997 /// \brief Add a new line and the required indent before the first Token
998 /// of the \c UnwrappedLine if there was no structural parsing error.
999 void formatFirstToken(FormatToken &RootToken,
1000 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
1001 unsigned Indent, bool InPPDirective) {
1002 unsigned Newlines =
1003 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1004 // Remove empty lines before "}" where applicable.
1005 if (RootToken.is(tok::r_brace) &&
1006 (!RootToken.Next ||
1007 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1008 Newlines = std::min(Newlines, 1u);
1009 if (Newlines == 0 && !RootToken.IsFirst)
1010 Newlines = 1;
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001011 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1012 Newlines = 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001013
Daniel Jasper11164bd2014-03-21 12:58:53 +00001014 // Remove empty lines after "{".
Daniel Jaspera26fc5c2014-03-21 13:43:14 +00001015 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1016 PreviousLine->Last->is(tok::l_brace) &&
Daniel Jasper01b35482014-03-21 13:03:33 +00001017 PreviousLine->First->isNot(tok::kw_namespace))
Daniel Jasper11164bd2014-03-21 12:58:53 +00001018 Newlines = 1;
1019
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001020 // Insert extra new line before access specifiers.
1021 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1022 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1023 ++Newlines;
1024
1025 // Remove empty lines after access specifiers.
1026 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
1027 Newlines = std::min(1u, Newlines);
1028
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001029 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
1030 Indent, InPPDirective &&
1031 !RootToken.HasUnescapedNewline);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001032 }
1033
1034 /// \brief Get the indent of \p Level from \p IndentForLevel.
1035 ///
1036 /// \p IndentForLevel must contain the indent for the level \c l
1037 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1038 /// that level is unknown.
1039 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
1040 if (IndentForLevel[Level] != -1)
1041 return IndentForLevel[Level];
1042 if (Level == 0)
1043 return 0;
1044 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
1045 }
1046
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001047 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1048 assert(!A.Last->Next);
1049 assert(!B.First->Previous);
Daniel Jasper5500f612013-11-25 11:08:59 +00001050 if (B.Affected)
1051 A.Affected = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001052 A.Last->Next = B.First;
1053 B.First->Previous = A.Last;
Daniel Jasper98fb6e12013-11-08 17:33:27 +00001054 B.First->CanBreakBefore = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001055 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1056 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1057 Tok->TotalLength += LengthA;
1058 A.Last = Tok;
1059 }
1060 }
1061
1062 unsigned getColumnLimit(bool InPPDirective) const {
1063 // In preprocessor directives reserve two chars for trailing " \"
1064 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1065 }
1066
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001067 struct CompareLineStatePointers {
1068 bool operator()(LineState *obj1, LineState *obj2) const {
1069 return *obj1 < *obj2;
1070 }
1071 };
1072
Daniel Jasper4b866272013-02-01 11:00:45 +00001073 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +00001074 ///
Daniel Jasper4b866272013-02-01 11:00:45 +00001075 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1076 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1077 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001078 /// to a state where all tokens are placed. Returns the penalty.
1079 ///
1080 /// If \p DryRun is \c false, directly applies the changes.
1081 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001082 std::set<LineState *, CompareLineStatePointers> Seen;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001083
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001084 // Increasing count of \c StateNode items we have created. This is used to
1085 // create a deterministic order independent of the container.
1086 unsigned Count = 0;
1087 QueueType Queue;
1088
Daniel Jasper4b866272013-02-01 11:00:45 +00001089 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001090 StateNode *Node =
Craig Topper2145bc02014-05-09 08:15:10 +00001091 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001092 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1093 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001094
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001095 unsigned Penalty = 0;
1096
Daniel Jasper4b866272013-02-01 11:00:45 +00001097 // While not empty, take first element and follow edges.
1098 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001099 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001100 StateNode *Node = Queue.top().second;
Craig Topper2145bc02014-05-09 08:15:10 +00001101 if (!Node->State.NextToken) {
Alexander Kornienko49149672013-05-10 11:56:10 +00001102 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001103 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001104 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001105 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001106
Daniel Jasperf8114cf2013-05-22 05:27:42 +00001107 // Cut off the analysis of certain solutions if the analysis gets too
1108 // complex. See description of IgnoreStackForComparison.
1109 if (Count > 10000)
1110 Node->State.IgnoreStackForComparison = true;
1111
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001112 if (!Seen.insert(&Node->State).second)
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001113 // State already examined with lower penalty.
1114 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001115
Manuel Klimek71814b42013-10-11 21:25:45 +00001116 FormatDecision LastFormat = Node->State.NextToken->Decision;
1117 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001118 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimek71814b42013-10-11 21:25:45 +00001119 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001120 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper4b866272013-02-01 11:00:45 +00001121 }
1122
Manuel Klimek71814b42013-10-11 21:25:45 +00001123 if (Queue.empty()) {
Daniel Jasper4b866272013-02-01 11:00:45 +00001124 // We were unable to find a solution, do nothing.
1125 // FIXME: Add diagnostic?
Manuel Klimek71814b42013-10-11 21:25:45 +00001126 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001127 return 0;
Manuel Klimek71814b42013-10-11 21:25:45 +00001128 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001129
Daniel Jasper4b866272013-02-01 11:00:45 +00001130 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001131 if (!DryRun)
1132 reconstructPath(InitialState, Queue.top().second);
1133
Alexander Kornienko49149672013-05-10 11:56:10 +00001134 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1135 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001136
1137 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001138 }
1139
1140 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001141 std::deque<StateNode *> Path;
1142 // We do not need a break before the initial token.
1143 while (Current->Previous) {
1144 Path.push_front(Current);
1145 Current = Current->Previous;
1146 }
1147 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1148 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001149 unsigned Penalty = 0;
1150 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1151 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1152
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001153 DEBUG({
1154 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001155 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001156 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001157 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001158 }
1159 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001160 }
Daniel Jasper4b866272013-02-01 11:00:45 +00001161 }
1162
Manuel Klimekaf491072013-02-13 10:54:19 +00001163 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001164 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001165 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001166 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001167 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001168 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001169 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001170 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001171 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001172 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001173
1174 StateNode *Node = new (Allocator.Allocate())
1175 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001176 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1177 return;
1178
Daniel Jasperde0328a2013-08-16 11:20:30 +00001179 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001180
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001181 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1182 ++(*Count);
Daniel Jasper4b866272013-02-01 11:00:45 +00001183 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001184
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001185 /// \brief If the \p State's next token is an r_brace closing a nested block,
1186 /// format the nested block before it.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001187 ///
1188 /// Returns \c true if all children could be placed successfully and adapts
1189 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1190 /// creates changes using \c Whitespaces.
1191 ///
1192 /// The crucial idea here is that children always get formatted upon
1193 /// encountering the closing brace right after the nested block. Now, if we
1194 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1195 /// \c false), the entire block has to be kept on the same line (which is only
1196 /// possible if it fits on the line, only contains a single statement, etc.
1197 ///
1198 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1199 /// break after the "{", format all lines with correct indentation and the put
1200 /// the closing "}" on yet another new line.
1201 ///
1202 /// This enables us to keep the simple structure of the
1203 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1204 /// break or don't break.
1205 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1206 unsigned &Penalty) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001207 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001208 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1209 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1210 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001211 // The previous token does not open a block. Nothing to do. We don't
1212 // assert so that we can simply call this function for all tokens.
Daniel Jasper36c28ce2013-09-06 08:54:24 +00001213 return true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001214
1215 if (NewLine) {
Daniel Jasper58cb2ed2014-06-06 13:49:04 +00001216 int AdditionalIndent =
1217 State.FirstIndent - State.Line->Level * Style.IndentWidth;
Daniel Jasperb16b9692014-05-21 12:51:23 +00001218 if (State.Stack.size() < 2 ||
1219 !State.Stack[State.Stack.size() - 2].JSFunctionInlined) {
1220 AdditionalIndent = State.Stack.back().Indent -
1221 Previous.Children[0]->Level * Style.IndentWidth;
1222 }
1223
Daniel Jasper9c199562013-11-28 15:58:55 +00001224 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1225 /*FixBadIndentation=*/true);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001226 return true;
1227 }
1228
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001229 // Cannot merge multiple statements into a single line.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001230 if (Previous.Children.size() > 1)
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001231 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001232
Daniel Jasper21397a32014-04-09 12:21:48 +00001233 // Cannot merge into one line if this line ends on a comment.
1234 if (Previous.is(tok::comment))
1235 return false;
1236
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001237 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001238 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001239 return false;
1240
Daniel Jasper98583d52014-04-15 08:28:06 +00001241 // If the child line exceeds the column limit, we wouldn't want to merge it.
1242 // We add +2 for the trailing " }".
1243 if (Style.ColumnLimit > 0 &&
1244 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
1245 Style.ColumnLimit)
1246 return false;
1247
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001248 if (!DryRun) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001249 Whitespaces->replaceWhitespace(
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001250 *Previous.Children[0]->First,
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001251 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001252 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001253 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001254 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001255
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001256 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001257 return true;
1258 }
1259
Daniel Jasperde0328a2013-08-16 11:20:30 +00001260 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001261 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001262 FormatStyle Style;
Daniel Jasper56f8b432013-11-06 23:12:09 +00001263 LineJoiner Joiner;
Manuel Klimekaf491072013-02-13 10:54:19 +00001264
1265 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperc359ad02014-04-15 08:13:47 +00001266
1267 // Cache to store the penalty of formatting a vector of AnnotatedLines
1268 // starting from a specific additional offset. Improves performance if there
1269 // are many nested blocks.
1270 std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
1271 unsigned> PenaltyCache;
Daniel Jasperf7935112012-12-03 18:12:45 +00001272};
1273
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001274class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001275public:
Manuel Klimek31c85922013-08-29 15:21:40 +00001276 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001277 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +00001278 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
1279 Column(0), TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasper4db69bd2014-09-04 18:23:42 +00001280 Style(Style), IdentTable(getFormattingLangOpts(Style)),
1281 Encoding(Encoding), FirstInLineIndex(0), FormattingDisabled(false) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001282 Lex.SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +00001283
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001284 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +00001285 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1286 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001287 }
1288
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001289 ArrayRef<FormatToken *> lex() {
1290 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +00001291 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001292 do {
1293 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001294 tryMergePreviousTokens();
Manuel Klimek68b03042014-04-14 09:14:11 +00001295 if (Tokens.back()->NewlinesBefore > 0)
1296 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001297 } while (Tokens.back()->Tok.isNot(tok::eof));
1298 return Tokens;
1299 }
1300
1301 IdentifierTable &getIdentTable() { return IdentTable; }
1302
1303private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001304 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001305 if (tryMerge_TMacro())
1306 return;
Manuel Klimek68b03042014-04-14 09:14:11 +00001307 if (tryMergeConflictMarkers())
1308 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001309
1310 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001311 if (tryMergeEscapeSequence())
1312 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001313 if (tryMergeJSRegexLiteral())
1314 return;
1315
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001316 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1317 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1318 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1319 tok::greaterequal };
Daniel Jasper78214392014-05-19 07:27:02 +00001320 static tok::TokenKind JSRightArrow[] = { tok::equal, tok::greater };
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001321 // FIXME: We probably need to change token type to mimic operator with the
1322 // correct priority.
1323 if (tryMergeTokens(JSIdentity))
1324 return;
1325 if (tryMergeTokens(JSNotIdentity))
1326 return;
1327 if (tryMergeTokens(JSShiftEqual))
1328 return;
Daniel Jasper78214392014-05-19 07:27:02 +00001329 if (tryMergeTokens(JSRightArrow))
1330 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001331 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001332 }
1333
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001334 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1335 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001336 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001337
1338 SmallVectorImpl<FormatToken *>::const_iterator First =
1339 Tokens.end() - Kinds.size();
1340 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001341 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001342 unsigned AddLength = 0;
1343 for (unsigned i = 1; i < Kinds.size(); ++i) {
1344 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1345 First[i]->WhitespaceRange.getEnd())
1346 return false;
1347 AddLength += First[i]->TokenText.size();
1348 }
1349 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1350 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1351 First[0]->TokenText.size() + AddLength);
1352 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001353 return true;
1354 }
1355
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001356 // Tries to merge an escape sequence, i.e. a "\\" and the following
Alp Tokerc3f36af2014-05-15 01:35:53 +00001357 // character. Use e.g. inside JavaScript regex literals.
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001358 bool tryMergeEscapeSequence() {
1359 if (Tokens.size() < 2)
1360 return false;
1361 FormatToken *Previous = Tokens[Tokens.size() - 2];
1362 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\" ||
1363 Tokens.back()->NewlinesBefore != 0)
1364 return false;
1365 Previous->ColumnWidth += Tokens.back()->ColumnWidth;
1366 StringRef Text = Previous->TokenText;
1367 Previous->TokenText =
1368 StringRef(Text.data(), Text.size() + Tokens.back()->TokenText.size());
1369 Tokens.resize(Tokens.size() - 1);
1370 return true;
1371 }
1372
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001373 // Try to determine whether the current token ends a JavaScript regex literal.
1374 // We heuristically assume that this is a regex literal if we find two
1375 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +00001376 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
1377 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001378 bool tryMergeJSRegexLiteral() {
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001379 if (Tokens.size() < 2 || Tokens.back()->isNot(tok::slash) ||
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001380 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
1381 Tokens[Tokens.size() - 2]->TokenText == "\\"))
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001382 return false;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001383 unsigned TokenCount = 0;
1384 unsigned LastColumn = Tokens.back()->OriginalColumn;
1385 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
1386 ++TokenCount;
1387 if (I[0]->is(tok::slash) && I + 1 != E &&
1388 (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
1389 tok::exclaim, tok::l_square, tok::colon, tok::comma,
1390 tok::question, tok::kw_return) ||
1391 I[1]->isBinaryOperator())) {
1392 Tokens.resize(Tokens.size() - TokenCount);
1393 Tokens.back()->Tok.setKind(tok::unknown);
1394 Tokens.back()->Type = TT_RegexLiteral;
1395 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
1396 return true;
1397 }
1398
1399 // There can't be a newline inside a regex literal.
1400 if (I[0]->NewlinesBefore > 0)
1401 return false;
1402 }
1403 return false;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001404 }
1405
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001406 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001407 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001408 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001409 FormatToken *Last = Tokens.back();
1410 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001411 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001412
1413 FormatToken *String = Tokens[Tokens.size() - 2];
1414 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001415 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001416
1417 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001418 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001419
1420 FormatToken *Macro = Tokens[Tokens.size() - 4];
1421 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001422 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001423
1424 const char *Start = Macro->TokenText.data();
1425 const char *End = Last->TokenText.data() + Last->TokenText.size();
1426 String->TokenText = StringRef(Start, End - Start);
1427 String->IsFirst = Macro->IsFirst;
1428 String->LastNewlineOffset = Macro->LastNewlineOffset;
1429 String->WhitespaceRange = Macro->WhitespaceRange;
1430 String->OriginalColumn = Macro->OriginalColumn;
1431 String->ColumnWidth = encoding::columnWidthWithTabs(
1432 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1433
1434 Tokens.pop_back();
1435 Tokens.pop_back();
1436 Tokens.pop_back();
1437 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001438 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001439 }
1440
Manuel Klimek68b03042014-04-14 09:14:11 +00001441 bool tryMergeConflictMarkers() {
1442 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1443 return false;
1444
1445 // Conflict lines look like:
1446 // <marker> <text from the vcs>
1447 // For example:
1448 // >>>>>>> /file/in/file/system at revision 1234
1449 //
1450 // We merge all tokens in a line that starts with a conflict marker
1451 // into a single token with a special token type that the unwrapped line
1452 // parser will use to correctly rebuild the underlying code.
1453
1454 FileID ID;
1455 // Get the position of the first token in the line.
1456 unsigned FirstInLineOffset;
1457 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1458 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1459 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1460 // Calculate the offset of the start of the current line.
1461 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1462 if (LineOffset == StringRef::npos) {
1463 LineOffset = 0;
1464 } else {
1465 ++LineOffset;
1466 }
1467
1468 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1469 StringRef LineStart;
1470 if (FirstSpace == StringRef::npos) {
1471 LineStart = Buffer.substr(LineOffset);
1472 } else {
1473 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1474 }
1475
1476 TokenType Type = TT_Unknown;
1477 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1478 Type = TT_ConflictStart;
1479 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1480 LineStart == "====") {
1481 Type = TT_ConflictAlternative;
1482 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1483 Type = TT_ConflictEnd;
1484 }
1485
1486 if (Type != TT_Unknown) {
1487 FormatToken *Next = Tokens.back();
1488
1489 Tokens.resize(FirstInLineIndex + 1);
1490 // We do not need to build a complete token here, as we will skip it
1491 // during parsing anyway (as we must not touch whitespace around conflict
1492 // markers).
1493 Tokens.back()->Type = Type;
1494 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1495
1496 Tokens.push_back(Next);
1497 return true;
1498 }
1499
1500 return false;
1501 }
1502
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001503 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001504 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001505 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +00001506 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001507 Token Greater = FormatTok->Tok;
1508 FormatTok = new (Allocator.Allocate()) FormatToken;
1509 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001510 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001511 FormatTok->Tok.getLocation().getLocWithOffset(1);
1512 FormatTok->WhitespaceRange =
1513 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001514 FormatTok->TokenText = ">";
Alexander Kornienko39856b72013-09-10 09:38:25 +00001515 FormatTok->ColumnWidth = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001516 GreaterStashed = false;
1517 return FormatTok;
1518 }
1519
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001520 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001521 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001522 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001523 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001524 FormatTok->IsFirst = IsFirstToken;
1525 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001526
1527 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001528 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001529 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001530 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1531 switch (FormatTok->TokenText[i]) {
1532 case '\n':
1533 ++FormatTok->NewlinesBefore;
1534 // FIXME: This is technically incorrect, as it could also
1535 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001536 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1537 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1538 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +00001539 FormatTok->HasUnescapedNewline = true;
1540 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1541 Column = 0;
1542 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001543 case '\r':
1544 case '\f':
1545 case '\v':
1546 Column = 0;
1547 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001548 case ' ':
1549 ++Column;
1550 break;
1551 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001552 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001553 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001554 case '\\':
1555 ++Column;
1556 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1557 FormatTok->TokenText[i + 1] != '\n'))
1558 FormatTok->Type = TT_ImplicitStringLiteral;
1559 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001560 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001561 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001562 ++Column;
1563 break;
1564 }
1565 }
1566
Daniel Jasper877615c2013-10-11 19:45:02 +00001567 if (FormatTok->Type == TT_ImplicitStringLiteral)
1568 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001569 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001570
Daniel Jasper8369aa52013-07-16 20:28:33 +00001571 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001572 }
Manuel Klimekef920692013-01-07 07:56:50 +00001573
Manuel Klimek1abf7892013-01-04 23:34:14 +00001574 // In case the token starts with escaped newlines, we want to
1575 // take them into account as whitespace - this pattern is quite frequent
1576 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001577 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001578 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1579 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001580 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001581 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001582 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001583 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001584 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001585
1586 FormatTok->WhitespaceRange = SourceRange(
1587 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1588
Manuel Klimek31c85922013-08-29 15:21:40 +00001589 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001590
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001591 TrailingWhitespace = 0;
1592 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001593 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001594 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001595 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001596 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001597 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001598 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001599 FormatTok->Tok.setIdentifierInfo(&Info);
1600 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001601 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001602 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001603 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001604 GreaterStashed = true;
1605 }
1606
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001607 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001608
Alexander Kornienko39856b72013-09-10 09:38:25 +00001609 StringRef Text = FormatTok->TokenText;
1610 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001611 if (FirstNewlinePos == StringRef::npos) {
1612 // FIXME: ColumnWidth actually depends on the start column, we need to
1613 // take this into account when the token is moved.
1614 FormatTok->ColumnWidth =
1615 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1616 Column += FormatTok->ColumnWidth;
1617 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001618 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001619 // FIXME: ColumnWidth actually depends on the start column, we need to
1620 // take this into account when the token is moved.
1621 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1622 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1623
Alexander Kornienko39856b72013-09-10 09:38:25 +00001624 // The last line of the token always starts in column 0.
1625 // Thus, the length can be precomputed even in the presence of tabs.
1626 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1627 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1628 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001629 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001630 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001631
Daniel Jaspere1e43192014-04-01 12:55:11 +00001632 FormatTok->IsForEachMacro =
1633 std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1634 FormatTok->Tok.getIdentifierInfo());
1635
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001636 return FormatTok;
1637 }
1638
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001639 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001640 bool IsFirstToken;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001641 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001642 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001643 unsigned TrailingWhitespace;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001644 Lexer &Lex;
1645 SourceManager &SourceMgr;
Manuel Klimek31c85922013-08-29 15:21:40 +00001646 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001647 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001648 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001649 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001650 // Index (in 'Tokens') of the last token that starts a new line.
1651 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001652 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001653 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001654
NAKAMURA Takumi7160c4d2014-08-06 16:53:13 +00001655 bool FormattingDisabled;
Daniel Jasper471894432014-08-06 13:40:26 +00001656
Daniel Jasper8369aa52013-07-16 20:28:33 +00001657 void readRawToken(FormatToken &Tok) {
1658 Lex.LexFromRawLexer(Tok.Tok);
1659 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1660 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001661 // For formatting, treat unterminated string literals like normal string
1662 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001663 if (Tok.is(tok::unknown)) {
1664 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1665 Tok.Tok.setKind(tok::string_literal);
1666 Tok.IsUnterminatedLiteral = true;
1667 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1668 Tok.TokenText == "''") {
1669 Tok.Tok.setKind(tok::char_constant);
1670 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001671 }
Daniel Jasper471894432014-08-06 13:40:26 +00001672 if (Tok.is(tok::comment) && Tok.TokenText == "// clang-format on")
1673 FormattingDisabled = false;
1674 Tok.Finalized = FormattingDisabled;
1675 if (Tok.is(tok::comment) && Tok.TokenText == "// clang-format off")
1676 FormattingDisabled = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001677 }
1678};
1679
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001680static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1681 switch (Language) {
1682 case FormatStyle::LK_Cpp:
1683 return "C++";
1684 case FormatStyle::LK_JavaScript:
1685 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001686 case FormatStyle::LK_Proto:
1687 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001688 default:
1689 return "Unknown";
1690 }
1691}
1692
Daniel Jasperf7935112012-12-03 18:12:45 +00001693class Formatter : public UnwrappedLineConsumer {
1694public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001695 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001696 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001697 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001698 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001699 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Manuel Klimek71814b42013-10-11 21:25:45 +00001700 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001701 DEBUG(llvm::dbgs() << "File encoding: "
1702 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1703 : "unknown")
1704 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001705 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1706 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001707 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001708
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001709 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001710 tooling::Replacements Result;
Manuel Klimek31c85922013-08-29 15:21:40 +00001711 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001712
1713 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001714 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001715 assert(UnwrappedLines.rbegin()->empty());
1716 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1717 ++Run) {
1718 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1719 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1720 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1721 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1722 }
1723 tooling::Replacements RunResult =
1724 format(AnnotatedLines, StructuralError, Tokens);
1725 DEBUG({
1726 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1727 for (tooling::Replacements::iterator I = RunResult.begin(),
1728 E = RunResult.end();
1729 I != E; ++I) {
1730 llvm::dbgs() << I->toString() << "\n";
1731 }
1732 });
1733 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1734 delete AnnotatedLines[i];
1735 }
1736 Result.insert(RunResult.begin(), RunResult.end());
1737 Whitespaces.reset();
1738 }
1739 return Result;
1740 }
1741
1742 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1743 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001744 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001745 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001746 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001747 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001748 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001749 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001750 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001751 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001752 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001753
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001754 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001755 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1756 BinPackInconclusiveFunctions);
Daniel Jasper5500f612013-11-25 11:08:59 +00001757 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001758 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001759 return Whitespaces.generateReplacements();
1760 }
1761
1762private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001763 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001764 // Returns \c true if at least one line between I and E or one of their
1765 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001766 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1767 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1768 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001769 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001770 while (I != E) {
1771 AnnotatedLine *Line = *I;
1772 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1773
1774 // If a line is part of a preprocessor directive, it needs to be formatted
1775 // if any token within the directive is affected.
1776 if (Line->InPPDirective) {
1777 FormatToken *Last = Line->Last;
1778 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1779 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1780 Last = (*PPEnd)->Last;
1781 ++PPEnd;
1782 }
1783
1784 if (affectsTokenRange(*Line->First, *Last,
1785 /*IncludeLeadingNewlines=*/false)) {
1786 SomeLineAffected = true;
1787 markAllAsAffected(I, PPEnd);
1788 }
1789 I = PPEnd;
1790 continue;
1791 }
1792
Daniel Jasper38c82402013-11-29 09:27:43 +00001793 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001794 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001795
Daniel Jasper38c82402013-11-29 09:27:43 +00001796 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001797 ++I;
1798 }
1799 return SomeLineAffected;
1800 }
1801
Daniel Jasper9c199562013-11-28 15:58:55 +00001802 // Determines whether 'Line' is affected by the SourceRanges given as input.
1803 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001804 bool nonPPLineAffected(AnnotatedLine *Line,
1805 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001806 bool SomeLineAffected = false;
1807 Line->ChildrenAffected =
1808 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1809 if (Line->ChildrenAffected)
1810 SomeLineAffected = true;
1811
1812 // Stores whether one of the line's tokens is directly affected.
1813 bool SomeTokenAffected = false;
1814 // Stores whether we need to look at the leading newlines of the next token
1815 // in order to determine whether it was affected.
1816 bool IncludeLeadingNewlines = false;
1817
1818 // Stores whether the first child line of any of this line's tokens is
1819 // affected.
1820 bool SomeFirstChildAffected = false;
1821
1822 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1823 // Determine whether 'Tok' was affected.
1824 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1825 SomeTokenAffected = true;
1826
1827 // Determine whether the first child of 'Tok' was affected.
1828 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1829 SomeFirstChildAffected = true;
1830
1831 IncludeLeadingNewlines = Tok->Children.empty();
1832 }
1833
1834 // Was this line moved, i.e. has it previously been on the same line as an
1835 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001836 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1837 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001838
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001839 bool IsContinuedComment =
1840 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1841 Line->First->NewlinesBefore < 2 && PreviousLine &&
1842 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001843
1844 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1845 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001846 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001847 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001848 }
1849 return SomeLineAffected;
1850 }
1851
Daniel Jasper5500f612013-11-25 11:08:59 +00001852 // Marks all lines between I and E as well as all their children as affected.
1853 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1854 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1855 while (I != E) {
1856 (*I)->Affected = true;
1857 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1858 ++I;
1859 }
1860 }
1861
1862 // Returns true if the range from 'First' to 'Last' intersects with one of the
1863 // input ranges.
1864 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1865 bool IncludeLeadingNewlines) {
1866 SourceLocation Start = First.WhitespaceRange.getBegin();
1867 if (!IncludeLeadingNewlines)
1868 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001869 SourceLocation End = Last.getStartOfNonWhitespace();
1870 if (Last.TokenText.size() > 0)
1871 End = End.getLocWithOffset(Last.TokenText.size() - 1);
Daniel Jasper5500f612013-11-25 11:08:59 +00001872 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1873 return affectsCharSourceRange(Range);
1874 }
1875
1876 // Returns true if one of the input ranges intersect the leading empty lines
1877 // before 'Tok'.
1878 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1879 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1880 Tok.WhitespaceRange.getBegin(),
1881 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1882 return affectsCharSourceRange(EmptyLineRange);
1883 }
1884
1885 // Returns true if 'Range' intersects with one of the input ranges.
1886 bool affectsCharSourceRange(const CharSourceRange &Range) {
1887 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1888 E = Ranges.end();
1889 I != E; ++I) {
1890 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1891 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1892 return true;
1893 }
1894 return false;
1895 }
1896
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001897 static bool inputUsesCRLF(StringRef Text) {
1898 return Text.count('\r') * 2 > Text.count('\n');
1899 }
1900
Manuel Klimek71814b42013-10-11 21:25:45 +00001901 void
1902 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001903 unsigned CountBoundToVariable = 0;
1904 unsigned CountBoundToType = 0;
1905 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001906 bool HasBinPackedFunction = false;
1907 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001908 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001909 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001910 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001911 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001912 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001913 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001914 bool SpacesBefore =
1915 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1916 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1917 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001918 if (SpacesBefore && !SpacesAfter)
1919 ++CountBoundToVariable;
1920 else if (!SpacesBefore && SpacesAfter)
1921 ++CountBoundToType;
1922 }
1923
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001924 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1925 if (Tok->is(tok::coloncolon) &&
1926 Tok->Previous->Type == TT_TemplateOpener)
1927 HasCpp03IncompatibleFormat = true;
1928 if (Tok->Type == TT_TemplateCloser &&
1929 Tok->Previous->Type == TT_TemplateCloser)
1930 HasCpp03IncompatibleFormat = true;
1931 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001932
1933 if (Tok->PackingKind == PPK_BinPacked)
1934 HasBinPackedFunction = true;
1935 if (Tok->PackingKind == PPK_OnePerLine)
1936 HasOnePerLineFunction = true;
1937
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001938 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001939 }
1940 }
Daniel Jasper553d4872014-06-17 12:40:34 +00001941 if (Style.DerivePointerAlignment) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001942 if (CountBoundToType > CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00001943 Style.PointerAlignment = FormatStyle::PAS_Left;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001944 else if (CountBoundToType < CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00001945 Style.PointerAlignment = FormatStyle::PAS_Right;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001946 }
1947 if (Style.Standard == FormatStyle::LS_Auto) {
1948 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1949 : FormatStyle::LS_Cpp03;
1950 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001951 BinPackInconclusiveFunctions =
1952 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001953 }
1954
Craig Topperfb6b25b2014-03-15 04:29:04 +00001955 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001956 assert(!UnwrappedLines.empty());
1957 UnwrappedLines.back().push_back(TheLine);
1958 }
1959
Craig Topperfb6b25b2014-03-15 04:29:04 +00001960 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001961 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001962 }
1963
1964 FormatStyle Style;
1965 Lexer &Lex;
1966 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001967 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001968 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001969 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001970
1971 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001972 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001973};
1974
Craig Topperaf35e852013-06-30 22:29:28 +00001975} // end anonymous namespace
1976
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001977tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1978 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001979 std::vector<CharSourceRange> Ranges) {
Daniel Jasperc64b09a2014-05-22 15:12:22 +00001980 if (Style.DisableFormat) {
1981 tooling::Replacements EmptyResult;
1982 return EmptyResult;
1983 }
1984
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001985 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001986 return formatter.format();
1987}
1988
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001989tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1990 std::vector<tooling::Range> Ranges,
1991 StringRef FileName) {
1992 FileManager Files((FileSystemOptions()));
1993 DiagnosticsEngine Diagnostics(
1994 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1995 new DiagnosticOptions);
1996 SourceManager SourceMgr(Diagnostics, Files);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001997 std::unique_ptr<llvm::MemoryBuffer> Buf =
1998 llvm::MemoryBuffer::getMemBuffer(Code, FileName);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001999 const clang::FileEntry *Entry =
2000 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
David Blaikie49cc3182014-08-27 20:54:45 +00002001 SourceMgr.overrideFileContents(Entry, std::move(Buf));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002002 FileID ID =
2003 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienko1e808872013-06-28 12:51:24 +00002004 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002005 getFormattingLangOpts(Style));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002006 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
2007 std::vector<CharSourceRange> CharRanges;
2008 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
2009 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
2010 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
2011 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
2012 }
2013 return reformat(Style, Lex, SourceMgr, CharRanges);
2014}
2015
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002016LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002017 LangOptions LangOpts;
2018 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002019 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2020 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00002021 LangOpts.LineComment = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002022 LangOpts.CXXOperatorNames =
2023 Style.Language != FormatStyle::LK_JavaScript ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002024 LangOpts.Bool = 1;
2025 LangOpts.ObjC1 = 1;
2026 LangOpts.ObjC2 = 1;
2027 return LangOpts;
2028}
2029
Edwin Vaned544aa72013-09-30 13:31:48 +00002030const char *StyleOptionHelpDescription =
2031 "Coding style, currently supports:\n"
2032 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
2033 "Use -style=file to load style configuration from\n"
2034 ".clang-format file located in one of the parent\n"
2035 "directories of the source file (or current\n"
2036 "directory for stdin).\n"
2037 "Use -style=\"{key: value, ...}\" to set specific\n"
2038 "parameters, e.g.:\n"
2039 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
2040
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002041static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002042 if (FileName.endswith_lower(".js")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002043 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00002044 } else if (FileName.endswith_lower(".proto") ||
2045 FileName.endswith_lower(".protodevel")) {
2046 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002047 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002048 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002049}
2050
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002051FormatStyle getStyle(StringRef StyleName, StringRef FileName,
2052 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002053 FormatStyle Style = getLLVMStyle();
2054 Style.Language = getLanguageByFileName(FileName);
2055 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002056 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
2057 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002058 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002059 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002060
2061 if (StyleName.startswith("{")) {
2062 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00002063 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002064 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
2065 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00002066 }
2067 return Style;
2068 }
2069
2070 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002071 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00002072 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
2073 << " style\n";
2074 return Style;
2075 }
2076
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002077 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002078 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00002079 SmallString<128> Path(FileName);
2080 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002081 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00002082 Directory = llvm::sys::path::parent_path(Directory)) {
2083 if (!llvm::sys::fs::is_directory(Directory))
2084 continue;
2085 SmallString<128> ConfigFile(Directory);
2086
2087 llvm::sys::path::append(ConfigFile, ".clang-format");
2088 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2089 bool IsFile = false;
2090 // Ignore errors from is_regular_file: we only need to know if we can read
2091 // the file or not.
2092 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2093
2094 if (!IsFile) {
2095 // Try _clang-format too, since dotfiles are not commonly used on Windows.
2096 ConfigFile = Directory;
2097 llvm::sys::path::append(ConfigFile, "_clang-format");
2098 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2099 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2100 }
2101
2102 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002103 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
2104 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
2105 if (std::error_code EC = Text.getError()) {
2106 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002107 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002108 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002109 if (std::error_code ec =
2110 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00002111 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002112 if (!UnsuitableConfigFiles.empty())
2113 UnsuitableConfigFiles.append(", ");
2114 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002115 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002116 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002117 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2118 << "\n";
2119 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002120 }
2121 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2122 return Style;
2123 }
2124 }
2125 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
2126 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002127 if (!UnsuitableConfigFiles.empty()) {
2128 llvm::errs() << "Configuration file(s) do(es) not support "
2129 << getLanguageName(Style.Language) << ": "
2130 << UnsuitableConfigFiles << "\n";
2131 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002132 return Style;
2133}
2134
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002135} // namespace format
2136} // namespace clang