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