blob: 2d1adb58e4a296ecea2e8902bd8e97da8c242368 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Daniel Jasperf7935112012-12-03 18:12:45 +00006//
7//===----------------------------------------------------------------------===//
8///
9/// \file
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010/// This file implements functions declared in Format.h. This will be
Daniel Jasperf7935112012-12-03 18:12:45 +000011/// split into separate files as we go.
12///
Daniel Jasperf7935112012-12-03 18:12:45 +000013//===----------------------------------------------------------------------===//
14
Daniel Jasper85c472d2015-09-29 07:53:08 +000015#include "clang/Format/Format.h"
Eric Liu4cfb88a2016-04-25 15:09:22 +000016#include "AffectedRangeManager.h"
Daniel Jasperde0328a2013-08-16 11:20:30 +000017#include "ContinuationIndenter.h"
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +000018#include "FormatInternal.h"
Martin Probstc4a0dd42016-05-20 11:24:24 +000019#include "FormatTokenLexer.h"
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +000020#include "NamespaceEndCommentsFixer.h"
Martin Probstc4a0dd42016-05-20 11:24:24 +000021#include "SortJavaScriptImports.h"
22#include "TokenAnalyzer.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000023#include "TokenAnnotator.h"
Daniel Jasper0df50932014-12-10 19:00:42 +000024#include "UnwrappedLineFormatter.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "UnwrappedLineParser.h"
Krasimir Georgievb03877a2017-06-21 12:03:12 +000026#include "UsingDeclarationsSorter.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000027#include "WhitespaceManager.h"
Daniel Jasperec04c0d2013-05-16 10:40:07 +000028#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000029#include "clang/Basic/DiagnosticOptions.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000030#include "clang/Basic/SourceManager.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000031#include "clang/Lex/Lexer.h"
Eric Liu44564ac2018-06-04 09:04:12 +000032#include "clang/Tooling/Inclusions/HeaderIncludes.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000033#include "llvm/ADT/STLExtras.h"
Ben Hamiltone2e3e672018-01-17 17:33:08 +000034#include "llvm/ADT/StringRef.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000035#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000036#include "llvm/Support/Debug.h"
Edwin Vaned544aa72013-09-30 13:31:48 +000037#include "llvm/Support/Path.h"
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +000038#include "llvm/Support/Regex.h"
Jonas Devliegherefc514902018-10-10 13:27:25 +000039#include "llvm/Support/VirtualFileSystem.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::RawStringFormat)
Daniel Jaspere1e43192014-04-01 12:55:11 +000052
Alexander Kornienkod6538332013-05-07 15:32:14 +000053namespace llvm {
54namespace yaml {
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000055template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
56 static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
57 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
Daniel Jasperc58c70e2014-09-15 11:21:46 +000058 IO.enumCase(Value, "Java", FormatStyle::LK_Java);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +000059 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
Daniel Jasper03a04fe2016-12-12 12:42:29 +000060 IO.enumCase(Value, "ObjC", FormatStyle::LK_ObjC);
Daniel Jasper7052ce62014-01-19 09:04:08 +000061 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
Daniel Jasper498f5582015-12-25 08:53:31 +000062 IO.enumCase(Value, "TableGen", FormatStyle::LK_TableGen);
Krasimir Georgiev26b144c2017-07-03 15:05:14 +000063 IO.enumCase(Value, "TextProto", FormatStyle::LK_TextProto);
Paul Hoadcbb726d2019-03-21 13:09:22 +000064 IO.enumCase(Value, "CSharp", FormatStyle::LK_CSharp);
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
Paul Hoad15000a12019-03-13 08:26:39 +0000110template <> struct ScalarEnumerationTraits<FormatStyle::ShortIfStyle> {
111 static void enumeration(IO &IO, FormatStyle::ShortIfStyle &Value) {
112 IO.enumCase(Value, "Never", FormatStyle::SIS_Never);
113 IO.enumCase(Value, "Always", FormatStyle::SIS_Always);
114 IO.enumCase(Value, "WithoutElse", FormatStyle::SIS_WithoutElse);
115
116 // For backward compatibility.
117 IO.enumCase(Value, "false", FormatStyle::SIS_Never);
118 IO.enumCase(Value, "true", FormatStyle::SIS_WithoutElse);
119 }
120};
121
Ben Hamilton4dc658c2018-02-02 20:15:14 +0000122template <> struct ScalarEnumerationTraits<FormatStyle::BinPackStyle> {
123 static void enumeration(IO &IO, FormatStyle::BinPackStyle &Value) {
124 IO.enumCase(Value, "Auto", FormatStyle::BPS_Auto);
125 IO.enumCase(Value, "Always", FormatStyle::BPS_Always);
126 IO.enumCase(Value, "Never", FormatStyle::BPS_Never);
127 }
128};
129
Daniel Jasperac043c92014-09-15 11:11:00 +0000130template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
131 static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
132 IO.enumCase(Value, "All", FormatStyle::BOS_All);
133 IO.enumCase(Value, "true", FormatStyle::BOS_All);
134 IO.enumCase(Value, "None", FormatStyle::BOS_None);
135 IO.enumCase(Value, "false", FormatStyle::BOS_None);
136 IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
137 }
138};
139
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000140template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
141 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
142 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
143 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
Birunthan Mohanathas305fa9c2015-07-12 03:13:54 +0000144 IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000145 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
146 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000147 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
Roman Kashitsyn291f64f2015-08-10 13:43:19 +0000148 IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000149 IO.enumCase(Value, "Custom", FormatStyle::BS_Custom);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000150 }
151};
152
Manuel Klimek89628f62017-09-20 09:51:03 +0000153template <>
154struct ScalarEnumerationTraits<FormatStyle::BreakConstructorInitializersStyle> {
155 static void
156 enumeration(IO &IO, FormatStyle::BreakConstructorInitializersStyle &Value) {
Francois Ferranda6b6d512017-05-24 11:36:58 +0000157 IO.enumCase(Value, "BeforeColon", FormatStyle::BCIS_BeforeColon);
158 IO.enumCase(Value, "BeforeComma", FormatStyle::BCIS_BeforeComma);
159 IO.enumCase(Value, "AfterColon", FormatStyle::BCIS_AfterColon);
160 }
161};
162
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000163template <>
Francois Ferrand6bb103f2018-06-11 14:41:26 +0000164struct ScalarEnumerationTraits<FormatStyle::BreakInheritanceListStyle> {
Paul Hoad5bcf99b2019-03-01 09:09:54 +0000165 static void enumeration(IO &IO,
166 FormatStyle::BreakInheritanceListStyle &Value) {
Francois Ferrand6bb103f2018-06-11 14:41:26 +0000167 IO.enumCase(Value, "BeforeColon", FormatStyle::BILS_BeforeColon);
168 IO.enumCase(Value, "BeforeComma", FormatStyle::BILS_BeforeComma);
169 IO.enumCase(Value, "AfterColon", FormatStyle::BILS_AfterColon);
170 }
171};
172
173template <>
Krasimir Georgievad47c902017-08-30 14:34:57 +0000174struct ScalarEnumerationTraits<FormatStyle::PPDirectiveIndentStyle> {
175 static void enumeration(IO &IO, FormatStyle::PPDirectiveIndentStyle &Value) {
176 IO.enumCase(Value, "None", FormatStyle::PPDIS_None);
177 IO.enumCase(Value, "AfterHash", FormatStyle::PPDIS_AfterHash);
Paul Hoad701a0d72019-03-20 20:49:43 +0000178 IO.enumCase(Value, "BeforeHash", FormatStyle::PPDIS_BeforeHash);
Krasimir Georgievad47c902017-08-30 14:34:57 +0000179 }
180};
181
182template <>
Zachary Turner448592e2015-12-18 22:20:15 +0000183struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
184 static void enumeration(IO &IO, FormatStyle::ReturnTypeBreakingStyle &Value) {
185 IO.enumCase(Value, "None", FormatStyle::RTBS_None);
186 IO.enumCase(Value, "All", FormatStyle::RTBS_All);
187 IO.enumCase(Value, "TopLevel", FormatStyle::RTBS_TopLevel);
188 IO.enumCase(Value, "TopLevelDefinitions",
189 FormatStyle::RTBS_TopLevelDefinitions);
190 IO.enumCase(Value, "AllDefinitions", FormatStyle::RTBS_AllDefinitions);
191 }
192};
193
194template <>
Francois Ferrand58e6fe52018-05-16 08:25:03 +0000195struct ScalarEnumerationTraits<FormatStyle::BreakTemplateDeclarationsStyle> {
Paul Hoad5bcf99b2019-03-01 09:09:54 +0000196 static void enumeration(IO &IO,
197 FormatStyle::BreakTemplateDeclarationsStyle &Value) {
Francois Ferrand58e6fe52018-05-16 08:25:03 +0000198 IO.enumCase(Value, "No", FormatStyle::BTDS_No);
199 IO.enumCase(Value, "MultiLine", FormatStyle::BTDS_MultiLine);
200 IO.enumCase(Value, "Yes", FormatStyle::BTDS_Yes);
201
202 // For backward compatibility.
203 IO.enumCase(Value, "false", FormatStyle::BTDS_MultiLine);
204 IO.enumCase(Value, "true", FormatStyle::BTDS_Yes);
205 }
206};
207
208template <>
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000209struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
210 static void
211 enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) {
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000212 IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
213 IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
214 IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
215
216 // For backward compatibility.
217 IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
218 IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
219 }
220};
221
Alexander Kornienkod6538332013-05-07 15:32:14 +0000222template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000223struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000224 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000225 FormatStyle::NamespaceIndentationKind &Value) {
226 IO.enumCase(Value, "None", FormatStyle::NI_None);
227 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
228 IO.enumCase(Value, "All", FormatStyle::NI_All);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000229 }
230};
231
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000232template <> struct ScalarEnumerationTraits<FormatStyle::BracketAlignmentStyle> {
233 static void enumeration(IO &IO, FormatStyle::BracketAlignmentStyle &Value) {
234 IO.enumCase(Value, "Align", FormatStyle::BAS_Align);
235 IO.enumCase(Value, "DontAlign", FormatStyle::BAS_DontAlign);
236 IO.enumCase(Value, "AlwaysBreak", FormatStyle::BAS_AlwaysBreak);
237
238 // For backward compatibility.
239 IO.enumCase(Value, "true", FormatStyle::BAS_Align);
240 IO.enumCase(Value, "false", FormatStyle::BAS_DontAlign);
241 }
242};
243
Manuel Klimek89628f62017-09-20 09:51:03 +0000244template <>
245struct ScalarEnumerationTraits<FormatStyle::EscapedNewlineAlignmentStyle> {
246 static void enumeration(IO &IO,
247 FormatStyle::EscapedNewlineAlignmentStyle &Value) {
Daniel Jasper7fdbb3f2017-05-08 15:08:00 +0000248 IO.enumCase(Value, "DontAlign", FormatStyle::ENAS_DontAlign);
249 IO.enumCase(Value, "Left", FormatStyle::ENAS_Left);
250 IO.enumCase(Value, "Right", FormatStyle::ENAS_Right);
251
252 // For backward compatibility.
253 IO.enumCase(Value, "true", FormatStyle::ENAS_Left);
254 IO.enumCase(Value, "false", FormatStyle::ENAS_Right);
255 }
256};
257
Jacques Pienaarfc275112015-02-18 23:48:37 +0000258template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
259 static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
Daniel Jasper553d4872014-06-17 12:40:34 +0000260 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
261 IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
262 IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
263
Alp Toker958027b2014-07-14 19:42:55 +0000264 // For backward compatibility.
Daniel Jasper553d4872014-06-17 12:40:34 +0000265 IO.enumCase(Value, "true", FormatStyle::PAS_Left);
266 IO.enumCase(Value, "false", FormatStyle::PAS_Right);
267 }
268};
269
270template <>
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000271struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000272 static void enumeration(IO &IO,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000273 FormatStyle::SpaceBeforeParensOptions &Value) {
274 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000275 IO.enumCase(Value, "ControlStatements",
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000276 FormatStyle::SBPO_ControlStatements);
277 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000278
279 // For backward compatibility.
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000280 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
281 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000282 }
283};
284
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000285template <> struct MappingTraits<FormatStyle> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000286 static void mapping(IO &IO, FormatStyle &Style) {
287 // When reading, read the language first, we need it for getPredefinedStyle.
288 IO.mapOptional("Language", Style.Language);
289
Alexander Kornienko49149672013-05-10 11:56:10 +0000290 if (IO.outputting()) {
Paul Hoadcbb726d2019-03-21 13:09:22 +0000291 StringRef StylesArray[] = {"LLVM", "Google", "Chromium", "Mozilla",
292 "WebKit", "GNU", "Microsoft"};
Alexander Kornienko49149672013-05-10 11:56:10 +0000293 ArrayRef<StringRef> Styles(StylesArray);
294 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
295 StringRef StyleName(Styles[i]);
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000296 FormatStyle PredefinedStyle;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000297 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000298 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000299 IO.mapOptional("# BasedOnStyle", StyleName);
300 break;
301 }
302 }
303 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000304 StringRef BasedOnStyle;
305 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000306 if (!BasedOnStyle.empty()) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000307 FormatStyle::LanguageKind OldLanguage = Style.Language;
308 FormatStyle::LanguageKind Language =
309 ((FormatStyle *)IO.getContext())->Language;
310 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000311 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
312 return;
313 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000314 Style.Language = OldLanguage;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000315 }
Alexander Kornienkod6538332013-05-07 15:32:14 +0000316 }
317
Birunthan Mohanathas50a6f912015-06-28 14:52:34 +0000318 // For backward compatibility.
319 if (!IO.outputting()) {
Daniel Jasper7fdbb3f2017-05-08 15:08:00 +0000320 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlines);
Birunthan Mohanathas50a6f912015-06-28 14:52:34 +0000321 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
322 IO.mapOptional("IndentFunctionDeclarationAfterType",
323 Style.IndentWrappedFunctionNames);
324 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
325 IO.mapOptional("SpaceAfterControlStatementKeyword",
326 Style.SpaceBeforeParens);
327 }
328
Alexander Kornienkod6538332013-05-07 15:32:14 +0000329 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jasper3aa9a6a2014-11-18 23:55:27 +0000330 IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000331 IO.mapOptional("AlignConsecutiveAssignments",
332 Style.AlignConsecutiveAssignments);
Daniel Jaspere12597c2015-10-01 10:06:54 +0000333 IO.mapOptional("AlignConsecutiveDeclarations",
334 Style.AlignConsecutiveDeclarations);
Daniel Jasper7fdbb3f2017-05-08 15:08:00 +0000335 IO.mapOptional("AlignEscapedNewlines", Style.AlignEscapedNewlines);
Daniel Jasper3219e432014-12-02 13:24:51 +0000336 IO.mapOptional("AlignOperands", Style.AlignOperands);
Daniel Jasper552f4a72013-07-31 23:55:15 +0000337 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Paul Hoadc6deae42019-03-23 14:37:58 +0000338 IO.mapOptional("AllowAllArgumentsOnNextLine",
339 Style.AllowAllArgumentsOnNextLine);
340 IO.mapOptional("AllowAllConstructorInitializersOnNextLine",
341 Style.AllowAllConstructorInitializersOnNextLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000342 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
343 Style.AllowAllParametersOfDeclarationOnNextLine);
Daniel Jasper17605d32014-05-14 09:33:35 +0000344 IO.mapOptional("AllowShortBlocksOnASingleLine",
345 Style.AllowShortBlocksOnASingleLine);
Daniel Jasperb87899b2014-09-10 13:11:45 +0000346 IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
347 Style.AllowShortCaseLabelsOnASingleLine);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000348 IO.mapOptional("AllowShortFunctionsOnASingleLine",
349 Style.AllowShortFunctionsOnASingleLine);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000350 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
351 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000352 IO.mapOptional("AllowShortLoopsOnASingleLine",
353 Style.AllowShortLoopsOnASingleLine);
Daniel Jasperca4ea1c2014-08-05 12:16:31 +0000354 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
355 Style.AlwaysBreakAfterDefinitionReturnType);
Zachary Turner448592e2015-12-18 22:20:15 +0000356 IO.mapOptional("AlwaysBreakAfterReturnType",
357 Style.AlwaysBreakAfterReturnType);
Paul Hoadc6deae42019-03-23 14:37:58 +0000358
Zachary Turner448592e2015-12-18 22:20:15 +0000359 // If AlwaysBreakAfterDefinitionReturnType was specified but
360 // AlwaysBreakAfterReturnType was not, initialize the latter from the
361 // former for backwards compatibility.
362 if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
363 Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None) {
364 if (Style.AlwaysBreakAfterDefinitionReturnType == FormatStyle::DRTBS_All)
365 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
366 else if (Style.AlwaysBreakAfterDefinitionReturnType ==
367 FormatStyle::DRTBS_TopLevel)
368 Style.AlwaysBreakAfterReturnType =
369 FormatStyle::RTBS_TopLevelDefinitions;
370 }
371
Alexander Kornienko58611712013-07-04 12:02:44 +0000372 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
373 Style.AlwaysBreakBeforeMultilineStrings);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000374 IO.mapOptional("AlwaysBreakTemplateDeclarations",
375 Style.AlwaysBreakTemplateDeclarations);
376 IO.mapOptional("BinPackArguments", Style.BinPackArguments);
377 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000378 IO.mapOptional("BraceWrapping", Style.BraceWrapping);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000379 IO.mapOptional("BreakBeforeBinaryOperators",
380 Style.BreakBeforeBinaryOperators);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000381 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Francois Ferrand6bb103f2018-06-11 14:41:26 +0000382
383 bool BreakBeforeInheritanceComma = false;
Paul Hoad5bcf99b2019-03-01 09:09:54 +0000384 IO.mapOptional("BreakBeforeInheritanceComma", BreakBeforeInheritanceComma);
385 IO.mapOptional("BreakInheritanceList", Style.BreakInheritanceList);
Francois Ferrand6bb103f2018-06-11 14:41:26 +0000386 // If BreakBeforeInheritanceComma was specified but
387 // BreakInheritance was not, initialize the latter from the
388 // former for backwards compatibility.
389 if (BreakBeforeInheritanceComma &&
390 Style.BreakInheritanceList == FormatStyle::BILS_BeforeColon)
391 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
392
Daniel Jasper165b29e2013-11-08 00:57:11 +0000393 IO.mapOptional("BreakBeforeTernaryOperators",
394 Style.BreakBeforeTernaryOperators);
Francois Ferranda6b6d512017-05-24 11:36:58 +0000395
396 bool BreakConstructorInitializersBeforeComma = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000397 IO.mapOptional("BreakConstructorInitializersBeforeComma",
Francois Ferranda6b6d512017-05-24 11:36:58 +0000398 BreakConstructorInitializersBeforeComma);
399 IO.mapOptional("BreakConstructorInitializers",
400 Style.BreakConstructorInitializers);
401 // If BreakConstructorInitializersBeforeComma was specified but
402 // BreakConstructorInitializers was not, initialize the latter from the
403 // former for backwards compatibility.
404 if (BreakConstructorInitializersBeforeComma &&
405 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon)
406 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
407
Daniel Jaspere1a7b762016-02-01 11:21:02 +0000408 IO.mapOptional("BreakAfterJavaFieldAnnotations",
409 Style.BreakAfterJavaFieldAnnotations);
410 IO.mapOptional("BreakStringLiterals", Style.BreakStringLiterals);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000411 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000412 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
Francois Ferrande56a8292017-06-14 12:29:47 +0000413 IO.mapOptional("CompactNamespaces", Style.CompactNamespaces);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000414 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
415 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000416 IO.mapOptional("ConstructorInitializerIndentWidth",
417 Style.ConstructorInitializerIndentWidth);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000418 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
419 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Daniel Jasper553d4872014-06-17 12:40:34 +0000420 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000421 IO.mapOptional("DisableFormat", Style.DisableFormat);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000422 IO.mapOptional("ExperimentalAutoDetectBinPacking",
423 Style.ExperimentalAutoDetectBinPacking);
Krasimir Georgiev32eaa862017-03-01 15:35:39 +0000424 IO.mapOptional("FixNamespaceComments", Style.FixNamespaceComments);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000425 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
Eric Liu9d92c022018-05-14 19:51:33 +0000426 IO.mapOptional("IncludeBlocks", Style.IncludeStyle.IncludeBlocks);
427 IO.mapOptional("IncludeCategories", Style.IncludeStyle.IncludeCategories);
428 IO.mapOptional("IncludeIsMainRegex", Style.IncludeStyle.IncludeIsMainRegex);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000429 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
Krasimir Georgievad47c902017-08-30 14:34:57 +0000430 IO.mapOptional("IndentPPDirectives", Style.IndentPPDirectives);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000431 IO.mapOptional("IndentWidth", Style.IndentWidth);
432 IO.mapOptional("IndentWrappedFunctionNames",
433 Style.IndentWrappedFunctionNames);
Krasimir Georgiev7e91b032018-10-05 17:19:26 +0000434 IO.mapOptional("JavaImportGroups", Style.JavaImportGroups);
Martin Probst0cd74ee2016-06-13 16:39:50 +0000435 IO.mapOptional("JavaScriptQuotes", Style.JavaScriptQuotes);
436 IO.mapOptional("JavaScriptWrapImports", Style.JavaScriptWrapImports);
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000437 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
438 Style.KeepEmptyLinesAtTheStartOfBlocks);
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000439 IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
440 IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000441 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000442 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Ben Hamilton4dc658c2018-02-02 20:15:14 +0000443 IO.mapOptional("ObjCBinPackProtocolList", Style.ObjCBinPackProtocolList);
Daniel Jasper50d634b2014-10-28 16:53:38 +0000444 IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
Daniel Jaspere9beea22014-01-28 15:20:33 +0000445 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000446 IO.mapOptional("ObjCSpaceBeforeProtocolList",
447 Style.ObjCSpaceBeforeProtocolList);
Manuel Klimek89628f62017-09-20 09:51:03 +0000448 IO.mapOptional("PenaltyBreakAssignment", Style.PenaltyBreakAssignment);
Daniel Jasper33b909c2013-10-25 14:29:37 +0000449 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
450 Style.PenaltyBreakBeforeFirstCallParameter);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000451 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000452 IO.mapOptional("PenaltyBreakFirstLessLess",
453 Style.PenaltyBreakFirstLessLess);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000454 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Francois Ferrand58e6fe52018-05-16 08:25:03 +0000455 IO.mapOptional("PenaltyBreakTemplateDeclaration",
456 Style.PenaltyBreakTemplateDeclaration);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000457 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
458 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
459 Style.PenaltyReturnTypeOnItsOwnLine);
Daniel Jasper553d4872014-06-17 12:40:34 +0000460 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000461 IO.mapOptional("RawStringFormats", Style.RawStringFormats);
Daniel Jaspera0a50392015-12-01 13:28:53 +0000462 IO.mapOptional("ReflowComments", Style.ReflowComments);
463 IO.mapOptional("SortIncludes", Style.SortIncludes);
Krasimir Georgievac16a202017-06-23 11:46:03 +0000464 IO.mapOptional("SortUsingDeclarations", Style.SortUsingDeclarations);
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000465 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
Manuel Klimek89628f62017-09-20 09:51:03 +0000466 IO.mapOptional("SpaceAfterTemplateKeyword",
467 Style.SpaceAfterTemplateKeyword);
Daniel Jasperd94bff32013-09-25 15:15:02 +0000468 IO.mapOptional("SpaceBeforeAssignmentOperators",
469 Style.SpaceBeforeAssignmentOperators);
Hans Wennborgbfc34062018-06-14 08:01:09 +0000470 IO.mapOptional("SpaceBeforeCpp11BracedList",
471 Style.SpaceBeforeCpp11BracedList);
Francois Ferrand2a9ea782018-03-01 10:09:13 +0000472 IO.mapOptional("SpaceBeforeCtorInitializerColon",
473 Style.SpaceBeforeCtorInitializerColon);
474 IO.mapOptional("SpaceBeforeInheritanceColon",
475 Style.SpaceBeforeInheritanceColon);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000476 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
Francois Ferrand2a9ea782018-03-01 10:09:13 +0000477 IO.mapOptional("SpaceBeforeRangeBasedForLoopColon",
478 Style.SpaceBeforeRangeBasedForLoopColon);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000479 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
480 IO.mapOptional("SpacesBeforeTrailingComments",
481 Style.SpacesBeforeTrailingComments);
482 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
483 IO.mapOptional("SpacesInContainerLiterals",
484 Style.SpacesInContainerLiterals);
485 IO.mapOptional("SpacesInCStyleCastParentheses",
486 Style.SpacesInCStyleCastParentheses);
487 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
488 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
489 IO.mapOptional("Standard", Style.Standard);
Francois Ferrand6f40e212018-10-02 16:37:51 +0000490 IO.mapOptional("StatementMacros", Style.StatementMacros);
Birunthan Mohanathas35cfbd72015-06-28 14:51:17 +0000491 IO.mapOptional("TabWidth", Style.TabWidth);
492 IO.mapOptional("UseTab", Style.UseTab);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000493 }
494};
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000495
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000496template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
497 static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
498 IO.mapOptional("AfterClass", Wrapping.AfterClass);
499 IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
500 IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
501 IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
502 IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
503 IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
504 IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
505 IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
Krasimir Georgievd6ce9372017-09-15 11:23:50 +0000506 IO.mapOptional("AfterExternBlock", Wrapping.AfterExternBlock);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000507 IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
508 IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
509 IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
Francois Ferrandad722562017-06-30 20:25:55 +0000510 IO.mapOptional("SplitEmptyFunction", Wrapping.SplitEmptyFunction);
511 IO.mapOptional("SplitEmptyRecord", Wrapping.SplitEmptyRecord);
512 IO.mapOptional("SplitEmptyNamespace", Wrapping.SplitEmptyNamespace);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000513 }
514};
515
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000516template <> struct MappingTraits<FormatStyle::RawStringFormat> {
517 static void mapping(IO &IO, FormatStyle::RawStringFormat &Format) {
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000518 IO.mapOptional("Language", Format.Language);
Krasimir Georgiev4527f132018-01-17 12:24:59 +0000519 IO.mapOptional("Delimiters", Format.Delimiters);
Krasimir Georgiev2537e222018-01-17 16:17:26 +0000520 IO.mapOptional("EnclosingFunctions", Format.EnclosingFunctions);
Krasimir Georgiev412ed092018-01-19 16:18:47 +0000521 IO.mapOptional("CanonicalDelimiter", Format.CanonicalDelimiter);
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000522 IO.mapOptional("BasedOnStyle", Format.BasedOnStyle);
523 }
524};
525
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000526// Allows to read vector<FormatStyle> while keeping default values.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000527// IO.getContext() should contain a pointer to the FormatStyle structure, that
528// will be used to get default values for missing keys.
529// If the first element has no Language specified, it will be treated as the
530// default one for the following elements.
Jacques Pienaarfc275112015-02-18 23:48:37 +0000531template <> struct DocumentListTraits<std::vector<FormatStyle>> {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000532 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
533 return Seq.size();
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000534 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000535 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000536 size_t Index) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000537 if (Index >= Seq.size()) {
538 assert(Index == Seq.size());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000539 FormatStyle Template;
Krasimir Georgiev1696bb62017-11-09 15:12:17 +0000540 if (!Seq.empty() && Seq[0].Language == FormatStyle::LK_None) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000541 Template = Seq[0];
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000542 } else {
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000543 Template = *((const FormatStyle *)IO.getContext());
Alexander Kornienko6d2c88e2013-12-10 10:30:34 +0000544 Template.Language = FormatStyle::LK_None;
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000545 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000546 Seq.resize(Index + 1, Template);
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000547 }
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000548 return Seq[Index];
Alexander Kornienkocabdd732013-11-29 15:19:43 +0000549 }
550};
Daniel Jasperd89ae9d2015-09-23 08:30:47 +0000551} // namespace yaml
552} // namespace llvm
Alexander Kornienkod6538332013-05-07 15:32:14 +0000553
Daniel Jasperf7935112012-12-03 18:12:45 +0000554namespace clang {
555namespace format {
556
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000557const std::error_category &getParseCategory() {
Benjamin Kramerf76861c2018-03-20 21:52:19 +0000558 static const ParseErrorCategory C{};
Rafael Espindolad0136702014-06-12 02:50:04 +0000559 return C;
560}
561std::error_code make_error_code(ParseError e) {
Rafael Espindola6d0d89b2014-06-12 03:31:26 +0000562 return std::error_code(static_cast<int>(e), getParseCategory());
Rafael Espindolad0136702014-06-12 02:50:04 +0000563}
564
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +0000565inline llvm::Error make_string_error(const llvm::Twine &Message) {
566 return llvm::make_error<llvm::StringError>(Message,
567 llvm::inconvertibleErrorCode());
568}
569
Reid Kleckner6432d452016-10-19 23:39:55 +0000570const char *ParseErrorCategory::name() const noexcept {
Rafael Espindolad0136702014-06-12 02:50:04 +0000571 return "clang-format.parse_error";
572}
573
574std::string ParseErrorCategory::message(int EV) const {
575 switch (static_cast<ParseError>(EV)) {
576 case ParseError::Success:
577 return "Success";
578 case ParseError::Error:
579 return "Invalid argument";
580 case ParseError::Unsuitable:
581 return "Unsuitable";
582 }
Saleem Abdulrasoolfbfbaf62014-06-12 19:33:26 +0000583 llvm_unreachable("unexpected parse error");
Rafael Espindolad0136702014-06-12 02:50:04 +0000584}
585
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000586static FormatStyle expandPresets(const FormatStyle &Style) {
Daniel Jasper55bbe662015-10-07 04:06:10 +0000587 if (Style.BreakBeforeBraces == FormatStyle::BS_Custom)
588 return Style;
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000589 FormatStyle Expanded = Style;
Manuel Klimek89628f62017-09-20 09:51:03 +0000590 Expanded.BraceWrapping = {false, false, false, false, false,
591 false, false, false, false, false,
592 false, false, true, true, true};
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000593 switch (Style.BreakBeforeBraces) {
594 case FormatStyle::BS_Linux:
595 Expanded.BraceWrapping.AfterClass = true;
596 Expanded.BraceWrapping.AfterFunction = true;
597 Expanded.BraceWrapping.AfterNamespace = true;
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000598 break;
599 case FormatStyle::BS_Mozilla:
600 Expanded.BraceWrapping.AfterClass = true;
601 Expanded.BraceWrapping.AfterEnum = true;
602 Expanded.BraceWrapping.AfterFunction = true;
603 Expanded.BraceWrapping.AfterStruct = true;
604 Expanded.BraceWrapping.AfterUnion = true;
Krasimir Georgievd6ce9372017-09-15 11:23:50 +0000605 Expanded.BraceWrapping.AfterExternBlock = true;
Sylvestre Ledru82c9a0e2017-09-13 20:03:29 +0000606 Expanded.BraceWrapping.SplitEmptyFunction = true;
Francois Ferrandad722562017-06-30 20:25:55 +0000607 Expanded.BraceWrapping.SplitEmptyRecord = false;
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000608 break;
609 case FormatStyle::BS_Stroustrup:
610 Expanded.BraceWrapping.AfterFunction = true;
611 Expanded.BraceWrapping.BeforeCatch = true;
612 Expanded.BraceWrapping.BeforeElse = true;
613 break;
614 case FormatStyle::BS_Allman:
615 Expanded.BraceWrapping.AfterClass = true;
616 Expanded.BraceWrapping.AfterControlStatement = true;
617 Expanded.BraceWrapping.AfterEnum = true;
618 Expanded.BraceWrapping.AfterFunction = true;
619 Expanded.BraceWrapping.AfterNamespace = true;
620 Expanded.BraceWrapping.AfterObjCDeclaration = true;
621 Expanded.BraceWrapping.AfterStruct = true;
Krasimir Georgievd6ce9372017-09-15 11:23:50 +0000622 Expanded.BraceWrapping.AfterExternBlock = true;
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000623 Expanded.BraceWrapping.BeforeCatch = true;
624 Expanded.BraceWrapping.BeforeElse = true;
625 break;
626 case FormatStyle::BS_GNU:
Manuel Klimek89628f62017-09-20 09:51:03 +0000627 Expanded.BraceWrapping = {true, true, true, true, true, true, true, true,
628 true, true, true, true, true, true, true};
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000629 break;
630 case FormatStyle::BS_WebKit:
631 Expanded.BraceWrapping.AfterFunction = true;
632 break;
633 default:
634 break;
635 }
636 return Expanded;
637}
638
Jordan Rupprecht8bd97e72019-02-28 19:16:45 +0000639FormatStyle getLLVMStyle(FormatStyle::LanguageKind Language) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000640 FormatStyle LLVMStyle;
Jordan Rupprecht8bd97e72019-02-28 19:16:45 +0000641 LLVMStyle.Language = Language;
Daniel Jasperf7935112012-12-03 18:12:45 +0000642 LLVMStyle.AccessModifierOffset = -2;
Daniel Jasper7fdbb3f2017-05-08 15:08:00 +0000643 LLVMStyle.AlignEscapedNewlines = FormatStyle::ENAS_Right;
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000644 LLVMStyle.AlignAfterOpenBracket = FormatStyle::BAS_Align;
Daniel Jasper3219e432014-12-02 13:24:51 +0000645 LLVMStyle.AlignOperands = true;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000646 LLVMStyle.AlignTrailingComments = true;
Daniel Jaspera44991332015-04-29 13:06:49 +0000647 LLVMStyle.AlignConsecutiveAssignments = false;
Daniel Jaspere12597c2015-10-01 10:06:54 +0000648 LLVMStyle.AlignConsecutiveDeclarations = false;
Paul Hoadc6deae42019-03-23 14:37:58 +0000649 LLVMStyle.AllowAllArgumentsOnNextLine = true;
650 LLVMStyle.AllowAllConstructorInitializersOnNextLine = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000651 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd74cf402014-04-08 12:46:38 +0000652 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
Daniel Jasper17605d32014-05-14 09:33:35 +0000653 LLVMStyle.AllowShortBlocksOnASingleLine = false;
Daniel Jasperb87899b2014-09-10 13:11:45 +0000654 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
Paul Hoad15000a12019-03-13 08:26:39 +0000655 LLVMStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000656 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Zachary Turner448592e2015-12-18 22:20:15 +0000657 LLVMStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000658 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
Alexander Kornienko58611712013-07-04 12:02:44 +0000659 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Francois Ferrand58e6fe52018-05-16 08:25:03 +0000660 LLVMStyle.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_MultiLine;
Daniel Jasper18210d72014-10-09 09:52:05 +0000661 LLVMStyle.BinPackArguments = true;
Francois Ferrande56a8292017-06-14 12:29:47 +0000662 LLVMStyle.BinPackParameters = true;
Daniel Jasperac043c92014-09-15 11:11:00 +0000663 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
Daniel Jasper165b29e2013-11-08 00:57:11 +0000664 LLVMStyle.BreakBeforeTernaryOperators = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000665 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Manuel Klimek89628f62017-09-20 09:51:03 +0000666 LLVMStyle.BraceWrapping = {false, false, false, false, false,
667 false, false, false, false, false,
668 false, false, true, true, true};
Nico Weber2cd92f12015-10-15 16:03:01 +0000669 LLVMStyle.BreakAfterJavaFieldAnnotations = false;
Francois Ferranda6b6d512017-05-24 11:36:58 +0000670 LLVMStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
Francois Ferrand6bb103f2018-06-11 14:41:26 +0000671 LLVMStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
Daniel Jaspere1a7b762016-02-01 11:21:02 +0000672 LLVMStyle.BreakStringLiterals = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000673 LLVMStyle.ColumnLimit = 80;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000674 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
Francois Ferrande56a8292017-06-14 12:29:47 +0000675 LLVMStyle.CompactNamespaces = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000676 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000677 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000678 LLVMStyle.ContinuationIndentWidth = 4;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000679 LLVMStyle.Cpp11BracedListStyle = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000680 LLVMStyle.DerivePointerAlignment = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000681 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Krasimir Georgiev32eaa862017-03-01 15:35:39 +0000682 LLVMStyle.FixNamespaceComments = true;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000683 LLVMStyle.ForEachMacros.push_back("foreach");
684 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
685 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
Eric Liu9d92c022018-05-14 19:51:33 +0000686 LLVMStyle.IncludeStyle.IncludeCategories = {
687 {"^\"(llvm|llvm-c|clang|clang-c)/", 2},
688 {"^(<|\"(gtest|gmock|isl|json)/)", 3},
689 {".*", 1}};
690 LLVMStyle.IncludeStyle.IncludeIsMainRegex = "(Test)?$";
691 LLVMStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Preserve;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000692 LLVMStyle.IndentCaseLabels = false;
Krasimir Georgievad47c902017-08-30 14:34:57 +0000693 LLVMStyle.IndentPPDirectives = FormatStyle::PPDIS_None;
Daniel Jasperc75e1ef2014-07-09 08:42:42 +0000694 LLVMStyle.IndentWrappedFunctionNames = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000695 LLVMStyle.IndentWidth = 2;
Martin Probstfb2342d2016-06-13 17:50:10 +0000696 LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
697 LLVMStyle.JavaScriptWrapImports = true;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000698 LLVMStyle.TabWidth = 8;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000699 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000700 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000701 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Ben Hamilton4dc658c2018-02-02 20:15:14 +0000702 LLVMStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Auto;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000703 LLVMStyle.ObjCBlockIndentWidth = 2;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000704 LLVMStyle.ObjCSpaceAfterProperty = false;
Nico Webera6087752013-01-10 20:12:55 +0000705 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000706 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000707 LLVMStyle.SpacesBeforeTrailingComments = 1;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000708 LLVMStyle.Standard = FormatStyle::LS_Cpp11;
Alexander Kornienko3c3d09c2013-09-27 16:14:22 +0000709 LLVMStyle.UseTab = FormatStyle::UT_Never;
Daniel Jaspera0a50392015-12-01 13:28:53 +0000710 LLVMStyle.ReflowComments = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000711 LLVMStyle.SpacesInParentheses = false;
Daniel Jasperad981f82014-08-26 11:41:14 +0000712 LLVMStyle.SpacesInSquareBrackets = false;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000713 LLVMStyle.SpaceInEmptyParentheses = false;
Daniel Jasperb2e10a52014-01-15 15:09:08 +0000714 LLVMStyle.SpacesInContainerLiterals = true;
Daniel Jasperb55acad2013-08-20 12:36:34 +0000715 LLVMStyle.SpacesInCStyleCastParentheses = false;
Daniel Jasperdb986eb2014-09-03 07:37:29 +0000716 LLVMStyle.SpaceAfterCStyleCast = false;
Sylvestre Ledru83bbd572016-08-09 14:24:40 +0000717 LLVMStyle.SpaceAfterTemplateKeyword = true;
Francois Ferrand2a9ea782018-03-01 10:09:13 +0000718 LLVMStyle.SpaceBeforeCtorInitializerColon = true;
719 LLVMStyle.SpaceBeforeInheritanceColon = true;
Alexander Kornienkofdca83d2013-12-10 10:18:34 +0000720 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
Francois Ferrand2a9ea782018-03-01 10:09:13 +0000721 LLVMStyle.SpaceBeforeRangeBasedForLoopColon = true;
Daniel Jasperd94bff32013-09-25 15:15:02 +0000722 LLVMStyle.SpaceBeforeAssignmentOperators = true;
Hans Wennborgbfc34062018-06-14 08:01:09 +0000723 LLVMStyle.SpaceBeforeCpp11BracedList = false;
Daniel Jasperdd978ae2013-10-29 14:52:02 +0000724 LLVMStyle.SpacesInAngles = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000725
Francois Ferrand9976efa2017-05-22 08:28:17 +0000726 LLVMStyle.PenaltyBreakAssignment = prec::Assignment;
Daniel Jasper19a541e2013-12-19 16:45:34 +0000727 LLVMStyle.PenaltyBreakComment = 300;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000728 LLVMStyle.PenaltyBreakFirstLessLess = 120;
729 LLVMStyle.PenaltyBreakString = 1000;
730 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000731 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000732 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
Francois Ferrand58e6fe52018-05-16 08:25:03 +0000733 LLVMStyle.PenaltyBreakTemplateDeclaration = prec::Relational;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000734
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000735 LLVMStyle.DisableFormat = false;
Daniel Jasperda446772015-11-16 12:38:56 +0000736 LLVMStyle.SortIncludes = true;
Krasimir Georgievac16a202017-06-23 11:46:03 +0000737 LLVMStyle.SortUsingDeclarations = true;
Francois Ferrand6f40e212018-10-02 16:37:51 +0000738 LLVMStyle.StatementMacros.push_back("Q_UNUSED");
739 LLVMStyle.StatementMacros.push_back("QT_REQUIRE_VERSION");
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000740
Jordan Rupprecht7f514162019-03-01 00:12:18 +0000741 // Defaults that differ when not C++.
742 if (Language == FormatStyle::LK_TableGen) {
743 LLVMStyle.SpacesInContainerLiterals = false;
744 }
745
Daniel Jasperf7935112012-12-03 18:12:45 +0000746 return LLVMStyle;
747}
748
Nico Weber514ecc82014-02-02 20:50:45 +0000749FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
Krasimir Georgiev26b144c2017-07-03 15:05:14 +0000750 if (Language == FormatStyle::LK_TextProto) {
751 FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_Proto);
752 GoogleStyle.Language = FormatStyle::LK_TextProto;
Krasimir Georgieveda222e2018-01-24 11:18:39 +0000753
Krasimir Georgiev26b144c2017-07-03 15:05:14 +0000754 return GoogleStyle;
755 }
756
Jordan Rupprecht8bd97e72019-02-28 19:16:45 +0000757 FormatStyle GoogleStyle = getLLVMStyle(Language);
Nico Weber514ecc82014-02-02 20:50:45 +0000758
Daniel Jasperf7935112012-12-03 18:12:45 +0000759 GoogleStyle.AccessModifierOffset = -1;
Daniel Jasper7fdbb3f2017-05-08 15:08:00 +0000760 GoogleStyle.AlignEscapedNewlines = FormatStyle::ENAS_Left;
Paul Hoad15000a12019-03-13 08:26:39 +0000761 GoogleStyle.AllowShortIfStatementsOnASingleLine =
762 FormatStyle::SIS_WithoutElse;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000763 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000764 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Francois Ferrand58e6fe52018-05-16 08:25:03 +0000765 GoogleStyle.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000766 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000767 GoogleStyle.DerivePointerAlignment = true;
Eric Liu9d92c022018-05-14 19:51:33 +0000768 GoogleStyle.IncludeStyle.IncludeCategories = {
Krasimir Georgieva84e7872017-09-26 14:58:29 +0000769 {"^<ext/.*\\.h>", 2}, {"^<.*\\.h>", 1}, {"^<.*", 2}, {".*", 3}};
Eric Liu9d92c022018-05-14 19:51:33 +0000770 GoogleStyle.IncludeStyle.IncludeIsMainRegex = "([-_](test|unittest))?$";
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000771 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspera26fc5c2014-03-21 13:43:14 +0000772 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
Ben Hamilton3a47fdd2018-02-08 01:49:10 +0000773 GoogleStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000774 GoogleStyle.ObjCSpaceAfterProperty = false;
Ben Hamiltonf84f1182018-01-18 18:37:16 +0000775 GoogleStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000776 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
Krasimir Georgiev5559cc32018-04-25 14:56:19 +0000777 GoogleStyle.RawStringFormats = {
Krasimir Georgiev4527f132018-01-17 12:24:59 +0000778 {
Krasimir Georgiev5559cc32018-04-25 14:56:19 +0000779 FormatStyle::LK_Cpp,
780 /*Delimiters=*/
781 {
782 "cc",
783 "CC",
784 "cpp",
785 "Cpp",
786 "CPP",
787 "c++",
788 "C++",
789 },
790 /*EnclosingFunctionNames=*/
791 {},
792 /*CanonicalDelimiter=*/"",
793 /*BasedOnStyle=*/"google",
Krasimir Georgiev4527f132018-01-17 12:24:59 +0000794 },
Krasimir Georgiev5559cc32018-04-25 14:56:19 +0000795 {
796 FormatStyle::LK_TextProto,
797 /*Delimiters=*/
798 {
799 "pb",
800 "PB",
801 "proto",
802 "PROTO",
803 },
804 /*EnclosingFunctionNames=*/
Krasimir Georgiev42948e32018-06-26 12:00:14 +0000805 {
Krasimir Georgiev42948e32018-06-26 12:00:14 +0000806 "EqualsProto",
Krasimir Georgiev61f46f22018-06-29 14:25:25 +0000807 "EquivToProto",
Krasimir Georgievce0b8d62018-08-01 12:35:23 +0000808 "PARSE_PARTIAL_TEXT_PROTO",
Krasimir Georgiev61f46f22018-06-29 14:25:25 +0000809 "PARSE_TEST_PROTO",
810 "PARSE_TEXT_PROTO",
811 "ParseTextOrDie",
Krasimir Georgievce0b8d62018-08-01 12:35:23 +0000812 "ParseTextProtoOrDie",
Krasimir Georgiev42948e32018-06-26 12:00:14 +0000813 },
Krasimir Georgiev5559cc32018-04-25 14:56:19 +0000814 /*CanonicalDelimiter=*/"",
815 /*BasedOnStyle=*/"google",
816 },
817 };
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000818 GoogleStyle.SpacesBeforeTrailingComments = 2;
819 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000820
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000821 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper33b909c2013-10-25 14:29:37 +0000822 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000823
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000824 if (Language == FormatStyle::LK_Java) {
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000825 GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
Daniel Jasper3219e432014-12-02 13:24:51 +0000826 GoogleStyle.AlignOperands = false;
Daniel Jasperfd4ed182015-01-04 20:40:45 +0000827 GoogleStyle.AlignTrailingComments = false;
Daniel Jasper9e709352014-11-26 10:43:58 +0000828 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
Paul Hoad15000a12019-03-13 08:26:39 +0000829 GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
Daniel Jasper1cd3c712015-01-14 12:24:59 +0000830 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000831 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
832 GoogleStyle.ColumnLimit = 100;
833 GoogleStyle.SpaceAfterCStyleCast = true;
Daniel Jasper61d81972014-11-14 08:22:46 +0000834 GoogleStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000835 } else if (Language == FormatStyle::LK_JavaScript) {
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000836 GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
Daniel Jasper41a2bf72015-12-21 13:52:19 +0000837 GoogleStyle.AlignOperands = false;
Daniel Jasper28d8a5a2016-09-07 23:01:13 +0000838 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000839 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere551bb72014-11-05 17:22:31 +0000840 GoogleStyle.BreakBeforeTernaryOperators = false;
Krasimir Georgiev6a5c95b2018-07-30 08:45:45 +0000841 // taze:, triple slash directives (`/// <...`), @see, which is commonly
842 // followed by overlong URLs.
843 GoogleStyle.CommentPragmas = "(taze:|^/[ \t]*<|@see)";
Daniel Jasper8f83a902014-05-09 10:28:58 +0000844 GoogleStyle.MaxEmptyLinesToKeep = 3;
Martin Probstece8c0c2016-06-13 16:41:28 +0000845 GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
Nico Weber514ecc82014-02-02 20:50:45 +0000846 GoogleStyle.SpacesInContainerLiterals = false;
Daniel Jasperabd1f572016-03-02 22:44:03 +0000847 GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single;
Martin Probst0cd74ee2016-06-13 16:39:50 +0000848 GoogleStyle.JavaScriptWrapImports = false;
Nico Weber514ecc82014-02-02 20:50:45 +0000849 } else if (Language == FormatStyle::LK_Proto) {
Daniel Jasper67e65212018-08-15 19:07:55 +0000850 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
Daniel Jasper9c95dfe2018-03-12 10:32:18 +0000851 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jasper783bac62014-04-15 09:54:30 +0000852 GoogleStyle.SpacesInContainerLiterals = false;
Krasimir Georgievc2091802018-01-31 10:14:10 +0000853 GoogleStyle.Cpp11BracedListStyle = false;
Krasimir Georgiev374e6de2018-02-08 10:47:12 +0000854 // This affects protocol buffer options specifications and text protos.
855 // Text protos are currently mostly formatted inside C++ raw string literals
856 // and often the current breaking behavior of string literals is not
857 // beneficial there. Investigate turning this on once proper string reflow
858 // has been implemented.
859 GoogleStyle.BreakStringLiterals = false;
Daniel Jasper03a04fe2016-12-12 12:42:29 +0000860 } else if (Language == FormatStyle::LK_ObjC) {
Ben Hamilton1ab722e2018-06-14 17:30:10 +0000861 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jasper03a04fe2016-12-12 12:42:29 +0000862 GoogleStyle.ColumnLimit = 100;
Nico Weber514ecc82014-02-02 20:50:45 +0000863 }
864
Daniel Jasperf7935112012-12-03 18:12:45 +0000865 return GoogleStyle;
866}
867
Nico Weber514ecc82014-02-02 20:50:45 +0000868FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
869 FormatStyle ChromiumStyle = getGoogleStyle(Language);
Nico Weber450425c2014-11-26 16:43:18 +0000870 if (Language == FormatStyle::LK_Java) {
Paul Hoad15000a12019-03-13 08:26:39 +0000871 ChromiumStyle.AllowShortIfStatementsOnASingleLine =
872 FormatStyle::SIS_WithoutElse;
Nico Weber2cd92f12015-10-15 16:03:01 +0000873 ChromiumStyle.BreakAfterJavaFieldAnnotations = true;
Nico Weber450425c2014-11-26 16:43:18 +0000874 ChromiumStyle.ContinuationIndentWidth = 8;
Nico Weber2cd92f12015-10-15 16:03:01 +0000875 ChromiumStyle.IndentWidth = 4;
Krasimir Georgiev7e91b032018-10-05 17:19:26 +0000876 // See styleguide for import groups:
877 // https://chromium.googlesource.com/chromium/src/+/master/styleguide/java/java.md#Import-Order
878 ChromiumStyle.JavaImportGroups = {
Paul Hoad5bcf99b2019-03-01 09:09:54 +0000879 "android", "com", "dalvik",
880 "junit", "org", "com.google.android.apps.chrome",
881 "org.chromium", "java", "javax",
Krasimir Georgiev7e91b032018-10-05 17:19:26 +0000882 };
883 ChromiumStyle.SortIncludes = true;
Nico Weberea649692017-01-04 02:33:36 +0000884 } else if (Language == FormatStyle::LK_JavaScript) {
Paul Hoad15000a12019-03-13 08:26:39 +0000885 ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
Nico Weberea649692017-01-04 02:33:36 +0000886 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Nico Weber450425c2014-11-26 16:43:18 +0000887 } else {
888 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
889 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Paul Hoad15000a12019-03-13 08:26:39 +0000890 ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
Nico Weber450425c2014-11-26 16:43:18 +0000891 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
892 ChromiumStyle.BinPackParameters = false;
893 ChromiumStyle.DerivePointerAlignment = false;
Nico Weber9e2bc302017-01-31 18:42:05 +0000894 if (Language == FormatStyle::LK_ObjC)
895 ChromiumStyle.ColumnLimit = 80;
Nico Weber450425c2014-11-26 16:43:18 +0000896 }
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000897 return ChromiumStyle;
898}
899
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000900FormatStyle getMozillaStyle() {
901 FormatStyle MozillaStyle = getLLVMStyle();
902 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000903 MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
Manuel Klimek89628f62017-09-20 09:51:03 +0000904 MozillaStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000905 MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
906 FormatStyle::DRTBS_TopLevel;
Francois Ferrand58e6fe52018-05-16 08:25:03 +0000907 MozillaStyle.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
Sylvestre Ledrudcb038d2016-12-14 16:09:29 +0000908 MozillaStyle.BinPackParameters = false;
909 MozillaStyle.BinPackArguments = false;
Birunthan Mohanathas305fa9c2015-07-12 03:13:54 +0000910 MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
Francois Ferranda6b6d512017-05-24 11:36:58 +0000911 MozillaStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
Francois Ferrand6bb103f2018-06-11 14:41:26 +0000912 MozillaStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
Birunthan Mohanathasa0810022015-06-29 15:18:58 +0000913 MozillaStyle.ConstructorInitializerIndentWidth = 2;
914 MozillaStyle.ContinuationIndentWidth = 2;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000915 MozillaStyle.Cpp11BracedListStyle = false;
Krasimir Georgiev32eaa862017-03-01 15:35:39 +0000916 MozillaStyle.FixNamespaceComments = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000917 MozillaStyle.IndentCaseLabels = true;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000918 MozillaStyle.ObjCSpaceAfterProperty = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000919 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
920 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper553d4872014-06-17 12:40:34 +0000921 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
Sylvestre Ledru83bbd572016-08-09 14:24:40 +0000922 MozillaStyle.SpaceAfterTemplateKeyword = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000923 return MozillaStyle;
924}
925
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000926FormatStyle getWebKitStyle() {
927 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000928 Style.AccessModifierOffset = -4;
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000929 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
Daniel Jasper3219e432014-12-02 13:24:51 +0000930 Style.AlignOperands = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000931 Style.AlignTrailingComments = false;
Daniel Jasperac043c92014-09-15 11:11:00 +0000932 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Roman Kashitsyn291f64f2015-08-10 13:43:19 +0000933 Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
Francois Ferranda6b6d512017-05-24 11:36:58 +0000934 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000935 Style.Cpp11BracedListStyle = false;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000936 Style.ColumnLimit = 0;
Krasimir Georgiev32eaa862017-03-01 15:35:39 +0000937 Style.FixNamespaceComments = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000938 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000939 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasper50d634b2014-10-28 16:53:38 +0000940 Style.ObjCBlockIndentWidth = 4;
Daniel Jaspere9beea22014-01-28 15:20:33 +0000941 Style.ObjCSpaceAfterProperty = true;
Daniel Jasper553d4872014-06-17 12:40:34 +0000942 Style.PointerAlignment = FormatStyle::PAS_Left;
Hans Wennborgbfc34062018-06-14 08:01:09 +0000943 Style.SpaceBeforeCpp11BracedList = true;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000944 return Style;
945}
946
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000947FormatStyle getGNUStyle() {
948 FormatStyle Style = getLLVMStyle();
Birunthan Mohanathasa0388a82015-06-29 15:30:42 +0000949 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
Zachary Turner448592e2015-12-18 22:20:15 +0000950 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
Daniel Jasperac043c92014-09-15 11:11:00 +0000951 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000952 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000953 Style.BreakBeforeTernaryOperators = true;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000954 Style.Cpp11BracedListStyle = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000955 Style.ColumnLimit = 79;
Krasimir Georgiev32eaa862017-03-01 15:35:39 +0000956 Style.FixNamespaceComments = false;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000957 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
Chandler Carruthf8b72662014-03-02 12:37:31 +0000958 Style.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +0000959 return Style;
960}
961
Paul Hoadcbb726d2019-03-21 13:09:22 +0000962FormatStyle getMicrosoftStyle(FormatStyle::LanguageKind Language) {
963 FormatStyle Style = getLLVMStyle();
964 Style.ColumnLimit = 120;
965 Style.TabWidth = 4;
966 Style.IndentWidth = 4;
967 Style.UseTab = FormatStyle::UT_Never;
968 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
969 Style.BraceWrapping.AfterClass = true;
970 Style.BraceWrapping.AfterControlStatement = true;
971 Style.BraceWrapping.AfterEnum = true;
972 Style.BraceWrapping.AfterFunction = true;
973 Style.BraceWrapping.AfterNamespace = true;
974 Style.BraceWrapping.AfterObjCDeclaration = true;
975 Style.BraceWrapping.AfterStruct = true;
976 Style.BraceWrapping.AfterExternBlock = true;
977 Style.BraceWrapping.BeforeCatch = true;
978 Style.BraceWrapping.BeforeElse = true;
979 Style.PenaltyReturnTypeOnItsOwnLine = 1000;
980 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
981 Style.AllowShortBlocksOnASingleLine = false;
982 Style.AllowShortCaseLabelsOnASingleLine = false;
983 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
984 Style.AllowShortLoopsOnASingleLine = false;
985 return Style;
986}
987
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000988FormatStyle getNoStyle() {
989 FormatStyle NoStyle = getLLVMStyle();
990 NoStyle.DisableFormat = true;
Daniel Jasperda446772015-11-16 12:38:56 +0000991 NoStyle.SortIncludes = false;
Krasimir Georgievac16a202017-06-23 11:46:03 +0000992 NoStyle.SortUsingDeclarations = false;
Daniel Jasperc64b09a2014-05-22 15:12:22 +0000993 return NoStyle;
994}
995
Alexander Kornienkoc1637f12013-12-10 11:28:13 +0000996bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
997 FormatStyle *Style) {
998 if (Name.equals_lower("llvm")) {
Jordan Rupprecht55881d52019-03-13 21:13:01 +0000999 *Style = getLLVMStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001000 } else if (Name.equals_lower("chromium")) {
Nico Weber514ecc82014-02-02 20:50:45 +00001001 *Style = getChromiumStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001002 } else if (Name.equals_lower("mozilla")) {
Alexander Kornienko006b5c82013-05-19 00:53:30 +00001003 *Style = getMozillaStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001004 } else if (Name.equals_lower("google")) {
Nico Weber514ecc82014-02-02 20:50:45 +00001005 *Style = getGoogleStyle(Language);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001006 } else if (Name.equals_lower("webkit")) {
Daniel Jasperffefb3d2013-07-24 13:10:59 +00001007 *Style = getWebKitStyle();
Alexander Kornienkofe7a57f2013-12-10 15:42:15 +00001008 } else if (Name.equals_lower("gnu")) {
1009 *Style = getGNUStyle();
Paul Hoadcbb726d2019-03-21 13:09:22 +00001010 } else if (Name.equals_lower("microsoft")) {
1011 *Style = getMicrosoftStyle(Language);
Daniel Jasperc64b09a2014-05-22 15:12:22 +00001012 } else if (Name.equals_lower("none")) {
1013 *Style = getNoStyle();
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001014 } else {
Alexander Kornienko006b5c82013-05-19 00:53:30 +00001015 return false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001016 }
Alexander Kornienkod6538332013-05-07 15:32:14 +00001017
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001018 Style->Language = Language;
Alexander Kornienko006b5c82013-05-19 00:53:30 +00001019 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +00001020}
1021
Rafael Espindolac0809172014-06-12 14:02:15 +00001022std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001023 assert(Style);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001024 FormatStyle::LanguageKind Language = Style->Language;
1025 assert(Language != FormatStyle::LK_None);
Alexander Kornienko06e00332013-05-20 15:18:01 +00001026 if (Text.trim().empty())
Rafael Espindolad0136702014-06-12 02:50:04 +00001027 return make_error_code(ParseError::Error);
Krasimir Georgiev54076fe2018-01-15 12:06:16 +00001028 Style->StyleSet.Clear();
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001029 std::vector<FormatStyle> Styles;
Alexander Kornienkod6538332013-05-07 15:32:14 +00001030 llvm::yaml::Input Input(Text);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001031 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
1032 // values for the fields, keys for which are missing from the configuration.
1033 // Mapping also uses the context to get the language to find the correct
1034 // base style.
1035 Input.setContext(Style);
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001036 Input >> Styles;
1037 if (Input.error())
1038 return Input.error();
1039
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001040 for (unsigned i = 0; i < Styles.size(); ++i) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001041 // Ensures that only the first configuration can skip the Language option.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001042 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
Rafael Espindolad0136702014-06-12 02:50:04 +00001043 return make_error_code(ParseError::Error);
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001044 // Ensure that each language is configured at most once.
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001045 for (unsigned j = 0; j < i; ++j) {
1046 if (Styles[i].Language == Styles[j].Language) {
Nicola Zaghen3538b392018-05-15 13:30:56 +00001047 LLVM_DEBUG(llvm::dbgs()
1048 << "Duplicate languages in the config file on positions "
1049 << j << " and " << i << "\n");
Rafael Espindolad0136702014-06-12 02:50:04 +00001050 return make_error_code(ParseError::Error);
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001051 }
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001052 }
1053 }
1054 // Look for a suitable configuration starting from the end, so we can
1055 // find the configuration for the specific language first, and the default
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001056 // configuration (which can only be at slot 0) after it.
Krasimir Georgiev54076fe2018-01-15 12:06:16 +00001057 FormatStyle::FormatStyleSet StyleSet;
1058 bool LanguageFound = false;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00001059 for (int i = Styles.size() - 1; i >= 0; --i) {
Krasimir Georgiev54076fe2018-01-15 12:06:16 +00001060 if (Styles[i].Language != FormatStyle::LK_None)
1061 StyleSet.Add(Styles[i]);
1062 if (Styles[i].Language == Language)
1063 LanguageFound = true;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00001064 }
Krasimir Georgiev54076fe2018-01-15 12:06:16 +00001065 if (!LanguageFound) {
1066 if (Styles.empty() || Styles[0].Language != FormatStyle::LK_None)
1067 return make_error_code(ParseError::Unsuitable);
1068 FormatStyle DefaultStyle = Styles[0];
1069 DefaultStyle.Language = Language;
1070 StyleSet.Add(std::move(DefaultStyle));
1071 }
1072 *Style = *StyleSet.Get(Language);
1073 return make_error_code(ParseError::Success);
Alexander Kornienkod6538332013-05-07 15:32:14 +00001074}
1075
1076std::string configurationAsText(const FormatStyle &Style) {
1077 std::string Text;
1078 llvm::raw_string_ostream Stream(Text);
1079 llvm::yaml::Output Output(Stream);
1080 // We use the same mapping method for input and output, so we need a non-const
1081 // reference here.
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001082 FormatStyle NonConstStyle = expandPresets(Style);
Alexander Kornienkod6538332013-05-07 15:32:14 +00001083 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +00001084 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +00001085}
1086
Krasimir Georgiev54076fe2018-01-15 12:06:16 +00001087llvm::Optional<FormatStyle>
1088FormatStyle::FormatStyleSet::Get(FormatStyle::LanguageKind Language) const {
1089 if (!Styles)
1090 return None;
1091 auto It = Styles->find(Language);
1092 if (It == Styles->end())
1093 return None;
1094 FormatStyle Style = It->second;
1095 Style.StyleSet = *this;
1096 return Style;
1097}
1098
1099void FormatStyle::FormatStyleSet::Add(FormatStyle Style) {
1100 assert(Style.Language != LK_None &&
1101 "Cannot add a style for LK_None to a StyleSet");
1102 assert(
1103 !Style.StyleSet.Styles &&
1104 "Cannot add a style associated with an existing StyleSet to a StyleSet");
1105 if (!Styles)
1106 Styles = std::make_shared<MapType>();
1107 (*Styles)[Style.Language] = std::move(Style);
1108}
1109
Paul Hoad5bcf99b2019-03-01 09:09:54 +00001110void FormatStyle::FormatStyleSet::Clear() { Styles.reset(); }
Krasimir Georgiev54076fe2018-01-15 12:06:16 +00001111
1112llvm::Optional<FormatStyle>
1113FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind Language) const {
1114 return StyleSet.Get(Language);
1115}
1116
Craig Topperaf35e852013-06-30 22:29:28 +00001117namespace {
1118
Daniel Jasper496c1992016-09-07 22:48:53 +00001119class JavaScriptRequoter : public TokenAnalyzer {
Eric Liu4cfb88a2016-04-25 15:09:22 +00001120public:
Daniel Jasper496c1992016-09-07 22:48:53 +00001121 JavaScriptRequoter(const Environment &Env, const FormatStyle &Style)
1122 : TokenAnalyzer(Env, Style) {}
Eric Liu4cfb88a2016-04-25 15:09:22 +00001123
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001124 std::pair<tooling::Replacements, unsigned>
Eric Liu4cfb88a2016-04-25 15:09:22 +00001125 analyze(TokenAnnotator &Annotator,
1126 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
Martin Probsta9855af2016-09-02 14:29:48 +00001127 FormatTokenLexer &Tokens) override {
Manuel Klimek0dddcf72018-04-23 09:34:26 +00001128 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
Daniel Jasper496c1992016-09-07 22:48:53 +00001129 tooling::Replacements Result;
1130 requoteJSStringLiteral(AnnotatedLines, Result);
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001131 return {Result, 0};
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001132 }
1133
1134private:
Daniel Jasper496c1992016-09-07 22:48:53 +00001135 // Replaces double/single-quoted string literal as appropriate, re-escaping
1136 // the contents in the process.
Daniel Jasper97439922016-03-17 13:03:41 +00001137 void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
Eric Liu4cfb88a2016-04-25 15:09:22 +00001138 tooling::Replacements &Result) {
Daniel Jasper97439922016-03-17 13:03:41 +00001139 for (AnnotatedLine *Line : Lines) {
1140 requoteJSStringLiteral(Line->Children, Result);
1141 if (!Line->Affected)
1142 continue;
1143 for (FormatToken *FormatTok = Line->First; FormatTok;
1144 FormatTok = FormatTok->Next) {
1145 StringRef Input = FormatTok->TokenText;
Martin Probsta1669792016-05-12 11:20:32 +00001146 if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
Daniel Jasper97439922016-03-17 13:03:41 +00001147 // NB: testing for not starting with a double quote to avoid
Daniel Jasper496c1992016-09-07 22:48:53 +00001148 // breaking `template strings`.
Eric Liu635423e2016-04-28 07:52:03 +00001149 (Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
Daniel Jasper97439922016-03-17 13:03:41 +00001150 !Input.startswith("\"")) ||
Eric Liu635423e2016-04-28 07:52:03 +00001151 (Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
Daniel Jasper97439922016-03-17 13:03:41 +00001152 !Input.startswith("\'")))
1153 continue;
1154
1155 // Change start and end quote.
Eric Liu635423e2016-04-28 07:52:03 +00001156 bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
Daniel Jasper97439922016-03-17 13:03:41 +00001157 SourceLocation Start = FormatTok->Tok.getLocation();
1158 auto Replace = [&](SourceLocation Start, unsigned Length,
1159 StringRef ReplacementText) {
Eric Liu40ef2fb2016-08-01 10:16:37 +00001160 auto Err = Result.add(tooling::Replacement(
1161 Env.getSourceManager(), Start, Length, ReplacementText));
1162 // FIXME: handle error. For now, print error message and skip the
1163 // replacement for release version.
Piotr Padlewski1ec383c2016-12-23 11:40:44 +00001164 if (Err) {
Eric Liu40ef2fb2016-08-01 10:16:37 +00001165 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Piotr Padlewski1ec383c2016-12-23 11:40:44 +00001166 assert(false);
1167 }
Daniel Jasper97439922016-03-17 13:03:41 +00001168 };
1169 Replace(Start, 1, IsSingle ? "'" : "\"");
1170 Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
1171 IsSingle ? "'" : "\"");
1172
1173 // Escape internal quotes.
Daniel Jasper97439922016-03-17 13:03:41 +00001174 bool Escaped = false;
1175 for (size_t i = 1; i < Input.size() - 1; i++) {
1176 switch (Input[i]) {
Eric Liu4cfb88a2016-04-25 15:09:22 +00001177 case '\\':
1178 if (!Escaped && i + 1 < Input.size() &&
1179 ((IsSingle && Input[i + 1] == '"') ||
1180 (!IsSingle && Input[i + 1] == '\''))) {
1181 // Remove this \, it's escaping a " or ' that no longer needs
1182 // escaping
Eric Liu4cfb88a2016-04-25 15:09:22 +00001183 Replace(Start.getLocWithOffset(i), 1, "");
1184 continue;
1185 }
1186 Escaped = !Escaped;
1187 break;
1188 case '\"':
1189 case '\'':
1190 if (!Escaped && IsSingle == (Input[i] == '\'')) {
1191 // Escape the quote.
1192 Replace(Start.getLocWithOffset(i), 0, "\\");
Eric Liu4cfb88a2016-04-25 15:09:22 +00001193 }
1194 Escaped = false;
1195 break;
1196 default:
1197 Escaped = false;
1198 break;
Daniel Jasper97439922016-03-17 13:03:41 +00001199 }
1200 }
Daniel Jasper97439922016-03-17 13:03:41 +00001201 }
1202 }
1203 }
Daniel Jasper496c1992016-09-07 22:48:53 +00001204};
1205
1206class Formatter : public TokenAnalyzer {
1207public:
1208 Formatter(const Environment &Env, const FormatStyle &Style,
Krasimir Georgievbcda54b2017-04-21 14:35:20 +00001209 FormattingAttemptStatus *Status)
1210 : TokenAnalyzer(Env, Style), Status(Status) {}
Daniel Jasper496c1992016-09-07 22:48:53 +00001211
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001212 std::pair<tooling::Replacements, unsigned>
Daniel Jasper496c1992016-09-07 22:48:53 +00001213 analyze(TokenAnnotator &Annotator,
1214 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1215 FormatTokenLexer &Tokens) override {
1216 tooling::Replacements Result;
1217 deriveLocalStyle(AnnotatedLines);
Manuel Klimek0dddcf72018-04-23 09:34:26 +00001218 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
Daniel Jasper496c1992016-09-07 22:48:53 +00001219 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1220 Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
1221 }
1222 Annotator.setCommentLineLevels(AnnotatedLines);
1223
1224 WhitespaceManager Whitespaces(
1225 Env.getSourceManager(), Style,
1226 inputUsesCRLF(Env.getSourceManager().getBufferData(Env.getFileID())));
1227 ContinuationIndenter Indenter(Style, Tokens.getKeywords(),
1228 Env.getSourceManager(), Whitespaces, Encoding,
1229 BinPackInconclusiveFunctions);
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001230 unsigned Penalty =
1231 UnwrappedLineFormatter(&Indenter, &Whitespaces, Style,
1232 Tokens.getKeywords(), Env.getSourceManager(),
1233 Status)
1234 .format(AnnotatedLines, /*DryRun=*/false,
1235 /*AdditionalIndent=*/0,
1236 /*FixBadIndentation=*/false,
1237 /*FirstStartColumn=*/Env.getFirstStartColumn(),
1238 /*NextStartColumn=*/Env.getNextStartColumn(),
1239 /*LastStartColumn=*/Env.getLastStartColumn());
Daniel Jasper496c1992016-09-07 22:48:53 +00001240 for (const auto &R : Whitespaces.generateReplacements())
1241 if (Result.add(R))
Krasimir Georgieve56e9a42017-10-30 14:30:14 +00001242 return std::make_pair(Result, 0);
1243 return std::make_pair(Result, Penalty);
Daniel Jasper496c1992016-09-07 22:48:53 +00001244 }
1245
1246private:
Alexander Kornienko9e649af2013-09-11 12:25:57 +00001247 static bool inputUsesCRLF(StringRef Text) {
1248 return Text.count('\r') * 2 > Text.count('\n');
1249 }
1250
Daniel Jasper352f0df2015-07-18 16:35:30 +00001251 bool
1252 hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
Eric Liu4cfb88a2016-04-25 15:09:22 +00001253 for (const AnnotatedLine *Line : Lines) {
Daniel Jasper352f0df2015-07-18 16:35:30 +00001254 if (hasCpp03IncompatibleFormat(Line->Children))
1255 return true;
1256 for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
1257 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1258 if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
1259 return true;
1260 if (Tok->is(TT_TemplateCloser) &&
1261 Tok->Previous->is(TT_TemplateCloser))
1262 return true;
1263 }
1264 }
1265 }
1266 return false;
1267 }
1268
1269 int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1270 int AlignmentDiff = 0;
Eric Liu4cfb88a2016-04-25 15:09:22 +00001271 for (const AnnotatedLine *Line : Lines) {
Daniel Jasper352f0df2015-07-18 16:35:30 +00001272 AlignmentDiff += countVariableAlignments(Line->Children);
1273 for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
1274 if (!Tok->is(TT_PointerOrReference))
1275 continue;
1276 bool SpaceBefore =
1277 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1278 bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() !=
1279 Tok->Next->WhitespaceRange.getEnd();
1280 if (SpaceBefore && !SpaceAfter)
1281 ++AlignmentDiff;
1282 if (!SpaceBefore && SpaceAfter)
1283 --AlignmentDiff;
1284 }
1285 }
1286 return AlignmentDiff;
1287 }
1288
Manuel Klimek71814b42013-10-11 21:25:45 +00001289 void
1290 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001291 bool HasBinPackedFunction = false;
1292 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001293 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001294 if (!AnnotatedLines[i]->First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001295 continue;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001296 FormatToken *Tok = AnnotatedLines[i]->First->Next;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001297 while (Tok->Next) {
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001298 if (Tok->PackingKind == PPK_BinPacked)
1299 HasBinPackedFunction = true;
1300 if (Tok->PackingKind == PPK_OnePerLine)
1301 HasOnePerLineFunction = true;
1302
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001303 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001304 }
1305 }
Eric Liu635423e2016-04-28 07:52:03 +00001306 if (Style.DerivePointerAlignment)
1307 Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
1308 ? FormatStyle::PAS_Left
1309 : FormatStyle::PAS_Right;
1310 if (Style.Standard == FormatStyle::LS_Auto)
1311 Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
1312 ? FormatStyle::LS_Cpp11
1313 : FormatStyle::LS_Cpp03;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001314 BinPackInconclusiveFunctions =
1315 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001316 }
1317
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001318 bool BinPackInconclusiveFunctions;
Krasimir Georgievbcda54b2017-04-21 14:35:20 +00001319 FormattingAttemptStatus *Status;
Eric Liu4cfb88a2016-04-25 15:09:22 +00001320};
1321
1322// This class clean up the erroneous/redundant code around the given ranges in
1323// file.
1324class Cleaner : public TokenAnalyzer {
1325public:
Eric Liu635423e2016-04-28 07:52:03 +00001326 Cleaner(const Environment &Env, const FormatStyle &Style)
1327 : TokenAnalyzer(Env, Style),
Eric Liu4cfb88a2016-04-25 15:09:22 +00001328 DeletedTokens(FormatTokenLess(Env.getSourceManager())) {}
1329
1330 // FIXME: eliminate unused parameters.
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001331 std::pair<tooling::Replacements, unsigned>
Eric Liu4cfb88a2016-04-25 15:09:22 +00001332 analyze(TokenAnnotator &Annotator,
1333 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
Martin Probsta9855af2016-09-02 14:29:48 +00001334 FormatTokenLexer &Tokens) override {
Eric Liu4cfb88a2016-04-25 15:09:22 +00001335 // FIXME: in the current implementation the granularity of affected range
1336 // is an annotated line. However, this is not sufficient. Furthermore,
1337 // redundant code introduced by replacements does not necessarily
1338 // intercept with ranges of replacements that result in the redundancy.
1339 // To determine if some redundant code is actually introduced by
1340 // replacements(e.g. deletions), we need to come up with a more
1341 // sophisticated way of computing affected ranges.
Manuel Klimek0dddcf72018-04-23 09:34:26 +00001342 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
Eric Liu4cfb88a2016-04-25 15:09:22 +00001343
1344 checkEmptyNamespace(AnnotatedLines);
1345
Eric Liuce5e4bc2016-05-18 08:02:56 +00001346 for (auto &Line : AnnotatedLines) {
1347 if (Line->Affected) {
1348 cleanupRight(Line->First, tok::comma, tok::comma);
1349 cleanupRight(Line->First, TT_CtorInitializerColon, tok::comma);
Eric Liu2574d152016-09-13 15:02:43 +00001350 cleanupRight(Line->First, tok::l_paren, tok::comma);
1351 cleanupLeft(Line->First, tok::comma, tok::r_paren);
Eric Liuce5e4bc2016-05-18 08:02:56 +00001352 cleanupLeft(Line->First, TT_CtorInitializerComma, tok::l_brace);
1353 cleanupLeft(Line->First, TT_CtorInitializerColon, tok::l_brace);
Malcolm Parsons5d8cdb82016-10-20 14:58:45 +00001354 cleanupLeft(Line->First, TT_CtorInitializerColon, tok::equal);
Eric Liuce5e4bc2016-05-18 08:02:56 +00001355 }
1356 }
1357
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001358 return {generateFixes(), 0};
Eric Liu4cfb88a2016-04-25 15:09:22 +00001359 }
1360
1361private:
1362 bool containsOnlyComments(const AnnotatedLine &Line) {
1363 for (FormatToken *Tok = Line.First; Tok != nullptr; Tok = Tok->Next) {
1364 if (Tok->isNot(tok::comment))
1365 return false;
1366 }
1367 return true;
1368 }
1369
1370 // Iterate through all lines and remove any empty (nested) namespaces.
1371 void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Eric Liu7956c402016-10-05 15:49:01 +00001372 std::set<unsigned> DeletedLines;
Eric Liu4cfb88a2016-04-25 15:09:22 +00001373 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1374 auto &Line = *AnnotatedLines[i];
Sam McCall6f3778c2018-09-05 07:44:02 +00001375 if (Line.startsWithNamespace()) {
Eric Liu7956c402016-10-05 15:49:01 +00001376 checkEmptyNamespace(AnnotatedLines, i, i, DeletedLines);
Eric Liu4cfb88a2016-04-25 15:09:22 +00001377 }
1378 }
1379
1380 for (auto Line : DeletedLines) {
1381 FormatToken *Tok = AnnotatedLines[Line]->First;
1382 while (Tok) {
1383 deleteToken(Tok);
1384 Tok = Tok->Next;
1385 }
1386 }
1387 }
1388
1389 // The function checks if the namespace, which starts from \p CurrentLine, and
1390 // its nested namespaces are empty and delete them if they are empty. It also
1391 // sets \p NewLine to the last line checked.
1392 // Returns true if the current namespace is empty.
1393 bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
Eric Liu7956c402016-10-05 15:49:01 +00001394 unsigned CurrentLine, unsigned &NewLine,
1395 std::set<unsigned> &DeletedLines) {
Eric Liu4cfb88a2016-04-25 15:09:22 +00001396 unsigned InitLine = CurrentLine, End = AnnotatedLines.size();
Eric Liu635423e2016-04-28 07:52:03 +00001397 if (Style.BraceWrapping.AfterNamespace) {
Eric Liu4cfb88a2016-04-25 15:09:22 +00001398 // If the left brace is in a new line, we should consume it first so that
1399 // it does not make the namespace non-empty.
1400 // FIXME: error handling if there is no left brace.
1401 if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
1402 NewLine = CurrentLine;
1403 return false;
1404 }
1405 } else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
1406 return false;
1407 }
1408 while (++CurrentLine < End) {
1409 if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
1410 break;
1411
Sam McCall6f3778c2018-09-05 07:44:02 +00001412 if (AnnotatedLines[CurrentLine]->startsWithNamespace()) {
Eric Liu7956c402016-10-05 15:49:01 +00001413 if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine,
1414 DeletedLines))
Eric Liu4cfb88a2016-04-25 15:09:22 +00001415 return false;
1416 CurrentLine = NewLine;
1417 continue;
1418 }
1419
1420 if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
1421 continue;
1422
1423 // If there is anything other than comments or nested namespaces in the
1424 // current namespace, the namespace cannot be empty.
1425 NewLine = CurrentLine;
1426 return false;
1427 }
1428
1429 NewLine = CurrentLine;
1430 if (CurrentLine >= End)
1431 return false;
1432
1433 // Check if the empty namespace is actually affected by changed ranges.
1434 if (!AffectedRangeMgr.affectsCharSourceRange(CharSourceRange::getCharRange(
1435 AnnotatedLines[InitLine]->First->Tok.getLocation(),
1436 AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc())))
1437 return false;
1438
1439 for (unsigned i = InitLine; i <= CurrentLine; ++i) {
1440 DeletedLines.insert(i);
1441 }
1442
1443 return true;
1444 }
1445
Eric Liuce5e4bc2016-05-18 08:02:56 +00001446 // Checks pairs {start, start->next},..., {end->previous, end} and deletes one
1447 // of the token in the pair if the left token has \p LK token kind and the
1448 // right token has \p RK token kind. If \p DeleteLeft is true, the left token
1449 // is deleted on match; otherwise, the right token is deleted.
1450 template <typename LeftKind, typename RightKind>
1451 void cleanupPair(FormatToken *Start, LeftKind LK, RightKind RK,
1452 bool DeleteLeft) {
1453 auto NextNotDeleted = [this](const FormatToken &Tok) -> FormatToken * {
1454 for (auto *Res = Tok.Next; Res; Res = Res->Next)
1455 if (!Res->is(tok::comment) &&
1456 DeletedTokens.find(Res) == DeletedTokens.end())
1457 return Res;
1458 return nullptr;
1459 };
1460 for (auto *Left = Start; Left;) {
1461 auto *Right = NextNotDeleted(*Left);
1462 if (!Right)
1463 break;
1464 if (Left->is(LK) && Right->is(RK)) {
1465 deleteToken(DeleteLeft ? Left : Right);
Eric Liu01426ff2016-09-09 17:50:49 +00001466 for (auto *Tok = Left->Next; Tok && Tok != Right; Tok = Tok->Next)
1467 deleteToken(Tok);
Eric Liuce5e4bc2016-05-18 08:02:56 +00001468 // If the right token is deleted, we should keep the left token
1469 // unchanged and pair it with the new right token.
1470 if (!DeleteLeft)
1471 continue;
1472 }
1473 Left = Right;
1474 }
1475 }
1476
1477 template <typename LeftKind, typename RightKind>
1478 void cleanupLeft(FormatToken *Start, LeftKind LK, RightKind RK) {
1479 cleanupPair(Start, LK, RK, /*DeleteLeft=*/true);
1480 }
1481
1482 template <typename LeftKind, typename RightKind>
1483 void cleanupRight(FormatToken *Start, LeftKind LK, RightKind RK) {
1484 cleanupPair(Start, LK, RK, /*DeleteLeft=*/false);
1485 }
1486
Eric Liu4cfb88a2016-04-25 15:09:22 +00001487 // Delete the given token.
1488 inline void deleteToken(FormatToken *Tok) {
1489 if (Tok)
1490 DeletedTokens.insert(Tok);
1491 }
1492
1493 tooling::Replacements generateFixes() {
1494 tooling::Replacements Fixes;
1495 std::vector<FormatToken *> Tokens;
1496 std::copy(DeletedTokens.begin(), DeletedTokens.end(),
1497 std::back_inserter(Tokens));
1498
1499 // Merge multiple continuous token deletions into one big deletion so that
1500 // the number of replacements can be reduced. This makes computing affected
1501 // ranges more efficient when we run reformat on the changed code.
1502 unsigned Idx = 0;
1503 while (Idx < Tokens.size()) {
1504 unsigned St = Idx, End = Idx;
1505 while ((End + 1) < Tokens.size() &&
1506 Tokens[End]->Next == Tokens[End + 1]) {
1507 End++;
1508 }
1509 auto SR = CharSourceRange::getCharRange(Tokens[St]->Tok.getLocation(),
1510 Tokens[End]->Tok.getEndLoc());
Eric Liu40ef2fb2016-08-01 10:16:37 +00001511 auto Err =
1512 Fixes.add(tooling::Replacement(Env.getSourceManager(), SR, ""));
1513 // FIXME: better error handling. for now just print error message and skip
1514 // for the release version.
Piotr Padlewski1ec383c2016-12-23 11:40:44 +00001515 if (Err) {
Eric Liu40ef2fb2016-08-01 10:16:37 +00001516 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Piotr Padlewski1ec383c2016-12-23 11:40:44 +00001517 assert(false && "Fixes must not conflict!");
1518 }
Eric Liu4cfb88a2016-04-25 15:09:22 +00001519 Idx = End + 1;
1520 }
1521
1522 return Fixes;
1523 }
1524
1525 // Class for less-than inequality comparason for the set `RedundantTokens`.
1526 // We store tokens in the order they appear in the translation unit so that
1527 // we do not need to sort them in `generateFixes()`.
1528 struct FormatTokenLess {
Eric Liu635423e2016-04-28 07:52:03 +00001529 FormatTokenLess(const SourceManager &SM) : SM(SM) {}
Eric Liu4cfb88a2016-04-25 15:09:22 +00001530
Eric Liu2874ac32016-05-18 08:14:49 +00001531 bool operator()(const FormatToken *LHS, const FormatToken *RHS) const {
Eric Liu4cfb88a2016-04-25 15:09:22 +00001532 return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(),
1533 RHS->Tok.getLocation());
1534 }
Eric Liu635423e2016-04-28 07:52:03 +00001535 const SourceManager &SM;
Eric Liu4cfb88a2016-04-25 15:09:22 +00001536 };
1537
1538 // Tokens to be deleted.
1539 std::set<FormatToken *, FormatTokenLess> DeletedTokens;
Daniel Jasperf7935112012-12-03 18:12:45 +00001540};
1541
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001542class ObjCHeaderStyleGuesser : public TokenAnalyzer {
1543public:
1544 ObjCHeaderStyleGuesser(const Environment &Env, const FormatStyle &Style)
1545 : TokenAnalyzer(Env, Style), IsObjC(false) {}
1546
1547 std::pair<tooling::Replacements, unsigned>
1548 analyze(TokenAnnotator &Annotator,
1549 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1550 FormatTokenLexer &Tokens) override {
1551 assert(Style.Language == FormatStyle::LK_Cpp);
Ben Hamilton0675e872018-11-05 16:59:33 +00001552 IsObjC = guessIsObjC(Env.getSourceManager(), AnnotatedLines,
1553 Tokens.getKeywords());
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001554 tooling::Replacements Result;
1555 return {Result, 0};
1556 }
1557
1558 bool isObjC() { return IsObjC; }
1559
1560private:
Ben Hamilton0675e872018-11-05 16:59:33 +00001561 static bool
1562 guessIsObjC(const SourceManager &SourceManager,
1563 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1564 const AdditionalKeywords &Keywords) {
Krasimir Georgiev8e216782018-01-17 20:01:02 +00001565 // Keep this array sorted, since we are binary searching over it.
1566 static constexpr llvm::StringLiteral FoundationIdentifiers[] = {
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001567 "CGFloat",
Ben Hamilton19c782d2018-03-22 03:25:22 +00001568 "CGPoint",
1569 "CGPointMake",
1570 "CGPointZero",
1571 "CGRect",
1572 "CGRectEdge",
1573 "CGRectInfinite",
1574 "CGRectMake",
1575 "CGRectNull",
1576 "CGRectZero",
1577 "CGSize",
1578 "CGSizeMake",
1579 "CGVector",
1580 "CGVectorMake",
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001581 "NSAffineTransform",
1582 "NSArray",
1583 "NSAttributedString",
Ben Hamiltonb1a79192018-04-12 15:11:53 +00001584 "NSBlockOperation",
Jacek Olesiakce4f0af2018-02-15 08:47:56 +00001585 "NSBundle",
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001586 "NSCache",
Jacek Olesiakce4f0af2018-02-15 08:47:56 +00001587 "NSCalendar",
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001588 "NSCharacterSet",
1589 "NSCountedSet",
1590 "NSData",
1591 "NSDataDetector",
1592 "NSDecimal",
1593 "NSDecimalNumber",
1594 "NSDictionary",
1595 "NSEdgeInsets",
1596 "NSHashTable",
1597 "NSIndexPath",
1598 "NSIndexSet",
1599 "NSInteger",
Ben Hamiltonb1a79192018-04-12 15:11:53 +00001600 "NSInvocationOperation",
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001601 "NSLocale",
1602 "NSMapTable",
1603 "NSMutableArray",
1604 "NSMutableAttributedString",
1605 "NSMutableCharacterSet",
1606 "NSMutableData",
1607 "NSMutableDictionary",
1608 "NSMutableIndexSet",
1609 "NSMutableOrderedSet",
1610 "NSMutableSet",
1611 "NSMutableString",
1612 "NSNumber",
1613 "NSNumberFormatter",
Jacek Olesiakce4f0af2018-02-15 08:47:56 +00001614 "NSObject",
Ben Hamiltonb1a79192018-04-12 15:11:53 +00001615 "NSOperation",
1616 "NSOperationQueue",
1617 "NSOperationQueuePriority",
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001618 "NSOrderedSet",
1619 "NSPoint",
1620 "NSPointerArray",
Ben Hamiltonb1a79192018-04-12 15:11:53 +00001621 "NSQualityOfService",
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001622 "NSRange",
1623 "NSRect",
1624 "NSRegularExpression",
1625 "NSSet",
1626 "NSSize",
1627 "NSString",
Jacek Olesiakce4f0af2018-02-15 08:47:56 +00001628 "NSTimeZone",
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001629 "NSUInteger",
1630 "NSURL",
1631 "NSURLComponents",
1632 "NSURLQueryItem",
1633 "NSUUID",
Jacek Olesiakce4f0af2018-02-15 08:47:56 +00001634 "NSValue",
Ben Hamilton19c782d2018-03-22 03:25:22 +00001635 "UIImage",
1636 "UIView",
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001637 };
1638
Ben Hamiltonea7a27b2018-03-27 15:01:21 +00001639 for (auto Line : AnnotatedLines) {
1640 for (const FormatToken *FormatTok = Line->First; FormatTok;
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001641 FormatTok = FormatTok->Next) {
Jacek Olesiakce4f0af2018-02-15 08:47:56 +00001642 if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) &&
Ben Hamiltonb1a79192018-04-12 15:11:53 +00001643 (FormatTok->Tok.getObjCKeywordID() != tok::objc_not_keyword ||
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001644 FormatTok->isOneOf(tok::numeric_constant, tok::l_square,
1645 tok::l_brace))) ||
1646 (FormatTok->Tok.isAnyIdentifier() &&
Krasimir Georgiev8e216782018-01-17 20:01:02 +00001647 std::binary_search(std::begin(FoundationIdentifiers),
1648 std::end(FoundationIdentifiers),
1649 FormatTok->TokenText)) ||
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001650 FormatTok->is(TT_ObjCStringLiteral) ||
1651 FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1652 TT_ObjCBlockLBrace, TT_ObjCBlockLParen,
1653 TT_ObjCDecl, TT_ObjCForIn, TT_ObjCMethodExpr,
1654 TT_ObjCMethodSpecifier, TT_ObjCProperty)) {
Ben Hamilton0675e872018-11-05 16:59:33 +00001655 LLVM_DEBUG(llvm::dbgs()
1656 << "Detected ObjC at location "
1657 << FormatTok->Tok.getLocation().printToString(
1658 SourceManager)
1659 << " token: " << FormatTok->TokenText << " token type: "
1660 << getTokenTypeName(FormatTok->Type) << "\n");
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001661 return true;
1662 }
Ben Hamilton0675e872018-11-05 16:59:33 +00001663 if (guessIsObjC(SourceManager, Line->Children, Keywords))
Ben Hamilton6432afe2018-03-22 17:37:19 +00001664 return true;
1665 }
Ben Hamiltone2e3e672018-01-17 17:33:08 +00001666 }
1667 return false;
1668 }
1669
1670 bool IsObjC;
1671};
1672
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001673struct IncludeDirective {
1674 StringRef Filename;
1675 StringRef Text;
1676 unsigned Offset;
Daniel Jasperd2629dc2015-12-16 10:10:16 +00001677 int Category;
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001678};
1679
Krasimir Georgiev7e91b032018-10-05 17:19:26 +00001680struct JavaImportDirective {
1681 StringRef Identifier;
1682 StringRef Text;
1683 unsigned Offset;
1684 std::vector<StringRef> AssociatedCommentLines;
1685 bool IsStatic;
1686};
1687
Craig Topperaf35e852013-06-30 22:29:28 +00001688} // end anonymous namespace
1689
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001690// Determines whether 'Ranges' intersects with ('Start', 'End').
1691static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
1692 unsigned End) {
1693 for (auto Range : Ranges) {
1694 if (Range.getOffset() < End &&
1695 Range.getOffset() + Range.getLength() > Start)
1696 return true;
1697 }
1698 return false;
1699}
1700
Eric Liua992afe2016-08-10 09:32:23 +00001701// Returns a pair (Index, OffsetToEOL) describing the position of the cursor
1702// before sorting/deduplicating. Index is the index of the include under the
1703// cursor in the original set of includes. If this include has duplicates, it is
1704// the index of the first of the duplicates as the others are going to be
1705// removed. OffsetToEOL describes the cursor's position relative to the end of
1706// its current line.
1707// If `Cursor` is not on any #include, `Index` will be UINT_MAX.
1708static std::pair<unsigned, unsigned>
1709FindCursorIndex(const SmallVectorImpl<IncludeDirective> &Includes,
1710 const SmallVectorImpl<unsigned> &Indices, unsigned Cursor) {
1711 unsigned CursorIndex = UINT_MAX;
1712 unsigned OffsetToEOL = 0;
1713 for (int i = 0, e = Includes.size(); i != e; ++i) {
1714 unsigned Start = Includes[Indices[i]].Offset;
1715 unsigned End = Start + Includes[Indices[i]].Text.size();
1716 if (!(Cursor >= Start && Cursor < End))
1717 continue;
1718 CursorIndex = Indices[i];
1719 OffsetToEOL = End - Cursor;
1720 // Put the cursor on the only remaining #include among the duplicate
1721 // #includes.
1722 while (--i >= 0 && Includes[CursorIndex].Text == Includes[Indices[i]].Text)
1723 CursorIndex = i;
1724 break;
1725 }
1726 return std::make_pair(CursorIndex, OffsetToEOL);
1727}
1728
1729// Sorts and deduplicate a block of includes given by 'Includes' alphabetically
1730// adding the necessary replacement to 'Replaces'. 'Includes' must be in strict
1731// source order.
1732// #include directives with the same text will be deduplicated, and only the
1733// first #include in the duplicate #includes remains. If the `Cursor` is
1734// provided and put on a deleted #include, it will be moved to the remaining
1735// #include in the duplicate #includes.
Martin Probstc4a0dd42016-05-20 11:24:24 +00001736static void sortCppIncludes(const FormatStyle &Style,
Eric Liua992afe2016-08-10 09:32:23 +00001737 const SmallVectorImpl<IncludeDirective> &Includes,
1738 ArrayRef<tooling::Range> Ranges, StringRef FileName,
1739 tooling::Replacements &Replaces, unsigned *Cursor) {
1740 unsigned IncludesBeginOffset = Includes.front().Offset;
Daniel Jasperd6a00782016-08-30 21:33:41 +00001741 unsigned IncludesEndOffset =
1742 Includes.back().Offset + Includes.back().Text.size();
1743 unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset;
1744 if (!affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset))
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001745 return;
1746 SmallVector<unsigned, 16> Indices;
1747 for (unsigned i = 0, e = Includes.size(); i != e; ++i)
1748 Indices.push_back(i);
Daniel Jasper94a96fc2016-03-03 17:34:14 +00001749 std::stable_sort(
1750 Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) {
1751 return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) <
1752 std::tie(Includes[RHSI].Category, Includes[RHSI].Filename);
1753 });
Eric Liua992afe2016-08-10 09:32:23 +00001754 // The index of the include on which the cursor will be put after
1755 // sorting/deduplicating.
1756 unsigned CursorIndex;
1757 // The offset from cursor to the end of line.
1758 unsigned CursorToEOLOffset;
1759 if (Cursor)
1760 std::tie(CursorIndex, CursorToEOLOffset) =
1761 FindCursorIndex(Includes, Indices, *Cursor);
1762
1763 // Deduplicate #includes.
1764 Indices.erase(std::unique(Indices.begin(), Indices.end(),
1765 [&](unsigned LHSI, unsigned RHSI) {
1766 return Includes[LHSI].Text == Includes[RHSI].Text;
1767 }),
1768 Indices.end());
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001769
Krasimir Georgiev4c2c9c32017-11-27 13:23:45 +00001770 int CurrentCategory = Includes.front().Category;
1771
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001772 // If the #includes are out of order, we generate a single replacement fixing
1773 // the entire block. Otherwise, no replacement is generated.
Eric Liua992afe2016-08-10 09:32:23 +00001774 if (Indices.size() == Includes.size() &&
Krasimir Georgiev4c2c9c32017-11-27 13:23:45 +00001775 std::is_sorted(Indices.begin(), Indices.end()) &&
Eric Liu9d92c022018-05-14 19:51:33 +00001776 Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Preserve)
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001777 return;
1778
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001779 std::string result;
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001780 for (unsigned Index : Indices) {
Krasimir Georgiev4c2c9c32017-11-27 13:23:45 +00001781 if (!result.empty()) {
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001782 result += "\n";
Eric Liu9d92c022018-05-14 19:51:33 +00001783 if (Style.IncludeStyle.IncludeBlocks ==
1784 tooling::IncludeStyle::IBS_Regroup &&
Krasimir Georgiev4c2c9c32017-11-27 13:23:45 +00001785 CurrentCategory != Includes[Index].Category)
1786 result += "\n";
1787 }
Daniel Jasperb68aabf2015-11-23 08:36:35 +00001788 result += Includes[Index].Text;
Eric Liua992afe2016-08-10 09:32:23 +00001789 if (Cursor && CursorIndex == Index)
1790 *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
Krasimir Georgiev4c2c9c32017-11-27 13:23:45 +00001791 CurrentCategory = Includes[Index].Category;
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001792 }
1793
Eric Liu40ef2fb2016-08-01 10:16:37 +00001794 auto Err = Replaces.add(tooling::Replacement(
Eric Liua992afe2016-08-10 09:32:23 +00001795 FileName, Includes.front().Offset, IncludesBlockSize, result));
Eric Liu40ef2fb2016-08-01 10:16:37 +00001796 // FIXME: better error handling. For now, just skip the replacement for the
1797 // release version.
Piotr Padlewski1ec383c2016-12-23 11:40:44 +00001798 if (Err) {
Eric Liu40ef2fb2016-08-01 10:16:37 +00001799 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Piotr Padlewski1ec383c2016-12-23 11:40:44 +00001800 assert(false);
1801 }
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001802}
1803
Eric Liu659afd52016-05-31 13:34:20 +00001804namespace {
1805
Krasimir Georgiev7e91b032018-10-05 17:19:26 +00001806const char CppIncludeRegexPattern[] =
Eric Liu659afd52016-05-31 13:34:20 +00001807 R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))";
1808
1809} // anonymous namespace
1810
Martin Probstc4a0dd42016-05-20 11:24:24 +00001811tooling::Replacements sortCppIncludes(const FormatStyle &Style, StringRef Code,
1812 ArrayRef<tooling::Range> Ranges,
1813 StringRef FileName,
1814 tooling::Replacements &Replaces,
1815 unsigned *Cursor) {
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001816 unsigned Prev = 0;
1817 unsigned SearchFrom = 0;
Krasimir Georgiev7e91b032018-10-05 17:19:26 +00001818 llvm::Regex IncludeRegex(CppIncludeRegexPattern);
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001819 SmallVector<StringRef, 4> Matches;
1820 SmallVector<IncludeDirective, 16> IncludesInBlock;
Daniel Jasper85c472d2015-09-29 07:53:08 +00001821
1822 // In compiled files, consider the first #include to be the main #include of
1823 // the file if it is not a system #include. This ensures that the header
1824 // doesn't have hidden dependencies
1825 // (http://llvm.org/docs/CodingStandards.html#include-style).
1826 //
1827 // FIXME: Do some sanity checking, e.g. edit distance of the base name, to fix
1828 // cases where the first #include is unlikely to be the main header.
Eric Liu7129e632018-05-14 20:17:53 +00001829 tooling::IncludeCategoryManager Categories(Style.IncludeStyle, FileName);
Daniel Jasper32d75fa2015-12-21 13:40:49 +00001830 bool FirstIncludeBlock = true;
Daniel Jaspera252f5d2015-12-21 17:28:24 +00001831 bool MainIncludeFound = false;
Daniel Jasper9b8c7c72015-11-21 09:17:08 +00001832 bool FormattingOff = false;
1833
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001834 for (;;) {
1835 auto Pos = Code.find('\n', SearchFrom);
1836 StringRef Line =
1837 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
Daniel Jasper9b8c7c72015-11-21 09:17:08 +00001838
1839 StringRef Trimmed = Line.trim();
Paul Hoad9b468c02019-03-02 09:08:51 +00001840 if (Trimmed == "// clang-format off" || Trimmed == "/* clang-format off */")
Daniel Jasper9b8c7c72015-11-21 09:17:08 +00001841 FormattingOff = true;
Paul Hoad9b468c02019-03-02 09:08:51 +00001842 else if (Trimmed == "// clang-format on" ||
1843 Trimmed == "/* clang-format on */")
Daniel Jasper9b8c7c72015-11-21 09:17:08 +00001844 FormattingOff = false;
1845
Krasimir Georgiev4c2c9c32017-11-27 13:23:45 +00001846 const bool EmptyLineSkipped =
Eric Liu9d92c022018-05-14 19:51:33 +00001847 Trimmed.empty() &&
1848 (Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Merge ||
1849 Style.IncludeStyle.IncludeBlocks ==
1850 tooling::IncludeStyle::IBS_Regroup);
Krasimir Georgiev4c2c9c32017-11-27 13:23:45 +00001851
Daniel Jasper9b8c7c72015-11-21 09:17:08 +00001852 if (!FormattingOff && !Line.endswith("\\")) {
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001853 if (IncludeRegex.match(Line, &Matches)) {
Nico Weberff063702015-10-21 17:13:45 +00001854 StringRef IncludeName = Matches[2];
Eric Liu659afd52016-05-31 13:34:20 +00001855 int Category = Categories.getIncludePriority(
1856 IncludeName,
1857 /*CheckMainHeader=*/!MainIncludeFound && FirstIncludeBlock);
1858 if (Category == 0)
1859 MainIncludeFound = true;
Nico Weberff063702015-10-21 17:13:45 +00001860 IncludesInBlock.push_back({IncludeName, Line, Prev, Category});
Krasimir Georgiev4c2c9c32017-11-27 13:23:45 +00001861 } else if (!IncludesInBlock.empty() && !EmptyLineSkipped) {
Martin Probstc4a0dd42016-05-20 11:24:24 +00001862 sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces,
1863 Cursor);
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001864 IncludesInBlock.clear();
Daniel Jasper32d75fa2015-12-21 13:40:49 +00001865 FirstIncludeBlock = false;
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00001866 }
1867 Prev = Pos + 1;
1868 }
1869 if (Pos == StringRef::npos || Pos + 1 == Code.size())
1870 break;
1871 SearchFrom = Pos + 1;
1872 }
1873 if (!IncludesInBlock.empty())
Martin Probstc4a0dd42016-05-20 11:24:24 +00001874 sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces, Cursor);
1875 return Replaces;
1876}
1877
Krasimir Georgiev7e91b032018-10-05 17:19:26 +00001878// Returns group number to use as a first order sort on imports. Gives UINT_MAX
1879// if the import does not match any given groups.
1880static unsigned findJavaImportGroup(const FormatStyle &Style,
1881 StringRef ImportIdentifier) {
1882 unsigned LongestMatchIndex = UINT_MAX;
1883 unsigned LongestMatchLength = 0;
1884 for (unsigned I = 0; I < Style.JavaImportGroups.size(); I++) {
1885 std::string GroupPrefix = Style.JavaImportGroups[I];
1886 if (ImportIdentifier.startswith(GroupPrefix) &&
1887 GroupPrefix.length() > LongestMatchLength) {
1888 LongestMatchIndex = I;
1889 LongestMatchLength = GroupPrefix.length();
1890 }
1891 }
1892 return LongestMatchIndex;
1893}
1894
1895// Sorts and deduplicates a block of includes given by 'Imports' based on
1896// JavaImportGroups, then adding the necessary replacement to 'Replaces'.
1897// Import declarations with the same text will be deduplicated. Between each
1898// import group, a newline is inserted, and within each import group, a
1899// lexicographic sort based on ASCII value is performed.
1900static void sortJavaImports(const FormatStyle &Style,
1901 const SmallVectorImpl<JavaImportDirective> &Imports,
1902 ArrayRef<tooling::Range> Ranges, StringRef FileName,
Paul Hoad5bcf99b2019-03-01 09:09:54 +00001903 StringRef Code, tooling::Replacements &Replaces) {
Krasimir Georgiev7e91b032018-10-05 17:19:26 +00001904 unsigned ImportsBeginOffset = Imports.front().Offset;
1905 unsigned ImportsEndOffset =
1906 Imports.back().Offset + Imports.back().Text.size();
1907 unsigned ImportsBlockSize = ImportsEndOffset - ImportsBeginOffset;
1908 if (!affectsRange(Ranges, ImportsBeginOffset, ImportsEndOffset))
1909 return;
1910 SmallVector<unsigned, 16> Indices;
1911 SmallVector<unsigned, 16> JavaImportGroups;
1912 for (unsigned i = 0, e = Imports.size(); i != e; ++i) {
1913 Indices.push_back(i);
1914 JavaImportGroups.push_back(
1915 findJavaImportGroup(Style, Imports[i].Identifier));
1916 }
Mandeep Singh Grangd36da8a2019-01-18 18:45:26 +00001917 llvm::sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
Krasimir Georgiev777bb822019-02-20 11:44:21 +00001918 // Negating IsStatic to push static imports above non-static imports.
1919 return std::make_tuple(!Imports[LHSI].IsStatic, JavaImportGroups[LHSI],
1920 Imports[LHSI].Identifier) <
1921 std::make_tuple(!Imports[RHSI].IsStatic, JavaImportGroups[RHSI],
1922 Imports[RHSI].Identifier);
1923 });
Krasimir Georgiev7e91b032018-10-05 17:19:26 +00001924
1925 // Deduplicate imports.
1926 Indices.erase(std::unique(Indices.begin(), Indices.end(),
1927 [&](unsigned LHSI, unsigned RHSI) {
1928 return Imports[LHSI].Text == Imports[RHSI].Text;
1929 }),
1930 Indices.end());
1931
1932 bool CurrentIsStatic = Imports[Indices.front()].IsStatic;
1933 unsigned CurrentImportGroup = JavaImportGroups[Indices.front()];
1934
1935 std::string result;
1936 for (unsigned Index : Indices) {
1937 if (!result.empty()) {
1938 result += "\n";
1939 if (CurrentIsStatic != Imports[Index].IsStatic ||
1940 CurrentImportGroup != JavaImportGroups[Index])
1941 result += "\n";
1942 }
1943 for (StringRef CommentLine : Imports[Index].AssociatedCommentLines) {
1944 result += CommentLine;
1945 result += "\n";
1946 }
1947 result += Imports[Index].Text;
1948 CurrentIsStatic = Imports[Index].IsStatic;
1949 CurrentImportGroup = JavaImportGroups[Index];
1950 }
1951
Krasimir Georgiev777bb822019-02-20 11:44:21 +00001952 // If the imports are out of order, we generate a single replacement fixing
1953 // the entire block. Otherwise, no replacement is generated.
1954 if (result == Code.substr(Imports.front().Offset, ImportsBlockSize))
1955 return;
1956
Krasimir Georgiev7e91b032018-10-05 17:19:26 +00001957 auto Err = Replaces.add(tooling::Replacement(FileName, Imports.front().Offset,
1958 ImportsBlockSize, result));
1959 // FIXME: better error handling. For now, just skip the replacement for the
1960 // release version.
1961 if (Err) {
1962 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
1963 assert(false);
1964 }
1965}
1966
1967namespace {
1968
1969const char JavaImportRegexPattern[] =
1970 "^[\t ]*import[\t ]*(static[\t ]*)?([^\t ]*)[\t ]*;";
1971
1972} // anonymous namespace
1973
1974tooling::Replacements sortJavaImports(const FormatStyle &Style, StringRef Code,
1975 ArrayRef<tooling::Range> Ranges,
1976 StringRef FileName,
1977 tooling::Replacements &Replaces) {
1978 unsigned Prev = 0;
1979 unsigned SearchFrom = 0;
1980 llvm::Regex ImportRegex(JavaImportRegexPattern);
1981 SmallVector<StringRef, 4> Matches;
1982 SmallVector<JavaImportDirective, 16> ImportsInBlock;
1983 std::vector<StringRef> AssociatedCommentLines;
1984
1985 bool FormattingOff = false;
1986
1987 for (;;) {
1988 auto Pos = Code.find('\n', SearchFrom);
1989 StringRef Line =
1990 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
1991
1992 StringRef Trimmed = Line.trim();
1993 if (Trimmed == "// clang-format off")
1994 FormattingOff = true;
1995 else if (Trimmed == "// clang-format on")
1996 FormattingOff = false;
1997
1998 if (ImportRegex.match(Line, &Matches)) {
1999 if (FormattingOff) {
2000 // If at least one import line has formatting turned off, turn off
2001 // formatting entirely.
2002 return Replaces;
2003 }
2004 StringRef Static = Matches[1];
2005 StringRef Identifier = Matches[2];
2006 bool IsStatic = false;
2007 if (Static.contains("static")) {
2008 IsStatic = true;
2009 }
Paul Hoad5bcf99b2019-03-01 09:09:54 +00002010 ImportsInBlock.push_back(
2011 {Identifier, Line, Prev, AssociatedCommentLines, IsStatic});
Krasimir Georgiev7e91b032018-10-05 17:19:26 +00002012 AssociatedCommentLines.clear();
2013 } else if (Trimmed.size() > 0 && !ImportsInBlock.empty()) {
2014 // Associating comments within the imports with the nearest import below
2015 AssociatedCommentLines.push_back(Line);
2016 }
2017 Prev = Pos + 1;
2018 if (Pos == StringRef::npos || Pos + 1 == Code.size())
2019 break;
2020 SearchFrom = Pos + 1;
2021 }
2022 if (!ImportsInBlock.empty())
Krasimir Georgiev777bb822019-02-20 11:44:21 +00002023 sortJavaImports(Style, ImportsInBlock, Ranges, FileName, Code, Replaces);
Krasimir Georgiev7e91b032018-10-05 17:19:26 +00002024 return Replaces;
2025}
2026
Martin Probstfa37b182017-01-27 09:09:11 +00002027bool isMpegTS(StringRef Code) {
2028 // MPEG transport streams use the ".ts" file extension. clang-format should
2029 // not attempt to format those. MPEG TS' frame format starts with 0x47 every
2030 // 189 bytes - detect that and return.
2031 return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
2032}
2033
Manuel Klimek89628f62017-09-20 09:51:03 +00002034bool isLikelyXml(StringRef Code) { return Code.ltrim().startswith("<"); }
Krasimir Georgieva2e7d0d2017-08-29 13:51:38 +00002035
Martin Probstc4a0dd42016-05-20 11:24:24 +00002036tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
2037 ArrayRef<tooling::Range> Ranges,
2038 StringRef FileName, unsigned *Cursor) {
2039 tooling::Replacements Replaces;
2040 if (!Style.SortIncludes)
2041 return Replaces;
Krasimir Georgiev86873032017-08-29 13:57:31 +00002042 if (isLikelyXml(Code))
2043 return Replaces;
2044 if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
2045 isMpegTS(Code))
Martin Probstfa37b182017-01-27 09:09:11 +00002046 return Replaces;
Martin Probstc4a0dd42016-05-20 11:24:24 +00002047 if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript)
2048 return sortJavaScriptImports(Style, Code, Ranges, FileName);
Krasimir Georgiev7e91b032018-10-05 17:19:26 +00002049 if (Style.Language == FormatStyle::LanguageKind::LK_Java)
2050 return sortJavaImports(Style, Code, Ranges, FileName, Replaces);
Martin Probstc4a0dd42016-05-20 11:24:24 +00002051 sortCppIncludes(Style, Code, Ranges, FileName, Replaces, Cursor);
Daniel Jasperd89ae9d2015-09-23 08:30:47 +00002052 return Replaces;
2053}
2054
Eric Liu4cfb88a2016-04-25 15:09:22 +00002055template <typename T>
Eric Liu4f8d9942016-07-11 13:53:12 +00002056static llvm::Expected<tooling::Replacements>
Eric Liu4cfb88a2016-04-25 15:09:22 +00002057processReplacements(T ProcessFunc, StringRef Code,
2058 const tooling::Replacements &Replaces,
2059 const FormatStyle &Style) {
Manuel Klimekb12e5a52016-03-01 12:37:30 +00002060 if (Replaces.empty())
2061 return tooling::Replacements();
2062
Eric Liu4f8d9942016-07-11 13:53:12 +00002063 auto NewCode = applyAllReplacements(Code, Replaces);
2064 if (!NewCode)
2065 return NewCode.takeError();
Eric Liu40ef2fb2016-08-01 10:16:37 +00002066 std::vector<tooling::Range> ChangedRanges = Replaces.getAffectedRanges();
Manuel Klimekb12e5a52016-03-01 12:37:30 +00002067 StringRef FileName = Replaces.begin()->getFilePath();
Eric Liu4cfb88a2016-04-25 15:09:22 +00002068
Manuel Klimekb12e5a52016-03-01 12:37:30 +00002069 tooling::Replacements FormatReplaces =
Eric Liu4f8d9942016-07-11 13:53:12 +00002070 ProcessFunc(Style, *NewCode, ChangedRanges, FileName);
Manuel Klimekb12e5a52016-03-01 12:37:30 +00002071
Eric Liu40ef2fb2016-08-01 10:16:37 +00002072 return Replaces.merge(FormatReplaces);
Manuel Klimekb12e5a52016-03-01 12:37:30 +00002073}
2074
Eric Liu4f8d9942016-07-11 13:53:12 +00002075llvm::Expected<tooling::Replacements>
2076formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
2077 const FormatStyle &Style) {
Eric Liu4cfb88a2016-04-25 15:09:22 +00002078 // We need to use lambda function here since there are two versions of
Eric Liubaf58c22016-05-18 13:43:48 +00002079 // `sortIncludes`.
2080 auto SortIncludes = [](const FormatStyle &Style, StringRef Code,
2081 std::vector<tooling::Range> Ranges,
2082 StringRef FileName) -> tooling::Replacements {
2083 return sortIncludes(Style, Code, Ranges, FileName);
2084 };
Eric Liu4f8d9942016-07-11 13:53:12 +00002085 auto SortedReplaces =
Eric Liubaf58c22016-05-18 13:43:48 +00002086 processReplacements(SortIncludes, Code, Replaces, Style);
Eric Liu4f8d9942016-07-11 13:53:12 +00002087 if (!SortedReplaces)
2088 return SortedReplaces.takeError();
Eric Liubaf58c22016-05-18 13:43:48 +00002089
2090 // We need to use lambda function here since there are two versions of
Eric Liu4cfb88a2016-04-25 15:09:22 +00002091 // `reformat`.
2092 auto Reformat = [](const FormatStyle &Style, StringRef Code,
2093 std::vector<tooling::Range> Ranges,
2094 StringRef FileName) -> tooling::Replacements {
2095 return reformat(Style, Code, Ranges, FileName);
2096 };
Eric Liu4f8d9942016-07-11 13:53:12 +00002097 return processReplacements(Reformat, Code, *SortedReplaces, Style);
Eric Liu4cfb88a2016-04-25 15:09:22 +00002098}
2099
Eric Liu659afd52016-05-31 13:34:20 +00002100namespace {
2101
2102inline bool isHeaderInsertion(const tooling::Replacement &Replace) {
Eric Liuc0d3a802016-09-23 15:10:56 +00002103 return Replace.getOffset() == UINT_MAX && Replace.getLength() == 0 &&
Krasimir Georgiev7e91b032018-10-05 17:19:26 +00002104 llvm::Regex(CppIncludeRegexPattern)
2105 .match(Replace.getReplacementText());
Eric Liu659afd52016-05-31 13:34:20 +00002106}
2107
Eric Liuc0d3a802016-09-23 15:10:56 +00002108inline bool isHeaderDeletion(const tooling::Replacement &Replace) {
2109 return Replace.getOffset() == UINT_MAX && Replace.getLength() == 1;
2110}
2111
Eric Liu659afd52016-05-31 13:34:20 +00002112// FIXME: insert empty lines between newly created blocks.
2113tooling::Replacements
2114fixCppIncludeInsertions(StringRef Code, const tooling::Replacements &Replaces,
2115 const FormatStyle &Style) {
Daniel Jasper1dbc2102017-03-31 13:30:24 +00002116 if (!Style.isCpp())
Eric Liu659afd52016-05-31 13:34:20 +00002117 return Replaces;
2118
2119 tooling::Replacements HeaderInsertions;
Eric Liuc0d3a802016-09-23 15:10:56 +00002120 std::set<llvm::StringRef> HeadersToDelete;
Eric Liu40ef2fb2016-08-01 10:16:37 +00002121 tooling::Replacements Result;
Eric Liu659afd52016-05-31 13:34:20 +00002122 for (const auto &R : Replaces) {
Eric Liu40ef2fb2016-08-01 10:16:37 +00002123 if (isHeaderInsertion(R)) {
2124 // Replacements from \p Replaces must be conflict-free already, so we can
2125 // simply consume the error.
2126 llvm::consumeError(HeaderInsertions.add(R));
Eric Liuc0d3a802016-09-23 15:10:56 +00002127 } else if (isHeaderDeletion(R)) {
2128 HeadersToDelete.insert(R.getReplacementText());
Eric Liu40ef2fb2016-08-01 10:16:37 +00002129 } else if (R.getOffset() == UINT_MAX) {
Eric Liu659afd52016-05-31 13:34:20 +00002130 llvm::errs() << "Insertions other than header #include insertion are "
2131 "not supported! "
2132 << R.getReplacementText() << "\n";
Eric Liu40ef2fb2016-08-01 10:16:37 +00002133 } else {
2134 llvm::consumeError(Result.add(R));
2135 }
Eric Liu659afd52016-05-31 13:34:20 +00002136 }
Eric Liuc0d3a802016-09-23 15:10:56 +00002137 if (HeaderInsertions.empty() && HeadersToDelete.empty())
Eric Liu659afd52016-05-31 13:34:20 +00002138 return Replaces;
Eric Liu659afd52016-05-31 13:34:20 +00002139
Eric Liu659afd52016-05-31 13:34:20 +00002140 StringRef FileName = Replaces.begin()->getFilePath();
Eric Liu7129e632018-05-14 20:17:53 +00002141 tooling::HeaderIncludes Includes(FileName, Code, Style.IncludeStyle);
Eric Liu659afd52016-05-31 13:34:20 +00002142
Eric Liubf4c41c2018-05-04 17:55:13 +00002143 for (const auto &Header : HeadersToDelete) {
2144 tooling::Replacements Replaces =
Eric Liu7129e632018-05-14 20:17:53 +00002145 Includes.remove(Header.trim("\"<>"), Header.startswith("<"));
Eric Liubf4c41c2018-05-04 17:55:13 +00002146 for (const auto &R : Replaces) {
2147 auto Err = Result.add(R);
2148 if (Err) {
2149 // Ignore the deletion on conflict.
2150 llvm::errs() << "Failed to add header deletion replacement for "
2151 << Header << ": " << llvm::toString(std::move(Err))
2152 << "\n";
Eric Liuc0d3a802016-09-23 15:10:56 +00002153 }
Eric Liu659afd52016-05-31 13:34:20 +00002154 }
Eric Liu659afd52016-05-31 13:34:20 +00002155 }
2156
Krasimir Georgiev7e91b032018-10-05 17:19:26 +00002157 llvm::Regex IncludeRegex = llvm::Regex(CppIncludeRegexPattern);
Eric Liubf4c41c2018-05-04 17:55:13 +00002158 llvm::SmallVector<StringRef, 4> Matches;
Eric Liu659afd52016-05-31 13:34:20 +00002159 for (const auto &R : HeaderInsertions) {
2160 auto IncludeDirective = R.getReplacementText();
2161 bool Matched = IncludeRegex.match(IncludeDirective, &Matches);
2162 assert(Matched && "Header insertion replacement must have replacement text "
2163 "'#include ...'");
Benjamin Kramer1cb7ee12016-05-31 14:14:42 +00002164 (void)Matched;
Eric Liu659afd52016-05-31 13:34:20 +00002165 auto IncludeName = Matches[2];
Eric Liubf4c41c2018-05-04 17:55:13 +00002166 auto Replace =
Eric Liu7129e632018-05-14 20:17:53 +00002167 Includes.insert(IncludeName.trim("\"<>"), IncludeName.startswith("<"));
Eric Liubf4c41c2018-05-04 17:55:13 +00002168 if (Replace) {
2169 auto Err = Result.add(*Replace);
2170 if (Err) {
2171 llvm::consumeError(std::move(Err));
Paul Hoad5bcf99b2019-03-01 09:09:54 +00002172 unsigned NewOffset =
2173 Result.getShiftedCodePosition(Replace->getOffset());
Eric Liubf4c41c2018-05-04 17:55:13 +00002174 auto Shifted = tooling::Replacement(FileName, NewOffset, 0,
2175 Replace->getReplacementText());
2176 Result = Result.merge(tooling::Replacements(Shifted));
2177 }
Eric Liu40ef2fb2016-08-01 10:16:37 +00002178 }
Eric Liu659afd52016-05-31 13:34:20 +00002179 }
2180 return Result;
2181}
2182
2183} // anonymous namespace
2184
Eric Liu4f8d9942016-07-11 13:53:12 +00002185llvm::Expected<tooling::Replacements>
Eric Liu4cfb88a2016-04-25 15:09:22 +00002186cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
2187 const FormatStyle &Style) {
2188 // We need to use lambda function here since there are two versions of
2189 // `cleanup`.
2190 auto Cleanup = [](const FormatStyle &Style, StringRef Code,
2191 std::vector<tooling::Range> Ranges,
2192 StringRef FileName) -> tooling::Replacements {
2193 return cleanup(Style, Code, Ranges, FileName);
2194 };
Eric Liu659afd52016-05-31 13:34:20 +00002195 // Make header insertion replacements insert new headers into correct blocks.
2196 tooling::Replacements NewReplaces =
2197 fixCppIncludeInsertions(Code, Replaces, Style);
2198 return processReplacements(Cleanup, Code, NewReplaces, Style);
Eric Liu4cfb88a2016-04-25 15:09:22 +00002199}
2200
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002201namespace internal {
2202std::pair<tooling::Replacements, unsigned>
2203reformat(const FormatStyle &Style, StringRef Code,
2204 ArrayRef<tooling::Range> Ranges, unsigned FirstStartColumn,
2205 unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName,
2206 FormattingAttemptStatus *Status) {
Eric Liu4cfb88a2016-04-25 15:09:22 +00002207 FormatStyle Expanded = expandPresets(Style);
2208 if (Expanded.DisableFormat)
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002209 return {tooling::Replacements(), 0};
Krasimir Georgiev86873032017-08-29 13:57:31 +00002210 if (isLikelyXml(Code))
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002211 return {tooling::Replacements(), 0};
Krasimir Georgiev86873032017-08-29 13:57:31 +00002212 if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code))
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002213 return {tooling::Replacements(), 0};
Daniel Jasper496c1992016-09-07 22:48:53 +00002214
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002215 typedef std::function<std::pair<tooling::Replacements, unsigned>(
2216 const Environment &)>
Krasimir Georgievac16a202017-06-23 11:46:03 +00002217 AnalyzerPass;
2218 SmallVector<AnalyzerPass, 4> Passes;
Krasimir Georgiev32eaa862017-03-01 15:35:39 +00002219
Krasimir Georgievac16a202017-06-23 11:46:03 +00002220 if (Style.Language == FormatStyle::LK_Cpp) {
2221 if (Style.FixNamespaceComments)
2222 Passes.emplace_back([&](const Environment &Env) {
2223 return NamespaceEndCommentsFixer(Env, Expanded).process();
2224 });
2225
2226 if (Style.SortUsingDeclarations)
2227 Passes.emplace_back([&](const Environment &Env) {
2228 return UsingDeclarationsSorter(Env, Expanded).process();
2229 });
Krasimir Georgiev32eaa862017-03-01 15:35:39 +00002230 }
2231
2232 if (Style.Language == FormatStyle::LK_JavaScript &&
Krasimir Georgievac16a202017-06-23 11:46:03 +00002233 Style.JavaScriptQuotes != FormatStyle::JSQS_Leave)
2234 Passes.emplace_back([&](const Environment &Env) {
2235 return JavaScriptRequoter(Env, Expanded).process();
2236 });
2237
2238 Passes.emplace_back([&](const Environment &Env) {
2239 return Formatter(Env, Expanded, Status).process();
2240 });
2241
Eric Liu2e538082018-05-09 21:35:52 +00002242 auto Env =
2243 llvm::make_unique<Environment>(Code, FileName, Ranges, FirstStartColumn,
2244 NextStartColumn, LastStartColumn);
Krasimir Georgievac16a202017-06-23 11:46:03 +00002245 llvm::Optional<std::string> CurrentCode = None;
2246 tooling::Replacements Fixes;
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002247 unsigned Penalty = 0;
Krasimir Georgievac16a202017-06-23 11:46:03 +00002248 for (size_t I = 0, E = Passes.size(); I < E; ++I) {
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002249 std::pair<tooling::Replacements, unsigned> PassFixes = Passes[I](*Env);
Krasimir Georgievac16a202017-06-23 11:46:03 +00002250 auto NewCode = applyAllReplacements(
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002251 CurrentCode ? StringRef(*CurrentCode) : Code, PassFixes.first);
Krasimir Georgievac16a202017-06-23 11:46:03 +00002252 if (NewCode) {
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002253 Fixes = Fixes.merge(PassFixes.first);
2254 Penalty += PassFixes.second;
Krasimir Georgievac16a202017-06-23 11:46:03 +00002255 if (I + 1 < E) {
2256 CurrentCode = std::move(*NewCode);
Eric Liu2e538082018-05-09 21:35:52 +00002257 Env = llvm::make_unique<Environment>(
Krasimir Georgievac16a202017-06-23 11:46:03 +00002258 *CurrentCode, FileName,
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002259 tooling::calculateRangesAfterReplacements(Fixes, Ranges),
2260 FirstStartColumn, NextStartColumn, LastStartColumn);
Krasimir Georgievac16a202017-06-23 11:46:03 +00002261 }
2262 }
Daniel Jasper496c1992016-09-07 22:48:53 +00002263 }
2264
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002265 return {Fixes, Penalty};
2266}
2267} // namespace internal
2268
2269tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
2270 ArrayRef<tooling::Range> Ranges,
2271 StringRef FileName,
2272 FormattingAttemptStatus *Status) {
2273 return internal::reformat(Style, Code, Ranges,
2274 /*FirstStartColumn=*/0,
2275 /*NextStartColumn=*/0,
2276 /*LastStartColumn=*/0, FileName, Status)
2277 .first;
Eric Liu4cfb88a2016-04-25 15:09:22 +00002278}
2279
Eric Liu4cfb88a2016-04-25 15:09:22 +00002280tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
2281 ArrayRef<tooling::Range> Ranges,
2282 StringRef FileName) {
Martin Probst816a9662017-05-29 08:41:11 +00002283 // cleanups only apply to C++ (they mostly concern ctor commas etc.)
2284 if (Style.Language != FormatStyle::LK_Cpp)
2285 return tooling::Replacements();
Eric Liu2e538082018-05-09 21:35:52 +00002286 return Cleaner(Environment(Code, FileName, Ranges), Style).process().first;
Daniel Jasperec04c0d2013-05-16 10:40:07 +00002287}
2288
Krasimir Georgievbcda54b2017-04-21 14:35:20 +00002289tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
2290 ArrayRef<tooling::Range> Ranges,
2291 StringRef FileName, bool *IncompleteFormat) {
2292 FormattingAttemptStatus Status;
2293 auto Result = reformat(Style, Code, Ranges, FileName, &Status);
2294 if (!Status.FormatComplete)
2295 *IncompleteFormat = true;
2296 return Result;
2297}
2298
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +00002299tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
2300 StringRef Code,
2301 ArrayRef<tooling::Range> Ranges,
2302 StringRef FileName) {
Eric Liu2e538082018-05-09 21:35:52 +00002303 return NamespaceEndCommentsFixer(Environment(Code, FileName, Ranges), Style)
2304 .process()
2305 .first;
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +00002306}
2307
Krasimir Georgievb03877a2017-06-21 12:03:12 +00002308tooling::Replacements sortUsingDeclarations(const FormatStyle &Style,
2309 StringRef Code,
2310 ArrayRef<tooling::Range> Ranges,
2311 StringRef FileName) {
Eric Liu2e538082018-05-09 21:35:52 +00002312 return UsingDeclarationsSorter(Environment(Code, FileName, Ranges), Style)
2313 .process()
2314 .first;
Krasimir Georgievb03877a2017-06-21 12:03:12 +00002315}
2316
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002317LangOptions getFormattingLangOpts(const FormatStyle &Style) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002318 LangOptions LangOpts;
2319 LangOpts.CPlusPlus = 1;
Daniel Jasper4db69bd2014-09-04 18:23:42 +00002320 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2321 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002322 LangOpts.CPlusPlus17 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Richard Smithc70f1d62017-12-14 15:16:18 +00002323 LangOpts.CPlusPlus2a = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00002324 LangOpts.LineComment = 1;
Daniel Jasper1dbc2102017-03-31 13:30:24 +00002325 bool AlternativeOperators = Style.isCpp();
Daniel Jasper30a24062014-11-14 09:02:28 +00002326 LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002327 LangOpts.Bool = 1;
Erik Pilkingtonfa983902018-10-30 20:31:30 +00002328 LangOpts.ObjC = 1;
Eric Liu4cfb88a2016-04-25 15:09:22 +00002329 LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
Saleem Abdulrasoold170c4b2015-10-04 17:51:05 +00002330 LangOpts.DeclSpecKeyword = 1; // To get __declspec.
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002331 return LangOpts;
2332}
2333
Edwin Vaned544aa72013-09-30 13:31:48 +00002334const char *StyleOptionHelpDescription =
2335 "Coding style, currently supports:\n"
2336 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
2337 "Use -style=file to load style configuration from\n"
2338 ".clang-format file located in one of the parent\n"
2339 "directories of the source file (or current\n"
2340 "directory for stdin).\n"
2341 "Use -style=\"{key: value, ...}\" to set specific\n"
2342 "parameters, e.g.:\n"
2343 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
2344
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002345static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
Daniel Jasper498f5582015-12-25 08:53:31 +00002346 if (FileName.endswith(".java"))
Daniel Jasperc58c70e2014-09-15 11:21:46 +00002347 return FormatStyle::LK_Java;
Daniel Jasper498f5582015-12-25 08:53:31 +00002348 if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts"))
2349 return FormatStyle::LK_JavaScript; // JavaScript or TypeScript.
Daniel Jasper03a04fe2016-12-12 12:42:29 +00002350 if (FileName.endswith(".m") || FileName.endswith(".mm"))
2351 return FormatStyle::LK_ObjC;
Daniel Jasper498f5582015-12-25 08:53:31 +00002352 if (FileName.endswith_lower(".proto") ||
2353 FileName.endswith_lower(".protodevel"))
Daniel Jasper7052ce62014-01-19 09:04:08 +00002354 return FormatStyle::LK_Proto;
Krasimir Georgiev66496652017-11-17 15:10:49 +00002355 if (FileName.endswith_lower(".textpb") ||
2356 FileName.endswith_lower(".pb.txt") ||
2357 FileName.endswith_lower(".textproto") ||
2358 FileName.endswith_lower(".asciipb"))
2359 return FormatStyle::LK_TextProto;
Daniel Jasper498f5582015-12-25 08:53:31 +00002360 if (FileName.endswith_lower(".td"))
2361 return FormatStyle::LK_TableGen;
Paul Hoadcbb726d2019-03-21 13:09:22 +00002362 if (FileName.endswith_lower(".cs"))
2363 return FormatStyle::LK_CSharp;
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002364 return FormatStyle::LK_Cpp;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002365}
2366
Ben Hamilton3b345c32018-02-21 15:54:31 +00002367FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code) {
Ben Hamilton6e066352018-02-27 15:56:40 +00002368 const auto GuessedLanguage = getLanguageByFileName(FileName);
2369 if (GuessedLanguage == FormatStyle::LK_Cpp) {
Ben Hamilton07e58362018-02-21 21:27:27 +00002370 auto Extension = llvm::sys::path::extension(FileName);
Ben Hamilton3b345c32018-02-21 15:54:31 +00002371 // If there's no file extension (or it's .h), we need to check the contents
2372 // of the code to see if it contains Objective-C.
Ben Hamilton07e58362018-02-21 21:27:27 +00002373 if (Extension.empty() || Extension == ".h") {
2374 auto NonEmptyFileName = FileName.empty() ? "guess.h" : FileName;
Eric Liu2e538082018-05-09 21:35:52 +00002375 Environment Env(Code, NonEmptyFileName, /*Ranges=*/{});
2376 ObjCHeaderStyleGuesser Guesser(Env, getLLVMStyle());
Ben Hamilton3b345c32018-02-21 15:54:31 +00002377 Guesser.process();
Ben Hamilton6e066352018-02-27 15:56:40 +00002378 if (Guesser.isObjC())
2379 return FormatStyle::LK_ObjC;
Ben Hamilton3b345c32018-02-21 15:54:31 +00002380 }
2381 }
Ben Hamilton6e066352018-02-27 15:56:40 +00002382 return GuessedLanguage;
Ben Hamilton3b345c32018-02-21 15:54:31 +00002383}
2384
Eric Liub4adc912018-06-25 16:29:19 +00002385const char *DefaultFormatStyle = "file";
2386
2387const char *DefaultFallbackStyle = "LLVM";
2388
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00002389llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
Antonio Maiorano7eb75072017-01-20 01:22:42 +00002390 StringRef FallbackStyleName,
Jonas Devliegherefc514902018-10-10 13:27:25 +00002391 StringRef Code,
2392 llvm::vfs::FileSystem *FS) {
Eric Liu547d8792016-03-24 13:22:42 +00002393 if (!FS) {
Jonas Devliegherefc514902018-10-10 13:27:25 +00002394 FS = llvm::vfs::getRealFileSystem().get();
Eric Liu547d8792016-03-24 13:22:42 +00002395 }
Jordan Rupprecht8bd97e72019-02-28 19:16:45 +00002396 FormatStyle Style = getLLVMStyle(guessLanguage(FileName, Code));
Daniel Jasper03a04fe2016-12-12 12:42:29 +00002397
Antonio Maiorano7eb75072017-01-20 01:22:42 +00002398 FormatStyle FallbackStyle = getNoStyle();
2399 if (!getPredefinedStyle(FallbackStyleName, Style.Language, &FallbackStyle))
2400 return make_string_error("Invalid fallback style \"" + FallbackStyleName);
Edwin Vaned544aa72013-09-30 13:31:48 +00002401
2402 if (StyleName.startswith("{")) {
2403 // Parse YAML/JSON style from the command line.
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00002404 if (std::error_code ec = parseConfiguration(StyleName, &Style))
2405 return make_string_error("Error parsing -style: " + ec.message());
Edwin Vaned544aa72013-09-30 13:31:48 +00002406 return Style;
2407 }
2408
2409 if (!StyleName.equals_lower("file")) {
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002410 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00002411 return make_string_error("Invalid value for -style");
Edwin Vaned544aa72013-09-30 13:31:48 +00002412 return Style;
2413 }
2414
Alexander Kornienkoc1637f12013-12-10 11:28:13 +00002415 // Look for .clang-format/_clang-format file in the file's parent directories.
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002416 SmallString<128> UnsuitableConfigFiles;
Edwin Vaned544aa72013-09-30 13:31:48 +00002417 SmallString<128> Path(FileName);
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00002418 if (std::error_code EC = FS->makeAbsolute(Path))
2419 return make_string_error(EC.message());
Antonio Maiorano34c03762016-12-22 05:10:07 +00002420
Alexander Kornienkoe2e03872013-10-14 00:46:35 +00002421 for (StringRef Directory = Path; !Directory.empty();
Edwin Vaned544aa72013-09-30 13:31:48 +00002422 Directory = llvm::sys::path::parent_path(Directory)) {
Eric Liu547d8792016-03-24 13:22:42 +00002423
2424 auto Status = FS->status(Directory);
2425 if (!Status ||
2426 Status->getType() != llvm::sys::fs::file_type::directory_file) {
Edwin Vaned544aa72013-09-30 13:31:48 +00002427 continue;
Eric Liu547d8792016-03-24 13:22:42 +00002428 }
2429
Edwin Vaned544aa72013-09-30 13:31:48 +00002430 SmallString<128> ConfigFile(Directory);
2431
2432 llvm::sys::path::append(ConfigFile, ".clang-format");
Nicola Zaghen3538b392018-05-15 13:30:56 +00002433 LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
Eric Liud4758322016-03-24 13:22:37 +00002434
Eric Liu547d8792016-03-24 13:22:42 +00002435 Status = FS->status(ConfigFile.str());
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00002436 bool FoundConfigFile =
Eric Liu547d8792016-03-24 13:22:42 +00002437 Status && (Status->getType() == llvm::sys::fs::file_type::regular_file);
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00002438 if (!FoundConfigFile) {
Edwin Vaned544aa72013-09-30 13:31:48 +00002439 // Try _clang-format too, since dotfiles are not commonly used on Windows.
2440 ConfigFile = Directory;
2441 llvm::sys::path::append(ConfigFile, "_clang-format");
Nicola Zaghen3538b392018-05-15 13:30:56 +00002442 LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
Eric Liu547d8792016-03-24 13:22:42 +00002443 Status = FS->status(ConfigFile.str());
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00002444 FoundConfigFile = Status && (Status->getType() ==
2445 llvm::sys::fs::file_type::regular_file);
Edwin Vaned544aa72013-09-30 13:31:48 +00002446 }
2447
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00002448 if (FoundConfigFile) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002449 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
Eric Liu547d8792016-03-24 13:22:42 +00002450 FS->getBufferForFile(ConfigFile.str());
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00002451 if (std::error_code EC = Text.getError())
2452 return make_string_error(EC.message());
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002453 if (std::error_code ec =
2454 parseConfiguration(Text.get()->getBuffer(), &Style)) {
Rafael Espindolad0136702014-06-12 02:50:04 +00002455 if (ec == ParseError::Unsuitable) {
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002456 if (!UnsuitableConfigFiles.empty())
2457 UnsuitableConfigFiles.append(", ");
2458 UnsuitableConfigFiles.append(ConfigFile);
Alexander Kornienkobc4ae442013-12-02 15:21:38 +00002459 continue;
Alexander Kornienkocabdd732013-11-29 15:19:43 +00002460 }
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00002461 return make_string_error("Error reading " + ConfigFile + ": " +
2462 ec.message());
Edwin Vaned544aa72013-09-30 13:31:48 +00002463 }
Nicola Zaghen3538b392018-05-15 13:30:56 +00002464 LLVM_DEBUG(llvm::dbgs()
2465 << "Using configuration file " << ConfigFile << "\n");
Edwin Vaned544aa72013-09-30 13:31:48 +00002466 return Style;
2467 }
2468 }
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +00002469 if (!UnsuitableConfigFiles.empty())
2470 return make_string_error("Configuration file(s) do(es) not support " +
2471 getLanguageName(Style.Language) + ": " +
2472 UnsuitableConfigFiles);
Antonio Maiorano7eb75072017-01-20 01:22:42 +00002473 return FallbackStyle;
Edwin Vaned544aa72013-09-30 13:31:48 +00002474}
2475
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002476} // namespace format
2477} // namespace clang