blob: aaca6d2cef7cd5dd7b50a24ca0eaf54c9240bc0f [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 Jasper85c472d2015-09-29 07:53:08 +000016#include "clang/Format/Format.h"
Eric Liu4cfb88a2016-04-25 15:09:22 +000017#include "AffectedRangeManager.h"
Daniel Jasperde0328a2013-08-16 11:20:30 +000018#include "ContinuationIndenter.h"
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +000019#include "FormatInternal.h"
Martin Probstc4a0dd42016-05-20 11:24:24 +000020#include "FormatTokenLexer.h"
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +000021#include "NamespaceEndCommentsFixer.h"
Martin Probstc4a0dd42016-05-20 11:24:24 +000022#include "SortJavaScriptImports.h"
23#include "TokenAnalyzer.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000024#include "TokenAnnotator.h"
Daniel Jasper0df50932014-12-10 19:00:42 +000025#include "UnwrappedLineFormatter.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "UnwrappedLineParser.h"
Krasimir Georgievb03877a2017-06-21 12:03:12 +000027#include "UsingDeclarationsSorter.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000028#include "WhitespaceManager.h"
Daniel Jasperec04c0d2013-05-16 10:40:07 +000029#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000030#include "clang/Basic/DiagnosticOptions.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000031#include "clang/Basic/SourceManager.h"
Marianne Mailhot-Sarrasin4988fa12016-04-14 14:47:37 +000032#include "clang/Basic/VirtualFileSystem.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000033#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000034#include "llvm/ADT/STLExtras.h"
Ben Hamiltone2e3e672018-01-17 17:33:08 +000035#include "llvm/ADT/StringRef.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000036#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000037#include "llvm/Support/Debug.h"
Edwin Vaned544aa72013-09-30 13:31:48 +000038#include "llvm/Support/Path.h"
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +000039#include "llvm/Support/Regex.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000040#include "llvm/Support/YAMLTraits.h"
Martin Probst081f1762016-06-01 15:19:53 +000041#include <algorithm>
Eric Liu4cfb88a2016-04-25 15:09:22 +000042#include <memory>
Eric Liubf4c41c2018-05-04 17:55:13 +000043#include <mutex>
Daniel Jasper8b529712012-12-04 13:02:32 +000044#include <string>
Eric Liubf4c41c2018-05-04 17:55:13 +000045#include <unordered_map>
Daniel Jasper8b529712012-12-04 13:02:32 +000046
Chandler Carruth10346662014-04-22 03:17:02 +000047#define DEBUG_TYPE "format-formatter"
48
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000049using clang::format::FormatStyle;
50
NAKAMURA Takumi057a9422017-11-01 04:43:22 +000051LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::IncludeCategory)
52LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::RawStringFormat)
Daniel Jaspere1e43192014-04-01 12:55:11 +000053
Alexander Kornienkod6538332013-05-07 15:32:14 +000054namespace llvm {
55namespace yaml {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000056template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
57 static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
58 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
Daniel Jasperc58c70e2014-09-15 11:21:46 +000059 IO.enumCase(Value, "Java", FormatStyle::LK_Java);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000060 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
Daniel Jasper03a04fe2016-12-12 12:42:29 +000061 IO.enumCase(Value, "ObjC", FormatStyle::LK_ObjC);
Daniel Jasper7052ce62014-01-19 09:04:08 +000062 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
Daniel Jasper498f5582015-12-25 08:53:31 +000063 IO.enumCase(Value, "TableGen", FormatStyle::LK_TableGen);
Krasimir Georgiev26b144c2017-07-03 15:05:14 +000064 IO.enumCase(Value, "TextProto", FormatStyle::LK_TextProto);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000065 }
66};
67
68template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
69 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
70 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
71 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
72 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
73 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
74 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
75 }
76};
77
78template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
79 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
80 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
81 IO.enumCase(Value, "false", FormatStyle::UT_Never);
82 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
83 IO.enumCase(Value, "true", FormatStyle::UT_Always);
84 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
Marianne Mailhot-Sarrasin51fe2792016-04-14 14:52:26 +000085 IO.enumCase(Value, "ForContinuationAndIndentation",
86 FormatStyle::UT_ForContinuationAndIndentation);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000087 }
88};
89
Daniel Jasperabd1f572016-03-02 22:44:03 +000090template <> struct ScalarEnumerationTraits<FormatStyle::JavaScriptQuoteStyle> {
91 static void enumeration(IO &IO, FormatStyle::JavaScriptQuoteStyle &Value) {
92 IO.enumCase(Value, "Leave", FormatStyle::JSQS_Leave);
93 IO.enumCase(Value, "Single", FormatStyle::JSQS_Single);
94 IO.enumCase(Value, "Double", FormatStyle::JSQS_Double);
95 }
96};
97
Daniel Jasperd74cf402014-04-08 12:46:38 +000098template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
99 static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
100 IO.enumCase(Value, "None", FormatStyle::SFS_None);
101 IO.enumCase(Value, "false", FormatStyle::SFS_None);
102 IO.enumCase(Value, "All", FormatStyle::SFS_All);
103 IO.enumCase(Value, "true", FormatStyle::SFS_All);
104 IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
Francois Ferrandd3f0e3d2017-06-21 13:56:02 +0000105 IO.enumCase(Value, "InlineOnly", FormatStyle::SFS_InlineOnly);
Daniel Jasper9e709352014-11-26 10:43:58 +0000106 IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
Daniel Jasperd74cf402014-04-08 12:46:38 +0000107 }
108};
109
Ben Hamilton4dc658c2018-02-02 20:15:14 +0000110template <> struct ScalarEnumerationTraits<FormatStyle::BinPackStyle> {
111 static void enumeration(IO &IO, FormatStyle::BinPackStyle &Value) {
112 IO.enumCase(Value, "Auto", FormatStyle::BPS_Auto);
113 IO.enumCase(Value, "Always", FormatStyle::BPS_Always);
114 IO.enumCase(Value, "Never", FormatStyle::BPS_Never);
115 }
116};
117
Daniel Jasperac043c92014-09-15 11:11:00 +0000118template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
119 static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
120 IO.enumCase(Value, "All", FormatStyle::BOS_All);
121 IO.enumCase(Value, "true", FormatStyle::BOS_All);
122 IO.enumCase(Value, "None", FormatStyle::BOS_None);
123 IO.enumCase(Value, "false", FormatStyle::BOS_None);
124 IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
125 }
126};
127
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000128template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
129 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
130 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
131 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
Birunthan Mohanathas305fa9c2015-07-12 03:13:54 +0000132 IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000133 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
134 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000135 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Roman Kashitsyn291f64f2015-08-10 13:43:19 +0000136 IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000137 IO.enumCase(Value, "Custom", FormatStyle::BS_Custom);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000138 }
139};
140
Manuel Klimek89628f62017-09-20 09:51:03 +0000141template <>
142struct ScalarEnumerationTraits<FormatStyle::BreakConstructorInitializersStyle> {
143 static void
144 enumeration(IO &IO, FormatStyle::BreakConstructorInitializersStyle &Value) {
Francois Ferranda6b6d512017-05-24 11:36:58 +0000145 IO.enumCase(Value, "BeforeColon", FormatStyle::BCIS_BeforeColon);
146 IO.enumCase(Value, "BeforeComma", FormatStyle::BCIS_BeforeComma);
147 IO.enumCase(Value, "AfterColon", FormatStyle::BCIS_AfterColon);
148 }
149};
150
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000151template <>
Krasimir Georgievad47c902017-08-30 14:34:57 +0000152struct ScalarEnumerationTraits<FormatStyle::PPDirectiveIndentStyle> {
153 static void enumeration(IO &IO, FormatStyle::PPDirectiveIndentStyle &Value) {
154 IO.enumCase(Value, "None", FormatStyle::PPDIS_None);
155 IO.enumCase(Value, "AfterHash", FormatStyle::PPDIS_AfterHash);
156 }
157};
158
159template <>
Zachary Turner448592e2015-12-18 22:20:15 +0000160struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
161 static void enumeration(IO &IO, FormatStyle::ReturnTypeBreakingStyle &Value) {
162 IO.enumCase(Value, "None", FormatStyle::RTBS_None);
163 IO.enumCase(Value, "All", FormatStyle::RTBS_All);
164 IO.enumCase(Value, "TopLevel", FormatStyle::RTBS_TopLevel);
165 IO.enumCase(Value, "TopLevelDefinitions",
166 FormatStyle::RTBS_TopLevelDefinitions);
167 IO.enumCase(Value, "AllDefinitions", FormatStyle::RTBS_AllDefinitions);
168 }
169};
170
171template <>
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000172struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
173 static void
174 enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) {
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000175 IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
176 IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
177 IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
178
179 // For backward compatibility.
180 IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
181 IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
182 }
183};
184
Alexander Kornienkod6538332013-05-07 15:32:14 +0000185template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000186struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000187 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000188 FormatStyle::NamespaceIndentationKind &Value) {
189 IO.enumCase(Value, "None", FormatStyle::NI_None);
190 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
191 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000192 }
193};
194
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000195template <> struct ScalarEnumerationTraits<FormatStyle::BracketAlignmentStyle> {
196 static void enumeration(IO &IO, FormatStyle::BracketAlignmentStyle &Value) {
197 IO.enumCase(Value, "Align", FormatStyle::BAS_Align);
198 IO.enumCase(Value, "DontAlign", FormatStyle::BAS_DontAlign);
199 IO.enumCase(Value, "AlwaysBreak", FormatStyle::BAS_AlwaysBreak);
200
201 // For backward compatibility.
202 IO.enumCase(Value, "true", FormatStyle::BAS_Align);
203 IO.enumCase(Value, "false", FormatStyle::BAS_DontAlign);
204 }
205};
206
Manuel Klimek89628f62017-09-20 09:51:03 +0000207template <>
208struct ScalarEnumerationTraits<FormatStyle::EscapedNewlineAlignmentStyle> {
209 static void enumeration(IO &IO,
210 FormatStyle::EscapedNewlineAlignmentStyle &Value) {
Daniel Jasper7fdbb3f2017-05-08 15:08:00 +0000211 IO.enumCase(Value, "DontAlign", FormatStyle::ENAS_DontAlign);
212 IO.enumCase(Value, "Left", FormatStyle::ENAS_Left);
213 IO.enumCase(Value, "Right", FormatStyle::ENAS_Right);
214
215 // For backward compatibility.
216 IO.enumCase(Value, "true", FormatStyle::ENAS_Left);
217 IO.enumCase(Value, "false", FormatStyle::ENAS_Right);
218 }
219};
220
Jacques Pienaarfc275112015-02-18 23:48:37 +0000221template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
222 static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
Daniel Jasper553d4872014-06-17 12:40:34 +0000223 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
224 IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
225 IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
226
Alp Toker958027b2014-07-14 19:42:55 +0000227 // For backward compatibility.
Daniel Jasper553d4872014-06-17 12:40:34 +0000228 IO.enumCase(Value, "true", FormatStyle::PAS_Left);
229 IO.enumCase(Value, "false", FormatStyle::PAS_Right);
230 }
231};
232
233template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000234struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000235 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000236 FormatStyle::SpaceBeforeParensOptions &Value) {
237 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000238 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000239 FormatStyle::SBPO_ControlStatements);
240 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000241
242 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000243 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
244 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000245 }
246};
247
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000248template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000249 static void mapping(IO &IO, FormatStyle &Style) {
250 // When reading, read the language first, we need it for getPredefinedStyle.
251 IO.mapOptional("Language", Style.Language);
252
Alexander Kornienko49149672013-05-10 11:56:10 +0000253 if (IO.outputting()) {
Jacques Pienaarfc275112015-02-18 23:48:37 +0000254 StringRef StylesArray[] = {"LLVM", "Google", "Chromium",
255 "Mozilla", "WebKit", "GNU"};
Alexander Kornienko49149672013-05-10 11:56:10 +0000256 ArrayRef<StringRef> Styles(StylesArray);
257 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
258 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000259 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000260 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000261 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000262 IO.mapOptional("# BasedOnStyle", StyleName);
263 break;
264 }
265 }
266 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000267 StringRef BasedOnStyle;
268 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000269 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000270 FormatStyle::LanguageKind OldLanguage = Style.Language;
271 FormatStyle::LanguageKind Language =
272 ((FormatStyle *)IO.getContext())->Language;
273 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000274 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
275 return;
276 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000277 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000278 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000279 }
280
Birunthan Mohanathas50a6f912015-06-28 14:52:34 +0000281 // For backward compatibility.
282 if (!IO.outputting()) {
Daniel Jasper7fdbb3f2017-05-08 15:08:00 +0000283 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlines);
Birunthan Mohanathas50a6f912015-06-28 14:52:34 +0000284 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
285 IO.mapOptional("IndentFunctionDeclarationAfterType",
286 Style.IndentWrappedFunctionNames);
287 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
288 IO.mapOptional("SpaceAfterControlStatementKeyword",
289 Style.SpaceBeforeParens);
290 }
291
Alexander Kornienkod6538332013-05-07 15:32:14 +0000292 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000293 IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000294 IO.mapOptional("AlignConsecutiveAssignments",
295 Style.AlignConsecutiveAssignments);
Daniel Jaspere12597c2015-10-01 10:06:54 +0000296 IO.mapOptional("AlignConsecutiveDeclarations",
297 Style.AlignConsecutiveDeclarations);
Daniel Jasper7fdbb3f2017-05-08 15:08:00 +0000298 IO.mapOptional("AlignEscapedNewlines", Style.AlignEscapedNewlines);
Daniel Jasper3219e432014-12-02 13:24:51 +0000299 IO.mapOptional("AlignOperands", Style.AlignOperands);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000300 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000301 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
302 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000303 IO.mapOptional("AllowShortBlocksOnASingleLine",
304 Style.AllowShortBlocksOnASingleLine);
Daniel Jasperb87899b2014-09-10 13:11:45 +0000305 IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
306 Style.AllowShortCaseLabelsOnASingleLine);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000307 IO.mapOptional("AllowShortFunctionsOnASingleLine",
308 Style.AllowShortFunctionsOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000309 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
310 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000311 IO.mapOptional("AllowShortLoopsOnASingleLine",
312 Style.AllowShortLoopsOnASingleLine);
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000313 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
314 Style.AlwaysBreakAfterDefinitionReturnType);
Zachary Turner448592e2015-12-18 22:20:15 +0000315 IO.mapOptional("AlwaysBreakAfterReturnType",
316 Style.AlwaysBreakAfterReturnType);
317 // If AlwaysBreakAfterDefinitionReturnType was specified but
318 // AlwaysBreakAfterReturnType was not, initialize the latter from the
319 // former for backwards compatibility.
320 if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
321 Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None) {
322 if (Style.AlwaysBreakAfterDefinitionReturnType == FormatStyle::DRTBS_All)
323 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
324 else if (Style.AlwaysBreakAfterDefinitionReturnType ==
325 FormatStyle::DRTBS_TopLevel)
326 Style.AlwaysBreakAfterReturnType =
327 FormatStyle::RTBS_TopLevelDefinitions;
328 }
329
Alexander Kornienko58611712013-07-04 12:02:44 +0000330 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
331 Style.AlwaysBreakBeforeMultilineStrings);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000332 IO.mapOptional("AlwaysBreakTemplateDeclarations",
333 Style.AlwaysBreakTemplateDeclarations);
334 IO.mapOptional("BinPackArguments", Style.BinPackArguments);
335 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000336 IO.mapOptional("BraceWrapping", Style.BraceWrapping);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000337 IO.mapOptional("BreakBeforeBinaryOperators",
338 Style.BreakBeforeBinaryOperators);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000339 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Francois Ferrande56a8292017-06-14 12:29:47 +0000340 IO.mapOptional("BreakBeforeInheritanceComma",
341 Style.BreakBeforeInheritanceComma);
Daniel Jasper165b29e2013-11-08 00:57:11 +0000342 IO.mapOptional("BreakBeforeTernaryOperators",
343 Style.BreakBeforeTernaryOperators);
Francois Ferranda6b6d512017-05-24 11:36:58 +0000344
345 bool BreakConstructorInitializersBeforeComma = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000346 IO.mapOptional("BreakConstructorInitializersBeforeComma",
Francois Ferranda6b6d512017-05-24 11:36:58 +0000347 BreakConstructorInitializersBeforeComma);
348 IO.mapOptional("BreakConstructorInitializers",
349 Style.BreakConstructorInitializers);
350 // If BreakConstructorInitializersBeforeComma was specified but
351 // BreakConstructorInitializers was not, initialize the latter from the
352 // former for backwards compatibility.
353 if (BreakConstructorInitializersBeforeComma &&
354 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon)
355 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
356
Daniel Jaspere1a7b762016-02-01 11:21:02 +0000357 IO.mapOptional("BreakAfterJavaFieldAnnotations",
358 Style.BreakAfterJavaFieldAnnotations);
359 IO.mapOptional("BreakStringLiterals", Style.BreakStringLiterals);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000360 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000361 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Francois Ferrande56a8292017-06-14 12:29:47 +0000362 IO.mapOptional("CompactNamespaces", Style.CompactNamespaces);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000363 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
364 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000365 IO.mapOptional("ConstructorInitializerIndentWidth",
366 Style.ConstructorInitializerIndentWidth);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000367 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
368 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Daniel Jasper553d4872014-06-17 12:40:34 +0000369 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000370 IO.mapOptional("DisableFormat", Style.DisableFormat);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000371 IO.mapOptional("ExperimentalAutoDetectBinPacking",
372 Style.ExperimentalAutoDetectBinPacking);
Krasimir Georgiev32eaa862017-03-01 15:35:39 +0000373 IO.mapOptional("FixNamespaceComments", Style.FixNamespaceComments);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000374 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Krasimir Georgiev4c2c9c32017-11-27 13:23:45 +0000375 IO.mapOptional("IncludeBlocks", Style.IncludeBlocks);
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +0000376 IO.mapOptional("IncludeCategories", Style.IncludeCategories);
Daniel Jasper9c8ff352016-03-21 14:11:27 +0000377 IO.mapOptional("IncludeIsMainRegex", Style.IncludeIsMainRegex);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000378 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Krasimir Georgievad47c902017-08-30 14:34:57 +0000379 IO.mapOptional("IndentPPDirectives", Style.IndentPPDirectives);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000380 IO.mapOptional("IndentWidth", Style.IndentWidth);
381 IO.mapOptional("IndentWrappedFunctionNames",
382 Style.IndentWrappedFunctionNames);
Martin Probst0cd74ee2016-06-13 16:39:50 +0000383 IO.mapOptional("JavaScriptQuotes", Style.JavaScriptQuotes);
384 IO.mapOptional("JavaScriptWrapImports", Style.JavaScriptWrapImports);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000385 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
386 Style.KeepEmptyLinesAtTheStartOfBlocks);
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000387 IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
388 IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000389 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000390 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Ben Hamilton4dc658c2018-02-02 20:15:14 +0000391 IO.mapOptional("ObjCBinPackProtocolList", Style.ObjCBinPackProtocolList);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000392 IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000393 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000394 IO.mapOptional("ObjCSpaceBeforeProtocolList",
395 Style.ObjCSpaceBeforeProtocolList);
Manuel Klimek89628f62017-09-20 09:51:03 +0000396 IO.mapOptional("PenaltyBreakAssignment", Style.PenaltyBreakAssignment);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000397 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
398 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000399 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000400 IO.mapOptional("PenaltyBreakFirstLessLess",
401 Style.PenaltyBreakFirstLessLess);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000402 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000403 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
404 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
405 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000406 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000407 IO.mapOptional("RawStringFormats", Style.RawStringFormats);
Daniel Jaspera0a50392015-12-01 13:28:53 +0000408 IO.mapOptional("ReflowComments", Style.ReflowComments);
409 IO.mapOptional("SortIncludes", Style.SortIncludes);
Krasimir Georgievac16a202017-06-23 11:46:03 +0000410 IO.mapOptional("SortUsingDeclarations", Style.SortUsingDeclarations);
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000411 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
Manuel Klimek89628f62017-09-20 09:51:03 +0000412 IO.mapOptional("SpaceAfterTemplateKeyword",
413 Style.SpaceAfterTemplateKeyword);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000414 IO.mapOptional("SpaceBeforeAssignmentOperators",
415 Style.SpaceBeforeAssignmentOperators);
Francois Ferrand2a9ea782018-03-01 10:09:13 +0000416 IO.mapOptional("SpaceBeforeCtorInitializerColon",
417 Style.SpaceBeforeCtorInitializerColon);
418 IO.mapOptional("SpaceBeforeInheritanceColon",
419 Style.SpaceBeforeInheritanceColon);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000420 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Francois Ferrand2a9ea782018-03-01 10:09:13 +0000421 IO.mapOptional("SpaceBeforeRangeBasedForLoopColon",
422 Style.SpaceBeforeRangeBasedForLoopColon);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000423 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
424 IO.mapOptional("SpacesBeforeTrailingComments",
425 Style.SpacesBeforeTrailingComments);
426 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
427 IO.mapOptional("SpacesInContainerLiterals",
428 Style.SpacesInContainerLiterals);
429 IO.mapOptional("SpacesInCStyleCastParentheses",
430 Style.SpacesInCStyleCastParentheses);
431 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
432 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
433 IO.mapOptional("Standard", Style.Standard);
434 IO.mapOptional("TabWidth", Style.TabWidth);
435 IO.mapOptional("UseTab", Style.UseTab);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000436 }
437};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000438
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000439template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
440 static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
441 IO.mapOptional("AfterClass", Wrapping.AfterClass);
442 IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
443 IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
444 IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
445 IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
446 IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
447 IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
448 IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
Krasimir Georgievd6ce9372017-09-15 11:23:50 +0000449 IO.mapOptional("AfterExternBlock", Wrapping.AfterExternBlock);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000450 IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
451 IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
452 IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
Francois Ferrandad722562017-06-30 20:25:55 +0000453 IO.mapOptional("SplitEmptyFunction", Wrapping.SplitEmptyFunction);
454 IO.mapOptional("SplitEmptyRecord", Wrapping.SplitEmptyRecord);
455 IO.mapOptional("SplitEmptyNamespace", Wrapping.SplitEmptyNamespace);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000456 }
457};
458
Daniel Jasper8ce1b8d2015-10-06 11:54:18 +0000459template <> struct MappingTraits<FormatStyle::IncludeCategory> {
460 static void mapping(IO &IO, FormatStyle::IncludeCategory &Category) {
461 IO.mapOptional("Regex", Category.Regex);
462 IO.mapOptional("Priority", Category.Priority);
463 }
464};
465
Krasimir Georgiev4c2c9c32017-11-27 13:23:45 +0000466template <> struct ScalarEnumerationTraits<FormatStyle::IncludeBlocksStyle> {
467 static void enumeration(IO &IO, FormatStyle::IncludeBlocksStyle &Value) {
468 IO.enumCase(Value, "Preserve", FormatStyle::IBS_Preserve);
469 IO.enumCase(Value, "Merge", FormatStyle::IBS_Merge);
470 IO.enumCase(Value, "Regroup", FormatStyle::IBS_Regroup);
471 }
472};
473
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000474template <> struct MappingTraits<FormatStyle::RawStringFormat> {
475 static void mapping(IO &IO, FormatStyle::RawStringFormat &Format) {
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000476 IO.mapOptional("Language", Format.Language);
Krasimir Georgiev4527f132018-01-17 12:24:59 +0000477 IO.mapOptional("Delimiters", Format.Delimiters);
Krasimir Georgiev2537e222018-01-17 16:17:26 +0000478 IO.mapOptional("EnclosingFunctions", Format.EnclosingFunctions);
Krasimir Georgiev412ed092018-01-19 16:18:47 +0000479 IO.mapOptional("CanonicalDelimiter", Format.CanonicalDelimiter);
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000480 IO.mapOptional("BasedOnStyle", Format.BasedOnStyle);
481 }
482};
483
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000484// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000485// IO.getContext() should contain a pointer to the FormatStyle structure, that
486// will be used to get default values for missing keys.
487// If the first element has no Language specified, it will be treated as the
488// default one for the following elements.
Jacques Pienaarfc275112015-02-18 23:48:37 +0000489template <> struct DocumentListTraits<std::vector<FormatStyle>> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000490 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
491 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000492 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000493 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000494 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000495 if (Index >= Seq.size()) {
496 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000497 FormatStyle Template;
Krasimir Georgiev1696bb62017-11-09 15:12:17 +0000498 if (!Seq.empty() && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000499 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000500 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000501 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000502 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000503 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000504 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000505 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000506 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000507 }
508};
Daniel Jasperd89ae9d2015-09-23 08:30:47 +0000509} // namespace yaml
510} // namespace llvm
Alexander Kornienkod6538332013-05-07 15:32:14 +0000511
Daniel Jasperf7935112012-12-03 18:12:45 +0000512namespace clang {
513namespace format {
514
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000515const std::error_category &getParseCategory() {
Benjamin Kramerf76861c2018-03-20 21:52:19 +0000516 static const ParseErrorCategory C{};
Rafael Espindolad0136702014-06-12 02:50:04 +0000517 return C;
518}
519std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000520 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000521}
522
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +0000523inline llvm::Error make_string_error(const llvm::Twine &Message) {
524 return llvm::make_error<llvm::StringError>(Message,
525 llvm::inconvertibleErrorCode());
526}
527
Reid Kleckner6432d452016-10-19 23:39:55 +0000528const char *ParseErrorCategory::name() const noexcept {
Rafael Espindolad0136702014-06-12 02:50:04 +0000529 return "clang-format.parse_error";
530}
531
532std::string ParseErrorCategory::message(int EV) const {
533 switch (static_cast<ParseError>(EV)) {
534 case ParseError::Success:
535 return "Success";
536 case ParseError::Error:
537 return "Invalid argument";
538 case ParseError::Unsuitable:
539 return "Unsuitable";
540 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000541 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000542}
543
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000544static FormatStyle expandPresets(const FormatStyle &Style) {
Daniel Jasper55bbe662015-10-07 04:06:10 +0000545 if (Style.BreakBeforeBraces == FormatStyle::BS_Custom)
546 return Style;
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000547 FormatStyle Expanded = Style;
Manuel Klimek89628f62017-09-20 09:51:03 +0000548 Expanded.BraceWrapping = {false, false, false, false, false,
549 false, false, false, false, false,
550 false, false, true, true, true};
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000551 switch (Style.BreakBeforeBraces) {
552 case FormatStyle::BS_Linux:
553 Expanded.BraceWrapping.AfterClass = true;
554 Expanded.BraceWrapping.AfterFunction = true;
555 Expanded.BraceWrapping.AfterNamespace = true;
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000556 break;
557 case FormatStyle::BS_Mozilla:
558 Expanded.BraceWrapping.AfterClass = true;
559 Expanded.BraceWrapping.AfterEnum = true;
560 Expanded.BraceWrapping.AfterFunction = true;
561 Expanded.BraceWrapping.AfterStruct = true;
562 Expanded.BraceWrapping.AfterUnion = true;
Krasimir Georgievd6ce9372017-09-15 11:23:50 +0000563 Expanded.BraceWrapping.AfterExternBlock = true;
Sylvestre Ledru82c9a0e2017-09-13 20:03:29 +0000564 Expanded.BraceWrapping.SplitEmptyFunction = true;
Francois Ferrandad722562017-06-30 20:25:55 +0000565 Expanded.BraceWrapping.SplitEmptyRecord = false;
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000566 break;
567 case FormatStyle::BS_Stroustrup:
568 Expanded.BraceWrapping.AfterFunction = true;
569 Expanded.BraceWrapping.BeforeCatch = true;
570 Expanded.BraceWrapping.BeforeElse = true;
571 break;
572 case FormatStyle::BS_Allman:
573 Expanded.BraceWrapping.AfterClass = true;
574 Expanded.BraceWrapping.AfterControlStatement = true;
575 Expanded.BraceWrapping.AfterEnum = true;
576 Expanded.BraceWrapping.AfterFunction = true;
577 Expanded.BraceWrapping.AfterNamespace = true;
578 Expanded.BraceWrapping.AfterObjCDeclaration = true;
579 Expanded.BraceWrapping.AfterStruct = true;
Krasimir Georgievd6ce9372017-09-15 11:23:50 +0000580 Expanded.BraceWrapping.AfterExternBlock = true;
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000581 Expanded.BraceWrapping.BeforeCatch = true;
582 Expanded.BraceWrapping.BeforeElse = true;
583 break;
584 case FormatStyle::BS_GNU:
Manuel Klimek89628f62017-09-20 09:51:03 +0000585 Expanded.BraceWrapping = {true, true, true, true, true, true, true, true,
586 true, true, true, true, true, true, true};
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000587 break;
588 case FormatStyle::BS_WebKit:
589 Expanded.BraceWrapping.AfterFunction = true;
590 break;
591 default:
592 break;
593 }
594 return Expanded;
595}
596
Daniel Jasperf7935112012-12-03 18:12:45 +0000597FormatStyle getLLVMStyle() {
598 FormatStyle LLVMStyle;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000599 LLVMStyle.Language = FormatStyle::LK_Cpp;
Daniel Jasperf7935112012-12-03 18:12:45 +0000600 LLVMStyle.AccessModifierOffset = -2;
Daniel Jasper7fdbb3f2017-05-08 15:08:00 +0000601 LLVMStyle.AlignEscapedNewlines = FormatStyle::ENAS_Right;
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000602 LLVMStyle.AlignAfterOpenBracket = FormatStyle::BAS_Align;
Daniel Jasper3219e432014-12-02 13:24:51 +0000603 LLVMStyle.AlignOperands = true;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000604 LLVMStyle.AlignTrailingComments = true;
Daniel Jaspera44991332015-04-29 13:06:49 +0000605 LLVMStyle.AlignConsecutiveAssignments = false;
Daniel Jaspere12597c2015-10-01 10:06:54 +0000606 LLVMStyle.AlignConsecutiveDeclarations = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000607 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000608 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000609 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000610 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000611 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000612 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Zachary Turner448592e2015-12-18 22:20:15 +0000613 LLVMStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000614 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
Alexander Kornienko58611712013-07-04 12:02:44 +0000615 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000616 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Daniel Jasper18210d72014-10-09 09:52:05 +0000617 LLVMStyle.BinPackArguments = true;
Francois Ferrande56a8292017-06-14 12:29:47 +0000618 LLVMStyle.BinPackParameters = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000619 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000620 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000621 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Manuel Klimek89628f62017-09-20 09:51:03 +0000622 LLVMStyle.BraceWrapping = {false, false, false, false, false,
623 false, false, false, false, false,
624 false, false, true, true, true};
Nico Weber2cd92f12015-10-15 16:03:01 +0000625 LLVMStyle.BreakAfterJavaFieldAnnotations = false;
Francois Ferranda6b6d512017-05-24 11:36:58 +0000626 LLVMStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
Andi-Bogdan Postelnicu0ef8ee12017-03-10 15:10:37 +0000627 LLVMStyle.BreakBeforeInheritanceComma = false;
Daniel Jaspere1a7b762016-02-01 11:21:02 +0000628 LLVMStyle.BreakStringLiterals = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000629 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000630 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Francois Ferrande56a8292017-06-14 12:29:47 +0000631 LLVMStyle.CompactNamespaces = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000632 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000633 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000634 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000635 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000636 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000637 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Krasimir Georgiev32eaa862017-03-01 15:35:39 +0000638 LLVMStyle.FixNamespaceComments = true;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000639 LLVMStyle.ForEachMacros.push_back("foreach");
640 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
641 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Daniel Jasper85c472d2015-09-29 07:53:08 +0000642 LLVMStyle.IncludeCategories = {{"^\"(llvm|llvm-c|clang|clang-c)/", 2},
Chandler Carruthd676ab12017-06-29 23:20:54 +0000643 {"^(<|\"(gtest|gmock|isl|json)/)", 3},
Daniel Jasper85c472d2015-09-29 07:53:08 +0000644 {".*", 1}};
Chandler Carruthd676ab12017-06-29 23:20:54 +0000645 LLVMStyle.IncludeIsMainRegex = "(Test)?$";
Krasimir Georgiev4c2c9c32017-11-27 13:23:45 +0000646 LLVMStyle.IncludeBlocks = FormatStyle::IBS_Preserve;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000647 LLVMStyle.IndentCaseLabels = false;
Krasimir Georgievad47c902017-08-30 14:34:57 +0000648 LLVMStyle.IndentPPDirectives = FormatStyle::PPDIS_None;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000649 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000650 LLVMStyle.IndentWidth = 2;
Martin Probstfb2342d2016-06-13 17:50:10 +0000651 LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
652 LLVMStyle.JavaScriptWrapImports = true;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000653 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000654 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000655 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000656 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Ben Hamilton4dc658c2018-02-02 20:15:14 +0000657 LLVMStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Auto;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000658 LLVMStyle.ObjCBlockIndentWidth = 2;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000659 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000660 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000661 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000662 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000663 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000664 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jaspera0a50392015-12-01 13:28:53 +0000665 LLVMStyle.ReflowComments = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000666 LLVMStyle.SpacesInParentheses = false;
Daniel Jasperad981f82014-08-26 11:41:14 +0000667 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000668 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000669 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000670 LLVMStyle.SpacesInCStyleCastParentheses = false;
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000671 LLVMStyle.SpaceAfterCStyleCast = false;
Sylvestre Ledru83bbd572016-08-09 14:24:40 +0000672 LLVMStyle.SpaceAfterTemplateKeyword = true;
Francois Ferrand2a9ea782018-03-01 10:09:13 +0000673 LLVMStyle.SpaceBeforeCtorInitializerColon = true;
674 LLVMStyle.SpaceBeforeInheritanceColon = true;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000675 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Francois Ferrand2a9ea782018-03-01 10:09:13 +0000676 LLVMStyle.SpaceBeforeRangeBasedForLoopColon = true;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000677 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000678 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000679
Francois Ferrand9976efa2017-05-22 08:28:17 +0000680 LLVMStyle.PenaltyBreakAssignment = prec::Assignment;
Daniel Jasper19a541e2013-12-19 16:45:34 +0000681 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000682 LLVMStyle.PenaltyBreakFirstLessLess = 120;
683 LLVMStyle.PenaltyBreakString = 1000;
684 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000685 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000686 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000687
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000688 LLVMStyle.DisableFormat = false;
Daniel Jasperda446772015-11-16 12:38:56 +0000689 LLVMStyle.SortIncludes = true;
Krasimir Georgievac16a202017-06-23 11:46:03 +0000690 LLVMStyle.SortUsingDeclarations = true;
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000691
Daniel Jasperf7935112012-12-03 18:12:45 +0000692 return LLVMStyle;
693}
694
Nico Weber514ecc82014-02-02 20:50:45 +0000695FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Krasimir Georgiev26b144c2017-07-03 15:05:14 +0000696 if (Language == FormatStyle::LK_TextProto) {
697 FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_Proto);
698 GoogleStyle.Language = FormatStyle::LK_TextProto;
Krasimir Georgieveda222e2018-01-24 11:18:39 +0000699
Krasimir Georgiev26b144c2017-07-03 15:05:14 +0000700 return GoogleStyle;
701 }
702
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000703 FormatStyle GoogleStyle = getLLVMStyle();
Nico Weber514ecc82014-02-02 20:50:45 +0000704 GoogleStyle.Language = Language;
705
Daniel Jasperf7935112012-12-03 18:12:45 +0000706 GoogleStyle.AccessModifierOffset = -1;
Daniel Jasper7fdbb3f2017-05-08 15:08:00 +0000707 GoogleStyle.AlignEscapedNewlines = FormatStyle::ENAS_Left;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000708 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000709 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000710 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000711 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000712 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000713 GoogleStyle.DerivePointerAlignment = true;
Krasimir Georgieva84e7872017-09-26 14:58:29 +0000714 GoogleStyle.IncludeCategories = {
715 {"^<ext/.*\\.h>", 2}, {"^<.*\\.h>", 1}, {"^<.*", 2}, {".*", 3}};
Daniel Jasper9c8ff352016-03-21 14:11:27 +0000716 GoogleStyle.IncludeIsMainRegex = "([-_](test|unittest))?$";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000717 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000718 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Ben Hamilton3a47fdd2018-02-08 01:49:10 +0000719 GoogleStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000720 GoogleStyle.ObjCSpaceAfterProperty = false;
Ben Hamiltonf84f1182018-01-18 18:37:16 +0000721 GoogleStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000722 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Krasimir Georgiev5559cc32018-04-25 14:56:19 +0000723 GoogleStyle.RawStringFormats = {
Krasimir Georgiev4527f132018-01-17 12:24:59 +0000724 {
Krasimir Georgiev5559cc32018-04-25 14:56:19 +0000725 FormatStyle::LK_Cpp,
726 /*Delimiters=*/
727 {
728 "cc",
729 "CC",
730 "cpp",
731 "Cpp",
732 "CPP",
733 "c++",
734 "C++",
735 },
736 /*EnclosingFunctionNames=*/
737 {},
738 /*CanonicalDelimiter=*/"",
739 /*BasedOnStyle=*/"google",
Krasimir Georgiev4527f132018-01-17 12:24:59 +0000740 },
Krasimir Georgiev5559cc32018-04-25 14:56:19 +0000741 {
742 FormatStyle::LK_TextProto,
743 /*Delimiters=*/
744 {
745 "pb",
746 "PB",
747 "proto",
748 "PROTO",
749 },
750 /*EnclosingFunctionNames=*/
751 {},
752 /*CanonicalDelimiter=*/"",
753 /*BasedOnStyle=*/"google",
754 },
755 };
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000756 GoogleStyle.SpacesBeforeTrailingComments = 2;
757 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000758
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000759 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000760 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000761
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000762 if (Language == FormatStyle::LK_Java) {
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000763 GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
Daniel Jasper3219e432014-12-02 13:24:51 +0000764 GoogleStyle.AlignOperands = false;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000765 GoogleStyle.AlignTrailingComments = false;
Daniel Jasper9e709352014-11-26 10:43:58 +0000766 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000767 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper1cd3c712015-01-14 12:24:59 +0000768 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000769 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
770 GoogleStyle.ColumnLimit = 100;
771 GoogleStyle.SpaceAfterCStyleCast = true;
Daniel Jasper61d81972014-11-14 08:22:46 +0000772 GoogleStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000773 } else if (Language == FormatStyle::LK_JavaScript) {
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000774 GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
Daniel Jasper41a2bf72015-12-21 13:52:19 +0000775 GoogleStyle.AlignOperands = false;
Daniel Jasper28d8a5a2016-09-07 23:01:13 +0000776 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000777 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere551bb72014-11-05 17:22:31 +0000778 GoogleStyle.BreakBeforeTernaryOperators = false;
Martin Probst2083f312017-05-09 12:45:48 +0000779 // taze:, triple slash directives (`/// <...`), @tag followed by { for a lot
780 // of JSDoc tags, and @see, which is commonly followed by overlong URLs.
781 GoogleStyle.CommentPragmas =
782 "(taze:|^/[ \t]*<|(@[A-Za-z_0-9-]+[ \\t]*{)|@see)";
Daniel Jasper8f83a902014-05-09 10:28:58 +0000783 GoogleStyle.MaxEmptyLinesToKeep = 3;
Martin Probstece8c0c2016-06-13 16:41:28 +0000784 GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
Nico Weber514ecc82014-02-02 20:50:45 +0000785 GoogleStyle.SpacesInContainerLiterals = false;
Daniel Jasperabd1f572016-03-02 22:44:03 +0000786 GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single;
Martin Probst0cd74ee2016-06-13 16:39:50 +0000787 GoogleStyle.JavaScriptWrapImports = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000788 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasperd74cf402014-04-08 12:46:38 +0000789 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
Daniel Jasper9c95dfe2018-03-12 10:32:18 +0000790 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jasper783bac62014-04-15 09:54:30 +0000791 GoogleStyle.SpacesInContainerLiterals = false;
Krasimir Georgievc2091802018-01-31 10:14:10 +0000792 GoogleStyle.Cpp11BracedListStyle = false;
Krasimir Georgiev374e6de2018-02-08 10:47:12 +0000793 // This affects protocol buffer options specifications and text protos.
794 // Text protos are currently mostly formatted inside C++ raw string literals
795 // and often the current breaking behavior of string literals is not
796 // beneficial there. Investigate turning this on once proper string reflow
797 // has been implemented.
798 GoogleStyle.BreakStringLiterals = false;
Daniel Jasper03a04fe2016-12-12 12:42:29 +0000799 } else if (Language == FormatStyle::LK_ObjC) {
800 GoogleStyle.ColumnLimit = 100;
Nico Weber514ecc82014-02-02 20:50:45 +0000801 }
802
Daniel Jasperf7935112012-12-03 18:12:45 +0000803 return GoogleStyle;
804}
805
Nico Weber514ecc82014-02-02 20:50:45 +0000806FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
807 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Nico Weber450425c2014-11-26 16:43:18 +0000808 if (Language == FormatStyle::LK_Java) {
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000809 ChromiumStyle.AllowShortIfStatementsOnASingleLine = true;
Nico Weber2cd92f12015-10-15 16:03:01 +0000810 ChromiumStyle.BreakAfterJavaFieldAnnotations = true;
Nico Weber450425c2014-11-26 16:43:18 +0000811 ChromiumStyle.ContinuationIndentWidth = 8;
Nico Weber2cd92f12015-10-15 16:03:01 +0000812 ChromiumStyle.IndentWidth = 4;
Nico Weberea649692017-01-04 02:33:36 +0000813 } else if (Language == FormatStyle::LK_JavaScript) {
814 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
815 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Nico Weber450425c2014-11-26 16:43:18 +0000816 } else {
817 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
818 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
819 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
820 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
821 ChromiumStyle.BinPackParameters = false;
822 ChromiumStyle.DerivePointerAlignment = false;
Nico Weber9e2bc302017-01-31 18:42:05 +0000823 if (Language == FormatStyle::LK_ObjC)
824 ChromiumStyle.ColumnLimit = 80;
Nico Weber450425c2014-11-26 16:43:18 +0000825 }
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000826 return ChromiumStyle;
827}
828
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000829FormatStyle getMozillaStyle() {
830 FormatStyle MozillaStyle = getLLVMStyle();
831 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000832 MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Manuel Klimek89628f62017-09-20 09:51:03 +0000833 MozillaStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000834 MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
835 FormatStyle::DRTBS_TopLevel;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000836 MozillaStyle.AlwaysBreakTemplateDeclarations = true;
Sylvestre Ledrudcb038d2016-12-14 16:09:29 +0000837 MozillaStyle.BinPackParameters = false;
838 MozillaStyle.BinPackArguments = false;
Birunthan Mohanathas305fa9c2015-07-12 03:13:54 +0000839 MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
Francois Ferranda6b6d512017-05-24 11:36:58 +0000840 MozillaStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
Andi-Bogdan Postelnicu0ef8ee12017-03-10 15:10:37 +0000841 MozillaStyle.BreakBeforeInheritanceComma = true;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000842 MozillaStyle.ConstructorInitializerIndentWidth = 2;
843 MozillaStyle.ContinuationIndentWidth = 2;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000844 MozillaStyle.Cpp11BracedListStyle = false;
Krasimir Georgiev32eaa862017-03-01 15:35:39 +0000845 MozillaStyle.FixNamespaceComments = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000846 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000847 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000848 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
849 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000850 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Sylvestre Ledru83bbd572016-08-09 14:24:40 +0000851 MozillaStyle.SpaceAfterTemplateKeyword = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000852 return MozillaStyle;
853}
854
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000855FormatStyle getWebKitStyle() {
856 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000857 Style.AccessModifierOffset = -4;
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000858 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
Daniel Jasper3219e432014-12-02 13:24:51 +0000859 Style.AlignOperands = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000860 Style.AlignTrailingComments = false;
Daniel Jasperac043c92014-09-15 11:11:00 +0000861 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Roman Kashitsyn291f64f2015-08-10 13:43:19 +0000862 Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
Francois Ferranda6b6d512017-05-24 11:36:58 +0000863 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000864 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000865 Style.ColumnLimit = 0;
Krasimir Georgiev32eaa862017-03-01 15:35:39 +0000866 Style.FixNamespaceComments = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000867 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000868 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000869 Style.ObjCBlockIndentWidth = 4;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000870 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000871 Style.PointerAlignment = FormatStyle::PAS_Left;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000872 return Style;
873}
874
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000875FormatStyle getGNUStyle() {
876 FormatStyle Style = getLLVMStyle();
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000877 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
Zachary Turner448592e2015-12-18 22:20:15 +0000878 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
Daniel Jasperac043c92014-09-15 11:11:00 +0000879 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000880 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000881 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000882 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000883 Style.ColumnLimit = 79;
Krasimir Georgiev32eaa862017-03-01 15:35:39 +0000884 Style.FixNamespaceComments = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000885 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000886 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000887 return Style;
888}
889
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000890FormatStyle getNoStyle() {
891 FormatStyle NoStyle = getLLVMStyle();
892 NoStyle.DisableFormat = true;
Daniel Jasperda446772015-11-16 12:38:56 +0000893 NoStyle.SortIncludes = false;
Krasimir Georgievac16a202017-06-23 11:46:03 +0000894 NoStyle.SortUsingDeclarations = false;
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000895 return NoStyle;
896}
897
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000898bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
899 FormatStyle *Style) {
900 if (Name.equals_lower("llvm")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000901 *Style = getLLVMStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000902 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000903 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000904 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000905 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000906 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +0000907 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000908 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000909 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000910 } else if (Name.equals_lower("gnu")) {
911 *Style = getGNUStyle();
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000912 } else if (Name.equals_lower("none")) {
913 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000914 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000915 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000916 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000917
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000918 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000919 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000920}
921
Rafael Espindolac0809172014-06-12 14:02:15 +0000922std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000923 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000924 FormatStyle::LanguageKind Language = Style->Language;
925 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +0000926 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +0000927 return make_error_code(ParseError::Error);
Krasimir Georgiev54076fe2018-01-15 12:06:16 +0000928 Style->StyleSet.Clear();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000929 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000930 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000931 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
932 // values for the fields, keys for which are missing from the configuration.
933 // Mapping also uses the context to get the language to find the correct
934 // base style.
935 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000936 Input >> Styles;
937 if (Input.error())
938 return Input.error();
939
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000940 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000941 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000942 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +0000943 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000944 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000945 for (unsigned j = 0; j < i; ++j) {
946 if (Styles[i].Language == Styles[j].Language) {
947 DEBUG(llvm::dbgs()
948 << "Duplicate languages in the config file on positions " << j
949 << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +0000950 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000951 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000952 }
953 }
954 // Look for a suitable configuration starting from the end, so we can
955 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000956 // configuration (which can only be at slot 0) after it.
Krasimir Georgiev54076fe2018-01-15 12:06:16 +0000957 FormatStyle::FormatStyleSet StyleSet;
958 bool LanguageFound = false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000959 for (int i = Styles.size() - 1; i >= 0; --i) {
Krasimir Georgiev54076fe2018-01-15 12:06:16 +0000960 if (Styles[i].Language != FormatStyle::LK_None)
961 StyleSet.Add(Styles[i]);
962 if (Styles[i].Language == Language)
963 LanguageFound = true;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000964 }
Krasimir Georgiev54076fe2018-01-15 12:06:16 +0000965 if (!LanguageFound) {
966 if (Styles.empty() || Styles[0].Language != FormatStyle::LK_None)
967 return make_error_code(ParseError::Unsuitable);
968 FormatStyle DefaultStyle = Styles[0];
969 DefaultStyle.Language = Language;
970 StyleSet.Add(std::move(DefaultStyle));
971 }
972 *Style = *StyleSet.Get(Language);
973 return make_error_code(ParseError::Success);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000974}
975
976std::string configurationAsText(const FormatStyle &Style) {
977 std::string Text;
978 llvm::raw_string_ostream Stream(Text);
979 llvm::yaml::Output Output(Stream);
980 // We use the same mapping method for input and output, so we need a non-const
981 // reference here.
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000982 FormatStyle NonConstStyle = expandPresets(Style);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000983 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000984 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000985}
986
Krasimir Georgiev54076fe2018-01-15 12:06:16 +0000987llvm::Optional<FormatStyle>
988FormatStyle::FormatStyleSet::Get(FormatStyle::LanguageKind Language) const {
989 if (!Styles)
990 return None;
991 auto It = Styles->find(Language);
992 if (It == Styles->end())
993 return None;
994 FormatStyle Style = It->second;
995 Style.StyleSet = *this;
996 return Style;
997}
998
999void FormatStyle::FormatStyleSet::Add(FormatStyle Style) {
1000 assert(Style.Language != LK_None &&
1001 "Cannot add a style for LK_None to a StyleSet");
1002 assert(
1003 !Style.StyleSet.Styles &&
1004 "Cannot add a style associated with an existing StyleSet to a StyleSet");
1005 if (!Styles)
1006 Styles = std::make_shared<MapType>();
1007 (*Styles)[Style.Language] = std::move(Style);
1008}
1009
1010void FormatStyle::FormatStyleSet::Clear() {
1011 Styles.reset();
1012}
1013
1014llvm::Optional<FormatStyle>
1015FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind Language) const {
1016 return StyleSet.Get(Language);
1017}
1018
Craig Topperaf35e852013-06-30 22:29:28 +00001019namespace {
1020
Daniel Jasper496c1992016-09-07 22:48:53 +00001021class JavaScriptRequoter : public TokenAnalyzer {
Eric Liu4cfb88a2016-04-25 15:09:22 +00001022public:
Daniel Jasper496c1992016-09-07 22:48:53 +00001023 JavaScriptRequoter(const Environment &Env, const FormatStyle &Style)
1024 : TokenAnalyzer(Env, Style) {}
Eric Liu4cfb88a2016-04-25 15:09:22 +00001025
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001026 std::pair<tooling::Replacements, unsigned>
Eric Liu4cfb88a2016-04-25 15:09:22 +00001027 analyze(TokenAnnotator &Annotator,
1028 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
Martin Probsta9855af2016-09-02 14:29:48 +00001029 FormatTokenLexer &Tokens) override {
Manuel Klimek0dddcf72018-04-23 09:34:26 +00001030 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
Daniel Jasper496c1992016-09-07 22:48:53 +00001031 tooling::Replacements Result;
1032 requoteJSStringLiteral(AnnotatedLines, Result);
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001033 return {Result, 0};
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001034 }
1035
1036private:
Daniel Jasper496c1992016-09-07 22:48:53 +00001037 // Replaces double/single-quoted string literal as appropriate, re-escaping
1038 // the contents in the process.
Daniel Jasper97439922016-03-17 13:03:41 +00001039 void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
Eric Liu4cfb88a2016-04-25 15:09:22 +00001040 tooling::Replacements &Result) {
Daniel Jasper97439922016-03-17 13:03:41 +00001041 for (AnnotatedLine *Line : Lines) {
1042 requoteJSStringLiteral(Line->Children, Result);
1043 if (!Line->Affected)
1044 continue;
1045 for (FormatToken *FormatTok = Line->First; FormatTok;
1046 FormatTok = FormatTok->Next) {
1047 StringRef Input = FormatTok->TokenText;
Martin Probsta1669792016-05-12 11:20:32 +00001048 if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
Daniel Jasper97439922016-03-17 13:03:41 +00001049 // NB: testing for not starting with a double quote to avoid
Daniel Jasper496c1992016-09-07 22:48:53 +00001050 // breaking `template strings`.
Eric Liu635423e2016-04-28 07:52:03 +00001051 (Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
Daniel Jasper97439922016-03-17 13:03:41 +00001052 !Input.startswith("\"")) ||
Eric Liu635423e2016-04-28 07:52:03 +00001053 (Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
Daniel Jasper97439922016-03-17 13:03:41 +00001054 !Input.startswith("\'")))
1055 continue;
1056
1057 // Change start and end quote.
Eric Liu635423e2016-04-28 07:52:03 +00001058 bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
Daniel Jasper97439922016-03-17 13:03:41 +00001059 SourceLocation Start = FormatTok->Tok.getLocation();
1060 auto Replace = [&](SourceLocation Start, unsigned Length,
1061 StringRef ReplacementText) {
Eric Liu40ef2fb2016-08-01 10:16:37 +00001062 auto Err = Result.add(tooling::Replacement(
1063 Env.getSourceManager(), Start, Length, ReplacementText));
1064 // FIXME: handle error. For now, print error message and skip the
1065 // replacement for release version.
Piotr Padlewski1ec383c2016-12-23 11:40:44 +00001066 if (Err) {
Eric Liu40ef2fb2016-08-01 10:16:37 +00001067 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Piotr Padlewski1ec383c2016-12-23 11:40:44 +00001068 assert(false);
1069 }
Daniel Jasper97439922016-03-17 13:03:41 +00001070 };
1071 Replace(Start, 1, IsSingle ? "'" : "\"");
1072 Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
1073 IsSingle ? "'" : "\"");
1074
1075 // Escape internal quotes.
Daniel Jasper97439922016-03-17 13:03:41 +00001076 bool Escaped = false;
1077 for (size_t i = 1; i < Input.size() - 1; i++) {
1078 switch (Input[i]) {
Eric Liu4cfb88a2016-04-25 15:09:22 +00001079 case '\\':
1080 if (!Escaped && i + 1 < Input.size() &&
1081 ((IsSingle && Input[i + 1] == '"') ||
1082 (!IsSingle && Input[i + 1] == '\''))) {
1083 // Remove this \, it's escaping a " or ' that no longer needs
1084 // escaping
Eric Liu4cfb88a2016-04-25 15:09:22 +00001085 Replace(Start.getLocWithOffset(i), 1, "");
1086 continue;
1087 }
1088 Escaped = !Escaped;
1089 break;
1090 case '\"':
1091 case '\'':
1092 if (!Escaped && IsSingle == (Input[i] == '\'')) {
1093 // Escape the quote.
1094 Replace(Start.getLocWithOffset(i), 0, "\\");
Eric Liu4cfb88a2016-04-25 15:09:22 +00001095 }
1096 Escaped = false;
1097 break;
1098 default:
1099 Escaped = false;
1100 break;
Daniel Jasper97439922016-03-17 13:03:41 +00001101 }
1102 }
Daniel Jasper97439922016-03-17 13:03:41 +00001103 }
1104 }
1105 }
Daniel Jasper496c1992016-09-07 22:48:53 +00001106};
1107
1108class Formatter : public TokenAnalyzer {
1109public:
1110 Formatter(const Environment &Env, const FormatStyle &Style,
Krasimir Georgievbcda54b2017-04-21 14:35:20 +00001111 FormattingAttemptStatus *Status)
1112 : TokenAnalyzer(Env, Style), Status(Status) {}
Daniel Jasper496c1992016-09-07 22:48:53 +00001113
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001114 std::pair<tooling::Replacements, unsigned>
Daniel Jasper496c1992016-09-07 22:48:53 +00001115 analyze(TokenAnnotator &Annotator,
1116 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1117 FormatTokenLexer &Tokens) override {
1118 tooling::Replacements Result;
1119 deriveLocalStyle(AnnotatedLines);
Manuel Klimek0dddcf72018-04-23 09:34:26 +00001120 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
Daniel Jasper496c1992016-09-07 22:48:53 +00001121 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1122 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
1123 }
1124 Annotator.setCommentLineLevels(AnnotatedLines);
1125
1126 WhitespaceManager Whitespaces(
1127 Env.getSourceManager(), Style,
1128 inputUsesCRLF(Env.getSourceManager().getBufferData(Env.getFileID())));
1129 ContinuationIndenter Indenter(Style, Tokens.getKeywords(),
1130 Env.getSourceManager(), Whitespaces, Encoding,
1131 BinPackInconclusiveFunctions);
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001132 unsigned Penalty =
1133 UnwrappedLineFormatter(&Indenter, &Whitespaces, Style,
1134 Tokens.getKeywords(), Env.getSourceManager(),
1135 Status)
1136 .format(AnnotatedLines, /*DryRun=*/false,
1137 /*AdditionalIndent=*/0,
1138 /*FixBadIndentation=*/false,
1139 /*FirstStartColumn=*/Env.getFirstStartColumn(),
1140 /*NextStartColumn=*/Env.getNextStartColumn(),
1141 /*LastStartColumn=*/Env.getLastStartColumn());
Daniel Jasper496c1992016-09-07 22:48:53 +00001142 for (const auto &R : Whitespaces.generateReplacements())
1143 if (Result.add(R))
Krasimir Georgieve56e9a42017-10-30 14:30:14 +00001144 return std::make_pair(Result, 0);
1145 return std::make_pair(Result, Penalty);
Daniel Jasper496c1992016-09-07 22:48:53 +00001146 }
1147
1148private:
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001149 static bool inputUsesCRLF(StringRef Text) {
1150 return Text.count('\r') * 2 > Text.count('\n');
1151 }
1152
Daniel Jasper352f0df2015-07-18 16:35:30 +00001153 bool
1154 hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
Eric Liu4cfb88a2016-04-25 15:09:22 +00001155 for (const AnnotatedLine *Line : Lines) {
Daniel Jasper352f0df2015-07-18 16:35:30 +00001156 if (hasCpp03IncompatibleFormat(Line->Children))
1157 return true;
1158 for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
1159 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1160 if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
1161 return true;
1162 if (Tok->is(TT_TemplateCloser) &&
1163 Tok->Previous->is(TT_TemplateCloser))
1164 return true;
1165 }
1166 }
1167 }
1168 return false;
1169 }
1170
1171 int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1172 int AlignmentDiff = 0;
Eric Liu4cfb88a2016-04-25 15:09:22 +00001173 for (const AnnotatedLine *Line : Lines) {
Daniel Jasper352f0df2015-07-18 16:35:30 +00001174 AlignmentDiff += countVariableAlignments(Line->Children);
1175 for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
1176 if (!Tok->is(TT_PointerOrReference))
1177 continue;
1178 bool SpaceBefore =
1179 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1180 bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() !=
1181 Tok->Next->WhitespaceRange.getEnd();
1182 if (SpaceBefore && !SpaceAfter)
1183 ++AlignmentDiff;
1184 if (!SpaceBefore && SpaceAfter)
1185 --AlignmentDiff;
1186 }
1187 }
1188 return AlignmentDiff;
1189 }
1190
Manuel Klimek71814b42013-10-11 21:25:45 +00001191 void
1192 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001193 bool HasBinPackedFunction = false;
1194 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001195 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001196 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001197 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001198 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001199 while (Tok->Next) {
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001200 if (Tok->PackingKind == PPK_BinPacked)
1201 HasBinPackedFunction = true;
1202 if (Tok->PackingKind == PPK_OnePerLine)
1203 HasOnePerLineFunction = true;
1204
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001205 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001206 }
1207 }
Eric Liu635423e2016-04-28 07:52:03 +00001208 if (Style.DerivePointerAlignment)
1209 Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
1210 ? FormatStyle::PAS_Left
1211 : FormatStyle::PAS_Right;
1212 if (Style.Standard == FormatStyle::LS_Auto)
1213 Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
1214 ? FormatStyle::LS_Cpp11
1215 : FormatStyle::LS_Cpp03;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001216 BinPackInconclusiveFunctions =
1217 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001218 }
1219
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001220 bool BinPackInconclusiveFunctions;
Krasimir Georgievbcda54b2017-04-21 14:35:20 +00001221 FormattingAttemptStatus *Status;
Eric Liu4cfb88a2016-04-25 15:09:22 +00001222};
1223
1224// This class clean up the erroneous/redundant code around the given ranges in
1225// file.
1226class Cleaner : public TokenAnalyzer {
1227public:
Eric Liu635423e2016-04-28 07:52:03 +00001228 Cleaner(const Environment &Env, const FormatStyle &Style)
1229 : TokenAnalyzer(Env, Style),
Eric Liu4cfb88a2016-04-25 15:09:22 +00001230 DeletedTokens(FormatTokenLess(Env.getSourceManager())) {}
1231
1232 // FIXME: eliminate unused parameters.
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001233 std::pair<tooling::Replacements, unsigned>
Eric Liu4cfb88a2016-04-25 15:09:22 +00001234 analyze(TokenAnnotator &Annotator,
1235 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
Martin Probsta9855af2016-09-02 14:29:48 +00001236 FormatTokenLexer &Tokens) override {
Eric Liu4cfb88a2016-04-25 15:09:22 +00001237 // FIXME: in the current implementation the granularity of affected range
1238 // is an annotated line. However, this is not sufficient. Furthermore,
1239 // redundant code introduced by replacements does not necessarily
1240 // intercept with ranges of replacements that result in the redundancy.
1241 // To determine if some redundant code is actually introduced by
1242 // replacements(e.g. deletions), we need to come up with a more
1243 // sophisticated way of computing affected ranges.
Manuel Klimek0dddcf72018-04-23 09:34:26 +00001244 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
Eric Liu4cfb88a2016-04-25 15:09:22 +00001245
1246 checkEmptyNamespace(AnnotatedLines);
1247
Eric Liuce5e4bc2016-05-18 08:02:56 +00001248 for (auto &Line : AnnotatedLines) {
1249 if (Line->Affected) {
1250 cleanupRight(Line->First, tok::comma, tok::comma);
1251 cleanupRight(Line->First, TT_CtorInitializerColon, tok::comma);
Eric Liu2574d152016-09-13 15:02:43 +00001252 cleanupRight(Line->First, tok::l_paren, tok::comma);
1253 cleanupLeft(Line->First, tok::comma, tok::r_paren);
Eric Liuce5e4bc2016-05-18 08:02:56 +00001254 cleanupLeft(Line->First, TT_CtorInitializerComma, tok::l_brace);
1255 cleanupLeft(Line->First, TT_CtorInitializerColon, tok::l_brace);
Malcolm Parsons5d8cdb82016-10-20 14:58:45 +00001256 cleanupLeft(Line->First, TT_CtorInitializerColon, tok::equal);
Eric Liuce5e4bc2016-05-18 08:02:56 +00001257 }
1258 }
1259
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001260 return {generateFixes(), 0};
Eric Liu4cfb88a2016-04-25 15:09:22 +00001261 }
1262
1263private:
1264 bool containsOnlyComments(const AnnotatedLine &Line) {
1265 for (FormatToken *Tok = Line.First; Tok != nullptr; Tok = Tok->Next) {
1266 if (Tok->isNot(tok::comment))
1267 return false;
1268 }
1269 return true;
1270 }
1271
1272 // Iterate through all lines and remove any empty (nested) namespaces.
1273 void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Eric Liu7956c402016-10-05 15:49:01 +00001274 std::set<unsigned> DeletedLines;
Eric Liu4cfb88a2016-04-25 15:09:22 +00001275 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1276 auto &Line = *AnnotatedLines[i];
1277 if (Line.startsWith(tok::kw_namespace) ||
1278 Line.startsWith(tok::kw_inline, tok::kw_namespace)) {
Eric Liu7956c402016-10-05 15:49:01 +00001279 checkEmptyNamespace(AnnotatedLines, i, i, DeletedLines);
Eric Liu4cfb88a2016-04-25 15:09:22 +00001280 }
1281 }
1282
1283 for (auto Line : DeletedLines) {
1284 FormatToken *Tok = AnnotatedLines[Line]->First;
1285 while (Tok) {
1286 deleteToken(Tok);
1287 Tok = Tok->Next;
1288 }
1289 }
1290 }
1291
1292 // The function checks if the namespace, which starts from \p CurrentLine, and
1293 // its nested namespaces are empty and delete them if they are empty. It also
1294 // sets \p NewLine to the last line checked.
1295 // Returns true if the current namespace is empty.
1296 bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
Eric Liu7956c402016-10-05 15:49:01 +00001297 unsigned CurrentLine, unsigned &NewLine,
1298 std::set<unsigned> &DeletedLines) {
Eric Liu4cfb88a2016-04-25 15:09:22 +00001299 unsigned InitLine = CurrentLine, End = AnnotatedLines.size();
Eric Liu635423e2016-04-28 07:52:03 +00001300 if (Style.BraceWrapping.AfterNamespace) {
Eric Liu4cfb88a2016-04-25 15:09:22 +00001301 // If the left brace is in a new line, we should consume it first so that
1302 // it does not make the namespace non-empty.
1303 // FIXME: error handling if there is no left brace.
1304 if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
1305 NewLine = CurrentLine;
1306 return false;
1307 }
1308 } else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
1309 return false;
1310 }
1311 while (++CurrentLine < End) {
1312 if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
1313 break;
1314
1315 if (AnnotatedLines[CurrentLine]->startsWith(tok::kw_namespace) ||
1316 AnnotatedLines[CurrentLine]->startsWith(tok::kw_inline,
1317 tok::kw_namespace)) {
Eric Liu7956c402016-10-05 15:49:01 +00001318 if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine,
1319 DeletedLines))
Eric Liu4cfb88a2016-04-25 15:09:22 +00001320 return false;
1321 CurrentLine = NewLine;
1322 continue;
1323 }
1324
1325 if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
1326 continue;
1327
1328 // If there is anything other than comments or nested namespaces in the
1329 // current namespace, the namespace cannot be empty.
1330 NewLine = CurrentLine;
1331 return false;
1332 }
1333
1334 NewLine = CurrentLine;
1335 if (CurrentLine >= End)
1336 return false;
1337
1338 // Check if the empty namespace is actually affected by changed ranges.
1339 if (!AffectedRangeMgr.affectsCharSourceRange(CharSourceRange::getCharRange(
1340 AnnotatedLines[InitLine]->First->Tok.getLocation(),
1341 AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc())))
1342 return false;
1343
1344 for (unsigned i = InitLine; i <= CurrentLine; ++i) {
1345 DeletedLines.insert(i);
1346 }
1347
1348 return true;
1349 }
1350
Eric Liuce5e4bc2016-05-18 08:02:56 +00001351 // Checks pairs {start, start->next},..., {end->previous, end} and deletes one
1352 // of the token in the pair if the left token has \p LK token kind and the
1353 // right token has \p RK token kind. If \p DeleteLeft is true, the left token
1354 // is deleted on match; otherwise, the right token is deleted.
1355 template <typename LeftKind, typename RightKind>
1356 void cleanupPair(FormatToken *Start, LeftKind LK, RightKind RK,
1357 bool DeleteLeft) {
1358 auto NextNotDeleted = [this](const FormatToken &Tok) -> FormatToken * {
1359 for (auto *Res = Tok.Next; Res; Res = Res->Next)
1360 if (!Res->is(tok::comment) &&
1361 DeletedTokens.find(Res) == DeletedTokens.end())
1362 return Res;
1363 return nullptr;
1364 };
1365 for (auto *Left = Start; Left;) {
1366 auto *Right = NextNotDeleted(*Left);
1367 if (!Right)
1368 break;
1369 if (Left->is(LK) && Right->is(RK)) {
1370 deleteToken(DeleteLeft ? Left : Right);
Eric Liu01426ff2016-09-09 17:50:49 +00001371 for (auto *Tok = Left->Next; Tok && Tok != Right; Tok = Tok->Next)
1372 deleteToken(Tok);
Eric Liuce5e4bc2016-05-18 08:02:56 +00001373 // If the right token is deleted, we should keep the left token
1374 // unchanged and pair it with the new right token.
1375 if (!DeleteLeft)
1376 continue;
1377 }
1378 Left = Right;
1379 }
1380 }
1381
1382 template <typename LeftKind, typename RightKind>
1383 void cleanupLeft(FormatToken *Start, LeftKind LK, RightKind RK) {
1384 cleanupPair(Start, LK, RK, /*DeleteLeft=*/true);
1385 }
1386
1387 template <typename LeftKind, typename RightKind>
1388 void cleanupRight(FormatToken *Start, LeftKind LK, RightKind RK) {
1389 cleanupPair(Start, LK, RK, /*DeleteLeft=*/false);
1390 }
1391
Eric Liu4cfb88a2016-04-25 15:09:22 +00001392 // Delete the given token.
1393 inline void deleteToken(FormatToken *Tok) {
1394 if (Tok)
1395 DeletedTokens.insert(Tok);
1396 }
1397
1398 tooling::Replacements generateFixes() {
1399 tooling::Replacements Fixes;
1400 std::vector<FormatToken *> Tokens;
1401 std::copy(DeletedTokens.begin(), DeletedTokens.end(),
1402 std::back_inserter(Tokens));
1403
1404 // Merge multiple continuous token deletions into one big deletion so that
1405 // the number of replacements can be reduced. This makes computing affected
1406 // ranges more efficient when we run reformat on the changed code.
1407 unsigned Idx = 0;
1408 while (Idx < Tokens.size()) {
1409 unsigned St = Idx, End = Idx;
1410 while ((End + 1) < Tokens.size() &&
1411 Tokens[End]->Next == Tokens[End + 1]) {
1412 End++;
1413 }
1414 auto SR = CharSourceRange::getCharRange(Tokens[St]->Tok.getLocation(),
1415 Tokens[End]->Tok.getEndLoc());
Eric Liu40ef2fb2016-08-01 10:16:37 +00001416 auto Err =
1417 Fixes.add(tooling::Replacement(Env.getSourceManager(), SR, ""));
1418 // FIXME: better error handling. for now just print error message and skip
1419 // for the release version.
Piotr Padlewski1ec383c2016-12-23 11:40:44 +00001420 if (Err) {
Eric Liu40ef2fb2016-08-01 10:16:37 +00001421 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Piotr Padlewski1ec383c2016-12-23 11:40:44 +00001422 assert(false && "Fixes must not conflict!");
1423 }
Eric Liu4cfb88a2016-04-25 15:09:22 +00001424 Idx = End + 1;
1425 }
1426
1427 return Fixes;
1428 }
1429
1430 // Class for less-than inequality comparason for the set `RedundantTokens`.
1431 // We store tokens in the order they appear in the translation unit so that
1432 // we do not need to sort them in `generateFixes()`.
1433 struct FormatTokenLess {
Eric Liu635423e2016-04-28 07:52:03 +00001434 FormatTokenLess(const SourceManager &SM) : SM(SM) {}
Eric Liu4cfb88a2016-04-25 15:09:22 +00001435
Eric Liu2874ac32016-05-18 08:14:49 +00001436 bool operator()(const FormatToken *LHS, const FormatToken *RHS) const {
Eric Liu4cfb88a2016-04-25 15:09:22 +00001437 return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(),
1438 RHS->Tok.getLocation());
1439 }
Eric Liu635423e2016-04-28 07:52:03 +00001440 const SourceManager &SM;
Eric Liu4cfb88a2016-04-25 15:09:22 +00001441 };
1442
1443 // Tokens to be deleted.
1444 std::set<FormatToken *, FormatTokenLess> DeletedTokens;
Daniel Jasperf7935112012-12-03 18:12:45 +00001445};
1446
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001447class ObjCHeaderStyleGuesser : public TokenAnalyzer {
1448public:
1449 ObjCHeaderStyleGuesser(const Environment &Env, const FormatStyle &Style)
1450 : TokenAnalyzer(Env, Style), IsObjC(false) {}
1451
1452 std::pair<tooling::Replacements, unsigned>
1453 analyze(TokenAnnotator &Annotator,
1454 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1455 FormatTokenLexer &Tokens) override {
1456 assert(Style.Language == FormatStyle::LK_Cpp);
1457 IsObjC = guessIsObjC(AnnotatedLines, Tokens.getKeywords());
1458 tooling::Replacements Result;
1459 return {Result, 0};
1460 }
1461
1462 bool isObjC() { return IsObjC; }
1463
1464private:
1465 static bool guessIsObjC(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1466 const AdditionalKeywords &Keywords) {
Krasimir Georgiev8e216782018-01-17 20:01:02 +00001467 // Keep this array sorted, since we are binary searching over it.
1468 static constexpr llvm::StringLiteral FoundationIdentifiers[] = {
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001469 "CGFloat",
Ben Hamilton19c782d2018-03-22 03:25:22 +00001470 "CGPoint",
1471 "CGPointMake",
1472 "CGPointZero",
1473 "CGRect",
1474 "CGRectEdge",
1475 "CGRectInfinite",
1476 "CGRectMake",
1477 "CGRectNull",
1478 "CGRectZero",
1479 "CGSize",
1480 "CGSizeMake",
1481 "CGVector",
1482 "CGVectorMake",
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001483 "NSAffineTransform",
1484 "NSArray",
1485 "NSAttributedString",
Ben Hamiltonb1a79192018-04-12 15:11:53 +00001486 "NSBlockOperation",
Jacek Olesiakce4f0af2018-02-15 08:47:56 +00001487 "NSBundle",
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001488 "NSCache",
Jacek Olesiakce4f0af2018-02-15 08:47:56 +00001489 "NSCalendar",
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001490 "NSCharacterSet",
1491 "NSCountedSet",
1492 "NSData",
1493 "NSDataDetector",
1494 "NSDecimal",
1495 "NSDecimalNumber",
1496 "NSDictionary",
1497 "NSEdgeInsets",
1498 "NSHashTable",
1499 "NSIndexPath",
1500 "NSIndexSet",
1501 "NSInteger",
Ben Hamiltonb1a79192018-04-12 15:11:53 +00001502 "NSInvocationOperation",
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001503 "NSLocale",
1504 "NSMapTable",
1505 "NSMutableArray",
1506 "NSMutableAttributedString",
1507 "NSMutableCharacterSet",
1508 "NSMutableData",
1509 "NSMutableDictionary",
1510 "NSMutableIndexSet",
1511 "NSMutableOrderedSet",
1512 "NSMutableSet",
1513 "NSMutableString",
1514 "NSNumber",
1515 "NSNumberFormatter",
Jacek Olesiakce4f0af2018-02-15 08:47:56 +00001516 "NSObject",
Ben Hamiltonb1a79192018-04-12 15:11:53 +00001517 "NSOperation",
1518 "NSOperationQueue",
1519 "NSOperationQueuePriority",
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001520 "NSOrderedSet",
1521 "NSPoint",
1522 "NSPointerArray",
Ben Hamiltonb1a79192018-04-12 15:11:53 +00001523 "NSQualityOfService",
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001524 "NSRange",
1525 "NSRect",
1526 "NSRegularExpression",
1527 "NSSet",
1528 "NSSize",
1529 "NSString",
Jacek Olesiakce4f0af2018-02-15 08:47:56 +00001530 "NSTimeZone",
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001531 "NSUInteger",
1532 "NSURL",
1533 "NSURLComponents",
1534 "NSURLQueryItem",
1535 "NSUUID",
Jacek Olesiakce4f0af2018-02-15 08:47:56 +00001536 "NSValue",
Ben Hamilton19c782d2018-03-22 03:25:22 +00001537 "UIImage",
1538 "UIView",
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001539 };
1540
Ben Hamiltonea7a27b2018-03-27 15:01:21 +00001541 for (auto Line : AnnotatedLines) {
1542 for (const FormatToken *FormatTok = Line->First; FormatTok;
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001543 FormatTok = FormatTok->Next) {
Jacek Olesiakce4f0af2018-02-15 08:47:56 +00001544 if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) &&
Ben Hamiltonb1a79192018-04-12 15:11:53 +00001545 (FormatTok->Tok.getObjCKeywordID() != tok::objc_not_keyword ||
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001546 FormatTok->isOneOf(tok::numeric_constant, tok::l_square,
1547 tok::l_brace))) ||
1548 (FormatTok->Tok.isAnyIdentifier() &&
Krasimir Georgiev8e216782018-01-17 20:01:02 +00001549 std::binary_search(std::begin(FoundationIdentifiers),
1550 std::end(FoundationIdentifiers),
1551 FormatTok->TokenText)) ||
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001552 FormatTok->is(TT_ObjCStringLiteral) ||
1553 FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1554 TT_ObjCBlockLBrace, TT_ObjCBlockLParen,
1555 TT_ObjCDecl, TT_ObjCForIn, TT_ObjCMethodExpr,
1556 TT_ObjCMethodSpecifier, TT_ObjCProperty)) {
1557 return true;
1558 }
Ben Hamiltonea7a27b2018-03-27 15:01:21 +00001559 if (guessIsObjC(Line->Children, Keywords))
Ben Hamilton6432afe2018-03-22 17:37:19 +00001560 return true;
1561 }
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001562 }
1563 return false;
1564 }
1565
1566 bool IsObjC;
1567};
1568
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001569struct IncludeDirective {
1570 StringRef Filename;
1571 StringRef Text;
1572 unsigned Offset;
Daniel Jasperd2629dc2015-12-16 10:10:16 +00001573 int Category;
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001574};
1575
Craig Topperaf35e852013-06-30 22:29:28 +00001576} // end anonymous namespace
1577
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001578// Determines whether 'Ranges' intersects with ('Start', 'End').
1579static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
1580 unsigned End) {
1581 for (auto Range : Ranges) {
1582 if (Range.getOffset() < End &&
1583 Range.getOffset() + Range.getLength() > Start)
1584 return true;
1585 }
1586 return false;
1587}
1588
Eric Liua992afe2016-08-10 09:32:23 +00001589// Returns a pair (Index, OffsetToEOL) describing the position of the cursor
1590// before sorting/deduplicating. Index is the index of the include under the
1591// cursor in the original set of includes. If this include has duplicates, it is
1592// the index of the first of the duplicates as the others are going to be
1593// removed. OffsetToEOL describes the cursor's position relative to the end of
1594// its current line.
1595// If `Cursor` is not on any #include, `Index` will be UINT_MAX.
1596static std::pair<unsigned, unsigned>
1597FindCursorIndex(const SmallVectorImpl<IncludeDirective> &Includes,
1598 const SmallVectorImpl<unsigned> &Indices, unsigned Cursor) {
1599 unsigned CursorIndex = UINT_MAX;
1600 unsigned OffsetToEOL = 0;
1601 for (int i = 0, e = Includes.size(); i != e; ++i) {
1602 unsigned Start = Includes[Indices[i]].Offset;
1603 unsigned End = Start + Includes[Indices[i]].Text.size();
1604 if (!(Cursor >= Start && Cursor < End))
1605 continue;
1606 CursorIndex = Indices[i];
1607 OffsetToEOL = End - Cursor;
1608 // Put the cursor on the only remaining #include among the duplicate
1609 // #includes.
1610 while (--i >= 0 && Includes[CursorIndex].Text == Includes[Indices[i]].Text)
1611 CursorIndex = i;
1612 break;
1613 }
1614 return std::make_pair(CursorIndex, OffsetToEOL);
1615}
1616
1617// Sorts and deduplicate a block of includes given by 'Includes' alphabetically
1618// adding the necessary replacement to 'Replaces'. 'Includes' must be in strict
1619// source order.
1620// #include directives with the same text will be deduplicated, and only the
1621// first #include in the duplicate #includes remains. If the `Cursor` is
1622// provided and put on a deleted #include, it will be moved to the remaining
1623// #include in the duplicate #includes.
Martin Probstc4a0dd42016-05-20 11:24:24 +00001624static void sortCppIncludes(const FormatStyle &Style,
Eric Liua992afe2016-08-10 09:32:23 +00001625 const SmallVectorImpl<IncludeDirective> &Includes,
1626 ArrayRef<tooling::Range> Ranges, StringRef FileName,
1627 tooling::Replacements &Replaces, unsigned *Cursor) {
1628 unsigned IncludesBeginOffset = Includes.front().Offset;
Daniel Jasperd6a00782016-08-30 21:33:41 +00001629 unsigned IncludesEndOffset =
1630 Includes.back().Offset + Includes.back().Text.size();
1631 unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset;
1632 if (!affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset))
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001633 return;
1634 SmallVector<unsigned, 16> Indices;
1635 for (unsigned i = 0, e = Includes.size(); i != e; ++i)
1636 Indices.push_back(i);
Daniel Jasper94a96fc2016-03-03 17:34:14 +00001637 std::stable_sort(
1638 Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) {
1639 return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) <
1640 std::tie(Includes[RHSI].Category, Includes[RHSI].Filename);
1641 });
Eric Liua992afe2016-08-10 09:32:23 +00001642 // The index of the include on which the cursor will be put after
1643 // sorting/deduplicating.
1644 unsigned CursorIndex;
1645 // The offset from cursor to the end of line.
1646 unsigned CursorToEOLOffset;
1647 if (Cursor)
1648 std::tie(CursorIndex, CursorToEOLOffset) =
1649 FindCursorIndex(Includes, Indices, *Cursor);
1650
1651 // Deduplicate #includes.
1652 Indices.erase(std::unique(Indices.begin(), Indices.end(),
1653 [&](unsigned LHSI, unsigned RHSI) {
1654 return Includes[LHSI].Text == Includes[RHSI].Text;
1655 }),
1656 Indices.end());
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001657
Krasimir Georgiev4c2c9c32017-11-27 13:23:45 +00001658 int CurrentCategory = Includes.front().Category;
1659
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001660 // If the #includes are out of order, we generate a single replacement fixing
1661 // the entire block. Otherwise, no replacement is generated.
Eric Liua992afe2016-08-10 09:32:23 +00001662 if (Indices.size() == Includes.size() &&
Krasimir Georgiev4c2c9c32017-11-27 13:23:45 +00001663 std::is_sorted(Indices.begin(), Indices.end()) &&
1664 Style.IncludeBlocks == FormatStyle::IBS_Preserve)
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001665 return;
1666
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001667 std::string result;
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001668 for (unsigned Index : Indices) {
Krasimir Georgiev4c2c9c32017-11-27 13:23:45 +00001669 if (!result.empty()) {
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001670 result += "\n";
Krasimir Georgiev4c2c9c32017-11-27 13:23:45 +00001671 if (Style.IncludeBlocks == FormatStyle::IBS_Regroup &&
1672 CurrentCategory != Includes[Index].Category)
1673 result += "\n";
1674 }
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001675 result += Includes[Index].Text;
Eric Liua992afe2016-08-10 09:32:23 +00001676 if (Cursor && CursorIndex == Index)
1677 *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
Krasimir Georgiev4c2c9c32017-11-27 13:23:45 +00001678 CurrentCategory = Includes[Index].Category;
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001679 }
1680
Eric Liu40ef2fb2016-08-01 10:16:37 +00001681 auto Err = Replaces.add(tooling::Replacement(
Eric Liua992afe2016-08-10 09:32:23 +00001682 FileName, Includes.front().Offset, IncludesBlockSize, result));
Eric Liu40ef2fb2016-08-01 10:16:37 +00001683 // FIXME: better error handling. For now, just skip the replacement for the
1684 // release version.
Piotr Padlewski1ec383c2016-12-23 11:40:44 +00001685 if (Err) {
Eric Liu40ef2fb2016-08-01 10:16:37 +00001686 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Piotr Padlewski1ec383c2016-12-23 11:40:44 +00001687 assert(false);
1688 }
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001689}
1690
Eric Liu659afd52016-05-31 13:34:20 +00001691namespace {
1692
1693// This class manages priorities of #include categories and calculates
1694// priorities for headers.
1695class IncludeCategoryManager {
1696public:
1697 IncludeCategoryManager(const FormatStyle &Style, StringRef FileName)
1698 : Style(Style), FileName(FileName) {
1699 FileStem = llvm::sys::path::stem(FileName);
1700 for (const auto &Category : Style.IncludeCategories)
Chandler Carruthd676ab12017-06-29 23:20:54 +00001701 CategoryRegexs.emplace_back(Category.Regex, llvm::Regex::IgnoreCase);
Eric Liu659afd52016-05-31 13:34:20 +00001702 IsMainFile = FileName.endswith(".c") || FileName.endswith(".cc") ||
1703 FileName.endswith(".cpp") || FileName.endswith(".c++") ||
1704 FileName.endswith(".cxx") || FileName.endswith(".m") ||
1705 FileName.endswith(".mm");
1706 }
1707
1708 // Returns the priority of the category which \p IncludeName belongs to.
1709 // If \p CheckMainHeader is true and \p IncludeName is a main header, returns
1710 // 0. Otherwise, returns the priority of the matching category or INT_MAX.
Eric Liubf4c41c2018-05-04 17:55:13 +00001711 // NOTE: this API is not thread-safe!
1712 int getIncludePriority(StringRef IncludeName, bool CheckMainHeader) const {
Eric Liu659afd52016-05-31 13:34:20 +00001713 int Ret = INT_MAX;
1714 for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i)
1715 if (CategoryRegexs[i].match(IncludeName)) {
1716 Ret = Style.IncludeCategories[i].Priority;
1717 break;
1718 }
1719 if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName))
1720 Ret = 0;
1721 return Ret;
1722 }
1723
1724private:
1725 bool isMainHeader(StringRef IncludeName) const {
1726 if (!IncludeName.startswith("\""))
1727 return false;
1728 StringRef HeaderStem =
1729 llvm::sys::path::stem(IncludeName.drop_front(1).drop_back(1));
Chandler Carruthd676ab12017-06-29 23:20:54 +00001730 if (FileStem.startswith(HeaderStem) ||
1731 FileStem.startswith_lower(HeaderStem)) {
Eric Liu659afd52016-05-31 13:34:20 +00001732 llvm::Regex MainIncludeRegex(
Chandler Carruthd676ab12017-06-29 23:20:54 +00001733 (HeaderStem + Style.IncludeIsMainRegex).str(),
1734 llvm::Regex::IgnoreCase);
Eric Liu659afd52016-05-31 13:34:20 +00001735 if (MainIncludeRegex.match(FileStem))
1736 return true;
1737 }
1738 return false;
1739 }
1740
1741 const FormatStyle &Style;
1742 bool IsMainFile;
1743 StringRef FileName;
1744 StringRef FileStem;
Eric Liubf4c41c2018-05-04 17:55:13 +00001745 // Regex is not thread-safe.
1746 mutable SmallVector<llvm::Regex, 4> CategoryRegexs;
Eric Liu659afd52016-05-31 13:34:20 +00001747};
1748
1749const char IncludeRegexPattern[] =
1750 R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))";
1751
1752} // anonymous namespace
1753
Martin Probstc4a0dd42016-05-20 11:24:24 +00001754tooling::Replacements sortCppIncludes(const FormatStyle &Style, StringRef Code,
1755 ArrayRef<tooling::Range> Ranges,
1756 StringRef FileName,
1757 tooling::Replacements &Replaces,
1758 unsigned *Cursor) {
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001759 unsigned Prev = 0;
1760 unsigned SearchFrom = 0;
Eric Liu659afd52016-05-31 13:34:20 +00001761 llvm::Regex IncludeRegex(IncludeRegexPattern);
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001762 SmallVector<StringRef, 4> Matches;
1763 SmallVector<IncludeDirective, 16> IncludesInBlock;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001764
1765 // In compiled files, consider the first #include to be the main #include of
1766 // the file if it is not a system #include. This ensures that the header
1767 // doesn't have hidden dependencies
1768 // (http://llvm.org/docs/CodingStandards.html#include-style).
1769 //
1770 // FIXME: Do some sanity checking, e.g. edit distance of the base name, to fix
1771 // cases where the first #include is unlikely to be the main header.
Eric Liu659afd52016-05-31 13:34:20 +00001772 IncludeCategoryManager Categories(Style, FileName);
Daniel Jasper32d75fa2015-12-21 13:40:49 +00001773 bool FirstIncludeBlock = true;
Daniel Jaspera252f5d2015-12-21 17:28:24 +00001774 bool MainIncludeFound = false;
Daniel Jasper9b8c7c72015-11-21 09:17:08 +00001775 bool FormattingOff = false;
1776
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001777 for (;;) {
1778 auto Pos = Code.find('\n', SearchFrom);
1779 StringRef Line =
1780 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
Daniel Jasper9b8c7c72015-11-21 09:17:08 +00001781
1782 StringRef Trimmed = Line.trim();
1783 if (Trimmed == "// clang-format off")
1784 FormattingOff = true;
1785 else if (Trimmed == "// clang-format on")
1786 FormattingOff = false;
1787
Krasimir Georgiev4c2c9c32017-11-27 13:23:45 +00001788 const bool EmptyLineSkipped =
1789 Trimmed.empty() && (Style.IncludeBlocks == FormatStyle::IBS_Merge ||
1790 Style.IncludeBlocks == FormatStyle::IBS_Regroup);
1791
Daniel Jasper9b8c7c72015-11-21 09:17:08 +00001792 if (!FormattingOff && !Line.endswith("\\")) {
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001793 if (IncludeRegex.match(Line, &Matches)) {
Nico Weberff063702015-10-21 17:13:45 +00001794 StringRef IncludeName = Matches[2];
Eric Liu659afd52016-05-31 13:34:20 +00001795 int Category = Categories.getIncludePriority(
1796 IncludeName,
1797 /*CheckMainHeader=*/!MainIncludeFound && FirstIncludeBlock);
1798 if (Category == 0)
1799 MainIncludeFound = true;
Nico Weberff063702015-10-21 17:13:45 +00001800 IncludesInBlock.push_back({IncludeName, Line, Prev, Category});
Krasimir Georgiev4c2c9c32017-11-27 13:23:45 +00001801 } else if (!IncludesInBlock.empty() && !EmptyLineSkipped) {
Martin Probstc4a0dd42016-05-20 11:24:24 +00001802 sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces,
1803 Cursor);
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001804 IncludesInBlock.clear();
Daniel Jasper32d75fa2015-12-21 13:40:49 +00001805 FirstIncludeBlock = false;
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001806 }
1807 Prev = Pos + 1;
1808 }
1809 if (Pos == StringRef::npos || Pos + 1 == Code.size())
1810 break;
1811 SearchFrom = Pos + 1;
1812 }
1813 if (!IncludesInBlock.empty())
Martin Probstc4a0dd42016-05-20 11:24:24 +00001814 sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces, Cursor);
1815 return Replaces;
1816}
1817
Martin Probstfa37b182017-01-27 09:09:11 +00001818bool isMpegTS(StringRef Code) {
1819 // MPEG transport streams use the ".ts" file extension. clang-format should
1820 // not attempt to format those. MPEG TS' frame format starts with 0x47 every
1821 // 189 bytes - detect that and return.
1822 return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
1823}
1824
Manuel Klimek89628f62017-09-20 09:51:03 +00001825bool isLikelyXml(StringRef Code) { return Code.ltrim().startswith("<"); }
Krasimir Georgieva2e7d0d2017-08-29 13:51:38 +00001826
Martin Probstc4a0dd42016-05-20 11:24:24 +00001827tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
1828 ArrayRef<tooling::Range> Ranges,
1829 StringRef FileName, unsigned *Cursor) {
1830 tooling::Replacements Replaces;
1831 if (!Style.SortIncludes)
1832 return Replaces;
Krasimir Georgiev86873032017-08-29 13:57:31 +00001833 if (isLikelyXml(Code))
1834 return Replaces;
1835 if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
1836 isMpegTS(Code))
Martin Probstfa37b182017-01-27 09:09:11 +00001837 return Replaces;
Martin Probstc4a0dd42016-05-20 11:24:24 +00001838 if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript)
1839 return sortJavaScriptImports(Style, Code, Ranges, FileName);
1840 sortCppIncludes(Style, Code, Ranges, FileName, Replaces, Cursor);
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001841 return Replaces;
1842}
1843
Eric Liu4cfb88a2016-04-25 15:09:22 +00001844template <typename T>
Eric Liu4f8d9942016-07-11 13:53:12 +00001845static llvm::Expected<tooling::Replacements>
Eric Liu4cfb88a2016-04-25 15:09:22 +00001846processReplacements(T ProcessFunc, StringRef Code,
1847 const tooling::Replacements &Replaces,
1848 const FormatStyle &Style) {
Manuel Klimekb12e5a52016-03-01 12:37:30 +00001849 if (Replaces.empty())
1850 return tooling::Replacements();
1851
Eric Liu4f8d9942016-07-11 13:53:12 +00001852 auto NewCode = applyAllReplacements(Code, Replaces);
1853 if (!NewCode)
1854 return NewCode.takeError();
Eric Liu40ef2fb2016-08-01 10:16:37 +00001855 std::vector<tooling::Range> ChangedRanges = Replaces.getAffectedRanges();
Manuel Klimekb12e5a52016-03-01 12:37:30 +00001856 StringRef FileName = Replaces.begin()->getFilePath();
Eric Liu4cfb88a2016-04-25 15:09:22 +00001857
Manuel Klimekb12e5a52016-03-01 12:37:30 +00001858 tooling::Replacements FormatReplaces =
Eric Liu4f8d9942016-07-11 13:53:12 +00001859 ProcessFunc(Style, *NewCode, ChangedRanges, FileName);
Manuel Klimekb12e5a52016-03-01 12:37:30 +00001860
Eric Liu40ef2fb2016-08-01 10:16:37 +00001861 return Replaces.merge(FormatReplaces);
Manuel Klimekb12e5a52016-03-01 12:37:30 +00001862}
1863
Eric Liu4f8d9942016-07-11 13:53:12 +00001864llvm::Expected<tooling::Replacements>
1865formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
1866 const FormatStyle &Style) {
Eric Liu4cfb88a2016-04-25 15:09:22 +00001867 // We need to use lambda function here since there are two versions of
Eric Liubaf58c22016-05-18 13:43:48 +00001868 // `sortIncludes`.
1869 auto SortIncludes = [](const FormatStyle &Style, StringRef Code,
1870 std::vector<tooling::Range> Ranges,
1871 StringRef FileName) -> tooling::Replacements {
1872 return sortIncludes(Style, Code, Ranges, FileName);
1873 };
Eric Liu4f8d9942016-07-11 13:53:12 +00001874 auto SortedReplaces =
Eric Liubaf58c22016-05-18 13:43:48 +00001875 processReplacements(SortIncludes, Code, Replaces, Style);
Eric Liu4f8d9942016-07-11 13:53:12 +00001876 if (!SortedReplaces)
1877 return SortedReplaces.takeError();
Eric Liubaf58c22016-05-18 13:43:48 +00001878
1879 // We need to use lambda function here since there are two versions of
Eric Liu4cfb88a2016-04-25 15:09:22 +00001880 // `reformat`.
1881 auto Reformat = [](const FormatStyle &Style, StringRef Code,
1882 std::vector<tooling::Range> Ranges,
1883 StringRef FileName) -> tooling::Replacements {
1884 return reformat(Style, Code, Ranges, FileName);
1885 };
Eric Liu4f8d9942016-07-11 13:53:12 +00001886 return processReplacements(Reformat, Code, *SortedReplaces, Style);
Eric Liu4cfb88a2016-04-25 15:09:22 +00001887}
1888
Eric Liu659afd52016-05-31 13:34:20 +00001889namespace {
1890
1891inline bool isHeaderInsertion(const tooling::Replacement &Replace) {
Eric Liuc0d3a802016-09-23 15:10:56 +00001892 return Replace.getOffset() == UINT_MAX && Replace.getLength() == 0 &&
Eric Liu659afd52016-05-31 13:34:20 +00001893 llvm::Regex(IncludeRegexPattern).match(Replace.getReplacementText());
1894}
1895
Eric Liuc0d3a802016-09-23 15:10:56 +00001896inline bool isHeaderDeletion(const tooling::Replacement &Replace) {
1897 return Replace.getOffset() == UINT_MAX && Replace.getLength() == 1;
1898}
1899
Eric Liu964782a2016-12-02 11:01:43 +00001900// Returns the offset after skipping a sequence of tokens, matched by \p
1901// GetOffsetAfterSequence, from the start of the code.
1902// \p GetOffsetAfterSequence should be a function that matches a sequence of
1903// tokens and returns an offset after the sequence.
1904unsigned getOffsetAfterTokenSequence(
1905 StringRef FileName, StringRef Code, const FormatStyle &Style,
Krasimir Georgiev317c5392017-03-08 09:13:25 +00001906 llvm::function_ref<unsigned(const SourceManager &, Lexer &, Token &)>
1907 GetOffsetAfterSequence) {
Eric Liu964782a2016-12-02 11:01:43 +00001908 std::unique_ptr<Environment> Env =
1909 Environment::CreateVirtualEnvironment(Code, FileName, /*Ranges=*/{});
1910 const SourceManager &SourceMgr = Env->getSourceManager();
1911 Lexer Lex(Env->getFileID(), SourceMgr.getBuffer(Env->getFileID()), SourceMgr,
1912 getFormattingLangOpts(Style));
1913 Token Tok;
1914 // Get the first token.
1915 Lex.LexFromRawLexer(Tok);
Krasimir Georgiev317c5392017-03-08 09:13:25 +00001916 return GetOffsetAfterSequence(SourceMgr, Lex, Tok);
Eric Liu35288322016-06-06 11:00:13 +00001917}
1918
1919// Check if a sequence of tokens is like "#<Name> <raw_identifier>". If it is,
1920// \p Tok will be the token after this directive; otherwise, it can be any token
1921// after the given \p Tok (including \p Tok).
1922bool checkAndConsumeDirectiveWithName(Lexer &Lex, StringRef Name, Token &Tok) {
1923 bool Matched = Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) &&
1924 Tok.is(tok::raw_identifier) &&
1925 Tok.getRawIdentifier() == Name && !Lex.LexFromRawLexer(Tok) &&
Eric Liu93459d32016-12-19 10:41:05 +00001926 Tok.is(tok::raw_identifier);
Eric Liu35288322016-06-06 11:00:13 +00001927 if (Matched)
1928 Lex.LexFromRawLexer(Tok);
1929 return Matched;
1930}
1931
Eric Liu964782a2016-12-02 11:01:43 +00001932void skipComments(Lexer &Lex, Token &Tok) {
1933 while (Tok.is(tok::comment))
1934 if (Lex.LexFromRawLexer(Tok))
1935 return;
1936}
1937
1938// Returns the offset after header guard directives and any comments
1939// before/after header guards. If no header guard presents in the code, this
1940// will returns the offset after skipping all comments from the start of the
1941// code.
Eric Liu35288322016-06-06 11:00:13 +00001942unsigned getOffsetAfterHeaderGuardsAndComments(StringRef FileName,
1943 StringRef Code,
Eric Liu43d67b62016-06-11 11:45:08 +00001944 const FormatStyle &Style) {
Eric Liu964782a2016-12-02 11:01:43 +00001945 return getOffsetAfterTokenSequence(
1946 FileName, Code, Style,
1947 [](const SourceManager &SM, Lexer &Lex, Token Tok) {
1948 skipComments(Lex, Tok);
1949 unsigned InitialOffset = SM.getFileOffset(Tok.getLocation());
1950 if (checkAndConsumeDirectiveWithName(Lex, "ifndef", Tok)) {
1951 skipComments(Lex, Tok);
1952 if (checkAndConsumeDirectiveWithName(Lex, "define", Tok))
1953 return SM.getFileOffset(Tok.getLocation());
1954 }
1955 return InitialOffset;
1956 });
1957}
1958
1959// Check if a sequence of tokens is like
1960// "#include ("header.h" | <header.h>)".
1961// If it is, \p Tok will be the token after this directive; otherwise, it can be
1962// any token after the given \p Tok (including \p Tok).
1963bool checkAndConsumeInclusiveDirective(Lexer &Lex, Token &Tok) {
1964 auto Matched = [&]() {
1965 Lex.LexFromRawLexer(Tok);
1966 return true;
1967 };
1968 if (Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) &&
1969 Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "include") {
1970 if (Lex.LexFromRawLexer(Tok))
1971 return false;
1972 if (Tok.is(tok::string_literal))
1973 return Matched();
1974 if (Tok.is(tok::less)) {
1975 while (!Lex.LexFromRawLexer(Tok) && Tok.isNot(tok::greater)) {
1976 }
1977 if (Tok.is(tok::greater))
1978 return Matched();
1979 }
Eric Liu35288322016-06-06 11:00:13 +00001980 }
Eric Liu964782a2016-12-02 11:01:43 +00001981 return false;
1982}
1983
1984// Returns the offset of the last #include directive after which a new
1985// #include can be inserted. This ignores #include's after the #include block(s)
1986// in the beginning of a file to avoid inserting headers into code sections
1987// where new #include's should not be added by default.
1988// These code sections include:
1989// - raw string literals (containing #include).
1990// - #if blocks.
1991// - Special #include's among declarations (e.g. functions).
1992//
1993// If no #include after which a new #include can be inserted, this returns the
1994// offset after skipping all comments from the start of the code.
1995// Inserting after an #include is not allowed if it comes after code that is not
1996// #include (e.g. pre-processing directive that is not #include, declarations).
1997unsigned getMaxHeaderInsertionOffset(StringRef FileName, StringRef Code,
1998 const FormatStyle &Style) {
1999 return getOffsetAfterTokenSequence(
2000 FileName, Code, Style,
2001 [](const SourceManager &SM, Lexer &Lex, Token Tok) {
2002 skipComments(Lex, Tok);
2003 unsigned MaxOffset = SM.getFileOffset(Tok.getLocation());
2004 while (checkAndConsumeInclusiveDirective(Lex, Tok))
2005 MaxOffset = SM.getFileOffset(Tok.getLocation());
2006 return MaxOffset;
2007 });
Eric Liu35288322016-06-06 11:00:13 +00002008}
2009
Eric Liubf4c41c2018-05-04 17:55:13 +00002010/// Generates replacements for inserting or deleting #include directives in a
2011/// file.
2012class HeaderIncludes {
2013public:
2014 HeaderIncludes(llvm::StringRef FileName, llvm::StringRef Code,
2015 const FormatStyle &Style);
2016
2017 /// Inserts an #include directive of \p Header into the code. If \p IsAngled
2018 /// is true, \p Header will be quoted with <> in the directive; otherwise, it
2019 /// will be quoted with "".
2020 ///
2021 /// When searching for points to insert new header, this ignores #include's
2022 /// after the #include block(s) in the beginning of a file to avoid inserting
2023 /// headers into code sections where new #include's should not be added by
2024 /// default. These code sections include:
2025 /// - raw string literals (containing #include).
2026 /// - #if blocks.
2027 /// - Special #include's among declarations (e.g. functions).
2028 ///
2029 /// Returns a replacement that inserts the new header into a suitable #include
2030 /// block of the same category. This respects the order of the existing
2031 /// #includes in the block; if the existing #includes are not already sorted,
2032 /// this will simply insert the #include in front of the first #include of the
2033 /// same category in the code that should be sorted after \p IncludeName. If
2034 /// \p IncludeName already exists (with exactly the same spelling), this
2035 /// returns None.
2036 llvm::Optional<tooling::Replacement> insert(llvm::StringRef Header,
2037 bool IsAngled) const;
2038
2039 /// Removes all existing #includes of \p Header quoted with <> if \p IsAngled
2040 /// is true or "" if \p IsAngled is false.
2041 /// This doesn't resolve the header file path; it only deletes #includes with
2042 /// exactly the same spelling.
2043 tooling::Replacements remove(llvm::StringRef Header, bool IsAngled) const;
2044
2045private:
2046 struct Include {
2047 Include(StringRef Name, tooling::Range R) : Name(Name), R(R) {}
2048
2049 // An include header quoted with either <> or "".
2050 std::string Name;
2051 // The range of the whole line of include directive including any eading
2052 // whitespaces and trailing comment.
2053 tooling::Range R;
2054 };
2055
2056 void addExistingInclude(Include IncludeToAdd, unsigned NextLineOffset);
2057
2058 std::string FileName;
2059 std::string Code;
2060
2061 // Map from include name (quotation trimmed) to a list of existing includes
2062 // (in case there are more than one) with the name in the current file. <x>
2063 // and "x" will be treated as the same header when deleting #includes.
2064 llvm::StringMap<llvm::SmallVector<Include, 1>> ExistingIncludes;
2065
2066 /// Map from priorities of #include categories to all #includes in the same
2067 /// category. This is used to find #includes of the same category when
2068 /// inserting new #includes. #includes in the same categories are sorted in
2069 /// in the order they appear in the source file.
2070 /// See comment for "FormatStyle::IncludeCategories" for details about include
2071 /// priorities.
2072 std::unordered_map<int, llvm::SmallVector<const Include *, 8>>
2073 IncludesByPriority;
2074
2075 int FirstIncludeOffset;
2076 // All new headers should be inserted after this offset (e.g. after header
2077 // guards, file comment).
2078 unsigned MinInsertOffset;
2079 // Max insertion offset in the original code. For example, we want to avoid
2080 // inserting new #includes into the actual code section (e.g. after a
2081 // declaration).
2082 unsigned MaxInsertOffset;
2083 IncludeCategoryManager Categories;
2084 // Record the offset of the end of the last include in each category.
2085 std::unordered_map<int, int> CategoryEndOffsets;
2086
2087 // All possible priorities.
2088 std::set<int> Priorities;
2089
2090 // Matches a whole #include directive.
2091 llvm::Regex IncludeRegex;
2092};
2093
2094HeaderIncludes::HeaderIncludes(StringRef FileName, StringRef Code,
2095 const FormatStyle &Style)
2096 : FileName(FileName), Code(Code), FirstIncludeOffset(-1),
2097 MinInsertOffset(
2098 getOffsetAfterHeaderGuardsAndComments(FileName, Code, Style)),
2099 MaxInsertOffset(MinInsertOffset +
2100 getMaxHeaderInsertionOffset(
2101 FileName, Code.drop_front(MinInsertOffset), Style)),
2102 Categories(Style, FileName),
2103 IncludeRegex(llvm::Regex(IncludeRegexPattern)) {
2104 // Add 0 for main header and INT_MAX for headers that are not in any
2105 // category.
2106 Priorities = {0, INT_MAX};
2107 for (const auto &Category : Style.IncludeCategories)
2108 Priorities.insert(Category.Priority);
2109 SmallVector<StringRef, 32> Lines;
2110 Code.drop_front(MinInsertOffset).split(Lines, "\n");
2111
2112 unsigned Offset = MinInsertOffset;
2113 unsigned NextLineOffset;
2114 SmallVector<StringRef, 4> Matches;
2115 for (auto Line : Lines) {
2116 NextLineOffset = std::min(Code.size(), Offset + Line.size() + 1);
2117 if (IncludeRegex.match(Line, &Matches)) {
2118 // If this is the last line without trailing newline, we need to make
2119 // sure we don't delete across the file boundary.
2120 addExistingInclude(
2121 Include(Matches[2],
2122 tooling::Range(
2123 Offset, std::min(Line.size() + 1, Code.size() - Offset))),
2124 NextLineOffset);
2125 }
2126 Offset = NextLineOffset;
2127 }
2128
2129 // Populate CategoryEndOfssets:
2130 // - Ensure that CategoryEndOffset[Highest] is always populated.
2131 // - If CategoryEndOffset[Priority] isn't set, use the next higher value
2132 // that is set, up to CategoryEndOffset[Highest].
2133 auto Highest = Priorities.begin();
2134 if (CategoryEndOffsets.find(*Highest) == CategoryEndOffsets.end()) {
2135 if (FirstIncludeOffset >= 0)
2136 CategoryEndOffsets[*Highest] = FirstIncludeOffset;
2137 else
2138 CategoryEndOffsets[*Highest] = MinInsertOffset;
2139 }
2140 // By this point, CategoryEndOffset[Highest] is always set appropriately:
2141 // - to an appropriate location before/after existing #includes, or
2142 // - to right after the header guard, or
2143 // - to the beginning of the file.
2144 for (auto I = ++Priorities.begin(), E = Priorities.end(); I != E; ++I)
2145 if (CategoryEndOffsets.find(*I) == CategoryEndOffsets.end())
2146 CategoryEndOffsets[*I] = CategoryEndOffsets[*std::prev(I)];
2147}
2148
2149inline StringRef trimInclude(StringRef IncludeName) {
2150 return IncludeName.trim("\"<>");
2151}
2152
2153// \p Offset: the start of the line following this include directive.
2154void HeaderIncludes::addExistingInclude(Include IncludeToAdd,
2155 unsigned NextLineOffset) {
2156 auto Iter =
2157 ExistingIncludes.try_emplace(trimInclude(IncludeToAdd.Name)).first;
2158 Iter->second.push_back(std::move(IncludeToAdd));
2159 auto &CurInclude = Iter->second.back();
2160 // The header name with quotes or angle brackets.
2161 // Only record the offset of current #include if we can insert after it.
2162 if (CurInclude.R.getOffset() <= MaxInsertOffset) {
2163 int Priority = Categories.getIncludePriority(
2164 CurInclude.Name, /*CheckMainHeader=*/FirstIncludeOffset < 0);
2165 CategoryEndOffsets[Priority] = NextLineOffset;
2166 IncludesByPriority[Priority].push_back(&CurInclude);
2167 if (FirstIncludeOffset < 0)
2168 FirstIncludeOffset = CurInclude.R.getOffset();
2169 }
2170}
2171
2172llvm::Optional<tooling::Replacement>
2173HeaderIncludes::insert(llvm::StringRef IncludeName, bool IsAngled) const {
2174 assert(IncludeName == trimInclude(IncludeName));
2175 // If a <header> ("header") already exists in code, "header" (<header>) with
2176 // different quotation will still be inserted.
2177 // FIXME: figure out if this is the best behavior.
2178 auto It = ExistingIncludes.find(IncludeName);
2179 if (It != ExistingIncludes.end())
2180 for (const auto &Inc : It->second)
2181 if ((IsAngled && StringRef(Inc.Name).startswith("<")) ||
2182 (!IsAngled && StringRef(Inc.Name).startswith("\"")))
2183 return llvm::None;
2184 std::string Quoted = IsAngled ? ("<" + IncludeName + ">").str()
2185 : ("\"" + IncludeName + "\"").str();
2186 StringRef QuotedName = Quoted;
2187 int Priority = Categories.getIncludePriority(
2188 QuotedName, /*CheckMainHeader=*/FirstIncludeOffset < 0);
2189 auto CatOffset = CategoryEndOffsets.find(Priority);
2190 assert(CatOffset != CategoryEndOffsets.end());
2191 unsigned InsertOffset = CatOffset->second; // Fall back offset
2192 auto Iter = IncludesByPriority.find(Priority);
2193 if (Iter != IncludesByPriority.end()) {
2194 for (const auto *Inc : Iter->second) {
2195 if (QuotedName < Inc->Name) {
2196 InsertOffset = Inc->R.getOffset();
2197 break;
2198 }
2199 }
2200 }
2201 assert(InsertOffset <= Code.size());
2202 std::string NewInclude = ("#include " + QuotedName + "\n").str();
2203 // When inserting headers at end of the code, also append '\n' to the code
2204 // if it does not end with '\n'.
2205 // FIXME: when inserting multiple #includes at the end of code, only one
2206 // newline should be added.
2207 if (InsertOffset == Code.size() && (!Code.empty() && Code.back() != '\n'))
2208 NewInclude = "\n" + NewInclude;
2209 return tooling::Replacement(FileName, InsertOffset, 0, NewInclude);
2210}
2211
2212tooling::Replacements HeaderIncludes::remove(llvm::StringRef IncludeName,
2213 bool IsAngled) const {
2214 assert(IncludeName == trimInclude(IncludeName));
2215 tooling::Replacements Result;
2216 auto Iter = ExistingIncludes.find(IncludeName);
2217 if (Iter == ExistingIncludes.end())
2218 return Result;
2219 for (const auto &Inc : Iter->second) {
2220 if ((IsAngled && StringRef(Inc.Name).startswith("\"")) ||
2221 (!IsAngled && StringRef(Inc.Name).startswith("<")))
2222 continue;
2223 llvm::Error Err = Result.add(tooling::Replacement(
2224 FileName, Inc.R.getOffset(), Inc.R.getLength(), ""));
2225 if (Err) {
2226 auto ErrMsg = "Unexpected conflicts in #include deletions: " +
2227 llvm::toString(std::move(Err));
2228 llvm_unreachable(ErrMsg.c_str());
2229 }
2230 }
2231 return Result;
Eric Liuc0d3a802016-09-23 15:10:56 +00002232}
2233
Eric Liu659afd52016-05-31 13:34:20 +00002234// FIXME: insert empty lines between newly created blocks.
2235tooling::Replacements
2236fixCppIncludeInsertions(StringRef Code, const tooling::Replacements &Replaces,
2237 const FormatStyle &Style) {
Daniel Jasper1dbc2102017-03-31 13:30:24 +00002238 if (!Style.isCpp())
Eric Liu659afd52016-05-31 13:34:20 +00002239 return Replaces;
2240
2241 tooling::Replacements HeaderInsertions;
Eric Liuc0d3a802016-09-23 15:10:56 +00002242 std::set<llvm::StringRef> HeadersToDelete;
Eric Liu40ef2fb2016-08-01 10:16:37 +00002243 tooling::Replacements Result;
Eric Liu659afd52016-05-31 13:34:20 +00002244 for (const auto &R : Replaces) {
Eric Liu40ef2fb2016-08-01 10:16:37 +00002245 if (isHeaderInsertion(R)) {
2246 // Replacements from \p Replaces must be conflict-free already, so we can
2247 // simply consume the error.
2248 llvm::consumeError(HeaderInsertions.add(R));
Eric Liuc0d3a802016-09-23 15:10:56 +00002249 } else if (isHeaderDeletion(R)) {
2250 HeadersToDelete.insert(R.getReplacementText());
Eric Liu40ef2fb2016-08-01 10:16:37 +00002251 } else if (R.getOffset() == UINT_MAX) {
Eric Liu659afd52016-05-31 13:34:20 +00002252 llvm::errs() << "Insertions other than header #include insertion are "
2253 "not supported! "
2254 << R.getReplacementText() << "\n";
Eric Liu40ef2fb2016-08-01 10:16:37 +00002255 } else {
2256 llvm::consumeError(Result.add(R));
2257 }
Eric Liu659afd52016-05-31 13:34:20 +00002258 }
Eric Liuc0d3a802016-09-23 15:10:56 +00002259 if (HeaderInsertions.empty() && HeadersToDelete.empty())
Eric Liu659afd52016-05-31 13:34:20 +00002260 return Replaces;
Eric Liu659afd52016-05-31 13:34:20 +00002261
Eric Liu659afd52016-05-31 13:34:20 +00002262
2263 StringRef FileName = Replaces.begin()->getFilePath();
Eric Liubf4c41c2018-05-04 17:55:13 +00002264 HeaderIncludes Includes(FileName, Code, Style);
Eric Liu659afd52016-05-31 13:34:20 +00002265
Eric Liubf4c41c2018-05-04 17:55:13 +00002266 for (const auto &Header : HeadersToDelete) {
2267 tooling::Replacements Replaces =
2268 Includes.remove(trimInclude(Header), Header.startswith("<"));
2269 for (const auto &R : Replaces) {
2270 auto Err = Result.add(R);
2271 if (Err) {
2272 // Ignore the deletion on conflict.
2273 llvm::errs() << "Failed to add header deletion replacement for "
2274 << Header << ": " << llvm::toString(std::move(Err))
2275 << "\n";
Eric Liuc0d3a802016-09-23 15:10:56 +00002276 }
Eric Liu659afd52016-05-31 13:34:20 +00002277 }
Eric Liu659afd52016-05-31 13:34:20 +00002278 }
2279
Eric Liubf4c41c2018-05-04 17:55:13 +00002280 llvm::Regex IncludeRegex = llvm::Regex(IncludeRegexPattern);
2281 llvm::SmallVector<StringRef, 4> Matches;
Eric Liu659afd52016-05-31 13:34:20 +00002282 for (const auto &R : HeaderInsertions) {
2283 auto IncludeDirective = R.getReplacementText();
2284 bool Matched = IncludeRegex.match(IncludeDirective, &Matches);
2285 assert(Matched && "Header insertion replacement must have replacement text "
2286 "'#include ...'");
Benjamin Kramer1cb7ee12016-05-31 14:14:42 +00002287 (void)Matched;
Eric Liu659afd52016-05-31 13:34:20 +00002288 auto IncludeName = Matches[2];
Eric Liubf4c41c2018-05-04 17:55:13 +00002289 auto Replace =
2290 Includes.insert(trimInclude(IncludeName), IncludeName.startswith("<"));
2291 if (Replace) {
2292 auto Err = Result.add(*Replace);
2293 if (Err) {
2294 llvm::consumeError(std::move(Err));
2295 unsigned NewOffset = Result.getShiftedCodePosition(Replace->getOffset());
2296 auto Shifted = tooling::Replacement(FileName, NewOffset, 0,
2297 Replace->getReplacementText());
2298 Result = Result.merge(tooling::Replacements(Shifted));
2299 }
Eric Liu40ef2fb2016-08-01 10:16:37 +00002300 }
Eric Liu659afd52016-05-31 13:34:20 +00002301 }
2302 return Result;
2303}
2304
2305} // anonymous namespace
2306
Eric Liu4f8d9942016-07-11 13:53:12 +00002307llvm::Expected<tooling::Replacements>
Eric Liu4cfb88a2016-04-25 15:09:22 +00002308cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
2309 const FormatStyle &Style) {
2310 // We need to use lambda function here since there are two versions of
2311 // `cleanup`.
2312 auto Cleanup = [](const FormatStyle &Style, StringRef Code,
2313 std::vector<tooling::Range> Ranges,
2314 StringRef FileName) -> tooling::Replacements {
2315 return cleanup(Style, Code, Ranges, FileName);
2316 };
Eric Liu659afd52016-05-31 13:34:20 +00002317 // Make header insertion replacements insert new headers into correct blocks.
2318 tooling::Replacements NewReplaces =
2319 fixCppIncludeInsertions(Code, Replaces, Style);
2320 return processReplacements(Cleanup, Code, NewReplaces, Style);
Eric Liu4cfb88a2016-04-25 15:09:22 +00002321}
2322
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002323namespace internal {
2324std::pair<tooling::Replacements, unsigned>
2325reformat(const FormatStyle &Style, StringRef Code,
2326 ArrayRef<tooling::Range> Ranges, unsigned FirstStartColumn,
2327 unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName,
2328 FormattingAttemptStatus *Status) {
Eric Liu4cfb88a2016-04-25 15:09:22 +00002329 FormatStyle Expanded = expandPresets(Style);
2330 if (Expanded.DisableFormat)
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002331 return {tooling::Replacements(), 0};
Krasimir Georgiev86873032017-08-29 13:57:31 +00002332 if (isLikelyXml(Code))
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002333 return {tooling::Replacements(), 0};
Krasimir Georgiev86873032017-08-29 13:57:31 +00002334 if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code))
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002335 return {tooling::Replacements(), 0};
Daniel Jasper496c1992016-09-07 22:48:53 +00002336
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002337 typedef std::function<std::pair<tooling::Replacements, unsigned>(
2338 const Environment &)>
Krasimir Georgievac16a202017-06-23 11:46:03 +00002339 AnalyzerPass;
2340 SmallVector<AnalyzerPass, 4> Passes;
Krasimir Georgiev32eaa862017-03-01 15:35:39 +00002341
Krasimir Georgievac16a202017-06-23 11:46:03 +00002342 if (Style.Language == FormatStyle::LK_Cpp) {
2343 if (Style.FixNamespaceComments)
2344 Passes.emplace_back([&](const Environment &Env) {
2345 return NamespaceEndCommentsFixer(Env, Expanded).process();
2346 });
2347
2348 if (Style.SortUsingDeclarations)
2349 Passes.emplace_back([&](const Environment &Env) {
2350 return UsingDeclarationsSorter(Env, Expanded).process();
2351 });
Krasimir Georgiev32eaa862017-03-01 15:35:39 +00002352 }
2353
2354 if (Style.Language == FormatStyle::LK_JavaScript &&
Krasimir Georgievac16a202017-06-23 11:46:03 +00002355 Style.JavaScriptQuotes != FormatStyle::JSQS_Leave)
2356 Passes.emplace_back([&](const Environment &Env) {
2357 return JavaScriptRequoter(Env, Expanded).process();
2358 });
2359
2360 Passes.emplace_back([&](const Environment &Env) {
2361 return Formatter(Env, Expanded, Status).process();
2362 });
2363
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002364 std::unique_ptr<Environment> Env = Environment::CreateVirtualEnvironment(
2365 Code, FileName, Ranges, FirstStartColumn, NextStartColumn,
2366 LastStartColumn);
Krasimir Georgievac16a202017-06-23 11:46:03 +00002367 llvm::Optional<std::string> CurrentCode = None;
2368 tooling::Replacements Fixes;
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002369 unsigned Penalty = 0;
Krasimir Georgievac16a202017-06-23 11:46:03 +00002370 for (size_t I = 0, E = Passes.size(); I < E; ++I) {
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002371 std::pair<tooling::Replacements, unsigned> PassFixes = Passes[I](*Env);
Krasimir Georgievac16a202017-06-23 11:46:03 +00002372 auto NewCode = applyAllReplacements(
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002373 CurrentCode ? StringRef(*CurrentCode) : Code, PassFixes.first);
Krasimir Georgievac16a202017-06-23 11:46:03 +00002374 if (NewCode) {
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002375 Fixes = Fixes.merge(PassFixes.first);
2376 Penalty += PassFixes.second;
Krasimir Georgievac16a202017-06-23 11:46:03 +00002377 if (I + 1 < E) {
2378 CurrentCode = std::move(*NewCode);
2379 Env = Environment::CreateVirtualEnvironment(
2380 *CurrentCode, FileName,
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002381 tooling::calculateRangesAfterReplacements(Fixes, Ranges),
2382 FirstStartColumn, NextStartColumn, LastStartColumn);
Krasimir Georgievac16a202017-06-23 11:46:03 +00002383 }
2384 }
Daniel Jasper496c1992016-09-07 22:48:53 +00002385 }
2386
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002387 return {Fixes, Penalty};
2388}
2389} // namespace internal
2390
2391tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
2392 ArrayRef<tooling::Range> Ranges,
2393 StringRef FileName,
2394 FormattingAttemptStatus *Status) {
2395 return internal::reformat(Style, Code, Ranges,
2396 /*FirstStartColumn=*/0,
2397 /*NextStartColumn=*/0,
2398 /*LastStartColumn=*/0, FileName, Status)
2399 .first;
Eric Liu4cfb88a2016-04-25 15:09:22 +00002400}
2401
Eric Liu4cfb88a2016-04-25 15:09:22 +00002402tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
2403 ArrayRef<tooling::Range> Ranges,
2404 StringRef FileName) {
Martin Probst816a9662017-05-29 08:41:11 +00002405 // cleanups only apply to C++ (they mostly concern ctor commas etc.)
2406 if (Style.Language != FormatStyle::LK_Cpp)
2407 return tooling::Replacements();
Eric Liu4cfb88a2016-04-25 15:09:22 +00002408 std::unique_ptr<Environment> Env =
Eric Liu635423e2016-04-28 07:52:03 +00002409 Environment::CreateVirtualEnvironment(Code, FileName, Ranges);
2410 Cleaner Clean(*Env, Style);
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002411 return Clean.process().first;
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002412}
2413
Krasimir Georgievbcda54b2017-04-21 14:35:20 +00002414tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
2415 ArrayRef<tooling::Range> Ranges,
2416 StringRef FileName, bool *IncompleteFormat) {
2417 FormattingAttemptStatus Status;
2418 auto Result = reformat(Style, Code, Ranges, FileName, &Status);
2419 if (!Status.FormatComplete)
2420 *IncompleteFormat = true;
2421 return Result;
2422}
2423
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +00002424tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
2425 StringRef Code,
2426 ArrayRef<tooling::Range> Ranges,
2427 StringRef FileName) {
2428 std::unique_ptr<Environment> Env =
2429 Environment::CreateVirtualEnvironment(Code, FileName, Ranges);
2430 NamespaceEndCommentsFixer Fix(*Env, Style);
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002431 return Fix.process().first;
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +00002432}
2433
Krasimir Georgievb03877a2017-06-21 12:03:12 +00002434tooling::Replacements sortUsingDeclarations(const FormatStyle &Style,
2435 StringRef Code,
2436 ArrayRef<tooling::Range> Ranges,
2437 StringRef FileName) {
2438 std::unique_ptr<Environment> Env =
2439 Environment::CreateVirtualEnvironment(Code, FileName, Ranges);
2440 UsingDeclarationsSorter Sorter(*Env, Style);
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002441 return Sorter.process().first;
Krasimir Georgievb03877a2017-06-21 12:03:12 +00002442}
2443
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002444LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002445 LangOptions LangOpts;
2446 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002447 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2448 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002449 LangOpts.CPlusPlus17 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Richard Smithc70f1d62017-12-14 15:16:18 +00002450 LangOpts.CPlusPlus2a = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00002451 LangOpts.LineComment = 1;
Daniel Jasper1dbc2102017-03-31 13:30:24 +00002452 bool AlternativeOperators = Style.isCpp();
Daniel Jasper30a24062014-11-14 09:02:28 +00002453 LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002454 LangOpts.Bool = 1;
2455 LangOpts.ObjC1 = 1;
2456 LangOpts.ObjC2 = 1;
Eric Liu4cfb88a2016-04-25 15:09:22 +00002457 LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
Saleem Abdulrasoold170c4b2015-10-04 17:51:05 +00002458 LangOpts.DeclSpecKeyword = 1; // To get __declspec.
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002459 return LangOpts;
2460}
2461
Edwin Vaned544aa72013-09-30 13:31:48 +00002462const char *StyleOptionHelpDescription =
2463 "Coding style, currently supports:\n"
2464 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
2465 "Use -style=file to load style configuration from\n"
2466 ".clang-format file located in one of the parent\n"
2467 "directories of the source file (or current\n"
2468 "directory for stdin).\n"
2469 "Use -style=\"{key: value, ...}\" to set specific\n"
2470 "parameters, e.g.:\n"
2471 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
2472
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002473static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Daniel Jasper498f5582015-12-25 08:53:31 +00002474 if (FileName.endswith(".java"))
Daniel Jasperc58c70e2014-09-15 11:21:46 +00002475 return FormatStyle::LK_Java;
Daniel Jasper498f5582015-12-25 08:53:31 +00002476 if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts"))
2477 return FormatStyle::LK_JavaScript; // JavaScript or TypeScript.
Daniel Jasper03a04fe2016-12-12 12:42:29 +00002478 if (FileName.endswith(".m") || FileName.endswith(".mm"))
2479 return FormatStyle::LK_ObjC;
Daniel Jasper498f5582015-12-25 08:53:31 +00002480 if (FileName.endswith_lower(".proto") ||
2481 FileName.endswith_lower(".protodevel"))
Daniel Jasper7052ce62014-01-19 09:04:08 +00002482 return FormatStyle::LK_Proto;
Krasimir Georgiev66496652017-11-17 15:10:49 +00002483 if (FileName.endswith_lower(".textpb") ||
2484 FileName.endswith_lower(".pb.txt") ||
2485 FileName.endswith_lower(".textproto") ||
2486 FileName.endswith_lower(".asciipb"))
2487 return FormatStyle::LK_TextProto;
Daniel Jasper498f5582015-12-25 08:53:31 +00002488 if (FileName.endswith_lower(".td"))
2489 return FormatStyle::LK_TableGen;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002490 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002491}
2492
Ben Hamilton3b345c32018-02-21 15:54:31 +00002493FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code) {
Ben Hamilton6e066352018-02-27 15:56:40 +00002494 const auto GuessedLanguage = getLanguageByFileName(FileName);
2495 if (GuessedLanguage == FormatStyle::LK_Cpp) {
Ben Hamilton07e58362018-02-21 21:27:27 +00002496 auto Extension = llvm::sys::path::extension(FileName);
Ben Hamilton3b345c32018-02-21 15:54:31 +00002497 // If there's no file extension (or it's .h), we need to check the contents
2498 // of the code to see if it contains Objective-C.
Ben Hamilton07e58362018-02-21 21:27:27 +00002499 if (Extension.empty() || Extension == ".h") {
2500 auto NonEmptyFileName = FileName.empty() ? "guess.h" : FileName;
Ben Hamilton3b345c32018-02-21 15:54:31 +00002501 std::unique_ptr<Environment> Env =
Ben Hamilton07e58362018-02-21 21:27:27 +00002502 Environment::CreateVirtualEnvironment(Code, NonEmptyFileName, /*Ranges=*/{});
Ben Hamilton3b345c32018-02-21 15:54:31 +00002503 ObjCHeaderStyleGuesser Guesser(*Env, getLLVMStyle());
2504 Guesser.process();
Ben Hamilton6e066352018-02-27 15:56:40 +00002505 if (Guesser.isObjC())
2506 return FormatStyle::LK_ObjC;
Ben Hamilton3b345c32018-02-21 15:54:31 +00002507 }
2508 }
Ben Hamilton6e066352018-02-27 15:56:40 +00002509 return GuessedLanguage;
Ben Hamilton3b345c32018-02-21 15:54:31 +00002510}
2511
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00002512llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
Antonio Maiorano7eb75072017-01-20 01:22:42 +00002513 StringRef FallbackStyleName,
2514 StringRef Code, vfs::FileSystem *FS) {
Eric Liu547d8792016-03-24 13:22:42 +00002515 if (!FS) {
2516 FS = vfs::getRealFileSystem().get();
2517 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002518 FormatStyle Style = getLLVMStyle();
Ben Hamilton3b345c32018-02-21 15:54:31 +00002519 Style.Language = guessLanguage(FileName, Code);
Daniel Jasper03a04fe2016-12-12 12:42:29 +00002520
Antonio Maiorano7eb75072017-01-20 01:22:42 +00002521 FormatStyle FallbackStyle = getNoStyle();
2522 if (!getPredefinedStyle(FallbackStyleName, Style.Language, &FallbackStyle))
2523 return make_string_error("Invalid fallback style \"" + FallbackStyleName);
Edwin Vaned544aa72013-09-30 13:31:48 +00002524
2525 if (StyleName.startswith("{")) {
2526 // Parse YAML/JSON style from the command line.
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00002527 if (std::error_code ec = parseConfiguration(StyleName, &Style))
2528 return make_string_error("Error parsing -style: " + ec.message());
Edwin Vaned544aa72013-09-30 13:31:48 +00002529 return Style;
2530 }
2531
2532 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002533 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00002534 return make_string_error("Invalid value for -style");
Edwin Vaned544aa72013-09-30 13:31:48 +00002535 return Style;
2536 }
2537
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002538 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002539 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00002540 SmallString<128> Path(FileName);
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00002541 if (std::error_code EC = FS->makeAbsolute(Path))
2542 return make_string_error(EC.message());
Antonio Maiorano34c03762016-12-22 05:10:07 +00002543
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002544 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00002545 Directory = llvm::sys::path::parent_path(Directory)) {
Eric Liu547d8792016-03-24 13:22:42 +00002546
2547 auto Status = FS->status(Directory);
2548 if (!Status ||
2549 Status->getType() != llvm::sys::fs::file_type::directory_file) {
Edwin Vaned544aa72013-09-30 13:31:48 +00002550 continue;
Eric Liu547d8792016-03-24 13:22:42 +00002551 }
2552
Edwin Vaned544aa72013-09-30 13:31:48 +00002553 SmallString<128> ConfigFile(Directory);
2554
2555 llvm::sys::path::append(ConfigFile, ".clang-format");
2556 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
Eric Liud4758322016-03-24 13:22:37 +00002557
Eric Liu547d8792016-03-24 13:22:42 +00002558 Status = FS->status(ConfigFile.str());
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00002559 bool FoundConfigFile =
Eric Liu547d8792016-03-24 13:22:42 +00002560 Status && (Status->getType() == llvm::sys::fs::file_type::regular_file);
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00002561 if (!FoundConfigFile) {
Edwin Vaned544aa72013-09-30 13:31:48 +00002562 // Try _clang-format too, since dotfiles are not commonly used on Windows.
2563 ConfigFile = Directory;
2564 llvm::sys::path::append(ConfigFile, "_clang-format");
2565 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
Eric Liu547d8792016-03-24 13:22:42 +00002566 Status = FS->status(ConfigFile.str());
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00002567 FoundConfigFile = Status && (Status->getType() ==
2568 llvm::sys::fs::file_type::regular_file);
Edwin Vaned544aa72013-09-30 13:31:48 +00002569 }
2570
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00002571 if (FoundConfigFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002572 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
Eric Liu547d8792016-03-24 13:22:42 +00002573 FS->getBufferForFile(ConfigFile.str());
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00002574 if (std::error_code EC = Text.getError())
2575 return make_string_error(EC.message());
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002576 if (std::error_code ec =
2577 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00002578 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002579 if (!UnsuitableConfigFiles.empty())
2580 UnsuitableConfigFiles.append(", ");
2581 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002582 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002583 }
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00002584 return make_string_error("Error reading " + ConfigFile + ": " +
2585 ec.message());
Edwin Vaned544aa72013-09-30 13:31:48 +00002586 }
2587 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2588 return Style;
2589 }
2590 }
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00002591 if (!UnsuitableConfigFiles.empty())
2592 return make_string_error("Configuration file(s) do(es) not support " +
2593 getLanguageName(Style.Language) + ": " +
2594 UnsuitableConfigFiles);
Antonio Maiorano7eb75072017-01-20 01:22:42 +00002595 return FallbackStyle;
Edwin Vaned544aa72013-09-30 13:31:48 +00002596}
2597
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002598} // namespace format
2599} // namespace clang