blob: 2948ec48cde9ff12ea70b239f1d8028e37095d84 [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);
202 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
203 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
204 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000205 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000206 IO.mapOptional("ExperimentalAutoDetectBinPacking",
207 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000208 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000209 IO.mapOptional("IndentWrappedFunctionNames",
210 Style.IndentWrappedFunctionNames);
211 IO.mapOptional("IndentFunctionDeclarationAfterType",
212 Style.IndentWrappedFunctionNames);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000213 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000214 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
215 Style.KeepEmptyLinesAtTheStartOfBlocks);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000216 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000217 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000218 IO.mapOptional("ObjCSpaceBeforeProtocolList",
219 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000220 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
221 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000222 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
223 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000224 IO.mapOptional("PenaltyBreakFirstLessLess",
225 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000226 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
227 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
228 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000229 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000230 IO.mapOptional("SpacesBeforeTrailingComments",
231 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000232 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000233 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000234 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000235 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000236 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000237 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000238 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperad981f82014-08-26 11:41:14 +0000239 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000240 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasperf110e202013-08-21 08:39:01 +0000241 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000242 IO.mapOptional("SpacesInCStyleCastParentheses",
243 Style.SpacesInCStyleCastParentheses);
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000244 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000245 IO.mapOptional("SpacesInContainerLiterals",
246 Style.SpacesInContainerLiterals);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000247 IO.mapOptional("SpaceBeforeAssignmentOperators",
248 Style.SpaceBeforeAssignmentOperators);
Daniel Jasper6633ab82013-10-18 10:38:14 +0000249 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000250 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000251 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000252
253 // For backward compatibility.
254 if (!IO.outputting()) {
255 IO.mapOptional("SpaceAfterControlStatementKeyword",
256 Style.SpaceBeforeParens);
Daniel Jasper553d4872014-06-17 12:40:34 +0000257 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
258 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000259 }
260 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000261 IO.mapOptional("DisableFormat", Style.DisableFormat);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000262 }
263};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000264
265// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000266// IO.getContext() should contain a pointer to the FormatStyle structure, that
267// will be used to get default values for missing keys.
268// If the first element has no Language specified, it will be treated as the
269// default one for the following elements.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000270template <> struct DocumentListTraits<std::vector<FormatStyle> > {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000271 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
272 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000273 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000274 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000275 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000276 if (Index >= Seq.size()) {
277 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000278 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000279 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000280 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000281 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000282 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000283 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000284 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000285 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000286 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000287 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000288 }
289};
Alexander Kornienkod6538332013-05-07 15:32:14 +0000290}
291}
292
Daniel Jasperf7935112012-12-03 18:12:45 +0000293namespace clang {
294namespace format {
295
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000296const std::error_category &getParseCategory() {
Rafael Espindolad0136702014-06-12 02:50:04 +0000297 static ParseErrorCategory C;
298 return C;
299}
300std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000301 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000302}
303
304const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
305 return "clang-format.parse_error";
306}
307
308std::string ParseErrorCategory::message(int EV) const {
309 switch (static_cast<ParseError>(EV)) {
310 case ParseError::Success:
311 return "Success";
312 case ParseError::Error:
313 return "Invalid argument";
314 case ParseError::Unsuitable:
315 return "Unsuitable";
316 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000317 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000318}
319
Daniel Jasperf7935112012-12-03 18:12:45 +0000320FormatStyle getLLVMStyle() {
321 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000322 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000323 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000324 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000325 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000326 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000327 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000328 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000329 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000330 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000331 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000332 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000333 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000334 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000335 LLVMStyle.BinPackParameters = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000336 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000337 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000338 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
339 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000340 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000341 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000342 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000343 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000344 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000345 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000346 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000347 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000348 LLVMStyle.ForEachMacros.push_back("foreach");
349 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
350 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000351 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000352 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000353 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000354 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000355 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000356 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000357 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000358 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000359 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000360 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000361 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000362 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000363 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000364 LLVMStyle.SpacesInParentheses = false;
Daniel Jasperad981f82014-08-26 11:41:14 +0000365 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000366 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000367 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000368 LLVMStyle.SpacesInCStyleCastParentheses = false;
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000369 LLVMStyle.SpaceAfterCStyleCast = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000370 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000371 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000372 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000373
Daniel Jasper19a541e2013-12-19 16:45:34 +0000374 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000375 LLVMStyle.PenaltyBreakFirstLessLess = 120;
376 LLVMStyle.PenaltyBreakString = 1000;
377 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000378 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000379 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000380
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000381 LLVMStyle.DisableFormat = false;
382
Daniel Jasperf7935112012-12-03 18:12:45 +0000383 return LLVMStyle;
384}
385
Nico Weber514ecc82014-02-02 20:50:45 +0000386FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000387 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000388 GoogleStyle.Language = Language;
389
Daniel Jasperf7935112012-12-03 18:12:45 +0000390 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000391 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000392 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000393 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000394 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000395 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000396 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000397 GoogleStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000398 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000399 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000400 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000401 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000402 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000403 GoogleStyle.SpacesBeforeTrailingComments = 2;
404 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000405
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000406 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000407 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000408
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000409 if (Language == FormatStyle::LK_Java) {
410 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
411 GoogleStyle.ColumnLimit = 100;
412 GoogleStyle.SpaceAfterCStyleCast = true;
413 } else if (Language == FormatStyle::LK_JavaScript) {
Nico Weber514ecc82014-02-02 20:50:45 +0000414 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000415 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000416 GoogleStyle.SpacesInContainerLiterals = false;
417 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000418 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000419 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000420 }
421
Daniel Jasperf7935112012-12-03 18:12:45 +0000422 return GoogleStyle;
423}
424
Nico Weber514ecc82014-02-02 20:50:45 +0000425FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
426 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Daniel Jasperf7db4332013-01-29 16:03:49 +0000427 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000428 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000429 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000430 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000431 ChromiumStyle.BinPackParameters = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000432 ChromiumStyle.DerivePointerAlignment = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000433 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000434 return ChromiumStyle;
435}
436
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000437FormatStyle getMozillaStyle() {
438 FormatStyle MozillaStyle = getLLVMStyle();
439 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000440 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000441 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000442 MozillaStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000443 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000444 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000445 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
446 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000447 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000448 MozillaStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000449 return MozillaStyle;
450}
451
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000452FormatStyle getWebKitStyle() {
453 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000454 Style.AccessModifierOffset = -4;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000455 Style.AlignTrailingComments = false;
Daniel Jasperac043c92014-09-15 11:11:00 +0000456 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000457 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000458 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000459 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000460 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000461 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000462 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000463 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000464 Style.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000465 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000466 return Style;
467}
468
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000469FormatStyle getGNUStyle() {
470 FormatStyle Style = getLLVMStyle();
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000471 Style.AlwaysBreakAfterDefinitionReturnType = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000472 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000473 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000474 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000475 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000476 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000477 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000478 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000479 return Style;
480}
481
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000482FormatStyle getNoStyle() {
483 FormatStyle NoStyle = getLLVMStyle();
484 NoStyle.DisableFormat = true;
485 return NoStyle;
486}
487
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000488bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
489 FormatStyle *Style) {
490 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000491 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000492 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000493 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000494 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000495 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000496 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000497 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000498 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000499 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000500 } else if (Name.equals_lower("gnu")) {
501 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000502 } else if (Name.equals_lower("none")) {
503 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000504 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000505 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000506 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000507
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000508 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000509 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000510}
511
Rafael Espindolac0809172014-06-12 14:02:15 +0000512std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000513 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000514 FormatStyle::LanguageKind Language = Style->Language;
515 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000516 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000517 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000518
519 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000520 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000521 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
522 // values for the fields, keys for which are missing from the configuration.
523 // Mapping also uses the context to get the language to find the correct
524 // base style.
525 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000526 Input >> Styles;
527 if (Input.error())
528 return Input.error();
529
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000530 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000531 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000532 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000533 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000534 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000535 for (unsigned j = 0; j < i; ++j) {
536 if (Styles[i].Language == Styles[j].Language) {
537 DEBUG(llvm::dbgs()
538 << "Duplicate languages in the config file on positions " << j
539 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000540 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000541 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000542 }
543 }
544 // Look for a suitable configuration starting from the end, so we can
545 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000546 // configuration (which can only be at slot 0) after it.
547 for (int i = Styles.size() - 1; i >= 0; --i) {
548 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000549 Styles[i].Language == FormatStyle::LK_None) {
550 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000551 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000552 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000553 }
554 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000555 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000556}
557
558std::string configurationAsText(const FormatStyle &Style) {
559 std::string Text;
560 llvm::raw_string_ostream Stream(Text);
561 llvm::yaml::Output Output(Stream);
562 // We use the same mapping method for input and output, so we need a non-const
563 // reference here.
564 FormatStyle NonConstStyle = Style;
565 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000566 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000567}
568
Craig Topperaf35e852013-06-30 22:29:28 +0000569namespace {
570
Daniel Jasperde0328a2013-08-16 11:20:30 +0000571class NoColumnLimitFormatter {
572public:
Daniel Jasperf110e202013-08-21 08:39:01 +0000573 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000574
575 /// \brief Formats the line starting at \p State, simply keeping all of the
576 /// input's line breaking decisions.
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000577 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000578 LineState State =
579 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Craig Topper2145bc02014-05-09 08:15:10 +0000580 while (State.NextToken) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000581 bool Newline =
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000582 Indenter->mustBreak(State) ||
Daniel Jasperde0328a2013-08-16 11:20:30 +0000583 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
584 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
585 }
586 }
Daniel Jasperf110e202013-08-21 08:39:01 +0000587
Daniel Jasperde0328a2013-08-16 11:20:30 +0000588private:
589 ContinuationIndenter *Indenter;
590};
591
Daniel Jasper56f8b432013-11-06 23:12:09 +0000592class LineJoiner {
593public:
594 LineJoiner(const FormatStyle &Style) : Style(Style) {}
595
596 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
597 unsigned
598 tryFitMultipleLinesInOne(unsigned Indent,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000599 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000600 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
601 // We can never merge stuff if there are trailing line comments.
Daniel Jasper234379f2013-12-24 13:31:25 +0000602 const AnnotatedLine *TheLine = *I;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000603 if (TheLine->Last->Type == TT_LineComment)
604 return 0;
605
Alexander Kornienkoecc232d2013-12-04 13:25:26 +0000606 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
607 return 0;
608
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000609 unsigned Limit =
610 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000611 // If we already exceed the column limit, we set 'Limit' to 0. The different
612 // tryMerge..() functions can then decide whether to still do merging.
613 Limit = TheLine->Last->TotalLength > Limit
614 ? 0
615 : Limit - TheLine->Last->TotalLength;
616
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000617 if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000618 return 0;
619
Daniel Jasperd74cf402014-04-08 12:46:38 +0000620 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
621 // If necessary, change to something smarter.
622 bool MergeShortFunctions =
623 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
624 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
625 TheLine->Level != 0);
626
Daniel Jasper234379f2013-12-24 13:31:25 +0000627 if (TheLine->Last->Type == TT_FunctionLBrace &&
628 TheLine->First != TheLine->Last) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000629 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000630 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000631 if (TheLine->Last->is(tok::l_brace)) {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000632 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000633 ? tryMergeSimpleBlock(I, E, Limit)
634 : 0;
635 }
636 if (I[1]->First->Type == TT_FunctionLBrace &&
637 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
Alp Tokerba5b4dc2013-12-30 02:06:29 +0000638 // Check for Limit <= 2 to account for the " {".
Daniel Jasper234379f2013-12-24 13:31:25 +0000639 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
640 return 0;
641 Limit -= 2;
642
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000643 unsigned MergedLines = 0;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000644 if (MergeShortFunctions) {
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000645 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
646 // If we managed to merge the block, count the function header, which is
647 // on a separate line.
648 if (MergedLines > 0)
649 ++MergedLines;
650 }
651 return MergedLines;
652 }
653 if (TheLine->First->is(tok::kw_if)) {
654 return Style.AllowShortIfStatementsOnASingleLine
655 ? tryMergeSimpleControlStatement(I, E, Limit)
656 : 0;
657 }
658 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
659 return Style.AllowShortLoopsOnASingleLine
660 ? tryMergeSimpleControlStatement(I, E, Limit)
661 : 0;
662 }
Daniel Jasperb87899b2014-09-10 13:11:45 +0000663 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
664 return Style.AllowShortCaseLabelsOnASingleLine
665 ? tryMergeShortCaseLabels(I, E, Limit)
666 : 0;
667 }
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000668 if (TheLine->InPPDirective &&
669 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000670 return tryMergeSimplePPDirective(I, E, Limit);
671 }
672 return 0;
673 }
674
675private:
676 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000677 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000678 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
679 unsigned Limit) {
680 if (Limit == 0)
681 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000682 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000683 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000684 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000685 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000686 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000687 return 0;
688 return 1;
689 }
690
691 unsigned tryMergeSimpleControlStatement(
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000692 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000693 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
694 if (Limit == 0)
695 return 0;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000696 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
697 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
Daniel Jasper17605d32014-05-14 09:33:35 +0000698 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000699 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000700 if (I[1]->InPPDirective != (*I)->InPPDirective ||
701 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000702 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000703 Limit = limitConsideringMacros(I + 1, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000704 AnnotatedLine &Line = **I;
705 if (Line.Last->isNot(tok::r_paren))
706 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000707 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000708 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000709 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000710 tok::kw_while) ||
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000711 I[1]->First->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000712 return 0;
713 // Only inline simple if's (no nested if or else).
714 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000715 I[2]->First->is(tok::kw_else))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000716 return 0;
717 return 1;
718 }
719
Daniel Jasperb87899b2014-09-10 13:11:45 +0000720 unsigned tryMergeShortCaseLabels(
721 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
722 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
723 if (Limit == 0 || I + 1 == E ||
724 I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
725 return 0;
726 unsigned NumStmts = 0;
727 unsigned Length = 0;
728 for (; NumStmts < 3; ++NumStmts) {
729 if (I + 1 + NumStmts == E)
730 break;
731 const AnnotatedLine *Line = I[1 + NumStmts];
732 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
733 break;
734 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
735 tok::kw_while))
736 return 0;
737 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
738 }
739 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
740 return 0;
741 return NumStmts;
742 }
743
Daniel Jasper56f8b432013-11-06 23:12:09 +0000744 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000745 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000746 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
747 unsigned Limit) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000748 AnnotatedLine &Line = **I;
Daniel Jasper17605d32014-05-14 09:33:35 +0000749
750 // Don't merge ObjC @ keywords and methods.
751 if (Line.First->isOneOf(tok::at, tok::minus, tok::plus))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000752 return 0;
753
Daniel Jasper17605d32014-05-14 09:33:35 +0000754 // Check that the current line allows merging. This depends on whether we
755 // are in a control flow statements as well as several style flags.
756 if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
757 return 0;
758 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
759 tok::kw_catch, tok::kw_for, tok::r_brace)) {
760 if (!Style.AllowShortBlocksOnASingleLine)
761 return 0;
762 if (!Style.AllowShortIfStatementsOnASingleLine &&
763 Line.First->is(tok::kw_if))
764 return 0;
765 if (!Style.AllowShortLoopsOnASingleLine &&
766 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
767 return 0;
768 // FIXME: Consider an option to allow short exception handling clauses on
769 // a single line.
770 if (Line.First->isOneOf(tok::kw_try, tok::kw_catch))
771 return 0;
772 }
773
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000774 FormatToken *Tok = I[1]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000775 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Craig Topper2145bc02014-05-09 08:15:10 +0000776 (Tok->getNextNonComment() == nullptr ||
Daniel Jasper56f8b432013-11-06 23:12:09 +0000777 Tok->getNextNonComment()->is(tok::semi))) {
778 // We merge empty blocks even if the line exceeds the column limit.
779 Tok->SpacesRequiredBefore = 0;
780 Tok->CanBreakBefore = true;
781 return 1;
782 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Daniel Jasper79dffb42014-05-07 09:48:30 +0000783 // We don't merge short records.
784 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
785 return 0;
786
Daniel Jasper56f8b432013-11-06 23:12:09 +0000787 // Check that we still have three lines and they fit into the limit.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000788 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000789 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000790 Limit = limitConsideringMacros(I + 2, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000791
792 if (!nextTwoLinesFitInto(I, Limit))
793 return 0;
794
795 // Second, check that the next line does not contain any braces - if it
796 // does, readability declines when putting it into a single line.
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000797 if (I[1]->Last->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000798 return 0;
799 do {
Daniel Jasperbd630732014-05-22 13:25:26 +0000800 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000801 return 0;
802 Tok = Tok->Next;
Craig Topper2145bc02014-05-09 08:15:10 +0000803 } while (Tok);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000804
Daniel Jasper79dffb42014-05-07 09:48:30 +0000805 // Last, check that the third line starts with a closing brace.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000806 Tok = I[2]->First;
Daniel Jasper79dffb42014-05-07 09:48:30 +0000807 if (Tok->isNot(tok::r_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000808 return 0;
809
810 return 2;
811 }
812 return 0;
813 }
814
Daniel Jasper64989962014-02-07 13:45:27 +0000815 /// Returns the modified column limit for \p I if it is inside a macro and
816 /// needs a trailing '\'.
817 unsigned
Daniel Jaspera0407742014-02-11 10:08:11 +0000818 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper64989962014-02-07 13:45:27 +0000819 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
820 unsigned Limit) {
821 if (I[0]->InPPDirective && I + 1 != E &&
822 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
823 return Limit < 2 ? 0 : Limit - 2;
824 }
825 return Limit;
826 }
827
Daniel Jasper56f8b432013-11-06 23:12:09 +0000828 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
829 unsigned Limit) {
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000830 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
831 return false;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000832 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000833 }
834
Daniel Jasper234379f2013-12-24 13:31:25 +0000835 bool containsMustBreak(const AnnotatedLine *Line) {
836 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
837 if (Tok->MustBreakBefore)
838 return true;
839 }
840 return false;
841 }
842
Daniel Jasper56f8b432013-11-06 23:12:09 +0000843 const FormatStyle &Style;
844};
845
Daniel Jasperf7935112012-12-03 18:12:45 +0000846class UnwrappedLineFormatter {
847public:
Daniel Jasper5500f612013-11-25 11:08:59 +0000848 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000849 WhitespaceManager *Whitespaces,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000850 const FormatStyle &Style)
Daniel Jasper5500f612013-11-25 11:08:59 +0000851 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
852 Joiner(Style) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000853
Daniel Jasper56f8b432013-11-06 23:12:09 +0000854 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper9c199562013-11-28 15:58:55 +0000855 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Daniel Jasperc359ad02014-04-15 08:13:47 +0000856 // Try to look up already computed penalty in DryRun-mode.
NAKAMURA Takumi22059522014-04-15 23:29:04 +0000857 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
858 &Lines, AdditionalIndent);
Daniel Jasperc359ad02014-04-15 08:13:47 +0000859 auto CacheIt = PenaltyCache.find(CacheKey);
860 if (DryRun && CacheIt != PenaltyCache.end())
861 return CacheIt->second;
862
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000863 assert(!Lines.empty());
864 unsigned Penalty = 0;
865 std::vector<int> IndentForLevel;
866 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
867 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Craig Topper2145bc02014-05-09 08:15:10 +0000868 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000869 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
870 E = Lines.end();
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000871 I != E; ++I) {
872 const AnnotatedLine &TheLine = **I;
873 const FormatToken *FirstTok = TheLine.First;
874 int Offset = getIndentOffset(*FirstTok);
875
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000876 // Determine indent and try to merge multiple unwrapped lines.
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000877 unsigned Indent;
878 if (TheLine.InPPDirective) {
879 Indent = TheLine.Level * Style.IndentWidth;
880 } else {
881 while (IndentForLevel.size() <= TheLine.Level)
882 IndentForLevel.push_back(-1);
883 IndentForLevel.resize(TheLine.Level + 1);
884 Indent = getIndent(IndentForLevel, TheLine.Level);
885 }
886 unsigned LevelIndent = Indent;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000887 if (static_cast<int>(Indent) + Offset >= 0)
888 Indent += Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000889
890 // Merge multiple lines if possible.
Daniel Jasper56f8b432013-11-06 23:12:09 +0000891 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
Alexander Kornienko31e95542013-12-04 12:21:08 +0000892 if (MergedLines > 0 && Style.ColumnLimit == 0) {
893 // Disallow line merging if there is a break at the start of one of the
894 // input lines.
895 for (unsigned i = 0; i < MergedLines; ++i) {
896 if (I[i + 1]->First->NewlinesBefore > 0)
897 MergedLines = 0;
898 }
899 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000900 if (!DryRun) {
901 for (unsigned i = 0; i < MergedLines; ++i) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000902 join(*I[i], *I[i + 1]);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000903 }
904 }
905 I += MergedLines;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000906
Daniel Jasper9c199562013-11-28 15:58:55 +0000907 bool FixIndentation =
908 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000909 if (TheLine.First->is(tok::eof)) {
Daniel Jasper5500f612013-11-25 11:08:59 +0000910 if (PreviousLine && PreviousLine->Affected && !DryRun) {
911 // Remove the file's trailing whitespace.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000912 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
913 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
914 /*IndentLevel=*/0, /*Spaces=*/0,
915 /*TargetColumn=*/0);
916 }
Daniel Jasper9c199562013-11-28 15:58:55 +0000917 } else if (TheLine.Type != LT_Invalid &&
918 (TheLine.Affected || FixIndentation)) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000919 if (FirstTok->WhitespaceRange.isValid()) {
920 if (!DryRun)
921 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
922 Indent, TheLine.InPPDirective);
923 } else {
924 Indent = LevelIndent = FirstTok->OriginalColumn;
925 }
926
927 // If everything fits on a single line, just put it there.
928 unsigned ColumnLimit = Style.ColumnLimit;
929 if (I + 1 != E) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000930 AnnotatedLine *NextLine = I[1];
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000931 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
932 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
933 }
934
935 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
936 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000937 while (State.NextToken) {
938 formatChildren(State, /*Newline=*/false, /*DryRun=*/false, Penalty);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000939 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000940 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000941 } else if (Style.ColumnLimit == 0) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000942 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000943 NoColumnLimitFormatter Formatter(Indenter);
944 if (!DryRun)
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000945 Formatter.format(Indent, &TheLine);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000946 } else {
947 Penalty += format(TheLine, Indent, DryRun);
948 }
949
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000950 if (!TheLine.InPPDirective)
951 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper9c199562013-11-28 15:58:55 +0000952 } else if (TheLine.ChildrenAffected) {
953 format(TheLine.Children, DryRun);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000954 } else {
955 // Format the first token if necessary, and notify the WhitespaceManager
956 // about the unchanged whitespace.
Craig Topper2145bc02014-05-09 08:15:10 +0000957 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000958 if (Tok == TheLine.First &&
959 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
960 unsigned LevelIndent = Tok->OriginalColumn;
961 if (!DryRun) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000962 // Remove trailing whitespace of the previous line.
Daniel Jasper5500f612013-11-25 11:08:59 +0000963 if ((PreviousLine && PreviousLine->Affected) ||
964 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000965 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
966 TheLine.InPPDirective);
967 } else {
968 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
969 }
970 }
971
972 if (static_cast<int>(LevelIndent) - Offset >= 0)
973 LevelIndent -= Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000974 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000975 IndentForLevel[TheLine.Level] = LevelIndent;
976 } else if (!DryRun) {
977 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
978 }
979 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000980 }
981 if (!DryRun) {
Craig Topper2145bc02014-05-09 08:15:10 +0000982 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000983 Tok->Finalized = true;
984 }
985 }
986 PreviousLine = *I;
987 }
Daniel Jasperc359ad02014-04-15 08:13:47 +0000988 PenaltyCache[CacheKey] = Penalty;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000989 return Penalty;
990 }
991
992private:
993 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000994 ///
995 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000996 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
997 bool DryRun) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000998 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +0000999
Daniel Jasperacc33662013-02-08 08:22:00 +00001000 // If the ObjC method declaration does not fit on a line, we should format
1001 // it with one arg per line.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001002 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperacc33662013-02-08 08:22:00 +00001003 State.Stack.back().BreakBeforeParameter = true;
1004
Daniel Jasper4b866272013-02-01 11:00:45 +00001005 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001006 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +00001007 }
1008
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001009 /// \brief An edge in the solution space from \c Previous->State to \c State,
1010 /// inserting a newline dependent on the \c NewLine.
1011 struct StateNode {
1012 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001013 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001014 LineState State;
1015 bool NewLine;
1016 StateNode *Previous;
1017 };
Daniel Jasper4b866272013-02-01 11:00:45 +00001018
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001019 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
1020 ///
1021 /// In case of equal penalties, we want to prefer states that were inserted
1022 /// first. During state generation we make sure that we insert states first
1023 /// that break the line as late as possible.
1024 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1025
1026 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
1027 /// \c State has the given \c OrderedPenalty.
1028 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1029
1030 /// \brief The BFS queue type.
1031 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1032 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +00001033
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001034 /// \brief Get the offset of the line relatively to the level.
1035 ///
1036 /// For example, 'public:' labels in classes are offset by 1 or 2
1037 /// characters to the left from their level.
1038 int getIndentOffset(const FormatToken &RootToken) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001039 if (Style.Language == FormatStyle::LK_Java)
1040 return 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001041 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
1042 return Style.AccessModifierOffset;
1043 return 0;
1044 }
1045
1046 /// \brief Add a new line and the required indent before the first Token
1047 /// of the \c UnwrappedLine if there was no structural parsing error.
1048 void formatFirstToken(FormatToken &RootToken,
1049 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
1050 unsigned Indent, bool InPPDirective) {
1051 unsigned Newlines =
1052 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1053 // Remove empty lines before "}" where applicable.
1054 if (RootToken.is(tok::r_brace) &&
1055 (!RootToken.Next ||
1056 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1057 Newlines = std::min(Newlines, 1u);
1058 if (Newlines == 0 && !RootToken.IsFirst)
1059 Newlines = 1;
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001060 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1061 Newlines = 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001062
Daniel Jasper11164bd2014-03-21 12:58:53 +00001063 // Remove empty lines after "{".
Daniel Jaspera26fc5c2014-03-21 13:43:14 +00001064 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1065 PreviousLine->Last->is(tok::l_brace) &&
Daniel Jasper01b35482014-03-21 13:03:33 +00001066 PreviousLine->First->isNot(tok::kw_namespace))
Daniel Jasper11164bd2014-03-21 12:58:53 +00001067 Newlines = 1;
1068
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001069 // Insert extra new line before access specifiers.
1070 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1071 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1072 ++Newlines;
1073
1074 // Remove empty lines after access specifiers.
1075 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
1076 Newlines = std::min(1u, Newlines);
1077
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001078 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
1079 Indent, InPPDirective &&
1080 !RootToken.HasUnescapedNewline);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001081 }
1082
1083 /// \brief Get the indent of \p Level from \p IndentForLevel.
1084 ///
1085 /// \p IndentForLevel must contain the indent for the level \c l
1086 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1087 /// that level is unknown.
1088 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
1089 if (IndentForLevel[Level] != -1)
1090 return IndentForLevel[Level];
1091 if (Level == 0)
1092 return 0;
1093 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
1094 }
1095
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001096 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1097 assert(!A.Last->Next);
1098 assert(!B.First->Previous);
Daniel Jasper5500f612013-11-25 11:08:59 +00001099 if (B.Affected)
1100 A.Affected = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001101 A.Last->Next = B.First;
1102 B.First->Previous = A.Last;
Daniel Jasper98fb6e12013-11-08 17:33:27 +00001103 B.First->CanBreakBefore = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001104 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1105 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1106 Tok->TotalLength += LengthA;
1107 A.Last = Tok;
1108 }
1109 }
1110
1111 unsigned getColumnLimit(bool InPPDirective) const {
1112 // In preprocessor directives reserve two chars for trailing " \"
1113 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1114 }
1115
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001116 struct CompareLineStatePointers {
1117 bool operator()(LineState *obj1, LineState *obj2) const {
1118 return *obj1 < *obj2;
1119 }
1120 };
1121
Daniel Jasper4b866272013-02-01 11:00:45 +00001122 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +00001123 ///
Daniel Jasper4b866272013-02-01 11:00:45 +00001124 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1125 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1126 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001127 /// to a state where all tokens are placed. Returns the penalty.
1128 ///
1129 /// If \p DryRun is \c false, directly applies the changes.
1130 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001131 std::set<LineState *, CompareLineStatePointers> Seen;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001132
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001133 // Increasing count of \c StateNode items we have created. This is used to
1134 // create a deterministic order independent of the container.
1135 unsigned Count = 0;
1136 QueueType Queue;
1137
Daniel Jasper4b866272013-02-01 11:00:45 +00001138 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001139 StateNode *Node =
Craig Topper2145bc02014-05-09 08:15:10 +00001140 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001141 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1142 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001143
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001144 unsigned Penalty = 0;
1145
Daniel Jasper4b866272013-02-01 11:00:45 +00001146 // While not empty, take first element and follow edges.
1147 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001148 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001149 StateNode *Node = Queue.top().second;
Craig Topper2145bc02014-05-09 08:15:10 +00001150 if (!Node->State.NextToken) {
Alexander Kornienko49149672013-05-10 11:56:10 +00001151 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001152 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001153 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001154 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001155
Daniel Jasperf8114cf2013-05-22 05:27:42 +00001156 // Cut off the analysis of certain solutions if the analysis gets too
1157 // complex. See description of IgnoreStackForComparison.
1158 if (Count > 10000)
1159 Node->State.IgnoreStackForComparison = true;
1160
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001161 if (!Seen.insert(&Node->State).second)
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001162 // State already examined with lower penalty.
1163 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001164
Manuel Klimek71814b42013-10-11 21:25:45 +00001165 FormatDecision LastFormat = Node->State.NextToken->Decision;
1166 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001167 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimek71814b42013-10-11 21:25:45 +00001168 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001169 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper4b866272013-02-01 11:00:45 +00001170 }
1171
Manuel Klimek71814b42013-10-11 21:25:45 +00001172 if (Queue.empty()) {
Daniel Jasper4b866272013-02-01 11:00:45 +00001173 // We were unable to find a solution, do nothing.
1174 // FIXME: Add diagnostic?
Manuel Klimek71814b42013-10-11 21:25:45 +00001175 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001176 return 0;
Manuel Klimek71814b42013-10-11 21:25:45 +00001177 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001178
Daniel Jasper4b866272013-02-01 11:00:45 +00001179 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001180 if (!DryRun)
1181 reconstructPath(InitialState, Queue.top().second);
1182
Alexander Kornienko49149672013-05-10 11:56:10 +00001183 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1184 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001185
1186 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001187 }
1188
1189 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001190 std::deque<StateNode *> Path;
1191 // We do not need a break before the initial token.
1192 while (Current->Previous) {
1193 Path.push_front(Current);
1194 Current = Current->Previous;
1195 }
1196 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1197 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001198 unsigned Penalty = 0;
1199 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1200 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1201
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001202 DEBUG({
1203 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001204 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001205 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001206 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001207 }
1208 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001209 }
Daniel Jasper4b866272013-02-01 11:00:45 +00001210 }
1211
Manuel Klimekaf491072013-02-13 10:54:19 +00001212 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001213 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001214 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001215 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001216 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001217 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001218 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001219 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001220 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001221 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001222
1223 StateNode *Node = new (Allocator.Allocate())
1224 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001225 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1226 return;
1227
Daniel Jasperde0328a2013-08-16 11:20:30 +00001228 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001229
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001230 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1231 ++(*Count);
Daniel Jasper4b866272013-02-01 11:00:45 +00001232 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001233
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001234 /// \brief If the \p State's next token is an r_brace closing a nested block,
1235 /// format the nested block before it.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001236 ///
1237 /// Returns \c true if all children could be placed successfully and adapts
1238 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1239 /// creates changes using \c Whitespaces.
1240 ///
1241 /// The crucial idea here is that children always get formatted upon
1242 /// encountering the closing brace right after the nested block. Now, if we
1243 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1244 /// \c false), the entire block has to be kept on the same line (which is only
1245 /// possible if it fits on the line, only contains a single statement, etc.
1246 ///
1247 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1248 /// break after the "{", format all lines with correct indentation and the put
1249 /// the closing "}" on yet another new line.
1250 ///
1251 /// This enables us to keep the simple structure of the
1252 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1253 /// break or don't break.
1254 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1255 unsigned &Penalty) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001256 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001257 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1258 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1259 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001260 // The previous token does not open a block. Nothing to do. We don't
1261 // assert so that we can simply call this function for all tokens.
Daniel Jasper36c28ce2013-09-06 08:54:24 +00001262 return true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001263
1264 if (NewLine) {
Daniel Jasper58cb2ed2014-06-06 13:49:04 +00001265 int AdditionalIndent =
1266 State.FirstIndent - State.Line->Level * Style.IndentWidth;
Daniel Jasperb16b9692014-05-21 12:51:23 +00001267 if (State.Stack.size() < 2 ||
1268 !State.Stack[State.Stack.size() - 2].JSFunctionInlined) {
1269 AdditionalIndent = State.Stack.back().Indent -
1270 Previous.Children[0]->Level * Style.IndentWidth;
1271 }
1272
Daniel Jasper9c199562013-11-28 15:58:55 +00001273 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1274 /*FixBadIndentation=*/true);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001275 return true;
1276 }
1277
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001278 // Cannot merge multiple statements into a single line.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001279 if (Previous.Children.size() > 1)
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001280 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001281
Daniel Jasper21397a32014-04-09 12:21:48 +00001282 // Cannot merge into one line if this line ends on a comment.
1283 if (Previous.is(tok::comment))
1284 return false;
1285
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001286 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001287 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001288 return false;
1289
Daniel Jasper98583d52014-04-15 08:28:06 +00001290 // If the child line exceeds the column limit, we wouldn't want to merge it.
1291 // We add +2 for the trailing " }".
1292 if (Style.ColumnLimit > 0 &&
1293 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
1294 Style.ColumnLimit)
1295 return false;
1296
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001297 if (!DryRun) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001298 Whitespaces->replaceWhitespace(
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001299 *Previous.Children[0]->First,
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001300 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001301 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001302 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001303 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001304
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001305 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001306 return true;
1307 }
1308
Daniel Jasperde0328a2013-08-16 11:20:30 +00001309 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001310 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001311 FormatStyle Style;
Daniel Jasper56f8b432013-11-06 23:12:09 +00001312 LineJoiner Joiner;
Manuel Klimekaf491072013-02-13 10:54:19 +00001313
1314 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperc359ad02014-04-15 08:13:47 +00001315
1316 // Cache to store the penalty of formatting a vector of AnnotatedLines
1317 // starting from a specific additional offset. Improves performance if there
1318 // are many nested blocks.
1319 std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
1320 unsigned> PenaltyCache;
Daniel Jasperf7935112012-12-03 18:12:45 +00001321};
1322
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001323class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001324public:
Daniel Jasper23376252014-09-09 14:37:39 +00001325 FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001326 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +00001327 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
Daniel Jasper23376252014-09-09 14:37:39 +00001328 Column(0), TrailingWhitespace(0),
1329 SourceMgr(SourceMgr), ID(ID), Style(Style),
1330 IdentTable(getFormattingLangOpts(Style)), Encoding(Encoding),
1331 FirstInLineIndex(0), FormattingDisabled(false) {
1332 Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
1333 getFormattingLangOpts(Style)));
1334 Lex->SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +00001335
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001336 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +00001337 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1338 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001339 }
1340
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001341 ArrayRef<FormatToken *> lex() {
1342 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +00001343 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001344 do {
1345 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001346 tryMergePreviousTokens();
Manuel Klimek68b03042014-04-14 09:14:11 +00001347 if (Tokens.back()->NewlinesBefore > 0)
1348 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001349 } while (Tokens.back()->Tok.isNot(tok::eof));
1350 return Tokens;
1351 }
1352
1353 IdentifierTable &getIdentTable() { return IdentTable; }
1354
1355private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001356 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001357 if (tryMerge_TMacro())
1358 return;
Manuel Klimek68b03042014-04-14 09:14:11 +00001359 if (tryMergeConflictMarkers())
1360 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001361
1362 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001363 if (tryMergeJSRegexLiteral())
1364 return;
Daniel Jasper23376252014-09-09 14:37:39 +00001365 if (tryMergeEscapeSequence())
1366 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001367
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001368 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1369 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1370 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1371 tok::greaterequal };
Daniel Jasper78214392014-05-19 07:27:02 +00001372 static tok::TokenKind JSRightArrow[] = { tok::equal, tok::greater };
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001373 // FIXME: We probably need to change token type to mimic operator with the
1374 // correct priority.
1375 if (tryMergeTokens(JSIdentity))
1376 return;
1377 if (tryMergeTokens(JSNotIdentity))
1378 return;
1379 if (tryMergeTokens(JSShiftEqual))
1380 return;
Daniel Jasper78214392014-05-19 07:27:02 +00001381 if (tryMergeTokens(JSRightArrow))
1382 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001383 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001384 }
1385
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001386 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1387 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001388 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001389
1390 SmallVectorImpl<FormatToken *>::const_iterator First =
1391 Tokens.end() - Kinds.size();
1392 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001393 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001394 unsigned AddLength = 0;
1395 for (unsigned i = 1; i < Kinds.size(); ++i) {
1396 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1397 First[i]->WhitespaceRange.getEnd())
1398 return false;
1399 AddLength += First[i]->TokenText.size();
1400 }
1401 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1402 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1403 First[0]->TokenText.size() + AddLength);
1404 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001405 return true;
1406 }
1407
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001408 // Tries to merge an escape sequence, i.e. a "\\" and the following
Alp Tokerc3f36af2014-05-15 01:35:53 +00001409 // character. Use e.g. inside JavaScript regex literals.
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001410 bool tryMergeEscapeSequence() {
1411 if (Tokens.size() < 2)
1412 return false;
1413 FormatToken *Previous = Tokens[Tokens.size() - 2];
1414 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\" ||
1415 Tokens.back()->NewlinesBefore != 0)
1416 return false;
1417 Previous->ColumnWidth += Tokens.back()->ColumnWidth;
1418 StringRef Text = Previous->TokenText;
1419 Previous->TokenText =
1420 StringRef(Text.data(), Text.size() + Tokens.back()->TokenText.size());
1421 Tokens.resize(Tokens.size() - 1);
1422 return true;
1423 }
1424
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001425 // Try to determine whether the current token ends a JavaScript regex literal.
1426 // We heuristically assume that this is a regex literal if we find two
1427 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +00001428 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
1429 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001430 bool tryMergeJSRegexLiteral() {
Daniel Jasper23376252014-09-09 14:37:39 +00001431 if (Tokens.size() < 2)
1432 return false;
1433 // If a regex literal ends in "\//", this gets represented by an unknown
1434 // token "\" and a comment.
1435 bool MightEndWithEscapedSlash =
1436 Tokens.back()->is(tok::comment) &&
1437 Tokens.back()->TokenText.startswith("//") &&
1438 Tokens[Tokens.size() - 2]->TokenText == "\\";
1439 if (!MightEndWithEscapedSlash &&
1440 (Tokens.back()->isNot(tok::slash) ||
1441 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
1442 Tokens[Tokens.size() - 2]->TokenText == "\\")))
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001443 return false;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001444 unsigned TokenCount = 0;
1445 unsigned LastColumn = Tokens.back()->OriginalColumn;
1446 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
1447 ++TokenCount;
1448 if (I[0]->is(tok::slash) && I + 1 != E &&
1449 (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
1450 tok::exclaim, tok::l_square, tok::colon, tok::comma,
1451 tok::question, tok::kw_return) ||
1452 I[1]->isBinaryOperator())) {
Daniel Jasper23376252014-09-09 14:37:39 +00001453 if (MightEndWithEscapedSlash) {
1454 StringRef Buffer = SourceMgr.getBufferData(ID);
1455 // This regex literal ends in '\//'. Skip past the '//' of the last
1456 // token and re-start lexing from there.
1457 int offset =
1458 SourceMgr.getFileOffset(Tokens.back()->Tok.getLocation()) + 2;
1459 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1460 getFormattingLangOpts(Style), Buffer.begin(),
1461 Buffer.begin() + offset, Buffer.end()));
1462 Lex->SetKeepWhitespaceMode(true);
1463 }
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001464 Tokens.resize(Tokens.size() - TokenCount);
1465 Tokens.back()->Tok.setKind(tok::unknown);
1466 Tokens.back()->Type = TT_RegexLiteral;
1467 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
1468 return true;
1469 }
1470
1471 // There can't be a newline inside a regex literal.
1472 if (I[0]->NewlinesBefore > 0)
1473 return false;
1474 }
1475 return false;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001476 }
1477
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001478 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001479 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001480 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001481 FormatToken *Last = Tokens.back();
1482 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001483 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001484
1485 FormatToken *String = Tokens[Tokens.size() - 2];
1486 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001487 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001488
1489 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001490 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001491
1492 FormatToken *Macro = Tokens[Tokens.size() - 4];
1493 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001494 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001495
1496 const char *Start = Macro->TokenText.data();
1497 const char *End = Last->TokenText.data() + Last->TokenText.size();
1498 String->TokenText = StringRef(Start, End - Start);
1499 String->IsFirst = Macro->IsFirst;
1500 String->LastNewlineOffset = Macro->LastNewlineOffset;
1501 String->WhitespaceRange = Macro->WhitespaceRange;
1502 String->OriginalColumn = Macro->OriginalColumn;
1503 String->ColumnWidth = encoding::columnWidthWithTabs(
1504 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1505
1506 Tokens.pop_back();
1507 Tokens.pop_back();
1508 Tokens.pop_back();
1509 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001510 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001511 }
1512
Manuel Klimek68b03042014-04-14 09:14:11 +00001513 bool tryMergeConflictMarkers() {
1514 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1515 return false;
1516
1517 // Conflict lines look like:
1518 // <marker> <text from the vcs>
1519 // For example:
1520 // >>>>>>> /file/in/file/system at revision 1234
1521 //
1522 // We merge all tokens in a line that starts with a conflict marker
1523 // into a single token with a special token type that the unwrapped line
1524 // parser will use to correctly rebuild the underlying code.
1525
1526 FileID ID;
1527 // Get the position of the first token in the line.
1528 unsigned FirstInLineOffset;
1529 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1530 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1531 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1532 // Calculate the offset of the start of the current line.
1533 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1534 if (LineOffset == StringRef::npos) {
1535 LineOffset = 0;
1536 } else {
1537 ++LineOffset;
1538 }
1539
1540 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1541 StringRef LineStart;
1542 if (FirstSpace == StringRef::npos) {
1543 LineStart = Buffer.substr(LineOffset);
1544 } else {
1545 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1546 }
1547
1548 TokenType Type = TT_Unknown;
1549 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1550 Type = TT_ConflictStart;
1551 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1552 LineStart == "====") {
1553 Type = TT_ConflictAlternative;
1554 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1555 Type = TT_ConflictEnd;
1556 }
1557
1558 if (Type != TT_Unknown) {
1559 FormatToken *Next = Tokens.back();
1560
1561 Tokens.resize(FirstInLineIndex + 1);
1562 // We do not need to build a complete token here, as we will skip it
1563 // during parsing anyway (as we must not touch whitespace around conflict
1564 // markers).
1565 Tokens.back()->Type = Type;
1566 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1567
1568 Tokens.push_back(Next);
1569 return true;
1570 }
1571
1572 return false;
1573 }
1574
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001575 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001576 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001577 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +00001578 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001579 Token Greater = FormatTok->Tok;
1580 FormatTok = new (Allocator.Allocate()) FormatToken;
1581 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001582 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001583 FormatTok->Tok.getLocation().getLocWithOffset(1);
1584 FormatTok->WhitespaceRange =
1585 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001586 FormatTok->TokenText = ">";
Alexander Kornienko39856b72013-09-10 09:38:25 +00001587 FormatTok->ColumnWidth = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001588 GreaterStashed = false;
1589 return FormatTok;
1590 }
1591
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001592 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001593 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001594 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001595 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001596 FormatTok->IsFirst = IsFirstToken;
1597 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001598
1599 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001600 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001601 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001602 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1603 switch (FormatTok->TokenText[i]) {
1604 case '\n':
1605 ++FormatTok->NewlinesBefore;
1606 // FIXME: This is technically incorrect, as it could also
1607 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001608 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1609 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1610 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +00001611 FormatTok->HasUnescapedNewline = true;
1612 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1613 Column = 0;
1614 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001615 case '\r':
1616 case '\f':
1617 case '\v':
1618 Column = 0;
1619 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001620 case ' ':
1621 ++Column;
1622 break;
1623 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001624 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001625 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001626 case '\\':
1627 ++Column;
1628 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1629 FormatTok->TokenText[i + 1] != '\n'))
1630 FormatTok->Type = TT_ImplicitStringLiteral;
1631 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001632 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001633 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001634 ++Column;
1635 break;
1636 }
1637 }
1638
Daniel Jasper877615c2013-10-11 19:45:02 +00001639 if (FormatTok->Type == TT_ImplicitStringLiteral)
1640 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001641 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001642
Daniel Jasper8369aa52013-07-16 20:28:33 +00001643 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001644 }
Manuel Klimekef920692013-01-07 07:56:50 +00001645
Manuel Klimek1abf7892013-01-04 23:34:14 +00001646 // In case the token starts with escaped newlines, we want to
1647 // take them into account as whitespace - this pattern is quite frequent
1648 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001649 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001650 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1651 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001652 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001653 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001654 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001655 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001656 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001657
1658 FormatTok->WhitespaceRange = SourceRange(
1659 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1660
Manuel Klimek31c85922013-08-29 15:21:40 +00001661 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001662
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001663 TrailingWhitespace = 0;
1664 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001665 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001666 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001667 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001668 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001669 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001670 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001671 FormatTok->Tok.setIdentifierInfo(&Info);
1672 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001673 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001674 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001675 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001676 GreaterStashed = true;
1677 }
1678
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001679 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001680
Alexander Kornienko39856b72013-09-10 09:38:25 +00001681 StringRef Text = FormatTok->TokenText;
1682 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001683 if (FirstNewlinePos == StringRef::npos) {
1684 // FIXME: ColumnWidth actually depends on the start column, we need to
1685 // take this into account when the token is moved.
1686 FormatTok->ColumnWidth =
1687 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1688 Column += FormatTok->ColumnWidth;
1689 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001690 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001691 // FIXME: ColumnWidth actually depends on the start column, we need to
1692 // take this into account when the token is moved.
1693 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1694 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1695
Alexander Kornienko39856b72013-09-10 09:38:25 +00001696 // The last line of the token always starts in column 0.
1697 // Thus, the length can be precomputed even in the presence of tabs.
1698 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1699 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1700 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001701 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001702 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001703
Daniel Jaspere1e43192014-04-01 12:55:11 +00001704 FormatTok->IsForEachMacro =
1705 std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1706 FormatTok->Tok.getIdentifierInfo());
1707
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001708 return FormatTok;
1709 }
1710
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001711 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001712 bool IsFirstToken;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001713 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001714 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001715 unsigned TrailingWhitespace;
Daniel Jasper23376252014-09-09 14:37:39 +00001716 std::unique_ptr<Lexer> Lex;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001717 SourceManager &SourceMgr;
Daniel Jasper23376252014-09-09 14:37:39 +00001718 FileID ID;
Manuel Klimek31c85922013-08-29 15:21:40 +00001719 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001720 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001721 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001722 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001723 // Index (in 'Tokens') of the last token that starts a new line.
1724 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001725 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001726 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001727
NAKAMURA Takumi7160c4d2014-08-06 16:53:13 +00001728 bool FormattingDisabled;
Daniel Jasper471894432014-08-06 13:40:26 +00001729
Daniel Jasper8369aa52013-07-16 20:28:33 +00001730 void readRawToken(FormatToken &Tok) {
Daniel Jasper23376252014-09-09 14:37:39 +00001731 Lex->LexFromRawLexer(Tok.Tok);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001732 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1733 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001734 // For formatting, treat unterminated string literals like normal string
1735 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001736 if (Tok.is(tok::unknown)) {
1737 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1738 Tok.Tok.setKind(tok::string_literal);
1739 Tok.IsUnterminatedLiteral = true;
1740 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1741 Tok.TokenText == "''") {
1742 Tok.Tok.setKind(tok::char_constant);
1743 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001744 }
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001745
1746 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1747 Tok.TokenText == "/* clang-format on */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001748 FormattingDisabled = false;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001749 }
1750
Daniel Jasper471894432014-08-06 13:40:26 +00001751 Tok.Finalized = FormattingDisabled;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001752
1753 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1754 Tok.TokenText == "/* clang-format off */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001755 FormattingDisabled = true;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001756 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001757 }
1758};
1759
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001760static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1761 switch (Language) {
1762 case FormatStyle::LK_Cpp:
1763 return "C++";
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001764 case FormatStyle::LK_Java:
1765 return "Java";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001766 case FormatStyle::LK_JavaScript:
1767 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001768 case FormatStyle::LK_Proto:
1769 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001770 default:
1771 return "Unknown";
1772 }
1773}
1774
Daniel Jasperf7935112012-12-03 18:12:45 +00001775class Formatter : public UnwrappedLineConsumer {
1776public:
Daniel Jasper23376252014-09-09 14:37:39 +00001777 Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
Daniel Jasperf7935112012-12-03 18:12:45 +00001778 const std::vector<CharSourceRange> &Ranges)
Daniel Jasper23376252014-09-09 14:37:39 +00001779 : Style(Style), ID(ID), SourceMgr(SourceMgr),
1780 Whitespaces(SourceMgr, Style,
1781 inputUsesCRLF(SourceMgr.getBufferData(ID))),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001782 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Daniel Jasper23376252014-09-09 14:37:39 +00001783 Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001784 DEBUG(llvm::dbgs() << "File encoding: "
1785 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1786 : "unknown")
1787 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001788 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1789 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001790 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001791
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001792 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001793 tooling::Replacements Result;
Daniel Jasper23376252014-09-09 14:37:39 +00001794 FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001795
1796 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001797 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001798 assert(UnwrappedLines.rbegin()->empty());
1799 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1800 ++Run) {
1801 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1802 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1803 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1804 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1805 }
1806 tooling::Replacements RunResult =
1807 format(AnnotatedLines, StructuralError, Tokens);
1808 DEBUG({
1809 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1810 for (tooling::Replacements::iterator I = RunResult.begin(),
1811 E = RunResult.end();
1812 I != E; ++I) {
1813 llvm::dbgs() << I->toString() << "\n";
1814 }
1815 });
1816 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1817 delete AnnotatedLines[i];
1818 }
1819 Result.insert(RunResult.begin(), RunResult.end());
1820 Whitespaces.reset();
1821 }
1822 return Result;
1823 }
1824
1825 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1826 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001827 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001828 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001829 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001830 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001831 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001832 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001833 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001834 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001835 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001836
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001837 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001838 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1839 BinPackInconclusiveFunctions);
Daniel Jasper5500f612013-11-25 11:08:59 +00001840 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001841 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001842 return Whitespaces.generateReplacements();
1843 }
1844
1845private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001846 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001847 // Returns \c true if at least one line between I and E or one of their
1848 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001849 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1850 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1851 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001852 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001853 while (I != E) {
1854 AnnotatedLine *Line = *I;
1855 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1856
1857 // If a line is part of a preprocessor directive, it needs to be formatted
1858 // if any token within the directive is affected.
1859 if (Line->InPPDirective) {
1860 FormatToken *Last = Line->Last;
1861 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1862 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1863 Last = (*PPEnd)->Last;
1864 ++PPEnd;
1865 }
1866
1867 if (affectsTokenRange(*Line->First, *Last,
1868 /*IncludeLeadingNewlines=*/false)) {
1869 SomeLineAffected = true;
1870 markAllAsAffected(I, PPEnd);
1871 }
1872 I = PPEnd;
1873 continue;
1874 }
1875
Daniel Jasper38c82402013-11-29 09:27:43 +00001876 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001877 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001878
Daniel Jasper38c82402013-11-29 09:27:43 +00001879 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001880 ++I;
1881 }
1882 return SomeLineAffected;
1883 }
1884
Daniel Jasper9c199562013-11-28 15:58:55 +00001885 // Determines whether 'Line' is affected by the SourceRanges given as input.
1886 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001887 bool nonPPLineAffected(AnnotatedLine *Line,
1888 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001889 bool SomeLineAffected = false;
1890 Line->ChildrenAffected =
1891 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1892 if (Line->ChildrenAffected)
1893 SomeLineAffected = true;
1894
1895 // Stores whether one of the line's tokens is directly affected.
1896 bool SomeTokenAffected = false;
1897 // Stores whether we need to look at the leading newlines of the next token
1898 // in order to determine whether it was affected.
1899 bool IncludeLeadingNewlines = false;
1900
1901 // Stores whether the first child line of any of this line's tokens is
1902 // affected.
1903 bool SomeFirstChildAffected = false;
1904
1905 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1906 // Determine whether 'Tok' was affected.
1907 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1908 SomeTokenAffected = true;
1909
1910 // Determine whether the first child of 'Tok' was affected.
1911 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1912 SomeFirstChildAffected = true;
1913
1914 IncludeLeadingNewlines = Tok->Children.empty();
1915 }
1916
1917 // Was this line moved, i.e. has it previously been on the same line as an
1918 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001919 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1920 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001921
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001922 bool IsContinuedComment =
1923 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1924 Line->First->NewlinesBefore < 2 && PreviousLine &&
1925 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001926
1927 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1928 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001929 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001930 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001931 }
1932 return SomeLineAffected;
1933 }
1934
Daniel Jasper5500f612013-11-25 11:08:59 +00001935 // Marks all lines between I and E as well as all their children as affected.
1936 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1937 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1938 while (I != E) {
1939 (*I)->Affected = true;
1940 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1941 ++I;
1942 }
1943 }
1944
1945 // Returns true if the range from 'First' to 'Last' intersects with one of the
1946 // input ranges.
1947 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1948 bool IncludeLeadingNewlines) {
1949 SourceLocation Start = First.WhitespaceRange.getBegin();
1950 if (!IncludeLeadingNewlines)
1951 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001952 SourceLocation End = Last.getStartOfNonWhitespace();
1953 if (Last.TokenText.size() > 0)
1954 End = End.getLocWithOffset(Last.TokenText.size() - 1);
Daniel Jasper5500f612013-11-25 11:08:59 +00001955 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1956 return affectsCharSourceRange(Range);
1957 }
1958
1959 // Returns true if one of the input ranges intersect the leading empty lines
1960 // before 'Tok'.
1961 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1962 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1963 Tok.WhitespaceRange.getBegin(),
1964 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1965 return affectsCharSourceRange(EmptyLineRange);
1966 }
1967
1968 // Returns true if 'Range' intersects with one of the input ranges.
1969 bool affectsCharSourceRange(const CharSourceRange &Range) {
1970 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1971 E = Ranges.end();
1972 I != E; ++I) {
1973 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1974 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1975 return true;
1976 }
1977 return false;
1978 }
1979
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001980 static bool inputUsesCRLF(StringRef Text) {
1981 return Text.count('\r') * 2 > Text.count('\n');
1982 }
1983
Manuel Klimek71814b42013-10-11 21:25:45 +00001984 void
1985 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001986 unsigned CountBoundToVariable = 0;
1987 unsigned CountBoundToType = 0;
1988 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001989 bool HasBinPackedFunction = false;
1990 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001991 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001992 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001993 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001994 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001995 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001996 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001997 bool SpacesBefore =
1998 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1999 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
2000 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002001 if (SpacesBefore && !SpacesAfter)
2002 ++CountBoundToVariable;
2003 else if (!SpacesBefore && SpacesAfter)
2004 ++CountBoundToType;
2005 }
2006
Daniel Jasperfba84ff2013-10-12 05:16:06 +00002007 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
2008 if (Tok->is(tok::coloncolon) &&
2009 Tok->Previous->Type == TT_TemplateOpener)
2010 HasCpp03IncompatibleFormat = true;
2011 if (Tok->Type == TT_TemplateCloser &&
2012 Tok->Previous->Type == TT_TemplateCloser)
2013 HasCpp03IncompatibleFormat = true;
2014 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002015
2016 if (Tok->PackingKind == PPK_BinPacked)
2017 HasBinPackedFunction = true;
2018 if (Tok->PackingKind == PPK_OnePerLine)
2019 HasOnePerLineFunction = true;
2020
Manuel Klimek6e6310e2013-05-29 14:47:47 +00002021 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002022 }
2023 }
Daniel Jasper553d4872014-06-17 12:40:34 +00002024 if (Style.DerivePointerAlignment) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002025 if (CountBoundToType > CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00002026 Style.PointerAlignment = FormatStyle::PAS_Left;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002027 else if (CountBoundToType < CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00002028 Style.PointerAlignment = FormatStyle::PAS_Right;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002029 }
2030 if (Style.Standard == FormatStyle::LS_Auto) {
2031 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
2032 : FormatStyle::LS_Cpp03;
2033 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002034 BinPackInconclusiveFunctions =
2035 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002036 }
2037
Craig Topperfb6b25b2014-03-15 04:29:04 +00002038 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00002039 assert(!UnwrappedLines.empty());
2040 UnwrappedLines.back().push_back(TheLine);
2041 }
2042
Craig Topperfb6b25b2014-03-15 04:29:04 +00002043 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00002044 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00002045 }
2046
2047 FormatStyle Style;
Daniel Jasper23376252014-09-09 14:37:39 +00002048 FileID ID;
Daniel Jasperf7935112012-12-03 18:12:45 +00002049 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00002050 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00002051 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00002052 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00002053
2054 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002055 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00002056};
2057
Craig Topperaf35e852013-06-30 22:29:28 +00002058} // end anonymous namespace
2059
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00002060tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
2061 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00002062 std::vector<CharSourceRange> Ranges) {
Daniel Jasper23376252014-09-09 14:37:39 +00002063 if (Style.DisableFormat)
2064 return tooling::Replacements();
2065 return reformat(Style, SourceMgr,
2066 SourceMgr.getFileID(Lex.getSourceLocation()), Ranges);
2067}
Daniel Jasperc64b09a2014-05-22 15:12:22 +00002068
Daniel Jasper23376252014-09-09 14:37:39 +00002069tooling::Replacements reformat(const FormatStyle &Style,
2070 SourceManager &SourceMgr, FileID ID,
2071 std::vector<CharSourceRange> Ranges) {
2072 if (Style.DisableFormat)
2073 return tooling::Replacements();
2074 Formatter formatter(Style, SourceMgr, ID, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00002075 return formatter.format();
2076}
2077
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002078tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
2079 std::vector<tooling::Range> Ranges,
2080 StringRef FileName) {
Daniel Jasper23376252014-09-09 14:37:39 +00002081 if (Style.DisableFormat)
2082 return tooling::Replacements();
2083
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002084 FileManager Files((FileSystemOptions()));
2085 DiagnosticsEngine Diagnostics(
2086 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2087 new DiagnosticOptions);
2088 SourceManager SourceMgr(Diagnostics, Files);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00002089 std::unique_ptr<llvm::MemoryBuffer> Buf =
2090 llvm::MemoryBuffer::getMemBuffer(Code, FileName);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002091 const clang::FileEntry *Entry =
2092 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
David Blaikie49cc3182014-08-27 20:54:45 +00002093 SourceMgr.overrideFileContents(Entry, std::move(Buf));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002094 FileID ID =
2095 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002096 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
2097 std::vector<CharSourceRange> CharRanges;
2098 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
2099 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
2100 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
2101 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
2102 }
Daniel Jasper23376252014-09-09 14:37:39 +00002103 return reformat(Style, SourceMgr, ID, CharRanges);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002104}
2105
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002106LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002107 LangOptions LangOpts;
2108 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002109 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2110 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00002111 LangOpts.LineComment = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002112 LangOpts.CXXOperatorNames =
2113 Style.Language != FormatStyle::LK_JavaScript ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002114 LangOpts.Bool = 1;
2115 LangOpts.ObjC1 = 1;
2116 LangOpts.ObjC2 = 1;
2117 return LangOpts;
2118}
2119
Edwin Vaned544aa72013-09-30 13:31:48 +00002120const char *StyleOptionHelpDescription =
2121 "Coding style, currently supports:\n"
2122 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
2123 "Use -style=file to load style configuration from\n"
2124 ".clang-format file located in one of the parent\n"
2125 "directories of the source file (or current\n"
2126 "directory for stdin).\n"
2127 "Use -style=\"{key: value, ...}\" to set specific\n"
2128 "parameters, e.g.:\n"
2129 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
2130
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002131static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00002132 if (FileName.endswith(".java")) {
2133 return FormatStyle::LK_Java;
2134 } else if (FileName.endswith_lower(".js")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002135 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00002136 } else if (FileName.endswith_lower(".proto") ||
2137 FileName.endswith_lower(".protodevel")) {
2138 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002139 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002140 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002141}
2142
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002143FormatStyle getStyle(StringRef StyleName, StringRef FileName,
2144 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002145 FormatStyle Style = getLLVMStyle();
2146 Style.Language = getLanguageByFileName(FileName);
2147 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002148 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
2149 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002150 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002151 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002152
2153 if (StyleName.startswith("{")) {
2154 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00002155 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002156 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
2157 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00002158 }
2159 return Style;
2160 }
2161
2162 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002163 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00002164 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
2165 << " style\n";
2166 return Style;
2167 }
2168
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002169 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002170 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00002171 SmallString<128> Path(FileName);
2172 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002173 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00002174 Directory = llvm::sys::path::parent_path(Directory)) {
2175 if (!llvm::sys::fs::is_directory(Directory))
2176 continue;
2177 SmallString<128> ConfigFile(Directory);
2178
2179 llvm::sys::path::append(ConfigFile, ".clang-format");
2180 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2181 bool IsFile = false;
2182 // Ignore errors from is_regular_file: we only need to know if we can read
2183 // the file or not.
2184 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2185
2186 if (!IsFile) {
2187 // Try _clang-format too, since dotfiles are not commonly used on Windows.
2188 ConfigFile = Directory;
2189 llvm::sys::path::append(ConfigFile, "_clang-format");
2190 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2191 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2192 }
2193
2194 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002195 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
2196 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
2197 if (std::error_code EC = Text.getError()) {
2198 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002199 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002200 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002201 if (std::error_code ec =
2202 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00002203 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002204 if (!UnsuitableConfigFiles.empty())
2205 UnsuitableConfigFiles.append(", ");
2206 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002207 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002208 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002209 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2210 << "\n";
2211 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002212 }
2213 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2214 return Style;
2215 }
2216 }
2217 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
2218 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002219 if (!UnsuitableConfigFiles.empty()) {
2220 llvm::errs() << "Configuration file(s) do(es) not support "
2221 << getLanguageName(Style.Language) << ": "
2222 << UnsuitableConfigFiles << "\n";
2223 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002224 return Style;
2225}
2226
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002227} // namespace format
2228} // namespace clang