blob: b9d13ab691e749912f2800376e3a4ef55544717f [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);
Daniel Jasperc58c70e2014-09-15 11:21:46 +000044 IO.enumCase(Value, "Java", FormatStyle::LK_Java);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000045 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
Daniel Jasper7052ce62014-01-19 09:04:08 +000046 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000047 }
48};
49
50template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
51 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
52 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
53 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
54 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
55 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
56 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
57 }
58};
59
60template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
61 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
62 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
63 IO.enumCase(Value, "false", FormatStyle::UT_Never);
64 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
65 IO.enumCase(Value, "true", FormatStyle::UT_Always);
66 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
67 }
68};
69
Daniel Jasperd74cf402014-04-08 12:46:38 +000070template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
71 static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
72 IO.enumCase(Value, "None", FormatStyle::SFS_None);
73 IO.enumCase(Value, "false", FormatStyle::SFS_None);
74 IO.enumCase(Value, "All", FormatStyle::SFS_All);
75 IO.enumCase(Value, "true", FormatStyle::SFS_All);
76 IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
77 }
78};
79
Daniel Jasperac043c92014-09-15 11:11:00 +000080template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
81 static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
82 IO.enumCase(Value, "All", FormatStyle::BOS_All);
83 IO.enumCase(Value, "true", FormatStyle::BOS_All);
84 IO.enumCase(Value, "None", FormatStyle::BOS_None);
85 IO.enumCase(Value, "false", FormatStyle::BOS_None);
86 IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
87 }
88};
89
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000090template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
91 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
92 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
93 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
94 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
95 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
Alexander Kornienko3a33f022013-12-12 09:49:52 +000096 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000097 }
98};
99
Alexander Kornienkod6538332013-05-07 15:32:14 +0000100template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000101struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000102 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000103 FormatStyle::NamespaceIndentationKind &Value) {
104 IO.enumCase(Value, "None", FormatStyle::NI_None);
105 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
106 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000107 }
108};
109
110template <>
Daniel Jasper553d4872014-06-17 12:40:34 +0000111struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
112 static void enumeration(IO &IO,
113 FormatStyle::PointerAlignmentStyle &Value) {
114 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
115 IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
116 IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
117
Alp Toker958027b2014-07-14 19:42:55 +0000118 // For backward compatibility.
Daniel Jasper553d4872014-06-17 12:40:34 +0000119 IO.enumCase(Value, "true", FormatStyle::PAS_Left);
120 IO.enumCase(Value, "false", FormatStyle::PAS_Right);
121 }
122};
123
124template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000125struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000126 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000127 FormatStyle::SpaceBeforeParensOptions &Value) {
128 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000129 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000130 FormatStyle::SBPO_ControlStatements);
131 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000132
133 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000134 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
135 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000136 }
137};
138
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000139template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000140 static void mapping(IO &IO, FormatStyle &Style) {
141 // When reading, read the language first, we need it for getPredefinedStyle.
142 IO.mapOptional("Language", Style.Language);
143
Alexander Kornienko49149672013-05-10 11:56:10 +0000144 if (IO.outputting()) {
Alexander Kornienkoe3648fb2013-09-02 16:39:23 +0000145 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000146 "Mozilla", "WebKit", "GNU" };
Alexander Kornienko49149672013-05-10 11:56:10 +0000147 ArrayRef<StringRef> Styles(StylesArray);
148 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
149 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000150 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000151 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000152 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000153 IO.mapOptional("# BasedOnStyle", StyleName);
154 break;
155 }
156 }
157 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000158 StringRef BasedOnStyle;
159 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000160 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000161 FormatStyle::LanguageKind OldLanguage = Style.Language;
162 FormatStyle::LanguageKind Language =
163 ((FormatStyle *)IO.getContext())->Language;
164 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000165 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
166 return;
167 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000168 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000169 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000170 }
171
172 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000173 IO.mapOptional("ConstructorInitializerIndentWidth",
174 Style.ConstructorInitializerIndentWidth);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000175 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000176 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000177 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
178 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000179 IO.mapOptional("AllowShortBlocksOnASingleLine",
180 Style.AllowShortBlocksOnASingleLine);
Daniel Jasperb87899b2014-09-10 13:11:45 +0000181 IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
182 Style.AllowShortCaseLabelsOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000183 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
184 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000185 IO.mapOptional("AllowShortLoopsOnASingleLine",
186 Style.AllowShortLoopsOnASingleLine);
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000187 IO.mapOptional("AllowShortFunctionsOnASingleLine",
188 Style.AllowShortFunctionsOnASingleLine);
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000189 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
190 Style.AlwaysBreakAfterDefinitionReturnType);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000191 IO.mapOptional("AlwaysBreakTemplateDeclarations",
192 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko58611712013-07-04 12:02:44 +0000193 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
194 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000195 IO.mapOptional("BreakBeforeBinaryOperators",
196 Style.BreakBeforeBinaryOperators);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000197 IO.mapOptional("BreakBeforeTernaryOperators",
198 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000199 IO.mapOptional("BreakConstructorInitializersBeforeComma",
200 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000201 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
Daniel Jasper18210d72014-10-09 09:52:05 +0000202 IO.mapOptional("BinPackArguments", Style.BinPackArguments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000203 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
204 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
205 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000206 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000207 IO.mapOptional("ExperimentalAutoDetectBinPacking",
208 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000209 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000210 IO.mapOptional("IndentWrappedFunctionNames",
211 Style.IndentWrappedFunctionNames);
212 IO.mapOptional("IndentFunctionDeclarationAfterType",
213 Style.IndentWrappedFunctionNames);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000214 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000215 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
216 Style.KeepEmptyLinesAtTheStartOfBlocks);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000217 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000218 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000219 IO.mapOptional("ObjCSpaceBeforeProtocolList",
220 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000221 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
222 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000223 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
224 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000225 IO.mapOptional("PenaltyBreakFirstLessLess",
226 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000227 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
228 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
229 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000230 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000231 IO.mapOptional("SpacesBeforeTrailingComments",
232 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000233 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000234 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000235 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000236 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000237 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000238 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000239 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperad981f82014-08-26 11:41:14 +0000240 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000241 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasperf110e202013-08-21 08:39:01 +0000242 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000243 IO.mapOptional("SpacesInCStyleCastParentheses",
244 Style.SpacesInCStyleCastParentheses);
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000245 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000246 IO.mapOptional("SpacesInContainerLiterals",
247 Style.SpacesInContainerLiterals);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000248 IO.mapOptional("SpaceBeforeAssignmentOperators",
249 Style.SpaceBeforeAssignmentOperators);
Daniel Jasper6633ab82013-10-18 10:38:14 +0000250 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000251 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000252 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000253
254 // For backward compatibility.
255 if (!IO.outputting()) {
256 IO.mapOptional("SpaceAfterControlStatementKeyword",
257 Style.SpaceBeforeParens);
Daniel Jasper553d4872014-06-17 12:40:34 +0000258 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
259 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000260 }
261 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000262 IO.mapOptional("DisableFormat", Style.DisableFormat);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000263 }
264};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000265
266// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000267// IO.getContext() should contain a pointer to the FormatStyle structure, that
268// will be used to get default values for missing keys.
269// If the first element has no Language specified, it will be treated as the
270// default one for the following elements.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000271template <> struct DocumentListTraits<std::vector<FormatStyle> > {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000272 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
273 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000274 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000275 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000276 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000277 if (Index >= Seq.size()) {
278 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000279 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000280 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000281 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000282 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000283 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000284 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000285 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000286 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000287 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000288 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000289 }
290};
Alexander Kornienkod6538332013-05-07 15:32:14 +0000291}
292}
293
Daniel Jasperf7935112012-12-03 18:12:45 +0000294namespace clang {
295namespace format {
296
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000297const std::error_category &getParseCategory() {
Rafael Espindolad0136702014-06-12 02:50:04 +0000298 static ParseErrorCategory C;
299 return C;
300}
301std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000302 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000303}
304
305const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
306 return "clang-format.parse_error";
307}
308
309std::string ParseErrorCategory::message(int EV) const {
310 switch (static_cast<ParseError>(EV)) {
311 case ParseError::Success:
312 return "Success";
313 case ParseError::Error:
314 return "Invalid argument";
315 case ParseError::Unsuitable:
316 return "Unsuitable";
317 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000318 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000319}
320
Daniel Jasperf7935112012-12-03 18:12:45 +0000321FormatStyle getLLVMStyle() {
322 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000323 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000324 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000325 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000326 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000327 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000328 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000329 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000330 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000331 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000332 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000333 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000334 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000335 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000336 LLVMStyle.BinPackParameters = true;
Daniel Jasper18210d72014-10-09 09:52:05 +0000337 LLVMStyle.BinPackArguments = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000338 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000339 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000340 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
341 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000342 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000343 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000344 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000345 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000346 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000347 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000348 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000349 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000350 LLVMStyle.ForEachMacros.push_back("foreach");
351 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
352 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000353 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000354 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000355 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000356 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000357 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000358 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000359 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000360 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000361 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000362 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000363 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000364 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000365 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000366 LLVMStyle.SpacesInParentheses = false;
Daniel Jasperad981f82014-08-26 11:41:14 +0000367 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000368 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000369 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000370 LLVMStyle.SpacesInCStyleCastParentheses = false;
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000371 LLVMStyle.SpaceAfterCStyleCast = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000372 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000373 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000374 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000375
Daniel Jasper19a541e2013-12-19 16:45:34 +0000376 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000377 LLVMStyle.PenaltyBreakFirstLessLess = 120;
378 LLVMStyle.PenaltyBreakString = 1000;
379 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000380 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000381 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000382
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000383 LLVMStyle.DisableFormat = false;
384
Daniel Jasperf7935112012-12-03 18:12:45 +0000385 return LLVMStyle;
386}
387
Nico Weber514ecc82014-02-02 20:50:45 +0000388FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000389 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000390 GoogleStyle.Language = Language;
391
Daniel Jasperf7935112012-12-03 18:12:45 +0000392 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000393 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000394 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000395 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000396 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000397 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000398 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000399 GoogleStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000400 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000401 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000402 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000403 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000404 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000405 GoogleStyle.SpacesBeforeTrailingComments = 2;
406 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000407
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000408 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000409 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000410
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000411 if (Language == FormatStyle::LK_Java) {
412 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
413 GoogleStyle.ColumnLimit = 100;
414 GoogleStyle.SpaceAfterCStyleCast = true;
415 } else if (Language == FormatStyle::LK_JavaScript) {
Nico Weber514ecc82014-02-02 20:50:45 +0000416 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000417 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000418 GoogleStyle.SpacesInContainerLiterals = false;
Daniel Jasper67f8ad22014-09-30 17:57:06 +0000419 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Nico Weber514ecc82014-02-02 20:50:45 +0000420 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000421 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000422 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000423 }
424
Daniel Jasperf7935112012-12-03 18:12:45 +0000425 return GoogleStyle;
426}
427
Nico Weber514ecc82014-02-02 20:50:45 +0000428FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
429 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Daniel Jasperf7db4332013-01-29 16:03:49 +0000430 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000431 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000432 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000433 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000434 ChromiumStyle.BinPackParameters = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000435 ChromiumStyle.DerivePointerAlignment = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000436 return ChromiumStyle;
437}
438
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000439FormatStyle getMozillaStyle() {
440 FormatStyle MozillaStyle = getLLVMStyle();
441 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000442 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000443 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000444 MozillaStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000445 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000446 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000447 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
448 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000449 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000450 MozillaStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000451 return MozillaStyle;
452}
453
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000454FormatStyle getWebKitStyle() {
455 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000456 Style.AccessModifierOffset = -4;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000457 Style.AlignTrailingComments = false;
Daniel Jasperac043c92014-09-15 11:11:00 +0000458 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000459 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000460 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000461 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000462 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000463 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000464 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000465 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000466 Style.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000467 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000468 return Style;
469}
470
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000471FormatStyle getGNUStyle() {
472 FormatStyle Style = getLLVMStyle();
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000473 Style.AlwaysBreakAfterDefinitionReturnType = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000474 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000475 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000476 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000477 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000478 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000479 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000480 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000481 return Style;
482}
483
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000484FormatStyle getNoStyle() {
485 FormatStyle NoStyle = getLLVMStyle();
486 NoStyle.DisableFormat = true;
487 return NoStyle;
488}
489
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000490bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
491 FormatStyle *Style) {
492 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000493 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000494 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000495 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000496 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000497 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000498 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000499 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000500 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000501 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000502 } else if (Name.equals_lower("gnu")) {
503 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000504 } else if (Name.equals_lower("none")) {
505 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000506 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000507 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000508 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000509
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000510 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000511 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000512}
513
Rafael Espindolac0809172014-06-12 14:02:15 +0000514std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000515 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000516 FormatStyle::LanguageKind Language = Style->Language;
517 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000518 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000519 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000520
521 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000522 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000523 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
524 // values for the fields, keys for which are missing from the configuration.
525 // Mapping also uses the context to get the language to find the correct
526 // base style.
527 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000528 Input >> Styles;
529 if (Input.error())
530 return Input.error();
531
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000532 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000533 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000534 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000535 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000536 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000537 for (unsigned j = 0; j < i; ++j) {
538 if (Styles[i].Language == Styles[j].Language) {
539 DEBUG(llvm::dbgs()
540 << "Duplicate languages in the config file on positions " << j
541 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000542 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000543 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000544 }
545 }
546 // Look for a suitable configuration starting from the end, so we can
547 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000548 // configuration (which can only be at slot 0) after it.
549 for (int i = Styles.size() - 1; i >= 0; --i) {
550 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000551 Styles[i].Language == FormatStyle::LK_None) {
552 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000553 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000554 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000555 }
556 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000557 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000558}
559
560std::string configurationAsText(const FormatStyle &Style) {
561 std::string Text;
562 llvm::raw_string_ostream Stream(Text);
563 llvm::yaml::Output Output(Stream);
564 // We use the same mapping method for input and output, so we need a non-const
565 // reference here.
566 FormatStyle NonConstStyle = Style;
567 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000568 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000569}
570
Craig Topperaf35e852013-06-30 22:29:28 +0000571namespace {
572
Daniel Jasperde0328a2013-08-16 11:20:30 +0000573class NoColumnLimitFormatter {
574public:
Daniel Jasperf110e202013-08-21 08:39:01 +0000575 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000576
577 /// \brief Formats the line starting at \p State, simply keeping all of the
578 /// input's line breaking decisions.
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000579 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000580 LineState State =
581 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Craig Topper2145bc02014-05-09 08:15:10 +0000582 while (State.NextToken) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000583 bool Newline =
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000584 Indenter->mustBreak(State) ||
Daniel Jasperde0328a2013-08-16 11:20:30 +0000585 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
586 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
587 }
588 }
Daniel Jasperf110e202013-08-21 08:39:01 +0000589
Daniel Jasperde0328a2013-08-16 11:20:30 +0000590private:
591 ContinuationIndenter *Indenter;
592};
593
Daniel Jasper56f8b432013-11-06 23:12:09 +0000594class LineJoiner {
595public:
596 LineJoiner(const FormatStyle &Style) : Style(Style) {}
597
598 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
599 unsigned
600 tryFitMultipleLinesInOne(unsigned Indent,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000601 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000602 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
603 // We can never merge stuff if there are trailing line comments.
Daniel Jasper234379f2013-12-24 13:31:25 +0000604 const AnnotatedLine *TheLine = *I;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000605 if (TheLine->Last->Type == TT_LineComment)
606 return 0;
607
Alexander Kornienkoecc232d2013-12-04 13:25:26 +0000608 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
609 return 0;
610
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000611 unsigned Limit =
612 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000613 // If we already exceed the column limit, we set 'Limit' to 0. The different
614 // tryMerge..() functions can then decide whether to still do merging.
615 Limit = TheLine->Last->TotalLength > Limit
616 ? 0
617 : Limit - TheLine->Last->TotalLength;
618
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000619 if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000620 return 0;
621
Daniel Jasperd74cf402014-04-08 12:46:38 +0000622 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
623 // If necessary, change to something smarter.
624 bool MergeShortFunctions =
625 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
626 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
627 TheLine->Level != 0);
628
Daniel Jasper234379f2013-12-24 13:31:25 +0000629 if (TheLine->Last->Type == TT_FunctionLBrace &&
630 TheLine->First != TheLine->Last) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000631 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000632 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000633 if (TheLine->Last->is(tok::l_brace)) {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000634 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000635 ? tryMergeSimpleBlock(I, E, Limit)
636 : 0;
637 }
638 if (I[1]->First->Type == TT_FunctionLBrace &&
639 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
Alp Tokerba5b4dc2013-12-30 02:06:29 +0000640 // Check for Limit <= 2 to account for the " {".
Daniel Jasper234379f2013-12-24 13:31:25 +0000641 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
642 return 0;
643 Limit -= 2;
644
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000645 unsigned MergedLines = 0;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000646 if (MergeShortFunctions) {
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000647 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
648 // If we managed to merge the block, count the function header, which is
649 // on a separate line.
650 if (MergedLines > 0)
651 ++MergedLines;
652 }
653 return MergedLines;
654 }
655 if (TheLine->First->is(tok::kw_if)) {
656 return Style.AllowShortIfStatementsOnASingleLine
657 ? tryMergeSimpleControlStatement(I, E, Limit)
658 : 0;
659 }
660 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
661 return Style.AllowShortLoopsOnASingleLine
662 ? tryMergeSimpleControlStatement(I, E, Limit)
663 : 0;
664 }
Daniel Jasperb87899b2014-09-10 13:11:45 +0000665 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
666 return Style.AllowShortCaseLabelsOnASingleLine
667 ? tryMergeShortCaseLabels(I, E, Limit)
668 : 0;
669 }
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000670 if (TheLine->InPPDirective &&
671 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000672 return tryMergeSimplePPDirective(I, E, Limit);
673 }
674 return 0;
675 }
676
677private:
678 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000679 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000680 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
681 unsigned Limit) {
682 if (Limit == 0)
683 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000684 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000685 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000686 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000687 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000688 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000689 return 0;
690 return 1;
691 }
692
693 unsigned tryMergeSimpleControlStatement(
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000694 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000695 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
696 if (Limit == 0)
697 return 0;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000698 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
699 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
Daniel Jasper17605d32014-05-14 09:33:35 +0000700 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000701 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000702 if (I[1]->InPPDirective != (*I)->InPPDirective ||
703 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000704 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000705 Limit = limitConsideringMacros(I + 1, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000706 AnnotatedLine &Line = **I;
707 if (Line.Last->isNot(tok::r_paren))
708 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000709 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000710 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000711 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000712 tok::kw_while) ||
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000713 I[1]->First->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000714 return 0;
715 // Only inline simple if's (no nested if or else).
716 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000717 I[2]->First->is(tok::kw_else))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000718 return 0;
719 return 1;
720 }
721
Daniel Jasperb87899b2014-09-10 13:11:45 +0000722 unsigned tryMergeShortCaseLabels(
723 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
724 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
725 if (Limit == 0 || I + 1 == E ||
726 I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
727 return 0;
728 unsigned NumStmts = 0;
729 unsigned Length = 0;
730 for (; NumStmts < 3; ++NumStmts) {
731 if (I + 1 + NumStmts == E)
732 break;
733 const AnnotatedLine *Line = I[1 + NumStmts];
734 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
735 break;
736 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
737 tok::kw_while))
738 return 0;
739 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
740 }
741 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
742 return 0;
743 return NumStmts;
744 }
745
Daniel Jasper56f8b432013-11-06 23:12:09 +0000746 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000747 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000748 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
749 unsigned Limit) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000750 AnnotatedLine &Line = **I;
Daniel Jasper17605d32014-05-14 09:33:35 +0000751
752 // Don't merge ObjC @ keywords and methods.
753 if (Line.First->isOneOf(tok::at, tok::minus, tok::plus))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000754 return 0;
755
Daniel Jasper17605d32014-05-14 09:33:35 +0000756 // Check that the current line allows merging. This depends on whether we
757 // are in a control flow statements as well as several style flags.
758 if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
759 return 0;
760 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
761 tok::kw_catch, tok::kw_for, tok::r_brace)) {
762 if (!Style.AllowShortBlocksOnASingleLine)
763 return 0;
764 if (!Style.AllowShortIfStatementsOnASingleLine &&
765 Line.First->is(tok::kw_if))
766 return 0;
767 if (!Style.AllowShortLoopsOnASingleLine &&
768 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
769 return 0;
770 // FIXME: Consider an option to allow short exception handling clauses on
771 // a single line.
772 if (Line.First->isOneOf(tok::kw_try, tok::kw_catch))
773 return 0;
774 }
775
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000776 FormatToken *Tok = I[1]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000777 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Craig Topper2145bc02014-05-09 08:15:10 +0000778 (Tok->getNextNonComment() == nullptr ||
Daniel Jasper56f8b432013-11-06 23:12:09 +0000779 Tok->getNextNonComment()->is(tok::semi))) {
780 // We merge empty blocks even if the line exceeds the column limit.
781 Tok->SpacesRequiredBefore = 0;
782 Tok->CanBreakBefore = true;
783 return 1;
784 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Daniel Jasper79dffb42014-05-07 09:48:30 +0000785 // We don't merge short records.
786 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
787 return 0;
788
Daniel Jasper56f8b432013-11-06 23:12:09 +0000789 // Check that we still have three lines and they fit into the limit.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000790 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000791 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000792 Limit = limitConsideringMacros(I + 2, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000793
794 if (!nextTwoLinesFitInto(I, Limit))
795 return 0;
796
797 // Second, check that the next line does not contain any braces - if it
798 // does, readability declines when putting it into a single line.
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000799 if (I[1]->Last->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000800 return 0;
801 do {
Daniel Jasperbd630732014-05-22 13:25:26 +0000802 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000803 return 0;
804 Tok = Tok->Next;
Craig Topper2145bc02014-05-09 08:15:10 +0000805 } while (Tok);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000806
Daniel Jasper79dffb42014-05-07 09:48:30 +0000807 // Last, check that the third line starts with a closing brace.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000808 Tok = I[2]->First;
Daniel Jasper79dffb42014-05-07 09:48:30 +0000809 if (Tok->isNot(tok::r_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000810 return 0;
811
812 return 2;
813 }
814 return 0;
815 }
816
Daniel Jasper64989962014-02-07 13:45:27 +0000817 /// Returns the modified column limit for \p I if it is inside a macro and
818 /// needs a trailing '\'.
819 unsigned
Daniel Jaspera0407742014-02-11 10:08:11 +0000820 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper64989962014-02-07 13:45:27 +0000821 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
822 unsigned Limit) {
823 if (I[0]->InPPDirective && I + 1 != E &&
824 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
825 return Limit < 2 ? 0 : Limit - 2;
826 }
827 return Limit;
828 }
829
Daniel Jasper56f8b432013-11-06 23:12:09 +0000830 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
831 unsigned Limit) {
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000832 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
833 return false;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000834 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000835 }
836
Daniel Jasper234379f2013-12-24 13:31:25 +0000837 bool containsMustBreak(const AnnotatedLine *Line) {
838 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
839 if (Tok->MustBreakBefore)
840 return true;
841 }
842 return false;
843 }
844
Daniel Jasper56f8b432013-11-06 23:12:09 +0000845 const FormatStyle &Style;
846};
847
Daniel Jasperf7935112012-12-03 18:12:45 +0000848class UnwrappedLineFormatter {
849public:
Daniel Jasper5500f612013-11-25 11:08:59 +0000850 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000851 WhitespaceManager *Whitespaces,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000852 const FormatStyle &Style)
Daniel Jasper5500f612013-11-25 11:08:59 +0000853 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
854 Joiner(Style) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000855
Daniel Jasper56f8b432013-11-06 23:12:09 +0000856 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper9c199562013-11-28 15:58:55 +0000857 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Daniel Jasperc359ad02014-04-15 08:13:47 +0000858 // Try to look up already computed penalty in DryRun-mode.
NAKAMURA Takumi22059522014-04-15 23:29:04 +0000859 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
860 &Lines, AdditionalIndent);
Daniel Jasperc359ad02014-04-15 08:13:47 +0000861 auto CacheIt = PenaltyCache.find(CacheKey);
862 if (DryRun && CacheIt != PenaltyCache.end())
863 return CacheIt->second;
864
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000865 assert(!Lines.empty());
866 unsigned Penalty = 0;
867 std::vector<int> IndentForLevel;
868 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
869 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Craig Topper2145bc02014-05-09 08:15:10 +0000870 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000871 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
872 E = Lines.end();
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000873 I != E; ++I) {
874 const AnnotatedLine &TheLine = **I;
875 const FormatToken *FirstTok = TheLine.First;
876 int Offset = getIndentOffset(*FirstTok);
877
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000878 // Determine indent and try to merge multiple unwrapped lines.
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000879 unsigned Indent;
880 if (TheLine.InPPDirective) {
881 Indent = TheLine.Level * Style.IndentWidth;
882 } else {
883 while (IndentForLevel.size() <= TheLine.Level)
884 IndentForLevel.push_back(-1);
885 IndentForLevel.resize(TheLine.Level + 1);
886 Indent = getIndent(IndentForLevel, TheLine.Level);
887 }
888 unsigned LevelIndent = Indent;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000889 if (static_cast<int>(Indent) + Offset >= 0)
890 Indent += Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000891
892 // Merge multiple lines if possible.
Daniel Jasper56f8b432013-11-06 23:12:09 +0000893 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
Alexander Kornienko31e95542013-12-04 12:21:08 +0000894 if (MergedLines > 0 && Style.ColumnLimit == 0) {
895 // Disallow line merging if there is a break at the start of one of the
896 // input lines.
897 for (unsigned i = 0; i < MergedLines; ++i) {
898 if (I[i + 1]->First->NewlinesBefore > 0)
899 MergedLines = 0;
900 }
901 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000902 if (!DryRun) {
903 for (unsigned i = 0; i < MergedLines; ++i) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000904 join(*I[i], *I[i + 1]);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000905 }
906 }
907 I += MergedLines;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000908
Daniel Jasper9c199562013-11-28 15:58:55 +0000909 bool FixIndentation =
910 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000911 if (TheLine.First->is(tok::eof)) {
Daniel Jasper5500f612013-11-25 11:08:59 +0000912 if (PreviousLine && PreviousLine->Affected && !DryRun) {
913 // Remove the file's trailing whitespace.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000914 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
915 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
916 /*IndentLevel=*/0, /*Spaces=*/0,
917 /*TargetColumn=*/0);
918 }
Daniel Jasper9c199562013-11-28 15:58:55 +0000919 } else if (TheLine.Type != LT_Invalid &&
920 (TheLine.Affected || FixIndentation)) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000921 if (FirstTok->WhitespaceRange.isValid()) {
922 if (!DryRun)
923 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
924 Indent, TheLine.InPPDirective);
925 } else {
926 Indent = LevelIndent = FirstTok->OriginalColumn;
927 }
928
929 // If everything fits on a single line, just put it there.
930 unsigned ColumnLimit = Style.ColumnLimit;
931 if (I + 1 != E) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000932 AnnotatedLine *NextLine = I[1];
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000933 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
934 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
935 }
936
937 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
938 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000939 while (State.NextToken) {
940 formatChildren(State, /*Newline=*/false, /*DryRun=*/false, Penalty);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000941 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000942 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000943 } else if (Style.ColumnLimit == 0) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000944 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000945 NoColumnLimitFormatter Formatter(Indenter);
946 if (!DryRun)
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000947 Formatter.format(Indent, &TheLine);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000948 } else {
949 Penalty += format(TheLine, Indent, DryRun);
950 }
951
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000952 if (!TheLine.InPPDirective)
953 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper9c199562013-11-28 15:58:55 +0000954 } else if (TheLine.ChildrenAffected) {
955 format(TheLine.Children, DryRun);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000956 } else {
957 // Format the first token if necessary, and notify the WhitespaceManager
958 // about the unchanged whitespace.
Craig Topper2145bc02014-05-09 08:15:10 +0000959 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000960 if (Tok == TheLine.First &&
961 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
962 unsigned LevelIndent = Tok->OriginalColumn;
963 if (!DryRun) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000964 // Remove trailing whitespace of the previous line.
Daniel Jasper5500f612013-11-25 11:08:59 +0000965 if ((PreviousLine && PreviousLine->Affected) ||
966 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000967 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
968 TheLine.InPPDirective);
969 } else {
970 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
971 }
972 }
973
974 if (static_cast<int>(LevelIndent) - Offset >= 0)
975 LevelIndent -= Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000976 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000977 IndentForLevel[TheLine.Level] = LevelIndent;
978 } else if (!DryRun) {
979 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
980 }
981 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000982 }
983 if (!DryRun) {
Craig Topper2145bc02014-05-09 08:15:10 +0000984 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000985 Tok->Finalized = true;
986 }
987 }
988 PreviousLine = *I;
989 }
Daniel Jasperc359ad02014-04-15 08:13:47 +0000990 PenaltyCache[CacheKey] = Penalty;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000991 return Penalty;
992 }
993
994private:
995 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000996 ///
997 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000998 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
999 bool DryRun) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001000 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +00001001
Daniel Jasperacc33662013-02-08 08:22:00 +00001002 // If the ObjC method declaration does not fit on a line, we should format
1003 // it with one arg per line.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001004 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperacc33662013-02-08 08:22:00 +00001005 State.Stack.back().BreakBeforeParameter = true;
1006
Daniel Jasper4b866272013-02-01 11:00:45 +00001007 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001008 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +00001009 }
1010
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001011 /// \brief An edge in the solution space from \c Previous->State to \c State,
1012 /// inserting a newline dependent on the \c NewLine.
1013 struct StateNode {
1014 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001015 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001016 LineState State;
1017 bool NewLine;
1018 StateNode *Previous;
1019 };
Daniel Jasper4b866272013-02-01 11:00:45 +00001020
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001021 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
1022 ///
1023 /// In case of equal penalties, we want to prefer states that were inserted
1024 /// first. During state generation we make sure that we insert states first
1025 /// that break the line as late as possible.
1026 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1027
1028 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
1029 /// \c State has the given \c OrderedPenalty.
1030 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1031
1032 /// \brief The BFS queue type.
1033 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1034 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +00001035
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001036 /// \brief Get the offset of the line relatively to the level.
1037 ///
1038 /// For example, 'public:' labels in classes are offset by 1 or 2
1039 /// characters to the left from their level.
1040 int getIndentOffset(const FormatToken &RootToken) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001041 if (Style.Language == FormatStyle::LK_Java)
1042 return 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001043 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
1044 return Style.AccessModifierOffset;
1045 return 0;
1046 }
1047
1048 /// \brief Add a new line and the required indent before the first Token
1049 /// of the \c UnwrappedLine if there was no structural parsing error.
1050 void formatFirstToken(FormatToken &RootToken,
1051 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
1052 unsigned Indent, bool InPPDirective) {
1053 unsigned Newlines =
1054 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1055 // Remove empty lines before "}" where applicable.
1056 if (RootToken.is(tok::r_brace) &&
1057 (!RootToken.Next ||
1058 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1059 Newlines = std::min(Newlines, 1u);
1060 if (Newlines == 0 && !RootToken.IsFirst)
1061 Newlines = 1;
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001062 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1063 Newlines = 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001064
Daniel Jasper11164bd2014-03-21 12:58:53 +00001065 // Remove empty lines after "{".
Daniel Jaspera26fc5c2014-03-21 13:43:14 +00001066 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1067 PreviousLine->Last->is(tok::l_brace) &&
Daniel Jasper01b35482014-03-21 13:03:33 +00001068 PreviousLine->First->isNot(tok::kw_namespace))
Daniel Jasper11164bd2014-03-21 12:58:53 +00001069 Newlines = 1;
1070
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001071 // Insert extra new line before access specifiers.
1072 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1073 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1074 ++Newlines;
1075
1076 // Remove empty lines after access specifiers.
1077 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
1078 Newlines = std::min(1u, Newlines);
1079
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001080 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
1081 Indent, InPPDirective &&
1082 !RootToken.HasUnescapedNewline);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001083 }
1084
1085 /// \brief Get the indent of \p Level from \p IndentForLevel.
1086 ///
1087 /// \p IndentForLevel must contain the indent for the level \c l
1088 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1089 /// that level is unknown.
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001090 unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001091 if (IndentForLevel[Level] != -1)
1092 return IndentForLevel[Level];
1093 if (Level == 0)
1094 return 0;
1095 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
1096 }
1097
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001098 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1099 assert(!A.Last->Next);
1100 assert(!B.First->Previous);
Daniel Jasper5500f612013-11-25 11:08:59 +00001101 if (B.Affected)
1102 A.Affected = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001103 A.Last->Next = B.First;
1104 B.First->Previous = A.Last;
Daniel Jasper98fb6e12013-11-08 17:33:27 +00001105 B.First->CanBreakBefore = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001106 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1107 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1108 Tok->TotalLength += LengthA;
1109 A.Last = Tok;
1110 }
1111 }
1112
1113 unsigned getColumnLimit(bool InPPDirective) const {
1114 // In preprocessor directives reserve two chars for trailing " \"
1115 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1116 }
1117
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001118 struct CompareLineStatePointers {
1119 bool operator()(LineState *obj1, LineState *obj2) const {
1120 return *obj1 < *obj2;
1121 }
1122 };
1123
Daniel Jasper4b866272013-02-01 11:00:45 +00001124 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +00001125 ///
Daniel Jasper4b866272013-02-01 11:00:45 +00001126 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1127 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1128 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001129 /// to a state where all tokens are placed. Returns the penalty.
1130 ///
1131 /// If \p DryRun is \c false, directly applies the changes.
1132 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001133 std::set<LineState *, CompareLineStatePointers> Seen;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001134
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001135 // Increasing count of \c StateNode items we have created. This is used to
1136 // create a deterministic order independent of the container.
1137 unsigned Count = 0;
1138 QueueType Queue;
1139
Daniel Jasper4b866272013-02-01 11:00:45 +00001140 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001141 StateNode *Node =
Craig Topper2145bc02014-05-09 08:15:10 +00001142 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001143 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1144 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001145
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001146 unsigned Penalty = 0;
1147
Daniel Jasper4b866272013-02-01 11:00:45 +00001148 // While not empty, take first element and follow edges.
1149 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001150 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001151 StateNode *Node = Queue.top().second;
Craig Topper2145bc02014-05-09 08:15:10 +00001152 if (!Node->State.NextToken) {
Alexander Kornienko49149672013-05-10 11:56:10 +00001153 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001154 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001155 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001156 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001157
Daniel Jasperf8114cf2013-05-22 05:27:42 +00001158 // Cut off the analysis of certain solutions if the analysis gets too
1159 // complex. See description of IgnoreStackForComparison.
1160 if (Count > 10000)
1161 Node->State.IgnoreStackForComparison = true;
1162
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001163 if (!Seen.insert(&Node->State).second)
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001164 // State already examined with lower penalty.
1165 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001166
Manuel Klimek71814b42013-10-11 21:25:45 +00001167 FormatDecision LastFormat = Node->State.NextToken->Decision;
1168 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001169 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimek71814b42013-10-11 21:25:45 +00001170 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001171 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper4b866272013-02-01 11:00:45 +00001172 }
1173
Manuel Klimek71814b42013-10-11 21:25:45 +00001174 if (Queue.empty()) {
Daniel Jasper4b866272013-02-01 11:00:45 +00001175 // We were unable to find a solution, do nothing.
1176 // FIXME: Add diagnostic?
Manuel Klimek71814b42013-10-11 21:25:45 +00001177 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001178 return 0;
Manuel Klimek71814b42013-10-11 21:25:45 +00001179 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001180
Daniel Jasper4b866272013-02-01 11:00:45 +00001181 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001182 if (!DryRun)
1183 reconstructPath(InitialState, Queue.top().second);
1184
Alexander Kornienko49149672013-05-10 11:56:10 +00001185 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1186 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001187
1188 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001189 }
1190
1191 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001192 std::deque<StateNode *> Path;
1193 // We do not need a break before the initial token.
1194 while (Current->Previous) {
1195 Path.push_front(Current);
1196 Current = Current->Previous;
1197 }
1198 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1199 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001200 unsigned Penalty = 0;
1201 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1202 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1203
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001204 DEBUG({
1205 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001206 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001207 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001208 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001209 }
1210 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001211 }
Daniel Jasper4b866272013-02-01 11:00:45 +00001212 }
1213
Manuel Klimekaf491072013-02-13 10:54:19 +00001214 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001215 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001216 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001217 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001218 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001219 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001220 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001221 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001222 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001223 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001224
1225 StateNode *Node = new (Allocator.Allocate())
1226 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001227 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1228 return;
1229
Daniel Jasperde0328a2013-08-16 11:20:30 +00001230 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001231
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001232 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1233 ++(*Count);
Daniel Jasper4b866272013-02-01 11:00:45 +00001234 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001235
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001236 /// \brief If the \p State's next token is an r_brace closing a nested block,
1237 /// format the nested block before it.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001238 ///
1239 /// Returns \c true if all children could be placed successfully and adapts
1240 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1241 /// creates changes using \c Whitespaces.
1242 ///
1243 /// The crucial idea here is that children always get formatted upon
1244 /// encountering the closing brace right after the nested block. Now, if we
1245 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1246 /// \c false), the entire block has to be kept on the same line (which is only
1247 /// possible if it fits on the line, only contains a single statement, etc.
1248 ///
1249 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1250 /// break after the "{", format all lines with correct indentation and the put
1251 /// the closing "}" on yet another new line.
1252 ///
1253 /// This enables us to keep the simple structure of the
1254 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1255 /// break or don't break.
1256 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1257 unsigned &Penalty) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001258 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001259 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1260 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1261 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001262 // The previous token does not open a block. Nothing to do. We don't
1263 // assert so that we can simply call this function for all tokens.
Daniel Jasper36c28ce2013-09-06 08:54:24 +00001264 return true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001265
1266 if (NewLine) {
Daniel Jasper58cb2ed2014-06-06 13:49:04 +00001267 int AdditionalIndent =
1268 State.FirstIndent - State.Line->Level * Style.IndentWidth;
Daniel Jasperb16b9692014-05-21 12:51:23 +00001269 if (State.Stack.size() < 2 ||
1270 !State.Stack[State.Stack.size() - 2].JSFunctionInlined) {
1271 AdditionalIndent = State.Stack.back().Indent -
1272 Previous.Children[0]->Level * Style.IndentWidth;
1273 }
1274
Daniel Jasper9c199562013-11-28 15:58:55 +00001275 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1276 /*FixBadIndentation=*/true);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001277 return true;
1278 }
1279
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001280 // Cannot merge multiple statements into a single line.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001281 if (Previous.Children.size() > 1)
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001282 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001283
Daniel Jasper21397a32014-04-09 12:21:48 +00001284 // Cannot merge into one line if this line ends on a comment.
1285 if (Previous.is(tok::comment))
1286 return false;
1287
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001288 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001289 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001290 return false;
1291
Daniel Jasper98583d52014-04-15 08:28:06 +00001292 // If the child line exceeds the column limit, we wouldn't want to merge it.
1293 // We add +2 for the trailing " }".
1294 if (Style.ColumnLimit > 0 &&
1295 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
1296 Style.ColumnLimit)
1297 return false;
1298
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001299 if (!DryRun) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001300 Whitespaces->replaceWhitespace(
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001301 *Previous.Children[0]->First,
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001302 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001303 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001304 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001305 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001306
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001307 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001308 return true;
1309 }
1310
Daniel Jasperde0328a2013-08-16 11:20:30 +00001311 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001312 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001313 FormatStyle Style;
Daniel Jasper56f8b432013-11-06 23:12:09 +00001314 LineJoiner Joiner;
Manuel Klimekaf491072013-02-13 10:54:19 +00001315
1316 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperc359ad02014-04-15 08:13:47 +00001317
1318 // Cache to store the penalty of formatting a vector of AnnotatedLines
1319 // starting from a specific additional offset. Improves performance if there
1320 // are many nested blocks.
1321 std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
1322 unsigned> PenaltyCache;
Daniel Jasperf7935112012-12-03 18:12:45 +00001323};
1324
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001325class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001326public:
Daniel Jasper23376252014-09-09 14:37:39 +00001327 FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001328 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +00001329 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
Daniel Jasper23376252014-09-09 14:37:39 +00001330 Column(0), TrailingWhitespace(0),
1331 SourceMgr(SourceMgr), ID(ID), Style(Style),
1332 IdentTable(getFormattingLangOpts(Style)), Encoding(Encoding),
1333 FirstInLineIndex(0), FormattingDisabled(false) {
1334 Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
1335 getFormattingLangOpts(Style)));
1336 Lex->SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +00001337
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001338 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +00001339 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1340 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001341 }
1342
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001343 ArrayRef<FormatToken *> lex() {
1344 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +00001345 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001346 do {
1347 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001348 tryMergePreviousTokens();
Manuel Klimek68b03042014-04-14 09:14:11 +00001349 if (Tokens.back()->NewlinesBefore > 0)
1350 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001351 } while (Tokens.back()->Tok.isNot(tok::eof));
1352 return Tokens;
1353 }
1354
1355 IdentifierTable &getIdentTable() { return IdentTable; }
1356
1357private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001358 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001359 if (tryMerge_TMacro())
1360 return;
Manuel Klimek68b03042014-04-14 09:14:11 +00001361 if (tryMergeConflictMarkers())
1362 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001363
1364 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001365 if (tryMergeJSRegexLiteral())
1366 return;
Daniel Jasper23376252014-09-09 14:37:39 +00001367 if (tryMergeEscapeSequence())
1368 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001369
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001370 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1371 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1372 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1373 tok::greaterequal };
Daniel Jasper78214392014-05-19 07:27:02 +00001374 static tok::TokenKind JSRightArrow[] = { tok::equal, tok::greater };
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001375 // FIXME: We probably need to change token type to mimic operator with the
1376 // correct priority.
1377 if (tryMergeTokens(JSIdentity))
1378 return;
1379 if (tryMergeTokens(JSNotIdentity))
1380 return;
1381 if (tryMergeTokens(JSShiftEqual))
1382 return;
Daniel Jasper78214392014-05-19 07:27:02 +00001383 if (tryMergeTokens(JSRightArrow))
1384 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001385 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001386 }
1387
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001388 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1389 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001390 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001391
1392 SmallVectorImpl<FormatToken *>::const_iterator First =
1393 Tokens.end() - Kinds.size();
1394 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001395 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001396 unsigned AddLength = 0;
1397 for (unsigned i = 1; i < Kinds.size(); ++i) {
1398 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1399 First[i]->WhitespaceRange.getEnd())
1400 return false;
1401 AddLength += First[i]->TokenText.size();
1402 }
1403 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1404 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1405 First[0]->TokenText.size() + AddLength);
1406 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001407 return true;
1408 }
1409
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001410 // Tries to merge an escape sequence, i.e. a "\\" and the following
Alp Tokerc3f36af2014-05-15 01:35:53 +00001411 // character. Use e.g. inside JavaScript regex literals.
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001412 bool tryMergeEscapeSequence() {
1413 if (Tokens.size() < 2)
1414 return false;
1415 FormatToken *Previous = Tokens[Tokens.size() - 2];
1416 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\" ||
1417 Tokens.back()->NewlinesBefore != 0)
1418 return false;
1419 Previous->ColumnWidth += Tokens.back()->ColumnWidth;
1420 StringRef Text = Previous->TokenText;
1421 Previous->TokenText =
1422 StringRef(Text.data(), Text.size() + Tokens.back()->TokenText.size());
1423 Tokens.resize(Tokens.size() - 1);
1424 return true;
1425 }
1426
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001427 // Try to determine whether the current token ends a JavaScript regex literal.
1428 // We heuristically assume that this is a regex literal if we find two
1429 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +00001430 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
1431 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001432 bool tryMergeJSRegexLiteral() {
Daniel Jasper23376252014-09-09 14:37:39 +00001433 if (Tokens.size() < 2)
1434 return false;
1435 // If a regex literal ends in "\//", this gets represented by an unknown
1436 // token "\" and a comment.
1437 bool MightEndWithEscapedSlash =
1438 Tokens.back()->is(tok::comment) &&
1439 Tokens.back()->TokenText.startswith("//") &&
1440 Tokens[Tokens.size() - 2]->TokenText == "\\";
1441 if (!MightEndWithEscapedSlash &&
1442 (Tokens.back()->isNot(tok::slash) ||
1443 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
1444 Tokens[Tokens.size() - 2]->TokenText == "\\")))
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001445 return false;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001446 unsigned TokenCount = 0;
1447 unsigned LastColumn = Tokens.back()->OriginalColumn;
1448 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
1449 ++TokenCount;
1450 if (I[0]->is(tok::slash) && I + 1 != E &&
1451 (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
1452 tok::exclaim, tok::l_square, tok::colon, tok::comma,
1453 tok::question, tok::kw_return) ||
1454 I[1]->isBinaryOperator())) {
Daniel Jasper23376252014-09-09 14:37:39 +00001455 if (MightEndWithEscapedSlash) {
1456 StringRef Buffer = SourceMgr.getBufferData(ID);
1457 // This regex literal ends in '\//'. Skip past the '//' of the last
1458 // token and re-start lexing from there.
1459 int offset =
1460 SourceMgr.getFileOffset(Tokens.back()->Tok.getLocation()) + 2;
1461 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1462 getFormattingLangOpts(Style), Buffer.begin(),
1463 Buffer.begin() + offset, Buffer.end()));
1464 Lex->SetKeepWhitespaceMode(true);
1465 }
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001466 Tokens.resize(Tokens.size() - TokenCount);
1467 Tokens.back()->Tok.setKind(tok::unknown);
1468 Tokens.back()->Type = TT_RegexLiteral;
1469 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
1470 return true;
1471 }
1472
1473 // There can't be a newline inside a regex literal.
1474 if (I[0]->NewlinesBefore > 0)
1475 return false;
1476 }
1477 return false;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001478 }
1479
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001480 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001481 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001482 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001483 FormatToken *Last = Tokens.back();
1484 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001485 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001486
1487 FormatToken *String = Tokens[Tokens.size() - 2];
1488 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001489 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001490
1491 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001492 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001493
1494 FormatToken *Macro = Tokens[Tokens.size() - 4];
1495 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001496 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001497
1498 const char *Start = Macro->TokenText.data();
1499 const char *End = Last->TokenText.data() + Last->TokenText.size();
1500 String->TokenText = StringRef(Start, End - Start);
1501 String->IsFirst = Macro->IsFirst;
1502 String->LastNewlineOffset = Macro->LastNewlineOffset;
1503 String->WhitespaceRange = Macro->WhitespaceRange;
1504 String->OriginalColumn = Macro->OriginalColumn;
1505 String->ColumnWidth = encoding::columnWidthWithTabs(
1506 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1507
1508 Tokens.pop_back();
1509 Tokens.pop_back();
1510 Tokens.pop_back();
1511 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001512 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001513 }
1514
Manuel Klimek68b03042014-04-14 09:14:11 +00001515 bool tryMergeConflictMarkers() {
1516 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1517 return false;
1518
1519 // Conflict lines look like:
1520 // <marker> <text from the vcs>
1521 // For example:
1522 // >>>>>>> /file/in/file/system at revision 1234
1523 //
1524 // We merge all tokens in a line that starts with a conflict marker
1525 // into a single token with a special token type that the unwrapped line
1526 // parser will use to correctly rebuild the underlying code.
1527
1528 FileID ID;
1529 // Get the position of the first token in the line.
1530 unsigned FirstInLineOffset;
1531 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1532 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1533 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1534 // Calculate the offset of the start of the current line.
1535 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1536 if (LineOffset == StringRef::npos) {
1537 LineOffset = 0;
1538 } else {
1539 ++LineOffset;
1540 }
1541
1542 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1543 StringRef LineStart;
1544 if (FirstSpace == StringRef::npos) {
1545 LineStart = Buffer.substr(LineOffset);
1546 } else {
1547 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1548 }
1549
1550 TokenType Type = TT_Unknown;
1551 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1552 Type = TT_ConflictStart;
1553 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1554 LineStart == "====") {
1555 Type = TT_ConflictAlternative;
1556 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1557 Type = TT_ConflictEnd;
1558 }
1559
1560 if (Type != TT_Unknown) {
1561 FormatToken *Next = Tokens.back();
1562
1563 Tokens.resize(FirstInLineIndex + 1);
1564 // We do not need to build a complete token here, as we will skip it
1565 // during parsing anyway (as we must not touch whitespace around conflict
1566 // markers).
1567 Tokens.back()->Type = Type;
1568 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1569
1570 Tokens.push_back(Next);
1571 return true;
1572 }
1573
1574 return false;
1575 }
1576
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001577 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001578 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001579 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +00001580 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001581 Token Greater = FormatTok->Tok;
1582 FormatTok = new (Allocator.Allocate()) FormatToken;
1583 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001584 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001585 FormatTok->Tok.getLocation().getLocWithOffset(1);
1586 FormatTok->WhitespaceRange =
1587 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001588 FormatTok->TokenText = ">";
Alexander Kornienko39856b72013-09-10 09:38:25 +00001589 FormatTok->ColumnWidth = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001590 GreaterStashed = false;
1591 return FormatTok;
1592 }
1593
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001594 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001595 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001596 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001597 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001598 FormatTok->IsFirst = IsFirstToken;
1599 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001600
1601 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001602 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001603 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001604 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1605 switch (FormatTok->TokenText[i]) {
1606 case '\n':
1607 ++FormatTok->NewlinesBefore;
1608 // FIXME: This is technically incorrect, as it could also
1609 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001610 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1611 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1612 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +00001613 FormatTok->HasUnescapedNewline = true;
1614 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1615 Column = 0;
1616 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001617 case '\r':
1618 case '\f':
1619 case '\v':
1620 Column = 0;
1621 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001622 case ' ':
1623 ++Column;
1624 break;
1625 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001626 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001627 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001628 case '\\':
1629 ++Column;
1630 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1631 FormatTok->TokenText[i + 1] != '\n'))
1632 FormatTok->Type = TT_ImplicitStringLiteral;
1633 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001634 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001635 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001636 ++Column;
1637 break;
1638 }
1639 }
1640
Daniel Jasper877615c2013-10-11 19:45:02 +00001641 if (FormatTok->Type == TT_ImplicitStringLiteral)
1642 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001643 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001644
Daniel Jasper8369aa52013-07-16 20:28:33 +00001645 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001646 }
Manuel Klimekef920692013-01-07 07:56:50 +00001647
Manuel Klimek1abf7892013-01-04 23:34:14 +00001648 // In case the token starts with escaped newlines, we want to
1649 // take them into account as whitespace - this pattern is quite frequent
1650 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001651 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001652 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1653 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001654 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001655 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001656 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001657 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001658 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001659
1660 FormatTok->WhitespaceRange = SourceRange(
1661 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1662
Manuel Klimek31c85922013-08-29 15:21:40 +00001663 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001664
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001665 TrailingWhitespace = 0;
1666 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001667 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001668 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001669 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001670 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001671 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001672 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001673 FormatTok->Tok.setIdentifierInfo(&Info);
1674 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001675 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001676 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001677 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001678 GreaterStashed = true;
1679 }
1680
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001681 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001682
Alexander Kornienko39856b72013-09-10 09:38:25 +00001683 StringRef Text = FormatTok->TokenText;
1684 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001685 if (FirstNewlinePos == StringRef::npos) {
1686 // FIXME: ColumnWidth actually depends on the start column, we need to
1687 // take this into account when the token is moved.
1688 FormatTok->ColumnWidth =
1689 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1690 Column += FormatTok->ColumnWidth;
1691 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001692 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001693 // FIXME: ColumnWidth actually depends on the start column, we need to
1694 // take this into account when the token is moved.
1695 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1696 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1697
Alexander Kornienko39856b72013-09-10 09:38:25 +00001698 // The last line of the token always starts in column 0.
1699 // Thus, the length can be precomputed even in the presence of tabs.
1700 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1701 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1702 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001703 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001704 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001705
Daniel Jaspere1e43192014-04-01 12:55:11 +00001706 FormatTok->IsForEachMacro =
1707 std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1708 FormatTok->Tok.getIdentifierInfo());
1709
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001710 return FormatTok;
1711 }
1712
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001713 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001714 bool IsFirstToken;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001715 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001716 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001717 unsigned TrailingWhitespace;
Daniel Jasper23376252014-09-09 14:37:39 +00001718 std::unique_ptr<Lexer> Lex;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001719 SourceManager &SourceMgr;
Daniel Jasper23376252014-09-09 14:37:39 +00001720 FileID ID;
Manuel Klimek31c85922013-08-29 15:21:40 +00001721 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001722 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001723 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001724 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001725 // Index (in 'Tokens') of the last token that starts a new line.
1726 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001727 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001728 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001729
NAKAMURA Takumi7160c4d2014-08-06 16:53:13 +00001730 bool FormattingDisabled;
Daniel Jasper471894432014-08-06 13:40:26 +00001731
Daniel Jasper8369aa52013-07-16 20:28:33 +00001732 void readRawToken(FormatToken &Tok) {
Daniel Jasper23376252014-09-09 14:37:39 +00001733 Lex->LexFromRawLexer(Tok.Tok);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001734 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1735 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001736 // For formatting, treat unterminated string literals like normal string
1737 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001738 if (Tok.is(tok::unknown)) {
1739 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1740 Tok.Tok.setKind(tok::string_literal);
1741 Tok.IsUnterminatedLiteral = true;
1742 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1743 Tok.TokenText == "''") {
1744 Tok.Tok.setKind(tok::char_constant);
1745 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001746 }
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001747
1748 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1749 Tok.TokenText == "/* clang-format on */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001750 FormattingDisabled = false;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001751 }
1752
Daniel Jasper471894432014-08-06 13:40:26 +00001753 Tok.Finalized = FormattingDisabled;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001754
1755 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1756 Tok.TokenText == "/* clang-format off */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001757 FormattingDisabled = true;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001758 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001759 }
1760};
1761
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001762static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1763 switch (Language) {
1764 case FormatStyle::LK_Cpp:
1765 return "C++";
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001766 case FormatStyle::LK_Java:
1767 return "Java";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001768 case FormatStyle::LK_JavaScript:
1769 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001770 case FormatStyle::LK_Proto:
1771 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001772 default:
1773 return "Unknown";
1774 }
1775}
1776
Daniel Jasperf7935112012-12-03 18:12:45 +00001777class Formatter : public UnwrappedLineConsumer {
1778public:
Daniel Jasper23376252014-09-09 14:37:39 +00001779 Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001780 ArrayRef<CharSourceRange> Ranges)
Daniel Jasper23376252014-09-09 14:37:39 +00001781 : Style(Style), ID(ID), SourceMgr(SourceMgr),
1782 Whitespaces(SourceMgr, Style,
1783 inputUsesCRLF(SourceMgr.getBufferData(ID))),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001784 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Daniel Jasper23376252014-09-09 14:37:39 +00001785 Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001786 DEBUG(llvm::dbgs() << "File encoding: "
1787 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1788 : "unknown")
1789 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001790 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1791 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001792 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001793
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001794 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001795 tooling::Replacements Result;
Daniel Jasper23376252014-09-09 14:37:39 +00001796 FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001797
1798 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001799 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001800 assert(UnwrappedLines.rbegin()->empty());
1801 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1802 ++Run) {
1803 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1804 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1805 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1806 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1807 }
1808 tooling::Replacements RunResult =
1809 format(AnnotatedLines, StructuralError, Tokens);
1810 DEBUG({
1811 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1812 for (tooling::Replacements::iterator I = RunResult.begin(),
1813 E = RunResult.end();
1814 I != E; ++I) {
1815 llvm::dbgs() << I->toString() << "\n";
1816 }
1817 });
1818 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1819 delete AnnotatedLines[i];
1820 }
1821 Result.insert(RunResult.begin(), RunResult.end());
1822 Whitespaces.reset();
1823 }
1824 return Result;
1825 }
1826
1827 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1828 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001829 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001830 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001831 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001832 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001833 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001834 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001835 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001836 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001837 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001838
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001839 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001840 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1841 BinPackInconclusiveFunctions);
Daniel Jasper5500f612013-11-25 11:08:59 +00001842 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001843 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001844 return Whitespaces.generateReplacements();
1845 }
1846
1847private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001848 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001849 // Returns \c true if at least one line between I and E or one of their
1850 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001851 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1852 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1853 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001854 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001855 while (I != E) {
1856 AnnotatedLine *Line = *I;
1857 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1858
1859 // If a line is part of a preprocessor directive, it needs to be formatted
1860 // if any token within the directive is affected.
1861 if (Line->InPPDirective) {
1862 FormatToken *Last = Line->Last;
1863 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1864 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1865 Last = (*PPEnd)->Last;
1866 ++PPEnd;
1867 }
1868
1869 if (affectsTokenRange(*Line->First, *Last,
1870 /*IncludeLeadingNewlines=*/false)) {
1871 SomeLineAffected = true;
1872 markAllAsAffected(I, PPEnd);
1873 }
1874 I = PPEnd;
1875 continue;
1876 }
1877
Daniel Jasper38c82402013-11-29 09:27:43 +00001878 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001879 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001880
Daniel Jasper38c82402013-11-29 09:27:43 +00001881 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001882 ++I;
1883 }
1884 return SomeLineAffected;
1885 }
1886
Daniel Jasper9c199562013-11-28 15:58:55 +00001887 // Determines whether 'Line' is affected by the SourceRanges given as input.
1888 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001889 bool nonPPLineAffected(AnnotatedLine *Line,
1890 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001891 bool SomeLineAffected = false;
1892 Line->ChildrenAffected =
1893 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1894 if (Line->ChildrenAffected)
1895 SomeLineAffected = true;
1896
1897 // Stores whether one of the line's tokens is directly affected.
1898 bool SomeTokenAffected = false;
1899 // Stores whether we need to look at the leading newlines of the next token
1900 // in order to determine whether it was affected.
1901 bool IncludeLeadingNewlines = false;
1902
1903 // Stores whether the first child line of any of this line's tokens is
1904 // affected.
1905 bool SomeFirstChildAffected = false;
1906
1907 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1908 // Determine whether 'Tok' was affected.
1909 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1910 SomeTokenAffected = true;
1911
1912 // Determine whether the first child of 'Tok' was affected.
1913 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1914 SomeFirstChildAffected = true;
1915
1916 IncludeLeadingNewlines = Tok->Children.empty();
1917 }
1918
1919 // Was this line moved, i.e. has it previously been on the same line as an
1920 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001921 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1922 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001923
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001924 bool IsContinuedComment =
1925 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1926 Line->First->NewlinesBefore < 2 && PreviousLine &&
1927 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001928
1929 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1930 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001931 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001932 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001933 }
1934 return SomeLineAffected;
1935 }
1936
Daniel Jasper5500f612013-11-25 11:08:59 +00001937 // Marks all lines between I and E as well as all their children as affected.
1938 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1939 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1940 while (I != E) {
1941 (*I)->Affected = true;
1942 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1943 ++I;
1944 }
1945 }
1946
1947 // Returns true if the range from 'First' to 'Last' intersects with one of the
1948 // input ranges.
1949 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1950 bool IncludeLeadingNewlines) {
1951 SourceLocation Start = First.WhitespaceRange.getBegin();
1952 if (!IncludeLeadingNewlines)
1953 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001954 SourceLocation End = Last.getStartOfNonWhitespace();
1955 if (Last.TokenText.size() > 0)
1956 End = End.getLocWithOffset(Last.TokenText.size() - 1);
Daniel Jasper5500f612013-11-25 11:08:59 +00001957 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1958 return affectsCharSourceRange(Range);
1959 }
1960
1961 // Returns true if one of the input ranges intersect the leading empty lines
1962 // before 'Tok'.
1963 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1964 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1965 Tok.WhitespaceRange.getBegin(),
1966 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1967 return affectsCharSourceRange(EmptyLineRange);
1968 }
1969
1970 // Returns true if 'Range' intersects with one of the input ranges.
1971 bool affectsCharSourceRange(const CharSourceRange &Range) {
1972 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1973 E = Ranges.end();
1974 I != E; ++I) {
1975 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1976 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1977 return true;
1978 }
1979 return false;
1980 }
1981
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001982 static bool inputUsesCRLF(StringRef Text) {
1983 return Text.count('\r') * 2 > Text.count('\n');
1984 }
1985
Manuel Klimek71814b42013-10-11 21:25:45 +00001986 void
1987 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001988 unsigned CountBoundToVariable = 0;
1989 unsigned CountBoundToType = 0;
1990 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001991 bool HasBinPackedFunction = false;
1992 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001993 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001994 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001995 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001996 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001997 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001998 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001999 bool SpacesBefore =
2000 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
2001 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
2002 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002003 if (SpacesBefore && !SpacesAfter)
2004 ++CountBoundToVariable;
2005 else if (!SpacesBefore && SpacesAfter)
2006 ++CountBoundToType;
2007 }
2008
Daniel Jasperfba84ff2013-10-12 05:16:06 +00002009 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
2010 if (Tok->is(tok::coloncolon) &&
2011 Tok->Previous->Type == TT_TemplateOpener)
2012 HasCpp03IncompatibleFormat = true;
2013 if (Tok->Type == TT_TemplateCloser &&
2014 Tok->Previous->Type == TT_TemplateCloser)
2015 HasCpp03IncompatibleFormat = true;
2016 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002017
2018 if (Tok->PackingKind == PPK_BinPacked)
2019 HasBinPackedFunction = true;
2020 if (Tok->PackingKind == PPK_OnePerLine)
2021 HasOnePerLineFunction = true;
2022
Manuel Klimek6e6310e2013-05-29 14:47:47 +00002023 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002024 }
2025 }
Daniel Jasper553d4872014-06-17 12:40:34 +00002026 if (Style.DerivePointerAlignment) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002027 if (CountBoundToType > CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00002028 Style.PointerAlignment = FormatStyle::PAS_Left;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002029 else if (CountBoundToType < CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00002030 Style.PointerAlignment = FormatStyle::PAS_Right;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002031 }
2032 if (Style.Standard == FormatStyle::LS_Auto) {
2033 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
2034 : FormatStyle::LS_Cpp03;
2035 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002036 BinPackInconclusiveFunctions =
2037 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002038 }
2039
Craig Topperfb6b25b2014-03-15 04:29:04 +00002040 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00002041 assert(!UnwrappedLines.empty());
2042 UnwrappedLines.back().push_back(TheLine);
2043 }
2044
Craig Topperfb6b25b2014-03-15 04:29:04 +00002045 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00002046 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00002047 }
2048
2049 FormatStyle Style;
Daniel Jasper23376252014-09-09 14:37:39 +00002050 FileID ID;
Daniel Jasperf7935112012-12-03 18:12:45 +00002051 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00002052 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00002053 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00002054 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00002055
2056 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002057 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00002058};
2059
Craig Topperaf35e852013-06-30 22:29:28 +00002060} // end anonymous namespace
2061
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00002062tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
2063 SourceManager &SourceMgr,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002064 ArrayRef<CharSourceRange> Ranges) {
Daniel Jasper23376252014-09-09 14:37:39 +00002065 if (Style.DisableFormat)
2066 return tooling::Replacements();
2067 return reformat(Style, SourceMgr,
2068 SourceMgr.getFileID(Lex.getSourceLocation()), Ranges);
2069}
Daniel Jasperc64b09a2014-05-22 15:12:22 +00002070
Daniel Jasper23376252014-09-09 14:37:39 +00002071tooling::Replacements reformat(const FormatStyle &Style,
2072 SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002073 ArrayRef<CharSourceRange> Ranges) {
Daniel Jasper23376252014-09-09 14:37:39 +00002074 if (Style.DisableFormat)
2075 return tooling::Replacements();
2076 Formatter formatter(Style, SourceMgr, ID, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00002077 return formatter.format();
2078}
2079
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002080tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002081 ArrayRef<tooling::Range> Ranges,
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002082 StringRef FileName) {
Daniel Jasper23376252014-09-09 14:37:39 +00002083 if (Style.DisableFormat)
2084 return tooling::Replacements();
2085
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002086 FileManager Files((FileSystemOptions()));
2087 DiagnosticsEngine Diagnostics(
2088 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2089 new DiagnosticOptions);
2090 SourceManager SourceMgr(Diagnostics, Files);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00002091 std::unique_ptr<llvm::MemoryBuffer> Buf =
2092 llvm::MemoryBuffer::getMemBuffer(Code, FileName);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002093 const clang::FileEntry *Entry =
2094 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
David Blaikie49cc3182014-08-27 20:54:45 +00002095 SourceMgr.overrideFileContents(Entry, std::move(Buf));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002096 FileID ID =
2097 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002098 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
2099 std::vector<CharSourceRange> CharRanges;
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002100 for (const tooling::Range &Range : Ranges) {
2101 SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
2102 SourceLocation End = Start.getLocWithOffset(Range.getLength());
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002103 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
2104 }
Daniel Jasper23376252014-09-09 14:37:39 +00002105 return reformat(Style, SourceMgr, ID, CharRanges);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002106}
2107
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002108LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002109 LangOptions LangOpts;
2110 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002111 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2112 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00002113 LangOpts.LineComment = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002114 LangOpts.CXXOperatorNames =
2115 Style.Language != FormatStyle::LK_JavaScript ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002116 LangOpts.Bool = 1;
2117 LangOpts.ObjC1 = 1;
2118 LangOpts.ObjC2 = 1;
2119 return LangOpts;
2120}
2121
Edwin Vaned544aa72013-09-30 13:31:48 +00002122const char *StyleOptionHelpDescription =
2123 "Coding style, currently supports:\n"
2124 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
2125 "Use -style=file to load style configuration from\n"
2126 ".clang-format file located in one of the parent\n"
2127 "directories of the source file (or current\n"
2128 "directory for stdin).\n"
2129 "Use -style=\"{key: value, ...}\" to set specific\n"
2130 "parameters, e.g.:\n"
2131 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
2132
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002133static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00002134 if (FileName.endswith(".java")) {
2135 return FormatStyle::LK_Java;
2136 } else if (FileName.endswith_lower(".js")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002137 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00002138 } else if (FileName.endswith_lower(".proto") ||
2139 FileName.endswith_lower(".protodevel")) {
2140 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002141 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002142 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002143}
2144
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002145FormatStyle getStyle(StringRef StyleName, StringRef FileName,
2146 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002147 FormatStyle Style = getLLVMStyle();
2148 Style.Language = getLanguageByFileName(FileName);
2149 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002150 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
2151 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002152 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002153 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002154
2155 if (StyleName.startswith("{")) {
2156 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00002157 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002158 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
2159 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00002160 }
2161 return Style;
2162 }
2163
2164 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002165 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00002166 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
2167 << " style\n";
2168 return Style;
2169 }
2170
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002171 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002172 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00002173 SmallString<128> Path(FileName);
2174 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002175 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00002176 Directory = llvm::sys::path::parent_path(Directory)) {
2177 if (!llvm::sys::fs::is_directory(Directory))
2178 continue;
2179 SmallString<128> ConfigFile(Directory);
2180
2181 llvm::sys::path::append(ConfigFile, ".clang-format");
2182 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2183 bool IsFile = false;
2184 // Ignore errors from is_regular_file: we only need to know if we can read
2185 // the file or not.
2186 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2187
2188 if (!IsFile) {
2189 // Try _clang-format too, since dotfiles are not commonly used on Windows.
2190 ConfigFile = Directory;
2191 llvm::sys::path::append(ConfigFile, "_clang-format");
2192 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2193 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2194 }
2195
2196 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002197 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
2198 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
2199 if (std::error_code EC = Text.getError()) {
2200 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002201 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002202 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002203 if (std::error_code ec =
2204 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00002205 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002206 if (!UnsuitableConfigFiles.empty())
2207 UnsuitableConfigFiles.append(", ");
2208 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002209 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002210 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002211 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2212 << "\n";
2213 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002214 }
2215 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2216 return Style;
2217 }
2218 }
2219 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
2220 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002221 if (!UnsuitableConfigFiles.empty()) {
2222 llvm::errs() << "Configuration file(s) do(es) not support "
2223 << getLanguageName(Style.Language) << ": "
2224 << UnsuitableConfigFiles << "\n";
2225 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002226 return Style;
2227}
2228
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002229} // namespace format
2230} // namespace clang