blob: 60706b1b3bef6e1cb8084f6d07c075c96f97760e [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);
154 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
155 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000156 IO.mapOptional("AllowShortLoopsOnASingleLine",
157 Style.AllowShortLoopsOnASingleLine);
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000158 IO.mapOptional("AllowShortFunctionsOnASingleLine",
159 Style.AllowShortFunctionsOnASingleLine);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000160 IO.mapOptional("AlwaysBreakTemplateDeclarations",
161 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko58611712013-07-04 12:02:44 +0000162 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
163 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000164 IO.mapOptional("BreakBeforeBinaryOperators",
165 Style.BreakBeforeBinaryOperators);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000166 IO.mapOptional("BreakBeforeTernaryOperators",
167 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000168 IO.mapOptional("BreakConstructorInitializersBeforeComma",
169 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000170 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
171 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
172 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
173 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
174 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000175 IO.mapOptional("ExperimentalAutoDetectBinPacking",
176 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000177 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
178 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000179 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
180 Style.KeepEmptyLinesAtTheStartOfBlocks);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000181 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000182 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000183 IO.mapOptional("ObjCSpaceBeforeProtocolList",
184 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000185 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
186 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000187 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
188 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000189 IO.mapOptional("PenaltyBreakFirstLessLess",
190 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000191 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
192 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
193 Style.PenaltyReturnTypeOnItsOwnLine);
194 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
195 IO.mapOptional("SpacesBeforeTrailingComments",
196 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000197 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000198 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000199 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000200 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000201 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000202 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimek836c2862013-06-21 17:25:42 +0000203 IO.mapOptional("IndentFunctionDeclarationAfterType",
204 Style.IndentFunctionDeclarationAfterType);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000205 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000206 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasperf110e202013-08-21 08:39:01 +0000207 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000208 IO.mapOptional("SpacesInCStyleCastParentheses",
209 Style.SpacesInCStyleCastParentheses);
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000210 IO.mapOptional("SpacesInContainerLiterals",
211 Style.SpacesInContainerLiterals);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000212 IO.mapOptional("SpaceBeforeAssignmentOperators",
213 Style.SpaceBeforeAssignmentOperators);
Daniel Jasper6633ab82013-10-18 10:38:14 +0000214 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000215 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000216 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000217
218 // For backward compatibility.
219 if (!IO.outputting()) {
220 IO.mapOptional("SpaceAfterControlStatementKeyword",
221 Style.SpaceBeforeParens);
222 }
223 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000224 }
225};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000226
227// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000228// IO.getContext() should contain a pointer to the FormatStyle structure, that
229// will be used to get default values for missing keys.
230// If the first element has no Language specified, it will be treated as the
231// default one for the following elements.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000232template <> struct DocumentListTraits<std::vector<FormatStyle> > {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000233 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
234 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000235 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000236 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000237 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000238 if (Index >= Seq.size()) {
239 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000240 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000241 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000242 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000243 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000244 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000245 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000246 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000247 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000248 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000249 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000250 }
251};
Alexander Kornienkod6538332013-05-07 15:32:14 +0000252}
253}
254
Daniel Jasperf7935112012-12-03 18:12:45 +0000255namespace clang {
256namespace format {
257
Daniel Jasperf7935112012-12-03 18:12:45 +0000258FormatStyle getLLVMStyle() {
259 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000260 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000261 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000262 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000263 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000264 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000265 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000266 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000267 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000268 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000269 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000270 LLVMStyle.BinPackParameters = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000271 LLVMStyle.BreakBeforeBinaryOperators = false;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000272 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000273 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
274 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000275 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000276 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000277 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000278 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000279 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000280 LLVMStyle.Cpp11BracedListStyle = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000281 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000282 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000283 LLVMStyle.ForEachMacros.push_back("foreach");
284 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
285 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000286 LLVMStyle.IndentCaseLabels = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000287 LLVMStyle.IndentFunctionDeclarationAfterType = false;
288 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000289 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000290 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000291 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000292 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000293 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000294 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000295 LLVMStyle.PointerBindsToType = false;
296 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000297 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000298 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000299 LLVMStyle.SpacesInParentheses = false;
300 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000301 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000302 LLVMStyle.SpacesInCStyleCastParentheses = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000303 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000304 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000305 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000306
Daniel Jasper19a541e2013-12-19 16:45:34 +0000307 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000308 LLVMStyle.PenaltyBreakFirstLessLess = 120;
309 LLVMStyle.PenaltyBreakString = 1000;
310 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000311 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000312 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000313
Daniel Jasperf7935112012-12-03 18:12:45 +0000314 return LLVMStyle;
315}
316
Nico Weber514ecc82014-02-02 20:50:45 +0000317FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000318 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000319 GoogleStyle.Language = Language;
320
Daniel Jasperf7935112012-12-03 18:12:45 +0000321 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000322 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000323 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000324 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000325 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000326 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000327 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
328 GoogleStyle.DerivePointerBinding = true;
329 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000330 GoogleStyle.IndentFunctionDeclarationAfterType = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000331 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000332 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000333 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000334 GoogleStyle.PointerBindsToType = true;
335 GoogleStyle.SpacesBeforeTrailingComments = 2;
336 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000337
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000338 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000339 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000340
Nico Weber514ecc82014-02-02 20:50:45 +0000341 if (Language == FormatStyle::LK_JavaScript) {
342 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000343 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000344 GoogleStyle.SpacesInContainerLiterals = false;
345 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000346 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000347 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000348 }
349
Daniel Jasperf7935112012-12-03 18:12:45 +0000350 return GoogleStyle;
351}
352
Nico Weber514ecc82014-02-02 20:50:45 +0000353FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
354 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Daniel Jasperf7db4332013-01-29 16:03:49 +0000355 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000356 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000357 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000358 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000359 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000360 ChromiumStyle.DerivePointerBinding = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000361 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000362 return ChromiumStyle;
363}
364
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000365FormatStyle getMozillaStyle() {
366 FormatStyle MozillaStyle = getLLVMStyle();
367 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000368 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000369 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
370 MozillaStyle.DerivePointerBinding = true;
371 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000372 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000373 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
374 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
375 MozillaStyle.PointerBindsToType = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000376 MozillaStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000377 return MozillaStyle;
378}
379
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000380FormatStyle getWebKitStyle() {
381 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000382 Style.AccessModifierOffset = -4;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000383 Style.AlignTrailingComments = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000384 Style.BreakBeforeBinaryOperators = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000385 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000386 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000387 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000388 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000389 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000390 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000391 Style.ObjCSpaceAfterProperty = true;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000392 Style.PointerBindsToType = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000393 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000394 return Style;
395}
396
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000397FormatStyle getGNUStyle() {
398 FormatStyle Style = getLLVMStyle();
399 Style.BreakBeforeBinaryOperators = true;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000400 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000401 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000402 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000403 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000404 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000405 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000406 return Style;
407}
408
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000409bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
410 FormatStyle *Style) {
411 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000412 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000413 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000414 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000415 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000416 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000417 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000418 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000419 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000420 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000421 } else if (Name.equals_lower("gnu")) {
422 *Style = getGNUStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000423 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000424 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000425 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000426
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000427 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000428 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000429}
430
431llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000432 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000433 FormatStyle::LanguageKind Language = Style->Language;
434 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000435 if (Text.trim().empty())
436 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000437
438 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000439 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000440 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
441 // values for the fields, keys for which are missing from the configuration.
442 // Mapping also uses the context to get the language to find the correct
443 // base style.
444 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000445 Input >> Styles;
446 if (Input.error())
447 return Input.error();
448
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000449 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000450 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000451 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000452 return llvm::make_error_code(llvm::errc::invalid_argument);
453 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000454 for (unsigned j = 0; j < i; ++j) {
455 if (Styles[i].Language == Styles[j].Language) {
456 DEBUG(llvm::dbgs()
457 << "Duplicate languages in the config file on positions " << j
458 << " and " << i << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000459 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000460 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000461 }
462 }
463 // Look for a suitable configuration starting from the end, so we can
464 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000465 // configuration (which can only be at slot 0) after it.
466 for (int i = Styles.size() - 1; i >= 0; --i) {
467 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000468 Styles[i].Language == FormatStyle::LK_None) {
469 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000470 Style->Language = Language;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000471 return llvm::make_error_code(llvm::errc::success);
472 }
473 }
474 return llvm::make_error_code(llvm::errc::not_supported);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000475}
476
477std::string configurationAsText(const FormatStyle &Style) {
478 std::string Text;
479 llvm::raw_string_ostream Stream(Text);
480 llvm::yaml::Output Output(Stream);
481 // We use the same mapping method for input and output, so we need a non-const
482 // reference here.
483 FormatStyle NonConstStyle = Style;
484 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000485 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000486}
487
Craig Topperaf35e852013-06-30 22:29:28 +0000488namespace {
489
Daniel Jasperde0328a2013-08-16 11:20:30 +0000490class NoColumnLimitFormatter {
491public:
Daniel Jasperf110e202013-08-21 08:39:01 +0000492 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000493
494 /// \brief Formats the line starting at \p State, simply keeping all of the
495 /// input's line breaking decisions.
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000496 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000497 LineState State =
498 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Craig Topper2145bc02014-05-09 08:15:10 +0000499 while (State.NextToken) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000500 bool Newline =
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000501 Indenter->mustBreak(State) ||
Daniel Jasperde0328a2013-08-16 11:20:30 +0000502 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
503 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
504 }
505 }
Daniel Jasperf110e202013-08-21 08:39:01 +0000506
Daniel Jasperde0328a2013-08-16 11:20:30 +0000507private:
508 ContinuationIndenter *Indenter;
509};
510
Daniel Jasper56f8b432013-11-06 23:12:09 +0000511class LineJoiner {
512public:
513 LineJoiner(const FormatStyle &Style) : Style(Style) {}
514
515 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
516 unsigned
517 tryFitMultipleLinesInOne(unsigned Indent,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000518 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000519 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
520 // We can never merge stuff if there are trailing line comments.
Daniel Jasper234379f2013-12-24 13:31:25 +0000521 const AnnotatedLine *TheLine = *I;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000522 if (TheLine->Last->Type == TT_LineComment)
523 return 0;
524
Alexander Kornienkoecc232d2013-12-04 13:25:26 +0000525 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
526 return 0;
527
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000528 unsigned Limit =
529 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000530 // If we already exceed the column limit, we set 'Limit' to 0. The different
531 // tryMerge..() functions can then decide whether to still do merging.
532 Limit = TheLine->Last->TotalLength > Limit
533 ? 0
534 : Limit - TheLine->Last->TotalLength;
535
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000536 if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000537 return 0;
538
Daniel Jasperd74cf402014-04-08 12:46:38 +0000539 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
540 // If necessary, change to something smarter.
541 bool MergeShortFunctions =
542 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
543 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
544 TheLine->Level != 0);
545
Daniel Jasper234379f2013-12-24 13:31:25 +0000546 if (TheLine->Last->Type == TT_FunctionLBrace &&
547 TheLine->First != TheLine->Last) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000548 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000549 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000550 if (TheLine->Last->is(tok::l_brace)) {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000551 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000552 ? tryMergeSimpleBlock(I, E, Limit)
553 : 0;
554 }
555 if (I[1]->First->Type == TT_FunctionLBrace &&
556 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
Alp Tokerba5b4dc2013-12-30 02:06:29 +0000557 // Check for Limit <= 2 to account for the " {".
Daniel Jasper234379f2013-12-24 13:31:25 +0000558 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
559 return 0;
560 Limit -= 2;
561
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000562 unsigned MergedLines = 0;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000563 if (MergeShortFunctions) {
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000564 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
565 // If we managed to merge the block, count the function header, which is
566 // on a separate line.
567 if (MergedLines > 0)
568 ++MergedLines;
569 }
570 return MergedLines;
571 }
572 if (TheLine->First->is(tok::kw_if)) {
573 return Style.AllowShortIfStatementsOnASingleLine
574 ? tryMergeSimpleControlStatement(I, E, Limit)
575 : 0;
576 }
577 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
578 return Style.AllowShortLoopsOnASingleLine
579 ? tryMergeSimpleControlStatement(I, E, Limit)
580 : 0;
581 }
582 if (TheLine->InPPDirective &&
583 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000584 return tryMergeSimplePPDirective(I, E, Limit);
585 }
586 return 0;
587 }
588
589private:
590 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000591 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000592 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
593 unsigned Limit) {
594 if (Limit == 0)
595 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000596 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000597 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000598 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000599 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000600 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000601 return 0;
602 return 1;
603 }
604
605 unsigned tryMergeSimpleControlStatement(
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000606 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000607 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
608 if (Limit == 0)
609 return 0;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000610 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
611 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000612 I[1]->First->is(tok::l_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000613 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000614 if (I[1]->InPPDirective != (*I)->InPPDirective ||
615 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000616 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000617 Limit = limitConsideringMacros(I + 1, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000618 AnnotatedLine &Line = **I;
619 if (Line.Last->isNot(tok::r_paren))
620 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000621 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000622 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000623 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000624 tok::kw_while) ||
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000625 I[1]->First->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000626 return 0;
627 // Only inline simple if's (no nested if or else).
628 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000629 I[2]->First->is(tok::kw_else))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000630 return 0;
631 return 1;
632 }
633
634 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000635 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000636 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
637 unsigned Limit) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000638 // First, check that the current line allows merging. This is the case if
639 // we're not in a control flow statement and the last token is an opening
640 // brace.
641 AnnotatedLine &Line = **I;
642 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
643 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jasper922349c2014-04-04 06:46:23 +0000644 tok::kw_for, tok::kw_case,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000645 // This gets rid of all ObjC @ keywords and methods.
646 tok::at, tok::minus, tok::plus))
647 return 0;
648
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000649 FormatToken *Tok = I[1]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000650 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Craig Topper2145bc02014-05-09 08:15:10 +0000651 (Tok->getNextNonComment() == nullptr ||
Daniel Jasper56f8b432013-11-06 23:12:09 +0000652 Tok->getNextNonComment()->is(tok::semi))) {
653 // We merge empty blocks even if the line exceeds the column limit.
654 Tok->SpacesRequiredBefore = 0;
655 Tok->CanBreakBefore = true;
656 return 1;
657 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Daniel Jasper79dffb42014-05-07 09:48:30 +0000658 // We don't merge short records.
659 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
660 return 0;
661
Daniel Jasper56f8b432013-11-06 23:12:09 +0000662 // Check that we still have three lines and they fit into the limit.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000663 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000664 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000665 Limit = limitConsideringMacros(I + 2, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000666
667 if (!nextTwoLinesFitInto(I, Limit))
668 return 0;
669
670 // Second, check that the next line does not contain any braces - if it
671 // does, readability declines when putting it into a single line.
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000672 if (I[1]->Last->Type == TT_LineComment)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000673 return 0;
674 do {
675 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
676 return 0;
677 Tok = Tok->Next;
Craig Topper2145bc02014-05-09 08:15:10 +0000678 } while (Tok);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000679
Daniel Jasper79dffb42014-05-07 09:48:30 +0000680 // Last, check that the third line starts with a closing brace.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000681 Tok = I[2]->First;
Daniel Jasper79dffb42014-05-07 09:48:30 +0000682 if (Tok->isNot(tok::r_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000683 return 0;
684
685 return 2;
686 }
687 return 0;
688 }
689
Daniel Jasper64989962014-02-07 13:45:27 +0000690 /// Returns the modified column limit for \p I if it is inside a macro and
691 /// needs a trailing '\'.
692 unsigned
Daniel Jaspera0407742014-02-11 10:08:11 +0000693 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper64989962014-02-07 13:45:27 +0000694 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
695 unsigned Limit) {
696 if (I[0]->InPPDirective && I + 1 != E &&
697 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
698 return Limit < 2 ? 0 : Limit - 2;
699 }
700 return Limit;
701 }
702
Daniel Jasper56f8b432013-11-06 23:12:09 +0000703 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
704 unsigned Limit) {
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000705 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
706 return false;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000707 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000708 }
709
Daniel Jasper234379f2013-12-24 13:31:25 +0000710 bool containsMustBreak(const AnnotatedLine *Line) {
711 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
712 if (Tok->MustBreakBefore)
713 return true;
714 }
715 return false;
716 }
717
Daniel Jasper56f8b432013-11-06 23:12:09 +0000718 const FormatStyle &Style;
719};
720
Daniel Jasperf7935112012-12-03 18:12:45 +0000721class UnwrappedLineFormatter {
722public:
Daniel Jasper5500f612013-11-25 11:08:59 +0000723 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000724 WhitespaceManager *Whitespaces,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000725 const FormatStyle &Style)
Daniel Jasper5500f612013-11-25 11:08:59 +0000726 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
727 Joiner(Style) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000728
Daniel Jasper56f8b432013-11-06 23:12:09 +0000729 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper9c199562013-11-28 15:58:55 +0000730 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Daniel Jasperc359ad02014-04-15 08:13:47 +0000731 // Try to look up already computed penalty in DryRun-mode.
NAKAMURA Takumi22059522014-04-15 23:29:04 +0000732 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
733 &Lines, AdditionalIndent);
Daniel Jasperc359ad02014-04-15 08:13:47 +0000734 auto CacheIt = PenaltyCache.find(CacheKey);
735 if (DryRun && CacheIt != PenaltyCache.end())
736 return CacheIt->second;
737
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000738 assert(!Lines.empty());
739 unsigned Penalty = 0;
740 std::vector<int> IndentForLevel;
741 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
742 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Craig Topper2145bc02014-05-09 08:15:10 +0000743 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000744 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
745 E = Lines.end();
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000746 I != E; ++I) {
747 const AnnotatedLine &TheLine = **I;
748 const FormatToken *FirstTok = TheLine.First;
749 int Offset = getIndentOffset(*FirstTok);
750
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000751 // Determine indent and try to merge multiple unwrapped lines.
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000752 unsigned Indent;
753 if (TheLine.InPPDirective) {
754 Indent = TheLine.Level * Style.IndentWidth;
755 } else {
756 while (IndentForLevel.size() <= TheLine.Level)
757 IndentForLevel.push_back(-1);
758 IndentForLevel.resize(TheLine.Level + 1);
759 Indent = getIndent(IndentForLevel, TheLine.Level);
760 }
761 unsigned LevelIndent = Indent;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000762 if (static_cast<int>(Indent) + Offset >= 0)
763 Indent += Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000764
765 // Merge multiple lines if possible.
Daniel Jasper56f8b432013-11-06 23:12:09 +0000766 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
Alexander Kornienko31e95542013-12-04 12:21:08 +0000767 if (MergedLines > 0 && Style.ColumnLimit == 0) {
768 // Disallow line merging if there is a break at the start of one of the
769 // input lines.
770 for (unsigned i = 0; i < MergedLines; ++i) {
771 if (I[i + 1]->First->NewlinesBefore > 0)
772 MergedLines = 0;
773 }
774 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000775 if (!DryRun) {
776 for (unsigned i = 0; i < MergedLines; ++i) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000777 join(*I[i], *I[i + 1]);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000778 }
779 }
780 I += MergedLines;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000781
Daniel Jasper9c199562013-11-28 15:58:55 +0000782 bool FixIndentation =
783 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000784 if (TheLine.First->is(tok::eof)) {
Daniel Jasper5500f612013-11-25 11:08:59 +0000785 if (PreviousLine && PreviousLine->Affected && !DryRun) {
786 // Remove the file's trailing whitespace.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000787 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
788 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
789 /*IndentLevel=*/0, /*Spaces=*/0,
790 /*TargetColumn=*/0);
791 }
Daniel Jasper9c199562013-11-28 15:58:55 +0000792 } else if (TheLine.Type != LT_Invalid &&
793 (TheLine.Affected || FixIndentation)) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000794 if (FirstTok->WhitespaceRange.isValid()) {
795 if (!DryRun)
796 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
797 Indent, TheLine.InPPDirective);
798 } else {
799 Indent = LevelIndent = FirstTok->OriginalColumn;
800 }
801
802 // If everything fits on a single line, just put it there.
803 unsigned ColumnLimit = Style.ColumnLimit;
804 if (I + 1 != E) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000805 AnnotatedLine *NextLine = I[1];
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000806 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
807 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
808 }
809
810 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
811 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
Craig Topper2145bc02014-05-09 08:15:10 +0000812 while (State.NextToken)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000813 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
814 } else if (Style.ColumnLimit == 0) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000815 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000816 NoColumnLimitFormatter Formatter(Indenter);
817 if (!DryRun)
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000818 Formatter.format(Indent, &TheLine);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000819 } else {
820 Penalty += format(TheLine, Indent, DryRun);
821 }
822
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000823 if (!TheLine.InPPDirective)
824 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper9c199562013-11-28 15:58:55 +0000825 } else if (TheLine.ChildrenAffected) {
826 format(TheLine.Children, DryRun);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000827 } else {
828 // Format the first token if necessary, and notify the WhitespaceManager
829 // about the unchanged whitespace.
Craig Topper2145bc02014-05-09 08:15:10 +0000830 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000831 if (Tok == TheLine.First &&
832 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
833 unsigned LevelIndent = Tok->OriginalColumn;
834 if (!DryRun) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000835 // Remove trailing whitespace of the previous line.
Daniel Jasper5500f612013-11-25 11:08:59 +0000836 if ((PreviousLine && PreviousLine->Affected) ||
837 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000838 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
839 TheLine.InPPDirective);
840 } else {
841 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
842 }
843 }
844
845 if (static_cast<int>(LevelIndent) - Offset >= 0)
846 LevelIndent -= Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000847 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000848 IndentForLevel[TheLine.Level] = LevelIndent;
849 } else if (!DryRun) {
850 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
851 }
852 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000853 }
854 if (!DryRun) {
Craig Topper2145bc02014-05-09 08:15:10 +0000855 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000856 Tok->Finalized = true;
857 }
858 }
859 PreviousLine = *I;
860 }
Daniel Jasperc359ad02014-04-15 08:13:47 +0000861 PenaltyCache[CacheKey] = Penalty;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000862 return Penalty;
863 }
864
865private:
866 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000867 ///
868 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000869 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
870 bool DryRun) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000871 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +0000872
Daniel Jasperacc33662013-02-08 08:22:00 +0000873 // If the ObjC method declaration does not fit on a line, we should format
874 // it with one arg per line.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000875 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperacc33662013-02-08 08:22:00 +0000876 State.Stack.back().BreakBeforeParameter = true;
877
Daniel Jasper4b866272013-02-01 11:00:45 +0000878 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000879 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +0000880 }
881
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000882 /// \brief An edge in the solution space from \c Previous->State to \c State,
883 /// inserting a newline dependent on the \c NewLine.
884 struct StateNode {
885 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000886 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000887 LineState State;
888 bool NewLine;
889 StateNode *Previous;
890 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000891
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000892 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
893 ///
894 /// In case of equal penalties, we want to prefer states that were inserted
895 /// first. During state generation we make sure that we insert states first
896 /// that break the line as late as possible.
897 typedef std::pair<unsigned, unsigned> OrderedPenalty;
898
899 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
900 /// \c State has the given \c OrderedPenalty.
901 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
902
903 /// \brief The BFS queue type.
904 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
905 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000906
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000907 /// \brief Get the offset of the line relatively to the level.
908 ///
909 /// For example, 'public:' labels in classes are offset by 1 or 2
910 /// characters to the left from their level.
911 int getIndentOffset(const FormatToken &RootToken) {
912 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
913 return Style.AccessModifierOffset;
914 return 0;
915 }
916
917 /// \brief Add a new line and the required indent before the first Token
918 /// of the \c UnwrappedLine if there was no structural parsing error.
919 void formatFirstToken(FormatToken &RootToken,
920 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
921 unsigned Indent, bool InPPDirective) {
922 unsigned Newlines =
923 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
924 // Remove empty lines before "}" where applicable.
925 if (RootToken.is(tok::r_brace) &&
926 (!RootToken.Next ||
927 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
928 Newlines = std::min(Newlines, 1u);
929 if (Newlines == 0 && !RootToken.IsFirst)
930 Newlines = 1;
Manuel Klimek1fcbe672014-04-11 12:27:47 +0000931 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
932 Newlines = 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000933
Daniel Jasper11164bd2014-03-21 12:58:53 +0000934 // Remove empty lines after "{".
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000935 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
936 PreviousLine->Last->is(tok::l_brace) &&
Daniel Jasper01b35482014-03-21 13:03:33 +0000937 PreviousLine->First->isNot(tok::kw_namespace))
Daniel Jasper11164bd2014-03-21 12:58:53 +0000938 Newlines = 1;
939
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000940 // Insert extra new line before access specifiers.
941 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
942 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
943 ++Newlines;
944
945 // Remove empty lines after access specifiers.
946 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
947 Newlines = std::min(1u, Newlines);
948
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000949 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
950 Indent, InPPDirective &&
951 !RootToken.HasUnescapedNewline);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000952 }
953
954 /// \brief Get the indent of \p Level from \p IndentForLevel.
955 ///
956 /// \p IndentForLevel must contain the indent for the level \c l
957 /// at \p IndentForLevel[l], or a value < 0 if the indent for
958 /// that level is unknown.
959 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
960 if (IndentForLevel[Level] != -1)
961 return IndentForLevel[Level];
962 if (Level == 0)
963 return 0;
964 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
965 }
966
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000967 void join(AnnotatedLine &A, const AnnotatedLine &B) {
968 assert(!A.Last->Next);
969 assert(!B.First->Previous);
Daniel Jasper5500f612013-11-25 11:08:59 +0000970 if (B.Affected)
971 A.Affected = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000972 A.Last->Next = B.First;
973 B.First->Previous = A.Last;
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000974 B.First->CanBreakBefore = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000975 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
976 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
977 Tok->TotalLength += LengthA;
978 A.Last = Tok;
979 }
980 }
981
982 unsigned getColumnLimit(bool InPPDirective) const {
983 // In preprocessor directives reserve two chars for trailing " \"
984 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
985 }
986
Daniel Jasper4b866272013-02-01 11:00:45 +0000987 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000988 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000989 /// This implements a variant of Dijkstra's algorithm on the graph that spans
990 /// the solution space (\c LineStates are the nodes). The algorithm tries to
991 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000992 /// to a state where all tokens are placed. Returns the penalty.
993 ///
994 /// If \p DryRun is \c false, directly applies the changes.
995 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000996 std::set<LineState> Seen;
997
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000998 // Increasing count of \c StateNode items we have created. This is used to
999 // create a deterministic order independent of the container.
1000 unsigned Count = 0;
1001 QueueType Queue;
1002
Daniel Jasper4b866272013-02-01 11:00:45 +00001003 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001004 StateNode *Node =
Craig Topper2145bc02014-05-09 08:15:10 +00001005 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001006 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1007 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001008
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001009 unsigned Penalty = 0;
1010
Daniel Jasper4b866272013-02-01 11:00:45 +00001011 // While not empty, take first element and follow edges.
1012 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001013 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001014 StateNode *Node = Queue.top().second;
Craig Topper2145bc02014-05-09 08:15:10 +00001015 if (!Node->State.NextToken) {
Alexander Kornienko49149672013-05-10 11:56:10 +00001016 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001017 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001018 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001019 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001020
Daniel Jasperf8114cf2013-05-22 05:27:42 +00001021 // Cut off the analysis of certain solutions if the analysis gets too
1022 // complex. See description of IgnoreStackForComparison.
1023 if (Count > 10000)
1024 Node->State.IgnoreStackForComparison = true;
1025
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001026 if (!Seen.insert(Node->State).second)
1027 // State already examined with lower penalty.
1028 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001029
Manuel Klimek71814b42013-10-11 21:25:45 +00001030 FormatDecision LastFormat = Node->State.NextToken->Decision;
1031 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001032 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimek71814b42013-10-11 21:25:45 +00001033 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001034 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper4b866272013-02-01 11:00:45 +00001035 }
1036
Manuel Klimek71814b42013-10-11 21:25:45 +00001037 if (Queue.empty()) {
Daniel Jasper4b866272013-02-01 11:00:45 +00001038 // We were unable to find a solution, do nothing.
1039 // FIXME: Add diagnostic?
Manuel Klimek71814b42013-10-11 21:25:45 +00001040 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001041 return 0;
Manuel Klimek71814b42013-10-11 21:25:45 +00001042 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001043
Daniel Jasper4b866272013-02-01 11:00:45 +00001044 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001045 if (!DryRun)
1046 reconstructPath(InitialState, Queue.top().second);
1047
Alexander Kornienko49149672013-05-10 11:56:10 +00001048 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1049 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001050
1051 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001052 }
1053
1054 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001055 std::deque<StateNode *> Path;
1056 // We do not need a break before the initial token.
1057 while (Current->Previous) {
1058 Path.push_front(Current);
1059 Current = Current->Previous;
1060 }
1061 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1062 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001063 unsigned Penalty = 0;
1064 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1065 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1066
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001067 DEBUG({
1068 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001069 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001070 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001071 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001072 }
1073 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001074 }
Daniel Jasper4b866272013-02-01 11:00:45 +00001075 }
1076
Manuel Klimekaf491072013-02-13 10:54:19 +00001077 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001078 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001079 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001080 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001081 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001082 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001083 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001084 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001085 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001086 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001087
1088 StateNode *Node = new (Allocator.Allocate())
1089 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001090 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1091 return;
1092
Daniel Jasperde0328a2013-08-16 11:20:30 +00001093 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001094
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001095 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1096 ++(*Count);
Daniel Jasper4b866272013-02-01 11:00:45 +00001097 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001098
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001099 /// \brief If the \p State's next token is an r_brace closing a nested block,
1100 /// format the nested block before it.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001101 ///
1102 /// Returns \c true if all children could be placed successfully and adapts
1103 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1104 /// creates changes using \c Whitespaces.
1105 ///
1106 /// The crucial idea here is that children always get formatted upon
1107 /// encountering the closing brace right after the nested block. Now, if we
1108 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1109 /// \c false), the entire block has to be kept on the same line (which is only
1110 /// possible if it fits on the line, only contains a single statement, etc.
1111 ///
1112 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1113 /// break after the "{", format all lines with correct indentation and the put
1114 /// the closing "}" on yet another new line.
1115 ///
1116 /// This enables us to keep the simple structure of the
1117 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1118 /// break or don't break.
1119 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1120 unsigned &Penalty) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001121 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001122 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1123 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1124 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001125 // The previous token does not open a block. Nothing to do. We don't
1126 // assert so that we can simply call this function for all tokens.
Daniel Jasper36c28ce2013-09-06 08:54:24 +00001127 return true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001128
1129 if (NewLine) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001130 int AdditionalIndent = State.Stack.back().Indent -
1131 Previous.Children[0]->Level * Style.IndentWidth;
Daniel Jasper9c199562013-11-28 15:58:55 +00001132 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1133 /*FixBadIndentation=*/true);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001134 return true;
1135 }
1136
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001137 // Cannot merge multiple statements into a single line.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001138 if (Previous.Children.size() > 1)
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001139 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001140
Daniel Jasper21397a32014-04-09 12:21:48 +00001141 // Cannot merge into one line if this line ends on a comment.
1142 if (Previous.is(tok::comment))
1143 return false;
1144
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001145 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001146 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001147 return false;
1148
Daniel Jasper98583d52014-04-15 08:28:06 +00001149 // If the child line exceeds the column limit, we wouldn't want to merge it.
1150 // We add +2 for the trailing " }".
1151 if (Style.ColumnLimit > 0 &&
1152 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
1153 Style.ColumnLimit)
1154 return false;
1155
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001156 if (!DryRun) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001157 Whitespaces->replaceWhitespace(
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001158 *Previous.Children[0]->First,
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001159 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001160 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001161 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001162 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001163
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001164 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001165 return true;
1166 }
1167
Daniel Jasperde0328a2013-08-16 11:20:30 +00001168 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001169 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001170 FormatStyle Style;
Daniel Jasper56f8b432013-11-06 23:12:09 +00001171 LineJoiner Joiner;
Manuel Klimekaf491072013-02-13 10:54:19 +00001172
1173 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperc359ad02014-04-15 08:13:47 +00001174
1175 // Cache to store the penalty of formatting a vector of AnnotatedLines
1176 // starting from a specific additional offset. Improves performance if there
1177 // are many nested blocks.
1178 std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
1179 unsigned> PenaltyCache;
Daniel Jasperf7935112012-12-03 18:12:45 +00001180};
1181
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001182class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001183public:
Manuel Klimek31c85922013-08-29 15:21:40 +00001184 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001185 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +00001186 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
1187 Column(0), TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr),
1188 Style(Style), IdentTable(getFormattingLangOpts()), Encoding(Encoding),
Manuel Klimek68b03042014-04-14 09:14:11 +00001189 FirstInLineIndex(0) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001190 Lex.SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +00001191
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001192 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +00001193 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1194 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001195 }
1196
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001197 ArrayRef<FormatToken *> lex() {
1198 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +00001199 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001200 do {
1201 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001202 tryMergePreviousTokens();
Manuel Klimek68b03042014-04-14 09:14:11 +00001203 if (Tokens.back()->NewlinesBefore > 0)
1204 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001205 } while (Tokens.back()->Tok.isNot(tok::eof));
1206 return Tokens;
1207 }
1208
1209 IdentifierTable &getIdentTable() { return IdentTable; }
1210
1211private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001212 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001213 if (tryMerge_TMacro())
1214 return;
Manuel Klimek68b03042014-04-14 09:14:11 +00001215 if (tryMergeConflictMarkers())
1216 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001217
1218 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001219 if (tryMergeEscapeSequence())
1220 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001221 if (tryMergeJSRegexLiteral())
1222 return;
1223
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001224 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1225 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1226 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1227 tok::greaterequal };
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001228 // FIXME: We probably need to change token type to mimic operator with the
1229 // correct priority.
1230 if (tryMergeTokens(JSIdentity))
1231 return;
1232 if (tryMergeTokens(JSNotIdentity))
1233 return;
1234 if (tryMergeTokens(JSShiftEqual))
1235 return;
1236 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001237 }
1238
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001239 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1240 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001241 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001242
1243 SmallVectorImpl<FormatToken *>::const_iterator First =
1244 Tokens.end() - Kinds.size();
1245 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001246 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001247 unsigned AddLength = 0;
1248 for (unsigned i = 1; i < Kinds.size(); ++i) {
1249 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1250 First[i]->WhitespaceRange.getEnd())
1251 return false;
1252 AddLength += First[i]->TokenText.size();
1253 }
1254 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1255 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1256 First[0]->TokenText.size() + AddLength);
1257 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001258 return true;
1259 }
1260
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001261 // Tries to merge an escape sequence, i.e. a "\\" and the following
1262 // charachter. Use e.g. inside JavaScript regex literals.
1263 bool tryMergeEscapeSequence() {
1264 if (Tokens.size() < 2)
1265 return false;
1266 FormatToken *Previous = Tokens[Tokens.size() - 2];
1267 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\" ||
1268 Tokens.back()->NewlinesBefore != 0)
1269 return false;
1270 Previous->ColumnWidth += Tokens.back()->ColumnWidth;
1271 StringRef Text = Previous->TokenText;
1272 Previous->TokenText =
1273 StringRef(Text.data(), Text.size() + Tokens.back()->TokenText.size());
1274 Tokens.resize(Tokens.size() - 1);
1275 return true;
1276 }
1277
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001278 // Try to determine whether the current token ends a JavaScript regex literal.
1279 // We heuristically assume that this is a regex literal if we find two
1280 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +00001281 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
1282 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001283 bool tryMergeJSRegexLiteral() {
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001284 if (Tokens.size() < 2 || Tokens.back()->isNot(tok::slash) ||
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001285 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
1286 Tokens[Tokens.size() - 2]->TokenText == "\\"))
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001287 return false;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001288 unsigned TokenCount = 0;
1289 unsigned LastColumn = Tokens.back()->OriginalColumn;
1290 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
1291 ++TokenCount;
1292 if (I[0]->is(tok::slash) && I + 1 != E &&
1293 (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
1294 tok::exclaim, tok::l_square, tok::colon, tok::comma,
1295 tok::question, tok::kw_return) ||
1296 I[1]->isBinaryOperator())) {
1297 Tokens.resize(Tokens.size() - TokenCount);
1298 Tokens.back()->Tok.setKind(tok::unknown);
1299 Tokens.back()->Type = TT_RegexLiteral;
1300 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
1301 return true;
1302 }
1303
1304 // There can't be a newline inside a regex literal.
1305 if (I[0]->NewlinesBefore > 0)
1306 return false;
1307 }
1308 return false;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001309 }
1310
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001311 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001312 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001313 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001314 FormatToken *Last = Tokens.back();
1315 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001316 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001317
1318 FormatToken *String = Tokens[Tokens.size() - 2];
1319 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001320 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001321
1322 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001323 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001324
1325 FormatToken *Macro = Tokens[Tokens.size() - 4];
1326 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001327 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001328
1329 const char *Start = Macro->TokenText.data();
1330 const char *End = Last->TokenText.data() + Last->TokenText.size();
1331 String->TokenText = StringRef(Start, End - Start);
1332 String->IsFirst = Macro->IsFirst;
1333 String->LastNewlineOffset = Macro->LastNewlineOffset;
1334 String->WhitespaceRange = Macro->WhitespaceRange;
1335 String->OriginalColumn = Macro->OriginalColumn;
1336 String->ColumnWidth = encoding::columnWidthWithTabs(
1337 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1338
1339 Tokens.pop_back();
1340 Tokens.pop_back();
1341 Tokens.pop_back();
1342 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001343 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001344 }
1345
Manuel Klimek68b03042014-04-14 09:14:11 +00001346 bool tryMergeConflictMarkers() {
1347 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1348 return false;
1349
1350 // Conflict lines look like:
1351 // <marker> <text from the vcs>
1352 // For example:
1353 // >>>>>>> /file/in/file/system at revision 1234
1354 //
1355 // We merge all tokens in a line that starts with a conflict marker
1356 // into a single token with a special token type that the unwrapped line
1357 // parser will use to correctly rebuild the underlying code.
1358
1359 FileID ID;
1360 // Get the position of the first token in the line.
1361 unsigned FirstInLineOffset;
1362 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1363 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1364 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1365 // Calculate the offset of the start of the current line.
1366 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1367 if (LineOffset == StringRef::npos) {
1368 LineOffset = 0;
1369 } else {
1370 ++LineOffset;
1371 }
1372
1373 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1374 StringRef LineStart;
1375 if (FirstSpace == StringRef::npos) {
1376 LineStart = Buffer.substr(LineOffset);
1377 } else {
1378 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1379 }
1380
1381 TokenType Type = TT_Unknown;
1382 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1383 Type = TT_ConflictStart;
1384 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1385 LineStart == "====") {
1386 Type = TT_ConflictAlternative;
1387 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1388 Type = TT_ConflictEnd;
1389 }
1390
1391 if (Type != TT_Unknown) {
1392 FormatToken *Next = Tokens.back();
1393
1394 Tokens.resize(FirstInLineIndex + 1);
1395 // We do not need to build a complete token here, as we will skip it
1396 // during parsing anyway (as we must not touch whitespace around conflict
1397 // markers).
1398 Tokens.back()->Type = Type;
1399 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1400
1401 Tokens.push_back(Next);
1402 return true;
1403 }
1404
1405 return false;
1406 }
1407
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001408 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001409 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001410 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +00001411 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001412 Token Greater = FormatTok->Tok;
1413 FormatTok = new (Allocator.Allocate()) FormatToken;
1414 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001415 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001416 FormatTok->Tok.getLocation().getLocWithOffset(1);
1417 FormatTok->WhitespaceRange =
1418 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001419 FormatTok->TokenText = ">";
Alexander Kornienko39856b72013-09-10 09:38:25 +00001420 FormatTok->ColumnWidth = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001421 GreaterStashed = false;
1422 return FormatTok;
1423 }
1424
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001425 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001426 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001427 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001428 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001429 FormatTok->IsFirst = IsFirstToken;
1430 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001431
1432 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001433 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001434 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001435 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1436 switch (FormatTok->TokenText[i]) {
1437 case '\n':
1438 ++FormatTok->NewlinesBefore;
1439 // FIXME: This is technically incorrect, as it could also
1440 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001441 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1442 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1443 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +00001444 FormatTok->HasUnescapedNewline = true;
1445 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1446 Column = 0;
1447 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001448 case '\r':
1449 case '\f':
1450 case '\v':
1451 Column = 0;
1452 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001453 case ' ':
1454 ++Column;
1455 break;
1456 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001457 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001458 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001459 case '\\':
1460 ++Column;
1461 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1462 FormatTok->TokenText[i + 1] != '\n'))
1463 FormatTok->Type = TT_ImplicitStringLiteral;
1464 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001465 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001466 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001467 ++Column;
1468 break;
1469 }
1470 }
1471
Daniel Jasper877615c2013-10-11 19:45:02 +00001472 if (FormatTok->Type == TT_ImplicitStringLiteral)
1473 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001474 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001475
Daniel Jasper8369aa52013-07-16 20:28:33 +00001476 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001477 }
Manuel Klimekef920692013-01-07 07:56:50 +00001478
Manuel Klimek1abf7892013-01-04 23:34:14 +00001479 // In case the token starts with escaped newlines, we want to
1480 // take them into account as whitespace - this pattern is quite frequent
1481 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001482 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001483 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1484 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001485 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001486 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001487 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001488 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001489 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001490
1491 FormatTok->WhitespaceRange = SourceRange(
1492 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1493
Manuel Klimek31c85922013-08-29 15:21:40 +00001494 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001495
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001496 TrailingWhitespace = 0;
1497 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001498 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001499 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001500 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001501 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001502 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001503 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001504 FormatTok->Tok.setIdentifierInfo(&Info);
1505 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001506 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001507 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001508 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001509 GreaterStashed = true;
1510 }
1511
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001512 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001513
Alexander Kornienko39856b72013-09-10 09:38:25 +00001514 StringRef Text = FormatTok->TokenText;
1515 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001516 if (FirstNewlinePos == StringRef::npos) {
1517 // FIXME: ColumnWidth actually depends on the start column, we need to
1518 // take this into account when the token is moved.
1519 FormatTok->ColumnWidth =
1520 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1521 Column += FormatTok->ColumnWidth;
1522 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001523 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001524 // FIXME: ColumnWidth actually depends on the start column, we need to
1525 // take this into account when the token is moved.
1526 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1527 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1528
Alexander Kornienko39856b72013-09-10 09:38:25 +00001529 // The last line of the token always starts in column 0.
1530 // Thus, the length can be precomputed even in the presence of tabs.
1531 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1532 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1533 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001534 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001535 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001536
Daniel Jaspere1e43192014-04-01 12:55:11 +00001537 FormatTok->IsForEachMacro =
1538 std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1539 FormatTok->Tok.getIdentifierInfo());
1540
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001541 return FormatTok;
1542 }
1543
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001544 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001545 bool IsFirstToken;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001546 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001547 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001548 unsigned TrailingWhitespace;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001549 Lexer &Lex;
1550 SourceManager &SourceMgr;
Manuel Klimek31c85922013-08-29 15:21:40 +00001551 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001552 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001553 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001554 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001555 // Index (in 'Tokens') of the last token that starts a new line.
1556 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001557 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001558 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001559
Daniel Jasper8369aa52013-07-16 20:28:33 +00001560 void readRawToken(FormatToken &Tok) {
1561 Lex.LexFromRawLexer(Tok.Tok);
1562 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1563 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001564 // For formatting, treat unterminated string literals like normal string
1565 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001566 if (Tok.is(tok::unknown)) {
1567 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1568 Tok.Tok.setKind(tok::string_literal);
1569 Tok.IsUnterminatedLiteral = true;
1570 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1571 Tok.TokenText == "''") {
1572 Tok.Tok.setKind(tok::char_constant);
1573 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001574 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001575 }
1576};
1577
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001578static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1579 switch (Language) {
1580 case FormatStyle::LK_Cpp:
1581 return "C++";
1582 case FormatStyle::LK_JavaScript:
1583 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001584 case FormatStyle::LK_Proto:
1585 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001586 default:
1587 return "Unknown";
1588 }
1589}
1590
Daniel Jasperf7935112012-12-03 18:12:45 +00001591class Formatter : public UnwrappedLineConsumer {
1592public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001593 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001594 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001595 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001596 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001597 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Manuel Klimek71814b42013-10-11 21:25:45 +00001598 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001599 DEBUG(llvm::dbgs() << "File encoding: "
1600 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1601 : "unknown")
1602 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001603 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1604 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001605 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001606
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001607 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001608 tooling::Replacements Result;
Manuel Klimek31c85922013-08-29 15:21:40 +00001609 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001610
1611 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001612 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001613 assert(UnwrappedLines.rbegin()->empty());
1614 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1615 ++Run) {
1616 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1617 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1618 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1619 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1620 }
1621 tooling::Replacements RunResult =
1622 format(AnnotatedLines, StructuralError, Tokens);
1623 DEBUG({
1624 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1625 for (tooling::Replacements::iterator I = RunResult.begin(),
1626 E = RunResult.end();
1627 I != E; ++I) {
1628 llvm::dbgs() << I->toString() << "\n";
1629 }
1630 });
1631 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1632 delete AnnotatedLines[i];
1633 }
1634 Result.insert(RunResult.begin(), RunResult.end());
1635 Whitespaces.reset();
1636 }
1637 return Result;
1638 }
1639
1640 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1641 bool StructuralError, FormatTokenLexer &Tokens) {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001642 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001643 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001644 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001645 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001646 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001647 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001648 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001649 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001650 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001651
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001652 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001653 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
1654 BinPackInconclusiveFunctions);
Daniel Jasper5500f612013-11-25 11:08:59 +00001655 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001656 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001657 return Whitespaces.generateReplacements();
1658 }
1659
1660private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001661 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001662 // Returns \c true if at least one line between I and E or one of their
1663 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001664 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1665 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1666 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001667 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001668 while (I != E) {
1669 AnnotatedLine *Line = *I;
1670 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1671
1672 // If a line is part of a preprocessor directive, it needs to be formatted
1673 // if any token within the directive is affected.
1674 if (Line->InPPDirective) {
1675 FormatToken *Last = Line->Last;
1676 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1677 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1678 Last = (*PPEnd)->Last;
1679 ++PPEnd;
1680 }
1681
1682 if (affectsTokenRange(*Line->First, *Last,
1683 /*IncludeLeadingNewlines=*/false)) {
1684 SomeLineAffected = true;
1685 markAllAsAffected(I, PPEnd);
1686 }
1687 I = PPEnd;
1688 continue;
1689 }
1690
Daniel Jasper38c82402013-11-29 09:27:43 +00001691 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001692 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001693
Daniel Jasper38c82402013-11-29 09:27:43 +00001694 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001695 ++I;
1696 }
1697 return SomeLineAffected;
1698 }
1699
Daniel Jasper9c199562013-11-28 15:58:55 +00001700 // Determines whether 'Line' is affected by the SourceRanges given as input.
1701 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001702 bool nonPPLineAffected(AnnotatedLine *Line,
1703 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001704 bool SomeLineAffected = false;
1705 Line->ChildrenAffected =
1706 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1707 if (Line->ChildrenAffected)
1708 SomeLineAffected = true;
1709
1710 // Stores whether one of the line's tokens is directly affected.
1711 bool SomeTokenAffected = false;
1712 // Stores whether we need to look at the leading newlines of the next token
1713 // in order to determine whether it was affected.
1714 bool IncludeLeadingNewlines = false;
1715
1716 // Stores whether the first child line of any of this line's tokens is
1717 // affected.
1718 bool SomeFirstChildAffected = false;
1719
1720 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1721 // Determine whether 'Tok' was affected.
1722 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1723 SomeTokenAffected = true;
1724
1725 // Determine whether the first child of 'Tok' was affected.
1726 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1727 SomeFirstChildAffected = true;
1728
1729 IncludeLeadingNewlines = Tok->Children.empty();
1730 }
1731
1732 // Was this line moved, i.e. has it previously been on the same line as an
1733 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001734 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1735 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001736
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001737 bool IsContinuedComment =
1738 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1739 Line->First->NewlinesBefore < 2 && PreviousLine &&
1740 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001741
1742 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1743 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001744 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001745 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001746 }
1747 return SomeLineAffected;
1748 }
1749
Daniel Jasper5500f612013-11-25 11:08:59 +00001750 // Marks all lines between I and E as well as all their children as affected.
1751 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1752 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1753 while (I != E) {
1754 (*I)->Affected = true;
1755 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1756 ++I;
1757 }
1758 }
1759
1760 // Returns true if the range from 'First' to 'Last' intersects with one of the
1761 // input ranges.
1762 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1763 bool IncludeLeadingNewlines) {
1764 SourceLocation Start = First.WhitespaceRange.getBegin();
1765 if (!IncludeLeadingNewlines)
1766 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001767 SourceLocation End = Last.getStartOfNonWhitespace();
1768 if (Last.TokenText.size() > 0)
1769 End = End.getLocWithOffset(Last.TokenText.size() - 1);
Daniel Jasper5500f612013-11-25 11:08:59 +00001770 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1771 return affectsCharSourceRange(Range);
1772 }
1773
1774 // Returns true if one of the input ranges intersect the leading empty lines
1775 // before 'Tok'.
1776 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1777 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1778 Tok.WhitespaceRange.getBegin(),
1779 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1780 return affectsCharSourceRange(EmptyLineRange);
1781 }
1782
1783 // Returns true if 'Range' intersects with one of the input ranges.
1784 bool affectsCharSourceRange(const CharSourceRange &Range) {
1785 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1786 E = Ranges.end();
1787 I != E; ++I) {
1788 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1789 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1790 return true;
1791 }
1792 return false;
1793 }
1794
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001795 static bool inputUsesCRLF(StringRef Text) {
1796 return Text.count('\r') * 2 > Text.count('\n');
1797 }
1798
Manuel Klimek71814b42013-10-11 21:25:45 +00001799 void
1800 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001801 unsigned CountBoundToVariable = 0;
1802 unsigned CountBoundToType = 0;
1803 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001804 bool HasBinPackedFunction = false;
1805 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001806 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001807 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001808 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001809 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001810 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001811 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001812 bool SpacesBefore =
1813 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1814 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1815 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001816 if (SpacesBefore && !SpacesAfter)
1817 ++CountBoundToVariable;
1818 else if (!SpacesBefore && SpacesAfter)
1819 ++CountBoundToType;
1820 }
1821
Daniel Jasperfba84ff2013-10-12 05:16:06 +00001822 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1823 if (Tok->is(tok::coloncolon) &&
1824 Tok->Previous->Type == TT_TemplateOpener)
1825 HasCpp03IncompatibleFormat = true;
1826 if (Tok->Type == TT_TemplateCloser &&
1827 Tok->Previous->Type == TT_TemplateCloser)
1828 HasCpp03IncompatibleFormat = true;
1829 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001830
1831 if (Tok->PackingKind == PPK_BinPacked)
1832 HasBinPackedFunction = true;
1833 if (Tok->PackingKind == PPK_OnePerLine)
1834 HasOnePerLineFunction = true;
1835
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001836 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001837 }
1838 }
1839 if (Style.DerivePointerBinding) {
1840 if (CountBoundToType > CountBoundToVariable)
1841 Style.PointerBindsToType = true;
1842 else if (CountBoundToType < CountBoundToVariable)
1843 Style.PointerBindsToType = false;
1844 }
1845 if (Style.Standard == FormatStyle::LS_Auto) {
1846 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1847 : FormatStyle::LS_Cpp03;
1848 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001849 BinPackInconclusiveFunctions =
1850 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001851 }
1852
Craig Topperfb6b25b2014-03-15 04:29:04 +00001853 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001854 assert(!UnwrappedLines.empty());
1855 UnwrappedLines.back().push_back(TheLine);
1856 }
1857
Craig Topperfb6b25b2014-03-15 04:29:04 +00001858 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00001859 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00001860 }
1861
1862 FormatStyle Style;
1863 Lexer &Lex;
1864 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001865 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001866 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00001867 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001868
1869 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001870 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001871};
1872
Craig Topperaf35e852013-06-30 22:29:28 +00001873} // end anonymous namespace
1874
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001875tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1876 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001877 std::vector<CharSourceRange> Ranges) {
1878 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001879 return formatter.format();
1880}
1881
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001882tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1883 std::vector<tooling::Range> Ranges,
1884 StringRef FileName) {
1885 FileManager Files((FileSystemOptions()));
1886 DiagnosticsEngine Diagnostics(
1887 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1888 new DiagnosticOptions);
1889 SourceManager SourceMgr(Diagnostics, Files);
1890 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1891 const clang::FileEntry *Entry =
1892 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1893 SourceMgr.overrideFileContents(Entry, Buf);
1894 FileID ID =
1895 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienko1e808872013-06-28 12:51:24 +00001896 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1897 getFormattingLangOpts(Style.Standard));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001898 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1899 std::vector<CharSourceRange> CharRanges;
1900 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1901 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1902 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1903 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1904 }
1905 return reformat(Style, Lex, SourceMgr, CharRanges);
1906}
1907
Alexander Kornienko1e808872013-06-28 12:51:24 +00001908LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001909 LangOptions LangOpts;
1910 LangOpts.CPlusPlus = 1;
Alexander Kornienko1e808872013-06-28 12:51:24 +00001911 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper20fd3c62014-04-15 08:49:21 +00001912 LangOpts.CPlusPlus1y = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001913 LangOpts.LineComment = 1;
Nikola Smiljanice08a91e2014-05-08 00:05:13 +00001914 LangOpts.CXXOperatorNames = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001915 LangOpts.Bool = 1;
1916 LangOpts.ObjC1 = 1;
1917 LangOpts.ObjC2 = 1;
1918 return LangOpts;
1919}
1920
Edwin Vaned544aa72013-09-30 13:31:48 +00001921const char *StyleOptionHelpDescription =
1922 "Coding style, currently supports:\n"
1923 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
1924 "Use -style=file to load style configuration from\n"
1925 ".clang-format file located in one of the parent\n"
1926 "directories of the source file (or current\n"
1927 "directory for stdin).\n"
1928 "Use -style=\"{key: value, ...}\" to set specific\n"
1929 "parameters, e.g.:\n"
1930 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
1931
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001932static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001933 if (FileName.endswith_lower(".js")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001934 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00001935 } else if (FileName.endswith_lower(".proto") ||
1936 FileName.endswith_lower(".protodevel")) {
1937 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001938 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001939 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001940}
1941
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001942FormatStyle getStyle(StringRef StyleName, StringRef FileName,
1943 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001944 FormatStyle Style = getLLVMStyle();
1945 Style.Language = getLanguageByFileName(FileName);
1946 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001947 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
1948 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001949 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001950 }
Edwin Vaned544aa72013-09-30 13:31:48 +00001951
1952 if (StyleName.startswith("{")) {
1953 // Parse YAML/JSON style from the command line.
1954 if (llvm::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001955 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
1956 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00001957 }
1958 return Style;
1959 }
1960
1961 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001962 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00001963 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
1964 << " style\n";
1965 return Style;
1966 }
1967
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001968 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001969 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00001970 SmallString<128> Path(FileName);
1971 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001972 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00001973 Directory = llvm::sys::path::parent_path(Directory)) {
1974 if (!llvm::sys::fs::is_directory(Directory))
1975 continue;
1976 SmallString<128> ConfigFile(Directory);
1977
1978 llvm::sys::path::append(ConfigFile, ".clang-format");
1979 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1980 bool IsFile = false;
1981 // Ignore errors from is_regular_file: we only need to know if we can read
1982 // the file or not.
1983 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1984
1985 if (!IsFile) {
1986 // Try _clang-format too, since dotfiles are not commonly used on Windows.
1987 ConfigFile = Directory;
1988 llvm::sys::path::append(ConfigFile, "_clang-format");
1989 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
1990 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
1991 }
1992
1993 if (IsFile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +00001994 std::unique_ptr<llvm::MemoryBuffer> Text;
Rafael Espindola1a3605c2013-10-25 19:00:49 +00001995 if (llvm::error_code ec =
1996 llvm::MemoryBuffer::getFile(ConfigFile.c_str(), Text)) {
Edwin Vaned544aa72013-09-30 13:31:48 +00001997 llvm::errs() << ec.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00001998 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00001999 }
2000 if (llvm::error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002001 if (ec == llvm::errc::not_supported) {
2002 if (!UnsuitableConfigFiles.empty())
2003 UnsuitableConfigFiles.append(", ");
2004 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002005 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002006 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002007 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2008 << "\n";
2009 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002010 }
2011 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2012 return Style;
2013 }
2014 }
2015 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
2016 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002017 if (!UnsuitableConfigFiles.empty()) {
2018 llvm::errs() << "Configuration file(s) do(es) not support "
2019 << getLanguageName(Style.Language) << ": "
2020 << UnsuitableConfigFiles << "\n";
2021 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002022 return Style;
2023}
2024
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002025} // namespace format
2026} // namespace clang