blob: 9fbab27bb51ea9a03c61155a59bf31ff14c2a255 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
Daniel Jasperf7935112012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Daniel Jasperde0328a2013-08-16 11:20:30 +000016#include "ContinuationIndenter.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000017#include "TokenAnnotator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "UnwrappedLineParser.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000019#include "WhitespaceManager.h"
Daniel Jasperec04c0d2013-05-16 10:40:07 +000020#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000021#include "clang/Basic/DiagnosticOptions.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000023#include "clang/Format/Format.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000024#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000025#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000026#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000027#include "llvm/Support/Debug.h"
Edwin Vaned544aa72013-09-30 13:31:48 +000028#include "llvm/Support/Path.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000029#include "llvm/Support/YAMLTraits.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000030#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000031#include <string>
32
Chandler Carruth10346662014-04-22 03:17:02 +000033#define DEBUG_TYPE "format-formatter"
34
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000035using clang::format::FormatStyle;
36
Daniel Jaspere1e43192014-04-01 12:55:11 +000037LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
38
Alexander Kornienkod6538332013-05-07 15:32:14 +000039namespace llvm {
40namespace yaml {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000041template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
42 static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
43 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
Daniel Jasperc58c70e2014-09-15 11:21:46 +000044 IO.enumCase(Value, "Java", FormatStyle::LK_Java);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000045 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
Daniel Jasper7052ce62014-01-19 09:04:08 +000046 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000047 }
48};
49
50template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
51 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
52 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
53 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
54 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
55 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
56 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
57 }
58};
59
60template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
61 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
62 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
63 IO.enumCase(Value, "false", FormatStyle::UT_Never);
64 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
65 IO.enumCase(Value, "true", FormatStyle::UT_Always);
66 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
67 }
68};
69
Daniel Jasperd74cf402014-04-08 12:46:38 +000070template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
71 static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
72 IO.enumCase(Value, "None", FormatStyle::SFS_None);
73 IO.enumCase(Value, "false", FormatStyle::SFS_None);
74 IO.enumCase(Value, "All", FormatStyle::SFS_All);
75 IO.enumCase(Value, "true", FormatStyle::SFS_All);
76 IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
Daniel Jasper9e709352014-11-26 10:43:58 +000077 IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
Daniel Jasperd74cf402014-04-08 12:46:38 +000078 }
79};
80
Daniel Jasperac043c92014-09-15 11:11:00 +000081template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
82 static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
83 IO.enumCase(Value, "All", FormatStyle::BOS_All);
84 IO.enumCase(Value, "true", FormatStyle::BOS_All);
85 IO.enumCase(Value, "None", FormatStyle::BOS_None);
86 IO.enumCase(Value, "false", FormatStyle::BOS_None);
87 IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
88 }
89};
90
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000091template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
92 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
93 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
94 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
95 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
96 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
Alexander Kornienko3a33f022013-12-12 09:49:52 +000097 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000098 }
99};
100
Alexander Kornienkod6538332013-05-07 15:32:14 +0000101template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000102struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000103 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000104 FormatStyle::NamespaceIndentationKind &Value) {
105 IO.enumCase(Value, "None", FormatStyle::NI_None);
106 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
107 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000108 }
109};
110
111template <>
Daniel Jasper553d4872014-06-17 12:40:34 +0000112struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
113 static void enumeration(IO &IO,
114 FormatStyle::PointerAlignmentStyle &Value) {
115 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
116 IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
117 IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
118
Alp Toker958027b2014-07-14 19:42:55 +0000119 // For backward compatibility.
Daniel Jasper553d4872014-06-17 12:40:34 +0000120 IO.enumCase(Value, "true", FormatStyle::PAS_Left);
121 IO.enumCase(Value, "false", FormatStyle::PAS_Right);
122 }
123};
124
125template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000126struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000127 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000128 FormatStyle::SpaceBeforeParensOptions &Value) {
129 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000130 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000131 FormatStyle::SBPO_ControlStatements);
132 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000133
134 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000135 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
136 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000137 }
138};
139
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000140template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000141 static void mapping(IO &IO, FormatStyle &Style) {
142 // When reading, read the language first, we need it for getPredefinedStyle.
143 IO.mapOptional("Language", Style.Language);
144
Alexander Kornienko49149672013-05-10 11:56:10 +0000145 if (IO.outputting()) {
Alexander Kornienkoe3648fb2013-09-02 16:39:23 +0000146 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000147 "Mozilla", "WebKit", "GNU" };
Alexander Kornienko49149672013-05-10 11:56:10 +0000148 ArrayRef<StringRef> Styles(StylesArray);
149 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
150 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000151 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000152 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000153 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000154 IO.mapOptional("# BasedOnStyle", StyleName);
155 break;
156 }
157 }
158 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000159 StringRef BasedOnStyle;
160 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000161 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000162 FormatStyle::LanguageKind OldLanguage = Style.Language;
163 FormatStyle::LanguageKind Language =
164 ((FormatStyle *)IO.getContext())->Language;
165 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000166 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
167 return;
168 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000169 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000170 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000171 }
172
173 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000174 IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000175 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000176 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000177 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
178 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000179 IO.mapOptional("AllowShortBlocksOnASingleLine",
180 Style.AllowShortBlocksOnASingleLine);
Daniel Jasperb87899b2014-09-10 13:11:45 +0000181 IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
182 Style.AllowShortCaseLabelsOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000183 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
184 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000185 IO.mapOptional("AllowShortLoopsOnASingleLine",
186 Style.AllowShortLoopsOnASingleLine);
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000187 IO.mapOptional("AllowShortFunctionsOnASingleLine",
188 Style.AllowShortFunctionsOnASingleLine);
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000189 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
190 Style.AlwaysBreakAfterDefinitionReturnType);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000191 IO.mapOptional("AlwaysBreakTemplateDeclarations",
192 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko58611712013-07-04 12:02:44 +0000193 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
194 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000195 IO.mapOptional("BreakBeforeBinaryOperators",
196 Style.BreakBeforeBinaryOperators);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000197 IO.mapOptional("BreakBeforeTernaryOperators",
198 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000199 IO.mapOptional("BreakConstructorInitializersBeforeComma",
200 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000201 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
Daniel Jasper18210d72014-10-09 09:52:05 +0000202 IO.mapOptional("BinPackArguments", Style.BinPackArguments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000203 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
204 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
205 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000206 IO.mapOptional("ConstructorInitializerIndentWidth",
207 Style.ConstructorInitializerIndentWidth);
Daniel Jasper553d4872014-06-17 12:40:34 +0000208 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000209 IO.mapOptional("ExperimentalAutoDetectBinPacking",
210 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000211 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000212 IO.mapOptional("IndentWrappedFunctionNames",
213 Style.IndentWrappedFunctionNames);
214 IO.mapOptional("IndentFunctionDeclarationAfterType",
215 Style.IndentWrappedFunctionNames);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000216 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000217 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
218 Style.KeepEmptyLinesAtTheStartOfBlocks);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000219 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000220 IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000221 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000222 IO.mapOptional("ObjCSpaceBeforeProtocolList",
223 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000224 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
225 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000226 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
227 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000228 IO.mapOptional("PenaltyBreakFirstLessLess",
229 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000230 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
231 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
232 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000233 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000234 IO.mapOptional("SpacesBeforeTrailingComments",
235 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000236 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000237 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000238 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000239 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000240 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000241 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000242 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperad981f82014-08-26 11:41:14 +0000243 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000244 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasperf110e202013-08-21 08:39:01 +0000245 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000246 IO.mapOptional("SpacesInCStyleCastParentheses",
247 Style.SpacesInCStyleCastParentheses);
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000248 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000249 IO.mapOptional("SpacesInContainerLiterals",
250 Style.SpacesInContainerLiterals);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000251 IO.mapOptional("SpaceBeforeAssignmentOperators",
252 Style.SpaceBeforeAssignmentOperators);
Daniel Jasper6633ab82013-10-18 10:38:14 +0000253 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000254 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000255 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000256
257 // For backward compatibility.
258 if (!IO.outputting()) {
259 IO.mapOptional("SpaceAfterControlStatementKeyword",
260 Style.SpaceBeforeParens);
Daniel Jasper553d4872014-06-17 12:40:34 +0000261 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
262 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000263 }
264 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000265 IO.mapOptional("DisableFormat", Style.DisableFormat);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000266 }
267};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000268
269// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000270// IO.getContext() should contain a pointer to the FormatStyle structure, that
271// will be used to get default values for missing keys.
272// If the first element has no Language specified, it will be treated as the
273// default one for the following elements.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000274template <> struct DocumentListTraits<std::vector<FormatStyle> > {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000275 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
276 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000277 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000278 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000279 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000280 if (Index >= Seq.size()) {
281 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000282 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000283 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000284 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000285 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000286 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000287 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000288 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000289 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000290 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000291 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000292 }
293};
Alexander Kornienkod6538332013-05-07 15:32:14 +0000294}
295}
296
Daniel Jasperf7935112012-12-03 18:12:45 +0000297namespace clang {
298namespace format {
299
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000300const std::error_category &getParseCategory() {
Rafael Espindolad0136702014-06-12 02:50:04 +0000301 static ParseErrorCategory C;
302 return C;
303}
304std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000305 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000306}
307
308const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
309 return "clang-format.parse_error";
310}
311
312std::string ParseErrorCategory::message(int EV) const {
313 switch (static_cast<ParseError>(EV)) {
314 case ParseError::Success:
315 return "Success";
316 case ParseError::Error:
317 return "Invalid argument";
318 case ParseError::Unsuitable:
319 return "Unsuitable";
320 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000321 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000322}
323
Daniel Jasperf7935112012-12-03 18:12:45 +0000324FormatStyle getLLVMStyle() {
325 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000326 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000327 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000328 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000329 LLVMStyle.AlignAfterOpenBracket = true;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000330 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000331 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000332 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000333 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000334 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000335 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000336 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000337 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000338 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000339 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000340 LLVMStyle.BinPackParameters = true;
Daniel Jasper18210d72014-10-09 09:52:05 +0000341 LLVMStyle.BinPackArguments = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000342 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000343 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000344 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
345 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000346 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000347 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000348 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000349 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000350 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000351 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000352 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000353 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000354 LLVMStyle.ForEachMacros.push_back("foreach");
355 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
356 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000357 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000358 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000359 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000360 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000361 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000362 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000363 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000364 LLVMStyle.ObjCBlockIndentWidth = 2;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000365 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000366 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000367 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000368 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000369 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000370 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000371 LLVMStyle.SpacesInParentheses = false;
Daniel Jasperad981f82014-08-26 11:41:14 +0000372 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000373 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000374 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000375 LLVMStyle.SpacesInCStyleCastParentheses = false;
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000376 LLVMStyle.SpaceAfterCStyleCast = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000377 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000378 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000379 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000380
Daniel Jasper19a541e2013-12-19 16:45:34 +0000381 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000382 LLVMStyle.PenaltyBreakFirstLessLess = 120;
383 LLVMStyle.PenaltyBreakString = 1000;
384 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000385 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000386 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000387
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000388 LLVMStyle.DisableFormat = false;
389
Daniel Jasperf7935112012-12-03 18:12:45 +0000390 return LLVMStyle;
391}
392
Nico Weber514ecc82014-02-02 20:50:45 +0000393FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000394 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000395 GoogleStyle.Language = Language;
396
Daniel Jasperf7935112012-12-03 18:12:45 +0000397 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000398 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000399 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000400 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000401 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000402 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000403 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000404 GoogleStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000405 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000406 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000407 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000408 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000409 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000410 GoogleStyle.SpacesBeforeTrailingComments = 2;
411 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000412
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000413 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000414 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000415
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000416 if (Language == FormatStyle::LK_Java) {
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000417 GoogleStyle.AlignAfterOpenBracket = false;
Daniel Jasper9e709352014-11-26 10:43:58 +0000418 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000419 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
420 GoogleStyle.ColumnLimit = 100;
421 GoogleStyle.SpaceAfterCStyleCast = true;
Daniel Jasper61d81972014-11-14 08:22:46 +0000422 GoogleStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000423 } else if (Language == FormatStyle::LK_JavaScript) {
Daniel Jaspere551bb72014-11-05 17:22:31 +0000424 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000425 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000426 GoogleStyle.SpacesInContainerLiterals = false;
Daniel Jasper67f8ad22014-09-30 17:57:06 +0000427 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Nico Weber514ecc82014-02-02 20:50:45 +0000428 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000429 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000430 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000431 }
432
Daniel Jasperf7935112012-12-03 18:12:45 +0000433 return GoogleStyle;
434}
435
Nico Weber514ecc82014-02-02 20:50:45 +0000436FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
437 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Nico Weber450425c2014-11-26 16:43:18 +0000438 if (Language == FormatStyle::LK_Java) {
439 ChromiumStyle.IndentWidth = 4;
440 ChromiumStyle.ContinuationIndentWidth = 8;
441 } else {
442 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
443 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
444 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
445 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
446 ChromiumStyle.BinPackParameters = false;
447 ChromiumStyle.DerivePointerAlignment = false;
448 }
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000449 return ChromiumStyle;
450}
451
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000452FormatStyle getMozillaStyle() {
453 FormatStyle MozillaStyle = getLLVMStyle();
454 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000455 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000456 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000457 MozillaStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000458 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000459 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000460 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
461 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000462 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000463 MozillaStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000464 return MozillaStyle;
465}
466
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000467FormatStyle getWebKitStyle() {
468 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000469 Style.AccessModifierOffset = -4;
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000470 Style.AlignAfterOpenBracket = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000471 Style.AlignTrailingComments = false;
Daniel Jasperac043c92014-09-15 11:11:00 +0000472 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000473 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000474 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000475 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000476 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000477 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000478 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000479 Style.ObjCBlockIndentWidth = 4;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000480 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000481 Style.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000482 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000483 return Style;
484}
485
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000486FormatStyle getGNUStyle() {
487 FormatStyle Style = getLLVMStyle();
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000488 Style.AlwaysBreakAfterDefinitionReturnType = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000489 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000490 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000491 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000492 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000493 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000494 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000495 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000496 return Style;
497}
498
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000499FormatStyle getNoStyle() {
500 FormatStyle NoStyle = getLLVMStyle();
501 NoStyle.DisableFormat = true;
502 return NoStyle;
503}
504
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000505bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
506 FormatStyle *Style) {
507 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000508 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000509 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000510 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000511 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000512 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000513 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000514 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000515 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000516 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000517 } else if (Name.equals_lower("gnu")) {
518 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000519 } else if (Name.equals_lower("none")) {
520 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000521 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000522 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000523 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000524
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000525 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000526 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000527}
528
Rafael Espindolac0809172014-06-12 14:02:15 +0000529std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000530 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000531 FormatStyle::LanguageKind Language = Style->Language;
532 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000533 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000534 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000535
536 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000537 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000538 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
539 // values for the fields, keys for which are missing from the configuration.
540 // Mapping also uses the context to get the language to find the correct
541 // base style.
542 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000543 Input >> Styles;
544 if (Input.error())
545 return Input.error();
546
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000547 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000548 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000549 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000550 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000551 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000552 for (unsigned j = 0; j < i; ++j) {
553 if (Styles[i].Language == Styles[j].Language) {
554 DEBUG(llvm::dbgs()
555 << "Duplicate languages in the config file on positions " << j
556 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000557 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000558 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000559 }
560 }
561 // Look for a suitable configuration starting from the end, so we can
562 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000563 // configuration (which can only be at slot 0) after it.
564 for (int i = Styles.size() - 1; i >= 0; --i) {
565 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000566 Styles[i].Language == FormatStyle::LK_None) {
567 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000568 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000569 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000570 }
571 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000572 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000573}
574
575std::string configurationAsText(const FormatStyle &Style) {
576 std::string Text;
577 llvm::raw_string_ostream Stream(Text);
578 llvm::yaml::Output Output(Stream);
579 // We use the same mapping method for input and output, so we need a non-const
580 // reference here.
581 FormatStyle NonConstStyle = Style;
582 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000583 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000584}
585
Craig Topperaf35e852013-06-30 22:29:28 +0000586namespace {
587
Nico Weber34272652014-11-13 16:25:37 +0000588bool startsExternCBlock(const AnnotatedLine &Line) {
589 const FormatToken *Next = Line.First->getNextNonComment();
590 const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr;
591 return Line.First->is(tok::kw_extern) && Next && Next->isStringLiteral() &&
592 NextNext && NextNext->is(tok::l_brace);
593}
594
Daniel Jasperde0328a2013-08-16 11:20:30 +0000595class NoColumnLimitFormatter {
596public:
Daniel Jasperf110e202013-08-21 08:39:01 +0000597 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000598
599 /// \brief Formats the line starting at \p State, simply keeping all of the
600 /// input's line breaking decisions.
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000601 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000602 LineState State =
603 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Craig Topper2145bc02014-05-09 08:15:10 +0000604 while (State.NextToken) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000605 bool Newline =
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000606 Indenter->mustBreak(State) ||
Daniel Jasperde0328a2013-08-16 11:20:30 +0000607 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
608 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
609 }
610 }
Daniel Jasperf110e202013-08-21 08:39:01 +0000611
Daniel Jasperde0328a2013-08-16 11:20:30 +0000612private:
613 ContinuationIndenter *Indenter;
614};
615
Daniel Jasper56f8b432013-11-06 23:12:09 +0000616class LineJoiner {
617public:
618 LineJoiner(const FormatStyle &Style) : Style(Style) {}
619
620 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
621 unsigned
622 tryFitMultipleLinesInOne(unsigned Indent,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000623 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000624 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
625 // We can never merge stuff if there are trailing line comments.
Daniel Jasper234379f2013-12-24 13:31:25 +0000626 const AnnotatedLine *TheLine = *I;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000627 if (TheLine->Last->is(TT_LineComment))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000628 return 0;
629
Alexander Kornienkoecc232d2013-12-04 13:25:26 +0000630 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
631 return 0;
632
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000633 unsigned Limit =
634 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000635 // If we already exceed the column limit, we set 'Limit' to 0. The different
636 // tryMerge..() functions can then decide whether to still do merging.
637 Limit = TheLine->Last->TotalLength > Limit
638 ? 0
639 : Limit - TheLine->Last->TotalLength;
640
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000641 if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000642 return 0;
643
Daniel Jasperd74cf402014-04-08 12:46:38 +0000644 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
645 // If necessary, change to something smarter.
646 bool MergeShortFunctions =
647 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
Daniel Jasper9e709352014-11-26 10:43:58 +0000648 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty &&
649 I[1]->First->is(tok::r_brace)) ||
Daniel Jasperd74cf402014-04-08 12:46:38 +0000650 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
651 TheLine->Level != 0);
652
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000653 if (TheLine->Last->is(TT_FunctionLBrace) &&
Daniel Jasper234379f2013-12-24 13:31:25 +0000654 TheLine->First != TheLine->Last) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000655 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000656 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000657 if (TheLine->Last->is(tok::l_brace)) {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000658 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000659 ? tryMergeSimpleBlock(I, E, Limit)
660 : 0;
661 }
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000662 if (I[1]->First->is(TT_FunctionLBrace) &&
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000663 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
Alp Tokerba5b4dc2013-12-30 02:06:29 +0000664 // Check for Limit <= 2 to account for the " {".
Daniel Jasper234379f2013-12-24 13:31:25 +0000665 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
666 return 0;
667 Limit -= 2;
668
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000669 unsigned MergedLines = 0;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000670 if (MergeShortFunctions) {
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000671 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
672 // If we managed to merge the block, count the function header, which is
673 // on a separate line.
674 if (MergedLines > 0)
675 ++MergedLines;
676 }
677 return MergedLines;
678 }
679 if (TheLine->First->is(tok::kw_if)) {
680 return Style.AllowShortIfStatementsOnASingleLine
681 ? tryMergeSimpleControlStatement(I, E, Limit)
682 : 0;
683 }
684 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
685 return Style.AllowShortLoopsOnASingleLine
686 ? tryMergeSimpleControlStatement(I, E, Limit)
687 : 0;
688 }
Daniel Jasperb87899b2014-09-10 13:11:45 +0000689 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
690 return Style.AllowShortCaseLabelsOnASingleLine
691 ? tryMergeShortCaseLabels(I, E, Limit)
692 : 0;
693 }
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000694 if (TheLine->InPPDirective &&
695 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000696 return tryMergeSimplePPDirective(I, E, Limit);
697 }
698 return 0;
699 }
700
701private:
702 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000703 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000704 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
705 unsigned Limit) {
706 if (Limit == 0)
707 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000708 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000709 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000710 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000711 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000712 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000713 return 0;
714 return 1;
715 }
716
717 unsigned tryMergeSimpleControlStatement(
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000718 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000719 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
720 if (Limit == 0)
721 return 0;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000722 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
723 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
Daniel Jasper17605d32014-05-14 09:33:35 +0000724 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000725 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000726 if (I[1]->InPPDirective != (*I)->InPPDirective ||
727 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000728 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000729 Limit = limitConsideringMacros(I + 1, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000730 AnnotatedLine &Line = **I;
731 if (Line.Last->isNot(tok::r_paren))
732 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000733 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000734 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000735 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000736 tok::kw_while, TT_LineComment))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000737 return 0;
738 // Only inline simple if's (no nested if or else).
739 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000740 I[2]->First->is(tok::kw_else))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000741 return 0;
742 return 1;
743 }
744
Daniel Jasperb87899b2014-09-10 13:11:45 +0000745 unsigned tryMergeShortCaseLabels(
746 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
747 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
748 if (Limit == 0 || I + 1 == E ||
749 I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
750 return 0;
751 unsigned NumStmts = 0;
752 unsigned Length = 0;
Daniel Jasper79f226e2014-11-23 21:45:03 +0000753 bool InPPDirective = I[0]->InPPDirective;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000754 for (; NumStmts < 3; ++NumStmts) {
755 if (I + 1 + NumStmts == E)
756 break;
757 const AnnotatedLine *Line = I[1 + NumStmts];
Daniel Jasper79f226e2014-11-23 21:45:03 +0000758 if (Line->InPPDirective != InPPDirective)
759 break;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000760 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
761 break;
762 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
Daniel Jasperd081e882014-11-21 12:36:25 +0000763 tok::kw_while, tok::comment))
Daniel Jasperb87899b2014-09-10 13:11:45 +0000764 return 0;
765 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
766 }
767 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
768 return 0;
769 return NumStmts;
770 }
771
Daniel Jasper56f8b432013-11-06 23:12:09 +0000772 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000773 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000774 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
775 unsigned Limit) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000776 AnnotatedLine &Line = **I;
Daniel Jasper17605d32014-05-14 09:33:35 +0000777
778 // Don't merge ObjC @ keywords and methods.
Daniel Jasper9e709352014-11-26 10:43:58 +0000779 if (Style.Language != FormatStyle::LK_Java &&
780 Line.First->isOneOf(tok::at, tok::minus, tok::plus))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000781 return 0;
782
Daniel Jasper17605d32014-05-14 09:33:35 +0000783 // Check that the current line allows merging. This depends on whether we
784 // are in a control flow statements as well as several style flags.
785 if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
786 return 0;
787 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
788 tok::kw_catch, tok::kw_for, tok::r_brace)) {
789 if (!Style.AllowShortBlocksOnASingleLine)
790 return 0;
791 if (!Style.AllowShortIfStatementsOnASingleLine &&
792 Line.First->is(tok::kw_if))
793 return 0;
794 if (!Style.AllowShortLoopsOnASingleLine &&
795 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
796 return 0;
797 // FIXME: Consider an option to allow short exception handling clauses on
798 // a single line.
799 if (Line.First->isOneOf(tok::kw_try, tok::kw_catch))
800 return 0;
801 }
802
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000803 FormatToken *Tok = I[1]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000804 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Craig Topper2145bc02014-05-09 08:15:10 +0000805 (Tok->getNextNonComment() == nullptr ||
Daniel Jasper56f8b432013-11-06 23:12:09 +0000806 Tok->getNextNonComment()->is(tok::semi))) {
807 // We merge empty blocks even if the line exceeds the column limit.
808 Tok->SpacesRequiredBefore = 0;
809 Tok->CanBreakBefore = true;
810 return 1;
Nico Weber34272652014-11-13 16:25:37 +0000811 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace) &&
812 !startsExternCBlock(Line)) {
Daniel Jasper79dffb42014-05-07 09:48:30 +0000813 // We don't merge short records.
814 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
815 return 0;
816
Daniel Jasper56f8b432013-11-06 23:12:09 +0000817 // Check that we still have three lines and they fit into the limit.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000818 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000819 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000820 Limit = limitConsideringMacros(I + 2, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000821
822 if (!nextTwoLinesFitInto(I, Limit))
823 return 0;
824
825 // Second, check that the next line does not contain any braces - if it
826 // does, readability declines when putting it into a single line.
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000827 if (I[1]->Last->is(TT_LineComment))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000828 return 0;
829 do {
Daniel Jasperbd630732014-05-22 13:25:26 +0000830 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000831 return 0;
832 Tok = Tok->Next;
Craig Topper2145bc02014-05-09 08:15:10 +0000833 } while (Tok);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000834
Daniel Jasper79dffb42014-05-07 09:48:30 +0000835 // Last, check that the third line starts with a closing brace.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000836 Tok = I[2]->First;
Daniel Jasper79dffb42014-05-07 09:48:30 +0000837 if (Tok->isNot(tok::r_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000838 return 0;
839
840 return 2;
841 }
842 return 0;
843 }
844
Daniel Jasper64989962014-02-07 13:45:27 +0000845 /// Returns the modified column limit for \p I if it is inside a macro and
846 /// needs a trailing '\'.
847 unsigned
Daniel Jaspera0407742014-02-11 10:08:11 +0000848 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper64989962014-02-07 13:45:27 +0000849 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
850 unsigned Limit) {
851 if (I[0]->InPPDirective && I + 1 != E &&
852 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
853 return Limit < 2 ? 0 : Limit - 2;
854 }
855 return Limit;
856 }
857
Daniel Jasper56f8b432013-11-06 23:12:09 +0000858 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
859 unsigned Limit) {
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000860 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
861 return false;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000862 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000863 }
864
Daniel Jasper234379f2013-12-24 13:31:25 +0000865 bool containsMustBreak(const AnnotatedLine *Line) {
866 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
867 if (Tok->MustBreakBefore)
868 return true;
869 }
870 return false;
871 }
872
Daniel Jasper56f8b432013-11-06 23:12:09 +0000873 const FormatStyle &Style;
874};
875
Daniel Jasperf7935112012-12-03 18:12:45 +0000876class UnwrappedLineFormatter {
877public:
Daniel Jasper5500f612013-11-25 11:08:59 +0000878 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000879 WhitespaceManager *Whitespaces,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000880 const FormatStyle &Style)
Daniel Jasper5500f612013-11-25 11:08:59 +0000881 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
882 Joiner(Style) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000883
Daniel Jasper56f8b432013-11-06 23:12:09 +0000884 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper9c199562013-11-28 15:58:55 +0000885 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Daniel Jasperc359ad02014-04-15 08:13:47 +0000886 // Try to look up already computed penalty in DryRun-mode.
NAKAMURA Takumi22059522014-04-15 23:29:04 +0000887 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
888 &Lines, AdditionalIndent);
Daniel Jasperc359ad02014-04-15 08:13:47 +0000889 auto CacheIt = PenaltyCache.find(CacheKey);
890 if (DryRun && CacheIt != PenaltyCache.end())
891 return CacheIt->second;
892
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000893 assert(!Lines.empty());
894 unsigned Penalty = 0;
895 std::vector<int> IndentForLevel;
896 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
897 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Craig Topper2145bc02014-05-09 08:15:10 +0000898 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000899 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
900 E = Lines.end();
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000901 I != E; ++I) {
902 const AnnotatedLine &TheLine = **I;
903 const FormatToken *FirstTok = TheLine.First;
904 int Offset = getIndentOffset(*FirstTok);
905
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000906 // Determine indent and try to merge multiple unwrapped lines.
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000907 unsigned Indent;
908 if (TheLine.InPPDirective) {
909 Indent = TheLine.Level * Style.IndentWidth;
910 } else {
911 while (IndentForLevel.size() <= TheLine.Level)
912 IndentForLevel.push_back(-1);
913 IndentForLevel.resize(TheLine.Level + 1);
914 Indent = getIndent(IndentForLevel, TheLine.Level);
915 }
916 unsigned LevelIndent = Indent;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000917 if (static_cast<int>(Indent) + Offset >= 0)
918 Indent += Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000919
920 // Merge multiple lines if possible.
Daniel Jasper56f8b432013-11-06 23:12:09 +0000921 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
Alexander Kornienko31e95542013-12-04 12:21:08 +0000922 if (MergedLines > 0 && Style.ColumnLimit == 0) {
923 // Disallow line merging if there is a break at the start of one of the
924 // input lines.
925 for (unsigned i = 0; i < MergedLines; ++i) {
926 if (I[i + 1]->First->NewlinesBefore > 0)
927 MergedLines = 0;
928 }
929 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000930 if (!DryRun) {
931 for (unsigned i = 0; i < MergedLines; ++i) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000932 join(*I[i], *I[i + 1]);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000933 }
934 }
935 I += MergedLines;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000936
Daniel Jasper9c199562013-11-28 15:58:55 +0000937 bool FixIndentation =
938 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000939 if (TheLine.First->is(tok::eof)) {
Daniel Jasper5500f612013-11-25 11:08:59 +0000940 if (PreviousLine && PreviousLine->Affected && !DryRun) {
941 // Remove the file's trailing whitespace.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000942 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
943 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
944 /*IndentLevel=*/0, /*Spaces=*/0,
945 /*TargetColumn=*/0);
946 }
Daniel Jasper9c199562013-11-28 15:58:55 +0000947 } else if (TheLine.Type != LT_Invalid &&
948 (TheLine.Affected || FixIndentation)) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000949 if (FirstTok->WhitespaceRange.isValid()) {
950 if (!DryRun)
951 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
952 Indent, TheLine.InPPDirective);
953 } else {
954 Indent = LevelIndent = FirstTok->OriginalColumn;
955 }
956
957 // If everything fits on a single line, just put it there.
958 unsigned ColumnLimit = Style.ColumnLimit;
959 if (I + 1 != E) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000960 AnnotatedLine *NextLine = I[1];
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000961 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
962 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
963 }
964
Daniel Jasper616de8642014-11-23 16:46:28 +0000965 if (TheLine.Last->TotalLength + Indent <= ColumnLimit ||
966 TheLine.Type == LT_ImportStatement) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000967 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000968 while (State.NextToken) {
969 formatChildren(State, /*Newline=*/false, /*DryRun=*/false, Penalty);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000970 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000971 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000972 } else if (Style.ColumnLimit == 0) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000973 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000974 NoColumnLimitFormatter Formatter(Indenter);
975 if (!DryRun)
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000976 Formatter.format(Indent, &TheLine);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000977 } else {
978 Penalty += format(TheLine, Indent, DryRun);
979 }
980
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000981 if (!TheLine.InPPDirective)
982 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper9c199562013-11-28 15:58:55 +0000983 } else if (TheLine.ChildrenAffected) {
984 format(TheLine.Children, DryRun);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000985 } else {
986 // Format the first token if necessary, and notify the WhitespaceManager
987 // about the unchanged whitespace.
Craig Topper2145bc02014-05-09 08:15:10 +0000988 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000989 if (Tok == TheLine.First &&
990 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
991 unsigned LevelIndent = Tok->OriginalColumn;
992 if (!DryRun) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000993 // Remove trailing whitespace of the previous line.
Daniel Jasper5500f612013-11-25 11:08:59 +0000994 if ((PreviousLine && PreviousLine->Affected) ||
995 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000996 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
997 TheLine.InPPDirective);
998 } else {
999 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
1000 }
1001 }
1002
1003 if (static_cast<int>(LevelIndent) - Offset >= 0)
1004 LevelIndent -= Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +00001005 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001006 IndentForLevel[TheLine.Level] = LevelIndent;
1007 } else if (!DryRun) {
1008 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
1009 }
1010 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001011 }
1012 if (!DryRun) {
Craig Topper2145bc02014-05-09 08:15:10 +00001013 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001014 Tok->Finalized = true;
1015 }
1016 }
1017 PreviousLine = *I;
1018 }
Daniel Jasperc359ad02014-04-15 08:13:47 +00001019 PenaltyCache[CacheKey] = Penalty;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001020 return Penalty;
1021 }
1022
1023private:
1024 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001025 ///
1026 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001027 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
1028 bool DryRun) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001029 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +00001030
Daniel Jasperacc33662013-02-08 08:22:00 +00001031 // If the ObjC method declaration does not fit on a line, we should format
1032 // it with one arg per line.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001033 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperacc33662013-02-08 08:22:00 +00001034 State.Stack.back().BreakBeforeParameter = true;
1035
Daniel Jasper4b866272013-02-01 11:00:45 +00001036 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001037 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +00001038 }
1039
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001040 /// \brief An edge in the solution space from \c Previous->State to \c State,
1041 /// inserting a newline dependent on the \c NewLine.
1042 struct StateNode {
1043 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001044 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001045 LineState State;
1046 bool NewLine;
1047 StateNode *Previous;
1048 };
Daniel Jasper4b866272013-02-01 11:00:45 +00001049
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001050 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
1051 ///
1052 /// In case of equal penalties, we want to prefer states that were inserted
1053 /// first. During state generation we make sure that we insert states first
1054 /// that break the line as late as possible.
1055 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1056
1057 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
1058 /// \c State has the given \c OrderedPenalty.
1059 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1060
1061 /// \brief The BFS queue type.
1062 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1063 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +00001064
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001065 /// \brief Get the offset of the line relatively to the level.
1066 ///
1067 /// For example, 'public:' labels in classes are offset by 1 or 2
1068 /// characters to the left from their level.
1069 int getIndentOffset(const FormatToken &RootToken) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001070 if (Style.Language == FormatStyle::LK_Java)
1071 return 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001072 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
1073 return Style.AccessModifierOffset;
1074 return 0;
1075 }
1076
1077 /// \brief Add a new line and the required indent before the first Token
1078 /// of the \c UnwrappedLine if there was no structural parsing error.
1079 void formatFirstToken(FormatToken &RootToken,
1080 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
1081 unsigned Indent, bool InPPDirective) {
1082 unsigned Newlines =
1083 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1084 // Remove empty lines before "}" where applicable.
1085 if (RootToken.is(tok::r_brace) &&
1086 (!RootToken.Next ||
1087 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1088 Newlines = std::min(Newlines, 1u);
1089 if (Newlines == 0 && !RootToken.IsFirst)
1090 Newlines = 1;
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001091 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1092 Newlines = 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001093
Daniel Jasper11164bd2014-03-21 12:58:53 +00001094 // Remove empty lines after "{".
Daniel Jaspera26fc5c2014-03-21 13:43:14 +00001095 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1096 PreviousLine->Last->is(tok::l_brace) &&
Nico Weber34272652014-11-13 16:25:37 +00001097 PreviousLine->First->isNot(tok::kw_namespace) &&
1098 !startsExternCBlock(*PreviousLine))
Daniel Jasper11164bd2014-03-21 12:58:53 +00001099 Newlines = 1;
1100
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001101 // Insert extra new line before access specifiers.
1102 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1103 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1104 ++Newlines;
1105
1106 // Remove empty lines after access specifiers.
1107 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
1108 Newlines = std::min(1u, Newlines);
1109
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001110 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
1111 Indent, InPPDirective &&
1112 !RootToken.HasUnescapedNewline);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001113 }
1114
1115 /// \brief Get the indent of \p Level from \p IndentForLevel.
1116 ///
1117 /// \p IndentForLevel must contain the indent for the level \c l
1118 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1119 /// that level is unknown.
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001120 unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001121 if (IndentForLevel[Level] != -1)
1122 return IndentForLevel[Level];
1123 if (Level == 0)
1124 return 0;
1125 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
1126 }
1127
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001128 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1129 assert(!A.Last->Next);
1130 assert(!B.First->Previous);
Daniel Jasper5500f612013-11-25 11:08:59 +00001131 if (B.Affected)
1132 A.Affected = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001133 A.Last->Next = B.First;
1134 B.First->Previous = A.Last;
Daniel Jasper98fb6e12013-11-08 17:33:27 +00001135 B.First->CanBreakBefore = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001136 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1137 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1138 Tok->TotalLength += LengthA;
1139 A.Last = Tok;
1140 }
1141 }
1142
1143 unsigned getColumnLimit(bool InPPDirective) const {
1144 // In preprocessor directives reserve two chars for trailing " \"
1145 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1146 }
1147
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001148 struct CompareLineStatePointers {
1149 bool operator()(LineState *obj1, LineState *obj2) const {
1150 return *obj1 < *obj2;
1151 }
1152 };
1153
Daniel Jasper4b866272013-02-01 11:00:45 +00001154 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +00001155 ///
Daniel Jasper4b866272013-02-01 11:00:45 +00001156 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1157 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1158 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001159 /// to a state where all tokens are placed. Returns the penalty.
1160 ///
1161 /// If \p DryRun is \c false, directly applies the changes.
1162 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001163 std::set<LineState *, CompareLineStatePointers> Seen;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001164
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001165 // Increasing count of \c StateNode items we have created. This is used to
1166 // create a deterministic order independent of the container.
1167 unsigned Count = 0;
1168 QueueType Queue;
1169
Daniel Jasper4b866272013-02-01 11:00:45 +00001170 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001171 StateNode *Node =
Craig Topper2145bc02014-05-09 08:15:10 +00001172 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001173 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1174 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001175
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001176 unsigned Penalty = 0;
1177
Daniel Jasper4b866272013-02-01 11:00:45 +00001178 // While not empty, take first element and follow edges.
1179 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001180 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001181 StateNode *Node = Queue.top().second;
Craig Topper2145bc02014-05-09 08:15:10 +00001182 if (!Node->State.NextToken) {
Alexander Kornienko49149672013-05-10 11:56:10 +00001183 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001184 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001185 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001186 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001187
Daniel Jasperf8114cf2013-05-22 05:27:42 +00001188 // Cut off the analysis of certain solutions if the analysis gets too
1189 // complex. See description of IgnoreStackForComparison.
1190 if (Count > 10000)
1191 Node->State.IgnoreStackForComparison = true;
1192
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001193 if (!Seen.insert(&Node->State).second)
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001194 // State already examined with lower penalty.
1195 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001196
Manuel Klimek71814b42013-10-11 21:25:45 +00001197 FormatDecision LastFormat = Node->State.NextToken->Decision;
1198 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001199 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimek71814b42013-10-11 21:25:45 +00001200 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001201 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper4b866272013-02-01 11:00:45 +00001202 }
1203
Manuel Klimek71814b42013-10-11 21:25:45 +00001204 if (Queue.empty()) {
Daniel Jasper4b866272013-02-01 11:00:45 +00001205 // We were unable to find a solution, do nothing.
1206 // FIXME: Add diagnostic?
Manuel Klimek71814b42013-10-11 21:25:45 +00001207 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001208 return 0;
Manuel Klimek71814b42013-10-11 21:25:45 +00001209 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001210
Daniel Jasper4b866272013-02-01 11:00:45 +00001211 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001212 if (!DryRun)
1213 reconstructPath(InitialState, Queue.top().second);
1214
Alexander Kornienko49149672013-05-10 11:56:10 +00001215 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1216 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001217
1218 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001219 }
1220
1221 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001222 std::deque<StateNode *> Path;
1223 // We do not need a break before the initial token.
1224 while (Current->Previous) {
1225 Path.push_front(Current);
1226 Current = Current->Previous;
1227 }
1228 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1229 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001230 unsigned Penalty = 0;
1231 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1232 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1233
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001234 DEBUG({
1235 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001236 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001237 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001238 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001239 }
1240 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001241 }
Daniel Jasper4b866272013-02-01 11:00:45 +00001242 }
1243
Manuel Klimekaf491072013-02-13 10:54:19 +00001244 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001245 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001246 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001247 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001248 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001249 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001250 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001251 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001252 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001253 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001254
1255 StateNode *Node = new (Allocator.Allocate())
1256 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001257 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1258 return;
1259
Daniel Jasperde0328a2013-08-16 11:20:30 +00001260 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001261
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001262 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1263 ++(*Count);
Daniel Jasper4b866272013-02-01 11:00:45 +00001264 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001265
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001266 /// \brief If the \p State's next token is an r_brace closing a nested block,
1267 /// format the nested block before it.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001268 ///
1269 /// Returns \c true if all children could be placed successfully and adapts
1270 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1271 /// creates changes using \c Whitespaces.
1272 ///
1273 /// The crucial idea here is that children always get formatted upon
1274 /// encountering the closing brace right after the nested block. Now, if we
1275 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1276 /// \c false), the entire block has to be kept on the same line (which is only
1277 /// possible if it fits on the line, only contains a single statement, etc.
1278 ///
1279 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1280 /// break after the "{", format all lines with correct indentation and the put
1281 /// the closing "}" on yet another new line.
1282 ///
1283 /// This enables us to keep the simple structure of the
1284 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1285 /// break or don't break.
1286 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1287 unsigned &Penalty) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001288 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001289 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1290 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1291 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001292 // The previous token does not open a block. Nothing to do. We don't
1293 // assert so that we can simply call this function for all tokens.
Daniel Jasper36c28ce2013-09-06 08:54:24 +00001294 return true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001295
1296 if (NewLine) {
Daniel Jasper58cb2ed2014-06-06 13:49:04 +00001297 int AdditionalIndent =
1298 State.FirstIndent - State.Line->Level * Style.IndentWidth;
Daniel Jasperb16b9692014-05-21 12:51:23 +00001299 if (State.Stack.size() < 2 ||
Daniel Jasper4b444492014-11-21 13:38:53 +00001300 !State.Stack[State.Stack.size() - 2].NestedBlockInlined) {
Daniel Jasperb16b9692014-05-21 12:51:23 +00001301 AdditionalIndent = State.Stack.back().Indent -
1302 Previous.Children[0]->Level * Style.IndentWidth;
1303 }
1304
Daniel Jasper9c199562013-11-28 15:58:55 +00001305 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1306 /*FixBadIndentation=*/true);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001307 return true;
1308 }
1309
Daniel Jasper56346192014-10-27 16:31:46 +00001310 if (Previous.Children[0]->First->MustBreakBefore)
1311 return false;
1312
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001313 // Cannot merge multiple statements into a single line.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001314 if (Previous.Children.size() > 1)
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001315 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001316
Daniel Jasper21397a32014-04-09 12:21:48 +00001317 // Cannot merge into one line if this line ends on a comment.
1318 if (Previous.is(tok::comment))
1319 return false;
1320
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001321 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001322 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001323 return false;
1324
Daniel Jasper98583d52014-04-15 08:28:06 +00001325 // If the child line exceeds the column limit, we wouldn't want to merge it.
1326 // We add +2 for the trailing " }".
1327 if (Style.ColumnLimit > 0 &&
1328 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
1329 Style.ColumnLimit)
1330 return false;
1331
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001332 if (!DryRun) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001333 Whitespaces->replaceWhitespace(
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001334 *Previous.Children[0]->First,
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001335 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001336 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001337 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001338 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001339
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001340 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001341 return true;
1342 }
1343
Daniel Jasperde0328a2013-08-16 11:20:30 +00001344 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001345 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001346 FormatStyle Style;
Daniel Jasper56f8b432013-11-06 23:12:09 +00001347 LineJoiner Joiner;
Manuel Klimekaf491072013-02-13 10:54:19 +00001348
1349 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperc359ad02014-04-15 08:13:47 +00001350
1351 // Cache to store the penalty of formatting a vector of AnnotatedLines
1352 // starting from a specific additional offset. Improves performance if there
1353 // are many nested blocks.
1354 std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
1355 unsigned> PenaltyCache;
Daniel Jasperf7935112012-12-03 18:12:45 +00001356};
1357
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001358class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001359public:
Daniel Jasper23376252014-09-09 14:37:39 +00001360 FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001361 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +00001362 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001363 Column(0), TrailingWhitespace(0), SourceMgr(SourceMgr), ID(ID),
1364 Style(Style), IdentTable(getFormattingLangOpts(Style)),
1365 Keywords(IdentTable), Encoding(Encoding), FirstInLineIndex(0),
1366 FormattingDisabled(false) {
Daniel Jasper23376252014-09-09 14:37:39 +00001367 Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
1368 getFormattingLangOpts(Style)));
1369 Lex->SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +00001370
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001371 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +00001372 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1373 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001374 }
1375
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001376 ArrayRef<FormatToken *> lex() {
1377 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +00001378 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001379 do {
1380 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001381 tryMergePreviousTokens();
Manuel Klimek68b03042014-04-14 09:14:11 +00001382 if (Tokens.back()->NewlinesBefore > 0)
1383 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001384 } while (Tokens.back()->Tok.isNot(tok::eof));
1385 return Tokens;
1386 }
1387
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001388 const AdditionalKeywords &getKeywords() { return Keywords; }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001389
1390private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001391 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001392 if (tryMerge_TMacro())
1393 return;
Manuel Klimek68b03042014-04-14 09:14:11 +00001394 if (tryMergeConflictMarkers())
1395 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001396
1397 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001398 if (tryMergeJSRegexLiteral())
1399 return;
Daniel Jasper23376252014-09-09 14:37:39 +00001400 if (tryMergeEscapeSequence())
1401 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001402
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001403 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1404 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1405 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1406 tok::greaterequal };
Daniel Jasper78214392014-05-19 07:27:02 +00001407 static tok::TokenKind JSRightArrow[] = { tok::equal, tok::greater };
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001408 // FIXME: We probably need to change token type to mimic operator with the
1409 // correct priority.
1410 if (tryMergeTokens(JSIdentity))
1411 return;
1412 if (tryMergeTokens(JSNotIdentity))
1413 return;
1414 if (tryMergeTokens(JSShiftEqual))
1415 return;
Daniel Jasper78214392014-05-19 07:27:02 +00001416 if (tryMergeTokens(JSRightArrow))
1417 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001418 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001419 }
1420
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001421 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1422 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001423 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001424
1425 SmallVectorImpl<FormatToken *>::const_iterator First =
1426 Tokens.end() - Kinds.size();
1427 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001428 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001429 unsigned AddLength = 0;
1430 for (unsigned i = 1; i < Kinds.size(); ++i) {
1431 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1432 First[i]->WhitespaceRange.getEnd())
1433 return false;
1434 AddLength += First[i]->TokenText.size();
1435 }
1436 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1437 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1438 First[0]->TokenText.size() + AddLength);
1439 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001440 return true;
1441 }
1442
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001443 // Tries to merge an escape sequence, i.e. a "\\" and the following
Alp Tokerc3f36af2014-05-15 01:35:53 +00001444 // character. Use e.g. inside JavaScript regex literals.
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001445 bool tryMergeEscapeSequence() {
1446 if (Tokens.size() < 2)
1447 return false;
1448 FormatToken *Previous = Tokens[Tokens.size() - 2];
Daniel Jasper49a9a282014-10-29 16:51:38 +00001449 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\")
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001450 return false;
Daniel Jasper49a9a282014-10-29 16:51:38 +00001451 ++Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001452 StringRef Text = Previous->TokenText;
Daniel Jasper49a9a282014-10-29 16:51:38 +00001453 Previous->TokenText = StringRef(Text.data(), Text.size() + 1);
1454 resetLexer(SourceMgr.getFileOffset(Tokens.back()->Tok.getLocation()) + 1);
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001455 Tokens.resize(Tokens.size() - 1);
Daniel Jasper49a9a282014-10-29 16:51:38 +00001456 Column = Previous->OriginalColumn + Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001457 return true;
1458 }
1459
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001460 // Try to determine whether the current token ends a JavaScript regex literal.
1461 // We heuristically assume that this is a regex literal if we find two
1462 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +00001463 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
1464 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001465 bool tryMergeJSRegexLiteral() {
Daniel Jasper23376252014-09-09 14:37:39 +00001466 if (Tokens.size() < 2)
1467 return false;
1468 // If a regex literal ends in "\//", this gets represented by an unknown
1469 // token "\" and a comment.
1470 bool MightEndWithEscapedSlash =
1471 Tokens.back()->is(tok::comment) &&
1472 Tokens.back()->TokenText.startswith("//") &&
1473 Tokens[Tokens.size() - 2]->TokenText == "\\";
1474 if (!MightEndWithEscapedSlash &&
1475 (Tokens.back()->isNot(tok::slash) ||
1476 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
1477 Tokens[Tokens.size() - 2]->TokenText == "\\")))
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001478 return false;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001479 unsigned TokenCount = 0;
1480 unsigned LastColumn = Tokens.back()->OriginalColumn;
1481 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
1482 ++TokenCount;
1483 if (I[0]->is(tok::slash) && I + 1 != E &&
1484 (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
1485 tok::exclaim, tok::l_square, tok::colon, tok::comma,
1486 tok::question, tok::kw_return) ||
1487 I[1]->isBinaryOperator())) {
Daniel Jasper23376252014-09-09 14:37:39 +00001488 if (MightEndWithEscapedSlash) {
Daniel Jasper23376252014-09-09 14:37:39 +00001489 // This regex literal ends in '\//'. Skip past the '//' of the last
1490 // token and re-start lexing from there.
Daniel Jasper49a9a282014-10-29 16:51:38 +00001491 SourceLocation Loc = Tokens.back()->Tok.getLocation();
1492 resetLexer(SourceMgr.getFileOffset(Loc) + 2);
Daniel Jasper23376252014-09-09 14:37:39 +00001493 }
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001494 Tokens.resize(Tokens.size() - TokenCount);
1495 Tokens.back()->Tok.setKind(tok::unknown);
1496 Tokens.back()->Type = TT_RegexLiteral;
1497 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
1498 return true;
1499 }
1500
1501 // There can't be a newline inside a regex literal.
1502 if (I[0]->NewlinesBefore > 0)
1503 return false;
1504 }
1505 return false;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001506 }
1507
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001508 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001509 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001510 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001511 FormatToken *Last = Tokens.back();
1512 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001513 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001514
1515 FormatToken *String = Tokens[Tokens.size() - 2];
1516 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001517 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001518
1519 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001520 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001521
1522 FormatToken *Macro = Tokens[Tokens.size() - 4];
1523 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001524 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001525
1526 const char *Start = Macro->TokenText.data();
1527 const char *End = Last->TokenText.data() + Last->TokenText.size();
1528 String->TokenText = StringRef(Start, End - Start);
1529 String->IsFirst = Macro->IsFirst;
1530 String->LastNewlineOffset = Macro->LastNewlineOffset;
1531 String->WhitespaceRange = Macro->WhitespaceRange;
1532 String->OriginalColumn = Macro->OriginalColumn;
1533 String->ColumnWidth = encoding::columnWidthWithTabs(
1534 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1535
1536 Tokens.pop_back();
1537 Tokens.pop_back();
1538 Tokens.pop_back();
1539 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001540 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001541 }
1542
Manuel Klimek68b03042014-04-14 09:14:11 +00001543 bool tryMergeConflictMarkers() {
1544 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1545 return false;
1546
1547 // Conflict lines look like:
1548 // <marker> <text from the vcs>
1549 // For example:
1550 // >>>>>>> /file/in/file/system at revision 1234
1551 //
1552 // We merge all tokens in a line that starts with a conflict marker
1553 // into a single token with a special token type that the unwrapped line
1554 // parser will use to correctly rebuild the underlying code.
1555
1556 FileID ID;
1557 // Get the position of the first token in the line.
1558 unsigned FirstInLineOffset;
1559 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1560 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1561 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1562 // Calculate the offset of the start of the current line.
1563 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1564 if (LineOffset == StringRef::npos) {
1565 LineOffset = 0;
1566 } else {
1567 ++LineOffset;
1568 }
1569
1570 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1571 StringRef LineStart;
1572 if (FirstSpace == StringRef::npos) {
1573 LineStart = Buffer.substr(LineOffset);
1574 } else {
1575 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1576 }
1577
1578 TokenType Type = TT_Unknown;
1579 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1580 Type = TT_ConflictStart;
1581 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1582 LineStart == "====") {
1583 Type = TT_ConflictAlternative;
1584 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1585 Type = TT_ConflictEnd;
1586 }
1587
1588 if (Type != TT_Unknown) {
1589 FormatToken *Next = Tokens.back();
1590
1591 Tokens.resize(FirstInLineIndex + 1);
1592 // We do not need to build a complete token here, as we will skip it
1593 // during parsing anyway (as we must not touch whitespace around conflict
1594 // markers).
1595 Tokens.back()->Type = Type;
1596 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1597
1598 Tokens.push_back(Next);
1599 return true;
1600 }
1601
1602 return false;
1603 }
1604
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001605 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001606 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001607 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +00001608 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001609 Token Greater = FormatTok->Tok;
1610 FormatTok = new (Allocator.Allocate()) FormatToken;
1611 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001612 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001613 FormatTok->Tok.getLocation().getLocWithOffset(1);
1614 FormatTok->WhitespaceRange =
1615 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001616 FormatTok->TokenText = ">";
Alexander Kornienko39856b72013-09-10 09:38:25 +00001617 FormatTok->ColumnWidth = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001618 GreaterStashed = false;
1619 return FormatTok;
1620 }
1621
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001622 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001623 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001624 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001625 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001626 FormatTok->IsFirst = IsFirstToken;
1627 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001628
1629 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001630 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001631 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001632 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1633 switch (FormatTok->TokenText[i]) {
1634 case '\n':
1635 ++FormatTok->NewlinesBefore;
1636 // FIXME: This is technically incorrect, as it could also
1637 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001638 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1639 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1640 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +00001641 FormatTok->HasUnescapedNewline = true;
1642 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1643 Column = 0;
1644 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001645 case '\r':
1646 case '\f':
1647 case '\v':
1648 Column = 0;
1649 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001650 case ' ':
1651 ++Column;
1652 break;
1653 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001654 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001655 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001656 case '\\':
1657 ++Column;
1658 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1659 FormatTok->TokenText[i + 1] != '\n'))
1660 FormatTok->Type = TT_ImplicitStringLiteral;
1661 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001662 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001663 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001664 ++Column;
1665 break;
1666 }
1667 }
1668
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001669 if (FormatTok->is(TT_ImplicitStringLiteral))
Daniel Jasper877615c2013-10-11 19:45:02 +00001670 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001671 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001672
Daniel Jasper8369aa52013-07-16 20:28:33 +00001673 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001674 }
Manuel Klimekef920692013-01-07 07:56:50 +00001675
Manuel Klimek1abf7892013-01-04 23:34:14 +00001676 // In case the token starts with escaped newlines, we want to
1677 // take them into account as whitespace - this pattern is quite frequent
1678 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001679 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001680 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1681 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001682 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001683 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001684 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001685 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001686 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001687
1688 FormatTok->WhitespaceRange = SourceRange(
1689 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1690
Manuel Klimek31c85922013-08-29 15:21:40 +00001691 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001692
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001693 TrailingWhitespace = 0;
1694 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001695 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001696 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001697 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001698 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001699 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001700 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001701 FormatTok->Tok.setIdentifierInfo(&Info);
1702 FormatTok->Tok.setKind(Info.getTokenID());
Daniel Jasperfe2cf662014-11-19 14:11:11 +00001703 if (Style.Language == FormatStyle::LK_Java &&
1704 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete)) {
1705 FormatTok->Tok.setKind(tok::identifier);
1706 FormatTok->Tok.setIdentifierInfo(nullptr);
1707 }
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001708 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001709 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001710 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001711 GreaterStashed = true;
1712 }
1713
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001714 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001715
Alexander Kornienko39856b72013-09-10 09:38:25 +00001716 StringRef Text = FormatTok->TokenText;
1717 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001718 if (FirstNewlinePos == StringRef::npos) {
1719 // FIXME: ColumnWidth actually depends on the start column, we need to
1720 // take this into account when the token is moved.
1721 FormatTok->ColumnWidth =
1722 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1723 Column += FormatTok->ColumnWidth;
1724 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001725 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001726 // FIXME: ColumnWidth actually depends on the start column, we need to
1727 // take this into account when the token is moved.
1728 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1729 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1730
Alexander Kornienko39856b72013-09-10 09:38:25 +00001731 // The last line of the token always starts in column 0.
1732 // Thus, the length can be precomputed even in the presence of tabs.
1733 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1734 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1735 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001736 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001737 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001738
Daniel Jaspere1e43192014-04-01 12:55:11 +00001739 FormatTok->IsForEachMacro =
1740 std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1741 FormatTok->Tok.getIdentifierInfo());
1742
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001743 return FormatTok;
1744 }
1745
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001746 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001747 bool IsFirstToken;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001748 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001749 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001750 unsigned TrailingWhitespace;
Daniel Jasper23376252014-09-09 14:37:39 +00001751 std::unique_ptr<Lexer> Lex;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001752 SourceManager &SourceMgr;
Daniel Jasper23376252014-09-09 14:37:39 +00001753 FileID ID;
Manuel Klimek31c85922013-08-29 15:21:40 +00001754 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001755 IdentifierTable IdentTable;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001756 AdditionalKeywords Keywords;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001757 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001758 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001759 // Index (in 'Tokens') of the last token that starts a new line.
1760 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001761 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001762 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001763
NAKAMURA Takumi7160c4d2014-08-06 16:53:13 +00001764 bool FormattingDisabled;
Daniel Jasper471894432014-08-06 13:40:26 +00001765
Daniel Jasper8369aa52013-07-16 20:28:33 +00001766 void readRawToken(FormatToken &Tok) {
Daniel Jasper23376252014-09-09 14:37:39 +00001767 Lex->LexFromRawLexer(Tok.Tok);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001768 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1769 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001770 // For formatting, treat unterminated string literals like normal string
1771 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001772 if (Tok.is(tok::unknown)) {
1773 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1774 Tok.Tok.setKind(tok::string_literal);
1775 Tok.IsUnterminatedLiteral = true;
1776 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1777 Tok.TokenText == "''") {
1778 Tok.Tok.setKind(tok::char_constant);
1779 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001780 }
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001781
1782 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1783 Tok.TokenText == "/* clang-format on */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001784 FormattingDisabled = false;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001785 }
1786
Daniel Jasper471894432014-08-06 13:40:26 +00001787 Tok.Finalized = FormattingDisabled;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001788
1789 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1790 Tok.TokenText == "/* clang-format off */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001791 FormattingDisabled = true;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001792 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001793 }
Daniel Jasper49a9a282014-10-29 16:51:38 +00001794
1795 void resetLexer(unsigned Offset) {
1796 StringRef Buffer = SourceMgr.getBufferData(ID);
1797 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1798 getFormattingLangOpts(Style), Buffer.begin(),
1799 Buffer.begin() + Offset, Buffer.end()));
1800 Lex->SetKeepWhitespaceMode(true);
1801 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001802};
1803
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001804static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1805 switch (Language) {
1806 case FormatStyle::LK_Cpp:
1807 return "C++";
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001808 case FormatStyle::LK_Java:
1809 return "Java";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001810 case FormatStyle::LK_JavaScript:
1811 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001812 case FormatStyle::LK_Proto:
1813 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001814 default:
1815 return "Unknown";
1816 }
1817}
1818
Daniel Jasperf7935112012-12-03 18:12:45 +00001819class Formatter : public UnwrappedLineConsumer {
1820public:
Daniel Jasper23376252014-09-09 14:37:39 +00001821 Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001822 ArrayRef<CharSourceRange> Ranges)
Daniel Jasper23376252014-09-09 14:37:39 +00001823 : Style(Style), ID(ID), SourceMgr(SourceMgr),
1824 Whitespaces(SourceMgr, Style,
1825 inputUsesCRLF(SourceMgr.getBufferData(ID))),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001826 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Daniel Jasper23376252014-09-09 14:37:39 +00001827 Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001828 DEBUG(llvm::dbgs() << "File encoding: "
1829 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1830 : "unknown")
1831 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001832 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1833 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001834 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001835
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001836 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001837 tooling::Replacements Result;
Daniel Jasper23376252014-09-09 14:37:39 +00001838 FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001839
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001840 UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
1841 *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001842 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001843 assert(UnwrappedLines.rbegin()->empty());
1844 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1845 ++Run) {
1846 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1847 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1848 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1849 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1850 }
1851 tooling::Replacements RunResult =
1852 format(AnnotatedLines, StructuralError, Tokens);
1853 DEBUG({
1854 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1855 for (tooling::Replacements::iterator I = RunResult.begin(),
1856 E = RunResult.end();
1857 I != E; ++I) {
1858 llvm::dbgs() << I->toString() << "\n";
1859 }
1860 });
1861 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1862 delete AnnotatedLines[i];
1863 }
1864 Result.insert(RunResult.begin(), RunResult.end());
1865 Whitespaces.reset();
1866 }
1867 return Result;
1868 }
1869
1870 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1871 bool StructuralError, FormatTokenLexer &Tokens) {
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001872 TokenAnnotator Annotator(Style, Tokens.getKeywords());
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001873 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001874 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001875 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001876 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001877 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001878 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001879 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001880 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001881
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001882 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001883 ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
1884 Whitespaces, Encoding,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001885 BinPackInconclusiveFunctions);
Daniel Jasper5500f612013-11-25 11:08:59 +00001886 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001887 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001888 return Whitespaces.generateReplacements();
1889 }
1890
1891private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001892 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001893 // Returns \c true if at least one line between I and E or one of their
1894 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001895 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1896 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1897 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001898 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001899 while (I != E) {
1900 AnnotatedLine *Line = *I;
1901 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1902
1903 // If a line is part of a preprocessor directive, it needs to be formatted
1904 // if any token within the directive is affected.
1905 if (Line->InPPDirective) {
1906 FormatToken *Last = Line->Last;
1907 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1908 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1909 Last = (*PPEnd)->Last;
1910 ++PPEnd;
1911 }
1912
1913 if (affectsTokenRange(*Line->First, *Last,
1914 /*IncludeLeadingNewlines=*/false)) {
1915 SomeLineAffected = true;
1916 markAllAsAffected(I, PPEnd);
1917 }
1918 I = PPEnd;
1919 continue;
1920 }
1921
Daniel Jasper38c82402013-11-29 09:27:43 +00001922 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001923 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001924
Daniel Jasper38c82402013-11-29 09:27:43 +00001925 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001926 ++I;
1927 }
1928 return SomeLineAffected;
1929 }
1930
Daniel Jasper9c199562013-11-28 15:58:55 +00001931 // Determines whether 'Line' is affected by the SourceRanges given as input.
1932 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001933 bool nonPPLineAffected(AnnotatedLine *Line,
1934 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001935 bool SomeLineAffected = false;
1936 Line->ChildrenAffected =
1937 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1938 if (Line->ChildrenAffected)
1939 SomeLineAffected = true;
1940
1941 // Stores whether one of the line's tokens is directly affected.
1942 bool SomeTokenAffected = false;
1943 // Stores whether we need to look at the leading newlines of the next token
1944 // in order to determine whether it was affected.
1945 bool IncludeLeadingNewlines = false;
1946
1947 // Stores whether the first child line of any of this line's tokens is
1948 // affected.
1949 bool SomeFirstChildAffected = false;
1950
1951 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1952 // Determine whether 'Tok' was affected.
1953 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1954 SomeTokenAffected = true;
1955
1956 // Determine whether the first child of 'Tok' was affected.
1957 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1958 SomeFirstChildAffected = true;
1959
1960 IncludeLeadingNewlines = Tok->Children.empty();
1961 }
1962
1963 // Was this line moved, i.e. has it previously been on the same line as an
1964 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001965 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1966 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001967
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001968 bool IsContinuedComment =
1969 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1970 Line->First->NewlinesBefore < 2 && PreviousLine &&
1971 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001972
1973 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1974 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001975 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001976 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001977 }
1978 return SomeLineAffected;
1979 }
1980
Daniel Jasper5500f612013-11-25 11:08:59 +00001981 // Marks all lines between I and E as well as all their children as affected.
1982 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1983 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1984 while (I != E) {
1985 (*I)->Affected = true;
1986 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1987 ++I;
1988 }
1989 }
1990
1991 // Returns true if the range from 'First' to 'Last' intersects with one of the
1992 // input ranges.
1993 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1994 bool IncludeLeadingNewlines) {
1995 SourceLocation Start = First.WhitespaceRange.getBegin();
1996 if (!IncludeLeadingNewlines)
1997 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001998 SourceLocation End = Last.getStartOfNonWhitespace();
Daniel Jasperac29eac2014-10-29 23:40:50 +00001999 End = End.getLocWithOffset(Last.TokenText.size());
Daniel Jasper5500f612013-11-25 11:08:59 +00002000 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
2001 return affectsCharSourceRange(Range);
2002 }
2003
2004 // Returns true if one of the input ranges intersect the leading empty lines
2005 // before 'Tok'.
2006 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
2007 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
2008 Tok.WhitespaceRange.getBegin(),
2009 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
2010 return affectsCharSourceRange(EmptyLineRange);
2011 }
2012
2013 // Returns true if 'Range' intersects with one of the input ranges.
2014 bool affectsCharSourceRange(const CharSourceRange &Range) {
2015 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
2016 E = Ranges.end();
2017 I != E; ++I) {
2018 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
2019 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
2020 return true;
2021 }
2022 return false;
2023 }
2024
Alexander Kornienko9e649af2013-09-11 12:25:57 +00002025 static bool inputUsesCRLF(StringRef Text) {
2026 return Text.count('\r') * 2 > Text.count('\n');
2027 }
2028
Manuel Klimek71814b42013-10-11 21:25:45 +00002029 void
2030 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002031 unsigned CountBoundToVariable = 0;
2032 unsigned CountBoundToType = 0;
2033 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002034 bool HasBinPackedFunction = false;
2035 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002036 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002037 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002038 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002039 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00002040 while (Tok->Next) {
Daniel Jaspera98b7b02014-11-25 10:05:17 +00002041 if (Tok->is(TT_PointerOrReference)) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00002042 bool SpacesBefore =
2043 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
2044 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
2045 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002046 if (SpacesBefore && !SpacesAfter)
2047 ++CountBoundToVariable;
2048 else if (!SpacesBefore && SpacesAfter)
2049 ++CountBoundToType;
2050 }
2051
Daniel Jasperfba84ff2013-10-12 05:16:06 +00002052 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
Daniel Jaspera98b7b02014-11-25 10:05:17 +00002053 if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
Daniel Jasperfba84ff2013-10-12 05:16:06 +00002054 HasCpp03IncompatibleFormat = true;
Daniel Jaspera98b7b02014-11-25 10:05:17 +00002055 if (Tok->is(TT_TemplateCloser) &&
2056 Tok->Previous->is(TT_TemplateCloser))
Daniel Jasperfba84ff2013-10-12 05:16:06 +00002057 HasCpp03IncompatibleFormat = true;
2058 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002059
2060 if (Tok->PackingKind == PPK_BinPacked)
2061 HasBinPackedFunction = true;
2062 if (Tok->PackingKind == PPK_OnePerLine)
2063 HasOnePerLineFunction = true;
2064
Manuel Klimek6e6310e2013-05-29 14:47:47 +00002065 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002066 }
2067 }
Daniel Jasper553d4872014-06-17 12:40:34 +00002068 if (Style.DerivePointerAlignment) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002069 if (CountBoundToType > CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00002070 Style.PointerAlignment = FormatStyle::PAS_Left;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002071 else if (CountBoundToType < CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00002072 Style.PointerAlignment = FormatStyle::PAS_Right;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002073 }
2074 if (Style.Standard == FormatStyle::LS_Auto) {
2075 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
2076 : FormatStyle::LS_Cpp03;
2077 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002078 BinPackInconclusiveFunctions =
2079 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002080 }
2081
Craig Topperfb6b25b2014-03-15 04:29:04 +00002082 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00002083 assert(!UnwrappedLines.empty());
2084 UnwrappedLines.back().push_back(TheLine);
2085 }
2086
Craig Topperfb6b25b2014-03-15 04:29:04 +00002087 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00002088 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00002089 }
2090
2091 FormatStyle Style;
Daniel Jasper23376252014-09-09 14:37:39 +00002092 FileID ID;
Daniel Jasperf7935112012-12-03 18:12:45 +00002093 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00002094 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00002095 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00002096 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00002097
2098 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002099 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00002100};
2101
Craig Topperaf35e852013-06-30 22:29:28 +00002102} // end anonymous namespace
2103
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00002104tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
2105 SourceManager &SourceMgr,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002106 ArrayRef<CharSourceRange> Ranges) {
Daniel Jasper23376252014-09-09 14:37:39 +00002107 if (Style.DisableFormat)
2108 return tooling::Replacements();
2109 return reformat(Style, SourceMgr,
2110 SourceMgr.getFileID(Lex.getSourceLocation()), Ranges);
2111}
Daniel Jasperc64b09a2014-05-22 15:12:22 +00002112
Daniel Jasper23376252014-09-09 14:37:39 +00002113tooling::Replacements reformat(const FormatStyle &Style,
2114 SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002115 ArrayRef<CharSourceRange> Ranges) {
Daniel Jasper23376252014-09-09 14:37:39 +00002116 if (Style.DisableFormat)
2117 return tooling::Replacements();
2118 Formatter formatter(Style, SourceMgr, ID, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00002119 return formatter.format();
2120}
2121
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002122tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002123 ArrayRef<tooling::Range> Ranges,
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002124 StringRef FileName) {
Daniel Jasper23376252014-09-09 14:37:39 +00002125 if (Style.DisableFormat)
2126 return tooling::Replacements();
2127
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002128 FileManager Files((FileSystemOptions()));
2129 DiagnosticsEngine Diagnostics(
2130 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2131 new DiagnosticOptions);
2132 SourceManager SourceMgr(Diagnostics, Files);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00002133 std::unique_ptr<llvm::MemoryBuffer> Buf =
2134 llvm::MemoryBuffer::getMemBuffer(Code, FileName);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002135 const clang::FileEntry *Entry =
2136 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
David Blaikie49cc3182014-08-27 20:54:45 +00002137 SourceMgr.overrideFileContents(Entry, std::move(Buf));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002138 FileID ID =
2139 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002140 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
2141 std::vector<CharSourceRange> CharRanges;
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002142 for (const tooling::Range &Range : Ranges) {
2143 SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
2144 SourceLocation End = Start.getLocWithOffset(Range.getLength());
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002145 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
2146 }
Daniel Jasper23376252014-09-09 14:37:39 +00002147 return reformat(Style, SourceMgr, ID, CharRanges);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002148}
2149
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002150LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002151 LangOptions LangOpts;
2152 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002153 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2154 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00002155 LangOpts.LineComment = 1;
Daniel Jasper30a24062014-11-14 09:02:28 +00002156 bool AlternativeOperators = Style.Language != FormatStyle::LK_JavaScript &&
2157 Style.Language != FormatStyle::LK_Java;
2158 LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002159 LangOpts.Bool = 1;
2160 LangOpts.ObjC1 = 1;
2161 LangOpts.ObjC2 = 1;
2162 return LangOpts;
2163}
2164
Edwin Vaned544aa72013-09-30 13:31:48 +00002165const char *StyleOptionHelpDescription =
2166 "Coding style, currently supports:\n"
2167 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
2168 "Use -style=file to load style configuration from\n"
2169 ".clang-format file located in one of the parent\n"
2170 "directories of the source file (or current\n"
2171 "directory for stdin).\n"
2172 "Use -style=\"{key: value, ...}\" to set specific\n"
2173 "parameters, e.g.:\n"
2174 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
2175
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002176static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00002177 if (FileName.endswith(".java")) {
2178 return FormatStyle::LK_Java;
2179 } else if (FileName.endswith_lower(".js")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002180 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00002181 } else if (FileName.endswith_lower(".proto") ||
2182 FileName.endswith_lower(".protodevel")) {
2183 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002184 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002185 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002186}
2187
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002188FormatStyle getStyle(StringRef StyleName, StringRef FileName,
2189 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002190 FormatStyle Style = getLLVMStyle();
2191 Style.Language = getLanguageByFileName(FileName);
2192 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002193 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
2194 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002195 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002196 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002197
2198 if (StyleName.startswith("{")) {
2199 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00002200 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002201 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
2202 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00002203 }
2204 return Style;
2205 }
2206
2207 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002208 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00002209 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
2210 << " style\n";
2211 return Style;
2212 }
2213
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002214 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002215 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00002216 SmallString<128> Path(FileName);
2217 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002218 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00002219 Directory = llvm::sys::path::parent_path(Directory)) {
2220 if (!llvm::sys::fs::is_directory(Directory))
2221 continue;
2222 SmallString<128> ConfigFile(Directory);
2223
2224 llvm::sys::path::append(ConfigFile, ".clang-format");
2225 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2226 bool IsFile = false;
2227 // Ignore errors from is_regular_file: we only need to know if we can read
2228 // the file or not.
2229 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2230
2231 if (!IsFile) {
2232 // Try _clang-format too, since dotfiles are not commonly used on Windows.
2233 ConfigFile = Directory;
2234 llvm::sys::path::append(ConfigFile, "_clang-format");
2235 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2236 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2237 }
2238
2239 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002240 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
2241 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
2242 if (std::error_code EC = Text.getError()) {
2243 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002244 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002245 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002246 if (std::error_code ec =
2247 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00002248 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002249 if (!UnsuitableConfigFiles.empty())
2250 UnsuitableConfigFiles.append(", ");
2251 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002252 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002253 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002254 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2255 << "\n";
2256 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002257 }
2258 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2259 return Style;
2260 }
2261 }
2262 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
2263 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002264 if (!UnsuitableConfigFiles.empty()) {
2265 llvm::errs() << "Configuration file(s) do(es) not support "
2266 << getLanguageName(Style.Language) << ": "
2267 << UnsuitableConfigFiles << "\n";
2268 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002269 return Style;
2270}
2271
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002272} // namespace format
2273} // namespace clang