blob: 32808b519af5ab3d9dbf408272154cc25338a726 [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 Jasperb2e10a52014-01-15 15:09:08 +0000231 IO.mapOptional("SpacesInContainerLiterals",
232 Style.SpacesInContainerLiterals);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000233 IO.mapOptional("SpaceBeforeAssignmentOperators",
234 Style.SpaceBeforeAssignmentOperators);
Daniel Jasper6633ab82013-10-18 10:38:14 +0000235 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000236 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000237 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000238
239 // For backward compatibility.
240 if (!IO.outputting()) {
241 IO.mapOptional("SpaceAfterControlStatementKeyword",
242 Style.SpaceBeforeParens);
Daniel Jasper553d4872014-06-17 12:40:34 +0000243 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
244 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000245 }
246 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000247 IO.mapOptional("DisableFormat", Style.DisableFormat);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000248 }
249};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000250
251// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000252// IO.getContext() should contain a pointer to the FormatStyle structure, that
253// will be used to get default values for missing keys.
254// If the first element has no Language specified, it will be treated as the
255// default one for the following elements.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000256template <> struct DocumentListTraits<std::vector<FormatStyle> > {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000257 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
258 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000259 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000260 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000261 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000262 if (Index >= Seq.size()) {
263 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000264 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000265 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000266 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000267 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000268 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000269 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000270 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000271 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000272 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000273 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000274 }
275};
Alexander Kornienkod6538332013-05-07 15:32:14 +0000276}
277}
278
Daniel Jasperf7935112012-12-03 18:12:45 +0000279namespace clang {
280namespace format {
281
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000282const std::error_category &getParseCategory() {
Rafael Espindolad0136702014-06-12 02:50:04 +0000283 static ParseErrorCategory C;
284 return C;
285}
286std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000287 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000288}
289
290const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
291 return "clang-format.parse_error";
292}
293
294std::string ParseErrorCategory::message(int EV) const {
295 switch (static_cast<ParseError>(EV)) {
296 case ParseError::Success:
297 return "Success";
298 case ParseError::Error:
299 return "Invalid argument";
300 case ParseError::Unsuitable:
301 return "Unsuitable";
302 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000303 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000304}
305
Daniel Jasperf7935112012-12-03 18:12:45 +0000306FormatStyle getLLVMStyle() {
307 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000308 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000309 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000310 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000311 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000312 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000313 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000314 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000315 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000316 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000317 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000318 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000319 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000320 LLVMStyle.BinPackParameters = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000321 LLVMStyle.BreakBeforeBinaryOperators = false;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000322 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000323 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
324 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000325 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000326 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000327 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000328 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000329 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000330 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000331 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000332 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000333 LLVMStyle.ForEachMacros.push_back("foreach");
334 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
335 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000336 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000337 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000338 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000339 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000340 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000341 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000342 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000343 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000344 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000345 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000346 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000347 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000348 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000349 LLVMStyle.SpacesInParentheses = false;
Daniel Jasperad981f82014-08-26 11:41:14 +0000350 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000351 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000352 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000353 LLVMStyle.SpacesInCStyleCastParentheses = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000354 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000355 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000356 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000357
Daniel Jasper19a541e2013-12-19 16:45:34 +0000358 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000359 LLVMStyle.PenaltyBreakFirstLessLess = 120;
360 LLVMStyle.PenaltyBreakString = 1000;
361 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000362 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000363 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000364
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000365 LLVMStyle.DisableFormat = false;
366
Daniel Jasperf7935112012-12-03 18:12:45 +0000367 return LLVMStyle;
368}
369
Nico Weber514ecc82014-02-02 20:50:45 +0000370FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000371 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000372 GoogleStyle.Language = Language;
373
Daniel Jasperf7935112012-12-03 18:12:45 +0000374 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000375 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000376 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000377 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000378 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000379 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000380 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000381 GoogleStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000382 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000383 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000384 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000385 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000386 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000387 GoogleStyle.SpacesBeforeTrailingComments = 2;
388 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000389
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000390 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000391 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000392
Nico Weber514ecc82014-02-02 20:50:45 +0000393 if (Language == FormatStyle::LK_JavaScript) {
394 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000395 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000396 GoogleStyle.SpacesInContainerLiterals = false;
397 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000398 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000399 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000400 }
401
Daniel Jasperf7935112012-12-03 18:12:45 +0000402 return GoogleStyle;
403}
404
Nico Weber514ecc82014-02-02 20:50:45 +0000405FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
406 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Daniel Jasperf7db4332013-01-29 16:03:49 +0000407 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000408 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000409 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000410 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000411 ChromiumStyle.BinPackParameters = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000412 ChromiumStyle.DerivePointerAlignment = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000413 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000414 return ChromiumStyle;
415}
416
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000417FormatStyle getMozillaStyle() {
418 FormatStyle MozillaStyle = getLLVMStyle();
419 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000420 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000421 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000422 MozillaStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000423 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000424 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000425 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
426 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000427 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000428 MozillaStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000429 return MozillaStyle;
430}
431
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000432FormatStyle getWebKitStyle() {
433 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000434 Style.AccessModifierOffset = -4;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000435 Style.AlignTrailingComments = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000436 Style.BreakBeforeBinaryOperators = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000437 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000438 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000439 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000440 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000441 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000442 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000443 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000444 Style.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000445 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000446 return Style;
447}
448
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000449FormatStyle getGNUStyle() {
450 FormatStyle Style = getLLVMStyle();
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000451 Style.AlwaysBreakAfterDefinitionReturnType = true;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000452 Style.BreakBeforeBinaryOperators = true;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000453 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000454 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000455 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000456 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000457 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000458 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000459 return Style;
460}
461
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000462FormatStyle getNoStyle() {
463 FormatStyle NoStyle = getLLVMStyle();
464 NoStyle.DisableFormat = true;
465 return NoStyle;
466}
467
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000468bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
469 FormatStyle *Style) {
470 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000471 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000472 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000473 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000474 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000475 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000476 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000477 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000478 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000479 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000480 } else if (Name.equals_lower("gnu")) {
481 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000482 } else if (Name.equals_lower("none")) {
483 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000484 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000485 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000486 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000487
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000488 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000489 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000490}
491
Rafael Espindolac0809172014-06-12 14:02:15 +0000492std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000493 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000494 FormatStyle::LanguageKind Language = Style->Language;
495 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000496 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000497 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000498
499 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000500 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000501 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
502 // values for the fields, keys for which are missing from the configuration.
503 // Mapping also uses the context to get the language to find the correct
504 // base style.
505 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000506 Input >> Styles;
507 if (Input.error())
508 return Input.error();
509
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000510 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000511 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000512 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000513 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000514 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000515 for (unsigned j = 0; j < i; ++j) {
516 if (Styles[i].Language == Styles[j].Language) {
517 DEBUG(llvm::dbgs()
518 << "Duplicate languages in the config file on positions " << j
519 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000520 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000521 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000522 }
523 }
524 // Look for a suitable configuration starting from the end, so we can
525 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000526 // configuration (which can only be at slot 0) after it.
527 for (int i = Styles.size() - 1; i >= 0; --i) {
528 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000529 Styles[i].Language == FormatStyle::LK_None) {
530 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000531 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000532 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000533 }
534 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000535 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000536}
537
538std::string configurationAsText(const FormatStyle &Style) {
539 std::string Text;
540 llvm::raw_string_ostream Stream(Text);
541 llvm::yaml::Output Output(Stream);
542 // We use the same mapping method for input and output, so we need a non-const
543 // reference here.
544 FormatStyle NonConstStyle = Style;
545 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000546 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000547}
548
Craig Topperaf35e852013-06-30 22:29:28 +0000549namespace {
550
Daniel Jasperde0328a2013-08-16 11:20:30 +0000551class NoColumnLimitFormatter {
552public:
Daniel Jasperf110e202013-08-21 08:39:01 +0000553 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000554
555 /// \brief Formats the line starting at \p State, simply keeping all of the
556 /// input's line breaking decisions.
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000557 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000558 LineState State =
559 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Craig Topper2145bc02014-05-09 08:15:10 +0000560 while (State.NextToken) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000561 bool Newline =
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000562 Indenter->mustBreak(State) ||
Daniel Jasperde0328a2013-08-16 11:20:30 +0000563 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
564 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
565 }
566 }
Daniel Jasperf110e202013-08-21 08:39:01 +0000567
Daniel Jasperde0328a2013-08-16 11:20:30 +0000568private:
569 ContinuationIndenter *Indenter;
570};
571
Daniel Jasper56f8b432013-11-06 23:12:09 +0000572class LineJoiner {
573public:
574 LineJoiner(const FormatStyle &Style) : Style(Style) {}
575
576 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
577 unsigned
578 tryFitMultipleLinesInOne(unsigned Indent,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000579 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000580 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
581 // We can never merge stuff if there are trailing line comments.
Daniel Jasper234379f2013-12-24 13:31:25 +0000582 const AnnotatedLine *TheLine = *I;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000583 if (TheLine->Last->Type == TT_LineComment)
584 return 0;
585
Alexander Kornienkoecc232d2013-12-04 13:25:26 +0000586 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
587 return 0;
588
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000589 unsigned Limit =
590 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000591 // If we already exceed the column limit, we set 'Limit' to 0. The different
592 // tryMerge..() functions can then decide whether to still do merging.
593 Limit = TheLine->Last->TotalLength > Limit
594 ? 0
595 : Limit - TheLine->Last->TotalLength;
596
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000597 if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000598 return 0;
599
Daniel Jasperd74cf402014-04-08 12:46:38 +0000600 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
601 // If necessary, change to something smarter.
602 bool MergeShortFunctions =
603 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
604 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
605 TheLine->Level != 0);
606
Daniel Jasper234379f2013-12-24 13:31:25 +0000607 if (TheLine->Last->Type == TT_FunctionLBrace &&
608 TheLine->First != TheLine->Last) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000609 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000610 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000611 if (TheLine->Last->is(tok::l_brace)) {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000612 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000613 ? tryMergeSimpleBlock(I, E, Limit)
614 : 0;
615 }
616 if (I[1]->First->Type == TT_FunctionLBrace &&
617 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
Alp Tokerba5b4dc2013-12-30 02:06:29 +0000618 // Check for Limit <= 2 to account for the " {".
Daniel Jasper234379f2013-12-24 13:31:25 +0000619 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
620 return 0;
621 Limit -= 2;
622
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000623 unsigned MergedLines = 0;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000624 if (MergeShortFunctions) {
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000625 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
626 // If we managed to merge the block, count the function header, which is
627 // on a separate line.
628 if (MergedLines > 0)
629 ++MergedLines;
630 }
631 return MergedLines;
632 }
633 if (TheLine->First->is(tok::kw_if)) {
634 return Style.AllowShortIfStatementsOnASingleLine
635 ? tryMergeSimpleControlStatement(I, E, Limit)
636 : 0;
637 }
638 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
639 return Style.AllowShortLoopsOnASingleLine
640 ? tryMergeSimpleControlStatement(I, E, Limit)
641 : 0;
642 }
643 if (TheLine->InPPDirective &&
644 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000645 return tryMergeSimplePPDirective(I, E, Limit);
646 }
647 return 0;
648 }
649
650private:
651 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000652 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000653 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
654 unsigned Limit) {
655 if (Limit == 0)
656 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000657 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000658 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000659 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000660 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000661 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000662 return 0;
663 return 1;
664 }
665
666 unsigned tryMergeSimpleControlStatement(
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000667 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000668 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
669 if (Limit == 0)
670 return 0;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000671 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
672 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
Daniel Jasper17605d32014-05-14 09:33:35 +0000673 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000674 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000675 if (I[1]->InPPDirective != (*I)->InPPDirective ||
676 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000677 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000678 Limit = limitConsideringMacros(I + 1, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000679 AnnotatedLine &Line = **I;
680 if (Line.Last->isNot(tok::r_paren))
681 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000682 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000683 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000684 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000685 tok::kw_while) ||
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000686 I[1]->First->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000687 return 0;
688 // Only inline simple if's (no nested if or else).
689 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000690 I[2]->First->is(tok::kw_else))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000691 return 0;
692 return 1;
693 }
694
695 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000696 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000697 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
698 unsigned Limit) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000699 AnnotatedLine &Line = **I;
Daniel Jasper17605d32014-05-14 09:33:35 +0000700
701 // Don't merge ObjC @ keywords and methods.
702 if (Line.First->isOneOf(tok::at, tok::minus, tok::plus))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000703 return 0;
704
Daniel Jasper17605d32014-05-14 09:33:35 +0000705 // Check that the current line allows merging. This depends on whether we
706 // are in a control flow statements as well as several style flags.
707 if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
708 return 0;
709 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
710 tok::kw_catch, tok::kw_for, tok::r_brace)) {
711 if (!Style.AllowShortBlocksOnASingleLine)
712 return 0;
713 if (!Style.AllowShortIfStatementsOnASingleLine &&
714 Line.First->is(tok::kw_if))
715 return 0;
716 if (!Style.AllowShortLoopsOnASingleLine &&
717 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
718 return 0;
719 // FIXME: Consider an option to allow short exception handling clauses on
720 // a single line.
721 if (Line.First->isOneOf(tok::kw_try, tok::kw_catch))
722 return 0;
723 }
724
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000725 FormatToken *Tok = I[1]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000726 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Craig Topper2145bc02014-05-09 08:15:10 +0000727 (Tok->getNextNonComment() == nullptr ||
Daniel Jasper56f8b432013-11-06 23:12:09 +0000728 Tok->getNextNonComment()->is(tok::semi))) {
729 // We merge empty blocks even if the line exceeds the column limit.
730 Tok->SpacesRequiredBefore = 0;
731 Tok->CanBreakBefore = true;
732 return 1;
733 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Daniel Jasper79dffb42014-05-07 09:48:30 +0000734 // We don't merge short records.
735 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
736 return 0;
737
Daniel Jasper56f8b432013-11-06 23:12:09 +0000738 // Check that we still have three lines and they fit into the limit.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000739 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000740 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000741 Limit = limitConsideringMacros(I + 2, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000742
743 if (!nextTwoLinesFitInto(I, Limit))
744 return 0;
745
746 // Second, check that the next line does not contain any braces - if it
747 // does, readability declines when putting it into a single line.
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000748 if (I[1]->Last->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000749 return 0;
750 do {
Daniel Jasperbd630732014-05-22 13:25:26 +0000751 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000752 return 0;
753 Tok = Tok->Next;
Craig Topper2145bc02014-05-09 08:15:10 +0000754 } while (Tok);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000755
Daniel Jasper79dffb42014-05-07 09:48:30 +0000756 // Last, check that the third line starts with a closing brace.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000757 Tok = I[2]->First;
Daniel Jasper79dffb42014-05-07 09:48:30 +0000758 if (Tok->isNot(tok::r_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000759 return 0;
760
761 return 2;
762 }
763 return 0;
764 }
765
Daniel Jasper64989962014-02-07 13:45:27 +0000766 /// Returns the modified column limit for \p I if it is inside a macro and
767 /// needs a trailing '\'.
768 unsigned
Daniel Jaspera0407742014-02-11 10:08:11 +0000769 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper64989962014-02-07 13:45:27 +0000770 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
771 unsigned Limit) {
772 if (I[0]->InPPDirective && I + 1 != E &&
773 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
774 return Limit < 2 ? 0 : Limit - 2;
775 }
776 return Limit;
777 }
778
Daniel Jasper56f8b432013-11-06 23:12:09 +0000779 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
780 unsigned Limit) {
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000781 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
782 return false;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000783 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000784 }
785
Daniel Jasper234379f2013-12-24 13:31:25 +0000786 bool containsMustBreak(const AnnotatedLine *Line) {
787 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
788 if (Tok->MustBreakBefore)
789 return true;
790 }
791 return false;
792 }
793
Daniel Jasper56f8b432013-11-06 23:12:09 +0000794 const FormatStyle &Style;
795};
796
Daniel Jasperf7935112012-12-03 18:12:45 +0000797class UnwrappedLineFormatter {
798public:
Daniel Jasper5500f612013-11-25 11:08:59 +0000799 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000800 WhitespaceManager *Whitespaces,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000801 const FormatStyle &Style)
Daniel Jasper5500f612013-11-25 11:08:59 +0000802 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
803 Joiner(Style) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000804
Daniel Jasper56f8b432013-11-06 23:12:09 +0000805 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper9c199562013-11-28 15:58:55 +0000806 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Daniel Jasperc359ad02014-04-15 08:13:47 +0000807 // Try to look up already computed penalty in DryRun-mode.
NAKAMURA Takumi22059522014-04-15 23:29:04 +0000808 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
809 &Lines, AdditionalIndent);
Daniel Jasperc359ad02014-04-15 08:13:47 +0000810 auto CacheIt = PenaltyCache.find(CacheKey);
811 if (DryRun && CacheIt != PenaltyCache.end())
812 return CacheIt->second;
813
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000814 assert(!Lines.empty());
815 unsigned Penalty = 0;
816 std::vector<int> IndentForLevel;
817 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
818 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Craig Topper2145bc02014-05-09 08:15:10 +0000819 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000820 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
821 E = Lines.end();
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000822 I != E; ++I) {
823 const AnnotatedLine &TheLine = **I;
824 const FormatToken *FirstTok = TheLine.First;
825 int Offset = getIndentOffset(*FirstTok);
826
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000827 // Determine indent and try to merge multiple unwrapped lines.
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000828 unsigned Indent;
829 if (TheLine.InPPDirective) {
830 Indent = TheLine.Level * Style.IndentWidth;
831 } else {
832 while (IndentForLevel.size() <= TheLine.Level)
833 IndentForLevel.push_back(-1);
834 IndentForLevel.resize(TheLine.Level + 1);
835 Indent = getIndent(IndentForLevel, TheLine.Level);
836 }
837 unsigned LevelIndent = Indent;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000838 if (static_cast<int>(Indent) + Offset >= 0)
839 Indent += Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000840
841 // Merge multiple lines if possible.
Daniel Jasper56f8b432013-11-06 23:12:09 +0000842 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
Alexander Kornienko31e95542013-12-04 12:21:08 +0000843 if (MergedLines > 0 && Style.ColumnLimit == 0) {
844 // Disallow line merging if there is a break at the start of one of the
845 // input lines.
846 for (unsigned i = 0; i < MergedLines; ++i) {
847 if (I[i + 1]->First->NewlinesBefore > 0)
848 MergedLines = 0;
849 }
850 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000851 if (!DryRun) {
852 for (unsigned i = 0; i < MergedLines; ++i) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000853 join(*I[i], *I[i + 1]);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000854 }
855 }
856 I += MergedLines;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000857
Daniel Jasper9c199562013-11-28 15:58:55 +0000858 bool FixIndentation =
859 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000860 if (TheLine.First->is(tok::eof)) {
Daniel Jasper5500f612013-11-25 11:08:59 +0000861 if (PreviousLine && PreviousLine->Affected && !DryRun) {
862 // Remove the file's trailing whitespace.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000863 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
864 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
865 /*IndentLevel=*/0, /*Spaces=*/0,
866 /*TargetColumn=*/0);
867 }
Daniel Jasper9c199562013-11-28 15:58:55 +0000868 } else if (TheLine.Type != LT_Invalid &&
869 (TheLine.Affected || FixIndentation)) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000870 if (FirstTok->WhitespaceRange.isValid()) {
871 if (!DryRun)
872 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
873 Indent, TheLine.InPPDirective);
874 } else {
875 Indent = LevelIndent = FirstTok->OriginalColumn;
876 }
877
878 // If everything fits on a single line, just put it there.
879 unsigned ColumnLimit = Style.ColumnLimit;
880 if (I + 1 != E) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000881 AnnotatedLine *NextLine = I[1];
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000882 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
883 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
884 }
885
886 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
887 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000888 while (State.NextToken) {
889 formatChildren(State, /*Newline=*/false, /*DryRun=*/false, Penalty);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000890 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000891 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000892 } else if (Style.ColumnLimit == 0) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000893 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000894 NoColumnLimitFormatter Formatter(Indenter);
895 if (!DryRun)
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000896 Formatter.format(Indent, &TheLine);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000897 } else {
898 Penalty += format(TheLine, Indent, DryRun);
899 }
900
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000901 if (!TheLine.InPPDirective)
902 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper9c199562013-11-28 15:58:55 +0000903 } else if (TheLine.ChildrenAffected) {
904 format(TheLine.Children, DryRun);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000905 } else {
906 // Format the first token if necessary, and notify the WhitespaceManager
907 // about the unchanged whitespace.
Craig Topper2145bc02014-05-09 08:15:10 +0000908 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000909 if (Tok == TheLine.First &&
910 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
911 unsigned LevelIndent = Tok->OriginalColumn;
912 if (!DryRun) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000913 // Remove trailing whitespace of the previous line.
Daniel Jasper5500f612013-11-25 11:08:59 +0000914 if ((PreviousLine && PreviousLine->Affected) ||
915 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000916 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
917 TheLine.InPPDirective);
918 } else {
919 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
920 }
921 }
922
923 if (static_cast<int>(LevelIndent) - Offset >= 0)
924 LevelIndent -= Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000925 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000926 IndentForLevel[TheLine.Level] = LevelIndent;
927 } else if (!DryRun) {
928 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
929 }
930 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000931 }
932 if (!DryRun) {
Craig Topper2145bc02014-05-09 08:15:10 +0000933 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000934 Tok->Finalized = true;
935 }
936 }
937 PreviousLine = *I;
938 }
Daniel Jasperc359ad02014-04-15 08:13:47 +0000939 PenaltyCache[CacheKey] = Penalty;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000940 return Penalty;
941 }
942
943private:
944 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000945 ///
946 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000947 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
948 bool DryRun) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000949 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +0000950
Daniel Jasperacc33662013-02-08 08:22:00 +0000951 // If the ObjC method declaration does not fit on a line, we should format
952 // it with one arg per line.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000953 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperacc33662013-02-08 08:22:00 +0000954 State.Stack.back().BreakBeforeParameter = true;
955
Daniel Jasper4b866272013-02-01 11:00:45 +0000956 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000957 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +0000958 }
959
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000960 /// \brief An edge in the solution space from \c Previous->State to \c State,
961 /// inserting a newline dependent on the \c NewLine.
962 struct StateNode {
963 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000964 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000965 LineState State;
966 bool NewLine;
967 StateNode *Previous;
968 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000969
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000970 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
971 ///
972 /// In case of equal penalties, we want to prefer states that were inserted
973 /// first. During state generation we make sure that we insert states first
974 /// that break the line as late as possible.
975 typedef std::pair<unsigned, unsigned> OrderedPenalty;
976
977 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
978 /// \c State has the given \c OrderedPenalty.
979 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
980
981 /// \brief The BFS queue type.
982 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
983 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000984
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000985 /// \brief Get the offset of the line relatively to the level.
986 ///
987 /// For example, 'public:' labels in classes are offset by 1 or 2
988 /// characters to the left from their level.
989 int getIndentOffset(const FormatToken &RootToken) {
990 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
991 return Style.AccessModifierOffset;
992 return 0;
993 }
994
995 /// \brief Add a new line and the required indent before the first Token
996 /// of the \c UnwrappedLine if there was no structural parsing error.
997 void formatFirstToken(FormatToken &RootToken,
998 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
999 unsigned Indent, bool InPPDirective) {
1000 unsigned Newlines =
1001 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1002 // Remove empty lines before "}" where applicable.
1003 if (RootToken.is(tok::r_brace) &&
1004 (!RootToken.Next ||
1005 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1006 Newlines = std::min(Newlines, 1u);
1007 if (Newlines == 0 && !RootToken.IsFirst)
1008 Newlines = 1;
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001009 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1010 Newlines = 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001011
Daniel Jasper11164bd2014-03-21 12:58:53 +00001012 // Remove empty lines after "{".
Daniel Jaspera26fc5c2014-03-21 13:43:14 +00001013 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1014 PreviousLine->Last->is(tok::l_brace) &&
Daniel Jasper01b35482014-03-21 13:03:33 +00001015 PreviousLine->First->isNot(tok::kw_namespace))
Daniel Jasper11164bd2014-03-21 12:58:53 +00001016 Newlines = 1;
1017
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001018 // Insert extra new line before access specifiers.
1019 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1020 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1021 ++Newlines;
1022
1023 // Remove empty lines after access specifiers.
1024 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
1025 Newlines = std::min(1u, Newlines);
1026
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001027 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
1028 Indent, InPPDirective &&
1029 !RootToken.HasUnescapedNewline);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001030 }
1031
1032 /// \brief Get the indent of \p Level from \p IndentForLevel.
1033 ///
1034 /// \p IndentForLevel must contain the indent for the level \c l
1035 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1036 /// that level is unknown.
1037 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
1038 if (IndentForLevel[Level] != -1)
1039 return IndentForLevel[Level];
1040 if (Level == 0)
1041 return 0;
1042 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
1043 }
1044
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001045 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1046 assert(!A.Last->Next);
1047 assert(!B.First->Previous);
Daniel Jasper5500f612013-11-25 11:08:59 +00001048 if (B.Affected)
1049 A.Affected = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001050 A.Last->Next = B.First;
1051 B.First->Previous = A.Last;
Daniel Jasper98fb6e12013-11-08 17:33:27 +00001052 B.First->CanBreakBefore = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001053 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1054 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1055 Tok->TotalLength += LengthA;
1056 A.Last = Tok;
1057 }
1058 }
1059
1060 unsigned getColumnLimit(bool InPPDirective) const {
1061 // In preprocessor directives reserve two chars for trailing " \"
1062 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1063 }
1064
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001065 struct CompareLineStatePointers {
1066 bool operator()(LineState *obj1, LineState *obj2) const {
1067 return *obj1 < *obj2;
1068 }
1069 };
1070
Daniel Jasper4b866272013-02-01 11:00:45 +00001071 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +00001072 ///
Daniel Jasper4b866272013-02-01 11:00:45 +00001073 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1074 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1075 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001076 /// to a state where all tokens are placed. Returns the penalty.
1077 ///
1078 /// If \p DryRun is \c false, directly applies the changes.
1079 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001080 std::set<LineState *, CompareLineStatePointers> Seen;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001081
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001082 // Increasing count of \c StateNode items we have created. This is used to
1083 // create a deterministic order independent of the container.
1084 unsigned Count = 0;
1085 QueueType Queue;
1086
Daniel Jasper4b866272013-02-01 11:00:45 +00001087 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001088 StateNode *Node =
Craig Topper2145bc02014-05-09 08:15:10 +00001089 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001090 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1091 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001092
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001093 unsigned Penalty = 0;
1094
Daniel Jasper4b866272013-02-01 11:00:45 +00001095 // While not empty, take first element and follow edges.
1096 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001097 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001098 StateNode *Node = Queue.top().second;
Craig Topper2145bc02014-05-09 08:15:10 +00001099 if (!Node->State.NextToken) {
Alexander Kornienko49149672013-05-10 11:56:10 +00001100 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001101 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001102 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001103 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001104
Daniel Jasperf8114cf2013-05-22 05:27:42 +00001105 // Cut off the analysis of certain solutions if the analysis gets too
1106 // complex. See description of IgnoreStackForComparison.
1107 if (Count > 10000)
1108 Node->State.IgnoreStackForComparison = true;
1109
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001110 if (!Seen.insert(&Node->State).second)
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001111 // State already examined with lower penalty.
1112 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001113
Manuel Klimek71814b42013-10-11 21:25:45 +00001114 FormatDecision LastFormat = Node->State.NextToken->Decision;
1115 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001116 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimek71814b42013-10-11 21:25:45 +00001117 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001118 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper4b866272013-02-01 11:00:45 +00001119 }
1120
Manuel Klimek71814b42013-10-11 21:25:45 +00001121 if (Queue.empty()) {
Daniel Jasper4b866272013-02-01 11:00:45 +00001122 // We were unable to find a solution, do nothing.
1123 // FIXME: Add diagnostic?
Manuel Klimek71814b42013-10-11 21:25:45 +00001124 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001125 return 0;
Manuel Klimek71814b42013-10-11 21:25:45 +00001126 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001127
Daniel Jasper4b866272013-02-01 11:00:45 +00001128 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001129 if (!DryRun)
1130 reconstructPath(InitialState, Queue.top().second);
1131
Alexander Kornienko49149672013-05-10 11:56:10 +00001132 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1133 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001134
1135 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001136 }
1137
1138 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001139 std::deque<StateNode *> Path;
1140 // We do not need a break before the initial token.
1141 while (Current->Previous) {
1142 Path.push_front(Current);
1143 Current = Current->Previous;
1144 }
1145 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1146 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001147 unsigned Penalty = 0;
1148 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1149 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1150
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001151 DEBUG({
1152 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001153 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001154 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001155 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001156 }
1157 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001158 }
Daniel Jasper4b866272013-02-01 11:00:45 +00001159 }
1160
Manuel Klimekaf491072013-02-13 10:54:19 +00001161 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001162 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001163 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001164 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001165 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001166 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001167 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001168 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001169 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001170 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001171
1172 StateNode *Node = new (Allocator.Allocate())
1173 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001174 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1175 return;
1176
Daniel Jasperde0328a2013-08-16 11:20:30 +00001177 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001178
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001179 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1180 ++(*Count);
Daniel Jasper4b866272013-02-01 11:00:45 +00001181 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001182
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001183 /// \brief If the \p State's next token is an r_brace closing a nested block,
1184 /// format the nested block before it.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001185 ///
1186 /// Returns \c true if all children could be placed successfully and adapts
1187 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1188 /// creates changes using \c Whitespaces.
1189 ///
1190 /// The crucial idea here is that children always get formatted upon
1191 /// encountering the closing brace right after the nested block. Now, if we
1192 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1193 /// \c false), the entire block has to be kept on the same line (which is only
1194 /// possible if it fits on the line, only contains a single statement, etc.
1195 ///
1196 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1197 /// break after the "{", format all lines with correct indentation and the put
1198 /// the closing "}" on yet another new line.
1199 ///
1200 /// This enables us to keep the simple structure of the
1201 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1202 /// break or don't break.
1203 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1204 unsigned &Penalty) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001205 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001206 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1207 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1208 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001209 // The previous token does not open a block. Nothing to do. We don't
1210 // assert so that we can simply call this function for all tokens.
Daniel Jasper36c28ce2013-09-06 08:54:24 +00001211 return true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001212
1213 if (NewLine) {
Daniel Jasper58cb2ed2014-06-06 13:49:04 +00001214 int AdditionalIndent =
1215 State.FirstIndent - State.Line->Level * Style.IndentWidth;
Daniel Jasperb16b9692014-05-21 12:51:23 +00001216 if (State.Stack.size() < 2 ||
1217 !State.Stack[State.Stack.size() - 2].JSFunctionInlined) {
1218 AdditionalIndent = State.Stack.back().Indent -
1219 Previous.Children[0]->Level * Style.IndentWidth;
1220 }
1221
Daniel Jasper9c199562013-11-28 15:58:55 +00001222 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1223 /*FixBadIndentation=*/true);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001224 return true;
1225 }
1226
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001227 // Cannot merge multiple statements into a single line.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001228 if (Previous.Children.size() > 1)
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001229 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001230
Daniel Jasper21397a32014-04-09 12:21:48 +00001231 // Cannot merge into one line if this line ends on a comment.
1232 if (Previous.is(tok::comment))
1233 return false;
1234
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001235 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001236 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001237 return false;
1238
Daniel Jasper98583d52014-04-15 08:28:06 +00001239 // If the child line exceeds the column limit, we wouldn't want to merge it.
1240 // We add +2 for the trailing " }".
1241 if (Style.ColumnLimit > 0 &&
1242 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
1243 Style.ColumnLimit)
1244 return false;
1245
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001246 if (!DryRun) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001247 Whitespaces->replaceWhitespace(
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001248 *Previous.Children[0]->First,
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001249 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001250 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001251 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001252 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001253
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001254 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001255 return true;
1256 }
1257
Daniel Jasperde0328a2013-08-16 11:20:30 +00001258 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001259 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001260 FormatStyle Style;
Daniel Jasper56f8b432013-11-06 23:12:09 +00001261 LineJoiner Joiner;
Manuel Klimekaf491072013-02-13 10:54:19 +00001262
1263 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperc359ad02014-04-15 08:13:47 +00001264
1265 // Cache to store the penalty of formatting a vector of AnnotatedLines
1266 // starting from a specific additional offset. Improves performance if there
1267 // are many nested blocks.
1268 std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
1269 unsigned> PenaltyCache;
Daniel Jasperf7935112012-12-03 18:12:45 +00001270};
1271
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001272class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001273public:
Manuel Klimek31c85922013-08-29 15:21:40 +00001274 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001275 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +00001276 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
1277 Column(0), TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr),
1278 Style(Style), IdentTable(getFormattingLangOpts()), Encoding(Encoding),
NAKAMURA Takumi7160c4d2014-08-06 16:53:13 +00001279 FirstInLineIndex(0), FormattingDisabled(false) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001280 Lex.SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +00001281
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001282 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +00001283 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1284 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001285 }
1286
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001287 ArrayRef<FormatToken *> lex() {
1288 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +00001289 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001290 do {
1291 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001292 tryMergePreviousTokens();
Manuel Klimek68b03042014-04-14 09:14:11 +00001293 if (Tokens.back()->NewlinesBefore > 0)
1294 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001295 } while (Tokens.back()->Tok.isNot(tok::eof));
1296 return Tokens;
1297 }
1298
1299 IdentifierTable &getIdentTable() { return IdentTable; }
1300
1301private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001302 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001303 if (tryMerge_TMacro())
1304 return;
Manuel Klimek68b03042014-04-14 09:14:11 +00001305 if (tryMergeConflictMarkers())
1306 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001307
1308 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001309 if (tryMergeEscapeSequence())
1310 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001311 if (tryMergeJSRegexLiteral())
1312 return;
1313
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001314 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1315 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1316 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1317 tok::greaterequal };
Daniel Jasper78214392014-05-19 07:27:02 +00001318 static tok::TokenKind JSRightArrow[] = { tok::equal, tok::greater };
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001319 // FIXME: We probably need to change token type to mimic operator with the
1320 // correct priority.
1321 if (tryMergeTokens(JSIdentity))
1322 return;
1323 if (tryMergeTokens(JSNotIdentity))
1324 return;
1325 if (tryMergeTokens(JSShiftEqual))
1326 return;
Daniel Jasper78214392014-05-19 07:27:02 +00001327 if (tryMergeTokens(JSRightArrow))
1328 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001329 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001330 }
1331
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001332 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1333 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001334 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001335
1336 SmallVectorImpl<FormatToken *>::const_iterator First =
1337 Tokens.end() - Kinds.size();
1338 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001339 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001340 unsigned AddLength = 0;
1341 for (unsigned i = 1; i < Kinds.size(); ++i) {
1342 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1343 First[i]->WhitespaceRange.getEnd())
1344 return false;
1345 AddLength += First[i]->TokenText.size();
1346 }
1347 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1348 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1349 First[0]->TokenText.size() + AddLength);
1350 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001351 return true;
1352 }
1353
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001354 // Tries to merge an escape sequence, i.e. a "\\" and the following
Alp Tokerc3f36af2014-05-15 01:35:53 +00001355 // character. Use e.g. inside JavaScript regex literals.
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001356 bool tryMergeEscapeSequence() {
1357 if (Tokens.size() < 2)
1358 return false;
1359 FormatToken *Previous = Tokens[Tokens.size() - 2];
1360 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\" ||
1361 Tokens.back()->NewlinesBefore != 0)
1362 return false;
1363 Previous->ColumnWidth += Tokens.back()->ColumnWidth;
1364 StringRef Text = Previous->TokenText;
1365 Previous->TokenText =
1366 StringRef(Text.data(), Text.size() + Tokens.back()->TokenText.size());
1367 Tokens.resize(Tokens.size() - 1);
1368 return true;
1369 }
1370
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001371 // Try to determine whether the current token ends a JavaScript regex literal.
1372 // We heuristically assume that this is a regex literal if we find two
1373 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +00001374 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
1375 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001376 bool tryMergeJSRegexLiteral() {
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001377 if (Tokens.size() < 2 || Tokens.back()->isNot(tok::slash) ||
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001378 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
1379 Tokens[Tokens.size() - 2]->TokenText == "\\"))
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001380 return false;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001381 unsigned TokenCount = 0;
1382 unsigned LastColumn = Tokens.back()->OriginalColumn;
1383 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
1384 ++TokenCount;
1385 if (I[0]->is(tok::slash) && I + 1 != E &&
1386 (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
1387 tok::exclaim, tok::l_square, tok::colon, tok::comma,
1388 tok::question, tok::kw_return) ||
1389 I[1]->isBinaryOperator())) {
1390 Tokens.resize(Tokens.size() - TokenCount);
1391 Tokens.back()->Tok.setKind(tok::unknown);
1392 Tokens.back()->Type = TT_RegexLiteral;
1393 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
1394 return true;
1395 }
1396
1397 // There can't be a newline inside a regex literal.
1398 if (I[0]->NewlinesBefore > 0)
1399 return false;
1400 }
1401 return false;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001402 }
1403
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001404 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001405 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001406 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001407 FormatToken *Last = Tokens.back();
1408 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001409 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001410
1411 FormatToken *String = Tokens[Tokens.size() - 2];
1412 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001413 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001414
1415 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001416 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001417
1418 FormatToken *Macro = Tokens[Tokens.size() - 4];
1419 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001420 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001421
1422 const char *Start = Macro->TokenText.data();
1423 const char *End = Last->TokenText.data() + Last->TokenText.size();
1424 String->TokenText = StringRef(Start, End - Start);
1425 String->IsFirst = Macro->IsFirst;
1426 String->LastNewlineOffset = Macro->LastNewlineOffset;
1427 String->WhitespaceRange = Macro->WhitespaceRange;
1428 String->OriginalColumn = Macro->OriginalColumn;
1429 String->ColumnWidth = encoding::columnWidthWithTabs(
1430 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1431
1432 Tokens.pop_back();
1433 Tokens.pop_back();
1434 Tokens.pop_back();
1435 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001436 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001437 }
1438
Manuel Klimek68b03042014-04-14 09:14:11 +00001439 bool tryMergeConflictMarkers() {
1440 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1441 return false;
1442
1443 // Conflict lines look like:
1444 // <marker> <text from the vcs>
1445 // For example:
1446 // >>>>>>> /file/in/file/system at revision 1234
1447 //
1448 // We merge all tokens in a line that starts with a conflict marker
1449 // into a single token with a special token type that the unwrapped line
1450 // parser will use to correctly rebuild the underlying code.
1451
1452 FileID ID;
1453 // Get the position of the first token in the line.
1454 unsigned FirstInLineOffset;
1455 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1456 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1457 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1458 // Calculate the offset of the start of the current line.
1459 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1460 if (LineOffset == StringRef::npos) {
1461 LineOffset = 0;
1462 } else {
1463 ++LineOffset;
1464 }
1465
1466 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1467 StringRef LineStart;
1468 if (FirstSpace == StringRef::npos) {
1469 LineStart = Buffer.substr(LineOffset);
1470 } else {
1471 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1472 }
1473
1474 TokenType Type = TT_Unknown;
1475 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1476 Type = TT_ConflictStart;
1477 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1478 LineStart == "====") {
1479 Type = TT_ConflictAlternative;
1480 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1481 Type = TT_ConflictEnd;
1482 }
1483
1484 if (Type != TT_Unknown) {
1485 FormatToken *Next = Tokens.back();
1486
1487 Tokens.resize(FirstInLineIndex + 1);
1488 // We do not need to build a complete token here, as we will skip it
1489 // during parsing anyway (as we must not touch whitespace around conflict
1490 // markers).
1491 Tokens.back()->Type = Type;
1492 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1493
1494 Tokens.push_back(Next);
1495 return true;
1496 }
1497
1498 return false;
1499 }
1500
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001501 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001502 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001503 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +00001504 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001505 Token Greater = FormatTok->Tok;
1506 FormatTok = new (Allocator.Allocate()) FormatToken;
1507 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001508 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001509 FormatTok->Tok.getLocation().getLocWithOffset(1);
1510 FormatTok->WhitespaceRange =
1511 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001512 FormatTok->TokenText = ">";
Alexander Kornienko39856b72013-09-10 09:38:25 +00001513 FormatTok->ColumnWidth = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001514 GreaterStashed = false;
1515 return FormatTok;
1516 }
1517
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001518 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001519 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001520 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001521 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001522 FormatTok->IsFirst = IsFirstToken;
1523 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001524
1525 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001526 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001527 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001528 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1529 switch (FormatTok->TokenText[i]) {
1530 case '\n':
1531 ++FormatTok->NewlinesBefore;
1532 // FIXME: This is technically incorrect, as it could also
1533 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001534 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1535 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1536 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +00001537 FormatTok->HasUnescapedNewline = true;
1538 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1539 Column = 0;
1540 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001541 case '\r':
1542 case '\f':
1543 case '\v':
1544 Column = 0;
1545 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001546 case ' ':
1547 ++Column;
1548 break;
1549 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001550 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001551 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001552 case '\\':
1553 ++Column;
1554 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1555 FormatTok->TokenText[i + 1] != '\n'))
1556 FormatTok->Type = TT_ImplicitStringLiteral;
1557 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001558 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001559 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001560 ++Column;
1561 break;
1562 }
1563 }
1564
Daniel Jasper877615c2013-10-11 19:45:02 +00001565 if (FormatTok->Type == TT_ImplicitStringLiteral)
1566 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001567 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001568
Daniel Jasper8369aa52013-07-16 20:28:33 +00001569 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001570 }
Manuel Klimekef920692013-01-07 07:56:50 +00001571
Manuel Klimek1abf7892013-01-04 23:34:14 +00001572 // In case the token starts with escaped newlines, we want to
1573 // take them into account as whitespace - this pattern is quite frequent
1574 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001575 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001576 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1577 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001578 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001579 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001580 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001581 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001582 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001583
1584 FormatTok->WhitespaceRange = SourceRange(
1585 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1586
Manuel Klimek31c85922013-08-29 15:21:40 +00001587 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001588
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001589 TrailingWhitespace = 0;
1590 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001591 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001592 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001593 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001594 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001595 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001596 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001597 FormatTok->Tok.setIdentifierInfo(&Info);
1598 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001599 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001600 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001601 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001602 GreaterStashed = true;
1603 }
1604
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001605 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001606
Alexander Kornienko39856b72013-09-10 09:38:25 +00001607 StringRef Text = FormatTok->TokenText;
1608 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001609 if (FirstNewlinePos == StringRef::npos) {
1610 // FIXME: ColumnWidth actually depends on the start column, we need to
1611 // take this into account when the token is moved.
1612 FormatTok->ColumnWidth =
1613 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1614 Column += FormatTok->ColumnWidth;
1615 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001616 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001617 // FIXME: ColumnWidth actually depends on the start column, we need to
1618 // take this into account when the token is moved.
1619 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1620 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1621
Alexander Kornienko39856b72013-09-10 09:38:25 +00001622 // The last line of the token always starts in column 0.
1623 // Thus, the length can be precomputed even in the presence of tabs.
1624 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1625 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1626 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001627 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001628 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001629
Daniel Jaspere1e43192014-04-01 12:55:11 +00001630 FormatTok->IsForEachMacro =
1631 std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1632 FormatTok->Tok.getIdentifierInfo());
1633
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001634 return FormatTok;
1635 }
1636
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001637 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001638 bool IsFirstToken;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001639 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001640 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001641 unsigned TrailingWhitespace;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001642 Lexer &Lex;
1643 SourceManager &SourceMgr;
Manuel Klimek31c85922013-08-29 15:21:40 +00001644 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001645 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001646 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001647 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001648 // Index (in 'Tokens') of the last token that starts a new line.
1649 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001650 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001651 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001652
NAKAMURA Takumi7160c4d2014-08-06 16:53:13 +00001653 bool FormattingDisabled;
Daniel Jasper471894432014-08-06 13:40:26 +00001654
Daniel Jasper8369aa52013-07-16 20:28:33 +00001655 void readRawToken(FormatToken &Tok) {
1656 Lex.LexFromRawLexer(Tok.Tok);
1657 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1658 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001659 // For formatting, treat unterminated string literals like normal string
1660 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001661 if (Tok.is(tok::unknown)) {
1662 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1663 Tok.Tok.setKind(tok::string_literal);
1664 Tok.IsUnterminatedLiteral = true;
1665 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1666 Tok.TokenText == "''") {
1667 Tok.Tok.setKind(tok::char_constant);
1668 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001669 }
Daniel Jasper471894432014-08-06 13:40:26 +00001670 if (Tok.is(tok::comment) && Tok.TokenText == "// clang-format on")
1671 FormattingDisabled = false;
1672 Tok.Finalized = FormattingDisabled;
1673 if (Tok.is(tok::comment) && Tok.TokenText == "// clang-format off")
1674 FormattingDisabled = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001675 }
1676};
1677
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001678static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1679 switch (Language) {
1680 case FormatStyle::LK_Cpp:
1681 return "C++";
1682 case FormatStyle::LK_JavaScript:
1683 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001684 case FormatStyle::LK_Proto:
1685 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001686 default:
1687 return "Unknown";
1688 }
1689}
1690
Daniel Jasperf7935112012-12-03 18:12:45 +00001691class Formatter : public UnwrappedLineConsumer {
1692public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001693 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001694 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001695 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001696 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001697 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Manuel Klimek71814b42013-10-11 21:25:45 +00001698 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001699 DEBUG(llvm::dbgs() << "File encoding: "
1700 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1701 : "unknown")
1702 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001703 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1704 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001705 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001706
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001707 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001708 tooling::Replacements Result;
Manuel Klimek31c85922013-08-29 15:21:40 +00001709 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001710
1711 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001712 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001713 assert(UnwrappedLines.rbegin()->empty());
1714 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1715 ++Run) {
1716 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1717 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1718 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1719 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1720 }
1721 tooling::Replacements RunResult =
1722 format(AnnotatedLines, StructuralError, Tokens);
1723 DEBUG({
1724 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1725 for (tooling::Replacements::iterator I = RunResult.begin(),
1726 E = RunResult.end();
1727 I != E; ++I) {
1728 llvm::dbgs() << I->toString() << "\n";
1729 }
1730 });
1731 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1732 delete AnnotatedLines[i];
1733 }
1734 Result.insert(RunResult.begin(), RunResult.end());
1735 Whitespaces.reset();
1736 }
1737 return Result;
1738 }
1739
1740 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1741 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001742 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001743 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001744 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001745 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001746 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001747 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001748 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001749 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001750 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001751
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001752 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001753 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1754 BinPackInconclusiveFunctions);
Daniel Jasper5500f612013-11-25 11:08:59 +00001755 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001756 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001757 return Whitespaces.generateReplacements();
1758 }
1759
1760private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001761 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001762 // Returns \c true if at least one line between I and E or one of their
1763 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001764 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1765 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1766 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001767 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001768 while (I != E) {
1769 AnnotatedLine *Line = *I;
1770 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1771
1772 // If a line is part of a preprocessor directive, it needs to be formatted
1773 // if any token within the directive is affected.
1774 if (Line->InPPDirective) {
1775 FormatToken *Last = Line->Last;
1776 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1777 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1778 Last = (*PPEnd)->Last;
1779 ++PPEnd;
1780 }
1781
1782 if (affectsTokenRange(*Line->First, *Last,
1783 /*IncludeLeadingNewlines=*/false)) {
1784 SomeLineAffected = true;
1785 markAllAsAffected(I, PPEnd);
1786 }
1787 I = PPEnd;
1788 continue;
1789 }
1790
Daniel Jasper38c82402013-11-29 09:27:43 +00001791 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001792 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001793
Daniel Jasper38c82402013-11-29 09:27:43 +00001794 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001795 ++I;
1796 }
1797 return SomeLineAffected;
1798 }
1799
Daniel Jasper9c199562013-11-28 15:58:55 +00001800 // Determines whether 'Line' is affected by the SourceRanges given as input.
1801 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001802 bool nonPPLineAffected(AnnotatedLine *Line,
1803 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001804 bool SomeLineAffected = false;
1805 Line->ChildrenAffected =
1806 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1807 if (Line->ChildrenAffected)
1808 SomeLineAffected = true;
1809
1810 // Stores whether one of the line's tokens is directly affected.
1811 bool SomeTokenAffected = false;
1812 // Stores whether we need to look at the leading newlines of the next token
1813 // in order to determine whether it was affected.
1814 bool IncludeLeadingNewlines = false;
1815
1816 // Stores whether the first child line of any of this line's tokens is
1817 // affected.
1818 bool SomeFirstChildAffected = false;
1819
1820 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1821 // Determine whether 'Tok' was affected.
1822 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1823 SomeTokenAffected = true;
1824
1825 // Determine whether the first child of 'Tok' was affected.
1826 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1827 SomeFirstChildAffected = true;
1828
1829 IncludeLeadingNewlines = Tok->Children.empty();
1830 }
1831
1832 // Was this line moved, i.e. has it previously been on the same line as an
1833 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001834 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1835 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001836
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001837 bool IsContinuedComment =
1838 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1839 Line->First->NewlinesBefore < 2 && PreviousLine &&
1840 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001841
1842 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1843 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001844 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001845 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001846 }
1847 return SomeLineAffected;
1848 }
1849
Daniel Jasper5500f612013-11-25 11:08:59 +00001850 // Marks all lines between I and E as well as all their children as affected.
1851 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1852 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1853 while (I != E) {
1854 (*I)->Affected = true;
1855 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1856 ++I;
1857 }
1858 }
1859
1860 // Returns true if the range from 'First' to 'Last' intersects with one of the
1861 // input ranges.
1862 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1863 bool IncludeLeadingNewlines) {
1864 SourceLocation Start = First.WhitespaceRange.getBegin();
1865 if (!IncludeLeadingNewlines)
1866 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001867 SourceLocation End = Last.getStartOfNonWhitespace();
1868 if (Last.TokenText.size() > 0)
1869 End = End.getLocWithOffset(Last.TokenText.size() - 1);
Daniel Jasper5500f612013-11-25 11:08:59 +00001870 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1871 return affectsCharSourceRange(Range);
1872 }
1873
1874 // Returns true if one of the input ranges intersect the leading empty lines
1875 // before 'Tok'.
1876 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1877 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1878 Tok.WhitespaceRange.getBegin(),
1879 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1880 return affectsCharSourceRange(EmptyLineRange);
1881 }
1882
1883 // Returns true if 'Range' intersects with one of the input ranges.
1884 bool affectsCharSourceRange(const CharSourceRange &Range) {
1885 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1886 E = Ranges.end();
1887 I != E; ++I) {
1888 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1889 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1890 return true;
1891 }
1892 return false;
1893 }
1894
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001895 static bool inputUsesCRLF(StringRef Text) {
1896 return Text.count('\r') * 2 > Text.count('\n');
1897 }
1898
Manuel Klimek71814b42013-10-11 21:25:45 +00001899 void
1900 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001901 unsigned CountBoundToVariable = 0;
1902 unsigned CountBoundToType = 0;
1903 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001904 bool HasBinPackedFunction = false;
1905 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001906 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001907 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001908 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001909 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001910 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001911 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001912 bool SpacesBefore =
1913 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1914 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1915 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001916 if (SpacesBefore && !SpacesAfter)
1917 ++CountBoundToVariable;
1918 else if (!SpacesBefore && SpacesAfter)
1919 ++CountBoundToType;
1920 }
1921
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001922 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1923 if (Tok->is(tok::coloncolon) &&
1924 Tok->Previous->Type == TT_TemplateOpener)
1925 HasCpp03IncompatibleFormat = true;
1926 if (Tok->Type == TT_TemplateCloser &&
1927 Tok->Previous->Type == TT_TemplateCloser)
1928 HasCpp03IncompatibleFormat = true;
1929 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001930
1931 if (Tok->PackingKind == PPK_BinPacked)
1932 HasBinPackedFunction = true;
1933 if (Tok->PackingKind == PPK_OnePerLine)
1934 HasOnePerLineFunction = true;
1935
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001936 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001937 }
1938 }
Daniel Jasper553d4872014-06-17 12:40:34 +00001939 if (Style.DerivePointerAlignment) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001940 if (CountBoundToType > CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00001941 Style.PointerAlignment = FormatStyle::PAS_Left;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001942 else if (CountBoundToType < CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00001943 Style.PointerAlignment = FormatStyle::PAS_Right;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001944 }
1945 if (Style.Standard == FormatStyle::LS_Auto) {
1946 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1947 : FormatStyle::LS_Cpp03;
1948 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001949 BinPackInconclusiveFunctions =
1950 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001951 }
1952
Craig Topperfb6b25b2014-03-15 04:29:04 +00001953 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001954 assert(!UnwrappedLines.empty());
1955 UnwrappedLines.back().push_back(TheLine);
1956 }
1957
Craig Topperfb6b25b2014-03-15 04:29:04 +00001958 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001959 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001960 }
1961
1962 FormatStyle Style;
1963 Lexer &Lex;
1964 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001965 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001966 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001967 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001968
1969 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001970 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001971};
1972
Craig Topperaf35e852013-06-30 22:29:28 +00001973} // end anonymous namespace
1974
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001975tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1976 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001977 std::vector<CharSourceRange> Ranges) {
Daniel Jasperc64b09a2014-05-22 15:12:22 +00001978 if (Style.DisableFormat) {
1979 tooling::Replacements EmptyResult;
1980 return EmptyResult;
1981 }
1982
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001983 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001984 return formatter.format();
1985}
1986
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001987tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1988 std::vector<tooling::Range> Ranges,
1989 StringRef FileName) {
1990 FileManager Files((FileSystemOptions()));
1991 DiagnosticsEngine Diagnostics(
1992 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1993 new DiagnosticOptions);
1994 SourceManager SourceMgr(Diagnostics, Files);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001995 std::unique_ptr<llvm::MemoryBuffer> Buf =
1996 llvm::MemoryBuffer::getMemBuffer(Code, FileName);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001997 const clang::FileEntry *Entry =
1998 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001999 SourceMgr.overrideFileContents(Entry, Buf.release());
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002000 FileID ID =
2001 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienko1e808872013-06-28 12:51:24 +00002002 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
2003 getFormattingLangOpts(Style.Standard));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002004 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
2005 std::vector<CharSourceRange> CharRanges;
2006 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
2007 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
2008 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
2009 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
2010 }
2011 return reformat(Style, Lex, SourceMgr, CharRanges);
2012}
2013
Alexander Kornienko1e808872013-06-28 12:51:24 +00002014LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002015 LangOptions LangOpts;
2016 LangOpts.CPlusPlus = 1;
Alexander Kornienko1e808872013-06-28 12:51:24 +00002017 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002018 LangOpts.CPlusPlus14 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00002019 LangOpts.LineComment = 1;
Nikola Smiljanice08a91e2014-05-08 00:05:13 +00002020 LangOpts.CXXOperatorNames = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002021 LangOpts.Bool = 1;
2022 LangOpts.ObjC1 = 1;
2023 LangOpts.ObjC2 = 1;
2024 return LangOpts;
2025}
2026
Edwin Vaned544aa72013-09-30 13:31:48 +00002027const char *StyleOptionHelpDescription =
2028 "Coding style, currently supports:\n"
2029 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
2030 "Use -style=file to load style configuration from\n"
2031 ".clang-format file located in one of the parent\n"
2032 "directories of the source file (or current\n"
2033 "directory for stdin).\n"
2034 "Use -style=\"{key: value, ...}\" to set specific\n"
2035 "parameters, e.g.:\n"
2036 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
2037
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002038static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002039 if (FileName.endswith_lower(".js")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002040 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00002041 } else if (FileName.endswith_lower(".proto") ||
2042 FileName.endswith_lower(".protodevel")) {
2043 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002044 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002045 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002046}
2047
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002048FormatStyle getStyle(StringRef StyleName, StringRef FileName,
2049 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002050 FormatStyle Style = getLLVMStyle();
2051 Style.Language = getLanguageByFileName(FileName);
2052 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002053 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
2054 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002055 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002056 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002057
2058 if (StyleName.startswith("{")) {
2059 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00002060 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002061 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
2062 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00002063 }
2064 return Style;
2065 }
2066
2067 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002068 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00002069 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
2070 << " style\n";
2071 return Style;
2072 }
2073
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002074 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002075 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00002076 SmallString<128> Path(FileName);
2077 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002078 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00002079 Directory = llvm::sys::path::parent_path(Directory)) {
2080 if (!llvm::sys::fs::is_directory(Directory))
2081 continue;
2082 SmallString<128> ConfigFile(Directory);
2083
2084 llvm::sys::path::append(ConfigFile, ".clang-format");
2085 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2086 bool IsFile = false;
2087 // Ignore errors from is_regular_file: we only need to know if we can read
2088 // the file or not.
2089 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2090
2091 if (!IsFile) {
2092 // Try _clang-format too, since dotfiles are not commonly used on Windows.
2093 ConfigFile = Directory;
2094 llvm::sys::path::append(ConfigFile, "_clang-format");
2095 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2096 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2097 }
2098
2099 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002100 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
2101 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
2102 if (std::error_code EC = Text.getError()) {
2103 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002104 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002105 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002106 if (std::error_code ec =
2107 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00002108 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002109 if (!UnsuitableConfigFiles.empty())
2110 UnsuitableConfigFiles.append(", ");
2111 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002112 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002113 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002114 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2115 << "\n";
2116 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002117 }
2118 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2119 return Style;
2120 }
2121 }
2122 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
2123 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002124 if (!UnsuitableConfigFiles.empty()) {
2125 llvm::errs() << "Configuration file(s) do(es) not support "
2126 << getLanguageName(Style.Language) << ": "
2127 << UnsuitableConfigFiles << "\n";
2128 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002129 return Style;
2130}
2131
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002132} // namespace format
2133} // namespace clang