blob: d8633d88f1d84df51800e728abf09bbf8a0b7ddc [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 <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000100struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000101 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000102 FormatStyle::SpaceBeforeParensOptions &Value) {
103 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000104 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000105 FormatStyle::SBPO_ControlStatements);
106 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000107
108 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000109 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
110 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000111 }
112};
113
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000114template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000115 static void mapping(IO &IO, FormatStyle &Style) {
116 // When reading, read the language first, we need it for getPredefinedStyle.
117 IO.mapOptional("Language", Style.Language);
118
Alexander Kornienko49149672013-05-10 11:56:10 +0000119 if (IO.outputting()) {
Alexander Kornienkoe3648fb2013-09-02 16:39:23 +0000120 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000121 "Mozilla", "WebKit", "GNU" };
Alexander Kornienko49149672013-05-10 11:56:10 +0000122 ArrayRef<StringRef> Styles(StylesArray);
123 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
124 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000125 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000126 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000127 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000128 IO.mapOptional("# BasedOnStyle", StyleName);
129 break;
130 }
131 }
132 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000133 StringRef BasedOnStyle;
134 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000135 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000136 FormatStyle::LanguageKind OldLanguage = Style.Language;
137 FormatStyle::LanguageKind Language =
138 ((FormatStyle *)IO.getContext())->Language;
139 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000140 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
141 return;
142 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000143 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000144 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000145 }
146
147 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000148 IO.mapOptional("ConstructorInitializerIndentWidth",
149 Style.ConstructorInitializerIndentWidth);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000150 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000151 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000152 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
153 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000154 IO.mapOptional("AllowShortBlocksOnASingleLine",
155 Style.AllowShortBlocksOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000156 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
157 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000158 IO.mapOptional("AllowShortLoopsOnASingleLine",
159 Style.AllowShortLoopsOnASingleLine);
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000160 IO.mapOptional("AllowShortFunctionsOnASingleLine",
161 Style.AllowShortFunctionsOnASingleLine);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000162 IO.mapOptional("AlwaysBreakTemplateDeclarations",
163 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko58611712013-07-04 12:02:44 +0000164 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
165 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000166 IO.mapOptional("BreakBeforeBinaryOperators",
167 Style.BreakBeforeBinaryOperators);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000168 IO.mapOptional("BreakBeforeTernaryOperators",
169 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000170 IO.mapOptional("BreakConstructorInitializersBeforeComma",
171 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000172 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
173 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
174 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
175 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
176 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000177 IO.mapOptional("ExperimentalAutoDetectBinPacking",
178 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000179 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
180 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000181 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
182 Style.KeepEmptyLinesAtTheStartOfBlocks);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000183 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000184 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000185 IO.mapOptional("ObjCSpaceBeforeProtocolList",
186 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000187 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
188 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000189 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
190 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000191 IO.mapOptional("PenaltyBreakFirstLessLess",
192 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000193 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
194 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
195 Style.PenaltyReturnTypeOnItsOwnLine);
196 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
197 IO.mapOptional("SpacesBeforeTrailingComments",
198 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000199 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000200 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000201 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000202 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000203 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000204 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimek836c2862013-06-21 17:25:42 +0000205 IO.mapOptional("IndentFunctionDeclarationAfterType",
206 Style.IndentFunctionDeclarationAfterType);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000207 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000208 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasperf110e202013-08-21 08:39:01 +0000209 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000210 IO.mapOptional("SpacesInCStyleCastParentheses",
211 Style.SpacesInCStyleCastParentheses);
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000212 IO.mapOptional("SpacesInContainerLiterals",
213 Style.SpacesInContainerLiterals);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000214 IO.mapOptional("SpaceBeforeAssignmentOperators",
215 Style.SpaceBeforeAssignmentOperators);
Daniel Jasper6633ab82013-10-18 10:38:14 +0000216 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000217 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000218 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000219
220 // For backward compatibility.
221 if (!IO.outputting()) {
222 IO.mapOptional("SpaceAfterControlStatementKeyword",
223 Style.SpaceBeforeParens);
224 }
225 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000226 IO.mapOptional("DisableFormat", Style.DisableFormat);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000227 }
228};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000229
230// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000231// IO.getContext() should contain a pointer to the FormatStyle structure, that
232// will be used to get default values for missing keys.
233// If the first element has no Language specified, it will be treated as the
234// default one for the following elements.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000235template <> struct DocumentListTraits<std::vector<FormatStyle> > {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000236 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
237 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000238 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000239 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000240 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000241 if (Index >= Seq.size()) {
242 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000243 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000244 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000245 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000246 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000247 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000248 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000249 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000250 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000251 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000252 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000253 }
254};
Alexander Kornienkod6538332013-05-07 15:32:14 +0000255}
256}
257
Daniel Jasperf7935112012-12-03 18:12:45 +0000258namespace clang {
259namespace format {
260
Rafael Espindolad0136702014-06-12 02:50:04 +0000261const std::error_category &getParestCategory() {
262 static ParseErrorCategory C;
263 return C;
264}
265std::error_code make_error_code(ParseError e) {
266 return std::error_code(static_cast<int>(e), getParestCategory());
267}
268
269const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
270 return "clang-format.parse_error";
271}
272
273std::string ParseErrorCategory::message(int EV) const {
274 switch (static_cast<ParseError>(EV)) {
275 case ParseError::Success:
276 return "Success";
277 case ParseError::Error:
278 return "Invalid argument";
279 case ParseError::Unsuitable:
280 return "Unsuitable";
281 }
282}
283
Daniel Jasperf7935112012-12-03 18:12:45 +0000284FormatStyle getLLVMStyle() {
285 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000286 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000287 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000288 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000289 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000290 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000291 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000292 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000293 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000294 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000295 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000296 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000297 LLVMStyle.BinPackParameters = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000298 LLVMStyle.BreakBeforeBinaryOperators = false;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000299 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000300 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
301 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000302 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000303 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000304 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000305 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000306 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000307 LLVMStyle.Cpp11BracedListStyle = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000308 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000309 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000310 LLVMStyle.ForEachMacros.push_back("foreach");
311 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
312 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000313 LLVMStyle.IndentCaseLabels = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000314 LLVMStyle.IndentFunctionDeclarationAfterType = false;
315 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000316 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000317 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000318 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000319 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000320 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000321 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000322 LLVMStyle.PointerBindsToType = false;
323 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000324 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000325 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000326 LLVMStyle.SpacesInParentheses = false;
327 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000328 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000329 LLVMStyle.SpacesInCStyleCastParentheses = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000330 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000331 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000332 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000333
Daniel Jasper19a541e2013-12-19 16:45:34 +0000334 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000335 LLVMStyle.PenaltyBreakFirstLessLess = 120;
336 LLVMStyle.PenaltyBreakString = 1000;
337 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000338 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000339 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000340
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000341 LLVMStyle.DisableFormat = false;
342
Daniel Jasperf7935112012-12-03 18:12:45 +0000343 return LLVMStyle;
344}
345
Nico Weber514ecc82014-02-02 20:50:45 +0000346FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000347 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000348 GoogleStyle.Language = Language;
349
Daniel Jasperf7935112012-12-03 18:12:45 +0000350 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000351 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000352 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000353 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000354 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000355 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000356 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
357 GoogleStyle.DerivePointerBinding = true;
358 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000359 GoogleStyle.IndentFunctionDeclarationAfterType = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000360 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000361 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000362 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000363 GoogleStyle.PointerBindsToType = true;
364 GoogleStyle.SpacesBeforeTrailingComments = 2;
365 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000366
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000367 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000368 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000369
Nico Weber514ecc82014-02-02 20:50:45 +0000370 if (Language == FormatStyle::LK_JavaScript) {
371 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000372 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000373 GoogleStyle.SpacesInContainerLiterals = false;
374 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000375 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000376 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000377 }
378
Daniel Jasperf7935112012-12-03 18:12:45 +0000379 return GoogleStyle;
380}
381
Nico Weber514ecc82014-02-02 20:50:45 +0000382FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
383 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Daniel Jasperf7db4332013-01-29 16:03:49 +0000384 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000385 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000386 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000387 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000388 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000389 ChromiumStyle.DerivePointerBinding = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000390 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000391 return ChromiumStyle;
392}
393
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000394FormatStyle getMozillaStyle() {
395 FormatStyle MozillaStyle = getLLVMStyle();
396 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000397 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000398 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
399 MozillaStyle.DerivePointerBinding = true;
400 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000401 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000402 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
403 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
404 MozillaStyle.PointerBindsToType = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000405 MozillaStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000406 return MozillaStyle;
407}
408
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000409FormatStyle getWebKitStyle() {
410 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000411 Style.AccessModifierOffset = -4;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000412 Style.AlignTrailingComments = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000413 Style.BreakBeforeBinaryOperators = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000414 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000415 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000416 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000417 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000418 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000419 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000420 Style.ObjCSpaceAfterProperty = true;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000421 Style.PointerBindsToType = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000422 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000423 return Style;
424}
425
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000426FormatStyle getGNUStyle() {
427 FormatStyle Style = getLLVMStyle();
428 Style.BreakBeforeBinaryOperators = true;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000429 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000430 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000431 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000432 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000433 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000434 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000435 return Style;
436}
437
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000438FormatStyle getNoStyle() {
439 FormatStyle NoStyle = getLLVMStyle();
440 NoStyle.DisableFormat = true;
441 return NoStyle;
442}
443
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000444bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
445 FormatStyle *Style) {
446 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000447 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000448 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000449 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000450 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000451 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000452 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000453 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000454 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000455 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000456 } else if (Name.equals_lower("gnu")) {
457 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000458 } else if (Name.equals_lower("none")) {
459 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000460 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000461 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000462 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000463
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000464 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000465 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000466}
467
468llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000469 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000470 FormatStyle::LanguageKind Language = Style->Language;
471 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000472 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000473 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000474
475 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000476 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000477 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
478 // values for the fields, keys for which are missing from the configuration.
479 // Mapping also uses the context to get the language to find the correct
480 // base style.
481 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000482 Input >> Styles;
483 if (Input.error())
484 return Input.error();
485
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000486 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000487 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000488 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000489 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000490 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000491 for (unsigned j = 0; j < i; ++j) {
492 if (Styles[i].Language == Styles[j].Language) {
493 DEBUG(llvm::dbgs()
494 << "Duplicate languages in the config file on positions " << j
495 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000496 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000497 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000498 }
499 }
500 // Look for a suitable configuration starting from the end, so we can
501 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000502 // configuration (which can only be at slot 0) after it.
503 for (int i = Styles.size() - 1; i >= 0; --i) {
504 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000505 Styles[i].Language == FormatStyle::LK_None) {
506 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000507 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000508 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000509 }
510 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000511 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000512}
513
514std::string configurationAsText(const FormatStyle &Style) {
515 std::string Text;
516 llvm::raw_string_ostream Stream(Text);
517 llvm::yaml::Output Output(Stream);
518 // We use the same mapping method for input and output, so we need a non-const
519 // reference here.
520 FormatStyle NonConstStyle = Style;
521 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000522 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000523}
524
Craig Topperaf35e852013-06-30 22:29:28 +0000525namespace {
526
Daniel Jasperde0328a2013-08-16 11:20:30 +0000527class NoColumnLimitFormatter {
528public:
Daniel Jasperf110e202013-08-21 08:39:01 +0000529 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000530
531 /// \brief Formats the line starting at \p State, simply keeping all of the
532 /// input's line breaking decisions.
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000533 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000534 LineState State =
535 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Craig Topper2145bc02014-05-09 08:15:10 +0000536 while (State.NextToken) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000537 bool Newline =
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000538 Indenter->mustBreak(State) ||
Daniel Jasperde0328a2013-08-16 11:20:30 +0000539 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
540 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
541 }
542 }
Daniel Jasperf110e202013-08-21 08:39:01 +0000543
Daniel Jasperde0328a2013-08-16 11:20:30 +0000544private:
545 ContinuationIndenter *Indenter;
546};
547
Daniel Jasper56f8b432013-11-06 23:12:09 +0000548class LineJoiner {
549public:
550 LineJoiner(const FormatStyle &Style) : Style(Style) {}
551
552 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
553 unsigned
554 tryFitMultipleLinesInOne(unsigned Indent,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000555 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000556 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
557 // We can never merge stuff if there are trailing line comments.
Daniel Jasper234379f2013-12-24 13:31:25 +0000558 const AnnotatedLine *TheLine = *I;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000559 if (TheLine->Last->Type == TT_LineComment)
560 return 0;
561
Alexander Kornienkoecc232d2013-12-04 13:25:26 +0000562 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
563 return 0;
564
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000565 unsigned Limit =
566 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000567 // If we already exceed the column limit, we set 'Limit' to 0. The different
568 // tryMerge..() functions can then decide whether to still do merging.
569 Limit = TheLine->Last->TotalLength > Limit
570 ? 0
571 : Limit - TheLine->Last->TotalLength;
572
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000573 if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000574 return 0;
575
Daniel Jasperd74cf402014-04-08 12:46:38 +0000576 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
577 // If necessary, change to something smarter.
578 bool MergeShortFunctions =
579 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
580 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
581 TheLine->Level != 0);
582
Daniel Jasper234379f2013-12-24 13:31:25 +0000583 if (TheLine->Last->Type == TT_FunctionLBrace &&
584 TheLine->First != TheLine->Last) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000585 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000586 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000587 if (TheLine->Last->is(tok::l_brace)) {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000588 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000589 ? tryMergeSimpleBlock(I, E, Limit)
590 : 0;
591 }
592 if (I[1]->First->Type == TT_FunctionLBrace &&
593 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
Alp Tokerba5b4dc2013-12-30 02:06:29 +0000594 // Check for Limit <= 2 to account for the " {".
Daniel Jasper234379f2013-12-24 13:31:25 +0000595 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
596 return 0;
597 Limit -= 2;
598
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000599 unsigned MergedLines = 0;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000600 if (MergeShortFunctions) {
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000601 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
602 // If we managed to merge the block, count the function header, which is
603 // on a separate line.
604 if (MergedLines > 0)
605 ++MergedLines;
606 }
607 return MergedLines;
608 }
609 if (TheLine->First->is(tok::kw_if)) {
610 return Style.AllowShortIfStatementsOnASingleLine
611 ? tryMergeSimpleControlStatement(I, E, Limit)
612 : 0;
613 }
614 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
615 return Style.AllowShortLoopsOnASingleLine
616 ? tryMergeSimpleControlStatement(I, E, Limit)
617 : 0;
618 }
619 if (TheLine->InPPDirective &&
620 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000621 return tryMergeSimplePPDirective(I, E, Limit);
622 }
623 return 0;
624 }
625
626private:
627 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000628 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000629 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
630 unsigned Limit) {
631 if (Limit == 0)
632 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000633 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000634 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000635 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000636 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000637 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000638 return 0;
639 return 1;
640 }
641
642 unsigned tryMergeSimpleControlStatement(
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000643 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000644 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
645 if (Limit == 0)
646 return 0;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000647 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
648 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
Daniel Jasper17605d32014-05-14 09:33:35 +0000649 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000650 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000651 if (I[1]->InPPDirective != (*I)->InPPDirective ||
652 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000653 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000654 Limit = limitConsideringMacros(I + 1, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000655 AnnotatedLine &Line = **I;
656 if (Line.Last->isNot(tok::r_paren))
657 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000658 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000659 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000660 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000661 tok::kw_while) ||
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000662 I[1]->First->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000663 return 0;
664 // Only inline simple if's (no nested if or else).
665 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000666 I[2]->First->is(tok::kw_else))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000667 return 0;
668 return 1;
669 }
670
671 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000672 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000673 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
674 unsigned Limit) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000675 AnnotatedLine &Line = **I;
Daniel Jasper17605d32014-05-14 09:33:35 +0000676
677 // Don't merge ObjC @ keywords and methods.
678 if (Line.First->isOneOf(tok::at, tok::minus, tok::plus))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000679 return 0;
680
Daniel Jasper17605d32014-05-14 09:33:35 +0000681 // Check that the current line allows merging. This depends on whether we
682 // are in a control flow statements as well as several style flags.
683 if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
684 return 0;
685 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
686 tok::kw_catch, tok::kw_for, tok::r_brace)) {
687 if (!Style.AllowShortBlocksOnASingleLine)
688 return 0;
689 if (!Style.AllowShortIfStatementsOnASingleLine &&
690 Line.First->is(tok::kw_if))
691 return 0;
692 if (!Style.AllowShortLoopsOnASingleLine &&
693 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
694 return 0;
695 // FIXME: Consider an option to allow short exception handling clauses on
696 // a single line.
697 if (Line.First->isOneOf(tok::kw_try, tok::kw_catch))
698 return 0;
699 }
700
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000701 FormatToken *Tok = I[1]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000702 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Craig Topper2145bc02014-05-09 08:15:10 +0000703 (Tok->getNextNonComment() == nullptr ||
Daniel Jasper56f8b432013-11-06 23:12:09 +0000704 Tok->getNextNonComment()->is(tok::semi))) {
705 // We merge empty blocks even if the line exceeds the column limit.
706 Tok->SpacesRequiredBefore = 0;
707 Tok->CanBreakBefore = true;
708 return 1;
709 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Daniel Jasper79dffb42014-05-07 09:48:30 +0000710 // We don't merge short records.
711 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
712 return 0;
713
Daniel Jasper56f8b432013-11-06 23:12:09 +0000714 // Check that we still have three lines and they fit into the limit.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000715 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000716 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000717 Limit = limitConsideringMacros(I + 2, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000718
719 if (!nextTwoLinesFitInto(I, Limit))
720 return 0;
721
722 // Second, check that the next line does not contain any braces - if it
723 // does, readability declines when putting it into a single line.
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000724 if (I[1]->Last->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000725 return 0;
726 do {
Daniel Jasperbd630732014-05-22 13:25:26 +0000727 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000728 return 0;
729 Tok = Tok->Next;
Craig Topper2145bc02014-05-09 08:15:10 +0000730 } while (Tok);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000731
Daniel Jasper79dffb42014-05-07 09:48:30 +0000732 // Last, check that the third line starts with a closing brace.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000733 Tok = I[2]->First;
Daniel Jasper79dffb42014-05-07 09:48:30 +0000734 if (Tok->isNot(tok::r_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000735 return 0;
736
737 return 2;
738 }
739 return 0;
740 }
741
Daniel Jasper64989962014-02-07 13:45:27 +0000742 /// Returns the modified column limit for \p I if it is inside a macro and
743 /// needs a trailing '\'.
744 unsigned
Daniel Jaspera0407742014-02-11 10:08:11 +0000745 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper64989962014-02-07 13:45:27 +0000746 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
747 unsigned Limit) {
748 if (I[0]->InPPDirective && I + 1 != E &&
749 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
750 return Limit < 2 ? 0 : Limit - 2;
751 }
752 return Limit;
753 }
754
Daniel Jasper56f8b432013-11-06 23:12:09 +0000755 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
756 unsigned Limit) {
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000757 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
758 return false;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000759 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000760 }
761
Daniel Jasper234379f2013-12-24 13:31:25 +0000762 bool containsMustBreak(const AnnotatedLine *Line) {
763 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
764 if (Tok->MustBreakBefore)
765 return true;
766 }
767 return false;
768 }
769
Daniel Jasper56f8b432013-11-06 23:12:09 +0000770 const FormatStyle &Style;
771};
772
Daniel Jasperf7935112012-12-03 18:12:45 +0000773class UnwrappedLineFormatter {
774public:
Daniel Jasper5500f612013-11-25 11:08:59 +0000775 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000776 WhitespaceManager *Whitespaces,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000777 const FormatStyle &Style)
Daniel Jasper5500f612013-11-25 11:08:59 +0000778 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
779 Joiner(Style) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000780
Daniel Jasper56f8b432013-11-06 23:12:09 +0000781 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper9c199562013-11-28 15:58:55 +0000782 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Daniel Jasperc359ad02014-04-15 08:13:47 +0000783 // Try to look up already computed penalty in DryRun-mode.
NAKAMURA Takumi22059522014-04-15 23:29:04 +0000784 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
785 &Lines, AdditionalIndent);
Daniel Jasperc359ad02014-04-15 08:13:47 +0000786 auto CacheIt = PenaltyCache.find(CacheKey);
787 if (DryRun && CacheIt != PenaltyCache.end())
788 return CacheIt->second;
789
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000790 assert(!Lines.empty());
791 unsigned Penalty = 0;
792 std::vector<int> IndentForLevel;
793 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
794 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Craig Topper2145bc02014-05-09 08:15:10 +0000795 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000796 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
797 E = Lines.end();
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000798 I != E; ++I) {
799 const AnnotatedLine &TheLine = **I;
800 const FormatToken *FirstTok = TheLine.First;
801 int Offset = getIndentOffset(*FirstTok);
802
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000803 // Determine indent and try to merge multiple unwrapped lines.
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000804 unsigned Indent;
805 if (TheLine.InPPDirective) {
806 Indent = TheLine.Level * Style.IndentWidth;
807 } else {
808 while (IndentForLevel.size() <= TheLine.Level)
809 IndentForLevel.push_back(-1);
810 IndentForLevel.resize(TheLine.Level + 1);
811 Indent = getIndent(IndentForLevel, TheLine.Level);
812 }
813 unsigned LevelIndent = Indent;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000814 if (static_cast<int>(Indent) + Offset >= 0)
815 Indent += Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000816
817 // Merge multiple lines if possible.
Daniel Jasper56f8b432013-11-06 23:12:09 +0000818 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
Alexander Kornienko31e95542013-12-04 12:21:08 +0000819 if (MergedLines > 0 && Style.ColumnLimit == 0) {
820 // Disallow line merging if there is a break at the start of one of the
821 // input lines.
822 for (unsigned i = 0; i < MergedLines; ++i) {
823 if (I[i + 1]->First->NewlinesBefore > 0)
824 MergedLines = 0;
825 }
826 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000827 if (!DryRun) {
828 for (unsigned i = 0; i < MergedLines; ++i) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000829 join(*I[i], *I[i + 1]);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000830 }
831 }
832 I += MergedLines;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000833
Daniel Jasper9c199562013-11-28 15:58:55 +0000834 bool FixIndentation =
835 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000836 if (TheLine.First->is(tok::eof)) {
Daniel Jasper5500f612013-11-25 11:08:59 +0000837 if (PreviousLine && PreviousLine->Affected && !DryRun) {
838 // Remove the file's trailing whitespace.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000839 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
840 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
841 /*IndentLevel=*/0, /*Spaces=*/0,
842 /*TargetColumn=*/0);
843 }
Daniel Jasper9c199562013-11-28 15:58:55 +0000844 } else if (TheLine.Type != LT_Invalid &&
845 (TheLine.Affected || FixIndentation)) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000846 if (FirstTok->WhitespaceRange.isValid()) {
847 if (!DryRun)
848 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
849 Indent, TheLine.InPPDirective);
850 } else {
851 Indent = LevelIndent = FirstTok->OriginalColumn;
852 }
853
854 // If everything fits on a single line, just put it there.
855 unsigned ColumnLimit = Style.ColumnLimit;
856 if (I + 1 != E) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000857 AnnotatedLine *NextLine = I[1];
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000858 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
859 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
860 }
861
862 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
863 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000864 while (State.NextToken) {
865 formatChildren(State, /*Newline=*/false, /*DryRun=*/false, Penalty);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000866 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000867 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000868 } else if (Style.ColumnLimit == 0) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000869 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000870 NoColumnLimitFormatter Formatter(Indenter);
871 if (!DryRun)
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000872 Formatter.format(Indent, &TheLine);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000873 } else {
874 Penalty += format(TheLine, Indent, DryRun);
875 }
876
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000877 if (!TheLine.InPPDirective)
878 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper9c199562013-11-28 15:58:55 +0000879 } else if (TheLine.ChildrenAffected) {
880 format(TheLine.Children, DryRun);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000881 } else {
882 // Format the first token if necessary, and notify the WhitespaceManager
883 // about the unchanged whitespace.
Craig Topper2145bc02014-05-09 08:15:10 +0000884 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000885 if (Tok == TheLine.First &&
886 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
887 unsigned LevelIndent = Tok->OriginalColumn;
888 if (!DryRun) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000889 // Remove trailing whitespace of the previous line.
Daniel Jasper5500f612013-11-25 11:08:59 +0000890 if ((PreviousLine && PreviousLine->Affected) ||
891 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000892 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
893 TheLine.InPPDirective);
894 } else {
895 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
896 }
897 }
898
899 if (static_cast<int>(LevelIndent) - Offset >= 0)
900 LevelIndent -= Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000901 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000902 IndentForLevel[TheLine.Level] = LevelIndent;
903 } else if (!DryRun) {
904 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
905 }
906 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000907 }
908 if (!DryRun) {
Craig Topper2145bc02014-05-09 08:15:10 +0000909 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000910 Tok->Finalized = true;
911 }
912 }
913 PreviousLine = *I;
914 }
Daniel Jasperc359ad02014-04-15 08:13:47 +0000915 PenaltyCache[CacheKey] = Penalty;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000916 return Penalty;
917 }
918
919private:
920 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000921 ///
922 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000923 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
924 bool DryRun) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000925 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +0000926
Daniel Jasperacc33662013-02-08 08:22:00 +0000927 // If the ObjC method declaration does not fit on a line, we should format
928 // it with one arg per line.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000929 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperacc33662013-02-08 08:22:00 +0000930 State.Stack.back().BreakBeforeParameter = true;
931
Daniel Jasper4b866272013-02-01 11:00:45 +0000932 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000933 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +0000934 }
935
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000936 /// \brief An edge in the solution space from \c Previous->State to \c State,
937 /// inserting a newline dependent on the \c NewLine.
938 struct StateNode {
939 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000940 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000941 LineState State;
942 bool NewLine;
943 StateNode *Previous;
944 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000945
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000946 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
947 ///
948 /// In case of equal penalties, we want to prefer states that were inserted
949 /// first. During state generation we make sure that we insert states first
950 /// that break the line as late as possible.
951 typedef std::pair<unsigned, unsigned> OrderedPenalty;
952
953 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
954 /// \c State has the given \c OrderedPenalty.
955 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
956
957 /// \brief The BFS queue type.
958 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
959 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000960
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000961 /// \brief Get the offset of the line relatively to the level.
962 ///
963 /// For example, 'public:' labels in classes are offset by 1 or 2
964 /// characters to the left from their level.
965 int getIndentOffset(const FormatToken &RootToken) {
966 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
967 return Style.AccessModifierOffset;
968 return 0;
969 }
970
971 /// \brief Add a new line and the required indent before the first Token
972 /// of the \c UnwrappedLine if there was no structural parsing error.
973 void formatFirstToken(FormatToken &RootToken,
974 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
975 unsigned Indent, bool InPPDirective) {
976 unsigned Newlines =
977 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
978 // Remove empty lines before "}" where applicable.
979 if (RootToken.is(tok::r_brace) &&
980 (!RootToken.Next ||
981 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
982 Newlines = std::min(Newlines, 1u);
983 if (Newlines == 0 && !RootToken.IsFirst)
984 Newlines = 1;
Manuel Klimek1fcbe672014-04-11 12:27:47 +0000985 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
986 Newlines = 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000987
Daniel Jasper11164bd2014-03-21 12:58:53 +0000988 // Remove empty lines after "{".
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000989 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
990 PreviousLine->Last->is(tok::l_brace) &&
Daniel Jasper01b35482014-03-21 13:03:33 +0000991 PreviousLine->First->isNot(tok::kw_namespace))
Daniel Jasper11164bd2014-03-21 12:58:53 +0000992 Newlines = 1;
993
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000994 // Insert extra new line before access specifiers.
995 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
996 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
997 ++Newlines;
998
999 // Remove empty lines after access specifiers.
1000 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
1001 Newlines = std::min(1u, Newlines);
1002
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001003 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
1004 Indent, InPPDirective &&
1005 !RootToken.HasUnescapedNewline);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001006 }
1007
1008 /// \brief Get the indent of \p Level from \p IndentForLevel.
1009 ///
1010 /// \p IndentForLevel must contain the indent for the level \c l
1011 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1012 /// that level is unknown.
1013 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
1014 if (IndentForLevel[Level] != -1)
1015 return IndentForLevel[Level];
1016 if (Level == 0)
1017 return 0;
1018 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
1019 }
1020
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001021 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1022 assert(!A.Last->Next);
1023 assert(!B.First->Previous);
Daniel Jasper5500f612013-11-25 11:08:59 +00001024 if (B.Affected)
1025 A.Affected = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001026 A.Last->Next = B.First;
1027 B.First->Previous = A.Last;
Daniel Jasper98fb6e12013-11-08 17:33:27 +00001028 B.First->CanBreakBefore = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001029 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1030 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1031 Tok->TotalLength += LengthA;
1032 A.Last = Tok;
1033 }
1034 }
1035
1036 unsigned getColumnLimit(bool InPPDirective) const {
1037 // In preprocessor directives reserve two chars for trailing " \"
1038 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1039 }
1040
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001041 struct CompareLineStatePointers {
1042 bool operator()(LineState *obj1, LineState *obj2) const {
1043 return *obj1 < *obj2;
1044 }
1045 };
1046
Daniel Jasper4b866272013-02-01 11:00:45 +00001047 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +00001048 ///
Daniel Jasper4b866272013-02-01 11:00:45 +00001049 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1050 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1051 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001052 /// to a state where all tokens are placed. Returns the penalty.
1053 ///
1054 /// If \p DryRun is \c false, directly applies the changes.
1055 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001056 std::set<LineState *, CompareLineStatePointers> Seen;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001057
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001058 // Increasing count of \c StateNode items we have created. This is used to
1059 // create a deterministic order independent of the container.
1060 unsigned Count = 0;
1061 QueueType Queue;
1062
Daniel Jasper4b866272013-02-01 11:00:45 +00001063 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001064 StateNode *Node =
Craig Topper2145bc02014-05-09 08:15:10 +00001065 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001066 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1067 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001068
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001069 unsigned Penalty = 0;
1070
Daniel Jasper4b866272013-02-01 11:00:45 +00001071 // While not empty, take first element and follow edges.
1072 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001073 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001074 StateNode *Node = Queue.top().second;
Craig Topper2145bc02014-05-09 08:15:10 +00001075 if (!Node->State.NextToken) {
Alexander Kornienko49149672013-05-10 11:56:10 +00001076 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001077 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001078 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001079 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001080
Daniel Jasperf8114cf2013-05-22 05:27:42 +00001081 // Cut off the analysis of certain solutions if the analysis gets too
1082 // complex. See description of IgnoreStackForComparison.
1083 if (Count > 10000)
1084 Node->State.IgnoreStackForComparison = true;
1085
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001086 if (!Seen.insert(&Node->State).second)
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001087 // State already examined with lower penalty.
1088 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001089
Manuel Klimek71814b42013-10-11 21:25:45 +00001090 FormatDecision LastFormat = Node->State.NextToken->Decision;
1091 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001092 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimek71814b42013-10-11 21:25:45 +00001093 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001094 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper4b866272013-02-01 11:00:45 +00001095 }
1096
Manuel Klimek71814b42013-10-11 21:25:45 +00001097 if (Queue.empty()) {
Daniel Jasper4b866272013-02-01 11:00:45 +00001098 // We were unable to find a solution, do nothing.
1099 // FIXME: Add diagnostic?
Manuel Klimek71814b42013-10-11 21:25:45 +00001100 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001101 return 0;
Manuel Klimek71814b42013-10-11 21:25:45 +00001102 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001103
Daniel Jasper4b866272013-02-01 11:00:45 +00001104 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001105 if (!DryRun)
1106 reconstructPath(InitialState, Queue.top().second);
1107
Alexander Kornienko49149672013-05-10 11:56:10 +00001108 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1109 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001110
1111 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001112 }
1113
1114 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001115 std::deque<StateNode *> Path;
1116 // We do not need a break before the initial token.
1117 while (Current->Previous) {
1118 Path.push_front(Current);
1119 Current = Current->Previous;
1120 }
1121 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1122 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001123 unsigned Penalty = 0;
1124 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1125 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1126
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001127 DEBUG({
1128 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001129 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001130 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001131 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001132 }
1133 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001134 }
Daniel Jasper4b866272013-02-01 11:00:45 +00001135 }
1136
Manuel Klimekaf491072013-02-13 10:54:19 +00001137 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001138 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001139 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001140 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001141 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001142 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001143 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001144 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001145 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001146 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001147
1148 StateNode *Node = new (Allocator.Allocate())
1149 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001150 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1151 return;
1152
Daniel Jasperde0328a2013-08-16 11:20:30 +00001153 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001154
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001155 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1156 ++(*Count);
Daniel Jasper4b866272013-02-01 11:00:45 +00001157 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001158
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001159 /// \brief If the \p State's next token is an r_brace closing a nested block,
1160 /// format the nested block before it.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001161 ///
1162 /// Returns \c true if all children could be placed successfully and adapts
1163 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1164 /// creates changes using \c Whitespaces.
1165 ///
1166 /// The crucial idea here is that children always get formatted upon
1167 /// encountering the closing brace right after the nested block. Now, if we
1168 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1169 /// \c false), the entire block has to be kept on the same line (which is only
1170 /// possible if it fits on the line, only contains a single statement, etc.
1171 ///
1172 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1173 /// break after the "{", format all lines with correct indentation and the put
1174 /// the closing "}" on yet another new line.
1175 ///
1176 /// This enables us to keep the simple structure of the
1177 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1178 /// break or don't break.
1179 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1180 unsigned &Penalty) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001181 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001182 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1183 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1184 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001185 // The previous token does not open a block. Nothing to do. We don't
1186 // assert so that we can simply call this function for all tokens.
Daniel Jasper36c28ce2013-09-06 08:54:24 +00001187 return true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001188
1189 if (NewLine) {
Daniel Jasper58cb2ed2014-06-06 13:49:04 +00001190 int AdditionalIndent =
1191 State.FirstIndent - State.Line->Level * Style.IndentWidth;
Daniel Jasperb16b9692014-05-21 12:51:23 +00001192 if (State.Stack.size() < 2 ||
1193 !State.Stack[State.Stack.size() - 2].JSFunctionInlined) {
1194 AdditionalIndent = State.Stack.back().Indent -
1195 Previous.Children[0]->Level * Style.IndentWidth;
1196 }
1197
Daniel Jasper9c199562013-11-28 15:58:55 +00001198 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1199 /*FixBadIndentation=*/true);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001200 return true;
1201 }
1202
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001203 // Cannot merge multiple statements into a single line.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001204 if (Previous.Children.size() > 1)
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001205 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001206
Daniel Jasper21397a32014-04-09 12:21:48 +00001207 // Cannot merge into one line if this line ends on a comment.
1208 if (Previous.is(tok::comment))
1209 return false;
1210
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001211 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001212 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001213 return false;
1214
Daniel Jasper98583d52014-04-15 08:28:06 +00001215 // If the child line exceeds the column limit, we wouldn't want to merge it.
1216 // We add +2 for the trailing " }".
1217 if (Style.ColumnLimit > 0 &&
1218 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
1219 Style.ColumnLimit)
1220 return false;
1221
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001222 if (!DryRun) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001223 Whitespaces->replaceWhitespace(
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001224 *Previous.Children[0]->First,
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001225 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001226 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001227 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001228 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001229
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001230 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001231 return true;
1232 }
1233
Daniel Jasperde0328a2013-08-16 11:20:30 +00001234 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001235 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001236 FormatStyle Style;
Daniel Jasper56f8b432013-11-06 23:12:09 +00001237 LineJoiner Joiner;
Manuel Klimekaf491072013-02-13 10:54:19 +00001238
1239 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperc359ad02014-04-15 08:13:47 +00001240
1241 // Cache to store the penalty of formatting a vector of AnnotatedLines
1242 // starting from a specific additional offset. Improves performance if there
1243 // are many nested blocks.
1244 std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
1245 unsigned> PenaltyCache;
Daniel Jasperf7935112012-12-03 18:12:45 +00001246};
1247
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001248class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001249public:
Manuel Klimek31c85922013-08-29 15:21:40 +00001250 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001251 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +00001252 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
1253 Column(0), TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr),
1254 Style(Style), IdentTable(getFormattingLangOpts()), Encoding(Encoding),
Manuel Klimek68b03042014-04-14 09:14:11 +00001255 FirstInLineIndex(0) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001256 Lex.SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +00001257
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001258 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +00001259 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1260 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001261 }
1262
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001263 ArrayRef<FormatToken *> lex() {
1264 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +00001265 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001266 do {
1267 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001268 tryMergePreviousTokens();
Manuel Klimek68b03042014-04-14 09:14:11 +00001269 if (Tokens.back()->NewlinesBefore > 0)
1270 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001271 } while (Tokens.back()->Tok.isNot(tok::eof));
1272 return Tokens;
1273 }
1274
1275 IdentifierTable &getIdentTable() { return IdentTable; }
1276
1277private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001278 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001279 if (tryMerge_TMacro())
1280 return;
Manuel Klimek68b03042014-04-14 09:14:11 +00001281 if (tryMergeConflictMarkers())
1282 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001283
1284 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001285 if (tryMergeEscapeSequence())
1286 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001287 if (tryMergeJSRegexLiteral())
1288 return;
1289
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001290 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1291 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1292 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1293 tok::greaterequal };
Daniel Jasper78214392014-05-19 07:27:02 +00001294 static tok::TokenKind JSRightArrow[] = { tok::equal, tok::greater };
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001295 // FIXME: We probably need to change token type to mimic operator with the
1296 // correct priority.
1297 if (tryMergeTokens(JSIdentity))
1298 return;
1299 if (tryMergeTokens(JSNotIdentity))
1300 return;
1301 if (tryMergeTokens(JSShiftEqual))
1302 return;
Daniel Jasper78214392014-05-19 07:27:02 +00001303 if (tryMergeTokens(JSRightArrow))
1304 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001305 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001306 }
1307
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001308 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1309 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001310 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001311
1312 SmallVectorImpl<FormatToken *>::const_iterator First =
1313 Tokens.end() - Kinds.size();
1314 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001315 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001316 unsigned AddLength = 0;
1317 for (unsigned i = 1; i < Kinds.size(); ++i) {
1318 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1319 First[i]->WhitespaceRange.getEnd())
1320 return false;
1321 AddLength += First[i]->TokenText.size();
1322 }
1323 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1324 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1325 First[0]->TokenText.size() + AddLength);
1326 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001327 return true;
1328 }
1329
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001330 // Tries to merge an escape sequence, i.e. a "\\" and the following
Alp Tokerc3f36af2014-05-15 01:35:53 +00001331 // character. Use e.g. inside JavaScript regex literals.
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001332 bool tryMergeEscapeSequence() {
1333 if (Tokens.size() < 2)
1334 return false;
1335 FormatToken *Previous = Tokens[Tokens.size() - 2];
1336 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\" ||
1337 Tokens.back()->NewlinesBefore != 0)
1338 return false;
1339 Previous->ColumnWidth += Tokens.back()->ColumnWidth;
1340 StringRef Text = Previous->TokenText;
1341 Previous->TokenText =
1342 StringRef(Text.data(), Text.size() + Tokens.back()->TokenText.size());
1343 Tokens.resize(Tokens.size() - 1);
1344 return true;
1345 }
1346
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001347 // Try to determine whether the current token ends a JavaScript regex literal.
1348 // We heuristically assume that this is a regex literal if we find two
1349 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +00001350 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
1351 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001352 bool tryMergeJSRegexLiteral() {
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001353 if (Tokens.size() < 2 || Tokens.back()->isNot(tok::slash) ||
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001354 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
1355 Tokens[Tokens.size() - 2]->TokenText == "\\"))
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001356 return false;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001357 unsigned TokenCount = 0;
1358 unsigned LastColumn = Tokens.back()->OriginalColumn;
1359 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
1360 ++TokenCount;
1361 if (I[0]->is(tok::slash) && I + 1 != E &&
1362 (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
1363 tok::exclaim, tok::l_square, tok::colon, tok::comma,
1364 tok::question, tok::kw_return) ||
1365 I[1]->isBinaryOperator())) {
1366 Tokens.resize(Tokens.size() - TokenCount);
1367 Tokens.back()->Tok.setKind(tok::unknown);
1368 Tokens.back()->Type = TT_RegexLiteral;
1369 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
1370 return true;
1371 }
1372
1373 // There can't be a newline inside a regex literal.
1374 if (I[0]->NewlinesBefore > 0)
1375 return false;
1376 }
1377 return false;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001378 }
1379
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001380 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001381 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001382 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001383 FormatToken *Last = Tokens.back();
1384 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001385 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001386
1387 FormatToken *String = Tokens[Tokens.size() - 2];
1388 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001389 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001390
1391 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001392 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001393
1394 FormatToken *Macro = Tokens[Tokens.size() - 4];
1395 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001396 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001397
1398 const char *Start = Macro->TokenText.data();
1399 const char *End = Last->TokenText.data() + Last->TokenText.size();
1400 String->TokenText = StringRef(Start, End - Start);
1401 String->IsFirst = Macro->IsFirst;
1402 String->LastNewlineOffset = Macro->LastNewlineOffset;
1403 String->WhitespaceRange = Macro->WhitespaceRange;
1404 String->OriginalColumn = Macro->OriginalColumn;
1405 String->ColumnWidth = encoding::columnWidthWithTabs(
1406 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1407
1408 Tokens.pop_back();
1409 Tokens.pop_back();
1410 Tokens.pop_back();
1411 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001412 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001413 }
1414
Manuel Klimek68b03042014-04-14 09:14:11 +00001415 bool tryMergeConflictMarkers() {
1416 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1417 return false;
1418
1419 // Conflict lines look like:
1420 // <marker> <text from the vcs>
1421 // For example:
1422 // >>>>>>> /file/in/file/system at revision 1234
1423 //
1424 // We merge all tokens in a line that starts with a conflict marker
1425 // into a single token with a special token type that the unwrapped line
1426 // parser will use to correctly rebuild the underlying code.
1427
1428 FileID ID;
1429 // Get the position of the first token in the line.
1430 unsigned FirstInLineOffset;
1431 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1432 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1433 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1434 // Calculate the offset of the start of the current line.
1435 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1436 if (LineOffset == StringRef::npos) {
1437 LineOffset = 0;
1438 } else {
1439 ++LineOffset;
1440 }
1441
1442 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1443 StringRef LineStart;
1444 if (FirstSpace == StringRef::npos) {
1445 LineStart = Buffer.substr(LineOffset);
1446 } else {
1447 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1448 }
1449
1450 TokenType Type = TT_Unknown;
1451 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1452 Type = TT_ConflictStart;
1453 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1454 LineStart == "====") {
1455 Type = TT_ConflictAlternative;
1456 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1457 Type = TT_ConflictEnd;
1458 }
1459
1460 if (Type != TT_Unknown) {
1461 FormatToken *Next = Tokens.back();
1462
1463 Tokens.resize(FirstInLineIndex + 1);
1464 // We do not need to build a complete token here, as we will skip it
1465 // during parsing anyway (as we must not touch whitespace around conflict
1466 // markers).
1467 Tokens.back()->Type = Type;
1468 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1469
1470 Tokens.push_back(Next);
1471 return true;
1472 }
1473
1474 return false;
1475 }
1476
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001477 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001478 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001479 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +00001480 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001481 Token Greater = FormatTok->Tok;
1482 FormatTok = new (Allocator.Allocate()) FormatToken;
1483 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001484 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001485 FormatTok->Tok.getLocation().getLocWithOffset(1);
1486 FormatTok->WhitespaceRange =
1487 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001488 FormatTok->TokenText = ">";
Alexander Kornienko39856b72013-09-10 09:38:25 +00001489 FormatTok->ColumnWidth = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001490 GreaterStashed = false;
1491 return FormatTok;
1492 }
1493
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001494 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001495 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001496 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001497 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001498 FormatTok->IsFirst = IsFirstToken;
1499 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001500
1501 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001502 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001503 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001504 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1505 switch (FormatTok->TokenText[i]) {
1506 case '\n':
1507 ++FormatTok->NewlinesBefore;
1508 // FIXME: This is technically incorrect, as it could also
1509 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001510 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1511 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1512 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +00001513 FormatTok->HasUnescapedNewline = true;
1514 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1515 Column = 0;
1516 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001517 case '\r':
1518 case '\f':
1519 case '\v':
1520 Column = 0;
1521 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001522 case ' ':
1523 ++Column;
1524 break;
1525 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001526 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001527 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001528 case '\\':
1529 ++Column;
1530 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1531 FormatTok->TokenText[i + 1] != '\n'))
1532 FormatTok->Type = TT_ImplicitStringLiteral;
1533 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001534 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001535 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001536 ++Column;
1537 break;
1538 }
1539 }
1540
Daniel Jasper877615c2013-10-11 19:45:02 +00001541 if (FormatTok->Type == TT_ImplicitStringLiteral)
1542 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001543 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001544
Daniel Jasper8369aa52013-07-16 20:28:33 +00001545 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001546 }
Manuel Klimekef920692013-01-07 07:56:50 +00001547
Manuel Klimek1abf7892013-01-04 23:34:14 +00001548 // In case the token starts with escaped newlines, we want to
1549 // take them into account as whitespace - this pattern is quite frequent
1550 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001551 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001552 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1553 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001554 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001555 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001556 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001557 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001558 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001559
1560 FormatTok->WhitespaceRange = SourceRange(
1561 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1562
Manuel Klimek31c85922013-08-29 15:21:40 +00001563 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001564
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001565 TrailingWhitespace = 0;
1566 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001567 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001568 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001569 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001570 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001571 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001572 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001573 FormatTok->Tok.setIdentifierInfo(&Info);
1574 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001575 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001576 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001577 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001578 GreaterStashed = true;
1579 }
1580
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001581 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001582
Alexander Kornienko39856b72013-09-10 09:38:25 +00001583 StringRef Text = FormatTok->TokenText;
1584 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001585 if (FirstNewlinePos == StringRef::npos) {
1586 // FIXME: ColumnWidth actually depends on the start column, we need to
1587 // take this into account when the token is moved.
1588 FormatTok->ColumnWidth =
1589 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1590 Column += FormatTok->ColumnWidth;
1591 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001592 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001593 // FIXME: ColumnWidth actually depends on the start column, we need to
1594 // take this into account when the token is moved.
1595 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1596 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1597
Alexander Kornienko39856b72013-09-10 09:38:25 +00001598 // The last line of the token always starts in column 0.
1599 // Thus, the length can be precomputed even in the presence of tabs.
1600 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1601 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1602 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001603 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001604 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001605
Daniel Jaspere1e43192014-04-01 12:55:11 +00001606 FormatTok->IsForEachMacro =
1607 std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1608 FormatTok->Tok.getIdentifierInfo());
1609
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001610 return FormatTok;
1611 }
1612
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001613 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001614 bool IsFirstToken;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001615 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001616 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001617 unsigned TrailingWhitespace;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001618 Lexer &Lex;
1619 SourceManager &SourceMgr;
Manuel Klimek31c85922013-08-29 15:21:40 +00001620 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001621 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001622 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001623 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001624 // Index (in 'Tokens') of the last token that starts a new line.
1625 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001626 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001627 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001628
Daniel Jasper8369aa52013-07-16 20:28:33 +00001629 void readRawToken(FormatToken &Tok) {
1630 Lex.LexFromRawLexer(Tok.Tok);
1631 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1632 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001633 // For formatting, treat unterminated string literals like normal string
1634 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001635 if (Tok.is(tok::unknown)) {
1636 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1637 Tok.Tok.setKind(tok::string_literal);
1638 Tok.IsUnterminatedLiteral = true;
1639 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1640 Tok.TokenText == "''") {
1641 Tok.Tok.setKind(tok::char_constant);
1642 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001643 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001644 }
1645};
1646
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001647static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1648 switch (Language) {
1649 case FormatStyle::LK_Cpp:
1650 return "C++";
1651 case FormatStyle::LK_JavaScript:
1652 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001653 case FormatStyle::LK_Proto:
1654 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001655 default:
1656 return "Unknown";
1657 }
1658}
1659
Daniel Jasperf7935112012-12-03 18:12:45 +00001660class Formatter : public UnwrappedLineConsumer {
1661public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001662 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001663 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001664 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001665 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001666 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Manuel Klimek71814b42013-10-11 21:25:45 +00001667 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001668 DEBUG(llvm::dbgs() << "File encoding: "
1669 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1670 : "unknown")
1671 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001672 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1673 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001674 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001675
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001676 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001677 tooling::Replacements Result;
Manuel Klimek31c85922013-08-29 15:21:40 +00001678 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001679
1680 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001681 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001682 assert(UnwrappedLines.rbegin()->empty());
1683 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1684 ++Run) {
1685 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1686 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1687 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1688 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1689 }
1690 tooling::Replacements RunResult =
1691 format(AnnotatedLines, StructuralError, Tokens);
1692 DEBUG({
1693 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1694 for (tooling::Replacements::iterator I = RunResult.begin(),
1695 E = RunResult.end();
1696 I != E; ++I) {
1697 llvm::dbgs() << I->toString() << "\n";
1698 }
1699 });
1700 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1701 delete AnnotatedLines[i];
1702 }
1703 Result.insert(RunResult.begin(), RunResult.end());
1704 Whitespaces.reset();
1705 }
1706 return Result;
1707 }
1708
1709 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1710 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001711 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001712 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001713 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001714 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001715 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001716 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001717 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001718 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001719 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001720
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001721 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001722 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1723 BinPackInconclusiveFunctions);
Daniel Jasper5500f612013-11-25 11:08:59 +00001724 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001725 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001726 return Whitespaces.generateReplacements();
1727 }
1728
1729private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001730 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001731 // Returns \c true if at least one line between I and E or one of their
1732 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001733 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1734 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1735 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001736 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001737 while (I != E) {
1738 AnnotatedLine *Line = *I;
1739 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1740
1741 // If a line is part of a preprocessor directive, it needs to be formatted
1742 // if any token within the directive is affected.
1743 if (Line->InPPDirective) {
1744 FormatToken *Last = Line->Last;
1745 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1746 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1747 Last = (*PPEnd)->Last;
1748 ++PPEnd;
1749 }
1750
1751 if (affectsTokenRange(*Line->First, *Last,
1752 /*IncludeLeadingNewlines=*/false)) {
1753 SomeLineAffected = true;
1754 markAllAsAffected(I, PPEnd);
1755 }
1756 I = PPEnd;
1757 continue;
1758 }
1759
Daniel Jasper38c82402013-11-29 09:27:43 +00001760 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001761 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001762
Daniel Jasper38c82402013-11-29 09:27:43 +00001763 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001764 ++I;
1765 }
1766 return SomeLineAffected;
1767 }
1768
Daniel Jasper9c199562013-11-28 15:58:55 +00001769 // Determines whether 'Line' is affected by the SourceRanges given as input.
1770 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001771 bool nonPPLineAffected(AnnotatedLine *Line,
1772 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001773 bool SomeLineAffected = false;
1774 Line->ChildrenAffected =
1775 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1776 if (Line->ChildrenAffected)
1777 SomeLineAffected = true;
1778
1779 // Stores whether one of the line's tokens is directly affected.
1780 bool SomeTokenAffected = false;
1781 // Stores whether we need to look at the leading newlines of the next token
1782 // in order to determine whether it was affected.
1783 bool IncludeLeadingNewlines = false;
1784
1785 // Stores whether the first child line of any of this line's tokens is
1786 // affected.
1787 bool SomeFirstChildAffected = false;
1788
1789 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1790 // Determine whether 'Tok' was affected.
1791 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1792 SomeTokenAffected = true;
1793
1794 // Determine whether the first child of 'Tok' was affected.
1795 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1796 SomeFirstChildAffected = true;
1797
1798 IncludeLeadingNewlines = Tok->Children.empty();
1799 }
1800
1801 // Was this line moved, i.e. has it previously been on the same line as an
1802 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001803 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1804 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001805
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001806 bool IsContinuedComment =
1807 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1808 Line->First->NewlinesBefore < 2 && PreviousLine &&
1809 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001810
1811 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1812 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001813 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001814 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001815 }
1816 return SomeLineAffected;
1817 }
1818
Daniel Jasper5500f612013-11-25 11:08:59 +00001819 // Marks all lines between I and E as well as all their children as affected.
1820 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1821 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1822 while (I != E) {
1823 (*I)->Affected = true;
1824 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1825 ++I;
1826 }
1827 }
1828
1829 // Returns true if the range from 'First' to 'Last' intersects with one of the
1830 // input ranges.
1831 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1832 bool IncludeLeadingNewlines) {
1833 SourceLocation Start = First.WhitespaceRange.getBegin();
1834 if (!IncludeLeadingNewlines)
1835 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001836 SourceLocation End = Last.getStartOfNonWhitespace();
1837 if (Last.TokenText.size() > 0)
1838 End = End.getLocWithOffset(Last.TokenText.size() - 1);
Daniel Jasper5500f612013-11-25 11:08:59 +00001839 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1840 return affectsCharSourceRange(Range);
1841 }
1842
1843 // Returns true if one of the input ranges intersect the leading empty lines
1844 // before 'Tok'.
1845 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1846 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1847 Tok.WhitespaceRange.getBegin(),
1848 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1849 return affectsCharSourceRange(EmptyLineRange);
1850 }
1851
1852 // Returns true if 'Range' intersects with one of the input ranges.
1853 bool affectsCharSourceRange(const CharSourceRange &Range) {
1854 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1855 E = Ranges.end();
1856 I != E; ++I) {
1857 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1858 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1859 return true;
1860 }
1861 return false;
1862 }
1863
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001864 static bool inputUsesCRLF(StringRef Text) {
1865 return Text.count('\r') * 2 > Text.count('\n');
1866 }
1867
Manuel Klimek71814b42013-10-11 21:25:45 +00001868 void
1869 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001870 unsigned CountBoundToVariable = 0;
1871 unsigned CountBoundToType = 0;
1872 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001873 bool HasBinPackedFunction = false;
1874 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001875 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001876 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001877 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001878 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001879 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001880 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001881 bool SpacesBefore =
1882 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1883 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1884 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001885 if (SpacesBefore && !SpacesAfter)
1886 ++CountBoundToVariable;
1887 else if (!SpacesBefore && SpacesAfter)
1888 ++CountBoundToType;
1889 }
1890
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001891 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1892 if (Tok->is(tok::coloncolon) &&
1893 Tok->Previous->Type == TT_TemplateOpener)
1894 HasCpp03IncompatibleFormat = true;
1895 if (Tok->Type == TT_TemplateCloser &&
1896 Tok->Previous->Type == TT_TemplateCloser)
1897 HasCpp03IncompatibleFormat = true;
1898 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001899
1900 if (Tok->PackingKind == PPK_BinPacked)
1901 HasBinPackedFunction = true;
1902 if (Tok->PackingKind == PPK_OnePerLine)
1903 HasOnePerLineFunction = true;
1904
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001905 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001906 }
1907 }
1908 if (Style.DerivePointerBinding) {
1909 if (CountBoundToType > CountBoundToVariable)
1910 Style.PointerBindsToType = true;
1911 else if (CountBoundToType < CountBoundToVariable)
1912 Style.PointerBindsToType = false;
1913 }
1914 if (Style.Standard == FormatStyle::LS_Auto) {
1915 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1916 : FormatStyle::LS_Cpp03;
1917 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001918 BinPackInconclusiveFunctions =
1919 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001920 }
1921
Craig Topperfb6b25b2014-03-15 04:29:04 +00001922 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001923 assert(!UnwrappedLines.empty());
1924 UnwrappedLines.back().push_back(TheLine);
1925 }
1926
Craig Topperfb6b25b2014-03-15 04:29:04 +00001927 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001928 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001929 }
1930
1931 FormatStyle Style;
1932 Lexer &Lex;
1933 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001934 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001935 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001936 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001937
1938 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001939 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001940};
1941
Craig Topperaf35e852013-06-30 22:29:28 +00001942} // end anonymous namespace
1943
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001944tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1945 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001946 std::vector<CharSourceRange> Ranges) {
Daniel Jasperc64b09a2014-05-22 15:12:22 +00001947 if (Style.DisableFormat) {
1948 tooling::Replacements EmptyResult;
1949 return EmptyResult;
1950 }
1951
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001952 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001953 return formatter.format();
1954}
1955
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001956tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1957 std::vector<tooling::Range> Ranges,
1958 StringRef FileName) {
1959 FileManager Files((FileSystemOptions()));
1960 DiagnosticsEngine Diagnostics(
1961 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1962 new DiagnosticOptions);
1963 SourceManager SourceMgr(Diagnostics, Files);
1964 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1965 const clang::FileEntry *Entry =
1966 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1967 SourceMgr.overrideFileContents(Entry, Buf);
1968 FileID ID =
1969 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienko1e808872013-06-28 12:51:24 +00001970 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1971 getFormattingLangOpts(Style.Standard));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001972 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1973 std::vector<CharSourceRange> CharRanges;
1974 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1975 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1976 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1977 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1978 }
1979 return reformat(Style, Lex, SourceMgr, CharRanges);
1980}
1981
Alexander Kornienko1e808872013-06-28 12:51:24 +00001982LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001983 LangOptions LangOpts;
1984 LangOpts.CPlusPlus = 1;
Alexander Kornienko1e808872013-06-28 12:51:24 +00001985 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper20fd3c62014-04-15 08:49:21 +00001986 LangOpts.CPlusPlus1y = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001987 LangOpts.LineComment = 1;
Nikola Smiljanice08a91e2014-05-08 00:05:13 +00001988 LangOpts.CXXOperatorNames = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001989 LangOpts.Bool = 1;
1990 LangOpts.ObjC1 = 1;
1991 LangOpts.ObjC2 = 1;
1992 return LangOpts;
1993}
1994
Edwin Vaned544aa72013-09-30 13:31:48 +00001995const char *StyleOptionHelpDescription =
1996 "Coding style, currently supports:\n"
1997 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1998 "Use -style=file to load style configuration from\n"
1999 ".clang-format file located in one of the parent\n"
2000 "directories of the source file (or current\n"
2001 "directory for stdin).\n"
2002 "Use -style=\"{key: value, ...}\" to set specific\n"
2003 "parameters, e.g.:\n"
2004 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
2005
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002006static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002007 if (FileName.endswith_lower(".js")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002008 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00002009 } else if (FileName.endswith_lower(".proto") ||
2010 FileName.endswith_lower(".protodevel")) {
2011 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002012 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002013 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002014}
2015
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002016FormatStyle getStyle(StringRef StyleName, StringRef FileName,
2017 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002018 FormatStyle Style = getLLVMStyle();
2019 Style.Language = getLanguageByFileName(FileName);
2020 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002021 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
2022 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002023 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002024 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002025
2026 if (StyleName.startswith("{")) {
2027 // Parse YAML/JSON style from the command line.
2028 if (llvm::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002029 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
2030 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00002031 }
2032 return Style;
2033 }
2034
2035 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002036 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00002037 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
2038 << " style\n";
2039 return Style;
2040 }
2041
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002042 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002043 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00002044 SmallString<128> Path(FileName);
2045 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002046 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00002047 Directory = llvm::sys::path::parent_path(Directory)) {
2048 if (!llvm::sys::fs::is_directory(Directory))
2049 continue;
2050 SmallString<128> ConfigFile(Directory);
2051
2052 llvm::sys::path::append(ConfigFile, ".clang-format");
2053 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2054 bool IsFile = false;
2055 // Ignore errors from is_regular_file: we only need to know if we can read
2056 // the file or not.
2057 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2058
2059 if (!IsFile) {
2060 // Try _clang-format too, since dotfiles are not commonly used on Windows.
2061 ConfigFile = Directory;
2062 llvm::sys::path::append(ConfigFile, "_clang-format");
2063 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2064 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2065 }
2066
2067 if (IsFile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +00002068 std::unique_ptr<llvm::MemoryBuffer> Text;
Rafael Espindola1a3605c2013-10-25 19:00:49 +00002069 if (llvm::error_code ec =
2070 llvm::MemoryBuffer::getFile(ConfigFile.c_str(), Text)) {
Edwin Vaned544aa72013-09-30 13:31:48 +00002071 llvm::errs() << ec.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002072 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002073 }
2074 if (llvm::error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00002075 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002076 if (!UnsuitableConfigFiles.empty())
2077 UnsuitableConfigFiles.append(", ");
2078 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002079 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002080 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002081 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2082 << "\n";
2083 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002084 }
2085 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2086 return Style;
2087 }
2088 }
2089 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
2090 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002091 if (!UnsuitableConfigFiles.empty()) {
2092 llvm::errs() << "Configuration file(s) do(es) not support "
2093 << getLanguageName(Style.Language) << ": "
2094 << UnsuitableConfigFiles << "\n";
2095 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002096 return Style;
2097}
2098
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002099} // namespace format
2100} // namespace clang