blob: 92086461d489aee9b5bc6744d226f7a517110731 [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);
Daniel Jasperf7db4332013-01-29 16:03:49 +0000438 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000439 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000440 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000441 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000442 ChromiumStyle.BinPackParameters = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000443 ChromiumStyle.DerivePointerAlignment = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000444 return ChromiumStyle;
445}
446
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000447FormatStyle getMozillaStyle() {
448 FormatStyle MozillaStyle = getLLVMStyle();
449 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000450 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000451 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000452 MozillaStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000453 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000454 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000455 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
456 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000457 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000458 MozillaStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000459 return MozillaStyle;
460}
461
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000462FormatStyle getWebKitStyle() {
463 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000464 Style.AccessModifierOffset = -4;
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000465 Style.AlignAfterOpenBracket = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000466 Style.AlignTrailingComments = false;
Daniel Jasperac043c92014-09-15 11:11:00 +0000467 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000468 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000469 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000470 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000471 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000472 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000473 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000474 Style.ObjCBlockIndentWidth = 4;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000475 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000476 Style.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000477 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000478 return Style;
479}
480
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000481FormatStyle getGNUStyle() {
482 FormatStyle Style = getLLVMStyle();
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000483 Style.AlwaysBreakAfterDefinitionReturnType = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000484 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000485 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000486 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000487 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000488 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000489 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000490 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000491 return Style;
492}
493
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000494FormatStyle getNoStyle() {
495 FormatStyle NoStyle = getLLVMStyle();
496 NoStyle.DisableFormat = true;
497 return NoStyle;
498}
499
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000500bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
501 FormatStyle *Style) {
502 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000503 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000504 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000505 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000506 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000507 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000508 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000509 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000510 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000511 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000512 } else if (Name.equals_lower("gnu")) {
513 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000514 } else if (Name.equals_lower("none")) {
515 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000516 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000517 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000518 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000519
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000520 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000521 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000522}
523
Rafael Espindolac0809172014-06-12 14:02:15 +0000524std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000525 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000526 FormatStyle::LanguageKind Language = Style->Language;
527 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000528 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000529 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000530
531 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000532 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000533 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
534 // values for the fields, keys for which are missing from the configuration.
535 // Mapping also uses the context to get the language to find the correct
536 // base style.
537 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000538 Input >> Styles;
539 if (Input.error())
540 return Input.error();
541
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000542 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000543 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000544 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000545 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000546 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000547 for (unsigned j = 0; j < i; ++j) {
548 if (Styles[i].Language == Styles[j].Language) {
549 DEBUG(llvm::dbgs()
550 << "Duplicate languages in the config file on positions " << j
551 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000552 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000553 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000554 }
555 }
556 // Look for a suitable configuration starting from the end, so we can
557 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000558 // configuration (which can only be at slot 0) after it.
559 for (int i = Styles.size() - 1; i >= 0; --i) {
560 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000561 Styles[i].Language == FormatStyle::LK_None) {
562 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000563 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000564 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000565 }
566 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000567 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000568}
569
570std::string configurationAsText(const FormatStyle &Style) {
571 std::string Text;
572 llvm::raw_string_ostream Stream(Text);
573 llvm::yaml::Output Output(Stream);
574 // We use the same mapping method for input and output, so we need a non-const
575 // reference here.
576 FormatStyle NonConstStyle = Style;
577 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000578 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000579}
580
Craig Topperaf35e852013-06-30 22:29:28 +0000581namespace {
582
Nico Weber34272652014-11-13 16:25:37 +0000583bool startsExternCBlock(const AnnotatedLine &Line) {
584 const FormatToken *Next = Line.First->getNextNonComment();
585 const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr;
586 return Line.First->is(tok::kw_extern) && Next && Next->isStringLiteral() &&
587 NextNext && NextNext->is(tok::l_brace);
588}
589
Daniel Jasperde0328a2013-08-16 11:20:30 +0000590class NoColumnLimitFormatter {
591public:
Daniel Jasperf110e202013-08-21 08:39:01 +0000592 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000593
594 /// \brief Formats the line starting at \p State, simply keeping all of the
595 /// input's line breaking decisions.
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000596 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000597 LineState State =
598 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Craig Topper2145bc02014-05-09 08:15:10 +0000599 while (State.NextToken) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000600 bool Newline =
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000601 Indenter->mustBreak(State) ||
Daniel Jasperde0328a2013-08-16 11:20:30 +0000602 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
603 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
604 }
605 }
Daniel Jasperf110e202013-08-21 08:39:01 +0000606
Daniel Jasperde0328a2013-08-16 11:20:30 +0000607private:
608 ContinuationIndenter *Indenter;
609};
610
Daniel Jasper56f8b432013-11-06 23:12:09 +0000611class LineJoiner {
612public:
613 LineJoiner(const FormatStyle &Style) : Style(Style) {}
614
615 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
616 unsigned
617 tryFitMultipleLinesInOne(unsigned Indent,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000618 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000619 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
620 // We can never merge stuff if there are trailing line comments.
Daniel Jasper234379f2013-12-24 13:31:25 +0000621 const AnnotatedLine *TheLine = *I;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000622 if (TheLine->Last->is(TT_LineComment))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000623 return 0;
624
Alexander Kornienkoecc232d2013-12-04 13:25:26 +0000625 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
626 return 0;
627
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000628 unsigned Limit =
629 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000630 // If we already exceed the column limit, we set 'Limit' to 0. The different
631 // tryMerge..() functions can then decide whether to still do merging.
632 Limit = TheLine->Last->TotalLength > Limit
633 ? 0
634 : Limit - TheLine->Last->TotalLength;
635
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000636 if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000637 return 0;
638
Daniel Jasperd74cf402014-04-08 12:46:38 +0000639 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
640 // If necessary, change to something smarter.
641 bool MergeShortFunctions =
642 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
Daniel Jasper9e709352014-11-26 10:43:58 +0000643 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty &&
644 I[1]->First->is(tok::r_brace)) ||
Daniel Jasperd74cf402014-04-08 12:46:38 +0000645 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
646 TheLine->Level != 0);
647
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000648 if (TheLine->Last->is(TT_FunctionLBrace) &&
Daniel Jasper234379f2013-12-24 13:31:25 +0000649 TheLine->First != TheLine->Last) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000650 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000651 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000652 if (TheLine->Last->is(tok::l_brace)) {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000653 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000654 ? tryMergeSimpleBlock(I, E, Limit)
655 : 0;
656 }
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000657 if (I[1]->First->is(TT_FunctionLBrace) &&
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000658 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
Alp Tokerba5b4dc2013-12-30 02:06:29 +0000659 // Check for Limit <= 2 to account for the " {".
Daniel Jasper234379f2013-12-24 13:31:25 +0000660 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
661 return 0;
662 Limit -= 2;
663
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000664 unsigned MergedLines = 0;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000665 if (MergeShortFunctions) {
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000666 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
667 // If we managed to merge the block, count the function header, which is
668 // on a separate line.
669 if (MergedLines > 0)
670 ++MergedLines;
671 }
672 return MergedLines;
673 }
674 if (TheLine->First->is(tok::kw_if)) {
675 return Style.AllowShortIfStatementsOnASingleLine
676 ? tryMergeSimpleControlStatement(I, E, Limit)
677 : 0;
678 }
679 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
680 return Style.AllowShortLoopsOnASingleLine
681 ? tryMergeSimpleControlStatement(I, E, Limit)
682 : 0;
683 }
Daniel Jasperb87899b2014-09-10 13:11:45 +0000684 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
685 return Style.AllowShortCaseLabelsOnASingleLine
686 ? tryMergeShortCaseLabels(I, E, Limit)
687 : 0;
688 }
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000689 if (TheLine->InPPDirective &&
690 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000691 return tryMergeSimplePPDirective(I, E, Limit);
692 }
693 return 0;
694 }
695
696private:
697 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000698 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000699 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
700 unsigned Limit) {
701 if (Limit == 0)
702 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000703 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000704 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000705 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000706 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000707 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000708 return 0;
709 return 1;
710 }
711
712 unsigned tryMergeSimpleControlStatement(
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000713 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000714 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
715 if (Limit == 0)
716 return 0;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000717 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
718 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
Daniel Jasper17605d32014-05-14 09:33:35 +0000719 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000720 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000721 if (I[1]->InPPDirective != (*I)->InPPDirective ||
722 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000723 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000724 Limit = limitConsideringMacros(I + 1, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000725 AnnotatedLine &Line = **I;
726 if (Line.Last->isNot(tok::r_paren))
727 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000728 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000729 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000730 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000731 tok::kw_while, TT_LineComment))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000732 return 0;
733 // Only inline simple if's (no nested if or else).
734 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000735 I[2]->First->is(tok::kw_else))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000736 return 0;
737 return 1;
738 }
739
Daniel Jasperb87899b2014-09-10 13:11:45 +0000740 unsigned tryMergeShortCaseLabels(
741 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
742 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
743 if (Limit == 0 || I + 1 == E ||
744 I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
745 return 0;
746 unsigned NumStmts = 0;
747 unsigned Length = 0;
Daniel Jasper79f226e2014-11-23 21:45:03 +0000748 bool InPPDirective = I[0]->InPPDirective;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000749 for (; NumStmts < 3; ++NumStmts) {
750 if (I + 1 + NumStmts == E)
751 break;
752 const AnnotatedLine *Line = I[1 + NumStmts];
Daniel Jasper79f226e2014-11-23 21:45:03 +0000753 if (Line->InPPDirective != InPPDirective)
754 break;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000755 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
756 break;
757 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
Daniel Jasperd081e882014-11-21 12:36:25 +0000758 tok::kw_while, tok::comment))
Daniel Jasperb87899b2014-09-10 13:11:45 +0000759 return 0;
760 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
761 }
762 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
763 return 0;
764 return NumStmts;
765 }
766
Daniel Jasper56f8b432013-11-06 23:12:09 +0000767 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000768 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000769 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
770 unsigned Limit) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000771 AnnotatedLine &Line = **I;
Daniel Jasper17605d32014-05-14 09:33:35 +0000772
773 // Don't merge ObjC @ keywords and methods.
Daniel Jasper9e709352014-11-26 10:43:58 +0000774 if (Style.Language != FormatStyle::LK_Java &&
775 Line.First->isOneOf(tok::at, tok::minus, tok::plus))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000776 return 0;
777
Daniel Jasper17605d32014-05-14 09:33:35 +0000778 // Check that the current line allows merging. This depends on whether we
779 // are in a control flow statements as well as several style flags.
780 if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
781 return 0;
782 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
783 tok::kw_catch, tok::kw_for, tok::r_brace)) {
784 if (!Style.AllowShortBlocksOnASingleLine)
785 return 0;
786 if (!Style.AllowShortIfStatementsOnASingleLine &&
787 Line.First->is(tok::kw_if))
788 return 0;
789 if (!Style.AllowShortLoopsOnASingleLine &&
790 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
791 return 0;
792 // FIXME: Consider an option to allow short exception handling clauses on
793 // a single line.
794 if (Line.First->isOneOf(tok::kw_try, tok::kw_catch))
795 return 0;
796 }
797
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000798 FormatToken *Tok = I[1]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000799 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Craig Topper2145bc02014-05-09 08:15:10 +0000800 (Tok->getNextNonComment() == nullptr ||
Daniel Jasper56f8b432013-11-06 23:12:09 +0000801 Tok->getNextNonComment()->is(tok::semi))) {
802 // We merge empty blocks even if the line exceeds the column limit.
803 Tok->SpacesRequiredBefore = 0;
804 Tok->CanBreakBefore = true;
805 return 1;
Nico Weber34272652014-11-13 16:25:37 +0000806 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace) &&
807 !startsExternCBlock(Line)) {
Daniel Jasper79dffb42014-05-07 09:48:30 +0000808 // We don't merge short records.
809 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
810 return 0;
811
Daniel Jasper56f8b432013-11-06 23:12:09 +0000812 // Check that we still have three lines and they fit into the limit.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000813 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000814 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000815 Limit = limitConsideringMacros(I + 2, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000816
817 if (!nextTwoLinesFitInto(I, Limit))
818 return 0;
819
820 // Second, check that the next line does not contain any braces - if it
821 // does, readability declines when putting it into a single line.
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000822 if (I[1]->Last->is(TT_LineComment))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000823 return 0;
824 do {
Daniel Jasperbd630732014-05-22 13:25:26 +0000825 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000826 return 0;
827 Tok = Tok->Next;
Craig Topper2145bc02014-05-09 08:15:10 +0000828 } while (Tok);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000829
Daniel Jasper79dffb42014-05-07 09:48:30 +0000830 // Last, check that the third line starts with a closing brace.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000831 Tok = I[2]->First;
Daniel Jasper79dffb42014-05-07 09:48:30 +0000832 if (Tok->isNot(tok::r_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000833 return 0;
834
835 return 2;
836 }
837 return 0;
838 }
839
Daniel Jasper64989962014-02-07 13:45:27 +0000840 /// Returns the modified column limit for \p I if it is inside a macro and
841 /// needs a trailing '\'.
842 unsigned
Daniel Jaspera0407742014-02-11 10:08:11 +0000843 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper64989962014-02-07 13:45:27 +0000844 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
845 unsigned Limit) {
846 if (I[0]->InPPDirective && I + 1 != E &&
847 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
848 return Limit < 2 ? 0 : Limit - 2;
849 }
850 return Limit;
851 }
852
Daniel Jasper56f8b432013-11-06 23:12:09 +0000853 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
854 unsigned Limit) {
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000855 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
856 return false;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000857 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000858 }
859
Daniel Jasper234379f2013-12-24 13:31:25 +0000860 bool containsMustBreak(const AnnotatedLine *Line) {
861 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
862 if (Tok->MustBreakBefore)
863 return true;
864 }
865 return false;
866 }
867
Daniel Jasper56f8b432013-11-06 23:12:09 +0000868 const FormatStyle &Style;
869};
870
Daniel Jasperf7935112012-12-03 18:12:45 +0000871class UnwrappedLineFormatter {
872public:
Daniel Jasper5500f612013-11-25 11:08:59 +0000873 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000874 WhitespaceManager *Whitespaces,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000875 const FormatStyle &Style)
Daniel Jasper5500f612013-11-25 11:08:59 +0000876 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
877 Joiner(Style) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000878
Daniel Jasper56f8b432013-11-06 23:12:09 +0000879 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper9c199562013-11-28 15:58:55 +0000880 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Daniel Jasperc359ad02014-04-15 08:13:47 +0000881 // Try to look up already computed penalty in DryRun-mode.
NAKAMURA Takumi22059522014-04-15 23:29:04 +0000882 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
883 &Lines, AdditionalIndent);
Daniel Jasperc359ad02014-04-15 08:13:47 +0000884 auto CacheIt = PenaltyCache.find(CacheKey);
885 if (DryRun && CacheIt != PenaltyCache.end())
886 return CacheIt->second;
887
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000888 assert(!Lines.empty());
889 unsigned Penalty = 0;
890 std::vector<int> IndentForLevel;
891 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
892 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Craig Topper2145bc02014-05-09 08:15:10 +0000893 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000894 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
895 E = Lines.end();
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000896 I != E; ++I) {
897 const AnnotatedLine &TheLine = **I;
898 const FormatToken *FirstTok = TheLine.First;
899 int Offset = getIndentOffset(*FirstTok);
900
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000901 // Determine indent and try to merge multiple unwrapped lines.
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000902 unsigned Indent;
903 if (TheLine.InPPDirective) {
904 Indent = TheLine.Level * Style.IndentWidth;
905 } else {
906 while (IndentForLevel.size() <= TheLine.Level)
907 IndentForLevel.push_back(-1);
908 IndentForLevel.resize(TheLine.Level + 1);
909 Indent = getIndent(IndentForLevel, TheLine.Level);
910 }
911 unsigned LevelIndent = Indent;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000912 if (static_cast<int>(Indent) + Offset >= 0)
913 Indent += Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000914
915 // Merge multiple lines if possible.
Daniel Jasper56f8b432013-11-06 23:12:09 +0000916 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
Alexander Kornienko31e95542013-12-04 12:21:08 +0000917 if (MergedLines > 0 && Style.ColumnLimit == 0) {
918 // Disallow line merging if there is a break at the start of one of the
919 // input lines.
920 for (unsigned i = 0; i < MergedLines; ++i) {
921 if (I[i + 1]->First->NewlinesBefore > 0)
922 MergedLines = 0;
923 }
924 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000925 if (!DryRun) {
926 for (unsigned i = 0; i < MergedLines; ++i) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000927 join(*I[i], *I[i + 1]);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000928 }
929 }
930 I += MergedLines;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000931
Daniel Jasper9c199562013-11-28 15:58:55 +0000932 bool FixIndentation =
933 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000934 if (TheLine.First->is(tok::eof)) {
Daniel Jasper5500f612013-11-25 11:08:59 +0000935 if (PreviousLine && PreviousLine->Affected && !DryRun) {
936 // Remove the file's trailing whitespace.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000937 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
938 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
939 /*IndentLevel=*/0, /*Spaces=*/0,
940 /*TargetColumn=*/0);
941 }
Daniel Jasper9c199562013-11-28 15:58:55 +0000942 } else if (TheLine.Type != LT_Invalid &&
943 (TheLine.Affected || FixIndentation)) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000944 if (FirstTok->WhitespaceRange.isValid()) {
945 if (!DryRun)
946 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
947 Indent, TheLine.InPPDirective);
948 } else {
949 Indent = LevelIndent = FirstTok->OriginalColumn;
950 }
951
952 // If everything fits on a single line, just put it there.
953 unsigned ColumnLimit = Style.ColumnLimit;
954 if (I + 1 != E) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000955 AnnotatedLine *NextLine = I[1];
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000956 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
957 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
958 }
959
Daniel Jasper616de8642014-11-23 16:46:28 +0000960 if (TheLine.Last->TotalLength + Indent <= ColumnLimit ||
961 TheLine.Type == LT_ImportStatement) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000962 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000963 while (State.NextToken) {
964 formatChildren(State, /*Newline=*/false, /*DryRun=*/false, Penalty);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000965 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000966 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000967 } else if (Style.ColumnLimit == 0) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000968 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000969 NoColumnLimitFormatter Formatter(Indenter);
970 if (!DryRun)
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000971 Formatter.format(Indent, &TheLine);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000972 } else {
973 Penalty += format(TheLine, Indent, DryRun);
974 }
975
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000976 if (!TheLine.InPPDirective)
977 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper9c199562013-11-28 15:58:55 +0000978 } else if (TheLine.ChildrenAffected) {
979 format(TheLine.Children, DryRun);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000980 } else {
981 // Format the first token if necessary, and notify the WhitespaceManager
982 // about the unchanged whitespace.
Craig Topper2145bc02014-05-09 08:15:10 +0000983 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000984 if (Tok == TheLine.First &&
985 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
986 unsigned LevelIndent = Tok->OriginalColumn;
987 if (!DryRun) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000988 // Remove trailing whitespace of the previous line.
Daniel Jasper5500f612013-11-25 11:08:59 +0000989 if ((PreviousLine && PreviousLine->Affected) ||
990 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000991 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
992 TheLine.InPPDirective);
993 } else {
994 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
995 }
996 }
997
998 if (static_cast<int>(LevelIndent) - Offset >= 0)
999 LevelIndent -= Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +00001000 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001001 IndentForLevel[TheLine.Level] = LevelIndent;
1002 } else if (!DryRun) {
1003 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
1004 }
1005 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001006 }
1007 if (!DryRun) {
Craig Topper2145bc02014-05-09 08:15:10 +00001008 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001009 Tok->Finalized = true;
1010 }
1011 }
1012 PreviousLine = *I;
1013 }
Daniel Jasperc359ad02014-04-15 08:13:47 +00001014 PenaltyCache[CacheKey] = Penalty;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001015 return Penalty;
1016 }
1017
1018private:
1019 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001020 ///
1021 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001022 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
1023 bool DryRun) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001024 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +00001025
Daniel Jasperacc33662013-02-08 08:22:00 +00001026 // If the ObjC method declaration does not fit on a line, we should format
1027 // it with one arg per line.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001028 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperacc33662013-02-08 08:22:00 +00001029 State.Stack.back().BreakBeforeParameter = true;
1030
Daniel Jasper4b866272013-02-01 11:00:45 +00001031 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001032 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +00001033 }
1034
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001035 /// \brief An edge in the solution space from \c Previous->State to \c State,
1036 /// inserting a newline dependent on the \c NewLine.
1037 struct StateNode {
1038 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001039 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001040 LineState State;
1041 bool NewLine;
1042 StateNode *Previous;
1043 };
Daniel Jasper4b866272013-02-01 11:00:45 +00001044
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001045 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
1046 ///
1047 /// In case of equal penalties, we want to prefer states that were inserted
1048 /// first. During state generation we make sure that we insert states first
1049 /// that break the line as late as possible.
1050 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1051
1052 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
1053 /// \c State has the given \c OrderedPenalty.
1054 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1055
1056 /// \brief The BFS queue type.
1057 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1058 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +00001059
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001060 /// \brief Get the offset of the line relatively to the level.
1061 ///
1062 /// For example, 'public:' labels in classes are offset by 1 or 2
1063 /// characters to the left from their level.
1064 int getIndentOffset(const FormatToken &RootToken) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001065 if (Style.Language == FormatStyle::LK_Java)
1066 return 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001067 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
1068 return Style.AccessModifierOffset;
1069 return 0;
1070 }
1071
1072 /// \brief Add a new line and the required indent before the first Token
1073 /// of the \c UnwrappedLine if there was no structural parsing error.
1074 void formatFirstToken(FormatToken &RootToken,
1075 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
1076 unsigned Indent, bool InPPDirective) {
1077 unsigned Newlines =
1078 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1079 // Remove empty lines before "}" where applicable.
1080 if (RootToken.is(tok::r_brace) &&
1081 (!RootToken.Next ||
1082 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1083 Newlines = std::min(Newlines, 1u);
1084 if (Newlines == 0 && !RootToken.IsFirst)
1085 Newlines = 1;
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001086 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1087 Newlines = 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001088
Daniel Jasper11164bd2014-03-21 12:58:53 +00001089 // Remove empty lines after "{".
Daniel Jaspera26fc5c2014-03-21 13:43:14 +00001090 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1091 PreviousLine->Last->is(tok::l_brace) &&
Nico Weber34272652014-11-13 16:25:37 +00001092 PreviousLine->First->isNot(tok::kw_namespace) &&
1093 !startsExternCBlock(*PreviousLine))
Daniel Jasper11164bd2014-03-21 12:58:53 +00001094 Newlines = 1;
1095
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001096 // Insert extra new line before access specifiers.
1097 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1098 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1099 ++Newlines;
1100
1101 // Remove empty lines after access specifiers.
1102 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
1103 Newlines = std::min(1u, Newlines);
1104
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001105 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
1106 Indent, InPPDirective &&
1107 !RootToken.HasUnescapedNewline);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001108 }
1109
1110 /// \brief Get the indent of \p Level from \p IndentForLevel.
1111 ///
1112 /// \p IndentForLevel must contain the indent for the level \c l
1113 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1114 /// that level is unknown.
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001115 unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001116 if (IndentForLevel[Level] != -1)
1117 return IndentForLevel[Level];
1118 if (Level == 0)
1119 return 0;
1120 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
1121 }
1122
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001123 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1124 assert(!A.Last->Next);
1125 assert(!B.First->Previous);
Daniel Jasper5500f612013-11-25 11:08:59 +00001126 if (B.Affected)
1127 A.Affected = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001128 A.Last->Next = B.First;
1129 B.First->Previous = A.Last;
Daniel Jasper98fb6e12013-11-08 17:33:27 +00001130 B.First->CanBreakBefore = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001131 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1132 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1133 Tok->TotalLength += LengthA;
1134 A.Last = Tok;
1135 }
1136 }
1137
1138 unsigned getColumnLimit(bool InPPDirective) const {
1139 // In preprocessor directives reserve two chars for trailing " \"
1140 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1141 }
1142
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001143 struct CompareLineStatePointers {
1144 bool operator()(LineState *obj1, LineState *obj2) const {
1145 return *obj1 < *obj2;
1146 }
1147 };
1148
Daniel Jasper4b866272013-02-01 11:00:45 +00001149 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +00001150 ///
Daniel Jasper4b866272013-02-01 11:00:45 +00001151 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1152 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1153 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001154 /// to a state where all tokens are placed. Returns the penalty.
1155 ///
1156 /// If \p DryRun is \c false, directly applies the changes.
1157 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001158 std::set<LineState *, CompareLineStatePointers> Seen;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001159
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001160 // Increasing count of \c StateNode items we have created. This is used to
1161 // create a deterministic order independent of the container.
1162 unsigned Count = 0;
1163 QueueType Queue;
1164
Daniel Jasper4b866272013-02-01 11:00:45 +00001165 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001166 StateNode *Node =
Craig Topper2145bc02014-05-09 08:15:10 +00001167 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001168 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1169 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001170
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001171 unsigned Penalty = 0;
1172
Daniel Jasper4b866272013-02-01 11:00:45 +00001173 // While not empty, take first element and follow edges.
1174 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001175 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001176 StateNode *Node = Queue.top().second;
Craig Topper2145bc02014-05-09 08:15:10 +00001177 if (!Node->State.NextToken) {
Alexander Kornienko49149672013-05-10 11:56:10 +00001178 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001179 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001180 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001181 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001182
Daniel Jasperf8114cf2013-05-22 05:27:42 +00001183 // Cut off the analysis of certain solutions if the analysis gets too
1184 // complex. See description of IgnoreStackForComparison.
1185 if (Count > 10000)
1186 Node->State.IgnoreStackForComparison = true;
1187
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001188 if (!Seen.insert(&Node->State).second)
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001189 // State already examined with lower penalty.
1190 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001191
Manuel Klimek71814b42013-10-11 21:25:45 +00001192 FormatDecision LastFormat = Node->State.NextToken->Decision;
1193 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001194 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimek71814b42013-10-11 21:25:45 +00001195 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001196 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper4b866272013-02-01 11:00:45 +00001197 }
1198
Manuel Klimek71814b42013-10-11 21:25:45 +00001199 if (Queue.empty()) {
Daniel Jasper4b866272013-02-01 11:00:45 +00001200 // We were unable to find a solution, do nothing.
1201 // FIXME: Add diagnostic?
Manuel Klimek71814b42013-10-11 21:25:45 +00001202 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001203 return 0;
Manuel Klimek71814b42013-10-11 21:25:45 +00001204 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001205
Daniel Jasper4b866272013-02-01 11:00:45 +00001206 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001207 if (!DryRun)
1208 reconstructPath(InitialState, Queue.top().second);
1209
Alexander Kornienko49149672013-05-10 11:56:10 +00001210 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1211 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001212
1213 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001214 }
1215
1216 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001217 std::deque<StateNode *> Path;
1218 // We do not need a break before the initial token.
1219 while (Current->Previous) {
1220 Path.push_front(Current);
1221 Current = Current->Previous;
1222 }
1223 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1224 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001225 unsigned Penalty = 0;
1226 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1227 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1228
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001229 DEBUG({
1230 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001231 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001232 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001233 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001234 }
1235 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001236 }
Daniel Jasper4b866272013-02-01 11:00:45 +00001237 }
1238
Manuel Klimekaf491072013-02-13 10:54:19 +00001239 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001240 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001241 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001242 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001243 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001244 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001245 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001246 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001247 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001248 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001249
1250 StateNode *Node = new (Allocator.Allocate())
1251 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001252 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1253 return;
1254
Daniel Jasperde0328a2013-08-16 11:20:30 +00001255 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001256
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001257 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1258 ++(*Count);
Daniel Jasper4b866272013-02-01 11:00:45 +00001259 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001260
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001261 /// \brief If the \p State's next token is an r_brace closing a nested block,
1262 /// format the nested block before it.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001263 ///
1264 /// Returns \c true if all children could be placed successfully and adapts
1265 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1266 /// creates changes using \c Whitespaces.
1267 ///
1268 /// The crucial idea here is that children always get formatted upon
1269 /// encountering the closing brace right after the nested block. Now, if we
1270 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1271 /// \c false), the entire block has to be kept on the same line (which is only
1272 /// possible if it fits on the line, only contains a single statement, etc.
1273 ///
1274 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1275 /// break after the "{", format all lines with correct indentation and the put
1276 /// the closing "}" on yet another new line.
1277 ///
1278 /// This enables us to keep the simple structure of the
1279 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1280 /// break or don't break.
1281 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1282 unsigned &Penalty) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001283 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001284 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1285 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1286 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001287 // The previous token does not open a block. Nothing to do. We don't
1288 // assert so that we can simply call this function for all tokens.
Daniel Jasper36c28ce2013-09-06 08:54:24 +00001289 return true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001290
1291 if (NewLine) {
Daniel Jasper58cb2ed2014-06-06 13:49:04 +00001292 int AdditionalIndent =
1293 State.FirstIndent - State.Line->Level * Style.IndentWidth;
Daniel Jasperb16b9692014-05-21 12:51:23 +00001294 if (State.Stack.size() < 2 ||
Daniel Jasper4b444492014-11-21 13:38:53 +00001295 !State.Stack[State.Stack.size() - 2].NestedBlockInlined) {
Daniel Jasperb16b9692014-05-21 12:51:23 +00001296 AdditionalIndent = State.Stack.back().Indent -
1297 Previous.Children[0]->Level * Style.IndentWidth;
1298 }
1299
Daniel Jasper9c199562013-11-28 15:58:55 +00001300 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1301 /*FixBadIndentation=*/true);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001302 return true;
1303 }
1304
Daniel Jasper56346192014-10-27 16:31:46 +00001305 if (Previous.Children[0]->First->MustBreakBefore)
1306 return false;
1307
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001308 // Cannot merge multiple statements into a single line.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001309 if (Previous.Children.size() > 1)
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001310 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001311
Daniel Jasper21397a32014-04-09 12:21:48 +00001312 // Cannot merge into one line if this line ends on a comment.
1313 if (Previous.is(tok::comment))
1314 return false;
1315
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001316 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001317 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001318 return false;
1319
Daniel Jasper98583d52014-04-15 08:28:06 +00001320 // If the child line exceeds the column limit, we wouldn't want to merge it.
1321 // We add +2 for the trailing " }".
1322 if (Style.ColumnLimit > 0 &&
1323 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
1324 Style.ColumnLimit)
1325 return false;
1326
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001327 if (!DryRun) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001328 Whitespaces->replaceWhitespace(
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001329 *Previous.Children[0]->First,
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001330 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001331 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001332 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001333 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001334
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001335 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001336 return true;
1337 }
1338
Daniel Jasperde0328a2013-08-16 11:20:30 +00001339 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001340 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001341 FormatStyle Style;
Daniel Jasper56f8b432013-11-06 23:12:09 +00001342 LineJoiner Joiner;
Manuel Klimekaf491072013-02-13 10:54:19 +00001343
1344 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperc359ad02014-04-15 08:13:47 +00001345
1346 // Cache to store the penalty of formatting a vector of AnnotatedLines
1347 // starting from a specific additional offset. Improves performance if there
1348 // are many nested blocks.
1349 std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
1350 unsigned> PenaltyCache;
Daniel Jasperf7935112012-12-03 18:12:45 +00001351};
1352
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001353class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001354public:
Daniel Jasper23376252014-09-09 14:37:39 +00001355 FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001356 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +00001357 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001358 Column(0), TrailingWhitespace(0), SourceMgr(SourceMgr), ID(ID),
1359 Style(Style), IdentTable(getFormattingLangOpts(Style)),
1360 Keywords(IdentTable), Encoding(Encoding), FirstInLineIndex(0),
1361 FormattingDisabled(false) {
Daniel Jasper23376252014-09-09 14:37:39 +00001362 Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
1363 getFormattingLangOpts(Style)));
1364 Lex->SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +00001365
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001366 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +00001367 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1368 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001369 }
1370
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001371 ArrayRef<FormatToken *> lex() {
1372 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +00001373 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001374 do {
1375 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001376 tryMergePreviousTokens();
Manuel Klimek68b03042014-04-14 09:14:11 +00001377 if (Tokens.back()->NewlinesBefore > 0)
1378 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001379 } while (Tokens.back()->Tok.isNot(tok::eof));
1380 return Tokens;
1381 }
1382
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001383 const AdditionalKeywords &getKeywords() { return Keywords; }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001384
1385private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001386 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001387 if (tryMerge_TMacro())
1388 return;
Manuel Klimek68b03042014-04-14 09:14:11 +00001389 if (tryMergeConflictMarkers())
1390 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001391
1392 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001393 if (tryMergeJSRegexLiteral())
1394 return;
Daniel Jasper23376252014-09-09 14:37:39 +00001395 if (tryMergeEscapeSequence())
1396 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001397
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001398 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1399 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1400 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1401 tok::greaterequal };
Daniel Jasper78214392014-05-19 07:27:02 +00001402 static tok::TokenKind JSRightArrow[] = { tok::equal, tok::greater };
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001403 // FIXME: We probably need to change token type to mimic operator with the
1404 // correct priority.
1405 if (tryMergeTokens(JSIdentity))
1406 return;
1407 if (tryMergeTokens(JSNotIdentity))
1408 return;
1409 if (tryMergeTokens(JSShiftEqual))
1410 return;
Daniel Jasper78214392014-05-19 07:27:02 +00001411 if (tryMergeTokens(JSRightArrow))
1412 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001413 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001414 }
1415
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001416 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1417 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001418 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001419
1420 SmallVectorImpl<FormatToken *>::const_iterator First =
1421 Tokens.end() - Kinds.size();
1422 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001423 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001424 unsigned AddLength = 0;
1425 for (unsigned i = 1; i < Kinds.size(); ++i) {
1426 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1427 First[i]->WhitespaceRange.getEnd())
1428 return false;
1429 AddLength += First[i]->TokenText.size();
1430 }
1431 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1432 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1433 First[0]->TokenText.size() + AddLength);
1434 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001435 return true;
1436 }
1437
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001438 // Tries to merge an escape sequence, i.e. a "\\" and the following
Alp Tokerc3f36af2014-05-15 01:35:53 +00001439 // character. Use e.g. inside JavaScript regex literals.
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001440 bool tryMergeEscapeSequence() {
1441 if (Tokens.size() < 2)
1442 return false;
1443 FormatToken *Previous = Tokens[Tokens.size() - 2];
Daniel Jasper49a9a282014-10-29 16:51:38 +00001444 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\")
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001445 return false;
Daniel Jasper49a9a282014-10-29 16:51:38 +00001446 ++Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001447 StringRef Text = Previous->TokenText;
Daniel Jasper49a9a282014-10-29 16:51:38 +00001448 Previous->TokenText = StringRef(Text.data(), Text.size() + 1);
1449 resetLexer(SourceMgr.getFileOffset(Tokens.back()->Tok.getLocation()) + 1);
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001450 Tokens.resize(Tokens.size() - 1);
Daniel Jasper49a9a282014-10-29 16:51:38 +00001451 Column = Previous->OriginalColumn + Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001452 return true;
1453 }
1454
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001455 // Try to determine whether the current token ends a JavaScript regex literal.
1456 // We heuristically assume that this is a regex literal if we find two
1457 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +00001458 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
1459 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001460 bool tryMergeJSRegexLiteral() {
Daniel Jasper23376252014-09-09 14:37:39 +00001461 if (Tokens.size() < 2)
1462 return false;
1463 // If a regex literal ends in "\//", this gets represented by an unknown
1464 // token "\" and a comment.
1465 bool MightEndWithEscapedSlash =
1466 Tokens.back()->is(tok::comment) &&
1467 Tokens.back()->TokenText.startswith("//") &&
1468 Tokens[Tokens.size() - 2]->TokenText == "\\";
1469 if (!MightEndWithEscapedSlash &&
1470 (Tokens.back()->isNot(tok::slash) ||
1471 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
1472 Tokens[Tokens.size() - 2]->TokenText == "\\")))
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001473 return false;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001474 unsigned TokenCount = 0;
1475 unsigned LastColumn = Tokens.back()->OriginalColumn;
1476 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
1477 ++TokenCount;
1478 if (I[0]->is(tok::slash) && I + 1 != E &&
1479 (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
1480 tok::exclaim, tok::l_square, tok::colon, tok::comma,
1481 tok::question, tok::kw_return) ||
1482 I[1]->isBinaryOperator())) {
Daniel Jasper23376252014-09-09 14:37:39 +00001483 if (MightEndWithEscapedSlash) {
Daniel Jasper23376252014-09-09 14:37:39 +00001484 // This regex literal ends in '\//'. Skip past the '//' of the last
1485 // token and re-start lexing from there.
Daniel Jasper49a9a282014-10-29 16:51:38 +00001486 SourceLocation Loc = Tokens.back()->Tok.getLocation();
1487 resetLexer(SourceMgr.getFileOffset(Loc) + 2);
Daniel Jasper23376252014-09-09 14:37:39 +00001488 }
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001489 Tokens.resize(Tokens.size() - TokenCount);
1490 Tokens.back()->Tok.setKind(tok::unknown);
1491 Tokens.back()->Type = TT_RegexLiteral;
1492 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
1493 return true;
1494 }
1495
1496 // There can't be a newline inside a regex literal.
1497 if (I[0]->NewlinesBefore > 0)
1498 return false;
1499 }
1500 return false;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001501 }
1502
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001503 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001504 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001505 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001506 FormatToken *Last = Tokens.back();
1507 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001508 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001509
1510 FormatToken *String = Tokens[Tokens.size() - 2];
1511 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001512 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001513
1514 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001515 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001516
1517 FormatToken *Macro = Tokens[Tokens.size() - 4];
1518 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001519 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001520
1521 const char *Start = Macro->TokenText.data();
1522 const char *End = Last->TokenText.data() + Last->TokenText.size();
1523 String->TokenText = StringRef(Start, End - Start);
1524 String->IsFirst = Macro->IsFirst;
1525 String->LastNewlineOffset = Macro->LastNewlineOffset;
1526 String->WhitespaceRange = Macro->WhitespaceRange;
1527 String->OriginalColumn = Macro->OriginalColumn;
1528 String->ColumnWidth = encoding::columnWidthWithTabs(
1529 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1530
1531 Tokens.pop_back();
1532 Tokens.pop_back();
1533 Tokens.pop_back();
1534 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001535 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001536 }
1537
Manuel Klimek68b03042014-04-14 09:14:11 +00001538 bool tryMergeConflictMarkers() {
1539 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1540 return false;
1541
1542 // Conflict lines look like:
1543 // <marker> <text from the vcs>
1544 // For example:
1545 // >>>>>>> /file/in/file/system at revision 1234
1546 //
1547 // We merge all tokens in a line that starts with a conflict marker
1548 // into a single token with a special token type that the unwrapped line
1549 // parser will use to correctly rebuild the underlying code.
1550
1551 FileID ID;
1552 // Get the position of the first token in the line.
1553 unsigned FirstInLineOffset;
1554 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1555 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1556 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1557 // Calculate the offset of the start of the current line.
1558 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1559 if (LineOffset == StringRef::npos) {
1560 LineOffset = 0;
1561 } else {
1562 ++LineOffset;
1563 }
1564
1565 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1566 StringRef LineStart;
1567 if (FirstSpace == StringRef::npos) {
1568 LineStart = Buffer.substr(LineOffset);
1569 } else {
1570 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1571 }
1572
1573 TokenType Type = TT_Unknown;
1574 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1575 Type = TT_ConflictStart;
1576 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1577 LineStart == "====") {
1578 Type = TT_ConflictAlternative;
1579 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1580 Type = TT_ConflictEnd;
1581 }
1582
1583 if (Type != TT_Unknown) {
1584 FormatToken *Next = Tokens.back();
1585
1586 Tokens.resize(FirstInLineIndex + 1);
1587 // We do not need to build a complete token here, as we will skip it
1588 // during parsing anyway (as we must not touch whitespace around conflict
1589 // markers).
1590 Tokens.back()->Type = Type;
1591 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1592
1593 Tokens.push_back(Next);
1594 return true;
1595 }
1596
1597 return false;
1598 }
1599
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001600 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001601 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001602 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +00001603 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001604 Token Greater = FormatTok->Tok;
1605 FormatTok = new (Allocator.Allocate()) FormatToken;
1606 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001607 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001608 FormatTok->Tok.getLocation().getLocWithOffset(1);
1609 FormatTok->WhitespaceRange =
1610 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001611 FormatTok->TokenText = ">";
Alexander Kornienko39856b72013-09-10 09:38:25 +00001612 FormatTok->ColumnWidth = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001613 GreaterStashed = false;
1614 return FormatTok;
1615 }
1616
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001617 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001618 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001619 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001620 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001621 FormatTok->IsFirst = IsFirstToken;
1622 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001623
1624 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001625 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001626 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001627 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1628 switch (FormatTok->TokenText[i]) {
1629 case '\n':
1630 ++FormatTok->NewlinesBefore;
1631 // FIXME: This is technically incorrect, as it could also
1632 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001633 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1634 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1635 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +00001636 FormatTok->HasUnescapedNewline = true;
1637 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1638 Column = 0;
1639 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001640 case '\r':
1641 case '\f':
1642 case '\v':
1643 Column = 0;
1644 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001645 case ' ':
1646 ++Column;
1647 break;
1648 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001649 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001650 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001651 case '\\':
1652 ++Column;
1653 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1654 FormatTok->TokenText[i + 1] != '\n'))
1655 FormatTok->Type = TT_ImplicitStringLiteral;
1656 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001657 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001658 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001659 ++Column;
1660 break;
1661 }
1662 }
1663
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001664 if (FormatTok->is(TT_ImplicitStringLiteral))
Daniel Jasper877615c2013-10-11 19:45:02 +00001665 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001666 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001667
Daniel Jasper8369aa52013-07-16 20:28:33 +00001668 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001669 }
Manuel Klimekef920692013-01-07 07:56:50 +00001670
Manuel Klimek1abf7892013-01-04 23:34:14 +00001671 // In case the token starts with escaped newlines, we want to
1672 // take them into account as whitespace - this pattern is quite frequent
1673 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001674 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001675 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1676 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001677 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001678 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001679 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001680 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001681 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001682
1683 FormatTok->WhitespaceRange = SourceRange(
1684 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1685
Manuel Klimek31c85922013-08-29 15:21:40 +00001686 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001687
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001688 TrailingWhitespace = 0;
1689 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001690 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001691 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001692 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001693 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001694 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001695 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001696 FormatTok->Tok.setIdentifierInfo(&Info);
1697 FormatTok->Tok.setKind(Info.getTokenID());
Daniel Jasperfe2cf662014-11-19 14:11:11 +00001698 if (Style.Language == FormatStyle::LK_Java &&
1699 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete)) {
1700 FormatTok->Tok.setKind(tok::identifier);
1701 FormatTok->Tok.setIdentifierInfo(nullptr);
1702 }
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001703 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001704 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001705 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001706 GreaterStashed = true;
1707 }
1708
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001709 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001710
Alexander Kornienko39856b72013-09-10 09:38:25 +00001711 StringRef Text = FormatTok->TokenText;
1712 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001713 if (FirstNewlinePos == StringRef::npos) {
1714 // FIXME: ColumnWidth actually depends on the start column, we need to
1715 // take this into account when the token is moved.
1716 FormatTok->ColumnWidth =
1717 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1718 Column += FormatTok->ColumnWidth;
1719 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001720 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001721 // FIXME: ColumnWidth actually depends on the start column, we need to
1722 // take this into account when the token is moved.
1723 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1724 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1725
Alexander Kornienko39856b72013-09-10 09:38:25 +00001726 // The last line of the token always starts in column 0.
1727 // Thus, the length can be precomputed even in the presence of tabs.
1728 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1729 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1730 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001731 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001732 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001733
Daniel Jaspere1e43192014-04-01 12:55:11 +00001734 FormatTok->IsForEachMacro =
1735 std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1736 FormatTok->Tok.getIdentifierInfo());
1737
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001738 return FormatTok;
1739 }
1740
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001741 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001742 bool IsFirstToken;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001743 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001744 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001745 unsigned TrailingWhitespace;
Daniel Jasper23376252014-09-09 14:37:39 +00001746 std::unique_ptr<Lexer> Lex;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001747 SourceManager &SourceMgr;
Daniel Jasper23376252014-09-09 14:37:39 +00001748 FileID ID;
Manuel Klimek31c85922013-08-29 15:21:40 +00001749 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001750 IdentifierTable IdentTable;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001751 AdditionalKeywords Keywords;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001752 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001753 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001754 // Index (in 'Tokens') of the last token that starts a new line.
1755 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001756 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001757 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001758
NAKAMURA Takumi7160c4d2014-08-06 16:53:13 +00001759 bool FormattingDisabled;
Daniel Jasper471894432014-08-06 13:40:26 +00001760
Daniel Jasper8369aa52013-07-16 20:28:33 +00001761 void readRawToken(FormatToken &Tok) {
Daniel Jasper23376252014-09-09 14:37:39 +00001762 Lex->LexFromRawLexer(Tok.Tok);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001763 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1764 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001765 // For formatting, treat unterminated string literals like normal string
1766 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001767 if (Tok.is(tok::unknown)) {
1768 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1769 Tok.Tok.setKind(tok::string_literal);
1770 Tok.IsUnterminatedLiteral = true;
1771 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1772 Tok.TokenText == "''") {
1773 Tok.Tok.setKind(tok::char_constant);
1774 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001775 }
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001776
1777 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1778 Tok.TokenText == "/* clang-format on */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001779 FormattingDisabled = false;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001780 }
1781
Daniel Jasper471894432014-08-06 13:40:26 +00001782 Tok.Finalized = FormattingDisabled;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001783
1784 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1785 Tok.TokenText == "/* clang-format off */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001786 FormattingDisabled = true;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001787 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001788 }
Daniel Jasper49a9a282014-10-29 16:51:38 +00001789
1790 void resetLexer(unsigned Offset) {
1791 StringRef Buffer = SourceMgr.getBufferData(ID);
1792 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1793 getFormattingLangOpts(Style), Buffer.begin(),
1794 Buffer.begin() + Offset, Buffer.end()));
1795 Lex->SetKeepWhitespaceMode(true);
1796 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001797};
1798
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001799static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1800 switch (Language) {
1801 case FormatStyle::LK_Cpp:
1802 return "C++";
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001803 case FormatStyle::LK_Java:
1804 return "Java";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001805 case FormatStyle::LK_JavaScript:
1806 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001807 case FormatStyle::LK_Proto:
1808 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001809 default:
1810 return "Unknown";
1811 }
1812}
1813
Daniel Jasperf7935112012-12-03 18:12:45 +00001814class Formatter : public UnwrappedLineConsumer {
1815public:
Daniel Jasper23376252014-09-09 14:37:39 +00001816 Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001817 ArrayRef<CharSourceRange> Ranges)
Daniel Jasper23376252014-09-09 14:37:39 +00001818 : Style(Style), ID(ID), SourceMgr(SourceMgr),
1819 Whitespaces(SourceMgr, Style,
1820 inputUsesCRLF(SourceMgr.getBufferData(ID))),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001821 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Daniel Jasper23376252014-09-09 14:37:39 +00001822 Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001823 DEBUG(llvm::dbgs() << "File encoding: "
1824 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1825 : "unknown")
1826 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001827 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1828 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001829 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001830
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001831 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001832 tooling::Replacements Result;
Daniel Jasper23376252014-09-09 14:37:39 +00001833 FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001834
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001835 UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
1836 *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001837 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001838 assert(UnwrappedLines.rbegin()->empty());
1839 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1840 ++Run) {
1841 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1842 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1843 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1844 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1845 }
1846 tooling::Replacements RunResult =
1847 format(AnnotatedLines, StructuralError, Tokens);
1848 DEBUG({
1849 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1850 for (tooling::Replacements::iterator I = RunResult.begin(),
1851 E = RunResult.end();
1852 I != E; ++I) {
1853 llvm::dbgs() << I->toString() << "\n";
1854 }
1855 });
1856 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1857 delete AnnotatedLines[i];
1858 }
1859 Result.insert(RunResult.begin(), RunResult.end());
1860 Whitespaces.reset();
1861 }
1862 return Result;
1863 }
1864
1865 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1866 bool StructuralError, FormatTokenLexer &Tokens) {
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001867 TokenAnnotator Annotator(Style, Tokens.getKeywords());
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001868 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001869 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001870 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001871 deriveLocalStyle(AnnotatedLines);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001872 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001873 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001874 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001875 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001876
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001877 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001878 ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
1879 Whitespaces, Encoding,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001880 BinPackInconclusiveFunctions);
Daniel Jasper5500f612013-11-25 11:08:59 +00001881 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001882 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001883 return Whitespaces.generateReplacements();
1884 }
1885
1886private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001887 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001888 // Returns \c true if at least one line between I and E or one of their
1889 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001890 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1891 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1892 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001893 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001894 while (I != E) {
1895 AnnotatedLine *Line = *I;
1896 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1897
1898 // If a line is part of a preprocessor directive, it needs to be formatted
1899 // if any token within the directive is affected.
1900 if (Line->InPPDirective) {
1901 FormatToken *Last = Line->Last;
1902 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1903 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1904 Last = (*PPEnd)->Last;
1905 ++PPEnd;
1906 }
1907
1908 if (affectsTokenRange(*Line->First, *Last,
1909 /*IncludeLeadingNewlines=*/false)) {
1910 SomeLineAffected = true;
1911 markAllAsAffected(I, PPEnd);
1912 }
1913 I = PPEnd;
1914 continue;
1915 }
1916
Daniel Jasper38c82402013-11-29 09:27:43 +00001917 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001918 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001919
Daniel Jasper38c82402013-11-29 09:27:43 +00001920 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001921 ++I;
1922 }
1923 return SomeLineAffected;
1924 }
1925
Daniel Jasper9c199562013-11-28 15:58:55 +00001926 // Determines whether 'Line' is affected by the SourceRanges given as input.
1927 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001928 bool nonPPLineAffected(AnnotatedLine *Line,
1929 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001930 bool SomeLineAffected = false;
1931 Line->ChildrenAffected =
1932 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1933 if (Line->ChildrenAffected)
1934 SomeLineAffected = true;
1935
1936 // Stores whether one of the line's tokens is directly affected.
1937 bool SomeTokenAffected = false;
1938 // Stores whether we need to look at the leading newlines of the next token
1939 // in order to determine whether it was affected.
1940 bool IncludeLeadingNewlines = false;
1941
1942 // Stores whether the first child line of any of this line's tokens is
1943 // affected.
1944 bool SomeFirstChildAffected = false;
1945
1946 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1947 // Determine whether 'Tok' was affected.
1948 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1949 SomeTokenAffected = true;
1950
1951 // Determine whether the first child of 'Tok' was affected.
1952 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1953 SomeFirstChildAffected = true;
1954
1955 IncludeLeadingNewlines = Tok->Children.empty();
1956 }
1957
1958 // Was this line moved, i.e. has it previously been on the same line as an
1959 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001960 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1961 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001962
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001963 bool IsContinuedComment =
1964 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1965 Line->First->NewlinesBefore < 2 && PreviousLine &&
1966 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001967
1968 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1969 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001970 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001971 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001972 }
1973 return SomeLineAffected;
1974 }
1975
Daniel Jasper5500f612013-11-25 11:08:59 +00001976 // Marks all lines between I and E as well as all their children as affected.
1977 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1978 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1979 while (I != E) {
1980 (*I)->Affected = true;
1981 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1982 ++I;
1983 }
1984 }
1985
1986 // Returns true if the range from 'First' to 'Last' intersects with one of the
1987 // input ranges.
1988 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1989 bool IncludeLeadingNewlines) {
1990 SourceLocation Start = First.WhitespaceRange.getBegin();
1991 if (!IncludeLeadingNewlines)
1992 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001993 SourceLocation End = Last.getStartOfNonWhitespace();
Daniel Jasperac29eac2014-10-29 23:40:50 +00001994 End = End.getLocWithOffset(Last.TokenText.size());
Daniel Jasper5500f612013-11-25 11:08:59 +00001995 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1996 return affectsCharSourceRange(Range);
1997 }
1998
1999 // Returns true if one of the input ranges intersect the leading empty lines
2000 // before 'Tok'.
2001 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
2002 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
2003 Tok.WhitespaceRange.getBegin(),
2004 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
2005 return affectsCharSourceRange(EmptyLineRange);
2006 }
2007
2008 // Returns true if 'Range' intersects with one of the input ranges.
2009 bool affectsCharSourceRange(const CharSourceRange &Range) {
2010 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
2011 E = Ranges.end();
2012 I != E; ++I) {
2013 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
2014 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
2015 return true;
2016 }
2017 return false;
2018 }
2019
Alexander Kornienko9e649af2013-09-11 12:25:57 +00002020 static bool inputUsesCRLF(StringRef Text) {
2021 return Text.count('\r') * 2 > Text.count('\n');
2022 }
2023
Manuel Klimek71814b42013-10-11 21:25:45 +00002024 void
2025 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002026 unsigned CountBoundToVariable = 0;
2027 unsigned CountBoundToType = 0;
2028 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002029 bool HasBinPackedFunction = false;
2030 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002031 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002032 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002033 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002034 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00002035 while (Tok->Next) {
Daniel Jaspera98b7b02014-11-25 10:05:17 +00002036 if (Tok->is(TT_PointerOrReference)) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00002037 bool SpacesBefore =
2038 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
2039 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
2040 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002041 if (SpacesBefore && !SpacesAfter)
2042 ++CountBoundToVariable;
2043 else if (!SpacesBefore && SpacesAfter)
2044 ++CountBoundToType;
2045 }
2046
Daniel Jasperfba84ff2013-10-12 05:16:06 +00002047 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
Daniel Jaspera98b7b02014-11-25 10:05:17 +00002048 if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
Daniel Jasperfba84ff2013-10-12 05:16:06 +00002049 HasCpp03IncompatibleFormat = true;
Daniel Jaspera98b7b02014-11-25 10:05:17 +00002050 if (Tok->is(TT_TemplateCloser) &&
2051 Tok->Previous->is(TT_TemplateCloser))
Daniel Jasperfba84ff2013-10-12 05:16:06 +00002052 HasCpp03IncompatibleFormat = true;
2053 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002054
2055 if (Tok->PackingKind == PPK_BinPacked)
2056 HasBinPackedFunction = true;
2057 if (Tok->PackingKind == PPK_OnePerLine)
2058 HasOnePerLineFunction = true;
2059
Manuel Klimek6e6310e2013-05-29 14:47:47 +00002060 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002061 }
2062 }
Daniel Jasper553d4872014-06-17 12:40:34 +00002063 if (Style.DerivePointerAlignment) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002064 if (CountBoundToType > CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00002065 Style.PointerAlignment = FormatStyle::PAS_Left;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002066 else if (CountBoundToType < CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00002067 Style.PointerAlignment = FormatStyle::PAS_Right;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002068 }
2069 if (Style.Standard == FormatStyle::LS_Auto) {
2070 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
2071 : FormatStyle::LS_Cpp03;
2072 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002073 BinPackInconclusiveFunctions =
2074 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002075 }
2076
Craig Topperfb6b25b2014-03-15 04:29:04 +00002077 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00002078 assert(!UnwrappedLines.empty());
2079 UnwrappedLines.back().push_back(TheLine);
2080 }
2081
Craig Topperfb6b25b2014-03-15 04:29:04 +00002082 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00002083 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00002084 }
2085
2086 FormatStyle Style;
Daniel Jasper23376252014-09-09 14:37:39 +00002087 FileID ID;
Daniel Jasperf7935112012-12-03 18:12:45 +00002088 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00002089 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00002090 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00002091 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00002092
2093 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002094 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00002095};
2096
Craig Topperaf35e852013-06-30 22:29:28 +00002097} // end anonymous namespace
2098
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00002099tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
2100 SourceManager &SourceMgr,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002101 ArrayRef<CharSourceRange> Ranges) {
Daniel Jasper23376252014-09-09 14:37:39 +00002102 if (Style.DisableFormat)
2103 return tooling::Replacements();
2104 return reformat(Style, SourceMgr,
2105 SourceMgr.getFileID(Lex.getSourceLocation()), Ranges);
2106}
Daniel Jasperc64b09a2014-05-22 15:12:22 +00002107
Daniel Jasper23376252014-09-09 14:37:39 +00002108tooling::Replacements reformat(const FormatStyle &Style,
2109 SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002110 ArrayRef<CharSourceRange> Ranges) {
Daniel Jasper23376252014-09-09 14:37:39 +00002111 if (Style.DisableFormat)
2112 return tooling::Replacements();
2113 Formatter formatter(Style, SourceMgr, ID, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00002114 return formatter.format();
2115}
2116
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002117tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002118 ArrayRef<tooling::Range> Ranges,
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002119 StringRef FileName) {
Daniel Jasper23376252014-09-09 14:37:39 +00002120 if (Style.DisableFormat)
2121 return tooling::Replacements();
2122
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002123 FileManager Files((FileSystemOptions()));
2124 DiagnosticsEngine Diagnostics(
2125 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2126 new DiagnosticOptions);
2127 SourceManager SourceMgr(Diagnostics, Files);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00002128 std::unique_ptr<llvm::MemoryBuffer> Buf =
2129 llvm::MemoryBuffer::getMemBuffer(Code, FileName);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002130 const clang::FileEntry *Entry =
2131 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
David Blaikie49cc3182014-08-27 20:54:45 +00002132 SourceMgr.overrideFileContents(Entry, std::move(Buf));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002133 FileID ID =
2134 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002135 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
2136 std::vector<CharSourceRange> CharRanges;
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002137 for (const tooling::Range &Range : Ranges) {
2138 SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
2139 SourceLocation End = Start.getLocWithOffset(Range.getLength());
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002140 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
2141 }
Daniel Jasper23376252014-09-09 14:37:39 +00002142 return reformat(Style, SourceMgr, ID, CharRanges);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002143}
2144
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002145LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002146 LangOptions LangOpts;
2147 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002148 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2149 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00002150 LangOpts.LineComment = 1;
Daniel Jasper30a24062014-11-14 09:02:28 +00002151 bool AlternativeOperators = Style.Language != FormatStyle::LK_JavaScript &&
2152 Style.Language != FormatStyle::LK_Java;
2153 LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002154 LangOpts.Bool = 1;
2155 LangOpts.ObjC1 = 1;
2156 LangOpts.ObjC2 = 1;
2157 return LangOpts;
2158}
2159
Edwin Vaned544aa72013-09-30 13:31:48 +00002160const char *StyleOptionHelpDescription =
2161 "Coding style, currently supports:\n"
2162 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
2163 "Use -style=file to load style configuration from\n"
2164 ".clang-format file located in one of the parent\n"
2165 "directories of the source file (or current\n"
2166 "directory for stdin).\n"
2167 "Use -style=\"{key: value, ...}\" to set specific\n"
2168 "parameters, e.g.:\n"
2169 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
2170
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002171static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00002172 if (FileName.endswith(".java")) {
2173 return FormatStyle::LK_Java;
2174 } else if (FileName.endswith_lower(".js")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002175 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00002176 } else if (FileName.endswith_lower(".proto") ||
2177 FileName.endswith_lower(".protodevel")) {
2178 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002179 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002180 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002181}
2182
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002183FormatStyle getStyle(StringRef StyleName, StringRef FileName,
2184 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002185 FormatStyle Style = getLLVMStyle();
2186 Style.Language = getLanguageByFileName(FileName);
2187 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002188 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
2189 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002190 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002191 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002192
2193 if (StyleName.startswith("{")) {
2194 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00002195 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002196 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
2197 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00002198 }
2199 return Style;
2200 }
2201
2202 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002203 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00002204 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
2205 << " style\n";
2206 return Style;
2207 }
2208
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002209 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002210 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00002211 SmallString<128> Path(FileName);
2212 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002213 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00002214 Directory = llvm::sys::path::parent_path(Directory)) {
2215 if (!llvm::sys::fs::is_directory(Directory))
2216 continue;
2217 SmallString<128> ConfigFile(Directory);
2218
2219 llvm::sys::path::append(ConfigFile, ".clang-format");
2220 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2221 bool IsFile = false;
2222 // Ignore errors from is_regular_file: we only need to know if we can read
2223 // the file or not.
2224 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2225
2226 if (!IsFile) {
2227 // Try _clang-format too, since dotfiles are not commonly used on Windows.
2228 ConfigFile = Directory;
2229 llvm::sys::path::append(ConfigFile, "_clang-format");
2230 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2231 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2232 }
2233
2234 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002235 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
2236 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
2237 if (std::error_code EC = Text.getError()) {
2238 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002239 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002240 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002241 if (std::error_code ec =
2242 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00002243 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002244 if (!UnsuitableConfigFiles.empty())
2245 UnsuitableConfigFiles.append(", ");
2246 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002247 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002248 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002249 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2250 << "\n";
2251 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002252 }
2253 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2254 return Style;
2255 }
2256 }
2257 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
2258 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002259 if (!UnsuitableConfigFiles.empty()) {
2260 llvm::errs() << "Configuration file(s) do(es) not support "
2261 << getLanguageName(Style.Language) << ": "
2262 << UnsuitableConfigFiles << "\n";
2263 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002264 return Style;
2265}
2266
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002267} // namespace format
2268} // namespace clang