clang  19.0.0git
Format.cpp
Go to the documentation of this file.
1 //===--- Format.cpp - Format C++ code -------------------------------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file implements functions declared in Format.h. This will be
11 /// split into separate files as we go.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/Format/Format.h"
21 #include "SortJavaScriptImports.h"
22 #include "UnwrappedLineFormatter.h"
25 #include "llvm/ADT/Sequence.h"
26 
27 #define DEBUG_TYPE "format-formatter"
28 
30 
31 LLVM_YAML_IS_SEQUENCE_VECTOR(FormatStyle::RawStringFormat)
32 
33 namespace llvm {
34 namespace yaml {
35 template <>
36 struct ScalarEnumerationTraits<FormatStyle::BreakBeforeNoexceptSpecifierStyle> {
37  static void
38  enumeration(IO &IO, FormatStyle::BreakBeforeNoexceptSpecifierStyle &Value) {
39  IO.enumCase(Value, "Never", FormatStyle::BBNSS_Never);
40  IO.enumCase(Value, "OnlyWithParen", FormatStyle::BBNSS_OnlyWithParen);
41  IO.enumCase(Value, "Always", FormatStyle::BBNSS_Always);
42  }
43 };
44 
45 template <> struct MappingTraits<FormatStyle::AlignConsecutiveStyle> {
46  static void enumInput(IO &IO, FormatStyle::AlignConsecutiveStyle &Value) {
47  IO.enumCase(Value, "None",
48  FormatStyle::AlignConsecutiveStyle(
49  {/*Enabled=*/false, /*AcrossEmptyLines=*/false,
50  /*AcrossComments=*/false, /*AlignCompound=*/false,
51  /*AlignFunctionPointers=*/false, /*PadOperators=*/true}));
52  IO.enumCase(Value, "Consecutive",
53  FormatStyle::AlignConsecutiveStyle(
54  {/*Enabled=*/true, /*AcrossEmptyLines=*/false,
55  /*AcrossComments=*/false, /*AlignCompound=*/false,
56  /*AlignFunctionPointers=*/false, /*PadOperators=*/true}));
57  IO.enumCase(Value, "AcrossEmptyLines",
58  FormatStyle::AlignConsecutiveStyle(
59  {/*Enabled=*/true, /*AcrossEmptyLines=*/true,
60  /*AcrossComments=*/false, /*AlignCompound=*/false,
61  /*AlignFunctionPointers=*/false, /*PadOperators=*/true}));
62  IO.enumCase(Value, "AcrossComments",
63  FormatStyle::AlignConsecutiveStyle(
64  {/*Enabled=*/true, /*AcrossEmptyLines=*/false,
65  /*AcrossComments=*/true, /*AlignCompound=*/false,
66  /*AlignFunctionPointers=*/false, /*PadOperators=*/true}));
67  IO.enumCase(Value, "AcrossEmptyLinesAndComments",
68  FormatStyle::AlignConsecutiveStyle(
69  {/*Enabled=*/true, /*AcrossEmptyLines=*/true,
70  /*AcrossComments=*/true, /*AlignCompound=*/false,
71  /*AlignFunctionPointers=*/false, /*PadOperators=*/true}));
72 
73  // For backward compatibility.
74  IO.enumCase(Value, "true",
75  FormatStyle::AlignConsecutiveStyle(
76  {/*Enabled=*/true, /*AcrossEmptyLines=*/false,
77  /*AcrossComments=*/false, /*AlignCompound=*/false,
78  /*AlignFunctionPointers=*/false, /*PadOperators=*/true}));
79  IO.enumCase(Value, "false",
80  FormatStyle::AlignConsecutiveStyle(
81  {/*Enabled=*/false, /*AcrossEmptyLines=*/false,
82  /*AcrossComments=*/false, /*AlignCompound=*/false,
83  /*AlignFunctionPointers=*/false, /*PadOperators=*/true}));
84  }
85 
86  static void mapping(IO &IO, FormatStyle::AlignConsecutiveStyle &Value) {
87  IO.mapOptional("Enabled", Value.Enabled);
88  IO.mapOptional("AcrossEmptyLines", Value.AcrossEmptyLines);
89  IO.mapOptional("AcrossComments", Value.AcrossComments);
90  IO.mapOptional("AlignCompound", Value.AlignCompound);
91  IO.mapOptional("AlignFunctionPointers", Value.AlignFunctionPointers);
92  IO.mapOptional("PadOperators", Value.PadOperators);
93  }
94 };
95 
96 template <>
97 struct MappingTraits<FormatStyle::ShortCaseStatementsAlignmentStyle> {
98  static void mapping(IO &IO,
99  FormatStyle::ShortCaseStatementsAlignmentStyle &Value) {
100  IO.mapOptional("Enabled", Value.Enabled);
101  IO.mapOptional("AcrossEmptyLines", Value.AcrossEmptyLines);
102  IO.mapOptional("AcrossComments", Value.AcrossComments);
103  IO.mapOptional("AlignCaseArrows", Value.AlignCaseArrows);
104  IO.mapOptional("AlignCaseColons", Value.AlignCaseColons);
105  }
106 };
107 
108 template <>
109 struct ScalarEnumerationTraits<FormatStyle::AttributeBreakingStyle> {
110  static void enumeration(IO &IO, FormatStyle::AttributeBreakingStyle &Value) {
111  IO.enumCase(Value, "Always", FormatStyle::ABS_Always);
112  IO.enumCase(Value, "Leave", FormatStyle::ABS_Leave);
113  IO.enumCase(Value, "Never", FormatStyle::ABS_Never);
114  }
115 };
116 
117 template <>
118 struct ScalarEnumerationTraits<FormatStyle::ArrayInitializerAlignmentStyle> {
119  static void enumeration(IO &IO,
120  FormatStyle::ArrayInitializerAlignmentStyle &Value) {
121  IO.enumCase(Value, "None", FormatStyle::AIAS_None);
122  IO.enumCase(Value, "Left", FormatStyle::AIAS_Left);
123  IO.enumCase(Value, "Right", FormatStyle::AIAS_Right);
124  }
125 };
126 
127 template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
128  static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
129  IO.enumCase(Value, "All", FormatStyle::BOS_All);
130  IO.enumCase(Value, "true", FormatStyle::BOS_All);
131  IO.enumCase(Value, "None", FormatStyle::BOS_None);
132  IO.enumCase(Value, "false", FormatStyle::BOS_None);
133  IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
134  }
135 };
136 
137 template <> struct ScalarEnumerationTraits<FormatStyle::BinPackStyle> {
138  static void enumeration(IO &IO, FormatStyle::BinPackStyle &Value) {
139  IO.enumCase(Value, "Auto", FormatStyle::BPS_Auto);
140  IO.enumCase(Value, "Always", FormatStyle::BPS_Always);
141  IO.enumCase(Value, "Never", FormatStyle::BPS_Never);
142  }
143 };
144 
145 template <>
146 struct ScalarEnumerationTraits<FormatStyle::BitFieldColonSpacingStyle> {
147  static void enumeration(IO &IO,
148  FormatStyle::BitFieldColonSpacingStyle &Value) {
149  IO.enumCase(Value, "Both", FormatStyle::BFCS_Both);
150  IO.enumCase(Value, "None", FormatStyle::BFCS_None);
151  IO.enumCase(Value, "Before", FormatStyle::BFCS_Before);
152  IO.enumCase(Value, "After", FormatStyle::BFCS_After);
153  }
154 };
155 
156 template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
157  static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
158  IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
159  IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
160  IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
161  IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
162  IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
163  IO.enumCase(Value, "Whitesmiths", FormatStyle::BS_Whitesmiths);
164  IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
165  IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
166  IO.enumCase(Value, "Custom", FormatStyle::BS_Custom);
167  }
168 };
169 
170 template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
171  static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
172  IO.mapOptional("AfterCaseLabel", Wrapping.AfterCaseLabel);
173  IO.mapOptional("AfterClass", Wrapping.AfterClass);
174  IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
175  IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
176  IO.mapOptional("AfterExternBlock", Wrapping.AfterExternBlock);
177  IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
178  IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
179  IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
180  IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
181  IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
182  IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
183  IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
184  IO.mapOptional("BeforeLambdaBody", Wrapping.BeforeLambdaBody);
185  IO.mapOptional("BeforeWhile", Wrapping.BeforeWhile);
186  IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
187  IO.mapOptional("SplitEmptyFunction", Wrapping.SplitEmptyFunction);
188  IO.mapOptional("SplitEmptyRecord", Wrapping.SplitEmptyRecord);
189  IO.mapOptional("SplitEmptyNamespace", Wrapping.SplitEmptyNamespace);
190  }
191 };
192 
193 template <> struct ScalarEnumerationTraits<FormatStyle::BracketAlignmentStyle> {
194  static void enumeration(IO &IO, FormatStyle::BracketAlignmentStyle &Value) {
195  IO.enumCase(Value, "Align", FormatStyle::BAS_Align);
196  IO.enumCase(Value, "DontAlign", FormatStyle::BAS_DontAlign);
197  IO.enumCase(Value, "AlwaysBreak", FormatStyle::BAS_AlwaysBreak);
198  IO.enumCase(Value, "BlockIndent", FormatStyle::BAS_BlockIndent);
199 
200  // For backward compatibility.
201  IO.enumCase(Value, "true", FormatStyle::BAS_Align);
202  IO.enumCase(Value, "false", FormatStyle::BAS_DontAlign);
203  }
204 };
205 
206 template <>
207 struct ScalarEnumerationTraits<
208  FormatStyle::BraceWrappingAfterControlStatementStyle> {
209  static void
210  enumeration(IO &IO,
211  FormatStyle::BraceWrappingAfterControlStatementStyle &Value) {
212  IO.enumCase(Value, "Never", FormatStyle::BWACS_Never);
213  IO.enumCase(Value, "MultiLine", FormatStyle::BWACS_MultiLine);
214  IO.enumCase(Value, "Always", FormatStyle::BWACS_Always);
215 
216  // For backward compatibility.
217  IO.enumCase(Value, "false", FormatStyle::BWACS_Never);
218  IO.enumCase(Value, "true", FormatStyle::BWACS_Always);
219  }
220 };
221 
222 template <>
223 struct ScalarEnumerationTraits<
224  FormatStyle::BreakBeforeConceptDeclarationsStyle> {
225  static void
226  enumeration(IO &IO, FormatStyle::BreakBeforeConceptDeclarationsStyle &Value) {
227  IO.enumCase(Value, "Never", FormatStyle::BBCDS_Never);
228  IO.enumCase(Value, "Allowed", FormatStyle::BBCDS_Allowed);
229  IO.enumCase(Value, "Always", FormatStyle::BBCDS_Always);
230 
231  // For backward compatibility.
232  IO.enumCase(Value, "true", FormatStyle::BBCDS_Always);
233  IO.enumCase(Value, "false", FormatStyle::BBCDS_Allowed);
234  }
235 };
236 
237 template <>
238 struct ScalarEnumerationTraits<FormatStyle::BreakBeforeInlineASMColonStyle> {
239  static void enumeration(IO &IO,
240  FormatStyle::BreakBeforeInlineASMColonStyle &Value) {
241  IO.enumCase(Value, "Never", FormatStyle::BBIAS_Never);
242  IO.enumCase(Value, "OnlyMultiline", FormatStyle::BBIAS_OnlyMultiline);
243  IO.enumCase(Value, "Always", FormatStyle::BBIAS_Always);
244  }
245 };
246 
247 template <>
248 struct ScalarEnumerationTraits<FormatStyle::BreakConstructorInitializersStyle> {
249  static void
250  enumeration(IO &IO, FormatStyle::BreakConstructorInitializersStyle &Value) {
251  IO.enumCase(Value, "BeforeColon", FormatStyle::BCIS_BeforeColon);
252  IO.enumCase(Value, "BeforeComma", FormatStyle::BCIS_BeforeComma);
253  IO.enumCase(Value, "AfterColon", FormatStyle::BCIS_AfterColon);
254  }
255 };
256 
257 template <>
258 struct ScalarEnumerationTraits<FormatStyle::BreakInheritanceListStyle> {
259  static void enumeration(IO &IO,
260  FormatStyle::BreakInheritanceListStyle &Value) {
261  IO.enumCase(Value, "BeforeColon", FormatStyle::BILS_BeforeColon);
262  IO.enumCase(Value, "BeforeComma", FormatStyle::BILS_BeforeComma);
263  IO.enumCase(Value, "AfterColon", FormatStyle::BILS_AfterColon);
264  IO.enumCase(Value, "AfterComma", FormatStyle::BILS_AfterComma);
265  }
266 };
267 
268 template <>
269 struct ScalarEnumerationTraits<FormatStyle::BreakTemplateDeclarationsStyle> {
270  static void enumeration(IO &IO,
271  FormatStyle::BreakTemplateDeclarationsStyle &Value) {
272  IO.enumCase(Value, "Leave", FormatStyle::BTDS_Leave);
273  IO.enumCase(Value, "No", FormatStyle::BTDS_No);
274  IO.enumCase(Value, "MultiLine", FormatStyle::BTDS_MultiLine);
275  IO.enumCase(Value, "Yes", FormatStyle::BTDS_Yes);
276 
277  // For backward compatibility.
278  IO.enumCase(Value, "false", FormatStyle::BTDS_MultiLine);
279  IO.enumCase(Value, "true", FormatStyle::BTDS_Yes);
280  }
281 };
282 
283 template <> struct ScalarEnumerationTraits<FormatStyle::DAGArgStyle> {
284  static void enumeration(IO &IO, FormatStyle::DAGArgStyle &Value) {
285  IO.enumCase(Value, "DontBreak", FormatStyle::DAS_DontBreak);
286  IO.enumCase(Value, "BreakElements", FormatStyle::DAS_BreakElements);
287  IO.enumCase(Value, "BreakAll", FormatStyle::DAS_BreakAll);
288  }
289 };
290 
291 template <>
292 struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
293  static void
294  enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) {
295  IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
296  IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
297  IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
298 
299  // For backward compatibility.
300  IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
301  IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
302  }
303 };
304 
305 template <>
306 struct ScalarEnumerationTraits<FormatStyle::EscapedNewlineAlignmentStyle> {
307  static void enumeration(IO &IO,
308  FormatStyle::EscapedNewlineAlignmentStyle &Value) {
309  IO.enumCase(Value, "DontAlign", FormatStyle::ENAS_DontAlign);
310  IO.enumCase(Value, "Left", FormatStyle::ENAS_Left);
311  IO.enumCase(Value, "LeftWithLastLine", FormatStyle::ENAS_LeftWithLastLine);
312  IO.enumCase(Value, "Right", FormatStyle::ENAS_Right);
313 
314  // For backward compatibility.
315  IO.enumCase(Value, "true", FormatStyle::ENAS_Left);
316  IO.enumCase(Value, "false", FormatStyle::ENAS_Right);
317  }
318 };
319 
320 template <>
321 struct ScalarEnumerationTraits<FormatStyle::EmptyLineAfterAccessModifierStyle> {
322  static void
323  enumeration(IO &IO, FormatStyle::EmptyLineAfterAccessModifierStyle &Value) {
324  IO.enumCase(Value, "Never", FormatStyle::ELAAMS_Never);
325  IO.enumCase(Value, "Leave", FormatStyle::ELAAMS_Leave);
326  IO.enumCase(Value, "Always", FormatStyle::ELAAMS_Always);
327  }
328 };
329 
330 template <>
331 struct ScalarEnumerationTraits<
332  FormatStyle::EmptyLineBeforeAccessModifierStyle> {
333  static void
334  enumeration(IO &IO, FormatStyle::EmptyLineBeforeAccessModifierStyle &Value) {
335  IO.enumCase(Value, "Never", FormatStyle::ELBAMS_Never);
336  IO.enumCase(Value, "Leave", FormatStyle::ELBAMS_Leave);
337  IO.enumCase(Value, "LogicalBlock", FormatStyle::ELBAMS_LogicalBlock);
338  IO.enumCase(Value, "Always", FormatStyle::ELBAMS_Always);
339  }
340 };
341 
342 template <>
343 struct ScalarEnumerationTraits<FormatStyle::IndentExternBlockStyle> {
344  static void enumeration(IO &IO, FormatStyle::IndentExternBlockStyle &Value) {
345  IO.enumCase(Value, "AfterExternBlock", FormatStyle::IEBS_AfterExternBlock);
346  IO.enumCase(Value, "Indent", FormatStyle::IEBS_Indent);
347  IO.enumCase(Value, "NoIndent", FormatStyle::IEBS_NoIndent);
348  IO.enumCase(Value, "true", FormatStyle::IEBS_Indent);
349  IO.enumCase(Value, "false", FormatStyle::IEBS_NoIndent);
350  }
351 };
352 
353 template <> struct MappingTraits<FormatStyle::IntegerLiteralSeparatorStyle> {
354  static void mapping(IO &IO, FormatStyle::IntegerLiteralSeparatorStyle &Base) {
355  IO.mapOptional("Binary", Base.Binary);
356  IO.mapOptional("BinaryMinDigits", Base.BinaryMinDigits);
357  IO.mapOptional("Decimal", Base.Decimal);
358  IO.mapOptional("DecimalMinDigits", Base.DecimalMinDigits);
359  IO.mapOptional("Hex", Base.Hex);
360  IO.mapOptional("HexMinDigits", Base.HexMinDigits);
361  }
362 };
363 
364 template <> struct ScalarEnumerationTraits<FormatStyle::JavaScriptQuoteStyle> {
365  static void enumeration(IO &IO, FormatStyle::JavaScriptQuoteStyle &Value) {
366  IO.enumCase(Value, "Leave", FormatStyle::JSQS_Leave);
367  IO.enumCase(Value, "Single", FormatStyle::JSQS_Single);
368  IO.enumCase(Value, "Double", FormatStyle::JSQS_Double);
369  }
370 };
371 
372 template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
373  static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
374  IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
375  IO.enumCase(Value, "Java", FormatStyle::LK_Java);
376  IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
377  IO.enumCase(Value, "ObjC", FormatStyle::LK_ObjC);
378  IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
379  IO.enumCase(Value, "TableGen", FormatStyle::LK_TableGen);
380  IO.enumCase(Value, "TextProto", FormatStyle::LK_TextProto);
381  IO.enumCase(Value, "CSharp", FormatStyle::LK_CSharp);
382  IO.enumCase(Value, "Json", FormatStyle::LK_Json);
383  IO.enumCase(Value, "Verilog", FormatStyle::LK_Verilog);
384  }
385 };
386 
387 template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
388  static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
389  IO.enumCase(Value, "c++03", FormatStyle::LS_Cpp03);
390  IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03); // Legacy alias
391  IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03); // Legacy alias
392 
393  IO.enumCase(Value, "c++11", FormatStyle::LS_Cpp11);
394  IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11); // Legacy alias
395 
396  IO.enumCase(Value, "c++14", FormatStyle::LS_Cpp14);
397  IO.enumCase(Value, "c++17", FormatStyle::LS_Cpp17);
398  IO.enumCase(Value, "c++20", FormatStyle::LS_Cpp20);
399 
400  IO.enumCase(Value, "Latest", FormatStyle::LS_Latest);
401  IO.enumCase(Value, "Cpp11", FormatStyle::LS_Latest); // Legacy alias
402  IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
403  }
404 };
405 
406 template <>
407 struct ScalarEnumerationTraits<FormatStyle::LambdaBodyIndentationKind> {
408  static void enumeration(IO &IO,
409  FormatStyle::LambdaBodyIndentationKind &Value) {
410  IO.enumCase(Value, "Signature", FormatStyle::LBI_Signature);
411  IO.enumCase(Value, "OuterScope", FormatStyle::LBI_OuterScope);
412  }
413 };
414 
415 template <> struct ScalarEnumerationTraits<FormatStyle::LineEndingStyle> {
416  static void enumeration(IO &IO, FormatStyle::LineEndingStyle &Value) {
417  IO.enumCase(Value, "LF", FormatStyle::LE_LF);
418  IO.enumCase(Value, "CRLF", FormatStyle::LE_CRLF);
419  IO.enumCase(Value, "DeriveLF", FormatStyle::LE_DeriveLF);
420  IO.enumCase(Value, "DeriveCRLF", FormatStyle::LE_DeriveCRLF);
421  }
422 };
423 
424 template <>
425 struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
426  static void enumeration(IO &IO,
427  FormatStyle::NamespaceIndentationKind &Value) {
428  IO.enumCase(Value, "None", FormatStyle::NI_None);
429  IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
430  IO.enumCase(Value, "All", FormatStyle::NI_All);
431  }
432 };
433 
434 template <> struct ScalarEnumerationTraits<FormatStyle::OperandAlignmentStyle> {
435  static void enumeration(IO &IO, FormatStyle::OperandAlignmentStyle &Value) {
436  IO.enumCase(Value, "DontAlign", FormatStyle::OAS_DontAlign);
437  IO.enumCase(Value, "Align", FormatStyle::OAS_Align);
438  IO.enumCase(Value, "AlignAfterOperator",
439  FormatStyle::OAS_AlignAfterOperator);
440 
441  // For backward compatibility.
442  IO.enumCase(Value, "true", FormatStyle::OAS_Align);
443  IO.enumCase(Value, "false", FormatStyle::OAS_DontAlign);
444  }
445 };
446 
447 template <>
448 struct ScalarEnumerationTraits<FormatStyle::PackConstructorInitializersStyle> {
449  static void
450  enumeration(IO &IO, FormatStyle::PackConstructorInitializersStyle &Value) {
451  IO.enumCase(Value, "Never", FormatStyle::PCIS_Never);
452  IO.enumCase(Value, "BinPack", FormatStyle::PCIS_BinPack);
453  IO.enumCase(Value, "CurrentLine", FormatStyle::PCIS_CurrentLine);
454  IO.enumCase(Value, "NextLine", FormatStyle::PCIS_NextLine);
455  IO.enumCase(Value, "NextLineOnly", FormatStyle::PCIS_NextLineOnly);
456  }
457 };
458 
459 template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
460  static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
461  IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
462  IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
463  IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
464 
465  // For backward compatibility.
466  IO.enumCase(Value, "true", FormatStyle::PAS_Left);
467  IO.enumCase(Value, "false", FormatStyle::PAS_Right);
468  }
469 };
470 
471 template <>
472 struct ScalarEnumerationTraits<FormatStyle::PPDirectiveIndentStyle> {
473  static void enumeration(IO &IO, FormatStyle::PPDirectiveIndentStyle &Value) {
474  IO.enumCase(Value, "None", FormatStyle::PPDIS_None);
475  IO.enumCase(Value, "AfterHash", FormatStyle::PPDIS_AfterHash);
476  IO.enumCase(Value, "BeforeHash", FormatStyle::PPDIS_BeforeHash);
477  }
478 };
479 
480 template <>
481 struct ScalarEnumerationTraits<FormatStyle::QualifierAlignmentStyle> {
482  static void enumeration(IO &IO, FormatStyle::QualifierAlignmentStyle &Value) {
483  IO.enumCase(Value, "Leave", FormatStyle::QAS_Leave);
484  IO.enumCase(Value, "Left", FormatStyle::QAS_Left);
485  IO.enumCase(Value, "Right", FormatStyle::QAS_Right);
486  IO.enumCase(Value, "Custom", FormatStyle::QAS_Custom);
487  }
488 };
489 
490 template <> struct MappingTraits<FormatStyle::RawStringFormat> {
491  static void mapping(IO &IO, FormatStyle::RawStringFormat &Format) {
492  IO.mapOptional("Language", Format.Language);
493  IO.mapOptional("Delimiters", Format.Delimiters);
494  IO.mapOptional("EnclosingFunctions", Format.EnclosingFunctions);
495  IO.mapOptional("CanonicalDelimiter", Format.CanonicalDelimiter);
496  IO.mapOptional("BasedOnStyle", Format.BasedOnStyle);
497  }
498 };
499 
500 template <>
501 struct ScalarEnumerationTraits<FormatStyle::ReferenceAlignmentStyle> {
502  static void enumeration(IO &IO, FormatStyle::ReferenceAlignmentStyle &Value) {
503  IO.enumCase(Value, "Pointer", FormatStyle::RAS_Pointer);
504  IO.enumCase(Value, "Middle", FormatStyle::RAS_Middle);
505  IO.enumCase(Value, "Left", FormatStyle::RAS_Left);
506  IO.enumCase(Value, "Right", FormatStyle::RAS_Right);
507  }
508 };
509 
510 template <>
511 struct ScalarEnumerationTraits<FormatStyle::RemoveParenthesesStyle> {
512  static void enumeration(IO &IO, FormatStyle::RemoveParenthesesStyle &Value) {
513  IO.enumCase(Value, "Leave", FormatStyle::RPS_Leave);
514  IO.enumCase(Value, "MultipleParentheses",
515  FormatStyle::RPS_MultipleParentheses);
516  IO.enumCase(Value, "ReturnStatement", FormatStyle::RPS_ReturnStatement);
517  }
518 };
519 
520 template <>
521 struct ScalarEnumerationTraits<FormatStyle::RequiresClausePositionStyle> {
522  static void enumeration(IO &IO,
523  FormatStyle::RequiresClausePositionStyle &Value) {
524  IO.enumCase(Value, "OwnLine", FormatStyle::RCPS_OwnLine);
525  IO.enumCase(Value, "WithPreceding", FormatStyle::RCPS_WithPreceding);
526  IO.enumCase(Value, "WithFollowing", FormatStyle::RCPS_WithFollowing);
527  IO.enumCase(Value, "SingleLine", FormatStyle::RCPS_SingleLine);
528  }
529 };
530 
531 template <>
532 struct ScalarEnumerationTraits<FormatStyle::RequiresExpressionIndentationKind> {
533  static void
534  enumeration(IO &IO, FormatStyle::RequiresExpressionIndentationKind &Value) {
535  IO.enumCase(Value, "Keyword", FormatStyle::REI_Keyword);
536  IO.enumCase(Value, "OuterScope", FormatStyle::REI_OuterScope);
537  }
538 };
539 
540 template <>
541 struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
542  static void enumeration(IO &IO, FormatStyle::ReturnTypeBreakingStyle &Value) {
543  IO.enumCase(Value, "None", FormatStyle::RTBS_None);
544  IO.enumCase(Value, "Automatic", FormatStyle::RTBS_Automatic);
545  IO.enumCase(Value, "ExceptShortType", FormatStyle::RTBS_ExceptShortType);
546  IO.enumCase(Value, "All", FormatStyle::RTBS_All);
547  IO.enumCase(Value, "TopLevel", FormatStyle::RTBS_TopLevel);
548  IO.enumCase(Value, "TopLevelDefinitions",
549  FormatStyle::RTBS_TopLevelDefinitions);
550  IO.enumCase(Value, "AllDefinitions", FormatStyle::RTBS_AllDefinitions);
551  }
552 };
553 
554 template <>
555 struct ScalarEnumerationTraits<FormatStyle::SeparateDefinitionStyle> {
556  static void enumeration(IO &IO, FormatStyle::SeparateDefinitionStyle &Value) {
557  IO.enumCase(Value, "Leave", FormatStyle::SDS_Leave);
558  IO.enumCase(Value, "Always", FormatStyle::SDS_Always);
559  IO.enumCase(Value, "Never", FormatStyle::SDS_Never);
560  }
561 };
562 
563 template <> struct ScalarEnumerationTraits<FormatStyle::ShortBlockStyle> {
564  static void enumeration(IO &IO, FormatStyle::ShortBlockStyle &Value) {
565  IO.enumCase(Value, "Never", FormatStyle::SBS_Never);
566  IO.enumCase(Value, "false", FormatStyle::SBS_Never);
567  IO.enumCase(Value, "Always", FormatStyle::SBS_Always);
568  IO.enumCase(Value, "true", FormatStyle::SBS_Always);
569  IO.enumCase(Value, "Empty", FormatStyle::SBS_Empty);
570  }
571 };
572 
573 template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
574  static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
575  IO.enumCase(Value, "None", FormatStyle::SFS_None);
576  IO.enumCase(Value, "false", FormatStyle::SFS_None);
577  IO.enumCase(Value, "All", FormatStyle::SFS_All);
578  IO.enumCase(Value, "true", FormatStyle::SFS_All);
579  IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
580  IO.enumCase(Value, "InlineOnly", FormatStyle::SFS_InlineOnly);
581  IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
582  }
583 };
584 
585 template <> struct ScalarEnumerationTraits<FormatStyle::ShortIfStyle> {
586  static void enumeration(IO &IO, FormatStyle::ShortIfStyle &Value) {
587  IO.enumCase(Value, "Never", FormatStyle::SIS_Never);
588  IO.enumCase(Value, "WithoutElse", FormatStyle::SIS_WithoutElse);
589  IO.enumCase(Value, "OnlyFirstIf", FormatStyle::SIS_OnlyFirstIf);
590  IO.enumCase(Value, "AllIfsAndElse", FormatStyle::SIS_AllIfsAndElse);
591 
592  // For backward compatibility.
593  IO.enumCase(Value, "Always", FormatStyle::SIS_OnlyFirstIf);
594  IO.enumCase(Value, "false", FormatStyle::SIS_Never);
595  IO.enumCase(Value, "true", FormatStyle::SIS_WithoutElse);
596  }
597 };
598 
599 template <> struct ScalarEnumerationTraits<FormatStyle::ShortLambdaStyle> {
600  static void enumeration(IO &IO, FormatStyle::ShortLambdaStyle &Value) {
601  IO.enumCase(Value, "None", FormatStyle::SLS_None);
602  IO.enumCase(Value, "false", FormatStyle::SLS_None);
603  IO.enumCase(Value, "Empty", FormatStyle::SLS_Empty);
604  IO.enumCase(Value, "Inline", FormatStyle::SLS_Inline);
605  IO.enumCase(Value, "All", FormatStyle::SLS_All);
606  IO.enumCase(Value, "true", FormatStyle::SLS_All);
607  }
608 };
609 
610 template <> struct ScalarEnumerationTraits<FormatStyle::SortIncludesOptions> {
611  static void enumeration(IO &IO, FormatStyle::SortIncludesOptions &Value) {
612  IO.enumCase(Value, "Never", FormatStyle::SI_Never);
613  IO.enumCase(Value, "CaseInsensitive", FormatStyle::SI_CaseInsensitive);
614  IO.enumCase(Value, "CaseSensitive", FormatStyle::SI_CaseSensitive);
615 
616  // For backward compatibility.
617  IO.enumCase(Value, "false", FormatStyle::SI_Never);
618  IO.enumCase(Value, "true", FormatStyle::SI_CaseSensitive);
619  }
620 };
621 
622 template <>
623 struct ScalarEnumerationTraits<FormatStyle::SortJavaStaticImportOptions> {
624  static void enumeration(IO &IO,
625  FormatStyle::SortJavaStaticImportOptions &Value) {
626  IO.enumCase(Value, "Before", FormatStyle::SJSIO_Before);
627  IO.enumCase(Value, "After", FormatStyle::SJSIO_After);
628  }
629 };
630 
631 template <>
632 struct ScalarEnumerationTraits<FormatStyle::SortUsingDeclarationsOptions> {
633  static void enumeration(IO &IO,
634  FormatStyle::SortUsingDeclarationsOptions &Value) {
635  IO.enumCase(Value, "Never", FormatStyle::SUD_Never);
636  IO.enumCase(Value, "Lexicographic", FormatStyle::SUD_Lexicographic);
637  IO.enumCase(Value, "LexicographicNumeric",
638  FormatStyle::SUD_LexicographicNumeric);
639 
640  // For backward compatibility.
641  IO.enumCase(Value, "false", FormatStyle::SUD_Never);
642  IO.enumCase(Value, "true", FormatStyle::SUD_LexicographicNumeric);
643  }
644 };
645 
646 template <>
647 struct ScalarEnumerationTraits<FormatStyle::SpaceAroundPointerQualifiersStyle> {
648  static void
649  enumeration(IO &IO, FormatStyle::SpaceAroundPointerQualifiersStyle &Value) {
650  IO.enumCase(Value, "Default", FormatStyle::SAPQ_Default);
651  IO.enumCase(Value, "Before", FormatStyle::SAPQ_Before);
652  IO.enumCase(Value, "After", FormatStyle::SAPQ_After);
653  IO.enumCase(Value, "Both", FormatStyle::SAPQ_Both);
654  }
655 };
656 
657 template <> struct MappingTraits<FormatStyle::SpaceBeforeParensCustom> {
658  static void mapping(IO &IO, FormatStyle::SpaceBeforeParensCustom &Spacing) {
659  IO.mapOptional("AfterControlStatements", Spacing.AfterControlStatements);
660  IO.mapOptional("AfterForeachMacros", Spacing.AfterForeachMacros);
661  IO.mapOptional("AfterFunctionDefinitionName",
662  Spacing.AfterFunctionDefinitionName);
663  IO.mapOptional("AfterFunctionDeclarationName",
664  Spacing.AfterFunctionDeclarationName);
665  IO.mapOptional("AfterIfMacros", Spacing.AfterIfMacros);
666  IO.mapOptional("AfterOverloadedOperator", Spacing.AfterOverloadedOperator);
667  IO.mapOptional("AfterPlacementOperator", Spacing.AfterPlacementOperator);
668  IO.mapOptional("AfterRequiresInClause", Spacing.AfterRequiresInClause);
669  IO.mapOptional("AfterRequiresInExpression",
670  Spacing.AfterRequiresInExpression);
671  IO.mapOptional("BeforeNonEmptyParentheses",
672  Spacing.BeforeNonEmptyParentheses);
673  }
674 };
675 
676 template <>
677 struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensStyle> {
678  static void enumeration(IO &IO, FormatStyle::SpaceBeforeParensStyle &Value) {
679  IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
680  IO.enumCase(Value, "ControlStatements",
681  FormatStyle::SBPO_ControlStatements);
682  IO.enumCase(Value, "ControlStatementsExceptControlMacros",
683  FormatStyle::SBPO_ControlStatementsExceptControlMacros);
684  IO.enumCase(Value, "NonEmptyParentheses",
685  FormatStyle::SBPO_NonEmptyParentheses);
686  IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
687  IO.enumCase(Value, "Custom", FormatStyle::SBPO_Custom);
688 
689  // For backward compatibility.
690  IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
691  IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
692  IO.enumCase(Value, "ControlStatementsExceptForEachMacros",
693  FormatStyle::SBPO_ControlStatementsExceptControlMacros);
694  }
695 };
696 
697 template <> struct ScalarEnumerationTraits<FormatStyle::SpacesInAnglesStyle> {
698  static void enumeration(IO &IO, FormatStyle::SpacesInAnglesStyle &Value) {
699  IO.enumCase(Value, "Never", FormatStyle::SIAS_Never);
700  IO.enumCase(Value, "Always", FormatStyle::SIAS_Always);
701  IO.enumCase(Value, "Leave", FormatStyle::SIAS_Leave);
702 
703  // For backward compatibility.
704  IO.enumCase(Value, "false", FormatStyle::SIAS_Never);
705  IO.enumCase(Value, "true", FormatStyle::SIAS_Always);
706  }
707 };
708 
709 template <> struct MappingTraits<FormatStyle::SpacesInLineComment> {
710  static void mapping(IO &IO, FormatStyle::SpacesInLineComment &Space) {
711  // Transform the maximum to signed, to parse "-1" correctly
712  int signedMaximum = static_cast<int>(Space.Maximum);
713  IO.mapOptional("Minimum", Space.Minimum);
714  IO.mapOptional("Maximum", signedMaximum);
715  Space.Maximum = static_cast<unsigned>(signedMaximum);
716 
717  if (Space.Maximum != -1u)
718  Space.Minimum = std::min(Space.Minimum, Space.Maximum);
719  }
720 };
721 
722 template <> struct MappingTraits<FormatStyle::SpacesInParensCustom> {
723  static void mapping(IO &IO, FormatStyle::SpacesInParensCustom &Spaces) {
724  IO.mapOptional("InCStyleCasts", Spaces.InCStyleCasts);
725  IO.mapOptional("InConditionalStatements", Spaces.InConditionalStatements);
726  IO.mapOptional("InEmptyParentheses", Spaces.InEmptyParentheses);
727  IO.mapOptional("Other", Spaces.Other);
728  }
729 };
730 
731 template <> struct ScalarEnumerationTraits<FormatStyle::SpacesInParensStyle> {
732  static void enumeration(IO &IO, FormatStyle::SpacesInParensStyle &Value) {
733  IO.enumCase(Value, "Never", FormatStyle::SIPO_Never);
734  IO.enumCase(Value, "Custom", FormatStyle::SIPO_Custom);
735  }
736 };
737 
738 template <> struct ScalarEnumerationTraits<FormatStyle::TrailingCommaStyle> {
739  static void enumeration(IO &IO, FormatStyle::TrailingCommaStyle &Value) {
740  IO.enumCase(Value, "None", FormatStyle::TCS_None);
741  IO.enumCase(Value, "Wrapped", FormatStyle::TCS_Wrapped);
742  }
743 };
744 
745 template <>
746 struct ScalarEnumerationTraits<FormatStyle::TrailingCommentsAlignmentKinds> {
747  static void enumeration(IO &IO,
748  FormatStyle::TrailingCommentsAlignmentKinds &Value) {
749  IO.enumCase(Value, "Leave", FormatStyle::TCAS_Leave);
750  IO.enumCase(Value, "Always", FormatStyle::TCAS_Always);
751  IO.enumCase(Value, "Never", FormatStyle::TCAS_Never);
752  }
753 };
754 
755 template <> struct MappingTraits<FormatStyle::TrailingCommentsAlignmentStyle> {
756  static void enumInput(IO &IO,
757  FormatStyle::TrailingCommentsAlignmentStyle &Value) {
758  IO.enumCase(Value, "Leave",
759  FormatStyle::TrailingCommentsAlignmentStyle(
760  {FormatStyle::TCAS_Leave, 0}));
761 
762  IO.enumCase(Value, "Always",
763  FormatStyle::TrailingCommentsAlignmentStyle(
764  {FormatStyle::TCAS_Always, 0}));
765 
766  IO.enumCase(Value, "Never",
767  FormatStyle::TrailingCommentsAlignmentStyle(
768  {FormatStyle::TCAS_Never, 0}));
769 
770  // For backwards compatibility
771  IO.enumCase(Value, "true",
772  FormatStyle::TrailingCommentsAlignmentStyle(
773  {FormatStyle::TCAS_Always, 0}));
774  IO.enumCase(Value, "false",
775  FormatStyle::TrailingCommentsAlignmentStyle(
776  {FormatStyle::TCAS_Never, 0}));
777  }
778 
779  static void mapping(IO &IO,
780  FormatStyle::TrailingCommentsAlignmentStyle &Value) {
781  IO.mapOptional("Kind", Value.Kind);
782  IO.mapOptional("OverEmptyLines", Value.OverEmptyLines);
783  }
784 };
785 
786 template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
787  static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
788  IO.enumCase(Value, "Never", FormatStyle::UT_Never);
789  IO.enumCase(Value, "false", FormatStyle::UT_Never);
790  IO.enumCase(Value, "Always", FormatStyle::UT_Always);
791  IO.enumCase(Value, "true", FormatStyle::UT_Always);
792  IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
793  IO.enumCase(Value, "ForContinuationAndIndentation",
794  FormatStyle::UT_ForContinuationAndIndentation);
795  IO.enumCase(Value, "AlignWithSpaces", FormatStyle::UT_AlignWithSpaces);
796  }
797 };
798 
799 template <> struct MappingTraits<FormatStyle> {
800  static void mapping(IO &IO, FormatStyle &Style) {
801  // When reading, read the language first, we need it for getPredefinedStyle.
802  IO.mapOptional("Language", Style.Language);
803 
804  StringRef BasedOnStyle;
805  if (IO.outputting()) {
806  StringRef Styles[] = {"LLVM", "Google", "Chromium", "Mozilla",
807  "WebKit", "GNU", "Microsoft", "clang-format"};
808  for (StringRef StyleName : Styles) {
809  FormatStyle PredefinedStyle;
810  if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
811  Style == PredefinedStyle) {
812  BasedOnStyle = StyleName;
813  break;
814  }
815  }
816  } else {
817  IO.mapOptional("BasedOnStyle", BasedOnStyle);
818  if (!BasedOnStyle.empty()) {
819  FormatStyle::LanguageKind OldLanguage = Style.Language;
820  FormatStyle::LanguageKind Language =
821  ((FormatStyle *)IO.getContext())->Language;
822  if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
823  IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
824  return;
825  }
826  Style.Language = OldLanguage;
827  }
828  }
829 
830  // Initialize some variables used in the parsing. The using logic is at the
831  // end.
832 
833  // For backward compatibility:
834  // The default value of ConstructorInitializerAllOnOneLineOrOnePerLine was
835  // false unless BasedOnStyle was Google or Chromium whereas that of
836  // AllowAllConstructorInitializersOnNextLine was always true, so the
837  // equivalent default value of PackConstructorInitializers is PCIS_NextLine
838  // for Google/Chromium or PCIS_BinPack otherwise. If the deprecated options
839  // had a non-default value while PackConstructorInitializers has a default
840  // value, set the latter to an equivalent non-default value if needed.
841  const bool IsGoogleOrChromium = BasedOnStyle.equals_insensitive("google") ||
842  BasedOnStyle.equals_insensitive("chromium");
843  bool OnCurrentLine = IsGoogleOrChromium;
844  bool OnNextLine = true;
845 
846  bool BreakBeforeInheritanceComma = false;
847  bool BreakConstructorInitializersBeforeComma = false;
848 
849  bool DeriveLineEnding = true;
850  bool UseCRLF = false;
851 
852  bool SpaceInEmptyParentheses = false;
853  bool SpacesInConditionalStatement = false;
854  bool SpacesInCStyleCastParentheses = false;
855  bool SpacesInParentheses = false;
856 
857  // For backward compatibility.
858  if (!IO.outputting()) {
859  IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlines);
860  IO.mapOptional("AllowAllConstructorInitializersOnNextLine", OnNextLine);
861  IO.mapOptional("AlwaysBreakAfterReturnType", Style.BreakAfterReturnType);
862  IO.mapOptional("AlwaysBreakTemplateDeclarations",
864  IO.mapOptional("BreakBeforeInheritanceComma",
865  BreakBeforeInheritanceComma);
866  IO.mapOptional("BreakConstructorInitializersBeforeComma",
867  BreakConstructorInitializersBeforeComma);
868  IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
869  OnCurrentLine);
870  IO.mapOptional("DeriveLineEnding", DeriveLineEnding);
871  IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
872  IO.mapOptional("IndentFunctionDeclarationAfterType",
874  IO.mapOptional("IndentRequires", Style.IndentRequiresClause);
875  IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
876  IO.mapOptional("SpaceAfterControlStatementKeyword",
877  Style.SpaceBeforeParens);
878  IO.mapOptional("SpaceInEmptyParentheses", SpaceInEmptyParentheses);
879  IO.mapOptional("SpacesInConditionalStatement",
880  SpacesInConditionalStatement);
881  IO.mapOptional("SpacesInCStyleCastParentheses",
882  SpacesInCStyleCastParentheses);
883  IO.mapOptional("SpacesInParentheses", SpacesInParentheses);
884  IO.mapOptional("UseCRLF", UseCRLF);
885  }
886 
887  IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
888  IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
889  IO.mapOptional("AlignArrayOfStructures", Style.AlignArrayOfStructures);
890  IO.mapOptional("AlignConsecutiveAssignments",
892  IO.mapOptional("AlignConsecutiveBitFields",
894  IO.mapOptional("AlignConsecutiveDeclarations",
896  IO.mapOptional("AlignConsecutiveMacros", Style.AlignConsecutiveMacros);
897  IO.mapOptional("AlignConsecutiveShortCaseStatements",
899  IO.mapOptional("AlignConsecutiveTableGenBreakingDAGArgColons",
901  IO.mapOptional("AlignConsecutiveTableGenCondOperatorColons",
903  IO.mapOptional("AlignConsecutiveTableGenDefinitionColons",
905  IO.mapOptional("AlignEscapedNewlines", Style.AlignEscapedNewlines);
906  IO.mapOptional("AlignOperands", Style.AlignOperands);
907  IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
908  IO.mapOptional("AllowAllArgumentsOnNextLine",
910  IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
912  IO.mapOptional("AllowBreakBeforeNoexceptSpecifier",
914  IO.mapOptional("AllowShortBlocksOnASingleLine",
916  IO.mapOptional("AllowShortCaseExpressionOnASingleLine",
918  IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
920  IO.mapOptional("AllowShortCompoundRequirementOnASingleLine",
922  IO.mapOptional("AllowShortEnumsOnASingleLine",
924  IO.mapOptional("AllowShortFunctionsOnASingleLine",
926  IO.mapOptional("AllowShortIfStatementsOnASingleLine",
928  IO.mapOptional("AllowShortLambdasOnASingleLine",
930  IO.mapOptional("AllowShortLoopsOnASingleLine",
932  IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
934  IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
936  IO.mapOptional("AttributeMacros", Style.AttributeMacros);
937  IO.mapOptional("BinPackArguments", Style.BinPackArguments);
938  IO.mapOptional("BinPackParameters", Style.BinPackParameters);
939  IO.mapOptional("BitFieldColonSpacing", Style.BitFieldColonSpacing);
940  IO.mapOptional("BracedInitializerIndentWidth",
942  IO.mapOptional("BraceWrapping", Style.BraceWrapping);
943  IO.mapOptional("BreakAdjacentStringLiterals",
945  IO.mapOptional("BreakAfterAttributes", Style.BreakAfterAttributes);
946  IO.mapOptional("BreakAfterJavaFieldAnnotations",
948  IO.mapOptional("BreakAfterReturnType", Style.BreakAfterReturnType);
949  IO.mapOptional("BreakArrays", Style.BreakArrays);
950  IO.mapOptional("BreakBeforeBinaryOperators",
952  IO.mapOptional("BreakBeforeConceptDeclarations",
954  IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
955  IO.mapOptional("BreakBeforeInlineASMColon",
957  IO.mapOptional("BreakBeforeTernaryOperators",
959  IO.mapOptional("BreakConstructorInitializers",
961  IO.mapOptional("BreakFunctionDefinitionParameters",
963  IO.mapOptional("BreakInheritanceList", Style.BreakInheritanceList);
964  IO.mapOptional("BreakStringLiterals", Style.BreakStringLiterals);
965  IO.mapOptional("BreakTemplateDeclarations",
967  IO.mapOptional("ColumnLimit", Style.ColumnLimit);
968  IO.mapOptional("CommentPragmas", Style.CommentPragmas);
969  IO.mapOptional("CompactNamespaces", Style.CompactNamespaces);
970  IO.mapOptional("ConstructorInitializerIndentWidth",
972  IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
973  IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
974  IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
975  IO.mapOptional("DisableFormat", Style.DisableFormat);
976  IO.mapOptional("EmptyLineAfterAccessModifier",
978  IO.mapOptional("EmptyLineBeforeAccessModifier",
980  IO.mapOptional("ExperimentalAutoDetectBinPacking",
982  IO.mapOptional("FixNamespaceComments", Style.FixNamespaceComments);
983  IO.mapOptional("ForEachMacros", Style.ForEachMacros);
984  IO.mapOptional("IfMacros", Style.IfMacros);
985  IO.mapOptional("IncludeBlocks", Style.IncludeStyle.IncludeBlocks);
986  IO.mapOptional("IncludeCategories", Style.IncludeStyle.IncludeCategories);
987  IO.mapOptional("IncludeIsMainRegex", Style.IncludeStyle.IncludeIsMainRegex);
988  IO.mapOptional("IncludeIsMainSourceRegex",
990  IO.mapOptional("IndentAccessModifiers", Style.IndentAccessModifiers);
991  IO.mapOptional("IndentCaseBlocks", Style.IndentCaseBlocks);
992  IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
993  IO.mapOptional("IndentExternBlock", Style.IndentExternBlock);
994  IO.mapOptional("IndentGotoLabels", Style.IndentGotoLabels);
995  IO.mapOptional("IndentPPDirectives", Style.IndentPPDirectives);
996  IO.mapOptional("IndentRequiresClause", Style.IndentRequiresClause);
997  IO.mapOptional("IndentWidth", Style.IndentWidth);
998  IO.mapOptional("IndentWrappedFunctionNames",
1000  IO.mapOptional("InsertBraces", Style.InsertBraces);
1001  IO.mapOptional("InsertNewlineAtEOF", Style.InsertNewlineAtEOF);
1002  IO.mapOptional("InsertTrailingCommas", Style.InsertTrailingCommas);
1003  IO.mapOptional("IntegerLiteralSeparator", Style.IntegerLiteralSeparator);
1004  IO.mapOptional("JavaImportGroups", Style.JavaImportGroups);
1005  IO.mapOptional("JavaScriptQuotes", Style.JavaScriptQuotes);
1006  IO.mapOptional("JavaScriptWrapImports", Style.JavaScriptWrapImports);
1007  IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
1009  IO.mapOptional("KeepEmptyLinesAtEOF", Style.KeepEmptyLinesAtEOF);
1010  IO.mapOptional("LambdaBodyIndentation", Style.LambdaBodyIndentation);
1011  IO.mapOptional("LineEnding", Style.LineEnding);
1012  IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
1013  IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
1014  IO.mapOptional("Macros", Style.Macros);
1015  IO.mapOptional("MainIncludeChar", Style.IncludeStyle.MainIncludeChar);
1016  IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
1017  IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
1018  IO.mapOptional("NamespaceMacros", Style.NamespaceMacros);
1019  IO.mapOptional("ObjCBinPackProtocolList", Style.ObjCBinPackProtocolList);
1020  IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
1021  IO.mapOptional("ObjCBreakBeforeNestedBlockParam",
1023  IO.mapOptional("ObjCPropertyAttributeOrder",
1025  IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
1026  IO.mapOptional("ObjCSpaceBeforeProtocolList",
1028  IO.mapOptional("PackConstructorInitializers",
1030  IO.mapOptional("PenaltyBreakAssignment", Style.PenaltyBreakAssignment);
1031  IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
1033  IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
1034  IO.mapOptional("PenaltyBreakFirstLessLess",
1036  IO.mapOptional("PenaltyBreakOpenParenthesis",
1038  IO.mapOptional("PenaltyBreakScopeResolution",
1040  IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
1041  IO.mapOptional("PenaltyBreakTemplateDeclaration",
1043  IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
1044  IO.mapOptional("PenaltyIndentedWhitespace",
1046  IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
1048  IO.mapOptional("PointerAlignment", Style.PointerAlignment);
1049  IO.mapOptional("PPIndentWidth", Style.PPIndentWidth);
1050  IO.mapOptional("QualifierAlignment", Style.QualifierAlignment);
1051  // Default Order for Left/Right based Qualifier alignment.
1052  if (Style.QualifierAlignment == FormatStyle::QAS_Right)
1053  Style.QualifierOrder = {"type", "const", "volatile"};
1054  else if (Style.QualifierAlignment == FormatStyle::QAS_Left)
1055  Style.QualifierOrder = {"const", "volatile", "type"};
1056  else if (Style.QualifierAlignment == FormatStyle::QAS_Custom)
1057  IO.mapOptional("QualifierOrder", Style.QualifierOrder);
1058  IO.mapOptional("RawStringFormats", Style.RawStringFormats);
1059  IO.mapOptional("ReferenceAlignment", Style.ReferenceAlignment);
1060  IO.mapOptional("ReflowComments", Style.ReflowComments);
1061  IO.mapOptional("RemoveBracesLLVM", Style.RemoveBracesLLVM);
1062  IO.mapOptional("RemoveParentheses", Style.RemoveParentheses);
1063  IO.mapOptional("RemoveSemicolon", Style.RemoveSemicolon);
1064  IO.mapOptional("RequiresClausePosition", Style.RequiresClausePosition);
1065  IO.mapOptional("RequiresExpressionIndentation",
1067  IO.mapOptional("SeparateDefinitionBlocks", Style.SeparateDefinitionBlocks);
1068  IO.mapOptional("ShortNamespaceLines", Style.ShortNamespaceLines);
1069  IO.mapOptional("SkipMacroDefinitionBody", Style.SkipMacroDefinitionBody);
1070  IO.mapOptional("SortIncludes", Style.SortIncludes);
1071  IO.mapOptional("SortJavaStaticImport", Style.SortJavaStaticImport);
1072  IO.mapOptional("SortUsingDeclarations", Style.SortUsingDeclarations);
1073  IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
1074  IO.mapOptional("SpaceAfterLogicalNot", Style.SpaceAfterLogicalNot);
1075  IO.mapOptional("SpaceAfterTemplateKeyword",
1077  IO.mapOptional("SpaceAroundPointerQualifiers",
1079  IO.mapOptional("SpaceBeforeAssignmentOperators",
1081  IO.mapOptional("SpaceBeforeCaseColon", Style.SpaceBeforeCaseColon);
1082  IO.mapOptional("SpaceBeforeCpp11BracedList",
1084  IO.mapOptional("SpaceBeforeCtorInitializerColon",
1086  IO.mapOptional("SpaceBeforeInheritanceColon",
1088  IO.mapOptional("SpaceBeforeJsonColon", Style.SpaceBeforeJsonColon);
1089  IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
1090  IO.mapOptional("SpaceBeforeParensOptions", Style.SpaceBeforeParensOptions);
1091  IO.mapOptional("SpaceBeforeRangeBasedForLoopColon",
1093  IO.mapOptional("SpaceBeforeSquareBrackets",
1095  IO.mapOptional("SpaceInEmptyBlock", Style.SpaceInEmptyBlock);
1096  IO.mapOptional("SpacesBeforeTrailingComments",
1098  IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
1099  IO.mapOptional("SpacesInContainerLiterals",
1101  IO.mapOptional("SpacesInLineCommentPrefix",
1103  IO.mapOptional("SpacesInParens", Style.SpacesInParens);
1104  IO.mapOptional("SpacesInParensOptions", Style.SpacesInParensOptions);
1105  IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
1106  IO.mapOptional("Standard", Style.Standard);
1107  IO.mapOptional("StatementAttributeLikeMacros",
1109  IO.mapOptional("StatementMacros", Style.StatementMacros);
1110  IO.mapOptional("TableGenBreakingDAGArgOperators",
1112  IO.mapOptional("TableGenBreakInsideDAGArg",
1114  IO.mapOptional("TabWidth", Style.TabWidth);
1115  IO.mapOptional("TypeNames", Style.TypeNames);
1116  IO.mapOptional("TypenameMacros", Style.TypenameMacros);
1117  IO.mapOptional("UseTab", Style.UseTab);
1118  IO.mapOptional("VerilogBreakBetweenInstancePorts",
1120  IO.mapOptional("WhitespaceSensitiveMacros",
1122 
1123  // If AlwaysBreakAfterDefinitionReturnType was specified but
1124  // BreakAfterReturnType was not, initialize the latter from the former for
1125  // backwards compatibility.
1126  if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
1127  Style.BreakAfterReturnType == FormatStyle::RTBS_None) {
1129  FormatStyle::DRTBS_All) {
1130  Style.BreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
1131  } else if (Style.AlwaysBreakAfterDefinitionReturnType ==
1132  FormatStyle::DRTBS_TopLevel) {
1133  Style.BreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
1134  }
1135  }
1136 
1137  // If BreakBeforeInheritanceComma was specified but BreakInheritance was
1138  // not, initialize the latter from the former for backwards compatibility.
1139  if (BreakBeforeInheritanceComma &&
1140  Style.BreakInheritanceList == FormatStyle::BILS_BeforeColon) {
1141  Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
1142  }
1143 
1144  // If BreakConstructorInitializersBeforeComma was specified but
1145  // BreakConstructorInitializers was not, initialize the latter from the
1146  // former for backwards compatibility.
1147  if (BreakConstructorInitializersBeforeComma &&
1148  Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon) {
1149  Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
1150  }
1151 
1152  if (!IsGoogleOrChromium) {
1153  if (Style.PackConstructorInitializers == FormatStyle::PCIS_BinPack &&
1154  OnCurrentLine) {
1155  Style.PackConstructorInitializers = OnNextLine
1156  ? FormatStyle::PCIS_NextLine
1157  : FormatStyle::PCIS_CurrentLine;
1158  }
1159  } else if (Style.PackConstructorInitializers ==
1160  FormatStyle::PCIS_NextLine) {
1161  if (!OnCurrentLine)
1162  Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
1163  else if (!OnNextLine)
1164  Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
1165  }
1166 
1167  if (Style.LineEnding == FormatStyle::LE_DeriveLF) {
1168  if (!DeriveLineEnding)
1169  Style.LineEnding = UseCRLF ? FormatStyle::LE_CRLF : FormatStyle::LE_LF;
1170  else if (UseCRLF)
1171  Style.LineEnding = FormatStyle::LE_DeriveCRLF;
1172  }
1173 
1174  if (Style.SpacesInParens != FormatStyle::SIPO_Custom &&
1175  (SpacesInParentheses || SpaceInEmptyParentheses ||
1176  SpacesInConditionalStatement || SpacesInCStyleCastParentheses)) {
1177  if (SpacesInParentheses) {
1178  // set all options except InCStyleCasts and InEmptyParentheses
1179  // to true for backward compatibility.
1182  SpacesInCStyleCastParentheses;
1184  SpaceInEmptyParentheses;
1185  Style.SpacesInParensOptions.Other = true;
1186  } else {
1187  Style.SpacesInParensOptions = {};
1189  SpacesInConditionalStatement;
1191  SpacesInCStyleCastParentheses;
1193  SpaceInEmptyParentheses;
1194  }
1195  Style.SpacesInParens = FormatStyle::SIPO_Custom;
1196  }
1197  }
1198 };
1199 
1200 // Allows to read vector<FormatStyle> while keeping default values.
1201 // IO.getContext() should contain a pointer to the FormatStyle structure, that
1202 // will be used to get default values for missing keys.
1203 // If the first element has no Language specified, it will be treated as the
1204 // default one for the following elements.
1205 template <> struct DocumentListTraits<std::vector<FormatStyle>> {
1206  static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
1207  return Seq.size();
1208  }
1209  static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
1210  size_t Index) {
1211  if (Index >= Seq.size()) {
1212  assert(Index == Seq.size());
1213  FormatStyle Template;
1214  if (!Seq.empty() && Seq[0].Language == FormatStyle::LK_None) {
1215  Template = Seq[0];
1216  } else {
1217  Template = *((const FormatStyle *)IO.getContext());
1218  Template.Language = FormatStyle::LK_None;
1219  }
1220  Seq.resize(Index + 1, Template);
1221  }
1222  return Seq[Index];
1223  }
1224 };
1225 } // namespace yaml
1226 } // namespace llvm
1227 
1228 namespace clang {
1229 namespace format {
1230 
1231 const std::error_category &getParseCategory() {
1232  static const ParseErrorCategory C{};
1233  return C;
1234 }
1235 std::error_code make_error_code(ParseError e) {
1236  return std::error_code(static_cast<int>(e), getParseCategory());
1237 }
1238 
1239 inline llvm::Error make_string_error(const Twine &Message) {
1240  return llvm::make_error<llvm::StringError>(Message,
1241  llvm::inconvertibleErrorCode());
1242 }
1243 
1244 const char *ParseErrorCategory::name() const noexcept {
1245  return "clang-format.parse_error";
1246 }
1247 
1248 std::string ParseErrorCategory::message(int EV) const {
1249  switch (static_cast<ParseError>(EV)) {
1250  case ParseError::Success:
1251  return "Success";
1252  case ParseError::Error:
1253  return "Invalid argument";
1255  return "Unsuitable";
1257  return "trailing comma insertion cannot be used with bin packing";
1259  return "Invalid qualifier specified in QualifierOrder";
1261  return "Duplicate qualifier specified in QualifierOrder";
1263  return "Missing type in QualifierOrder";
1265  return "Missing QualifierOrder";
1266  }
1267  llvm_unreachable("unexpected parse error");
1268 }
1269 
1270 static void expandPresetsBraceWrapping(FormatStyle &Expanded) {
1271  if (Expanded.BreakBeforeBraces == FormatStyle::BS_Custom)
1272  return;
1273  Expanded.BraceWrapping = {/*AfterCaseLabel=*/false,
1274  /*AfterClass=*/false,
1275  /*AfterControlStatement=*/FormatStyle::BWACS_Never,
1276  /*AfterEnum=*/false,
1277  /*AfterFunction=*/false,
1278  /*AfterNamespace=*/false,
1279  /*AfterObjCDeclaration=*/false,
1280  /*AfterStruct=*/false,
1281  /*AfterUnion=*/false,
1282  /*AfterExternBlock=*/false,
1283  /*BeforeCatch=*/false,
1284  /*BeforeElse=*/false,
1285  /*BeforeLambdaBody=*/false,
1286  /*BeforeWhile=*/false,
1287  /*IndentBraces=*/false,
1288  /*SplitEmptyFunction=*/true,
1289  /*SplitEmptyRecord=*/true,
1290  /*SplitEmptyNamespace=*/true};
1291  switch (Expanded.BreakBeforeBraces) {
1292  case FormatStyle::BS_Linux:
1293  Expanded.BraceWrapping.AfterClass = true;
1294  Expanded.BraceWrapping.AfterFunction = true;
1295  Expanded.BraceWrapping.AfterNamespace = true;
1296  break;
1298  Expanded.BraceWrapping.AfterClass = true;
1299  Expanded.BraceWrapping.AfterEnum = true;
1300  Expanded.BraceWrapping.AfterFunction = true;
1301  Expanded.BraceWrapping.AfterStruct = true;
1302  Expanded.BraceWrapping.AfterUnion = true;
1303  Expanded.BraceWrapping.AfterExternBlock = true;
1304  Expanded.BraceWrapping.SplitEmptyFunction = true;
1305  Expanded.BraceWrapping.SplitEmptyRecord = false;
1306  break;
1308  Expanded.BraceWrapping.AfterFunction = true;
1309  Expanded.BraceWrapping.BeforeCatch = true;
1310  Expanded.BraceWrapping.BeforeElse = true;
1311  break;
1313  Expanded.BraceWrapping.AfterCaseLabel = true;
1314  Expanded.BraceWrapping.AfterClass = true;
1316  Expanded.BraceWrapping.AfterEnum = true;
1317  Expanded.BraceWrapping.AfterFunction = true;
1318  Expanded.BraceWrapping.AfterNamespace = true;
1319  Expanded.BraceWrapping.AfterObjCDeclaration = true;
1320  Expanded.BraceWrapping.AfterStruct = true;
1321  Expanded.BraceWrapping.AfterUnion = true;
1322  Expanded.BraceWrapping.AfterExternBlock = true;
1323  Expanded.BraceWrapping.BeforeCatch = true;
1324  Expanded.BraceWrapping.BeforeElse = true;
1325  Expanded.BraceWrapping.BeforeLambdaBody = true;
1326  break;
1328  Expanded.BraceWrapping.AfterCaseLabel = true;
1329  Expanded.BraceWrapping.AfterClass = true;
1331  Expanded.BraceWrapping.AfterEnum = true;
1332  Expanded.BraceWrapping.AfterFunction = true;
1333  Expanded.BraceWrapping.AfterNamespace = true;
1334  Expanded.BraceWrapping.AfterObjCDeclaration = true;
1335  Expanded.BraceWrapping.AfterStruct = true;
1336  Expanded.BraceWrapping.AfterExternBlock = true;
1337  Expanded.BraceWrapping.BeforeCatch = true;
1338  Expanded.BraceWrapping.BeforeElse = true;
1339  Expanded.BraceWrapping.BeforeLambdaBody = true;
1340  break;
1341  case FormatStyle::BS_GNU:
1342  Expanded.BraceWrapping = {
1343  /*AfterCaseLabel=*/true,
1344  /*AfterClass=*/true,
1345  /*AfterControlStatement=*/FormatStyle::BWACS_Always,
1346  /*AfterEnum=*/true,
1347  /*AfterFunction=*/true,
1348  /*AfterNamespace=*/true,
1349  /*AfterObjCDeclaration=*/true,
1350  /*AfterStruct=*/true,
1351  /*AfterUnion=*/true,
1352  /*AfterExternBlock=*/true,
1353  /*BeforeCatch=*/true,
1354  /*BeforeElse=*/true,
1355  /*BeforeLambdaBody=*/false,
1356  /*BeforeWhile=*/true,
1357  /*IndentBraces=*/true,
1358  /*SplitEmptyFunction=*/true,
1359  /*SplitEmptyRecord=*/true,
1360  /*SplitEmptyNamespace=*/true};
1361  break;
1363  Expanded.BraceWrapping.AfterFunction = true;
1364  break;
1365  default:
1366  break;
1367  }
1368 }
1369 
1372  return;
1373  // Reset all flags
1374  Expanded.SpaceBeforeParensOptions = {};
1376 
1377  switch (Expanded.SpaceBeforeParens) {
1381  Expanded.SpaceBeforeParensOptions.AfterIfMacros = true;
1382  break;
1385  break;
1388  break;
1389  default:
1390  break;
1391  }
1392 }
1393 
1395  if (Expanded.SpacesInParens == FormatStyle::SIPO_Custom)
1396  return;
1397  assert(Expanded.SpacesInParens == FormatStyle::SIPO_Never);
1398  // Reset all flags
1399  Expanded.SpacesInParensOptions = {};
1400 }
1401 
1403  FormatStyle LLVMStyle;
1404  LLVMStyle.AccessModifierOffset = -2;
1407  LLVMStyle.AlignConsecutiveAssignments = {};
1408  LLVMStyle.AlignConsecutiveAssignments.AcrossComments = false;
1410  LLVMStyle.AlignConsecutiveAssignments.AlignCompound = false;
1412  LLVMStyle.AlignConsecutiveAssignments.Enabled = false;
1413  LLVMStyle.AlignConsecutiveAssignments.PadOperators = true;
1414  LLVMStyle.AlignConsecutiveBitFields = {};
1415  LLVMStyle.AlignConsecutiveDeclarations = {};
1416  LLVMStyle.AlignConsecutiveMacros = {};
1417  LLVMStyle.AlignConsecutiveShortCaseStatements = {};
1423  LLVMStyle.AlignTrailingComments = {};
1425  LLVMStyle.AlignTrailingComments.OverEmptyLines = 0;
1426  LLVMStyle.AllowAllArgumentsOnNextLine = true;
1430  LLVMStyle.AllowShortCaseExpressionOnASingleLine = true;
1431  LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
1433  LLVMStyle.AllowShortEnumsOnASingleLine = true;
1437  LLVMStyle.AllowShortLoopsOnASingleLine = false;
1439  LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
1440  LLVMStyle.AttributeMacros.push_back("__capability");
1441  LLVMStyle.BinPackArguments = true;
1442  LLVMStyle.BinPackParameters = true;
1444  LLVMStyle.BracedInitializerIndentWidth = std::nullopt;
1445  LLVMStyle.BraceWrapping = {/*AfterCaseLabel=*/false,
1446  /*AfterClass=*/false,
1447  /*AfterControlStatement=*/FormatStyle::BWACS_Never,
1448  /*AfterEnum=*/false,
1449  /*AfterFunction=*/false,
1450  /*AfterNamespace=*/false,
1451  /*AfterObjCDeclaration=*/false,
1452  /*AfterStruct=*/false,
1453  /*AfterUnion=*/false,
1454  /*AfterExternBlock=*/false,
1455  /*BeforeCatch=*/false,
1456  /*BeforeElse=*/false,
1457  /*BeforeLambdaBody=*/false,
1458  /*BeforeWhile=*/false,
1459  /*IndentBraces=*/false,
1460  /*SplitEmptyFunction=*/true,
1461  /*SplitEmptyRecord=*/true,
1462  /*SplitEmptyNamespace=*/true};
1463  LLVMStyle.BreakAdjacentStringLiterals = true;
1465  LLVMStyle.BreakAfterJavaFieldAnnotations = false;
1467  LLVMStyle.BreakArrays = true;
1472  LLVMStyle.BreakBeforeTernaryOperators = true;
1474  LLVMStyle.BreakFunctionDefinitionParameters = false;
1476  LLVMStyle.BreakStringLiterals = true;
1478  LLVMStyle.ColumnLimit = 80;
1479  LLVMStyle.CommentPragmas = "^ IWYU pragma:";
1480  LLVMStyle.CompactNamespaces = false;
1481  LLVMStyle.ConstructorInitializerIndentWidth = 4;
1482  LLVMStyle.ContinuationIndentWidth = 4;
1483  LLVMStyle.Cpp11BracedListStyle = true;
1484  LLVMStyle.DerivePointerAlignment = false;
1485  LLVMStyle.DisableFormat = false;
1488  LLVMStyle.ExperimentalAutoDetectBinPacking = false;
1489  LLVMStyle.FixNamespaceComments = true;
1490  LLVMStyle.ForEachMacros.push_back("foreach");
1491  LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
1492  LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
1493  LLVMStyle.IfMacros.push_back("KJ_IF_MAYBE");
1495  LLVMStyle.IncludeStyle.IncludeCategories = {
1496  {"^\"(llvm|llvm-c|clang|clang-c)/", 2, 0, false},
1497  {"^(<|\"(gtest|gmock|isl|json)/)", 3, 0, false},
1498  {".*", 1, 0, false}};
1499  LLVMStyle.IncludeStyle.IncludeIsMainRegex = "(Test)?$";
1501  LLVMStyle.IndentAccessModifiers = false;
1502  LLVMStyle.IndentCaseBlocks = false;
1503  LLVMStyle.IndentCaseLabels = false;
1505  LLVMStyle.IndentGotoLabels = true;
1507  LLVMStyle.IndentRequiresClause = true;
1508  LLVMStyle.IndentWidth = 2;
1509  LLVMStyle.IndentWrappedFunctionNames = false;
1510  LLVMStyle.InheritsParentConfig = false;
1511  LLVMStyle.InsertBraces = false;
1512  LLVMStyle.InsertNewlineAtEOF = false;
1514  LLVMStyle.IntegerLiteralSeparator = {
1515  /*Binary=*/0, /*BinaryMinDigits=*/0,
1516  /*Decimal=*/0, /*DecimalMinDigits=*/0,
1517  /*Hex=*/0, /*HexMinDigits=*/0};
1519  LLVMStyle.JavaScriptWrapImports = true;
1520  LLVMStyle.KeepEmptyLinesAtEOF = false;
1521  LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
1523  LLVMStyle.Language = Language;
1525  LLVMStyle.MaxEmptyLinesToKeep = 1;
1528  LLVMStyle.ObjCBlockIndentWidth = 2;
1529  LLVMStyle.ObjCBreakBeforeNestedBlockParam = true;
1530  LLVMStyle.ObjCSpaceAfterProperty = false;
1531  LLVMStyle.ObjCSpaceBeforeProtocolList = true;
1534  LLVMStyle.PPIndentWidth = -1;
1537  LLVMStyle.ReflowComments = true;
1538  LLVMStyle.RemoveBracesLLVM = false;
1540  LLVMStyle.RemoveSemicolon = false;
1544  LLVMStyle.ShortNamespaceLines = 1;
1545  LLVMStyle.SkipMacroDefinitionBody = false;
1549  LLVMStyle.SpaceAfterCStyleCast = false;
1550  LLVMStyle.SpaceAfterLogicalNot = false;
1551  LLVMStyle.SpaceAfterTemplateKeyword = true;
1553  LLVMStyle.SpaceBeforeAssignmentOperators = true;
1554  LLVMStyle.SpaceBeforeCaseColon = false;
1555  LLVMStyle.SpaceBeforeCpp11BracedList = false;
1556  LLVMStyle.SpaceBeforeCtorInitializerColon = true;
1557  LLVMStyle.SpaceBeforeInheritanceColon = true;
1558  LLVMStyle.SpaceBeforeJsonColon = false;
1560  LLVMStyle.SpaceBeforeParensOptions = {};
1563  LLVMStyle.SpaceBeforeParensOptions.AfterIfMacros = true;
1564  LLVMStyle.SpaceBeforeRangeBasedForLoopColon = true;
1565  LLVMStyle.SpaceBeforeSquareBrackets = false;
1566  LLVMStyle.SpaceInEmptyBlock = false;
1567  LLVMStyle.SpacesBeforeTrailingComments = 1;
1569  LLVMStyle.SpacesInContainerLiterals = true;
1570  LLVMStyle.SpacesInLineCommentPrefix = {/*Minimum=*/1, /*Maximum=*/-1u};
1572  LLVMStyle.SpacesInSquareBrackets = false;
1573  LLVMStyle.Standard = FormatStyle::LS_Latest;
1574  LLVMStyle.StatementAttributeLikeMacros.push_back("Q_EMIT");
1575  LLVMStyle.StatementMacros.push_back("Q_UNUSED");
1576  LLVMStyle.StatementMacros.push_back("QT_REQUIRE_VERSION");
1577  LLVMStyle.TableGenBreakingDAGArgOperators = {};
1579  LLVMStyle.TabWidth = 8;
1580  LLVMStyle.UseTab = FormatStyle::UT_Never;
1581  LLVMStyle.VerilogBreakBetweenInstancePorts = true;
1582  LLVMStyle.WhitespaceSensitiveMacros.push_back("BOOST_PP_STRINGIZE");
1583  LLVMStyle.WhitespaceSensitiveMacros.push_back("CF_SWIFT_NAME");
1584  LLVMStyle.WhitespaceSensitiveMacros.push_back("NS_SWIFT_NAME");
1585  LLVMStyle.WhitespaceSensitiveMacros.push_back("PP_STRINGIZE");
1586  LLVMStyle.WhitespaceSensitiveMacros.push_back("STRINGIZE");
1587 
1589  LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
1590  LLVMStyle.PenaltyBreakComment = 300;
1591  LLVMStyle.PenaltyBreakFirstLessLess = 120;
1592  LLVMStyle.PenaltyBreakOpenParenthesis = 0;
1593  LLVMStyle.PenaltyBreakScopeResolution = 500;
1594  LLVMStyle.PenaltyBreakString = 1000;
1596  LLVMStyle.PenaltyExcessCharacter = 1'000'000;
1597  LLVMStyle.PenaltyIndentedWhitespace = 0;
1598  LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
1599 
1600  // Defaults that differ when not C++.
1601  switch (Language) {
1603  LLVMStyle.SpacesInContainerLiterals = false;
1604  break;
1605  case FormatStyle::LK_Json:
1606  LLVMStyle.ColumnLimit = 0;
1607  break;
1609  LLVMStyle.IndentCaseLabels = true;
1610  LLVMStyle.SpacesInContainerLiterals = false;
1611  break;
1612  default:
1613  break;
1614  }
1615 
1616  return LLVMStyle;
1617 }
1618 
1622  GoogleStyle.Language = FormatStyle::LK_TextProto;
1623 
1624  return GoogleStyle;
1625  }
1626 
1627  FormatStyle GoogleStyle = getLLVMStyle(Language);
1628 
1629  GoogleStyle.AccessModifierOffset = -1;
1633  GoogleStyle.AllowShortLoopsOnASingleLine = true;
1634  GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
1636  GoogleStyle.DerivePointerAlignment = true;
1638  GoogleStyle.IncludeStyle.IncludeCategories = {{"^<ext/.*\\.h>", 2, 0, false},
1639  {"^<.*\\.h>", 1, 0, false},
1640  {"^<.*", 2, 0, false},
1641  {".*", 3, 0, false}};
1642  GoogleStyle.IncludeStyle.IncludeIsMainRegex = "([-_](test|unittest))?$";
1643  GoogleStyle.IndentCaseLabels = true;
1644  GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
1646  GoogleStyle.ObjCSpaceAfterProperty = false;
1647  GoogleStyle.ObjCSpaceBeforeProtocolList = true;
1650  GoogleStyle.RawStringFormats = {
1651  {
1653  /*Delimiters=*/
1654  {
1655  "cc",
1656  "CC",
1657  "cpp",
1658  "Cpp",
1659  "CPP",
1660  "c++",
1661  "C++",
1662  },
1663  /*EnclosingFunctionNames=*/
1664  {},
1665  /*CanonicalDelimiter=*/"",
1666  /*BasedOnStyle=*/"google",
1667  },
1668  {
1670  /*Delimiters=*/
1671  {
1672  "pb",
1673  "PB",
1674  "proto",
1675  "PROTO",
1676  },
1677  /*EnclosingFunctionNames=*/
1678  {
1679  "EqualsProto",
1680  "EquivToProto",
1681  "PARSE_PARTIAL_TEXT_PROTO",
1682  "PARSE_TEST_PROTO",
1683  "PARSE_TEXT_PROTO",
1684  "ParseTextOrDie",
1685  "ParseTextProtoOrDie",
1686  "ParseTestProto",
1687  "ParsePartialTestProto",
1688  },
1689  /*CanonicalDelimiter=*/"pb",
1690  /*BasedOnStyle=*/"google",
1691  },
1692  };
1693 
1694  GoogleStyle.SpacesBeforeTrailingComments = 2;
1695  GoogleStyle.Standard = FormatStyle::LS_Auto;
1696 
1697  GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
1698  GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
1699 
1700  if (Language == FormatStyle::LK_Java) {
1703  GoogleStyle.AlignTrailingComments = {};
1707  GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
1709  GoogleStyle.ColumnLimit = 100;
1710  GoogleStyle.SpaceAfterCStyleCast = true;
1711  GoogleStyle.SpacesBeforeTrailingComments = 1;
1712  } else if (Language == FormatStyle::LK_JavaScript) {
1716  // TODO: still under discussion whether to switch to SLS_All.
1718  GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
1719  GoogleStyle.BreakBeforeTernaryOperators = false;
1720  // taze:, triple slash directives (`/// <...`), tslint:, and @see, which is
1721  // commonly followed by overlong URLs.
1722  GoogleStyle.CommentPragmas = "(taze:|^/[ \t]*<|tslint:|@see)";
1723  // TODO: enable once decided, in particular re disabling bin packing.
1724  // https://google.github.io/styleguide/jsguide.html#features-arrays-trailing-comma
1725  // GoogleStyle.InsertTrailingCommas = FormatStyle::TCS_Wrapped;
1727  GoogleStyle.JavaScriptWrapImports = false;
1728  GoogleStyle.MaxEmptyLinesToKeep = 3;
1730  GoogleStyle.SpacesInContainerLiterals = false;
1731  } else if (Language == FormatStyle::LK_Proto) {
1733  GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
1734  // This affects protocol buffer options specifications and text protos.
1735  // Text protos are currently mostly formatted inside C++ raw string literals
1736  // and often the current breaking behavior of string literals is not
1737  // beneficial there. Investigate turning this on once proper string reflow
1738  // has been implemented.
1739  GoogleStyle.BreakStringLiterals = false;
1740  GoogleStyle.Cpp11BracedListStyle = false;
1741  GoogleStyle.SpacesInContainerLiterals = false;
1742  } else if (Language == FormatStyle::LK_ObjC) {
1743  GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
1744  GoogleStyle.ColumnLimit = 100;
1745  // "Regroup" doesn't work well for ObjC yet (main header heuristic,
1746  // relationship between ObjC standard library headers and other heades,
1747  // #imports, etc.)
1748  GoogleStyle.IncludeStyle.IncludeBlocks =
1750  } else if (Language == FormatStyle::LK_CSharp) {
1753  GoogleStyle.BreakStringLiterals = false;
1754  GoogleStyle.ColumnLimit = 100;
1756  }
1757 
1758  return GoogleStyle;
1759 }
1760 
1762  FormatStyle ChromiumStyle = getGoogleStyle(Language);
1763 
1764  // Disable include reordering across blocks in Chromium code.
1765  // - clang-format tries to detect that foo.h is the "main" header for
1766  // foo.cc and foo_unittest.cc via IncludeIsMainRegex. However, Chromium
1767  // uses many other suffices (_win.cc, _mac.mm, _posix.cc, _browsertest.cc,
1768  // _private.cc, _impl.cc etc) in different permutations
1769  // (_win_browsertest.cc) so disable this until IncludeIsMainRegex has a
1770  // better default for Chromium code.
1771  // - The default for .cc and .mm files is different (r357695) for Google style
1772  // for the same reason. The plan is to unify this again once the main
1773  // header detection works for Google's ObjC code, but this hasn't happened
1774  // yet. Since Chromium has some ObjC code, switching Chromium is blocked
1775  // on that.
1776  // - Finally, "If include reordering is harmful, put things in different
1777  // blocks to prevent it" has been a recommendation for a long time that
1778  // people are used to. We'll need a dev education push to change this to
1779  // "If include reordering is harmful, put things in a different block and
1780  // _prepend that with a comment_ to prevent it" before changing behavior.
1781  ChromiumStyle.IncludeStyle.IncludeBlocks =
1783 
1784  if (Language == FormatStyle::LK_Java) {
1785  ChromiumStyle.AllowShortIfStatementsOnASingleLine =
1787  ChromiumStyle.BreakAfterJavaFieldAnnotations = true;
1788  ChromiumStyle.ContinuationIndentWidth = 8;
1789  ChromiumStyle.IndentWidth = 4;
1790  // See styleguide for import groups:
1791  // https://chromium.googlesource.com/chromium/src/+/refs/heads/main/styleguide/java/java.md#Import-Order
1792  ChromiumStyle.JavaImportGroups = {
1793  "android",
1794  "androidx",
1795  "com",
1796  "dalvik",
1797  "junit",
1798  "org",
1799  "com.google.android.apps.chrome",
1800  "org.chromium",
1801  "java",
1802  "javax",
1803  };
1805  } else if (Language == FormatStyle::LK_JavaScript) {
1807  ChromiumStyle.AllowShortLoopsOnASingleLine = false;
1808  } else {
1809  ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
1812  ChromiumStyle.AllowShortLoopsOnASingleLine = false;
1813  ChromiumStyle.BinPackParameters = false;
1814  ChromiumStyle.DerivePointerAlignment = false;
1816  ChromiumStyle.ColumnLimit = 80;
1817  }
1818  return ChromiumStyle;
1819 }
1820 
1822  FormatStyle MozillaStyle = getLLVMStyle();
1823  MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
1827  MozillaStyle.BinPackArguments = false;
1828  MozillaStyle.BinPackParameters = false;
1834  MozillaStyle.ConstructorInitializerIndentWidth = 2;
1835  MozillaStyle.ContinuationIndentWidth = 2;
1836  MozillaStyle.Cpp11BracedListStyle = false;
1837  MozillaStyle.FixNamespaceComments = false;
1838  MozillaStyle.IndentCaseLabels = true;
1839  MozillaStyle.ObjCSpaceAfterProperty = true;
1840  MozillaStyle.ObjCSpaceBeforeProtocolList = false;
1841  MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
1842  MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
1843  MozillaStyle.SpaceAfterTemplateKeyword = false;
1844  return MozillaStyle;
1845 }
1846 
1848  FormatStyle Style = getLLVMStyle();
1849  Style.AccessModifierOffset = -4;
1852  Style.AlignTrailingComments = {};
1858  Style.ColumnLimit = 0;
1859  Style.Cpp11BracedListStyle = false;
1860  Style.FixNamespaceComments = false;
1861  Style.IndentWidth = 4;
1863  Style.ObjCBlockIndentWidth = 4;
1864  Style.ObjCSpaceAfterProperty = true;
1866  Style.SpaceBeforeCpp11BracedList = true;
1867  Style.SpaceInEmptyBlock = true;
1868  return Style;
1869 }
1870 
1872  FormatStyle Style = getLLVMStyle();
1877  Style.BreakBeforeTernaryOperators = true;
1878  Style.ColumnLimit = 79;
1879  Style.Cpp11BracedListStyle = false;
1880  Style.FixNamespaceComments = false;
1883  return Style;
1884 }
1885 
1888  Style.ColumnLimit = 120;
1889  Style.TabWidth = 4;
1890  Style.IndentWidth = 4;
1891  Style.UseTab = FormatStyle::UT_Never;
1893  Style.BraceWrapping.AfterClass = true;
1895  Style.BraceWrapping.AfterEnum = true;
1896  Style.BraceWrapping.AfterFunction = true;
1897  Style.BraceWrapping.AfterNamespace = true;
1898  Style.BraceWrapping.AfterObjCDeclaration = true;
1899  Style.BraceWrapping.AfterStruct = true;
1900  Style.BraceWrapping.AfterExternBlock = true;
1901  Style.BraceWrapping.BeforeCatch = true;
1902  Style.BraceWrapping.BeforeElse = true;
1903  Style.BraceWrapping.BeforeWhile = false;
1904  Style.PenaltyReturnTypeOnItsOwnLine = 1000;
1905  Style.AllowShortEnumsOnASingleLine = false;
1907  Style.AllowShortCaseLabelsOnASingleLine = false;
1909  Style.AllowShortLoopsOnASingleLine = false;
1912  return Style;
1913 }
1914 
1916  FormatStyle Style = getLLVMStyle();
1917  Style.InsertBraces = true;
1918  Style.InsertNewlineAtEOF = true;
1919  Style.IntegerLiteralSeparator.Decimal = 3;
1922  Style.RemoveBracesLLVM = true;
1924  Style.RemoveSemicolon = true;
1925  return Style;
1926 }
1927 
1929  FormatStyle NoStyle = getLLVMStyle();
1930  NoStyle.DisableFormat = true;
1933  return NoStyle;
1934 }
1935 
1937  FormatStyle *Style) {
1938  if (Name.equals_insensitive("llvm"))
1939  *Style = getLLVMStyle(Language);
1940  else if (Name.equals_insensitive("chromium"))
1941  *Style = getChromiumStyle(Language);
1942  else if (Name.equals_insensitive("mozilla"))
1943  *Style = getMozillaStyle();
1944  else if (Name.equals_insensitive("google"))
1945  *Style = getGoogleStyle(Language);
1946  else if (Name.equals_insensitive("webkit"))
1947  *Style = getWebKitStyle();
1948  else if (Name.equals_insensitive("gnu"))
1949  *Style = getGNUStyle();
1950  else if (Name.equals_insensitive("microsoft"))
1951  *Style = getMicrosoftStyle(Language);
1952  else if (Name.equals_insensitive("clang-format"))
1953  *Style = getClangFormatStyle();
1954  else if (Name.equals_insensitive("none"))
1955  *Style = getNoStyle();
1956  else if (Name.equals_insensitive("inheritparentconfig"))
1957  Style->InheritsParentConfig = true;
1958  else
1959  return false;
1960 
1961  Style->Language = Language;
1962  return true;
1963 }
1964 
1966  // If its empty then it means don't do anything.
1967  if (Style->QualifierOrder.empty())
1969 
1970  // Ensure the list contains only currently valid qualifiers.
1971  for (const auto &Qualifier : Style->QualifierOrder) {
1972  if (Qualifier == "type")
1973  continue;
1974  auto token =
1976  if (token == tok::identifier)
1978  }
1979 
1980  // Ensure the list is unique (no duplicates).
1981  std::set<std::string> UniqueQualifiers(Style->QualifierOrder.begin(),
1982  Style->QualifierOrder.end());
1983  if (Style->QualifierOrder.size() != UniqueQualifiers.size()) {
1984  LLVM_DEBUG(llvm::dbgs()
1985  << "Duplicate Qualifiers " << Style->QualifierOrder.size()
1986  << " vs " << UniqueQualifiers.size() << "\n");
1988  }
1989 
1990  // Ensure the list has 'type' in it.
1991  if (!llvm::is_contained(Style->QualifierOrder, "type"))
1993 
1994  return ParseError::Success;
1995 }
1996 
1997 std::error_code parseConfiguration(llvm::MemoryBufferRef Config,
1998  FormatStyle *Style, bool AllowUnknownOptions,
1999  llvm::SourceMgr::DiagHandlerTy DiagHandler,
2000  void *DiagHandlerCtxt) {
2001  assert(Style);
2003  assert(Language != FormatStyle::LK_None);
2004  if (Config.getBuffer().trim().empty())
2006  Style->StyleSet.Clear();
2007  std::vector<FormatStyle> Styles;
2008  llvm::yaml::Input Input(Config, /*Ctxt=*/nullptr, DiagHandler,
2009  DiagHandlerCtxt);
2010  // DocumentListTraits<vector<FormatStyle>> uses the context to get default
2011  // values for the fields, keys for which are missing from the configuration.
2012  // Mapping also uses the context to get the language to find the correct
2013  // base style.
2014  Input.setContext(Style);
2015  Input.setAllowUnknownKeys(AllowUnknownOptions);
2016  Input >> Styles;
2017  if (Input.error())
2018  return Input.error();
2019 
2020  for (unsigned i = 0; i < Styles.size(); ++i) {
2021  // Ensures that only the first configuration can skip the Language option.
2022  if (Styles[i].Language == FormatStyle::LK_None && i != 0)
2024  // Ensure that each language is configured at most once.
2025  for (unsigned j = 0; j < i; ++j) {
2026  if (Styles[i].Language == Styles[j].Language) {
2027  LLVM_DEBUG(llvm::dbgs()
2028  << "Duplicate languages in the config file on positions "
2029  << j << " and " << i << "\n");
2031  }
2032  }
2033  }
2034  // Look for a suitable configuration starting from the end, so we can
2035  // find the configuration for the specific language first, and the default
2036  // configuration (which can only be at slot 0) after it.
2037  FormatStyle::FormatStyleSet StyleSet;
2038  bool LanguageFound = false;
2039  for (const FormatStyle &Style : llvm::reverse(Styles)) {
2040  if (Style.Language != FormatStyle::LK_None)
2041  StyleSet.Add(Style);
2042  if (Style.Language == Language)
2043  LanguageFound = true;
2044  }
2045  if (!LanguageFound) {
2046  if (Styles.empty() || Styles[0].Language != FormatStyle::LK_None)
2048  FormatStyle DefaultStyle = Styles[0];
2049  DefaultStyle.Language = Language;
2050  StyleSet.Add(std::move(DefaultStyle));
2051  }
2052  *Style = *StyleSet.Get(Language);
2054  Style->BinPackArguments) {
2055  // See comment on FormatStyle::TSC_Wrapped.
2057  }
2059  return make_error_code(validateQualifierOrder(Style));
2061 }
2062 
2063 std::string configurationAsText(const FormatStyle &Style) {
2064  std::string Text;
2065  llvm::raw_string_ostream Stream(Text);
2066  llvm::yaml::Output Output(Stream);
2067  // We use the same mapping method for input and output, so we need a non-const
2068  // reference here.
2069  FormatStyle NonConstStyle = Style;
2070  expandPresetsBraceWrapping(NonConstStyle);
2071  expandPresetsSpaceBeforeParens(NonConstStyle);
2072  expandPresetsSpacesInParens(NonConstStyle);
2073  Output << NonConstStyle;
2074 
2075  return Stream.str();
2076 }
2077 
2078 std::optional<FormatStyle>
2080  if (!Styles)
2081  return std::nullopt;
2082  auto It = Styles->find(Language);
2083  if (It == Styles->end())
2084  return std::nullopt;
2085  FormatStyle Style = It->second;
2086  Style.StyleSet = *this;
2087  return Style;
2088 }
2089 
2091  assert(Style.Language != LK_None &&
2092  "Cannot add a style for LK_None to a StyleSet");
2093  assert(
2094  !Style.StyleSet.Styles &&
2095  "Cannot add a style associated with an existing StyleSet to a StyleSet");
2096  if (!Styles)
2097  Styles = std::make_shared<MapType>();
2098  (*Styles)[Style.Language] = std::move(Style);
2099 }
2100 
2101 void FormatStyle::FormatStyleSet::Clear() { Styles.reset(); }
2102 
2103 std::optional<FormatStyle>
2105  return StyleSet.Get(Language);
2106 }
2107 
2108 namespace {
2109 
2110 class ParensRemover : public TokenAnalyzer {
2111 public:
2112  ParensRemover(const Environment &Env, const FormatStyle &Style)
2113  : TokenAnalyzer(Env, Style) {}
2114 
2115  std::pair<tooling::Replacements, unsigned>
2116  analyze(TokenAnnotator &Annotator,
2117  SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2118  FormatTokenLexer &Tokens) override {
2119  AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2120  tooling::Replacements Result;
2121  removeParens(AnnotatedLines, Result);
2122  return {Result, 0};
2123  }
2124 
2125 private:
2126  void removeParens(SmallVectorImpl<AnnotatedLine *> &Lines,
2127  tooling::Replacements &Result) {
2128  const auto &SourceMgr = Env.getSourceManager();
2129  for (auto *Line : Lines) {
2130  removeParens(Line->Children, Result);
2131  if (!Line->Affected)
2132  continue;
2133  for (const auto *Token = Line->First; Token && !Token->Finalized;
2134  Token = Token->Next) {
2135  if (!Token->Optional || !Token->isOneOf(tok::l_paren, tok::r_paren))
2136  continue;
2137  auto *Next = Token->Next;
2138  assert(Next && Next->isNot(tok::eof));
2139  SourceLocation Start;
2140  if (Next->NewlinesBefore == 0) {
2141  Start = Token->Tok.getLocation();
2142  Next->WhitespaceRange = Token->WhitespaceRange;
2143  } else {
2144  Start = Token->WhitespaceRange.getBegin();
2145  }
2146  const auto &Range =
2147  CharSourceRange::getCharRange(Start, Token->Tok.getEndLoc());
2148  cantFail(Result.add(tooling::Replacement(SourceMgr, Range, " ")));
2149  }
2150  }
2151  }
2152 };
2153 
2154 class BracesInserter : public TokenAnalyzer {
2155 public:
2156  BracesInserter(const Environment &Env, const FormatStyle &Style)
2157  : TokenAnalyzer(Env, Style) {}
2158 
2159  std::pair<tooling::Replacements, unsigned>
2160  analyze(TokenAnnotator &Annotator,
2161  SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2162  FormatTokenLexer &Tokens) override {
2163  AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2164  tooling::Replacements Result;
2165  insertBraces(AnnotatedLines, Result);
2166  return {Result, 0};
2167  }
2168 
2169 private:
2170  void insertBraces(SmallVectorImpl<AnnotatedLine *> &Lines,
2171  tooling::Replacements &Result) {
2172  const auto &SourceMgr = Env.getSourceManager();
2173  int OpeningBraceSurplus = 0;
2174  for (AnnotatedLine *Line : Lines) {
2175  insertBraces(Line->Children, Result);
2176  if (!Line->Affected && OpeningBraceSurplus == 0)
2177  continue;
2178  for (FormatToken *Token = Line->First; Token && !Token->Finalized;
2179  Token = Token->Next) {
2180  int BraceCount = Token->BraceCount;
2181  if (BraceCount == 0)
2182  continue;
2183  std::string Brace;
2184  if (BraceCount < 0) {
2185  assert(BraceCount == -1);
2186  if (!Line->Affected)
2187  break;
2188  Brace = Token->is(tok::comment) ? "\n{" : "{";
2189  ++OpeningBraceSurplus;
2190  } else {
2191  if (OpeningBraceSurplus == 0)
2192  break;
2193  if (OpeningBraceSurplus < BraceCount)
2194  BraceCount = OpeningBraceSurplus;
2195  Brace = '\n' + std::string(BraceCount, '}');
2196  OpeningBraceSurplus -= BraceCount;
2197  }
2198  Token->BraceCount = 0;
2199  const auto Start = Token->Tok.getEndLoc();
2200  cantFail(Result.add(tooling::Replacement(SourceMgr, Start, 0, Brace)));
2201  }
2202  }
2203  assert(OpeningBraceSurplus == 0);
2204  }
2205 };
2206 
2207 class BracesRemover : public TokenAnalyzer {
2208 public:
2209  BracesRemover(const Environment &Env, const FormatStyle &Style)
2210  : TokenAnalyzer(Env, Style) {}
2211 
2212  std::pair<tooling::Replacements, unsigned>
2213  analyze(TokenAnnotator &Annotator,
2214  SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2215  FormatTokenLexer &Tokens) override {
2216  AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2217  tooling::Replacements Result;
2218  removeBraces(AnnotatedLines, Result);
2219  return {Result, 0};
2220  }
2221 
2222 private:
2223  void removeBraces(SmallVectorImpl<AnnotatedLine *> &Lines,
2224  tooling::Replacements &Result) {
2225  const auto &SourceMgr = Env.getSourceManager();
2226  const auto End = Lines.end();
2227  for (auto I = Lines.begin(); I != End; ++I) {
2228  const auto Line = *I;
2229  removeBraces(Line->Children, Result);
2230  if (!Line->Affected)
2231  continue;
2232  const auto NextLine = I + 1 == End ? nullptr : I[1];
2233  for (auto Token = Line->First; Token && !Token->Finalized;
2234  Token = Token->Next) {
2235  if (!Token->Optional)
2236  continue;
2237  if (!Token->isOneOf(tok::l_brace, tok::r_brace))
2238  continue;
2239  auto Next = Token->Next;
2240  assert(Next || Token == Line->Last);
2241  if (!Next && NextLine)
2242  Next = NextLine->First;
2243  SourceLocation Start;
2244  if (Next && Next->NewlinesBefore == 0 && Next->isNot(tok::eof)) {
2245  Start = Token->Tok.getLocation();
2246  Next->WhitespaceRange = Token->WhitespaceRange;
2247  } else {
2248  Start = Token->WhitespaceRange.getBegin();
2249  }
2250  const auto Range =
2251  CharSourceRange::getCharRange(Start, Token->Tok.getEndLoc());
2252  cantFail(Result.add(tooling::Replacement(SourceMgr, Range, "")));
2253  }
2254  }
2255  }
2256 };
2257 
2258 class SemiRemover : public TokenAnalyzer {
2259 public:
2260  SemiRemover(const Environment &Env, const FormatStyle &Style)
2261  : TokenAnalyzer(Env, Style) {}
2262 
2263  std::pair<tooling::Replacements, unsigned>
2264  analyze(TokenAnnotator &Annotator,
2265  SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2266  FormatTokenLexer &Tokens) override {
2267  AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2268  tooling::Replacements Result;
2269  removeSemi(Annotator, AnnotatedLines, Result);
2270  return {Result, 0};
2271  }
2272 
2273 private:
2274  void removeSemi(TokenAnnotator &Annotator,
2275  SmallVectorImpl<AnnotatedLine *> &Lines,
2276  tooling::Replacements &Result) {
2277  auto PrecededByFunctionRBrace = [](const FormatToken &Tok) {
2278  const auto *Prev = Tok.Previous;
2279  if (!Prev || Prev->isNot(tok::r_brace))
2280  return false;
2281  const auto *LBrace = Prev->MatchingParen;
2282  return LBrace && LBrace->is(TT_FunctionLBrace);
2283  };
2284  const auto &SourceMgr = Env.getSourceManager();
2285  const auto End = Lines.end();
2286  for (auto I = Lines.begin(); I != End; ++I) {
2287  const auto Line = *I;
2288  removeSemi(Annotator, Line->Children, Result);
2289  if (!Line->Affected)
2290  continue;
2291  Annotator.calculateFormattingInformation(*Line);
2292  const auto NextLine = I + 1 == End ? nullptr : I[1];
2293  for (auto Token = Line->First; Token && !Token->Finalized;
2294  Token = Token->Next) {
2295  if (Token->isNot(tok::semi) ||
2296  (!Token->Optional && !PrecededByFunctionRBrace(*Token))) {
2297  continue;
2298  }
2299  auto Next = Token->Next;
2300  assert(Next || Token == Line->Last);
2301  if (!Next && NextLine)
2302  Next = NextLine->First;
2303  SourceLocation Start;
2304  if (Next && Next->NewlinesBefore == 0 && Next->isNot(tok::eof)) {
2305  Start = Token->Tok.getLocation();
2306  Next->WhitespaceRange = Token->WhitespaceRange;
2307  } else {
2308  Start = Token->WhitespaceRange.getBegin();
2309  }
2310  const auto Range =
2311  CharSourceRange::getCharRange(Start, Token->Tok.getEndLoc());
2312  cantFail(Result.add(tooling::Replacement(SourceMgr, Range, "")));
2313  }
2314  }
2315  }
2316 };
2317 
2318 class JavaScriptRequoter : public TokenAnalyzer {
2319 public:
2320  JavaScriptRequoter(const Environment &Env, const FormatStyle &Style)
2321  : TokenAnalyzer(Env, Style) {}
2322 
2323  std::pair<tooling::Replacements, unsigned>
2324  analyze(TokenAnnotator &Annotator,
2325  SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2326  FormatTokenLexer &Tokens) override {
2327  AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2328  tooling::Replacements Result;
2329  requoteJSStringLiteral(AnnotatedLines, Result);
2330  return {Result, 0};
2331  }
2332 
2333 private:
2334  // Replaces double/single-quoted string literal as appropriate, re-escaping
2335  // the contents in the process.
2336  void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
2337  tooling::Replacements &Result) {
2338  for (AnnotatedLine *Line : Lines) {
2339  requoteJSStringLiteral(Line->Children, Result);
2340  if (!Line->Affected)
2341  continue;
2342  for (FormatToken *FormatTok = Line->First; FormatTok;
2343  FormatTok = FormatTok->Next) {
2344  StringRef Input = FormatTok->TokenText;
2345  if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
2346  // NB: testing for not starting with a double quote to avoid
2347  // breaking `template strings`.
2349  !Input.starts_with("\"")) ||
2351  !Input.starts_with("\'"))) {
2352  continue;
2353  }
2354 
2355  // Change start and end quote.
2356  bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
2357  SourceLocation Start = FormatTok->Tok.getLocation();
2358  auto Replace = [&](SourceLocation Start, unsigned Length,
2359  StringRef ReplacementText) {
2360  auto Err = Result.add(tooling::Replacement(
2361  Env.getSourceManager(), Start, Length, ReplacementText));
2362  // FIXME: handle error. For now, print error message and skip the
2363  // replacement for release version.
2364  if (Err) {
2365  llvm::errs() << toString(std::move(Err)) << "\n";
2366  assert(false);
2367  }
2368  };
2369  Replace(Start, 1, IsSingle ? "'" : "\"");
2370  Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
2371  IsSingle ? "'" : "\"");
2372 
2373  // Escape internal quotes.
2374  bool Escaped = false;
2375  for (size_t i = 1; i < Input.size() - 1; i++) {
2376  switch (Input[i]) {
2377  case '\\':
2378  if (!Escaped && i + 1 < Input.size() &&
2379  ((IsSingle && Input[i + 1] == '"') ||
2380  (!IsSingle && Input[i + 1] == '\''))) {
2381  // Remove this \, it's escaping a " or ' that no longer needs
2382  // escaping
2383  Replace(Start.getLocWithOffset(i), 1, "");
2384  continue;
2385  }
2386  Escaped = !Escaped;
2387  break;
2388  case '\"':
2389  case '\'':
2390  if (!Escaped && IsSingle == (Input[i] == '\'')) {
2391  // Escape the quote.
2392  Replace(Start.getLocWithOffset(i), 0, "\\");
2393  }
2394  Escaped = false;
2395  break;
2396  default:
2397  Escaped = false;
2398  break;
2399  }
2400  }
2401  }
2402  }
2403  }
2404 };
2405 
2406 class Formatter : public TokenAnalyzer {
2407 public:
2408  Formatter(const Environment &Env, const FormatStyle &Style,
2409  FormattingAttemptStatus *Status)
2410  : TokenAnalyzer(Env, Style), Status(Status) {}
2411 
2412  std::pair<tooling::Replacements, unsigned>
2413  analyze(TokenAnnotator &Annotator,
2414  SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2415  FormatTokenLexer &Tokens) override {
2416  tooling::Replacements Result;
2417  deriveLocalStyle(AnnotatedLines);
2418  AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2419  for (AnnotatedLine *Line : AnnotatedLines)
2420  Annotator.calculateFormattingInformation(*Line);
2421  Annotator.setCommentLineLevels(AnnotatedLines);
2422 
2423  WhitespaceManager Whitespaces(
2424  Env.getSourceManager(), Style,
2427  Env.getSourceManager().getBufferData(Env.getFileID()),
2429  : Style.LineEnding == FormatStyle::LE_CRLF);
2430  ContinuationIndenter Indenter(Style, Tokens.getKeywords(),
2431  Env.getSourceManager(), Whitespaces, Encoding,
2432  BinPackInconclusiveFunctions);
2433  unsigned Penalty =
2434  UnwrappedLineFormatter(&Indenter, &Whitespaces, Style,
2435  Tokens.getKeywords(), Env.getSourceManager(),
2436  Status)
2437  .format(AnnotatedLines, /*DryRun=*/false,
2438  /*AdditionalIndent=*/0,
2439  /*FixBadIndentation=*/false,
2440  /*FirstStartColumn=*/Env.getFirstStartColumn(),
2441  /*NextStartColumn=*/Env.getNextStartColumn(),
2442  /*LastStartColumn=*/Env.getLastStartColumn());
2443  for (const auto &R : Whitespaces.generateReplacements())
2444  if (Result.add(R))
2445  return std::make_pair(Result, 0);
2446  return std::make_pair(Result, Penalty);
2447  }
2448 
2449 private:
2450  bool
2451  hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
2452  for (const AnnotatedLine *Line : Lines) {
2453  if (hasCpp03IncompatibleFormat(Line->Children))
2454  return true;
2455  for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
2456  if (!Tok->hasWhitespaceBefore()) {
2457  if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
2458  return true;
2459  if (Tok->is(TT_TemplateCloser) &&
2460  Tok->Previous->is(TT_TemplateCloser)) {
2461  return true;
2462  }
2463  }
2464  }
2465  }
2466  return false;
2467  }
2468 
2469  int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
2470  int AlignmentDiff = 0;
2471  for (const AnnotatedLine *Line : Lines) {
2472  AlignmentDiff += countVariableAlignments(Line->Children);
2473  for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
2474  if (Tok->isNot(TT_PointerOrReference))
2475  continue;
2476  // Don't treat space in `void foo() &&` as evidence.
2477  if (const auto *Prev = Tok->getPreviousNonComment()) {
2478  if (Prev->is(tok::r_paren) && Prev->MatchingParen) {
2479  if (const auto *Func =
2480  Prev->MatchingParen->getPreviousNonComment()) {
2481  if (Func->isOneOf(TT_FunctionDeclarationName, TT_StartOfName,
2482  TT_OverloadedOperator)) {
2483  continue;
2484  }
2485  }
2486  }
2487  }
2488  bool SpaceBefore = Tok->hasWhitespaceBefore();
2489  bool SpaceAfter = Tok->Next->hasWhitespaceBefore();
2490  if (SpaceBefore && !SpaceAfter)
2491  ++AlignmentDiff;
2492  if (!SpaceBefore && SpaceAfter)
2493  --AlignmentDiff;
2494  }
2495  }
2496  return AlignmentDiff;
2497  }
2498 
2499  void
2500  deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
2501  bool HasBinPackedFunction = false;
2502  bool HasOnePerLineFunction = false;
2503  for (AnnotatedLine *Line : AnnotatedLines) {
2504  if (!Line->First->Next)
2505  continue;
2506  FormatToken *Tok = Line->First->Next;
2507  while (Tok->Next) {
2508  if (Tok->is(PPK_BinPacked))
2509  HasBinPackedFunction = true;
2510  if (Tok->is(PPK_OnePerLine))
2511  HasOnePerLineFunction = true;
2512 
2513  Tok = Tok->Next;
2514  }
2515  }
2516  if (Style.DerivePointerAlignment) {
2517  const auto NetRightCount = countVariableAlignments(AnnotatedLines);
2518  if (NetRightCount > 0)
2520  else if (NetRightCount < 0)
2523  }
2524  if (Style.Standard == FormatStyle::LS_Auto) {
2525  Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
2528  }
2529  BinPackInconclusiveFunctions =
2530  HasBinPackedFunction || !HasOnePerLineFunction;
2531  }
2532 
2533  bool BinPackInconclusiveFunctions;
2534  FormattingAttemptStatus *Status;
2535 };
2536 
2537 /// TrailingCommaInserter inserts trailing commas into container literals.
2538 /// E.g.:
2539 /// const x = [
2540 /// 1,
2541 /// ];
2542 /// TrailingCommaInserter runs after formatting. To avoid causing a required
2543 /// reformatting (and thus reflow), it never inserts a comma that'd exceed the
2544 /// ColumnLimit.
2545 ///
2546 /// Because trailing commas disable binpacking of arrays, TrailingCommaInserter
2547 /// is conceptually incompatible with bin packing.
2548 class TrailingCommaInserter : public TokenAnalyzer {
2549 public:
2550  TrailingCommaInserter(const Environment &Env, const FormatStyle &Style)
2551  : TokenAnalyzer(Env, Style) {}
2552 
2553  std::pair<tooling::Replacements, unsigned>
2554  analyze(TokenAnnotator &Annotator,
2555  SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2556  FormatTokenLexer &Tokens) override {
2557  AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2558  tooling::Replacements Result;
2559  insertTrailingCommas(AnnotatedLines, Result);
2560  return {Result, 0};
2561  }
2562 
2563 private:
2564  /// Inserts trailing commas in [] and {} initializers if they wrap over
2565  /// multiple lines.
2566  void insertTrailingCommas(SmallVectorImpl<AnnotatedLine *> &Lines,
2567  tooling::Replacements &Result) {
2568  for (AnnotatedLine *Line : Lines) {
2569  insertTrailingCommas(Line->Children, Result);
2570  if (!Line->Affected)
2571  continue;
2572  for (FormatToken *FormatTok = Line->First; FormatTok;
2573  FormatTok = FormatTok->Next) {
2574  if (FormatTok->NewlinesBefore == 0)
2575  continue;
2576  FormatToken *Matching = FormatTok->MatchingParen;
2577  if (!Matching || !FormatTok->getPreviousNonComment())
2578  continue;
2579  if (!(FormatTok->is(tok::r_square) &&
2580  Matching->is(TT_ArrayInitializerLSquare)) &&
2581  !(FormatTok->is(tok::r_brace) && Matching->is(TT_DictLiteral))) {
2582  continue;
2583  }
2584  FormatToken *Prev = FormatTok->getPreviousNonComment();
2585  if (Prev->is(tok::comma) || Prev->is(tok::semi))
2586  continue;
2587  // getEndLoc is not reliably set during re-lexing, use text length
2588  // instead.
2589  SourceLocation Start =
2590  Prev->Tok.getLocation().getLocWithOffset(Prev->TokenText.size());
2591  // If inserting a comma would push the code over the column limit, skip
2592  // this location - it'd introduce an unstable formatting due to the
2593  // required reflow.
2594  unsigned ColumnNumber =
2595  Env.getSourceManager().getSpellingColumnNumber(Start);
2596  if (ColumnNumber > Style.ColumnLimit)
2597  continue;
2598  // Comma insertions cannot conflict with each other, and this pass has a
2599  // clean set of Replacements, so the operation below cannot fail.
2600  cantFail(Result.add(
2601  tooling::Replacement(Env.getSourceManager(), Start, 0, ",")));
2602  }
2603  }
2604  }
2605 };
2606 
2607 // This class clean up the erroneous/redundant code around the given ranges in
2608 // file.
2609 class Cleaner : public TokenAnalyzer {
2610 public:
2611  Cleaner(const Environment &Env, const FormatStyle &Style)
2612  : TokenAnalyzer(Env, Style),
2613  DeletedTokens(FormatTokenLess(Env.getSourceManager())) {}
2614 
2615  // FIXME: eliminate unused parameters.
2616  std::pair<tooling::Replacements, unsigned>
2617  analyze(TokenAnnotator &Annotator,
2618  SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2619  FormatTokenLexer &Tokens) override {
2620  // FIXME: in the current implementation the granularity of affected range
2621  // is an annotated line. However, this is not sufficient. Furthermore,
2622  // redundant code introduced by replacements does not necessarily
2623  // intercept with ranges of replacements that result in the redundancy.
2624  // To determine if some redundant code is actually introduced by
2625  // replacements(e.g. deletions), we need to come up with a more
2626  // sophisticated way of computing affected ranges.
2627  AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2628 
2629  checkEmptyNamespace(AnnotatedLines);
2630 
2631  for (auto *Line : AnnotatedLines)
2632  cleanupLine(Line);
2633 
2634  return {generateFixes(), 0};
2635  }
2636 
2637 private:
2638  void cleanupLine(AnnotatedLine *Line) {
2639  for (auto *Child : Line->Children)
2640  cleanupLine(Child);
2641 
2642  if (Line->Affected) {
2643  cleanupRight(Line->First, tok::comma, tok::comma);
2644  cleanupRight(Line->First, TT_CtorInitializerColon, tok::comma);
2645  cleanupRight(Line->First, tok::l_paren, tok::comma);
2646  cleanupLeft(Line->First, tok::comma, tok::r_paren);
2647  cleanupLeft(Line->First, TT_CtorInitializerComma, tok::l_brace);
2648  cleanupLeft(Line->First, TT_CtorInitializerColon, tok::l_brace);
2649  cleanupLeft(Line->First, TT_CtorInitializerColon, tok::equal);
2650  }
2651  }
2652 
2653  bool containsOnlyComments(const AnnotatedLine &Line) {
2654  for (FormatToken *Tok = Line.First; Tok; Tok = Tok->Next)
2655  if (Tok->isNot(tok::comment))
2656  return false;
2657  return true;
2658  }
2659 
2660  // Iterate through all lines and remove any empty (nested) namespaces.
2661  void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
2662  std::set<unsigned> DeletedLines;
2663  for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
2664  auto &Line = *AnnotatedLines[i];
2665  if (Line.startsWithNamespace())
2666  checkEmptyNamespace(AnnotatedLines, i, i, DeletedLines);
2667  }
2668 
2669  for (auto Line : DeletedLines) {
2670  FormatToken *Tok = AnnotatedLines[Line]->First;
2671  while (Tok) {
2672  deleteToken(Tok);
2673  Tok = Tok->Next;
2674  }
2675  }
2676  }
2677 
2678  // The function checks if the namespace, which starts from \p CurrentLine, and
2679  // its nested namespaces are empty and delete them if they are empty. It also
2680  // sets \p NewLine to the last line checked.
2681  // Returns true if the current namespace is empty.
2682  bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2683  unsigned CurrentLine, unsigned &NewLine,
2684  std::set<unsigned> &DeletedLines) {
2685  unsigned InitLine = CurrentLine, End = AnnotatedLines.size();
2686  if (Style.BraceWrapping.AfterNamespace) {
2687  // If the left brace is in a new line, we should consume it first so that
2688  // it does not make the namespace non-empty.
2689  // FIXME: error handling if there is no left brace.
2690  if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
2691  NewLine = CurrentLine;
2692  return false;
2693  }
2694  } else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
2695  return false;
2696  }
2697  while (++CurrentLine < End) {
2698  if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
2699  break;
2700 
2701  if (AnnotatedLines[CurrentLine]->startsWithNamespace()) {
2702  if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine,
2703  DeletedLines)) {
2704  return false;
2705  }
2706  CurrentLine = NewLine;
2707  continue;
2708  }
2709 
2710  if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
2711  continue;
2712 
2713  // If there is anything other than comments or nested namespaces in the
2714  // current namespace, the namespace cannot be empty.
2715  NewLine = CurrentLine;
2716  return false;
2717  }
2718 
2719  NewLine = CurrentLine;
2720  if (CurrentLine >= End)
2721  return false;
2722 
2723  // Check if the empty namespace is actually affected by changed ranges.
2724  if (!AffectedRangeMgr.affectsCharSourceRange(CharSourceRange::getCharRange(
2725  AnnotatedLines[InitLine]->First->Tok.getLocation(),
2726  AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc()))) {
2727  return false;
2728  }
2729 
2730  for (unsigned i = InitLine; i <= CurrentLine; ++i)
2731  DeletedLines.insert(i);
2732 
2733  return true;
2734  }
2735 
2736  // Checks pairs {start, start->next},..., {end->previous, end} and deletes one
2737  // of the token in the pair if the left token has \p LK token kind and the
2738  // right token has \p RK token kind. If \p DeleteLeft is true, the left token
2739  // is deleted on match; otherwise, the right token is deleted.
2740  template <typename LeftKind, typename RightKind>
2741  void cleanupPair(FormatToken *Start, LeftKind LK, RightKind RK,
2742  bool DeleteLeft) {
2743  auto NextNotDeleted = [this](const FormatToken &Tok) -> FormatToken * {
2744  for (auto *Res = Tok.Next; Res; Res = Res->Next) {
2745  if (Res->isNot(tok::comment) &&
2746  DeletedTokens.find(Res) == DeletedTokens.end()) {
2747  return Res;
2748  }
2749  }
2750  return nullptr;
2751  };
2752  for (auto *Left = Start; Left;) {
2753  auto *Right = NextNotDeleted(*Left);
2754  if (!Right)
2755  break;
2756  if (Left->is(LK) && Right->is(RK)) {
2757  deleteToken(DeleteLeft ? Left : Right);
2758  for (auto *Tok = Left->Next; Tok && Tok != Right; Tok = Tok->Next)
2759  deleteToken(Tok);
2760  // If the right token is deleted, we should keep the left token
2761  // unchanged and pair it with the new right token.
2762  if (!DeleteLeft)
2763  continue;
2764  }
2765  Left = Right;
2766  }
2767  }
2768 
2769  template <typename LeftKind, typename RightKind>
2770  void cleanupLeft(FormatToken *Start, LeftKind LK, RightKind RK) {
2771  cleanupPair(Start, LK, RK, /*DeleteLeft=*/true);
2772  }
2773 
2774  template <typename LeftKind, typename RightKind>
2775  void cleanupRight(FormatToken *Start, LeftKind LK, RightKind RK) {
2776  cleanupPair(Start, LK, RK, /*DeleteLeft=*/false);
2777  }
2778 
2779  // Delete the given token.
2780  inline void deleteToken(FormatToken *Tok) {
2781  if (Tok)
2782  DeletedTokens.insert(Tok);
2783  }
2784 
2785  tooling::Replacements generateFixes() {
2786  tooling::Replacements Fixes;
2787  SmallVector<FormatToken *> Tokens;
2788  std::copy(DeletedTokens.begin(), DeletedTokens.end(),
2789  std::back_inserter(Tokens));
2790 
2791  // Merge multiple continuous token deletions into one big deletion so that
2792  // the number of replacements can be reduced. This makes computing affected
2793  // ranges more efficient when we run reformat on the changed code.
2794  unsigned Idx = 0;
2795  while (Idx < Tokens.size()) {
2796  unsigned St = Idx, End = Idx;
2797  while ((End + 1) < Tokens.size() && Tokens[End]->Next == Tokens[End + 1])
2798  ++End;
2799  auto SR = CharSourceRange::getCharRange(Tokens[St]->Tok.getLocation(),
2800  Tokens[End]->Tok.getEndLoc());
2801  auto Err =
2802  Fixes.add(tooling::Replacement(Env.getSourceManager(), SR, ""));
2803  // FIXME: better error handling. for now just print error message and skip
2804  // for the release version.
2805  if (Err) {
2806  llvm::errs() << toString(std::move(Err)) << "\n";
2807  assert(false && "Fixes must not conflict!");
2808  }
2809  Idx = End + 1;
2810  }
2811 
2812  return Fixes;
2813  }
2814 
2815  // Class for less-than inequality comparason for the set `RedundantTokens`.
2816  // We store tokens in the order they appear in the translation unit so that
2817  // we do not need to sort them in `generateFixes()`.
2818  struct FormatTokenLess {
2819  FormatTokenLess(const SourceManager &SM) : SM(SM) {}
2820 
2821  bool operator()(const FormatToken *LHS, const FormatToken *RHS) const {
2822  return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(),
2823  RHS->Tok.getLocation());
2824  }
2825  const SourceManager &SM;
2826  };
2827 
2828  // Tokens to be deleted.
2829  std::set<FormatToken *, FormatTokenLess> DeletedTokens;
2830 };
2831 
2832 class ObjCHeaderStyleGuesser : public TokenAnalyzer {
2833 public:
2834  ObjCHeaderStyleGuesser(const Environment &Env, const FormatStyle &Style)
2835  : TokenAnalyzer(Env, Style), IsObjC(false) {}
2836 
2837  std::pair<tooling::Replacements, unsigned>
2838  analyze(TokenAnnotator &Annotator,
2839  SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2840  FormatTokenLexer &Tokens) override {
2841  assert(Style.Language == FormatStyle::LK_Cpp);
2842  IsObjC = guessIsObjC(Env.getSourceManager(), AnnotatedLines,
2843  Tokens.getKeywords());
2844  tooling::Replacements Result;
2845  return {Result, 0};
2846  }
2847 
2848  bool isObjC() { return IsObjC; }
2849 
2850 private:
2851  static bool
2852  guessIsObjC(const SourceManager &SourceManager,
2853  const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2854  const AdditionalKeywords &Keywords) {
2855  // Keep this array sorted, since we are binary searching over it.
2856  static constexpr llvm::StringLiteral FoundationIdentifiers[] = {
2857  "CGFloat",
2858  "CGPoint",
2859  "CGPointMake",
2860  "CGPointZero",
2861  "CGRect",
2862  "CGRectEdge",
2863  "CGRectInfinite",
2864  "CGRectMake",
2865  "CGRectNull",
2866  "CGRectZero",
2867  "CGSize",
2868  "CGSizeMake",
2869  "CGVector",
2870  "CGVectorMake",
2871  "FOUNDATION_EXPORT", // This is an alias for FOUNDATION_EXTERN.
2872  "FOUNDATION_EXTERN",
2873  "NSAffineTransform",
2874  "NSArray",
2875  "NSAttributedString",
2876  "NSBlockOperation",
2877  "NSBundle",
2878  "NSCache",
2879  "NSCalendar",
2880  "NSCharacterSet",
2881  "NSCountedSet",
2882  "NSData",
2883  "NSDataDetector",
2884  "NSDecimal",
2885  "NSDecimalNumber",
2886  "NSDictionary",
2887  "NSEdgeInsets",
2888  "NSError",
2889  "NSErrorDomain",
2890  "NSHashTable",
2891  "NSIndexPath",
2892  "NSIndexSet",
2893  "NSInteger",
2894  "NSInvocationOperation",
2895  "NSLocale",
2896  "NSMapTable",
2897  "NSMutableArray",
2898  "NSMutableAttributedString",
2899  "NSMutableCharacterSet",
2900  "NSMutableData",
2901  "NSMutableDictionary",
2902  "NSMutableIndexSet",
2903  "NSMutableOrderedSet",
2904  "NSMutableSet",
2905  "NSMutableString",
2906  "NSNumber",
2907  "NSNumberFormatter",
2908  "NSObject",
2909  "NSOperation",
2910  "NSOperationQueue",
2911  "NSOperationQueuePriority",
2912  "NSOrderedSet",
2913  "NSPoint",
2914  "NSPointerArray",
2915  "NSQualityOfService",
2916  "NSRange",
2917  "NSRect",
2918  "NSRegularExpression",
2919  "NSSet",
2920  "NSSize",
2921  "NSString",
2922  "NSTimeZone",
2923  "NSUInteger",
2924  "NSURL",
2925  "NSURLComponents",
2926  "NSURLQueryItem",
2927  "NSUUID",
2928  "NSValue",
2929  "NS_ASSUME_NONNULL_BEGIN",
2930  "UIImage",
2931  "UIView",
2932  };
2933 
2934  for (auto *Line : AnnotatedLines) {
2935  if (Line->First && (Line->First->TokenText.starts_with("#") ||
2936  Line->First->TokenText == "__pragma" ||
2937  Line->First->TokenText == "_Pragma")) {
2938  continue;
2939  }
2940  for (const FormatToken *FormatTok = Line->First; FormatTok;
2941  FormatTok = FormatTok->Next) {
2942  if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) &&
2943  (FormatTok->Tok.getObjCKeywordID() != tok::objc_not_keyword ||
2944  FormatTok->isOneOf(tok::numeric_constant, tok::l_square,
2945  tok::l_brace))) ||
2946  (FormatTok->Tok.isAnyIdentifier() &&
2947  std::binary_search(std::begin(FoundationIdentifiers),
2948  std::end(FoundationIdentifiers),
2949  FormatTok->TokenText)) ||
2950  FormatTok->is(TT_ObjCStringLiteral) ||
2951  FormatTok->isOneOf(Keywords.kw_NS_CLOSED_ENUM, Keywords.kw_NS_ENUM,
2952  Keywords.kw_NS_ERROR_ENUM,
2953  Keywords.kw_NS_OPTIONS, TT_ObjCBlockLBrace,
2954  TT_ObjCBlockLParen, TT_ObjCDecl, TT_ObjCForIn,
2955  TT_ObjCMethodExpr, TT_ObjCMethodSpecifier,
2956  TT_ObjCProperty)) {
2957  LLVM_DEBUG(llvm::dbgs()
2958  << "Detected ObjC at location "
2959  << FormatTok->Tok.getLocation().printToString(
2960  SourceManager)
2961  << " token: " << FormatTok->TokenText << " token type: "
2962  << getTokenTypeName(FormatTok->getType()) << "\n");
2963  return true;
2964  }
2965  }
2966  if (guessIsObjC(SourceManager, Line->Children, Keywords))
2967  return true;
2968  }
2969  return false;
2970  }
2971 
2972  bool IsObjC;
2973 };
2974 
2975 struct IncludeDirective {
2976  StringRef Filename;
2977  StringRef Text;
2978  unsigned Offset;
2981 };
2982 
2983 struct JavaImportDirective {
2984  StringRef Identifier;
2985  StringRef Text;
2986  unsigned Offset;
2987  SmallVector<StringRef> AssociatedCommentLines;
2988  bool IsStatic;
2989 };
2990 
2991 } // end anonymous namespace
2992 
2993 // Determines whether 'Ranges' intersects with ('Start', 'End').
2994 static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
2995  unsigned End) {
2996  for (const auto &Range : Ranges) {
2997  if (Range.getOffset() < End &&
2998  Range.getOffset() + Range.getLength() > Start) {
2999  return true;
3000  }
3001  }
3002  return false;
3003 }
3004 
3005 // Returns a pair (Index, OffsetToEOL) describing the position of the cursor
3006 // before sorting/deduplicating. Index is the index of the include under the
3007 // cursor in the original set of includes. If this include has duplicates, it is
3008 // the index of the first of the duplicates as the others are going to be
3009 // removed. OffsetToEOL describes the cursor's position relative to the end of
3010 // its current line.
3011 // If `Cursor` is not on any #include, `Index` will be UINT_MAX.
3012 static std::pair<unsigned, unsigned>
3014  const SmallVectorImpl<unsigned> &Indices, unsigned Cursor) {
3015  unsigned CursorIndex = UINT_MAX;
3016  unsigned OffsetToEOL = 0;
3017  for (int i = 0, e = Includes.size(); i != e; ++i) {
3018  unsigned Start = Includes[Indices[i]].Offset;
3019  unsigned End = Start + Includes[Indices[i]].Text.size();
3020  if (!(Cursor >= Start && Cursor < End))
3021  continue;
3022  CursorIndex = Indices[i];
3023  OffsetToEOL = End - Cursor;
3024  // Put the cursor on the only remaining #include among the duplicate
3025  // #includes.
3026  while (--i >= 0 && Includes[CursorIndex].Text == Includes[Indices[i]].Text)
3027  CursorIndex = i;
3028  break;
3029  }
3030  return std::make_pair(CursorIndex, OffsetToEOL);
3031 }
3032 
3033 // Replace all "\r\n" with "\n".
3034 std::string replaceCRLF(const std::string &Code) {
3035  std::string NewCode;
3036  size_t Pos = 0, LastPos = 0;
3037 
3038  do {
3039  Pos = Code.find("\r\n", LastPos);
3040  if (Pos == LastPos) {
3041  ++LastPos;
3042  continue;
3043  }
3044  if (Pos == std::string::npos) {
3045  NewCode += Code.substr(LastPos);
3046  break;
3047  }
3048  NewCode += Code.substr(LastPos, Pos - LastPos) + "\n";
3049  LastPos = Pos + 2;
3050  } while (Pos != std::string::npos);
3051 
3052  return NewCode;
3053 }
3054 
3055 // Sorts and deduplicate a block of includes given by 'Includes' alphabetically
3056 // adding the necessary replacement to 'Replaces'. 'Includes' must be in strict
3057 // source order.
3058 // #include directives with the same text will be deduplicated, and only the
3059 // first #include in the duplicate #includes remains. If the `Cursor` is
3060 // provided and put on a deleted #include, it will be moved to the remaining
3061 // #include in the duplicate #includes.
3062 static void sortCppIncludes(const FormatStyle &Style,
3063  const SmallVectorImpl<IncludeDirective> &Includes,
3064  ArrayRef<tooling::Range> Ranges, StringRef FileName,
3065  StringRef Code, tooling::Replacements &Replaces,
3066  unsigned *Cursor) {
3068  const unsigned IncludesBeginOffset = Includes.front().Offset;
3069  const unsigned IncludesEndOffset =
3070  Includes.back().Offset + Includes.back().Text.size();
3071  const unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset;
3072  if (!affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset))
3073  return;
3074  SmallVector<unsigned, 16> Indices =
3075  llvm::to_vector<16>(llvm::seq<unsigned>(0, Includes.size()));
3076 
3078  stable_sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
3079  const auto LHSFilenameLower = Includes[LHSI].Filename.lower();
3080  const auto RHSFilenameLower = Includes[RHSI].Filename.lower();
3081  return std::tie(Includes[LHSI].Priority, LHSFilenameLower,
3082  Includes[LHSI].Filename) <
3083  std::tie(Includes[RHSI].Priority, RHSFilenameLower,
3084  Includes[RHSI].Filename);
3085  });
3086  } else {
3087  stable_sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
3088  return std::tie(Includes[LHSI].Priority, Includes[LHSI].Filename) <
3089  std::tie(Includes[RHSI].Priority, Includes[RHSI].Filename);
3090  });
3091  }
3092 
3093  // The index of the include on which the cursor will be put after
3094  // sorting/deduplicating.
3095  unsigned CursorIndex;
3096  // The offset from cursor to the end of line.
3097  unsigned CursorToEOLOffset;
3098  if (Cursor) {
3099  std::tie(CursorIndex, CursorToEOLOffset) =
3100  FindCursorIndex(Includes, Indices, *Cursor);
3101  }
3102 
3103  // Deduplicate #includes.
3104  Indices.erase(std::unique(Indices.begin(), Indices.end(),
3105  [&](unsigned LHSI, unsigned RHSI) {
3106  return Includes[LHSI].Text.trim() ==
3107  Includes[RHSI].Text.trim();
3108  }),
3109  Indices.end());
3110 
3111  int CurrentCategory = Includes.front().Category;
3112 
3113  // If the #includes are out of order, we generate a single replacement fixing
3114  // the entire block. Otherwise, no replacement is generated.
3115  // In case Style.IncldueStyle.IncludeBlocks != IBS_Preserve, this check is not
3116  // enough as additional newlines might be added or removed across #include
3117  // blocks. This we handle below by generating the updated #include blocks and
3118  // comparing it to the original.
3119  if (Indices.size() == Includes.size() && is_sorted(Indices) &&
3121  return;
3122  }
3123 
3124  const auto OldCursor = Cursor ? *Cursor : 0;
3125  std::string result;
3126  for (unsigned Index : Indices) {
3127  if (!result.empty()) {
3128  result += "\n";
3129  if (Style.IncludeStyle.IncludeBlocks ==
3131  CurrentCategory != Includes[Index].Category) {
3132  result += "\n";
3133  }
3134  }
3135  result += Includes[Index].Text;
3136  if (Cursor && CursorIndex == Index)
3137  *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
3138  CurrentCategory = Includes[Index].Category;
3139  }
3140 
3141  if (Cursor && *Cursor >= IncludesEndOffset)
3142  *Cursor += result.size() - IncludesBlockSize;
3143 
3144  // If the #includes are out of order, we generate a single replacement fixing
3145  // the entire range of blocks. Otherwise, no replacement is generated.
3146  if (replaceCRLF(result) == replaceCRLF(std::string(Code.substr(
3147  IncludesBeginOffset, IncludesBlockSize)))) {
3148  if (Cursor)
3149  *Cursor = OldCursor;
3150  return;
3151  }
3152 
3153  auto Err = Replaces.add(tooling::Replacement(
3154  FileName, Includes.front().Offset, IncludesBlockSize, result));
3155  // FIXME: better error handling. For now, just skip the replacement for the
3156  // release version.
3157  if (Err) {
3158  llvm::errs() << toString(std::move(Err)) << "\n";
3159  assert(false);
3160  }
3161 }
3162 
3164  ArrayRef<tooling::Range> Ranges,
3165  StringRef FileName,
3166  tooling::Replacements &Replaces,
3167  unsigned *Cursor) {
3168  unsigned Prev = llvm::StringSwitch<size_t>(Code)
3169  .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
3170  .Default(0);
3171  unsigned SearchFrom = 0;
3172  SmallVector<StringRef, 4> Matches;
3173  SmallVector<IncludeDirective, 16> IncludesInBlock;
3174 
3175  // In compiled files, consider the first #include to be the main #include of
3176  // the file if it is not a system #include. This ensures that the header
3177  // doesn't have hidden dependencies
3178  // (http://llvm.org/docs/CodingStandards.html#include-style).
3179  //
3180  // FIXME: Do some validation, e.g. edit distance of the base name, to fix
3181  // cases where the first #include is unlikely to be the main header.
3183  bool FirstIncludeBlock = true;
3184  bool MainIncludeFound = false;
3185  bool FormattingOff = false;
3186 
3187  // '[' must be the first and '-' the last character inside [...].
3188  llvm::Regex RawStringRegex(
3189  "R\"([][A-Za-z0-9_{}#<>%:;.?*+/^&\\$|~!=,'-]*)\\(");
3190  SmallVector<StringRef, 2> RawStringMatches;
3191  std::string RawStringTermination = ")\"";
3192 
3193  for (;;) {
3194  auto Pos = Code.find('\n', SearchFrom);
3195  StringRef Line =
3196  Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
3197 
3198  StringRef Trimmed = Line.trim();
3199 
3200  // #includes inside raw string literals need to be ignored.
3201  // or we will sort the contents of the string.
3202  // Skip past until we think we are at the rawstring literal close.
3203  if (RawStringRegex.match(Trimmed, &RawStringMatches)) {
3204  std::string CharSequence = RawStringMatches[1].str();
3205  RawStringTermination = ")" + CharSequence + "\"";
3206  FormattingOff = true;
3207  }
3208 
3209  if (Trimmed.contains(RawStringTermination))
3210  FormattingOff = false;
3211 
3212  if (isClangFormatOff(Trimmed))
3213  FormattingOff = true;
3214  else if (isClangFormatOn(Trimmed))
3215  FormattingOff = false;
3216 
3217  const bool EmptyLineSkipped =
3218  Trimmed.empty() &&
3220  Style.IncludeStyle.IncludeBlocks ==
3222 
3223  bool MergeWithNextLine = Trimmed.ends_with("\\");
3224  if (!FormattingOff && !MergeWithNextLine) {
3225  if (tooling::HeaderIncludes::IncludeRegex.match(Line, &Matches)) {
3226  StringRef IncludeName = Matches[2];
3227  if (Line.contains("/*") && !Line.contains("*/")) {
3228  // #include with a start of a block comment, but without the end.
3229  // Need to keep all the lines until the end of the comment together.
3230  // FIXME: This is somehow simplified check that probably does not work
3231  // correctly if there are multiple comments on a line.
3232  Pos = Code.find("*/", SearchFrom);
3233  Line = Code.substr(
3234  Prev, (Pos != StringRef::npos ? Pos + 2 : Code.size()) - Prev);
3235  }
3236  int Category = Categories.getIncludePriority(
3237  IncludeName,
3238  /*CheckMainHeader=*/!MainIncludeFound && FirstIncludeBlock);
3239  int Priority = Categories.getSortIncludePriority(
3240  IncludeName, !MainIncludeFound && FirstIncludeBlock);
3241  if (Category == 0)
3242  MainIncludeFound = true;
3243  IncludesInBlock.push_back(
3244  {IncludeName, Line, Prev, Category, Priority});
3245  } else if (!IncludesInBlock.empty() && !EmptyLineSkipped) {
3246  sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Code,
3247  Replaces, Cursor);
3248  IncludesInBlock.clear();
3249  if (Trimmed.starts_with("#pragma hdrstop")) // Precompiled headers.
3250  FirstIncludeBlock = true;
3251  else
3252  FirstIncludeBlock = false;
3253  }
3254  }
3255  if (Pos == StringRef::npos || Pos + 1 == Code.size())
3256  break;
3257 
3258  if (!MergeWithNextLine)
3259  Prev = Pos + 1;
3260  SearchFrom = Pos + 1;
3261  }
3262  if (!IncludesInBlock.empty()) {
3263  sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Code, Replaces,
3264  Cursor);
3265  }
3266  return Replaces;
3267 }
3268 
3269 // Returns group number to use as a first order sort on imports. Gives UINT_MAX
3270 // if the import does not match any given groups.
3271 static unsigned findJavaImportGroup(const FormatStyle &Style,
3272  StringRef ImportIdentifier) {
3273  unsigned LongestMatchIndex = UINT_MAX;
3274  unsigned LongestMatchLength = 0;
3275  for (unsigned I = 0; I < Style.JavaImportGroups.size(); I++) {
3276  const std::string &GroupPrefix = Style.JavaImportGroups[I];
3277  if (ImportIdentifier.starts_with(GroupPrefix) &&
3278  GroupPrefix.length() > LongestMatchLength) {
3279  LongestMatchIndex = I;
3280  LongestMatchLength = GroupPrefix.length();
3281  }
3282  }
3283  return LongestMatchIndex;
3284 }
3285 
3286 // Sorts and deduplicates a block of includes given by 'Imports' based on
3287 // JavaImportGroups, then adding the necessary replacement to 'Replaces'.
3288 // Import declarations with the same text will be deduplicated. Between each
3289 // import group, a newline is inserted, and within each import group, a
3290 // lexicographic sort based on ASCII value is performed.
3291 static void sortJavaImports(const FormatStyle &Style,
3292  const SmallVectorImpl<JavaImportDirective> &Imports,
3293  ArrayRef<tooling::Range> Ranges, StringRef FileName,
3294  StringRef Code, tooling::Replacements &Replaces) {
3295  unsigned ImportsBeginOffset = Imports.front().Offset;
3296  unsigned ImportsEndOffset =
3297  Imports.back().Offset + Imports.back().Text.size();
3298  unsigned ImportsBlockSize = ImportsEndOffset - ImportsBeginOffset;
3299  if (!affectsRange(Ranges, ImportsBeginOffset, ImportsEndOffset))
3300  return;
3301 
3302  SmallVector<unsigned, 16> Indices =
3303  llvm::to_vector<16>(llvm::seq<unsigned>(0, Imports.size()));
3305  JavaImportGroups.reserve(Imports.size());
3306  for (const JavaImportDirective &Import : Imports)
3307  JavaImportGroups.push_back(findJavaImportGroup(Style, Import.Identifier));
3308 
3309  bool StaticImportAfterNormalImport =
3311  sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
3312  // Negating IsStatic to push static imports above non-static imports.
3313  return std::make_tuple(!Imports[LHSI].IsStatic ^
3314  StaticImportAfterNormalImport,
3315  JavaImportGroups[LHSI], Imports[LHSI].Identifier) <
3316  std::make_tuple(!Imports[RHSI].IsStatic ^
3317  StaticImportAfterNormalImport,
3318  JavaImportGroups[RHSI], Imports[RHSI].Identifier);
3319  });
3320 
3321  // Deduplicate imports.
3322  Indices.erase(std::unique(Indices.begin(), Indices.end(),
3323  [&](unsigned LHSI, unsigned RHSI) {
3324  return Imports[LHSI].Text == Imports[RHSI].Text;
3325  }),
3326  Indices.end());
3327 
3328  bool CurrentIsStatic = Imports[Indices.front()].IsStatic;
3329  unsigned CurrentImportGroup = JavaImportGroups[Indices.front()];
3330 
3331  std::string result;
3332  for (unsigned Index : Indices) {
3333  if (!result.empty()) {
3334  result += "\n";
3335  if (CurrentIsStatic != Imports[Index].IsStatic ||
3336  CurrentImportGroup != JavaImportGroups[Index]) {
3337  result += "\n";
3338  }
3339  }
3340  for (StringRef CommentLine : Imports[Index].AssociatedCommentLines) {
3341  result += CommentLine;
3342  result += "\n";
3343  }
3344  result += Imports[Index].Text;
3345  CurrentIsStatic = Imports[Index].IsStatic;
3346  CurrentImportGroup = JavaImportGroups[Index];
3347  }
3348 
3349  // If the imports are out of order, we generate a single replacement fixing
3350  // the entire block. Otherwise, no replacement is generated.
3351  if (replaceCRLF(result) == replaceCRLF(std::string(Code.substr(
3352  Imports.front().Offset, ImportsBlockSize)))) {
3353  return;
3354  }
3355 
3356  auto Err = Replaces.add(tooling::Replacement(FileName, Imports.front().Offset,
3357  ImportsBlockSize, result));
3358  // FIXME: better error handling. For now, just skip the replacement for the
3359  // release version.
3360  if (Err) {
3361  llvm::errs() << toString(std::move(Err)) << "\n";
3362  assert(false);
3363  }
3364 }
3365 
3366 namespace {
3367 
3368 const char JavaImportRegexPattern[] =
3369  "^[\t ]*import[\t ]+(static[\t ]*)?([^\t ]*)[\t ]*;";
3370 
3371 } // anonymous namespace
3372 
3374  ArrayRef<tooling::Range> Ranges,
3375  StringRef FileName,
3376  tooling::Replacements &Replaces) {
3377  unsigned Prev = 0;
3378  unsigned SearchFrom = 0;
3379  llvm::Regex ImportRegex(JavaImportRegexPattern);
3380  SmallVector<StringRef, 4> Matches;
3381  SmallVector<JavaImportDirective, 16> ImportsInBlock;
3383 
3384  bool FormattingOff = false;
3385 
3386  for (;;) {
3387  auto Pos = Code.find('\n', SearchFrom);
3388  StringRef Line =
3389  Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
3390 
3391  StringRef Trimmed = Line.trim();
3392  if (isClangFormatOff(Trimmed))
3393  FormattingOff = true;
3394  else if (isClangFormatOn(Trimmed))
3395  FormattingOff = false;
3396 
3397  if (ImportRegex.match(Line, &Matches)) {
3398  if (FormattingOff) {
3399  // If at least one import line has formatting turned off, turn off
3400  // formatting entirely.
3401  return Replaces;
3402  }
3403  StringRef Static = Matches[1];
3404  StringRef Identifier = Matches[2];
3405  bool IsStatic = false;
3406  if (Static.contains("static"))
3407  IsStatic = true;
3408  ImportsInBlock.push_back(
3409  {Identifier, Line, Prev, AssociatedCommentLines, IsStatic});
3410  AssociatedCommentLines.clear();
3411  } else if (Trimmed.size() > 0 && !ImportsInBlock.empty()) {
3412  // Associating comments within the imports with the nearest import below
3413  AssociatedCommentLines.push_back(Line);
3414  }
3415  Prev = Pos + 1;
3416  if (Pos == StringRef::npos || Pos + 1 == Code.size())
3417  break;
3418  SearchFrom = Pos + 1;
3419  }
3420  if (!ImportsInBlock.empty())
3421  sortJavaImports(Style, ImportsInBlock, Ranges, FileName, Code, Replaces);
3422  return Replaces;
3423 }
3424 
3425 bool isMpegTS(StringRef Code) {
3426  // MPEG transport streams use the ".ts" file extension. clang-format should
3427  // not attempt to format those. MPEG TS' frame format starts with 0x47 every
3428  // 189 bytes - detect that and return.
3429  return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
3430 }
3431 
3432 bool isLikelyXml(StringRef Code) { return Code.ltrim().starts_with("<"); }
3433 
3434 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
3435  ArrayRef<tooling::Range> Ranges,
3436  StringRef FileName, unsigned *Cursor) {
3437  tooling::Replacements Replaces;
3438  if (!Style.SortIncludes || Style.DisableFormat)
3439  return Replaces;
3440  if (isLikelyXml(Code))
3441  return Replaces;
3442  if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
3443  isMpegTS(Code)) {
3444  return Replaces;
3445  }
3446  if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript)
3447  return sortJavaScriptImports(Style, Code, Ranges, FileName);
3448  if (Style.Language == FormatStyle::LanguageKind::LK_Java)
3449  return sortJavaImports(Style, Code, Ranges, FileName, Replaces);
3450  sortCppIncludes(Style, Code, Ranges, FileName, Replaces, Cursor);
3451  return Replaces;
3452 }
3453 
3454 template <typename T>
3456 processReplacements(T ProcessFunc, StringRef Code,
3457  const tooling::Replacements &Replaces,
3458  const FormatStyle &Style) {
3459  if (Replaces.empty())
3460  return tooling::Replacements();
3461 
3462  auto NewCode = applyAllReplacements(Code, Replaces);
3463  if (!NewCode)
3464  return NewCode.takeError();
3465  std::vector<tooling::Range> ChangedRanges = Replaces.getAffectedRanges();
3466  StringRef FileName = Replaces.begin()->getFilePath();
3467 
3468  tooling::Replacements FormatReplaces =
3469  ProcessFunc(Style, *NewCode, ChangedRanges, FileName);
3470 
3471  return Replaces.merge(FormatReplaces);
3472 }
3473 
3475 formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
3476  const FormatStyle &Style) {
3477  // We need to use lambda function here since there are two versions of
3478  // `sortIncludes`.
3479  auto SortIncludes = [](const FormatStyle &Style, StringRef Code,
3480  std::vector<tooling::Range> Ranges,
3481  StringRef FileName) -> tooling::Replacements {
3482  return sortIncludes(Style, Code, Ranges, FileName);
3483  };
3484  auto SortedReplaces =
3485  processReplacements(SortIncludes, Code, Replaces, Style);
3486  if (!SortedReplaces)
3487  return SortedReplaces.takeError();
3488 
3489  // We need to use lambda function here since there are two versions of
3490  // `reformat`.
3491  auto Reformat = [](const FormatStyle &Style, StringRef Code,
3492  std::vector<tooling::Range> Ranges,
3493  StringRef FileName) -> tooling::Replacements {
3494  return reformat(Style, Code, Ranges, FileName);
3495  };
3496  return processReplacements(Reformat, Code, *SortedReplaces, Style);
3497 }
3498 
3499 namespace {
3500 
3501 inline bool isHeaderInsertion(const tooling::Replacement &Replace) {
3502  return Replace.getOffset() == UINT_MAX && Replace.getLength() == 0 &&
3504  Replace.getReplacementText());
3505 }
3506 
3507 inline bool isHeaderDeletion(const tooling::Replacement &Replace) {
3508  return Replace.getOffset() == UINT_MAX && Replace.getLength() == 1;
3509 }
3510 
3511 // FIXME: insert empty lines between newly created blocks.
3512 tooling::Replacements
3513 fixCppIncludeInsertions(StringRef Code, const tooling::Replacements &Replaces,
3514  const FormatStyle &Style) {
3515  if (!Style.isCpp())
3516  return Replaces;
3517 
3518  tooling::Replacements HeaderInsertions;
3519  std::set<StringRef> HeadersToDelete;
3520  tooling::Replacements Result;
3521  for (const auto &R : Replaces) {
3522  if (isHeaderInsertion(R)) {
3523  // Replacements from \p Replaces must be conflict-free already, so we can
3524  // simply consume the error.
3525  consumeError(HeaderInsertions.add(R));
3526  } else if (isHeaderDeletion(R)) {
3527  HeadersToDelete.insert(R.getReplacementText());
3528  } else if (R.getOffset() == UINT_MAX) {
3529  llvm::errs() << "Insertions other than header #include insertion are "
3530  "not supported! "
3531  << R.getReplacementText() << "\n";
3532  } else {
3533  consumeError(Result.add(R));
3534  }
3535  }
3536  if (HeaderInsertions.empty() && HeadersToDelete.empty())
3537  return Replaces;
3538 
3539  StringRef FileName = Replaces.begin()->getFilePath();
3540  tooling::HeaderIncludes Includes(FileName, Code, Style.IncludeStyle);
3541 
3542  for (const auto &Header : HeadersToDelete) {
3543  tooling::Replacements Replaces =
3544  Includes.remove(Header.trim("\"<>"), Header.starts_with("<"));
3545  for (const auto &R : Replaces) {
3546  auto Err = Result.add(R);
3547  if (Err) {
3548  // Ignore the deletion on conflict.
3549  llvm::errs() << "Failed to add header deletion replacement for "
3550  << Header << ": " << toString(std::move(Err)) << "\n";
3551  }
3552  }
3553  }
3554 
3555  SmallVector<StringRef, 4> Matches;
3556  for (const auto &R : HeaderInsertions) {
3557  auto IncludeDirective = R.getReplacementText();
3558  bool Matched =
3560  assert(Matched && "Header insertion replacement must have replacement text "
3561  "'#include ...'");
3562  (void)Matched;
3563  auto IncludeName = Matches[2];
3564  auto Replace =
3565  Includes.insert(IncludeName.trim("\"<>"), IncludeName.starts_with("<"),
3567  if (Replace) {
3568  auto Err = Result.add(*Replace);
3569  if (Err) {
3570  consumeError(std::move(Err));
3571  unsigned NewOffset =
3572  Result.getShiftedCodePosition(Replace->getOffset());
3573  auto Shifted = tooling::Replacement(FileName, NewOffset, 0,
3574  Replace->getReplacementText());
3575  Result = Result.merge(tooling::Replacements(Shifted));
3576  }
3577  }
3578  }
3579  return Result;
3580 }
3581 
3582 } // anonymous namespace
3583 
3584 Expected<tooling::Replacements>
3585 cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
3586  const FormatStyle &Style) {
3587  // We need to use lambda function here since there are two versions of
3588  // `cleanup`.
3589  auto Cleanup = [](const FormatStyle &Style, StringRef Code,
3590  ArrayRef<tooling::Range> Ranges,
3591  StringRef FileName) -> tooling::Replacements {
3592  return cleanup(Style, Code, Ranges, FileName);
3593  };
3594  // Make header insertion replacements insert new headers into correct blocks.
3595  tooling::Replacements NewReplaces =
3596  fixCppIncludeInsertions(Code, Replaces, Style);
3597  return cantFail(processReplacements(Cleanup, Code, NewReplaces, Style));
3598 }
3599 
3600 namespace internal {
3601 std::pair<tooling::Replacements, unsigned>
3602 reformat(const FormatStyle &Style, StringRef Code,
3603  ArrayRef<tooling::Range> Ranges, unsigned FirstStartColumn,
3604  unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName,
3605  FormattingAttemptStatus *Status) {
3606  FormatStyle Expanded = Style;
3607  expandPresetsBraceWrapping(Expanded);
3609  expandPresetsSpacesInParens(Expanded);
3610  Expanded.InsertBraces = false;
3611  Expanded.RemoveBracesLLVM = false;
3613  Expanded.RemoveSemicolon = false;
3614  switch (Expanded.RequiresClausePosition) {
3617  Expanded.IndentRequiresClause = false;
3618  break;
3619  default:
3620  break;
3621  }
3622 
3623  if (Expanded.DisableFormat)
3624  return {tooling::Replacements(), 0};
3625  if (isLikelyXml(Code))
3626  return {tooling::Replacements(), 0};
3627  if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code))
3628  return {tooling::Replacements(), 0};
3629 
3630  // JSON only needs the formatting passing.
3631  if (Style.isJson()) {
3632  std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
3633  auto Env = Environment::make(Code, FileName, Ranges, FirstStartColumn,
3634  NextStartColumn, LastStartColumn);
3635  if (!Env)
3636  return {};
3637  // Perform the actual formatting pass.
3638  tooling::Replacements Replaces =
3639  Formatter(*Env, Style, Status).process().first;
3640  // add a replacement to remove the "x = " from the result.
3641  Replaces = Replaces.merge(
3643  // apply the reformatting changes and the removal of "x = ".
3644  if (applyAllReplacements(Code, Replaces))
3645  return {Replaces, 0};
3646  return {tooling::Replacements(), 0};
3647  }
3648 
3649  auto Env = Environment::make(Code, FileName, Ranges, FirstStartColumn,
3650  NextStartColumn, LastStartColumn);
3651  if (!Env)
3652  return {};
3653 
3654  typedef std::function<std::pair<tooling::Replacements, unsigned>(
3655  const Environment &)>
3656  AnalyzerPass;
3657 
3659 
3660  Passes.emplace_back([&](const Environment &Env) {
3661  return IntegerLiteralSeparatorFixer().process(Env, Expanded);
3662  });
3663 
3664  if (Style.isCpp()) {
3666  addQualifierAlignmentFixerPasses(Expanded, Passes);
3667 
3669  FormatStyle S = Expanded;
3670  S.RemoveParentheses = Style.RemoveParentheses;
3671  Passes.emplace_back([&, S = std::move(S)](const Environment &Env) {
3672  return ParensRemover(Env, S).process(/*SkipAnnotation=*/true);
3673  });
3674  }
3675 
3676  if (Style.InsertBraces) {
3677  FormatStyle S = Expanded;
3678  S.InsertBraces = true;
3679  Passes.emplace_back([&, S = std::move(S)](const Environment &Env) {
3680  return BracesInserter(Env, S).process(/*SkipAnnotation=*/true);
3681  });
3682  }
3683 
3684  if (Style.RemoveBracesLLVM) {
3685  FormatStyle S = Expanded;
3686  S.RemoveBracesLLVM = true;
3687  Passes.emplace_back([&, S = std::move(S)](const Environment &Env) {
3688  return BracesRemover(Env, S).process(/*SkipAnnotation=*/true);
3689  });
3690  }
3691 
3692  if (Style.RemoveSemicolon) {
3693  FormatStyle S = Expanded;
3694  S.RemoveSemicolon = true;
3695  Passes.emplace_back([&, S = std::move(S)](const Environment &Env) {
3696  return SemiRemover(Env, S).process();
3697  });
3698  }
3699 
3700  if (Style.FixNamespaceComments) {
3701  Passes.emplace_back([&](const Environment &Env) {
3702  return NamespaceEndCommentsFixer(Env, Expanded).process();
3703  });
3704  }
3705 
3707  Passes.emplace_back([&](const Environment &Env) {
3708  return UsingDeclarationsSorter(Env, Expanded).process();
3709  });
3710  }
3711  }
3712 
3714  Passes.emplace_back([&](const Environment &Env) {
3715  return DefinitionBlockSeparator(Env, Expanded).process();
3716  });
3717  }
3718 
3719  if (Style.Language == FormatStyle::LK_ObjC &&
3720  !Style.ObjCPropertyAttributeOrder.empty()) {
3721  Passes.emplace_back([&](const Environment &Env) {
3722  return ObjCPropertyAttributeOrderFixer(Env, Expanded).process();
3723  });
3724  }
3725 
3726  if (Style.isJavaScript() &&
3728  Passes.emplace_back([&](const Environment &Env) {
3729  return JavaScriptRequoter(Env, Expanded).process(/*SkipAnnotation=*/true);
3730  });
3731  }
3732 
3733  Passes.emplace_back([&](const Environment &Env) {
3734  return Formatter(Env, Expanded, Status).process();
3735  });
3736 
3737  if (Style.isJavaScript() &&
3739  Passes.emplace_back([&](const Environment &Env) {
3740  return TrailingCommaInserter(Env, Expanded).process();
3741  });
3742  }
3743 
3744  std::optional<std::string> CurrentCode;
3745  tooling::Replacements Fixes;
3746  unsigned Penalty = 0;
3747  for (size_t I = 0, E = Passes.size(); I < E; ++I) {
3748  std::pair<tooling::Replacements, unsigned> PassFixes = Passes[I](*Env);
3749  auto NewCode = applyAllReplacements(
3750  CurrentCode ? StringRef(*CurrentCode) : Code, PassFixes.first);
3751  if (NewCode) {
3752  Fixes = Fixes.merge(PassFixes.first);
3753  Penalty += PassFixes.second;
3754  if (I + 1 < E) {
3755  CurrentCode = std::move(*NewCode);
3757  *CurrentCode, FileName,
3759  FirstStartColumn, NextStartColumn, LastStartColumn);
3760  if (!Env)
3761  return {};
3762  }
3763  }
3764  }
3765 
3767  // Don't make replacements that replace nothing. QualifierAlignment can
3768  // produce them if one of its early passes changes e.g. `const volatile` to
3769  // `volatile const` and then a later pass changes it back again.
3770  tooling::Replacements NonNoOpFixes;
3771  for (const tooling::Replacement &Fix : Fixes) {
3772  StringRef OriginalCode = Code.substr(Fix.getOffset(), Fix.getLength());
3773  if (OriginalCode != Fix.getReplacementText()) {
3774  auto Err = NonNoOpFixes.add(Fix);
3775  if (Err) {
3776  llvm::errs() << "Error adding replacements : "
3777  << toString(std::move(Err)) << "\n";
3778  }
3779  }
3780  }
3781  Fixes = std::move(NonNoOpFixes);
3782  }
3783 
3784  return {Fixes, Penalty};
3785 }
3786 } // namespace internal
3787 
3788 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
3789  ArrayRef<tooling::Range> Ranges,
3790  StringRef FileName,
3791  FormattingAttemptStatus *Status) {
3792  return internal::reformat(Style, Code, Ranges,
3793  /*FirstStartColumn=*/0,
3794  /*NextStartColumn=*/0,
3795  /*LastStartColumn=*/0, FileName, Status)
3796  .first;
3797 }
3798 
3799 tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
3800  ArrayRef<tooling::Range> Ranges,
3801  StringRef FileName) {
3802  // cleanups only apply to C++ (they mostly concern ctor commas etc.)
3803  if (Style.Language != FormatStyle::LK_Cpp)
3804  return tooling::Replacements();
3805  auto Env = Environment::make(Code, FileName, Ranges);
3806  if (!Env)
3807  return {};
3808  return Cleaner(*Env, Style).process().first;
3809 }
3810 
3811 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
3812  ArrayRef<tooling::Range> Ranges,
3813  StringRef FileName, bool *IncompleteFormat) {
3814  FormattingAttemptStatus Status;
3815  auto Result = reformat(Style, Code, Ranges, FileName, &Status);
3816  if (!Status.FormatComplete)
3817  *IncompleteFormat = true;
3818  return Result;
3819 }
3820 
3822  StringRef Code,
3823  ArrayRef<tooling::Range> Ranges,
3824  StringRef FileName) {
3825  auto Env = Environment::make(Code, FileName, Ranges);
3826  if (!Env)
3827  return {};
3828  return NamespaceEndCommentsFixer(*Env, Style).process().first;
3829 }
3830 
3832  StringRef Code,
3833  ArrayRef<tooling::Range> Ranges,
3834  StringRef FileName) {
3835  auto Env = Environment::make(Code, FileName, Ranges);
3836  if (!Env)
3837  return {};
3838  return UsingDeclarationsSorter(*Env, Style).process().first;
3839 }
3840 
3842  LangOptions LangOpts;
3843 
3844  FormatStyle::LanguageStandard LexingStd = Style.Standard;
3845  if (LexingStd == FormatStyle::LS_Auto)
3846  LexingStd = FormatStyle::LS_Latest;
3847  if (LexingStd == FormatStyle::LS_Latest)
3848  LexingStd = FormatStyle::LS_Cpp20;
3849  LangOpts.CPlusPlus = 1;
3850  LangOpts.CPlusPlus11 = LexingStd >= FormatStyle::LS_Cpp11;
3851  LangOpts.CPlusPlus14 = LexingStd >= FormatStyle::LS_Cpp14;
3852  LangOpts.CPlusPlus17 = LexingStd >= FormatStyle::LS_Cpp17;
3853  LangOpts.CPlusPlus20 = LexingStd >= FormatStyle::LS_Cpp20;
3854  LangOpts.Char8 = LexingStd >= FormatStyle::LS_Cpp20;
3855  // Turning on digraphs in standards before C++0x is error-prone, because e.g.
3856  // the sequence "<::" will be unconditionally treated as "[:".
3857  // Cf. Lexer::LexTokenInternal.
3858  LangOpts.Digraphs = LexingStd >= FormatStyle::LS_Cpp11;
3859 
3860  LangOpts.LineComment = 1;
3861  LangOpts.CXXOperatorNames = Style.isCpp();
3862  LangOpts.Bool = 1;
3863  LangOpts.ObjC = 1;
3864  LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
3865  LangOpts.DeclSpecKeyword = 1; // To get __declspec.
3866  LangOpts.C99 = 1; // To get kw_restrict for non-underscore-prefixed restrict.
3867  return LangOpts;
3868 }
3869 
3871  "Set coding style. <string> can be:\n"
3872  "1. A preset: LLVM, GNU, Google, Chromium, Microsoft,\n"
3873  " Mozilla, WebKit.\n"
3874  "2. 'file' to load style configuration from a\n"
3875  " .clang-format file in one of the parent directories\n"
3876  " of the source file (for stdin, see --assume-filename).\n"
3877  " If no .clang-format file is found, falls back to\n"
3878  " --fallback-style.\n"
3879  " --style=file is the default.\n"
3880  "3. 'file:<format_file_path>' to explicitly specify\n"
3881  " the configuration file.\n"
3882  "4. \"{key: value, ...}\" to set specific parameters, e.g.:\n"
3883  " --style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
3884 
3886  if (FileName.ends_with(".java"))
3887  return FormatStyle::LK_Java;
3888  if (FileName.ends_with_insensitive(".js") ||
3889  FileName.ends_with_insensitive(".mjs") ||
3890  FileName.ends_with_insensitive(".ts")) {
3891  return FormatStyle::LK_JavaScript; // (module) JavaScript or TypeScript.
3892  }
3893  if (FileName.ends_with(".m") || FileName.ends_with(".mm"))
3894  return FormatStyle::LK_ObjC;
3895  if (FileName.ends_with_insensitive(".proto") ||
3896  FileName.ends_with_insensitive(".protodevel")) {
3897  return FormatStyle::LK_Proto;
3898  }
3899  // txtpb is the canonical extension, and textproto is the legacy canonical
3900  // extension
3901  // https://protobuf.dev/reference/protobuf/textformat-spec/#text-format-files
3902  if (FileName.ends_with_insensitive(".txtpb") ||
3903  FileName.ends_with_insensitive(".textpb") ||
3904  FileName.ends_with_insensitive(".pb.txt") ||
3905  FileName.ends_with_insensitive(".textproto") ||
3906  FileName.ends_with_insensitive(".asciipb")) {
3908  }
3909  if (FileName.ends_with_insensitive(".td"))
3910  return FormatStyle::LK_TableGen;
3911  if (FileName.ends_with_insensitive(".cs"))
3912  return FormatStyle::LK_CSharp;
3913  if (FileName.ends_with_insensitive(".json"))
3914  return FormatStyle::LK_Json;
3915  if (FileName.ends_with_insensitive(".sv") ||
3916  FileName.ends_with_insensitive(".svh") ||
3917  FileName.ends_with_insensitive(".v") ||
3918  FileName.ends_with_insensitive(".vh")) {
3919  return FormatStyle::LK_Verilog;
3920  }
3921  return FormatStyle::LK_Cpp;
3922 }
3923 
3924 FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code) {
3925  const auto GuessedLanguage = getLanguageByFileName(FileName);
3926  if (GuessedLanguage == FormatStyle::LK_Cpp) {
3927  auto Extension = llvm::sys::path::extension(FileName);
3928  // If there's no file extension (or it's .h), we need to check the contents
3929  // of the code to see if it contains Objective-C.
3930  if (!Code.empty() && (Extension.empty() || Extension == ".h")) {
3931  auto NonEmptyFileName = FileName.empty() ? "guess.h" : FileName;
3932  Environment Env(Code, NonEmptyFileName, /*Ranges=*/{});
3933  ObjCHeaderStyleGuesser Guesser(Env, getLLVMStyle());
3934  Guesser.process();
3935  if (Guesser.isObjC())
3936  return FormatStyle::LK_ObjC;
3937  }
3938  }
3939  return GuessedLanguage;
3940 }
3941 
3942 // Update StyleOptionHelpDescription above when changing this.
3943 const char *DefaultFormatStyle = "file";
3944 
3945 const char *DefaultFallbackStyle = "LLVM";
3946 
3947 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
3948 loadAndParseConfigFile(StringRef ConfigFile, llvm::vfs::FileSystem *FS,
3949  FormatStyle *Style, bool AllowUnknownOptions) {
3950  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
3951  FS->getBufferForFile(ConfigFile.str());
3952  if (auto EC = Text.getError())
3953  return EC;
3954  if (auto EC = parseConfiguration(*Text.get(), Style, AllowUnknownOptions))
3955  return EC;
3956  return Text;
3957 }
3958 
3959 Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
3960  StringRef FallbackStyleName, StringRef Code,
3961  llvm::vfs::FileSystem *FS,
3962  bool AllowUnknownOptions) {
3964  FormatStyle FallbackStyle = getNoStyle();
3965  if (!getPredefinedStyle(FallbackStyleName, Style.Language, &FallbackStyle))
3966  return make_string_error("Invalid fallback style: " + FallbackStyleName);
3967 
3968  SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 1> ChildFormatTextToApply;
3969 
3970  if (StyleName.starts_with("{")) {
3971  // Parse YAML/JSON style from the command line.
3972  StringRef Source = "<command-line>";
3973  if (std::error_code ec =
3974  parseConfiguration(llvm::MemoryBufferRef(StyleName, Source), &Style,
3975  AllowUnknownOptions)) {
3976  return make_string_error("Error parsing -style: " + ec.message());
3977  }
3978 
3979  if (!Style.InheritsParentConfig)
3980  return Style;
3981 
3982  ChildFormatTextToApply.emplace_back(
3983  llvm::MemoryBuffer::getMemBuffer(StyleName, Source, false));
3984  }
3985 
3986  if (!FS)
3987  FS = llvm::vfs::getRealFileSystem().get();
3988  assert(FS);
3989 
3990  // User provided clang-format file using -style=file:path/to/format/file.
3991  if (!Style.InheritsParentConfig &&
3992  StyleName.starts_with_insensitive("file:")) {
3993  auto ConfigFile = StyleName.substr(5);
3994  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
3995  loadAndParseConfigFile(ConfigFile, FS, &Style, AllowUnknownOptions);
3996  if (auto EC = Text.getError()) {
3997  return make_string_error("Error reading " + ConfigFile + ": " +
3998  EC.message());
3999  }
4000 
4001  LLVM_DEBUG(llvm::dbgs()
4002  << "Using configuration file " << ConfigFile << "\n");
4003 
4004  if (!Style.InheritsParentConfig)
4005  return Style;
4006 
4007  // Search for parent configs starting from the parent directory of
4008  // ConfigFile.
4009  FileName = ConfigFile;
4010  ChildFormatTextToApply.emplace_back(std::move(*Text));
4011  }
4012 
4013  // If the style inherits the parent configuration it is a command line
4014  // configuration, which wants to inherit, so we have to skip the check of the
4015  // StyleName.
4016  if (!Style.InheritsParentConfig && !StyleName.equals_insensitive("file")) {
4017  if (!getPredefinedStyle(StyleName, Style.Language, &Style))
4018  return make_string_error("Invalid value for -style");
4019  if (!Style.InheritsParentConfig)
4020  return Style;
4021  }
4022 
4023  SmallString<128> Path(FileName);
4024  if (std::error_code EC = FS->makeAbsolute(Path))
4025  return make_string_error(EC.message());
4026 
4027  // Reset possible inheritance
4028  Style.InheritsParentConfig = false;
4029 
4030  auto dropDiagnosticHandler = [](const llvm::SMDiagnostic &, void *) {};
4031 
4032  auto applyChildFormatTexts = [&](FormatStyle *Style) {
4033  for (const auto &MemBuf : llvm::reverse(ChildFormatTextToApply)) {
4034  auto EC = parseConfiguration(*MemBuf, Style, AllowUnknownOptions,
4035  dropDiagnosticHandler);
4036  // It was already correctly parsed.
4037  assert(!EC);
4038  static_cast<void>(EC);
4039  }
4040  };
4041 
4042  // Look for .clang-format/_clang-format file in the file's parent directories.
4043  SmallVector<std::string, 2> FilesToLookFor;
4044  FilesToLookFor.push_back(".clang-format");
4045  FilesToLookFor.push_back("_clang-format");
4046 
4047  SmallString<128> UnsuitableConfigFiles;
4048  for (StringRef Directory = Path; !Directory.empty();
4049  Directory = llvm::sys::path::parent_path(Directory)) {
4050  auto Status = FS->status(Directory);
4051  if (!Status ||
4052  Status->getType() != llvm::sys::fs::file_type::directory_file) {
4053  continue;
4054  }
4055 
4056  for (const auto &F : FilesToLookFor) {
4057  SmallString<128> ConfigFile(Directory);
4058 
4059  llvm::sys::path::append(ConfigFile, F);
4060  LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
4061 
4062  Status = FS->status(ConfigFile);
4063  if (!Status ||
4064  Status->getType() != llvm::sys::fs::file_type::regular_file) {
4065  continue;
4066  }
4067 
4068  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
4069  loadAndParseConfigFile(ConfigFile, FS, &Style, AllowUnknownOptions);
4070  if (auto EC = Text.getError()) {
4071  if (EC != ParseError::Unsuitable) {
4072  return make_string_error("Error reading " + ConfigFile + ": " +
4073  EC.message());
4074  }
4075  if (!UnsuitableConfigFiles.empty())
4076  UnsuitableConfigFiles.append(", ");
4077  UnsuitableConfigFiles.append(ConfigFile);
4078  continue;
4079  }
4080 
4081  LLVM_DEBUG(llvm::dbgs()
4082  << "Using configuration file " << ConfigFile << "\n");
4083 
4084  if (!Style.InheritsParentConfig) {
4085  if (!ChildFormatTextToApply.empty()) {
4086  LLVM_DEBUG(llvm::dbgs() << "Applying child configurations\n");
4087  applyChildFormatTexts(&Style);
4088  }
4089  return Style;
4090  }
4091 
4092  LLVM_DEBUG(llvm::dbgs() << "Inherits parent configuration\n");
4093 
4094  // Reset inheritance of style
4095  Style.InheritsParentConfig = false;
4096 
4097  ChildFormatTextToApply.emplace_back(std::move(*Text));
4098 
4099  // Breaking out of the inner loop, since we don't want to parse
4100  // .clang-format AND _clang-format, if both exist. Then we continue the
4101  // outer loop (parent directories) in search for the parent
4102  // configuration.
4103  break;
4104  }
4105  }
4106 
4107  if (!UnsuitableConfigFiles.empty()) {
4108  return make_string_error("Configuration file(s) do(es) not support " +
4109  getLanguageName(Style.Language) + ": " +
4110  UnsuitableConfigFiles);
4111  }
4112 
4113  if (!ChildFormatTextToApply.empty()) {
4114  LLVM_DEBUG(llvm::dbgs()
4115  << "Applying child configurations on fallback style\n");
4116  applyChildFormatTexts(&FallbackStyle);
4117  }
4118 
4119  return FallbackStyle;
4120 }
4121 
4122 static bool isClangFormatOnOff(StringRef Comment, bool On) {
4123  if (Comment == (On ? "/* clang-format on */" : "/* clang-format off */"))
4124  return true;
4125 
4126  static const char ClangFormatOn[] = "// clang-format on";
4127  static const char ClangFormatOff[] = "// clang-format off";
4128  const unsigned Size = (On ? sizeof ClangFormatOn : sizeof ClangFormatOff) - 1;
4129 
4130  return Comment.starts_with(On ? ClangFormatOn : ClangFormatOff) &&
4131  (Comment.size() == Size || Comment[Size] == ':');
4132 }
4133 
4134 bool isClangFormatOn(StringRef Comment) {
4135  return isClangFormatOnOff(Comment, /*On=*/true);
4136 }
4137 
4138 bool isClangFormatOff(StringRef Comment) {
4139  return isClangFormatOnOff(Comment, /*On=*/false);
4140 }
4141 
4142 } // namespace format
4143 } // namespace clang
This file declares DefinitionBlockSeparator, a TokenAnalyzer that inserts or removes empty lines sepa...
StringRef Text
Definition: Format.cpp:2977
int Priority
Definition: Format.cpp:2980
SmallVector< StringRef > AssociatedCommentLines
Definition: Format.cpp:2987
const SourceManager & SM
Definition: Format.cpp:2825
unsigned Offset
Definition: Format.cpp:2978
int Category
Definition: Format.cpp:2979
bool IsStatic
Definition: Format.cpp:2988
StringRef Filename
Definition: Format.cpp:2976
StringRef Identifier
Definition: Format.cpp:2984
Various functions to configurably format source code.
const Environment & Env
Definition: HTMLLogger.cpp:148
This file declares IntegerLiteralSeparatorFixer that fixes C++ integer literal separators.
This file declares NamespaceEndCommentsFixer, a TokenAnalyzer that fixes namespace end comments.
This file declares ObjCPropertyAttributeOrderFixer, a TokenAnalyzer that adjusts the order of attribu...
This file declares QualifierAlignmentFixer, a TokenAnalyzer that enforces either east or west const d...
SourceRange Range
Definition: SemaObjC.cpp:754
This file implements a sorter for JavaScript ES6 imports.
SourceLocation End
ContinuationIndenter * Indenter
Implements a combinatorial exploration of all the different linebreaks unwrapped lines can be formatt...
This file declares UsingDeclarationsSorter, a TokenAnalyzer that sorts consecutive using declarations...
__DEVICE__ int min(int __a, int __b)
static CharSourceRange getCharRange(SourceRange R)
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:482
static std::unique_ptr< Environment > make(StringRef Code, StringRef FileName, ArrayRef< tooling::Range > Ranges, unsigned FirstStartColumn=0, unsigned NextStartColumn=0, unsigned LastStartColumn=0)
std::pair< tooling::Replacements, unsigned > process(const Environment &Env, const FormatStyle &Style)
static tok::TokenKind getTokenFromQualifier(const std::string &Qualifier)
const char * name() const noexcept override
Definition: Format.cpp:1244
std::string message(int EV) const override
Definition: Format.cpp:1248
std::pair< tooling::Replacements, unsigned > process(bool SkipAnnotation=false)
static bool inputUsesCRLF(StringRef Text, bool DefaultToCRLF)
Infers whether the input is using CRLF.
static const llvm::Regex IncludeRegex
This class manages priorities of C++ #include categories and calculates priorities for headers.
int getIncludePriority(StringRef IncludeName, bool CheckMainHeader) const
Returns the priority of the category which IncludeName belongs to.
int getSortIncludePriority(StringRef IncludeName, bool CheckMainHeader) const
A source range independent of the SourceManager.
Definition: Replacement.h:44
A text replacement.
Definition: Replacement.h:83
unsigned getLength() const
Definition: Replacement.h:122
StringRef getReplacementText() const
Definition: Replacement.h:123
unsigned getOffset() const
Definition: Replacement.h:121
Maintains a set of replacements that are conflict-free.
Definition: Replacement.h:212
std::vector< Range > getAffectedRanges() const
const_iterator begin() const
Definition: Replacement.h:281
llvm::Error add(const Replacement &R)
Adds a new replacement R to the current set of replacements.
Replacements merge(const Replacements &Replaces) const
Merges Replaces into the current replacements.
#define UINT_MAX
Definition: limits.h:64
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition: Types.cpp:218
std::pair< tooling::Replacements, unsigned > reformat(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, unsigned FirstStartColumn, unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName, FormattingAttemptStatus *Status)
Reformats the given Ranges in the code fragment Code.
Definition: Format.cpp:3602
const char * StyleOptionHelpDescription
Description to be used for help text for a llvm::cl option for specifying format style.
Definition: Format.cpp:3870
void addQualifierAlignmentFixerPasses(const FormatStyle &Style, SmallVectorImpl< AnalyzerPass > &Passes)
static void expandPresetsSpaceBeforeParens(FormatStyle &Expanded)
Definition: Format.cpp:1370
const char * DefaultFallbackStyle
The suggested predefined style to use as the fallback style in getStyle.
Definition: Format.cpp:3945
static bool affectsRange(ArrayRef< tooling::Range > Ranges, unsigned Start, unsigned End)
Definition: Format.cpp:2994
const char * getTokenTypeName(TokenType Type)
Determines the name of a token type.
Definition: FormatToken.cpp:24
FormatStyle getWebKitStyle()
Returns a format style complying with Webkit's style guide: http://www.webkit.org/coding/coding-style...
Definition: Format.cpp:1847
static Expected< tooling::Replacements > processReplacements(T ProcessFunc, StringRef Code, const tooling::Replacements &Replaces, const FormatStyle &Style)
Definition: Format.cpp:3456
bool isLikelyXml(StringRef Code)
Definition: Format.cpp:3432
static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName)
Definition: Format.cpp:3885
static unsigned findJavaImportGroup(const FormatStyle &Style, StringRef ImportIdentifier)
Definition: Format.cpp:3271
std::string replaceCRLF(const std::string &Code)
Definition: Format.cpp:3034
std::error_code make_error_code(ParseError e)
Definition: Format.cpp:1235
FormatStyle getClangFormatStyle()
Definition: Format.cpp:1915
FormatStyle getLLVMStyle(FormatStyle::LanguageKind Language=FormatStyle::LanguageKind::LK_Cpp)
Returns a format style complying with the LLVM coding standards: http://llvm.org/docs/CodingStandards...
Definition: Format.cpp:1402
FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language)
Returns a format style complying with one of Google's style guides: http://google-styleguide....
Definition: Format.cpp:1619
std::function< std::pair< tooling::Replacements, unsigned > const Environment &)> AnalyzerPass
std::string configurationAsText(const FormatStyle &Style)
Gets configuration in a YAML string.
Definition: Format.cpp:2063
FormatStyle getMicrosoftStyle(FormatStyle::LanguageKind Language)
Returns a format style complying with Microsoft style guide: https://docs.microsoft....
Definition: Format.cpp:1886
std::error_code parseConfiguration(llvm::MemoryBufferRef Config, FormatStyle *Style, bool AllowUnknownOptions=false, llvm::SourceMgr::DiagHandlerTy DiagHandler=nullptr, void *DiagHandlerCtx=nullptr)
Parse configuration from YAML-formatted text.
Definition: Format.cpp:1997
const std::error_category & getParseCategory()
Definition: Format.cpp:1231
tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Fix namespace end comments in the given Ranges in Code.
Definition: Format.cpp:3821
FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code)
Definition: Format.cpp:3924
bool isMpegTS(StringRef Code)
Definition: Format.cpp:3425
const char * DefaultFormatStyle
The suggested format style to use by default.
Definition: Format.cpp:3943
FormatStyle getGNUStyle()
Returns a format style complying with GNU Coding Standards: http://www.gnu.org/prep/standards/standar...
Definition: Format.cpp:1871
bool isClangFormatOff(StringRef Comment)
Definition: Format.cpp:4138
LangOptions getFormattingLangOpts(const FormatStyle &Style=getLLVMStyle())
Returns the LangOpts that the formatter expects you to set.
Definition: Format.cpp:3841
static bool isClangFormatOnOff(StringRef Comment, bool On)
Definition: Format.cpp:4122
tooling::Replacements sortJavaScriptImports(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName)
FormatStyle getMozillaStyle()
Returns a format style complying with Mozilla's style guide: https://firefox-source-docs....
Definition: Format.cpp:1821
bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language, FormatStyle *Style)
Gets a predefined style for the specified language by name.
Definition: Format.cpp:1936
Expected< tooling::Replacements > cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces, const FormatStyle &Style)
Returns the replacements corresponding to applying Replaces and cleaning up the code after that on su...
Definition: Format.cpp:3585
static void expandPresetsBraceWrapping(FormatStyle &Expanded)
Definition: Format.cpp:1270
Expected< FormatStyle > getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyle, StringRef Code="", llvm::vfs::FileSystem *FS=nullptr, bool AllowUnknownOptions=false)
Construct a FormatStyle based on StyleName.
Definition: Format.cpp:3959
static void sortJavaImports(const FormatStyle &Style, const SmallVectorImpl< JavaImportDirective > &Imports, ArrayRef< tooling::Range > Ranges, StringRef FileName, StringRef Code, tooling::Replacements &Replaces)
Definition: Format.cpp:3291
tooling::Replacements reformat(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>", FormattingAttemptStatus *Status=nullptr)
Reformats the given Ranges in Code.
Definition: Format.cpp:3788
bool isClangFormatOn(StringRef Comment)
Definition: Format.cpp:4134
tooling::Replacements sortUsingDeclarations(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Sort consecutive using declarations in the given Ranges in Code.
Definition: Format.cpp:3831
llvm::Error make_string_error(const Twine &Message)
Definition: Format.cpp:1239
ParseError validateQualifierOrder(FormatStyle *Style)
Definition: Format.cpp:1965
FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language)
Returns a format style complying with Chromium's style guide: http://www.chromium....
Definition: Format.cpp:1761
static void expandPresetsSpacesInParens(FormatStyle &Expanded)
Definition: Format.cpp:1394
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
Definition: Format.cpp:3799
Expected< tooling::Replacements > formatReplacements(StringRef Code, const tooling::Replacements &Replaces, const FormatStyle &Style)
Returns the replacements corresponding to applying and formatting Replaces on success; otheriwse,...
Definition: Format.cpp:3475
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > loadAndParseConfigFile(StringRef ConfigFile, llvm::vfs::FileSystem *FS, FormatStyle *Style, bool AllowUnknownOptions)
Definition: Format.cpp:3948
FormatStyle getNoStyle()
Returns style indicating formatting should be not applied at all.
Definition: Format.cpp:1928
tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName, unsigned *Cursor=nullptr)
Returns the replacements necessary to sort all #include blocks that are affected by Ranges.
Definition: Format.cpp:3434
static void sortCppIncludes(const FormatStyle &Style, const SmallVectorImpl< IncludeDirective > &Includes, ArrayRef< tooling::Range > Ranges, StringRef FileName, StringRef Code, tooling::Replacements &Replaces, unsigned *Cursor)
Definition: Format.cpp:3062
static std::pair< unsigned, unsigned > FindCursorIndex(const SmallVectorImpl< IncludeDirective > &Includes, const SmallVectorImpl< unsigned > &Indices, unsigned Cursor)
Definition: Format.cpp:3013
StringRef getLanguageName(FormatStyle::LanguageKind Language)
Definition: Format.h:5400
std::string toString(const til::SExpr *E)
bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite)
Apply all replacements in Replaces to the Rewriter Rewrite.
std::vector< Range > calculateRangesAfterReplacements(const Replacements &Replaces, const std::vector< Range > &Ranges)
Calculates the new ranges after Replaces are applied.
The JSON file list parser is used to communicate input to InstallAPI.
Language
The language for the input, used to select and validate the language standard and possible actions.
Definition: LangStandard.h:23
const FunctionProtoType * T
Diagnostic wrappers for TextAPI types for error reporting.
Definition: Dominators.h:30
Definition: Format.h:5433
bool AcrossEmptyLines
Whether to align across empty lines.
Definition: Format.h:202
bool PadOperators
Only for AlignConsecutiveAssignments.
Definition: Format.h:262
bool AlignFunctionPointers
Only for AlignConsecutiveDeclarations.
Definition: Format.h:243
bool Enabled
Whether aligning is enabled.
Definition: Format.h:185
bool AlignCompound
Only for AlignConsecutiveAssignments.
Definition: Format.h:227
bool AcrossComments
Whether to align across comments.
Definition: Format.h:215
bool SplitEmptyRecord
If false, empty record (e.g.
Definition: Format.h:1523
bool AfterClass
Wrap class definitions.
Definition: Format.h:1339
bool AfterStruct
Wrap struct definitions.
Definition: Format.h:1406
bool AfterUnion
Wrap union definitions.
Definition: Format.h:1420
bool AfterEnum
Wrap enum definitions.
Definition: Format.h:1354
bool AfterObjCDeclaration
Wrap ObjC definitions (interfaces, implementations...).
Definition: Format.h:1392
bool AfterNamespace
Wrap namespace definitions.
Definition: Format.h:1386
BraceWrappingAfterControlStatementStyle AfterControlStatement
Wrap control statements (if/for/while/switch/..).
Definition: Format.h:1342
bool AfterFunction
Wrap function definitions.
Definition: Format.h:1370
bool SplitEmptyFunction
If false, empty function body can be put on a single line.
Definition: Format.h:1511
bool AfterExternBlock
Wrap extern blocks.
Definition: Format.h:1434
std::optional< FormatStyle > Get(FormatStyle::LanguageKind Language) const
Definition: Format.cpp:2079
int8_t DecimalMinDigits
Format separators in decimal literals with a minimum number of digits.
Definition: Format.h:2991
int8_t Decimal
Format separators in decimal literals.
Definition: Format.h:2983
bool AfterControlStatements
If true, put space between control statement keywords (for/if/while...) and opening parentheses.
Definition: Format.h:4365
bool AfterForeachMacros
If true, put space between foreach macros and opening parentheses.
Definition: Format.h:4372
bool BeforeNonEmptyParentheses
If true, put a space before opening parentheses only if the parentheses are not empty.
Definition: Format.h:4436
bool AfterIfMacros
If true, put space between if macros and opening parentheses.
Definition: Format.h:4393
bool AfterPlacementOperator
If true, put a space between operator new/delete and opening parenthesis.
Definition: Format.h:4409
bool Other
Put a space in parentheses not covered by preceding options.
Definition: Format.h:4687
bool InEmptyParentheses
Put a space in parentheses only if the parentheses are empty i.e.
Definition: Format.h:4681
bool InCStyleCasts
Put a space in C style casts.
Definition: Format.h:4670
bool InConditionalStatements
Put a space in parentheses only inside conditional statements (for/if/while/switch....
Definition: Format.h:4664
TrailingCommentsAlignmentKinds Kind
Specifies the way to align trailing comments.
Definition: Format.h:585
unsigned OverEmptyLines
How many empty lines to apply alignment.
Definition: Format.h:608
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition: Format.h:55
@ UT_Never
Never use tab.
Definition: Format.h:4890
bool SpaceBeforeInheritanceColon
If false, spaces will be removed before inheritance colon.
Definition: Format.h:4276
unsigned ContinuationIndentWidth
Indent width for line continuations.
Definition: Format.h:2436
bool AlwaysBreakBeforeMultilineStrings
This option is renamed to BreakAfterReturnType.
Definition: Format.h:1104
LanguageStandard Standard
Parse and format C++ constructs compatible with this standard.
Definition: Format.h:4768
bool BreakAdjacentStringLiterals
Break between adjacent string literals.
Definition: Format.h:1564
ReturnTypeBreakingStyle BreakAfterReturnType
The function declaration return type breaking style to use.
Definition: Format.h:1655
LanguageKind
Supported languages.
Definition: Format.h:3152
@ LK_CSharp
Should be used for C#.
Definition: Format.h:3158
@ LK_None
Do not use.
Definition: Format.h:3154
@ LK_Java
Should be used for Java.
Definition: Format.h:3160
@ LK_Cpp
Should be used for C, C++.
Definition: Format.h:3156
@ LK_JavaScript
Should be used for JavaScript.
Definition: Format.h:3162
@ LK_ObjC
Should be used for Objective-C, Objective-C++.
Definition: Format.h:3166
@ LK_Verilog
Should be used for Verilog and SystemVerilog.
Definition: Format.h:3178
@ LK_TableGen
Should be used for TableGen code.
Definition: Format.h:3171
@ LK_Proto
Should be used for Protocol Buffers (https://developers.google.com/protocol-buffers/).
Definition: Format.h:3169
@ LK_Json
Should be used for JSON.
Definition: Format.h:3164
@ LK_TextProto
Should be used for Protocol Buffer messages in text format (https://developers.google....
Definition: Format.h:3174
bool Cpp11BracedListStyle
If true, format braced lists as best suited for C++11 braced lists.
Definition: Format.h:2459
SortIncludesOptions SortIncludes
Controls if and how clang-format will sort #includes.
Definition: Format.h:4103
BreakInheritanceListStyle BreakInheritanceList
The inheritance list style to use.
Definition: Format.h:2387
unsigned IndentWidth
The number of columns to use for indentation.
Definition: Format.h:2859
std::vector< std::string > AttributeMacros
This option is renamed to BreakTemplateDeclarations.
Definition: Format.h:1174
@ SLS_All
Merge all lambdas fitting on a single line.
Definition: Format.h:962
@ SLS_Empty
Only merge empty lambdas.
Definition: Format.h:948
@ SDS_Leave
Leave definition blocks as they are.
Definition: Format.h:3989
bool IndentRequiresClause
Indent the requires clause in a template.
Definition: Format.h:2845
SpacesInAnglesStyle SpacesInAngles
The SpacesInAnglesStyle to use for template argument lists.
Definition: Format.h:4551
bool IndentCaseLabels
Indent case labels one level from the switch statement.
Definition: Format.h:2731
std::vector< RawStringFormat > RawStringFormats
Defines hints for detecting supported languages code blocks in raw strings.
Definition: Format.h:3724
@ SJSIO_Before
Static imports are placed before non-static imports.
Definition: Format.h:4113
@ SJSIO_After
Static imports are placed after non-static imports.
Definition: Format.h:4120
PPDirectiveIndentStyle IndentPPDirectives
The preprocessor directive indenting style to use.
Definition: Format.h:2823
bool RemoveSemicolon
Remove semicolons after the closing braces of functions and constructors/destructors.
Definition: Format.h:3877
std::vector< std::string > Macros
A list of macros of the form <definition>=<expansion> .
Definition: Format.h:3281
bool SpaceBeforeJsonColon
If true, a space will be added before a JSON colon.
Definition: Format.h:4287
@ TCS_Wrapped
Insert trailing commas in container literals that were wrapped over multiple lines.
Definition: Format.h:2920
@ TCS_None
Do not insert trailing commas.
Definition: Format.h:2914
unsigned PenaltyBreakBeforeFirstCallParameter
The penalty for breaking a function call after call(.
Definition: Format.h:3517
bool SpaceBeforeCtorInitializerColon
If false, spaces will be removed before constructor initializer colon.
Definition: Format.h:4268
BinaryOperatorStyle BreakBeforeBinaryOperators
The way to wrap binary operators.
Definition: Format.h:1729
@ SI_Never
Includes are never sorted.
Definition: Format.h:4080
@ SI_CaseSensitive
Includes are sorted in an ASCIIbetical or case sensitive fashion.
Definition: Format.h:4089
@ SI_CaseInsensitive
Includes are sorted in an alphabetical or case insensitive fashion.
Definition: Format.h:4098
@ BPS_Never
Never bin-pack parameters.
Definition: Format.h:1684
@ BPS_Auto
Automatically determine parameter bin-packing behavior.
Definition: Format.h:1680
BitFieldColonSpacingStyle BitFieldColonSpacing
The BitFieldColonSpacingStyle to use for bitfields.
Definition: Format.h:1237
@ ELBAMS_LogicalBlock
Add empty line only when access modifier starts a new logical block.
Definition: Format.h:2565
unsigned SpacesBeforeTrailingComments
If true, spaces may be inserted into ().
Definition: Format.h:4528
@ BCIS_BeforeColon
Break constructor initializers before the colon and after the commas.
Definition: Format.h:2242
@ BCIS_BeforeComma
Break constructor initializers before the colon and commas, and align the commas with the colon.
Definition: Format.h:2250
@ IEBS_AfterExternBlock
Backwards compatible with AfterExternBlock's indenting.
Definition: Format.h:2769
bool IndentCaseBlocks
Indent case label blocks one level from the case label.
Definition: Format.h:2712
bool InsertBraces
Insert braces after control statements (if, else, for, do, and while) in C++ unless the control state...
Definition: Format.h:2905
BreakBeforeConceptDeclarationsStyle BreakBeforeConceptDeclarations
The concept declaration style to use.
Definition: Format.h:2188
BreakTemplateDeclarationsStyle BreakTemplateDeclarations
The template declaration breaking style to use.
Definition: Format.h:2391
bool DerivePointerAlignment
This option is deprecated.
Definition: Format.h:2472
@ BOS_All
Break before operators.
Definition: Format.h:1724
@ BOS_None
Break after operators.
Definition: Format.h:1700
@ BOS_NonAssignment
Break before operators that aren't assignments.
Definition: Format.h:1712
@ LE_DeriveLF
Use \n unless the input has more lines ending in \r\n.
Definition: Format.h:3201
@ LE_DeriveCRLF
Use \r\n unless the input has more lines ending in \n.
Definition: Format.h:3203
bool SpacesInSquareBrackets
If true, spaces will be inserted after [ and before ].
Definition: Format.h:4733
bool IndentWrappedFunctionNames
Indent if a function definition or declaration is wrapped after the type.
Definition: Format.h:2873
AlignConsecutiveStyle AlignConsecutiveTableGenBreakingDAGArgColons
Style of aligning consecutive TableGen DAGArg operator colons.
Definition: Format.h:449
bool FixNamespaceComments
If true, clang-format adds missing namespace end comments for namespaces and fixes invalid existing o...
Definition: Format.h:2621
bool ObjCSpaceBeforeProtocolList
Add a space in front of an Objective-C protocol list, i.e.
Definition: Format.h:3447
@ TCAS_Never
Don't align trailing comments but other formatter applies.
Definition: Format.h:579
@ TCAS_Always
Align trailing comments.
Definition: Format.h:570
RemoveParenthesesStyle RemoveParentheses
Remove redundant parentheses.
Definition: Format.h:3859
std::string MacroBlockBegin
A regular expression matching macros that start a block.
Definition: Format.h:3237
bool SpaceInEmptyBlock
If true, spaces will be inserted into {}.
Definition: Format.h:4502
LanguageKind Language
Language, this format style is targeted at.
Definition: Format.h:3192
@ SIPO_Custom
Configure each individual space in parentheses in SpacesInParensOptions.
Definition: Format.h:4632
@ SIPO_Never
Never put a space in parentheses.
Definition: Format.h:4629
bool RemoveBracesLLVM
Remove optional braces of control statements (if, else, for, and while) in C++ according to the LLVM ...
Definition: Format.h:3823
@ BAS_DontAlign
Don't align, instead use ContinuationIndentWidth, e.g.
Definition: Format.h:78
@ BAS_AlwaysBreak
Always break after an open bracket, if the parameters don't fit on a single line, e....
Definition: Format.h:85
@ BAS_Align
Align parameters on the open bracket, e.g.
Definition: Format.h:72
@ BBIAS_OnlyMultiline
Break before inline ASM colon if the line length is longer than column limit.
Definition: Format.h:2205
bool VerilogBreakBetweenInstancePorts
For Verilog, put each port on its own line in module instantiations.
Definition: Format.h:4920
unsigned TabWidth
The number of columns used for tab stops.
Definition: Format.h:4854
@ PPDIS_None
Does not indent any directives.
Definition: Format.h:2800
@ LBI_Signature
Align lambda body relative to the lambda signature.
Definition: Format.h:3122
std::vector< std::string > JavaImportGroups
A vector of prefixes ordered by the desired groups for Java imports.
Definition: Format.h:3052
bool AllowShortCaseLabelsOnASingleLine
If true, short case labels will be contracted to a single line.
Definition: Format.h:777
unsigned PenaltyBreakFirstLessLess
The penalty for breaking before the first <<.
Definition: Format.h:3525
std::vector< std::string > StatementAttributeLikeMacros
Macros which are ignored in front of a statement, as if they were an attribute.
Definition: Format.h:4785
unsigned ObjCBlockIndentWidth
The number of characters to use for indentation of ObjC blocks.
Definition: Format.h:3390
bool AllowShortLoopsOnASingleLine
If true, while (true) continue; can be put on a single line.
Definition: Format.h:973
int AccessModifierOffset
The extra indent or outdent of access modifiers, e.g.
Definition: Format.h:63
std::vector< std::string > QualifierOrder
The order in which the qualifiers appear.
Definition: Format.h:3664
bool AllowShortEnumsOnASingleLine
Allow short enums on a single line.
Definition: Format.h:810
@ SBS_Empty
Only merge empty blocks.
Definition: Format.h:738
@ SBS_Never
Never merge blocks into a single line.
Definition: Format.h:730
std::optional< FormatStyle > GetLanguageStyle(LanguageKind Language) const
Definition: Format.cpp:2104
std::vector< std::string > IfMacros
A vector of macros that should be interpreted as conditionals instead of as function calls.
Definition: Format.h:2662
NamespaceIndentationKind NamespaceIndentation
The indentation used for namespaces.
Definition: Format.h:3333
bool BreakArrays
If true, clang-format will always break after a Json array [ otherwise it will scan until the closing...
Definition: Format.h:1674
bool BreakAfterJavaFieldAnnotations
Break after each annotation on a field in Java files.
Definition: Format.h:2286
@ SIS_WithoutElse
Put short ifs on the same line only if there is no else statement.
Definition: Format.h:899
@ SIS_Never
Never put short ifs on the same line.
Definition: Format.h:883
std::optional< unsigned > BracedInitializerIndentWidth
The number of columns to use to indent the contents of braced init lists.
Definition: Format.h:1270
std::vector< std::string > ObjCPropertyAttributeOrder
The order in which ObjC property attributes should appear.
Definition: Format.h:3437
bool ExperimentalAutoDetectBinPacking
If true, clang-format detects whether function calls and definitions are formatted with one parameter...
Definition: Format.h:2605
bool ObjCBreakBeforeNestedBlockParam
Break parameters list into lines when there is nested block parameters in a function call.
Definition: Format.h:3414
OperandAlignmentStyle AlignOperands
If true, horizontally align operands of binary and ternary expressions.
Definition: Format.h:549
unsigned PenaltyBreakOpenParenthesis
The penalty for breaking after (.
Definition: Format.h:3529
@ BTDS_MultiLine
Force break after template declaration only when the following declaration spans multiple lines.
Definition: Format.h:1138
@ BTDS_Yes
Always break after template declaration.
Definition: Format.h:1149
bool AllowShortCompoundRequirementOnASingleLine
Allow short compound requirement on a single line.
Definition: Format.h:796
friend std::error_code parseConfiguration(llvm::MemoryBufferRef Config, FormatStyle *Style, bool AllowUnknownOptions, llvm::SourceMgr::DiagHandlerTy DiagHandler, void *DiagHandlerCtxt)
Parse configuration from YAML-formatted text.
Definition: Format.cpp:1997
SpacesInParensStyle SpacesInParens
If true, spaces will be inserted after ( and before ).
Definition: Format.h:4646
SpacesInParensCustom SpacesInParensOptions
Control of individual spaces in parentheses.
Definition: Format.h:4722
std::vector< std::string > ForEachMacros
A vector of macros that should be interpreted as foreach loops instead of as function calls.
Definition: Format.h:2639
ReferenceAlignmentStyle ReferenceAlignment
Reference alignment style (overrides PointerAlignment for references).
Definition: Format.h:3750
AlignConsecutiveStyle AlignConsecutiveTableGenDefinitionColons
Style of aligning consecutive TableGen definition colons.
Definition: Format.h:469
TrailingCommaStyle InsertTrailingCommas
If set to TCS_Wrapped will insert trailing commas in container literals (arrays and objects) that wra...
Definition: Format.h:2939
unsigned PenaltyBreakTemplateDeclaration
The penalty for breaking after template declaration.
Definition: Format.h:3541
SpaceBeforeParensCustom SpaceBeforeParensOptions
Control of individual space before parentheses.
Definition: Format.h:4474
BreakConstructorInitializersStyle BreakConstructorInitializers
The break constructor initializers style to use.
Definition: Format.h:2262
bool BreakStringLiterals
Allow breaking string literals when formatting.
Definition: Format.h:2329
bool SpaceAfterLogicalNot
If true, a space is inserted after the logical not operator (!).
Definition: Format.h:4187
@ SBPO_Custom
Configure each individual space before parentheses in SpaceBeforeParensOptions.
Definition: Format.h:4343
@ SBPO_NonEmptyParentheses
Put a space before opening parentheses only if the parentheses are not empty i.e.
Definition: Format.h:4328
@ SBPO_ControlStatementsExceptControlMacros
Same as SBPO_ControlStatements except this option doesn't apply to ForEach and If macros.
Definition: Format.h:4317
@ SBPO_ControlStatements
Put a space before opening parentheses only after control statement keywords (for/if/while....
Definition: Format.h:4304
@ SBPO_Always
Always put a space before opening parentheses, except when it's prohibited by the syntax rules (in fu...
Definition: Format.h:4340
@ PCIS_BinPack
Bin-pack constructor initializers.
Definition: Format.h:3464
@ PCIS_NextLine
Same as PCIS_CurrentLine except that if all constructor initializers do not fit on the current line,...
Definition: Format.h:3489
std::vector< std::string > TypeNames
A vector of non-keyword identifiers that should be interpreted as type names.
Definition: Format.h:4864
bool ObjCSpaceAfterProperty
Add a space after @property in Objective-C, i.e.
Definition: Format.h:3442
BraceBreakingStyle BreakBeforeBraces
The brace breaking style to use.
Definition: Format.h:2164
@ BILS_BeforeColon
Break inheritance list before the colon and after the commas.
Definition: Format.h:2358
@ BILS_BeforeComma
Break inheritance list before the colon and commas, and align the commas with the colon.
Definition: Format.h:2367
unsigned PenaltyExcessCharacter
The penalty for each character outside of the column limit.
Definition: Format.h:3545
std::vector< std::string > WhitespaceSensitiveMacros
A vector of macros which are whitespace-sensitive and should not be touched.
Definition: Format.h:4937
bool BinPackParameters
If false, a function declaration's or function definition's parameters will either all be on the same...
Definition: Format.h:1208
@ DAS_DontBreak
Never break inside DAGArg.
Definition: Format.h:4830
unsigned ConstructorInitializerIndentWidth
This option is deprecated.
Definition: Format.h:2425
@ BBNSS_Never
No line break allowed.
Definition: Format.h:689
bool CompactNamespaces
If true, consecutive namespace declarations will be on the same line.
Definition: Format.h:2415
@ RCPS_OwnLine
Always put the requires clause on its own line.
Definition: Format.h:3898
@ RCPS_WithPreceding
Try to put the clause together with the preceding part of a declaration.
Definition: Format.h:3915
@ RCPS_SingleLine
Try to put everything in the same line if possible.
Definition: Format.h:3953
LanguageStandard
Supported language standards for parsing and formatting C++ constructs.
Definition: Format.h:4743
@ LS_Cpp17
Parse and format as C++17.
Definition: Format.h:4752
@ LS_Latest
Parse and format using the latest supported language version.
Definition: Format.h:4757
@ LS_Cpp11
Parse and format as C++11.
Definition: Format.h:4748
@ LS_Auto
Automatic detection based on the input.
Definition: Format.h:4759
@ LS_Cpp03
Parse and format as C++03.
Definition: Format.h:4746
@ LS_Cpp14
Parse and format as C++14.
Definition: Format.h:4750
@ LS_Cpp20
Parse and format as C++20.
Definition: Format.h:4754
@ BWACS_Always
Always wrap braces after a control statement.
Definition: Format.h:1303
@ BWACS_Never
Never wrap braces after a control statement.
Definition: Format.h:1282
RequiresClausePositionStyle RequiresClausePosition
The position of the requires clause.
Definition: Format.h:3958
@ JSQS_Double
Always use double quotes.
Definition: Format.h:3074
@ JSQS_Single
Always use single quotes.
Definition: Format.h:3068
@ JSQS_Leave
Leave string quotes as they are.
Definition: Format.h:3062
bool SpaceAfterCStyleCast
If true, a space is inserted after C style casts.
Definition: Format.h:4179
AlignConsecutiveStyle AlignConsecutiveBitFields
Style of aligning consecutive bit fields.
Definition: Format.h:307
int PPIndentWidth
The number of columns to use for indentation of preprocessor statements.
Definition: Format.h:3592
AlignConsecutiveStyle AlignConsecutiveDeclarations
Style of aligning consecutive declarations.
Definition: Format.h:318
IntegerLiteralSeparatorStyle IntegerLiteralSeparator
Format integer literal separators (' for C++ and _ for C#, Java, and JavaScript).
Definition: Format.h:3018
SpaceAroundPointerQualifiersStyle SpaceAroundPointerQualifiers
Defines in which cases to put a space before or after pointer qualifiers.
Definition: Format.h:4228
DefinitionReturnTypeBreakingStyle AlwaysBreakAfterDefinitionReturnType
The function definition return type breaking style to use.
Definition: Format.h:1084
bool SpaceBeforeAssignmentOperators
If false, spaces will be removed before assignment operators.
Definition: Format.h:4237
BreakBeforeInlineASMColonStyle BreakBeforeInlineASMColon
The inline ASM colon style to use.
Definition: Format.h:2217
@ BS_Mozilla
Like Attach, but break before braces on enum, function, and record definitions.
Definition: Format.h:1877
@ BS_Whitesmiths
Like Allman but always indent braces and line up code with braces.
Definition: Format.h:2047
@ BS_Allman
Always break before braces.
Definition: Format.h:1987
@ BS_Stroustrup
Like Attach, but break before function definitions, catch, and else.
Definition: Format.h:1927
@ BS_Linux
Like Attach, but break before braces on function, namespace and class definitions.
Definition: Format.h:1827
@ BS_WebKit
Like Attach, but break before functions.
Definition: Format.h:2157
@ BS_Custom
Configure each individual brace in BraceWrapping.
Definition: Format.h:2159
@ BS_GNU
Always break before braces and add an extra level of indentation to braces of control statements,...
Definition: Format.h:2110
@ BS_Attach
Always attach braces to surrounding context.
Definition: Format.h:1777
@ ABS_Leave
Leave the line breaking after attributes as is.
Definition: Format.h:1621
bool BinPackArguments
If false, a function call's arguments will either be all on the same line or will have one line each.
Definition: Format.h:1193
ShortLambdaStyle AllowShortLambdasOnASingleLine
Dependent on the value, auto lambda []() { return 0; } can be put on a single line.
Definition: Format.h:968
unsigned PenaltyBreakScopeResolution
The penalty for breaking after ::.
Definition: Format.h:3533
unsigned PenaltyReturnTypeOnItsOwnLine
Penalty for putting the return type of a function onto its own line.
Definition: Format.h:3554
@ BFCS_Both
Add one space on each side of the :
Definition: Format.h:1216
PointerAlignmentStyle PointerAlignment
Pointer and reference alignment style.
Definition: Format.h:3577
@ SFS_Inline
Only merge functions defined inside a class.
Definition: Format.h:849
@ SFS_All
Merge all functions fitting on a single line.
Definition: Format.h:857
@ SFS_Empty
Only merge empty functions.
Definition: Format.h:838
@ SFS_None
Never merge functions into a single line.
Definition: Format.h:816
bool BreakFunctionDefinitionParameters
If true, clang-format will always break before function definition parameters.
Definition: Format.h:2276
@ REI_OuterScope
Align requires expression body relative to the indentation level of the outer scope the requires expr...
Definition: Format.h:3971
PackConstructorInitializersStyle PackConstructorInitializers
The pack constructor initializers style to use.
Definition: Format.h:3509
@ BBCDS_Always
Always break before concept, putting it in the line after the template declaration.
Definition: Format.h:2183
bool AllowAllParametersOfDeclarationOnNextLine
This option is deprecated.
Definition: Format.h:676
BracketAlignmentStyle AlignAfterOpenBracket
If true, horizontally aligns arguments after an open bracket.
Definition: Format.h:107
AlignConsecutiveStyle AlignConsecutiveTableGenCondOperatorColons
Style of aligning consecutive TableGen cond operator colons.
Definition: Format.h:459
bool AllowShortCaseExpressionOnASingleLine
Whether to merge a short switch labeled rule into a single line.
Definition: Format.h:763
bool ReflowComments
If true, clang-format will attempt to re-flow comments.
Definition: Format.h:3768
unsigned MaxEmptyLinesToKeep
The maximum number of consecutive empty lines to keep.
Definition: Format.h:3295
bool SpaceBeforeSquareBrackets
If true, spaces will be before [.
Definition: Format.h:4484
BinPackStyle ObjCBinPackProtocolList
Controls bin-packing Objective-C protocol conformance list items into as few lines as possible when t...
Definition: Format.h:3379
ShortCaseStatementsAlignmentStyle AlignConsecutiveShortCaseStatements
Style of aligning consecutive short case labels.
Definition: Format.h:434
EscapedNewlineAlignmentStyle AlignEscapedNewlines
Options for aligning backslashes in escaped newlines.
Definition: Format.h:510
SpacesInLineComment SpacesInLineCommentPrefix
How many spaces are allowed at the start of a line comment.
Definition: Format.h:4617
std::string CommentPragmas
A regular expression that describes comments with special meaning, which should not be split into lin...
Definition: Format.h:2347
bool isJavaScript() const
Definition: Format.h:3183
DAGArgStyle TableGenBreakInsideDAGArg
The styles of the line break inside the DAGArg in TableGen.
Definition: Format.h:4850
JavaScriptQuoteStyle JavaScriptQuotes
The JavaScriptQuoteStyle to use for JavaScript strings.
Definition: Format.h:3079
bool SpacesInContainerLiterals
If true, spaces will be inserted around if/for/switch/while conditions.
Definition: Format.h:4569
SortJavaStaticImportOptions SortJavaStaticImport
When sorting Java imports, by default static imports are placed before non-static imports.
Definition: Format.h:4127
@ SAPQ_Default
Don't ensure spaces around pointer qualifiers and use PointerAlignment instead.
Definition: Format.h:4205
bool SpaceBeforeRangeBasedForLoopColon
If false, spaces will be removed before range-based for loop colon.
Definition: Format.h:4493
bool DisableFormat
Disables formatting completely.
Definition: Format.h:2476
@ ELAAMS_Never
Remove all empty lines after access modifiers.
Definition: Format.h:2496
@ DRTBS_All
Always break after the return type.
Definition: Format.h:982
@ DRTBS_TopLevel
Always break after the return types of top-level functions.
Definition: Format.h:984
@ DRTBS_None
Break after return type automatically.
Definition: Format.h:980
std::vector< std::string > NamespaceMacros
A vector of macros which are used to open namespace blocks.
Definition: Format.h:3346
AttributeBreakingStyle BreakAfterAttributes
Break after a group of C++11 attributes before variable or function (including constructor/destructor...
Definition: Format.h:1651
TrailingCommentsAlignmentStyle AlignTrailingComments
Control of trailing comments.
Definition: Format.h:636
@ AIAS_None
Don't align array initializer columns.
Definition: Format.h:132
LambdaBodyIndentationKind LambdaBodyIndentation
The indentation style of lambda bodies.
Definition: Format.h:3145
QualifierAlignmentStyle QualifierAlignment
Different ways to arrange specifiers and qualifiers (e.g.
Definition: Format.h:3638
bool IndentGotoLabels
Indent goto labels.
Definition: Format.h:2748
BraceWrappingFlags BraceWrapping
Control of individual brace wrapping cases.
Definition: Format.h:1551
@ ENAS_Left
Align escaped newlines as far left as possible.
Definition: Format.h:488
@ ENAS_Right
Align escaped newlines in the right-most column.
Definition: Format.h:505
AlignConsecutiveStyle AlignConsecutiveMacros
Style of aligning consecutive macro definitions.
Definition: Format.h:286
std::vector< std::string > StatementMacros
A vector of macros that should be interpreted as complete statements.
Definition: Format.h:4796
@ SIAS_Never
Remove spaces after < and before >.
Definition: Format.h:4538
@ SUD_LexicographicNumeric
Using declarations are sorted in the order defined as follows: Split the strings by "::" and discard ...
Definition: Format.h:4166
@ SUD_Never
Using declarations are never sorted.
Definition: Format.h:4139
AlignConsecutiveStyle AlignConsecutiveAssignments
Style of aligning consecutive assignments.
Definition: Format.h:296
ShortIfStyle AllowShortIfStatementsOnASingleLine
Dependent on the value, if (a) return; can be put on a single line.
Definition: Format.h:934
@ RPS_Leave
Do not remove parentheses.
Definition: Format.h:3833
@ RPS_ReturnStatement
Also remove parentheses enclosing the expression in a return/co_return statement.
Definition: Format.h:3848
std::vector< std::string > TableGenBreakingDAGArgOperators
Works only when TableGenBreakInsideDAGArg is not DontBreak.
Definition: Format.h:4822
EmptyLineBeforeAccessModifierStyle EmptyLineBeforeAccessModifier
Defines in which cases to put empty line before access modifiers.
Definition: Format.h:2590
bool SpaceBeforeCaseColon
If false, spaces will be removed before case colon.
Definition: Format.h:4247
BreakBeforeNoexceptSpecifierStyle AllowBreakBeforeNoexceptSpecifier
Controls if there could be a line break before a noexcept specifier.
Definition: Format.h:717
bool JavaScriptWrapImports
Whether to wrap JavaScript import/export statements.
Definition: Format.h:3095
bool SkipMacroDefinitionBody
Do not format macro definition body.
Definition: Format.h:4068
unsigned PenaltyBreakAssignment
The penalty for breaking around an assignment operator.
Definition: Format.h:3513
@ PAS_Left
Align pointer to the left.
Definition: Format.h:3562
@ PAS_Right
Align pointer to the right.
Definition: Format.h:3567
unsigned PenaltyBreakString
The penalty for each line break introduced inside a string literal.
Definition: Format.h:3537
RequiresExpressionIndentationKind RequiresExpressionIndentation
The indentation used for requires expression bodies.
Definition: Format.h:3984
bool SpaceAfterTemplateKeyword
If true, a space will be inserted after the 'template' keyword.
Definition: Format.h:4195
unsigned PenaltyIndentedWhitespace
Penalty for each character of whitespace indentation (counted relative to leading non-whitespace colu...
Definition: Format.h:3550
ArrayInitializerAlignmentStyle AlignArrayOfStructures
if not None, when using initialization for an array of structs aligns the fields into columns.
Definition: Format.h:143
@ NI_None
Don't indent in namespaces.
Definition: Format.h:3308
@ NI_All
Indent in all namespaces.
Definition: Format.h:3328
@ NI_Inner
Indent only in inner namespaces (nested in other namespaces).
Definition: Format.h:3318
bool KeepEmptyLinesAtEOF
Keep empty lines (up to MaxEmptyLinesToKeep) at end of file.
Definition: Format.h:3100
ShortBlockStyle AllowShortBlocksOnASingleLine
Dependent on the value, while (true) { continue; } can be put on a single line.
Definition: Format.h:750
std::string MacroBlockEnd
A regular expression matching macros that end a block.
Definition: Format.h:3241
ShortFunctionStyle AllowShortFunctionsOnASingleLine
Dependent on the value, int f() { return 0; } can be put on a single line.
Definition: Format.h:863
bool AllowAllArgumentsOnNextLine
If a function call or braced initializer list doesn't fit on a line, allow putting all arguments onto...
Definition: Format.h:653
bool KeepEmptyLinesAtTheStartOfBlocks
If true, the empty line at the start of blocks is kept.
Definition: Format.h:3111
unsigned PenaltyBreakComment
The penalty for each line break introduced inside a comment.
Definition: Format.h:3521
@ RTBS_TopLevel
Always break after the return types of top-level functions.
Definition: Format.h:1047
@ RTBS_None
This is deprecated. See Automatic below.
Definition: Format.h:991
@ RTBS_AllDefinitions
Always break after the return type of function definitions.
Definition: Format.h:1064
@ RAS_Pointer
Align reference like PointerAlignment.
Definition: Format.h:3729
EmptyLineAfterAccessModifierStyle EmptyLineAfterAccessModifier
Defines when to put an empty line after access modifiers.
Definition: Format.h:2527
bool IndentAccessModifiers
Specify whether access modifiers should have their own indentation level.
Definition: Format.h:2689
bool InsertNewlineAtEOF
Insert a newline at end of file if missing.
Definition: Format.h:2909
SpaceBeforeParensStyle SpaceBeforeParens
Defines in which cases to put a space before opening parentheses.
Definition: Format.h:4348
bool SpaceBeforeCpp11BracedList
If true, a space will be inserted before a C++11 braced list used to initialize an object (after the ...
Definition: Format.h:4259
UseTabStyle UseTab
The way to use tab characters in the resulting file.
Definition: Format.h:4906
@ QAS_Leave
Don't change specifiers/qualifiers to either Left or Right alignment (default).
Definition: Format.h:3602
std::vector< std::string > TypenameMacros
A vector of macros that should be interpreted as type declarations instead of as function calls.
Definition: Format.h:4881
@ OAS_Align
Horizontally align operands of binary and ternary expressions.
Definition: Format.h:533
@ OAS_DontAlign
Do not align operands of binary and ternary expressions.
Definition: Format.h:517
LineEndingStyle LineEnding
Line ending style (\n or \r\n) to use.
Definition: Format.h:3208
bool BreakBeforeTernaryOperators
If true, ternary operators will be placed after line breaks.
Definition: Format.h:2232
unsigned ShortNamespaceLines
The maximal number of unwrapped lines that a short namespace spans.
Definition: Format.h:4064
SortUsingDeclarationsOptions SortUsingDeclarations
Controls if and how clang-format will sort using declarations.
Definition: Format.h:4171
IndentExternBlockStyle IndentExternBlock
IndentExternBlockStyle is the type of indenting of extern blocks.
Definition: Format.h:2788
SeparateDefinitionStyle SeparateDefinitionBlocks
Specifies the use of empty lines to separate definition blocks, including classes,...
Definition: Format.h:4042
tooling::IncludeStyle IncludeStyle
Definition: Format.h:2641
unsigned ColumnLimit
The column limit.
Definition: Format.h:2337
Represents the status of a formatting attempt.
Definition: Format.h:5270
MainIncludeCharDiscriminator MainIncludeChar
When guessing whether a #include is the "main" include, only the include directives that use the spec...
Definition: IncludeStyle.h:168
@ IBS_Preserve
Sort each #include block separately.
Definition: IncludeStyle.h:30
@ IBS_Regroup
Merge multiple #include blocks together and sort as one.
Definition: IncludeStyle.h:48
@ IBS_Merge
Merge multiple #include blocks together and sort as one.
Definition: IncludeStyle.h:38
std::string IncludeIsMainRegex
Specify a regular expression of suffixes that are allowed in the file-to-main-include mapping.
Definition: IncludeStyle.h:132
std::string IncludeIsMainSourceRegex
Specify a regular expression for files being formatted that are allowed to be considered "main" in th...
Definition: IncludeStyle.h:153
@ MICD_Quote
Main include uses quotes: #include "foo.hpp" (the default).
Definition: IncludeStyle.h:158
IncludeBlocksStyle IncludeBlocks
Dependent on the value, multiple #include blocks can be sorted as one and divided based on category.
Definition: IncludeStyle.h:54
std::vector< IncludeCategory > IncludeCategories
Regular expressions denoting the different #include categories used for ordering #includes.
Definition: IncludeStyle.h:118
static FormatStyle & element(IO &IO, std::vector< FormatStyle > &Seq, size_t Index)
Definition: Format.cpp:1209
static size_t size(IO &IO, std::vector< FormatStyle > &Seq)
Definition: Format.cpp:1206
static void mapping(IO &IO, FormatStyle &Style)
Definition: Format.cpp:800
static void enumInput(IO &IO, FormatStyle::AlignConsecutiveStyle &Value)
Definition: Format.cpp:46
static void mapping(IO &IO, FormatStyle::AlignConsecutiveStyle &Value)
Definition: Format.cpp:86
static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping)
Definition: Format.cpp:171
static void mapping(IO &IO, FormatStyle::IntegerLiteralSeparatorStyle &Base)
Definition: Format.cpp:354
static void mapping(IO &IO, FormatStyle::RawStringFormat &Format)
Definition: Format.cpp:491
static void mapping(IO &IO, FormatStyle::ShortCaseStatementsAlignmentStyle &Value)
Definition: Format.cpp:98
static void mapping(IO &IO, FormatStyle::SpaceBeforeParensCustom &Spacing)
Definition: Format.cpp:658
static void mapping(IO &IO, FormatStyle::SpacesInLineComment &Space)
Definition: Format.cpp:710
static void mapping(IO &IO, FormatStyle::SpacesInParensCustom &Spaces)
Definition: Format.cpp:723
static void mapping(IO &IO, FormatStyle::TrailingCommentsAlignmentStyle &Value)
Definition: Format.cpp:779
static void enumInput(IO &IO, FormatStyle::TrailingCommentsAlignmentStyle &Value)
Definition: Format.cpp:756
static void enumeration(IO &IO, FormatStyle::ArrayInitializerAlignmentStyle &Value)
Definition: Format.cpp:119
static void enumeration(IO &IO, FormatStyle::AttributeBreakingStyle &Value)
Definition: Format.cpp:110
static void enumeration(IO &IO, FormatStyle::BinPackStyle &Value)
Definition: Format.cpp:138
static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value)
Definition: Format.cpp:128
static void enumeration(IO &IO, FormatStyle::BitFieldColonSpacingStyle &Value)
Definition: Format.cpp:147
static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value)
Definition: Format.cpp:157
static void enumeration(IO &IO, FormatStyle::BraceWrappingAfterControlStatementStyle &Value)
Definition: Format.cpp:210
static void enumeration(IO &IO, FormatStyle::BracketAlignmentStyle &Value)
Definition: Format.cpp:194
static void enumeration(IO &IO, FormatStyle::BreakBeforeConceptDeclarationsStyle &Value)
Definition: Format.cpp:226
static void enumeration(IO &IO, FormatStyle::BreakBeforeInlineASMColonStyle &Value)
Definition: Format.cpp:239
static void enumeration(IO &IO, FormatStyle::BreakBeforeNoexceptSpecifierStyle &Value)
Definition: Format.cpp:38
static void enumeration(IO &IO, FormatStyle::BreakConstructorInitializersStyle &Value)
Definition: Format.cpp:250
static void enumeration(IO &IO, FormatStyle::BreakInheritanceListStyle &Value)
Definition: Format.cpp:259
static void enumeration(IO &IO, FormatStyle::BreakTemplateDeclarationsStyle &Value)
Definition: Format.cpp:270
static void enumeration(IO &IO, FormatStyle::DAGArgStyle &Value)
Definition: Format.cpp:284
static void enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value)
Definition: Format.cpp:294
static void enumeration(IO &IO, FormatStyle::EmptyLineAfterAccessModifierStyle &Value)
Definition: Format.cpp:323
static void enumeration(IO &IO, FormatStyle::EmptyLineBeforeAccessModifierStyle &Value)
Definition: Format.cpp:334
static void enumeration(IO &IO, FormatStyle::EscapedNewlineAlignmentStyle &Value)
Definition: Format.cpp:307
static void enumeration(IO &IO, FormatStyle::IndentExternBlockStyle &Value)
Definition: Format.cpp:344
static void enumeration(IO &IO, FormatStyle::JavaScriptQuoteStyle &Value)
Definition: Format.cpp:365
static void enumeration(IO &IO, FormatStyle::LambdaBodyIndentationKind &Value)
Definition: Format.cpp:408
static void enumeration(IO &IO, FormatStyle::LanguageKind &Value)
Definition: Format.cpp:373
static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value)
Definition: Format.cpp:388
static void enumeration(IO &IO, FormatStyle::LineEndingStyle &Value)
Definition: Format.cpp:416
static void enumeration(IO &IO, FormatStyle::NamespaceIndentationKind &Value)
Definition: Format.cpp:426
static void enumeration(IO &IO, FormatStyle::OperandAlignmentStyle &Value)
Definition: Format.cpp:435
static void enumeration(IO &IO, FormatStyle::PPDirectiveIndentStyle &Value)
Definition: Format.cpp:473
static void enumeration(IO &IO, FormatStyle::PackConstructorInitializersStyle &Value)
Definition: Format.cpp:450
static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value)
Definition: Format.cpp:460
static void enumeration(IO &IO, FormatStyle::QualifierAlignmentStyle &Value)
Definition: Format.cpp:482
static void enumeration(IO &IO, FormatStyle::ReferenceAlignmentStyle &Value)
Definition: Format.cpp:502
static void enumeration(IO &IO, FormatStyle::RemoveParenthesesStyle &Value)
Definition: Format.cpp:512
static void enumeration(IO &IO, FormatStyle::RequiresClausePositionStyle &Value)
Definition: Format.cpp:522
static void enumeration(IO &IO, FormatStyle::RequiresExpressionIndentationKind &Value)
Definition: Format.cpp:534
static void enumeration(IO &IO, FormatStyle::ReturnTypeBreakingStyle &Value)
Definition: Format.cpp:542
static void enumeration(IO &IO, FormatStyle::SeparateDefinitionStyle &Value)
Definition: Format.cpp:556
static void enumeration(IO &IO, FormatStyle::ShortBlockStyle &Value)
Definition: Format.cpp:564
static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value)
Definition: Format.cpp:574
static void enumeration(IO &IO, FormatStyle::ShortIfStyle &Value)
Definition: Format.cpp:586
static void enumeration(IO &IO, FormatStyle::ShortLambdaStyle &Value)
Definition: Format.cpp:600
static void enumeration(IO &IO, FormatStyle::SortIncludesOptions &Value)
Definition: Format.cpp:611
static void enumeration(IO &IO, FormatStyle::SortJavaStaticImportOptions &Value)
Definition: Format.cpp:624
static void enumeration(IO &IO, FormatStyle::SortUsingDeclarationsOptions &Value)
Definition: Format.cpp:633
static void enumeration(IO &IO, FormatStyle::SpaceAroundPointerQualifiersStyle &Value)
Definition: Format.cpp:649
static void enumeration(IO &IO, FormatStyle::SpaceBeforeParensStyle &Value)
Definition: Format.cpp:678
static void enumeration(IO &IO, FormatStyle::SpacesInAnglesStyle &Value)
Definition: Format.cpp:698
static void enumeration(IO &IO, FormatStyle::SpacesInParensStyle &Value)
Definition: Format.cpp:732
static void enumeration(IO &IO, FormatStyle::TrailingCommaStyle &Value)
Definition: Format.cpp:739
static void enumeration(IO &IO, FormatStyle::TrailingCommentsAlignmentKinds &Value)
Definition: Format.cpp:747
static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value)
Definition: Format.cpp:787