26#include "llvm/ADT/Sequence.h"
27#include "llvm/ADT/StringSet.h"
30#define DEBUG_TYPE "format-formatter"
32using clang::format::FormatStyle;
34LLVM_YAML_IS_SEQUENCE_VECTOR(FormatStyle::RawStringFormat)
35LLVM_YAML_IS_SEQUENCE_VECTOR(FormatStyle::BinaryOperationBreakRule)
49struct ScalarEnumerationTraits<FormatStyle::BreakBeforeNoexceptSpecifierStyle> {
52 IO.enumCase(
Value,
"Never", FormatStyle::BBNSS_Never);
53 IO.enumCase(
Value,
"OnlyWithParen", FormatStyle::BBNSS_OnlyWithParen);
54 IO.enumCase(
Value,
"Always", FormatStyle::BBNSS_Always);
58template <>
struct MappingTraits<FormatStyle::AlignConsecutiveStyle> {
60 IO.enumCase(
Value,
"None", FormatStyle::AlignConsecutiveStyle{});
61 IO.enumCase(
Value,
"Consecutive",
62 FormatStyle::AlignConsecutiveStyle(
67 IO.enumCase(
Value,
"AcrossEmptyLines",
68 FormatStyle::AlignConsecutiveStyle(
73 IO.enumCase(
Value,
"AcrossComments",
74 FormatStyle::AlignConsecutiveStyle(
79 IO.enumCase(
Value,
"AcrossEmptyLinesAndComments",
80 FormatStyle::AlignConsecutiveStyle(
87 IO.enumCase(
Value,
"true",
88 FormatStyle::AlignConsecutiveStyle(
93 IO.enumCase(
Value,
"false", FormatStyle::AlignConsecutiveStyle{});
96 static void mapping(IO &IO, FormatStyle::AlignConsecutiveStyle &
Value) {
97 IO.mapOptional(
"Enabled",
Value.Enabled);
98 IO.mapOptional(
"AcrossEmptyLines",
Value.AcrossEmptyLines);
99 IO.mapOptional(
"AcrossComments",
Value.AcrossComments);
100 IO.mapOptional(
"AlignCompound",
Value.AlignCompound);
101 IO.mapOptional(
"AlignFunctionDeclarations",
102 Value.AlignFunctionDeclarations);
103 IO.mapOptional(
"AlignFunctionPointers",
Value.AlignFunctionPointers);
104 IO.mapOptional(
"PadOperators",
Value.PadOperators);
109struct MappingTraits<FormatStyle::ShortCaseStatementsAlignmentStyle> {
111 FormatStyle::ShortCaseStatementsAlignmentStyle &
Value) {
112 IO.mapOptional(
"Enabled",
Value.Enabled);
113 IO.mapOptional(
"AcrossEmptyLines",
Value.AcrossEmptyLines);
114 IO.mapOptional(
"AcrossComments",
Value.AcrossComments);
115 IO.mapOptional(
"AlignCaseArrows",
Value.AlignCaseArrows);
116 IO.mapOptional(
"AlignCaseColons",
Value.AlignCaseColons);
121struct ScalarEnumerationTraits<FormatStyle::AttributeBreakingStyle> {
123 IO.enumCase(
Value,
"Always", FormatStyle::ABS_Always);
124 IO.enumCase(
Value,
"Leave", FormatStyle::ABS_Leave);
125 IO.enumCase(
Value,
"LeaveAll", FormatStyle::ABS_LeaveAll);
126 IO.enumCase(
Value,
"Never", FormatStyle::ABS_Never);
131struct ScalarEnumerationTraits<FormatStyle::ArrayInitializerAlignmentStyle> {
133 FormatStyle::ArrayInitializerAlignmentStyle &
Value) {
134 IO.enumCase(
Value,
"None", FormatStyle::AIAS_None);
135 IO.enumCase(
Value,
"Left", FormatStyle::AIAS_Left);
136 IO.enumCase(
Value,
"Right", FormatStyle::AIAS_Right);
140template <>
struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
142 IO.enumCase(
Value,
"All", FormatStyle::BOS_All);
143 IO.enumCase(
Value,
"true", FormatStyle::BOS_All);
144 IO.enumCase(
Value,
"None", FormatStyle::BOS_None);
145 IO.enumCase(
Value,
"false", FormatStyle::BOS_None);
146 IO.enumCase(
Value,
"NonAssignment", FormatStyle::BOS_NonAssignment);
150template <>
struct ScalarEnumerationTraits<FormatStyle::BinPackArgumentsStyle> {
152 IO.enumCase(
Value,
"BinPack", FormatStyle::BPAS_BinPack);
153 IO.enumCase(
Value,
"OnePerLine", FormatStyle::BPAS_OnePerLine);
154 IO.enumCase(
Value,
"UseBreakAfter", FormatStyle::BPAS_UseBreakAfter);
157 IO.enumCase(
Value,
"true", FormatStyle::BPAS_BinPack);
158 IO.enumCase(
Value,
"false", FormatStyle::BPAS_OnePerLine);
163struct ScalarEnumerationTraits<FormatStyle::BinPackParametersStyle> {
165 IO.enumCase(
Value,
"BinPack", FormatStyle::BPPS_BinPack);
166 IO.enumCase(
Value,
"OnePerLine", FormatStyle::BPPS_OnePerLine);
167 IO.enumCase(
Value,
"AlwaysOnePerLine", FormatStyle::BPPS_AlwaysOnePerLine);
168 IO.enumCase(
Value,
"UseBreakAfter", FormatStyle::BPPS_UseBreakAfter);
171 IO.enumCase(
Value,
"true", FormatStyle::BPPS_BinPack);
172 IO.enumCase(
Value,
"false", FormatStyle::BPPS_OnePerLine);
176template <>
struct ScalarEnumerationTraits<FormatStyle::BinPackStyle> {
178 IO.enumCase(
Value,
"Auto", FormatStyle::BPS_Auto);
179 IO.enumCase(
Value,
"Always", FormatStyle::BPS_Always);
180 IO.enumCase(
Value,
"Never", FormatStyle::BPS_Never);
185struct ScalarEnumerationTraits<FormatStyle::BitFieldColonSpacingStyle> {
187 FormatStyle::BitFieldColonSpacingStyle &
Value) {
188 IO.enumCase(
Value,
"Both", FormatStyle::BFCS_Both);
189 IO.enumCase(
Value,
"None", FormatStyle::BFCS_None);
190 IO.enumCase(
Value,
"Before", FormatStyle::BFCS_Before);
191 IO.enumCase(
Value,
"After", FormatStyle::BFCS_After);
195template <>
struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
197 IO.enumCase(
Value,
"Attach", FormatStyle::BS_Attach);
198 IO.enumCase(
Value,
"Linux", FormatStyle::BS_Linux);
199 IO.enumCase(
Value,
"Mozilla", FormatStyle::BS_Mozilla);
200 IO.enumCase(
Value,
"Stroustrup", FormatStyle::BS_Stroustrup);
201 IO.enumCase(
Value,
"Allman", FormatStyle::BS_Allman);
202 IO.enumCase(
Value,
"Whitesmiths", FormatStyle::BS_Whitesmiths);
203 IO.enumCase(
Value,
"GNU", FormatStyle::BS_GNU);
204 IO.enumCase(
Value,
"WebKit", FormatStyle::BS_WebKit);
205 IO.enumCase(
Value,
"Custom", FormatStyle::BS_Custom);
209template <>
struct MappingTraits<FormatStyle::BraceWrappingFlags> {
210 static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
211 IO.mapOptional(
"AfterCaseLabel", Wrapping.AfterCaseLabel);
212 IO.mapOptional(
"AfterClass", Wrapping.AfterClass);
213 IO.mapOptional(
"AfterControlStatement", Wrapping.AfterControlStatement);
214 IO.mapOptional(
"AfterEnum", Wrapping.AfterEnum);
215 IO.mapOptional(
"AfterExternBlock", Wrapping.AfterExternBlock);
216 IO.mapOptional(
"AfterFunction", Wrapping.AfterFunction);
217 IO.mapOptional(
"AfterNamespace", Wrapping.AfterNamespace);
218 IO.mapOptional(
"AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
219 IO.mapOptional(
"AfterStruct", Wrapping.AfterStruct);
220 IO.mapOptional(
"AfterUnion", Wrapping.AfterUnion);
221 IO.mapOptional(
"BeforeCatch", Wrapping.BeforeCatch);
222 IO.mapOptional(
"BeforeElse", Wrapping.BeforeElse);
223 IO.mapOptional(
"BeforeLambdaBody", Wrapping.BeforeLambdaBody);
224 IO.mapOptional(
"BeforeWhile", Wrapping.BeforeWhile);
225 IO.mapOptional(
"IndentBraces", Wrapping.IndentBraces);
226 IO.mapOptional(
"SplitEmptyFunction", Wrapping.SplitEmptyFunction);
227 IO.mapOptional(
"SplitEmptyRecord", Wrapping.SplitEmptyRecord);
228 IO.mapOptional(
"SplitEmptyNamespace", Wrapping.SplitEmptyNamespace);
246struct ScalarEnumerationTraits<
247 FormatStyle::BraceWrappingAfterControlStatementStyle> {
250 FormatStyle::BraceWrappingAfterControlStatementStyle &
Value) {
251 IO.enumCase(
Value,
"Never", FormatStyle::BWACS_Never);
252 IO.enumCase(
Value,
"MultiLine", FormatStyle::BWACS_MultiLine);
253 IO.enumCase(
Value,
"Always", FormatStyle::BWACS_Always);
256 IO.enumCase(
Value,
"false", FormatStyle::BWACS_Never);
257 IO.enumCase(
Value,
"true", FormatStyle::BWACS_Always);
262struct ScalarEnumerationTraits<
263 FormatStyle::BreakBeforeConceptDeclarationsStyle> {
266 IO.enumCase(
Value,
"Never", FormatStyle::BBCDS_Never);
267 IO.enumCase(
Value,
"Allowed", FormatStyle::BBCDS_Allowed);
268 IO.enumCase(
Value,
"Always", FormatStyle::BBCDS_Always);
271 IO.enumCase(
Value,
"true", FormatStyle::BBCDS_Always);
272 IO.enumCase(
Value,
"false", FormatStyle::BBCDS_Allowed);
277struct ScalarEnumerationTraits<FormatStyle::BreakBeforeInlineASMColonStyle> {
279 FormatStyle::BreakBeforeInlineASMColonStyle &
Value) {
280 IO.enumCase(
Value,
"Never", FormatStyle::BBIAS_Never);
281 IO.enumCase(
Value,
"OnlyMultiline", FormatStyle::BBIAS_OnlyMultiline);
282 IO.enumCase(
Value,
"Always", FormatStyle::BBIAS_Always);
287struct ScalarEnumerationTraits<FormatStyle::BreakBinaryOperationsStyle> {
289 FormatStyle::BreakBinaryOperationsStyle &
Value) {
290 IO.enumCase(
Value,
"Never", FormatStyle::BBO_Never);
291 IO.enumCase(
Value,
"OnePerLine", FormatStyle::BBO_OnePerLine);
292 IO.enumCase(
Value,
"RespectPrecedence", FormatStyle::BBO_RespectPrecedence);
296template <>
struct ScalarTraits<
clang::tok::TokenKind> {
298 llvm::raw_ostream &Out) {
305 static StringRef
input(StringRef Scalar,
void *,
308#define PUNCTUATOR(Name, Spelling) \
309 if (Scalar == Spelling) { \
310 Value = clang::tok::Name; \
313#include "clang/Basic/TokenKinds.def"
314 return "unknown operator";
317 static QuotingType
mustQuote(StringRef) {
return QuotingType::None; }
320template <>
struct MappingTraits<FormatStyle::BinaryOperationBreakRule> {
321 static void mapping(IO &IO, FormatStyle::BinaryOperationBreakRule &
Value) {
322 IO.mapOptional(
"Operators",
Value.Operators);
324 if (!IO.outputting())
325 Value.Style = FormatStyle::BBO_OnePerLine;
326 IO.mapOptional(
"Style",
Value.Style);
327 IO.mapOptional(
"MinChainLength",
Value.MinChainLength);
331template <>
struct MappingTraits<FormatStyle::BreakBinaryOperationsOptions> {
333 FormatStyle::BreakBinaryOperationsOptions &
Value) {
334 IO.enumCase(
Value,
"Never",
335 FormatStyle::BreakBinaryOperationsOptions(
336 {FormatStyle::BBO_Never, {}}));
337 IO.enumCase(
Value,
"OnePerLine",
338 FormatStyle::BreakBinaryOperationsOptions(
339 {FormatStyle::BBO_OnePerLine, {}}));
340 IO.enumCase(
Value,
"RespectPrecedence",
341 FormatStyle::BreakBinaryOperationsOptions(
342 {FormatStyle::BBO_RespectPrecedence, {}}));
346 FormatStyle::BreakBinaryOperationsOptions &
Value) {
347 IO.mapOptional(
"Default",
Value.Default);
348 IO.mapOptional(
"PerOperator",
Value.PerOperator);
353struct ScalarEnumerationTraits<FormatStyle::BreakConstructorInitializersStyle> {
356 IO.enumCase(
Value,
"BeforeColon", FormatStyle::BCIS_BeforeColon);
357 IO.enumCase(
Value,
"BeforeComma", FormatStyle::BCIS_BeforeComma);
358 IO.enumCase(
Value,
"AfterColon", FormatStyle::BCIS_AfterColon);
359 IO.enumCase(
Value,
"AfterComma", FormatStyle::BCIS_AfterComma);
364struct ScalarEnumerationTraits<FormatStyle::BreakInheritanceListStyle> {
366 FormatStyle::BreakInheritanceListStyle &
Value) {
367 IO.enumCase(
Value,
"BeforeColon", FormatStyle::BILS_BeforeColon);
368 IO.enumCase(
Value,
"BeforeComma", FormatStyle::BILS_BeforeComma);
369 IO.enumCase(
Value,
"AfterColon", FormatStyle::BILS_AfterColon);
370 IO.enumCase(
Value,
"AfterComma", FormatStyle::BILS_AfterComma);
375struct ScalarEnumerationTraits<FormatStyle::BreakTemplateDeclarationsStyle> {
377 FormatStyle::BreakTemplateDeclarationsStyle &
Value) {
378 IO.enumCase(
Value,
"Leave", FormatStyle::BTDS_Leave);
379 IO.enumCase(
Value,
"No", FormatStyle::BTDS_No);
380 IO.enumCase(
Value,
"MultiLine", FormatStyle::BTDS_MultiLine);
381 IO.enumCase(
Value,
"Yes", FormatStyle::BTDS_Yes);
384 IO.enumCase(
Value,
"false", FormatStyle::BTDS_MultiLine);
385 IO.enumCase(
Value,
"true", FormatStyle::BTDS_Yes);
389template <>
struct ScalarEnumerationTraits<FormatStyle::BracedListStyle> {
391 IO.enumCase(
Value,
"Block", FormatStyle::BLS_Block);
392 IO.enumCase(
Value,
"FunctionCall", FormatStyle::BLS_FunctionCall);
393 IO.enumCase(
Value,
"AlignFirstComment", FormatStyle::BLS_AlignFirstComment);
396 IO.enumCase(
Value,
"false", FormatStyle::BLS_Block);
397 IO.enumCase(
Value,
"true", FormatStyle::BLS_AlignFirstComment);
401template <>
struct ScalarEnumerationTraits<FormatStyle::DAGArgStyle> {
403 IO.enumCase(
Value,
"DontBreak", FormatStyle::DAS_DontBreak);
404 IO.enumCase(
Value,
"BreakElements", FormatStyle::DAS_BreakElements);
405 IO.enumCase(
Value,
"BreakAll", FormatStyle::DAS_BreakAll);
410struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
413 IO.enumCase(
Value,
"None", FormatStyle::DRTBS_None);
414 IO.enumCase(
Value,
"All", FormatStyle::DRTBS_All);
415 IO.enumCase(
Value,
"TopLevel", FormatStyle::DRTBS_TopLevel);
418 IO.enumCase(
Value,
"false", FormatStyle::DRTBS_None);
419 IO.enumCase(
Value,
"true", FormatStyle::DRTBS_All);
424struct ScalarEnumerationTraits<FormatStyle::EscapedNewlineAlignmentStyle> {
426 FormatStyle::EscapedNewlineAlignmentStyle &
Value) {
427 IO.enumCase(
Value,
"DontAlign", FormatStyle::ENAS_DontAlign);
428 IO.enumCase(
Value,
"Left", FormatStyle::ENAS_Left);
429 IO.enumCase(
Value,
"LeftWithLastLine", FormatStyle::ENAS_LeftWithLastLine);
430 IO.enumCase(
Value,
"Right", FormatStyle::ENAS_Right);
433 IO.enumCase(
Value,
"true", FormatStyle::ENAS_Left);
434 IO.enumCase(
Value,
"false", FormatStyle::ENAS_Right);
439struct ScalarEnumerationTraits<FormatStyle::EmptyLineAfterAccessModifierStyle> {
442 IO.enumCase(
Value,
"Never", FormatStyle::ELAAMS_Never);
443 IO.enumCase(
Value,
"Leave", FormatStyle::ELAAMS_Leave);
444 IO.enumCase(
Value,
"Always", FormatStyle::ELAAMS_Always);
449struct ScalarEnumerationTraits<
450 FormatStyle::EmptyLineBeforeAccessModifierStyle> {
453 IO.enumCase(
Value,
"Never", FormatStyle::ELBAMS_Never);
454 IO.enumCase(
Value,
"Leave", FormatStyle::ELBAMS_Leave);
455 IO.enumCase(
Value,
"LogicalBlock", FormatStyle::ELBAMS_LogicalBlock);
456 IO.enumCase(
Value,
"Always", FormatStyle::ELBAMS_Always);
461struct ScalarEnumerationTraits<FormatStyle::EnumTrailingCommaStyle> {
463 IO.enumCase(
Value,
"Leave", FormatStyle::ETC_Leave);
464 IO.enumCase(
Value,
"Insert", FormatStyle::ETC_Insert);
465 IO.enumCase(
Value,
"Remove", FormatStyle::ETC_Remove);
470struct ScalarEnumerationTraits<FormatStyle::IndentExternBlockStyle> {
472 IO.enumCase(
Value,
"AfterExternBlock", FormatStyle::IEBS_AfterExternBlock);
473 IO.enumCase(
Value,
"Indent", FormatStyle::IEBS_Indent);
474 IO.enumCase(
Value,
"NoIndent", FormatStyle::IEBS_NoIndent);
475 IO.enumCase(
Value,
"true", FormatStyle::IEBS_Indent);
476 IO.enumCase(
Value,
"false", FormatStyle::IEBS_NoIndent);
480template <>
struct MappingTraits<FormatStyle::IntegerLiteralSeparatorStyle> {
481 static void mapping(IO &IO, FormatStyle::IntegerLiteralSeparatorStyle &
Base) {
482 IO.mapOptional(
"Binary",
Base.Binary);
483 IO.mapOptional(
"BinaryMinDigitsInsert",
Base.BinaryMinDigitsInsert);
484 IO.mapOptional(
"BinaryMaxDigitsRemove",
Base.BinaryMaxDigitsRemove);
485 IO.mapOptional(
"Decimal",
Base.Decimal);
486 IO.mapOptional(
"DecimalMinDigitsInsert",
Base.DecimalMinDigitsInsert);
487 IO.mapOptional(
"DecimalMaxDigitsRemove",
Base.DecimalMaxDigitsRemove);
488 IO.mapOptional(
"Hex",
Base.Hex);
489 IO.mapOptional(
"HexMinDigitsInsert",
Base.HexMinDigitsInsert);
490 IO.mapOptional(
"HexMaxDigitsRemove",
Base.HexMaxDigitsRemove);
493 IO.mapOptional(
"BinaryMinDigits",
Base.BinaryMinDigitsInsert);
494 IO.mapOptional(
"DecimalMinDigits",
Base.DecimalMinDigitsInsert);
495 IO.mapOptional(
"HexMinDigits",
Base.HexMinDigitsInsert);
499template <>
struct ScalarEnumerationTraits<FormatStyle::JavaScriptQuoteStyle> {
501 IO.enumCase(
Value,
"Leave", FormatStyle::JSQS_Leave);
502 IO.enumCase(
Value,
"Single", FormatStyle::JSQS_Single);
503 IO.enumCase(
Value,
"Double", FormatStyle::JSQS_Double);
507template <>
struct MappingTraits<FormatStyle::KeepEmptyLinesStyle> {
509 IO.mapOptional(
"AtEndOfFile",
Value.AtEndOfFile);
510 IO.mapOptional(
"AtStartOfBlock",
Value.AtStartOfBlock);
511 IO.mapOptional(
"AtStartOfFile",
Value.AtStartOfFile);
515template <>
struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
517 IO.enumCase(
Value,
"C", FormatStyle::LK_C);
518 IO.enumCase(
Value,
"Cpp", FormatStyle::LK_Cpp);
519 IO.enumCase(
Value,
"Java", FormatStyle::LK_Java);
520 IO.enumCase(
Value,
"JavaScript", FormatStyle::LK_JavaScript);
521 IO.enumCase(
Value,
"ObjC", FormatStyle::LK_ObjC);
522 IO.enumCase(
Value,
"Proto", FormatStyle::LK_Proto);
523 IO.enumCase(
Value,
"TableGen", FormatStyle::LK_TableGen);
524 IO.enumCase(
Value,
"TextProto", FormatStyle::LK_TextProto);
525 IO.enumCase(
Value,
"CSharp", FormatStyle::LK_CSharp);
526 IO.enumCase(
Value,
"Json", FormatStyle::LK_Json);
527 IO.enumCase(
Value,
"Verilog", FormatStyle::LK_Verilog);
531template <>
struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
533 IO.enumCase(
Value,
"c++03", FormatStyle::LS_Cpp03);
534 IO.enumCase(
Value,
"C++03", FormatStyle::LS_Cpp03);
535 IO.enumCase(
Value,
"Cpp03", FormatStyle::LS_Cpp03);
537 IO.enumCase(
Value,
"c++11", FormatStyle::LS_Cpp11);
538 IO.enumCase(
Value,
"C++11", FormatStyle::LS_Cpp11);
540 IO.enumCase(
Value,
"c++14", FormatStyle::LS_Cpp14);
541 IO.enumCase(
Value,
"c++17", FormatStyle::LS_Cpp17);
542 IO.enumCase(
Value,
"c++20", FormatStyle::LS_Cpp20);
543 IO.enumCase(
Value,
"c++23", FormatStyle::LS_Cpp23);
544 IO.enumCase(
Value,
"c++26", FormatStyle::LS_Cpp26);
546 IO.enumCase(
Value,
"Latest", FormatStyle::LS_Latest);
547 IO.enumCase(
Value,
"Cpp11", FormatStyle::LS_Latest);
548 IO.enumCase(
Value,
"Auto", FormatStyle::LS_Auto);
553struct ScalarEnumerationTraits<FormatStyle::LambdaBodyIndentationKind> {
555 FormatStyle::LambdaBodyIndentationKind &
Value) {
556 IO.enumCase(
Value,
"Signature", FormatStyle::LBI_Signature);
557 IO.enumCase(
Value,
"OuterScope", FormatStyle::LBI_OuterScope);
561template <>
struct ScalarEnumerationTraits<FormatStyle::LineEndingStyle> {
563 IO.enumCase(
Value,
"LF", FormatStyle::LE_LF);
564 IO.enumCase(
Value,
"CRLF", FormatStyle::LE_CRLF);
565 IO.enumCase(
Value,
"DeriveLF", FormatStyle::LE_DeriveLF);
566 IO.enumCase(
Value,
"DeriveCRLF", FormatStyle::LE_DeriveCRLF);
571struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
573 FormatStyle::NamespaceIndentationKind &
Value) {
574 IO.enumCase(
Value,
"None", FormatStyle::NI_None);
575 IO.enumCase(
Value,
"Inner", FormatStyle::NI_Inner);
576 IO.enumCase(
Value,
"All", FormatStyle::NI_All);
581struct ScalarEnumerationTraits<FormatStyle::NumericLiteralComponentStyle> {
583 FormatStyle::NumericLiteralComponentStyle &
Value) {
584 IO.enumCase(
Value,
"Leave", FormatStyle::NLCS_Leave);
585 IO.enumCase(
Value,
"Upper", FormatStyle::NLCS_Upper);
586 IO.enumCase(
Value,
"Lower", FormatStyle::NLCS_Lower);
590template <>
struct MappingTraits<FormatStyle::NumericLiteralCaseStyle> {
591 static void mapping(IO &IO, FormatStyle::NumericLiteralCaseStyle &
Value) {
592 IO.mapOptional(
"ExponentLetter",
Value.ExponentLetter);
593 IO.mapOptional(
"HexDigit",
Value.HexDigit);
594 IO.mapOptional(
"Prefix",
Value.Prefix);
595 IO.mapOptional(
"Suffix",
Value.Suffix);
599template <>
struct ScalarEnumerationTraits<FormatStyle::OperandAlignmentStyle> {
601 IO.enumCase(
Value,
"DontAlign", FormatStyle::OAS_DontAlign);
602 IO.enumCase(
Value,
"Align", FormatStyle::OAS_Align);
603 IO.enumCase(
Value,
"AlignAfterOperator",
604 FormatStyle::OAS_AlignAfterOperator);
607 IO.enumCase(
Value,
"true", FormatStyle::OAS_Align);
608 IO.enumCase(
Value,
"false", FormatStyle::OAS_DontAlign);
612template <>
struct MappingTraits<FormatStyle::PackParametersStyle> {
614 IO.mapOptional(
"BinPack",
Value.BinPack);
615 IO.mapOptional(
"BreakAfter",
Value.BreakAfter);
620struct ScalarEnumerationTraits<FormatStyle::PackConstructorInitializersStyle> {
623 IO.enumCase(
Value,
"Never", FormatStyle::PCIS_Never);
624 IO.enumCase(
Value,
"BinPack", FormatStyle::PCIS_BinPack);
625 IO.enumCase(
Value,
"CurrentLine", FormatStyle::PCIS_CurrentLine);
626 IO.enumCase(
Value,
"NextLine", FormatStyle::PCIS_NextLine);
627 IO.enumCase(
Value,
"NextLineOnly", FormatStyle::PCIS_NextLineOnly);
631template <>
struct MappingTraits<FormatStyle::PackArgumentsStyle> {
633 IO.mapOptional(
"BinPack",
Value.BinPack);
634 IO.mapOptional(
"BreakAfter",
Value.BreakAfter);
638template <>
struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
640 IO.enumCase(
Value,
"Middle", FormatStyle::PAS_Middle);
641 IO.enumCase(
Value,
"Left", FormatStyle::PAS_Left);
642 IO.enumCase(
Value,
"Right", FormatStyle::PAS_Right);
645 IO.enumCase(
Value,
"true", FormatStyle::PAS_Left);
646 IO.enumCase(
Value,
"false", FormatStyle::PAS_Right);
651struct ScalarEnumerationTraits<FormatStyle::PPDirectiveIndentStyle> {
653 IO.enumCase(
Value,
"None", FormatStyle::PPDIS_None);
654 IO.enumCase(
Value,
"AfterHash", FormatStyle::PPDIS_AfterHash);
655 IO.enumCase(
Value,
"BeforeHash", FormatStyle::PPDIS_BeforeHash);
656 IO.enumCase(
Value,
"Leave", FormatStyle::PPDIS_Leave);
661struct ScalarEnumerationTraits<FormatStyle::QualifierAlignmentStyle> {
663 IO.enumCase(
Value,
"Leave", FormatStyle::QAS_Leave);
664 IO.enumCase(
Value,
"Left", FormatStyle::QAS_Left);
665 IO.enumCase(
Value,
"Right", FormatStyle::QAS_Right);
666 IO.enumCase(
Value,
"Custom", FormatStyle::QAS_Custom);
670template <>
struct MappingTraits<FormatStyle::RawStringFormat> {
671 static void mapping(IO &IO, FormatStyle::RawStringFormat &Format) {
672 IO.mapOptional(
"Language", Format.Language);
673 IO.mapOptional(
"Delimiters", Format.Delimiters);
674 IO.mapOptional(
"EnclosingFunctions", Format.EnclosingFunctions);
675 IO.mapOptional(
"CanonicalDelimiter", Format.CanonicalDelimiter);
676 IO.mapOptional(
"BasedOnStyle", Format.BasedOnStyle);
680template <>
struct ScalarEnumerationTraits<FormatStyle::ReflowCommentsStyle> {
682 IO.enumCase(
Value,
"Never", FormatStyle::RCS_Never);
683 IO.enumCase(
Value,
"IndentOnly", FormatStyle::RCS_IndentOnly);
684 IO.enumCase(
Value,
"Always", FormatStyle::RCS_Always);
686 IO.enumCase(
Value,
"false", FormatStyle::RCS_Never);
687 IO.enumCase(
Value,
"true", FormatStyle::RCS_Always);
692struct ScalarEnumerationTraits<FormatStyle::ReferenceAlignmentStyle> {
694 IO.enumCase(
Value,
"Pointer", FormatStyle::RAS_Pointer);
695 IO.enumCase(
Value,
"Middle", FormatStyle::RAS_Middle);
696 IO.enumCase(
Value,
"Left", FormatStyle::RAS_Left);
697 IO.enumCase(
Value,
"Right", FormatStyle::RAS_Right);
702struct ScalarEnumerationTraits<FormatStyle::RemoveParenthesesStyle> {
704 IO.enumCase(
Value,
"Leave", FormatStyle::RPS_Leave);
705 IO.enumCase(
Value,
"MultipleParentheses",
706 FormatStyle::RPS_MultipleParentheses);
707 IO.enumCase(
Value,
"ReturnStatement", FormatStyle::RPS_ReturnStatement);
712struct ScalarEnumerationTraits<FormatStyle::RequiresClausePositionStyle> {
714 FormatStyle::RequiresClausePositionStyle &
Value) {
715 IO.enumCase(
Value,
"OwnLine", FormatStyle::RCPS_OwnLine);
716 IO.enumCase(
Value,
"OwnLineWithBrace", FormatStyle::RCPS_OwnLineWithBrace);
717 IO.enumCase(
Value,
"WithPreceding", FormatStyle::RCPS_WithPreceding);
718 IO.enumCase(
Value,
"WithFollowing", FormatStyle::RCPS_WithFollowing);
719 IO.enumCase(
Value,
"SingleLine", FormatStyle::RCPS_SingleLine);
724struct ScalarEnumerationTraits<FormatStyle::RequiresExpressionIndentationKind> {
727 IO.enumCase(
Value,
"Keyword", FormatStyle::REI_Keyword);
728 IO.enumCase(
Value,
"OuterScope", FormatStyle::REI_OuterScope);
733struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
735 IO.enumCase(
Value,
"None", FormatStyle::RTBS_None);
736 IO.enumCase(
Value,
"Automatic", FormatStyle::RTBS_Automatic);
737 IO.enumCase(
Value,
"ExceptShortType", FormatStyle::RTBS_ExceptShortType);
738 IO.enumCase(
Value,
"All", FormatStyle::RTBS_All);
739 IO.enumCase(
Value,
"TopLevel", FormatStyle::RTBS_TopLevel);
740 IO.enumCase(
Value,
"TopLevelDefinitions",
741 FormatStyle::RTBS_TopLevelDefinitions);
742 IO.enumCase(
Value,
"AllDefinitions", FormatStyle::RTBS_AllDefinitions);
747struct ScalarEnumerationTraits<FormatStyle::SeparateDefinitionStyle> {
749 IO.enumCase(
Value,
"Leave", FormatStyle::SDS_Leave);
750 IO.enumCase(
Value,
"Always", FormatStyle::SDS_Always);
751 IO.enumCase(
Value,
"Never", FormatStyle::SDS_Never);
755template <>
struct ScalarEnumerationTraits<FormatStyle::ShortBlockStyle> {
757 IO.enumCase(
Value,
"Never", FormatStyle::SBS_Never);
758 IO.enumCase(
Value,
"false", FormatStyle::SBS_Never);
759 IO.enumCase(
Value,
"Always", FormatStyle::SBS_Always);
760 IO.enumCase(
Value,
"true", FormatStyle::SBS_Always);
761 IO.enumCase(
Value,
"Empty", FormatStyle::SBS_Empty);
765template <>
struct MappingTraits<FormatStyle::ShortFunctionStyle> {
767 IO.enumCase(
Value,
"None", FormatStyle::ShortFunctionStyle());
768 IO.enumCase(
Value,
"Empty",
769 FormatStyle::ShortFunctionStyle::setEmptyOnly());
770 IO.enumCase(
Value,
"Inline",
771 FormatStyle::ShortFunctionStyle::setEmptyAndInline());
772 IO.enumCase(
Value,
"InlineOnly",
773 FormatStyle::ShortFunctionStyle::setInlineOnly());
774 IO.enumCase(
Value,
"All", FormatStyle::ShortFunctionStyle::setAll());
777 IO.enumCase(
Value,
"true", FormatStyle::ShortFunctionStyle::setAll());
778 IO.enumCase(
Value,
"false", FormatStyle::ShortFunctionStyle());
782 IO.mapOptional(
"Empty",
Value.Empty);
783 IO.mapOptional(
"Inline",
Value.Inline);
784 IO.mapOptional(
"Other",
Value.Other);
788template <>
struct ScalarEnumerationTraits<FormatStyle::ShortIfStyle> {
790 IO.enumCase(
Value,
"Never", FormatStyle::SIS_Never);
791 IO.enumCase(
Value,
"WithoutElse", FormatStyle::SIS_WithoutElse);
792 IO.enumCase(
Value,
"OnlyFirstIf", FormatStyle::SIS_OnlyFirstIf);
793 IO.enumCase(
Value,
"AllIfsAndElse", FormatStyle::SIS_AllIfsAndElse);
796 IO.enumCase(
Value,
"Always", FormatStyle::SIS_OnlyFirstIf);
797 IO.enumCase(
Value,
"false", FormatStyle::SIS_Never);
798 IO.enumCase(
Value,
"true", FormatStyle::SIS_WithoutElse);
802template <>
struct ScalarEnumerationTraits<FormatStyle::ShortLambdaStyle> {
804 IO.enumCase(
Value,
"None", FormatStyle::SLS_None);
805 IO.enumCase(
Value,
"false", FormatStyle::SLS_None);
806 IO.enumCase(
Value,
"Empty", FormatStyle::SLS_Empty);
807 IO.enumCase(
Value,
"Inline", FormatStyle::SLS_Inline);
808 IO.enumCase(
Value,
"All", FormatStyle::SLS_All);
809 IO.enumCase(
Value,
"true", FormatStyle::SLS_All);
813template <>
struct ScalarEnumerationTraits<FormatStyle::ShortRecordStyle> {
815 IO.enumCase(
Value,
"Never", FormatStyle::SRS_Never);
816 IO.enumCase(
Value,
"EmptyAndAttached", FormatStyle::SRS_EmptyAndAttached);
817 IO.enumCase(
Value,
"Empty", FormatStyle::SRS_Empty);
818 IO.enumCase(
Value,
"Always", FormatStyle::SRS_Always);
822template <>
struct MappingTraits<FormatStyle::SortIncludesOptions> {
824 IO.enumCase(
Value,
"Never", FormatStyle::SortIncludesOptions{});
825 IO.enumCase(
Value,
"CaseInsensitive",
826 FormatStyle::SortIncludesOptions{
true,
829 IO.enumCase(
Value,
"CaseSensitive",
830 FormatStyle::SortIncludesOptions{
true,
835 IO.enumCase(
Value,
"false", FormatStyle::SortIncludesOptions{});
836 IO.enumCase(
Value,
"true",
837 FormatStyle::SortIncludesOptions{
true,
843 IO.mapOptional(
"Enabled",
Value.Enabled);
844 IO.mapOptional(
"IgnoreCase",
Value.IgnoreCase);
845 IO.mapOptional(
"IgnoreExtension",
Value.IgnoreExtension);
850struct ScalarEnumerationTraits<FormatStyle::SortJavaStaticImportOptions> {
852 FormatStyle::SortJavaStaticImportOptions &
Value) {
853 IO.enumCase(
Value,
"Before", FormatStyle::SJSIO_Before);
854 IO.enumCase(
Value,
"After", FormatStyle::SJSIO_After);
859struct ScalarEnumerationTraits<FormatStyle::SortUsingDeclarationsOptions> {
861 FormatStyle::SortUsingDeclarationsOptions &
Value) {
862 IO.enumCase(
Value,
"Never", FormatStyle::SUD_Never);
863 IO.enumCase(
Value,
"Lexicographic", FormatStyle::SUD_Lexicographic);
864 IO.enumCase(
Value,
"LexicographicNumeric",
865 FormatStyle::SUD_LexicographicNumeric);
868 IO.enumCase(
Value,
"false", FormatStyle::SUD_Never);
869 IO.enumCase(
Value,
"true", FormatStyle::SUD_LexicographicNumeric);
874struct ScalarEnumerationTraits<FormatStyle::SpaceAroundPointerQualifiersStyle> {
877 IO.enumCase(
Value,
"Default", FormatStyle::SAPQ_Default);
878 IO.enumCase(
Value,
"Before", FormatStyle::SAPQ_Before);
879 IO.enumCase(
Value,
"After", FormatStyle::SAPQ_After);
880 IO.enumCase(
Value,
"Both", FormatStyle::SAPQ_Both);
884template <>
struct MappingTraits<FormatStyle::SpaceBeforeParensCustom> {
885 static void mapping(IO &IO, FormatStyle::SpaceBeforeParensCustom &Spacing) {
886 IO.mapOptional(
"AfterControlStatements", Spacing.AfterControlStatements);
887 IO.mapOptional(
"AfterForeachMacros", Spacing.AfterForeachMacros);
888 IO.mapOptional(
"AfterFunctionDefinitionName",
889 Spacing.AfterFunctionDefinitionName);
890 IO.mapOptional(
"AfterFunctionDeclarationName",
891 Spacing.AfterFunctionDeclarationName);
892 IO.mapOptional(
"AfterIfMacros", Spacing.AfterIfMacros);
893 IO.mapOptional(
"AfterNot", Spacing.AfterNot);
894 IO.mapOptional(
"AfterOverloadedOperator", Spacing.AfterOverloadedOperator);
895 IO.mapOptional(
"AfterPlacementOperator", Spacing.AfterPlacementOperator);
896 IO.mapOptional(
"AfterRequiresInClause", Spacing.AfterRequiresInClause);
897 IO.mapOptional(
"AfterRequiresInExpression",
898 Spacing.AfterRequiresInExpression);
899 IO.mapOptional(
"BeforeNonEmptyParentheses",
900 Spacing.BeforeNonEmptyParentheses);
905struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensStyle> {
907 IO.enumCase(
Value,
"Never", FormatStyle::SBPO_Never);
908 IO.enumCase(
Value,
"ControlStatements",
909 FormatStyle::SBPO_ControlStatements);
910 IO.enumCase(
Value,
"ControlStatementsExceptControlMacros",
911 FormatStyle::SBPO_ControlStatementsExceptControlMacros);
912 IO.enumCase(
Value,
"NonEmptyParentheses",
913 FormatStyle::SBPO_NonEmptyParentheses);
914 IO.enumCase(
Value,
"Always", FormatStyle::SBPO_Always);
915 IO.enumCase(
Value,
"Custom", FormatStyle::SBPO_Custom);
918 IO.enumCase(
Value,
"false", FormatStyle::SBPO_Never);
919 IO.enumCase(
Value,
"true", FormatStyle::SBPO_ControlStatements);
920 IO.enumCase(
Value,
"ControlStatementsExceptForEachMacros",
921 FormatStyle::SBPO_ControlStatementsExceptControlMacros);
926struct ScalarEnumerationTraits<FormatStyle::SpaceInEmptyBracesStyle> {
928 IO.enumCase(
Value,
"Always", FormatStyle::SIEB_Always);
929 IO.enumCase(
Value,
"Block", FormatStyle::SIEB_Block);
930 IO.enumCase(
Value,
"Never", FormatStyle::SIEB_Never);
934template <>
struct ScalarEnumerationTraits<FormatStyle::SpacesInAnglesStyle> {
936 IO.enumCase(
Value,
"Never", FormatStyle::SIAS_Never);
937 IO.enumCase(
Value,
"Always", FormatStyle::SIAS_Always);
938 IO.enumCase(
Value,
"Leave", FormatStyle::SIAS_Leave);
941 IO.enumCase(
Value,
"false", FormatStyle::SIAS_Never);
942 IO.enumCase(
Value,
"true", FormatStyle::SIAS_Always);
946template <>
struct MappingTraits<FormatStyle::SpacesInLineComment> {
947 static void mapping(IO &IO, FormatStyle::SpacesInLineComment &Space) {
949 int signedMaximum =
static_cast<int>(Space.Maximum);
950 IO.mapOptional(
"Minimum", Space.Minimum);
951 IO.mapOptional(
"Maximum", signedMaximum);
952 Space.Maximum =
static_cast<unsigned>(signedMaximum);
954 if (Space.Maximum < std::numeric_limits<unsigned>::max())
955 Space.Minimum = std::min(Space.Minimum, Space.Maximum);
959template <>
struct MappingTraits<FormatStyle::SpacesInParensCustom> {
960 static void mapping(IO &IO, FormatStyle::SpacesInParensCustom &Spaces) {
961 IO.mapOptional(
"ExceptDoubleParentheses", Spaces.ExceptDoubleParentheses);
962 IO.mapOptional(
"InCStyleCasts", Spaces.InCStyleCasts);
963 IO.mapOptional(
"InConditionalStatements", Spaces.InConditionalStatements);
964 IO.mapOptional(
"InEmptyParentheses", Spaces.InEmptyParentheses);
965 IO.mapOptional(
"Other", Spaces.Other);
969template <>
struct ScalarEnumerationTraits<FormatStyle::SpacesInParensStyle> {
971 IO.enumCase(
Value,
"Never", FormatStyle::SIPO_Never);
972 IO.enumCase(
Value,
"Custom", FormatStyle::SIPO_Custom);
976template <>
struct ScalarEnumerationTraits<FormatStyle::TrailingCommaStyle> {
978 IO.enumCase(
Value,
"None", FormatStyle::TCS_None);
979 IO.enumCase(
Value,
"Wrapped", FormatStyle::TCS_Wrapped);
984struct ScalarEnumerationTraits<FormatStyle::TrailingCommentsAlignmentKinds> {
986 FormatStyle::TrailingCommentsAlignmentKinds &
Value) {
987 IO.enumCase(
Value,
"Leave", FormatStyle::TCAS_Leave);
988 IO.enumCase(
Value,
"Always", FormatStyle::TCAS_Always);
989 IO.enumCase(
Value,
"Never", FormatStyle::TCAS_Never);
993template <>
struct MappingTraits<FormatStyle::TrailingCommentsAlignmentStyle> {
995 FormatStyle::TrailingCommentsAlignmentStyle &
Value) {
996 IO.enumCase(
Value,
"Leave",
997 FormatStyle::TrailingCommentsAlignmentStyle(
998 {FormatStyle::TCAS_Leave, 0,
true}));
1000 IO.enumCase(
Value,
"Always",
1001 FormatStyle::TrailingCommentsAlignmentStyle(
1002 {FormatStyle::TCAS_Always, 0,
true}));
1004 IO.enumCase(
Value,
"Never",
1005 FormatStyle::TrailingCommentsAlignmentStyle(
1006 {FormatStyle::TCAS_Never, 0,
true}));
1009 IO.enumCase(
Value,
"true",
1010 FormatStyle::TrailingCommentsAlignmentStyle(
1011 {FormatStyle::TCAS_Always, 0,
true}));
1012 IO.enumCase(
Value,
"false",
1013 FormatStyle::TrailingCommentsAlignmentStyle(
1014 {FormatStyle::TCAS_Never, 0,
true}));
1018 FormatStyle::TrailingCommentsAlignmentStyle &
Value) {
1019 IO.mapOptional(
"AlignPPAndNotPP",
Value.AlignPPAndNotPP);
1020 IO.mapOptional(
"Kind",
Value.Kind);
1021 IO.mapOptional(
"OverEmptyLines",
Value.OverEmptyLines);
1025template <>
struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
1027 IO.enumCase(
Value,
"Never", FormatStyle::UT_Never);
1028 IO.enumCase(
Value,
"false", FormatStyle::UT_Never);
1029 IO.enumCase(
Value,
"Always", FormatStyle::UT_Always);
1030 IO.enumCase(
Value,
"true", FormatStyle::UT_Always);
1031 IO.enumCase(
Value,
"ForIndentation", FormatStyle::UT_ForIndentation);
1032 IO.enumCase(
Value,
"ForContinuationAndIndentation",
1033 FormatStyle::UT_ForContinuationAndIndentation);
1034 IO.enumCase(
Value,
"AlignWithSpaces", FormatStyle::UT_AlignWithSpaces);
1039struct ScalarEnumerationTraits<
1040 FormatStyle::WrapNamespaceBodyWithEmptyLinesStyle> {
1043 FormatStyle::WrapNamespaceBodyWithEmptyLinesStyle &
Value) {
1044 IO.enumCase(
Value,
"Never", FormatStyle::WNBWELS_Never);
1045 IO.enumCase(
Value,
"Always", FormatStyle::WNBWELS_Always);
1046 IO.enumCase(
Value,
"Leave", FormatStyle::WNBWELS_Leave);
1050template <>
struct MappingTraits<FormatStyle> {
1053 IO.mapOptional(
"Language", Style.Language);
1055 StringRef BasedOnStyle;
1056 if (IO.outputting()) {
1057 StringRef Styles[] = {
"LLVM",
"Google",
"Chromium",
"Mozilla",
1058 "WebKit",
"GNU",
"Microsoft",
"clang-format"};
1059 for (StringRef StyleName : Styles) {
1060 FormatStyle PredefinedStyle;
1062 Style == PredefinedStyle) {
1063 BasedOnStyle = StyleName;
1068 IO.mapOptional(
"BasedOnStyle", BasedOnStyle);
1069 if (!BasedOnStyle.empty()) {
1070 FormatStyle::LanguageKind OldLanguage = Style.Language;
1071 FormatStyle::LanguageKind Language =
1072 ((FormatStyle *)IO.getContext())->Language;
1074 IO.setError(Twine(
"Unknown value for BasedOnStyle: ", BasedOnStyle));
1077 Style.Language = OldLanguage;
1092 const bool IsGoogleOrChromium = BasedOnStyle.equals_insensitive(
"google") ||
1093 BasedOnStyle.equals_insensitive(
"chromium");
1094 bool OnCurrentLine = IsGoogleOrChromium;
1095 bool OnNextLine =
true;
1097 bool BreakBeforeInheritanceComma =
false;
1098 bool BreakConstructorInitializersBeforeComma =
false;
1100 bool DeriveLineEnding =
true;
1101 bool UseCRLF =
false;
1103 bool SpaceInEmptyBlock =
false;
1104 bool SpaceInEmptyParentheses =
false;
1105 bool SpacesInConditionalStatement =
false;
1106 bool SpacesInCStyleCastParentheses =
false;
1107 bool SpacesInParentheses =
false;
1109 if (IO.outputting()) {
1110 IO.mapOptional(
"AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
1114 if (IsGoogleOrChromium) {
1115 FormatStyle::LanguageKind Language = Style.Language;
1116 if (Language == FormatStyle::LK_None)
1117 Language = ((FormatStyle *)IO.getContext())->Language;
1118 if (Language == FormatStyle::LK_JavaScript)
1120 else if (Language == FormatStyle::LK_Java)
1122 }
else if (BasedOnStyle.equals_insensitive(
"webkit")) {
1125 IO.mapOptional(
"AlignAfterOpenBracket", LocalBAS);
1129 Style.AlignAfterOpenBracket =
false;
1130 Style.BreakAfterOpenBracketBracedList =
false;
1131 Style.BreakAfterOpenBracketFunction =
false;
1132 Style.BreakAfterOpenBracketIf =
false;
1133 Style.BreakAfterOpenBracketLoop =
false;
1134 Style.BreakAfterOpenBracketSwitch =
false;
1135 Style.BreakBeforeCloseBracketBracedList =
false;
1136 Style.BreakBeforeCloseBracketFunction =
false;
1137 Style.BreakBeforeCloseBracketIf =
false;
1138 Style.BreakBeforeCloseBracketLoop =
false;
1139 Style.BreakBeforeCloseBracketSwitch =
false;
1142 Style.AlignAfterOpenBracket =
true;
1143 Style.BreakBeforeCloseBracketBracedList =
true;
1144 Style.BreakBeforeCloseBracketFunction =
true;
1145 Style.BreakBeforeCloseBracketIf =
true;
1146 Style.BreakAfterOpenBracketLoop =
false;
1147 Style.BreakAfterOpenBracketSwitch =
false;
1148 Style.BreakBeforeCloseBracketBracedList =
false;
1149 Style.BreakBeforeCloseBracketFunction =
false;
1150 Style.BreakBeforeCloseBracketIf =
false;
1151 Style.BreakBeforeCloseBracketLoop =
false;
1152 Style.BreakBeforeCloseBracketSwitch =
false;
1155 Style.AlignAfterOpenBracket =
true;
1156 Style.BreakAfterOpenBracketBracedList =
true;
1157 Style.BreakAfterOpenBracketFunction =
true;
1158 Style.BreakAfterOpenBracketIf =
true;
1159 Style.BreakAfterOpenBracketLoop =
false;
1160 Style.BreakAfterOpenBracketSwitch =
false;
1161 Style.BreakBeforeCloseBracketBracedList =
false;
1162 Style.BreakBeforeCloseBracketFunction =
false;
1163 Style.BreakBeforeCloseBracketIf =
false;
1164 Style.BreakBeforeCloseBracketLoop =
false;
1165 Style.BreakBeforeCloseBracketSwitch =
false;
1168 Style.AlignAfterOpenBracket =
true;
1169 Style.BreakAfterOpenBracketBracedList =
false;
1170 Style.BreakAfterOpenBracketFunction =
false;
1171 Style.BreakAfterOpenBracketIf =
false;
1172 Style.BreakAfterOpenBracketLoop =
false;
1173 Style.BreakAfterOpenBracketSwitch =
false;
1174 Style.BreakBeforeCloseBracketBracedList =
false;
1175 Style.BreakBeforeCloseBracketFunction =
false;
1176 Style.BreakBeforeCloseBracketIf =
false;
1177 Style.BreakBeforeCloseBracketLoop =
false;
1178 Style.BreakBeforeCloseBracketSwitch =
false;
1186 if (!IO.outputting()) {
1187 IO.mapOptional(
"AlignEscapedNewlinesLeft", Style.AlignEscapedNewlines);
1188 IO.mapOptional(
"AllowAllConstructorInitializersOnNextLine", OnNextLine);
1189 IO.mapOptional(
"AlwaysBreakAfterReturnType", Style.BreakAfterReturnType);
1190 IO.mapOptional(
"AlwaysBreakTemplateDeclarations",
1191 Style.BreakTemplateDeclarations);
1192 IO.mapOptional(
"BinPackArguments", Style.PackArguments.BinPack);
1193 IO.mapOptional(
"BinPackParameters", Style.PackParameters.BinPack);
1194 IO.mapOptional(
"BreakBeforeInheritanceComma",
1195 BreakBeforeInheritanceComma);
1196 IO.mapOptional(
"BreakConstructorInitializersBeforeComma",
1197 BreakConstructorInitializersBeforeComma);
1198 IO.mapOptional(
"ConstructorInitializerAllOnOneLineOrOnePerLine",
1200 IO.mapOptional(
"DeriveLineEnding", DeriveLineEnding);
1201 IO.mapOptional(
"DerivePointerBinding", Style.DerivePointerAlignment);
1202 IO.mapOptional(
"KeepEmptyLinesAtEOF", Style.KeepEmptyLines.AtEndOfFile);
1203 IO.mapOptional(
"KeepEmptyLinesAtTheStartOfBlocks",
1204 Style.KeepEmptyLines.AtStartOfBlock);
1205 IO.mapOptional(
"IndentFunctionDeclarationAfterType",
1206 Style.IndentWrappedFunctionNames);
1207 IO.mapOptional(
"IndentRequires", Style.IndentRequiresClause);
1208 IO.mapOptional(
"PointerBindsToType", Style.PointerAlignment);
1209 IO.mapOptional(
"SpaceAfterControlStatementKeyword",
1210 Style.SpaceBeforeParens);
1211 IO.mapOptional(
"SpaceInEmptyBlock", SpaceInEmptyBlock);
1212 IO.mapOptional(
"SpaceInEmptyParentheses", SpaceInEmptyParentheses);
1213 IO.mapOptional(
"SpacesInConditionalStatement",
1214 SpacesInConditionalStatement);
1215 IO.mapOptional(
"SpacesInCStyleCastParentheses",
1216 SpacesInCStyleCastParentheses);
1217 IO.mapOptional(
"SpacesInParentheses", SpacesInParentheses);
1218 IO.mapOptional(
"UseCRLF", UseCRLF);
1221 IO.mapOptional(
"AccessModifierOffset", Style.AccessModifierOffset);
1222 IO.mapOptional(
"AlignArrayOfStructures", Style.AlignArrayOfStructures);
1223 IO.mapOptional(
"AlignConsecutiveAssignments",
1224 Style.AlignConsecutiveAssignments);
1225 IO.mapOptional(
"AlignConsecutiveBitFields",
1226 Style.AlignConsecutiveBitFields);
1227 IO.mapOptional(
"AlignConsecutiveDeclarations",
1228 Style.AlignConsecutiveDeclarations);
1229 IO.mapOptional(
"AlignConsecutiveMacros", Style.AlignConsecutiveMacros);
1230 IO.mapOptional(
"AlignConsecutiveShortCaseStatements",
1231 Style.AlignConsecutiveShortCaseStatements);
1232 IO.mapOptional(
"AlignConsecutiveTableGenBreakingDAGArgColons",
1233 Style.AlignConsecutiveTableGenBreakingDAGArgColons);
1234 IO.mapOptional(
"AlignConsecutiveTableGenCondOperatorColons",
1235 Style.AlignConsecutiveTableGenCondOperatorColons);
1236 IO.mapOptional(
"AlignConsecutiveTableGenDefinitionColons",
1237 Style.AlignConsecutiveTableGenDefinitionColons);
1238 IO.mapOptional(
"AlignEscapedNewlines", Style.AlignEscapedNewlines);
1239 IO.mapOptional(
"AlignOperands", Style.AlignOperands);
1240 IO.mapOptional(
"AlignTrailingComments", Style.AlignTrailingComments);
1241 IO.mapOptional(
"AllowAllArgumentsOnNextLine",
1242 Style.AllowAllArgumentsOnNextLine);
1243 IO.mapOptional(
"AllowAllParametersOfDeclarationOnNextLine",
1244 Style.AllowAllParametersOfDeclarationOnNextLine);
1245 IO.mapOptional(
"AllowBreakBeforeNoexceptSpecifier",
1246 Style.AllowBreakBeforeNoexceptSpecifier);
1247 IO.mapOptional(
"AllowBreakBeforeQtProperty",
1248 Style.AllowBreakBeforeQtProperty);
1249 IO.mapOptional(
"AllowShortBlocksOnASingleLine",
1250 Style.AllowShortBlocksOnASingleLine);
1251 IO.mapOptional(
"AllowShortCaseExpressionOnASingleLine",
1252 Style.AllowShortCaseExpressionOnASingleLine);
1253 IO.mapOptional(
"AllowShortCaseLabelsOnASingleLine",
1254 Style.AllowShortCaseLabelsOnASingleLine);
1255 IO.mapOptional(
"AllowShortCompoundRequirementOnASingleLine",
1256 Style.AllowShortCompoundRequirementOnASingleLine);
1257 IO.mapOptional(
"AllowShortEnumsOnASingleLine",
1258 Style.AllowShortEnumsOnASingleLine);
1259 IO.mapOptional(
"AllowShortFunctionsOnASingleLine",
1260 Style.AllowShortFunctionsOnASingleLine);
1261 IO.mapOptional(
"AllowShortIfStatementsOnASingleLine",
1262 Style.AllowShortIfStatementsOnASingleLine);
1263 IO.mapOptional(
"AllowShortLambdasOnASingleLine",
1264 Style.AllowShortLambdasOnASingleLine);
1265 IO.mapOptional(
"AllowShortLoopsOnASingleLine",
1266 Style.AllowShortLoopsOnASingleLine);
1267 IO.mapOptional(
"AllowShortNamespacesOnASingleLine",
1268 Style.AllowShortNamespacesOnASingleLine);
1269 IO.mapOptional(
"AllowShortRecordOnASingleLine",
1270 Style.AllowShortRecordOnASingleLine);
1271 IO.mapOptional(
"AlwaysBreakAfterDefinitionReturnType",
1272 Style.AlwaysBreakAfterDefinitionReturnType);
1273 IO.mapOptional(
"AlwaysBreakBeforeMultilineStrings",
1274 Style.AlwaysBreakBeforeMultilineStrings);
1275 IO.mapOptional(
"AttributeMacros", Style.AttributeMacros);
1276 IO.mapOptional(
"BinPackLongBracedList", Style.BinPackLongBracedList);
1277 IO.mapOptional(
"BitFieldColonSpacing", Style.BitFieldColonSpacing);
1278 IO.mapOptional(
"BracedInitializerIndentWidth",
1279 Style.BracedInitializerIndentWidth);
1280 IO.mapOptional(
"BraceWrapping", Style.BraceWrapping);
1281 IO.mapOptional(
"BreakAdjacentStringLiterals",
1282 Style.BreakAdjacentStringLiterals);
1283 IO.mapOptional(
"BreakAfterAttributes", Style.BreakAfterAttributes);
1284 IO.mapOptional(
"BreakAfterJavaFieldAnnotations",
1285 Style.BreakAfterJavaFieldAnnotations);
1286 IO.mapOptional(
"BreakAfterOpenBracketBracedList",
1287 Style.BreakAfterOpenBracketBracedList);
1288 IO.mapOptional(
"BreakAfterOpenBracketFunction",
1289 Style.BreakAfterOpenBracketFunction);
1290 IO.mapOptional(
"BreakAfterOpenBracketIf", Style.BreakAfterOpenBracketIf);
1291 IO.mapOptional(
"BreakAfterOpenBracketLoop",
1292 Style.BreakAfterOpenBracketLoop);
1293 IO.mapOptional(
"BreakAfterOpenBracketSwitch",
1294 Style.BreakAfterOpenBracketSwitch);
1295 IO.mapOptional(
"BreakAfterReturnType", Style.BreakAfterReturnType);
1296 IO.mapOptional(
"BreakArrays", Style.BreakArrays);
1297 IO.mapOptional(
"BreakBeforeBinaryOperators",
1298 Style.BreakBeforeBinaryOperators);
1299 IO.mapOptional(
"BreakBeforeCloseBracketBracedList",
1300 Style.BreakBeforeCloseBracketBracedList);
1301 IO.mapOptional(
"BreakBeforeCloseBracketFunction",
1302 Style.BreakBeforeCloseBracketFunction);
1303 IO.mapOptional(
"BreakBeforeCloseBracketIf",
1304 Style.BreakBeforeCloseBracketIf);
1305 IO.mapOptional(
"BreakBeforeCloseBracketLoop",
1306 Style.BreakBeforeCloseBracketLoop);
1307 IO.mapOptional(
"BreakBeforeCloseBracketSwitch",
1308 Style.BreakBeforeCloseBracketSwitch);
1309 IO.mapOptional(
"BreakBeforeConceptDeclarations",
1310 Style.BreakBeforeConceptDeclarations);
1311 IO.mapOptional(
"BreakBeforeBraces", Style.BreakBeforeBraces);
1312 IO.mapOptional(
"BreakBeforeInlineASMColon",
1313 Style.BreakBeforeInlineASMColon);
1314 IO.mapOptional(
"BreakBeforeTemplateCloser",
1315 Style.BreakBeforeTemplateCloser);
1316 IO.mapOptional(
"BreakBeforeTernaryOperators",
1317 Style.BreakBeforeTernaryOperators);
1318 IO.mapOptional(
"BreakBinaryOperations", Style.BreakBinaryOperations);
1319 IO.mapOptional(
"BreakConstructorInitializers",
1320 Style.BreakConstructorInitializers);
1321 IO.mapOptional(
"BreakFunctionDeclarationParameters",
1322 Style.BreakFunctionDeclarationParameters);
1323 IO.mapOptional(
"BreakFunctionDefinitionParameters",
1324 Style.BreakFunctionDefinitionParameters);
1325 IO.mapOptional(
"BreakInheritanceList", Style.BreakInheritanceList);
1326 IO.mapOptional(
"BreakStringLiterals", Style.BreakStringLiterals);
1327 IO.mapOptional(
"BreakTemplateDeclarations",
1328 Style.BreakTemplateDeclarations);
1329 IO.mapOptional(
"ColumnLimit", Style.ColumnLimit);
1330 IO.mapOptional(
"CommentPragmas", Style.CommentPragmas);
1331 IO.mapOptional(
"CompactNamespaces", Style.CompactNamespaces);
1332 IO.mapOptional(
"ConstructorInitializerIndentWidth",
1333 Style.ConstructorInitializerIndentWidth);
1334 IO.mapOptional(
"ContinuationIndentWidth", Style.ContinuationIndentWidth);
1335 IO.mapOptional(
"Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
1336 IO.mapOptional(
"DerivePointerAlignment", Style.DerivePointerAlignment);
1337 IO.mapOptional(
"DisableFormat", Style.DisableFormat);
1338 IO.mapOptional(
"EmptyLineAfterAccessModifier",
1339 Style.EmptyLineAfterAccessModifier);
1340 IO.mapOptional(
"EmptyLineBeforeAccessModifier",
1341 Style.EmptyLineBeforeAccessModifier);
1342 IO.mapOptional(
"EnumTrailingComma", Style.EnumTrailingComma);
1343 IO.mapOptional(
"ExperimentalAutoDetectBinPacking",
1344 Style.ExperimentalAutoDetectBinPacking);
1345 IO.mapOptional(
"FixNamespaceComments", Style.FixNamespaceComments);
1346 IO.mapOptional(
"ForEachMacros", Style.ForEachMacros);
1347 IO.mapOptional(
"IfMacros", Style.IfMacros);
1348 IO.mapOptional(
"IncludeBlocks", Style.IncludeStyle.IncludeBlocks);
1349 IO.mapOptional(
"IncludeCategories", Style.IncludeStyle.IncludeCategories);
1350 IO.mapOptional(
"IncludeIsMainRegex", Style.IncludeStyle.IncludeIsMainRegex);
1351 IO.mapOptional(
"IncludeIsMainSourceRegex",
1352 Style.IncludeStyle.IncludeIsMainSourceRegex);
1353 IO.mapOptional(
"IndentAccessModifiers", Style.IndentAccessModifiers);
1354 IO.mapOptional(
"IndentCaseBlocks", Style.IndentCaseBlocks);
1355 IO.mapOptional(
"IndentCaseLabels", Style.IndentCaseLabels);
1356 IO.mapOptional(
"IndentExportBlock", Style.IndentExportBlock);
1357 IO.mapOptional(
"IndentExternBlock", Style.IndentExternBlock);
1358 IO.mapOptional(
"IndentGotoLabels", Style.IndentGotoLabels);
1359 IO.mapOptional(
"IndentPPDirectives", Style.IndentPPDirectives);
1360 IO.mapOptional(
"IndentRequiresClause", Style.IndentRequiresClause);
1361 IO.mapOptional(
"IndentWidth", Style.IndentWidth);
1362 IO.mapOptional(
"IndentWrappedFunctionNames",
1363 Style.IndentWrappedFunctionNames);
1364 IO.mapOptional(
"InsertBraces", Style.InsertBraces);
1365 IO.mapOptional(
"InsertNewlineAtEOF", Style.InsertNewlineAtEOF);
1366 IO.mapOptional(
"InsertTrailingCommas", Style.InsertTrailingCommas);
1367 IO.mapOptional(
"IntegerLiteralSeparator", Style.IntegerLiteralSeparator);
1368 IO.mapOptional(
"JavaImportGroups", Style.JavaImportGroups);
1369 IO.mapOptional(
"JavaScriptQuotes", Style.JavaScriptQuotes);
1370 IO.mapOptional(
"JavaScriptWrapImports", Style.JavaScriptWrapImports);
1371 IO.mapOptional(
"KeepEmptyLines", Style.KeepEmptyLines);
1372 IO.mapOptional(
"KeepFormFeed", Style.KeepFormFeed);
1373 IO.mapOptional(
"LambdaBodyIndentation", Style.LambdaBodyIndentation);
1374 IO.mapOptional(
"LineEnding", Style.LineEnding);
1375 IO.mapOptional(
"MacroBlockBegin", Style.MacroBlockBegin);
1376 IO.mapOptional(
"MacroBlockEnd", Style.MacroBlockEnd);
1377 IO.mapOptional(
"Macros", Style.Macros);
1378 IO.mapOptional(
"MacrosSkippedByRemoveParentheses",
1379 Style.MacrosSkippedByRemoveParentheses);
1380 IO.mapOptional(
"MainIncludeChar", Style.IncludeStyle.MainIncludeChar);
1381 IO.mapOptional(
"MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
1382 IO.mapOptional(
"NamespaceIndentation", Style.NamespaceIndentation);
1383 IO.mapOptional(
"NamespaceMacros", Style.NamespaceMacros);
1384 IO.mapOptional(
"NumericLiteralCase", Style.NumericLiteralCase);
1385 IO.mapOptional(
"ObjCBinPackProtocolList", Style.ObjCBinPackProtocolList);
1386 IO.mapOptional(
"ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
1387 IO.mapOptional(
"ObjCBreakBeforeNestedBlockParam",
1388 Style.ObjCBreakBeforeNestedBlockParam);
1389 IO.mapOptional(
"ObjCPropertyAttributeOrder",
1390 Style.ObjCPropertyAttributeOrder);
1391 IO.mapOptional(
"ObjCSpaceAfterMethodDeclarationPrefix",
1392 Style.ObjCSpaceAfterMethodDeclarationPrefix);
1393 IO.mapOptional(
"ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
1394 IO.mapOptional(
"ObjCSpaceBeforeProtocolList",
1395 Style.ObjCSpaceBeforeProtocolList);
1396 IO.mapOptional(
"OneLineFormatOffRegex", Style.OneLineFormatOffRegex);
1397 IO.mapOptional(
"PackArguments", Style.PackArguments);
1398 IO.mapOptional(
"PackConstructorInitializers",
1399 Style.PackConstructorInitializers);
1400 IO.mapOptional(
"PackParameters", Style.PackParameters);
1401 IO.mapOptional(
"PenaltyBreakAssignment", Style.PenaltyBreakAssignment);
1402 IO.mapOptional(
"PenaltyBreakBeforeFirstCallParameter",
1403 Style.PenaltyBreakBeforeFirstCallParameter);
1404 IO.mapOptional(
"PenaltyBreakBeforeMemberAccess",
1405 Style.PenaltyBreakBeforeMemberAccess);
1406 IO.mapOptional(
"PenaltyBreakComment", Style.PenaltyBreakComment);
1407 IO.mapOptional(
"PenaltyBreakFirstLessLess",
1408 Style.PenaltyBreakFirstLessLess);
1409 IO.mapOptional(
"PenaltyBreakOpenParenthesis",
1410 Style.PenaltyBreakOpenParenthesis);
1411 IO.mapOptional(
"PenaltyBreakScopeResolution",
1412 Style.PenaltyBreakScopeResolution);
1413 IO.mapOptional(
"PenaltyBreakString", Style.PenaltyBreakString);
1414 IO.mapOptional(
"PenaltyBreakTemplateDeclaration",
1415 Style.PenaltyBreakTemplateDeclaration);
1416 IO.mapOptional(
"PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
1417 IO.mapOptional(
"PenaltyIndentedWhitespace",
1418 Style.PenaltyIndentedWhitespace);
1419 IO.mapOptional(
"PenaltyReturnTypeOnItsOwnLine",
1420 Style.PenaltyReturnTypeOnItsOwnLine);
1421 IO.mapOptional(
"PointerAlignment", Style.PointerAlignment);
1422 IO.mapOptional(
"PPIndentWidth", Style.PPIndentWidth);
1423 IO.mapOptional(
"QualifierAlignment", Style.QualifierAlignment);
1425 if (Style.QualifierAlignment == FormatStyle::QAS_Right)
1426 Style.QualifierOrder = {
"type",
"const",
"volatile"};
1427 else if (Style.QualifierAlignment == FormatStyle::QAS_Left)
1428 Style.QualifierOrder = {
"const",
"volatile",
"type"};
1429 else if (Style.QualifierAlignment == FormatStyle::QAS_Custom)
1430 IO.mapOptional(
"QualifierOrder", Style.QualifierOrder);
1431 IO.mapOptional(
"RawStringFormats", Style.RawStringFormats);
1432 IO.mapOptional(
"ReferenceAlignment", Style.ReferenceAlignment);
1433 IO.mapOptional(
"ReflowComments", Style.ReflowComments);
1434 IO.mapOptional(
"RemoveBracesLLVM", Style.RemoveBracesLLVM);
1435 IO.mapOptional(
"RemoveEmptyLinesInUnwrappedLines",
1436 Style.RemoveEmptyLinesInUnwrappedLines);
1437 IO.mapOptional(
"RemoveParentheses", Style.RemoveParentheses);
1438 IO.mapOptional(
"RemoveSemicolon", Style.RemoveSemicolon);
1439 IO.mapOptional(
"RequiresClausePosition", Style.RequiresClausePosition);
1440 IO.mapOptional(
"RequiresExpressionIndentation",
1441 Style.RequiresExpressionIndentation);
1442 IO.mapOptional(
"SeparateDefinitionBlocks", Style.SeparateDefinitionBlocks);
1443 IO.mapOptional(
"ShortNamespaceLines", Style.ShortNamespaceLines);
1444 IO.mapOptional(
"SkipMacroDefinitionBody", Style.SkipMacroDefinitionBody);
1445 IO.mapOptional(
"SortIncludes", Style.SortIncludes);
1446 IO.mapOptional(
"SortJavaStaticImport", Style.SortJavaStaticImport);
1447 IO.mapOptional(
"SortUsingDeclarations", Style.SortUsingDeclarations);
1448 IO.mapOptional(
"SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
1449 IO.mapOptional(
"SpaceAfterLogicalNot", Style.SpaceAfterLogicalNot);
1450 IO.mapOptional(
"SpaceAfterOperatorKeyword",
1451 Style.SpaceAfterOperatorKeyword);
1452 IO.mapOptional(
"SpaceAfterTemplateKeyword",
1453 Style.SpaceAfterTemplateKeyword);
1454 IO.mapOptional(
"SpaceAroundPointerQualifiers",
1455 Style.SpaceAroundPointerQualifiers);
1456 IO.mapOptional(
"SpaceBeforeAssignmentOperators",
1457 Style.SpaceBeforeAssignmentOperators);
1458 IO.mapOptional(
"SpaceBeforeCaseColon", Style.SpaceBeforeCaseColon);
1459 IO.mapOptional(
"SpaceBeforeCpp11BracedList",
1460 Style.SpaceBeforeCpp11BracedList);
1461 IO.mapOptional(
"SpaceBeforeCtorInitializerColon",
1462 Style.SpaceBeforeCtorInitializerColon);
1463 IO.mapOptional(
"SpaceBeforeEnumUnderlyingTypeColon",
1464 Style.SpaceBeforeEnumUnderlyingTypeColon);
1465 IO.mapOptional(
"SpaceBeforeInheritanceColon",
1466 Style.SpaceBeforeInheritanceColon);
1467 IO.mapOptional(
"SpaceBeforeJsonColon", Style.SpaceBeforeJsonColon);
1468 IO.mapOptional(
"SpaceBeforeParens", Style.SpaceBeforeParens);
1469 IO.mapOptional(
"SpaceBeforeParensOptions", Style.SpaceBeforeParensOptions);
1470 IO.mapOptional(
"SpaceBeforeRangeBasedForLoopColon",
1471 Style.SpaceBeforeRangeBasedForLoopColon);
1472 IO.mapOptional(
"SpaceBeforeSquareBrackets",
1473 Style.SpaceBeforeSquareBrackets);
1474 IO.mapOptional(
"SpaceInEmptyBraces", Style.SpaceInEmptyBraces);
1475 IO.mapOptional(
"SpacesBeforeTrailingComments",
1476 Style.SpacesBeforeTrailingComments);
1477 IO.mapOptional(
"SpacesInAngles", Style.SpacesInAngles);
1478 IO.mapOptional(
"SpacesInContainerLiterals",
1479 Style.SpacesInContainerLiterals);
1480 IO.mapOptional(
"SpacesInLineCommentPrefix",
1481 Style.SpacesInLineCommentPrefix);
1482 IO.mapOptional(
"SpacesInParens", Style.SpacesInParens);
1483 IO.mapOptional(
"SpacesInParensOptions", Style.SpacesInParensOptions);
1484 IO.mapOptional(
"SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
1485 IO.mapOptional(
"Standard", Style.Standard);
1486 IO.mapOptional(
"StatementAttributeLikeMacros",
1487 Style.StatementAttributeLikeMacros);
1488 IO.mapOptional(
"StatementMacros", Style.StatementMacros);
1489 IO.mapOptional(
"TableGenBreakingDAGArgOperators",
1490 Style.TableGenBreakingDAGArgOperators);
1491 IO.mapOptional(
"TableGenBreakInsideDAGArg",
1492 Style.TableGenBreakInsideDAGArg);
1493 IO.mapOptional(
"TabWidth", Style.TabWidth);
1494 IO.mapOptional(
"TemplateNames", Style.TemplateNames);
1495 IO.mapOptional(
"TypeNames", Style.TypeNames);
1496 IO.mapOptional(
"TypenameMacros", Style.TypenameMacros);
1497 IO.mapOptional(
"UseTab", Style.UseTab);
1498 IO.mapOptional(
"VariableTemplates", Style.VariableTemplates);
1499 IO.mapOptional(
"VerilogBreakBetweenInstancePorts",
1500 Style.VerilogBreakBetweenInstancePorts);
1501 IO.mapOptional(
"WhitespaceSensitiveMacros",
1502 Style.WhitespaceSensitiveMacros);
1503 IO.mapOptional(
"WrapNamespaceBodyWithEmptyLines",
1504 Style.WrapNamespaceBodyWithEmptyLines);
1509 if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
1510 Style.BreakAfterReturnType == FormatStyle::RTBS_None) {
1511 if (Style.AlwaysBreakAfterDefinitionReturnType ==
1512 FormatStyle::DRTBS_All) {
1513 Style.BreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
1514 }
else if (Style.AlwaysBreakAfterDefinitionReturnType ==
1515 FormatStyle::DRTBS_TopLevel) {
1516 Style.BreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
1522 if (BreakBeforeInheritanceComma &&
1523 Style.BreakInheritanceList == FormatStyle::BILS_BeforeColon) {
1524 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
1530 if (BreakConstructorInitializersBeforeComma &&
1531 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon) {
1532 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
1535 if (!IsGoogleOrChromium) {
1536 if (Style.PackConstructorInitializers == FormatStyle::PCIS_BinPack &&
1538 Style.PackConstructorInitializers = OnNextLine
1539 ? FormatStyle::PCIS_NextLine
1540 : FormatStyle::PCIS_CurrentLine;
1542 }
else if (Style.PackConstructorInitializers ==
1543 FormatStyle::PCIS_NextLine) {
1545 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
1546 else if (!OnNextLine)
1547 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
1550 if (Style.LineEnding == FormatStyle::LE_DeriveLF) {
1551 if (!DeriveLineEnding)
1552 Style.LineEnding = UseCRLF ? FormatStyle::LE_CRLF : FormatStyle::LE_LF;
1554 Style.LineEnding = FormatStyle::LE_DeriveCRLF;
1559 if (SpaceInEmptyBlock &&
1560 Style.SpaceInEmptyBraces == FormatStyle::SIEB_Never) {
1561 Style.SpaceInEmptyBraces = FormatStyle::SIEB_Block;
1564 if (Style.SpacesInParens != FormatStyle::SIPO_Custom &&
1565 (SpacesInParentheses || SpaceInEmptyParentheses ||
1566 SpacesInConditionalStatement || SpacesInCStyleCastParentheses)) {
1567 if (SpacesInParentheses) {
1569 Style.SpacesInParensOptions.ExceptDoubleParentheses =
false;
1570 Style.SpacesInParensOptions.InConditionalStatements =
true;
1571 Style.SpacesInParensOptions.InCStyleCasts =
1572 SpacesInCStyleCastParentheses;
1573 Style.SpacesInParensOptions.InEmptyParentheses =
1574 SpaceInEmptyParentheses;
1575 Style.SpacesInParensOptions.Other =
true;
1577 Style.SpacesInParensOptions = {};
1578 Style.SpacesInParensOptions.InConditionalStatements =
1579 SpacesInConditionalStatement;
1580 Style.SpacesInParensOptions.InCStyleCasts =
1581 SpacesInCStyleCastParentheses;
1582 Style.SpacesInParensOptions.InEmptyParentheses =
1583 SpaceInEmptyParentheses;
1585 Style.SpacesInParens = FormatStyle::SIPO_Custom;
1595template <>
struct DocumentListTraits<
std::vector<FormatStyle>> {
1596 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
1599 static FormatStyle &
element(IO &IO, std::vector<FormatStyle> &Seq,
1601 if (Index >= Seq.size()) {
1602 assert(Index == Seq.size());
1603 FormatStyle Template;
1604 if (!Seq.empty() && Seq[0].Language == FormatStyle::LK_None) {
1607 Template = *((
const FormatStyle *)IO.getContext());
1608 Template.Language = FormatStyle::LK_None;
1610 Seq.resize(Index + 1, Template);
1616template <>
struct ScalarEnumerationTraits<FormatStyle::IndentGotoLabelStyle> {
1618 IO.enumCase(
Value,
"NoIndent", FormatStyle::IGLS_NoIndent);
1619 IO.enumCase(
Value,
"OuterIndent", FormatStyle::IGLS_OuterIndent);
1620 IO.enumCase(
Value,
"InnerIndent", FormatStyle::IGLS_InnerIndent);
1621 IO.enumCase(
Value,
"HalfIndent", FormatStyle::IGLS_HalfIndent);
1624 IO.enumCase(
Value,
"false", FormatStyle::IGLS_NoIndent);
1625 IO.enumCase(
Value,
"true", FormatStyle::IGLS_OuterIndent);
1644 return llvm::make_error<llvm::StringError>(Message,
1645 llvm::inconvertibleErrorCode());
1649 return "clang-format.parse_error";
1657 return "Invalid argument";
1659 return "Unsuitable";
1661 return "trailing comma insertion cannot be used with bin packing";
1663 return "Invalid qualifier specified in QualifierOrder";
1665 return "Duplicate qualifier specified in QualifierOrder";
1667 return "Missing type in QualifierOrder";
1669 return "Missing QualifierOrder";
1671 llvm_unreachable(
"unexpected parse error");
1675 if (Expanded.BreakBeforeBraces == FormatStyle::BS_Custom)
1677 Expanded.BraceWrapping = {
false,
1679 FormatStyle::BWACS_Never,
1695 switch (Expanded.BreakBeforeBraces) {
1696 case FormatStyle::BS_Linux:
1697 Expanded.BraceWrapping.AfterClass =
true;
1698 Expanded.BraceWrapping.AfterFunction =
true;
1699 Expanded.BraceWrapping.AfterNamespace =
true;
1701 case FormatStyle::BS_Mozilla:
1702 Expanded.BraceWrapping.AfterClass =
true;
1703 Expanded.BraceWrapping.AfterEnum =
true;
1704 Expanded.BraceWrapping.AfterFunction =
true;
1705 Expanded.BraceWrapping.AfterStruct =
true;
1706 Expanded.BraceWrapping.AfterUnion =
true;
1707 Expanded.BraceWrapping.AfterExternBlock =
true;
1708 Expanded.BraceWrapping.SplitEmptyFunction =
true;
1709 Expanded.BraceWrapping.SplitEmptyRecord =
false;
1711 case FormatStyle::BS_Stroustrup:
1712 Expanded.BraceWrapping.AfterFunction =
true;
1713 Expanded.BraceWrapping.BeforeCatch =
true;
1714 Expanded.BraceWrapping.BeforeElse =
true;
1716 case FormatStyle::BS_Allman:
1717 Expanded.BraceWrapping.AfterCaseLabel =
true;
1718 Expanded.BraceWrapping.AfterClass =
true;
1719 Expanded.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1720 Expanded.BraceWrapping.AfterEnum =
true;
1721 Expanded.BraceWrapping.AfterFunction =
true;
1722 Expanded.BraceWrapping.AfterNamespace =
true;
1723 Expanded.BraceWrapping.AfterObjCDeclaration =
true;
1724 Expanded.BraceWrapping.AfterStruct =
true;
1725 Expanded.BraceWrapping.AfterUnion =
true;
1726 Expanded.BraceWrapping.AfterExternBlock =
true;
1727 Expanded.BraceWrapping.BeforeCatch =
true;
1728 Expanded.BraceWrapping.BeforeElse =
true;
1729 Expanded.BraceWrapping.BeforeLambdaBody =
true;
1731 case FormatStyle::BS_Whitesmiths:
1732 Expanded.BraceWrapping.AfterCaseLabel =
true;
1733 Expanded.BraceWrapping.AfterClass =
true;
1734 Expanded.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1735 Expanded.BraceWrapping.AfterEnum =
true;
1736 Expanded.BraceWrapping.AfterFunction =
true;
1737 Expanded.BraceWrapping.AfterNamespace =
true;
1738 Expanded.BraceWrapping.AfterObjCDeclaration =
true;
1739 Expanded.BraceWrapping.AfterStruct =
true;
1740 Expanded.BraceWrapping.AfterExternBlock =
true;
1741 Expanded.BraceWrapping.BeforeCatch =
true;
1742 Expanded.BraceWrapping.BeforeElse =
true;
1743 Expanded.BraceWrapping.BeforeLambdaBody =
true;
1745 case FormatStyle::BS_GNU:
1746 Expanded.BraceWrapping = {
1749 FormatStyle::BWACS_Always,
1766 case FormatStyle::BS_WebKit:
1767 Expanded.BraceWrapping.AfterFunction =
true;
1775 if (Expanded.SpaceBeforeParens == FormatStyle::SBPO_Custom)
1778 Expanded.SpaceBeforeParensOptions = {};
1779 Expanded.SpaceBeforeParensOptions.AfterPlacementOperator =
true;
1781 switch (Expanded.SpaceBeforeParens) {
1782 case FormatStyle::SBPO_ControlStatements:
1783 Expanded.SpaceBeforeParensOptions.AfterControlStatements =
true;
1784 Expanded.SpaceBeforeParensOptions.AfterForeachMacros =
true;
1785 Expanded.SpaceBeforeParensOptions.AfterIfMacros =
true;
1787 case FormatStyle::SBPO_ControlStatementsExceptControlMacros:
1788 Expanded.SpaceBeforeParensOptions.AfterControlStatements =
true;
1790 case FormatStyle::SBPO_NonEmptyParentheses:
1791 Expanded.SpaceBeforeParensOptions.BeforeNonEmptyParentheses =
true;
1799 if (Expanded.SpacesInParens == FormatStyle::SIPO_Custom)
1801 assert(Expanded.SpacesInParens == FormatStyle::SIPO_Never);
1803 Expanded.SpacesInParensOptions = {};
1807 FormatStyle LLVMStyle;
1808 LLVMStyle.AccessModifierOffset = -2;
1809 LLVMStyle.AlignAfterOpenBracket =
true;
1810 LLVMStyle.AlignArrayOfStructures = FormatStyle::AIAS_None;
1811 LLVMStyle.AlignConsecutiveAssignments = {};
1812 LLVMStyle.AlignConsecutiveAssignments.PadOperators =
true;
1813 LLVMStyle.AlignConsecutiveBitFields = {};
1814 LLVMStyle.AlignConsecutiveDeclarations = {};
1815 LLVMStyle.AlignConsecutiveDeclarations.AlignFunctionDeclarations =
true;
1816 LLVMStyle.AlignConsecutiveMacros = {};
1817 LLVMStyle.AlignConsecutiveShortCaseStatements = {};
1818 LLVMStyle.AlignConsecutiveTableGenBreakingDAGArgColons = {};
1819 LLVMStyle.AlignConsecutiveTableGenCondOperatorColons = {};
1820 LLVMStyle.AlignConsecutiveTableGenDefinitionColons = {};
1821 LLVMStyle.AlignEscapedNewlines = FormatStyle::ENAS_Right;
1822 LLVMStyle.AlignOperands = FormatStyle::OAS_Align;
1823 LLVMStyle.AlignTrailingComments = {};
1824 LLVMStyle.AlignTrailingComments.Kind = FormatStyle::TCAS_Always;
1825 LLVMStyle.AlignTrailingComments.OverEmptyLines = 0;
1826 LLVMStyle.AlignTrailingComments.AlignPPAndNotPP =
true;
1827 LLVMStyle.AllowAllArgumentsOnNextLine =
true;
1828 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine =
true;
1829 LLVMStyle.AllowBreakBeforeNoexceptSpecifier = FormatStyle::BBNSS_Never;
1830 LLVMStyle.AllowBreakBeforeQtProperty =
false;
1831 LLVMStyle.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
1832 LLVMStyle.AllowShortCaseExpressionOnASingleLine =
true;
1833 LLVMStyle.AllowShortCaseLabelsOnASingleLine =
false;
1834 LLVMStyle.AllowShortCompoundRequirementOnASingleLine =
true;
1835 LLVMStyle.AllowShortEnumsOnASingleLine =
true;
1836 LLVMStyle.AllowShortFunctionsOnASingleLine =
1837 FormatStyle::ShortFunctionStyle::setAll();
1838 LLVMStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
1839 LLVMStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
1840 LLVMStyle.AllowShortLoopsOnASingleLine =
false;
1841 LLVMStyle.AllowShortNamespacesOnASingleLine =
false;
1842 LLVMStyle.AllowShortRecordOnASingleLine = FormatStyle::SRS_EmptyAndAttached;
1843 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
1844 LLVMStyle.AlwaysBreakBeforeMultilineStrings =
false;
1845 LLVMStyle.AttributeMacros.push_back(
"__capability");
1846 LLVMStyle.BinPackLongBracedList =
true;
1847 LLVMStyle.BitFieldColonSpacing = FormatStyle::BFCS_Both;
1848 LLVMStyle.BracedInitializerIndentWidth = -1;
1849 LLVMStyle.BraceWrapping = {
false,
1851 FormatStyle::BWACS_Never,
1867 LLVMStyle.BreakAdjacentStringLiterals =
true;
1868 LLVMStyle.BreakAfterAttributes = FormatStyle::ABS_Leave;
1869 LLVMStyle.BreakAfterJavaFieldAnnotations =
false;
1870 LLVMStyle.BreakAfterOpenBracketBracedList =
false;
1871 LLVMStyle.BreakAfterOpenBracketFunction =
false;
1872 LLVMStyle.BreakAfterOpenBracketIf =
false;
1873 LLVMStyle.BreakAfterOpenBracketLoop =
false;
1874 LLVMStyle.BreakAfterOpenBracketSwitch =
false;
1875 LLVMStyle.BreakAfterReturnType = FormatStyle::RTBS_None;
1876 LLVMStyle.BreakArrays =
true;
1877 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
1878 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
1879 LLVMStyle.BreakBeforeCloseBracketBracedList =
false;
1880 LLVMStyle.BreakBeforeCloseBracketFunction =
false;
1881 LLVMStyle.BreakBeforeCloseBracketIf =
false;
1882 LLVMStyle.BreakBeforeCloseBracketLoop =
false;
1883 LLVMStyle.BreakBeforeCloseBracketSwitch =
false;
1884 LLVMStyle.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Always;
1885 LLVMStyle.BreakBeforeInlineASMColon = FormatStyle::BBIAS_OnlyMultiline;
1886 LLVMStyle.BreakBeforeTemplateCloser =
false;
1887 LLVMStyle.BreakBeforeTernaryOperators =
true;
1888 LLVMStyle.BreakBinaryOperations = {FormatStyle::BBO_Never, {}};
1889 LLVMStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
1890 LLVMStyle.BreakFunctionDeclarationParameters =
false;
1891 LLVMStyle.BreakFunctionDefinitionParameters =
false;
1892 LLVMStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
1893 LLVMStyle.BreakStringLiterals =
true;
1894 LLVMStyle.BreakTemplateDeclarations = FormatStyle::BTDS_MultiLine;
1895 LLVMStyle.ColumnLimit = 80;
1896 LLVMStyle.CommentPragmas =
"^ IWYU pragma:";
1897 LLVMStyle.CompactNamespaces =
false;
1898 LLVMStyle.ConstructorInitializerIndentWidth = 4;
1899 LLVMStyle.ContinuationIndentWidth = 4;
1900 LLVMStyle.Cpp11BracedListStyle = FormatStyle::BLS_AlignFirstComment;
1901 LLVMStyle.DerivePointerAlignment =
false;
1902 LLVMStyle.DisableFormat =
false;
1903 LLVMStyle.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
1904 LLVMStyle.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
1905 LLVMStyle.EnumTrailingComma = FormatStyle::ETC_Leave;
1906 LLVMStyle.ExperimentalAutoDetectBinPacking =
false;
1907 LLVMStyle.FixNamespaceComments =
true;
1908 LLVMStyle.ForEachMacros.push_back(
"foreach");
1909 LLVMStyle.ForEachMacros.push_back(
"Q_FOREACH");
1910 LLVMStyle.ForEachMacros.push_back(
"BOOST_FOREACH");
1911 LLVMStyle.IfMacros.push_back(
"KJ_IF_MAYBE");
1913 LLVMStyle.IncludeStyle.IncludeCategories = {
1914 {
"^\"(llvm|llvm-c|clang|clang-c)/", 2, 0,
false},
1915 {
"^(<|\"(gtest|gmock|isl|json)/)", 3, 0,
false},
1916 {
".*", 1, 0,
false}};
1917 LLVMStyle.IncludeStyle.IncludeIsMainRegex =
"(Test)?$";
1918 LLVMStyle.IncludeStyle.MainIncludeChar = tooling::IncludeStyle::MICD_Quote;
1919 LLVMStyle.IndentAccessModifiers =
false;
1920 LLVMStyle.IndentCaseBlocks =
false;
1921 LLVMStyle.IndentCaseLabels =
false;
1922 LLVMStyle.IndentExportBlock =
true;
1923 LLVMStyle.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
1924 LLVMStyle.IndentGotoLabels = FormatStyle::IGLS_OuterIndent;
1925 LLVMStyle.IndentPPDirectives = FormatStyle::PPDIS_None;
1926 LLVMStyle.IndentRequiresClause =
true;
1927 LLVMStyle.IndentWidth = 2;
1928 LLVMStyle.IndentWrappedFunctionNames =
false;
1929 LLVMStyle.InsertBraces =
false;
1930 LLVMStyle.InsertNewlineAtEOF =
false;
1931 LLVMStyle.InsertTrailingCommas = FormatStyle::TCS_None;
1932 LLVMStyle.IntegerLiteralSeparator = {};
1933 LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
1934 LLVMStyle.JavaScriptWrapImports =
true;
1935 LLVMStyle.KeepEmptyLines = {
1940 LLVMStyle.KeepFormFeed =
false;
1941 LLVMStyle.LambdaBodyIndentation = FormatStyle::LBI_Signature;
1943 LLVMStyle.LineEnding = FormatStyle::LE_DeriveLF;
1944 LLVMStyle.MaxEmptyLinesToKeep = 1;
1945 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
1946 LLVMStyle.NumericLiteralCase = {FormatStyle::NLCS_Leave,
1947 FormatStyle::NLCS_Leave,
1948 FormatStyle::NLCS_Leave,
1949 FormatStyle::NLCS_Leave};
1950 LLVMStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Auto;
1951 LLVMStyle.ObjCBlockIndentWidth = 2;
1952 LLVMStyle.ObjCBreakBeforeNestedBlockParam =
true;
1953 LLVMStyle.ObjCSpaceAfterMethodDeclarationPrefix =
true;
1954 LLVMStyle.ObjCSpaceAfterProperty =
false;
1955 LLVMStyle.ObjCSpaceBeforeProtocolList =
true;
1956 LLVMStyle.PackArguments = {FormatStyle::BPAS_BinPack,
1958 LLVMStyle.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
1959 LLVMStyle.PackParameters = {FormatStyle::BPPS_BinPack,
1961 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
1962 LLVMStyle.PPIndentWidth = -1;
1963 LLVMStyle.QualifierAlignment = FormatStyle::QAS_Leave;
1964 LLVMStyle.ReferenceAlignment = FormatStyle::RAS_Pointer;
1965 LLVMStyle.ReflowComments = FormatStyle::RCS_Always;
1966 LLVMStyle.RemoveBracesLLVM =
false;
1967 LLVMStyle.RemoveEmptyLinesInUnwrappedLines =
false;
1968 LLVMStyle.RemoveParentheses = FormatStyle::RPS_Leave;
1969 LLVMStyle.RemoveSemicolon =
false;
1970 LLVMStyle.RequiresClausePosition = FormatStyle::RCPS_OwnLine;
1971 LLVMStyle.RequiresExpressionIndentation = FormatStyle::REI_OuterScope;
1972 LLVMStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Leave;
1973 LLVMStyle.ShortNamespaceLines = 1;
1974 LLVMStyle.SkipMacroDefinitionBody =
false;
1975 LLVMStyle.SortIncludes = {
true,
false,
1977 LLVMStyle.SortJavaStaticImport = FormatStyle::SJSIO_Before;
1978 LLVMStyle.SortUsingDeclarations = FormatStyle::SUD_LexicographicNumeric;
1979 LLVMStyle.SpaceAfterCStyleCast =
false;
1980 LLVMStyle.SpaceAfterLogicalNot =
false;
1981 LLVMStyle.SpaceAfterOperatorKeyword =
false;
1982 LLVMStyle.SpaceAfterTemplateKeyword =
true;
1983 LLVMStyle.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
1984 LLVMStyle.SpaceBeforeAssignmentOperators =
true;
1985 LLVMStyle.SpaceBeforeCaseColon =
false;
1986 LLVMStyle.SpaceBeforeCpp11BracedList =
false;
1987 LLVMStyle.SpaceBeforeCtorInitializerColon =
true;
1988 LLVMStyle.SpaceBeforeEnumUnderlyingTypeColon =
true;
1989 LLVMStyle.SpaceBeforeInheritanceColon =
true;
1990 LLVMStyle.SpaceBeforeJsonColon =
false;
1991 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
1992 LLVMStyle.SpaceBeforeParensOptions = {};
1993 LLVMStyle.SpaceBeforeParensOptions.AfterControlStatements =
true;
1994 LLVMStyle.SpaceBeforeParensOptions.AfterForeachMacros =
true;
1995 LLVMStyle.SpaceBeforeParensOptions.AfterIfMacros =
true;
1996 LLVMStyle.SpaceBeforeRangeBasedForLoopColon =
true;
1997 LLVMStyle.SpaceBeforeSquareBrackets =
false;
1998 LLVMStyle.SpaceInEmptyBraces = FormatStyle::SIEB_Never;
1999 LLVMStyle.SpacesBeforeTrailingComments = 1;
2000 LLVMStyle.SpacesInAngles = FormatStyle::SIAS_Never;
2001 LLVMStyle.SpacesInContainerLiterals =
true;
2002 LLVMStyle.SpacesInLineCommentPrefix = {
2003 1, std::numeric_limits<unsigned>::max()};
2004 LLVMStyle.SpacesInParens = FormatStyle::SIPO_Never;
2005 LLVMStyle.SpacesInSquareBrackets =
false;
2006 LLVMStyle.Standard = FormatStyle::LS_Latest;
2007 LLVMStyle.StatementAttributeLikeMacros.push_back(
"Q_EMIT");
2008 LLVMStyle.StatementMacros.push_back(
"Q_UNUSED");
2009 LLVMStyle.StatementMacros.push_back(
"QT_REQUIRE_VERSION");
2010 LLVMStyle.TableGenBreakingDAGArgOperators = {};
2011 LLVMStyle.TableGenBreakInsideDAGArg = FormatStyle::DAS_DontBreak;
2012 LLVMStyle.TabWidth = 8;
2013 LLVMStyle.UseTab = FormatStyle::UT_Never;
2014 LLVMStyle.VerilogBreakBetweenInstancePorts =
true;
2015 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"BOOST_PP_STRINGIZE");
2016 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"CF_SWIFT_NAME");
2017 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"NS_SWIFT_NAME");
2018 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"PP_STRINGIZE");
2019 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"STRINGIZE");
2020 LLVMStyle.WrapNamespaceBodyWithEmptyLines = FormatStyle::WNBWELS_Leave;
2023 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
2024 LLVMStyle.PenaltyBreakBeforeMemberAccess = 150;
2025 LLVMStyle.PenaltyBreakComment = 300;
2026 LLVMStyle.PenaltyBreakFirstLessLess = 120;
2027 LLVMStyle.PenaltyBreakOpenParenthesis = 0;
2028 LLVMStyle.PenaltyBreakScopeResolution = 500;
2029 LLVMStyle.PenaltyBreakString = 1000;
2031 LLVMStyle.PenaltyExcessCharacter = 1'000'000;
2032 LLVMStyle.PenaltyIndentedWhitespace = 0;
2033 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
2037 case FormatStyle::LK_TableGen:
2038 LLVMStyle.SpacesInContainerLiterals =
false;
2040 case FormatStyle::LK_Json:
2041 LLVMStyle.ColumnLimit = 0;
2043 case FormatStyle::LK_Verilog:
2044 LLVMStyle.IndentCaseLabels =
true;
2045 LLVMStyle.SpacesInContainerLiterals =
false;
2055 if (
Language == FormatStyle::LK_TextProto) {
2057 GoogleStyle.Language = FormatStyle::LK_TextProto;
2064 GoogleStyle.AccessModifierOffset = -1;
2065 GoogleStyle.AlignEscapedNewlines = FormatStyle::ENAS_Left;
2066 GoogleStyle.AllowShortIfStatementsOnASingleLine =
2067 FormatStyle::SIS_WithoutElse;
2068 GoogleStyle.AllowShortLoopsOnASingleLine =
true;
2069 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
true;
2071 GoogleStyle.AttributeMacros.push_back(
"absl_nonnull");
2072 GoogleStyle.AttributeMacros.push_back(
"absl_nullable");
2073 GoogleStyle.AttributeMacros.push_back(
"absl_nullability_unknown");
2074 GoogleStyle.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
2076 GoogleStyle.IncludeStyle.IncludeCategories = {{
"^<ext/.*\\.h>", 2, 0,
false},
2077 {
"^<.*\\.h>", 1, 0,
false},
2078 {
"^<.*", 2, 0,
false},
2079 {
".*", 3, 0,
false}};
2080 GoogleStyle.IncludeStyle.IncludeIsMainRegex =
"([-_](test|unittest))?$";
2081 GoogleStyle.IndentCaseLabels =
true;
2082 GoogleStyle.KeepEmptyLines.AtStartOfBlock =
false;
2083 GoogleStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
2084 GoogleStyle.ObjCSpaceAfterProperty =
false;
2085 GoogleStyle.ObjCSpaceBeforeProtocolList =
true;
2086 GoogleStyle.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
2087 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
2088 GoogleStyle.RawStringFormats = {
2090 FormatStyle::LK_Cpp,
2107 FormatStyle::LK_TextProto,
2119 "PARSE_PARTIAL_TEXT_PROTO",
2123 "ParseTextProtoOrDie",
2125 "ParsePartialTestProto",
2132 GoogleStyle.SpacesBeforeTrailingComments = 2;
2133 GoogleStyle.Standard = FormatStyle::LS_Auto;
2135 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
2136 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
2138 if (
Language == FormatStyle::LK_Java) {
2139 GoogleStyle.AlignAfterOpenBracket =
false;
2140 GoogleStyle.AlignOperands = FormatStyle::OAS_DontAlign;
2141 GoogleStyle.AlignTrailingComments = {};
2142 GoogleStyle.AlignTrailingComments.Kind = FormatStyle::TCAS_Never;
2143 GoogleStyle.AllowShortFunctionsOnASingleLine =
2144 FormatStyle::ShortFunctionStyle::setEmptyOnly();
2145 GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
2146 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
2147 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
2148 GoogleStyle.ColumnLimit = 100;
2149 GoogleStyle.SpaceAfterCStyleCast =
true;
2150 GoogleStyle.SpacesBeforeTrailingComments = 1;
2151 }
else if (
Language == FormatStyle::LK_JavaScript) {
2152 GoogleStyle.BreakAfterOpenBracketBracedList =
true;
2153 GoogleStyle.BreakAfterOpenBracketFunction =
true;
2154 GoogleStyle.BreakAfterOpenBracketIf =
true;
2155 GoogleStyle.AlignOperands = FormatStyle::OAS_DontAlign;
2156 GoogleStyle.AllowShortFunctionsOnASingleLine =
2157 FormatStyle::ShortFunctionStyle::setEmptyOnly();
2159 GoogleStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
2160 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
2161 GoogleStyle.BreakBeforeTernaryOperators =
false;
2164 GoogleStyle.CommentPragmas =
"(taze:|^/[ \t]*<|tslint:|@see)";
2168 GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single;
2169 GoogleStyle.JavaScriptWrapImports =
false;
2170 GoogleStyle.MaxEmptyLinesToKeep = 3;
2171 GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
2172 GoogleStyle.SpacesInContainerLiterals =
false;
2173 }
else if (
Language == FormatStyle::LK_Proto) {
2174 GoogleStyle.AllowShortFunctionsOnASingleLine =
2175 FormatStyle::ShortFunctionStyle::setEmptyOnly();
2176 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
2182 GoogleStyle.BreakStringLiterals =
false;
2183 GoogleStyle.Cpp11BracedListStyle = FormatStyle::BLS_Block;
2184 GoogleStyle.SpacesInContainerLiterals =
false;
2185 }
else if (
Language == FormatStyle::LK_ObjC) {
2186 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
2187 GoogleStyle.ColumnLimit = 100;
2188 GoogleStyle.DerivePointerAlignment =
true;
2192 GoogleStyle.IncludeStyle.IncludeBlocks =
2194 }
else if (
Language == FormatStyle::LK_CSharp) {
2195 GoogleStyle.AllowShortFunctionsOnASingleLine =
2196 FormatStyle::ShortFunctionStyle::setEmptyOnly();
2197 GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
2198 GoogleStyle.BreakStringLiterals =
false;
2199 GoogleStyle.ColumnLimit = 100;
2200 GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
2226 ChromiumStyle.IncludeStyle.IncludeBlocks =
2229 if (
Language == FormatStyle::LK_Java) {
2230 ChromiumStyle.AllowShortIfStatementsOnASingleLine =
2231 FormatStyle::SIS_WithoutElse;
2232 ChromiumStyle.BreakAfterJavaFieldAnnotations =
true;
2233 ChromiumStyle.ContinuationIndentWidth = 8;
2234 ChromiumStyle.IndentWidth = 4;
2237 ChromiumStyle.JavaImportGroups = {
2244 "com.google.android.apps.chrome",
2249 }
else if (
Language == FormatStyle::LK_JavaScript) {
2250 ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
2251 ChromiumStyle.AllowShortLoopsOnASingleLine =
false;
2253 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine =
false;
2254 ChromiumStyle.AllowShortFunctionsOnASingleLine =
2255 FormatStyle::ShortFunctionStyle::setEmptyAndInline();
2256 ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
2257 ChromiumStyle.AllowShortLoopsOnASingleLine =
false;
2258 ChromiumStyle.PackParameters.BinPack = FormatStyle::BPPS_OnePerLine;
2259 ChromiumStyle.DerivePointerAlignment =
false;
2260 if (
Language == FormatStyle::LK_ObjC)
2261 ChromiumStyle.ColumnLimit = 80;
2263 return ChromiumStyle;
2268 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine =
false;
2269 MozillaStyle.AllowShortFunctionsOnASingleLine =
2270 FormatStyle::ShortFunctionStyle::setEmptyAndInline();
2271 MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
2272 FormatStyle::DRTBS_TopLevel;
2273 MozillaStyle.PackArguments.BinPack = FormatStyle::BPAS_OnePerLine;
2274 MozillaStyle.PackParameters.BinPack = FormatStyle::BPPS_OnePerLine;
2275 MozillaStyle.BreakAfterReturnType = FormatStyle::RTBS_TopLevel;
2276 MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
2277 MozillaStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
2278 MozillaStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
2279 MozillaStyle.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
2280 MozillaStyle.ConstructorInitializerIndentWidth = 2;
2281 MozillaStyle.ContinuationIndentWidth = 2;
2282 MozillaStyle.Cpp11BracedListStyle = FormatStyle::BLS_Block;
2283 MozillaStyle.FixNamespaceComments =
false;
2284 MozillaStyle.IndentCaseLabels =
true;
2285 MozillaStyle.ObjCSpaceAfterProperty =
true;
2286 MozillaStyle.ObjCSpaceBeforeProtocolList =
false;
2287 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
2288 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
2289 MozillaStyle.SpaceAfterTemplateKeyword =
false;
2290 return MozillaStyle;
2295 Style.AccessModifierOffset = -4;
2296 Style.AlignAfterOpenBracket =
false;
2297 Style.AlignOperands = FormatStyle::OAS_DontAlign;
2298 Style.AlignTrailingComments = {};
2299 Style.AlignTrailingComments.Kind = FormatStyle::TCAS_Never;
2300 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
2301 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
2302 Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
2303 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
2304 Style.ColumnLimit = 0;
2305 Style.Cpp11BracedListStyle = FormatStyle::BLS_Block;
2306 Style.FixNamespaceComments =
false;
2307 Style.IndentWidth = 4;
2308 Style.NamespaceIndentation = FormatStyle::NI_Inner;
2309 Style.ObjCBlockIndentWidth = 4;
2310 Style.ObjCSpaceAfterProperty =
true;
2311 Style.PointerAlignment = FormatStyle::PAS_Left;
2312 Style.SpaceBeforeCpp11BracedList =
true;
2313 Style.SpaceInEmptyBraces = FormatStyle::SIEB_Always;
2319 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
2320 Style.BreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
2321 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
2322 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
2323 Style.BreakBeforeTernaryOperators =
true;
2324 Style.ColumnLimit = 79;
2325 Style.Cpp11BracedListStyle = FormatStyle::BLS_Block;
2326 Style.FixNamespaceComments =
false;
2327 Style.KeepFormFeed =
true;
2328 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
2334 Style.ColumnLimit = 120;
2336 Style.IndentWidth = 4;
2337 Style.UseTab = FormatStyle::UT_Never;
2338 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2339 Style.BraceWrapping.AfterClass =
true;
2340 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2341 Style.BraceWrapping.AfterEnum =
true;
2342 Style.BraceWrapping.AfterFunction =
true;
2343 Style.BraceWrapping.AfterNamespace =
true;
2344 Style.BraceWrapping.AfterObjCDeclaration =
true;
2345 Style.BraceWrapping.AfterStruct =
true;
2346 Style.BraceWrapping.AfterExternBlock =
true;
2347 Style.BraceWrapping.BeforeCatch =
true;
2348 Style.BraceWrapping.BeforeElse =
true;
2349 Style.BraceWrapping.BeforeWhile =
false;
2350 Style.PenaltyReturnTypeOnItsOwnLine = 1000;
2351 Style.AllowShortEnumsOnASingleLine =
false;
2352 Style.AllowShortFunctionsOnASingleLine = FormatStyle::ShortFunctionStyle();
2353 Style.AllowShortCaseLabelsOnASingleLine =
false;
2354 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
2355 Style.AllowShortLoopsOnASingleLine =
false;
2356 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
2357 Style.BreakAfterReturnType = FormatStyle::RTBS_None;
2363 Style.InsertBraces =
true;
2364 Style.InsertNewlineAtEOF =
true;
2365 Style.IntegerLiteralSeparator.Decimal = 3;
2366 Style.IntegerLiteralSeparator.DecimalMinDigitsInsert = 5;
2367 Style.LineEnding = FormatStyle::LE_LF;
2368 Style.RemoveBracesLLVM =
true;
2369 Style.RemoveEmptyLinesInUnwrappedLines =
true;
2370 Style.RemoveParentheses = FormatStyle::RPS_ReturnStatement;
2371 Style.RemoveSemicolon =
true;
2377 NoStyle.DisableFormat =
true;
2378 NoStyle.SortIncludes = {};
2379 NoStyle.SortUsingDeclarations = FormatStyle::SUD_Never;
2384 FormatStyle *Style) {
2385 constexpr StringRef Prefix(
"inheritparentconfig=");
2387 if (Name.equals_insensitive(
"llvm"))
2389 else if (Name.equals_insensitive(
"chromium"))
2391 else if (Name.equals_insensitive(
"mozilla"))
2393 else if (Name.equals_insensitive(
"google"))
2395 else if (Name.equals_insensitive(
"webkit"))
2397 else if (Name.equals_insensitive(
"gnu"))
2399 else if (Name.equals_insensitive(
"microsoft"))
2401 else if (Name.equals_insensitive(
"clang-format"))
2403 else if (Name.equals_insensitive(
"none"))
2405 else if (Name.equals_insensitive(Prefix.drop_back()))
2406 Style->InheritConfig =
"..";
2407 else if (Name.size() > Prefix.size() && Name.starts_with_insensitive(Prefix))
2408 Style->InheritConfig = Name.substr(Prefix.size());
2418 if (Style->QualifierOrder.empty())
2422 for (
const auto &Qualifier : Style->QualifierOrder) {
2423 if (Qualifier ==
"type")
2427 if (token == tok::identifier)
2432 std::set<std::string> UniqueQualifiers(Style->QualifierOrder.begin(),
2433 Style->QualifierOrder.end());
2434 if (Style->QualifierOrder.size() != UniqueQualifiers.size()) {
2435 LLVM_DEBUG(llvm::dbgs()
2436 <<
"Duplicate Qualifiers " << Style->QualifierOrder.size()
2437 <<
" vs " << UniqueQualifiers.size() <<
"\n");
2442 if (!llvm::is_contained(Style->QualifierOrder,
"type"))
2449 FormatStyle *Style,
bool AllowUnknownOptions,
2450 llvm::SourceMgr::DiagHandlerTy DiagHandler,
2451 void *DiagHandlerCtxt,
bool IsDotHFile) {
2453 FormatStyle::LanguageKind
Language = Style->Language;
2454 assert(
Language != FormatStyle::LK_None);
2455 if (Config.getBuffer().trim().empty())
2457 Style->StyleSet.Clear();
2458 std::vector<FormatStyle> Styles;
2459 llvm::yaml::Input Input(Config,
nullptr, DiagHandler,
2465 Input.setContext(Style);
2466 Input.setAllowUnknownKeys(AllowUnknownOptions);
2469 return Input.error();
2473 const auto StyleCount = Styles.size();
2476 for (
unsigned I = 1; I < StyleCount; ++I) {
2477 const auto Lang = Styles[I].Language;
2478 if (Lang == FormatStyle::LK_None)
2481 for (
unsigned J = 0; J < I; ++J) {
2483 LLVM_DEBUG(llvm::dbgs()
2484 <<
"Duplicate languages in the config file on positions "
2485 << J <<
" and " << I <<
'\n');
2491 int LanguagePos = -1;
2497 for (
unsigned I = 0; I < StyleCount; ++I) {
2498 const auto Lang = Styles[I].Language;
2503 if (Lang == FormatStyle::LK_Cpp)
2505 else if (Lang == FormatStyle::LK_C)
2512 if (LanguagePos < 0) {
2513 if (Styles[0].
Language == FormatStyle::LK_None)
2515 else if (IsDotHFile &&
Language == FormatStyle::LK_Cpp)
2517 else if (!IsDotHFile &&
Language == FormatStyle::LK_C)
2518 LanguagePos = CppPos;
2519 if (LanguagePos < 0)
2523 for (
const auto &S : llvm::reverse(llvm::drop_begin(Styles)))
2524 Style->StyleSet.Add(S);
2526 *Style = Styles[LanguagePos];
2528 if (LanguagePos == 0) {
2529 if (Style->Language == FormatStyle::LK_None)
2531 Style->StyleSet.Add(*Style);
2534 if (Style->InsertTrailingCommas != FormatStyle::TCS_None &&
2535 (Style->PackArguments.BinPack == FormatStyle::BPAS_BinPack ||
2536 Style->PackArguments.BinPack == FormatStyle::BPAS_UseBreakAfter)) {
2540 if (Style->QualifierAlignment != FormatStyle::QAS_Leave)
2547 llvm::raw_string_ostream Stream(
Text);
2548 llvm::yaml::Output Output(Stream);
2551 FormatStyle NonConstStyle = Style;
2555 Output << NonConstStyle;
2557 return Stream.str();
2560std::optional<FormatStyle>
2561FormatStyle::FormatStyleSet::Get(FormatStyle::LanguageKind
Language)
const {
2563 return std::nullopt;
2565 if (It == Styles->end())
2566 return std::nullopt;
2567 FormatStyle Style = It->second;
2568 Style.StyleSet = *
this;
2572void FormatStyle::FormatStyleSet::Add(FormatStyle Style) {
2573 assert(Style.Language !=
LK_None &&
2574 "Cannot add a style for LK_None to a StyleSet");
2576 !Style.StyleSet.Styles &&
2577 "Cannot add a style associated with an existing StyleSet to a StyleSet");
2579 Styles = std::make_shared<MapType>();
2580 (*Styles)[Style.Language] = std::move(Style);
2583void FormatStyle::FormatStyleSet::Clear() { Styles.reset(); }
2585std::optional<FormatStyle>
2586FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind
Language)
const {
2593 const SourceManager &SourceMgr, tooling::Replacements &
Result,
2594 StringRef
Text =
"") {
2595 const auto &
Tok = Token.Tok;
2596 SourceLocation Start;
2598 Start =
Tok.getLocation();
2601 Start = Token.WhitespaceRange.getBegin();
2604 cantFail(
Result.add(tooling::Replacement(SourceMgr, Range,
Text)));
2609 ParensRemover(
const Environment &Env,
const FormatStyle &Style)
2610 : TokenAnalyzer(Env, Style) {}
2612 std::pair<tooling::Replacements, unsigned>
2613 analyze(TokenAnnotator &Annotator,
2614 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2615 FormatTokenLexer &Tokens)
override {
2616 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2617 tooling::Replacements
Result;
2618 removeParens(AnnotatedLines,
Result);
2623 void removeParens(SmallVectorImpl<AnnotatedLine *> &Lines,
2624 tooling::Replacements &
Result) {
2625 const auto &SourceMgr = Env.getSourceManager();
2626 for (
auto *
Line : Lines) {
2627 if (!
Line->Children.empty())
2629 if (!
Line->Affected)
2631 for (
const auto *Token =
Line->First; Token && !Token->Finalized;
2632 Token = Token->Next) {
2633 if (Token->Optional && Token->isOneOf(tok::l_paren, tok::r_paren))
2642 BracesInserter(
const Environment &Env,
const FormatStyle &Style)
2643 : TokenAnalyzer(Env, Style) {}
2645 std::pair<tooling::Replacements, unsigned>
2646 analyze(TokenAnnotator &Annotator,
2647 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2648 FormatTokenLexer &Tokens)
override {
2649 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2650 tooling::Replacements
Result;
2651 insertBraces(AnnotatedLines,
Result);
2656 void insertBraces(SmallVectorImpl<AnnotatedLine *> &Lines,
2657 tooling::Replacements &
Result) {
2658 const auto &SourceMgr = Env.getSourceManager();
2659 int OpeningBraceSurplus = 0;
2660 for (AnnotatedLine *
Line : Lines) {
2661 if (!
Line->Children.empty())
2663 if (!
Line->Affected && OpeningBraceSurplus == 0)
2666 Token = Token->Next) {
2673 if (!
Line->Affected)
2675 Brace = Token->is(tok::comment) ?
"\n{" :
"{";
2676 ++OpeningBraceSurplus;
2678 if (OpeningBraceSurplus == 0)
2685 Token->BraceCount = 0;
2686 const auto Start = Token->Tok.getEndLoc();
2687 cantFail(
Result.add(tooling::Replacement(SourceMgr, Start, 0,
Brace)));
2690 assert(OpeningBraceSurplus == 0);
2696 BracesRemover(
const Environment &Env,
const FormatStyle &Style)
2697 : TokenAnalyzer(Env, Style) {}
2699 std::pair<tooling::Replacements, unsigned>
2700 analyze(TokenAnnotator &Annotator,
2701 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2702 FormatTokenLexer &Tokens)
override {
2703 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2704 tooling::Replacements
Result;
2705 removeBraces(AnnotatedLines,
Result);
2710 void removeBraces(SmallVectorImpl<AnnotatedLine *> &Lines,
2711 tooling::Replacements &
Result) {
2712 const auto &SourceMgr = Env.getSourceManager();
2713 const auto *End = Lines.end();
2714 for (
const auto *I = Lines.begin(); I != End; ++I) {
2715 const auto &
Line = *I;
2716 if (!
Line->Children.empty())
2718 if (!
Line->Affected)
2720 const auto *NextLine = I + 1 == End ?
nullptr : I[1];
2721 for (
const auto *Token =
Line->First; Token && !Token->Finalized;
2722 Token = Token->Next) {
2723 if (!Token->Optional || Token->isNoneOf(tok::l_brace, tok::r_brace))
2725 auto *
Next = Token->Next;
2726 assert(
Next || Token ==
Line->Last);
2727 if (!
Next && NextLine)
2728 Next = NextLine->First;
2737 SemiRemover(
const Environment &Env,
const FormatStyle &Style)
2738 : TokenAnalyzer(Env, Style) {}
2740 std::pair<tooling::Replacements, unsigned>
2741 analyze(TokenAnnotator &Annotator,
2742 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2743 FormatTokenLexer &Tokens)
override {
2744 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2745 tooling::Replacements
Result;
2746 removeSemi(Annotator, AnnotatedLines,
Result);
2751 void removeSemi(TokenAnnotator &Annotator,
2752 SmallVectorImpl<AnnotatedLine *> &Lines,
2753 tooling::Replacements &
Result) {
2755 const auto *Prev =
Tok.Previous;
2756 if (!Prev || Prev->isNot(tok::r_brace))
2758 const auto *LBrace = Prev->MatchingParen;
2759 return LBrace && LBrace->is(TT_FunctionLBrace);
2761 const auto &SourceMgr = Env.getSourceManager();
2762 const auto *End = Lines.end();
2763 for (
const auto *I = Lines.begin(); I != End; ++I) {
2764 const auto &
Line = *I;
2765 if (!
Line->Children.empty())
2766 removeSemi(Annotator,
Line->Children,
Result);
2767 if (!
Line->Affected)
2769 Annotator.calculateFormattingInformation(*
Line);
2770 const auto *NextLine = I + 1 == End ?
nullptr : I[1];
2771 for (
const auto *Token =
Line->First; Token && !Token->Finalized;
2772 Token = Token->Next) {
2773 if (Token->isNot(tok::semi) ||
2774 (!Token->Optional && !PrecededByFunctionRBrace(*Token))) {
2777 auto *
Next = Token->Next;
2778 assert(
Next || Token ==
Line->Last);
2779 if (!
Next && NextLine)
2780 Next = NextLine->First;
2789 EnumTrailingCommaEditor(
const Environment &Env,
const FormatStyle &Style)
2790 : TokenAnalyzer(Env, Style) {}
2792 std::pair<tooling::Replacements, unsigned>
2793 analyze(TokenAnnotator &Annotator,
2794 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2795 FormatTokenLexer &Tokens)
override {
2796 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2797 tooling::Replacements
Result;
2798 editEnumTrailingComma(AnnotatedLines,
Result);
2803 void editEnumTrailingComma(SmallVectorImpl<AnnotatedLine *> &Lines,
2804 tooling::Replacements &
Result) {
2805 bool InEnumBraces =
false;
2807 const auto &SourceMgr = Env.getSourceManager();
2808 for (
auto *
Line : Lines) {
2809 if (!
Line->Children.empty())
2810 editEnumTrailingComma(
Line->Children,
Result);
2811 for (
const auto *Token =
Line->First; Token && !Token->Finalized;
2812 Token = Token->Next) {
2813 if (Token->isNot(TT_EnumRBrace)) {
2814 if (Token->is(TT_EnumLBrace))
2815 InEnumBraces =
true;
2816 else if (InEnumBraces && Token->isNot(tok::comment))
2817 BeforeRBrace =
Line->Affected ? Token :
nullptr;
2820 InEnumBraces =
false;
2823 if (BeforeRBrace->is(tok::comma)) {
2824 if (Style.EnumTrailingComma == FormatStyle::ETC_Remove)
2826 }
else if (Style.EnumTrailingComma == FormatStyle::ETC_Insert) {
2827 cantFail(
Result.add(tooling::Replacement(
2828 SourceMgr, BeforeRBrace->Tok.getEndLoc(), 0,
",")));
2830 BeforeRBrace =
nullptr;
2838 JavaScriptRequoter(
const Environment &Env,
const FormatStyle &Style)
2839 : TokenAnalyzer(Env, Style) {}
2841 std::pair<tooling::Replacements, unsigned>
2842 analyze(TokenAnnotator &Annotator,
2843 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2844 FormatTokenLexer &Tokens)
override {
2845 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2846 tooling::Replacements
Result;
2847 requoteJSStringLiteral(AnnotatedLines,
Result);
2854 void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
2855 tooling::Replacements &
Result) {
2856 for (AnnotatedLine *
Line : Lines) {
2857 requoteJSStringLiteral(
Line->Children,
Result);
2858 if (!
Line->Affected)
2861 FormatTok = FormatTok->Next) {
2862 StringRef Input = FormatTok->TokenText;
2863 if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
2866 (Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
2867 !Input.starts_with(
"\"")) ||
2868 (Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
2869 !Input.starts_with(
"\'"))) {
2874 bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
2875 SourceLocation Start = FormatTok->Tok.getLocation();
2876 auto Replace = [&](SourceLocation Start,
unsigned Length,
2877 StringRef ReplacementText) {
2878 auto Err =
Result.add(tooling::Replacement(
2879 Env.getSourceManager(), Start, Length, ReplacementText));
2883 llvm::errs() <<
toString(std::move(Err)) <<
"\n";
2887 Replace(Start, 1, IsSingle ?
"'" :
"\"");
2888 Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
2889 IsSingle ?
"'" :
"\"");
2892 bool Escaped =
false;
2893 for (
size_t i = 1; i < Input.size() - 1; i++) {
2896 if (!Escaped && i + 1 < Input.size() &&
2897 ((IsSingle && Input[i + 1] ==
'"') ||
2898 (!IsSingle && Input[i + 1] ==
'\''))) {
2901 Replace(Start.getLocWithOffset(i), 1,
"");
2908 if (!Escaped && IsSingle == (Input[i] ==
'\'')) {
2910 Replace(Start.getLocWithOffset(i), 0,
"\\");
2926 Formatter(
const Environment &Env,
const FormatStyle &Style,
2927 FormattingAttemptStatus *Status)
2928 : TokenAnalyzer(Env, Style), Status(Status) {}
2930 std::pair<tooling::Replacements, unsigned>
2931 analyze(TokenAnnotator &Annotator,
2932 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2933 FormatTokenLexer &Tokens)
override {
2934 tooling::Replacements
Result;
2935 deriveLocalStyle(AnnotatedLines);
2936 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2937 for (AnnotatedLine *
Line : AnnotatedLines)
2938 Annotator.calculateFormattingInformation(*
Line);
2939 Annotator.setCommentLineLevels(AnnotatedLines);
2941 WhitespaceManager Whitespaces(
2942 Env.getSourceManager(), Style,
2943 Style.LineEnding > FormatStyle::LE_CRLF
2945 Env.getSourceManager().getBufferData(Env.getFileID()),
2946 Style.LineEnding == FormatStyle::LE_DeriveCRLF)
2947 : Style.LineEnding == FormatStyle::LE_CRLF);
2948 ContinuationIndenter Indenter(Style, Tokens.getKeywords(),
2949 Env.getSourceManager(), Whitespaces, Encoding,
2950 BinPackInconclusiveFunctions);
2952 UnwrappedLineFormatter(&Indenter, &Whitespaces, Style,
2953 Tokens.getKeywords(), Env.getSourceManager(),
2955 .format(AnnotatedLines,
false,
2958 Env.getFirstStartColumn(),
2959 Env.getNextStartColumn(),
2960 Env.getLastStartColumn());
2961 for (
const auto &R : Whitespaces.generateReplacements())
2963 return std::make_pair(
Result, 0);
2964 return std::make_pair(
Result, Penalty);
2969 hasCpp03IncompatibleFormat(
const SmallVectorImpl<AnnotatedLine *> &Lines) {
2970 for (
const AnnotatedLine *
Line : Lines) {
2971 if (hasCpp03IncompatibleFormat(
Line->Children))
2974 if (!
Tok->hasWhitespaceBefore()) {
2975 if (
Tok->is(tok::coloncolon) &&
Tok->Previous->is(TT_TemplateOpener))
2977 if (
Tok->is(TT_TemplateCloser) &&
2978 Tok->Previous->is(TT_TemplateCloser)) {
2987 int countVariableAlignments(
const SmallVectorImpl<AnnotatedLine *> &Lines) {
2988 int AlignmentDiff = 0;
2990 for (
const AnnotatedLine *
Line : Lines) {
2991 AlignmentDiff += countVariableAlignments(
Line->Children);
2994 if (
Tok->isNot(TT_PointerOrReference))
2997 const auto *Prev =
Tok->Previous;
2998 const bool PrecededByName = Prev && Prev->Tok.getIdentifierInfo();
2999 const bool SpaceBefore =
Tok->hasWhitespaceBefore();
3002 while (
Tok->Next &&
Tok->Next->is(TT_PointerOrReference))
3006 const bool FollowedByName =
Next &&
Next->Tok.getIdentifierInfo();
3007 const bool SpaceAfter =
Next &&
Next->hasWhitespaceBefore();
3009 if ((!PrecededByName && !FollowedByName) ||
3011 (PrecededByName && FollowedByName && SpaceBefore == SpaceAfter)) {
3015 if ((PrecededByName && SpaceBefore) ||
3016 (FollowedByName && !SpaceAfter)) {
3019 }
else if ((PrecededByName && !SpaceBefore) ||
3020 (FollowedByName && SpaceAfter)) {
3027 return AlignmentDiff;
3031 deriveLocalStyle(
const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
3032 bool HasBinPackedFunction =
false;
3033 bool HasOnePerLineFunction =
false;
3034 for (AnnotatedLine *
Line : AnnotatedLines) {
3035 if (!
Line->First->Next)
3040 HasBinPackedFunction =
true;
3042 HasOnePerLineFunction =
true;
3047 if (Style.DerivePointerAlignment) {
3048 const auto NetRightCount = countVariableAlignments(AnnotatedLines);
3049 if (NetRightCount > 0)
3050 Style.PointerAlignment = FormatStyle::PAS_Right;
3051 else if (NetRightCount < 0)
3052 Style.PointerAlignment = FormatStyle::PAS_Left;
3053 Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
3055 if (Style.Standard == FormatStyle::LS_Auto) {
3056 Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
3057 ? FormatStyle::LS_Latest
3058 : FormatStyle::LS_Cpp03;
3060 BinPackInconclusiveFunctions =
3061 HasBinPackedFunction || !HasOnePerLineFunction;
3064 bool BinPackInconclusiveFunctions;
3065 FormattingAttemptStatus *Status;
3081 TrailingCommaInserter(
const Environment &Env,
const FormatStyle &Style)
3082 : TokenAnalyzer(Env, Style) {}
3084 std::pair<tooling::Replacements, unsigned>
3085 analyze(TokenAnnotator &Annotator,
3086 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3087 FormatTokenLexer &Tokens)
override {
3088 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
3089 tooling::Replacements
Result;
3090 insertTrailingCommas(AnnotatedLines,
Result);
3097 void insertTrailingCommas(SmallVectorImpl<AnnotatedLine *> &Lines,
3098 tooling::Replacements &
Result) {
3099 for (AnnotatedLine *
Line : Lines) {
3100 insertTrailingCommas(
Line->Children,
Result);
3101 if (!
Line->Affected)
3104 FormatTok = FormatTok->Next) {
3105 if (FormatTok->NewlinesBefore == 0)
3108 if (!Matching || !FormatTok->getPreviousNonComment())
3110 if (!(FormatTok->is(tok::r_square) &&
3111 Matching->is(TT_ArrayInitializerLSquare)) &&
3112 !(FormatTok->is(tok::r_brace) && Matching->is(TT_DictLiteral))) {
3115 FormatToken *Prev = FormatTok->getPreviousNonComment();
3116 if (Prev->is(tok::comma) || Prev->is(tok::semi))
3120 SourceLocation Start =
3121 Prev->Tok.getLocation().getLocWithOffset(Prev->TokenText.size());
3125 unsigned ColumnNumber =
3126 Env.getSourceManager().getSpellingColumnNumber(Start);
3127 if (ColumnNumber > Style.ColumnLimit)
3132 tooling::Replacement(Env.getSourceManager(), Start, 0,
",")));
3142 Cleaner(
const Environment &Env,
const FormatStyle &Style)
3143 : TokenAnalyzer(Env, Style),
3144 DeletedTokens(FormatTokenLess(Env.getSourceManager())) {}
3147 std::pair<tooling::Replacements, unsigned>
3148 analyze(TokenAnnotator &Annotator,
3149 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3150 FormatTokenLexer &Tokens)
override {
3158 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
3160 checkEmptyNamespace(AnnotatedLines);
3162 for (
auto *
Line : AnnotatedLines)
3165 return {generateFixes(), 0};
3169 void cleanupLine(AnnotatedLine *
Line) {
3170 for (
auto *Child :
Line->Children)
3173 if (
Line->Affected) {
3174 cleanupRight(
Line->First, tok::comma, tok::comma);
3175 cleanupRight(
Line->First, TT_CtorInitializerColon, tok::comma);
3176 cleanupRight(
Line->First, tok::l_paren, tok::comma);
3177 cleanupLeft(
Line->First, tok::comma, tok::r_paren);
3178 cleanupLeft(
Line->First, TT_CtorInitializerComma, tok::l_brace);
3179 cleanupLeft(
Line->First, TT_CtorInitializerColon, tok::l_brace);
3180 cleanupLeft(
Line->First, TT_CtorInitializerColon, tok::equal);
3184 bool containsOnlyComments(
const AnnotatedLine &
Line) {
3186 if (
Tok->isNot(tok::comment))
3192 void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
3193 std::set<unsigned> DeletedLines;
3194 for (
unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
3195 auto &
Line = *AnnotatedLines[i];
3196 if (
Line.startsWithNamespace())
3197 checkEmptyNamespace(AnnotatedLines, i, i, DeletedLines);
3200 for (
auto Line : DeletedLines) {
3213 bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3214 unsigned CurrentLine,
unsigned &NewLine,
3215 std::set<unsigned> &DeletedLines) {
3216 unsigned InitLine = CurrentLine, End = AnnotatedLines.size();
3217 if (Style.BraceWrapping.AfterNamespace) {
3221 if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
3222 NewLine = CurrentLine;
3225 }
else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
3228 while (++CurrentLine < End) {
3229 if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
3232 if (AnnotatedLines[CurrentLine]->startsWithNamespace()) {
3233 if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine,
3237 CurrentLine = NewLine;
3241 if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
3246 NewLine = CurrentLine;
3250 NewLine = CurrentLine;
3251 if (CurrentLine >= End)
3256 AnnotatedLines[InitLine]->First->Tok.getLocation(),
3257 AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc()))) {
3261 for (
unsigned i = InitLine; i <= CurrentLine; ++i)
3262 DeletedLines.insert(i);
3271 template <
typename LeftKind,
typename RightKind>
3272 void cleanupPair(
FormatToken *Start, LeftKind LK, RightKind RK,
3275 for (
auto *Res =
Tok.Next; Res; Res = Res->Next) {
3276 if (Res->isNot(tok::comment) &&
3277 DeletedTokens.find(Res) == DeletedTokens.end()) {
3283 for (
auto *Left = Start;
Left;) {
3284 auto *
Right = NextNotDeleted(*Left);
3288 deleteToken(DeleteLeft ? Left : Right);
3300 template <
typename LeftKind,
typename RightKind>
3301 void cleanupLeft(
FormatToken *Start, LeftKind LK, RightKind RK) {
3302 cleanupPair(Start, LK, RK,
true);
3305 template <
typename LeftKind,
typename RightKind>
3306 void cleanupRight(
FormatToken *Start, LeftKind LK, RightKind RK) {
3307 cleanupPair(Start, LK, RK,
false);
3313 DeletedTokens.insert(
Tok);
3316 tooling::Replacements generateFixes() {
3317 tooling::Replacements Fixes;
3318 SmallVector<FormatToken *> Tokens;
3319 std::copy(DeletedTokens.begin(), DeletedTokens.end(),
3320 std::back_inserter(Tokens));
3326 while (Idx < Tokens.size()) {
3327 unsigned St = Idx, End = Idx;
3328 while ((End + 1) < Tokens.size() && Tokens[End]->Next == Tokens[End + 1])
3331 Tokens[End]->Tok.getEndLoc());
3333 Fixes.add(tooling::Replacement(Env.getSourceManager(), SR,
""));
3337 llvm::errs() <<
toString(std::move(Err)) <<
"\n";
3338 assert(
false &&
"Fixes must not conflict!");
3349 struct FormatTokenLess {
3350 FormatTokenLess(
const SourceManager &SM) : SM(SM) {}
3353 return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(),
3354 RHS->Tok.getLocation());
3356 const SourceManager &SM;
3360 std::set<FormatToken *, FormatTokenLess> DeletedTokens;
3365 ObjCHeaderStyleGuesser(
const Environment &Env,
const FormatStyle &Style)
3366 : TokenAnalyzer(Env, Style), IsObjC(
false) {}
3368 std::pair<tooling::Replacements, unsigned>
3369 analyze(TokenAnnotator &Annotator,
3370 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3371 FormatTokenLexer &Tokens)
override {
3372 assert(Style.Language == FormatStyle::LK_Cpp);
3373 IsObjC = guessIsObjC(Env.getSourceManager(), AnnotatedLines,
3374 Tokens.getKeywords());
3375 tooling::Replacements
Result;
3379 bool isObjC() {
return IsObjC; }
3383 guessIsObjC(
const SourceManager &SourceManager,
3384 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3385 const AdditionalKeywords &Keywords) {
3387 static constexpr llvm::StringLiteral FoundationIdentifiers[] = {
3402 "FOUNDATION_EXPORT",
3403 "FOUNDATION_EXTERN",
3404 "NSAffineTransform",
3406 "NSAttributedString",
3425 "NSInvocationOperation",
3429 "NSMutableAttributedString",
3430 "NSMutableCharacterSet",
3432 "NSMutableDictionary",
3433 "NSMutableIndexSet",
3434 "NSMutableOrderedSet",
3438 "NSNumberFormatter",
3442 "NSOperationQueuePriority",
3446 "NSQualityOfService",
3449 "NSRegularExpression",
3460 "NS_ASSUME_NONNULL_BEGIN",
3464 assert(llvm::is_sorted(FoundationIdentifiers));
3466 for (
auto *
Line : AnnotatedLines) {
3467 if (
Line->First && (
Line->First->TokenText.starts_with(
"#") ||
3468 Line->First->TokenText ==
"__pragma" ||
3469 Line->First->TokenText ==
"_Pragma")) {
3473 FormatTok = FormatTok->Next) {
3474 if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) &&
3475 (FormatTok->isNot(tok::objc_not_keyword) ||
3476 FormatTok->isOneOf(tok::numeric_constant, tok::l_square,
3478 (FormatTok->Tok.isAnyIdentifier() &&
3479 llvm::binary_search(FoundationIdentifiers,
3480 FormatTok->TokenText)) ||
3481 FormatTok->is(TT_ObjCStringLiteral) ||
3482 FormatTok->isOneOf(Keywords.kw_NS_CLOSED_ENUM, Keywords.kw_NS_ENUM,
3483 Keywords.kw_NS_ERROR_ENUM,
3484 Keywords.kw_NS_OPTIONS, TT_ObjCBlockLBrace,
3485 TT_ObjCBlockLParen, TT_ObjCDecl, TT_ObjCForIn,
3486 TT_ObjCMethodExpr, TT_ObjCMethodSpecifier,
3487 TT_ObjCProperty, TT_ObjCSelector)) {
3488 LLVM_DEBUG(llvm::dbgs()
3489 <<
"Detected ObjC at location "
3490 << FormatTok->Tok.getLocation().printToString(
3492 <<
" token: " << FormatTok->TokenText <<
" token type: "
3497 if (guessIsObjC(SourceManager,
Line->Children, Keywords))
3506struct IncludeDirective {
3514struct JavaImportDirective {
3515 StringRef Identifier;
3518 SmallVector<StringRef> AssociatedCommentLines;
3527 for (
const auto &Range : Ranges) {
3528 if (Range.getOffset() < End &&
3529 Range.getOffset() + Range.getLength() > Start) {
3544static std::pair<unsigned, unsigned>
3547 unsigned CursorIndex = std::numeric_limits<unsigned>::max();
3548 unsigned OffsetToEOL = 0;
3549 for (
int i = 0, e = Includes.size(); i != e; ++i) {
3550 unsigned Start = Includes[Indices[i]].Offset;
3551 unsigned End = Start + Includes[Indices[i]].Text.size();
3552 if (!(Cursor >= Start && Cursor < End))
3554 CursorIndex = Indices[i];
3555 OffsetToEOL = End - Cursor;
3558 while (--i >= 0 && Includes[CursorIndex].
Text == Includes[Indices[i]].
Text)
3562 return std::make_pair(CursorIndex, OffsetToEOL);
3567 std::string NewCode;
3568 size_t Pos = 0, LastPos = 0;
3571 Pos = Code.find(
"\r\n", LastPos);
3572 if (Pos == LastPos) {
3576 if (Pos == std::string::npos) {
3577 NewCode += Code.substr(LastPos);
3580 NewCode += Code.substr(LastPos, Pos - LastPos) +
"\n";
3582 }
while (Pos != std::string::npos);
3600 const unsigned IncludesBeginOffset = Includes.front().Offset;
3601 const unsigned IncludesEndOffset =
3602 Includes.back().Offset + Includes.back().Text.size();
3603 const unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset;
3604 if (!
affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset))
3607 llvm::to_vector<16>(llvm::seq<unsigned>(0, Includes.size()));
3609 if (Style.SortIncludes.Enabled) {
3610 stable_sort(Indices, [&](
unsigned LHSI,
unsigned RHSI) {
3612 if (Style.SortIncludes.IgnoreExtension) {
3613 LHSStem = Includes[LHSI].Filename;
3614 RHSStem = Includes[RHSI].Filename;
3615 llvm::sys::path::replace_extension(LHSStem,
"");
3616 llvm::sys::path::replace_extension(RHSStem,
"");
3618 std::string LHSStemLower, RHSStemLower;
3619 std::string LHSFilenameLower, RHSFilenameLower;
3620 if (Style.SortIncludes.IgnoreCase) {
3621 LHSStemLower = LHSStem.str().lower();
3622 RHSStemLower = RHSStem.str().lower();
3623 LHSFilenameLower = Includes[LHSI].Filename.lower();
3624 RHSFilenameLower = Includes[RHSI].Filename.lower();
3626 return std::tie(Includes[LHSI].Priority, LHSStemLower, LHSStem,
3627 LHSFilenameLower, Includes[LHSI].Filename) <
3628 std::tie(Includes[RHSI].Priority, RHSStemLower, RHSStem,
3629 RHSFilenameLower, Includes[RHSI].Filename);
3635 unsigned CursorIndex;
3637 unsigned CursorToEOLOffset;
3639 std::tie(CursorIndex, CursorToEOLOffset) =
3644 Indices.erase(llvm::unique(Indices,
3645 [&](
unsigned LHSI,
unsigned RHSI) {
3646 return Includes[LHSI].Text.trim() ==
3647 Includes[RHSI].Text.trim();
3651 int CurrentCategory = Includes.front().Category;
3659 if (Indices.size() == Includes.size() && is_sorted(Indices) &&
3664 const auto OldCursor = Cursor ? *Cursor : 0;
3666 for (
unsigned Index : Indices) {
3667 if (!result.empty()) {
3669 if (Style.IncludeStyle.IncludeBlocks ==
3671 CurrentCategory != Includes[Index].Category) {
3675 result += Includes[Index].Text;
3676 if (Cursor && CursorIndex == Index)
3677 *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
3678 CurrentCategory = Includes[Index].Category;
3681 if (Cursor && *Cursor >= IncludesEndOffset)
3682 *Cursor += result.size() - IncludesBlockSize;
3687 IncludesBeginOffset, IncludesBlockSize)))) {
3689 *Cursor = OldCursor;
3694 FileName, Includes.front().Offset, IncludesBlockSize, result));
3698 llvm::errs() <<
toString(std::move(Err)) <<
"\n";
3708 unsigned Prev = llvm::StringSwitch<size_t>(Code)
3709 .StartsWith(
"\xEF\xBB\xBF", 3)
3711 unsigned SearchFrom = 0;
3723 bool FirstIncludeBlock =
true;
3724 bool MainIncludeFound =
false;
3725 bool FormattingOff =
false;
3728 llvm::Regex RawStringRegex(
3729 "R\"([][A-Za-z0-9_{}#<>%:;.?*+/^&\\$|~!=,'-]*)\\(");
3731 std::string RawStringTermination =
")\"";
3733 for (
const auto Size = Code.size(); SearchFrom < Size;) {
3734 size_t Pos = SearchFrom;
3735 if (Code[SearchFrom] !=
'\n') {
3738 Pos = Code.find(
'\n', Pos);
3739 }
while (Pos != StringRef::npos && Code[Pos - 1] ==
'\\');
3743 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
3745 StringRef Trimmed =
Line.trim();
3750 if (RawStringRegex.match(Trimmed, &RawStringMatches)) {
3751 std::string CharSequence = RawStringMatches[1].str();
3752 RawStringTermination =
")" + CharSequence +
"\"";
3753 FormattingOff =
true;
3756 if (Trimmed.contains(RawStringTermination))
3757 FormattingOff =
false;
3759 bool IsBlockComment =
false;
3762 FormattingOff =
true;
3764 FormattingOff =
false;
3765 }
else if (Trimmed.starts_with(
"/*")) {
3766 IsBlockComment =
true;
3767 Pos = Code.find(
"*/", SearchFrom + 2);
3770 const bool EmptyLineSkipped =
3773 Style.IncludeStyle.IncludeBlocks ==
3776 bool MergeWithNextLine = Trimmed.ends_with(
"\\");
3777 if (!FormattingOff && !MergeWithNextLine) {
3778 if (!IsBlockComment &&
3780 StringRef IncludeName = Matches[2];
3781 if (Trimmed.contains(
"/*") && !Trimmed.contains(
"*/")) {
3786 Pos = Code.find(
"*/", SearchFrom);
3788 Prev, (Pos != StringRef::npos ? Pos + 2 : Code.size()) - Prev);
3792 !MainIncludeFound && FirstIncludeBlock);
3794 IncludeName, !MainIncludeFound && FirstIncludeBlock);
3796 MainIncludeFound =
true;
3797 IncludesInBlock.push_back(
3798 {IncludeName,
Line, Prev, Category, Priority});
3799 }
else if (!IncludesInBlock.empty() && !EmptyLineSkipped) {
3802 IncludesInBlock.clear();
3803 if (Trimmed.starts_with(
"#pragma hdrstop"))
3804 FirstIncludeBlock =
true;
3806 FirstIncludeBlock =
false;
3809 if (Pos == StringRef::npos || Pos + 1 == Code.size())
3812 if (!MergeWithNextLine)
3814 SearchFrom = Pos + 1;
3816 if (!IncludesInBlock.empty()) {
3827 StringRef ImportIdentifier) {
3828 unsigned LongestMatchIndex = std::numeric_limits<unsigned>::max();
3829 unsigned LongestMatchLength = 0;
3830 for (
unsigned I = 0; I < Style.JavaImportGroups.size(); I++) {
3831 const std::string &GroupPrefix = Style.JavaImportGroups[I];
3832 if (ImportIdentifier.starts_with(GroupPrefix) &&
3833 GroupPrefix.length() > LongestMatchLength) {
3834 LongestMatchIndex = I;
3835 LongestMatchLength = GroupPrefix.length();
3838 return LongestMatchIndex;
3850 unsigned ImportsBeginOffset = Imports.front().Offset;
3851 unsigned ImportsEndOffset =
3852 Imports.back().Offset + Imports.back().Text.size();
3853 unsigned ImportsBlockSize = ImportsEndOffset - ImportsBeginOffset;
3854 if (!
affectsRange(Ranges, ImportsBeginOffset, ImportsEndOffset))
3858 llvm::to_vector<16>(llvm::seq<unsigned>(0, Imports.size()));
3861 for (
const JavaImportDirective &Import : Imports)
3864 bool StaticImportAfterNormalImport =
3865 Style.SortJavaStaticImport == FormatStyle::SJSIO_After;
3866 sort(Indices, [&](
unsigned LHSI,
unsigned RHSI) {
3868 return std::make_tuple(!Imports[LHSI].IsStatic ^
3869 StaticImportAfterNormalImport,
3871 std::make_tuple(!Imports[RHSI].IsStatic ^
3872 StaticImportAfterNormalImport,
3877 Indices.erase(llvm::unique(Indices,
3878 [&](
unsigned LHSI,
unsigned RHSI) {
3879 return Imports[LHSI].Text == Imports[RHSI].Text;
3883 bool CurrentIsStatic = Imports[Indices.front()].IsStatic;
3887 for (
unsigned Index : Indices) {
3888 if (!result.empty()) {
3890 if (CurrentIsStatic != Imports[Index].IsStatic ||
3895 for (StringRef CommentLine : Imports[Index].AssociatedCommentLines) {
3896 result += CommentLine;
3899 result += Imports[Index].Text;
3900 CurrentIsStatic = Imports[Index].IsStatic;
3907 Imports.front().Offset, ImportsBlockSize)))) {
3912 ImportsBlockSize, result));
3916 llvm::errs() <<
toString(std::move(Err)) <<
"\n";
3924 JavaImportRegexPattern(
"^import[\t ]+(static[\t ]*)?([^\t ]*)[\t ]*;");
3926constexpr StringRef JavaPackageRegexPattern(
"^package[\t ]");
3935 bool HasImport =
false;
3936 llvm::Regex ImportRegex(JavaImportRegexPattern);
3937 llvm::Regex PackageRegex(JavaPackageRegexPattern);
3942 for (
bool FormattingOff =
false;;) {
3943 auto Pos = Code.find(
'\n', Prev);
3944 auto GetLine = [&] {
3945 return Code.substr(Prev,
3946 (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
3948 StringRef
Line = GetLine();
3950 StringRef Trimmed =
Line.trim();
3951 if (Trimmed.empty() || PackageRegex.match(Trimmed)) {
3954 FormattingOff =
true;
3956 FormattingOff =
false;
3957 }
else if (Trimmed.starts_with(
"//")) {
3960 AssociatedCommentLines.push_back(
Line);
3961 }
else if (Trimmed.starts_with(
"/*")) {
3962 Pos = Code.find(
"*/", Pos + 2);
3963 if (Pos != StringRef::npos)
3964 Pos = Code.find(
'\n', Pos + 2);
3969 AssociatedCommentLines.push_back(
Line);
3971 }
else if (ImportRegex.match(Trimmed, &Matches)) {
3972 if (FormattingOff) {
3977 StringRef
Static = Matches[1];
3978 StringRef Identifier = Matches[2];
3979 bool IsStatic =
false;
3980 if (
Static.contains(
"static"))
3982 ImportsInBlock.push_back(
3983 {Identifier,
Line, Prev, AssociatedCommentLines, IsStatic});
3985 AssociatedCommentLines.clear();
3991 if (Pos == StringRef::npos || Pos + 1 == Code.size())
4004 return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
4007bool isLikelyXml(StringRef Code) {
return Code.ltrim().starts_with(
"<"); }
4011 StringRef
FileName,
unsigned *Cursor) {
4013 if (!Style.SortIncludes.Enabled || Style.DisableFormat)
4017 if (Style.isJavaScript()) {
4029template <
typename T>
4033 const FormatStyle &Style) {
4034 if (Replaces.
empty())
4037 auto NewCode = applyAllReplacements(Code, Replaces);
4039 return NewCode.takeError();
4044 ProcessFunc(Style, *NewCode, ChangedRanges,
FileName);
4046 return Replaces.
merge(FormatReplaces);
4051 const FormatStyle &Style) {
4054 auto SortIncludes = [](
const FormatStyle &Style, StringRef Code,
4055 std::vector<tooling::Range> Ranges,
4059 auto SortedReplaces =
4061 if (!SortedReplaces)
4062 return SortedReplaces.takeError();
4066 auto Reformat = [](
const FormatStyle &Style, StringRef Code,
4067 std::vector<tooling::Range> Ranges,
4077 return Replace.
getOffset() == std::numeric_limits<unsigned>::max() &&
4083inline bool isHeaderDeletion(
const tooling::Replacement &Replace) {
4084 return Replace.getOffset() == std::numeric_limits<unsigned>::max() &&
4085 Replace.getLength() == 1;
4089tooling::Replacements
4090fixCppIncludeInsertions(StringRef Code,
const tooling::Replacements &Replaces,
4091 const FormatStyle &Style) {
4095 tooling::Replacements HeaderInsertions;
4096 std::set<StringRef> HeadersToDelete;
4097 tooling::Replacements
Result;
4098 for (
const auto &R : Replaces) {
4099 if (isHeaderInsertion(R)) {
4102 consumeError(HeaderInsertions.add(R));
4103 }
else if (isHeaderDeletion(R)) {
4104 HeadersToDelete.insert(
R.getReplacementText());
4105 }
else if (
R.getOffset() == std::numeric_limits<unsigned>::max()) {
4106 llvm::errs() <<
"Insertions other than header #include insertion are "
4108 <<
R.getReplacementText() <<
"\n";
4110 consumeError(
Result.add(R));
4113 if (HeaderInsertions.empty() && HeadersToDelete.empty())
4116 StringRef
FileName = Replaces.begin()->getFilePath();
4117 tooling::HeaderIncludes Includes(
FileName, Code, Style.IncludeStyle);
4119 for (
const auto &Header : HeadersToDelete) {
4120 tooling::Replacements Replaces =
4121 Includes.remove(Header.trim(
"\"<>"), Header.starts_with(
"<"));
4122 for (
const auto &R : Replaces) {
4123 auto Err =
Result.add(R);
4126 llvm::errs() <<
"Failed to add header deletion replacement for "
4127 << Header <<
": " <<
toString(std::move(Err)) <<
"\n";
4133 for (
const auto &R : HeaderInsertions) {
4134 auto IncludeDirective =
R.getReplacementText();
4137 assert(Matched &&
"Header insertion replacement must have replacement text "
4140 auto IncludeName = Matches[2];
4142 Includes.insert(IncludeName.trim(
"\"<>"), IncludeName.starts_with(
"<"),
4145 auto Err =
Result.add(*Replace);
4147 consumeError(std::move(Err));
4148 unsigned NewOffset =
4149 Result.getShiftedCodePosition(Replace->getOffset());
4150 auto Shifted = tooling::Replacement(
FileName, NewOffset, 0,
4151 Replace->getReplacementText());
4163 const FormatStyle &Style) {
4166 auto Cleanup = [](
const FormatStyle &Style, StringRef Code,
4173 fixCppIncludeInsertions(Code, Replaces, Style);
4178std::pair<tooling::Replacements, unsigned>
4181 unsigned NextStartColumn,
unsigned LastStartColumn, StringRef
FileName,
4183 FormatStyle Expanded = Style;
4189 Expanded.InsertBraces =
false;
4190 Expanded.RemoveBracesLLVM =
false;
4191 Expanded.RemoveParentheses = FormatStyle::RPS_Leave;
4192 Expanded.RemoveSemicolon =
false;
4195 switch (Expanded.RequiresClausePosition) {
4196 case FormatStyle::RCPS_SingleLine:
4197 case FormatStyle::RCPS_WithPreceding:
4198 Expanded.IndentRequiresClause =
false;
4203 if (Expanded.BraceWrapping.AfterEnum)
4204 Expanded.AllowShortEnumsOnASingleLine =
false;
4206 if (Expanded.DisableFormat)
4210 if (Expanded.isJavaScript() &&
isMpegTS(Code))
4214 if (Style.isJson()) {
4215 std::vector<tooling::Range> Ranges(1,
tooling::Range(0, Code.size()));
4217 NextStartColumn, LastStartColumn);
4222 Formatter(*Env, Style, Status).process().first;
4224 if (Code.starts_with(
"x = ")) {
4225 Replaces = Replaces.
merge(
4229 if (applyAllReplacements(Code, Replaces))
4230 return {Replaces, 0};
4235 NextStartColumn, LastStartColumn);
4253 if (Style.isCpp()) {
4254 if (Style.QualifierAlignment != FormatStyle::QAS_Leave)
4257 if (Style.RemoveParentheses != FormatStyle::RPS_Leave) {
4258 FormatStyle S = Expanded;
4259 S.RemoveParentheses = Style.RemoveParentheses;
4260 Passes.emplace_back([&, S = std::move(S)](
const Environment &Env) {
4261 return ParensRemover(Env, S).process(
true);
4265 if (Style.InsertBraces) {
4266 FormatStyle S = Expanded;
4267 S.InsertBraces =
true;
4268 Passes.emplace_back([&, S = std::move(S)](
const Environment &Env) {
4269 return BracesInserter(Env, S).process(
true);
4273 if (Style.RemoveBracesLLVM) {
4274 FormatStyle S = Expanded;
4275 S.RemoveBracesLLVM =
true;
4276 Passes.emplace_back([&, S = std::move(S)](
const Environment &Env) {
4277 return BracesRemover(Env, S).process(
true);
4281 if (Style.RemoveSemicolon) {
4282 FormatStyle S = Expanded;
4283 S.RemoveSemicolon =
true;
4284 Passes.emplace_back([&, S = std::move(S)](
const Environment &Env) {
4285 return SemiRemover(Env, S).process();
4289 if (Style.EnumTrailingComma != FormatStyle::ETC_Leave) {
4291 return EnumTrailingCommaEditor(Env, Expanded)
4296 if (Style.FixNamespaceComments) {
4302 if (Style.SortUsingDeclarations != FormatStyle::SUD_Never) {
4309 if (Style.SeparateDefinitionBlocks != FormatStyle::SDS_Leave) {
4315 if (Style.Language == FormatStyle::LK_ObjC &&
4316 !Style.ObjCPropertyAttributeOrder.empty()) {
4322 if (Style.isJavaScript() &&
4323 Style.JavaScriptQuotes != FormatStyle::JSQS_Leave) {
4325 return JavaScriptRequoter(Env, Expanded).process(
true);
4330 return Formatter(Env, Expanded, Status).process();
4333 if (Style.isJavaScript() &&
4334 Style.InsertTrailingCommas == FormatStyle::TCS_Wrapped) {
4336 return TrailingCommaInserter(Env, Expanded).process();
4340 std::optional<std::string> CurrentCode;
4342 unsigned Penalty = 0;
4343 for (
size_t I = 0, E = Passes.size(); I < E; ++I) {
4344 std::pair<tooling::Replacements, unsigned> PassFixes = Passes[I](*Env);
4345 auto NewCode = applyAllReplacements(
4346 CurrentCode ? StringRef(*CurrentCode) : Code, PassFixes.first);
4348 Fixes = Fixes.
merge(PassFixes.first);
4349 Penalty += PassFixes.second;
4351 CurrentCode = std::move(*NewCode);
4355 FirstStartColumn, NextStartColumn, LastStartColumn);
4362 if (Style.QualifierAlignment != FormatStyle::QAS_Leave) {
4368 StringRef OriginalCode = Code.substr(Fix.getOffset(), Fix.getLength());
4369 if (OriginalCode != Fix.getReplacementText()) {
4370 auto Err = NonNoOpFixes.
add(Fix);
4372 llvm::errs() <<
"Error adding replacements : "
4373 <<
toString(std::move(Err)) <<
"\n";
4377 Fixes = std::move(NonNoOpFixes);
4380 return {Fixes, Penalty};
4399 if (Style.Language != FormatStyle::LK_Cpp)
4404 return Cleaner(*Env, Style).process().first;
4409 StringRef
FileName,
bool *IncompleteFormat) {
4412 if (!Status.FormatComplete)
4413 *IncompleteFormat =
true;
4440 auto LexingStd = Style.Standard;
4441 if (LexingStd == FormatStyle::LS_Auto || LexingStd == FormatStyle::LS_Latest)
4442 LexingStd = FormatStyle::LS_Cpp20;
4444 const bool SinceCpp11 = LexingStd >= FormatStyle::LS_Cpp11;
4445 const bool SinceCpp20 = LexingStd >= FormatStyle::LS_Cpp20;
4447 switch (Style.Language) {
4448 case FormatStyle::LK_C:
4452 case FormatStyle::LK_Cpp:
4453 case FormatStyle::LK_ObjC:
4454 LangOpts.CXXOperatorNames = 1;
4455 LangOpts.CPlusPlus11 = SinceCpp11;
4456 LangOpts.CPlusPlus14 = LexingStd >= FormatStyle::LS_Cpp14;
4457 LangOpts.CPlusPlus17 = LexingStd >= FormatStyle::LS_Cpp17;
4458 LangOpts.CPlusPlus20 = SinceCpp20;
4459 LangOpts.CPlusPlus23 = LexingStd >= FormatStyle::LS_Cpp23;
4460 LangOpts.CPlusPlus26 = LexingStd >= FormatStyle::LS_Cpp26;
4463 LangOpts.CPlusPlus = 1;
4466 LangOpts.Char8 = SinceCpp20;
4467 LangOpts.AllowLiteralDigitSeparator = LangOpts.CPlusPlus14 || LangOpts.C23;
4471 LangOpts.Digraphs = SinceCpp11;
4473 LangOpts.LineComment = 1;
4476 LangOpts.MicrosoftExt = 1;
4477 LangOpts.DeclSpecKeyword = 1;
4484 "Set coding style. <string> can be:\n"
4485 "1. A preset: LLVM, GNU, Google, Chromium, Microsoft,\n"
4486 " Mozilla, WebKit.\n"
4487 "2. 'file' to load style configuration from a\n"
4488 " .clang-format file in one of the parent directories\n"
4489 " of the source file (for stdin, see --assume-filename).\n"
4490 " If no .clang-format file is found, falls back to\n"
4491 " --fallback-style.\n"
4492 " --style=file is the default.\n"
4493 "3. 'file:<format_file_path>' to explicitly specify\n"
4494 " the configuration file.\n"
4495 "4. \"{key: value, ...}\" to set specific parameters, e.g.:\n"
4496 " --style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
4499 static constexpr std::array<llvm::StringLiteral, 2> TemplateSuffixes{
4503 for (
auto Suffix : TemplateSuffixes)
4508 return FormatStyle::LK_C;
4510 return FormatStyle::LK_Java;
4511 if (
FileName.ends_with_insensitive(
".js") ||
4512 FileName.ends_with_insensitive(
".mjs") ||
4513 FileName.ends_with_insensitive(
".cjs") ||
4514 FileName.ends_with_insensitive(
".ts")) {
4515 return FormatStyle::LK_JavaScript;
4518 return FormatStyle::LK_ObjC;
4519 if (
FileName.ends_with_insensitive(
".proto") ||
4520 FileName.ends_with_insensitive(
".protodevel")) {
4521 return FormatStyle::LK_Proto;
4526 if (
FileName.ends_with_insensitive(
".txtpb") ||
4527 FileName.ends_with_insensitive(
".textpb") ||
4528 FileName.ends_with_insensitive(
".pb.txt") ||
4529 FileName.ends_with_insensitive(
".textproto") ||
4530 FileName.ends_with_insensitive(
".asciipb")) {
4531 return FormatStyle::LK_TextProto;
4533 if (
FileName.ends_with_insensitive(
".td"))
4534 return FormatStyle::LK_TableGen;
4535 if (
FileName.ends_with_insensitive(
".cs"))
4536 return FormatStyle::LK_CSharp;
4537 if (
FileName.ends_with_insensitive(
".json") ||
4538 FileName.ends_with_insensitive(
".ipynb")) {
4539 return FormatStyle::LK_Json;
4541 if (
FileName.ends_with_insensitive(
".sv") ||
4542 FileName.ends_with_insensitive(
".svh") ||
4543 FileName.ends_with_insensitive(
".v") ||
4544 FileName.ends_with_insensitive(
".vh")) {
4545 return FormatStyle::LK_Verilog;
4547 return FormatStyle::LK_Cpp;
4555 LangOpts.CPlusPlus = 1;
4556 LangOpts.LineComment = 1;
4558 Lexer Lex(ID, SourceMgr.getBufferOrFake(ID), SourceMgr, LangOpts);
4562 auto Text = StringRef(SourceMgr.getCharacterData(
Tok.getLocation()),
4564 if (!
Text.consume_front(
"// clang-format Language:"))
4569 return FormatStyle::LK_C;
4571 return FormatStyle::LK_Cpp;
4573 return FormatStyle::LK_ObjC;
4576 return FormatStyle::LK_None;
4581 if (GuessedLanguage == FormatStyle::LK_Cpp) {
4582 auto Extension = llvm::sys::path::extension(
FileName);
4585 if (!Code.empty() && (Extension.empty() || Extension ==
".h")) {
4589 Language != FormatStyle::LK_None) {
4594 if (Guesser.isObjC())
4595 return FormatStyle::LK_ObjC;
4598 return GuessedLanguage;
4606llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
4608 FormatStyle *Style,
bool AllowUnknownOptions,
4609 llvm::SourceMgr::DiagHandlerTy DiagHandler,
4611 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Text =
4612 FS->getBufferForFile(ConfigFile.str());
4613 if (
auto EC =
Text.getError())
4616 DiagHandler,
nullptr,
4624 StringRef FallbackStyleName, StringRef Code,
4625 llvm::vfs::FileSystem *FS,
4626 bool AllowUnknownOptions,
4627 llvm::SourceMgr::DiagHandlerTy DiagHandler) {
4635 if (StyleName.starts_with(
"{")) {
4637 StringRef Source =
"<command-line>";
4638 if (std::error_code ec =
4640 AllowUnknownOptions, DiagHandler)) {
4644 if (Style.InheritConfig.empty())
4647 ChildFormatTextToApply.emplace_back(
4648 llvm::MemoryBuffer::getMemBuffer(StyleName, Source,
false));
4652 FS = llvm::vfs::getRealFileSystem().get();
4655 const bool IsDotHFile =
FileName.ends_with(
".h");
4658 if (Style.InheritConfig.empty() &&
4659 StyleName.starts_with_insensitive(
"file:")) {
4660 auto ConfigFile = StyleName.substr(5);
4661 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Text =
4663 DiagHandler, IsDotHFile);
4664 if (
auto EC =
Text.getError()) {
4669 LLVM_DEBUG(llvm::dbgs()
4670 <<
"Using configuration file " << ConfigFile <<
"\n");
4672 if (Style.InheritConfig.empty())
4678 ChildFormatTextToApply.emplace_back(std::move(*
Text));
4684 if (Style.InheritConfig.empty() && !StyleName.equals_insensitive(
"file")) {
4687 if (Style.InheritConfig.empty())
4691 using namespace llvm::sys::path;
4695 if (std::error_code EC = FS->makeAbsolute(Path))
4698 auto Normalize = [](String &Path) {
4699 Path = convert_to_slash(Path);
4700 remove_dots(Path,
true, Style::posix);
4706 Style.InheritConfig.clear();
4708 auto dropDiagnosticHandler = [](
const llvm::SMDiagnostic &,
void *) {};
4710 auto applyChildFormatTexts = [&](FormatStyle *Style) {
4711 for (
const auto &MemBuf : llvm::reverse(ChildFormatTextToApply)) {
4714 DiagHandler ? DiagHandler : dropDiagnosticHandler);
4717 static_cast<void>(EC);
4723 FilesToLookFor.push_back(
".clang-format");
4724 FilesToLookFor.push_back(
"_clang-format");
4726 llvm::StringSet<> Directories;
4727 bool Redirected =
false;
4728 String Dir, UnsuitableConfigFiles;
4729 for (StringRef Directory = Path; !Directory.empty();
4730 Directory = Redirected ? Dir.str() : parent_path(Directory)) {
4731 auto Status = FS->status(Directory);
4733 Status->getType() != llvm::sys::fs::file_type::directory_file) {
4740 for (
const auto &F : FilesToLookFor) {
4741 String ConfigFile(Directory);
4743 append(ConfigFile, F);
4744 LLVM_DEBUG(llvm::dbgs() <<
"Trying " << ConfigFile <<
"...\n");
4746 Status = FS->status(ConfigFile);
4748 Status->getType() != llvm::sys::fs::file_type::regular_file) {
4752 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Text =
4754 DiagHandler, IsDotHFile);
4755 if (
auto EC =
Text.getError()) {
4760 if (!UnsuitableConfigFiles.empty())
4761 UnsuitableConfigFiles.append(
", ");
4762 UnsuitableConfigFiles.append(ConfigFile);
4766 LLVM_DEBUG(llvm::dbgs()
4767 <<
"Using configuration file " << ConfigFile <<
"\n");
4769 if (Style.InheritConfig.empty()) {
4770 if (!ChildFormatTextToApply.empty()) {
4771 LLVM_DEBUG(llvm::dbgs() <<
"Applying child configurations\n");
4772 applyChildFormatTexts(&Style);
4777 if (!Directories.insert(Directory).second) {
4779 "Loop detected when inheriting configuration file in " + Directory);
4782 LLVM_DEBUG(llvm::dbgs() <<
"Inherits parent configuration\n");
4784 if (Style.InheritConfig ==
"..") {
4789 llvm::sys::fs::expand_tilde(Style.InheritConfig, ExpandedDir);
4790 Normalize(ExpandedDir);
4791 if (is_absolute(ExpandedDir, Style::posix)) {
4794 Dir = Directory.str();
4795 append(Dir, Style::posix, ExpandedDir);
4800 Style.InheritConfig.clear();
4802 ChildFormatTextToApply.emplace_back(std::move(*
Text));
4812 if (!UnsuitableConfigFiles.empty()) {
4815 UnsuitableConfigFiles);
4818 if (!ChildFormatTextToApply.empty()) {
4819 LLVM_DEBUG(llvm::dbgs()
4820 <<
"Applying child configurations on fallback style\n");
4821 applyChildFormatTexts(&FallbackStyle);
4824 return FallbackStyle;
4828 if (Comment == (On ?
"/* clang-format on */" :
"/* clang-format off */"))
4831 static const char ClangFormatOn[] =
"// clang-format on";
4832 static const char ClangFormatOff[] =
"// clang-format off";
4833 const unsigned Size = (On ?
sizeof ClangFormatOn :
sizeof ClangFormatOff) - 1;
4835 return Comment.starts_with(On ? ClangFormatOn : ClangFormatOff) &&
4836 (Comment.size() == Size || Comment[Size] ==
':');
This file declares DefinitionBlockSeparator, a TokenAnalyzer that inserts or removes empty lines sepa...
This file declares IntegerLiteralSeparatorFixer that fixes C++ integer literal separators.
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.
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.
bool LexFromRawLexer(Token &Result)
LexFromRawLexer - Lex a token from a designated raw lexer (one with no associated preprocessor object...
void SetCommentRetentionState(bool Mode)
SetCommentRetentionMode - Change the comment retention mode of the lexer to the specified mode.
Token - This structure provides full information about a lexed token.
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).
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.
const char * getPunctuatorSpelling(TokenKind Kind) LLVM_READNONE
Determines the spelling of simple punctuation tokens like '!
The JSON file list parser is used to communicate input to InstallAPI.
std::vector< std::string > JavaImportGroups
A vector of prefixes ordered by the desired groups for Java imports.
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.
SortIncludesOptions SortIncludes
Controls if and how clang-format will sort #includes.
Diagnostic wrappers for TextAPI types for error reporting.
int const char * function
static void enumeration(IO &IO, BracketAlignmentStyle &Value)
static void enumeration(IO &IO, FormatStyle::IndentExternBlockStyle &Value)
static void enumeration(IO &IO, FormatStyle::LambdaBodyIndentationKind &Value)
static void enumeration(IO &IO, FormatStyle::WrapNamespaceBodyWithEmptyLinesStyle &Value)
static StringRef input(StringRef Scalar, void *, clang::tok::TokenKind &Value)
static QuotingType mustQuote(StringRef)
static void output(const clang::tok::TokenKind &Value, void *, llvm::raw_ostream &Out)