blob: 8a04571a8cb05f656d707edad3edbe12b2c10ef4 [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);
77 }
78};
79
Daniel Jasperac043c92014-09-15 11:11:00 +000080template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
81 static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
82 IO.enumCase(Value, "All", FormatStyle::BOS_All);
83 IO.enumCase(Value, "true", FormatStyle::BOS_All);
84 IO.enumCase(Value, "None", FormatStyle::BOS_None);
85 IO.enumCase(Value, "false", FormatStyle::BOS_None);
86 IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
87 }
88};
89
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000090template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
91 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
92 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
93 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
94 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
95 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
Alexander Kornienko3a33f022013-12-12 09:49:52 +000096 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000097 }
98};
99
Alexander Kornienkod6538332013-05-07 15:32:14 +0000100template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000101struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000102 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000103 FormatStyle::NamespaceIndentationKind &Value) {
104 IO.enumCase(Value, "None", FormatStyle::NI_None);
105 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
106 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000107 }
108};
109
110template <>
Daniel Jasper553d4872014-06-17 12:40:34 +0000111struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
112 static void enumeration(IO &IO,
113 FormatStyle::PointerAlignmentStyle &Value) {
114 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
115 IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
116 IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
117
Alp Toker958027b2014-07-14 19:42:55 +0000118 // For backward compatibility.
Daniel Jasper553d4872014-06-17 12:40:34 +0000119 IO.enumCase(Value, "true", FormatStyle::PAS_Left);
120 IO.enumCase(Value, "false", FormatStyle::PAS_Right);
121 }
122};
123
124template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000125struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000126 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000127 FormatStyle::SpaceBeforeParensOptions &Value) {
128 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000129 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000130 FormatStyle::SBPO_ControlStatements);
131 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000132
133 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000134 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
135 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000136 }
137};
138
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000139template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000140 static void mapping(IO &IO, FormatStyle &Style) {
141 // When reading, read the language first, we need it for getPredefinedStyle.
142 IO.mapOptional("Language", Style.Language);
143
Alexander Kornienko49149672013-05-10 11:56:10 +0000144 if (IO.outputting()) {
Alexander Kornienkoe3648fb2013-09-02 16:39:23 +0000145 StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000146 "Mozilla", "WebKit", "GNU" };
Alexander Kornienko49149672013-05-10 11:56:10 +0000147 ArrayRef<StringRef> Styles(StylesArray);
148 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
149 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000150 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000151 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000152 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000153 IO.mapOptional("# BasedOnStyle", StyleName);
154 break;
155 }
156 }
157 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000158 StringRef BasedOnStyle;
159 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000160 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000161 FormatStyle::LanguageKind OldLanguage = Style.Language;
162 FormatStyle::LanguageKind Language =
163 ((FormatStyle *)IO.getContext())->Language;
164 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000165 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
166 return;
167 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000168 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000169 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000170 }
171
172 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000173 IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000174 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000175 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000176 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
177 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000178 IO.mapOptional("AllowShortBlocksOnASingleLine",
179 Style.AllowShortBlocksOnASingleLine);
Daniel Jasperb87899b2014-09-10 13:11:45 +0000180 IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
181 Style.AllowShortCaseLabelsOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000182 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
183 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000184 IO.mapOptional("AllowShortLoopsOnASingleLine",
185 Style.AllowShortLoopsOnASingleLine);
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000186 IO.mapOptional("AllowShortFunctionsOnASingleLine",
187 Style.AllowShortFunctionsOnASingleLine);
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000188 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
189 Style.AlwaysBreakAfterDefinitionReturnType);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000190 IO.mapOptional("AlwaysBreakTemplateDeclarations",
191 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko58611712013-07-04 12:02:44 +0000192 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
193 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000194 IO.mapOptional("BreakBeforeBinaryOperators",
195 Style.BreakBeforeBinaryOperators);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000196 IO.mapOptional("BreakBeforeTernaryOperators",
197 Style.BreakBeforeTernaryOperators);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000198 IO.mapOptional("BreakConstructorInitializersBeforeComma",
199 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000200 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
Daniel Jasper18210d72014-10-09 09:52:05 +0000201 IO.mapOptional("BinPackArguments", Style.BinPackArguments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000202 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
203 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
204 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000205 IO.mapOptional("ConstructorInitializerIndentWidth",
206 Style.ConstructorInitializerIndentWidth);
Daniel Jasper553d4872014-06-17 12:40:34 +0000207 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000208 IO.mapOptional("ExperimentalAutoDetectBinPacking",
209 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000210 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000211 IO.mapOptional("IndentWrappedFunctionNames",
212 Style.IndentWrappedFunctionNames);
213 IO.mapOptional("IndentFunctionDeclarationAfterType",
214 Style.IndentWrappedFunctionNames);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000215 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000216 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
217 Style.KeepEmptyLinesAtTheStartOfBlocks);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000218 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000219 IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000220 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000221 IO.mapOptional("ObjCSpaceBeforeProtocolList",
222 Style.ObjCSpaceBeforeProtocolList);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000223 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
224 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000225 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
226 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000227 IO.mapOptional("PenaltyBreakFirstLessLess",
228 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000229 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
230 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
231 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000232 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000233 IO.mapOptional("SpacesBeforeTrailingComments",
234 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000235 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000236 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000237 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000238 IO.mapOptional("TabWidth", Style.TabWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000239 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000240 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000241 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasperad981f82014-08-26 11:41:14 +0000242 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000243 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
Daniel Jasperf110e202013-08-21 08:39:01 +0000244 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasperb55acad2013-08-20 12:36:34 +0000245 IO.mapOptional("SpacesInCStyleCastParentheses",
246 Style.SpacesInCStyleCastParentheses);
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000247 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000248 IO.mapOptional("SpacesInContainerLiterals",
249 Style.SpacesInContainerLiterals);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000250 IO.mapOptional("SpaceBeforeAssignmentOperators",
251 Style.SpaceBeforeAssignmentOperators);
Daniel Jasper6633ab82013-10-18 10:38:14 +0000252 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000253 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000254 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000255
256 // For backward compatibility.
257 if (!IO.outputting()) {
258 IO.mapOptional("SpaceAfterControlStatementKeyword",
259 Style.SpaceBeforeParens);
Daniel Jasper553d4872014-06-17 12:40:34 +0000260 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
261 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000262 }
263 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000264 IO.mapOptional("DisableFormat", Style.DisableFormat);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000265 }
266};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000267
268// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000269// IO.getContext() should contain a pointer to the FormatStyle structure, that
270// will be used to get default values for missing keys.
271// If the first element has no Language specified, it will be treated as the
272// default one for the following elements.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000273template <> struct DocumentListTraits<std::vector<FormatStyle> > {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000274 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
275 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000276 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000277 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000278 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000279 if (Index >= Seq.size()) {
280 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000281 FormatStyle Template;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000282 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000283 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000284 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000285 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000286 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000287 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000288 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000289 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000290 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000291 }
292};
Alexander Kornienkod6538332013-05-07 15:32:14 +0000293}
294}
295
Daniel Jasperf7935112012-12-03 18:12:45 +0000296namespace clang {
297namespace format {
298
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000299const std::error_category &getParseCategory() {
Rafael Espindolad0136702014-06-12 02:50:04 +0000300 static ParseErrorCategory C;
301 return C;
302}
303std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000304 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000305}
306
307const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
308 return "clang-format.parse_error";
309}
310
311std::string ParseErrorCategory::message(int EV) const {
312 switch (static_cast<ParseError>(EV)) {
313 case ParseError::Success:
314 return "Success";
315 case ParseError::Error:
316 return "Invalid argument";
317 case ParseError::Unsuitable:
318 return "Unsuitable";
319 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000320 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000321}
322
Daniel Jasperf7935112012-12-03 18:12:45 +0000323FormatStyle getLLVMStyle() {
324 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000325 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000326 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000327 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000328 LLVMStyle.AlignAfterOpenBracket = true;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000329 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000330 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000331 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000332 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000333 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000334 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000335 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000336 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000337 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000338 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000339 LLVMStyle.BinPackParameters = true;
Daniel Jasper18210d72014-10-09 09:52:05 +0000340 LLVMStyle.BinPackArguments = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000341 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000342 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000343 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
344 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000345 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000346 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000347 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000348 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000349 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000350 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000351 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000352 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000353 LLVMStyle.ForEachMacros.push_back("foreach");
354 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
355 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000356 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000357 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000358 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000359 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000360 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000361 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000362 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000363 LLVMStyle.ObjCBlockIndentWidth = 2;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000364 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000365 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000366 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000367 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000368 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000369 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000370 LLVMStyle.SpacesInParentheses = false;
Daniel Jasperad981f82014-08-26 11:41:14 +0000371 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000372 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000373 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000374 LLVMStyle.SpacesInCStyleCastParentheses = false;
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000375 LLVMStyle.SpaceAfterCStyleCast = false;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000376 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000377 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000378 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000379
Daniel Jasper19a541e2013-12-19 16:45:34 +0000380 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000381 LLVMStyle.PenaltyBreakFirstLessLess = 120;
382 LLVMStyle.PenaltyBreakString = 1000;
383 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000384 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000385 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000386
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000387 LLVMStyle.DisableFormat = false;
388
Daniel Jasperf7935112012-12-03 18:12:45 +0000389 return LLVMStyle;
390}
391
Nico Weber514ecc82014-02-02 20:50:45 +0000392FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000393 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000394 GoogleStyle.Language = Language;
395
Daniel Jasperf7935112012-12-03 18:12:45 +0000396 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000397 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000398 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000399 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000400 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000401 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000402 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000403 GoogleStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000404 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000405 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000406 GoogleStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000407 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000408 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000409 GoogleStyle.SpacesBeforeTrailingComments = 2;
410 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000411
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000412 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000413 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000414
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000415 if (Language == FormatStyle::LK_Java) {
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000416 GoogleStyle.AlignAfterOpenBracket = false;
Daniel Jasperb89fbe62014-10-28 16:15:52 +0000417 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000418 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
419 GoogleStyle.ColumnLimit = 100;
420 GoogleStyle.SpaceAfterCStyleCast = true;
Daniel Jasper61d81972014-11-14 08:22:46 +0000421 GoogleStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000422 } else if (Language == FormatStyle::LK_JavaScript) {
Daniel Jaspere551bb72014-11-05 17:22:31 +0000423 GoogleStyle.BreakBeforeTernaryOperators = false;
Daniel Jasper8f83a902014-05-09 10:28:58 +0000424 GoogleStyle.MaxEmptyLinesToKeep = 3;
Nico Weber514ecc82014-02-02 20:50:45 +0000425 GoogleStyle.SpacesInContainerLiterals = false;
Daniel Jasper67f8ad22014-09-30 17:57:06 +0000426 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Nico Weber514ecc82014-02-02 20:50:45 +0000427 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000428 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper783bac62014-04-15 09:54:30 +0000429 GoogleStyle.SpacesInContainerLiterals = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000430 }
431
Daniel Jasperf7935112012-12-03 18:12:45 +0000432 return GoogleStyle;
433}
434
Nico Weber514ecc82014-02-02 20:50:45 +0000435FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
436 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Daniel Jasperf7db4332013-01-29 16:03:49 +0000437 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000438 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000439 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000440 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000441 ChromiumStyle.BinPackParameters = false;
Daniel Jasper553d4872014-06-17 12:40:34 +0000442 ChromiumStyle.DerivePointerAlignment = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000443 return ChromiumStyle;
444}
445
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000446FormatStyle getMozillaStyle() {
447 FormatStyle MozillaStyle = getLLVMStyle();
448 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000449 MozillaStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000450 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000451 MozillaStyle.DerivePointerAlignment = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000452 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000453 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000454 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
455 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000456 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000457 MozillaStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000458 return MozillaStyle;
459}
460
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000461FormatStyle getWebKitStyle() {
462 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000463 Style.AccessModifierOffset = -4;
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000464 Style.AlignAfterOpenBracket = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000465 Style.AlignTrailingComments = false;
Daniel Jasperac043c92014-09-15 11:11:00 +0000466 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000467 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000468 Style.BreakConstructorInitializersBeforeComma = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000469 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000470 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000471 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000472 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000473 Style.ObjCBlockIndentWidth = 4;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000474 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000475 Style.PointerAlignment = FormatStyle::PAS_Left;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000476 Style.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000477 return Style;
478}
479
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000480FormatStyle getGNUStyle() {
481 FormatStyle Style = getLLVMStyle();
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000482 Style.AlwaysBreakAfterDefinitionReturnType = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000483 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000484 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000485 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000486 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000487 Style.ColumnLimit = 79;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000488 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000489 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000490 return Style;
491}
492
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000493FormatStyle getNoStyle() {
494 FormatStyle NoStyle = getLLVMStyle();
495 NoStyle.DisableFormat = true;
496 return NoStyle;
497}
498
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000499bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
500 FormatStyle *Style) {
501 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000502 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000503 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000504 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000505 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000506 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000507 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000508 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000509 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000510 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000511 } else if (Name.equals_lower("gnu")) {
512 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000513 } else if (Name.equals_lower("none")) {
514 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000515 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000516 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000517 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000518
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000519 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000520 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000521}
522
Rafael Espindolac0809172014-06-12 14:02:15 +0000523std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000524 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000525 FormatStyle::LanguageKind Language = Style->Language;
526 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000527 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000528 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000529
530 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000531 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000532 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
533 // values for the fields, keys for which are missing from the configuration.
534 // Mapping also uses the context to get the language to find the correct
535 // base style.
536 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000537 Input >> Styles;
538 if (Input.error())
539 return Input.error();
540
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000541 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000542 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000543 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000544 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000545 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000546 for (unsigned j = 0; j < i; ++j) {
547 if (Styles[i].Language == Styles[j].Language) {
548 DEBUG(llvm::dbgs()
549 << "Duplicate languages in the config file on positions " << j
550 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000551 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000552 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000553 }
554 }
555 // Look for a suitable configuration starting from the end, so we can
556 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000557 // configuration (which can only be at slot 0) after it.
558 for (int i = Styles.size() - 1; i >= 0; --i) {
559 if (Styles[i].Language == Language ||
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000560 Styles[i].Language == FormatStyle::LK_None) {
561 *Style = Styles[i];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000562 Style->Language = Language;
Rafael Espindolad0136702014-06-12 02:50:04 +0000563 return make_error_code(ParseError::Success);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000564 }
565 }
Rafael Espindolad0136702014-06-12 02:50:04 +0000566 return make_error_code(ParseError::Unsuitable);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000567}
568
569std::string configurationAsText(const FormatStyle &Style) {
570 std::string Text;
571 llvm::raw_string_ostream Stream(Text);
572 llvm::yaml::Output Output(Stream);
573 // We use the same mapping method for input and output, so we need a non-const
574 // reference here.
575 FormatStyle NonConstStyle = Style;
576 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000577 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000578}
579
Craig Topperaf35e852013-06-30 22:29:28 +0000580namespace {
581
Nico Weber34272652014-11-13 16:25:37 +0000582bool startsExternCBlock(const AnnotatedLine &Line) {
583 const FormatToken *Next = Line.First->getNextNonComment();
584 const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr;
585 return Line.First->is(tok::kw_extern) && Next && Next->isStringLiteral() &&
586 NextNext && NextNext->is(tok::l_brace);
587}
588
Daniel Jasperde0328a2013-08-16 11:20:30 +0000589class NoColumnLimitFormatter {
590public:
Daniel Jasperf110e202013-08-21 08:39:01 +0000591 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000592
593 /// \brief Formats the line starting at \p State, simply keeping all of the
594 /// input's line breaking decisions.
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000595 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +0000596 LineState State =
597 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
Craig Topper2145bc02014-05-09 08:15:10 +0000598 while (State.NextToken) {
Daniel Jasperde0328a2013-08-16 11:20:30 +0000599 bool Newline =
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000600 Indenter->mustBreak(State) ||
Daniel Jasperde0328a2013-08-16 11:20:30 +0000601 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
602 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
603 }
604 }
Daniel Jasperf110e202013-08-21 08:39:01 +0000605
Daniel Jasperde0328a2013-08-16 11:20:30 +0000606private:
607 ContinuationIndenter *Indenter;
608};
609
Daniel Jasper56f8b432013-11-06 23:12:09 +0000610class LineJoiner {
611public:
612 LineJoiner(const FormatStyle &Style) : Style(Style) {}
613
614 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
615 unsigned
616 tryFitMultipleLinesInOne(unsigned Indent,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000617 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000618 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
619 // We can never merge stuff if there are trailing line comments.
Daniel Jasper234379f2013-12-24 13:31:25 +0000620 const AnnotatedLine *TheLine = *I;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000621 if (TheLine->Last->is(TT_LineComment))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000622 return 0;
623
Alexander Kornienkoecc232d2013-12-04 13:25:26 +0000624 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
625 return 0;
626
Daniel Jasper98fb6e12013-11-08 17:33:27 +0000627 unsigned Limit =
628 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000629 // If we already exceed the column limit, we set 'Limit' to 0. The different
630 // tryMerge..() functions can then decide whether to still do merging.
631 Limit = TheLine->Last->TotalLength > Limit
632 ? 0
633 : Limit - TheLine->Last->TotalLength;
634
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000635 if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000636 return 0;
637
Daniel Jasperd74cf402014-04-08 12:46:38 +0000638 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
639 // If necessary, change to something smarter.
640 bool MergeShortFunctions =
641 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
642 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
643 TheLine->Level != 0);
644
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000645 if (TheLine->Last->is(TT_FunctionLBrace) &&
Daniel Jasper234379f2013-12-24 13:31:25 +0000646 TheLine->First != TheLine->Last) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000647 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000648 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000649 if (TheLine->Last->is(tok::l_brace)) {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000650 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000651 ? tryMergeSimpleBlock(I, E, Limit)
652 : 0;
653 }
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000654 if (I[1]->First->is(TT_FunctionLBrace) &&
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000655 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
Alp Tokerba5b4dc2013-12-30 02:06:29 +0000656 // Check for Limit <= 2 to account for the " {".
Daniel Jasper234379f2013-12-24 13:31:25 +0000657 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
658 return 0;
659 Limit -= 2;
660
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000661 unsigned MergedLines = 0;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000662 if (MergeShortFunctions) {
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000663 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
664 // If we managed to merge the block, count the function header, which is
665 // on a separate line.
666 if (MergedLines > 0)
667 ++MergedLines;
668 }
669 return MergedLines;
670 }
671 if (TheLine->First->is(tok::kw_if)) {
672 return Style.AllowShortIfStatementsOnASingleLine
673 ? tryMergeSimpleControlStatement(I, E, Limit)
674 : 0;
675 }
676 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
677 return Style.AllowShortLoopsOnASingleLine
678 ? tryMergeSimpleControlStatement(I, E, Limit)
679 : 0;
680 }
Daniel Jasperb87899b2014-09-10 13:11:45 +0000681 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
682 return Style.AllowShortCaseLabelsOnASingleLine
683 ? tryMergeShortCaseLabels(I, E, Limit)
684 : 0;
685 }
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000686 if (TheLine->InPPDirective &&
687 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000688 return tryMergeSimplePPDirective(I, E, Limit);
689 }
690 return 0;
691 }
692
693private:
694 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000695 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000696 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
697 unsigned Limit) {
698 if (Limit == 0)
699 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000700 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000701 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000702 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000703 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000704 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000705 return 0;
706 return 1;
707 }
708
709 unsigned tryMergeSimpleControlStatement(
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000710 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000711 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
712 if (Limit == 0)
713 return 0;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000714 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
715 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
Daniel Jasper17605d32014-05-14 09:33:35 +0000716 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000717 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000718 if (I[1]->InPPDirective != (*I)->InPPDirective ||
719 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000720 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000721 Limit = limitConsideringMacros(I + 1, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000722 AnnotatedLine &Line = **I;
723 if (Line.Last->isNot(tok::r_paren))
724 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000725 if (1 + I[1]->Last->TotalLength > Limit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000726 return 0;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000727 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000728 tok::kw_while, TT_LineComment))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000729 return 0;
730 // Only inline simple if's (no nested if or else).
731 if (I + 2 != E && Line.First->is(tok::kw_if) &&
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000732 I[2]->First->is(tok::kw_else))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000733 return 0;
734 return 1;
735 }
736
Daniel Jasperb87899b2014-09-10 13:11:45 +0000737 unsigned tryMergeShortCaseLabels(
738 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
739 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
740 if (Limit == 0 || I + 1 == E ||
741 I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
742 return 0;
743 unsigned NumStmts = 0;
744 unsigned Length = 0;
Daniel Jasper79f226e2014-11-23 21:45:03 +0000745 bool InPPDirective = I[0]->InPPDirective;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000746 for (; NumStmts < 3; ++NumStmts) {
747 if (I + 1 + NumStmts == E)
748 break;
749 const AnnotatedLine *Line = I[1 + NumStmts];
Daniel Jasper79f226e2014-11-23 21:45:03 +0000750 if (Line->InPPDirective != InPPDirective)
751 break;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000752 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
753 break;
754 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
Daniel Jasperd081e882014-11-21 12:36:25 +0000755 tok::kw_while, tok::comment))
Daniel Jasperb87899b2014-09-10 13:11:45 +0000756 return 0;
757 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
758 }
759 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
760 return 0;
761 return NumStmts;
762 }
763
Daniel Jasper56f8b432013-11-06 23:12:09 +0000764 unsigned
Alexander Kornienko3cfa9732013-11-20 16:33:05 +0000765 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper56f8b432013-11-06 23:12:09 +0000766 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
767 unsigned Limit) {
Daniel Jasper56f8b432013-11-06 23:12:09 +0000768 AnnotatedLine &Line = **I;
Daniel Jasper17605d32014-05-14 09:33:35 +0000769
770 // Don't merge ObjC @ keywords and methods.
771 if (Line.First->isOneOf(tok::at, tok::minus, tok::plus))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000772 return 0;
773
Daniel Jasper17605d32014-05-14 09:33:35 +0000774 // Check that the current line allows merging. This depends on whether we
775 // are in a control flow statements as well as several style flags.
776 if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
777 return 0;
778 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
779 tok::kw_catch, tok::kw_for, tok::r_brace)) {
780 if (!Style.AllowShortBlocksOnASingleLine)
781 return 0;
782 if (!Style.AllowShortIfStatementsOnASingleLine &&
783 Line.First->is(tok::kw_if))
784 return 0;
785 if (!Style.AllowShortLoopsOnASingleLine &&
786 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
787 return 0;
788 // FIXME: Consider an option to allow short exception handling clauses on
789 // a single line.
790 if (Line.First->isOneOf(tok::kw_try, tok::kw_catch))
791 return 0;
792 }
793
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000794 FormatToken *Tok = I[1]->First;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000795 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Craig Topper2145bc02014-05-09 08:15:10 +0000796 (Tok->getNextNonComment() == nullptr ||
Daniel Jasper56f8b432013-11-06 23:12:09 +0000797 Tok->getNextNonComment()->is(tok::semi))) {
798 // We merge empty blocks even if the line exceeds the column limit.
799 Tok->SpacesRequiredBefore = 0;
800 Tok->CanBreakBefore = true;
801 return 1;
Nico Weber34272652014-11-13 16:25:37 +0000802 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace) &&
803 !startsExternCBlock(Line)) {
Daniel Jasper79dffb42014-05-07 09:48:30 +0000804 // We don't merge short records.
805 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
806 return 0;
807
Daniel Jasper56f8b432013-11-06 23:12:09 +0000808 // Check that we still have three lines and they fit into the limit.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000809 if (I + 2 == E || I[2]->Type == LT_Invalid)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000810 return 0;
Daniel Jaspera0407742014-02-11 10:08:11 +0000811 Limit = limitConsideringMacros(I + 2, E, Limit);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000812
813 if (!nextTwoLinesFitInto(I, Limit))
814 return 0;
815
816 // Second, check that the next line does not contain any braces - if it
817 // does, readability declines when putting it into a single line.
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000818 if (I[1]->Last->is(TT_LineComment))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000819 return 0;
820 do {
Daniel Jasperbd630732014-05-22 13:25:26 +0000821 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
Daniel Jasper56f8b432013-11-06 23:12:09 +0000822 return 0;
823 Tok = Tok->Next;
Craig Topper2145bc02014-05-09 08:15:10 +0000824 } while (Tok);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000825
Daniel Jasper79dffb42014-05-07 09:48:30 +0000826 // Last, check that the third line starts with a closing brace.
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000827 Tok = I[2]->First;
Daniel Jasper79dffb42014-05-07 09:48:30 +0000828 if (Tok->isNot(tok::r_brace))
Daniel Jasper56f8b432013-11-06 23:12:09 +0000829 return 0;
830
831 return 2;
832 }
833 return 0;
834 }
835
Daniel Jasper64989962014-02-07 13:45:27 +0000836 /// Returns the modified column limit for \p I if it is inside a macro and
837 /// needs a trailing '\'.
838 unsigned
Daniel Jaspera0407742014-02-11 10:08:11 +0000839 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
Daniel Jasper64989962014-02-07 13:45:27 +0000840 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
841 unsigned Limit) {
842 if (I[0]->InPPDirective && I + 1 != E &&
843 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
844 return Limit < 2 ? 0 : Limit - 2;
845 }
846 return Limit;
847 }
848
Daniel Jasper56f8b432013-11-06 23:12:09 +0000849 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
850 unsigned Limit) {
Dinesh Dwivediafe6fb62014-05-05 11:36:35 +0000851 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
852 return false;
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000853 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000854 }
855
Daniel Jasper234379f2013-12-24 13:31:25 +0000856 bool containsMustBreak(const AnnotatedLine *Line) {
857 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
858 if (Tok->MustBreakBefore)
859 return true;
860 }
861 return false;
862 }
863
Daniel Jasper56f8b432013-11-06 23:12:09 +0000864 const FormatStyle &Style;
865};
866
Daniel Jasperf7935112012-12-03 18:12:45 +0000867class UnwrappedLineFormatter {
868public:
Daniel Jasper5500f612013-11-25 11:08:59 +0000869 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000870 WhitespaceManager *Whitespaces,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000871 const FormatStyle &Style)
Daniel Jasper5500f612013-11-25 11:08:59 +0000872 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
873 Joiner(Style) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000874
Daniel Jasper56f8b432013-11-06 23:12:09 +0000875 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
Daniel Jasper9c199562013-11-28 15:58:55 +0000876 int AdditionalIndent = 0, bool FixBadIndentation = false) {
Daniel Jasperc359ad02014-04-15 08:13:47 +0000877 // Try to look up already computed penalty in DryRun-mode.
NAKAMURA Takumi22059522014-04-15 23:29:04 +0000878 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
879 &Lines, AdditionalIndent);
Daniel Jasperc359ad02014-04-15 08:13:47 +0000880 auto CacheIt = PenaltyCache.find(CacheKey);
881 if (DryRun && CacheIt != PenaltyCache.end())
882 return CacheIt->second;
883
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000884 assert(!Lines.empty());
885 unsigned Penalty = 0;
886 std::vector<int> IndentForLevel;
887 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
888 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
Craig Topper2145bc02014-05-09 08:15:10 +0000889 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper56f8b432013-11-06 23:12:09 +0000890 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
891 E = Lines.end();
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000892 I != E; ++I) {
893 const AnnotatedLine &TheLine = **I;
894 const FormatToken *FirstTok = TheLine.First;
895 int Offset = getIndentOffset(*FirstTok);
896
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000897 // Determine indent and try to merge multiple unwrapped lines.
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000898 unsigned Indent;
899 if (TheLine.InPPDirective) {
900 Indent = TheLine.Level * Style.IndentWidth;
901 } else {
902 while (IndentForLevel.size() <= TheLine.Level)
903 IndentForLevel.push_back(-1);
904 IndentForLevel.resize(TheLine.Level + 1);
905 Indent = getIndent(IndentForLevel, TheLine.Level);
906 }
907 unsigned LevelIndent = Indent;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000908 if (static_cast<int>(Indent) + Offset >= 0)
909 Indent += Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000910
911 // Merge multiple lines if possible.
Daniel Jasper56f8b432013-11-06 23:12:09 +0000912 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
Alexander Kornienko31e95542013-12-04 12:21:08 +0000913 if (MergedLines > 0 && Style.ColumnLimit == 0) {
914 // Disallow line merging if there is a break at the start of one of the
915 // input lines.
916 for (unsigned i = 0; i < MergedLines; ++i) {
917 if (I[i + 1]->First->NewlinesBefore > 0)
918 MergedLines = 0;
919 }
920 }
Daniel Jasper56f8b432013-11-06 23:12:09 +0000921 if (!DryRun) {
922 for (unsigned i = 0; i < MergedLines; ++i) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000923 join(*I[i], *I[i + 1]);
Daniel Jasper56f8b432013-11-06 23:12:09 +0000924 }
925 }
926 I += MergedLines;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000927
Daniel Jasper9c199562013-11-28 15:58:55 +0000928 bool FixIndentation =
929 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000930 if (TheLine.First->is(tok::eof)) {
Daniel Jasper5500f612013-11-25 11:08:59 +0000931 if (PreviousLine && PreviousLine->Affected && !DryRun) {
932 // Remove the file's trailing whitespace.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000933 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
934 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
935 /*IndentLevel=*/0, /*Spaces=*/0,
936 /*TargetColumn=*/0);
937 }
Daniel Jasper9c199562013-11-28 15:58:55 +0000938 } else if (TheLine.Type != LT_Invalid &&
939 (TheLine.Affected || FixIndentation)) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000940 if (FirstTok->WhitespaceRange.isValid()) {
941 if (!DryRun)
942 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
943 Indent, TheLine.InPPDirective);
944 } else {
945 Indent = LevelIndent = FirstTok->OriginalColumn;
946 }
947
948 // If everything fits on a single line, just put it there.
949 unsigned ColumnLimit = Style.ColumnLimit;
950 if (I + 1 != E) {
Alexander Kornienkoc3021612013-11-19 14:30:44 +0000951 AnnotatedLine *NextLine = I[1];
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000952 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
953 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
954 }
955
Daniel Jasper616de8642014-11-23 16:46:28 +0000956 if (TheLine.Last->TotalLength + Indent <= ColumnLimit ||
957 TheLine.Type == LT_ImportStatement) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000958 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000959 while (State.NextToken) {
960 formatChildren(State, /*Newline=*/false, /*DryRun=*/false, Penalty);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000961 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
Daniel Jasper5f3ea472014-05-22 08:36:53 +0000962 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000963 } else if (Style.ColumnLimit == 0) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000964 // FIXME: Implement nested blocks for ColumnLimit = 0.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000965 NoColumnLimitFormatter Formatter(Indenter);
966 if (!DryRun)
Alexander Kornienkoa594ba82013-12-16 14:35:51 +0000967 Formatter.format(Indent, &TheLine);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000968 } else {
969 Penalty += format(TheLine, Indent, DryRun);
970 }
971
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000972 if (!TheLine.InPPDirective)
973 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper9c199562013-11-28 15:58:55 +0000974 } else if (TheLine.ChildrenAffected) {
975 format(TheLine.Children, DryRun);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000976 } else {
977 // Format the first token if necessary, and notify the WhitespaceManager
978 // about the unchanged whitespace.
Craig Topper2145bc02014-05-09 08:15:10 +0000979 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000980 if (Tok == TheLine.First &&
981 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
982 unsigned LevelIndent = Tok->OriginalColumn;
983 if (!DryRun) {
Daniel Jasper9c199562013-11-28 15:58:55 +0000984 // Remove trailing whitespace of the previous line.
Daniel Jasper5500f612013-11-25 11:08:59 +0000985 if ((PreviousLine && PreviousLine->Affected) ||
986 TheLine.LeadingEmptyLinesAffected) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000987 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
988 TheLine.InPPDirective);
989 } else {
990 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
991 }
992 }
993
994 if (static_cast<int>(LevelIndent) - Offset >= 0)
995 LevelIndent -= Offset;
Daniel Jasperbad63ae2013-12-17 12:38:55 +0000996 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +0000997 IndentForLevel[TheLine.Level] = LevelIndent;
998 } else if (!DryRun) {
999 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
1000 }
1001 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001002 }
1003 if (!DryRun) {
Craig Topper2145bc02014-05-09 08:15:10 +00001004 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001005 Tok->Finalized = true;
1006 }
1007 }
1008 PreviousLine = *I;
1009 }
Daniel Jasperc359ad02014-04-15 08:13:47 +00001010 PenaltyCache[CacheKey] = Penalty;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001011 return Penalty;
1012 }
1013
1014private:
1015 /// \brief Formats an \c AnnotatedLine and returns the penalty.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001016 ///
1017 /// If \p DryRun is \c false, directly applies the changes.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001018 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
1019 bool DryRun) {
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001020 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
Daniel Jasper4b866272013-02-01 11:00:45 +00001021
Daniel Jasperacc33662013-02-08 08:22:00 +00001022 // If the ObjC method declaration does not fit on a line, we should format
1023 // it with one arg per line.
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001024 if (State.Line->Type == LT_ObjCMethodDecl)
Daniel Jasperacc33662013-02-08 08:22:00 +00001025 State.Stack.back().BreakBeforeParameter = true;
1026
Daniel Jasper4b866272013-02-01 11:00:45 +00001027 // Find best solution in solution space.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001028 return analyzeSolutionSpace(State, DryRun);
Daniel Jasperf7935112012-12-03 18:12:45 +00001029 }
1030
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001031 /// \brief An edge in the solution space from \c Previous->State to \c State,
1032 /// inserting a newline dependent on the \c NewLine.
1033 struct StateNode {
1034 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001035 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001036 LineState State;
1037 bool NewLine;
1038 StateNode *Previous;
1039 };
Daniel Jasper4b866272013-02-01 11:00:45 +00001040
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001041 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
1042 ///
1043 /// In case of equal penalties, we want to prefer states that were inserted
1044 /// first. During state generation we make sure that we insert states first
1045 /// that break the line as late as possible.
1046 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1047
1048 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
1049 /// \c State has the given \c OrderedPenalty.
1050 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1051
1052 /// \brief The BFS queue type.
1053 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1054 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +00001055
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001056 /// \brief Get the offset of the line relatively to the level.
1057 ///
1058 /// For example, 'public:' labels in classes are offset by 1 or 2
1059 /// characters to the left from their level.
1060 int getIndentOffset(const FormatToken &RootToken) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001061 if (Style.Language == FormatStyle::LK_Java)
1062 return 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001063 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
1064 return Style.AccessModifierOffset;
1065 return 0;
1066 }
1067
1068 /// \brief Add a new line and the required indent before the first Token
1069 /// of the \c UnwrappedLine if there was no structural parsing error.
1070 void formatFirstToken(FormatToken &RootToken,
1071 const AnnotatedLine *PreviousLine, unsigned IndentLevel,
1072 unsigned Indent, bool InPPDirective) {
1073 unsigned Newlines =
1074 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1075 // Remove empty lines before "}" where applicable.
1076 if (RootToken.is(tok::r_brace) &&
1077 (!RootToken.Next ||
1078 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1079 Newlines = std::min(Newlines, 1u);
1080 if (Newlines == 0 && !RootToken.IsFirst)
1081 Newlines = 1;
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001082 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1083 Newlines = 0;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001084
Daniel Jasper11164bd2014-03-21 12:58:53 +00001085 // Remove empty lines after "{".
Daniel Jaspera26fc5c2014-03-21 13:43:14 +00001086 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1087 PreviousLine->Last->is(tok::l_brace) &&
Nico Weber34272652014-11-13 16:25:37 +00001088 PreviousLine->First->isNot(tok::kw_namespace) &&
1089 !startsExternCBlock(*PreviousLine))
Daniel Jasper11164bd2014-03-21 12:58:53 +00001090 Newlines = 1;
1091
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001092 // Insert extra new line before access specifiers.
1093 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1094 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1095 ++Newlines;
1096
1097 // Remove empty lines after access specifiers.
1098 if (PreviousLine && PreviousLine->First->isAccessSpecifier())
1099 Newlines = std::min(1u, Newlines);
1100
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001101 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
1102 Indent, InPPDirective &&
1103 !RootToken.HasUnescapedNewline);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001104 }
1105
1106 /// \brief Get the indent of \p Level from \p IndentForLevel.
1107 ///
1108 /// \p IndentForLevel must contain the indent for the level \c l
1109 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1110 /// that level is unknown.
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001111 unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001112 if (IndentForLevel[Level] != -1)
1113 return IndentForLevel[Level];
1114 if (Level == 0)
1115 return 0;
1116 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
1117 }
1118
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001119 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1120 assert(!A.Last->Next);
1121 assert(!B.First->Previous);
Daniel Jasper5500f612013-11-25 11:08:59 +00001122 if (B.Affected)
1123 A.Affected = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001124 A.Last->Next = B.First;
1125 B.First->Previous = A.Last;
Daniel Jasper98fb6e12013-11-08 17:33:27 +00001126 B.First->CanBreakBefore = true;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001127 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1128 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1129 Tok->TotalLength += LengthA;
1130 A.Last = Tok;
1131 }
1132 }
1133
1134 unsigned getColumnLimit(bool InPPDirective) const {
1135 // In preprocessor directives reserve two chars for trailing " \"
1136 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
1137 }
1138
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001139 struct CompareLineStatePointers {
1140 bool operator()(LineState *obj1, LineState *obj2) const {
1141 return *obj1 < *obj2;
1142 }
1143 };
1144
Daniel Jasper4b866272013-02-01 11:00:45 +00001145 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +00001146 ///
Daniel Jasper4b866272013-02-01 11:00:45 +00001147 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1148 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1149 /// find the shortest path (the one with lowest penalty) from \p InitialState
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001150 /// to a state where all tokens are placed. Returns the penalty.
1151 ///
1152 /// If \p DryRun is \c false, directly applies the changes.
1153 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001154 std::set<LineState *, CompareLineStatePointers> Seen;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001155
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001156 // Increasing count of \c StateNode items we have created. This is used to
1157 // create a deterministic order independent of the container.
1158 unsigned Count = 0;
1159 QueueType Queue;
1160
Daniel Jasper4b866272013-02-01 11:00:45 +00001161 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001162 StateNode *Node =
Craig Topper2145bc02014-05-09 08:15:10 +00001163 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001164 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1165 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001166
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001167 unsigned Penalty = 0;
1168
Daniel Jasper4b866272013-02-01 11:00:45 +00001169 // While not empty, take first element and follow edges.
1170 while (!Queue.empty()) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001171 Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001172 StateNode *Node = Queue.top().second;
Craig Topper2145bc02014-05-09 08:15:10 +00001173 if (!Node->State.NextToken) {
Alexander Kornienko49149672013-05-10 11:56:10 +00001174 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001175 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001176 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001177 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001178
Daniel Jasperf8114cf2013-05-22 05:27:42 +00001179 // Cut off the analysis of certain solutions if the analysis gets too
1180 // complex. See description of IgnoreStackForComparison.
1181 if (Count > 10000)
1182 Node->State.IgnoreStackForComparison = true;
1183
Daniel Jasper1f6c7e92014-05-22 11:47:01 +00001184 if (!Seen.insert(&Node->State).second)
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001185 // State already examined with lower penalty.
1186 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001187
Manuel Klimek71814b42013-10-11 21:25:45 +00001188 FormatDecision LastFormat = Node->State.NextToken->Decision;
1189 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001190 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
Manuel Klimek71814b42013-10-11 21:25:45 +00001191 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001192 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
Daniel Jasper4b866272013-02-01 11:00:45 +00001193 }
1194
Manuel Klimek71814b42013-10-11 21:25:45 +00001195 if (Queue.empty()) {
Daniel Jasper4b866272013-02-01 11:00:45 +00001196 // We were unable to find a solution, do nothing.
1197 // FIXME: Add diagnostic?
Manuel Klimek71814b42013-10-11 21:25:45 +00001198 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001199 return 0;
Manuel Klimek71814b42013-10-11 21:25:45 +00001200 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001201
Daniel Jasper4b866272013-02-01 11:00:45 +00001202 // Reconstruct the solution.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001203 if (!DryRun)
1204 reconstructPath(InitialState, Queue.top().second);
1205
Alexander Kornienko49149672013-05-10 11:56:10 +00001206 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1207 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001208
1209 return Penalty;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001210 }
1211
1212 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001213 std::deque<StateNode *> Path;
1214 // We do not need a break before the initial token.
1215 while (Current->Previous) {
1216 Path.push_front(Current);
1217 Current = Current->Previous;
1218 }
1219 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1220 I != E; ++I) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001221 unsigned Penalty = 0;
1222 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1223 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1224
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001225 DEBUG({
1226 if ((*I)->NewLine) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001227 llvm::dbgs() << "Penalty for placing "
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001228 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001229 << Penalty << "\n";
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001230 }
1231 });
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001232 }
Daniel Jasper4b866272013-02-01 11:00:45 +00001233 }
1234
Manuel Klimekaf491072013-02-13 10:54:19 +00001235 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001236 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001237 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001238 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001239 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001240 bool NewLine, unsigned *Count, QueueType *Queue) {
Daniel Jasperde0328a2013-08-16 11:20:30 +00001241 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001242 return;
Daniel Jasperde0328a2013-08-16 11:20:30 +00001243 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001244 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001245
1246 StateNode *Node = new (Allocator.Allocate())
1247 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001248 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1249 return;
1250
Daniel Jasperde0328a2013-08-16 11:20:30 +00001251 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001252
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001253 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1254 ++(*Count);
Daniel Jasper4b866272013-02-01 11:00:45 +00001255 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001256
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001257 /// \brief If the \p State's next token is an r_brace closing a nested block,
1258 /// format the nested block before it.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001259 ///
1260 /// Returns \c true if all children could be placed successfully and adapts
1261 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1262 /// creates changes using \c Whitespaces.
1263 ///
1264 /// The crucial idea here is that children always get formatted upon
1265 /// encountering the closing brace right after the nested block. Now, if we
1266 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1267 /// \c false), the entire block has to be kept on the same line (which is only
1268 /// possible if it fits on the line, only contains a single statement, etc.
1269 ///
1270 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1271 /// break after the "{", format all lines with correct indentation and the put
1272 /// the closing "}" on yet another new line.
1273 ///
1274 /// This enables us to keep the simple structure of the
1275 /// \c UnwrappedLineFormatter, where we only have two options for each token:
1276 /// break or don't break.
1277 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1278 unsigned &Penalty) {
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001279 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001280 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1281 if (!LBrace || LBrace->isNot(tok::l_brace) ||
1282 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
Daniel Jasperf3a5d002013-09-05 10:48:50 +00001283 // The previous token does not open a block. Nothing to do. We don't
1284 // assert so that we can simply call this function for all tokens.
Daniel Jasper36c28ce2013-09-06 08:54:24 +00001285 return true;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001286
1287 if (NewLine) {
Daniel Jasper58cb2ed2014-06-06 13:49:04 +00001288 int AdditionalIndent =
1289 State.FirstIndent - State.Line->Level * Style.IndentWidth;
Daniel Jasperb16b9692014-05-21 12:51:23 +00001290 if (State.Stack.size() < 2 ||
Daniel Jasper4b444492014-11-21 13:38:53 +00001291 !State.Stack[State.Stack.size() - 2].NestedBlockInlined) {
Daniel Jasperb16b9692014-05-21 12:51:23 +00001292 AdditionalIndent = State.Stack.back().Indent -
1293 Previous.Children[0]->Level * Style.IndentWidth;
1294 }
1295
Daniel Jasper9c199562013-11-28 15:58:55 +00001296 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
1297 /*FixBadIndentation=*/true);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001298 return true;
1299 }
1300
Daniel Jasper56346192014-10-27 16:31:46 +00001301 if (Previous.Children[0]->First->MustBreakBefore)
1302 return false;
1303
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001304 // Cannot merge multiple statements into a single line.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001305 if (Previous.Children.size() > 1)
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001306 return false;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001307
Daniel Jasper21397a32014-04-09 12:21:48 +00001308 // Cannot merge into one line if this line ends on a comment.
1309 if (Previous.is(tok::comment))
1310 return false;
1311
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001312 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001313 if (Previous.Children[0]->Last->isTrailingComment())
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001314 return false;
1315
Daniel Jasper98583d52014-04-15 08:28:06 +00001316 // If the child line exceeds the column limit, we wouldn't want to merge it.
1317 // We add +2 for the trailing " }".
1318 if (Style.ColumnLimit > 0 &&
1319 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
1320 Style.ColumnLimit)
1321 return false;
1322
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001323 if (!DryRun) {
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001324 Whitespaces->replaceWhitespace(
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001325 *Previous.Children[0]->First,
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00001326 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +00001327 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001328 }
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001329 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001330
Daniel Jasperdcd5da12013-10-20 17:28:32 +00001331 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001332 return true;
1333 }
1334
Daniel Jasperde0328a2013-08-16 11:20:30 +00001335 ContinuationIndenter *Indenter;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001336 WhitespaceManager *Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001337 FormatStyle Style;
Daniel Jasper56f8b432013-11-06 23:12:09 +00001338 LineJoiner Joiner;
Manuel Klimekaf491072013-02-13 10:54:19 +00001339
1340 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
Daniel Jasperc359ad02014-04-15 08:13:47 +00001341
1342 // Cache to store the penalty of formatting a vector of AnnotatedLines
1343 // starting from a specific additional offset. Improves performance if there
1344 // are many nested blocks.
1345 std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
1346 unsigned> PenaltyCache;
Daniel Jasperf7935112012-12-03 18:12:45 +00001347};
1348
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001349class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001350public:
Daniel Jasper23376252014-09-09 14:37:39 +00001351 FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001352 encoding::Encoding Encoding)
Craig Topper2145bc02014-05-09 08:15:10 +00001353 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001354 Column(0), TrailingWhitespace(0), SourceMgr(SourceMgr), ID(ID),
1355 Style(Style), IdentTable(getFormattingLangOpts(Style)),
1356 Keywords(IdentTable), Encoding(Encoding), FirstInLineIndex(0),
1357 FormattingDisabled(false) {
Daniel Jasper23376252014-09-09 14:37:39 +00001358 Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
1359 getFormattingLangOpts(Style)));
1360 Lex->SetKeepWhitespaceMode(true);
Daniel Jaspere1e43192014-04-01 12:55:11 +00001361
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001362 for (const std::string &ForEachMacro : Style.ForEachMacros)
Daniel Jaspere1e43192014-04-01 12:55:11 +00001363 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
1364 std::sort(ForEachMacros.begin(), ForEachMacros.end());
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001365 }
1366
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001367 ArrayRef<FormatToken *> lex() {
1368 assert(Tokens.empty());
Manuel Klimek68b03042014-04-14 09:14:11 +00001369 assert(FirstInLineIndex == 0);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001370 do {
1371 Tokens.push_back(getNextToken());
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001372 tryMergePreviousTokens();
Manuel Klimek68b03042014-04-14 09:14:11 +00001373 if (Tokens.back()->NewlinesBefore > 0)
1374 FirstInLineIndex = Tokens.size() - 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001375 } while (Tokens.back()->Tok.isNot(tok::eof));
1376 return Tokens;
1377 }
1378
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001379 const AdditionalKeywords &getKeywords() { return Keywords; }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001380
1381private:
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001382 void tryMergePreviousTokens() {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001383 if (tryMerge_TMacro())
1384 return;
Manuel Klimek68b03042014-04-14 09:14:11 +00001385 if (tryMergeConflictMarkers())
1386 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001387
1388 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001389 if (tryMergeJSRegexLiteral())
1390 return;
Daniel Jasper23376252014-09-09 14:37:39 +00001391 if (tryMergeEscapeSequence())
1392 return;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001393
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001394 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
1395 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
1396 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
1397 tok::greaterequal };
Daniel Jasper78214392014-05-19 07:27:02 +00001398 static tok::TokenKind JSRightArrow[] = { tok::equal, tok::greater };
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001399 // FIXME: We probably need to change token type to mimic operator with the
1400 // correct priority.
1401 if (tryMergeTokens(JSIdentity))
1402 return;
1403 if (tryMergeTokens(JSNotIdentity))
1404 return;
1405 if (tryMergeTokens(JSShiftEqual))
1406 return;
Daniel Jasper78214392014-05-19 07:27:02 +00001407 if (tryMergeTokens(JSRightArrow))
1408 return;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001409 }
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001410 }
1411
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001412 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
1413 if (Tokens.size() < Kinds.size())
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001414 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001415
1416 SmallVectorImpl<FormatToken *>::const_iterator First =
1417 Tokens.end() - Kinds.size();
1418 if (!First[0]->is(Kinds[0]))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001419 return false;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001420 unsigned AddLength = 0;
1421 for (unsigned i = 1; i < Kinds.size(); ++i) {
1422 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
1423 First[i]->WhitespaceRange.getEnd())
1424 return false;
1425 AddLength += First[i]->TokenText.size();
1426 }
1427 Tokens.resize(Tokens.size() - Kinds.size() + 1);
1428 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
1429 First[0]->TokenText.size() + AddLength);
1430 First[0]->ColumnWidth += AddLength;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001431 return true;
1432 }
1433
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001434 // Tries to merge an escape sequence, i.e. a "\\" and the following
Alp Tokerc3f36af2014-05-15 01:35:53 +00001435 // character. Use e.g. inside JavaScript regex literals.
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001436 bool tryMergeEscapeSequence() {
1437 if (Tokens.size() < 2)
1438 return false;
1439 FormatToken *Previous = Tokens[Tokens.size() - 2];
Daniel Jasper49a9a282014-10-29 16:51:38 +00001440 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\")
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001441 return false;
Daniel Jasper49a9a282014-10-29 16:51:38 +00001442 ++Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001443 StringRef Text = Previous->TokenText;
Daniel Jasper49a9a282014-10-29 16:51:38 +00001444 Previous->TokenText = StringRef(Text.data(), Text.size() + 1);
1445 resetLexer(SourceMgr.getFileOffset(Tokens.back()->Tok.getLocation()) + 1);
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001446 Tokens.resize(Tokens.size() - 1);
Daniel Jasper49a9a282014-10-29 16:51:38 +00001447 Column = Previous->OriginalColumn + Previous->ColumnWidth;
Daniel Jasperfb4333b2014-05-12 11:29:50 +00001448 return true;
1449 }
1450
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001451 // Try to determine whether the current token ends a JavaScript regex literal.
1452 // We heuristically assume that this is a regex literal if we find two
1453 // unescaped slashes on a line and the token before the first slash is one of
Daniel Jasperf7405c12014-05-08 07:45:18 +00001454 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
1455 // a division.
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001456 bool tryMergeJSRegexLiteral() {
Daniel Jasper23376252014-09-09 14:37:39 +00001457 if (Tokens.size() < 2)
1458 return false;
1459 // If a regex literal ends in "\//", this gets represented by an unknown
1460 // token "\" and a comment.
1461 bool MightEndWithEscapedSlash =
1462 Tokens.back()->is(tok::comment) &&
1463 Tokens.back()->TokenText.startswith("//") &&
1464 Tokens[Tokens.size() - 2]->TokenText == "\\";
1465 if (!MightEndWithEscapedSlash &&
1466 (Tokens.back()->isNot(tok::slash) ||
1467 (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
1468 Tokens[Tokens.size() - 2]->TokenText == "\\")))
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001469 return false;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001470 unsigned TokenCount = 0;
1471 unsigned LastColumn = Tokens.back()->OriginalColumn;
1472 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
1473 ++TokenCount;
1474 if (I[0]->is(tok::slash) && I + 1 != E &&
1475 (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
1476 tok::exclaim, tok::l_square, tok::colon, tok::comma,
1477 tok::question, tok::kw_return) ||
1478 I[1]->isBinaryOperator())) {
Daniel Jasper23376252014-09-09 14:37:39 +00001479 if (MightEndWithEscapedSlash) {
Daniel Jasper23376252014-09-09 14:37:39 +00001480 // This regex literal ends in '\//'. Skip past the '//' of the last
1481 // token and re-start lexing from there.
Daniel Jasper49a9a282014-10-29 16:51:38 +00001482 SourceLocation Loc = Tokens.back()->Tok.getLocation();
1483 resetLexer(SourceMgr.getFileOffset(Loc) + 2);
Daniel Jasper23376252014-09-09 14:37:39 +00001484 }
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001485 Tokens.resize(Tokens.size() - TokenCount);
1486 Tokens.back()->Tok.setKind(tok::unknown);
1487 Tokens.back()->Type = TT_RegexLiteral;
1488 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
1489 return true;
1490 }
1491
1492 // There can't be a newline inside a regex literal.
1493 if (I[0]->NewlinesBefore > 0)
1494 return false;
1495 }
1496 return false;
Daniel Jasperf9ae3122014-05-08 07:01:45 +00001497 }
1498
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001499 bool tryMerge_TMacro() {
Alexander Kornienko81e32942013-09-16 20:20:49 +00001500 if (Tokens.size() < 4)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001501 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001502 FormatToken *Last = Tokens.back();
1503 if (!Last->is(tok::r_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001504 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001505
1506 FormatToken *String = Tokens[Tokens.size() - 2];
1507 if (!String->is(tok::string_literal) || String->IsMultiline)
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001508 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001509
1510 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001511 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001512
1513 FormatToken *Macro = Tokens[Tokens.size() - 4];
1514 if (Macro->TokenText != "_T")
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001515 return false;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001516
1517 const char *Start = Macro->TokenText.data();
1518 const char *End = Last->TokenText.data() + Last->TokenText.size();
1519 String->TokenText = StringRef(Start, End - Start);
1520 String->IsFirst = Macro->IsFirst;
1521 String->LastNewlineOffset = Macro->LastNewlineOffset;
1522 String->WhitespaceRange = Macro->WhitespaceRange;
1523 String->OriginalColumn = Macro->OriginalColumn;
1524 String->ColumnWidth = encoding::columnWidthWithTabs(
1525 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1526
1527 Tokens.pop_back();
1528 Tokens.pop_back();
1529 Tokens.pop_back();
1530 Tokens.back() = String;
Alexander Kornienko9aa62402013-11-21 12:43:57 +00001531 return true;
Alexander Kornienko81e32942013-09-16 20:20:49 +00001532 }
1533
Manuel Klimek68b03042014-04-14 09:14:11 +00001534 bool tryMergeConflictMarkers() {
1535 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1536 return false;
1537
1538 // Conflict lines look like:
1539 // <marker> <text from the vcs>
1540 // For example:
1541 // >>>>>>> /file/in/file/system at revision 1234
1542 //
1543 // We merge all tokens in a line that starts with a conflict marker
1544 // into a single token with a special token type that the unwrapped line
1545 // parser will use to correctly rebuild the underlying code.
1546
1547 FileID ID;
1548 // Get the position of the first token in the line.
1549 unsigned FirstInLineOffset;
1550 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1551 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1552 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1553 // Calculate the offset of the start of the current line.
1554 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1555 if (LineOffset == StringRef::npos) {
1556 LineOffset = 0;
1557 } else {
1558 ++LineOffset;
1559 }
1560
1561 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1562 StringRef LineStart;
1563 if (FirstSpace == StringRef::npos) {
1564 LineStart = Buffer.substr(LineOffset);
1565 } else {
1566 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1567 }
1568
1569 TokenType Type = TT_Unknown;
1570 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1571 Type = TT_ConflictStart;
1572 } else if (LineStart == "|||||||" || LineStart == "=======" ||
1573 LineStart == "====") {
1574 Type = TT_ConflictAlternative;
1575 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1576 Type = TT_ConflictEnd;
1577 }
1578
1579 if (Type != TT_Unknown) {
1580 FormatToken *Next = Tokens.back();
1581
1582 Tokens.resize(FirstInLineIndex + 1);
1583 // We do not need to build a complete token here, as we will skip it
1584 // during parsing anyway (as we must not touch whitespace around conflict
1585 // markers).
1586 Tokens.back()->Type = Type;
1587 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1588
1589 Tokens.push_back(Next);
1590 return true;
1591 }
1592
1593 return false;
1594 }
1595
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001596 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001597 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001598 // Create a synthesized second '>' token.
Manuel Klimek31c85922013-08-29 15:21:40 +00001599 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001600 Token Greater = FormatTok->Tok;
1601 FormatTok = new (Allocator.Allocate()) FormatToken;
1602 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001603 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001604 FormatTok->Tok.getLocation().getLocWithOffset(1);
1605 FormatTok->WhitespaceRange =
1606 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001607 FormatTok->TokenText = ">";
Alexander Kornienko39856b72013-09-10 09:38:25 +00001608 FormatTok->ColumnWidth = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001609 GreaterStashed = false;
1610 return FormatTok;
1611 }
1612
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001613 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001614 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001615 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001616 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Alexander Kornienko393e3082013-11-13 14:04:17 +00001617 FormatTok->IsFirst = IsFirstToken;
1618 IsFirstToken = false;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001619
1620 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001621 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001622 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001623 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
1624 switch (FormatTok->TokenText[i]) {
1625 case '\n':
1626 ++FormatTok->NewlinesBefore;
1627 // FIXME: This is technically incorrect, as it could also
1628 // be a literal backslash at the end of the line.
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001629 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
1630 (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
1631 FormatTok->TokenText[i - 2] != '\\')))
Manuel Klimek31c85922013-08-29 15:21:40 +00001632 FormatTok->HasUnescapedNewline = true;
1633 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1634 Column = 0;
1635 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001636 case '\r':
1637 case '\f':
1638 case '\v':
1639 Column = 0;
1640 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001641 case ' ':
1642 ++Column;
1643 break;
1644 case '\t':
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +00001645 Column += Style.TabWidth - Column % Style.TabWidth;
Manuel Klimek31c85922013-08-29 15:21:40 +00001646 break;
Daniel Jasper877615c2013-10-11 19:45:02 +00001647 case '\\':
1648 ++Column;
1649 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
1650 FormatTok->TokenText[i + 1] != '\n'))
1651 FormatTok->Type = TT_ImplicitStringLiteral;
1652 break;
Manuel Klimek31c85922013-08-29 15:21:40 +00001653 default:
Daniel Jasper877615c2013-10-11 19:45:02 +00001654 FormatTok->Type = TT_ImplicitStringLiteral;
Manuel Klimek31c85922013-08-29 15:21:40 +00001655 ++Column;
1656 break;
1657 }
1658 }
1659
Daniel Jaspera98b7b02014-11-25 10:05:17 +00001660 if (FormatTok->is(TT_ImplicitStringLiteral))
Daniel Jasper877615c2013-10-11 19:45:02 +00001661 break;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001662 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001663
Daniel Jasper8369aa52013-07-16 20:28:33 +00001664 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001665 }
Manuel Klimekef920692013-01-07 07:56:50 +00001666
Manuel Klimek1abf7892013-01-04 23:34:14 +00001667 // In case the token starts with escaped newlines, we want to
1668 // take them into account as whitespace - this pattern is quite frequent
1669 // in macro definitions.
Manuel Klimek1abf7892013-01-04 23:34:14 +00001670 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001671 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1672 FormatTok->TokenText[1] == '\n') {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00001673 ++FormatTok->NewlinesBefore;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001674 WhitespaceLength += 2;
Manuel Klimek31c85922013-08-29 15:21:40 +00001675 Column = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001676 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001677 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001678
1679 FormatTok->WhitespaceRange = SourceRange(
1680 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1681
Manuel Klimek31c85922013-08-29 15:21:40 +00001682 FormatTok->OriginalColumn = Column;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001683
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001684 TrailingWhitespace = 0;
1685 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimek31c85922013-08-29 15:21:40 +00001686 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001687 StringRef UntrimmedText = FormatTok->TokenText;
Alexander Kornienko9ab4a772013-09-06 17:24:54 +00001688 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
Daniel Jasper8369aa52013-07-16 20:28:33 +00001689 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001690 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001691 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001692 FormatTok->Tok.setIdentifierInfo(&Info);
1693 FormatTok->Tok.setKind(Info.getTokenID());
Daniel Jasperfe2cf662014-11-19 14:11:11 +00001694 if (Style.Language == FormatStyle::LK_Java &&
1695 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete)) {
1696 FormatTok->Tok.setKind(tok::identifier);
1697 FormatTok->Tok.setIdentifierInfo(nullptr);
1698 }
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001699 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001700 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001701 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001702 GreaterStashed = true;
1703 }
1704
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001705 // Now FormatTok is the next non-whitespace token.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001706
Alexander Kornienko39856b72013-09-10 09:38:25 +00001707 StringRef Text = FormatTok->TokenText;
1708 size_t FirstNewlinePos = Text.find('\n');
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001709 if (FirstNewlinePos == StringRef::npos) {
1710 // FIXME: ColumnWidth actually depends on the start column, we need to
1711 // take this into account when the token is moved.
1712 FormatTok->ColumnWidth =
1713 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1714 Column += FormatTok->ColumnWidth;
1715 } else {
Alexander Kornienko39856b72013-09-10 09:38:25 +00001716 FormatTok->IsMultiline = true;
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001717 // FIXME: ColumnWidth actually depends on the start column, we need to
1718 // take this into account when the token is moved.
1719 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1720 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1721
Alexander Kornienko39856b72013-09-10 09:38:25 +00001722 // The last line of the token always starts in column 0.
1723 // Thus, the length can be precomputed even in the presence of tabs.
1724 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1725 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1726 Encoding);
Alexander Kornienko917f9e02013-09-10 12:29:48 +00001727 Column = FormatTok->LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +00001728 }
Alexander Kornienko39856b72013-09-10 09:38:25 +00001729
Daniel Jaspere1e43192014-04-01 12:55:11 +00001730 FormatTok->IsForEachMacro =
1731 std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
1732 FormatTok->Tok.getIdentifierInfo());
1733
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001734 return FormatTok;
1735 }
1736
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001737 FormatToken *FormatTok;
Alexander Kornienko393e3082013-11-13 14:04:17 +00001738 bool IsFirstToken;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001739 bool GreaterStashed;
Manuel Klimek31c85922013-08-29 15:21:40 +00001740 unsigned Column;
Manuel Klimek9043c742013-05-27 15:23:34 +00001741 unsigned TrailingWhitespace;
Daniel Jasper23376252014-09-09 14:37:39 +00001742 std::unique_ptr<Lexer> Lex;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001743 SourceManager &SourceMgr;
Daniel Jasper23376252014-09-09 14:37:39 +00001744 FileID ID;
Manuel Klimek31c85922013-08-29 15:21:40 +00001745 FormatStyle &Style;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001746 IdentifierTable IdentTable;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001747 AdditionalKeywords Keywords;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001748 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001749 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
Manuel Klimek68b03042014-04-14 09:14:11 +00001750 // Index (in 'Tokens') of the last token that starts a new line.
1751 unsigned FirstInLineIndex;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001752 SmallVector<FormatToken *, 16> Tokens;
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001753 SmallVector<IdentifierInfo *, 8> ForEachMacros;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001754
NAKAMURA Takumi7160c4d2014-08-06 16:53:13 +00001755 bool FormattingDisabled;
Daniel Jasper471894432014-08-06 13:40:26 +00001756
Daniel Jasper8369aa52013-07-16 20:28:33 +00001757 void readRawToken(FormatToken &Tok) {
Daniel Jasper23376252014-09-09 14:37:39 +00001758 Lex->LexFromRawLexer(Tok.Tok);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001759 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1760 Tok.Tok.getLength());
Daniel Jasper8369aa52013-07-16 20:28:33 +00001761 // For formatting, treat unterminated string literals like normal string
1762 // literals.
Daniel Jasper86fee2f2014-01-31 12:49:42 +00001763 if (Tok.is(tok::unknown)) {
1764 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1765 Tok.Tok.setKind(tok::string_literal);
1766 Tok.IsUnterminatedLiteral = true;
1767 } else if (Style.Language == FormatStyle::LK_JavaScript &&
1768 Tok.TokenText == "''") {
1769 Tok.Tok.setKind(tok::char_constant);
1770 }
Daniel Jasper8369aa52013-07-16 20:28:33 +00001771 }
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001772
1773 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1774 Tok.TokenText == "/* clang-format on */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001775 FormattingDisabled = false;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001776 }
1777
Daniel Jasper471894432014-08-06 13:40:26 +00001778 Tok.Finalized = FormattingDisabled;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001779
1780 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1781 Tok.TokenText == "/* clang-format off */")) {
Daniel Jasper471894432014-08-06 13:40:26 +00001782 FormattingDisabled = true;
Roman Kashitsyn650ecb52014-09-11 14:47:20 +00001783 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001784 }
Daniel Jasper49a9a282014-10-29 16:51:38 +00001785
1786 void resetLexer(unsigned Offset) {
1787 StringRef Buffer = SourceMgr.getBufferData(ID);
1788 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1789 getFormattingLangOpts(Style), Buffer.begin(),
1790 Buffer.begin() + Offset, Buffer.end()));
1791 Lex->SetKeepWhitespaceMode(true);
1792 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001793};
1794
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001795static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1796 switch (Language) {
1797 case FormatStyle::LK_Cpp:
1798 return "C++";
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001799 case FormatStyle::LK_Java:
1800 return "Java";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001801 case FormatStyle::LK_JavaScript:
1802 return "JavaScript";
Daniel Jasper7052ce62014-01-19 09:04:08 +00001803 case FormatStyle::LK_Proto:
1804 return "Proto";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001805 default:
1806 return "Unknown";
1807 }
1808}
1809
Daniel Jasperf7935112012-12-03 18:12:45 +00001810class Formatter : public UnwrappedLineConsumer {
1811public:
Daniel Jasper23376252014-09-09 14:37:39 +00001812 Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00001813 ArrayRef<CharSourceRange> Ranges)
Daniel Jasper23376252014-09-09 14:37:39 +00001814 : Style(Style), ID(ID), SourceMgr(SourceMgr),
1815 Whitespaces(SourceMgr, Style,
1816 inputUsesCRLF(SourceMgr.getBufferData(ID))),
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001817 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
Daniel Jasper23376252014-09-09 14:37:39 +00001818 Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001819 DEBUG(llvm::dbgs() << "File encoding: "
1820 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1821 : "unknown")
1822 << "\n");
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001823 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1824 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001825 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001826
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001827 tooling::Replacements format() {
Manuel Klimek71814b42013-10-11 21:25:45 +00001828 tooling::Replacements Result;
Daniel Jasper23376252014-09-09 14:37:39 +00001829 FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001830
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001831 UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
1832 *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001833 bool StructuralError = Parser.parse();
Manuel Klimek71814b42013-10-11 21:25:45 +00001834 assert(UnwrappedLines.rbegin()->empty());
1835 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1836 ++Run) {
1837 DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1838 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1839 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1840 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1841 }
1842 tooling::Replacements RunResult =
1843 format(AnnotatedLines, StructuralError, Tokens);
1844 DEBUG({
1845 llvm::dbgs() << "Replacements for run " << Run << ":\n";
1846 for (tooling::Replacements::iterator I = RunResult.begin(),
1847 E = RunResult.end();
1848 I != E; ++I) {
1849 llvm::dbgs() << I->toString() << "\n";
1850 }
1851 });
1852 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1853 delete AnnotatedLines[i];
1854 }
1855 Result.insert(RunResult.begin(), RunResult.end());
1856 Whitespaces.reset();
1857 }
1858 return Result;
1859 }
1860
1861 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1862 bool StructuralError, FormatTokenLexer &Tokens) {
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001863 TokenAnnotator Annotator(Style, Tokens.getKeywords());
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001864 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001865 Annotator.annotate(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001866 }
Manuel Klimek71814b42013-10-11 21:25:45 +00001867 deriveLocalStyle(AnnotatedLines);
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.calculateFormattingInformation(*AnnotatedLines[i]);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001870 }
Daniel Jasper5500f612013-11-25 11:08:59 +00001871 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
Daniel Jasperb67cc422013-04-09 17:46:55 +00001872
Daniel Jasper1c5d9df2013-09-06 07:54:20 +00001873 Annotator.setCommentLineLevels(AnnotatedLines);
Daniel Jasperd0ec0d62014-11-04 12:41:02 +00001874 ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
1875 Whitespaces, Encoding,
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001876 BinPackInconclusiveFunctions);
Daniel Jasper5500f612013-11-25 11:08:59 +00001877 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00001878 Formatter.format(AnnotatedLines, /*DryRun=*/false);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001879 return Whitespaces.generateReplacements();
1880 }
1881
1882private:
Daniel Jasper5500f612013-11-25 11:08:59 +00001883 // Determines which lines are affected by the SourceRanges given as input.
Daniel Jasper9c199562013-11-28 15:58:55 +00001884 // Returns \c true if at least one line between I and E or one of their
1885 // children is affected.
Daniel Jasper5500f612013-11-25 11:08:59 +00001886 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1887 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1888 bool SomeLineAffected = false;
Craig Topper2145bc02014-05-09 08:15:10 +00001889 const AnnotatedLine *PreviousLine = nullptr;
Daniel Jasper5500f612013-11-25 11:08:59 +00001890 while (I != E) {
1891 AnnotatedLine *Line = *I;
1892 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1893
1894 // If a line is part of a preprocessor directive, it needs to be formatted
1895 // if any token within the directive is affected.
1896 if (Line->InPPDirective) {
1897 FormatToken *Last = Line->Last;
1898 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1899 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1900 Last = (*PPEnd)->Last;
1901 ++PPEnd;
1902 }
1903
1904 if (affectsTokenRange(*Line->First, *Last,
1905 /*IncludeLeadingNewlines=*/false)) {
1906 SomeLineAffected = true;
1907 markAllAsAffected(I, PPEnd);
1908 }
1909 I = PPEnd;
1910 continue;
1911 }
1912
Daniel Jasper38c82402013-11-29 09:27:43 +00001913 if (nonPPLineAffected(Line, PreviousLine))
Daniel Jasper5500f612013-11-25 11:08:59 +00001914 SomeLineAffected = true;
Daniel Jasper5500f612013-11-25 11:08:59 +00001915
Daniel Jasper38c82402013-11-29 09:27:43 +00001916 PreviousLine = Line;
Daniel Jasper5500f612013-11-25 11:08:59 +00001917 ++I;
1918 }
1919 return SomeLineAffected;
1920 }
1921
Daniel Jasper9c199562013-11-28 15:58:55 +00001922 // Determines whether 'Line' is affected by the SourceRanges given as input.
1923 // Returns \c true if line or one if its children is affected.
Daniel Jasper38c82402013-11-29 09:27:43 +00001924 bool nonPPLineAffected(AnnotatedLine *Line,
1925 const AnnotatedLine *PreviousLine) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001926 bool SomeLineAffected = false;
1927 Line->ChildrenAffected =
1928 computeAffectedLines(Line->Children.begin(), Line->Children.end());
1929 if (Line->ChildrenAffected)
1930 SomeLineAffected = true;
1931
1932 // Stores whether one of the line's tokens is directly affected.
1933 bool SomeTokenAffected = false;
1934 // Stores whether we need to look at the leading newlines of the next token
1935 // in order to determine whether it was affected.
1936 bool IncludeLeadingNewlines = false;
1937
1938 // Stores whether the first child line of any of this line's tokens is
1939 // affected.
1940 bool SomeFirstChildAffected = false;
1941
1942 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1943 // Determine whether 'Tok' was affected.
1944 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1945 SomeTokenAffected = true;
1946
1947 // Determine whether the first child of 'Tok' was affected.
1948 if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1949 SomeFirstChildAffected = true;
1950
1951 IncludeLeadingNewlines = Tok->Children.empty();
1952 }
1953
1954 // Was this line moved, i.e. has it previously been on the same line as an
1955 // affected line?
Daniel Jasper38c82402013-11-29 09:27:43 +00001956 bool LineMoved = PreviousLine && PreviousLine->Affected &&
1957 Line->First->NewlinesBefore == 0;
Daniel Jasper9c199562013-11-28 15:58:55 +00001958
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001959 bool IsContinuedComment =
1960 Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1961 Line->First->NewlinesBefore < 2 && PreviousLine &&
1962 PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
Daniel Jasper38c82402013-11-29 09:27:43 +00001963
1964 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1965 IsContinuedComment) {
Daniel Jasper9c199562013-11-28 15:58:55 +00001966 Line->Affected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001967 SomeLineAffected = true;
Daniel Jasper9c199562013-11-28 15:58:55 +00001968 }
1969 return SomeLineAffected;
1970 }
1971
Daniel Jasper5500f612013-11-25 11:08:59 +00001972 // Marks all lines between I and E as well as all their children as affected.
1973 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1974 SmallVectorImpl<AnnotatedLine *>::iterator E) {
1975 while (I != E) {
1976 (*I)->Affected = true;
1977 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1978 ++I;
1979 }
1980 }
1981
1982 // Returns true if the range from 'First' to 'Last' intersects with one of the
1983 // input ranges.
1984 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1985 bool IncludeLeadingNewlines) {
1986 SourceLocation Start = First.WhitespaceRange.getBegin();
1987 if (!IncludeLeadingNewlines)
1988 Start = Start.getLocWithOffset(First.LastNewlineOffset);
Daniel Jasper5877bf12013-11-25 11:53:05 +00001989 SourceLocation End = Last.getStartOfNonWhitespace();
Daniel Jasperac29eac2014-10-29 23:40:50 +00001990 End = End.getLocWithOffset(Last.TokenText.size());
Daniel Jasper5500f612013-11-25 11:08:59 +00001991 CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1992 return affectsCharSourceRange(Range);
1993 }
1994
1995 // Returns true if one of the input ranges intersect the leading empty lines
1996 // before 'Tok'.
1997 bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1998 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1999 Tok.WhitespaceRange.getBegin(),
2000 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
2001 return affectsCharSourceRange(EmptyLineRange);
2002 }
2003
2004 // Returns true if 'Range' intersects with one of the input ranges.
2005 bool affectsCharSourceRange(const CharSourceRange &Range) {
2006 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
2007 E = Ranges.end();
2008 I != E; ++I) {
2009 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
2010 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
2011 return true;
2012 }
2013 return false;
2014 }
2015
Alexander Kornienko9e649af2013-09-11 12:25:57 +00002016 static bool inputUsesCRLF(StringRef Text) {
2017 return Text.count('\r') * 2 > Text.count('\n');
2018 }
2019
Manuel Klimek71814b42013-10-11 21:25:45 +00002020 void
2021 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002022 unsigned CountBoundToVariable = 0;
2023 unsigned CountBoundToType = 0;
2024 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002025 bool HasBinPackedFunction = false;
2026 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002027 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002028 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002029 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002030 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00002031 while (Tok->Next) {
Daniel Jaspera98b7b02014-11-25 10:05:17 +00002032 if (Tok->is(TT_PointerOrReference)) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00002033 bool SpacesBefore =
2034 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
2035 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
2036 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002037 if (SpacesBefore && !SpacesAfter)
2038 ++CountBoundToVariable;
2039 else if (!SpacesBefore && SpacesAfter)
2040 ++CountBoundToType;
2041 }
2042
Daniel Jasperfba84ff2013-10-12 05:16:06 +00002043 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
Daniel Jaspera98b7b02014-11-25 10:05:17 +00002044 if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
Daniel Jasperfba84ff2013-10-12 05:16:06 +00002045 HasCpp03IncompatibleFormat = true;
Daniel Jaspera98b7b02014-11-25 10:05:17 +00002046 if (Tok->is(TT_TemplateCloser) &&
2047 Tok->Previous->is(TT_TemplateCloser))
Daniel Jasperfba84ff2013-10-12 05:16:06 +00002048 HasCpp03IncompatibleFormat = true;
2049 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002050
2051 if (Tok->PackingKind == PPK_BinPacked)
2052 HasBinPackedFunction = true;
2053 if (Tok->PackingKind == PPK_OnePerLine)
2054 HasOnePerLineFunction = true;
2055
Manuel Klimek6e6310e2013-05-29 14:47:47 +00002056 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002057 }
2058 }
Daniel Jasper553d4872014-06-17 12:40:34 +00002059 if (Style.DerivePointerAlignment) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002060 if (CountBoundToType > CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00002061 Style.PointerAlignment = FormatStyle::PAS_Left;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002062 else if (CountBoundToType < CountBoundToVariable)
Daniel Jasper553d4872014-06-17 12:40:34 +00002063 Style.PointerAlignment = FormatStyle::PAS_Right;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002064 }
2065 if (Style.Standard == FormatStyle::LS_Auto) {
2066 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
2067 : FormatStyle::LS_Cpp03;
2068 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002069 BinPackInconclusiveFunctions =
2070 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00002071 }
2072
Craig Topperfb6b25b2014-03-15 04:29:04 +00002073 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
Manuel Klimek71814b42013-10-11 21:25:45 +00002074 assert(!UnwrappedLines.empty());
2075 UnwrappedLines.back().push_back(TheLine);
2076 }
2077
Craig Topperfb6b25b2014-03-15 04:29:04 +00002078 void finishRun() override {
Manuel Klimek71814b42013-10-11 21:25:45 +00002079 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
Daniel Jasperf7935112012-12-03 18:12:45 +00002080 }
2081
2082 FormatStyle Style;
Daniel Jasper23376252014-09-09 14:37:39 +00002083 FileID ID;
Daniel Jasperf7935112012-12-03 18:12:45 +00002084 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00002085 WhitespaceManager Whitespaces;
Daniel Jasperbbf5c1c2013-11-05 19:10:03 +00002086 SmallVector<CharSourceRange, 8> Ranges;
Manuel Klimek71814b42013-10-11 21:25:45 +00002087 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00002088
2089 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00002090 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00002091};
2092
Craig Topperaf35e852013-06-30 22:29:28 +00002093} // end anonymous namespace
2094
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00002095tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
2096 SourceManager &SourceMgr,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002097 ArrayRef<CharSourceRange> Ranges) {
Daniel Jasper23376252014-09-09 14:37:39 +00002098 if (Style.DisableFormat)
2099 return tooling::Replacements();
2100 return reformat(Style, SourceMgr,
2101 SourceMgr.getFileID(Lex.getSourceLocation()), Ranges);
2102}
Daniel Jasperc64b09a2014-05-22 15:12:22 +00002103
Daniel Jasper23376252014-09-09 14:37:39 +00002104tooling::Replacements reformat(const FormatStyle &Style,
2105 SourceManager &SourceMgr, FileID ID,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002106 ArrayRef<CharSourceRange> Ranges) {
Daniel Jasper23376252014-09-09 14:37:39 +00002107 if (Style.DisableFormat)
2108 return tooling::Replacements();
2109 Formatter formatter(Style, SourceMgr, ID, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00002110 return formatter.format();
2111}
2112
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002113tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002114 ArrayRef<tooling::Range> Ranges,
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002115 StringRef FileName) {
Daniel Jasper23376252014-09-09 14:37:39 +00002116 if (Style.DisableFormat)
2117 return tooling::Replacements();
2118
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002119 FileManager Files((FileSystemOptions()));
2120 DiagnosticsEngine Diagnostics(
2121 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2122 new DiagnosticOptions);
2123 SourceManager SourceMgr(Diagnostics, Files);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00002124 std::unique_ptr<llvm::MemoryBuffer> Buf =
2125 llvm::MemoryBuffer::getMemBuffer(Code, FileName);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002126 const clang::FileEntry *Entry =
2127 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
David Blaikie49cc3182014-08-27 20:54:45 +00002128 SourceMgr.overrideFileContents(Entry, std::move(Buf));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002129 FileID ID =
2130 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002131 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
2132 std::vector<CharSourceRange> CharRanges;
Benjamin Kramerd0eed3a2014-10-03 18:52:48 +00002133 for (const tooling::Range &Range : Ranges) {
2134 SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
2135 SourceLocation End = Start.getLocWithOffset(Range.getLength());
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002136 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
2137 }
Daniel Jasper23376252014-09-09 14:37:39 +00002138 return reformat(Style, SourceMgr, ID, CharRanges);
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002139}
2140
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002141LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002142 LangOptions LangOpts;
2143 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002144 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2145 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00002146 LangOpts.LineComment = 1;
Daniel Jasper30a24062014-11-14 09:02:28 +00002147 bool AlternativeOperators = Style.Language != FormatStyle::LK_JavaScript &&
2148 Style.Language != FormatStyle::LK_Java;
2149 LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002150 LangOpts.Bool = 1;
2151 LangOpts.ObjC1 = 1;
2152 LangOpts.ObjC2 = 1;
2153 return LangOpts;
2154}
2155
Edwin Vaned544aa72013-09-30 13:31:48 +00002156const char *StyleOptionHelpDescription =
2157 "Coding style, currently supports:\n"
2158 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
2159 "Use -style=file to load style configuration from\n"
2160 ".clang-format file located in one of the parent\n"
2161 "directories of the source file (or current\n"
2162 "directory for stdin).\n"
2163 "Use -style=\"{key: value, ...}\" to set specific\n"
2164 "parameters, e.g.:\n"
2165 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
2166
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002167static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Daniel Jasperc58c70e2014-09-15 11:21:46 +00002168 if (FileName.endswith(".java")) {
2169 return FormatStyle::LK_Java;
2170 } else if (FileName.endswith_lower(".js")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002171 return FormatStyle::LK_JavaScript;
Daniel Jasper7052ce62014-01-19 09:04:08 +00002172 } else if (FileName.endswith_lower(".proto") ||
2173 FileName.endswith_lower(".protodevel")) {
2174 return FormatStyle::LK_Proto;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002175 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002176 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002177}
2178
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002179FormatStyle getStyle(StringRef StyleName, StringRef FileName,
2180 StringRef FallbackStyle) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002181 FormatStyle Style = getLLVMStyle();
2182 Style.Language = getLanguageByFileName(FileName);
2183 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002184 llvm::errs() << "Invalid fallback style \"" << FallbackStyle
2185 << "\" using LLVM style\n";
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002186 return Style;
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002187 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002188
2189 if (StyleName.startswith("{")) {
2190 // Parse YAML/JSON style from the command line.
Rafael Espindolac0809172014-06-12 14:02:15 +00002191 if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002192 llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
2193 << FallbackStyle << " style\n";
Edwin Vaned544aa72013-09-30 13:31:48 +00002194 }
2195 return Style;
2196 }
2197
2198 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002199 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Edwin Vaned544aa72013-09-30 13:31:48 +00002200 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
2201 << " style\n";
2202 return Style;
2203 }
2204
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002205 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002206 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00002207 SmallString<128> Path(FileName);
2208 llvm::sys::fs::make_absolute(Path);
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002209 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00002210 Directory = llvm::sys::path::parent_path(Directory)) {
2211 if (!llvm::sys::fs::is_directory(Directory))
2212 continue;
2213 SmallString<128> ConfigFile(Directory);
2214
2215 llvm::sys::path::append(ConfigFile, ".clang-format");
2216 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2217 bool IsFile = false;
2218 // Ignore errors from is_regular_file: we only need to know if we can read
2219 // the file or not.
2220 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2221
2222 if (!IsFile) {
2223 // Try _clang-format too, since dotfiles are not commonly used on Windows.
2224 ConfigFile = Directory;
2225 llvm::sys::path::append(ConfigFile, "_clang-format");
2226 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2227 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
2228 }
2229
2230 if (IsFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002231 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
2232 llvm::MemoryBuffer::getFile(ConfigFile.c_str());
2233 if (std::error_code EC = Text.getError()) {
2234 llvm::errs() << EC.message() << "\n";
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002235 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002236 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002237 if (std::error_code ec =
2238 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00002239 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002240 if (!UnsuitableConfigFiles.empty())
2241 UnsuitableConfigFiles.append(", ");
2242 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002243 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002244 }
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002245 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2246 << "\n";
2247 break;
Edwin Vaned544aa72013-09-30 13:31:48 +00002248 }
2249 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2250 return Style;
2251 }
2252 }
2253 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
2254 << " style\n";
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002255 if (!UnsuitableConfigFiles.empty()) {
2256 llvm::errs() << "Configuration file(s) do(es) not support "
2257 << getLanguageName(Style.Language) << ": "
2258 << UnsuitableConfigFiles << "\n";
2259 }
Edwin Vaned544aa72013-09-30 13:31:48 +00002260 return Style;
2261}
2262
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002263} // namespace format
2264} // namespace clang