blob: 8f119d3b65026566ff8a1bce77b2796b9016dd61 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
Daniel Jasperf7935112012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Daniel Jasperde0328a2013-08-16 11:20:30 +000016#include "ContinuationIndenter.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000017#include "TokenAnnotator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "UnwrappedLineParser.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000019#include "WhitespaceManager.h"
Daniel Jasperec04c0d2013-05-16 10:40:07 +000020#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000021#include "clang/Basic/DiagnosticOptions.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000023#include "clang/Format/Format.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000024#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000025#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000026#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000027#include "llvm/Support/Debug.h"
Edwin Vaned544aa72013-09-30 13:31:48 +000028#include "llvm/Support/Path.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000029#include "llvm/Support/YAMLTraits.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000030#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000031#include <string>
32
Chandler Carruth10346662014-04-22 03:17:02 +000033#define DEBUG_TYPE "format-formatter"
34
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000035using clang::format::FormatStyle;
36
Daniel Jaspere1e43192014-04-01 12:55:11 +000037LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
38
Alexander Kornienkod6538332013-05-07 15:32:14 +000039namespace llvm {
40namespace yaml {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000041template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
42 static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
43 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
44 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
Daniel Jasper7052ce62014-01-19 09:04:08 +000045 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000046 }
47};
48
49template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
50 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
51 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
52 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
53 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
54 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
55 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
56 }
57};
58
59template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
60 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
61 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
62 IO.enumCase(Value, "false", FormatStyle::UT_Never);
63 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
64 IO.enumCase(Value, "true", FormatStyle::UT_Always);
65 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
66 }
67};
68
Daniel Jasperd74cf402014-04-08 12:46:38 +000069template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
70 static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
71 IO.enumCase(Value, "None", FormatStyle::SFS_None);
72 IO.enumCase(Value, "false", FormatStyle::SFS_None);
73 IO.enumCase(Value, "All", FormatStyle::SFS_All);
74 IO.enumCase(Value, "true", FormatStyle::SFS_All);
75 IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
76 }
77};
78
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000079template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
80 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
81 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
82 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
83 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
84 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
Alexander Kornienko3a33f022013-12-12 09:49:52 +000085 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000086 }
87};
88
Alexander Kornienkod6538332013-05-07 15:32:14 +000089template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000090struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +000091 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000092 FormatStyle::NamespaceIndentationKind &Value) {
93 IO.enumCase(Value, "None", FormatStyle::NI_None);
94 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
95 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +000096 }
97};
98
99template <>
Daniel Jasper553d4872014-06-17 12:40:34 +0000100struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
101 static void enumeration(IO &IO,
102 FormatStyle::PointerAlignmentStyle &Value) {
103 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
104 IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
105 IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
106
Alp Toker958027b2014-07-14 19:42:55 +0000107 // For backward compatibility.
Daniel Jasper553d4872014-06-17 12:40:34 +0000108 IO.enumCase(Value, "true", FormatStyle::PAS_Left);
109 IO.enumCase(Value, "false", FormatStyle::PAS_Right);
110 }
111};
112
113template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000114struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000115 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000116 FormatStyle::SpaceBeforeParensOptions &Value) {
117 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000118 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000119 FormatStyle::SBPO_ControlStatements);
120 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000121
122 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000123 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
124 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000125 }
126};
127
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000128template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000129 static void mapping(IO &IO, FormatStyle &Style) {
130 // When reading, read the language first, we need it for getPredefinedStyle.
131 IO.mapOptional("Language", Style.Language);
132
Alexander Kornienko49149672013-05-10 11:56:10 +0000133 if (IO.outputting()) {
Alexander Kornienkoe3648fb2013-09-02 16:39:23 +0000134 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000135 "Mozilla", "WebKit", "GNU" };
Alexander Kornienko49149672013-05-10 11:56:10 +0000136 ArrayRef<StringRef> Styles(StylesArray);
137 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
138 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000139 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000140 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000141 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000142 IO.mapOptional("# BasedOnStyle", StyleName);
143 break;
144 }
145 }
146 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000147 StringRef BasedOnStyle;
148 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000149 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000150 FormatStyle::LanguageKind OldLanguage = Style.Language;
151 FormatStyle::LanguageKind Language =
152 ((FormatStyle *)IO.getContext())->Language;
153 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000154 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
155 return;
156 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000157 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000158 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000159 }
160
161 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000162 IO.mapOptional("ConstructorInitializerIndentWidth",
163 Style.ConstructorInitializerIndentWidth);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000164 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000165 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000166 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
167 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000168 IO.mapOptional("AllowShortBlocksOnASingleLine",
169 Style.AllowShortBlocksOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000170 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
171 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000172 IO.mapOptional("AllowShortLoopsOnASingleLine",
173 Style.AllowShortLoopsOnASingleLine);
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000174 IO.mapOptional("AllowShortFunctionsOnASingleLine",
175 Style.AllowShortFunctionsOnASingleLine);
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000176 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
177 Style.AlwaysBreakAfterDefinitionReturnType);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000178 IO.mapOptional("AlwaysBreakTemplateDeclarations",
179 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko58611712013-07-04 12:02:44 +0000180 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
181 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000182 IO.mapOptional("BreakBeforeBinaryOperators",
183 Style.BreakBeforeBinaryOperators);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000184 IO.mapOptional("BreakBeforeTernaryOperators",
185 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000186 IO.mapOptional("BreakConstructorInitializersBeforeComma",
187 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000188 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
189 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
190 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
191 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000192 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000193 IO.mapOptional("ExperimentalAutoDetectBinPacking",
194 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000195 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000196 IO.mapOptional("IndentWrappedFunctionNames",
197 Style.IndentWrappedFunctionNames);
198 IO.mapOptional("IndentFunctionDeclarationAfterType",
199 Style.IndentWrappedFunctionNames);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000200 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000201 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
202 Style.KeepEmptyLinesAtTheStartOfBlocks);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000203 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000204 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000205 IO.mapOptional("ObjCSpaceBeforeProtocolList",
206 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000207 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
208 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000209 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
210 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000211 IO.mapOptional("PenaltyBreakFirstLessLess",
212 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000213 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
214 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
215 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000216 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000217 IO.mapOptional("SpacesBeforeTrailingComments",
218 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000219 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000220 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000221 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000222 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000223 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000224 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000225 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000226 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasperf110e202013-08-21 08:39:01 +0000227 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000228 IO.mapOptional("SpacesInCStyleCastParentheses",
229 Style.SpacesInCStyleCastParentheses);
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000230 IO.mapOptional("SpacesInContainerLiterals",
231 Style.SpacesInContainerLiterals);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000232 IO.mapOptional("SpaceBeforeAssignmentOperators",
233 Style.SpaceBeforeAssignmentOperators);
Daniel Jasper6633ab82013-10-18 10:38:14 +0000234 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000235 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000236 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000237
238 // For backward compatibility.
239 if (!IO.outputting()) {
240 IO.mapOptional("SpaceAfterControlStatementKeyword",
241 Style.SpaceBeforeParens);
Daniel Jasper553d4872014-06-17 12:40:34 +0000242 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
243 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000244 }
245 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000246 IO.mapOptional("DisableFormat", Style.DisableFormat);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000247 }
248};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000249
250// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000251// IO.getContext() should contain a pointer to the FormatStyle structure, that
252// will be used to get default values for missing keys.
253// If the first element has no Language specified, it will be treated as the
254// default one for the following elements.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000255template <> struct DocumentListTraits<std::vector<FormatStyle> > {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000256 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
257 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000258 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000259 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000260 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000261 if (Index >= Seq.size()) {
262 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000263 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000264 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000265 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000266 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000267 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000268 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000269 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000270 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000271 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000272 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000273 }
274};
Alexander Kornienkod6538332013-05-07 15:32:14 +0000275}
276}
277
Daniel Jasperf7935112012-12-03 18:12:45 +0000278namespace clang {
279namespace format {
280
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000281const std::error_category &getParseCategory() {
Rafael Espindolad0136702014-06-12 02:50:04 +0000282 static ParseErrorCategory C;
283 return C;
284}
285std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000286 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000287}
288
289const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
290 return "clang-format.parse_error";
291}
292
293std::string ParseErrorCategory::message(int EV) const {
294 switch (static_cast<ParseError>(EV)) {
295 case ParseError::Success:
296 return "Success";
297 case ParseError::Error:
298 return "Invalid argument";
299 case ParseError::Unsuitable:
300 return "Unsuitable";
301 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000302 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000303}
304
Daniel Jasperf7935112012-12-03 18:12:45 +0000305FormatStyle getLLVMStyle() {
306 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000307 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000308 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000309 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000310 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000311 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000312 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000313 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000314 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000315 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000316 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000317 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000318 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000319 LLVMStyle.BinPackParameters = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000320 LLVMStyle.BreakBeforeBinaryOperators = false;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000321 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000322 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
323 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000324 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000325 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000326 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000327 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000328 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000329 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000330 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000331 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000332 LLVMStyle.ForEachMacros.push_back("foreach");
333 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
334 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000335 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000336 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000337 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000338 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000339 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000340 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000341 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000342 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000343 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000344 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000345 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000346 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000347 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000348 LLVMStyle.SpacesInParentheses = false;
349 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000350 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000351 LLVMStyle.SpacesInCStyleCastParentheses = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000352 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000353 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000354 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000355
Daniel Jasper19a541e2013-12-19 16:45:34 +0000356 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000357 LLVMStyle.PenaltyBreakFirstLessLess = 120;
358 LLVMStyle.PenaltyBreakString = 1000;
359 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000360 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000361 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000362
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000363 LLVMStyle.DisableFormat = false;
364
Daniel Jasperf7935112012-12-03 18:12:45 +0000365 return LLVMStyle;
366}
367
Nico Weber514ecc82014-02-02 20:50:45 +0000368FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000369 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000370 GoogleStyle.Language = Language;
371
Daniel Jasperf7935112012-12-03 18:12:45 +0000372 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000373 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000374 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000375 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000376 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000377 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000378 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000379 GoogleStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000380 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000381 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000382 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000383 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000384 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000385 GoogleStyle.SpacesBeforeTrailingComments = 2;
386 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000387
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000388 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000389 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000390
Nico Weber514ecc82014-02-02 20:50:45 +0000391 if (Language == FormatStyle::LK_JavaScript) {
392 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000393 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000394 GoogleStyle.SpacesInContainerLiterals = false;
395 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000396 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000397 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000398 }
399
Daniel Jasperf7935112012-12-03 18:12:45 +0000400 return GoogleStyle;
401}
402
Nico Weber514ecc82014-02-02 20:50:45 +0000403FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
404 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Daniel Jasperf7db4332013-01-29 16:03:49 +0000405 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000406 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000407 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000408 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000409 ChromiumStyle.BinPackParameters = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000410 ChromiumStyle.DerivePointerAlignment = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000411 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000412 return ChromiumStyle;
413}
414
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000415FormatStyle getMozillaStyle() {
416 FormatStyle MozillaStyle = getLLVMStyle();
417 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000418 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000419 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000420 MozillaStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000421 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000422 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000423 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
424 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000425 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000426 MozillaStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000427 return MozillaStyle;
428}
429
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000430FormatStyle getWebKitStyle() {
431 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000432 Style.AccessModifierOffset = -4;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000433 Style.AlignTrailingComments = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000434 Style.BreakBeforeBinaryOperators = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000435 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000436 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000437 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000438 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000439 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000440 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000441 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000442 Style.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000443 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000444 return Style;
445}
446
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000447FormatStyle getGNUStyle() {
448 FormatStyle Style = getLLVMStyle();
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000449 Style.AlwaysBreakAfterDefinitionReturnType = true;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000450 Style.BreakBeforeBinaryOperators = true;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000451 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000452 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000453 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000454 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000455 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000456 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000457 return Style;
458}
459
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000460FormatStyle getNoStyle() {
461 FormatStyle NoStyle = getLLVMStyle();
462 NoStyle.DisableFormat = true;
463 return NoStyle;
464}
465
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000466bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
467 FormatStyle *Style) {
468 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000469 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000470 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000471 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000472 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000473 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000474 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000475 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000476 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000477 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000478 } else if (Name.equals_lower("gnu")) {
479 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000480 } else if (Name.equals_lower("none")) {
481 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000482 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000483 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000484 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000485
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000486 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000487 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000488}
489
Rafael Espindolac0809172014-06-12 14:02:15 +0000490std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000491 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000492 FormatStyle::LanguageKind Language = Style->Language;
493 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000494 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000495 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000496
497 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000498 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000499 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
500 // values for the fields, keys for which are missing from the configuration.
501 // Mapping also uses the context to get the language to find the correct
502 // base style.
503 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000504 Input >> Styles;
505 if (Input.error())
506 return Input.error();
507
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000508 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000509 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000510 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000511 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000512 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000513 for (unsigned j = 0; j < i; ++j) {
514 if (Styles[i].Language == Styles[j].Language) {
515 DEBUG(llvm::dbgs()
516 << "Duplicate languages in the config file on positions " << j
517 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000518 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000519 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000520 }
521 }
522 // Look for a suitable configuration starting from the end, so we can
523 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000524 // configuration (which can only be at slot 0) after it.
525 for (int i = Styles.size() - 1; i >= 0; --i) {
526 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000527 Styles[i].Language == FormatStyle::LK_None) {
528 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000529 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000530 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000531 }
532 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000533 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000534}
535
536std::string configurationAsText(const FormatStyle &Style) {
537 std::string Text;
538 llvm::raw_string_ostream Stream(Text);
539 llvm::yaml::Output Output(Stream);
540 // We use the same mapping method for input and output, so we need a non-const
541 // reference here.
542 FormatStyle NonConstStyle = Style;
543 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000544 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000545}
546
Craig Topperaf35e852013-06-30 22:29:28 +0000547namespace {
548
Daniel Jasperde0328a2013-08-16 11:20:30 +0000549class NoColumnLimitFormatter {
550public:
Daniel Jasperf110e202013-08-21 08:39:01 +0000551 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000552
553 /// \brief Formats the line starting at \p State, simply keeping all of the
554 /// input's line breaking decisions.
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000555 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000556 LineState State =
557 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Craig Topper2145bc02014-05-09 08:15:10 +0000558 while (State.NextToken) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000559 bool Newline =
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000560 Indenter->mustBreak(State) ||
Daniel Jasperde0328a2013-08-16 11:20:30 +0000561 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
562 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
563 }
564 }
Daniel Jasperf110e202013-08-21 08:39:01 +0000565
Daniel Jasperde0328a2013-08-16 11:20:30 +0000566private:
567 ContinuationIndenter *Indenter;
568};
569
Daniel Jasper56f8b432013-11-06 23:12:09 +0000570class LineJoiner {
571public:
572 LineJoiner(const FormatStyle &Style) : Style(Style) {}
573
574 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
575 unsigned
576 tryFitMultipleLinesInOne(unsigned Indent,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000577 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000578 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
579 // We can never merge stuff if there are trailing line comments.
Daniel Jasper234379f2013-12-24 13:31:25 +0000580 const AnnotatedLine *TheLine = *I;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000581 if (TheLine->Last->Type == TT_LineComment)
582 return 0;
583
Alexander Kornienkoecc232d2013-12-04 13:25:26 +0000584 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
585 return 0;
586
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000587 unsigned Limit =
588 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000589 // If we already exceed the column limit, we set 'Limit' to 0. The different
590 // tryMerge..() functions can then decide whether to still do merging.
591 Limit = TheLine->Last->TotalLength > Limit
592 ? 0
593 : Limit - TheLine->Last->TotalLength;
594
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000595 if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000596 return 0;
597
Daniel Jasperd74cf402014-04-08 12:46:38 +0000598 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
599 // If necessary, change to something smarter.
600 bool MergeShortFunctions =
601 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
602 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
603 TheLine->Level != 0);
604
Daniel Jasper234379f2013-12-24 13:31:25 +0000605 if (TheLine->Last->Type == TT_FunctionLBrace &&
606 TheLine->First != TheLine->Last) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000607 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000608 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000609 if (TheLine->Last->is(tok::l_brace)) {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000610 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000611 ? tryMergeSimpleBlock(I, E, Limit)
612 : 0;
613 }
614 if (I[1]->First->Type == TT_FunctionLBrace &&
615 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
Alp Tokerba5b4dc2013-12-30 02:06:29 +0000616 // Check for Limit <= 2 to account for the " {".
Daniel Jasper234379f2013-12-24 13:31:25 +0000617 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
618 return 0;
619 Limit -= 2;
620
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000621 unsigned MergedLines = 0;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000622 if (MergeShortFunctions) {
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000623 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
624 // If we managed to merge the block, count the function header, which is
625 // on a separate line.
626 if (MergedLines > 0)
627 ++MergedLines;
628 }
629 return MergedLines;
630 }
631 if (TheLine->First->is(tok::kw_if)) {
632 return Style.AllowShortIfStatementsOnASingleLine
633 ? tryMergeSimpleControlStatement(I, E, Limit)
634 : 0;
635 }
636 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
637 return Style.AllowShortLoopsOnASingleLine
638 ? tryMergeSimpleControlStatement(I, E, Limit)
639 : 0;
640 }
641 if (TheLine->InPPDirective &&
642 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000643 return tryMergeSimplePPDirective(I, E, Limit);
644 }
645 return 0;
646 }
647
648private:
649 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000650 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000651 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
652 unsigned Limit) {
653 if (Limit == 0)
654 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000655 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000656 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000657 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000658 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000659 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000660 return 0;
661 return 1;
662 }
663
664 unsigned tryMergeSimpleControlStatement(
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000665 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000666 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
667 if (Limit == 0)
668 return 0;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000669 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
670 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
Daniel Jasper17605d32014-05-14 09:33:35 +0000671 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000672 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000673 if (I[1]->InPPDirective != (*I)->InPPDirective ||
674 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000675 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000676 Limit = limitConsideringMacros(I + 1, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000677 AnnotatedLine &Line = **I;
678 if (Line.Last->isNot(tok::r_paren))
679 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000680 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000681 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000682 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000683 tok::kw_while) ||
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000684 I[1]->First->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000685 return 0;
686 // Only inline simple if's (no nested if or else).
687 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000688 I[2]->First->is(tok::kw_else))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000689 return 0;
690 return 1;
691 }
692
693 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000694 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000695 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
696 unsigned Limit) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000697 AnnotatedLine &Line = **I;
Daniel Jasper17605d32014-05-14 09:33:35 +0000698
699 // Don't merge ObjC @ keywords and methods.
700 if (Line.First->isOneOf(tok::at, tok::minus, tok::plus))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000701 return 0;
702
Daniel Jasper17605d32014-05-14 09:33:35 +0000703 // Check that the current line allows merging. This depends on whether we
704 // are in a control flow statements as well as several style flags.
705 if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
706 return 0;
707 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
708 tok::kw_catch, tok::kw_for, tok::r_brace)) {
709 if (!Style.AllowShortBlocksOnASingleLine)
710 return 0;
711 if (!Style.AllowShortIfStatementsOnASingleLine &&
712 Line.First->is(tok::kw_if))
713 return 0;
714 if (!Style.AllowShortLoopsOnASingleLine &&
715 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
716 return 0;
717 // FIXME: Consider an option to allow short exception handling clauses on
718 // a single line.
719 if (Line.First->isOneOf(tok::kw_try, tok::kw_catch))
720 return 0;
721 }
722
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000723 FormatToken *Tok = I[1]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000724 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Craig Topper2145bc02014-05-09 08:15:10 +0000725 (Tok->getNextNonComment() == nullptr ||
Daniel Jasper56f8b432013-11-06 23:12:09 +0000726 Tok->getNextNonComment()->is(tok::semi))) {
727 // We merge empty blocks even if the line exceeds the column limit.
728 Tok->SpacesRequiredBefore = 0;
729 Tok->CanBreakBefore = true;
730 return 1;
731 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Daniel Jasper79dffb42014-05-07 09:48:30 +0000732 // We don't merge short records.
733 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
734 return 0;
735
Daniel Jasper56f8b432013-11-06 23:12:09 +0000736 // Check that we still have three lines and they fit into the limit.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000737 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000738 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000739 Limit = limitConsideringMacros(I + 2, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000740
741 if (!nextTwoLinesFitInto(I, Limit))
742 return 0;
743
744 // Second, check that the next line does not contain any braces - if it
745 // does, readability declines when putting it into a single line.
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000746 if (I[1]->Last->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000747 return 0;
748 do {
Daniel Jasperbd630732014-05-22 13:25:26 +0000749 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000750 return 0;
751 Tok = Tok->Next;
Craig Topper2145bc02014-05-09 08:15:10 +0000752 } while (Tok);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000753
Daniel Jasper79dffb42014-05-07 09:48:30 +0000754 // Last, check that the third line starts with a closing brace.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000755 Tok = I[2]->First;
Daniel Jasper79dffb42014-05-07 09:48:30 +0000756 if (Tok->isNot(tok::r_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000757 return 0;
758
759 return 2;
760 }
761 return 0;
762 }
763
Daniel Jasper64989962014-02-07 13:45:27 +0000764 /// Returns the modified column limit for \p I if it is inside a macro and
765 /// needs a trailing '\'.
766 unsigned
Daniel Jaspera0407742014-02-11 10:08:11 +0000767 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper64989962014-02-07 13:45:27 +0000768 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
769 unsigned Limit) {
770 if (I[0]->InPPDirective && I + 1 != E &&
771 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
772 return Limit < 2 ? 0 : Limit - 2;
773 }
774 return Limit;
775 }
776
Daniel Jasper56f8b432013-11-06 23:12:09 +0000777 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
778 unsigned Limit) {
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000779 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
780 return false;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000781 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000782 }
783
Daniel Jasper234379f2013-12-24 13:31:25 +0000784 bool containsMustBreak(const AnnotatedLine *Line) {
785 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
786 if (Tok->MustBreakBefore)
787 return true;
788 }
789 return false;
790 }
791
Daniel Jasper56f8b432013-11-06 23:12:09 +0000792 const FormatStyle &Style;
793};
794
Daniel Jasperf7935112012-12-03 18:12:45 +0000795class UnwrappedLineFormatter {
796public:
Daniel Jasper5500f612013-11-25 11:08:59 +0000797 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000798 WhitespaceManager *Whitespaces,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000799 const FormatStyle &Style)
Daniel Jasper5500f612013-11-25 11:08:59 +0000800 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
801 Joiner(Style) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000802
Daniel Jasper56f8b432013-11-06 23:12:09 +0000803 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper9c199562013-11-28 15:58:55 +0000804 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Daniel Jasperc359ad02014-04-15 08:13:47 +0000805 // Try to look up already computed penalty in DryRun-mode.
NAKAMURA Takumi22059522014-04-15 23:29:04 +0000806 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
807 &Lines, AdditionalIndent);
Daniel Jasperc359ad02014-04-15 08:13:47 +0000808 auto CacheIt = PenaltyCache.find(CacheKey);
809 if (DryRun && CacheIt != PenaltyCache.end())
810 return CacheIt->second;
811
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000812 assert(!Lines.empty());
813 unsigned Penalty = 0;
814 std::vector<int> IndentForLevel;
815 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
816 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Craig Topper2145bc02014-05-09 08:15:10 +0000817 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000818 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
819 E = Lines.end();
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000820 I != E; ++I) {
821 const AnnotatedLine &TheLine = **I;
822 const FormatToken *FirstTok = TheLine.First;
823 int Offset = getIndentOffset(*FirstTok);
824
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000825 // Determine indent and try to merge multiple unwrapped lines.
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000826 unsigned Indent;
827 if (TheLine.InPPDirective) {
828 Indent = TheLine.Level * Style.IndentWidth;
829 } else {
830 while (IndentForLevel.size() <= TheLine.Level)
831 IndentForLevel.push_back(-1);
832 IndentForLevel.resize(TheLine.Level + 1);
833 Indent = getIndent(IndentForLevel, TheLine.Level);
834 }
835 unsigned LevelIndent = Indent;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000836 if (static_cast<int>(Indent) + Offset >= 0)
837 Indent += Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000838
839 // Merge multiple lines if possible.
Daniel Jasper56f8b432013-11-06 23:12:09 +0000840 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
Alexander Kornienko31e95542013-12-04 12:21:08 +0000841 if (MergedLines > 0 && Style.ColumnLimit == 0) {
842 // Disallow line merging if there is a break at the start of one of the
843 // input lines.
844 for (unsigned i = 0; i < MergedLines; ++i) {
845 if (I[i + 1]->First->NewlinesBefore > 0)
846 MergedLines = 0;
847 }
848 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000849 if (!DryRun) {
850 for (unsigned i = 0; i < MergedLines; ++i) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000851 join(*I[i], *I[i + 1]);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000852 }
853 }
854 I += MergedLines;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000855
Daniel Jasper9c199562013-11-28 15:58:55 +0000856 bool FixIndentation =
857 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000858 if (TheLine.First->is(tok::eof)) {
Daniel Jasper5500f612013-11-25 11:08:59 +0000859 if (PreviousLine && PreviousLine->Affected && !DryRun) {
860 // Remove the file's trailing whitespace.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000861 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
862 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
863 /*IndentLevel=*/0, /*Spaces=*/0,
864 /*TargetColumn=*/0);
865 }
Daniel Jasper9c199562013-11-28 15:58:55 +0000866 } else if (TheLine.Type != LT_Invalid &&
867 (TheLine.Affected || FixIndentation)) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000868 if (FirstTok->WhitespaceRange.isValid()) {
869 if (!DryRun)
870 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
871 Indent, TheLine.InPPDirective);
872 } else {
873 Indent = LevelIndent = FirstTok->OriginalColumn;
874 }
875
876 // If everything fits on a single line, just put it there.
877 unsigned ColumnLimit = Style.ColumnLimit;
878 if (I + 1 != E) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000879 AnnotatedLine *NextLine = I[1];
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000880 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
881 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
882 }
883
884 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
885 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000886 while (State.NextToken) {
887 formatChildren(State, /*Newline=*/false, /*DryRun=*/false, Penalty);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000888 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000889 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000890 } else if (Style.ColumnLimit == 0) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000891 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000892 NoColumnLimitFormatter Formatter(Indenter);
893 if (!DryRun)
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000894 Formatter.format(Indent, &TheLine);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000895 } else {
896 Penalty += format(TheLine, Indent, DryRun);
897 }
898
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000899 if (!TheLine.InPPDirective)
900 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper9c199562013-11-28 15:58:55 +0000901 } else if (TheLine.ChildrenAffected) {
902 format(TheLine.Children, DryRun);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000903 } else {
904 // Format the first token if necessary, and notify the WhitespaceManager
905 // about the unchanged whitespace.
Craig Topper2145bc02014-05-09 08:15:10 +0000906 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000907 if (Tok == TheLine.First &&
908 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
909 unsigned LevelIndent = Tok->OriginalColumn;
910 if (!DryRun) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000911 // Remove trailing whitespace of the previous line.
Daniel Jasper5500f612013-11-25 11:08:59 +0000912 if ((PreviousLine && PreviousLine->Affected) ||
913 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000914 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
915 TheLine.InPPDirective);
916 } else {
917 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
918 }
919 }
920
921 if (static_cast<int>(LevelIndent) - Offset >= 0)
922 LevelIndent -= Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000923 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000924 IndentForLevel[TheLine.Level] = LevelIndent;
925 } else if (!DryRun) {
926 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
927 }
928 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000929 }
930 if (!DryRun) {
Craig Topper2145bc02014-05-09 08:15:10 +0000931 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000932 Tok->Finalized = true;
933 }
934 }
935 PreviousLine = *I;
936 }
Daniel Jasperc359ad02014-04-15 08:13:47 +0000937 PenaltyCache[CacheKey] = Penalty;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000938 return Penalty;
939 }
940
941private:
942 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000943 ///
944 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000945 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
946 bool DryRun) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000947 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +0000948
Daniel Jasperacc33662013-02-08 08:22:00 +0000949 // If the ObjC method declaration does not fit on a line, we should format
950 // it with one arg per line.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000951 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperacc33662013-02-08 08:22:00 +0000952 State.Stack.back().BreakBeforeParameter = true;
953
Daniel Jasper4b866272013-02-01 11:00:45 +0000954 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000955 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +0000956 }
957
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000958 /// \brief An edge in the solution space from \c Previous->State to \c State,
959 /// inserting a newline dependent on the \c NewLine.
960 struct StateNode {
961 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000962 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000963 LineState State;
964 bool NewLine;
965 StateNode *Previous;
966 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000967
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000968 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
969 ///
970 /// In case of equal penalties, we want to prefer states that were inserted
971 /// first. During state generation we make sure that we insert states first
972 /// that break the line as late as possible.
973 typedef std::pair<unsigned, unsigned> OrderedPenalty;
974
975 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
976 /// \c State has the given \c OrderedPenalty.
977 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
978
979 /// \brief The BFS queue type.
980 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
981 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000982
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000983 /// \brief Get the offset of the line relatively to the level.
984 ///
985 /// For example, 'public:' labels in classes are offset by 1 or 2
986 /// characters to the left from their level.
987 int getIndentOffset(const FormatToken &RootToken) {
988 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
989 return Style.AccessModifierOffset;
990 return 0;
991 }
992
993 /// \brief Add a new line and the required indent before the first Token
994 /// of the \c UnwrappedLine if there was no structural parsing error.
995 void formatFirstToken(FormatToken &RootToken,
996 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
997 unsigned Indent, bool InPPDirective) {
998 unsigned Newlines =
999 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1000 // Remove empty lines before "}" where applicable.
1001 if (RootToken.is(tok::r_brace) &&
1002 (!RootToken.Next ||
1003 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1004 Newlines = std::min(Newlines, 1u);
1005 if (Newlines == 0 && !RootToken.IsFirst)
1006 Newlines = 1;
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001007 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1008 Newlines = 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001009
Daniel Jasper11164bd2014-03-21 12:58:53 +00001010 // Remove empty lines after "{".
Daniel Jaspera26fc5c2014-03-21 13:43:14 +00001011 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1012 PreviousLine->Last->is(tok::l_brace) &&
Daniel Jasper01b35482014-03-21 13:03:33 +00001013 PreviousLine->First->isNot(tok::kw_namespace))
Daniel Jasper11164bd2014-03-21 12:58:53 +00001014 Newlines = 1;
1015
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001016 // Insert extra new line before access specifiers.
1017 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1018 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1019 ++Newlines;
1020
1021 // Remove empty lines after access specifiers.
1022 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
1023 Newlines = std::min(1u, Newlines);
1024
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001025 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
1026 Indent, InPPDirective &&
1027 !RootToken.HasUnescapedNewline);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001028 }
1029
1030 /// \brief Get the indent of \p Level from \p IndentForLevel.
1031 ///
1032 /// \p IndentForLevel must contain the indent for the level \c l
1033 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1034 /// that level is unknown.
1035 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
1036 if (IndentForLevel[Level] != -1)
1037 return IndentForLevel[Level];
1038 if (Level == 0)
1039 return 0;
1040 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
1041 }
1042
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001043 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1044 assert(!A.Last->Next);
1045 assert(!B.First->Previous);
Daniel Jasper5500f612013-11-25 11:08:59 +00001046 if (B.Affected)
1047 A.Affected = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001048 A.Last->Next = B.First;
1049 B.First->Previous = A.Last;
Daniel Jasper98fb6e12013-11-08 17:33:27 +00001050 B.First->CanBreakBefore = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001051 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1052 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1053 Tok->TotalLength += LengthA;
1054 A.Last = Tok;
1055 }
1056 }
1057
1058 unsigned getColumnLimit(bool InPPDirective) const {
1059 // In preprocessor directives reserve two chars for trailing " \"
1060 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1061 }
1062
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001063 struct CompareLineStatePointers {
1064 bool operator()(LineState *obj1, LineState *obj2) const {
1065 return *obj1 < *obj2;
1066 }
1067 };
1068
Daniel Jasper4b866272013-02-01 11:00:45 +00001069 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +00001070 ///
Daniel Jasper4b866272013-02-01 11:00:45 +00001071 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1072 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1073 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001074 /// to a state where all tokens are placed. Returns the penalty.
1075 ///
1076 /// If \p DryRun is \c false, directly applies the changes.
1077 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001078 std::set<LineState *, CompareLineStatePointers> Seen;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001079
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001080 // Increasing count of \c StateNode items we have created. This is used to
1081 // create a deterministic order independent of the container.
1082 unsigned Count = 0;
1083 QueueType Queue;
1084
Daniel Jasper4b866272013-02-01 11:00:45 +00001085 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001086 StateNode *Node =
Craig Topper2145bc02014-05-09 08:15:10 +00001087 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001088 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1089 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001090
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001091 unsigned Penalty = 0;
1092
Daniel Jasper4b866272013-02-01 11:00:45 +00001093 // While not empty, take first element and follow edges.
1094 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001095 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001096 StateNode *Node = Queue.top().second;
Craig Topper2145bc02014-05-09 08:15:10 +00001097 if (!Node->State.NextToken) {
Alexander Kornienko49149672013-05-10 11:56:10 +00001098 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001099 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001100 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001101 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001102
Daniel Jasperf8114cf2013-05-22 05:27:42 +00001103 // Cut off the analysis of certain solutions if the analysis gets too
1104 // complex. See description of IgnoreStackForComparison.
1105 if (Count > 10000)
1106 Node->State.IgnoreStackForComparison = true;
1107
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001108 if (!Seen.insert(&Node->State).second)
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001109 // State already examined with lower penalty.
1110 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001111
Manuel Klimek71814b42013-10-11 21:25:45 +00001112 FormatDecision LastFormat = Node->State.NextToken->Decision;
1113 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001114 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimek71814b42013-10-11 21:25:45 +00001115 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001116 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper4b866272013-02-01 11:00:45 +00001117 }
1118
Manuel Klimek71814b42013-10-11 21:25:45 +00001119 if (Queue.empty()) {
Daniel Jasper4b866272013-02-01 11:00:45 +00001120 // We were unable to find a solution, do nothing.
1121 // FIXME: Add diagnostic?
Manuel Klimek71814b42013-10-11 21:25:45 +00001122 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001123 return 0;
Manuel Klimek71814b42013-10-11 21:25:45 +00001124 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001125
Daniel Jasper4b866272013-02-01 11:00:45 +00001126 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001127 if (!DryRun)
1128 reconstructPath(InitialState, Queue.top().second);
1129
Alexander Kornienko49149672013-05-10 11:56:10 +00001130 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1131 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001132
1133 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001134 }
1135
1136 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001137 std::deque<StateNode *> Path;
1138 // We do not need a break before the initial token.
1139 while (Current->Previous) {
1140 Path.push_front(Current);
1141 Current = Current->Previous;
1142 }
1143 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1144 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001145 unsigned Penalty = 0;
1146 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1147 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1148
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001149 DEBUG({
1150 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001151 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001152 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001153 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001154 }
1155 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001156 }
Daniel Jasper4b866272013-02-01 11:00:45 +00001157 }
1158
Manuel Klimekaf491072013-02-13 10:54:19 +00001159 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001160 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001161 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001162 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001163 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001164 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001165 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001166 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001167 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001168 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001169
1170 StateNode *Node = new (Allocator.Allocate())
1171 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001172 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1173 return;
1174
Daniel Jasperde0328a2013-08-16 11:20:30 +00001175 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001176
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001177 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1178 ++(*Count);
Daniel Jasper4b866272013-02-01 11:00:45 +00001179 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001180
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001181 /// \brief If the \p State's next token is an r_brace closing a nested block,
1182 /// format the nested block before it.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001183 ///
1184 /// Returns \c true if all children could be placed successfully and adapts
1185 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1186 /// creates changes using \c Whitespaces.
1187 ///
1188 /// The crucial idea here is that children always get formatted upon
1189 /// encountering the closing brace right after the nested block. Now, if we
1190 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1191 /// \c false), the entire block has to be kept on the same line (which is only
1192 /// possible if it fits on the line, only contains a single statement, etc.
1193 ///
1194 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1195 /// break after the "{", format all lines with correct indentation and the put
1196 /// the closing "}" on yet another new line.
1197 ///
1198 /// This enables us to keep the simple structure of the
1199 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1200 /// break or don't break.
1201 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1202 unsigned &Penalty) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001203 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001204 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1205 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1206 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001207 // The previous token does not open a block. Nothing to do. We don't
1208 // assert so that we can simply call this function for all tokens.
Daniel Jasper36c28ce2013-09-06 08:54:24 +00001209 return true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001210
1211 if (NewLine) {
Daniel Jasper58cb2ed2014-06-06 13:49:04 +00001212 int AdditionalIndent =
1213 State.FirstIndent - State.Line->Level * Style.IndentWidth;
Daniel Jasperb16b9692014-05-21 12:51:23 +00001214 if (State.Stack.size() < 2 ||
1215 !State.Stack[State.Stack.size() - 2].JSFunctionInlined) {
1216 AdditionalIndent = State.Stack.back().Indent -
1217 Previous.Children[0]->Level * Style.IndentWidth;
1218 }
1219
Daniel Jasper9c199562013-11-28 15:58:55 +00001220 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1221 /*FixBadIndentation=*/true);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001222 return true;
1223 }
1224
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001225 // Cannot merge multiple statements into a single line.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001226 if (Previous.Children.size() > 1)
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001227 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001228
Daniel Jasper21397a32014-04-09 12:21:48 +00001229 // Cannot merge into one line if this line ends on a comment.
1230 if (Previous.is(tok::comment))
1231 return false;
1232
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001233 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001234 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001235 return false;
1236
Daniel Jasper98583d52014-04-15 08:28:06 +00001237 // If the child line exceeds the column limit, we wouldn't want to merge it.
1238 // We add +2 for the trailing " }".
1239 if (Style.ColumnLimit > 0 &&
1240 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
1241 Style.ColumnLimit)
1242 return false;
1243
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001244 if (!DryRun) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001245 Whitespaces->replaceWhitespace(
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001246 *Previous.Children[0]->First,
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001247 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001248 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001249 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001250 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001251
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001252 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001253 return true;
1254 }
1255
Daniel Jasperde0328a2013-08-16 11:20:30 +00001256 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001257 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001258 FormatStyle Style;
Daniel Jasper56f8b432013-11-06 23:12:09 +00001259 LineJoiner Joiner;
Manuel Klimekaf491072013-02-13 10:54:19 +00001260
1261 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperc359ad02014-04-15 08:13:47 +00001262
1263 // Cache to store the penalty of formatting a vector of AnnotatedLines
1264 // starting from a specific additional offset. Improves performance if there
1265 // are many nested blocks.
1266 std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
1267 unsigned> PenaltyCache;
Daniel Jasperf7935112012-12-03 18:12:45 +00001268};
1269
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001270class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001271public:
Manuel Klimek31c85922013-08-29 15:21:40 +00001272 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001273 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +00001274 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
1275 Column(0), TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr),
1276 Style(Style), IdentTable(getFormattingLangOpts()), Encoding(Encoding),
Manuel Klimek68b03042014-04-14 09:14:11 +00001277 FirstInLineIndex(0) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001278 Lex.SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +00001279
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001280 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +00001281 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1282 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001283 }
1284
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001285 ArrayRef<FormatToken *> lex() {
1286 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +00001287 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001288 do {
1289 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001290 tryMergePreviousTokens();
Manuel Klimek68b03042014-04-14 09:14:11 +00001291 if (Tokens.back()->NewlinesBefore > 0)
1292 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001293 } while (Tokens.back()->Tok.isNot(tok::eof));
1294 return Tokens;
1295 }
1296
1297 IdentifierTable &getIdentTable() { return IdentTable; }
1298
1299private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001300 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001301 if (tryMerge_TMacro())
1302 return;
Manuel Klimek68b03042014-04-14 09:14:11 +00001303 if (tryMergeConflictMarkers())
1304 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001305
1306 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001307 if (tryMergeEscapeSequence())
1308 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001309 if (tryMergeJSRegexLiteral())
1310 return;
1311
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001312 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1313 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1314 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1315 tok::greaterequal };
Daniel Jasper78214392014-05-19 07:27:02 +00001316 static tok::TokenKind JSRightArrow[] = { tok::equal, tok::greater };
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001317 // FIXME: We probably need to change token type to mimic operator with the
1318 // correct priority.
1319 if (tryMergeTokens(JSIdentity))
1320 return;
1321 if (tryMergeTokens(JSNotIdentity))
1322 return;
1323 if (tryMergeTokens(JSShiftEqual))
1324 return;
Daniel Jasper78214392014-05-19 07:27:02 +00001325 if (tryMergeTokens(JSRightArrow))
1326 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001327 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001328 }
1329
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001330 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1331 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001332 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001333
1334 SmallVectorImpl<FormatToken *>::const_iterator First =
1335 Tokens.end() - Kinds.size();
1336 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001337 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001338 unsigned AddLength = 0;
1339 for (unsigned i = 1; i < Kinds.size(); ++i) {
1340 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1341 First[i]->WhitespaceRange.getEnd())
1342 return false;
1343 AddLength += First[i]->TokenText.size();
1344 }
1345 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1346 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1347 First[0]->TokenText.size() + AddLength);
1348 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001349 return true;
1350 }
1351
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001352 // Tries to merge an escape sequence, i.e. a "\\" and the following
Alp Tokerc3f36af2014-05-15 01:35:53 +00001353 // character. Use e.g. inside JavaScript regex literals.
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001354 bool tryMergeEscapeSequence() {
1355 if (Tokens.size() < 2)
1356 return false;
1357 FormatToken *Previous = Tokens[Tokens.size() - 2];
1358 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\" ||
1359 Tokens.back()->NewlinesBefore != 0)
1360 return false;
1361 Previous->ColumnWidth += Tokens.back()->ColumnWidth;
1362 StringRef Text = Previous->TokenText;
1363 Previous->TokenText =
1364 StringRef(Text.data(), Text.size() + Tokens.back()->TokenText.size());
1365 Tokens.resize(Tokens.size() - 1);
1366 return true;
1367 }
1368
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001369 // Try to determine whether the current token ends a JavaScript regex literal.
1370 // We heuristically assume that this is a regex literal if we find two
1371 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +00001372 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
1373 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001374 bool tryMergeJSRegexLiteral() {
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001375 if (Tokens.size() < 2 || Tokens.back()->isNot(tok::slash) ||
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001376 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
1377 Tokens[Tokens.size() - 2]->TokenText == "\\"))
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001378 return false;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001379 unsigned TokenCount = 0;
1380 unsigned LastColumn = Tokens.back()->OriginalColumn;
1381 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
1382 ++TokenCount;
1383 if (I[0]->is(tok::slash) && I + 1 != E &&
1384 (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
1385 tok::exclaim, tok::l_square, tok::colon, tok::comma,
1386 tok::question, tok::kw_return) ||
1387 I[1]->isBinaryOperator())) {
1388 Tokens.resize(Tokens.size() - TokenCount);
1389 Tokens.back()->Tok.setKind(tok::unknown);
1390 Tokens.back()->Type = TT_RegexLiteral;
1391 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
1392 return true;
1393 }
1394
1395 // There can't be a newline inside a regex literal.
1396 if (I[0]->NewlinesBefore > 0)
1397 return false;
1398 }
1399 return false;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001400 }
1401
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001402 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001403 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001404 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001405 FormatToken *Last = Tokens.back();
1406 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001407 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001408
1409 FormatToken *String = Tokens[Tokens.size() - 2];
1410 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001411 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001412
1413 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001414 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001415
1416 FormatToken *Macro = Tokens[Tokens.size() - 4];
1417 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001418 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001419
1420 const char *Start = Macro->TokenText.data();
1421 const char *End = Last->TokenText.data() + Last->TokenText.size();
1422 String->TokenText = StringRef(Start, End - Start);
1423 String->IsFirst = Macro->IsFirst;
1424 String->LastNewlineOffset = Macro->LastNewlineOffset;
1425 String->WhitespaceRange = Macro->WhitespaceRange;
1426 String->OriginalColumn = Macro->OriginalColumn;
1427 String->ColumnWidth = encoding::columnWidthWithTabs(
1428 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1429
1430 Tokens.pop_back();
1431 Tokens.pop_back();
1432 Tokens.pop_back();
1433 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001434 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001435 }
1436
Manuel Klimek68b03042014-04-14 09:14:11 +00001437 bool tryMergeConflictMarkers() {
1438 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1439 return false;
1440
1441 // Conflict lines look like:
1442 // <marker> <text from the vcs>
1443 // For example:
1444 // >>>>>>> /file/in/file/system at revision 1234
1445 //
1446 // We merge all tokens in a line that starts with a conflict marker
1447 // into a single token with a special token type that the unwrapped line
1448 // parser will use to correctly rebuild the underlying code.
1449
1450 FileID ID;
1451 // Get the position of the first token in the line.
1452 unsigned FirstInLineOffset;
1453 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1454 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1455 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1456 // Calculate the offset of the start of the current line.
1457 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1458 if (LineOffset == StringRef::npos) {
1459 LineOffset = 0;
1460 } else {
1461 ++LineOffset;
1462 }
1463
1464 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1465 StringRef LineStart;
1466 if (FirstSpace == StringRef::npos) {
1467 LineStart = Buffer.substr(LineOffset);
1468 } else {
1469 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1470 }
1471
1472 TokenType Type = TT_Unknown;
1473 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1474 Type = TT_ConflictStart;
1475 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1476 LineStart == "====") {
1477 Type = TT_ConflictAlternative;
1478 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1479 Type = TT_ConflictEnd;
1480 }
1481
1482 if (Type != TT_Unknown) {
1483 FormatToken *Next = Tokens.back();
1484
1485 Tokens.resize(FirstInLineIndex + 1);
1486 // We do not need to build a complete token here, as we will skip it
1487 // during parsing anyway (as we must not touch whitespace around conflict
1488 // markers).
1489 Tokens.back()->Type = Type;
1490 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1491
1492 Tokens.push_back(Next);
1493 return true;
1494 }
1495
1496 return false;
1497 }
1498
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001499 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001500 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001501 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +00001502 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001503 Token Greater = FormatTok->Tok;
1504 FormatTok = new (Allocator.Allocate()) FormatToken;
1505 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001506 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001507 FormatTok->Tok.getLocation().getLocWithOffset(1);
1508 FormatTok->WhitespaceRange =
1509 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001510 FormatTok->TokenText = ">";
Alexander Kornienko39856b72013-09-10 09:38:25 +00001511 FormatTok->ColumnWidth = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001512 GreaterStashed = false;
1513 return FormatTok;
1514 }
1515
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001516 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001517 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001518 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001519 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001520 FormatTok->IsFirst = IsFirstToken;
1521 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001522
1523 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001524 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001525 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001526 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1527 switch (FormatTok->TokenText[i]) {
1528 case '\n':
1529 ++FormatTok->NewlinesBefore;
1530 // FIXME: This is technically incorrect, as it could also
1531 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001532 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1533 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1534 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +00001535 FormatTok->HasUnescapedNewline = true;
1536 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1537 Column = 0;
1538 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001539 case '\r':
1540 case '\f':
1541 case '\v':
1542 Column = 0;
1543 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001544 case ' ':
1545 ++Column;
1546 break;
1547 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001548 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001549 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001550 case '\\':
1551 ++Column;
1552 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1553 FormatTok->TokenText[i + 1] != '\n'))
1554 FormatTok->Type = TT_ImplicitStringLiteral;
1555 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001556 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001557 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001558 ++Column;
1559 break;
1560 }
1561 }
1562
Daniel Jasper877615c2013-10-11 19:45:02 +00001563 if (FormatTok->Type == TT_ImplicitStringLiteral)
1564 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001565 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001566
Daniel Jasper8369aa52013-07-16 20:28:33 +00001567 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001568 }
Manuel Klimekef920692013-01-07 07:56:50 +00001569
Manuel Klimek1abf7892013-01-04 23:34:14 +00001570 // In case the token starts with escaped newlines, we want to
1571 // take them into account as whitespace - this pattern is quite frequent
1572 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001573 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001574 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1575 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001576 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001577 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001578 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001579 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001580 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001581
1582 FormatTok->WhitespaceRange = SourceRange(
1583 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1584
Manuel Klimek31c85922013-08-29 15:21:40 +00001585 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001586
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001587 TrailingWhitespace = 0;
1588 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001589 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001590 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001591 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001592 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001593 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001594 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001595 FormatTok->Tok.setIdentifierInfo(&Info);
1596 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001597 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001598 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001599 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001600 GreaterStashed = true;
1601 }
1602
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001603 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001604
Alexander Kornienko39856b72013-09-10 09:38:25 +00001605 StringRef Text = FormatTok->TokenText;
1606 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001607 if (FirstNewlinePos == StringRef::npos) {
1608 // FIXME: ColumnWidth actually depends on the start column, we need to
1609 // take this into account when the token is moved.
1610 FormatTok->ColumnWidth =
1611 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1612 Column += FormatTok->ColumnWidth;
1613 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001614 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001615 // FIXME: ColumnWidth actually depends on the start column, we need to
1616 // take this into account when the token is moved.
1617 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1618 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1619
Alexander Kornienko39856b72013-09-10 09:38:25 +00001620 // The last line of the token always starts in column 0.
1621 // Thus, the length can be precomputed even in the presence of tabs.
1622 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1623 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1624 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001625 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001626 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001627
Daniel Jaspere1e43192014-04-01 12:55:11 +00001628 FormatTok->IsForEachMacro =
1629 std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1630 FormatTok->Tok.getIdentifierInfo());
1631
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001632 return FormatTok;
1633 }
1634
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001635 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001636 bool IsFirstToken;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001637 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001638 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001639 unsigned TrailingWhitespace;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001640 Lexer &Lex;
1641 SourceManager &SourceMgr;
Manuel Klimek31c85922013-08-29 15:21:40 +00001642 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001643 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001644 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001645 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001646 // Index (in 'Tokens') of the last token that starts a new line.
1647 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001648 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001649 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001650
Daniel Jasper8369aa52013-07-16 20:28:33 +00001651 void readRawToken(FormatToken &Tok) {
1652 Lex.LexFromRawLexer(Tok.Tok);
1653 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1654 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001655 // For formatting, treat unterminated string literals like normal string
1656 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001657 if (Tok.is(tok::unknown)) {
1658 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1659 Tok.Tok.setKind(tok::string_literal);
1660 Tok.IsUnterminatedLiteral = true;
1661 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1662 Tok.TokenText == "''") {
1663 Tok.Tok.setKind(tok::char_constant);
1664 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001665 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001666 }
1667};
1668
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001669static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1670 switch (Language) {
1671 case FormatStyle::LK_Cpp:
1672 return "C++";
1673 case FormatStyle::LK_JavaScript:
1674 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001675 case FormatStyle::LK_Proto:
1676 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001677 default:
1678 return "Unknown";
1679 }
1680}
1681
Daniel Jasperf7935112012-12-03 18:12:45 +00001682class Formatter : public UnwrappedLineConsumer {
1683public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001684 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001685 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001686 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001687 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001688 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Manuel Klimek71814b42013-10-11 21:25:45 +00001689 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001690 DEBUG(llvm::dbgs() << "File encoding: "
1691 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1692 : "unknown")
1693 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001694 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1695 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001696 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001697
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001698 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001699 tooling::Replacements Result;
Manuel Klimek31c85922013-08-29 15:21:40 +00001700 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001701
1702 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001703 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001704 assert(UnwrappedLines.rbegin()->empty());
1705 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1706 ++Run) {
1707 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1708 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1709 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1710 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1711 }
1712 tooling::Replacements RunResult =
1713 format(AnnotatedLines, StructuralError, Tokens);
1714 DEBUG({
1715 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1716 for (tooling::Replacements::iterator I = RunResult.begin(),
1717 E = RunResult.end();
1718 I != E; ++I) {
1719 llvm::dbgs() << I->toString() << "\n";
1720 }
1721 });
1722 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1723 delete AnnotatedLines[i];
1724 }
1725 Result.insert(RunResult.begin(), RunResult.end());
1726 Whitespaces.reset();
1727 }
1728 return Result;
1729 }
1730
1731 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1732 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001733 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
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.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001736 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001737 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001738 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001739 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001740 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001741 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001742
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001743 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001744 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1745 BinPackInconclusiveFunctions);
Daniel Jasper5500f612013-11-25 11:08:59 +00001746 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001747 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001748 return Whitespaces.generateReplacements();
1749 }
1750
1751private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001752 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001753 // Returns \c true if at least one line between I and E or one of their
1754 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001755 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1756 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1757 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001758 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001759 while (I != E) {
1760 AnnotatedLine *Line = *I;
1761 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1762
1763 // If a line is part of a preprocessor directive, it needs to be formatted
1764 // if any token within the directive is affected.
1765 if (Line->InPPDirective) {
1766 FormatToken *Last = Line->Last;
1767 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1768 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1769 Last = (*PPEnd)->Last;
1770 ++PPEnd;
1771 }
1772
1773 if (affectsTokenRange(*Line->First, *Last,
1774 /*IncludeLeadingNewlines=*/false)) {
1775 SomeLineAffected = true;
1776 markAllAsAffected(I, PPEnd);
1777 }
1778 I = PPEnd;
1779 continue;
1780 }
1781
Daniel Jasper38c82402013-11-29 09:27:43 +00001782 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001783 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001784
Daniel Jasper38c82402013-11-29 09:27:43 +00001785 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001786 ++I;
1787 }
1788 return SomeLineAffected;
1789 }
1790
Daniel Jasper9c199562013-11-28 15:58:55 +00001791 // Determines whether 'Line' is affected by the SourceRanges given as input.
1792 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001793 bool nonPPLineAffected(AnnotatedLine *Line,
1794 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001795 bool SomeLineAffected = false;
1796 Line->ChildrenAffected =
1797 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1798 if (Line->ChildrenAffected)
1799 SomeLineAffected = true;
1800
1801 // Stores whether one of the line's tokens is directly affected.
1802 bool SomeTokenAffected = false;
1803 // Stores whether we need to look at the leading newlines of the next token
1804 // in order to determine whether it was affected.
1805 bool IncludeLeadingNewlines = false;
1806
1807 // Stores whether the first child line of any of this line's tokens is
1808 // affected.
1809 bool SomeFirstChildAffected = false;
1810
1811 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1812 // Determine whether 'Tok' was affected.
1813 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1814 SomeTokenAffected = true;
1815
1816 // Determine whether the first child of 'Tok' was affected.
1817 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1818 SomeFirstChildAffected = true;
1819
1820 IncludeLeadingNewlines = Tok->Children.empty();
1821 }
1822
1823 // Was this line moved, i.e. has it previously been on the same line as an
1824 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001825 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1826 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001827
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001828 bool IsContinuedComment =
1829 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1830 Line->First->NewlinesBefore < 2 && PreviousLine &&
1831 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001832
1833 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1834 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001835 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001836 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001837 }
1838 return SomeLineAffected;
1839 }
1840
Daniel Jasper5500f612013-11-25 11:08:59 +00001841 // Marks all lines between I and E as well as all their children as affected.
1842 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1843 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1844 while (I != E) {
1845 (*I)->Affected = true;
1846 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1847 ++I;
1848 }
1849 }
1850
1851 // Returns true if the range from 'First' to 'Last' intersects with one of the
1852 // input ranges.
1853 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1854 bool IncludeLeadingNewlines) {
1855 SourceLocation Start = First.WhitespaceRange.getBegin();
1856 if (!IncludeLeadingNewlines)
1857 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001858 SourceLocation End = Last.getStartOfNonWhitespace();
1859 if (Last.TokenText.size() > 0)
1860 End = End.getLocWithOffset(Last.TokenText.size() - 1);
Daniel Jasper5500f612013-11-25 11:08:59 +00001861 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1862 return affectsCharSourceRange(Range);
1863 }
1864
1865 // Returns true if one of the input ranges intersect the leading empty lines
1866 // before 'Tok'.
1867 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1868 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1869 Tok.WhitespaceRange.getBegin(),
1870 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1871 return affectsCharSourceRange(EmptyLineRange);
1872 }
1873
1874 // Returns true if 'Range' intersects with one of the input ranges.
1875 bool affectsCharSourceRange(const CharSourceRange &Range) {
1876 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1877 E = Ranges.end();
1878 I != E; ++I) {
1879 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1880 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1881 return true;
1882 }
1883 return false;
1884 }
1885
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001886 static bool inputUsesCRLF(StringRef Text) {
1887 return Text.count('\r') * 2 > Text.count('\n');
1888 }
1889
Manuel Klimek71814b42013-10-11 21:25:45 +00001890 void
1891 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001892 unsigned CountBoundToVariable = 0;
1893 unsigned CountBoundToType = 0;
1894 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001895 bool HasBinPackedFunction = false;
1896 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001897 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001898 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001899 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001900 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001901 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001902 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001903 bool SpacesBefore =
1904 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1905 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1906 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001907 if (SpacesBefore && !SpacesAfter)
1908 ++CountBoundToVariable;
1909 else if (!SpacesBefore && SpacesAfter)
1910 ++CountBoundToType;
1911 }
1912
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001913 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1914 if (Tok->is(tok::coloncolon) &&
1915 Tok->Previous->Type == TT_TemplateOpener)
1916 HasCpp03IncompatibleFormat = true;
1917 if (Tok->Type == TT_TemplateCloser &&
1918 Tok->Previous->Type == TT_TemplateCloser)
1919 HasCpp03IncompatibleFormat = true;
1920 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001921
1922 if (Tok->PackingKind == PPK_BinPacked)
1923 HasBinPackedFunction = true;
1924 if (Tok->PackingKind == PPK_OnePerLine)
1925 HasOnePerLineFunction = true;
1926
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001927 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001928 }
1929 }
Daniel Jasper553d4872014-06-17 12:40:34 +00001930 if (Style.DerivePointerAlignment) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001931 if (CountBoundToType > CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00001932 Style.PointerAlignment = FormatStyle::PAS_Left;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001933 else if (CountBoundToType < CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00001934 Style.PointerAlignment = FormatStyle::PAS_Right;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001935 }
1936 if (Style.Standard == FormatStyle::LS_Auto) {
1937 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1938 : FormatStyle::LS_Cpp03;
1939 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001940 BinPackInconclusiveFunctions =
1941 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001942 }
1943
Craig Topperfb6b25b2014-03-15 04:29:04 +00001944 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001945 assert(!UnwrappedLines.empty());
1946 UnwrappedLines.back().push_back(TheLine);
1947 }
1948
Craig Topperfb6b25b2014-03-15 04:29:04 +00001949 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001950 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001951 }
1952
1953 FormatStyle Style;
1954 Lexer &Lex;
1955 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001956 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001957 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001958 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001959
1960 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001961 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001962};
1963
Craig Topperaf35e852013-06-30 22:29:28 +00001964} // end anonymous namespace
1965
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001966tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1967 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001968 std::vector<CharSourceRange> Ranges) {
Daniel Jasperc64b09a2014-05-22 15:12:22 +00001969 if (Style.DisableFormat) {
1970 tooling::Replacements EmptyResult;
1971 return EmptyResult;
1972 }
1973
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001974 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001975 return formatter.format();
1976}
1977
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001978tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1979 std::vector<tooling::Range> Ranges,
1980 StringRef FileName) {
1981 FileManager Files((FileSystemOptions()));
1982 DiagnosticsEngine Diagnostics(
1983 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1984 new DiagnosticOptions);
1985 SourceManager SourceMgr(Diagnostics, Files);
1986 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1987 const clang::FileEntry *Entry =
1988 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1989 SourceMgr.overrideFileContents(Entry, Buf);
1990 FileID ID =
1991 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienko1e808872013-06-28 12:51:24 +00001992 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1993 getFormattingLangOpts(Style.Standard));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001994 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1995 std::vector<CharSourceRange> CharRanges;
1996 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1997 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1998 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1999 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
2000 }
2001 return reformat(Style, Lex, SourceMgr, CharRanges);
2002}
2003
Alexander Kornienko1e808872013-06-28 12:51:24 +00002004LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002005 LangOptions LangOpts;
2006 LangOpts.CPlusPlus = 1;
Alexander Kornienko1e808872013-06-28 12:51:24 +00002007 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper20fd3c62014-04-15 08:49:21 +00002008 LangOpts.CPlusPlus1y = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00002009 LangOpts.LineComment = 1;
Nikola Smiljanice08a91e2014-05-08 00:05:13 +00002010 LangOpts.CXXOperatorNames = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002011 LangOpts.Bool = 1;
2012 LangOpts.ObjC1 = 1;
2013 LangOpts.ObjC2 = 1;
2014 return LangOpts;
2015}
2016
Edwin Vaned544aa72013-09-30 13:31:48 +00002017const char *StyleOptionHelpDescription =
2018 "Coding style, currently supports:\n"
2019 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
2020 "Use -style=file to load style configuration from\n"
2021 ".clang-format file located in one of the parent\n"
2022 "directories of the source file (or current\n"
2023 "directory for stdin).\n"
2024 "Use -style=\"{key: value, ...}\" to set specific\n"
2025 "parameters, e.g.:\n"
2026 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
2027
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002028static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002029 if (FileName.endswith_lower(".js")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002030 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00002031 } else if (FileName.endswith_lower(".proto") ||
2032 FileName.endswith_lower(".protodevel")) {
2033 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002034 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002035 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002036}
2037
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002038FormatStyle getStyle(StringRef StyleName, StringRef FileName,
2039 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002040 FormatStyle Style = getLLVMStyle();
2041 Style.Language = getLanguageByFileName(FileName);
2042 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002043 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
2044 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002045 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002046 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002047
2048 if (StyleName.startswith("{")) {
2049 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00002050 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002051 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
2052 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00002053 }
2054 return Style;
2055 }
2056
2057 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002058 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00002059 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
2060 << " style\n";
2061 return Style;
2062 }
2063
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002064 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002065 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00002066 SmallString<128> Path(FileName);
2067 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002068 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00002069 Directory = llvm::sys::path::parent_path(Directory)) {
2070 if (!llvm::sys::fs::is_directory(Directory))
2071 continue;
2072 SmallString<128> ConfigFile(Directory);
2073
2074 llvm::sys::path::append(ConfigFile, ".clang-format");
2075 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2076 bool IsFile = false;
2077 // Ignore errors from is_regular_file: we only need to know if we can read
2078 // the file or not.
2079 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2080
2081 if (!IsFile) {
2082 // Try _clang-format too, since dotfiles are not commonly used on Windows.
2083 ConfigFile = Directory;
2084 llvm::sys::path::append(ConfigFile, "_clang-format");
2085 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2086 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2087 }
2088
2089 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002090 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
2091 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
2092 if (std::error_code EC = Text.getError()) {
2093 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002094 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002095 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002096 if (std::error_code ec =
2097 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00002098 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002099 if (!UnsuitableConfigFiles.empty())
2100 UnsuitableConfigFiles.append(", ");
2101 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002102 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002103 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002104 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2105 << "\n";
2106 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002107 }
2108 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2109 return Style;
2110 }
2111 }
2112 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
2113 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002114 if (!UnsuitableConfigFiles.empty()) {
2115 llvm::errs() << "Configuration file(s) do(es) not support "
2116 << getLanguageName(Style.Language) << ": "
2117 << UnsuitableConfigFiles << "\n";
2118 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002119 return Style;
2120}
2121
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002122} // namespace format
2123} // namespace clang