clang 24.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"
26#include "llvm/ADT/Sequence.h"
27#include "llvm/ADT/StringSet.h"
28#include "llvm/Support/FileSystem.h"
29#include "llvm/Support/VirtualFileSystem.h"
30#include <functional>
31#include <limits>
32
33#define DEBUG_TYPE "format-formatter"
34
36
37LLVM_YAML_IS_SEQUENCE_VECTOR(FormatStyle::RawStringFormat)
38LLVM_YAML_IS_SEQUENCE_VECTOR(FormatStyle::BinaryOperationBreakRule)
39LLVM_YAML_IS_SEQUENCE_VECTOR(clang::tok::TokenKind)
40
48
49namespace llvm {
50namespace yaml {
51template <>
52struct ScalarEnumerationTraits<FormatStyle::BreakBeforeNoexceptSpecifierStyle> {
53 static void
55 IO.enumCase(Value, "Never", FormatStyle::BBNSS_Never);
56 IO.enumCase(Value, "OnlyWithParen", FormatStyle::BBNSS_OnlyWithParen);
57 IO.enumCase(Value, "Always", FormatStyle::BBNSS_Always);
58 }
59};
60
61template <> struct MappingTraits<FormatStyle::AlignConsecutiveStyle> {
63 IO.enumCase(Value, "None", FormatStyle::AlignConsecutiveStyle{});
64 IO.enumCase(Value, "Consecutive",
66 {/*Enabled=*/true, /*AcrossEmptyLines=*/false,
67 /*AcrossComments=*/false, /*AlignCompound=*/false,
68 /*AlignFunctionDeclarations=*/true,
69 /*AlignFunctionPointers=*/false,
70 /*EnumAssignments=*/true, /*PadOperators=*/true}));
71 IO.enumCase(Value, "AcrossEmptyLines",
73 {/*Enabled=*/true, /*AcrossEmptyLines=*/true,
74 /*AcrossComments=*/false, /*AlignCompound=*/false,
75 /*AlignFunctionDeclarations=*/true,
76 /*AlignFunctionPointers=*/false,
77 /*EnumAssignments=*/true, /*PadOperators=*/true}));
78 IO.enumCase(Value, "AcrossComments",
80 {/*Enabled=*/true, /*AcrossEmptyLines=*/false,
81 /*AcrossComments=*/true, /*AlignCompound=*/false,
82 /*AlignFunctionDeclarations=*/true,
83 /*AlignFunctionPointers=*/false,
84 /*EnumAssignments=*/true, /*PadOperators=*/true}));
85 IO.enumCase(Value, "AcrossEmptyLinesAndComments",
87 {/*Enabled=*/true, /*AcrossEmptyLines=*/true,
88 /*AcrossComments=*/true, /*AlignCompound=*/false,
89 /*AlignFunctionDeclarations=*/true,
90 /*AlignFunctionPointers=*/false,
91 /*EnumAssignments=*/true, /*PadOperators=*/true}));
92
93 // For backward compatibility.
94 IO.enumCase(Value, "true",
96 {/*Enabled=*/true, /*AcrossEmptyLines=*/false,
97 /*AcrossComments=*/false, /*AlignCompound=*/false,
98 /*AlignFunctionDeclarations=*/true,
99 /*AlignFunctionPointers=*/false,
100 /*EnumAssignments=*/true, /*PadOperators=*/true}));
101 IO.enumCase(Value, "false", FormatStyle::AlignConsecutiveStyle{});
102 }
103
105 IO.mapOptional("Enabled", Value.Enabled);
106 IO.mapOptional("AcrossEmptyLines", Value.AcrossEmptyLines);
107 IO.mapOptional("AcrossComments", Value.AcrossComments);
108 IO.mapOptional("AlignCompound", Value.AlignCompound);
109 IO.mapOptional("AlignFunctionDeclarations",
110 Value.AlignFunctionDeclarations);
111 IO.mapOptional("AlignFunctionPointers", Value.AlignFunctionPointers);
112 IO.mapOptional("EnumAssignments", Value.EnumAssignments);
113 IO.mapOptional("PadOperators", Value.PadOperators);
114 }
115};
116
117template <>
118struct MappingTraits<FormatStyle::ShortCaseStatementsAlignmentStyle> {
119 static void mapping(IO &IO,
121 IO.mapOptional("Enabled", Value.Enabled);
122 IO.mapOptional("AcrossEmptyLines", Value.AcrossEmptyLines);
123 IO.mapOptional("AcrossComments", Value.AcrossComments);
124 IO.mapOptional("AlignCaseArrows", Value.AlignCaseArrows);
125 IO.mapOptional("AlignCaseColons", Value.AlignCaseColons);
126 }
127};
128
129template <>
130struct ScalarEnumerationTraits<FormatStyle::AttributeBreakingStyle> {
132 IO.enumCase(Value, "Always", FormatStyle::ABS_Always);
133 IO.enumCase(Value, "Leave", FormatStyle::ABS_Leave);
134 IO.enumCase(Value, "LeaveAll", FormatStyle::ABS_LeaveAll);
135 IO.enumCase(Value, "Never", FormatStyle::ABS_Never);
136 }
137};
138
139template <>
140struct ScalarEnumerationTraits<FormatStyle::ArrayInitializerAlignmentStyle> {
141 static void enumeration(IO &IO,
143 IO.enumCase(Value, "None", FormatStyle::AIAS_None);
144 IO.enumCase(Value, "Left", FormatStyle::AIAS_Left);
145 IO.enumCase(Value, "Right", FormatStyle::AIAS_Right);
146 }
147};
148
149template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
151 IO.enumCase(Value, "All", FormatStyle::BOS_All);
152 IO.enumCase(Value, "true", FormatStyle::BOS_All);
153 IO.enumCase(Value, "None", FormatStyle::BOS_None);
154 IO.enumCase(Value, "false", FormatStyle::BOS_None);
155 IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
156 }
157};
158
159template <> struct ScalarEnumerationTraits<FormatStyle::BinPackArgumentsStyle> {
161 IO.enumCase(Value, "BinPack", FormatStyle::BPAS_BinPack);
162 IO.enumCase(Value, "OnePerLine", FormatStyle::BPAS_OnePerLine);
163 IO.enumCase(Value, "UseBreakAfter", FormatStyle::BPAS_UseBreakAfter);
164
165 // For backward compatibility.
166 IO.enumCase(Value, "true", FormatStyle::BPAS_BinPack);
167 IO.enumCase(Value, "false", FormatStyle::BPAS_OnePerLine);
168 }
169};
170
171template <>
172struct ScalarEnumerationTraits<FormatStyle::BinPackParametersStyle> {
174 IO.enumCase(Value, "BinPack", FormatStyle::BPPS_BinPack);
175 IO.enumCase(Value, "OnePerLine", FormatStyle::BPPS_OnePerLine);
176 IO.enumCase(Value, "AlwaysOnePerLine", FormatStyle::BPPS_AlwaysOnePerLine);
177 IO.enumCase(Value, "UseBreakAfter", FormatStyle::BPPS_UseBreakAfter);
178
179 // For backward compatibility.
180 IO.enumCase(Value, "true", FormatStyle::BPPS_BinPack);
181 IO.enumCase(Value, "false", FormatStyle::BPPS_OnePerLine);
182 }
183};
184
185template <> struct ScalarEnumerationTraits<FormatStyle::BinPackStyle> {
187 IO.enumCase(Value, "Auto", FormatStyle::BPS_Auto);
188 IO.enumCase(Value, "Always", FormatStyle::BPS_Always);
189 IO.enumCase(Value, "Never", FormatStyle::BPS_Never);
190 }
191};
192
193template <>
194struct ScalarEnumerationTraits<FormatStyle::BitFieldColonSpacingStyle> {
195 static void enumeration(IO &IO,
197 IO.enumCase(Value, "Both", FormatStyle::BFCS_Both);
198 IO.enumCase(Value, "None", FormatStyle::BFCS_None);
199 IO.enumCase(Value, "Before", FormatStyle::BFCS_Before);
200 IO.enumCase(Value, "After", FormatStyle::BFCS_After);
201 }
202};
203
204template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
206 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
207 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
208 IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
209 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
210 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
211 IO.enumCase(Value, "Whitesmiths", FormatStyle::BS_Whitesmiths);
212 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
213 IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
214 IO.enumCase(Value, "Custom", FormatStyle::BS_Custom);
215 }
216};
217
218template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
219 static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
220 IO.mapOptional("AfterCaseLabel", Wrapping.AfterCaseLabel);
221 IO.mapOptional("AfterClass", Wrapping.AfterClass);
222 IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
223 IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
224 IO.mapOptional("AfterExportBlock", Wrapping.AfterExportBlock);
225 IO.mapOptional("AfterExternBlock", Wrapping.AfterExternBlock);
226 IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
227 IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
228 IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
229 IO.mapOptional("AfterRequiresExpression", Wrapping.AfterRequiresExpression);
230 IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
231 IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
232 IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
233 IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
234 IO.mapOptional("BeforeLambdaBody", Wrapping.BeforeLambdaBody);
235 IO.mapOptional("BeforeWhile", Wrapping.BeforeWhile);
236 IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
237 IO.mapOptional("SplitEmptyFunction", Wrapping.SplitEmptyFunction);
238 IO.mapOptional("SplitEmptyRecord", Wrapping.SplitEmptyRecord);
239 IO.mapOptional("SplitEmptyNamespace", Wrapping.SplitEmptyNamespace);
240 }
241};
242
243template <> struct ScalarEnumerationTraits<BracketAlignmentStyle> {
245 IO.enumCase(Value, "Align", BAS_Align);
246 IO.enumCase(Value, "DontAlign", BAS_DontAlign);
247
248 // For backward compatibility.
249 IO.enumCase(Value, "true", BAS_Align);
250 IO.enumCase(Value, "false", BAS_DontAlign);
251 IO.enumCase(Value, "AlwaysBreak", BAS_AlwaysBreak);
252 IO.enumCase(Value, "BlockIndent", BAS_BlockIndent);
253 }
254};
255
256template <>
257struct ScalarEnumerationTraits<
258 FormatStyle::BraceWrappingAfterControlStatementStyle> {
259 static void
262 IO.enumCase(Value, "Never", FormatStyle::BWACS_Never);
263 IO.enumCase(Value, "MultiLine", FormatStyle::BWACS_MultiLine);
264 IO.enumCase(Value, "Always", FormatStyle::BWACS_Always);
265
266 // For backward compatibility.
267 IO.enumCase(Value, "false", FormatStyle::BWACS_Never);
268 IO.enumCase(Value, "true", FormatStyle::BWACS_Always);
269 }
270};
271
272template <>
273struct ScalarEnumerationTraits<
274 FormatStyle::BreakBeforeConceptDeclarationsStyle> {
275 static void
277 IO.enumCase(Value, "Never", FormatStyle::BBCDS_Never);
278 IO.enumCase(Value, "Allowed", FormatStyle::BBCDS_Allowed);
279 IO.enumCase(Value, "Always", FormatStyle::BBCDS_Always);
280
281 // For backward compatibility.
282 IO.enumCase(Value, "true", FormatStyle::BBCDS_Always);
283 IO.enumCase(Value, "false", FormatStyle::BBCDS_Allowed);
284 }
285};
286
287template <>
288struct ScalarEnumerationTraits<FormatStyle::BreakBeforeInlineASMColonStyle> {
289 static void enumeration(IO &IO,
291 IO.enumCase(Value, "Never", FormatStyle::BBIAS_Never);
292 IO.enumCase(Value, "OnlyMultiline", FormatStyle::BBIAS_OnlyMultiline);
293 IO.enumCase(Value, "Always", FormatStyle::BBIAS_Always);
294 }
295};
296
297template <>
298struct ScalarEnumerationTraits<FormatStyle::BreakBinaryOperationsStyle> {
299 static void enumeration(IO &IO,
301 IO.enumCase(Value, "Never", FormatStyle::BBO_Never);
302 IO.enumCase(Value, "OnePerLine", FormatStyle::BBO_OnePerLine);
303 IO.enumCase(Value, "RespectPrecedence", FormatStyle::BBO_RespectPrecedence);
304 }
305};
306
307template <> struct ScalarTraits<clang::tok::TokenKind> {
308 static void output(const clang::tok::TokenKind &Value, void *,
309 llvm::raw_ostream &Out) {
310 if (const char *Spelling = clang::tok::getPunctuatorSpelling(Value))
311 Out << Spelling;
312 else
314 }
315
316 static StringRef input(StringRef Scalar, void *,
318 // Map operator spelling strings to tok::TokenKind.
319#define PUNCTUATOR(Name, Spelling) \
320 if (Scalar == Spelling) { \
321 Value = clang::tok::Name; \
322 return {}; \
323 }
324#include "clang/Basic/TokenKinds.def"
325 return "unknown operator";
326 }
327
328 static QuotingType mustQuote(StringRef) { return QuotingType::None; }
329};
330
331template <> struct MappingTraits<FormatStyle::BinaryOperationBreakRule> {
333 IO.mapOptional("Operators", Value.Operators);
334 // Default to OnePerLine since a per-operator rule with Never is a no-op.
335 if (!IO.outputting())
337 IO.mapOptional("Style", Value.Style);
338 IO.mapOptional("MinChainLength", Value.MinChainLength);
339 }
340};
341
342template <> struct MappingTraits<FormatStyle::BreakBinaryOperationsOptions> {
343 static void enumInput(IO &IO,
345 IO.enumCase(Value, "Never",
348 IO.enumCase(Value, "OnePerLine",
351 IO.enumCase(Value, "RespectPrecedence",
354 }
355
356 static void mapping(IO &IO,
358 IO.mapOptional("Default", Value.Default);
359 IO.mapOptional("PerOperator", Value.PerOperator);
360 }
361};
362
363template <>
364struct ScalarEnumerationTraits<FormatStyle::BreakConstructorInitializersStyle> {
365 static void
367 IO.enumCase(Value, "BeforeColon", FormatStyle::BCIS_BeforeColon);
368 IO.enumCase(Value, "BeforeComma", FormatStyle::BCIS_BeforeComma);
369 IO.enumCase(Value, "AfterColon", FormatStyle::BCIS_AfterColon);
370 IO.enumCase(Value, "AfterComma", FormatStyle::BCIS_AfterComma);
371 }
372};
373
374template <>
375struct ScalarEnumerationTraits<FormatStyle::BreakInheritanceListStyle> {
376 static void enumeration(IO &IO,
378 IO.enumCase(Value, "BeforeColon", FormatStyle::BILS_BeforeColon);
379 IO.enumCase(Value, "BeforeComma", FormatStyle::BILS_BeforeComma);
380 IO.enumCase(Value, "AfterColon", FormatStyle::BILS_AfterColon);
381 IO.enumCase(Value, "AfterComma", FormatStyle::BILS_AfterComma);
382 }
383};
384
385template <>
386struct ScalarEnumerationTraits<FormatStyle::BreakTemplateDeclarationsStyle> {
387 static void enumeration(IO &IO,
389 IO.enumCase(Value, "Leave", FormatStyle::BTDS_Leave);
390 IO.enumCase(Value, "No", FormatStyle::BTDS_No);
391 IO.enumCase(Value, "MultiLine", FormatStyle::BTDS_MultiLine);
392 IO.enumCase(Value, "Yes", FormatStyle::BTDS_Yes);
393
394 // For backward compatibility.
395 IO.enumCase(Value, "false", FormatStyle::BTDS_MultiLine);
396 IO.enumCase(Value, "true", FormatStyle::BTDS_Yes);
397 }
398};
399
400template <> struct ScalarEnumerationTraits<FormatStyle::BracedListStyle> {
402 IO.enumCase(Value, "Block", FormatStyle::BLS_Block);
403 IO.enumCase(Value, "FunctionCall", FormatStyle::BLS_FunctionCall);
404 IO.enumCase(Value, "AlignFirstComment", FormatStyle::BLS_AlignFirstComment);
405
406 // For backward compatibility.
407 IO.enumCase(Value, "false", FormatStyle::BLS_Block);
408 IO.enumCase(Value, "true", FormatStyle::BLS_AlignFirstComment);
409 }
410};
411
412template <> struct ScalarEnumerationTraits<FormatStyle::DAGArgStyle> {
414 IO.enumCase(Value, "DontBreak", FormatStyle::DAS_DontBreak);
415 IO.enumCase(Value, "BreakElements", FormatStyle::DAS_BreakElements);
416 IO.enumCase(Value, "BreakAll", FormatStyle::DAS_BreakAll);
417 }
418};
419
420template <>
421struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
422 static void
424 IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
425 IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
426 IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
427
428 // For backward compatibility.
429 IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
430 IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
431 }
432};
433
434template <>
435struct ScalarEnumerationTraits<FormatStyle::EscapedNewlineAlignmentStyle> {
436 static void enumeration(IO &IO,
438 IO.enumCase(Value, "DontAlign", FormatStyle::ENAS_DontAlign);
439 IO.enumCase(Value, "Left", FormatStyle::ENAS_Left);
440 IO.enumCase(Value, "LeftWithLastLine", FormatStyle::ENAS_LeftWithLastLine);
441 IO.enumCase(Value, "Right", FormatStyle::ENAS_Right);
442
443 // For backward compatibility.
444 IO.enumCase(Value, "true", FormatStyle::ENAS_Left);
445 IO.enumCase(Value, "false", FormatStyle::ENAS_Right);
446 }
447};
448
449template <>
450struct ScalarEnumerationTraits<FormatStyle::EmptyLineAfterAccessModifierStyle> {
451 static void
453 IO.enumCase(Value, "Never", FormatStyle::ELAAMS_Never);
454 IO.enumCase(Value, "Leave", FormatStyle::ELAAMS_Leave);
455 IO.enumCase(Value, "Always", FormatStyle::ELAAMS_Always);
456 }
457};
458
459template <>
460struct ScalarEnumerationTraits<
461 FormatStyle::EmptyLineBeforeAccessModifierStyle> {
462 static void
464 IO.enumCase(Value, "Never", FormatStyle::ELBAMS_Never);
465 IO.enumCase(Value, "Leave", FormatStyle::ELBAMS_Leave);
466 IO.enumCase(Value, "LogicalBlock", FormatStyle::ELBAMS_LogicalBlock);
467 IO.enumCase(Value, "Always", FormatStyle::ELBAMS_Always);
468 }
469};
470
471template <>
472struct ScalarEnumerationTraits<FormatStyle::EnumTrailingCommaStyle> {
474 IO.enumCase(Value, "Leave", FormatStyle::ETC_Leave);
475 IO.enumCase(Value, "Insert", FormatStyle::ETC_Insert);
476 IO.enumCase(Value, "Remove", FormatStyle::ETC_Remove);
477 }
478};
479
480template <>
481struct ScalarEnumerationTraits<FormatStyle::IndentAccessModifierStyle> {
482 static void enumeration(IO &IO,
484 IO.enumCase(Value, "Never", FormatStyle::IAMS_Never);
485 IO.enumCase(Value, "Always", FormatStyle::IAMS_Always);
486 IO.enumCase(Value, "AfterFirstAccessModifier",
488
489 // For backward compatibility.
490 IO.enumCase(Value, "false", FormatStyle::IAMS_Never);
491 IO.enumCase(Value, "true", FormatStyle::IAMS_Always);
492 }
493};
494
495template <>
496struct ScalarEnumerationTraits<FormatStyle::IndentExternBlockStyle> {
498 IO.enumCase(Value, "AfterExternBlock", FormatStyle::IEBS_AfterExternBlock);
499 IO.enumCase(Value, "Indent", FormatStyle::IEBS_Indent);
500 IO.enumCase(Value, "NoIndent", FormatStyle::IEBS_NoIndent);
501 IO.enumCase(Value, "true", FormatStyle::IEBS_Indent);
502 IO.enumCase(Value, "false", FormatStyle::IEBS_NoIndent);
503 }
504};
505
506template <> struct MappingTraits<FormatStyle::IntegerLiteralSeparatorStyle> {
508 IO.mapOptional("Binary", Base.Binary);
509 IO.mapOptional("BinaryMinDigitsInsert", Base.BinaryMinDigitsInsert);
510 IO.mapOptional("BinaryMaxDigitsRemove", Base.BinaryMaxDigitsRemove);
511 IO.mapOptional("Decimal", Base.Decimal);
512 IO.mapOptional("DecimalMinDigitsInsert", Base.DecimalMinDigitsInsert);
513 IO.mapOptional("DecimalMaxDigitsRemove", Base.DecimalMaxDigitsRemove);
514 IO.mapOptional("Hex", Base.Hex);
515 IO.mapOptional("HexMinDigitsInsert", Base.HexMinDigitsInsert);
516 IO.mapOptional("HexMaxDigitsRemove", Base.HexMaxDigitsRemove);
517
518 // For backward compatibility.
519 IO.mapOptional("BinaryMinDigits", Base.BinaryMinDigitsInsert);
520 IO.mapOptional("DecimalMinDigits", Base.DecimalMinDigitsInsert);
521 IO.mapOptional("HexMinDigits", Base.HexMinDigitsInsert);
522 }
523};
524
525template <> struct ScalarEnumerationTraits<FormatStyle::JavaScriptQuoteStyle> {
527 IO.enumCase(Value, "Leave", FormatStyle::JSQS_Leave);
528 IO.enumCase(Value, "Single", FormatStyle::JSQS_Single);
529 IO.enumCase(Value, "Double", FormatStyle::JSQS_Double);
530 }
531};
532
533template <> struct MappingTraits<FormatStyle::KeepEmptyLinesStyle> {
535 IO.mapOptional("AtEndOfBlock", Value.AtEndOfBlock);
536 IO.mapOptional("AtEndOfFile", Value.AtEndOfFile);
537 IO.mapOptional("AtStartOfBlock", Value.AtStartOfBlock);
538 IO.mapOptional("AtStartOfFile", Value.AtStartOfFile);
539 }
540};
541
542template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
544 IO.enumCase(Value, "C", FormatStyle::LK_C);
545 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
546 IO.enumCase(Value, "Java", FormatStyle::LK_Java);
547 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
548 IO.enumCase(Value, "ObjC", FormatStyle::LK_ObjC);
549 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
550 IO.enumCase(Value, "TableGen", FormatStyle::LK_TableGen);
551 IO.enumCase(Value, "TextProto", FormatStyle::LK_TextProto);
552 IO.enumCase(Value, "CSharp", FormatStyle::LK_CSharp);
553 IO.enumCase(Value, "Json", FormatStyle::LK_Json);
554 IO.enumCase(Value, "Verilog", FormatStyle::LK_Verilog);
555 }
556};
557
558template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
560 IO.enumCase(Value, "c++03", FormatStyle::LS_Cpp03);
561 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03); // Legacy alias
562 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03); // Legacy alias
563
564 IO.enumCase(Value, "c++11", FormatStyle::LS_Cpp11);
565 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11); // Legacy alias
566
567 IO.enumCase(Value, "c++14", FormatStyle::LS_Cpp14);
568 IO.enumCase(Value, "c++17", FormatStyle::LS_Cpp17);
569 IO.enumCase(Value, "c++20", FormatStyle::LS_Cpp20);
570 IO.enumCase(Value, "c++23", FormatStyle::LS_Cpp23);
571 IO.enumCase(Value, "c++26", FormatStyle::LS_Cpp26);
572
573 IO.enumCase(Value, "Latest", FormatStyle::LS_Latest);
574 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Latest); // Legacy alias
575 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
576 }
577};
578
579template <>
580struct ScalarEnumerationTraits<FormatStyle::LambdaBodyIndentationKind> {
581 static void enumeration(IO &IO,
583 IO.enumCase(Value, "Signature", FormatStyle::LBI_Signature);
584 IO.enumCase(Value, "OuterScope", FormatStyle::LBI_OuterScope);
585 }
586};
587
588template <> struct ScalarEnumerationTraits<FormatStyle::LineEndingStyle> {
590 IO.enumCase(Value, "LF", FormatStyle::LE_LF);
591 IO.enumCase(Value, "CRLF", FormatStyle::LE_CRLF);
592 IO.enumCase(Value, "DeriveLF", FormatStyle::LE_DeriveLF);
593 IO.enumCase(Value, "DeriveCRLF", FormatStyle::LE_DeriveCRLF);
594 }
595};
596
597template <>
598struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
599 static void enumeration(IO &IO,
601 IO.enumCase(Value, "None", FormatStyle::NI_None);
602 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
603 IO.enumCase(Value, "All", FormatStyle::NI_All);
604 }
605};
606
607template <>
608struct ScalarEnumerationTraits<FormatStyle::NumericLiteralComponentStyle> {
609 static void enumeration(IO &IO,
611 IO.enumCase(Value, "Leave", FormatStyle::NLCS_Leave);
612 IO.enumCase(Value, "Upper", FormatStyle::NLCS_Upper);
613 IO.enumCase(Value, "Lower", FormatStyle::NLCS_Lower);
614 }
615};
616
617template <> struct MappingTraits<FormatStyle::NumericLiteralCaseStyle> {
619 IO.mapOptional("ExponentLetter", Value.ExponentLetter);
620 IO.mapOptional("HexDigit", Value.HexDigit);
621 IO.mapOptional("Prefix", Value.Prefix);
622 IO.mapOptional("Suffix", Value.Suffix);
623 }
624};
625
626template <> struct ScalarEnumerationTraits<FormatStyle::OperandAlignmentStyle> {
628 IO.enumCase(Value, "DontAlign", FormatStyle::OAS_DontAlign);
629 IO.enumCase(Value, "Align", FormatStyle::OAS_Align);
630 IO.enumCase(Value, "AlignAfterOperator",
632
633 // For backward compatibility.
634 IO.enumCase(Value, "true", FormatStyle::OAS_Align);
635 IO.enumCase(Value, "false", FormatStyle::OAS_DontAlign);
636 }
637};
638
639template <> struct MappingTraits<FormatStyle::PackParametersStyle> {
641 IO.mapOptional("BinPack", Value.BinPack);
642 IO.mapOptional("BreakAfter", Value.BreakAfter);
643 }
644};
645
646template <>
647struct ScalarEnumerationTraits<FormatStyle::PackConstructorInitializersStyle> {
648 static void
650 IO.enumCase(Value, "Never", FormatStyle::PCIS_Never);
651 IO.enumCase(Value, "BinPack", FormatStyle::PCIS_BinPack);
652 IO.enumCase(Value, "CurrentLine", FormatStyle::PCIS_CurrentLine);
653 IO.enumCase(Value, "NextLine", FormatStyle::PCIS_NextLine);
654 IO.enumCase(Value, "NextLineOnly", FormatStyle::PCIS_NextLineOnly);
655 }
656};
657
658template <> struct MappingTraits<FormatStyle::PackArgumentsStyle> {
660 IO.mapOptional("BinPack", Value.BinPack);
661 IO.mapOptional("BreakAfter", Value.BreakAfter);
662 }
663};
664
665template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
667 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
668 IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
669 IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
670
671 // For backward compatibility.
672 IO.enumCase(Value, "true", FormatStyle::PAS_Left);
673 IO.enumCase(Value, "false", FormatStyle::PAS_Right);
674 }
675};
676
677template <>
678struct ScalarEnumerationTraits<FormatStyle::PPDirectiveIndentStyle> {
680 IO.enumCase(Value, "None", FormatStyle::PPDIS_None);
681 IO.enumCase(Value, "AfterHash", FormatStyle::PPDIS_AfterHash);
682 IO.enumCase(Value, "BeforeHash", FormatStyle::PPDIS_BeforeHash);
683 IO.enumCase(Value, "Leave", FormatStyle::PPDIS_Leave);
684 }
685};
686
687template <>
688struct ScalarEnumerationTraits<FormatStyle::QualifierAlignmentStyle> {
690 IO.enumCase(Value, "Leave", FormatStyle::QAS_Leave);
691 IO.enumCase(Value, "Left", FormatStyle::QAS_Left);
692 IO.enumCase(Value, "Right", FormatStyle::QAS_Right);
693 IO.enumCase(Value, "Custom", FormatStyle::QAS_Custom);
694 }
695};
696
697template <> struct MappingTraits<FormatStyle::RawStringFormat> {
698 static void mapping(IO &IO, FormatStyle::RawStringFormat &Format) {
699 IO.mapOptional("Language", Format.Language);
700 IO.mapOptional("Delimiters", Format.Delimiters);
701 IO.mapOptional("EnclosingFunctions", Format.EnclosingFunctions);
702 IO.mapOptional("CanonicalDelimiter", Format.CanonicalDelimiter);
703 IO.mapOptional("BasedOnStyle", Format.BasedOnStyle);
704 }
705};
706
707template <> struct ScalarEnumerationTraits<FormatStyle::ReflowCommentsStyle> {
709 IO.enumCase(Value, "Never", FormatStyle::RCS_Never);
710 IO.enumCase(Value, "IndentOnly", FormatStyle::RCS_IndentOnly);
711 IO.enumCase(Value, "Always", FormatStyle::RCS_Always);
712 // For backward compatibility:
713 IO.enumCase(Value, "false", FormatStyle::RCS_Never);
714 IO.enumCase(Value, "true", FormatStyle::RCS_Always);
715 }
716};
717
718template <>
719struct ScalarEnumerationTraits<FormatStyle::ReferenceAlignmentStyle> {
721 IO.enumCase(Value, "Pointer", FormatStyle::RAS_Pointer);
722 IO.enumCase(Value, "Middle", FormatStyle::RAS_Middle);
723 IO.enumCase(Value, "Left", FormatStyle::RAS_Left);
724 IO.enumCase(Value, "Right", FormatStyle::RAS_Right);
725 }
726};
727
728template <>
729struct ScalarEnumerationTraits<FormatStyle::RemoveParenthesesStyle> {
731 IO.enumCase(Value, "Leave", FormatStyle::RPS_Leave);
732 IO.enumCase(Value, "MultipleParentheses",
734 IO.enumCase(Value, "ReturnStatement", FormatStyle::RPS_ReturnStatement);
735 }
736};
737
738template <>
739struct ScalarEnumerationTraits<FormatStyle::RequiresClausePositionStyle> {
740 static void enumeration(IO &IO,
742 IO.enumCase(Value, "OwnLine", FormatStyle::RCPS_OwnLine);
743 IO.enumCase(Value, "OwnLineWithBrace", FormatStyle::RCPS_OwnLineWithBrace);
744 IO.enumCase(Value, "WithPreceding", FormatStyle::RCPS_WithPreceding);
745 IO.enumCase(Value, "WithFollowing", FormatStyle::RCPS_WithFollowing);
746 IO.enumCase(Value, "SingleLine", FormatStyle::RCPS_SingleLine);
747 }
748};
749
750template <>
751struct ScalarEnumerationTraits<FormatStyle::RequiresExpressionIndentationKind> {
752 static void
754 IO.enumCase(Value, "Keyword", FormatStyle::REI_Keyword);
755 IO.enumCase(Value, "OuterScope", FormatStyle::REI_OuterScope);
756 }
757};
758
759template <>
760struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
762 IO.enumCase(Value, "None", FormatStyle::RTBS_None);
763 IO.enumCase(Value, "Automatic", FormatStyle::RTBS_Automatic);
764 IO.enumCase(Value, "ExceptShortType", FormatStyle::RTBS_ExceptShortType);
765 IO.enumCase(Value, "All", FormatStyle::RTBS_All);
766 IO.enumCase(Value, "TopLevel", FormatStyle::RTBS_TopLevel);
767 IO.enumCase(Value, "TopLevelDefinitions",
769 IO.enumCase(Value, "AllDefinitions", FormatStyle::RTBS_AllDefinitions);
770 }
771};
772
773template <>
774struct ScalarEnumerationTraits<FormatStyle::BreakBeforeReturnTypeStyle> {
775 static void enumeration(IO &IO,
777 IO.enumCase(Value, "None", FormatStyle::BBRTS_None);
778 IO.enumCase(Value, "All", FormatStyle::BBRTS_All);
779 IO.enumCase(Value, "TopLevel", FormatStyle::BBRTS_TopLevel);
780 IO.enumCase(Value, "AllDefinitions", FormatStyle::BBRTS_AllDefinitions);
781 IO.enumCase(Value, "TopLevelDefinitions",
783 }
784};
785
786template <>
787struct ScalarEnumerationTraits<FormatStyle::SeparateDefinitionStyle> {
789 IO.enumCase(Value, "Leave", FormatStyle::SDS_Leave);
790 IO.enumCase(Value, "Always", FormatStyle::SDS_Always);
791 IO.enumCase(Value, "Never", FormatStyle::SDS_Never);
792 }
793};
794
795template <> struct ScalarEnumerationTraits<FormatStyle::ShortBlockStyle> {
797 IO.enumCase(Value, "Never", FormatStyle::SBS_Never);
798 IO.enumCase(Value, "false", FormatStyle::SBS_Never);
799 IO.enumCase(Value, "Always", FormatStyle::SBS_Always);
800 IO.enumCase(Value, "true", FormatStyle::SBS_Always);
801 IO.enumCase(Value, "Empty", FormatStyle::SBS_Empty);
802 }
803};
804
805template <> struct MappingTraits<FormatStyle::ShortFunctionStyle> {
807 IO.enumCase(Value, "None", FormatStyle::ShortFunctionStyle());
808 IO.enumCase(Value, "Empty",
810 IO.enumCase(Value, "Inline",
812 IO.enumCase(Value, "InlineOnly",
814 IO.enumCase(Value, "All", FormatStyle::ShortFunctionStyle::setAll());
815
816 // For backward compatibility.
817 IO.enumCase(Value, "true", FormatStyle::ShortFunctionStyle::setAll());
818 IO.enumCase(Value, "false", FormatStyle::ShortFunctionStyle());
819 }
820
822 IO.mapOptional("Empty", Value.Empty);
823 IO.mapOptional("Inline", Value.Inline);
824 IO.mapOptional("Other", Value.Other);
825 }
826};
827
828template <> struct ScalarEnumerationTraits<FormatStyle::ShortIfStyle> {
830 IO.enumCase(Value, "Never", FormatStyle::SIS_Never);
831 IO.enumCase(Value, "WithoutElse", FormatStyle::SIS_WithoutElse);
832 IO.enumCase(Value, "OnlyFirstIf", FormatStyle::SIS_OnlyFirstIf);
833 IO.enumCase(Value, "AllIfsAndElse", FormatStyle::SIS_AllIfsAndElse);
834
835 // For backward compatibility.
836 IO.enumCase(Value, "Always", FormatStyle::SIS_OnlyFirstIf);
837 IO.enumCase(Value, "false", FormatStyle::SIS_Never);
838 IO.enumCase(Value, "true", FormatStyle::SIS_WithoutElse);
839 }
840};
841
842template <> struct ScalarEnumerationTraits<FormatStyle::ShortLambdaStyle> {
844 IO.enumCase(Value, "None", FormatStyle::SLS_None);
845 IO.enumCase(Value, "false", FormatStyle::SLS_None);
846 IO.enumCase(Value, "Empty", FormatStyle::SLS_Empty);
847 IO.enumCase(Value, "Inline", FormatStyle::SLS_Inline);
848 IO.enumCase(Value, "All", FormatStyle::SLS_All);
849 IO.enumCase(Value, "true", FormatStyle::SLS_All);
850 }
851};
852
853template <> struct ScalarEnumerationTraits<FormatStyle::ShortRecordStyle> {
855 IO.enumCase(Value, "Never", FormatStyle::SRS_Never);
856 IO.enumCase(Value, "EmptyAndAttached", FormatStyle::SRS_EmptyAndAttached);
857 IO.enumCase(Value, "Empty", FormatStyle::SRS_Empty);
858 IO.enumCase(Value, "Always", FormatStyle::SRS_Always);
859 }
860};
861
862template <> struct MappingTraits<FormatStyle::SortIncludesOptions> {
864 IO.enumCase(Value, "Never", FormatStyle::SortIncludesOptions{});
865 IO.enumCase(Value, "CaseInsensitive",
866 FormatStyle::SortIncludesOptions{/*Enabled=*/true,
867 /*IgnoreCase=*/true,
868 /*IgnoreExtension=*/false,
869 /*Natural=*/false,
870 /*FilesBeforeFolders=*/false});
871 IO.enumCase(Value, "CaseSensitive",
872 FormatStyle::SortIncludesOptions{/*Enabled=*/true,
873 /*IgnoreCase=*/false,
874 /*IgnoreExtension=*/false,
875 /*Natural=*/false,
876 /*FilesBeforeFolders=*/false});
877 IO.enumCase(Value, "Natural",
878 FormatStyle::SortIncludesOptions{/*Enabled=*/true,
879 /*IgnoreCase=*/false,
880 /*IgnoreExtension=*/false,
881 /*Natural=*/true,
882 /*FilesBeforeFolders=*/false});
883
884 // For backward compatibility.
885 IO.enumCase(Value, "false", FormatStyle::SortIncludesOptions{});
886 IO.enumCase(Value, "true",
887 FormatStyle::SortIncludesOptions{/*Enabled=*/true,
888 /*IgnoreCase=*/false,
889 /*IgnoreExtension=*/false,
890 /*Natural=*/false,
891 /*FilesBeforeFolders=*/false});
892 }
894 IO.mapOptional("Enabled", Value.Enabled);
895 IO.mapOptional("IgnoreCase", Value.IgnoreCase);
896 IO.mapOptional("IgnoreExtension", Value.IgnoreExtension);
897 IO.mapOptional("Natural", Value.Natural);
898 IO.mapOptional("FilesBeforeFolders", Value.FilesBeforeFolders);
899 }
900};
901
902template <>
903struct ScalarEnumerationTraits<FormatStyle::SortJavaStaticImportOptions> {
904 static void enumeration(IO &IO,
906 IO.enumCase(Value, "Before", FormatStyle::SJSIO_Before);
907 IO.enumCase(Value, "After", FormatStyle::SJSIO_After);
908 }
909};
910
911template <>
912struct ScalarEnumerationTraits<FormatStyle::SortUsingDeclarationsOptions> {
913 static void enumeration(IO &IO,
915 IO.enumCase(Value, "Never", FormatStyle::SUD_Never);
916 IO.enumCase(Value, "Lexicographic", FormatStyle::SUD_Lexicographic);
917 IO.enumCase(Value, "LexicographicNumeric",
919
920 // For backward compatibility.
921 IO.enumCase(Value, "false", FormatStyle::SUD_Never);
922 IO.enumCase(Value, "true", FormatStyle::SUD_LexicographicNumeric);
923 }
924};
925
926template <>
927struct ScalarEnumerationTraits<FormatStyle::SpaceAroundPointerQualifiersStyle> {
928 static void
930 IO.enumCase(Value, "Default", FormatStyle::SAPQ_Default);
931 IO.enumCase(Value, "Before", FormatStyle::SAPQ_Before);
932 IO.enumCase(Value, "After", FormatStyle::SAPQ_After);
933 IO.enumCase(Value, "Both", FormatStyle::SAPQ_Both);
934 }
935};
936
937template <> struct MappingTraits<FormatStyle::SpaceBeforeParensCustom> {
938 static void mapping(IO &IO, FormatStyle::SpaceBeforeParensCustom &Spacing) {
939 IO.mapOptional("AfterControlStatements", Spacing.AfterControlStatements);
940 IO.mapOptional("AfterForeachMacros", Spacing.AfterForeachMacros);
941 IO.mapOptional("AfterFunctionDefinitionName",
943 IO.mapOptional("AfterFunctionDeclarationName",
945 IO.mapOptional("AfterIfMacros", Spacing.AfterIfMacros);
946 IO.mapOptional("AfterNot", Spacing.AfterNot);
947 IO.mapOptional("AfterOverloadedOperator", Spacing.AfterOverloadedOperator);
948 IO.mapOptional("AfterPlacementOperator", Spacing.AfterPlacementOperator);
949 IO.mapOptional("AfterRequiresInClause", Spacing.AfterRequiresInClause);
950 IO.mapOptional("AfterRequiresInExpression",
952 IO.mapOptional("BeforeNonEmptyParentheses",
954 }
955};
956
957template <>
958struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensStyle> {
960 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
961 IO.enumCase(Value, "ControlStatements",
963 IO.enumCase(Value, "ControlStatementsExceptControlMacros",
965 IO.enumCase(Value, "NonEmptyParentheses",
967 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
968 IO.enumCase(Value, "Custom", FormatStyle::SBPO_Custom);
969
970 // For backward compatibility.
971 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
972 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
973 IO.enumCase(Value, "ControlStatementsExceptForEachMacros",
975 }
976};
977
978template <>
979struct ScalarEnumerationTraits<FormatStyle::SpaceInEmptyBracesStyle> {
981 IO.enumCase(Value, "Always", FormatStyle::SIEB_Always);
982 IO.enumCase(Value, "Block", FormatStyle::SIEB_Block);
983 IO.enumCase(Value, "Never", FormatStyle::SIEB_Never);
984 }
985};
986
987template <> struct ScalarEnumerationTraits<FormatStyle::SpacesInAnglesStyle> {
989 IO.enumCase(Value, "Never", FormatStyle::SIAS_Never);
990 IO.enumCase(Value, "Always", FormatStyle::SIAS_Always);
991 IO.enumCase(Value, "Leave", FormatStyle::SIAS_Leave);
992
993 // For backward compatibility.
994 IO.enumCase(Value, "false", FormatStyle::SIAS_Never);
995 IO.enumCase(Value, "true", FormatStyle::SIAS_Always);
996 }
997};
998
999template <>
1000struct ScalarEnumerationTraits<FormatStyle::SpacesInBlockCommentsStyle> {
1001 static void enumeration(IO &IO,
1003 IO.enumCase(Value, "Never", FormatStyle::SIBCS_Never);
1004 IO.enumCase(Value, "Always", FormatStyle::SIBCS_Always);
1005 IO.enumCase(Value, "Leave", FormatStyle::SIBCS_Leave);
1006 }
1007};
1008
1009template <> struct MappingTraits<FormatStyle::SpacesInLineComment> {
1010 static void mapping(IO &IO, FormatStyle::SpacesInLineComment &Space) {
1011 // Transform the maximum to signed, to parse "-1" correctly
1012 int signedMaximum = static_cast<int>(Space.Maximum);
1013 IO.mapOptional("Minimum", Space.Minimum);
1014 IO.mapOptional("Maximum", signedMaximum);
1015 Space.Maximum = static_cast<unsigned>(signedMaximum);
1016
1017 if (Space.Maximum < std::numeric_limits<unsigned>::max())
1018 Space.Minimum = std::min(Space.Minimum, Space.Maximum);
1019 }
1020};
1021
1022template <> struct MappingTraits<FormatStyle::SpacesInParensCustom> {
1023 static void mapping(IO &IO, FormatStyle::SpacesInParensCustom &Spaces) {
1024 IO.mapOptional("ExceptDoubleParentheses", Spaces.ExceptDoubleParentheses);
1025 IO.mapOptional("InCStyleCasts", Spaces.InCStyleCasts);
1026 IO.mapOptional("InConditionalStatements", Spaces.InConditionalStatements);
1027 IO.mapOptional("InEmptyParentheses", Spaces.InEmptyParentheses);
1028 IO.mapOptional("Other", Spaces.Other);
1029 }
1030};
1031
1032template <> struct ScalarEnumerationTraits<FormatStyle::SpacesInParensStyle> {
1034 IO.enumCase(Value, "Never", FormatStyle::SIPO_Never);
1035 IO.enumCase(Value, "Custom", FormatStyle::SIPO_Custom);
1036 }
1037};
1038
1039template <> struct ScalarEnumerationTraits<FormatStyle::TrailingCommaStyle> {
1041 IO.enumCase(Value, "None", FormatStyle::TCS_None);
1042 IO.enumCase(Value, "Wrapped", FormatStyle::TCS_Wrapped);
1043 }
1044};
1045
1046template <>
1047struct ScalarEnumerationTraits<FormatStyle::TrailingCommentsAlignmentKinds> {
1048 static void enumeration(IO &IO,
1050 IO.enumCase(Value, "Leave", FormatStyle::TCAS_Leave);
1051 IO.enumCase(Value, "Always", FormatStyle::TCAS_Always);
1052 IO.enumCase(Value, "Never", FormatStyle::TCAS_Never);
1053 }
1054};
1055
1056template <> struct MappingTraits<FormatStyle::TrailingCommentsAlignmentStyle> {
1057 static void enumInput(IO &IO,
1059 IO.enumCase(Value, "Leave",
1061 {FormatStyle::TCAS_Leave, 0, true}));
1062
1063 IO.enumCase(Value, "Always",
1065 {FormatStyle::TCAS_Always, 0, true}));
1066
1067 IO.enumCase(Value, "Never",
1069 {FormatStyle::TCAS_Never, 0, true}));
1070
1071 // For backwards compatibility
1072 IO.enumCase(Value, "true",
1074 {FormatStyle::TCAS_Always, 0, true}));
1075 IO.enumCase(Value, "false",
1077 {FormatStyle::TCAS_Never, 0, true}));
1078 }
1079
1080 static void mapping(IO &IO,
1082 IO.mapOptional("AlignPPAndNotPP", Value.AlignPPAndNotPP);
1083 IO.mapOptional("Kind", Value.Kind);
1084 IO.mapOptional("OverEmptyLines", Value.OverEmptyLines);
1085 }
1086};
1087
1088template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
1090 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
1091 IO.enumCase(Value, "false", FormatStyle::UT_Never);
1092 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
1093 IO.enumCase(Value, "true", FormatStyle::UT_Always);
1094 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
1095 IO.enumCase(Value, "ForContinuationAndIndentation",
1097 IO.enumCase(Value, "AlignWithSpaces", FormatStyle::UT_AlignWithSpaces);
1098 }
1099};
1100
1101template <>
1102struct ScalarEnumerationTraits<
1103 FormatStyle::WrapNamespaceBodyWithEmptyLinesStyle> {
1104 static void
1107 IO.enumCase(Value, "Never", FormatStyle::WNBWELS_Never);
1108 IO.enumCase(Value, "Always", FormatStyle::WNBWELS_Always);
1109 IO.enumCase(Value, "Leave", FormatStyle::WNBWELS_Leave);
1110 }
1111};
1112
1113template <> struct MappingTraits<FormatStyle> {
1114 static void mapping(IO &IO, FormatStyle &Style) {
1115 // When reading, read the language first, we need it for getPredefinedStyle.
1116 IO.mapOptional("Language", Style.Language);
1117
1118 StringRef BasedOnStyle;
1119 if (IO.outputting()) {
1120 StringRef Styles[] = {"LLVM", "Google", "Chromium", "Mozilla",
1121 "WebKit", "GNU", "Microsoft", "clang-format"};
1122 for (StringRef StyleName : Styles) {
1123 FormatStyle PredefinedStyle;
1124 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
1125 Style == PredefinedStyle) {
1126 BasedOnStyle = StyleName;
1127 break;
1128 }
1129 }
1130 } else {
1131 IO.mapOptional("BasedOnStyle", BasedOnStyle);
1132 if (!BasedOnStyle.empty()) {
1133 FormatStyle::LanguageKind OldLanguage = Style.Language;
1134 FormatStyle::LanguageKind Language =
1135 ((FormatStyle *)IO.getContext())->Language;
1136 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
1137 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
1138 return;
1139 }
1140 Style.Language = OldLanguage;
1141 }
1142 }
1143
1144 // Initialize some variables used in the parsing. The using logic is at the
1145 // end.
1146
1147 // For backward compatibility:
1148 // The default value of ConstructorInitializerAllOnOneLineOrOnePerLine was
1149 // false unless BasedOnStyle was Google or Chromium whereas that of
1150 // AllowAllConstructorInitializersOnNextLine was always true, so the
1151 // equivalent default value of PackConstructorInitializers is PCIS_NextLine
1152 // for Google/Chromium or PCIS_BinPack otherwise. If the deprecated options
1153 // had a non-default value while PackConstructorInitializers has a default
1154 // value, set the latter to an equivalent non-default value if needed.
1155 const bool IsGoogleOrChromium = BasedOnStyle.equals_insensitive("google") ||
1156 BasedOnStyle.equals_insensitive("chromium");
1157 bool OnCurrentLine = IsGoogleOrChromium;
1158 bool OnNextLine = true;
1159
1160 bool BreakBeforeInheritanceComma = false;
1161 bool BreakConstructorInitializersBeforeComma = false;
1162
1163 bool DeriveLineEnding = true;
1164 bool UseCRLF = false;
1165
1166 bool SpaceInEmptyBlock = false;
1167 bool SpaceInEmptyParentheses = false;
1168 bool SpacesInConditionalStatement = false;
1169 bool SpacesInCStyleCastParentheses = false;
1170 bool SpacesInParentheses = false;
1171
1172 if (IO.outputting()) {
1173 IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
1174 } else {
1175 // For backward compatibility.
1177 if (IsGoogleOrChromium) {
1178 FormatStyle::LanguageKind Language = Style.Language;
1179 if (Language == FormatStyle::LK_None)
1180 Language = ((FormatStyle *)IO.getContext())->Language;
1181 if (Language == FormatStyle::LK_JavaScript)
1182 LocalBAS = BAS_AlwaysBreak;
1183 else if (Language == FormatStyle::LK_Java)
1184 LocalBAS = BAS_DontAlign;
1185 } else if (BasedOnStyle.equals_insensitive("webkit")) {
1186 LocalBAS = BAS_DontAlign;
1187 }
1188 IO.mapOptional("AlignAfterOpenBracket", LocalBAS);
1189
1190 switch (LocalBAS) {
1191 case BAS_DontAlign:
1192 Style.AlignAfterOpenBracket = false;
1193 Style.BreakAfterOpenBracketBracedList = false;
1194 Style.BreakAfterOpenBracketFunction = false;
1195 Style.BreakAfterOpenBracketIf = false;
1196 Style.BreakAfterOpenBracketLoop = false;
1197 Style.BreakAfterOpenBracketSwitch = false;
1198 Style.BreakBeforeCloseBracketBracedList = false;
1199 Style.BreakBeforeCloseBracketFunction = false;
1200 Style.BreakBeforeCloseBracketIf = false;
1201 Style.BreakBeforeCloseBracketLoop = false;
1202 Style.BreakBeforeCloseBracketSwitch = false;
1203 break;
1204 case BAS_BlockIndent:
1205 Style.AlignAfterOpenBracket = true;
1206 Style.BreakAfterOpenBracketBracedList = true;
1207 Style.BreakAfterOpenBracketFunction = true;
1208 Style.BreakAfterOpenBracketIf = true;
1209 Style.BreakAfterOpenBracketLoop = false;
1210 Style.BreakAfterOpenBracketSwitch = false;
1211 Style.BreakBeforeCloseBracketBracedList = true;
1212 Style.BreakBeforeCloseBracketFunction = true;
1213 Style.BreakBeforeCloseBracketIf = true;
1214 Style.BreakBeforeCloseBracketLoop = false;
1215 Style.BreakBeforeCloseBracketSwitch = false;
1216 break;
1217 case BAS_AlwaysBreak:
1218 Style.AlignAfterOpenBracket = true;
1219 Style.BreakAfterOpenBracketBracedList = true;
1220 Style.BreakAfterOpenBracketFunction = true;
1221 Style.BreakAfterOpenBracketIf = true;
1222 Style.BreakAfterOpenBracketLoop = false;
1223 Style.BreakAfterOpenBracketSwitch = false;
1224 Style.BreakBeforeCloseBracketBracedList = false;
1225 Style.BreakBeforeCloseBracketFunction = false;
1226 Style.BreakBeforeCloseBracketIf = false;
1227 Style.BreakBeforeCloseBracketLoop = false;
1228 Style.BreakBeforeCloseBracketSwitch = false;
1229 break;
1230 case BAS_Align:
1231 Style.AlignAfterOpenBracket = true;
1232 Style.BreakAfterOpenBracketBracedList = false;
1233 Style.BreakAfterOpenBracketFunction = false;
1234 Style.BreakAfterOpenBracketIf = false;
1235 Style.BreakAfterOpenBracketLoop = false;
1236 Style.BreakAfterOpenBracketSwitch = false;
1237 Style.BreakBeforeCloseBracketBracedList = false;
1238 Style.BreakBeforeCloseBracketFunction = false;
1239 Style.BreakBeforeCloseBracketIf = false;
1240 Style.BreakBeforeCloseBracketLoop = false;
1241 Style.BreakBeforeCloseBracketSwitch = false;
1242 break;
1243 case BAS_Ignore:
1244 break;
1245 }
1246 }
1247
1248 // For backward compatibility.
1249 if (!IO.outputting()) {
1250 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlines);
1251 IO.mapOptional("AllowAllConstructorInitializersOnNextLine", OnNextLine);
1252 IO.mapOptional("AlwaysBreakAfterReturnType", Style.BreakAfterReturnType);
1253 IO.mapOptional("AlwaysBreakTemplateDeclarations",
1254 Style.BreakTemplateDeclarations);
1255 IO.mapOptional("BinPackArguments", Style.PackArguments.BinPack);
1256 IO.mapOptional("BinPackParameters", Style.PackParameters.BinPack);
1257 IO.mapOptional("BreakBeforeInheritanceComma",
1258 BreakBeforeInheritanceComma);
1259 IO.mapOptional("BreakConstructorInitializersBeforeComma",
1260 BreakConstructorInitializersBeforeComma);
1261 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
1262 OnCurrentLine);
1263 IO.mapOptional("DeriveLineEnding", DeriveLineEnding);
1264 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
1265 IO.mapOptional("KeepEmptyLinesAtEOF", Style.KeepEmptyLines.AtEndOfFile);
1266 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
1267 Style.KeepEmptyLines.AtStartOfBlock);
1268 IO.mapOptional("IndentFunctionDeclarationAfterType",
1269 Style.IndentWrappedFunctionNames);
1270 IO.mapOptional("IndentRequires", Style.IndentRequiresClause);
1271 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
1272 IO.mapOptional("SpaceAfterControlStatementKeyword",
1273 Style.SpaceBeforeParens);
1274 IO.mapOptional("SpaceInEmptyBlock", SpaceInEmptyBlock);
1275 IO.mapOptional("SpaceInEmptyParentheses", SpaceInEmptyParentheses);
1276 IO.mapOptional("SpacesInConditionalStatement",
1277 SpacesInConditionalStatement);
1278 IO.mapOptional("SpacesInCStyleCastParentheses",
1279 SpacesInCStyleCastParentheses);
1280 IO.mapOptional("SpacesInParentheses", SpacesInParentheses);
1281 IO.mapOptional("UseCRLF", UseCRLF);
1282 }
1283
1284 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
1285 IO.mapOptional("AlignArrayOfStructures", Style.AlignArrayOfStructures);
1286 IO.mapOptional("AlignConsecutiveAssignments",
1287 Style.AlignConsecutiveAssignments);
1288 IO.mapOptional("AlignConsecutiveBitFields",
1289 Style.AlignConsecutiveBitFields);
1290 IO.mapOptional("AlignConsecutiveDeclarations",
1291 Style.AlignConsecutiveDeclarations);
1292 IO.mapOptional("AlignConsecutiveMacros", Style.AlignConsecutiveMacros);
1293 IO.mapOptional("AlignConsecutiveShortCaseStatements",
1294 Style.AlignConsecutiveShortCaseStatements);
1295 IO.mapOptional("AlignConsecutiveTableGenBreakingDAGArgColons",
1296 Style.AlignConsecutiveTableGenBreakingDAGArgColons);
1297 IO.mapOptional("AlignConsecutiveTableGenCondOperatorColons",
1298 Style.AlignConsecutiveTableGenCondOperatorColons);
1299 IO.mapOptional("AlignConsecutiveTableGenDefinitionColons",
1300 Style.AlignConsecutiveTableGenDefinitionColons);
1301 IO.mapOptional("AlignEscapedNewlines", Style.AlignEscapedNewlines);
1302 IO.mapOptional("AlignOperands", Style.AlignOperands);
1303 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
1304 IO.mapOptional("AllowAllArgumentsOnNextLine",
1305 Style.AllowAllArgumentsOnNextLine);
1306 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
1307 Style.AllowAllParametersOfDeclarationOnNextLine);
1308 IO.mapOptional("AllowBreakBeforeNoexceptSpecifier",
1309 Style.AllowBreakBeforeNoexceptSpecifier);
1310 IO.mapOptional("AllowBreakBeforeQtProperty",
1311 Style.AllowBreakBeforeQtProperty);
1312 IO.mapOptional("AllowShortBlocksOnASingleLine",
1313 Style.AllowShortBlocksOnASingleLine);
1314 IO.mapOptional("AllowShortCaseExpressionOnASingleLine",
1315 Style.AllowShortCaseExpressionOnASingleLine);
1316 IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
1317 Style.AllowShortCaseLabelsOnASingleLine);
1318 IO.mapOptional("AllowShortCompoundRequirementOnASingleLine",
1319 Style.AllowShortCompoundRequirementOnASingleLine);
1320 IO.mapOptional("AllowShortEnumsOnASingleLine",
1321 Style.AllowShortEnumsOnASingleLine);
1322 IO.mapOptional("AllowShortFunctionsOnASingleLine",
1323 Style.AllowShortFunctionsOnASingleLine);
1324 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
1325 Style.AllowShortIfStatementsOnASingleLine);
1326 IO.mapOptional("AllowShortLambdasOnASingleLine",
1327 Style.AllowShortLambdasOnASingleLine);
1328 IO.mapOptional("AllowShortLoopsOnASingleLine",
1329 Style.AllowShortLoopsOnASingleLine);
1330 IO.mapOptional("AllowShortNamespacesOnASingleLine",
1331 Style.AllowShortNamespacesOnASingleLine);
1332 IO.mapOptional("AllowShortRecordOnASingleLine",
1333 Style.AllowShortRecordOnASingleLine);
1334 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
1335 Style.AlwaysBreakAfterDefinitionReturnType);
1336 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
1337 Style.AlwaysBreakBeforeMultilineStrings);
1338 IO.mapOptional("AttributeMacros", Style.AttributeMacros);
1339 IO.mapOptional("BinPackLongBracedList", Style.BinPackLongBracedList);
1340 IO.mapOptional("BitFieldColonSpacing", Style.BitFieldColonSpacing);
1341 IO.mapOptional("BracedInitializerIndentWidth",
1342 Style.BracedInitializerIndentWidth);
1343 IO.mapOptional("BraceWrapping", Style.BraceWrapping);
1344 IO.mapOptional("BreakAdjacentStringLiterals",
1345 Style.BreakAdjacentStringLiterals);
1346 IO.mapOptional("BreakAfterAttributes", Style.BreakAfterAttributes);
1347 IO.mapOptional("BreakAfterJavaFieldAnnotations",
1348 Style.BreakAfterJavaFieldAnnotations);
1349 IO.mapOptional("BreakAfterOpenBracketBracedList",
1350 Style.BreakAfterOpenBracketBracedList);
1351 IO.mapOptional("BreakAfterOpenBracketFunction",
1352 Style.BreakAfterOpenBracketFunction);
1353 IO.mapOptional("BreakAfterOpenBracketIf", Style.BreakAfterOpenBracketIf);
1354 IO.mapOptional("BreakAfterOpenBracketLoop",
1355 Style.BreakAfterOpenBracketLoop);
1356 IO.mapOptional("BreakAfterOpenBracketSwitch",
1357 Style.BreakAfterOpenBracketSwitch);
1358 IO.mapOptional("BreakAfterReturnType", Style.BreakAfterReturnType);
1359 IO.mapOptional("BreakArrays", Style.BreakArrays);
1360 IO.mapOptional("BreakBeforeBinaryOperators",
1361 Style.BreakBeforeBinaryOperators);
1362 IO.mapOptional("BreakBeforeCloseBracketBracedList",
1363 Style.BreakBeforeCloseBracketBracedList);
1364 IO.mapOptional("BreakBeforeCloseBracketFunction",
1365 Style.BreakBeforeCloseBracketFunction);
1366 IO.mapOptional("BreakBeforeCloseBracketIf",
1367 Style.BreakBeforeCloseBracketIf);
1368 IO.mapOptional("BreakBeforeCloseBracketLoop",
1369 Style.BreakBeforeCloseBracketLoop);
1370 IO.mapOptional("BreakBeforeCloseBracketSwitch",
1371 Style.BreakBeforeCloseBracketSwitch);
1372 IO.mapOptional("BreakBeforeConceptDeclarations",
1373 Style.BreakBeforeConceptDeclarations);
1374 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
1375 IO.mapOptional("BreakBeforeInlineASMColon",
1376 Style.BreakBeforeInlineASMColon);
1377 IO.mapOptional("BreakBeforeReturnType", Style.BreakBeforeReturnType);
1378 IO.mapOptional("BreakBeforeTemplateCloser",
1379 Style.BreakBeforeTemplateCloser);
1380 IO.mapOptional("BreakBeforeTernaryOperators",
1381 Style.BreakBeforeTernaryOperators);
1382 IO.mapOptional("BreakBinaryOperations", Style.BreakBinaryOperations);
1383 IO.mapOptional("BreakConstructorInitializers",
1384 Style.BreakConstructorInitializers);
1385 IO.mapOptional("BreakFunctionDeclarationParameters",
1386 Style.BreakFunctionDeclarationParameters);
1387 IO.mapOptional("BreakFunctionDefinitionParameters",
1388 Style.BreakFunctionDefinitionParameters);
1389 IO.mapOptional("BreakInheritanceList", Style.BreakInheritanceList);
1390 IO.mapOptional("BreakStringLiterals", Style.BreakStringLiterals);
1391 IO.mapOptional("BreakTemplateDeclarations",
1392 Style.BreakTemplateDeclarations);
1393 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
1394 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
1395 IO.mapOptional("CompactCaseLabels", Style.CompactCaseLabels);
1396 IO.mapOptional("CompactNamespaces", Style.CompactNamespaces);
1397 IO.mapOptional("ConstructorInitializerIndentWidth",
1398 Style.ConstructorInitializerIndentWidth);
1399 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
1400 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
1401 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
1402 IO.mapOptional("DisableFormat", Style.DisableFormat);
1403 IO.mapOptional("EmptyLineAfterAccessModifier",
1404 Style.EmptyLineAfterAccessModifier);
1405 IO.mapOptional("EmptyLineBeforeAccessModifier",
1406 Style.EmptyLineBeforeAccessModifier);
1407 IO.mapOptional("EnumTrailingComma", Style.EnumTrailingComma);
1408 IO.mapOptional("ExperimentalAutoDetectBinPacking",
1409 Style.ExperimentalAutoDetectBinPacking);
1410 IO.mapOptional("FixNamespaceComments", Style.FixNamespaceComments);
1411 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
1412 IO.mapOptional("IfMacros", Style.IfMacros);
1413 IO.mapOptional("IncludeBlocks", Style.IncludeStyle.IncludeBlocks);
1414 IO.mapOptional("IncludeCategories", Style.IncludeStyle.IncludeCategories);
1415 IO.mapOptional("IncludeIsMainRegex", Style.IncludeStyle.IncludeIsMainRegex);
1416 IO.mapOptional("IncludeIsMainSourceRegex",
1417 Style.IncludeStyle.IncludeIsMainSourceRegex);
1418 IO.mapOptional("IndentAccessModifiers", Style.IndentAccessModifiers);
1419 IO.mapOptional("IndentCaseBlocks", Style.IndentCaseBlocks);
1420 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
1421 IO.mapOptional("IndentExportBlock", Style.IndentExportBlock);
1422 IO.mapOptional("IndentExternBlock", Style.IndentExternBlock);
1423 IO.mapOptional("IndentGotoLabels", Style.IndentGotoLabels);
1424 IO.mapOptional("IndentPPDirectives", Style.IndentPPDirectives);
1425 IO.mapOptional("IndentRequiresClause", Style.IndentRequiresClause);
1426 IO.mapOptional("IndentWidth", Style.IndentWidth);
1427 IO.mapOptional("IndentWrappedFunctionNames",
1428 Style.IndentWrappedFunctionNames);
1429 IO.mapOptional("InsertBraces", Style.InsertBraces);
1430 IO.mapOptional("InsertNewlineAtEOF", Style.InsertNewlineAtEOF);
1431 IO.mapOptional("InsertTrailingCommas", Style.InsertTrailingCommas);
1432 IO.mapOptional("IntegerLiteralSeparator", Style.IntegerLiteralSeparator);
1433 IO.mapOptional("JavaImportGroups", Style.JavaImportGroups);
1434 IO.mapOptional("JavaScriptQuotes", Style.JavaScriptQuotes);
1435 IO.mapOptional("JavaScriptWrapImports", Style.JavaScriptWrapImports);
1436 IO.mapOptional("KeepEmptyLines", Style.KeepEmptyLines);
1437 IO.mapOptional("KeepFormFeed", Style.KeepFormFeed);
1438 IO.mapOptional("LambdaBodyIndentation", Style.LambdaBodyIndentation);
1439 IO.mapOptional("LineEnding", Style.LineEnding);
1440 IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
1441 IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
1442 IO.mapOptional("Macros", Style.Macros);
1443 IO.mapOptional("MacrosSkippedByRemoveParentheses",
1444 Style.MacrosSkippedByRemoveParentheses);
1445 IO.mapOptional("MainIncludeChar", Style.IncludeStyle.MainIncludeChar);
1446 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
1447 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
1448 IO.mapOptional("NamespaceMacros", Style.NamespaceMacros);
1449 IO.mapOptional("NumericLiteralCase", Style.NumericLiteralCase);
1450 IO.mapOptional("ObjCBinPackProtocolList", Style.ObjCBinPackProtocolList);
1451 IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
1452 IO.mapOptional("ObjCBreakBeforeNestedBlockParam",
1453 Style.ObjCBreakBeforeNestedBlockParam);
1454 IO.mapOptional("ObjCPropertyAttributeOrder",
1455 Style.ObjCPropertyAttributeOrder);
1456 IO.mapOptional("ObjCSpaceAfterMethodDeclarationPrefix",
1457 Style.ObjCSpaceAfterMethodDeclarationPrefix);
1458 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
1459 IO.mapOptional("ObjCSpaceBeforeProtocolList",
1460 Style.ObjCSpaceBeforeProtocolList);
1461 IO.mapOptional("OneLineFormatOffRegex", Style.OneLineFormatOffRegex);
1462 IO.mapOptional("PackArguments", Style.PackArguments);
1463 IO.mapOptional("PackConstructorInitializers",
1464 Style.PackConstructorInitializers);
1465 IO.mapOptional("PackParameters", Style.PackParameters);
1466 IO.mapOptional("PenaltyBreakAssignment", Style.PenaltyBreakAssignment);
1467 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
1468 Style.PenaltyBreakBeforeFirstCallParameter);
1469 IO.mapOptional("PenaltyBreakBeforeMemberAccess",
1470 Style.PenaltyBreakBeforeMemberAccess);
1471 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
1472 IO.mapOptional("PenaltyBreakFirstLessLess",
1473 Style.PenaltyBreakFirstLessLess);
1474 IO.mapOptional("PenaltyBreakOpenParenthesis",
1475 Style.PenaltyBreakOpenParenthesis);
1476 IO.mapOptional("PenaltyBreakScopeResolution",
1477 Style.PenaltyBreakScopeResolution);
1478 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
1479 IO.mapOptional("PenaltyBreakTemplateDeclaration",
1480 Style.PenaltyBreakTemplateDeclaration);
1481 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
1482 IO.mapOptional("PenaltyIndentedWhitespace",
1483 Style.PenaltyIndentedWhitespace);
1484 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
1485 Style.PenaltyReturnTypeOnItsOwnLine);
1486 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
1487 IO.mapOptional("PPIndentWidth", Style.PPIndentWidth);
1488 IO.mapOptional("QualifierAlignment", Style.QualifierAlignment);
1489 // Default Order for Left/Right based Qualifier alignment.
1490 if (Style.QualifierAlignment == FormatStyle::QAS_Right)
1491 Style.QualifierOrder = {"type", "const", "volatile"};
1492 else if (Style.QualifierAlignment == FormatStyle::QAS_Left)
1493 Style.QualifierOrder = {"const", "volatile", "type"};
1494 else if (Style.QualifierAlignment == FormatStyle::QAS_Custom)
1495 IO.mapOptional("QualifierOrder", Style.QualifierOrder);
1496 IO.mapOptional("RawStringFormats", Style.RawStringFormats);
1497 IO.mapOptional("ReferenceAlignment", Style.ReferenceAlignment);
1498 IO.mapOptional("ReflowComments", Style.ReflowComments);
1499 IO.mapOptional("RemoveBracesLLVM", Style.RemoveBracesLLVM);
1500 IO.mapOptional("RemoveEmptyLinesInUnwrappedLines",
1501 Style.RemoveEmptyLinesInUnwrappedLines);
1502 IO.mapOptional("RemoveParentheses", Style.RemoveParentheses);
1503 IO.mapOptional("RemoveSemicolon", Style.RemoveSemicolon);
1504 IO.mapOptional("RequiresClausePosition", Style.RequiresClausePosition);
1505 IO.mapOptional("RequiresExpressionIndentation",
1506 Style.RequiresExpressionIndentation);
1507 IO.mapOptional("SeparateDefinitionBlocks", Style.SeparateDefinitionBlocks);
1508 IO.mapOptional("ShortNamespaceLines", Style.ShortNamespaceLines);
1509 IO.mapOptional("SkipMacroDefinitionBody", Style.SkipMacroDefinitionBody);
1510 IO.mapOptional("SortIncludes", Style.SortIncludes);
1511 IO.mapOptional("SortJavaStaticImport", Style.SortJavaStaticImport);
1512 IO.mapOptional("SortUsingDeclarations", Style.SortUsingDeclarations);
1513 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
1514 IO.mapOptional("SpaceAfterLogicalNot", Style.SpaceAfterLogicalNot);
1515 IO.mapOptional("SpaceAfterOperatorKeyword",
1516 Style.SpaceAfterOperatorKeyword);
1517 IO.mapOptional("SpaceAfterTemplateKeyword",
1518 Style.SpaceAfterTemplateKeyword);
1519 IO.mapOptional("SpaceAroundPointerQualifiers",
1520 Style.SpaceAroundPointerQualifiers);
1521 IO.mapOptional("SpaceBeforeAssignmentOperators",
1522 Style.SpaceBeforeAssignmentOperators);
1523 IO.mapOptional("SpaceBeforeCaseColon", Style.SpaceBeforeCaseColon);
1524 IO.mapOptional("SpaceBeforeCpp11BracedList",
1525 Style.SpaceBeforeCpp11BracedList);
1526 IO.mapOptional("SpaceBeforeCtorInitializerColon",
1527 Style.SpaceBeforeCtorInitializerColon);
1528 IO.mapOptional("SpaceBeforeEnumUnderlyingTypeColon",
1529 Style.SpaceBeforeEnumUnderlyingTypeColon);
1530 IO.mapOptional("SpaceBeforeInheritanceColon",
1531 Style.SpaceBeforeInheritanceColon);
1532 IO.mapOptional("SpaceBeforeJsonColon", Style.SpaceBeforeJsonColon);
1533 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
1534 IO.mapOptional("SpaceBeforeParensOptions", Style.SpaceBeforeParensOptions);
1535 IO.mapOptional("SpaceBeforeRangeBasedForLoopColon",
1536 Style.SpaceBeforeRangeBasedForLoopColon);
1537 IO.mapOptional("SpaceBeforeSquareBrackets",
1538 Style.SpaceBeforeSquareBrackets);
1539 IO.mapOptional("SpaceInEmptyBraces", Style.SpaceInEmptyBraces);
1540 IO.mapOptional("SpacesBeforeTrailingComments",
1541 Style.SpacesBeforeTrailingComments);
1542 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
1543 IO.mapOptional("SpacesInBlockComments", Style.SpacesInBlockComments);
1544 IO.mapOptional("SpacesInContainerLiterals",
1545 Style.SpacesInContainerLiterals);
1546 IO.mapOptional("SpacesInLineCommentPrefix",
1547 Style.SpacesInLineCommentPrefix);
1548 IO.mapOptional("SpacesInParens", Style.SpacesInParens);
1549 IO.mapOptional("SpacesInParensOptions", Style.SpacesInParensOptions);
1550 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
1551 IO.mapOptional("Standard", Style.Standard);
1552 IO.mapOptional("StatementAttributeLikeMacros",
1553 Style.StatementAttributeLikeMacros);
1554 IO.mapOptional("StatementMacros", Style.StatementMacros);
1555 IO.mapOptional("TableGenBreakingDAGArgOperators",
1556 Style.TableGenBreakingDAGArgOperators);
1557 IO.mapOptional("TableGenBreakInsideDAGArg",
1558 Style.TableGenBreakInsideDAGArg);
1559 IO.mapOptional("TabWidth", Style.TabWidth);
1560 IO.mapOptional("TemplateNames", Style.TemplateNames);
1561 IO.mapOptional("TypeNames", Style.TypeNames);
1562 IO.mapOptional("TypenameMacros", Style.TypenameMacros);
1563 IO.mapOptional("UseTab", Style.UseTab);
1564 IO.mapOptional("VariableTemplates", Style.VariableTemplates);
1565 IO.mapOptional("VerilogBreakBetweenInstancePorts",
1566 Style.VerilogBreakBetweenInstancePorts);
1567 IO.mapOptional("WhitespaceSensitiveMacros",
1568 Style.WhitespaceSensitiveMacros);
1569 IO.mapOptional("WrapNamespaceBodyWithEmptyLines",
1570 Style.WrapNamespaceBodyWithEmptyLines);
1571
1572 // If AlwaysBreakAfterDefinitionReturnType was specified but
1573 // BreakAfterReturnType was not, initialize the latter from the former for
1574 // backwards compatibility.
1575 if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
1576 Style.BreakAfterReturnType == FormatStyle::RTBS_None) {
1577 if (Style.AlwaysBreakAfterDefinitionReturnType ==
1579 Style.BreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
1580 } else if (Style.AlwaysBreakAfterDefinitionReturnType ==
1582 Style.BreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
1583 }
1584 }
1585
1586 // If BreakBeforeInheritanceComma was specified but BreakInheritance was
1587 // not, initialize the latter from the former for backwards compatibility.
1588 if (BreakBeforeInheritanceComma &&
1589 Style.BreakInheritanceList == FormatStyle::BILS_BeforeColon) {
1590 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
1591 }
1592
1593 // If BreakConstructorInitializersBeforeComma was specified but
1594 // BreakConstructorInitializers was not, initialize the latter from the
1595 // former for backwards compatibility.
1596 if (BreakConstructorInitializersBeforeComma &&
1597 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon) {
1598 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
1599 }
1600
1601 if (!IsGoogleOrChromium) {
1602 if (Style.PackConstructorInitializers == FormatStyle::PCIS_BinPack &&
1603 OnCurrentLine) {
1604 Style.PackConstructorInitializers = OnNextLine
1607 }
1608 } else if (Style.PackConstructorInitializers ==
1610 if (!OnCurrentLine)
1611 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
1612 else if (!OnNextLine)
1613 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
1614 }
1615
1616 if (Style.LineEnding == FormatStyle::LE_DeriveLF) {
1617 if (!DeriveLineEnding)
1618 Style.LineEnding = UseCRLF ? FormatStyle::LE_CRLF : FormatStyle::LE_LF;
1619 else if (UseCRLF)
1620 Style.LineEnding = FormatStyle::LE_DeriveCRLF;
1621 }
1622
1623 // If SpaceInEmptyBlock was specified but SpaceInEmptyBraces was not,
1624 // initialize the latter from the former for backward compatibility.
1625 if (SpaceInEmptyBlock &&
1626 Style.SpaceInEmptyBraces == FormatStyle::SIEB_Never) {
1627 Style.SpaceInEmptyBraces = FormatStyle::SIEB_Block;
1628 }
1629
1630 if (Style.SpacesInParens != FormatStyle::SIPO_Custom &&
1631 (SpacesInParentheses || SpaceInEmptyParentheses ||
1632 SpacesInConditionalStatement || SpacesInCStyleCastParentheses)) {
1633 if (SpacesInParentheses) {
1634 // For backward compatibility.
1635 Style.SpacesInParensOptions.ExceptDoubleParentheses = false;
1636 Style.SpacesInParensOptions.InConditionalStatements = true;
1637 Style.SpacesInParensOptions.InCStyleCasts =
1638 SpacesInCStyleCastParentheses;
1639 Style.SpacesInParensOptions.InEmptyParentheses =
1640 SpaceInEmptyParentheses;
1641 Style.SpacesInParensOptions.Other = true;
1642 } else {
1643 Style.SpacesInParensOptions = {};
1644 Style.SpacesInParensOptions.InConditionalStatements =
1645 SpacesInConditionalStatement;
1646 Style.SpacesInParensOptions.InCStyleCasts =
1647 SpacesInCStyleCastParentheses;
1648 Style.SpacesInParensOptions.InEmptyParentheses =
1649 SpaceInEmptyParentheses;
1650 }
1651 Style.SpacesInParens = FormatStyle::SIPO_Custom;
1652 }
1653 }
1654};
1655
1656// Allows to read vector<FormatStyle> while keeping default values.
1657// IO.getContext() should contain a pointer to the FormatStyle structure, that
1658// will be used to get default values for missing keys.
1659// If the first element has no Language specified, it will be treated as the
1660// default one for the following elements.
1661template <> struct DocumentListTraits<std::vector<FormatStyle>> {
1662 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
1663 return Seq.size();
1664 }
1665 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
1666 size_t Index) {
1667 if (Index >= Seq.size()) {
1668 assert(Index == Seq.size());
1669 FormatStyle Template;
1670 if (!Seq.empty() && Seq[0].Language == FormatStyle::LK_None) {
1671 Template = Seq[0];
1672 } else {
1673 Template = *((const FormatStyle *)IO.getContext());
1674 Template.Language = FormatStyle::LK_None;
1675 }
1676 Seq.resize(Index + 1, Template);
1677 }
1678 return Seq[Index];
1679 }
1680};
1681
1682template <> struct ScalarEnumerationTraits<FormatStyle::IndentGotoLabelStyle> {
1684 IO.enumCase(Value, "NoIndent", FormatStyle::IGLS_NoIndent);
1685 IO.enumCase(Value, "OuterIndent", FormatStyle::IGLS_OuterIndent);
1686 IO.enumCase(Value, "InnerIndent", FormatStyle::IGLS_InnerIndent);
1687 IO.enumCase(Value, "HalfIndent", FormatStyle::IGLS_HalfIndent);
1688
1689 // For backward compatibility.
1690 IO.enumCase(Value, "false", FormatStyle::IGLS_NoIndent);
1691 IO.enumCase(Value, "true", FormatStyle::IGLS_OuterIndent);
1692 }
1693};
1694
1695} // namespace yaml
1696} // namespace llvm
1697
1698namespace clang {
1699namespace format {
1700
1701const std::error_category &getParseCategory() {
1702 static const ParseErrorCategory C{};
1703 return C;
1704}
1705std::error_code make_error_code(ParseError e) {
1706 return std::error_code(static_cast<int>(e), getParseCategory());
1707}
1708
1709inline llvm::Error make_string_error(const Twine &Message) {
1710 return llvm::make_error<llvm::StringError>(Message,
1711 llvm::inconvertibleErrorCode());
1712}
1713
1714const char *ParseErrorCategory::name() const noexcept {
1715 return "clang-format.parse_error";
1716}
1717
1718std::string ParseErrorCategory::message(int EV) const {
1719 switch (static_cast<ParseError>(EV)) {
1721 return "Success";
1722 case ParseError::Error:
1723 return "Invalid argument";
1725 return "Unsuitable";
1727 return "trailing comma insertion cannot be used with bin packing";
1729 return "Invalid qualifier specified in QualifierOrder";
1731 return "Duplicate qualifier specified in QualifierOrder";
1733 return "Missing type in QualifierOrder";
1735 return "Missing QualifierOrder";
1736 }
1737 llvm_unreachable("unexpected parse error");
1738}
1739
1742 return;
1743 Expanded.BraceWrapping = {/*AfterCaseLabel=*/false,
1744 /*AfterClass=*/false,
1745 /*AfterControlStatement=*/FormatStyle::BWACS_Never,
1746 /*AfterEnum=*/false,
1747 /*AfterFunction=*/false,
1748 /*AfterNamespace=*/false,
1749 /*AfterObjCDeclaration=*/false,
1750 /*AfterRequiresExpression=*/false,
1751 /*AfterStruct=*/false,
1752 /*AfterUnion=*/false,
1753 /*AfterExportBlock=*/false,
1754 /*AfterExternBlock=*/false,
1755 /*BeforeCatch=*/false,
1756 /*BeforeElse=*/false,
1757 /*BeforeLambdaBody=*/false,
1758 /*BeforeWhile=*/false,
1759 /*IndentBraces=*/false,
1760 /*SplitEmptyFunction=*/true,
1761 /*SplitEmptyRecord=*/true,
1762 /*SplitEmptyNamespace=*/true};
1763 switch (Expanded.BreakBeforeBraces) {
1765 Expanded.BraceWrapping.AfterClass = true;
1766 Expanded.BraceWrapping.AfterFunction = true;
1767 Expanded.BraceWrapping.AfterNamespace = true;
1768 break;
1770 Expanded.BraceWrapping.AfterClass = true;
1771 Expanded.BraceWrapping.AfterEnum = true;
1772 Expanded.BraceWrapping.AfterFunction = true;
1773 Expanded.BraceWrapping.AfterStruct = true;
1774 Expanded.BraceWrapping.AfterUnion = true;
1775 Expanded.BraceWrapping.AfterExportBlock = true;
1776 Expanded.BraceWrapping.AfterExternBlock = true;
1777 Expanded.BraceWrapping.SplitEmptyFunction = true;
1778 Expanded.BraceWrapping.SplitEmptyRecord = false;
1779 break;
1781 Expanded.BraceWrapping.AfterFunction = true;
1782 Expanded.BraceWrapping.BeforeCatch = true;
1783 Expanded.BraceWrapping.BeforeElse = true;
1784 break;
1786 Expanded.BraceWrapping.AfterCaseLabel = true;
1787 Expanded.BraceWrapping.AfterClass = true;
1789 Expanded.BraceWrapping.AfterEnum = true;
1790 Expanded.BraceWrapping.AfterFunction = true;
1791 Expanded.BraceWrapping.AfterNamespace = true;
1792 Expanded.BraceWrapping.AfterObjCDeclaration = true;
1793 Expanded.BraceWrapping.AfterRequiresExpression = true;
1794 Expanded.BraceWrapping.AfterStruct = true;
1795 Expanded.BraceWrapping.AfterUnion = true;
1796 Expanded.BraceWrapping.AfterExportBlock = true;
1797 Expanded.BraceWrapping.AfterExternBlock = true;
1798 Expanded.BraceWrapping.BeforeCatch = true;
1799 Expanded.BraceWrapping.BeforeElse = true;
1800 Expanded.BraceWrapping.BeforeLambdaBody = true;
1801 break;
1803 Expanded.BraceWrapping.AfterCaseLabel = true;
1804 Expanded.BraceWrapping.AfterClass = true;
1806 Expanded.BraceWrapping.AfterEnum = true;
1807 Expanded.BraceWrapping.AfterFunction = true;
1808 Expanded.BraceWrapping.AfterNamespace = true;
1809 Expanded.BraceWrapping.AfterObjCDeclaration = true;
1810 Expanded.BraceWrapping.AfterRequiresExpression = true;
1811 Expanded.BraceWrapping.AfterStruct = true;
1812 Expanded.BraceWrapping.AfterExternBlock = true;
1813 Expanded.BraceWrapping.BeforeCatch = true;
1814 Expanded.BraceWrapping.BeforeElse = true;
1815 Expanded.BraceWrapping.BeforeLambdaBody = true;
1816 break;
1818 Expanded.BraceWrapping = {
1819 /*AfterCaseLabel=*/true,
1820 /*AfterClass=*/true,
1821 /*AfterControlStatement=*/FormatStyle::BWACS_Always,
1822 /*AfterEnum=*/true,
1823 /*AfterFunction=*/true,
1824 /*AfterNamespace=*/true,
1825 /*AfterObjCDeclaration=*/true,
1826 /*AfterRequiresExpression=*/true,
1827 /*AfterStruct=*/true,
1828 /*AfterUnion=*/true,
1829 /*AfterExportBlock=*/true,
1830 /*AfterExternBlock=*/true,
1831 /*BeforeCatch=*/true,
1832 /*BeforeElse=*/true,
1833 /*BeforeLambdaBody=*/true,
1834 /*BeforeWhile=*/true,
1835 /*IndentBraces=*/true,
1836 /*SplitEmptyFunction=*/true,
1837 /*SplitEmptyRecord=*/true,
1838 /*SplitEmptyNamespace=*/true};
1839 break;
1841 Expanded.BraceWrapping.AfterFunction = true;
1842 break;
1843 default:
1844 break;
1845 }
1846}
1847
1850 return;
1851 // Reset all flags
1852 Expanded.SpaceBeforeParensOptions = {};
1854
1855 switch (Expanded.SpaceBeforeParens) {
1860 break;
1863 break;
1866 break;
1867 default:
1868 break;
1869 }
1870}
1871
1874 return;
1875 assert(Expanded.SpacesInParens == FormatStyle::SIPO_Never);
1876 // Reset all flags
1877 Expanded.SpacesInParensOptions = {};
1878}
1879
1881 FormatStyle LLVMStyle;
1882 LLVMStyle.AccessModifierOffset = -2;
1883 LLVMStyle.AlignAfterOpenBracket = true;
1885 LLVMStyle.AlignConsecutiveAssignments = {};
1887 LLVMStyle.AlignConsecutiveBitFields = {};
1888 LLVMStyle.AlignConsecutiveDeclarations = {};
1890 LLVMStyle.AlignConsecutiveMacros = {};
1897 LLVMStyle.AlignTrailingComments = {};
1900 LLVMStyle.AlignTrailingComments.AlignPPAndNotPP = true;
1901 LLVMStyle.AllowAllArgumentsOnNextLine = true;
1904 LLVMStyle.AllowBreakBeforeQtProperty = false;
1907 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
1909 LLVMStyle.AllowShortEnumsOnASingleLine = true;
1914 LLVMStyle.AllowShortLoopsOnASingleLine = false;
1915 LLVMStyle.AllowShortNamespacesOnASingleLine = false;
1918 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
1919 LLVMStyle.AttributeMacros.push_back("__capability");
1920 LLVMStyle.BinPackLongBracedList = true;
1922 LLVMStyle.BracedInitializerIndentWidth = -1;
1923 LLVMStyle.BraceWrapping = {/*AfterCaseLabel=*/false,
1924 /*AfterClass=*/false,
1925 /*AfterControlStatement=*/FormatStyle::BWACS_Never,
1926 /*AfterEnum=*/false,
1927 /*AfterFunction=*/false,
1928 /*AfterNamespace=*/false,
1929 /*AfterObjCDeclaration=*/false,
1930 /*AfterRequiresExpression=*/false,
1931 /*AfterStruct=*/false,
1932 /*AfterUnion=*/false,
1933 /*AfterExportBlock=*/false,
1934 /*AfterExternBlock=*/false,
1935 /*BeforeCatch=*/false,
1936 /*BeforeElse=*/false,
1937 /*BeforeLambdaBody=*/false,
1938 /*BeforeWhile=*/false,
1939 /*IndentBraces=*/false,
1940 /*SplitEmptyFunction=*/true,
1941 /*SplitEmptyRecord=*/true,
1942 /*SplitEmptyNamespace=*/true};
1943 LLVMStyle.BreakAdjacentStringLiterals = true;
1945 LLVMStyle.BreakAfterJavaFieldAnnotations = false;
1946 LLVMStyle.BreakAfterOpenBracketBracedList = false;
1947 LLVMStyle.BreakAfterOpenBracketFunction = false;
1948 LLVMStyle.BreakAfterOpenBracketIf = false;
1949 LLVMStyle.BreakAfterOpenBracketLoop = false;
1950 LLVMStyle.BreakAfterOpenBracketSwitch = false;
1952 LLVMStyle.BreakArrays = true;
1955 LLVMStyle.BreakBeforeCloseBracketBracedList = false;
1956 LLVMStyle.BreakBeforeCloseBracketFunction = false;
1957 LLVMStyle.BreakBeforeCloseBracketIf = false;
1958 LLVMStyle.BreakBeforeCloseBracketLoop = false;
1959 LLVMStyle.BreakBeforeCloseBracketSwitch = false;
1963 LLVMStyle.BreakBeforeTemplateCloser = false;
1964 LLVMStyle.BreakBeforeTernaryOperators = true;
1967 LLVMStyle.BreakFunctionDeclarationParameters = false;
1968 LLVMStyle.BreakFunctionDefinitionParameters = false;
1970 LLVMStyle.BreakStringLiterals = true;
1972 LLVMStyle.ColumnLimit = 80;
1973 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
1974 LLVMStyle.CompactCaseLabels = false;
1975 LLVMStyle.CompactNamespaces = false;
1977 LLVMStyle.ContinuationIndentWidth = 4;
1979 LLVMStyle.DerivePointerAlignment = false;
1980 LLVMStyle.DisableFormat = false;
1984 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
1985 LLVMStyle.FixNamespaceComments = true;
1986 LLVMStyle.ForEachMacros.push_back("foreach");
1987 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
1988 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
1989 LLVMStyle.IfMacros.push_back("KJ_IF_MAYBE");
1991 LLVMStyle.IncludeStyle.IncludeCategories = {
1992 {"^\"(llvm|llvm-c|clang|clang-c)/", 2, 0, false},
1993 {"^(<|\"(gtest|gmock|isl|json)/)", 3, 0, false},
1994 {".*", 1, 0, false}};
1995 LLVMStyle.IncludeStyle.IncludeIsMainRegex = "(Test)?$";
1998 LLVMStyle.IndentCaseBlocks = false;
1999 LLVMStyle.IndentCaseLabels = false;
2000 LLVMStyle.IndentExportBlock = true;
2004 LLVMStyle.IndentRequiresClause = true;
2005 LLVMStyle.IndentWidth = 2;
2006 LLVMStyle.IndentWrappedFunctionNames = false;
2007 LLVMStyle.InsertBraces = false;
2008 LLVMStyle.InsertNewlineAtEOF = false;
2010 LLVMStyle.IntegerLiteralSeparator = {};
2012 LLVMStyle.JavaScriptWrapImports = true;
2013 LLVMStyle.KeepEmptyLines = {
2014 /*AtEndOfBlock=*/false,
2015 /*AtEndOfFile=*/false,
2016 /*AtStartOfBlock=*/true,
2017 /*AtStartOfFile=*/true,
2018 };
2019 LLVMStyle.KeepFormFeed = false;
2021 LLVMStyle.Language = Language;
2023 LLVMStyle.MaxEmptyLinesToKeep = 1;
2025 LLVMStyle.NumericLiteralCase = {/*ExponentLetter=*/FormatStyle::NLCS_Leave,
2026 /*HexDigit=*/FormatStyle::NLCS_Leave,
2027 /*Prefix=*/FormatStyle::NLCS_Leave,
2028 /*Suffix=*/FormatStyle::NLCS_Leave};
2030 LLVMStyle.ObjCBlockIndentWidth = 2;
2031 LLVMStyle.ObjCBreakBeforeNestedBlockParam = true;
2033 LLVMStyle.ObjCSpaceAfterProperty = false;
2034 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
2035 LLVMStyle.PackArguments = {/*BinPack=*/FormatStyle::BPAS_BinPack,
2036 /*BreakAfter=*/0};
2038 LLVMStyle.PackParameters = {/*BinPack=*/FormatStyle::BPPS_BinPack,
2039 /*BreakAfter=*/0};
2041 LLVMStyle.PPIndentWidth = -1;
2045 LLVMStyle.RemoveBracesLLVM = false;
2046 LLVMStyle.RemoveEmptyLinesInUnwrappedLines = false;
2048 LLVMStyle.RemoveSemicolon = false;
2052 LLVMStyle.ShortNamespaceLines = 1;
2053 LLVMStyle.SkipMacroDefinitionBody = false;
2054 LLVMStyle.SortIncludes = {/*Enabled=*/true, /*IgnoreCase=*/false,
2055 /*IgnoreExtension=*/false, /*Natural=*/false,
2056 /*FilesBeforeFolders=*/false};
2059 LLVMStyle.SpaceAfterCStyleCast = false;
2060 LLVMStyle.SpaceAfterLogicalNot = false;
2061 LLVMStyle.SpaceAfterOperatorKeyword = false;
2062 LLVMStyle.SpaceAfterTemplateKeyword = true;
2064 LLVMStyle.SpaceBeforeAssignmentOperators = true;
2065 LLVMStyle.SpaceBeforeCaseColon = false;
2066 LLVMStyle.SpaceBeforeCpp11BracedList = false;
2067 LLVMStyle.SpaceBeforeCtorInitializerColon = true;
2068 LLVMStyle.SpaceBeforeEnumUnderlyingTypeColon = true;
2069 LLVMStyle.SpaceBeforeInheritanceColon = true;
2070 LLVMStyle.SpaceBeforeJsonColon = false;
2072 LLVMStyle.SpaceBeforeParensOptions = {};
2075 LLVMStyle.SpaceBeforeParensOptions.AfterIfMacros = true;
2076 LLVMStyle.SpaceBeforeRangeBasedForLoopColon = true;
2077 LLVMStyle.SpaceBeforeSquareBrackets = false;
2079 LLVMStyle.SpacesBeforeTrailingComments = 1;
2081 LLVMStyle.SpacesInBlockComments = FormatStyle::SIBCS_Leave;
2082 LLVMStyle.SpacesInContainerLiterals = true;
2083 LLVMStyle.SpacesInLineCommentPrefix = {
2084 /*Minimum=*/1, /*Maximum=*/std::numeric_limits<unsigned>::max()};
2086 LLVMStyle.SpacesInSquareBrackets = false;
2087 LLVMStyle.Standard = FormatStyle::LS_Latest;
2088 LLVMStyle.StatementAttributeLikeMacros.push_back("Q_EMIT");
2089 LLVMStyle.StatementMacros.push_back("Q_UNUSED");
2090 LLVMStyle.StatementMacros.push_back("QT_REQUIRE_VERSION");
2091 LLVMStyle.TableGenBreakingDAGArgOperators = {};
2093 LLVMStyle.TabWidth = 8;
2094 LLVMStyle.UseTab = FormatStyle::UT_Never;
2095 LLVMStyle.VerilogBreakBetweenInstancePorts = true;
2096 LLVMStyle.WhitespaceSensitiveMacros.push_back("BOOST_PP_STRINGIZE");
2097 LLVMStyle.WhitespaceSensitiveMacros.push_back("CF_SWIFT_NAME");
2098 LLVMStyle.WhitespaceSensitiveMacros.push_back("NS_SWIFT_NAME");
2099 LLVMStyle.WhitespaceSensitiveMacros.push_back("PP_STRINGIZE");
2100 LLVMStyle.WhitespaceSensitiveMacros.push_back("STRINGIZE");
2102
2105 LLVMStyle.PenaltyBreakBeforeMemberAccess = 150;
2106 LLVMStyle.PenaltyBreakComment = 300;
2107 LLVMStyle.PenaltyBreakFirstLessLess = 120;
2108 LLVMStyle.PenaltyBreakOpenParenthesis = 0;
2109 LLVMStyle.PenaltyBreakScopeResolution = 500;
2110 LLVMStyle.PenaltyBreakString = 1000;
2112 LLVMStyle.PenaltyExcessCharacter = 1'000'000;
2113 LLVMStyle.PenaltyIndentedWhitespace = 0;
2114 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
2115
2116 // Defaults that differ when not C++.
2117 switch (Language) {
2119 LLVMStyle.SpacesInContainerLiterals = false;
2120 break;
2122 LLVMStyle.ColumnLimit = 0;
2123 break;
2125 LLVMStyle.IndentCaseLabels = true;
2126 LLVMStyle.SpacesInContainerLiterals = false;
2127 break;
2128 default:
2129 break;
2130 }
2131
2132 return LLVMStyle;
2133}
2134
2138 GoogleStyle.Language = FormatStyle::LK_TextProto;
2139
2140 return GoogleStyle;
2141 }
2142
2143 FormatStyle GoogleStyle = getLLVMStyle(Language);
2144
2145 GoogleStyle.AccessModifierOffset = -1;
2149 GoogleStyle.AllowShortLoopsOnASingleLine = true;
2150 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
2151 // Abseil aliases to clang's `_Nonnull`, `_Nullable` and `_Null_unspecified`.
2152 GoogleStyle.AttributeMacros.push_back("absl_nonnull");
2153 GoogleStyle.AttributeMacros.push_back("absl_nullable");
2154 GoogleStyle.AttributeMacros.push_back("absl_nullability_unknown");
2157 GoogleStyle.IncludeStyle.IncludeCategories = {{"^<ext/.*\\.h>", 2, 0, false},
2158 {"^<.*\\.h>", 1, 0, false},
2159 {"^<.*", 2, 0, false},
2160 {".*", 3, 0, false}};
2161 GoogleStyle.IncludeStyle.IncludeIsMainRegex = "([-_](test|unittest))?$";
2162 GoogleStyle.IndentCaseLabels = true;
2163 GoogleStyle.KeepEmptyLines.AtStartOfBlock = false;
2165 GoogleStyle.ObjCSpaceAfterProperty = false;
2166 GoogleStyle.ObjCSpaceBeforeProtocolList = true;
2169 GoogleStyle.RawStringFormats = {
2170 {
2172 /*Delimiters=*/
2173 {
2174 "cc",
2175 "CC",
2176 "cpp",
2177 "Cpp",
2178 "CPP",
2179 "c++",
2180 "C++",
2181 },
2182 /*EnclosingFunctionNames=*/
2183 {},
2184 /*CanonicalDelimiter=*/"",
2185 /*BasedOnStyle=*/"google",
2186 },
2187 {
2189 /*Delimiters=*/
2190 {
2191 "pb",
2192 "PB",
2193 "proto",
2194 "PROTO",
2195 },
2196 /*EnclosingFunctionNames=*/
2197 {
2198 "EqualsProto",
2199 "EquivToProto",
2200 "PARSE_PARTIAL_TEXT_PROTO",
2201 "PARSE_TEST_PROTO",
2202 "PARSE_TEXT_PROTO",
2203 "ParseTextOrDie",
2204 "ParseTextProtoOrDie",
2205 "ParseTestProto",
2206 "ParsePartialTestProto",
2207 },
2208 /*CanonicalDelimiter=*/"pb",
2209 /*BasedOnStyle=*/"google",
2210 },
2211 };
2212
2213 GoogleStyle.SpacesBeforeTrailingComments = 2;
2214 GoogleStyle.Standard = FormatStyle::LS_Auto;
2215
2217 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
2218
2220 GoogleStyle.AlignAfterOpenBracket = false;
2222 GoogleStyle.AlignTrailingComments = {};
2227 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
2229 GoogleStyle.ColumnLimit = 100;
2230 GoogleStyle.SpaceAfterCStyleCast = true;
2231 GoogleStyle.SpacesBeforeTrailingComments = 1;
2232 } else if (Language == FormatStyle::LK_JavaScript) {
2233 GoogleStyle.BreakAfterOpenBracketBracedList = true;
2234 GoogleStyle.BreakAfterOpenBracketFunction = true;
2235 GoogleStyle.BreakAfterOpenBracketIf = true;
2239 // TODO: still under discussion whether to switch to SLS_All.
2241 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
2242 GoogleStyle.BreakBeforeTernaryOperators = false;
2243 // taze:, triple slash directives (`/// <...`), tslint:, and @see, which is
2244 // commonly followed by overlong URLs.
2245 GoogleStyle.CommentPragmas = "(taze:|^/[ \t]*<|tslint:|@see)";
2246 // TODO: enable once decided, in particular re disabling bin packing.
2247 // https://google.github.io/styleguide/jsguide.html#features-arrays-trailing-comma
2248 // GoogleStyle.InsertTrailingCommas = FormatStyle::TCS_Wrapped;
2250 GoogleStyle.JavaScriptWrapImports = false;
2251 GoogleStyle.MaxEmptyLinesToKeep = 3;
2253 GoogleStyle.SpacesInContainerLiterals = false;
2254 } else if (Language == FormatStyle::LK_Proto) {
2257 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
2258 // This affects protocol buffer options specifications and text protos.
2259 // Text protos are currently mostly formatted inside C++ raw string literals
2260 // and often the current breaking behavior of string literals is not
2261 // beneficial there. Investigate turning this on once proper string reflow
2262 // has been implemented.
2263 GoogleStyle.BreakStringLiterals = false;
2265 GoogleStyle.SpacesInContainerLiterals = false;
2266 } else if (Language == FormatStyle::LK_ObjC) {
2267 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
2268 GoogleStyle.ColumnLimit = 100;
2269 GoogleStyle.DerivePointerAlignment = true;
2270 // "Regroup" doesn't work well for ObjC yet (main header heuristic,
2271 // relationship between ObjC standard library headers and other heades,
2272 // #imports, etc.)
2273 GoogleStyle.IncludeStyle.IncludeBlocks =
2275 } else if (Language == FormatStyle::LK_CSharp) {
2279 GoogleStyle.BreakStringLiterals = false;
2280 GoogleStyle.ColumnLimit = 100;
2282 }
2283
2284 return GoogleStyle;
2285}
2286
2288 FormatStyle ChromiumStyle = getGoogleStyle(Language);
2289
2290 // Disable include reordering across blocks in Chromium code.
2291 // - clang-format tries to detect that foo.h is the "main" header for
2292 // foo.cc and foo_unittest.cc via IncludeIsMainRegex. However, Chromium
2293 // uses many other suffices (_win.cc, _mac.mm, _posix.cc, _browsertest.cc,
2294 // _private.cc, _impl.cc etc) in different permutations
2295 // (_win_browsertest.cc) so disable this until IncludeIsMainRegex has a
2296 // better default for Chromium code.
2297 // - The default for .cc and .mm files is different (r357695) for Google style
2298 // for the same reason. The plan is to unify this again once the main
2299 // header detection works for Google's ObjC code, but this hasn't happened
2300 // yet. Since Chromium has some ObjC code, switching Chromium is blocked
2301 // on that.
2302 // - Finally, "If include reordering is harmful, put things in different
2303 // blocks to prevent it" has been a recommendation for a long time that
2304 // people are used to. We'll need a dev education push to change this to
2305 // "If include reordering is harmful, put things in a different block and
2306 // _prepend that with a comment_ to prevent it" before changing behavior.
2307 ChromiumStyle.IncludeStyle.IncludeBlocks =
2309
2313 ChromiumStyle.BreakAfterJavaFieldAnnotations = true;
2314 ChromiumStyle.ContinuationIndentWidth = 8;
2315 ChromiumStyle.IndentWidth = 4;
2316 // See styleguide for import groups:
2317 // https://chromium.googlesource.com/chromium/src/+/refs/heads/main/styleguide/java/java.md#Import-Order
2318 ChromiumStyle.JavaImportGroups = {
2319 "android",
2320 "androidx",
2321 "com",
2322 "dalvik",
2323 "junit",
2324 "org",
2325 "com.google.android.apps.chrome",
2326 "org.chromium",
2327 "java",
2328 "javax",
2329 };
2330 } else if (Language == FormatStyle::LK_JavaScript) {
2332 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
2333 } else {
2334 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
2335 ChromiumStyle.AllowShortFunctionsOnASingleLine =
2338 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
2340 ChromiumStyle.DerivePointerAlignment = false;
2342 ChromiumStyle.ColumnLimit = 80;
2343 }
2344 return ChromiumStyle;
2345}
2346
2348 FormatStyle MozillaStyle = getLLVMStyle();
2349 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
2361 MozillaStyle.ConstructorInitializerIndentWidth = 2;
2362 MozillaStyle.ContinuationIndentWidth = 2;
2364 MozillaStyle.FixNamespaceComments = false;
2365 MozillaStyle.IndentCaseLabels = true;
2366 MozillaStyle.ObjCSpaceAfterProperty = true;
2367 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
2368 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
2370 MozillaStyle.SpaceAfterTemplateKeyword = false;
2371 return MozillaStyle;
2372}
2373
2375 FormatStyle Style = getLLVMStyle();
2376 Style.AccessModifierOffset = -4;
2377 Style.AlignAfterOpenBracket = false;
2378 Style.AlignOperands = FormatStyle::OAS_DontAlign;
2379 Style.AlignTrailingComments = {};
2380 Style.AlignTrailingComments.Kind = FormatStyle::TCAS_Never;
2381 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
2382 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
2383 Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
2384 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
2385 Style.ColumnLimit = 0;
2386 Style.Cpp11BracedListStyle = FormatStyle::BLS_Block;
2387 Style.FixNamespaceComments = false;
2388 Style.IndentWidth = 4;
2389 Style.NamespaceIndentation = FormatStyle::NI_Inner;
2390 Style.ObjCBlockIndentWidth = 4;
2391 Style.ObjCSpaceAfterProperty = true;
2392 Style.PointerAlignment = FormatStyle::PAS_Left;
2393 Style.SpaceBeforeCpp11BracedList = true;
2394 Style.SpaceInEmptyBraces = FormatStyle::SIEB_Always;
2395 return Style;
2396}
2397
2399 FormatStyle Style = getLLVMStyle();
2400 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
2401 Style.BreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
2402 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
2403 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
2404 Style.BreakBeforeTernaryOperators = true;
2405 Style.ColumnLimit = 79;
2406 Style.Cpp11BracedListStyle = FormatStyle::BLS_Block;
2407 Style.FixNamespaceComments = false;
2408 Style.KeepFormFeed = true;
2409 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
2410 return Style;
2411}
2412
2415 Style.ColumnLimit = 120;
2416 Style.TabWidth = 4;
2417 Style.IndentWidth = 4;
2418 Style.UseTab = FormatStyle::UT_Never;
2419 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2420 Style.BraceWrapping.AfterClass = true;
2421 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2422 Style.BraceWrapping.AfterEnum = true;
2423 Style.BraceWrapping.AfterFunction = true;
2424 Style.BraceWrapping.AfterNamespace = true;
2425 Style.BraceWrapping.AfterObjCDeclaration = true;
2426 Style.BraceWrapping.AfterStruct = true;
2427 Style.BraceWrapping.AfterExternBlock = true;
2428 Style.BraceWrapping.BeforeCatch = true;
2429 Style.BraceWrapping.BeforeElse = true;
2430 Style.BraceWrapping.BeforeWhile = false;
2431 Style.PenaltyReturnTypeOnItsOwnLine = 1000;
2432 Style.AllowShortEnumsOnASingleLine = false;
2433 Style.AllowShortFunctionsOnASingleLine = FormatStyle::ShortFunctionStyle();
2434 Style.AllowShortCaseLabelsOnASingleLine = false;
2435 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
2436 Style.AllowShortLoopsOnASingleLine = false;
2437 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
2438 Style.BreakAfterReturnType = FormatStyle::RTBS_None;
2439 return Style;
2440}
2441
2443 FormatStyle Style = getLLVMStyle();
2444 Style.InsertBraces = true;
2445 Style.InsertNewlineAtEOF = true;
2446 Style.IntegerLiteralSeparator.Decimal = 3;
2447 Style.IntegerLiteralSeparator.DecimalMinDigitsInsert = 5;
2448 Style.LineEnding = FormatStyle::LE_LF;
2449 Style.RemoveBracesLLVM = true;
2450 Style.RemoveEmptyLinesInUnwrappedLines = true;
2451 Style.RemoveParentheses = FormatStyle::RPS_ReturnStatement;
2452 Style.RemoveSemicolon = true;
2453 return Style;
2454}
2455
2457 FormatStyle NoStyle = getLLVMStyle();
2458 NoStyle.DisableFormat = true;
2459 NoStyle.SortIncludes = {};
2461 return NoStyle;
2462}
2463
2465 FormatStyle *Style) {
2466 constexpr StringRef Prefix("inheritparentconfig=");
2467
2468 if (Name.equals_insensitive("llvm"))
2469 *Style = getLLVMStyle(Language);
2470 else if (Name.equals_insensitive("chromium"))
2471 *Style = getChromiumStyle(Language);
2472 else if (Name.equals_insensitive("mozilla"))
2473 *Style = getMozillaStyle();
2474 else if (Name.equals_insensitive("google"))
2475 *Style = getGoogleStyle(Language);
2476 else if (Name.equals_insensitive("webkit"))
2477 *Style = getWebKitStyle();
2478 else if (Name.equals_insensitive("gnu"))
2479 *Style = getGNUStyle();
2480 else if (Name.equals_insensitive("microsoft"))
2481 *Style = getMicrosoftStyle(Language);
2482 else if (Name.equals_insensitive("clang-format"))
2483 *Style = getClangFormatStyle();
2484 else if (Name.equals_insensitive("none"))
2485 *Style = getNoStyle();
2486 else if (Name.equals_insensitive(Prefix.drop_back()))
2487 Style->InheritConfig = "..";
2488 else if (Name.size() > Prefix.size() && Name.starts_with_insensitive(Prefix))
2489 Style->InheritConfig = Name.substr(Prefix.size());
2490 else
2491 return false;
2492
2493 Style->Language = Language;
2494 return true;
2495}
2496
2498 // If its empty then it means don't do anything.
2499 if (Style->QualifierOrder.empty())
2501
2502 // Ensure the list contains only currently valid qualifiers.
2503 for (const auto &Qualifier : Style->QualifierOrder) {
2504 if (Qualifier == "type")
2505 continue;
2506 auto token =
2508 if (token == tok::identifier)
2510 }
2511
2512 // Ensure the list is unique (no duplicates).
2513 std::set<std::string> UniqueQualifiers(Style->QualifierOrder.begin(),
2514 Style->QualifierOrder.end());
2515 if (Style->QualifierOrder.size() != UniqueQualifiers.size()) {
2516 LLVM_DEBUG(llvm::dbgs()
2517 << "Duplicate Qualifiers " << Style->QualifierOrder.size()
2518 << " vs " << UniqueQualifiers.size() << "\n");
2520 }
2521
2522 // Ensure the list has 'type' in it.
2523 if (!llvm::is_contained(Style->QualifierOrder, "type"))
2525
2526 return ParseError::Success;
2527}
2528
2529std::error_code parseConfiguration(llvm::MemoryBufferRef Config,
2530 FormatStyle *Style, bool AllowUnknownOptions,
2531 llvm::SourceMgr::DiagHandlerTy DiagHandler,
2532 void *DiagHandlerCtxt, bool IsDotHFile) {
2533 assert(Style);
2534 FormatStyle::LanguageKind Language = Style->Language;
2535 assert(Language != FormatStyle::LK_None);
2536 if (Config.getBuffer().trim().empty())
2538 Style->StyleSet.Clear();
2539 std::vector<FormatStyle> Styles;
2540 llvm::yaml::Input Input(Config, /*Ctxt=*/nullptr, DiagHandler,
2541 DiagHandlerCtxt);
2542 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
2543 // values for the fields, keys for which are missing from the configuration.
2544 // Mapping also uses the context to get the language to find the correct
2545 // base style.
2546 Input.setContext(Style);
2547 Input.setAllowUnknownKeys(AllowUnknownOptions);
2548 Input >> Styles;
2549 if (Input.error())
2550 return Input.error();
2551 if (Styles.empty())
2553
2554 const auto StyleCount = Styles.size();
2555
2556 // Start from the second style as (only) the first one may be the default.
2557 for (unsigned I = 1; I < StyleCount; ++I) {
2558 const auto Lang = Styles[I].Language;
2559 if (Lang == FormatStyle::LK_None)
2561 // Ensure that each language is configured at most once.
2562 for (unsigned J = 0; J < I; ++J) {
2563 if (Lang == Styles[J].Language) {
2564 LLVM_DEBUG(llvm::dbgs()
2565 << "Duplicate languages in the config file on positions "
2566 << J << " and " << I << '\n');
2568 }
2569 }
2570 }
2571
2572 int LanguagePos = -1; // Position of the style for Language.
2573 int CppPos = -1; // Position of the style for C++.
2574 int CPos = -1; // Position of the style for C.
2575
2576 // Search Styles for Language and store the positions of C++ and C styles in
2577 // case Language is not found.
2578 for (unsigned I = 0; I < StyleCount; ++I) {
2579 const auto Lang = Styles[I].Language;
2580 if (Lang == Language) {
2581 LanguagePos = I;
2582 break;
2583 }
2584 if (Lang == FormatStyle::LK_Cpp)
2585 CppPos = I;
2586 else if (Lang == FormatStyle::LK_C)
2587 CPos = I;
2588 }
2589
2590 // If Language is not found, use the default style if there is one. Otherwise,
2591 // use the C style for C++ .h files and for backward compatibility, the C++
2592 // style for .c files.
2593 if (LanguagePos < 0) {
2594 if (Styles[0].Language == FormatStyle::LK_None) // Default style.
2595 LanguagePos = 0;
2596 else if (IsDotHFile && Language == FormatStyle::LK_Cpp)
2597 LanguagePos = CPos;
2598 else if (!IsDotHFile && Language == FormatStyle::LK_C)
2599 LanguagePos = CppPos;
2600 if (LanguagePos < 0)
2602 }
2603
2604 for (const auto &S : llvm::reverse(llvm::drop_begin(Styles)))
2605 Style->StyleSet.Add(S);
2606
2607 *Style = Styles[LanguagePos];
2608
2609 if (LanguagePos == 0) {
2610 if (Style->Language == FormatStyle::LK_None) // Default style.
2611 Style->Language = Language;
2612 Style->StyleSet.Add(*Style);
2613 }
2614
2615 if (Style->InsertTrailingCommas != FormatStyle::TCS_None &&
2616 (Style->PackArguments.BinPack == FormatStyle::BPAS_BinPack ||
2617 Style->PackArguments.BinPack == FormatStyle::BPAS_UseBreakAfter)) {
2618 // See comment on FormatStyle::TSC_Wrapped.
2620 }
2621 if (Style->QualifierAlignment != FormatStyle::QAS_Leave)
2624}
2625
2626std::string configurationAsText(const FormatStyle &Style) {
2627 std::string Text;
2628 llvm::raw_string_ostream Stream(Text);
2629 llvm::yaml::Output Output(Stream);
2630 // We use the same mapping method for input and output, so we need a non-const
2631 // reference here.
2632 FormatStyle NonConstStyle = Style;
2633 expandPresetsBraceWrapping(NonConstStyle);
2634 expandPresetsSpaceBeforeParens(NonConstStyle);
2635 expandPresetsSpacesInParens(NonConstStyle);
2636 Output << NonConstStyle;
2637
2638 return Stream.str();
2639}
2640
2641std::optional<FormatStyle>
2643 if (!Styles)
2644 return std::nullopt;
2645 auto It = Styles->find(Language);
2646 if (It == Styles->end())
2647 return std::nullopt;
2648 FormatStyle Style = It->second;
2649 Style.StyleSet = *this;
2650 return Style;
2651}
2652
2654 assert(Style.Language != LK_None &&
2655 "Cannot add a style for LK_None to a StyleSet");
2656 assert(
2657 !Style.StyleSet.Styles &&
2658 "Cannot add a style associated with an existing StyleSet to a StyleSet");
2659 if (!Styles)
2660 Styles = std::make_shared<MapType>();
2661 (*Styles)[Style.Language] = std::move(Style);
2662}
2663
2664void FormatStyle::FormatStyleSet::Clear() { Styles.reset(); }
2665
2666std::optional<FormatStyle>
2670
2671namespace {
2672
2674 const SourceManager &SourceMgr, tooling::Replacements &Result,
2675 StringRef Text = "") {
2676 const auto &Tok = Token.Tok;
2677 SourceLocation Start;
2678 if (Next && Next->NewlinesBefore == 0 && Next->isNot(tok::eof)) {
2679 Start = Tok.getLocation();
2680 Next->WhitespaceRange = Token.WhitespaceRange;
2681 } else {
2682 Start = Token.WhitespaceRange.getBegin();
2683 }
2684 const auto &Range = CharSourceRange::getCharRange(Start, Tok.getEndLoc());
2685 cantFail(Result.add(tooling::Replacement(SourceMgr, Range, Text)));
2686}
2687
2688class ParensRemover : public TokenAnalyzer {
2689public:
2690 ParensRemover(const Environment &Env, const FormatStyle &Style)
2691 : TokenAnalyzer(Env, Style) {}
2692
2693 std::pair<tooling::Replacements, unsigned>
2694 analyze(TokenAnnotator &Annotator,
2695 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2696 FormatTokenLexer &Tokens) override {
2697 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2698 tooling::Replacements Result;
2699 removeParens(AnnotatedLines, Result);
2700 return {Result, 0};
2701 }
2702
2703private:
2704 void removeParens(SmallVectorImpl<AnnotatedLine *> &Lines,
2705 tooling::Replacements &Result) {
2706 const auto &SourceMgr = Env.getSourceManager();
2707 for (auto *Line : Lines) {
2708 if (!Line->Children.empty())
2709 removeParens(Line->Children, Result);
2710 if (!Line->Affected)
2711 continue;
2712 for (const auto *Token = Line->First; Token && !Token->Finalized;
2713 Token = Token->Next) {
2714 if (Token->Optional && Token->isOneOf(tok::l_paren, tok::r_paren))
2715 replaceToken(*Token, Token->Next, SourceMgr, Result, " ");
2716 }
2717 }
2718 }
2719};
2720
2721class BracesInserter : public TokenAnalyzer {
2722public:
2723 BracesInserter(const Environment &Env, const FormatStyle &Style)
2724 : TokenAnalyzer(Env, Style) {}
2725
2726 std::pair<tooling::Replacements, unsigned>
2727 analyze(TokenAnnotator &Annotator,
2728 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2729 FormatTokenLexer &Tokens) override {
2730 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2731 tooling::Replacements Result;
2732 insertBraces(AnnotatedLines, Result);
2733 return {Result, 0};
2734 }
2735
2736private:
2737 void insertBraces(SmallVectorImpl<AnnotatedLine *> &Lines,
2738 tooling::Replacements &Result) {
2739 const auto &SourceMgr = Env.getSourceManager();
2740 int OpeningBraceSurplus = 0;
2741 for (AnnotatedLine *Line : Lines) {
2742 if (!Line->Children.empty())
2743 insertBraces(Line->Children, Result);
2744 if (!Line->Affected && OpeningBraceSurplus == 0)
2745 continue;
2746 for (FormatToken *Token = Line->First; Token && !Token->Finalized;
2747 Token = Token->Next) {
2748 int BraceCount = Token->BraceCount;
2749 if (BraceCount == 0)
2750 continue;
2751 std::string Brace;
2752 if (BraceCount < 0) {
2753 assert(BraceCount == -1);
2754 // Keep the marker so that the parser doesn't mark the token again in
2755 // a later run.
2756 if (Token->LBraceInserted)
2757 continue;
2758 if (!Line->Affected)
2759 break;
2760 Brace = Token->is(tok::comment) ? "\n{" : "{";
2761 ++OpeningBraceSurplus;
2762 Token->LBraceInserted = true;
2763 } else {
2764 if (OpeningBraceSurplus == 0)
2765 break;
2766 if (OpeningBraceSurplus < BraceCount)
2767 BraceCount = OpeningBraceSurplus;
2768 Brace = '\n' + std::string(BraceCount, '}');
2769 OpeningBraceSurplus -= BraceCount;
2770 Token->BraceCount = 0;
2771 }
2772 const auto Start = Token->Tok.getEndLoc();
2773 cantFail(Result.add(tooling::Replacement(SourceMgr, Start, 0, Brace)));
2774 }
2775 }
2776 assert(OpeningBraceSurplus == 0);
2777 }
2778};
2779
2780class BracesRemover : public TokenAnalyzer {
2781public:
2782 BracesRemover(const Environment &Env, const FormatStyle &Style)
2783 : TokenAnalyzer(Env, Style) {}
2784
2785 std::pair<tooling::Replacements, unsigned>
2786 analyze(TokenAnnotator &Annotator,
2787 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2788 FormatTokenLexer &Tokens) override {
2789 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2790 tooling::Replacements Result;
2791 removeBraces(AnnotatedLines, Result);
2792 return {Result, 0};
2793 }
2794
2795private:
2796 void removeBraces(SmallVectorImpl<AnnotatedLine *> &Lines,
2797 tooling::Replacements &Result) {
2798 const auto &SourceMgr = Env.getSourceManager();
2799 const auto *End = Lines.end();
2800 for (const auto *I = Lines.begin(); I != End; ++I) {
2801 const auto &Line = *I;
2802 if (!Line->Children.empty())
2803 removeBraces(Line->Children, Result);
2804 if (!Line->Affected)
2805 continue;
2806 const auto *NextLine = I + 1 == End ? nullptr : I[1];
2807 for (const auto *Token = Line->First; Token && !Token->Finalized;
2808 Token = Token->Next) {
2809 if (!Token->Optional || Token->isNoneOf(tok::l_brace, tok::r_brace))
2810 continue;
2811 auto *Next = Token->Next;
2812 assert(Next || Token == Line->Last);
2813 if (!Next && NextLine)
2814 Next = NextLine->First;
2815 replaceToken(*Token, Next, SourceMgr, Result);
2816 }
2817 }
2818 }
2819};
2820
2821class SemiRemover : public TokenAnalyzer {
2822public:
2823 SemiRemover(const Environment &Env, const FormatStyle &Style)
2824 : TokenAnalyzer(Env, Style) {}
2825
2826 std::pair<tooling::Replacements, unsigned>
2827 analyze(TokenAnnotator &Annotator,
2828 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2829 FormatTokenLexer &Tokens) override {
2830 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2831 tooling::Replacements Result;
2832 removeSemi(Annotator, AnnotatedLines, Result);
2833 return {Result, 0};
2834 }
2835
2836private:
2837 void removeSemi(TokenAnnotator &Annotator,
2838 SmallVectorImpl<AnnotatedLine *> &Lines,
2839 tooling::Replacements &Result) {
2840 auto PrecededByFunctionRBrace = [](const FormatToken &Tok) {
2841 const auto *Prev = Tok.Previous;
2842 if (!Prev || Prev->isNot(tok::r_brace))
2843 return false;
2844 const auto *LBrace = Prev->MatchingParen;
2845 return LBrace && LBrace->is(TT_FunctionLBrace);
2846 };
2847 const auto &SourceMgr = Env.getSourceManager();
2848 const auto *End = Lines.end();
2849 for (const auto *I = Lines.begin(); I != End; ++I) {
2850 const auto &Line = *I;
2851 if (!Line->Children.empty())
2852 removeSemi(Annotator, Line->Children, Result);
2853 if (!Line->Affected)
2854 continue;
2855 Annotator.calculateFormattingInformation(*Line);
2856 const auto *NextLine = I + 1 == End ? nullptr : I[1];
2857 for (const auto *Token = Line->First; Token && !Token->Finalized;
2858 Token = Token->Next) {
2859 if (Token->isNot(tok::semi) ||
2860 (!Token->Optional && !PrecededByFunctionRBrace(*Token))) {
2861 continue;
2862 }
2863 auto *Next = Token->Next;
2864 assert(Next || Token == Line->Last);
2865 if (!Next && NextLine)
2866 Next = NextLine->First;
2867 replaceToken(*Token, Next, SourceMgr, Result);
2868 }
2869 }
2870 }
2871};
2872
2873class EnumTrailingCommaEditor : public TokenAnalyzer {
2874public:
2875 EnumTrailingCommaEditor(const Environment &Env, const FormatStyle &Style)
2876 : TokenAnalyzer(Env, Style) {}
2877
2878 std::pair<tooling::Replacements, unsigned>
2879 analyze(TokenAnnotator &Annotator,
2880 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2881 FormatTokenLexer &Tokens) override {
2882 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2883 tooling::Replacements Result;
2884 editEnumTrailingComma(AnnotatedLines, Result);
2885 return {Result, 0};
2886 }
2887
2888private:
2889 void editEnumTrailingComma(SmallVectorImpl<AnnotatedLine *> &Lines,
2890 tooling::Replacements &Result) {
2891 bool InEnumBraces = false;
2892 FormatToken *BeforeRBrace = nullptr;
2893 const auto &SourceMgr = Env.getSourceManager();
2894 for (auto *Line : Lines) {
2895 if (!Line->Children.empty())
2896 editEnumTrailingComma(Line->Children, Result);
2897 for (auto *Token = Line->First; Token && !Token->Finalized;
2898 Token = Token->Next) {
2899 if (Token->isNot(TT_EnumRBrace)) {
2900 if (Token->is(TT_EnumLBrace))
2901 InEnumBraces = true;
2902 else if (InEnumBraces && Token->isNot(tok::comment))
2903 BeforeRBrace = Line->Affected ? Token : nullptr;
2904 continue;
2905 }
2906 InEnumBraces = false;
2907 if (!BeforeRBrace || BeforeRBrace->HasEnumTrailingCommaHandled) {
2908 // Empty braces, or Line not affected, or already handled.
2909 continue;
2910 }
2911 if (BeforeRBrace->is(tok::comma)) {
2912 if (Style.EnumTrailingComma == FormatStyle::ETC_Remove)
2913 replaceToken(*BeforeRBrace, BeforeRBrace->Next, SourceMgr, Result);
2914 } else if (Style.EnumTrailingComma == FormatStyle::ETC_Insert) {
2915 cantFail(Result.add(tooling::Replacement(
2916 SourceMgr, BeforeRBrace->Tok.getEndLoc(), 0, ",")));
2917 }
2918 BeforeRBrace->HasEnumTrailingCommaHandled = true;
2919 BeforeRBrace = nullptr;
2920 }
2921 }
2922 }
2923};
2924
2925class JavaScriptRequoter : public TokenAnalyzer {
2926public:
2927 JavaScriptRequoter(const Environment &Env, const FormatStyle &Style)
2928 : TokenAnalyzer(Env, Style) {}
2929
2930 std::pair<tooling::Replacements, unsigned>
2931 analyze(TokenAnnotator &Annotator,
2932 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2933 FormatTokenLexer &Tokens) override {
2934 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2935 tooling::Replacements Result;
2936 requoteJSStringLiteral(AnnotatedLines, Result);
2937 return {Result, 0};
2938 }
2939
2940private:
2941 // Replaces double/single-quoted string literal as appropriate, re-escaping
2942 // the contents in the process.
2943 void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
2944 tooling::Replacements &Result) {
2945 for (AnnotatedLine *Line : Lines) {
2946 requoteJSStringLiteral(Line->Children, Result);
2947 if (!Line->Affected)
2948 continue;
2949 for (FormatToken *FormatTok = Line->First; FormatTok;
2950 FormatTok = FormatTok->Next) {
2951 StringRef Input = FormatTok->TokenText;
2952 if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
2953 // NB: testing for not starting with a double quote to avoid
2954 // breaking `template strings`.
2955 (Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
2956 !Input.starts_with("\"")) ||
2957 (Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
2958 !Input.starts_with("\'"))) {
2959 continue;
2960 }
2961
2962 // Change start and end quote.
2963 bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
2964 SourceLocation Start = FormatTok->Tok.getLocation();
2965 auto Replace = [&](SourceLocation Start, unsigned Length,
2966 StringRef ReplacementText) {
2967 auto Err = Result.add(tooling::Replacement(
2968 Env.getSourceManager(), Start, Length, ReplacementText));
2969 // FIXME: handle error. For now, print error message and skip the
2970 // replacement for release version.
2971 if (Err) {
2972 llvm::errs() << toString(std::move(Err)) << "\n";
2973 assert(false);
2974 }
2975 };
2976 Replace(Start, 1, IsSingle ? "'" : "\"");
2977 Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
2978 IsSingle ? "'" : "\"");
2979
2980 // Escape internal quotes.
2981 bool Escaped = false;
2982 for (size_t i = 1; i < Input.size() - 1; i++) {
2983 switch (Input[i]) {
2984 case '\\':
2985 if (!Escaped && i + 1 < Input.size() &&
2986 ((IsSingle && Input[i + 1] == '"') ||
2987 (!IsSingle && Input[i + 1] == '\''))) {
2988 // Remove this \, it's escaping a " or ' that no longer needs
2989 // escaping
2990 Replace(Start.getLocWithOffset(i), 1, "");
2991 continue;
2992 }
2993 Escaped = !Escaped;
2994 break;
2995 case '\"':
2996 case '\'':
2997 if (!Escaped && IsSingle == (Input[i] == '\'')) {
2998 // Escape the quote.
2999 Replace(Start.getLocWithOffset(i), 0, "\\");
3000 }
3001 Escaped = false;
3002 break;
3003 default:
3004 Escaped = false;
3005 break;
3006 }
3007 }
3008 }
3009 }
3010 }
3011};
3012
3013class Formatter : public TokenAnalyzer {
3014public:
3015 Formatter(const Environment &Env, const FormatStyle &Style,
3016 FormattingAttemptStatus *Status)
3017 : TokenAnalyzer(Env, Style), Status(Status) {}
3018
3019 std::pair<tooling::Replacements, unsigned>
3020 analyze(TokenAnnotator &Annotator,
3021 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3022 FormatTokenLexer &Tokens) override {
3023 tooling::Replacements Result;
3024 deriveLocalStyle(AnnotatedLines);
3025 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
3026 for (AnnotatedLine *Line : AnnotatedLines)
3027 Annotator.calculateFormattingInformation(*Line);
3028 Annotator.setCommentLineLevels(AnnotatedLines);
3029
3030 WhitespaceManager Whitespaces(
3031 Env.getSourceManager(), Style,
3032 Style.LineEnding > FormatStyle::LE_CRLF
3033 ? WhitespaceManager::inputUsesCRLF(
3034 Env.getSourceManager().getBufferData(Env.getFileID()),
3035 Style.LineEnding == FormatStyle::LE_DeriveCRLF)
3036 : Style.LineEnding == FormatStyle::LE_CRLF);
3037 ContinuationIndenter Indenter(Style, Tokens.getKeywords(),
3038 Env.getSourceManager(), Whitespaces, Encoding,
3039 BinPackInconclusiveFunctions);
3040 uint64_t Penalty =
3041 UnwrappedLineFormatter(&Indenter, &Whitespaces, Style,
3042 Tokens.getKeywords(), Env.getSourceManager(),
3043 Status)
3044 .format(AnnotatedLines, /*DryRun=*/false,
3045 /*AdditionalIndent=*/0,
3046 /*FixBadIndentation=*/false,
3047 /*FirstStartColumn=*/Env.getFirstStartColumn(),
3048 /*NextStartColumn=*/Env.getNextStartColumn(),
3049 /*LastStartColumn=*/Env.getLastStartColumn());
3050 for (const auto &R : Whitespaces.generateReplacements())
3051 if (Result.add(R))
3052 return std::make_pair(Result, 0);
3053 return std::make_pair(
3054 Result, static_cast<unsigned>(std::min<uint64_t>(Penalty, UINT_MAX)));
3055 }
3056
3057private:
3058 bool
3059 hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
3060 for (const AnnotatedLine *Line : Lines) {
3061 if (hasCpp03IncompatibleFormat(Line->Children))
3062 return true;
3063 for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
3064 if (!Tok->hasWhitespaceBefore()) {
3065 if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
3066 return true;
3067 if (Tok->is(TT_TemplateCloser) &&
3068 Tok->Previous->is(TT_TemplateCloser)) {
3069 return true;
3070 }
3071 }
3072 }
3073 }
3074 return false;
3075 }
3076
3077 int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
3078 int AlignmentDiff = 0;
3079
3080 for (const AnnotatedLine *Line : Lines) {
3081 AlignmentDiff += countVariableAlignments(Line->Children);
3082
3083 for (const auto *Tok = Line->getFirstNonComment(); Tok; Tok = Tok->Next) {
3084 if (Tok->isNot(TT_PointerOrReference))
3085 continue;
3086
3087 const auto *Prev = Tok->Previous;
3088 const bool PrecededByName = Prev && Prev->Tok.getIdentifierInfo();
3089 const bool SpaceBefore = Tok->hasWhitespaceBefore();
3090
3091 // e.g. `int **`, `int*&`, etc.
3092 while (Tok->Next && Tok->Next->is(TT_PointerOrReference))
3093 Tok = Tok->Next;
3094
3095 const auto *Next = Tok->Next;
3096 const bool FollowedByName = Next && Next->Tok.getIdentifierInfo();
3097 const bool SpaceAfter = Next && Next->hasWhitespaceBefore();
3098
3099 if ((!PrecededByName && !FollowedByName) ||
3100 // e.g. `int * i` or `int*i`
3101 (PrecededByName && FollowedByName && SpaceBefore == SpaceAfter)) {
3102 continue;
3103 }
3104
3105 if ((PrecededByName && SpaceBefore) ||
3106 (FollowedByName && !SpaceAfter)) {
3107 // Right alignment.
3108 ++AlignmentDiff;
3109 } else if ((PrecededByName && !SpaceBefore) ||
3110 (FollowedByName && SpaceAfter)) {
3111 // Left alignment.
3112 --AlignmentDiff;
3113 }
3114 }
3115 }
3116
3117 return AlignmentDiff;
3118 }
3119
3120 void
3121 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
3122 bool HasBinPackedFunction = false;
3123 bool HasOnePerLineFunction = false;
3124 for (AnnotatedLine *Line : AnnotatedLines) {
3125 if (!Line->First->Next)
3126 continue;
3127 FormatToken *Tok = Line->First->Next;
3128 while (Tok->Next) {
3129 if (Tok->is(PPK_BinPacked))
3130 HasBinPackedFunction = true;
3131 if (Tok->is(PPK_OnePerLine))
3132 HasOnePerLineFunction = true;
3133
3134 Tok = Tok->Next;
3135 }
3136 }
3137 if (Style.DerivePointerAlignment) {
3138 const auto NetRightCount = countVariableAlignments(AnnotatedLines);
3139 if (NetRightCount > 0)
3140 Style.PointerAlignment = FormatStyle::PAS_Right;
3141 else if (NetRightCount < 0)
3142 Style.PointerAlignment = FormatStyle::PAS_Left;
3143 Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
3144 }
3145 if (Style.Standard == FormatStyle::LS_Auto) {
3146 Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
3149 }
3150 BinPackInconclusiveFunctions =
3151 HasBinPackedFunction || !HasOnePerLineFunction;
3152 }
3153
3154 bool BinPackInconclusiveFunctions;
3155 FormattingAttemptStatus *Status;
3156};
3157
3158/// TrailingCommaInserter inserts trailing commas into container literals.
3159/// E.g.:
3160/// const x = [
3161/// 1,
3162/// ];
3163/// TrailingCommaInserter runs after formatting. To avoid causing a required
3164/// reformatting (and thus reflow), it never inserts a comma that'd exceed the
3165/// ColumnLimit.
3166///
3167/// Because trailing commas disable binpacking of arrays, TrailingCommaInserter
3168/// is conceptually incompatible with bin packing.
3169class TrailingCommaInserter : public TokenAnalyzer {
3170public:
3171 TrailingCommaInserter(const Environment &Env, const FormatStyle &Style)
3172 : TokenAnalyzer(Env, Style) {}
3173
3174 std::pair<tooling::Replacements, unsigned>
3175 analyze(TokenAnnotator &Annotator,
3176 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3177 FormatTokenLexer &Tokens) override {
3178 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
3179 tooling::Replacements Result;
3180 insertTrailingCommas(AnnotatedLines, Result);
3181 return {Result, 0};
3182 }
3183
3184private:
3185 /// Inserts trailing commas in [] and {} initializers if they wrap over
3186 /// multiple lines.
3187 void insertTrailingCommas(SmallVectorImpl<AnnotatedLine *> &Lines,
3188 tooling::Replacements &Result) {
3189 for (AnnotatedLine *Line : Lines) {
3190 insertTrailingCommas(Line->Children, Result);
3191 if (!Line->Affected)
3192 continue;
3193 for (FormatToken *FormatTok = Line->First; FormatTok;
3194 FormatTok = FormatTok->Next) {
3195 if (FormatTok->NewlinesBefore == 0)
3196 continue;
3197 FormatToken *Matching = FormatTok->MatchingParen;
3198 if (!Matching || !FormatTok->getPreviousNonComment())
3199 continue;
3200 if (!(FormatTok->is(tok::r_square) &&
3201 Matching->is(TT_ArrayInitializerLSquare)) &&
3202 !(FormatTok->is(tok::r_brace) && Matching->is(TT_DictLiteral))) {
3203 continue;
3204 }
3205 FormatToken *Prev = FormatTok->getPreviousNonComment();
3206 if (Prev->is(tok::comma) || Prev->is(tok::semi))
3207 continue;
3208 // getEndLoc is not reliably set during re-lexing, use text length
3209 // instead.
3210 SourceLocation Start =
3211 Prev->Tok.getLocation().getLocWithOffset(Prev->TokenText.size());
3212 // If inserting a comma would push the code over the column limit, skip
3213 // this location - it'd introduce an unstable formatting due to the
3214 // required reflow.
3215 unsigned ColumnNumber =
3216 Env.getSourceManager().getSpellingColumnNumber(Start);
3217 if (ColumnNumber > Style.ColumnLimit)
3218 continue;
3219 // Comma insertions cannot conflict with each other, and this pass has a
3220 // clean set of Replacements, so the operation below cannot fail.
3221 cantFail(Result.add(
3222 tooling::Replacement(Env.getSourceManager(), Start, 0, ",")));
3223 }
3224 }
3225 }
3226};
3227
3228// This class clean up the erroneous/redundant code around the given ranges in
3229// file.
3230class Cleaner : public TokenAnalyzer {
3231public:
3232 Cleaner(const Environment &Env, const FormatStyle &Style)
3233 : TokenAnalyzer(Env, Style),
3234 DeletedTokens(FormatTokenLess(Env.getSourceManager())) {}
3235
3236 // FIXME: eliminate unused parameters.
3237 std::pair<tooling::Replacements, unsigned>
3238 analyze(TokenAnnotator &Annotator,
3239 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3240 FormatTokenLexer &Tokens) override {
3241 // FIXME: in the current implementation the granularity of affected range
3242 // is an annotated line. However, this is not sufficient. Furthermore,
3243 // redundant code introduced by replacements does not necessarily
3244 // intercept with ranges of replacements that result in the redundancy.
3245 // To determine if some redundant code is actually introduced by
3246 // replacements(e.g. deletions), we need to come up with a more
3247 // sophisticated way of computing affected ranges.
3248 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
3249
3250 checkEmptyNamespace(AnnotatedLines);
3251
3252 for (auto *Line : AnnotatedLines)
3253 cleanupLine(Line);
3254
3255 return {generateFixes(), 0};
3256 }
3257
3258private:
3259 void cleanupLine(AnnotatedLine *Line) {
3260 for (auto *Child : Line->Children)
3261 cleanupLine(Child);
3262
3263 if (Line->Affected) {
3264 cleanupRight(Line->First, tok::comma, tok::comma);
3265 cleanupRight(Line->First, TT_CtorInitializerColon, tok::comma);
3266 cleanupRight(Line->First, tok::l_paren, tok::comma);
3267 cleanupLeft(Line->First, tok::comma, tok::r_paren);
3268 cleanupLeft(Line->First, TT_CtorInitializerComma, tok::l_brace);
3269 cleanupLeft(Line->First, TT_CtorInitializerColon, tok::l_brace);
3270 cleanupLeft(Line->First, TT_CtorInitializerColon, tok::equal);
3271 }
3272 }
3273
3274 bool containsOnlyComments(const AnnotatedLine &Line) {
3275 for (FormatToken *Tok = Line.First; Tok; Tok = Tok->Next)
3276 if (Tok->isNot(tok::comment))
3277 return false;
3278 return true;
3279 }
3280
3281 // Iterate through all lines and remove any empty (nested) namespaces.
3282 void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
3283 std::set<unsigned> DeletedLines;
3284 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
3285 auto &Line = *AnnotatedLines[i];
3286 if (Line.startsWithNamespace())
3287 checkEmptyNamespace(AnnotatedLines, i, i, DeletedLines);
3288 }
3289
3290 for (auto Line : DeletedLines) {
3291 FormatToken *Tok = AnnotatedLines[Line]->First;
3292 while (Tok) {
3293 deleteToken(Tok);
3294 Tok = Tok->Next;
3295 }
3296 }
3297 }
3298
3299 // The function checks if the namespace, which starts from \p CurrentLine, and
3300 // its nested namespaces are empty and delete them if they are empty. It also
3301 // sets \p NewLine to the last line checked.
3302 // Returns true if the current namespace is empty.
3303 bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3304 unsigned CurrentLine, unsigned &NewLine,
3305 std::set<unsigned> &DeletedLines) {
3306 unsigned InitLine = CurrentLine, End = AnnotatedLines.size();
3307 if (Style.BraceWrapping.AfterNamespace) {
3308 // If the left brace is in a new line, we should consume it first so that
3309 // it does not make the namespace non-empty.
3310 // FIXME: error handling if there is no left brace.
3311 if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
3312 NewLine = CurrentLine;
3313 return false;
3314 }
3315 } else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
3316 return false;
3317 }
3318 while (++CurrentLine < End) {
3319 if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
3320 break;
3321
3322 if (AnnotatedLines[CurrentLine]->startsWithNamespace()) {
3323 if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine,
3324 DeletedLines)) {
3325 return false;
3326 }
3327 CurrentLine = NewLine;
3328 continue;
3329 }
3330
3331 if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
3332 continue;
3333
3334 // If there is anything other than comments or nested namespaces in the
3335 // current namespace, the namespace cannot be empty.
3336 NewLine = CurrentLine;
3337 return false;
3338 }
3339
3340 NewLine = CurrentLine;
3341 if (CurrentLine >= End)
3342 return false;
3343
3344 // Check if the empty namespace is actually affected by changed ranges.
3345 if (!AffectedRangeMgr.affectsCharSourceRange(CharSourceRange::getCharRange(
3346 AnnotatedLines[InitLine]->First->Tok.getLocation(),
3347 AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc()))) {
3348 return false;
3349 }
3350
3351 for (unsigned i = InitLine; i <= CurrentLine; ++i)
3352 DeletedLines.insert(i);
3353
3354 return true;
3355 }
3356
3357 // Checks pairs {start, start->next},..., {end->previous, end} and deletes one
3358 // of the token in the pair if the left token has \p LK token kind and the
3359 // right token has \p RK token kind. If \p DeleteLeft is true, the left token
3360 // is deleted on match; otherwise, the right token is deleted.
3361 template <typename LeftKind, typename RightKind>
3362 void cleanupPair(FormatToken *Start, LeftKind LK, RightKind RK,
3363 bool DeleteLeft) {
3364 auto NextNotDeleted = [this](const FormatToken &Tok) -> FormatToken * {
3365 for (auto *Res = Tok.Next; Res; Res = Res->Next) {
3366 if (Res->isNot(tok::comment) &&
3367 DeletedTokens.find(Res) == DeletedTokens.end()) {
3368 return Res;
3369 }
3370 }
3371 return nullptr;
3372 };
3373 for (auto *Left = Start; Left;) {
3374 auto *Right = NextNotDeleted(*Left);
3375 if (!Right)
3376 break;
3377 if (Left->is(LK) && Right->is(RK)) {
3378 deleteToken(DeleteLeft ? Left : Right);
3379 for (auto *Tok = Left->Next; Tok && Tok != Right; Tok = Tok->Next)
3380 deleteToken(Tok);
3381 // If the right token is deleted, we should keep the left token
3382 // unchanged and pair it with the new right token.
3383 if (!DeleteLeft)
3384 continue;
3385 }
3386 Left = Right;
3387 }
3388 }
3389
3390 template <typename LeftKind, typename RightKind>
3391 void cleanupLeft(FormatToken *Start, LeftKind LK, RightKind RK) {
3392 cleanupPair(Start, LK, RK, /*DeleteLeft=*/true);
3393 }
3394
3395 template <typename LeftKind, typename RightKind>
3396 void cleanupRight(FormatToken *Start, LeftKind LK, RightKind RK) {
3397 cleanupPair(Start, LK, RK, /*DeleteLeft=*/false);
3398 }
3399
3400 // Delete the given token.
3401 inline void deleteToken(FormatToken *Tok) {
3402 if (Tok)
3403 DeletedTokens.insert(Tok);
3404 }
3405
3406 tooling::Replacements generateFixes() {
3407 tooling::Replacements Fixes;
3408 SmallVector<FormatToken *> Tokens;
3409 std::copy(DeletedTokens.begin(), DeletedTokens.end(),
3410 std::back_inserter(Tokens));
3411
3412 // Merge multiple continuous token deletions into one big deletion so that
3413 // the number of replacements can be reduced. This makes computing affected
3414 // ranges more efficient when we run reformat on the changed code.
3415 unsigned Idx = 0;
3416 while (Idx < Tokens.size()) {
3417 unsigned St = Idx, End = Idx;
3418 while ((End + 1) < Tokens.size() && Tokens[End]->Next == Tokens[End + 1])
3419 ++End;
3420 auto SR = CharSourceRange::getCharRange(Tokens[St]->Tok.getLocation(),
3421 Tokens[End]->Tok.getEndLoc());
3422 auto Err =
3423 Fixes.add(tooling::Replacement(Env.getSourceManager(), SR, ""));
3424 // FIXME: better error handling. for now just print error message and skip
3425 // for the release version.
3426 if (Err) {
3427 llvm::errs() << toString(std::move(Err)) << "\n";
3428 assert(false && "Fixes must not conflict!");
3429 }
3430 Idx = End + 1;
3431 }
3432
3433 return Fixes;
3434 }
3435
3436 // Class for less-than inequality comparason for the set `RedundantTokens`.
3437 // We store tokens in the order they appear in the translation unit so that
3438 // we do not need to sort them in `generateFixes()`.
3439 struct FormatTokenLess {
3440 FormatTokenLess(const SourceManager &SM) : SM(SM) {}
3441
3442 bool operator()(const FormatToken *LHS, const FormatToken *RHS) const {
3443 return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(),
3444 RHS->Tok.getLocation());
3445 }
3446 const SourceManager &SM;
3447 };
3448
3449 // Tokens to be deleted.
3450 std::set<FormatToken *, FormatTokenLess> DeletedTokens;
3451};
3452
3453class ObjCHeaderStyleGuesser : public TokenAnalyzer {
3454public:
3455 ObjCHeaderStyleGuesser(const Environment &Env, const FormatStyle &Style)
3456 : TokenAnalyzer(Env, Style), IsObjC(false) {}
3457
3458 std::pair<tooling::Replacements, unsigned>
3459 analyze(TokenAnnotator &Annotator,
3460 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3461 FormatTokenLexer &Tokens) override {
3462 assert(Style.Language == FormatStyle::LK_Cpp);
3463 IsObjC = guessIsObjC(Env.getSourceManager(), AnnotatedLines,
3464 Tokens.getKeywords());
3465 tooling::Replacements Result;
3466 return {Result, 0};
3467 }
3468
3469 bool isObjC() { return IsObjC; }
3470
3471private:
3472 static bool
3473 guessIsObjC(const SourceManager &SourceManager,
3474 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3475 const AdditionalKeywords &Keywords) {
3476 // Keep this array sorted, since we are binary searching over it.
3477 static constexpr llvm::StringLiteral FoundationIdentifiers[] = {
3478 "CGFloat",
3479 "CGPoint",
3480 "CGPointMake",
3481 "CGPointZero",
3482 "CGRect",
3483 "CGRectEdge",
3484 "CGRectInfinite",
3485 "CGRectMake",
3486 "CGRectNull",
3487 "CGRectZero",
3488 "CGSize",
3489 "CGSizeMake",
3490 "CGVector",
3491 "CGVectorMake",
3492 "FOUNDATION_EXPORT", // This is an alias for FOUNDATION_EXTERN.
3493 "FOUNDATION_EXTERN",
3494 "NSAffineTransform",
3495 "NSArray",
3496 "NSAttributedString",
3497 "NSBlockOperation",
3498 "NSBundle",
3499 "NSCache",
3500 "NSCalendar",
3501 "NSCharacterSet",
3502 "NSCountedSet",
3503 "NSData",
3504 "NSDataDetector",
3505 "NSDecimal",
3506 "NSDecimalNumber",
3507 "NSDictionary",
3508 "NSEdgeInsets",
3509 "NSError",
3510 "NSErrorDomain",
3511 "NSHashTable",
3512 "NSIndexPath",
3513 "NSIndexSet",
3514 "NSInteger",
3515 "NSInvocationOperation",
3516 "NSLocale",
3517 "NSMapTable",
3518 "NSMutableArray",
3519 "NSMutableAttributedString",
3520 "NSMutableCharacterSet",
3521 "NSMutableData",
3522 "NSMutableDictionary",
3523 "NSMutableIndexSet",
3524 "NSMutableOrderedSet",
3525 "NSMutableSet",
3526 "NSMutableString",
3527 "NSNumber",
3528 "NSNumberFormatter",
3529 "NSObject",
3530 "NSOperation",
3531 "NSOperationQueue",
3532 "NSOperationQueuePriority",
3533 "NSOrderedSet",
3534 "NSPoint",
3535 "NSPointerArray",
3536 "NSQualityOfService",
3537 "NSRange",
3538 "NSRect",
3539 "NSRegularExpression",
3540 "NSSet",
3541 "NSSize",
3542 "NSString",
3543 "NSTimeZone",
3544 "NSUInteger",
3545 "NSURL",
3546 "NSURLComponents",
3547 "NSURLQueryItem",
3548 "NSUUID",
3549 "NSValue",
3550 "NS_ASSUME_NONNULL_BEGIN",
3551 "UIImage",
3552 "UIView",
3553 };
3554 assert(llvm::is_sorted(FoundationIdentifiers));
3555
3556 for (auto *Line : AnnotatedLines) {
3557 if (Line->First && (Line->First->TokenText.starts_with("#") ||
3558 Line->First->TokenText == "__pragma" ||
3559 Line->First->TokenText == "_Pragma")) {
3560 continue;
3561 }
3562 for (const FormatToken *FormatTok = Line->First; FormatTok;
3563 FormatTok = FormatTok->Next) {
3564 if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) &&
3565 (FormatTok->isNot(tok::objc_not_keyword) ||
3566 FormatTok->isOneOf(tok::numeric_constant, tok::l_square,
3567 tok::l_brace))) ||
3568 (FormatTok->Tok.isAnyIdentifier() &&
3569 llvm::binary_search(FoundationIdentifiers,
3570 FormatTok->TokenText)) ||
3571 FormatTok->is(TT_ObjCStringLiteral) ||
3572 FormatTok->isOneOf(Keywords.kw_NS_CLOSED_ENUM, Keywords.kw_NS_ENUM,
3573 Keywords.kw_NS_ERROR_ENUM,
3574 Keywords.kw_NS_OPTIONS, TT_ObjCBlockLBrace,
3575 TT_ObjCBlockLParen, TT_ObjCDecl, TT_ObjCForIn,
3576 TT_ObjCMethodExpr, TT_ObjCMethodSpecifier,
3577 TT_ObjCProperty, TT_ObjCSelector)) {
3578 LLVM_DEBUG(llvm::dbgs()
3579 << "Detected ObjC at location "
3580 << FormatTok->Tok.getLocation().printToString(
3581 SourceManager)
3582 << " token: " << FormatTok->TokenText << " token type: "
3583 << getTokenTypeName(FormatTok->getType()) << "\n");
3584 return true;
3585 }
3586 }
3587 if (guessIsObjC(SourceManager, Line->Children, Keywords))
3588 return true;
3589 }
3590 return false;
3591 }
3592
3593 bool IsObjC;
3594};
3595
3596struct IncludeDirective {
3597 StringRef Filename;
3598 StringRef Text;
3599 unsigned Offset;
3600 int Category;
3601 int Priority;
3602};
3603
3604struct JavaImportDirective {
3605 StringRef Identifier;
3606 StringRef Text;
3607 unsigned Offset;
3608 SmallVector<StringRef> AssociatedCommentLines;
3609 bool IsStatic;
3610};
3611
3612} // end anonymous namespace
3613
3614// Determines whether 'Ranges' intersects with ('Start', 'End').
3615static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
3616 unsigned End) {
3617 for (const auto &Range : Ranges) {
3618 if (Range.getOffset() < End &&
3619 Range.getOffset() + Range.getLength() > Start) {
3620 return true;
3621 }
3622 }
3623 return false;
3624}
3625
3626// Returns a pair (Index, OffsetToEOL) describing the position of the cursor
3627// before sorting/deduplicating. Index is the index of the include under the
3628// cursor in the original set of includes. If this include has duplicates, it is
3629// the index of the first of the duplicates as the others are going to be
3630// removed. OffsetToEOL describes the cursor's position relative to the end of
3631// its current line.
3632// If `Cursor` is not on any #include, `Index` will be
3633// std::numeric_limits<unsigned>::max().
3634static std::pair<unsigned, unsigned>
3636 const ArrayRef<unsigned> &Indices, unsigned Cursor) {
3637 unsigned CursorIndex = std::numeric_limits<unsigned>::max();
3638 unsigned OffsetToEOL = 0;
3639 for (int i = 0, e = Includes.size(); i != e; ++i) {
3640 unsigned Start = Includes[Indices[i]].Offset;
3641 unsigned End = Start + Includes[Indices[i]].Text.size();
3642 if (!(Cursor >= Start && Cursor < End))
3643 continue;
3644 CursorIndex = Indices[i];
3645 OffsetToEOL = End - Cursor;
3646 // Put the cursor on the only remaining #include among the duplicate
3647 // #includes.
3648 while (--i >= 0 && Includes[CursorIndex].Text == Includes[Indices[i]].Text)
3649 CursorIndex = i;
3650 break;
3651 }
3652 return std::make_pair(CursorIndex, OffsetToEOL);
3653}
3654
3655// Replace all "\r\n" with "\n".
3656std::string replaceCRLF(const std::string &Code) {
3657 std::string NewCode;
3658 size_t Pos = 0, LastPos = 0;
3659
3660 do {
3661 Pos = Code.find("\r\n", LastPos);
3662 if (Pos == LastPos) {
3663 ++LastPos;
3664 continue;
3665 }
3666 if (Pos == std::string::npos) {
3667 NewCode += Code.substr(LastPos);
3668 break;
3669 }
3670 NewCode += Code.substr(LastPos, Pos - LastPos) + "\n";
3671 LastPos = Pos + 2;
3672 } while (Pos != std::string::npos);
3673
3674 return NewCode;
3675}
3676
3677// Sorts and deduplicate a block of includes given by 'Includes' alphabetically
3678// adding the necessary replacement to 'Replaces'. 'Includes' must be in strict
3679// source order.
3680// #include directives with the same text will be deduplicated, and only the
3681// first #include in the duplicate #includes remains. If the `Cursor` is
3682// provided and put on a deleted #include, it will be moved to the remaining
3683// #include in the duplicate #includes.
3684static void sortCppIncludes(const FormatStyle &Style,
3685 const ArrayRef<IncludeDirective> &Includes,
3686 ArrayRef<tooling::Range> Ranges, StringRef FileName,
3687 StringRef Code, tooling::Replacements &Replaces,
3688 unsigned *Cursor) {
3689 tooling::IncludeCategoryManager Categories(Style.IncludeStyle, FileName);
3690 const unsigned IncludesBeginOffset = Includes.front().Offset;
3691 const unsigned IncludesEndOffset =
3692 Includes.back().Offset + Includes.back().Text.size();
3693 const unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset;
3694 if (!affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset))
3695 return;
3697 llvm::to_vector<16>(llvm::seq<unsigned>(0, Includes.size()));
3698
3699 if (Style.SortIncludes.Enabled) {
3700 stable_sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
3701 if (Includes[LHSI].Priority != Includes[RHSI].Priority)
3702 return Includes[LHSI].Priority < Includes[RHSI].Priority;
3703
3704 auto LHSStem = Includes[LHSI].Filename;
3705 auto RHSStem = Includes[RHSI].Filename;
3706
3707 SmallString<128> LHSStemStorage, RHSStemStorage;
3708 if (Style.SortIncludes.IgnoreExtension) {
3709 LHSStemStorage = Includes[LHSI].Filename;
3710 RHSStemStorage = Includes[RHSI].Filename;
3711 llvm::sys::path::replace_extension(LHSStemStorage, "");
3712 llvm::sys::path::replace_extension(RHSStemStorage, "");
3713 LHSStem = LHSStemStorage;
3714 RHSStem = RHSStemStorage;
3715 }
3716
3717 std::string LHSStemLower, RHSStemLower;
3718 std::string LHSFilenameLower, RHSFilenameLower;
3719 if (Style.SortIncludes.IgnoreCase) {
3720 LHSStemLower = LHSStem.lower();
3721 RHSStemLower = RHSStem.lower();
3722 LHSFilenameLower = Includes[LHSI].Filename.lower();
3723 RHSFilenameLower = Includes[RHSI].Filename.lower();
3724 }
3725
3726 const auto Compare = Style.SortIncludes.Natural
3727 ? &StringRef::compare_numeric
3728 : &StringRef::compare;
3729
3730 while (Style.SortIncludes.FilesBeforeFolders) {
3731 auto [LHead, LTail] = LHSStem.split('/');
3732 auto [RHead, RTail] = RHSStem.split('/');
3733
3734 bool LIsFile = LTail.empty();
3735 bool RIsFile = RTail.empty();
3736
3737 // A file at this level sorts before a subdirectory at this level.
3738 if (LIsFile != RIsFile)
3739 return LIsFile;
3740
3741 // Both are leaf filenames — they are equal at this level, so we
3742 // can break out of the loop and compare the full filenames later.
3743 if (LIsFile)
3744 break;
3745
3746 // Both are directory components at this level — compare them.
3747 if (Style.SortIncludes.IgnoreCase) {
3748 int Cmp = std::invoke(Compare, StringRef(LHead.lower()),
3749 StringRef(RHead.lower()));
3750 if (Cmp != 0)
3751 return Cmp < 0;
3752 }
3753 if (int Cmp = std::invoke(Compare, LHead, RHead); Cmp != 0)
3754 return Cmp < 0;
3755
3756 // Directory components are equal; descend into the next level.
3757 LHSStem = LTail;
3758 RHSStem = RTail;
3759 }
3760
3761 if (Style.SortIncludes.IgnoreCase) {
3762 int Cmp = std::invoke(Compare, StringRef(LHSStemLower), RHSStemLower);
3763 if (Cmp != 0)
3764 return Cmp < 0;
3765 }
3766
3767 if (int Cmp = std::invoke(Compare, LHSStem, RHSStem); Cmp != 0)
3768 return Cmp < 0;
3769
3770 if (Style.SortIncludes.IgnoreCase) {
3771 int Cmp =
3772 std::invoke(Compare, StringRef(LHSFilenameLower), RHSFilenameLower);
3773 if (Cmp != 0)
3774 return Cmp < 0;
3775 }
3776 return std::invoke(Compare, Includes[LHSI].Filename,
3777 Includes[RHSI].Filename) < 0;
3778 });
3779 }
3780
3781 // The index of the include on which the cursor will be put after
3782 // sorting/deduplicating.
3783 unsigned CursorIndex;
3784 // The offset from cursor to the end of line.
3785 unsigned CursorToEOLOffset;
3786 if (Cursor) {
3787 std::tie(CursorIndex, CursorToEOLOffset) =
3788 FindCursorIndex(Includes, Indices, *Cursor);
3789 }
3790
3791 // Deduplicate #includes.
3792 Indices.erase(llvm::unique(Indices,
3793 [&](unsigned LHSI, unsigned RHSI) {
3794 return Includes[LHSI].Text.trim() ==
3795 Includes[RHSI].Text.trim();
3796 }),
3797 Indices.end());
3798
3799 int CurrentCategory = Includes.front().Category;
3800 const auto TopLevelDirectory = [](StringRef Filename) {
3801 Filename = Filename.drop_front(); // Strip leading '"' or '<'.
3802 const size_t SlashPos = Filename.find('/');
3803 return SlashPos == StringRef::npos ? StringRef()
3804 : Filename.take_front(SlashPos);
3805 };
3806 StringRef CurrentDirectory = TopLevelDirectory(Includes.front().Filename);
3807 const auto DirectoryChanged = [&](StringRef Filename) {
3808 const StringRef Directory = TopLevelDirectory(Filename);
3809 return Style.SortIncludes.IgnoreCase
3810 ? !CurrentDirectory.equals_insensitive(Directory)
3811 : CurrentDirectory != Directory;
3812 };
3813
3814 // If the #includes are out of order, we generate a single replacement fixing
3815 // the entire block. Otherwise, no replacement is generated.
3816 // In case Style.IncldueStyle.IncludeBlocks != IBS_Preserve, this check is not
3817 // enough as additional newlines might be added or removed across #include
3818 // blocks. This we handle below by generating the updated #include blocks and
3819 // comparing it to the original.
3820 if (Indices.size() == Includes.size() && is_sorted(Indices) &&
3821 Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Preserve) {
3822 return;
3823 }
3824
3825 const auto OldCursor = Cursor ? *Cursor : 0;
3826 std::string result;
3827 for (unsigned Index : Indices) {
3828 if (!result.empty()) {
3829 result += "\n";
3830 if (Style.IncludeStyle.IncludeBlocks ==
3832 CurrentCategory != Includes[Index].Category) {
3833 result += "\n";
3834 } else if (Style.IncludeStyle.IncludeBlocks ==
3836 (CurrentCategory != Includes[Index].Category ||
3837 DirectoryChanged(Includes[Index].Filename))) {
3838 result += "\n";
3839 }
3840 }
3841 result += Includes[Index].Text;
3842 if (Cursor && CursorIndex == Index)
3843 *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
3844 CurrentCategory = Includes[Index].Category;
3845 CurrentDirectory = TopLevelDirectory(Includes[Index].Filename);
3846 }
3847
3848 if (Cursor && *Cursor >= IncludesEndOffset)
3849 *Cursor += result.size() - IncludesBlockSize;
3850
3851 // If the #includes are out of order, we generate a single replacement fixing
3852 // the entire range of blocks. Otherwise, no replacement is generated.
3853 if (replaceCRLF(result) == replaceCRLF(std::string(Code.substr(
3854 IncludesBeginOffset, IncludesBlockSize)))) {
3855 if (Cursor)
3856 *Cursor = OldCursor;
3857 return;
3858 }
3859
3860 auto Err = Replaces.add(tooling::Replacement(
3861 FileName, Includes.front().Offset, IncludesBlockSize, result));
3862 // FIXME: better error handling. For now, just skip the replacement for the
3863 // release version.
3864 if (Err) {
3865 llvm::errs() << toString(std::move(Err)) << "\n";
3866 assert(false);
3867 }
3868}
3869
3872 StringRef FileName,
3873 tooling::Replacements &Replaces,
3874 unsigned *Cursor) {
3875 unsigned Prev = llvm::StringSwitch<size_t>(Code)
3876 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
3877 .Default(0);
3878 unsigned SearchFrom = 0;
3880 SmallVector<IncludeDirective, 16> IncludesInBlock;
3881
3882 // In compiled files, consider the first #include to be the main #include of
3883 // the file if it is not a system #include. This ensures that the header
3884 // doesn't have hidden dependencies
3885 // (http://llvm.org/docs/CodingStandards.html#include-style).
3886 //
3887 // FIXME: Do some validation, e.g. edit distance of the base name, to fix
3888 // cases where the first #include is unlikely to be the main header.
3889 tooling::IncludeCategoryManager Categories(Style.IncludeStyle, FileName);
3890 bool FirstIncludeBlock = true;
3891 bool MainIncludeFound = false;
3892 bool FormattingOff = false;
3893
3894 // '[' must be the first and '-' the last character inside [...].
3895 llvm::Regex RawStringRegex(
3896 "R\"([][A-Za-z0-9_{}#<>%:;.?*+/^&\\$|~!=,'-]*)\\(");
3897 SmallVector<StringRef, 2> RawStringMatches;
3898 std::string RawStringTermination = ")\"";
3899
3900 for (const auto Size = Code.size(); SearchFrom < Size;) {
3901 size_t Pos = SearchFrom;
3902 if (Code[SearchFrom] != '\n') {
3903 do { // Search for the first newline while skipping line splices.
3904 ++Pos;
3905 Pos = Code.find('\n', Pos);
3906 } while (Pos != StringRef::npos && Code[Pos - 1] == '\\');
3907 }
3908
3909 StringRef Line =
3910 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
3911
3912 StringRef Trimmed = Line.trim();
3913
3914 // #includes inside raw string literals need to be ignored.
3915 // or we will sort the contents of the string.
3916 // Skip past until we think we are at the rawstring literal close.
3917 if (RawStringRegex.match(Trimmed, &RawStringMatches)) {
3918 std::string CharSequence = RawStringMatches[1].str();
3919 RawStringTermination = ")" + CharSequence + "\"";
3920 FormattingOff = true;
3921 }
3922
3923 if (Trimmed.contains(RawStringTermination))
3924 FormattingOff = false;
3925
3926 bool IsBlockComment = false;
3927
3928 if (isClangFormatOff(Trimmed)) {
3929 FormattingOff = true;
3930 } else if (isClangFormatOn(Trimmed)) {
3931 FormattingOff = false;
3932 } else if (Trimmed.starts_with("/*")) {
3933 IsBlockComment = true;
3934 Pos = Code.find("*/", SearchFrom + 2);
3935 }
3936
3937 const bool EmptyLineSkipped =
3938 Trimmed.empty() &&
3939 (Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Merge ||
3940 Style.IncludeStyle.IncludeBlocks ==
3942 Style.IncludeStyle.IncludeBlocks ==
3944
3945 bool MergeWithNextLine = Trimmed.ends_with("\\");
3946 if (!FormattingOff && !MergeWithNextLine) {
3947 if (!IsBlockComment &&
3948 tooling::HeaderIncludes::IncludeRegex.match(Trimmed, &Matches)) {
3949 StringRef IncludeName = Matches[2];
3950 if (Trimmed.contains("/*") && !Trimmed.contains("*/")) {
3951 // #include with a start of a block comment, but without the end.
3952 // Need to keep all the lines until the end of the comment together.
3953 // FIXME: This is somehow simplified check that probably does not work
3954 // correctly if there are multiple comments on a line.
3955 Pos = Code.find("*/", SearchFrom);
3956 Line = Code.substr(
3957 Prev, (Pos != StringRef::npos ? Pos + 2 : Code.size()) - Prev);
3958 }
3959 int Category = Categories.getIncludePriority(
3960 IncludeName,
3961 /*CheckMainHeader=*/!MainIncludeFound && FirstIncludeBlock);
3962 int Priority = Categories.getSortIncludePriority(
3963 IncludeName, !MainIncludeFound && FirstIncludeBlock);
3964 if (Category == 0)
3965 MainIncludeFound = true;
3966 IncludesInBlock.push_back(
3967 {IncludeName, Line, Prev, Category, Priority});
3968 } else if (!IncludesInBlock.empty() && !EmptyLineSkipped) {
3969 sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Code,
3970 Replaces, Cursor);
3971 IncludesInBlock.clear();
3972 if (Trimmed.starts_with("#pragma hdrstop")) // Precompiled headers.
3973 FirstIncludeBlock = true;
3974 else
3975 FirstIncludeBlock = false;
3976 }
3977 }
3978 if (Pos == StringRef::npos || Pos + 1 == Code.size())
3979 break;
3980
3981 if (!MergeWithNextLine)
3982 Prev = Pos + 1;
3983 SearchFrom = Pos + 1;
3984 }
3985 if (!IncludesInBlock.empty()) {
3986 sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Code, Replaces,
3987 Cursor);
3988 }
3989 return Replaces;
3990}
3991
3992// Returns group number to use as a first order sort on imports. Gives
3993// std::numeric_limits<unsigned>::max() if the import does not match any given
3994// groups.
3995static unsigned findJavaImportGroup(const FormatStyle &Style,
3996 StringRef ImportIdentifier) {
3997 unsigned LongestMatchIndex = std::numeric_limits<unsigned>::max();
3998 unsigned LongestMatchLength = 0;
3999 for (unsigned I = 0; I < Style.JavaImportGroups.size(); I++) {
4000 const std::string &GroupPrefix = Style.JavaImportGroups[I];
4001 if (ImportIdentifier.starts_with(GroupPrefix) &&
4002 GroupPrefix.length() > LongestMatchLength) {
4003 LongestMatchIndex = I;
4004 LongestMatchLength = GroupPrefix.length();
4005 }
4006 }
4007 return LongestMatchIndex;
4008}
4009
4010// Sorts and deduplicates a block of includes given by 'Imports' based on
4011// JavaImportGroups, then adding the necessary replacement to 'Replaces'.
4012// Import declarations with the same text will be deduplicated. Between each
4013// import group, a newline is inserted, and within each import group, a
4014// lexicographic sort based on ASCII value is performed.
4015static void sortJavaImports(const FormatStyle &Style,
4016 const ArrayRef<JavaImportDirective> &Imports,
4017 ArrayRef<tooling::Range> Ranges, StringRef FileName,
4018 StringRef Code, tooling::Replacements &Replaces) {
4019 unsigned ImportsBeginOffset = Imports.front().Offset;
4020 unsigned ImportsEndOffset =
4021 Imports.back().Offset + Imports.back().Text.size();
4022 unsigned ImportsBlockSize = ImportsEndOffset - ImportsBeginOffset;
4023 if (!affectsRange(Ranges, ImportsBeginOffset, ImportsEndOffset))
4024 return;
4025
4027 llvm::to_vector<16>(llvm::seq<unsigned>(0, Imports.size()));
4029 JavaImportGroups.reserve(Imports.size());
4030 for (const JavaImportDirective &Import : Imports)
4031 JavaImportGroups.push_back(findJavaImportGroup(Style, Import.Identifier));
4032
4033 bool StaticImportAfterNormalImport =
4034 Style.SortJavaStaticImport == FormatStyle::SJSIO_After;
4035 sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
4036 // Negating IsStatic to push static imports above non-static imports.
4037 return std::make_tuple(!Imports[LHSI].IsStatic ^
4038 StaticImportAfterNormalImport,
4039 JavaImportGroups[LHSI], Imports[LHSI].Identifier) <
4040 std::make_tuple(!Imports[RHSI].IsStatic ^
4041 StaticImportAfterNormalImport,
4042 JavaImportGroups[RHSI], Imports[RHSI].Identifier);
4043 });
4044
4045 // Deduplicate imports.
4046 Indices.erase(llvm::unique(Indices,
4047 [&](unsigned LHSI, unsigned RHSI) {
4048 return Imports[LHSI].Text == Imports[RHSI].Text;
4049 }),
4050 Indices.end());
4051
4052 bool CurrentIsStatic = Imports[Indices.front()].IsStatic;
4053 unsigned CurrentImportGroup = JavaImportGroups[Indices.front()];
4054
4055 std::string result;
4056 for (unsigned Index : Indices) {
4057 if (!result.empty()) {
4058 result += "\n";
4059 if (CurrentIsStatic != Imports[Index].IsStatic ||
4060 CurrentImportGroup != JavaImportGroups[Index]) {
4061 result += "\n";
4062 }
4063 }
4064 for (StringRef CommentLine : Imports[Index].AssociatedCommentLines) {
4065 result += CommentLine;
4066 result += "\n";
4067 }
4068 result += Imports[Index].Text;
4069 CurrentIsStatic = Imports[Index].IsStatic;
4070 CurrentImportGroup = JavaImportGroups[Index];
4071 }
4072
4073 // If the imports are out of order, we generate a single replacement fixing
4074 // the entire block. Otherwise, no replacement is generated.
4075 if (replaceCRLF(result) == replaceCRLF(std::string(Code.substr(
4076 Imports.front().Offset, ImportsBlockSize)))) {
4077 return;
4078 }
4079
4080 auto Err = Replaces.add(tooling::Replacement(FileName, Imports.front().Offset,
4081 ImportsBlockSize, result));
4082 // FIXME: better error handling. For now, just skip the replacement for the
4083 // release version.
4084 if (Err) {
4085 llvm::errs() << toString(std::move(Err)) << "\n";
4086 assert(false);
4087 }
4088}
4089
4090namespace {
4091
4092constexpr StringRef
4093 JavaImportRegexPattern("^import[\t ]+(static[\t ]*)?([^\t ]*)[\t ]*;");
4094
4095constexpr StringRef JavaPackageRegexPattern("^package[\t ]");
4096
4097} // anonymous namespace
4098
4101 StringRef FileName,
4102 tooling::Replacements &Replaces) {
4103 unsigned Prev = 0;
4104 bool HasImport = false;
4105 llvm::Regex ImportRegex(JavaImportRegexPattern);
4106 llvm::Regex PackageRegex(JavaPackageRegexPattern);
4109 SmallVector<StringRef> AssociatedCommentLines;
4110
4111 for (bool FormattingOff = false;;) {
4112 auto Pos = Code.find('\n', Prev);
4113 auto GetLine = [&] {
4114 return Code.substr(Prev,
4115 (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
4116 };
4117 StringRef Line = GetLine();
4118
4119 StringRef Trimmed = Line.trim();
4120 if (Trimmed.empty() || PackageRegex.match(Trimmed)) {
4121 // Skip empty line and package statement.
4122 } else if (isClangFormatOff(Trimmed)) {
4123 FormattingOff = true;
4124 } else if (isClangFormatOn(Trimmed)) {
4125 FormattingOff = false;
4126 } else if (Trimmed.starts_with("//")) {
4127 // Associating comments within the imports with the nearest import below.
4128 if (HasImport)
4129 AssociatedCommentLines.push_back(Line);
4130 } else if (Trimmed.starts_with("/*")) {
4131 Pos = Code.find("*/", Pos + 2);
4132 if (Pos != StringRef::npos)
4133 Pos = Code.find('\n', Pos + 2);
4134 if (HasImport) {
4135 // Extend `Line` for a multiline comment to include all lines the
4136 // comment spans.
4137 Line = GetLine();
4138 AssociatedCommentLines.push_back(Line);
4139 }
4140 } else if (ImportRegex.match(Trimmed, &Matches)) {
4141 if (FormattingOff) {
4142 // If at least one import line has formatting turned off, turn off
4143 // formatting entirely.
4144 return Replaces;
4145 }
4146 StringRef Static = Matches[1];
4147 StringRef Identifier = Matches[2];
4148 bool IsStatic = false;
4149 if (Static.contains("static"))
4150 IsStatic = true;
4151 ImportsInBlock.push_back(
4152 {Identifier, Line, Prev, AssociatedCommentLines, IsStatic});
4153 HasImport = true;
4154 AssociatedCommentLines.clear();
4155 } else {
4156 // `Trimmed` is neither empty, nor a comment or a package/import
4157 // statement.
4158 break;
4159 }
4160 if (Pos == StringRef::npos || Pos + 1 == Code.size())
4161 break;
4162 Prev = Pos + 1;
4163 }
4164 if (HasImport)
4165 sortJavaImports(Style, ImportsInBlock, Ranges, FileName, Code, Replaces);
4166 return Replaces;
4167}
4168
4169bool isMpegTS(StringRef Code) {
4170 // MPEG transport streams use the ".ts" file extension. clang-format should
4171 // not attempt to format those. MPEG TS' frame format starts with 0x47 every
4172 // 189 bytes - detect that and return.
4173 return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
4174}
4175
4176bool isLikelyXml(StringRef Code) { return Code.ltrim().starts_with("<"); }
4177
4180 StringRef FileName, unsigned *Cursor) {
4181 tooling::Replacements Replaces;
4182 if (!Style.SortIncludes.Enabled || Style.DisableFormat)
4183 return Replaces;
4184 if (isLikelyXml(Code))
4185 return Replaces;
4186 if (Style.isJavaScript()) {
4187 if (isMpegTS(Code))
4188 return Replaces;
4189 return sortJavaScriptImports(Style, Code, Ranges, FileName);
4190 }
4191 if (Style.isJava())
4192 return sortJavaImports(Style, Code, Ranges, FileName, Replaces);
4193 if (Style.isCpp())
4194 sortCppIncludes(Style, Code, Ranges, FileName, Replaces, Cursor);
4195 return Replaces;
4196}
4197
4198template <typename T>
4200processReplacements(T ProcessFunc, StringRef Code,
4201 const tooling::Replacements &Replaces,
4202 const FormatStyle &Style) {
4203 if (Replaces.empty())
4204 return tooling::Replacements();
4205
4206 auto NewCode = applyAllReplacements(Code, Replaces);
4207 if (!NewCode)
4208 return NewCode.takeError();
4209 std::vector<tooling::Range> ChangedRanges = Replaces.getAffectedRanges();
4210 StringRef FileName = Replaces.begin()->getFilePath();
4211
4212 tooling::Replacements FormatReplaces =
4213 ProcessFunc(Style, *NewCode, ChangedRanges, FileName);
4214
4215 return Replaces.merge(FormatReplaces);
4216}
4217
4219formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
4220 const FormatStyle &Style) {
4221 // We need to use lambda function here since there are two versions of
4222 // `sortIncludes`.
4223 auto SortIncludes = [](const FormatStyle &Style, StringRef Code,
4224 std::vector<tooling::Range> Ranges,
4225 StringRef FileName) -> tooling::Replacements {
4226 return sortIncludes(Style, Code, Ranges, FileName);
4227 };
4228 auto SortedReplaces =
4229 processReplacements(SortIncludes, Code, Replaces, Style);
4230 if (!SortedReplaces)
4231 return SortedReplaces.takeError();
4232
4233 // We need to use lambda function here since there are two versions of
4234 // `reformat`.
4235 auto Reformat = [](const FormatStyle &Style, StringRef Code,
4236 std::vector<tooling::Range> Ranges,
4237 StringRef FileName) -> tooling::Replacements {
4238 return reformat(Style, Code, Ranges, FileName);
4239 };
4240 return processReplacements(Reformat, Code, *SortedReplaces, Style);
4241}
4242
4243namespace {
4244
4245inline bool isHeaderInsertion(const tooling::Replacement &Replace) {
4246 return Replace.getOffset() == std::numeric_limits<unsigned>::max() &&
4247 Replace.getLength() == 0 &&
4249 Replace.getReplacementText());
4250}
4251
4252inline bool isHeaderDeletion(const tooling::Replacement &Replace) {
4253 return Replace.getOffset() == std::numeric_limits<unsigned>::max() &&
4254 Replace.getLength() == 1;
4255}
4256
4257// FIXME: insert empty lines between newly created blocks.
4258tooling::Replacements
4259fixCppIncludeInsertions(StringRef Code, const tooling::Replacements &Replaces,
4260 const FormatStyle &Style) {
4261 if (!Style.isCpp())
4262 return Replaces;
4263
4264 tooling::Replacements HeaderInsertions;
4265 std::set<StringRef> HeadersToDelete;
4266 tooling::Replacements Result;
4267 for (const auto &R : Replaces) {
4268 if (isHeaderInsertion(R)) {
4269 // Replacements from \p Replaces must be conflict-free already, so we can
4270 // simply consume the error.
4271 consumeError(HeaderInsertions.add(R));
4272 } else if (isHeaderDeletion(R)) {
4273 HeadersToDelete.insert(R.getReplacementText());
4274 } else if (R.getOffset() == std::numeric_limits<unsigned>::max()) {
4275 llvm::errs() << "Insertions other than header #include insertion are "
4276 "not supported! "
4277 << R.getReplacementText() << "\n";
4278 } else {
4279 consumeError(Result.add(R));
4280 }
4281 }
4282 if (HeaderInsertions.empty() && HeadersToDelete.empty())
4283 return Replaces;
4284
4285 StringRef FileName = Replaces.begin()->getFilePath();
4286 tooling::HeaderIncludes Includes(FileName, Code, Style.IncludeStyle);
4287
4288 for (const auto &Header : HeadersToDelete) {
4289 tooling::Replacements Replaces =
4290 Includes.remove(Header.trim("\"<>"), Header.starts_with("<"));
4291 for (const auto &R : Replaces) {
4292 auto Err = Result.add(R);
4293 if (Err) {
4294 // Ignore the deletion on conflict.
4295 llvm::errs() << "Failed to add header deletion replacement for "
4296 << Header << ": " << toString(std::move(Err)) << "\n";
4297 }
4298 }
4299 }
4300
4301 SmallVector<StringRef, 4> Matches;
4302 SmallVector<tooling::HeaderIncludes::HeaderToInsert, 4> HeadersToInsert;
4303 for (const auto &R : HeaderInsertions) {
4304 auto IncludeDirective = R.getReplacementText();
4305 bool Matched =
4306 tooling::HeaderIncludes::IncludeRegex.match(IncludeDirective, &Matches);
4307 assert(Matched && "Header insertion replacement must have replacement text "
4308 "'#include ...'");
4309 (void)Matched;
4310 auto IncludeName = Matches[2];
4311 HeadersToInsert.emplace_back(IncludeName,
4313 }
4314 for (const auto &Replace : Includes.insert(HeadersToInsert)) {
4315 auto Err = Result.add(Replace);
4316 if (Err) {
4317 consumeError(std::move(Err));
4318 unsigned NewOffset = Result.getShiftedCodePosition(Replace.getOffset());
4319 auto Shifted = tooling::Replacement(FileName, NewOffset, 0,
4320 Replace.getReplacementText());
4321 Result = Result.merge(tooling::Replacements(Shifted));
4322 }
4323 }
4324 return Result;
4325}
4326
4327} // anonymous namespace
4328
4329Expected<tooling::Replacements>
4330cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
4331 const FormatStyle &Style) {
4332 // We need to use lambda function here since there are two versions of
4333 // `cleanup`.
4334 auto Cleanup = [](const FormatStyle &Style, StringRef Code,
4336 StringRef FileName) -> tooling::Replacements {
4337 return cleanup(Style, Code, Ranges, FileName);
4338 };
4339 // Make header insertion replacements insert new headers into correct blocks.
4340 tooling::Replacements NewReplaces =
4341 fixCppIncludeInsertions(Code, Replaces, Style);
4342 return cantFail(processReplacements(Cleanup, Code, NewReplaces, Style));
4343}
4344
4345namespace internal {
4346std::pair<tooling::Replacements, unsigned>
4347reformat(const FormatStyle &Style, StringRef Code,
4348 ArrayRef<tooling::Range> Ranges, unsigned FirstStartColumn,
4349 unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName,
4350 FormattingAttemptStatus *Status) {
4351 FormatStyle Expanded = Style;
4355
4356 // These are handled by separate passes.
4357 Expanded.InsertBraces = false;
4358 Expanded.RemoveBracesLLVM = false;
4360 Expanded.RemoveSemicolon = false;
4361
4362 // Make some sanity adjustments.
4363 switch (Expanded.RequiresClausePosition) {
4366 Expanded.IndentRequiresClause = false;
4367 break;
4368 default:
4369 break;
4370 }
4371 if (Expanded.BraceWrapping.AfterEnum)
4372 Expanded.AllowShortEnumsOnASingleLine = false;
4373
4374 if (Expanded.DisableFormat)
4375 return {tooling::Replacements(), 0};
4376 if (isLikelyXml(Code))
4377 return {tooling::Replacements(), 0};
4378 if (Expanded.isJavaScript() && isMpegTS(Code))
4379 return {tooling::Replacements(), 0};
4380
4381 // JSON only needs the formatting passing.
4382 if (Style.isJson()) {
4383 std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
4384 auto Env = Environment::make(Code, FileName, Ranges, FirstStartColumn,
4385 NextStartColumn, LastStartColumn);
4386 if (!Env)
4387 return {};
4388 // Perform the actual formatting pass.
4389 tooling::Replacements Replaces =
4390 Formatter(*Env, Style, Status).process().first;
4391 // add a replacement to remove the "x = " from the result.
4392 if (Code.starts_with("x = ")) {
4393 Replaces = Replaces.merge(
4395 }
4396 // apply the reformatting changes and the removal of "x = ".
4397 if (applyAllReplacements(Code, Replaces))
4398 return {Replaces, 0};
4399 return {tooling::Replacements(), 0};
4400 }
4401
4402 auto Env = Environment::make(Code, FileName, Ranges, FirstStartColumn,
4403 NextStartColumn, LastStartColumn);
4404 if (!Env)
4405 return {};
4406
4408 const Environment &)>
4410
4412
4413 Passes.emplace_back([&](const Environment &Env) {
4414 return IntegerLiteralSeparatorFixer().process(Env, Expanded);
4415 });
4416
4417 Passes.emplace_back([&](const Environment &Env) {
4418 return NumericLiteralCaseFixer().process(Env, Expanded);
4419 });
4420
4421 if (Style.isCpp()) {
4422 if (Style.QualifierAlignment != FormatStyle::QAS_Leave)
4423 addQualifierAlignmentFixerPasses(Expanded, Passes);
4424
4425 if (Style.RemoveParentheses != FormatStyle::RPS_Leave) {
4426 FormatStyle S = Expanded;
4427 S.RemoveParentheses = Style.RemoveParentheses;
4428 Passes.emplace_back([&, S = std::move(S)](const Environment &Env) {
4429 return ParensRemover(Env, S).process(/*SkipAnnotation=*/true);
4430 });
4431 }
4432
4433 if (Style.InsertBraces) {
4434 FormatStyle S = Expanded;
4435 S.InsertBraces = true;
4436 Passes.emplace_back([&, S = std::move(S)](const Environment &Env) {
4437 return BracesInserter(Env, S).process(/*SkipAnnotation=*/true);
4438 });
4439 }
4440
4441 if (Style.RemoveBracesLLVM) {
4442 FormatStyle S = Expanded;
4443 S.RemoveBracesLLVM = true;
4444 Passes.emplace_back([&, S = std::move(S)](const Environment &Env) {
4445 return BracesRemover(Env, S).process(/*SkipAnnotation=*/true);
4446 });
4447 }
4448
4449 if (Style.RemoveSemicolon) {
4450 FormatStyle S = Expanded;
4451 S.RemoveSemicolon = true;
4452 Passes.emplace_back([&, S = std::move(S)](const Environment &Env) {
4453 return SemiRemover(Env, S).process();
4454 });
4455 }
4456
4457 if (Style.EnumTrailingComma != FormatStyle::ETC_Leave) {
4458 Passes.emplace_back([&](const Environment &Env) {
4459 return EnumTrailingCommaEditor(Env, Expanded)
4460 .process(/*SkipAnnotation=*/true);
4461 });
4462 }
4463
4464 if (Style.FixNamespaceComments) {
4465 Passes.emplace_back([&](const Environment &Env) {
4466 return NamespaceEndCommentsFixer(Env, Expanded).process();
4467 });
4468 }
4469
4470 if (Style.SortUsingDeclarations != FormatStyle::SUD_Never) {
4471 Passes.emplace_back([&](const Environment &Env) {
4472 return UsingDeclarationsSorter(Env, Expanded).process();
4473 });
4474 }
4475 }
4476
4477 if (Style.Language == FormatStyle::LK_ObjC &&
4478 !Style.ObjCPropertyAttributeOrder.empty()) {
4479 Passes.emplace_back([&](const Environment &Env) {
4480 return ObjCPropertyAttributeOrderFixer(Env, Expanded).process();
4481 });
4482 }
4483
4484 if (Style.isJavaScript() &&
4485 Style.JavaScriptQuotes != FormatStyle::JSQS_Leave) {
4486 Passes.emplace_back([&](const Environment &Env) {
4487 return JavaScriptRequoter(Env, Expanded).process(/*SkipAnnotation=*/true);
4488 });
4489 }
4490
4491 Passes.emplace_back([&](const Environment &Env) {
4492 return Formatter(Env, Expanded, Status).process();
4493 });
4494
4495 if (Style.SeparateDefinitionBlocks != FormatStyle::SDS_Leave) {
4496 Passes.emplace_back([&](const Environment &Env) {
4497 return DefinitionBlockSeparator(Env, Expanded).process();
4498 });
4499 }
4500
4501 if (Style.isJavaScript() &&
4502 Style.InsertTrailingCommas == FormatStyle::TCS_Wrapped) {
4503 Passes.emplace_back([&](const Environment &Env) {
4504 return TrailingCommaInserter(Env, Expanded).process();
4505 });
4506 }
4507
4508 std::optional<std::string> CurrentCode;
4510 unsigned Penalty = 0;
4511 for (size_t I = 0, E = Passes.size(); I < E; ++I) {
4512 std::pair<tooling::Replacements, unsigned> PassFixes = Passes[I](*Env);
4513 auto NewCode = applyAllReplacements(
4514 CurrentCode ? StringRef(*CurrentCode) : Code, PassFixes.first);
4515 if (NewCode) {
4516 Fixes = Fixes.merge(PassFixes.first);
4517 Penalty += PassFixes.second;
4518 if (I + 1 < E) {
4519 CurrentCode = std::move(*NewCode);
4520 Env = Environment::make(
4521 *CurrentCode, FileName,
4523 FirstStartColumn, NextStartColumn, LastStartColumn);
4524 if (!Env)
4525 return {};
4526 }
4527 }
4528 }
4529
4530 if (Style.QualifierAlignment != FormatStyle::QAS_Leave) {
4531 // Don't make replacements that replace nothing. QualifierAlignment can
4532 // produce them if one of its early passes changes e.g. `const volatile` to
4533 // `volatile const` and then a later pass changes it back again.
4534 tooling::Replacements NonNoOpFixes;
4535 for (const tooling::Replacement &Fix : Fixes) {
4536 StringRef OriginalCode = Code.substr(Fix.getOffset(), Fix.getLength());
4537 if (OriginalCode != Fix.getReplacementText()) {
4538 auto Err = NonNoOpFixes.add(Fix);
4539 if (Err) {
4540 llvm::errs() << "Error adding replacements : "
4541 << toString(std::move(Err)) << "\n";
4542 }
4543 }
4544 }
4545 Fixes = std::move(NonNoOpFixes);
4546 }
4547
4548 return {Fixes, Penalty};
4549}
4550} // namespace internal
4551
4552tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
4554 StringRef FileName,
4555 FormattingAttemptStatus *Status) {
4556 return internal::reformat(Style, Code, Ranges,
4557 /*FirstStartColumn=*/0,
4558 /*NextStartColumn=*/0,
4559 /*LastStartColumn=*/0, FileName, Status)
4560 .first;
4561}
4562
4563tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
4565 StringRef FileName) {
4566 // cleanups only apply to C++ (they mostly concern ctor commas etc.)
4567 if (Style.Language != FormatStyle::LK_Cpp)
4568 return tooling::Replacements();
4569 auto Env = Environment::make(Code, FileName, Ranges);
4570 if (!Env)
4571 return {};
4572 return Cleaner(*Env, Style).process().first;
4573}
4574
4575tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
4577 StringRef FileName, bool *IncompleteFormat) {
4579 auto Result = reformat(Style, Code, Ranges, FileName, &Status);
4580 if (!Status.FormatComplete)
4581 *IncompleteFormat = true;
4582 return Result;
4583}
4584
4586 StringRef Code,
4588 StringRef FileName) {
4589 auto Env = Environment::make(Code, FileName, Ranges);
4590 if (!Env)
4591 return {};
4592 return NamespaceEndCommentsFixer(*Env, Style).process().first;
4593}
4594
4596 StringRef Code,
4598 StringRef FileName) {
4599 auto Env = Environment::make(Code, FileName, Ranges);
4600 if (!Env)
4601 return {};
4602 return UsingDeclarationsSorter(*Env, Style).process().first;
4603}
4604
4606 LangOptions LangOpts;
4607
4608 auto LexingStd = Style.Standard;
4609 if (LexingStd == FormatStyle::LS_Auto || LexingStd == FormatStyle::LS_Latest)
4610 LexingStd = FormatStyle::LS_Cpp20;
4611
4612 const bool SinceCpp11 = LexingStd >= FormatStyle::LS_Cpp11;
4613 const bool SinceCpp20 = LexingStd >= FormatStyle::LS_Cpp20;
4614
4615 switch (Style.Language) {
4616 case FormatStyle::LK_C:
4617 LangOpts.C11 = 1;
4618 LangOpts.C23 = 1;
4619 break;
4622 LangOpts.CXXOperatorNames = 1;
4623 LangOpts.CPlusPlus11 = SinceCpp11;
4624 LangOpts.CPlusPlus14 = LexingStd >= FormatStyle::LS_Cpp14;
4625 LangOpts.CPlusPlus17 = LexingStd >= FormatStyle::LS_Cpp17;
4626 LangOpts.CPlusPlus20 = SinceCpp20;
4627 LangOpts.CPlusPlus23 = LexingStd >= FormatStyle::LS_Cpp23;
4628 LangOpts.CPlusPlus26 = LexingStd >= FormatStyle::LS_Cpp26;
4629 [[fallthrough]];
4630 default:
4631 LangOpts.CPlusPlus = 1;
4632 }
4633
4634 LangOpts.Char8 = SinceCpp20;
4635 LangOpts.AllowLiteralDigitSeparator = LangOpts.CPlusPlus14 || LangOpts.C23;
4636 // Turning on digraphs in standards before C++0x is error-prone, because e.g.
4637 // the sequence "<::" will be unconditionally treated as "[:".
4638 // Cf. Lexer::LexTokenInternal.
4639 LangOpts.Digraphs = SinceCpp11;
4640
4641 LangOpts.LineComment = 1;
4642 LangOpts.Bool = 1;
4643 LangOpts.ObjC = 1;
4644 LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
4645 LangOpts.DeclSpecKeyword = 1; // To get __declspec.
4646 LangOpts.C99 = 1; // To get kw_restrict for non-underscore-prefixed restrict.
4647
4648 return LangOpts;
4649}
4650
4652 "Set coding style. <string> can be:\n"
4653 "1. A preset: LLVM, GNU, Google, Chromium, Microsoft,\n"
4654 " Mozilla, WebKit.\n"
4655 "2. 'file' to load style configuration from a\n"
4656 " .clang-format file in one of the parent directories\n"
4657 " of the source file (for stdin, see --assume-filename).\n"
4658 " If no .clang-format file is found, falls back to\n"
4659 " --fallback-style.\n"
4660 " --style=file is the default.\n"
4661 "3. 'file:<format_file_path>' to explicitly specify\n"
4662 " the configuration file.\n"
4663 "4. \"{key: value, ...}\" to set specific parameters, e.g.:\n"
4664 " --style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
4665
4667 static constexpr std::array<llvm::StringLiteral, 2> TemplateSuffixes{
4668 ".in",
4669 ".template",
4670 };
4671 for (auto Suffix : TemplateSuffixes)
4672 if (FileName.consume_back(Suffix))
4673 break;
4674
4675 if (FileName.ends_with(".c"))
4676 return FormatStyle::LK_C;
4677 if (FileName.ends_with(".java"))
4678 return FormatStyle::LK_Java;
4679 if (FileName.ends_with_insensitive(".js") ||
4680 FileName.ends_with_insensitive(".mjs") ||
4681 FileName.ends_with_insensitive(".cjs") ||
4682 FileName.ends_with_insensitive(".ts")) {
4683 return FormatStyle::LK_JavaScript; // (module) JavaScript or TypeScript.
4684 }
4685 if (FileName.ends_with(".m") || FileName.ends_with(".mm"))
4686 return FormatStyle::LK_ObjC;
4687 if (FileName.ends_with_insensitive(".proto") ||
4688 FileName.ends_with_insensitive(".protodevel")) {
4689 return FormatStyle::LK_Proto;
4690 }
4691 // txtpb is the canonical extension, and textproto is the legacy canonical
4692 // extension
4693 // https://protobuf.dev/reference/protobuf/textformat-spec/#text-format-files
4694 if (FileName.ends_with_insensitive(".txtpb") ||
4695 FileName.ends_with_insensitive(".textpb") ||
4696 FileName.ends_with_insensitive(".pb.txt") ||
4697 FileName.ends_with_insensitive(".textproto") ||
4698 FileName.ends_with_insensitive(".asciipb")) {
4700 }
4701 if (FileName.ends_with_insensitive(".td"))
4703 if (FileName.ends_with_insensitive(".cs"))
4705 if (FileName.ends_with_insensitive(".json") ||
4706 FileName.ends_with_insensitive(".ipynb")) {
4707 return FormatStyle::LK_Json;
4708 }
4709 if (FileName.ends_with_insensitive(".sv") ||
4710 FileName.ends_with_insensitive(".svh") ||
4711 FileName.ends_with_insensitive(".v") ||
4712 FileName.ends_with_insensitive(".vh")) {
4714 }
4715 return FormatStyle::LK_Cpp;
4716}
4717
4719 const auto ID = Env.getFileID();
4720 const auto &SourceMgr = Env.getSourceManager();
4721
4722 LangOptions LangOpts;
4723 LangOpts.CPlusPlus = 1;
4724 LangOpts.LineComment = 1;
4725
4726 Lexer Lex(ID, SourceMgr.getBufferOrFake(ID), SourceMgr, LangOpts);
4727 Lex.SetCommentRetentionState(true);
4728
4729 for (Token Tok; !Lex.LexFromRawLexer(Tok) && Tok.is(tok::comment);) {
4730 auto Text = StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
4731 Tok.getLength());
4732 if (!Text.consume_front("// clang-format Language:"))
4733 continue;
4734
4735 Text = Text.trim();
4736 if (Text == "C")
4737 return FormatStyle::LK_C;
4738 if (Text == "Cpp")
4739 return FormatStyle::LK_Cpp;
4740 if (Text == "ObjC")
4741 return FormatStyle::LK_ObjC;
4742 }
4743
4744 return FormatStyle::LK_None;
4745}
4746
4748 const auto GuessedLanguage = getLanguageByFileName(FileName);
4749 if (GuessedLanguage == FormatStyle::LK_Cpp) {
4750 auto Extension = llvm::sys::path::extension(FileName);
4751 // If there's no file extension (or it's .h), we need to check the contents
4752 // of the code to see if it contains Objective-C.
4753 if (!Code.empty() && (Extension.empty() || Extension == ".h")) {
4754 auto NonEmptyFileName = FileName.empty() ? "guess.h" : FileName;
4755 Environment Env(Code, NonEmptyFileName, /*Ranges=*/{});
4756 if (const auto Language = getLanguageByComment(Env);
4758 return Language;
4759 }
4760 ObjCHeaderStyleGuesser Guesser(Env, getLLVMStyle());
4761 Guesser.process();
4762 if (Guesser.isObjC())
4763 return FormatStyle::LK_ObjC;
4764 }
4765 }
4766 return GuessedLanguage;
4767}
4768
4769// Update StyleOptionHelpDescription above when changing this.
4770const char *DefaultFormatStyle = "file";
4771
4772const char *DefaultFallbackStyle = "LLVM";
4773
4774llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
4775loadAndParseConfigFile(StringRef ConfigFile, llvm::vfs::FileSystem *FS,
4776 FormatStyle *Style, bool AllowUnknownOptions,
4777 llvm::SourceMgr::DiagHandlerTy DiagHandler,
4778 bool IsDotHFile) {
4779 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
4780 FS->getBufferForFile(ConfigFile);
4781 if (auto EC = Text.getError())
4782 return EC;
4783 if (auto EC = parseConfiguration(*Text.get(), Style, AllowUnknownOptions,
4784 DiagHandler, /*DiagHandlerCtx=*/nullptr,
4785 IsDotHFile)) {
4786 return EC;
4787 }
4788 return Text;
4789}
4790
4791Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
4792 StringRef FallbackStyleName, StringRef Code,
4793 llvm::vfs::FileSystem *FS,
4794 bool AllowUnknownOptions,
4795 llvm::SourceMgr::DiagHandlerTy DiagHandler) {
4797 FormatStyle FallbackStyle = getNoStyle();
4798 if (!getPredefinedStyle(FallbackStyleName, Style.Language, &FallbackStyle))
4799 return make_string_error("Invalid fallback style: " + FallbackStyleName);
4800
4801 SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 1> ChildFormatTextToApply;
4802
4803 if (StyleName.starts_with("{")) {
4804 // Parse YAML/JSON style from the command line.
4805 StringRef Source = "<command-line>";
4806 if (std::error_code ec =
4807 parseConfiguration(llvm::MemoryBufferRef(StyleName, Source), &Style,
4808 AllowUnknownOptions, DiagHandler)) {
4809 return make_string_error("Error parsing -style: " + ec.message());
4810 }
4811
4812 if (Style.InheritConfig.empty())
4813 return Style;
4814
4815 ChildFormatTextToApply.emplace_back(
4816 llvm::MemoryBuffer::getMemBuffer(StyleName, Source, false));
4817 }
4818
4819 if (!FS)
4820 FS = llvm::vfs::getRealFileSystem().get();
4821 assert(FS);
4822
4823 const bool IsDotHFile = FileName.ends_with(".h");
4824
4825 // User provided clang-format file using -style=file:path/to/format/file.
4826 if (Style.InheritConfig.empty() &&
4827 StyleName.starts_with_insensitive("file:")) {
4828 auto ConfigFile = StyleName.substr(5);
4829 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
4830 loadAndParseConfigFile(ConfigFile, FS, &Style, AllowUnknownOptions,
4831 DiagHandler, IsDotHFile);
4832 if (auto EC = Text.getError()) {
4833 return make_string_error("Error reading " + ConfigFile + ": " +
4834 EC.message());
4835 }
4836
4837 LLVM_DEBUG(llvm::dbgs()
4838 << "Using configuration file " << ConfigFile << "\n");
4839
4840 if (Style.InheritConfig.empty())
4841 return Style;
4842
4843 // Search for parent configs starting from the parent directory of
4844 // ConfigFile.
4845 FileName = ConfigFile;
4846 ChildFormatTextToApply.emplace_back(std::move(*Text));
4847 }
4848
4849 // If the style inherits the parent configuration it is a command line
4850 // configuration, which wants to inherit, so we have to skip the check of the
4851 // StyleName.
4852 if (Style.InheritConfig.empty() && !StyleName.equals_insensitive("file")) {
4853 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
4854 return make_string_error("Invalid value for -style");
4855 if (Style.InheritConfig.empty())
4856 return Style;
4857 }
4858
4859 using namespace llvm::sys::path;
4860 using String = SmallString<128>;
4861
4862 String Path(FileName);
4863 if (std::error_code EC = FS->makeAbsolute(Path))
4864 return make_string_error(EC.message());
4865
4866 auto Normalize = [](String &Path) {
4867 Path = convert_to_slash(Path);
4868 remove_dots(Path, /*remove_dot_dot=*/true, Style::posix);
4869 };
4870
4871 Normalize(Path);
4872
4873 // Reset possible inheritance
4874 Style.InheritConfig.clear();
4875
4876 auto dropDiagnosticHandler = [](const llvm::SMDiagnostic &, void *) {};
4877
4878 auto applyChildFormatTexts = [&](FormatStyle *Style) {
4879 for (const auto &MemBuf : llvm::reverse(ChildFormatTextToApply)) {
4880 auto EC =
4881 parseConfiguration(*MemBuf, Style, AllowUnknownOptions,
4882 DiagHandler ? DiagHandler : dropDiagnosticHandler);
4883 // It was already correctly parsed.
4884 assert(!EC);
4885 static_cast<void>(EC);
4886 }
4887 };
4888
4889 // Look for .clang-format/_clang-format file in the file's parent directories.
4890 SmallVector<std::string, 2> FilesToLookFor;
4891 FilesToLookFor.push_back(".clang-format");
4892 FilesToLookFor.push_back("_clang-format");
4893
4894 llvm::StringSet<> Directories; // Inherited directories.
4895 bool Redirected = false;
4896 String Dir, UnsuitableConfigFiles;
4897 for (StringRef Directory = Path; !Directory.empty();
4898 Directory = Redirected ? Dir.str() : parent_path(Directory)) {
4899 auto Status = FS->status(Directory);
4900 if (!Status ||
4901 Status->getType() != llvm::sys::fs::file_type::directory_file) {
4902 if (!Redirected)
4903 continue;
4904 return make_string_error("Failed to inherit configuration directory " +
4905 Directory);
4906 }
4907
4908 for (const auto &F : FilesToLookFor) {
4909 String ConfigFile(Directory);
4910
4911 append(ConfigFile, F);
4912 LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
4913
4914 Status = FS->status(ConfigFile);
4915 if (!Status ||
4916 Status->getType() != llvm::sys::fs::file_type::regular_file) {
4917 continue;
4918 }
4919
4920 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
4921 loadAndParseConfigFile(ConfigFile, FS, &Style, AllowUnknownOptions,
4922 DiagHandler, IsDotHFile);
4923 if (auto EC = Text.getError()) {
4924 if (EC != ParseError::Unsuitable) {
4925 return make_string_error("Error reading " + ConfigFile + ": " +
4926 EC.message());
4927 }
4928 if (!UnsuitableConfigFiles.empty())
4929 UnsuitableConfigFiles.append(", ");
4930 UnsuitableConfigFiles.append(ConfigFile);
4931 continue;
4932 }
4933
4934 LLVM_DEBUG(llvm::dbgs()
4935 << "Using configuration file " << ConfigFile << "\n");
4936
4937 if (Style.InheritConfig.empty()) {
4938 if (!ChildFormatTextToApply.empty()) {
4939 LLVM_DEBUG(llvm::dbgs() << "Applying child configurations\n");
4940 applyChildFormatTexts(&Style);
4941 }
4942 return Style;
4943 }
4944
4945 if (!Directories.insert(Directory).second) {
4946 return make_string_error(
4947 "Loop detected when inheriting configuration file in " + Directory);
4948 }
4949
4950 LLVM_DEBUG(llvm::dbgs() << "Inherits parent configuration\n");
4951
4952 if (Style.InheritConfig == "..") {
4953 Redirected = false;
4954 } else {
4955 Redirected = true;
4956 String ExpandedDir;
4957 llvm::sys::fs::expand_tilde(Style.InheritConfig, ExpandedDir);
4958 Normalize(ExpandedDir);
4959 if (is_absolute(ExpandedDir, Style::posix)) {
4960 Dir = ExpandedDir;
4961 } else {
4962 Dir = Directory.str();
4963 append(Dir, Style::posix, ExpandedDir);
4964 }
4965 }
4966
4967 // Reset inheritance of style
4968 Style.InheritConfig.clear();
4969
4970 ChildFormatTextToApply.emplace_back(std::move(*Text));
4971
4972 // Breaking out of the inner loop, since we don't want to parse
4973 // .clang-format AND _clang-format, if both exist. Then we continue the
4974 // outer loop (parent directories) in search for the parent
4975 // configuration.
4976 break;
4977 }
4978 }
4979
4980 if (!UnsuitableConfigFiles.empty()) {
4981 return make_string_error("Configuration file(s) do(es) not support " +
4982 getLanguageName(Style.Language) + ": " +
4983 UnsuitableConfigFiles);
4984 }
4985
4986 if (!ChildFormatTextToApply.empty()) {
4987 LLVM_DEBUG(llvm::dbgs()
4988 << "Applying child configurations on fallback style\n");
4989 applyChildFormatTexts(&FallbackStyle);
4990 }
4991
4992 return FallbackStyle;
4993}
4994
4995static bool isClangFormatOnOff(StringRef Comment, bool On) {
4996 if (Comment == (On ? "/* clang-format on */" : "/* clang-format off */"))
4997 return true;
4998
4999 static const char ClangFormatOn[] = "// clang-format on";
5000 static const char ClangFormatOff[] = "// clang-format off";
5001 const unsigned Size = (On ? sizeof ClangFormatOn : sizeof ClangFormatOff) - 1;
5002
5003 return Comment.starts_with(On ? ClangFormatOn : ClangFormatOff) &&
5004 (Comment.size() == Size || Comment[Size] == ':');
5005}
5006
5007bool isClangFormatOn(StringRef Comment) {
5008 return isClangFormatOnOff(Comment, /*On=*/true);
5009}
5010
5011bool isClangFormatOff(StringRef Comment) {
5012 return isClangFormatOnOff(Comment, /*On=*/false);
5013}
5014
5015} // namespace format
5016} // namespace clang
This file declares DefinitionBlockSeparator, a TokenAnalyzer that inserts or removes empty lines sepa...
int8_t BraceCount
Number of optional braces to be inserted after this token: -1: a single left brace 0: no braces >0: n...
FormatToken()
Token Tok
The Token.
FormatToken * Next
The next token in the unwrapped line.
BracketAlignmentStyle
Definition Format.cpp:41
@ BAS_DontAlign
Definition Format.cpp:43
@ BAS_Ignore
Definition Format.cpp:46
@ BAS_BlockIndent
Definition Format.cpp:45
@ BAS_Align
Definition Format.cpp:42
@ BAS_AlwaysBreak
Definition Format.cpp:44
Various functions to configurably format source code.
This file declares IntegerLiteralSeparatorFixer that fixes C++ integer literal separators.
Result
Implement __builtin_bit_cast and related operations.
This file declares NamespaceEndCommentsFixer, a TokenAnalyzer that fixes namespace end comments.
This file declares NumericLiteralCaseFixer that standardizes character case within numeric literals.
This file declares ObjCPropertyAttributeOrderFixer, a TokenAnalyzer that adjusts the order of attribu...
This file declares QualifierAlignmentFixer, a TokenAnalyzer that enforces either east or west const d...
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file implements a sorter for JavaScript ES6 imports.
Implements a combinatorial exploration of all the different linebreaks unwrapped lines can be formatt...
This file declares UsingDeclarationsSorter, a TokenAnalyzer that sorts consecutive using declarations...
static CharSourceRange getCharRange(SourceRange R)
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens.
Definition Lexer.h:79
bool LexFromRawLexer(Token &Result)
LexFromRawLexer - Lex a token from a designated raw lexer (one with no associated preprocessor object...
Definition Lexer.h:236
void SetCommentRetentionState(bool Mode)
SetCommentRetentionMode - Change the comment retention mode of the lexer to the specified mode.
Definition Lexer.h:269
Encodes a location in the source.
This class handles loading and caching of source files into memory.
Token - This structure provides full information about a lexed token.
Definition Token.h:36
SourceLocation getEndLoc() const
Definition Token.h:169
SourceManager & getSourceManager() const
static std::unique_ptr< Environment > make(StringRef Code, StringRef FileName, ArrayRef< tooling::Range > Ranges, unsigned FirstStartColumn=0, unsigned NextStartColumn=0, unsigned LastStartColumn=0)
std::pair< tooling::Replacements, unsigned > process(const Environment &Env, const FormatStyle &Style)
static tok::TokenKind getTokenFromQualifier(const std::string &Qualifier)
std::pair< tooling::Replacements, unsigned > process(const Environment &Env, const FormatStyle &Style)
const char * name() const noexcept override
Definition Format.cpp:1714
std::string message(int EV) const override
Definition Format.cpp:1718
std::pair< tooling::Replacements, unsigned > process(bool SkipAnnotation=false)
static const llvm::Regex IncludeRegex
This class manages priorities of C++ include categories and calculates priorities for headers.
int getIncludePriority(StringRef IncludeName, bool CheckMainHeader) const
Returns the priority of the category which IncludeName belongs to.
int getSortIncludePriority(StringRef IncludeName, bool CheckMainHeader) const
A source range independent of the SourceManager.
Definition Replacement.h:44
A text replacement.
Definition Replacement.h:83
unsigned getLength() const
StringRef getReplacementText() const
unsigned getOffset() const
Maintains a set of replacements that are conflict-free.
std::vector< Range > getAffectedRanges() const
const_iterator begin() const
llvm::Error add(const Replacement &R)
Adds a new replacement R to the current set of replacements.
Replacements merge(const Replacements &Replaces) const
Merges Replaces into the current replacements.
#define UINT_MAX
Definition limits.h:64
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition Types.cpp:240
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:4347
const char * StyleOptionHelpDescription
Description to be used for help text for a llvm::cl option for specifying format style.
Definition Format.cpp:4651
void addQualifierAlignmentFixerPasses(const FormatStyle &Style, SmallVectorImpl< AnalyzerPass > &Passes)
static void expandPresetsSpaceBeforeParens(FormatStyle &Expanded)
Definition Format.cpp:1848
const char * DefaultFallbackStyle
The suggested predefined style to use as the fallback style in getStyle.
Definition Format.cpp:4772
static bool affectsRange(ArrayRef< tooling::Range > Ranges, unsigned Start, unsigned End)
Definition Format.cpp:3615
const char * getTokenTypeName(TokenType Type)
Determines the name of a token type.
FormatStyle getWebKitStyle()
Returns a format style complying with Webkit's style guide: http://www.webkit.org/coding/coding-style...
Definition Format.cpp:2374
bool isLikelyXml(StringRef Code)
Definition Format.cpp:4176
static unsigned findJavaImportGroup(const FormatStyle &Style, StringRef ImportIdentifier)
Definition Format.cpp:3995
std::string replaceCRLF(const std::string &Code)
Definition Format.cpp:3656
std::error_code make_error_code(ParseError e)
Definition Format.cpp:1705
FormatStyle getClangFormatStyle()
Definition Format.cpp:2442
std::function< std::pair< tooling::Replacements, unsigned >(const Environment &)> AnalyzerPass
FormatStyle getLLVMStyle(FormatStyle::LanguageKind Language=FormatStyle::LK_Cpp)
Returns a format style complying with the LLVM coding standards: http://llvm.org/docs/CodingStandards...
Definition Format.cpp:1880
static void replaceToken(const SourceManager &SourceMgr, tooling::Replacements &Fixes, const CharSourceRange &Range, std::string NewText)
FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language)
Returns a format style complying with one of Google's style guides: http://google-styleguide....
Definition Format.cpp:2135
std::string configurationAsText(const FormatStyle &Style)
Gets configuration in a YAML string.
Definition Format.cpp:2626
FormatStyle getMicrosoftStyle(FormatStyle::LanguageKind Language)
Returns a format style complying with Microsoft style guide: https://docs.microsoft....
Definition Format.cpp:2413
std::error_code parseConfiguration(llvm::MemoryBufferRef Config, FormatStyle *Style, bool AllowUnknownOptions=false, llvm::SourceMgr::DiagHandlerTy DiagHandler=nullptr, void *DiagHandlerCtx=nullptr, bool IsDotHFile=false)
Parse configuration from YAML-formatted text.
Definition Format.cpp:2529
const std::error_category & getParseCategory()
Definition Format.cpp:1701
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:4585
FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code)
Definition Format.cpp:4747
Expected< FormatStyle > getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyle, StringRef Code="", llvm::vfs::FileSystem *FS=nullptr, bool AllowUnknownOptions=false, llvm::SourceMgr::DiagHandlerTy DiagHandler=nullptr)
Construct a FormatStyle based on StyleName.
Definition Format.cpp:4791
bool isMpegTS(StringRef Code)
Definition Format.cpp:4169
static std::pair< unsigned, unsigned > FindCursorIndex(const ArrayRef< IncludeDirective > &Includes, const ArrayRef< unsigned > &Indices, unsigned Cursor)
Definition Format.cpp:3635
const char * DefaultFormatStyle
The suggested format style to use by default.
Definition Format.cpp:4770
static FormatStyle::LanguageKind getLanguageByComment(const Environment &Env)
Definition Format.cpp:4718
FormatStyle getGNUStyle()
Returns a format style complying with GNU Coding Standards: http://www.gnu.org/prep/standards/standar...
Definition Format.cpp:2398
bool isClangFormatOff(StringRef Comment)
Definition Format.cpp:5011
LangOptions getFormattingLangOpts(const FormatStyle &Style=getLLVMStyle())
Returns the LangOpts that the formatter expects you to set.
Definition Format.cpp:4605
static bool isClangFormatOnOff(StringRef Comment, bool On)
Definition Format.cpp:4995
static FormatStyle::LanguageKind getLanguageByFileName(StringRef &FileName)
Definition Format.cpp:4666
tooling::Replacements sortJavaScriptImports(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName)
static void sortJavaImports(const FormatStyle &Style, const ArrayRef< JavaImportDirective > &Imports, ArrayRef< tooling::Range > Ranges, StringRef FileName, StringRef Code, tooling::Replacements &Replaces)
Definition Format.cpp:4015
FormatStyle getMozillaStyle()
Returns a format style complying with Mozilla's style guide: https://firefox-source-docs....
Definition Format.cpp:2347
bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language, FormatStyle *Style)
Gets a predefined style for the specified language by name.
Definition Format.cpp:2464
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:4330
static void expandPresetsBraceWrapping(FormatStyle &Expanded)
Definition Format.cpp:1740
static void sortCppIncludes(const FormatStyle &Style, const ArrayRef< IncludeDirective > &Includes, ArrayRef< tooling::Range > Ranges, StringRef FileName, StringRef Code, tooling::Replacements &Replaces, unsigned *Cursor)
Definition Format.cpp:3684
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:4552
bool isClangFormatOn(StringRef Comment)
Definition Format.cpp:5007
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:4595
llvm::Error make_string_error(const Twine &Message)
Definition Format.cpp:1709
ParseError validateQualifierOrder(FormatStyle *Style)
Definition Format.cpp:2497
FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language)
Returns a format style complying with Chromium's style guide: http://www.chromium....
Definition Format.cpp:2287
static void expandPresetsSpacesInParens(FormatStyle &Expanded)
Definition Format.cpp:1872
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:4563
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:4219
FormatStyle getNoStyle()
Returns style indicating formatting should be not applied at all.
Definition Format.cpp:2456
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:4178
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > loadAndParseConfigFile(StringRef ConfigFile, llvm::vfs::FileSystem *FS, FormatStyle *Style, bool AllowUnknownOptions, llvm::SourceMgr::DiagHandlerTy DiagHandler, bool IsDotHFile)
Definition Format.cpp:4775
static Expected< tooling::Replacements > processReplacements(T ProcessFunc, StringRef Code, const tooling::Replacements &Replaces, const FormatStyle &Style)
Definition Format.cpp:4200
StringRef getLanguageName(FormatStyle::LanguageKind Language)
Definition Format.h:6666
const char * getTokenName(TokenKind Kind) LLVM_READNONE
Determines the name of a token as used within the front end.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:33
const char * getPunctuatorSpelling(TokenKind Kind) LLVM_READNONE
Determines the spelling of simple punctuation tokens like '!
std::vector< Range > calculateRangesAfterReplacements(const Replacements &Replaces, const std::vector< Range > &Ranges)
Calculates the new ranges after Replaces are applied.
Top level wrappers for InstallAPI frontend operations.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
Language
The language for the input, used to select and validate the language standard and possible actions.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
@ On
Always emit colors regardless of the output stream.
unsigned long uint64_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
int const char * function
Definition c++config.h:31
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 __builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t uint32_t uint32_t __builtin_riscv_mhacc_i32 __builtin_riscv_mhaccu_u32 __builtin_riscv_mhaccsu_i32 __builtin_riscv_mulq_i32 __builtin_riscv_mqwacc_i64 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 int8_t
#define false
Definition stdbool.h:26
A rule that specifies how to break a specific set of binary operators.
Definition Format.h:2585
Precise control over the wrapping of braces.
Definition Format.h:1425
bool SplitEmptyRecord
If false, empty record (e.g.
Definition Format.h:1660
bool AfterClass
Wrap class definitions.
Definition Format.h:1451
bool AfterCaseLabel
Wrap case labels.
Definition Format.h:1441
bool AfterStruct
Wrap struct definitions.
Definition Format.h:1534
bool AfterRequiresExpression
Wrap requires expression body.
Definition Format.h:1520
bool BeforeLambdaBody
Wrap lambda block.
Definition Format.h:1618
bool AfterUnion
Wrap union definitions.
Definition Format.h:1548
bool AfterExportBlock
Wrap export blocks.
Definition Format.h:1557
bool AfterEnum
Wrap enum definitions.
Definition Format.h:1466
bool IndentBraces
Indent the wrapped braces themselves.
Definition Format.h:1634
bool AfterObjCDeclaration
Wrap ObjC definitions (interfaces, implementations...).
Definition Format.h:1504
bool BeforeElse
Wrap before else.
Definition Format.h:1601
bool AfterNamespace
Wrap namespace definitions.
Definition Format.h:1498
bool BeforeWhile
Wrap before while.
Definition Format.h:1632
bool SplitEmptyNamespace
If false, empty namespace body can be put on a single line.
Definition Format.h:1672
BraceWrappingAfterControlStatementStyle AfterControlStatement
Wrap control statements (if/for/while/switch/..).
Definition Format.h:1454
bool AfterFunction
Wrap function definitions.
Definition Format.h:1482
bool BeforeCatch
Wrap before catch.
Definition Format.h:1587
bool SplitEmptyFunction
If false, empty function body can be put on a single line.
Definition Format.h:1648
bool AfterExternBlock
Wrap extern blocks.
Definition Format.h:1571
Options for BreakBinaryOperations.
Definition Format.h:2619
Separator format of integer literals of different bases.
Definition Format.h:3589
Options regarding which empty lines are kept.
Definition Format.h:3784
Separate control for each numeric literal component.
Definition Format.h:4102
Options related to packing arguments of function calls.
Definition Format.h:4309
Options related to packing parameters of function declarations and definitions.
Definition Format.h:4443
See documentation of RawStringFormats.
Definition Format.h:4656
Different styles for merging short functions containing at most one statement.
Definition Format.h:893
static ShortFunctionStyle setAll()
Definition Format.h:943
static ShortFunctionStyle setEmptyOnly()
Definition Format.h:934
static ShortFunctionStyle setInlineOnly()
Definition Format.h:940
static ShortFunctionStyle setEmptyAndInline()
Definition Format.h:937
Includes sorting options.
Definition Format.h:5123
Precise control over the spacing before parentheses.
Definition Format.h:5462
bool AfterControlStatements
If true, put space between control statement keywords (for/if/while...) and opening parentheses.
Definition Format.h:5469
bool AfterOverloadedOperator
If true, put a space between operator overloading and opening parentheses.
Definition Format.h:5512
bool AfterRequiresInExpression
If true, put space between requires keyword in a requires expression and opening parentheses.
Definition Format.h:5539
bool AfterFunctionDeclarationName
If true, put a space between function declaration name and opening parentheses.
Definition Format.h:5483
bool AfterRequiresInClause
If true, put space between requires keyword in a requires clause and opening parentheses,...
Definition Format.h:5529
bool AfterForeachMacros
If true, put space between foreach macros and opening parentheses.
Definition Format.h:5476
bool AfterNot
If true, put a space between alternative operator not and the opening parenthesis.
Definition Format.h:5504
bool AfterFunctionDefinitionName
If true, put a space between function definition name and opening parentheses.
Definition Format.h:5490
bool BeforeNonEmptyParentheses
If true, put a space before opening parentheses only if the parentheses are not empty.
Definition Format.h:5547
bool AfterIfMacros
If true, put space between if macros and opening parentheses.
Definition Format.h:5497
bool AfterPlacementOperator
If true, put a space between operator new/delete and opening parenthesis.
Definition Format.h:5520
If true, spaces may be inserted into C style casts.
Definition Format.h:5745
unsigned Maximum
The maximum number of spaces at the start of the comment.
Definition Format.h:5749
unsigned Minimum
The minimum number of spaces at the start of the comment.
Definition Format.h:5747
Precise control over the spacing in parentheses.
Definition Format.h:5824
bool ExceptDoubleParentheses
Override any of the following options to prevent addition of space when both opening and closing pare...
Definition Format.h:5835
bool Other
Put a space in parentheses not covered by preceding options.
Definition Format.h:5867
bool InEmptyParentheses
Insert a space in empty parentheses, i.e.
Definition Format.h:5861
bool InCStyleCasts
Put a space in C style casts.
Definition Format.h:5850
bool InConditionalStatements
Put a space in parentheses only inside conditional statements (for/if/while/switch....
Definition Format.h:5843
UseTabStyle
This option is deprecated.
Definition Format.h:6084
@ UT_AlignWithSpaces
Use tabs for line continuation and indentation, and spaces for alignment.
Definition Format.h:6094
@ UT_ForContinuationAndIndentation
Fill all leading whitespace with tabs, and use spaces for alignment that appears within a line (e....
Definition Format.h:6091
@ UT_ForIndentation
Use tabs only for indentation.
Definition Format.h:6088
@ UT_Always
Use tabs whenever we need to fill whitespace that spans at least from one tab stop to the next one.
Definition Format.h:6097
@ UT_Never
Never use tab.
Definition Format.h:6086
LanguageKind
Supported languages.
Definition Format.h:3874
@ LK_C
Should be used for C.
Definition Format.h:3878
@ LK_CSharp
Should be used for C#.
Definition Format.h:3882
@ LK_None
Do not use.
Definition Format.h:3876
@ LK_Java
Should be used for Java.
Definition Format.h:3884
@ LK_Cpp
Should be used for C++.
Definition Format.h:3880
@ LK_JavaScript
Should be used for JavaScript.
Definition Format.h:3886
@ LK_ObjC
Should be used for Objective-C, Objective-C++.
Definition Format.h:3890
@ LK_Verilog
Should be used for Verilog and SystemVerilog.
Definition Format.h:3901
@ LK_TableGen
Should be used for TableGen code.
Definition Format.h:3894
@ LK_Proto
Should be used for Protocol Buffers
Definition Format.h:3892
@ LK_Json
Should be used for JSON.
Definition Format.h:3888
@ LK_TextProto
Should be used for Protocol Buffer messages in text format.
Definition Format.h:3897
ShortLambdaStyle
Different styles for merging short lambdas containing at most one statement.
Definition Format.h:1026
@ SLS_All
Merge all lambdas fitting on a single line.
Definition Format.h:1050
@ SLS_Inline
Merge lambda into a single line if the lambda is argument of a function.
Definition Format.h:1044
@ SLS_None
Never merge lambdas into a single line.
Definition Format.h:1028
@ SLS_Empty
Only merge empty lambdas.
Definition Format.h:1036
SeparateDefinitionStyle
The style if definition blocks should be separated.
Definition Format.h:5039
@ SDS_Never
Remove any empty line between definition blocks.
Definition Format.h:5045
@ SDS_Always
Insert an empty line between definition blocks.
Definition Format.h:5043
@ SDS_Leave
Leave definition blocks as they are.
Definition Format.h:5041
SortJavaStaticImportOptions
Position for Java Static imports.
Definition Format.h:5194
@ SJSIO_Before
Static imports are placed before non-static imports.
Definition Format.h:5201
@ SJSIO_After
Static imports are placed after non-static imports.
Definition Format.h:5208
EnumTrailingCommaStyle
Styles for enum trailing commas.
Definition Format.h:3095
@ ETC_Remove
Remove trailing commas.
Definition Format.h:3113
@ ETC_Insert
Insert trailing commas.
Definition Format.h:3107
@ ETC_Leave
Don't insert or remove trailing commas.
Definition Format.h:3101
TrailingCommaStyle
The style of inserting trailing commas into container literals.
Definition Format.h:3530
@ TCS_Wrapped
Insert trailing commas in container literals that were wrapped over multiple lines.
Definition Format.h:3538
@ TCS_None
Do not insert trailing commas.
Definition Format.h:3532
BinPackParametersStyle
Different ways to try to fit all parameters on a line.
Definition Format.h:4412
@ BPPS_OnePerLine
Put all parameters on the current line if they fit.
Definition Format.h:4428
@ BPPS_UseBreakAfter
Use the BreakAfter option to handle parameter packing instead.
Definition Format.h:4438
@ BPPS_BinPack
Bin-pack parameters.
Definition Format.h:4418
@ BPPS_AlwaysOnePerLine
Always put each parameter on its own line.
Definition Format.h:4435
BinPackStyle
The style of wrapping parameters on the same line (bin-packed) or on one line each.
Definition Format.h:1881
@ BPS_Never
Never bin-pack parameters.
Definition Format.h:1887
@ BPS_Auto
Automatically determine parameter bin-packing behavior.
Definition Format.h:1883
@ BPS_Always
Always bin-pack parameters.
Definition Format.h:1885
ReflowCommentsStyle
Types of comment reflow style.
Definition Format.h:4742
@ RCS_IndentOnly
Only apply indentation rules, moving comments left or right, without changing formatting inside the c...
Definition Format.h:4759
@ RCS_Never
Leave comments untouched.
Definition Format.h:4750
@ RCS_Always
Apply indentation rules and reflow long comments into new lines, trying to obey the ColumnLimit.
Definition Format.h:4770
EmptyLineBeforeAccessModifierStyle
Different styles for empty line before access modifiers.
Definition Format.h:3032
@ ELBAMS_LogicalBlock
Add empty line only when access modifier starts a new logical block.
Definition Format.h:3067
@ ELBAMS_Never
Remove all empty lines before access modifiers.
Definition Format.h:3047
@ ELBAMS_Always
Always add empty line before access modifiers unless access modifier is at the start of struct or cla...
Definition Format.h:3087
@ ELBAMS_Leave
Keep existing empty lines before access modifiers.
Definition Format.h:3049
BreakConstructorInitializersStyle
Different ways to break initializers.
Definition Format.h:2663
@ BCIS_AfterColon
Break constructor initializers after the colon and commas.
Definition Format.h:2685
@ BCIS_AfterComma
Break constructor initializers only after the commas.
Definition Format.h:2691
@ BCIS_BeforeColon
Break constructor initializers before the colon and after the commas.
Definition Format.h:2670
@ BCIS_BeforeComma
Break constructor initializers before the colon and commas, and align the commas with the colon.
Definition Format.h:2678
IndentExternBlockStyle
Indents extern blocks.
Definition Format.h:3298
@ IEBS_AfterExternBlock
Backwards compatible with AfterExternBlock's indenting.
Definition Format.h:3316
@ IEBS_Indent
Indents extern blocks.
Definition Format.h:3330
@ IEBS_NoIndent
Does not indent extern blocks.
Definition Format.h:3323
BinaryOperatorStyle
The style of breaking before or after binary operators.
Definition Format.h:1891
@ BOS_All
Break before operators.
Definition Format.h:1927
@ BOS_None
Break after operators.
Definition Format.h:1903
@ BOS_NonAssignment
Break before operators that aren't assignments.
Definition Format.h:1915
LineEndingStyle
Line ending style.
Definition Format.h:3925
@ LE_DeriveLF
Use \n unless the input has more lines ending in \r\n.
Definition Format.h:3931
@ LE_CRLF
Use \r\n.
Definition Format.h:3929
@ LE_DeriveCRLF
Use \r\n unless the input has more lines ending in \n.
Definition Format.h:3933
@ LE_LF
Use \n.
Definition Format.h:3927
TrailingCommentsAlignmentKinds
Enums for AlignTrailingComments.
Definition Format.h:552
@ TCAS_Never
Don't align trailing comments but other formatter applies.
Definition Format.h:579
@ TCAS_Leave
Leave trailing comments as they are.
Definition Format.h:561
@ TCAS_Always
Align trailing comments.
Definition Format.h:570
NumericLiteralComponentStyle
Control over each component in a numeric literal.
Definition Format.h:4081
@ NLCS_Lower
Format this component with lowercase characters.
Definition Format.h:4087
@ NLCS_Leave
Leave this component of the literal as is.
Definition Format.h:4083
@ NLCS_Upper
Format this component with uppercase characters.
Definition Format.h:4085
SpacesInParensStyle
Different ways to put a space before opening and closing parentheses.
Definition Format.h:5787
@ SIPO_Custom
Configure each individual space in parentheses in SpacesInParensOptions.
Definition Format.h:5799
@ SIPO_Never
Never put a space in parentheses.
Definition Format.h:5796
ShortRecordStyle
Different styles for merging short records (class,struct, and union).
Definition Format.h:1069
@ SRS_EmptyAndAttached
Only merge empty records if the opening brace was not wrapped, i.e.
Definition Format.h:1074
@ SRS_Empty
Only merge empty records.
Definition Format.h:1083
@ SRS_Always
Merge all records that fit on a single line.
Definition Format.h:1089
@ SRS_Never
Never merge records into a single line.
Definition Format.h:1071
BreakBeforeInlineASMColonStyle
Different ways to break ASM parameters.
Definition Format.h:2457
@ BBIAS_Always
Always break before inline ASM colon.
Definition Format.h:2478
@ BBIAS_OnlyMultiline
Break before inline ASM colon if the line length is longer than column limit.
Definition Format.h:2471
@ BBIAS_Never
No break before inline ASM colon.
Definition Format.h:2462
PPDirectiveIndentStyle
Options for indenting preprocessor directives.
Definition Format.h:3396
@ PPDIS_Leave
Leaves indentation of directives as-is.
Definition Format.h:3435
@ PPDIS_BeforeHash
Indents directives before the hash.
Definition Format.h:3423
@ PPDIS_None
Does not indent any directives.
Definition Format.h:3405
@ PPDIS_AfterHash
Indents directives after the hash.
Definition Format.h:3414
LambdaBodyIndentationKind
Indentation logic for lambda bodies.
Definition Format.h:3836
@ LBI_OuterScope
For statements within block scope, align lambda body relative to the indentation level of the outer s...
Definition Format.h:3858
@ LBI_Signature
Align lambda body relative to the lambda signature.
Definition Format.h:3844
ShortBlockStyle
Different styles for merging short blocks containing at most one statement.
Definition Format.h:737
@ SBS_Always
Always merge short blocks into a single line.
Definition Format.h:760
@ SBS_Empty
Only merge empty blocks.
Definition Format.h:754
@ SBS_Never
Never merge blocks into a single line.
Definition Format.h:746
ShortIfStyle
Different styles for handling short if statements.
Definition Format.h:954
@ SIS_WithoutElse
Put short ifs on the same line only if there is no else statement.
Definition Format.h:987
@ SIS_Never
Never put short ifs on the same line.
Definition Format.h:971
@ SIS_OnlyFirstIf
Put short ifs, but not else ifs nor else statements, on the same line.
Definition Format.h:1003
@ SIS_AllIfsAndElse
Always put short ifs, else ifs and else statements on the same line.
Definition Format.h:1017
BreakTemplateDeclarationsStyle
Different ways to break after the template declaration.
Definition Format.h:1229
@ BTDS_No
Do not force break before declaration.
Definition Format.h:1249
@ BTDS_MultiLine
Force break after template declaration only when the following declaration spans multiple lines.
Definition Format.h:1260
@ BTDS_Yes
Always break after template declaration.
Definition Format.h:1271
@ BTDS_Leave
Do not change the line breaking before the declaration.
Definition Format.h:1239
SpaceBeforeParensStyle
Different ways to put a space before opening parentheses.
Definition Format.h:5394
@ SBPO_Never
This is deprecated and replaced by Custom below, with all SpaceBeforeParensOptions but AfterPlacement...
Definition Format.h:5398
@ SBPO_Custom
Configure each individual space before parentheses in SpaceBeforeParensOptions.
Definition Format.h:5447
@ SBPO_NonEmptyParentheses
Put a space before opening parentheses only if the parentheses are not empty.
Definition Format.h:5432
@ SBPO_ControlStatementsExceptControlMacros
Same as SBPO_ControlStatements except this option doesn't apply to ForEach and If macros.
Definition Format.h:5421
@ SBPO_ControlStatements
Put a space before opening parentheses only after control statement keywords (for/if/while....
Definition Format.h:5408
@ SBPO_Always
Always put a space before opening parentheses, except when it's prohibited by the syntax rules (in fu...
Definition Format.h:5444
PackConstructorInitializersStyle
Different ways to try to fit all constructor initializers on a line.
Definition Format.h:4350
@ PCIS_NextLineOnly
Put all constructor initializers on the next line if they fit.
Definition Format.h:4404
@ PCIS_Never
Always put each constructor initializer on its own line.
Definition Format.h:4357
@ PCIS_CurrentLine
Put all constructor initializers on the current line if they fit.
Definition Format.h:4375
@ PCIS_BinPack
Bin-pack constructor initializers.
Definition Format.h:4364
@ PCIS_NextLine
Same as PCIS_CurrentLine except that if all constructor initializers do not fit on the current line,...
Definition Format.h:4389
BreakBeforeReturnTypeStyle
Different ways to break before the function return type.
Definition Format.h:2486
@ BBRTS_None
Do not force a break before the return type.
Definition Format.h:2488
@ BBRTS_TopLevelDefinitions
Break before the return type of top-level definitions only.
Definition Format.h:2500
@ BBRTS_TopLevel
Break before the return type of top-level functions only.
Definition Format.h:2496
@ BBRTS_All
Always break before the return type.
Definition Format.h:2494
@ BBRTS_AllDefinitions
Break before the return type of function definitions only.
Definition Format.h:2498
BreakInheritanceListStyle
Different ways to break inheritance list.
Definition Format.h:2798
@ BILS_AfterColon
Break inheritance list after the colon and commas.
Definition Format.h:2823
@ BILS_AfterComma
Break inheritance list only after the commas.
Definition Format.h:2830
@ BILS_BeforeColon
Break inheritance list before the colon and after the commas.
Definition Format.h:2806
@ BILS_BeforeComma
Break inheritance list before the colon and commas, and align the commas with the colon.
Definition Format.h:2815
SpacesInBlockCommentsStyle
Styles for controlling spacing after /* and before `.
Definition Format.h:5698
@ SIBCS_Always
Add spaces after /* and before `.
Definition Format.h:5708
@ SIBCS_Leave
Leave existing spaces unchanged.
Definition Format.h:5710
@ SIBCS_Never
Remove spaces after /* and before `.
Definition Format.h:5703
DAGArgStyle
Different ways to control the format inside TableGen DAGArg.
Definition Format.h:6012
@ DAS_BreakElements
Break inside DAGArg after each list element but for the last.
Definition Format.h:6024
@ DAS_DontBreak
Never break inside DAGArg.
Definition Format.h:6017
@ DAS_BreakAll
Break inside DAGArg after the operator and the all elements.
Definition Format.h:6032
BreakBeforeNoexceptSpecifierStyle
Different ways to break before a noexcept specifier.
Definition Format.h:689
@ BBNSS_Never
No line break allowed.
Definition Format.h:699
@ BBNSS_Always
Line breaks are allowed.
Definition Format.h:722
@ BBNSS_OnlyWithParen
For a simple noexcept there is no line break allowed, but when we have a condition it is.
Definition Format.h:710
RequiresClausePositionStyle
The possible positions for the requires clause.
Definition Format.h:4911
@ RCPS_OwnLineWithBrace
As with OwnLine, except, unless otherwise prohibited, place a following open brace (of a function def...
Definition Format.h:4950
@ RCPS_OwnLine
Always put the requires clause on its own line (possibly followed by a semicolon).
Definition Format.h:4932
@ RCPS_WithPreceding
Try to put the clause together with the preceding part of a declaration.
Definition Format.h:4967
@ RCPS_SingleLine
Try to put everything in the same line if possible.
Definition Format.h:5005
@ RCPS_WithFollowing
Try to put the requires clause together with the class or function declaration.
Definition Format.h:4981
LanguageStandard
Supported language standards for parsing and formatting C++ constructs.
Definition Format.h:5927
@ LS_Cpp17
Parse and format as C++17.
Definition Format.h:5936
@ LS_Cpp26
Parse and format as C++26.
Definition Format.h:5942
@ LS_Cpp23
Parse and format as C++23.
Definition Format.h:5940
@ LS_Latest
Parse and format using the latest supported language version.
Definition Format.h:5945
@ LS_Cpp11
Parse and format as C++11.
Definition Format.h:5932
@ LS_Auto
Automatic detection based on the input.
Definition Format.h:5947
@ LS_Cpp03
Parse and format as C++03.
Definition Format.h:5930
@ LS_Cpp14
Parse and format as C++14.
Definition Format.h:5934
@ LS_Cpp20
Parse and format as C++20.
Definition Format.h:5938
BraceWrappingAfterControlStatementStyle
Different ways to wrap braces after control statements.
Definition Format.h:1385
@ BWACS_Always
Always wrap braces after a control statement.
Definition Format.h:1415
@ BWACS_Never
Never wrap braces after a control statement.
Definition Format.h:1394
@ BWACS_MultiLine
Only wrap braces after a multi-line control statement.
Definition Format.h:1405
JavaScriptQuoteStyle
Quotation styles for JavaScript strings.
Definition Format.h:3730
@ JSQS_Double
Always use double quotes.
Definition Format.h:3748
@ JSQS_Single
Always use single quotes.
Definition Format.h:3742
@ JSQS_Leave
Leave string quotes as they are.
Definition Format.h:3736
IndentAccessModifierStyle
Modes for indenting access modifiers and record members.
Definition Format.h:3200
@ IAMS_Never
Use AccessModifierOffset for access modifiers and indent members one level below the record.
Definition Format.h:3211
@ IAMS_AfterFirstAccessModifier
In C, C++, and Objective-C, indent members one level until the first explicit access modifier,...
Definition Format.h:3235
@ IAMS_Always
Give access modifiers their own indentation level and indent all members two levels below the record.
Definition Format.h:3223
WrapNamespaceBodyWithEmptyLinesStyle
Different styles for wrapping namespace body with empty lines.
Definition Format.h:6145
@ WNBWELS_Always
Always have at least one empty line at the beginning and the end of namespace body except that the nu...
Definition Format.h:6167
@ WNBWELS_Leave
Keep existing newlines at the beginning and the end of namespace body.
Definition Format.h:6170
@ WNBWELS_Never
Remove all empty lines at the beginning and the end of namespace body.
Definition Format.h:6154
BraceBreakingStyle
Different ways to attach braces to their surrounding context.
Definition Format.h:1935
@ BS_Mozilla
Like Attach, but break before braces on enum, function, and record definitions.
Definition Format.h:2080
@ BS_Whitesmiths
Like Allman but always indent braces and line up code with braces.
Definition Format.h:2250
@ BS_Allman
Always break before braces.
Definition Format.h:2190
@ BS_Stroustrup
Like Attach, but break before function definitions, catch, and else.
Definition Format.h:2130
@ BS_Linux
Like Attach, but break before braces on function, namespace and class definitions.
Definition Format.h:2030
@ BS_WebKit
Like Attach, but break before functions.
Definition Format.h:2360
@ BS_Custom
Configure each individual brace in BraceWrapping.
Definition Format.h:2362
@ BS_GNU
Always break before braces and add an extra level of indentation to braces of control statements,...
Definition Format.h:2313
@ BS_Attach
Always attach braces to surrounding context.
Definition Format.h:1980
AttributeBreakingStyle
Different ways to break after the last attribute of a group before a declaration or control statement...
Definition Format.h:1705
@ ABS_Leave
Leave the line breaking after the last attribute of the group as is.
Definition Format.h:1759
@ ABS_Never
Never break after the last attribute of the group.
Definition Format.h:1795
@ ABS_Always
Always break after the last attribute of the group.
Definition Format.h:1734
@ ABS_LeaveAll
Same as Leave except that it applies to all attributes of the group.
Definition Format.h:1773
BitFieldColonSpacingStyle
This option is deprecated.
Definition Format.h:1323
@ BFCS_Both
Add one space on each side of the :
Definition Format.h:1328
@ BFCS_Before
Add space before the : only.
Definition Format.h:1339
@ BFCS_None
Add no space around the : (except when needed for AlignConsecutiveBitFields).
Definition Format.h:1334
@ BFCS_After
Add space after the : only (space may be added before if needed for AlignConsecutiveBitFields).
Definition Format.h:1345
RequiresExpressionIndentationKind
Indentation logic for requires expression bodies.
Definition Format.h:5013
@ REI_Keyword
Align requires expression body relative to the requires keyword.
Definition Format.h:5031
@ REI_OuterScope
Align requires expression body relative to the indentation level of the outer scope the requires expr...
Definition Format.h:5023
BreakBeforeConceptDeclarationsStyle
Different ways to break before concept declarations.
Definition Format.h:2433
@ BBCDS_Allowed
Breaking between template declaration and concept is allowed.
Definition Format.h:2442
@ BBCDS_Never
Keep the template declaration line together with concept.
Definition Format.h:2438
@ BBCDS_Always
Always break before concept, putting it in the line after the template declaration.
Definition Format.h:2449
BracedListStyle
Different ways to handle braced lists.
Definition Format.h:2902
@ BLS_AlignFirstComment
Same as FunctionCall, except for the handling of a comment at the begin, it then aligns everything fo...
Definition Format.h:2956
@ BLS_FunctionCall
Best suited for C++11 braced lists.
Definition Format.h:2938
@ BLS_Block
Best suited for pre C++11 braced lists.
Definition Format.h:2918
SpaceAroundPointerQualifiersStyle
Different ways to put a space before opening parentheses.
Definition Format.h:5294
@ SAPQ_After
Ensure that there is a space after pointer qualifiers.
Definition Format.h:5313
@ SAPQ_Default
Don't ensure spaces around pointer qualifiers and use PointerAlignment instead.
Definition Format.h:5301
@ SAPQ_Both
Ensure that there is a space both before and after pointer qualifiers.
Definition Format.h:5319
@ SAPQ_Before
Ensure that there is a space before pointer qualifiers.
Definition Format.h:5307
EmptyLineAfterAccessModifierStyle
Different styles for empty line after access modifiers.
Definition Format.h:2983
@ ELAAMS_Always
Always add empty line after access modifiers if there are none.
Definition Format.h:3022
@ ELAAMS_Never
Remove all empty lines after access modifiers.
Definition Format.h:2998
@ ELAAMS_Leave
Keep existing empty lines after access modifiers.
Definition Format.h:3001
DefinitionReturnTypeBreakingStyle
Different ways to break after the function definition return type.
Definition Format.h:1099
@ DRTBS_All
Always break after the return type.
Definition Format.h:1104
@ DRTBS_TopLevel
Always break after the return types of top-level functions.
Definition Format.h:1106
@ DRTBS_None
Break after return type automatically.
Definition Format.h:1102
ArrayInitializerAlignmentStyle
Different style for aligning array initializers.
Definition Format.h:85
@ AIAS_Left
Align array column and left justify the columns e.g.:
Definition Format.h:95
@ AIAS_Right
Align array column and right justify the columns e.g.:
Definition Format.h:105
@ AIAS_None
Don't align array initializer columns.
Definition Format.h:107
BreakBinaryOperationsStyle
Different ways to break binary operations.
Definition Format.h:2553
@ BBO_OnePerLine
Binary operations will either be all on the same line, or each operation will have one line each.
Definition Format.h:2570
@ BBO_Never
Don't break binary operations.
Definition Format.h:2559
@ BBO_RespectPrecedence
Binary operations of a particular precedence that exceed the column limit will have one line each.
Definition Format.h:2580
EscapedNewlineAlignmentStyle
Different styles for aligning escaped newlines.
Definition Format.h:472
@ ENAS_DontAlign
Don't align escaped newlines.
Definition Format.h:480
@ ENAS_Left
Align escaped newlines as far left as possible.
Definition Format.h:488
@ ENAS_Right
Align escaped newlines in the right-most column.
Definition Format.h:505
@ ENAS_LeftWithLastLine
Align escaped newlines as far left as possible, using the last line of the preprocessor directive as ...
Definition Format.h:497
SpacesInAnglesStyle
Styles for adding spacing after < and before > in template argument lists.
Definition Format.h:5675
@ SIAS_Never
Remove spaces after < and before >.
Definition Format.h:5681
@ SIAS_Always
Add spaces after < and before >.
Definition Format.h:5687
@ SIAS_Leave
Keep a single space after < and before > if any spaces were present.
Definition Format.h:5690
BinPackArgumentsStyle
Different ways to try to fit all arguments on a line.
Definition Format.h:4284
@ BPAS_OnePerLine
Put all arguments on the current line if they fit.
Definition Format.h:4302
@ BPAS_BinPack
Bin-pack arguments.
Definition Format.h:4292
@ BPAS_UseBreakAfter
Use the BreakAfter option to handle argument packing instead.
Definition Format.h:4305
SortUsingDeclarationsOptions
Using declaration sorting options.
Definition Format.h:5218
@ SUD_LexicographicNumeric
Using declarations are sorted in the order defined as follows: Split the strings by :: and discard an...
Definition Format.h:5254
@ SUD_Lexicographic
Using declarations are sorted in the order defined as follows: Split the strings by :: and discard an...
Definition Format.h:5239
@ SUD_Never
Using declarations are never sorted.
Definition Format.h:5227
SpaceInEmptyBracesStyle
This option is deprecated.
Definition Format.h:5612
@ SIEB_Always
Always insert a space in empty braces.
Definition Format.h:5620
@ SIEB_Block
Only insert a space in empty blocks.
Definition Format.h:5628
@ SIEB_Never
Never insert a space in empty braces.
Definition Format.h:5636
RemoveParenthesesStyle
Types of redundant parentheses to remove.
Definition Format.h:4856
@ RPS_Leave
Do not remove parentheses.
Definition Format.h:4863
@ RPS_ReturnStatement
Also remove parentheses enclosing the expression in a return/co_return statement.
Definition Format.h:4878
@ RPS_MultipleParentheses
Replace multiple parentheses with single parentheses.
Definition Format.h:4870
PointerAlignmentStyle
The &, && and * alignment style.
Definition Format.h:4532
@ PAS_Left
Align pointer to the left.
Definition Format.h:4537
@ PAS_Middle
Align pointer in the middle.
Definition Format.h:4547
@ PAS_Right
Align pointer to the right.
Definition Format.h:4542
NamespaceIndentationKind
Different ways to indent namespace contents.
Definition Format.h:4030
@ NI_None
Don't indent in namespaces.
Definition Format.h:4040
@ NI_All
Indent in all namespaces.
Definition Format.h:4060
@ NI_Inner
Indent only in inner namespaces (nested in other namespaces).
Definition Format.h:4050
ReturnTypeBreakingStyle
Different ways to break after the function definition or declaration return type.
Definition Format.h:1111
@ RTBS_TopLevelDefinitions
Always break after the return type of top-level definitions.
Definition Format.h:1200
@ RTBS_ExceptShortType
Same as Automatic above, except that there is no break after short return types.
Definition Format.h:1136
@ RTBS_All
Always break after the return type.
Definition Format.h:1154
@ RTBS_TopLevel
Always break after the return types of top-level functions.
Definition Format.h:1169
@ RTBS_None
This is deprecated. See Automatic below.
Definition Format.h:1113
@ RTBS_Automatic
Break after return type based on PenaltyReturnTypeOnItsOwnLine.
Definition Format.h:1124
@ RTBS_AllDefinitions
Always break after the return type of function definitions.
Definition Format.h:1186
ReferenceAlignmentStyle
The & and && alignment style.
Definition Format.h:4716
@ RAS_Right
Align reference to the right.
Definition Format.h:4728
@ RAS_Left
Align reference to the left.
Definition Format.h:4723
@ RAS_Pointer
Align reference like PointerAlignment.
Definition Format.h:4718
@ RAS_Middle
Align reference in the middle.
Definition Format.h:4733
IndentGotoLabelStyle
Options for indenting goto labels.
Definition Format.h:3338
@ IGLS_InnerIndent
Indent goto labels to the surrounding statements (current indenting level).
Definition Format.h:3375
@ IGLS_OuterIndent
Indent goto labels to the enclosing block (previous indenting level).
Definition Format.h:3362
@ IGLS_HalfIndent
Indent goto labels to half the indentation of the surrounding code.
Definition Format.h:3388
@ IGLS_NoIndent
Do not indent goto labels.
Definition Format.h:3350
QualifierAlignmentStyle
Different specifiers and qualifiers alignment styles.
Definition Format.h:4570
@ QAS_Right
Change specifiers/qualifiers to be right-aligned.
Definition Format.h:4589
@ QAS_Custom
Change specifiers/qualifiers to be aligned based on QualifierOrder.
Definition Format.h:4601
@ QAS_Left
Change specifiers/qualifiers to be left-aligned.
Definition Format.h:4583
@ QAS_Leave
Don't change specifiers/qualifiers to either Left or Right alignment (default).
Definition Format.h:4577
OperandAlignmentStyle
Different styles for aligning operands.
Definition Format.h:513
@ OAS_Align
Horizontally align operands of binary and ternary expressions.
Definition Format.h:533
@ OAS_AlignAfterOperator
Horizontally align operands of binary and ternary expressions.
Definition Format.h:543
@ OAS_DontAlign
Do not align operands of binary and ternary expressions.
Definition Format.h:517
bool PadOperators
Only for AlignConsecutiveAssignments.
Definition Format.h:257
bool AlignFunctionDeclarations
Only for AlignConsecutiveDeclarations.
Definition Format.h:217
bool SplitEmptyRecord
If false, empty record (e.g.
Definition Format.h:1660
bool AfterClass
Wrap class definitions.
Definition Format.h:1451
bool AfterStruct
Wrap struct definitions.
Definition Format.h:1534
bool AfterRequiresExpression
Wrap requires expression body.
Definition Format.h:1520
bool AfterUnion
Wrap union definitions.
Definition Format.h:1548
bool AfterEnum
Wrap enum definitions.
Definition Format.h:1466
bool AfterObjCDeclaration
Wrap ObjC definitions (interfaces, implementations...).
Definition Format.h:1504
bool AfterNamespace
Wrap namespace definitions.
Definition Format.h:1498
BraceWrappingAfterControlStatementStyle AfterControlStatement
Wrap control statements (if/for/while/switch/..).
Definition Format.h:1454
bool AfterFunction
Wrap function definitions.
Definition Format.h:1482
bool SplitEmptyFunction
If false, empty function body can be put on a single line.
Definition Format.h:1648
std::optional< FormatStyle > Get(LanguageKind Language) const
Definition Format.cpp:2642
bool AtStartOfBlock
Keep empty lines at start of a block.
Definition Format.h:3804
BinPackArgumentsStyle BinPack
The bin pack arguments style to use.
Definition Format.h:4313
BinPackParametersStyle BinPack
The bin pack parameters style to use.
Definition Format.h:4447
Different styles for merging short functions containing at most one statement.
Definition Format.h:893
static ShortFunctionStyle setAll()
Definition Format.h:943
static ShortFunctionStyle setEmptyOnly()
Definition Format.h:934
static ShortFunctionStyle setEmptyAndInline()
Definition Format.h:937
bool AfterControlStatements
If true, put space between control statement keywords (for/if/while...) and opening parentheses.
Definition Format.h:5469
bool AfterForeachMacros
If true, put space between foreach macros and opening parentheses.
Definition Format.h:5476
bool BeforeNonEmptyParentheses
If true, put a space before opening parentheses only if the parentheses are not empty.
Definition Format.h:5547
bool AfterIfMacros
If true, put space between if macros and opening parentheses.
Definition Format.h:5497
bool AfterPlacementOperator
If true, put a space between operator new/delete and opening parenthesis.
Definition Format.h:5520
TrailingCommentsAlignmentKinds Kind
Specifies the way to align trailing comments.
Definition Format.h:585
unsigned OverEmptyLines
How many empty lines to apply alignment.
Definition Format.h:608
bool AlignPPAndNotPP
If comments following preprocessor directive should be aligned with comments that don't.
Definition Format.h:617
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition Format.h:51
@ UT_Never
Never use tab.
Definition Format.h:6086
bool SpaceBeforeInheritanceColon
If false, spaces will be removed before inheritance colon.
Definition Format.h:5380
unsigned ContinuationIndentWidth
Indent width for line continuations.
Definition Format.h:2899
bool AlwaysBreakBeforeMultilineStrings
This option is renamed to BreakAfterReturnType.
Definition Format.h:1226
LanguageStandard Standard
Parse and format C++ constructs compatible with this standard.
Definition Format.h:5956
bool BreakAdjacentStringLiterals
Break between adjacent string literals.
Definition Format.h:1701
ReturnTypeBreakingStyle BreakAfterReturnType
The function declaration return type breaking style to use.
Definition Format.h:1858
LanguageKind
Supported languages.
Definition Format.h:3874
@ LK_C
Should be used for C.
Definition Format.h:3878
@ LK_CSharp
Should be used for C#.
Definition Format.h:3882
@ LK_Java
Should be used for Java.
Definition Format.h:3884
@ LK_Cpp
Should be used for C++.
Definition Format.h:3880
@ LK_JavaScript
Should be used for JavaScript.
Definition Format.h:3886
@ LK_ObjC
Should be used for Objective-C, Objective-C++.
Definition Format.h:3890
@ LK_Verilog
Should be used for Verilog and SystemVerilog.
Definition Format.h:3901
@ LK_TableGen
Should be used for TableGen code.
Definition Format.h:3894
@ LK_Proto
Should be used for Protocol Buffers
Definition Format.h:3892
@ LK_Json
Should be used for JSON.
Definition Format.h:3888
@ LK_TextProto
Should be used for Protocol Buffer messages in text format.
Definition Format.h:3897
SortIncludesOptions SortIncludes
Controls if and how clang-format will sort #includes.
Definition Format.h:5191
BreakInheritanceListStyle BreakInheritanceList
The inheritance list style to use.
Definition Format.h:2835
bool BreakAfterOpenBracketIf
Force break after the left parenthesis of an if control statement when the expression exceeds the col...
Definition Format.h:1834
unsigned IndentWidth
The number of columns to use for indentation.
Definition Format.h:3477
std::vector< std::string > AttributeMacros
This option is renamed to BreakTemplateDeclarations.
Definition Format.h:1296
@ SLS_All
Merge all lambdas fitting on a single line.
Definition Format.h:1050
@ SLS_Empty
Only merge empty lambdas.
Definition Format.h:1036
@ SDS_Leave
Leave definition blocks as they are.
Definition Format.h:5041
bool IndentRequiresClause
Indent the requires clause in a template.
Definition Format.h:3463
SpacesInAnglesStyle SpacesInAngles
The SpacesInAnglesStyle to use for template argument lists.
Definition Format.h:5694
bool KeepFormFeed
This option is deprecated.
Definition Format.h:3833
bool IndentCaseLabels
Indent case labels one level from the switch statement.
Definition Format.h:3282
std::vector< RawStringFormat > RawStringFormats
Defines hints for detecting supported languages code blocks in raw strings.
Definition Format.h:4713
@ SJSIO_Before
Static imports are placed before non-static imports.
Definition Format.h:5201
@ SJSIO_After
Static imports are placed after non-static imports.
Definition Format.h:5208
PPDirectiveIndentStyle IndentPPDirectives
The preprocessor directive indenting style to use.
Definition Format.h:3440
bool RemoveSemicolon
Remove semicolons after the closing braces of functions and constructors/destructors.
Definition Format.h:4907
@ ETC_Leave
Don't insert or remove trailing commas.
Definition Format.h:3101
bool SpaceBeforeJsonColon
If true, a space will be added before a JSON colon.
Definition Format.h:5391
@ TCS_Wrapped
Insert trailing commas in container literals that were wrapped over multiple lines.
Definition Format.h:3538
@ TCS_None
Do not insert trailing commas.
Definition Format.h:3532
unsigned PenaltyBreakBeforeFirstCallParameter
The penalty for breaking a function call after call(.
Definition Format.h:4488
bool SpaceBeforeCtorInitializerColon
If false, spaces will be removed before constructor initializer colon.
Definition Format.h:5364
@ BPPS_OnePerLine
Put all parameters on the current line if they fit.
Definition Format.h:4428
@ BPPS_BinPack
Bin-pack parameters.
Definition Format.h:4418
BinaryOperatorStyle BreakBeforeBinaryOperators
The way to wrap binary operators.
Definition Format.h:1932
bool IndentExportBlock
If true, clang-format will indent the body of an export { ... } block.
Definition Format.h:3295
@ BPS_Never
Never bin-pack parameters.
Definition Format.h:1887
@ BPS_Auto
Automatically determine parameter bin-packing behavior.
Definition Format.h:1883
BitFieldColonSpacingStyle BitFieldColonSpacing
The BitFieldColonSpacingStyle to use for bitfields.
Definition Format.h:1349
@ RCS_Always
Apply indentation rules and reflow long comments into new lines, trying to obey the ColumnLimit.
Definition Format.h:4770
@ ELBAMS_LogicalBlock
Add empty line only when access modifier starts a new logical block.
Definition Format.h:3067
unsigned SpacesBeforeTrailingComments
If true, spaces may be inserted into ().
Definition Format.h:5671
@ BCIS_BeforeColon
Break constructor initializers before the colon and after the commas.
Definition Format.h:2670
@ BCIS_BeforeComma
Break constructor initializers before the colon and commas, and align the commas with the colon.
Definition Format.h:2678
@ IEBS_AfterExternBlock
Backwards compatible with AfterExternBlock's indenting.
Definition Format.h:3316
bool IndentCaseBlocks
Indent case label blocks one level from the case label.
Definition Format.h:3263
bool InsertBraces
Insert braces after control statements (if, else, for, do, and while) in C++ unless the control state...
Definition Format.h:3523
BreakBeforeConceptDeclarationsStyle BreakBeforeConceptDeclarations
The concept declaration style to use.
Definition Format.h:2454
BreakTemplateDeclarationsStyle BreakTemplateDeclarations
The template declaration breaking style to use.
Definition Format.h:2839
bool DerivePointerAlignment
This option is deprecated.
Definition Format.h:2974
@ BOS_All
Break before operators.
Definition Format.h:1927
@ BOS_None
Break after operators.
Definition Format.h:1903
@ BOS_NonAssignment
Break before operators that aren't assignments.
Definition Format.h:1915
@ LE_DeriveLF
Use \n unless the input has more lines ending in \r\n.
Definition Format.h:3931
bool SpacesInSquareBrackets
If true, spaces will be inserted after [ and before ].
Definition Format.h:5917
bool IndentWrappedFunctionNames
Indent if a function definition or declaration is wrapped after the type.
Definition Format.h:3491
AlignConsecutiveStyle AlignConsecutiveTableGenBreakingDAGArgColons
Style of aligning consecutive TableGen DAGArg operator colons.
Definition Format.h:449
WrapNamespaceBodyWithEmptyLinesStyle WrapNamespaceBodyWithEmptyLines
Wrap namespace body with empty lines.
Definition Format.h:6175
bool FixNamespaceComments
If true, clang-format adds missing namespace end comments for namespaces and fixes invalid existing o...
Definition Format.h:3156
bool ObjCSpaceBeforeProtocolList
Add a space in front of an Objective-C protocol list, i.e.
Definition Format.h:4256
@ TCAS_Never
Don't align trailing comments but other formatter applies.
Definition Format.h:579
@ TCAS_Always
Align trailing comments.
Definition Format.h:570
RemoveParenthesesStyle RemoveParentheses
Remove redundant parentheses.
Definition Format.h:4889
LanguageKind Language
The language that this format style targets.
Definition Format.h:3922
@ NLCS_Leave
Leave this component of the literal as is.
Definition Format.h:4083
bool BreakBeforeCloseBracketFunction
Force break before the right parenthesis of a function (declaration, definition, call) when the param...
Definition Format.h:2391
@ SIPO_Custom
Configure each individual space in parentheses in SpacesInParensOptions.
Definition Format.h:5799
@ SIPO_Never
Never put a space in parentheses.
Definition Format.h:5796
@ SRS_EmptyAndAttached
Only merge empty records if the opening brace was not wrapped, i.e.
Definition Format.h:1074
bool RemoveBracesLLVM
Remove optional braces of control statements (if, else, for, and while) in C++ according to the LLVM ...
Definition Format.h:4830
@ BBIAS_OnlyMultiline
Break before inline ASM colon if the line length is longer than column limit.
Definition Format.h:2471
bool VerilogBreakBetweenInstancePorts
For Verilog, put each port on its own line in module instantiations.
Definition Format.h:6125
unsigned TabWidth
The number of columns used for tab stops.
Definition Format.h:6041
BreakBeforeReturnTypeStyle BreakBeforeReturnType
The function declaration/definition return type breaking style to use.
Definition Format.h:2508
@ PPDIS_None
Does not indent any directives.
Definition Format.h:3405
@ LBI_Signature
Align lambda body relative to the lambda signature.
Definition Format.h:3844
std::vector< std::string > JavaImportGroups
A vector of prefixes ordered by the desired groups for Java imports.
Definition Format.h:3726
bool AllowShortCaseLabelsOnASingleLine
If true, short case labels will be contracted to a single line.
Definition Format.h:793
unsigned PenaltyBreakFirstLessLess
The penalty for breaking before the first <<.
Definition Format.h:4500
std::vector< std::string > StatementAttributeLikeMacros
Macros which are ignored in front of a statement, as if they were an attribute.
Definition Format.h:5973
unsigned ObjCBlockIndentWidth
The number of characters to use for indentation of ObjC blocks.
Definition Format.h:4189
bool AllowShortLoopsOnASingleLine
If true, while (true) continue; can be put on a single line.
Definition Format.h:1061
int AccessModifierOffset
The extra indent or outdent of access modifiers, e.g.
Definition Format.h:59
bool AllowShortEnumsOnASingleLine
Allow short enums on a single line.
Definition Format.h:826
@ SBS_Empty
Only merge empty blocks.
Definition Format.h:754
@ SBS_Never
Never merge blocks into a single line.
Definition Format.h:746
std::optional< FormatStyle > GetLanguageStyle(LanguageKind Language) const
Definition Format.cpp:2667
std::vector< std::string > IfMacros
A vector of macros that should be interpreted as conditionals instead of as function calls.
Definition Format.h:3197
bool SpaceBeforeEnumUnderlyingTypeColon
If false, spaces will be removed before enum underlying type colon.
Definition Format.h:5372
NamespaceIndentationKind NamespaceIndentation
The indentation used for namespaces.
Definition Format.h:4065
bool BreakArrays
If true, clang-format will always break after a Json array [ otherwise it will scan until the closing...
Definition Format.h:1877
bool BreakAfterJavaFieldAnnotations
Break after each annotation on a field in Java files.
Definition Format.h:2734
@ SIS_WithoutElse
Put short ifs on the same line only if there is no else statement.
Definition Format.h:987
@ SIS_Never
Never put short ifs on the same line.
Definition Format.h:971
bool AllowBreakBeforeQtProperty
Allow breaking before Q_Property keywords READ, WRITE, etc.
Definition Format.h:733
bool BreakBeforeCloseBracketBracedList
Force break before the right bracket of a braced initializer list (when Cpp11BracedListStyle is true)...
Definition Format.h:2380
bool ExperimentalAutoDetectBinPacking
If true, clang-format detects whether function calls and definitions are formatted with one parameter...
Definition Format.h:3140
bool ObjCBreakBeforeNestedBlockParam
Break parameters list into lines when there is nested block parameters in a function call.
Definition Format.h:4213
bool BreakFunctionDeclarationParameters
If true, clang-format will always break before function declaration parameters.
Definition Format.h:2710
OperandAlignmentStyle AlignOperands
If true, horizontally align operands of binary and ternary expressions.
Definition Format.h:549
unsigned PenaltyBreakOpenParenthesis
The penalty for breaking after (.
Definition Format.h:4504
bool BreakAfterOpenBracketLoop
Force break after the left parenthesis of a loop control statement when the expression exceeds the co...
Definition Format.h:1844
friend std::error_code parseConfiguration(llvm::MemoryBufferRef Config, FormatStyle *Style, bool AllowUnknownOptions, llvm::SourceMgr::DiagHandlerTy DiagHandler, void *DiagHandlerCtxt, bool IsDotHFile)
Parse configuration from YAML-formatted text.
Definition Format.cpp:2529
unsigned PenaltyBreakBeforeMemberAccess
The penalty for breaking before a member access operator (.
Definition Format.h:4492
@ BTDS_MultiLine
Force break after template declaration only when the following declaration spans multiple lines.
Definition Format.h:1260
@ BTDS_Yes
Always break after template declaration.
Definition Format.h:1271
bool AllowShortCompoundRequirementOnASingleLine
Allow short compound requirement on a single line.
Definition Format.h:812
SpacesInParensStyle SpacesInParens
If true, spaces will be inserted after ( and before ).
Definition Format.h:5813
SpacesInParensCustom SpacesInParensOptions
Control of individual spaces in parentheses.
Definition Format.h:5906
std::vector< std::string > ForEachMacros
A vector of macros that should be interpreted as foreach loops instead of as function calls.
Definition Format.h:3174
ReferenceAlignmentStyle ReferenceAlignment
Reference alignment style (overrides PointerAlignment for references).
Definition Format.h:4738
bool CompactCaseLabels
Keep the break keyword and the following case label on the same line.
Definition Format.h:2854
AlignConsecutiveStyle AlignConsecutiveTableGenDefinitionColons
Style of aligning consecutive TableGen definition colons.
Definition Format.h:469
TrailingCommaStyle InsertTrailingCommas
If set to TCS_Wrapped will insert trailing commas in container literals (arrays and objects) that wra...
Definition Format.h:3557
unsigned PenaltyBreakTemplateDeclaration
The penalty for breaking after template declaration.
Definition Format.h:4516
SpaceBeforeParensCustom SpaceBeforeParensOptions
Control of individual space before parentheses.
Definition Format.h:5586
BreakConstructorInitializersStyle BreakConstructorInitializers
The break constructor initializers style to use.
Definition Format.h:2696
bool RemoveEmptyLinesInUnwrappedLines
Remove empty lines within unwrapped lines.
Definition Format.h:4853
bool BreakStringLiterals
Allow breaking string literals when formatting.
Definition Format.h:2777
bool SpaceAfterLogicalNot
If true, a space is inserted after the logical not operator (!).
Definition Format.h:5275
@ SBPO_Custom
Configure each individual space before parentheses in SpaceBeforeParensOptions.
Definition Format.h:5447
@ SBPO_NonEmptyParentheses
Put a space before opening parentheses only if the parentheses are not empty.
Definition Format.h:5432
@ SBPO_ControlStatementsExceptControlMacros
Same as SBPO_ControlStatements except this option doesn't apply to ForEach and If macros.
Definition Format.h:5421
@ SBPO_ControlStatements
Put a space before opening parentheses only after control statement keywords (for/if/while....
Definition Format.h:5408
@ SBPO_Always
Always put a space before opening parentheses, except when it's prohibited by the syntax rules (in fu...
Definition Format.h:5444
@ PCIS_BinPack
Bin-pack constructor initializers.
Definition Format.h:4364
@ PCIS_NextLine
Same as PCIS_CurrentLine except that if all constructor initializers do not fit on the current line,...
Definition Format.h:4389
bool ObjCSpaceAfterProperty
Add a space after @property in Objective-C, i.e.
Definition Format.h:4251
@ BBRTS_None
Do not force a break before the return type.
Definition Format.h:2488
bool BreakAfterOpenBracketSwitch
Force break after the left parenthesis of a switch control statement when the expression exceeds the ...
Definition Format.h:1854
BraceBreakingStyle BreakBeforeBraces
The brace breaking style to use.
Definition Format.h:2367
@ BILS_BeforeColon
Break inheritance list before the colon and after the commas.
Definition Format.h:2806
@ BILS_BeforeComma
Break inheritance list before the colon and commas, and align the commas with the colon.
Definition Format.h:2815
@ SIBCS_Leave
Leave existing spaces unchanged.
Definition Format.h:5710
unsigned PenaltyExcessCharacter
The penalty for each character outside of the column limit.
Definition Format.h:4520
std::vector< std::string > WhitespaceSensitiveMacros
A vector of macros which are whitespace-sensitive and should not be touched.
Definition Format.h:6142
bool AlignAfterOpenBracket
If true, horizontally aligns arguments after an open bracket.
Definition Format.h:82
@ DAS_DontBreak
Never break inside DAGArg.
Definition Format.h:6017
unsigned ConstructorInitializerIndentWidth
This option is deprecated.
Definition Format.h:2888
@ BBNSS_Never
No line break allowed.
Definition Format.h:699
bool CompactNamespaces
If true, consecutive namespace declarations will be on the same line.
Definition Format.h:2878
@ RCPS_OwnLine
Always put the requires clause on its own line (possibly followed by a semicolon).
Definition Format.h:4932
@ RCPS_WithPreceding
Try to put the clause together with the preceding part of a declaration.
Definition Format.h:4967
@ RCPS_SingleLine
Try to put everything in the same line if possible.
Definition Format.h:5005
bool BreakBeforeCloseBracketSwitch
Force break before the right parenthesis of a switch control statement when the expression exceeds th...
Definition Format.h:2430
@ LS_Cpp17
Parse and format as C++17.
Definition Format.h:5936
@ LS_Cpp26
Parse and format as C++26.
Definition Format.h:5942
@ LS_Cpp23
Parse and format as C++23.
Definition Format.h:5940
@ LS_Latest
Parse and format using the latest supported language version.
Definition Format.h:5945
@ LS_Cpp11
Parse and format as C++11.
Definition Format.h:5932
@ LS_Auto
Automatic detection based on the input.
Definition Format.h:5947
@ LS_Cpp14
Parse and format as C++14.
Definition Format.h:5934
@ LS_Cpp20
Parse and format as C++20.
Definition Format.h:5938
@ BWACS_Always
Always wrap braces after a control statement.
Definition Format.h:1415
@ BWACS_Never
Never wrap braces after a control statement.
Definition Format.h:1394
RequiresClausePositionStyle RequiresClausePosition
The position of the requires clause.
Definition Format.h:5010
@ JSQS_Single
Always use single quotes.
Definition Format.h:3742
@ JSQS_Leave
Leave string quotes as they are.
Definition Format.h:3736
bool SpaceAfterCStyleCast
If true, a space is inserted after C style casts.
Definition Format.h:5267
AlignConsecutiveStyle AlignConsecutiveBitFields
Style of aligning consecutive bit fields.
Definition Format.h:293
int PPIndentWidth
The number of columns to use for indentation of preprocessor statements.
Definition Format.h:4567
AlignConsecutiveStyle AlignConsecutiveDeclarations
Style of aligning consecutive declarations.
Definition Format.h:305
IntegerLiteralSeparatorStyle IntegerLiteralSeparator
Format integer literal separators (‘’ for C/C++ and _` for C#, Java, and JavaScript).
Definition Format.h:3692
SpaceAroundPointerQualifiersStyle SpaceAroundPointerQualifiers
Defines in which cases to put a space before or after pointer qualifiers.
Definition Format.h:5324
@ IAMS_Never
Use AccessModifierOffset for access modifiers and indent members one level below the record.
Definition Format.h:3211
DefinitionReturnTypeBreakingStyle AlwaysBreakAfterDefinitionReturnType
The function definition return type breaking style to use.
Definition Format.h:1206
ShortRecordStyle AllowShortRecordOnASingleLine
Dependent on the value, struct bar { int i; }; can be put on a single line.
Definition Format.h:1095
bool SpaceBeforeAssignmentOperators
If false, spaces will be removed before assignment operators.
Definition Format.h:5333
BreakBeforeInlineASMColonStyle BreakBeforeInlineASMColon
The inline ASM colon style to use.
Definition Format.h:2483
@ WNBWELS_Leave
Keep existing newlines at the beginning and the end of namespace body.
Definition Format.h:6170
SpaceInEmptyBracesStyle SpaceInEmptyBraces
Specifies when to insert a space in empty braces.
Definition Format.h:5645
@ BS_Mozilla
Like Attach, but break before braces on enum, function, and record definitions.
Definition Format.h:2080
@ BS_Whitesmiths
Like Allman but always indent braces and line up code with braces.
Definition Format.h:2250
@ BS_Allman
Always break before braces.
Definition Format.h:2190
@ BS_Stroustrup
Like Attach, but break before function definitions, catch, and else.
Definition Format.h:2130
@ BS_Linux
Like Attach, but break before braces on function, namespace and class definitions.
Definition Format.h:2030
@ BS_WebKit
Like Attach, but break before functions.
Definition Format.h:2360
@ BS_Custom
Configure each individual brace in BraceWrapping.
Definition Format.h:2362
@ BS_GNU
Always break before braces and add an extra level of indentation to braces of control statements,...
Definition Format.h:2313
@ BS_Attach
Always attach braces to surrounding context.
Definition Format.h:1980
bool ObjCSpaceAfterMethodDeclarationPrefix
Add or remove a space between the '-'/'+' and the return type in Objective-C method declarations.
Definition Format.h:4246
@ ABS_Leave
Leave the line breaking after the last attribute of the group as is.
Definition Format.h:1759
bool BreakBeforeCloseBracketLoop
Force break before the right parenthesis of a loop control statement when the expression exceeds the ...
Definition Format.h:2417
ShortLambdaStyle AllowShortLambdasOnASingleLine
Dependent on the value, auto lambda []() { return 0; } can be put on a single line.
Definition Format.h:1056
bool BinPackLongBracedList
This option is deprecated.
Definition Format.h:1316
unsigned PenaltyBreakScopeResolution
The penalty for breaking after ::.
Definition Format.h:4508
unsigned PenaltyReturnTypeOnItsOwnLine
Penalty for putting the return type of a function onto its own line.
Definition Format.h:4529
@ BFCS_Both
Add one space on each side of the :
Definition Format.h:1328
PointerAlignmentStyle PointerAlignment
Pointer and reference alignment style.
Definition Format.h:4552
bool BreakBeforeTemplateCloser
If true, break before a template closing bracket (>) when there is a line break after the matching op...
Definition Format.h:2535
int BracedInitializerIndentWidth
The number of columns to use to indent the contents of braced init lists.
Definition Format.h:1382
PackParametersStyle PackParameters
Options related to packing parameters of function declarations and definitions.
Definition Format.h:4480
bool BreakFunctionDefinitionParameters
If true, clang-format will always break before function definition parameters.
Definition Format.h:2724
@ REI_OuterScope
Align requires expression body relative to the indentation level of the outer scope the requires expr...
Definition Format.h:5023
PackConstructorInitializersStyle PackConstructorInitializers
The pack constructor initializers style to use.
Definition Format.h:4409
@ BBCDS_Always
Always break before concept, putting it in the line after the template declaration.
Definition Format.h:2449
ReflowCommentsStyle ReflowComments
Comment reformatting style.
Definition Format.h:4776
KeepEmptyLinesStyle KeepEmptyLines
Which empty lines are kept.
Definition Format.h:3816
bool AllowAllParametersOfDeclarationOnNextLine
This option is deprecated.
Definition Format.h:686
AlignConsecutiveStyle AlignConsecutiveTableGenCondOperatorColons
Style of aligning consecutive TableGen cond operator colons.
Definition Format.h:459
@ BLS_AlignFirstComment
Same as FunctionCall, except for the handling of a comment at the begin, it then aligns everything fo...
Definition Format.h:2956
@ BLS_Block
Best suited for pre C++11 braced lists.
Definition Format.h:2918
bool AllowShortCaseExpressionOnASingleLine
Whether to merge a short switch labeled rule into a single line.
Definition Format.h:779
bool BreakBeforeCloseBracketIf
Force break before the right parenthesis of an if control statement when the expression exceeds the c...
Definition Format.h:2404
unsigned MaxEmptyLinesToKeep
The maximum number of consecutive empty lines to keep.
Definition Format.h:4027
bool SpaceBeforeSquareBrackets
If true, spaces will be before [.
Definition Format.h:5596
BinPackStyle ObjCBinPackProtocolList
Controls bin-packing Objective-C protocol conformance list items into as few lines as possible when t...
Definition Format.h:4178
PackArgumentsStyle PackArguments
Options related to packing arguments of function calls.
Definition Format.h:4347
ShortCaseStatementsAlignmentStyle AlignConsecutiveShortCaseStatements
Style of aligning consecutive short case labels.
Definition Format.h:434
EscapedNewlineAlignmentStyle AlignEscapedNewlines
Options for aligning backslashes in escaped newlines.
Definition Format.h:510
SpacesInLineComment SpacesInLineCommentPrefix
How many spaces are allowed at the start of a line comment.
Definition Format.h:5784
std::string CommentPragmas
A regular expression that describes comments with special meaning, which should not be split into lin...
Definition Format.h:2795
bool isJavaScript() const
Definition Format.h:3909
DAGArgStyle TableGenBreakInsideDAGArg
The styles of the line break inside the DAGArg in TableGen.
Definition Format.h:6037
JavaScriptQuoteStyle JavaScriptQuotes
The JavaScriptQuoteStyle to use for JavaScript strings.
Definition Format.h:3753
bool SpacesInContainerLiterals
If true, spaces will be inserted around if/for/switch/while conditions.
Definition Format.h:5736
SortJavaStaticImportOptions SortJavaStaticImport
When sorting Java imports, by default static imports are placed before non-static imports.
Definition Format.h:5215
BreakBinaryOperationsOptions BreakBinaryOperations
The break binary operations style to use.
Definition Format.h:2660
@ SAPQ_Default
Don't ensure spaces around pointer qualifiers and use PointerAlignment instead.
Definition Format.h:5301
bool SpaceBeforeRangeBasedForLoopColon
If false, spaces will be removed before range-based for loop colon.
Definition Format.h:5605
bool DisableFormat
Disables formatting completely.
Definition Format.h:2978
@ ELAAMS_Never
Remove all empty lines after access modifiers.
Definition Format.h:2998
@ DRTBS_All
Always break after the return type.
Definition Format.h:1104
@ DRTBS_TopLevel
Always break after the return types of top-level functions.
Definition Format.h:1106
@ DRTBS_None
Break after return type automatically.
Definition Format.h:1102
bool AllowShortNamespacesOnASingleLine
If true, namespace a { class b; } can be put on a single line.
Definition Format.h:1065
AttributeBreakingStyle BreakAfterAttributes
Break after a group of C++11 attributes before variable or function (including constructor/destructor...
Definition Format.h:1803
TrailingCommentsAlignmentStyle AlignTrailingComments
Control of trailing comments.
Definition Format.h:646
@ AIAS_None
Don't align array initializer columns.
Definition Format.h:107
LambdaBodyIndentationKind LambdaBodyIndentation
The indentation style of lambda bodies.
Definition Format.h:3867
QualifierAlignmentStyle QualifierAlignment
Different ways to arrange specifiers and qualifiers (e.g.
Definition Format.h:4613
@ BBO_Never
Don't break binary operations.
Definition Format.h:2559
BraceWrappingFlags BraceWrapping
Control of individual brace wrapping cases.
Definition Format.h:1688
@ ENAS_Left
Align escaped newlines as far left as possible.
Definition Format.h:488
@ ENAS_Right
Align escaped newlines in the right-most column.
Definition Format.h:505
AlignConsecutiveStyle AlignConsecutiveMacros
Style of aligning consecutive macro definitions.
Definition Format.h:318
IndentAccessModifierStyle IndentAccessModifiers
Specify how access modifiers and record members are indented.
Definition Format.h:3240
std::vector< std::string > StatementMacros
A vector of macros that should be interpreted as complete statements.
Definition Format.h:5983
@ SIAS_Never
Remove spaces after < and before >.
Definition Format.h:5681
@ BPAS_OnePerLine
Put all arguments on the current line if they fit.
Definition Format.h:4302
@ BPAS_BinPack
Bin-pack arguments.
Definition Format.h:4292
@ BPAS_UseBreakAfter
Use the BreakAfter option to handle argument packing instead.
Definition Format.h:4305
@ SUD_LexicographicNumeric
Using declarations are sorted in the order defined as follows: Split the strings by :: and discard an...
Definition Format.h:5254
@ SUD_Never
Using declarations are never sorted.
Definition Format.h:5227
AlignConsecutiveStyle AlignConsecutiveAssignments
Style of aligning consecutive assignments.
Definition Format.h:281
@ SIEB_Always
Always insert a space in empty braces.
Definition Format.h:5620
@ SIEB_Never
Never insert a space in empty braces.
Definition Format.h:5636
ShortIfStyle AllowShortIfStatementsOnASingleLine
Dependent on the value, if (a) return; can be put on a single line.
Definition Format.h:1022
@ RPS_Leave
Do not remove parentheses.
Definition Format.h:4863
@ RPS_ReturnStatement
Also remove parentheses enclosing the expression in a return/co_return statement.
Definition Format.h:4878
std::vector< std::string > TableGenBreakingDAGArgOperators
Works only when TableGenBreakInsideDAGArg is not DontBreak.
Definition Format.h:6009
EmptyLineBeforeAccessModifierStyle EmptyLineBeforeAccessModifier
Defines in which cases to put empty line before access modifiers.
Definition Format.h:3092
EnumTrailingCommaStyle EnumTrailingComma
Insert a comma (if missing) or remove the comma at the end of an enum enumerator list.
Definition Format.h:3125
bool SpaceBeforeCaseColon
If false, spaces will be removed before case colon.
Definition Format.h:5343
BreakBeforeNoexceptSpecifierStyle AllowBreakBeforeNoexceptSpecifier
Controls if there could be a line break before a noexcept specifier.
Definition Format.h:727
bool JavaScriptWrapImports
Whether to wrap JavaScript import/export statements.
Definition Format.h:3769
bool BreakAfterOpenBracketFunction
Force break after the left parenthesis of a function (declaration, definition, call) when the paramet...
Definition Format.h:1824
bool SkipMacroDefinitionBody
Do not format macro definition body.
Definition Format.h:5120
unsigned PenaltyBreakAssignment
The penalty for breaking around an assignment operator.
Definition Format.h:4484
@ PAS_Left
Align pointer to the left.
Definition Format.h:4537
@ PAS_Right
Align pointer to the right.
Definition Format.h:4542
unsigned PenaltyBreakString
The penalty for each line break introduced inside a string literal.
Definition Format.h:4512
RequiresExpressionIndentationKind RequiresExpressionIndentation
The indentation used for requires expression bodies.
Definition Format.h:5036
IndentGotoLabelStyle IndentGotoLabels
The goto label indenting style to use.
Definition Format.h:3393
bool SpaceAfterTemplateKeyword
If true, a space will be inserted after the template keyword.
Definition Format.h:5291
unsigned PenaltyIndentedWhitespace
Penalty for each character of whitespace indentation (counted relative to leading non-whitespace colu...
Definition Format.h:4525
ArrayInitializerAlignmentStyle AlignArrayOfStructures
If not None, when using initialization for an array of structs aligns the fields into columns.
Definition Format.h:118
@ NI_None
Don't indent in namespaces.
Definition Format.h:4040
@ NI_All
Indent in all namespaces.
Definition Format.h:4060
@ NI_Inner
Indent only in inner namespaces (nested in other namespaces).
Definition Format.h:4050
ShortBlockStyle AllowShortBlocksOnASingleLine
Dependent on the value, while (true) { continue; } can be put on a single line.
Definition Format.h:766
ShortFunctionStyle AllowShortFunctionsOnASingleLine
Dependent on the value, int f() { return 0; } can be put on a single line.
Definition Format.h:951
bool AllowAllArgumentsOnNextLine
If a function call or braced initializer list doesn't fit on a line, allow putting all arguments onto...
Definition Format.h:663
unsigned PenaltyBreakComment
The penalty for each line break introduced inside a comment.
Definition Format.h:4496
bool SpaceAfterOperatorKeyword
If true, a space will be inserted after the operator keyword.
Definition Format.h:5283
@ RTBS_TopLevel
Always break after the return types of top-level functions.
Definition Format.h:1169
@ RTBS_None
This is deprecated. See Automatic below.
Definition Format.h:1113
@ RTBS_AllDefinitions
Always break after the return type of function definitions.
Definition Format.h:1186
@ RAS_Pointer
Align reference like PointerAlignment.
Definition Format.h:4718
EmptyLineAfterAccessModifierStyle EmptyLineAfterAccessModifier
Defines when to put an empty line after access modifiers.
Definition Format.h:3029
@ IGLS_OuterIndent
Indent goto labels to the enclosing block (previous indenting level).
Definition Format.h:3362
bool InsertNewlineAtEOF
Insert a newline at end of file if missing.
Definition Format.h:3527
SpaceBeforeParensStyle SpaceBeforeParens
Defines in which cases to put a space before opening parentheses.
Definition Format.h:5452
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:5355
NumericLiteralCaseStyle NumericLiteralCase
Capitalization style for numeric literals.
Definition Format.h:4145
UseTabStyle UseTab
The way to use tab characters in the resulting file.
Definition Format.h:6102
@ QAS_Leave
Don't change specifiers/qualifiers to either Left or Right alignment (default).
Definition Format.h:4577
@ OAS_Align
Horizontally align operands of binary and ternary expressions.
Definition Format.h:533
@ OAS_DontAlign
Do not align operands of binary and ternary expressions.
Definition Format.h:517
LineEndingStyle LineEnding
Line ending style (\n or \r\n) to use.
Definition Format.h:3938
bool BreakAfterOpenBracketBracedList
Force break after the left bracket of a braced initializer list (when Cpp11BracedListStyle is true) w...
Definition Format.h:1814
bool BreakBeforeTernaryOperators
If true, ternary operators will be placed after line breaks.
Definition Format.h:2550
BracedListStyle Cpp11BracedListStyle
The style to handle braced lists.
Definition Format.h:2961
unsigned ShortNamespaceLines
The maximal number of unwrapped lines that a short namespace spans.
Definition Format.h:5116
SortUsingDeclarationsOptions SortUsingDeclarations
Controls if and how clang-format will sort using declarations.
Definition Format.h:5259
IndentExternBlockStyle IndentExternBlock
IndentExternBlockStyle is the type of indenting of extern blocks.
Definition Format.h:3335
SeparateDefinitionStyle SeparateDefinitionBlocks
Specifies the use of empty lines to separate definition blocks, including classes,...
Definition Format.h:5094
tooling::IncludeStyle IncludeStyle
Definition Format.h:3176
unsigned ColumnLimit
The column limit.
Definition Format.h:2785
A wrapper around a Token storing information about the whitespace characters preceding it.
bool Optional
Is optional and can be removed.
bool isNot(T Kind) const
unsigned Finalized
If true, this token has been fully formatted (indented and potentially re-formatted inside),...
bool isNoneOf(Ts... Ks) const
FormatToken * Next
The next token in the unwrapped line.
bool LBraceInserted
Whether a left brace was already inserted after this token when an earlier run was analyzed.
bool is(tok::TokenKind Kind) const
bool isOneOf(A K1, B K2) const
int8_t BraceCount
Number of optional braces to be inserted after this token: -1: a single left brace 0: no braces >0: n...
Represents the status of a formatting attempt.
Definition Format.h:6547
MainIncludeCharDiscriminator MainIncludeChar
When guessing whether a include is the "main" include, only the include directives that use the speci...
@ IBS_Preserve
Sort each #include block separately.
@ IBS_RegroupByDirectory
Merge multiple #include blocks together and sort as one.
@ IBS_Regroup
Merge multiple #include blocks together and sort as one.
@ IBS_Merge
Merge multiple #include blocks together and sort as one.
std::string IncludeIsMainRegex
Specify a regular expression of suffixes that are allowed in the file-to-main-include mapping.
@ MICD_Quote
Main include uses quotes: #include "foo.hpp" (the default).
IncludeBlocksStyle IncludeBlocks
Dependent on the value, multiple #include blocks can be sorted as one and divided based on category.
std::vector< IncludeCategory > IncludeCategories
Regular expressions denoting the different #include categories used for ordering #includes.
static FormatStyle & element(IO &IO, std::vector< FormatStyle > &Seq, size_t Index)
Definition Format.cpp:1665
static size_t size(IO &IO, std::vector< FormatStyle > &Seq)
Definition Format.cpp:1662
static void mapping(IO &IO, FormatStyle &Style)
Definition Format.cpp:1114
static void enumInput(IO &IO, FormatStyle::AlignConsecutiveStyle &Value)
Definition Format.cpp:62
static void mapping(IO &IO, FormatStyle::AlignConsecutiveStyle &Value)
Definition Format.cpp:104
static void mapping(IO &IO, FormatStyle::BinaryOperationBreakRule &Value)
Definition Format.cpp:332
static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping)
Definition Format.cpp:219
static void mapping(IO &IO, FormatStyle::BreakBinaryOperationsOptions &Value)
Definition Format.cpp:356
static void enumInput(IO &IO, FormatStyle::BreakBinaryOperationsOptions &Value)
Definition Format.cpp:343
static void mapping(IO &IO, FormatStyle::IntegerLiteralSeparatorStyle &Base)
Definition Format.cpp:507
static void mapping(IO &IO, FormatStyle::KeepEmptyLinesStyle &Value)
Definition Format.cpp:534
static void mapping(IO &IO, FormatStyle::NumericLiteralCaseStyle &Value)
Definition Format.cpp:618
static void mapping(IO &IO, FormatStyle::PackArgumentsStyle &Value)
Definition Format.cpp:659
static void mapping(IO &IO, FormatStyle::PackParametersStyle &Value)
Definition Format.cpp:640
static void mapping(IO &IO, FormatStyle::RawStringFormat &Format)
Definition Format.cpp:698
static void mapping(IO &IO, FormatStyle::ShortCaseStatementsAlignmentStyle &Value)
Definition Format.cpp:119
static void mapping(IO &IO, FormatStyle::ShortFunctionStyle &Value)
Definition Format.cpp:821
static void enumInput(IO &IO, FormatStyle::ShortFunctionStyle &Value)
Definition Format.cpp:806
static void mapping(IO &IO, FormatStyle::SortIncludesOptions &Value)
Definition Format.cpp:893
static void enumInput(IO &IO, FormatStyle::SortIncludesOptions &Value)
Definition Format.cpp:863
static void mapping(IO &IO, FormatStyle::SpaceBeforeParensCustom &Spacing)
Definition Format.cpp:938
static void mapping(IO &IO, FormatStyle::SpacesInLineComment &Space)
Definition Format.cpp:1010
static void mapping(IO &IO, FormatStyle::SpacesInParensCustom &Spaces)
Definition Format.cpp:1023
static void mapping(IO &IO, FormatStyle::TrailingCommentsAlignmentStyle &Value)
Definition Format.cpp:1080
static void enumInput(IO &IO, FormatStyle::TrailingCommentsAlignmentStyle &Value)
Definition Format.cpp:1057
static void enumeration(IO &IO, BracketAlignmentStyle &Value)
Definition Format.cpp:244
static void enumeration(IO &IO, FormatStyle::ArrayInitializerAlignmentStyle &Value)
Definition Format.cpp:141
static void enumeration(IO &IO, FormatStyle::AttributeBreakingStyle &Value)
Definition Format.cpp:131
static void enumeration(IO &IO, FormatStyle::BinPackArgumentsStyle &Value)
Definition Format.cpp:160
static void enumeration(IO &IO, FormatStyle::BinPackParametersStyle &Value)
Definition Format.cpp:173
static void enumeration(IO &IO, FormatStyle::BinPackStyle &Value)
Definition Format.cpp:186
static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value)
Definition Format.cpp:150
static void enumeration(IO &IO, FormatStyle::BitFieldColonSpacingStyle &Value)
Definition Format.cpp:195
static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value)
Definition Format.cpp:205
static void enumeration(IO &IO, FormatStyle::BraceWrappingAfterControlStatementStyle &Value)
Definition Format.cpp:260
static void enumeration(IO &IO, FormatStyle::BracedListStyle &Value)
Definition Format.cpp:401
static void enumeration(IO &IO, FormatStyle::BreakBeforeConceptDeclarationsStyle &Value)
Definition Format.cpp:276
static void enumeration(IO &IO, FormatStyle::BreakBeforeInlineASMColonStyle &Value)
Definition Format.cpp:289
static void enumeration(IO &IO, FormatStyle::BreakBeforeNoexceptSpecifierStyle &Value)
Definition Format.cpp:54
static void enumeration(IO &IO, FormatStyle::BreakBeforeReturnTypeStyle &Value)
Definition Format.cpp:775
static void enumeration(IO &IO, FormatStyle::BreakBinaryOperationsStyle &Value)
Definition Format.cpp:299
static void enumeration(IO &IO, FormatStyle::BreakConstructorInitializersStyle &Value)
Definition Format.cpp:366
static void enumeration(IO &IO, FormatStyle::BreakInheritanceListStyle &Value)
Definition Format.cpp:376
static void enumeration(IO &IO, FormatStyle::BreakTemplateDeclarationsStyle &Value)
Definition Format.cpp:387
static void enumeration(IO &IO, FormatStyle::DAGArgStyle &Value)
Definition Format.cpp:413
static void enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value)
Definition Format.cpp:423
static void enumeration(IO &IO, FormatStyle::EmptyLineAfterAccessModifierStyle &Value)
Definition Format.cpp:452
static void enumeration(IO &IO, FormatStyle::EmptyLineBeforeAccessModifierStyle &Value)
Definition Format.cpp:463
static void enumeration(IO &IO, FormatStyle::EnumTrailingCommaStyle &Value)
Definition Format.cpp:473
static void enumeration(IO &IO, FormatStyle::EscapedNewlineAlignmentStyle &Value)
Definition Format.cpp:436
static void enumeration(IO &IO, FormatStyle::IndentAccessModifierStyle &Value)
Definition Format.cpp:482
static void enumeration(IO &IO, FormatStyle::IndentExternBlockStyle &Value)
Definition Format.cpp:497
static void enumeration(IO &IO, FormatStyle::IndentGotoLabelStyle &Value)
Definition Format.cpp:1683
static void enumeration(IO &IO, FormatStyle::JavaScriptQuoteStyle &Value)
Definition Format.cpp:526
static void enumeration(IO &IO, FormatStyle::LambdaBodyIndentationKind &Value)
Definition Format.cpp:581
static void enumeration(IO &IO, FormatStyle::LanguageKind &Value)
Definition Format.cpp:543
static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value)
Definition Format.cpp:559
static void enumeration(IO &IO, FormatStyle::LineEndingStyle &Value)
Definition Format.cpp:589
static void enumeration(IO &IO, FormatStyle::NamespaceIndentationKind &Value)
Definition Format.cpp:599
static void enumeration(IO &IO, FormatStyle::NumericLiteralComponentStyle &Value)
Definition Format.cpp:609
static void enumeration(IO &IO, FormatStyle::OperandAlignmentStyle &Value)
Definition Format.cpp:627
static void enumeration(IO &IO, FormatStyle::PPDirectiveIndentStyle &Value)
Definition Format.cpp:679
static void enumeration(IO &IO, FormatStyle::PackConstructorInitializersStyle &Value)
Definition Format.cpp:649
static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value)
Definition Format.cpp:666
static void enumeration(IO &IO, FormatStyle::QualifierAlignmentStyle &Value)
Definition Format.cpp:689
static void enumeration(IO &IO, FormatStyle::ReferenceAlignmentStyle &Value)
Definition Format.cpp:720
static void enumeration(IO &IO, FormatStyle::ReflowCommentsStyle &Value)
Definition Format.cpp:708
static void enumeration(IO &IO, FormatStyle::RemoveParenthesesStyle &Value)
Definition Format.cpp:730
static void enumeration(IO &IO, FormatStyle::RequiresClausePositionStyle &Value)
Definition Format.cpp:740
static void enumeration(IO &IO, FormatStyle::RequiresExpressionIndentationKind &Value)
Definition Format.cpp:753
static void enumeration(IO &IO, FormatStyle::ReturnTypeBreakingStyle &Value)
Definition Format.cpp:761
static void enumeration(IO &IO, FormatStyle::SeparateDefinitionStyle &Value)
Definition Format.cpp:788
static void enumeration(IO &IO, FormatStyle::ShortBlockStyle &Value)
Definition Format.cpp:796
static void enumeration(IO &IO, FormatStyle::ShortIfStyle &Value)
Definition Format.cpp:829
static void enumeration(IO &IO, FormatStyle::ShortLambdaStyle &Value)
Definition Format.cpp:843
static void enumeration(IO &IO, FormatStyle::ShortRecordStyle &Value)
Definition Format.cpp:854
static void enumeration(IO &IO, FormatStyle::SortJavaStaticImportOptions &Value)
Definition Format.cpp:904
static void enumeration(IO &IO, FormatStyle::SortUsingDeclarationsOptions &Value)
Definition Format.cpp:913
static void enumeration(IO &IO, FormatStyle::SpaceAroundPointerQualifiersStyle &Value)
Definition Format.cpp:929
static void enumeration(IO &IO, FormatStyle::SpaceBeforeParensStyle &Value)
Definition Format.cpp:959
static void enumeration(IO &IO, FormatStyle::SpaceInEmptyBracesStyle &Value)
Definition Format.cpp:980
static void enumeration(IO &IO, FormatStyle::SpacesInAnglesStyle &Value)
Definition Format.cpp:988
static void enumeration(IO &IO, FormatStyle::SpacesInBlockCommentsStyle &Value)
Definition Format.cpp:1001
static void enumeration(IO &IO, FormatStyle::SpacesInParensStyle &Value)
Definition Format.cpp:1033
static void enumeration(IO &IO, FormatStyle::TrailingCommaStyle &Value)
Definition Format.cpp:1040
static void enumeration(IO &IO, FormatStyle::TrailingCommentsAlignmentKinds &Value)
Definition Format.cpp:1048
static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value)
Definition Format.cpp:1089
static void enumeration(IO &IO, FormatStyle::WrapNamespaceBodyWithEmptyLinesStyle &Value)
Definition Format.cpp:1105
static StringRef input(StringRef Scalar, void *, clang::tok::TokenKind &Value)
Definition Format.cpp:316
static QuotingType mustQuote(StringRef)
Definition Format.cpp:328
static void output(const clang::tok::TokenKind &Value, void *, llvm::raw_ostream &Out)
Definition Format.cpp:308