blob: 58dd5604e42799b048f0e10b463989512004ec18 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
Daniel Jasperf7935112012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Daniel Jasperde0328a2013-08-16 11:20:30 +000016#include "ContinuationIndenter.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000017#include "TokenAnnotator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "UnwrappedLineParser.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000019#include "WhitespaceManager.h"
Daniel Jasperec04c0d2013-05-16 10:40:07 +000020#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000021#include "clang/Basic/DiagnosticOptions.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000023#include "clang/Format/Format.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000024#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000025#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000026#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000027#include "llvm/Support/Debug.h"
Edwin Vaned544aa72013-09-30 13:31:48 +000028#include "llvm/Support/Path.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000029#include "llvm/Support/YAMLTraits.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000030#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000031#include <string>
32
Chandler Carruth10346662014-04-22 03:17:02 +000033#define DEBUG_TYPE "format-formatter"
34
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000035using clang::format::FormatStyle;
36
Daniel Jaspere1e43192014-04-01 12:55:11 +000037LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
38
Alexander Kornienkod6538332013-05-07 15:32:14 +000039namespace llvm {
40namespace yaml {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000041template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
42 static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
43 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
44 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
Daniel Jasper7052ce62014-01-19 09:04:08 +000045 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000046 }
47};
48
49template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
50 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
51 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
52 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
53 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
54 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
55 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
56 }
57};
58
59template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
60 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
61 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
62 IO.enumCase(Value, "false", FormatStyle::UT_Never);
63 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
64 IO.enumCase(Value, "true", FormatStyle::UT_Always);
65 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
66 }
67};
68
Daniel Jasperd74cf402014-04-08 12:46:38 +000069template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
70 static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
71 IO.enumCase(Value, "None", FormatStyle::SFS_None);
72 IO.enumCase(Value, "false", FormatStyle::SFS_None);
73 IO.enumCase(Value, "All", FormatStyle::SFS_All);
74 IO.enumCase(Value, "true", FormatStyle::SFS_All);
75 IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
76 }
77};
78
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000079template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
80 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
81 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
82 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
83 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
84 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
Alexander Kornienko3a33f022013-12-12 09:49:52 +000085 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000086 }
87};
88
Alexander Kornienkod6538332013-05-07 15:32:14 +000089template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000090struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +000091 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000092 FormatStyle::NamespaceIndentationKind &Value) {
93 IO.enumCase(Value, "None", FormatStyle::NI_None);
94 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
95 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +000096 }
97};
98
99template <>
Daniel Jasper553d4872014-06-17 12:40:34 +0000100struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
101 static void enumeration(IO &IO,
102 FormatStyle::PointerAlignmentStyle &Value) {
103 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
104 IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
105 IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
106
Alp Toker958027b2014-07-14 19:42:55 +0000107 // For backward compatibility.
Daniel Jasper553d4872014-06-17 12:40:34 +0000108 IO.enumCase(Value, "true", FormatStyle::PAS_Left);
109 IO.enumCase(Value, "false", FormatStyle::PAS_Right);
110 }
111};
112
113template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000114struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000115 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000116 FormatStyle::SpaceBeforeParensOptions &Value) {
117 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000118 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000119 FormatStyle::SBPO_ControlStatements);
120 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000121
122 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000123 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
124 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000125 }
126};
127
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000128template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000129 static void mapping(IO &IO, FormatStyle &Style) {
130 // When reading, read the language first, we need it for getPredefinedStyle.
131 IO.mapOptional("Language", Style.Language);
132
Alexander Kornienko49149672013-05-10 11:56:10 +0000133 if (IO.outputting()) {
Alexander Kornienkoe3648fb2013-09-02 16:39:23 +0000134 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000135 "Mozilla", "WebKit", "GNU" };
Alexander Kornienko49149672013-05-10 11:56:10 +0000136 ArrayRef<StringRef> Styles(StylesArray);
137 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
138 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000139 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000140 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000141 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000142 IO.mapOptional("# BasedOnStyle", StyleName);
143 break;
144 }
145 }
146 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000147 StringRef BasedOnStyle;
148 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000149 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000150 FormatStyle::LanguageKind OldLanguage = Style.Language;
151 FormatStyle::LanguageKind Language =
152 ((FormatStyle *)IO.getContext())->Language;
153 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000154 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
155 return;
156 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000157 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000158 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000159 }
160
161 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000162 IO.mapOptional("ConstructorInitializerIndentWidth",
163 Style.ConstructorInitializerIndentWidth);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000164 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000165 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000166 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
167 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000168 IO.mapOptional("AllowShortBlocksOnASingleLine",
169 Style.AllowShortBlocksOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000170 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
171 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000172 IO.mapOptional("AllowShortLoopsOnASingleLine",
173 Style.AllowShortLoopsOnASingleLine);
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000174 IO.mapOptional("AllowShortFunctionsOnASingleLine",
175 Style.AllowShortFunctionsOnASingleLine);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000176 IO.mapOptional("AlwaysBreakTemplateDeclarations",
177 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko58611712013-07-04 12:02:44 +0000178 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
179 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000180 IO.mapOptional("BreakBeforeBinaryOperators",
181 Style.BreakBeforeBinaryOperators);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000182 IO.mapOptional("BreakBeforeTernaryOperators",
183 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000184 IO.mapOptional("BreakConstructorInitializersBeforeComma",
185 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000186 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
187 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
188 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
189 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000190 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000191 IO.mapOptional("ExperimentalAutoDetectBinPacking",
192 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000193 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000194 IO.mapOptional("IndentWrappedFunctionNames",
195 Style.IndentWrappedFunctionNames);
196 IO.mapOptional("IndentFunctionDeclarationAfterType",
197 Style.IndentWrappedFunctionNames);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000198 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000199 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
200 Style.KeepEmptyLinesAtTheStartOfBlocks);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000201 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000202 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000203 IO.mapOptional("ObjCSpaceBeforeProtocolList",
204 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000205 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
206 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000207 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
208 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000209 IO.mapOptional("PenaltyBreakFirstLessLess",
210 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000211 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
212 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
213 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000214 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000215 IO.mapOptional("SpacesBeforeTrailingComments",
216 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000217 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000218 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000219 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000220 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000221 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000222 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000223 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000224 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasperf110e202013-08-21 08:39:01 +0000225 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000226 IO.mapOptional("SpacesInCStyleCastParentheses",
227 Style.SpacesInCStyleCastParentheses);
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000228 IO.mapOptional("SpacesInContainerLiterals",
229 Style.SpacesInContainerLiterals);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000230 IO.mapOptional("SpaceBeforeAssignmentOperators",
231 Style.SpaceBeforeAssignmentOperators);
Daniel Jasper6633ab82013-10-18 10:38:14 +0000232 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000233 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000234 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000235
236 // For backward compatibility.
237 if (!IO.outputting()) {
238 IO.mapOptional("SpaceAfterControlStatementKeyword",
239 Style.SpaceBeforeParens);
Daniel Jasper553d4872014-06-17 12:40:34 +0000240 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
241 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000242 }
243 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000244 IO.mapOptional("DisableFormat", Style.DisableFormat);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000245 }
246};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000247
248// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000249// IO.getContext() should contain a pointer to the FormatStyle structure, that
250// will be used to get default values for missing keys.
251// If the first element has no Language specified, it will be treated as the
252// default one for the following elements.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000253template <> struct DocumentListTraits<std::vector<FormatStyle> > {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000254 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
255 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000256 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000257 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000258 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000259 if (Index >= Seq.size()) {
260 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000261 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000262 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000263 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000264 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000265 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000266 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000267 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000268 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000269 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000270 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000271 }
272};
Alexander Kornienkod6538332013-05-07 15:32:14 +0000273}
274}
275
Daniel Jasperf7935112012-12-03 18:12:45 +0000276namespace clang {
277namespace format {
278
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000279const std::error_category &getParseCategory() {
Rafael Espindolad0136702014-06-12 02:50:04 +0000280 static ParseErrorCategory C;
281 return C;
282}
283std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000284 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000285}
286
287const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
288 return "clang-format.parse_error";
289}
290
291std::string ParseErrorCategory::message(int EV) const {
292 switch (static_cast<ParseError>(EV)) {
293 case ParseError::Success:
294 return "Success";
295 case ParseError::Error:
296 return "Invalid argument";
297 case ParseError::Unsuitable:
298 return "Unsuitable";
299 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000300 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000301}
302
Daniel Jasperf7935112012-12-03 18:12:45 +0000303FormatStyle getLLVMStyle() {
304 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000305 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000306 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000307 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000308 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000309 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000310 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000311 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000312 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000313 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000314 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000315 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000316 LLVMStyle.BinPackParameters = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000317 LLVMStyle.BreakBeforeBinaryOperators = false;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000318 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000319 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
320 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000321 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000322 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000323 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000324 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000325 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000326 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000327 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000328 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000329 LLVMStyle.ForEachMacros.push_back("foreach");
330 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
331 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000332 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000333 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000334 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000335 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000336 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000337 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000338 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000339 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000340 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000341 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000342 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000343 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000344 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000345 LLVMStyle.SpacesInParentheses = false;
346 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000347 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000348 LLVMStyle.SpacesInCStyleCastParentheses = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000349 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000350 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000351 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000352
Daniel Jasper19a541e2013-12-19 16:45:34 +0000353 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000354 LLVMStyle.PenaltyBreakFirstLessLess = 120;
355 LLVMStyle.PenaltyBreakString = 1000;
356 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000357 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000358 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000359
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000360 LLVMStyle.DisableFormat = false;
361
Daniel Jasperf7935112012-12-03 18:12:45 +0000362 return LLVMStyle;
363}
364
Nico Weber514ecc82014-02-02 20:50:45 +0000365FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000366 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000367 GoogleStyle.Language = Language;
368
Daniel Jasperf7935112012-12-03 18:12:45 +0000369 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000370 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000371 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000372 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000373 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000374 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000375 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000376 GoogleStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000377 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000378 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000379 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000380 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000381 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000382 GoogleStyle.SpacesBeforeTrailingComments = 2;
383 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000384
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000385 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000386 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000387
Nico Weber514ecc82014-02-02 20:50:45 +0000388 if (Language == FormatStyle::LK_JavaScript) {
389 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000390 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000391 GoogleStyle.SpacesInContainerLiterals = false;
392 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000393 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000394 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000395 }
396
Daniel Jasperf7935112012-12-03 18:12:45 +0000397 return GoogleStyle;
398}
399
Nico Weber514ecc82014-02-02 20:50:45 +0000400FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
401 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Daniel Jasperf7db4332013-01-29 16:03:49 +0000402 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000403 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000404 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000405 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000406 ChromiumStyle.BinPackParameters = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000407 ChromiumStyle.DerivePointerAlignment = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000408 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000409 return ChromiumStyle;
410}
411
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000412FormatStyle getMozillaStyle() {
413 FormatStyle MozillaStyle = getLLVMStyle();
414 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000415 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000416 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000417 MozillaStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000418 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000419 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000420 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
421 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000422 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000423 MozillaStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000424 return MozillaStyle;
425}
426
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000427FormatStyle getWebKitStyle() {
428 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000429 Style.AccessModifierOffset = -4;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000430 Style.AlignTrailingComments = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000431 Style.BreakBeforeBinaryOperators = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000432 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000433 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000434 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000435 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000436 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000437 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000438 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000439 Style.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000440 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000441 return Style;
442}
443
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000444FormatStyle getGNUStyle() {
445 FormatStyle Style = getLLVMStyle();
446 Style.BreakBeforeBinaryOperators = true;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000447 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000448 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000449 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000450 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000451 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000452 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000453 return Style;
454}
455
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000456FormatStyle getNoStyle() {
457 FormatStyle NoStyle = getLLVMStyle();
458 NoStyle.DisableFormat = true;
459 return NoStyle;
460}
461
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000462bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
463 FormatStyle *Style) {
464 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000465 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000466 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000467 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000468 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000469 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000470 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000471 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000472 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000473 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000474 } else if (Name.equals_lower("gnu")) {
475 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000476 } else if (Name.equals_lower("none")) {
477 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000478 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000479 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000480 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000481
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000482 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000483 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000484}
485
Rafael Espindolac0809172014-06-12 14:02:15 +0000486std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000487 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000488 FormatStyle::LanguageKind Language = Style->Language;
489 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000490 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000491 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000492
493 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000494 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000495 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
496 // values for the fields, keys for which are missing from the configuration.
497 // Mapping also uses the context to get the language to find the correct
498 // base style.
499 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000500 Input >> Styles;
501 if (Input.error())
502 return Input.error();
503
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000504 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000505 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000506 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000507 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000508 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000509 for (unsigned j = 0; j < i; ++j) {
510 if (Styles[i].Language == Styles[j].Language) {
511 DEBUG(llvm::dbgs()
512 << "Duplicate languages in the config file on positions " << j
513 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000514 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000515 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000516 }
517 }
518 // Look for a suitable configuration starting from the end, so we can
519 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000520 // configuration (which can only be at slot 0) after it.
521 for (int i = Styles.size() - 1; i >= 0; --i) {
522 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000523 Styles[i].Language == FormatStyle::LK_None) {
524 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000525 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000526 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000527 }
528 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000529 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000530}
531
532std::string configurationAsText(const FormatStyle &Style) {
533 std::string Text;
534 llvm::raw_string_ostream Stream(Text);
535 llvm::yaml::Output Output(Stream);
536 // We use the same mapping method for input and output, so we need a non-const
537 // reference here.
538 FormatStyle NonConstStyle = Style;
539 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000540 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000541}
542
Craig Topperaf35e852013-06-30 22:29:28 +0000543namespace {
544
Daniel Jasperde0328a2013-08-16 11:20:30 +0000545class NoColumnLimitFormatter {
546public:
Daniel Jasperf110e202013-08-21 08:39:01 +0000547 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000548
549 /// \brief Formats the line starting at \p State, simply keeping all of the
550 /// input's line breaking decisions.
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000551 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000552 LineState State =
553 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Craig Topper2145bc02014-05-09 08:15:10 +0000554 while (State.NextToken) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000555 bool Newline =
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000556 Indenter->mustBreak(State) ||
Daniel Jasperde0328a2013-08-16 11:20:30 +0000557 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
558 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
559 }
560 }
Daniel Jasperf110e202013-08-21 08:39:01 +0000561
Daniel Jasperde0328a2013-08-16 11:20:30 +0000562private:
563 ContinuationIndenter *Indenter;
564};
565
Daniel Jasper56f8b432013-11-06 23:12:09 +0000566class LineJoiner {
567public:
568 LineJoiner(const FormatStyle &Style) : Style(Style) {}
569
570 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
571 unsigned
572 tryFitMultipleLinesInOne(unsigned Indent,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000573 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000574 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
575 // We can never merge stuff if there are trailing line comments.
Daniel Jasper234379f2013-12-24 13:31:25 +0000576 const AnnotatedLine *TheLine = *I;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000577 if (TheLine->Last->Type == TT_LineComment)
578 return 0;
579
Alexander Kornienkoecc232d2013-12-04 13:25:26 +0000580 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
581 return 0;
582
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000583 unsigned Limit =
584 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000585 // If we already exceed the column limit, we set 'Limit' to 0. The different
586 // tryMerge..() functions can then decide whether to still do merging.
587 Limit = TheLine->Last->TotalLength > Limit
588 ? 0
589 : Limit - TheLine->Last->TotalLength;
590
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000591 if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000592 return 0;
593
Daniel Jasperd74cf402014-04-08 12:46:38 +0000594 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
595 // If necessary, change to something smarter.
596 bool MergeShortFunctions =
597 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
598 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
599 TheLine->Level != 0);
600
Daniel Jasper234379f2013-12-24 13:31:25 +0000601 if (TheLine->Last->Type == TT_FunctionLBrace &&
602 TheLine->First != TheLine->Last) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000603 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000604 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000605 if (TheLine->Last->is(tok::l_brace)) {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000606 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000607 ? tryMergeSimpleBlock(I, E, Limit)
608 : 0;
609 }
610 if (I[1]->First->Type == TT_FunctionLBrace &&
611 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
Alp Tokerba5b4dc2013-12-30 02:06:29 +0000612 // Check for Limit <= 2 to account for the " {".
Daniel Jasper234379f2013-12-24 13:31:25 +0000613 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
614 return 0;
615 Limit -= 2;
616
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000617 unsigned MergedLines = 0;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000618 if (MergeShortFunctions) {
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000619 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
620 // If we managed to merge the block, count the function header, which is
621 // on a separate line.
622 if (MergedLines > 0)
623 ++MergedLines;
624 }
625 return MergedLines;
626 }
627 if (TheLine->First->is(tok::kw_if)) {
628 return Style.AllowShortIfStatementsOnASingleLine
629 ? tryMergeSimpleControlStatement(I, E, Limit)
630 : 0;
631 }
632 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
633 return Style.AllowShortLoopsOnASingleLine
634 ? tryMergeSimpleControlStatement(I, E, Limit)
635 : 0;
636 }
637 if (TheLine->InPPDirective &&
638 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000639 return tryMergeSimplePPDirective(I, E, Limit);
640 }
641 return 0;
642 }
643
644private:
645 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000646 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000647 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
648 unsigned Limit) {
649 if (Limit == 0)
650 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000651 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000652 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000653 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000654 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000655 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000656 return 0;
657 return 1;
658 }
659
660 unsigned tryMergeSimpleControlStatement(
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000661 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000662 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
663 if (Limit == 0)
664 return 0;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000665 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
666 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
Daniel Jasper17605d32014-05-14 09:33:35 +0000667 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000668 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000669 if (I[1]->InPPDirective != (*I)->InPPDirective ||
670 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000671 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000672 Limit = limitConsideringMacros(I + 1, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000673 AnnotatedLine &Line = **I;
674 if (Line.Last->isNot(tok::r_paren))
675 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000676 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000677 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000678 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000679 tok::kw_while) ||
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000680 I[1]->First->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000681 return 0;
682 // Only inline simple if's (no nested if or else).
683 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000684 I[2]->First->is(tok::kw_else))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000685 return 0;
686 return 1;
687 }
688
689 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000690 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000691 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
692 unsigned Limit) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000693 AnnotatedLine &Line = **I;
Daniel Jasper17605d32014-05-14 09:33:35 +0000694
695 // Don't merge ObjC @ keywords and methods.
696 if (Line.First->isOneOf(tok::at, tok::minus, tok::plus))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000697 return 0;
698
Daniel Jasper17605d32014-05-14 09:33:35 +0000699 // Check that the current line allows merging. This depends on whether we
700 // are in a control flow statements as well as several style flags.
701 if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
702 return 0;
703 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
704 tok::kw_catch, tok::kw_for, tok::r_brace)) {
705 if (!Style.AllowShortBlocksOnASingleLine)
706 return 0;
707 if (!Style.AllowShortIfStatementsOnASingleLine &&
708 Line.First->is(tok::kw_if))
709 return 0;
710 if (!Style.AllowShortLoopsOnASingleLine &&
711 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
712 return 0;
713 // FIXME: Consider an option to allow short exception handling clauses on
714 // a single line.
715 if (Line.First->isOneOf(tok::kw_try, tok::kw_catch))
716 return 0;
717 }
718
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000719 FormatToken *Tok = I[1]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000720 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Craig Topper2145bc02014-05-09 08:15:10 +0000721 (Tok->getNextNonComment() == nullptr ||
Daniel Jasper56f8b432013-11-06 23:12:09 +0000722 Tok->getNextNonComment()->is(tok::semi))) {
723 // We merge empty blocks even if the line exceeds the column limit.
724 Tok->SpacesRequiredBefore = 0;
725 Tok->CanBreakBefore = true;
726 return 1;
727 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Daniel Jasper79dffb42014-05-07 09:48:30 +0000728 // We don't merge short records.
729 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
730 return 0;
731
Daniel Jasper56f8b432013-11-06 23:12:09 +0000732 // Check that we still have three lines and they fit into the limit.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000733 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000734 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000735 Limit = limitConsideringMacros(I + 2, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000736
737 if (!nextTwoLinesFitInto(I, Limit))
738 return 0;
739
740 // Second, check that the next line does not contain any braces - if it
741 // does, readability declines when putting it into a single line.
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000742 if (I[1]->Last->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000743 return 0;
744 do {
Daniel Jasperbd630732014-05-22 13:25:26 +0000745 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000746 return 0;
747 Tok = Tok->Next;
Craig Topper2145bc02014-05-09 08:15:10 +0000748 } while (Tok);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000749
Daniel Jasper79dffb42014-05-07 09:48:30 +0000750 // Last, check that the third line starts with a closing brace.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000751 Tok = I[2]->First;
Daniel Jasper79dffb42014-05-07 09:48:30 +0000752 if (Tok->isNot(tok::r_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000753 return 0;
754
755 return 2;
756 }
757 return 0;
758 }
759
Daniel Jasper64989962014-02-07 13:45:27 +0000760 /// Returns the modified column limit for \p I if it is inside a macro and
761 /// needs a trailing '\'.
762 unsigned
Daniel Jaspera0407742014-02-11 10:08:11 +0000763 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper64989962014-02-07 13:45:27 +0000764 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
765 unsigned Limit) {
766 if (I[0]->InPPDirective && I + 1 != E &&
767 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
768 return Limit < 2 ? 0 : Limit - 2;
769 }
770 return Limit;
771 }
772
Daniel Jasper56f8b432013-11-06 23:12:09 +0000773 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
774 unsigned Limit) {
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000775 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
776 return false;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000777 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000778 }
779
Daniel Jasper234379f2013-12-24 13:31:25 +0000780 bool containsMustBreak(const AnnotatedLine *Line) {
781 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
782 if (Tok->MustBreakBefore)
783 return true;
784 }
785 return false;
786 }
787
Daniel Jasper56f8b432013-11-06 23:12:09 +0000788 const FormatStyle &Style;
789};
790
Daniel Jasperf7935112012-12-03 18:12:45 +0000791class UnwrappedLineFormatter {
792public:
Daniel Jasper5500f612013-11-25 11:08:59 +0000793 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000794 WhitespaceManager *Whitespaces,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000795 const FormatStyle &Style)
Daniel Jasper5500f612013-11-25 11:08:59 +0000796 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
797 Joiner(Style) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000798
Daniel Jasper56f8b432013-11-06 23:12:09 +0000799 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper9c199562013-11-28 15:58:55 +0000800 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Daniel Jasperc359ad02014-04-15 08:13:47 +0000801 // Try to look up already computed penalty in DryRun-mode.
NAKAMURA Takumi22059522014-04-15 23:29:04 +0000802 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
803 &Lines, AdditionalIndent);
Daniel Jasperc359ad02014-04-15 08:13:47 +0000804 auto CacheIt = PenaltyCache.find(CacheKey);
805 if (DryRun && CacheIt != PenaltyCache.end())
806 return CacheIt->second;
807
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000808 assert(!Lines.empty());
809 unsigned Penalty = 0;
810 std::vector<int> IndentForLevel;
811 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
812 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Craig Topper2145bc02014-05-09 08:15:10 +0000813 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000814 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
815 E = Lines.end();
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000816 I != E; ++I) {
817 const AnnotatedLine &TheLine = **I;
818 const FormatToken *FirstTok = TheLine.First;
819 int Offset = getIndentOffset(*FirstTok);
820
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000821 // Determine indent and try to merge multiple unwrapped lines.
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000822 unsigned Indent;
823 if (TheLine.InPPDirective) {
824 Indent = TheLine.Level * Style.IndentWidth;
825 } else {
826 while (IndentForLevel.size() <= TheLine.Level)
827 IndentForLevel.push_back(-1);
828 IndentForLevel.resize(TheLine.Level + 1);
829 Indent = getIndent(IndentForLevel, TheLine.Level);
830 }
831 unsigned LevelIndent = Indent;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000832 if (static_cast<int>(Indent) + Offset >= 0)
833 Indent += Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000834
835 // Merge multiple lines if possible.
Daniel Jasper56f8b432013-11-06 23:12:09 +0000836 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
Alexander Kornienko31e95542013-12-04 12:21:08 +0000837 if (MergedLines > 0 && Style.ColumnLimit == 0) {
838 // Disallow line merging if there is a break at the start of one of the
839 // input lines.
840 for (unsigned i = 0; i < MergedLines; ++i) {
841 if (I[i + 1]->First->NewlinesBefore > 0)
842 MergedLines = 0;
843 }
844 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000845 if (!DryRun) {
846 for (unsigned i = 0; i < MergedLines; ++i) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000847 join(*I[i], *I[i + 1]);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000848 }
849 }
850 I += MergedLines;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000851
Daniel Jasper9c199562013-11-28 15:58:55 +0000852 bool FixIndentation =
853 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000854 if (TheLine.First->is(tok::eof)) {
Daniel Jasper5500f612013-11-25 11:08:59 +0000855 if (PreviousLine && PreviousLine->Affected && !DryRun) {
856 // Remove the file's trailing whitespace.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000857 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
858 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
859 /*IndentLevel=*/0, /*Spaces=*/0,
860 /*TargetColumn=*/0);
861 }
Daniel Jasper9c199562013-11-28 15:58:55 +0000862 } else if (TheLine.Type != LT_Invalid &&
863 (TheLine.Affected || FixIndentation)) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000864 if (FirstTok->WhitespaceRange.isValid()) {
865 if (!DryRun)
866 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
867 Indent, TheLine.InPPDirective);
868 } else {
869 Indent = LevelIndent = FirstTok->OriginalColumn;
870 }
871
872 // If everything fits on a single line, just put it there.
873 unsigned ColumnLimit = Style.ColumnLimit;
874 if (I + 1 != E) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000875 AnnotatedLine *NextLine = I[1];
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000876 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
877 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
878 }
879
880 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
881 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000882 while (State.NextToken) {
883 formatChildren(State, /*Newline=*/false, /*DryRun=*/false, Penalty);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000884 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000885 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000886 } else if (Style.ColumnLimit == 0) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000887 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000888 NoColumnLimitFormatter Formatter(Indenter);
889 if (!DryRun)
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000890 Formatter.format(Indent, &TheLine);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000891 } else {
892 Penalty += format(TheLine, Indent, DryRun);
893 }
894
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000895 if (!TheLine.InPPDirective)
896 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper9c199562013-11-28 15:58:55 +0000897 } else if (TheLine.ChildrenAffected) {
898 format(TheLine.Children, DryRun);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000899 } else {
900 // Format the first token if necessary, and notify the WhitespaceManager
901 // about the unchanged whitespace.
Craig Topper2145bc02014-05-09 08:15:10 +0000902 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000903 if (Tok == TheLine.First &&
904 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
905 unsigned LevelIndent = Tok->OriginalColumn;
906 if (!DryRun) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000907 // Remove trailing whitespace of the previous line.
Daniel Jasper5500f612013-11-25 11:08:59 +0000908 if ((PreviousLine && PreviousLine->Affected) ||
909 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000910 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
911 TheLine.InPPDirective);
912 } else {
913 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
914 }
915 }
916
917 if (static_cast<int>(LevelIndent) - Offset >= 0)
918 LevelIndent -= Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000919 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000920 IndentForLevel[TheLine.Level] = LevelIndent;
921 } else if (!DryRun) {
922 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
923 }
924 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000925 }
926 if (!DryRun) {
Craig Topper2145bc02014-05-09 08:15:10 +0000927 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000928 Tok->Finalized = true;
929 }
930 }
931 PreviousLine = *I;
932 }
Daniel Jasperc359ad02014-04-15 08:13:47 +0000933 PenaltyCache[CacheKey] = Penalty;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000934 return Penalty;
935 }
936
937private:
938 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000939 ///
940 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000941 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
942 bool DryRun) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000943 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +0000944
Daniel Jasperacc33662013-02-08 08:22:00 +0000945 // If the ObjC method declaration does not fit on a line, we should format
946 // it with one arg per line.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000947 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperacc33662013-02-08 08:22:00 +0000948 State.Stack.back().BreakBeforeParameter = true;
949
Daniel Jasper4b866272013-02-01 11:00:45 +0000950 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000951 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +0000952 }
953
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000954 /// \brief An edge in the solution space from \c Previous->State to \c State,
955 /// inserting a newline dependent on the \c NewLine.
956 struct StateNode {
957 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000958 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000959 LineState State;
960 bool NewLine;
961 StateNode *Previous;
962 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000963
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000964 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
965 ///
966 /// In case of equal penalties, we want to prefer states that were inserted
967 /// first. During state generation we make sure that we insert states first
968 /// that break the line as late as possible.
969 typedef std::pair<unsigned, unsigned> OrderedPenalty;
970
971 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
972 /// \c State has the given \c OrderedPenalty.
973 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
974
975 /// \brief The BFS queue type.
976 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
977 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000978
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000979 /// \brief Get the offset of the line relatively to the level.
980 ///
981 /// For example, 'public:' labels in classes are offset by 1 or 2
982 /// characters to the left from their level.
983 int getIndentOffset(const FormatToken &RootToken) {
984 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
985 return Style.AccessModifierOffset;
986 return 0;
987 }
988
989 /// \brief Add a new line and the required indent before the first Token
990 /// of the \c UnwrappedLine if there was no structural parsing error.
991 void formatFirstToken(FormatToken &RootToken,
992 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
993 unsigned Indent, bool InPPDirective) {
994 unsigned Newlines =
995 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
996 // Remove empty lines before "}" where applicable.
997 if (RootToken.is(tok::r_brace) &&
998 (!RootToken.Next ||
999 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1000 Newlines = std::min(Newlines, 1u);
1001 if (Newlines == 0 && !RootToken.IsFirst)
1002 Newlines = 1;
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001003 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1004 Newlines = 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001005
Daniel Jasper11164bd2014-03-21 12:58:53 +00001006 // Remove empty lines after "{".
Daniel Jaspera26fc5c2014-03-21 13:43:14 +00001007 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1008 PreviousLine->Last->is(tok::l_brace) &&
Daniel Jasper01b35482014-03-21 13:03:33 +00001009 PreviousLine->First->isNot(tok::kw_namespace))
Daniel Jasper11164bd2014-03-21 12:58:53 +00001010 Newlines = 1;
1011
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001012 // Insert extra new line before access specifiers.
1013 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1014 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1015 ++Newlines;
1016
1017 // Remove empty lines after access specifiers.
1018 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
1019 Newlines = std::min(1u, Newlines);
1020
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001021 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
1022 Indent, InPPDirective &&
1023 !RootToken.HasUnescapedNewline);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001024 }
1025
1026 /// \brief Get the indent of \p Level from \p IndentForLevel.
1027 ///
1028 /// \p IndentForLevel must contain the indent for the level \c l
1029 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1030 /// that level is unknown.
1031 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
1032 if (IndentForLevel[Level] != -1)
1033 return IndentForLevel[Level];
1034 if (Level == 0)
1035 return 0;
1036 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
1037 }
1038
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001039 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1040 assert(!A.Last->Next);
1041 assert(!B.First->Previous);
Daniel Jasper5500f612013-11-25 11:08:59 +00001042 if (B.Affected)
1043 A.Affected = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001044 A.Last->Next = B.First;
1045 B.First->Previous = A.Last;
Daniel Jasper98fb6e12013-11-08 17:33:27 +00001046 B.First->CanBreakBefore = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001047 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1048 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1049 Tok->TotalLength += LengthA;
1050 A.Last = Tok;
1051 }
1052 }
1053
1054 unsigned getColumnLimit(bool InPPDirective) const {
1055 // In preprocessor directives reserve two chars for trailing " \"
1056 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1057 }
1058
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001059 struct CompareLineStatePointers {
1060 bool operator()(LineState *obj1, LineState *obj2) const {
1061 return *obj1 < *obj2;
1062 }
1063 };
1064
Daniel Jasper4b866272013-02-01 11:00:45 +00001065 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +00001066 ///
Daniel Jasper4b866272013-02-01 11:00:45 +00001067 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1068 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1069 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001070 /// to a state where all tokens are placed. Returns the penalty.
1071 ///
1072 /// If \p DryRun is \c false, directly applies the changes.
1073 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001074 std::set<LineState *, CompareLineStatePointers> Seen;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001075
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001076 // Increasing count of \c StateNode items we have created. This is used to
1077 // create a deterministic order independent of the container.
1078 unsigned Count = 0;
1079 QueueType Queue;
1080
Daniel Jasper4b866272013-02-01 11:00:45 +00001081 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001082 StateNode *Node =
Craig Topper2145bc02014-05-09 08:15:10 +00001083 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001084 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1085 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001086
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001087 unsigned Penalty = 0;
1088
Daniel Jasper4b866272013-02-01 11:00:45 +00001089 // While not empty, take first element and follow edges.
1090 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001091 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001092 StateNode *Node = Queue.top().second;
Craig Topper2145bc02014-05-09 08:15:10 +00001093 if (!Node->State.NextToken) {
Alexander Kornienko49149672013-05-10 11:56:10 +00001094 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001095 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001096 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001097 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001098
Daniel Jasperf8114cf2013-05-22 05:27:42 +00001099 // Cut off the analysis of certain solutions if the analysis gets too
1100 // complex. See description of IgnoreStackForComparison.
1101 if (Count > 10000)
1102 Node->State.IgnoreStackForComparison = true;
1103
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001104 if (!Seen.insert(&Node->State).second)
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001105 // State already examined with lower penalty.
1106 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001107
Manuel Klimek71814b42013-10-11 21:25:45 +00001108 FormatDecision LastFormat = Node->State.NextToken->Decision;
1109 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001110 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimek71814b42013-10-11 21:25:45 +00001111 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001112 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper4b866272013-02-01 11:00:45 +00001113 }
1114
Manuel Klimek71814b42013-10-11 21:25:45 +00001115 if (Queue.empty()) {
Daniel Jasper4b866272013-02-01 11:00:45 +00001116 // We were unable to find a solution, do nothing.
1117 // FIXME: Add diagnostic?
Manuel Klimek71814b42013-10-11 21:25:45 +00001118 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001119 return 0;
Manuel Klimek71814b42013-10-11 21:25:45 +00001120 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001121
Daniel Jasper4b866272013-02-01 11:00:45 +00001122 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001123 if (!DryRun)
1124 reconstructPath(InitialState, Queue.top().second);
1125
Alexander Kornienko49149672013-05-10 11:56:10 +00001126 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1127 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001128
1129 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001130 }
1131
1132 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001133 std::deque<StateNode *> Path;
1134 // We do not need a break before the initial token.
1135 while (Current->Previous) {
1136 Path.push_front(Current);
1137 Current = Current->Previous;
1138 }
1139 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1140 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001141 unsigned Penalty = 0;
1142 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1143 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1144
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001145 DEBUG({
1146 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001147 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001148 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001149 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001150 }
1151 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001152 }
Daniel Jasper4b866272013-02-01 11:00:45 +00001153 }
1154
Manuel Klimekaf491072013-02-13 10:54:19 +00001155 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001156 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001157 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001158 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001159 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001160 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001161 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001162 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001163 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001164 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001165
1166 StateNode *Node = new (Allocator.Allocate())
1167 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001168 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1169 return;
1170
Daniel Jasperde0328a2013-08-16 11:20:30 +00001171 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001172
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001173 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1174 ++(*Count);
Daniel Jasper4b866272013-02-01 11:00:45 +00001175 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001176
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001177 /// \brief If the \p State's next token is an r_brace closing a nested block,
1178 /// format the nested block before it.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001179 ///
1180 /// Returns \c true if all children could be placed successfully and adapts
1181 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1182 /// creates changes using \c Whitespaces.
1183 ///
1184 /// The crucial idea here is that children always get formatted upon
1185 /// encountering the closing brace right after the nested block. Now, if we
1186 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1187 /// \c false), the entire block has to be kept on the same line (which is only
1188 /// possible if it fits on the line, only contains a single statement, etc.
1189 ///
1190 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1191 /// break after the "{", format all lines with correct indentation and the put
1192 /// the closing "}" on yet another new line.
1193 ///
1194 /// This enables us to keep the simple structure of the
1195 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1196 /// break or don't break.
1197 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1198 unsigned &Penalty) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001199 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001200 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1201 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1202 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001203 // The previous token does not open a block. Nothing to do. We don't
1204 // assert so that we can simply call this function for all tokens.
Daniel Jasper36c28ce2013-09-06 08:54:24 +00001205 return true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001206
1207 if (NewLine) {
Daniel Jasper58cb2ed2014-06-06 13:49:04 +00001208 int AdditionalIndent =
1209 State.FirstIndent - State.Line->Level * Style.IndentWidth;
Daniel Jasperb16b9692014-05-21 12:51:23 +00001210 if (State.Stack.size() < 2 ||
1211 !State.Stack[State.Stack.size() - 2].JSFunctionInlined) {
1212 AdditionalIndent = State.Stack.back().Indent -
1213 Previous.Children[0]->Level * Style.IndentWidth;
1214 }
1215
Daniel Jasper9c199562013-11-28 15:58:55 +00001216 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1217 /*FixBadIndentation=*/true);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001218 return true;
1219 }
1220
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001221 // Cannot merge multiple statements into a single line.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001222 if (Previous.Children.size() > 1)
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001223 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001224
Daniel Jasper21397a32014-04-09 12:21:48 +00001225 // Cannot merge into one line if this line ends on a comment.
1226 if (Previous.is(tok::comment))
1227 return false;
1228
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001229 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001230 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001231 return false;
1232
Daniel Jasper98583d52014-04-15 08:28:06 +00001233 // If the child line exceeds the column limit, we wouldn't want to merge it.
1234 // We add +2 for the trailing " }".
1235 if (Style.ColumnLimit > 0 &&
1236 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
1237 Style.ColumnLimit)
1238 return false;
1239
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001240 if (!DryRun) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001241 Whitespaces->replaceWhitespace(
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001242 *Previous.Children[0]->First,
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001243 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001244 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001245 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001246 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001247
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001248 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001249 return true;
1250 }
1251
Daniel Jasperde0328a2013-08-16 11:20:30 +00001252 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001253 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001254 FormatStyle Style;
Daniel Jasper56f8b432013-11-06 23:12:09 +00001255 LineJoiner Joiner;
Manuel Klimekaf491072013-02-13 10:54:19 +00001256
1257 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperc359ad02014-04-15 08:13:47 +00001258
1259 // Cache to store the penalty of formatting a vector of AnnotatedLines
1260 // starting from a specific additional offset. Improves performance if there
1261 // are many nested blocks.
1262 std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
1263 unsigned> PenaltyCache;
Daniel Jasperf7935112012-12-03 18:12:45 +00001264};
1265
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001266class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001267public:
Manuel Klimek31c85922013-08-29 15:21:40 +00001268 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001269 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +00001270 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
1271 Column(0), TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr),
1272 Style(Style), IdentTable(getFormattingLangOpts()), Encoding(Encoding),
Manuel Klimek68b03042014-04-14 09:14:11 +00001273 FirstInLineIndex(0) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001274 Lex.SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +00001275
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001276 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +00001277 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1278 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001279 }
1280
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001281 ArrayRef<FormatToken *> lex() {
1282 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +00001283 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001284 do {
1285 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001286 tryMergePreviousTokens();
Manuel Klimek68b03042014-04-14 09:14:11 +00001287 if (Tokens.back()->NewlinesBefore > 0)
1288 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001289 } while (Tokens.back()->Tok.isNot(tok::eof));
1290 return Tokens;
1291 }
1292
1293 IdentifierTable &getIdentTable() { return IdentTable; }
1294
1295private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001296 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001297 if (tryMerge_TMacro())
1298 return;
Manuel Klimek68b03042014-04-14 09:14:11 +00001299 if (tryMergeConflictMarkers())
1300 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001301
1302 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001303 if (tryMergeEscapeSequence())
1304 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001305 if (tryMergeJSRegexLiteral())
1306 return;
1307
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001308 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1309 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1310 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1311 tok::greaterequal };
Daniel Jasper78214392014-05-19 07:27:02 +00001312 static tok::TokenKind JSRightArrow[] = { tok::equal, tok::greater };
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001313 // FIXME: We probably need to change token type to mimic operator with the
1314 // correct priority.
1315 if (tryMergeTokens(JSIdentity))
1316 return;
1317 if (tryMergeTokens(JSNotIdentity))
1318 return;
1319 if (tryMergeTokens(JSShiftEqual))
1320 return;
Daniel Jasper78214392014-05-19 07:27:02 +00001321 if (tryMergeTokens(JSRightArrow))
1322 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001323 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001324 }
1325
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001326 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1327 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001328 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001329
1330 SmallVectorImpl<FormatToken *>::const_iterator First =
1331 Tokens.end() - Kinds.size();
1332 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001333 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001334 unsigned AddLength = 0;
1335 for (unsigned i = 1; i < Kinds.size(); ++i) {
1336 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1337 First[i]->WhitespaceRange.getEnd())
1338 return false;
1339 AddLength += First[i]->TokenText.size();
1340 }
1341 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1342 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1343 First[0]->TokenText.size() + AddLength);
1344 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001345 return true;
1346 }
1347
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001348 // Tries to merge an escape sequence, i.e. a "\\" and the following
Alp Tokerc3f36af2014-05-15 01:35:53 +00001349 // character. Use e.g. inside JavaScript regex literals.
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001350 bool tryMergeEscapeSequence() {
1351 if (Tokens.size() < 2)
1352 return false;
1353 FormatToken *Previous = Tokens[Tokens.size() - 2];
1354 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\" ||
1355 Tokens.back()->NewlinesBefore != 0)
1356 return false;
1357 Previous->ColumnWidth += Tokens.back()->ColumnWidth;
1358 StringRef Text = Previous->TokenText;
1359 Previous->TokenText =
1360 StringRef(Text.data(), Text.size() + Tokens.back()->TokenText.size());
1361 Tokens.resize(Tokens.size() - 1);
1362 return true;
1363 }
1364
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001365 // Try to determine whether the current token ends a JavaScript regex literal.
1366 // We heuristically assume that this is a regex literal if we find two
1367 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +00001368 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
1369 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001370 bool tryMergeJSRegexLiteral() {
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001371 if (Tokens.size() < 2 || Tokens.back()->isNot(tok::slash) ||
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001372 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
1373 Tokens[Tokens.size() - 2]->TokenText == "\\"))
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001374 return false;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001375 unsigned TokenCount = 0;
1376 unsigned LastColumn = Tokens.back()->OriginalColumn;
1377 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
1378 ++TokenCount;
1379 if (I[0]->is(tok::slash) && I + 1 != E &&
1380 (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
1381 tok::exclaim, tok::l_square, tok::colon, tok::comma,
1382 tok::question, tok::kw_return) ||
1383 I[1]->isBinaryOperator())) {
1384 Tokens.resize(Tokens.size() - TokenCount);
1385 Tokens.back()->Tok.setKind(tok::unknown);
1386 Tokens.back()->Type = TT_RegexLiteral;
1387 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
1388 return true;
1389 }
1390
1391 // There can't be a newline inside a regex literal.
1392 if (I[0]->NewlinesBefore > 0)
1393 return false;
1394 }
1395 return false;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001396 }
1397
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001398 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001399 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001400 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001401 FormatToken *Last = Tokens.back();
1402 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001403 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001404
1405 FormatToken *String = Tokens[Tokens.size() - 2];
1406 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001407 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001408
1409 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001410 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001411
1412 FormatToken *Macro = Tokens[Tokens.size() - 4];
1413 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001414 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001415
1416 const char *Start = Macro->TokenText.data();
1417 const char *End = Last->TokenText.data() + Last->TokenText.size();
1418 String->TokenText = StringRef(Start, End - Start);
1419 String->IsFirst = Macro->IsFirst;
1420 String->LastNewlineOffset = Macro->LastNewlineOffset;
1421 String->WhitespaceRange = Macro->WhitespaceRange;
1422 String->OriginalColumn = Macro->OriginalColumn;
1423 String->ColumnWidth = encoding::columnWidthWithTabs(
1424 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1425
1426 Tokens.pop_back();
1427 Tokens.pop_back();
1428 Tokens.pop_back();
1429 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001430 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001431 }
1432
Manuel Klimek68b03042014-04-14 09:14:11 +00001433 bool tryMergeConflictMarkers() {
1434 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1435 return false;
1436
1437 // Conflict lines look like:
1438 // <marker> <text from the vcs>
1439 // For example:
1440 // >>>>>>> /file/in/file/system at revision 1234
1441 //
1442 // We merge all tokens in a line that starts with a conflict marker
1443 // into a single token with a special token type that the unwrapped line
1444 // parser will use to correctly rebuild the underlying code.
1445
1446 FileID ID;
1447 // Get the position of the first token in the line.
1448 unsigned FirstInLineOffset;
1449 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1450 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1451 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1452 // Calculate the offset of the start of the current line.
1453 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1454 if (LineOffset == StringRef::npos) {
1455 LineOffset = 0;
1456 } else {
1457 ++LineOffset;
1458 }
1459
1460 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1461 StringRef LineStart;
1462 if (FirstSpace == StringRef::npos) {
1463 LineStart = Buffer.substr(LineOffset);
1464 } else {
1465 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1466 }
1467
1468 TokenType Type = TT_Unknown;
1469 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1470 Type = TT_ConflictStart;
1471 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1472 LineStart == "====") {
1473 Type = TT_ConflictAlternative;
1474 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1475 Type = TT_ConflictEnd;
1476 }
1477
1478 if (Type != TT_Unknown) {
1479 FormatToken *Next = Tokens.back();
1480
1481 Tokens.resize(FirstInLineIndex + 1);
1482 // We do not need to build a complete token here, as we will skip it
1483 // during parsing anyway (as we must not touch whitespace around conflict
1484 // markers).
1485 Tokens.back()->Type = Type;
1486 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1487
1488 Tokens.push_back(Next);
1489 return true;
1490 }
1491
1492 return false;
1493 }
1494
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001495 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001496 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001497 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +00001498 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001499 Token Greater = FormatTok->Tok;
1500 FormatTok = new (Allocator.Allocate()) FormatToken;
1501 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001502 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001503 FormatTok->Tok.getLocation().getLocWithOffset(1);
1504 FormatTok->WhitespaceRange =
1505 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001506 FormatTok->TokenText = ">";
Alexander Kornienko39856b72013-09-10 09:38:25 +00001507 FormatTok->ColumnWidth = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001508 GreaterStashed = false;
1509 return FormatTok;
1510 }
1511
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001512 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001513 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001514 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001515 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001516 FormatTok->IsFirst = IsFirstToken;
1517 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001518
1519 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001520 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001521 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001522 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1523 switch (FormatTok->TokenText[i]) {
1524 case '\n':
1525 ++FormatTok->NewlinesBefore;
1526 // FIXME: This is technically incorrect, as it could also
1527 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001528 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1529 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1530 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +00001531 FormatTok->HasUnescapedNewline = true;
1532 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1533 Column = 0;
1534 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001535 case '\r':
1536 case '\f':
1537 case '\v':
1538 Column = 0;
1539 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001540 case ' ':
1541 ++Column;
1542 break;
1543 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001544 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001545 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001546 case '\\':
1547 ++Column;
1548 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1549 FormatTok->TokenText[i + 1] != '\n'))
1550 FormatTok->Type = TT_ImplicitStringLiteral;
1551 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001552 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001553 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001554 ++Column;
1555 break;
1556 }
1557 }
1558
Daniel Jasper877615c2013-10-11 19:45:02 +00001559 if (FormatTok->Type == TT_ImplicitStringLiteral)
1560 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001561 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001562
Daniel Jasper8369aa52013-07-16 20:28:33 +00001563 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001564 }
Manuel Klimekef920692013-01-07 07:56:50 +00001565
Manuel Klimek1abf7892013-01-04 23:34:14 +00001566 // In case the token starts with escaped newlines, we want to
1567 // take them into account as whitespace - this pattern is quite frequent
1568 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001569 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001570 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1571 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001572 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001573 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001574 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001575 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001576 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001577
1578 FormatTok->WhitespaceRange = SourceRange(
1579 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1580
Manuel Klimek31c85922013-08-29 15:21:40 +00001581 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001582
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001583 TrailingWhitespace = 0;
1584 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001585 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001586 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001587 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001588 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001589 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001590 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001591 FormatTok->Tok.setIdentifierInfo(&Info);
1592 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001593 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001594 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001595 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001596 GreaterStashed = true;
1597 }
1598
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001599 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001600
Alexander Kornienko39856b72013-09-10 09:38:25 +00001601 StringRef Text = FormatTok->TokenText;
1602 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001603 if (FirstNewlinePos == StringRef::npos) {
1604 // FIXME: ColumnWidth actually depends on the start column, we need to
1605 // take this into account when the token is moved.
1606 FormatTok->ColumnWidth =
1607 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1608 Column += FormatTok->ColumnWidth;
1609 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001610 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001611 // FIXME: ColumnWidth actually depends on the start column, we need to
1612 // take this into account when the token is moved.
1613 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1614 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1615
Alexander Kornienko39856b72013-09-10 09:38:25 +00001616 // The last line of the token always starts in column 0.
1617 // Thus, the length can be precomputed even in the presence of tabs.
1618 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1619 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1620 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001621 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001622 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001623
Daniel Jaspere1e43192014-04-01 12:55:11 +00001624 FormatTok->IsForEachMacro =
1625 std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1626 FormatTok->Tok.getIdentifierInfo());
1627
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001628 return FormatTok;
1629 }
1630
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001631 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001632 bool IsFirstToken;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001633 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001634 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001635 unsigned TrailingWhitespace;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001636 Lexer &Lex;
1637 SourceManager &SourceMgr;
Manuel Klimek31c85922013-08-29 15:21:40 +00001638 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001639 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001640 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001641 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001642 // Index (in 'Tokens') of the last token that starts a new line.
1643 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001644 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001645 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001646
Daniel Jasper8369aa52013-07-16 20:28:33 +00001647 void readRawToken(FormatToken &Tok) {
1648 Lex.LexFromRawLexer(Tok.Tok);
1649 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1650 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001651 // For formatting, treat unterminated string literals like normal string
1652 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001653 if (Tok.is(tok::unknown)) {
1654 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1655 Tok.Tok.setKind(tok::string_literal);
1656 Tok.IsUnterminatedLiteral = true;
1657 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1658 Tok.TokenText == "''") {
1659 Tok.Tok.setKind(tok::char_constant);
1660 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001661 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001662 }
1663};
1664
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001665static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1666 switch (Language) {
1667 case FormatStyle::LK_Cpp:
1668 return "C++";
1669 case FormatStyle::LK_JavaScript:
1670 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001671 case FormatStyle::LK_Proto:
1672 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001673 default:
1674 return "Unknown";
1675 }
1676}
1677
Daniel Jasperf7935112012-12-03 18:12:45 +00001678class Formatter : public UnwrappedLineConsumer {
1679public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001680 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001681 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001682 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001683 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001684 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Manuel Klimek71814b42013-10-11 21:25:45 +00001685 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001686 DEBUG(llvm::dbgs() << "File encoding: "
1687 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1688 : "unknown")
1689 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001690 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1691 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001692 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001693
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001694 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001695 tooling::Replacements Result;
Manuel Klimek31c85922013-08-29 15:21:40 +00001696 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001697
1698 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001699 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001700 assert(UnwrappedLines.rbegin()->empty());
1701 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1702 ++Run) {
1703 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1704 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1705 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1706 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1707 }
1708 tooling::Replacements RunResult =
1709 format(AnnotatedLines, StructuralError, Tokens);
1710 DEBUG({
1711 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1712 for (tooling::Replacements::iterator I = RunResult.begin(),
1713 E = RunResult.end();
1714 I != E; ++I) {
1715 llvm::dbgs() << I->toString() << "\n";
1716 }
1717 });
1718 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1719 delete AnnotatedLines[i];
1720 }
1721 Result.insert(RunResult.begin(), RunResult.end());
1722 Whitespaces.reset();
1723 }
1724 return Result;
1725 }
1726
1727 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1728 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001729 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001730 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001731 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001732 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001733 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001734 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001735 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001736 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001737 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001738
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001739 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001740 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1741 BinPackInconclusiveFunctions);
Daniel Jasper5500f612013-11-25 11:08:59 +00001742 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001743 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001744 return Whitespaces.generateReplacements();
1745 }
1746
1747private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001748 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001749 // Returns \c true if at least one line between I and E or one of their
1750 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001751 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1752 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1753 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001754 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001755 while (I != E) {
1756 AnnotatedLine *Line = *I;
1757 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1758
1759 // If a line is part of a preprocessor directive, it needs to be formatted
1760 // if any token within the directive is affected.
1761 if (Line->InPPDirective) {
1762 FormatToken *Last = Line->Last;
1763 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1764 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1765 Last = (*PPEnd)->Last;
1766 ++PPEnd;
1767 }
1768
1769 if (affectsTokenRange(*Line->First, *Last,
1770 /*IncludeLeadingNewlines=*/false)) {
1771 SomeLineAffected = true;
1772 markAllAsAffected(I, PPEnd);
1773 }
1774 I = PPEnd;
1775 continue;
1776 }
1777
Daniel Jasper38c82402013-11-29 09:27:43 +00001778 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001779 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001780
Daniel Jasper38c82402013-11-29 09:27:43 +00001781 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001782 ++I;
1783 }
1784 return SomeLineAffected;
1785 }
1786
Daniel Jasper9c199562013-11-28 15:58:55 +00001787 // Determines whether 'Line' is affected by the SourceRanges given as input.
1788 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001789 bool nonPPLineAffected(AnnotatedLine *Line,
1790 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001791 bool SomeLineAffected = false;
1792 Line->ChildrenAffected =
1793 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1794 if (Line->ChildrenAffected)
1795 SomeLineAffected = true;
1796
1797 // Stores whether one of the line's tokens is directly affected.
1798 bool SomeTokenAffected = false;
1799 // Stores whether we need to look at the leading newlines of the next token
1800 // in order to determine whether it was affected.
1801 bool IncludeLeadingNewlines = false;
1802
1803 // Stores whether the first child line of any of this line's tokens is
1804 // affected.
1805 bool SomeFirstChildAffected = false;
1806
1807 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1808 // Determine whether 'Tok' was affected.
1809 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1810 SomeTokenAffected = true;
1811
1812 // Determine whether the first child of 'Tok' was affected.
1813 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1814 SomeFirstChildAffected = true;
1815
1816 IncludeLeadingNewlines = Tok->Children.empty();
1817 }
1818
1819 // Was this line moved, i.e. has it previously been on the same line as an
1820 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001821 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1822 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001823
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001824 bool IsContinuedComment =
1825 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1826 Line->First->NewlinesBefore < 2 && PreviousLine &&
1827 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001828
1829 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1830 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001831 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001832 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001833 }
1834 return SomeLineAffected;
1835 }
1836
Daniel Jasper5500f612013-11-25 11:08:59 +00001837 // Marks all lines between I and E as well as all their children as affected.
1838 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1839 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1840 while (I != E) {
1841 (*I)->Affected = true;
1842 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1843 ++I;
1844 }
1845 }
1846
1847 // Returns true if the range from 'First' to 'Last' intersects with one of the
1848 // input ranges.
1849 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1850 bool IncludeLeadingNewlines) {
1851 SourceLocation Start = First.WhitespaceRange.getBegin();
1852 if (!IncludeLeadingNewlines)
1853 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001854 SourceLocation End = Last.getStartOfNonWhitespace();
1855 if (Last.TokenText.size() > 0)
1856 End = End.getLocWithOffset(Last.TokenText.size() - 1);
Daniel Jasper5500f612013-11-25 11:08:59 +00001857 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1858 return affectsCharSourceRange(Range);
1859 }
1860
1861 // Returns true if one of the input ranges intersect the leading empty lines
1862 // before 'Tok'.
1863 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1864 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1865 Tok.WhitespaceRange.getBegin(),
1866 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1867 return affectsCharSourceRange(EmptyLineRange);
1868 }
1869
1870 // Returns true if 'Range' intersects with one of the input ranges.
1871 bool affectsCharSourceRange(const CharSourceRange &Range) {
1872 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1873 E = Ranges.end();
1874 I != E; ++I) {
1875 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1876 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1877 return true;
1878 }
1879 return false;
1880 }
1881
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001882 static bool inputUsesCRLF(StringRef Text) {
1883 return Text.count('\r') * 2 > Text.count('\n');
1884 }
1885
Manuel Klimek71814b42013-10-11 21:25:45 +00001886 void
1887 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001888 unsigned CountBoundToVariable = 0;
1889 unsigned CountBoundToType = 0;
1890 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001891 bool HasBinPackedFunction = false;
1892 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001893 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001894 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001895 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001896 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001897 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001898 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001899 bool SpacesBefore =
1900 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1901 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1902 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001903 if (SpacesBefore && !SpacesAfter)
1904 ++CountBoundToVariable;
1905 else if (!SpacesBefore && SpacesAfter)
1906 ++CountBoundToType;
1907 }
1908
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001909 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1910 if (Tok->is(tok::coloncolon) &&
1911 Tok->Previous->Type == TT_TemplateOpener)
1912 HasCpp03IncompatibleFormat = true;
1913 if (Tok->Type == TT_TemplateCloser &&
1914 Tok->Previous->Type == TT_TemplateCloser)
1915 HasCpp03IncompatibleFormat = true;
1916 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001917
1918 if (Tok->PackingKind == PPK_BinPacked)
1919 HasBinPackedFunction = true;
1920 if (Tok->PackingKind == PPK_OnePerLine)
1921 HasOnePerLineFunction = true;
1922
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001923 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001924 }
1925 }
Daniel Jasper553d4872014-06-17 12:40:34 +00001926 if (Style.DerivePointerAlignment) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001927 if (CountBoundToType > CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00001928 Style.PointerAlignment = FormatStyle::PAS_Left;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001929 else if (CountBoundToType < CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00001930 Style.PointerAlignment = FormatStyle::PAS_Right;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001931 }
1932 if (Style.Standard == FormatStyle::LS_Auto) {
1933 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1934 : FormatStyle::LS_Cpp03;
1935 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001936 BinPackInconclusiveFunctions =
1937 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001938 }
1939
Craig Topperfb6b25b2014-03-15 04:29:04 +00001940 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001941 assert(!UnwrappedLines.empty());
1942 UnwrappedLines.back().push_back(TheLine);
1943 }
1944
Craig Topperfb6b25b2014-03-15 04:29:04 +00001945 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001946 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001947 }
1948
1949 FormatStyle Style;
1950 Lexer &Lex;
1951 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001952 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001953 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001954 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001955
1956 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001957 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001958};
1959
Craig Topperaf35e852013-06-30 22:29:28 +00001960} // end anonymous namespace
1961
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001962tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1963 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001964 std::vector<CharSourceRange> Ranges) {
Daniel Jasperc64b09a2014-05-22 15:12:22 +00001965 if (Style.DisableFormat) {
1966 tooling::Replacements EmptyResult;
1967 return EmptyResult;
1968 }
1969
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001970 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001971 return formatter.format();
1972}
1973
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001974tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1975 std::vector<tooling::Range> Ranges,
1976 StringRef FileName) {
1977 FileManager Files((FileSystemOptions()));
1978 DiagnosticsEngine Diagnostics(
1979 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1980 new DiagnosticOptions);
1981 SourceManager SourceMgr(Diagnostics, Files);
1982 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1983 const clang::FileEntry *Entry =
1984 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1985 SourceMgr.overrideFileContents(Entry, Buf);
1986 FileID ID =
1987 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienko1e808872013-06-28 12:51:24 +00001988 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1989 getFormattingLangOpts(Style.Standard));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001990 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1991 std::vector<CharSourceRange> CharRanges;
1992 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1993 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1994 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1995 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1996 }
1997 return reformat(Style, Lex, SourceMgr, CharRanges);
1998}
1999
Alexander Kornienko1e808872013-06-28 12:51:24 +00002000LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002001 LangOptions LangOpts;
2002 LangOpts.CPlusPlus = 1;
Alexander Kornienko1e808872013-06-28 12:51:24 +00002003 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper20fd3c62014-04-15 08:49:21 +00002004 LangOpts.CPlusPlus1y = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00002005 LangOpts.LineComment = 1;
Nikola Smiljanice08a91e2014-05-08 00:05:13 +00002006 LangOpts.CXXOperatorNames = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002007 LangOpts.Bool = 1;
2008 LangOpts.ObjC1 = 1;
2009 LangOpts.ObjC2 = 1;
2010 return LangOpts;
2011}
2012
Edwin Vaned544aa72013-09-30 13:31:48 +00002013const char *StyleOptionHelpDescription =
2014 "Coding style, currently supports:\n"
2015 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
2016 "Use -style=file to load style configuration from\n"
2017 ".clang-format file located in one of the parent\n"
2018 "directories of the source file (or current\n"
2019 "directory for stdin).\n"
2020 "Use -style=\"{key: value, ...}\" to set specific\n"
2021 "parameters, e.g.:\n"
2022 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
2023
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002024static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002025 if (FileName.endswith_lower(".js")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002026 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00002027 } else if (FileName.endswith_lower(".proto") ||
2028 FileName.endswith_lower(".protodevel")) {
2029 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002030 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002031 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002032}
2033
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002034FormatStyle getStyle(StringRef StyleName, StringRef FileName,
2035 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002036 FormatStyle Style = getLLVMStyle();
2037 Style.Language = getLanguageByFileName(FileName);
2038 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002039 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
2040 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002041 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002042 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002043
2044 if (StyleName.startswith("{")) {
2045 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00002046 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002047 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
2048 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00002049 }
2050 return Style;
2051 }
2052
2053 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002054 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00002055 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
2056 << " style\n";
2057 return Style;
2058 }
2059
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002060 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002061 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00002062 SmallString<128> Path(FileName);
2063 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002064 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00002065 Directory = llvm::sys::path::parent_path(Directory)) {
2066 if (!llvm::sys::fs::is_directory(Directory))
2067 continue;
2068 SmallString<128> ConfigFile(Directory);
2069
2070 llvm::sys::path::append(ConfigFile, ".clang-format");
2071 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2072 bool IsFile = false;
2073 // Ignore errors from is_regular_file: we only need to know if we can read
2074 // the file or not.
2075 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2076
2077 if (!IsFile) {
2078 // Try _clang-format too, since dotfiles are not commonly used on Windows.
2079 ConfigFile = Directory;
2080 llvm::sys::path::append(ConfigFile, "_clang-format");
2081 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2082 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2083 }
2084
2085 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002086 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
2087 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
2088 if (std::error_code EC = Text.getError()) {
2089 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002090 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002091 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002092 if (std::error_code ec =
2093 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00002094 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002095 if (!UnsuitableConfigFiles.empty())
2096 UnsuitableConfigFiles.append(", ");
2097 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002098 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002099 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002100 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2101 << "\n";
2102 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002103 }
2104 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2105 return Style;
2106 }
2107 }
2108 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
2109 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002110 if (!UnsuitableConfigFiles.empty()) {
2111 llvm::errs() << "Configuration file(s) do(es) not support "
2112 << getLanguageName(Style.Language) << ": "
2113 << UnsuitableConfigFiles << "\n";
2114 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002115 return Style;
2116}
2117
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002118} // namespace format
2119} // namespace clang