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