26#include "llvm/ADT/Sequence.h"
29#define DEBUG_TYPE "format-formatter"
31using clang::format::FormatStyle;
33LLVM_YAML_IS_SEQUENCE_VECTOR(FormatStyle::RawStringFormat)
45struct ScalarEnumerationTraits<FormatStyle::BreakBeforeNoexceptSpecifierStyle> {
48 IO.enumCase(
Value,
"Never", FormatStyle::BBNSS_Never);
49 IO.enumCase(
Value,
"OnlyWithParen", FormatStyle::BBNSS_OnlyWithParen);
50 IO.enumCase(
Value,
"Always", FormatStyle::BBNSS_Always);
54template <>
struct MappingTraits<FormatStyle::AlignConsecutiveStyle> {
56 IO.enumCase(
Value,
"None", FormatStyle::AlignConsecutiveStyle({}));
57 IO.enumCase(
Value,
"Consecutive",
58 FormatStyle::AlignConsecutiveStyle(
63 IO.enumCase(
Value,
"AcrossEmptyLines",
64 FormatStyle::AlignConsecutiveStyle(
69 IO.enumCase(
Value,
"AcrossComments",
70 FormatStyle::AlignConsecutiveStyle(
75 IO.enumCase(
Value,
"AcrossEmptyLinesAndComments",
76 FormatStyle::AlignConsecutiveStyle(
83 IO.enumCase(
Value,
"true",
84 FormatStyle::AlignConsecutiveStyle(
89 IO.enumCase(
Value,
"false", FormatStyle::AlignConsecutiveStyle({}));
92 static void mapping(IO &IO, FormatStyle::AlignConsecutiveStyle &
Value) {
93 IO.mapOptional(
"Enabled",
Value.Enabled);
94 IO.mapOptional(
"AcrossEmptyLines",
Value.AcrossEmptyLines);
95 IO.mapOptional(
"AcrossComments",
Value.AcrossComments);
96 IO.mapOptional(
"AlignCompound",
Value.AlignCompound);
97 IO.mapOptional(
"AlignFunctionDeclarations",
98 Value.AlignFunctionDeclarations);
99 IO.mapOptional(
"AlignFunctionPointers",
Value.AlignFunctionPointers);
100 IO.mapOptional(
"PadOperators",
Value.PadOperators);
105struct MappingTraits<FormatStyle::ShortCaseStatementsAlignmentStyle> {
107 FormatStyle::ShortCaseStatementsAlignmentStyle &
Value) {
108 IO.mapOptional(
"Enabled",
Value.Enabled);
109 IO.mapOptional(
"AcrossEmptyLines",
Value.AcrossEmptyLines);
110 IO.mapOptional(
"AcrossComments",
Value.AcrossComments);
111 IO.mapOptional(
"AlignCaseArrows",
Value.AlignCaseArrows);
112 IO.mapOptional(
"AlignCaseColons",
Value.AlignCaseColons);
117struct ScalarEnumerationTraits<FormatStyle::AttributeBreakingStyle> {
119 IO.enumCase(
Value,
"Always", FormatStyle::ABS_Always);
120 IO.enumCase(
Value,
"Leave", FormatStyle::ABS_Leave);
121 IO.enumCase(
Value,
"Never", FormatStyle::ABS_Never);
126struct ScalarEnumerationTraits<FormatStyle::ArrayInitializerAlignmentStyle> {
128 FormatStyle::ArrayInitializerAlignmentStyle &
Value) {
129 IO.enumCase(
Value,
"None", FormatStyle::AIAS_None);
130 IO.enumCase(
Value,
"Left", FormatStyle::AIAS_Left);
131 IO.enumCase(
Value,
"Right", FormatStyle::AIAS_Right);
135template <>
struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
137 IO.enumCase(
Value,
"All", FormatStyle::BOS_All);
138 IO.enumCase(
Value,
"true", FormatStyle::BOS_All);
139 IO.enumCase(
Value,
"None", FormatStyle::BOS_None);
140 IO.enumCase(
Value,
"false", FormatStyle::BOS_None);
141 IO.enumCase(
Value,
"NonAssignment", FormatStyle::BOS_NonAssignment);
146struct ScalarEnumerationTraits<FormatStyle::BinPackParametersStyle> {
148 IO.enumCase(
Value,
"BinPack", FormatStyle::BPPS_BinPack);
149 IO.enumCase(
Value,
"OnePerLine", FormatStyle::BPPS_OnePerLine);
150 IO.enumCase(
Value,
"AlwaysOnePerLine", FormatStyle::BPPS_AlwaysOnePerLine);
153 IO.enumCase(
Value,
"true", FormatStyle::BPPS_BinPack);
154 IO.enumCase(
Value,
"false", FormatStyle::BPPS_OnePerLine);
158template <>
struct ScalarEnumerationTraits<FormatStyle::BinPackStyle> {
160 IO.enumCase(
Value,
"Auto", FormatStyle::BPS_Auto);
161 IO.enumCase(
Value,
"Always", FormatStyle::BPS_Always);
162 IO.enumCase(
Value,
"Never", FormatStyle::BPS_Never);
167struct ScalarEnumerationTraits<FormatStyle::BitFieldColonSpacingStyle> {
169 FormatStyle::BitFieldColonSpacingStyle &
Value) {
170 IO.enumCase(
Value,
"Both", FormatStyle::BFCS_Both);
171 IO.enumCase(
Value,
"None", FormatStyle::BFCS_None);
172 IO.enumCase(
Value,
"Before", FormatStyle::BFCS_Before);
173 IO.enumCase(
Value,
"After", FormatStyle::BFCS_After);
177template <>
struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
179 IO.enumCase(
Value,
"Attach", FormatStyle::BS_Attach);
180 IO.enumCase(
Value,
"Linux", FormatStyle::BS_Linux);
181 IO.enumCase(
Value,
"Mozilla", FormatStyle::BS_Mozilla);
182 IO.enumCase(
Value,
"Stroustrup", FormatStyle::BS_Stroustrup);
183 IO.enumCase(
Value,
"Allman", FormatStyle::BS_Allman);
184 IO.enumCase(
Value,
"Whitesmiths", FormatStyle::BS_Whitesmiths);
185 IO.enumCase(
Value,
"GNU", FormatStyle::BS_GNU);
186 IO.enumCase(
Value,
"WebKit", FormatStyle::BS_WebKit);
187 IO.enumCase(
Value,
"Custom", FormatStyle::BS_Custom);
191template <>
struct MappingTraits<FormatStyle::BraceWrappingFlags> {
192 static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
193 IO.mapOptional(
"AfterCaseLabel", Wrapping.AfterCaseLabel);
194 IO.mapOptional(
"AfterClass", Wrapping.AfterClass);
195 IO.mapOptional(
"AfterControlStatement", Wrapping.AfterControlStatement);
196 IO.mapOptional(
"AfterEnum", Wrapping.AfterEnum);
197 IO.mapOptional(
"AfterExternBlock", Wrapping.AfterExternBlock);
198 IO.mapOptional(
"AfterFunction", Wrapping.AfterFunction);
199 IO.mapOptional(
"AfterNamespace", Wrapping.AfterNamespace);
200 IO.mapOptional(
"AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
201 IO.mapOptional(
"AfterStruct", Wrapping.AfterStruct);
202 IO.mapOptional(
"AfterUnion", Wrapping.AfterUnion);
203 IO.mapOptional(
"BeforeCatch", Wrapping.BeforeCatch);
204 IO.mapOptional(
"BeforeElse", Wrapping.BeforeElse);
205 IO.mapOptional(
"BeforeLambdaBody", Wrapping.BeforeLambdaBody);
206 IO.mapOptional(
"BeforeWhile", Wrapping.BeforeWhile);
207 IO.mapOptional(
"IndentBraces", Wrapping.IndentBraces);
208 IO.mapOptional(
"SplitEmptyFunction", Wrapping.SplitEmptyFunction);
209 IO.mapOptional(
"SplitEmptyRecord", Wrapping.SplitEmptyRecord);
210 IO.mapOptional(
"SplitEmptyNamespace", Wrapping.SplitEmptyNamespace);
228struct ScalarEnumerationTraits<
229 FormatStyle::BraceWrappingAfterControlStatementStyle> {
232 FormatStyle::BraceWrappingAfterControlStatementStyle &
Value) {
233 IO.enumCase(
Value,
"Never", FormatStyle::BWACS_Never);
234 IO.enumCase(
Value,
"MultiLine", FormatStyle::BWACS_MultiLine);
235 IO.enumCase(
Value,
"Always", FormatStyle::BWACS_Always);
238 IO.enumCase(
Value,
"false", FormatStyle::BWACS_Never);
239 IO.enumCase(
Value,
"true", FormatStyle::BWACS_Always);
244struct ScalarEnumerationTraits<
245 FormatStyle::BreakBeforeConceptDeclarationsStyle> {
248 IO.enumCase(
Value,
"Never", FormatStyle::BBCDS_Never);
249 IO.enumCase(
Value,
"Allowed", FormatStyle::BBCDS_Allowed);
250 IO.enumCase(
Value,
"Always", FormatStyle::BBCDS_Always);
253 IO.enumCase(
Value,
"true", FormatStyle::BBCDS_Always);
254 IO.enumCase(
Value,
"false", FormatStyle::BBCDS_Allowed);
259struct ScalarEnumerationTraits<FormatStyle::BreakBeforeInlineASMColonStyle> {
261 FormatStyle::BreakBeforeInlineASMColonStyle &
Value) {
262 IO.enumCase(
Value,
"Never", FormatStyle::BBIAS_Never);
263 IO.enumCase(
Value,
"OnlyMultiline", FormatStyle::BBIAS_OnlyMultiline);
264 IO.enumCase(
Value,
"Always", FormatStyle::BBIAS_Always);
269struct ScalarEnumerationTraits<FormatStyle::BreakBinaryOperationsStyle> {
271 FormatStyle::BreakBinaryOperationsStyle &
Value) {
272 IO.enumCase(
Value,
"Never", FormatStyle::BBO_Never);
273 IO.enumCase(
Value,
"OnePerLine", FormatStyle::BBO_OnePerLine);
274 IO.enumCase(
Value,
"RespectPrecedence", FormatStyle::BBO_RespectPrecedence);
279struct ScalarEnumerationTraits<FormatStyle::BreakConstructorInitializersStyle> {
282 IO.enumCase(
Value,
"BeforeColon", FormatStyle::BCIS_BeforeColon);
283 IO.enumCase(
Value,
"BeforeComma", FormatStyle::BCIS_BeforeComma);
284 IO.enumCase(
Value,
"AfterColon", FormatStyle::BCIS_AfterColon);
289struct ScalarEnumerationTraits<FormatStyle::BreakInheritanceListStyle> {
291 FormatStyle::BreakInheritanceListStyle &
Value) {
292 IO.enumCase(
Value,
"BeforeColon", FormatStyle::BILS_BeforeColon);
293 IO.enumCase(
Value,
"BeforeComma", FormatStyle::BILS_BeforeComma);
294 IO.enumCase(
Value,
"AfterColon", FormatStyle::BILS_AfterColon);
295 IO.enumCase(
Value,
"AfterComma", FormatStyle::BILS_AfterComma);
300struct ScalarEnumerationTraits<FormatStyle::BreakTemplateDeclarationsStyle> {
302 FormatStyle::BreakTemplateDeclarationsStyle &
Value) {
303 IO.enumCase(
Value,
"Leave", FormatStyle::BTDS_Leave);
304 IO.enumCase(
Value,
"No", FormatStyle::BTDS_No);
305 IO.enumCase(
Value,
"MultiLine", FormatStyle::BTDS_MultiLine);
306 IO.enumCase(
Value,
"Yes", FormatStyle::BTDS_Yes);
309 IO.enumCase(
Value,
"false", FormatStyle::BTDS_MultiLine);
310 IO.enumCase(
Value,
"true", FormatStyle::BTDS_Yes);
314template <>
struct ScalarEnumerationTraits<FormatStyle::BracedListStyle> {
316 IO.enumCase(
Value,
"Block", FormatStyle::BLS_Block);
317 IO.enumCase(
Value,
"FunctionCall", FormatStyle::BLS_FunctionCall);
318 IO.enumCase(
Value,
"AlignFirstComment", FormatStyle::BLS_AlignFirstComment);
321 IO.enumCase(
Value,
"false", FormatStyle::BLS_Block);
322 IO.enumCase(
Value,
"true", FormatStyle::BLS_AlignFirstComment);
326template <>
struct ScalarEnumerationTraits<FormatStyle::DAGArgStyle> {
328 IO.enumCase(
Value,
"DontBreak", FormatStyle::DAS_DontBreak);
329 IO.enumCase(
Value,
"BreakElements", FormatStyle::DAS_BreakElements);
330 IO.enumCase(
Value,
"BreakAll", FormatStyle::DAS_BreakAll);
335struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
338 IO.enumCase(
Value,
"None", FormatStyle::DRTBS_None);
339 IO.enumCase(
Value,
"All", FormatStyle::DRTBS_All);
340 IO.enumCase(
Value,
"TopLevel", FormatStyle::DRTBS_TopLevel);
343 IO.enumCase(
Value,
"false", FormatStyle::DRTBS_None);
344 IO.enumCase(
Value,
"true", FormatStyle::DRTBS_All);
349struct ScalarEnumerationTraits<FormatStyle::EscapedNewlineAlignmentStyle> {
351 FormatStyle::EscapedNewlineAlignmentStyle &
Value) {
352 IO.enumCase(
Value,
"DontAlign", FormatStyle::ENAS_DontAlign);
353 IO.enumCase(
Value,
"Left", FormatStyle::ENAS_Left);
354 IO.enumCase(
Value,
"LeftWithLastLine", FormatStyle::ENAS_LeftWithLastLine);
355 IO.enumCase(
Value,
"Right", FormatStyle::ENAS_Right);
358 IO.enumCase(
Value,
"true", FormatStyle::ENAS_Left);
359 IO.enumCase(
Value,
"false", FormatStyle::ENAS_Right);
364struct ScalarEnumerationTraits<FormatStyle::EmptyLineAfterAccessModifierStyle> {
367 IO.enumCase(
Value,
"Never", FormatStyle::ELAAMS_Never);
368 IO.enumCase(
Value,
"Leave", FormatStyle::ELAAMS_Leave);
369 IO.enumCase(
Value,
"Always", FormatStyle::ELAAMS_Always);
374struct ScalarEnumerationTraits<
375 FormatStyle::EmptyLineBeforeAccessModifierStyle> {
378 IO.enumCase(
Value,
"Never", FormatStyle::ELBAMS_Never);
379 IO.enumCase(
Value,
"Leave", FormatStyle::ELBAMS_Leave);
380 IO.enumCase(
Value,
"LogicalBlock", FormatStyle::ELBAMS_LogicalBlock);
381 IO.enumCase(
Value,
"Always", FormatStyle::ELBAMS_Always);
386struct ScalarEnumerationTraits<FormatStyle::EnumTrailingCommaStyle> {
388 IO.enumCase(
Value,
"Leave", FormatStyle::ETC_Leave);
389 IO.enumCase(
Value,
"Insert", FormatStyle::ETC_Insert);
390 IO.enumCase(
Value,
"Remove", FormatStyle::ETC_Remove);
395struct ScalarEnumerationTraits<FormatStyle::IndentExternBlockStyle> {
397 IO.enumCase(
Value,
"AfterExternBlock", FormatStyle::IEBS_AfterExternBlock);
398 IO.enumCase(
Value,
"Indent", FormatStyle::IEBS_Indent);
399 IO.enumCase(
Value,
"NoIndent", FormatStyle::IEBS_NoIndent);
400 IO.enumCase(
Value,
"true", FormatStyle::IEBS_Indent);
401 IO.enumCase(
Value,
"false", FormatStyle::IEBS_NoIndent);
405template <>
struct MappingTraits<FormatStyle::IntegerLiteralSeparatorStyle> {
406 static void mapping(IO &IO, FormatStyle::IntegerLiteralSeparatorStyle &
Base) {
407 IO.mapOptional(
"Binary",
Base.Binary);
408 IO.mapOptional(
"BinaryMinDigits",
Base.BinaryMinDigits);
409 IO.mapOptional(
"Decimal",
Base.Decimal);
410 IO.mapOptional(
"DecimalMinDigits",
Base.DecimalMinDigits);
411 IO.mapOptional(
"Hex",
Base.Hex);
412 IO.mapOptional(
"HexMinDigits",
Base.HexMinDigits);
416template <>
struct ScalarEnumerationTraits<FormatStyle::JavaScriptQuoteStyle> {
418 IO.enumCase(
Value,
"Leave", FormatStyle::JSQS_Leave);
419 IO.enumCase(
Value,
"Single", FormatStyle::JSQS_Single);
420 IO.enumCase(
Value,
"Double", FormatStyle::JSQS_Double);
424template <>
struct MappingTraits<FormatStyle::KeepEmptyLinesStyle> {
426 IO.mapOptional(
"AtEndOfFile",
Value.AtEndOfFile);
427 IO.mapOptional(
"AtStartOfBlock",
Value.AtStartOfBlock);
428 IO.mapOptional(
"AtStartOfFile",
Value.AtStartOfFile);
432template <>
struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
434 IO.enumCase(
Value,
"C", FormatStyle::LK_C);
435 IO.enumCase(
Value,
"Cpp", FormatStyle::LK_Cpp);
436 IO.enumCase(
Value,
"Java", FormatStyle::LK_Java);
437 IO.enumCase(
Value,
"JavaScript", FormatStyle::LK_JavaScript);
438 IO.enumCase(
Value,
"ObjC", FormatStyle::LK_ObjC);
439 IO.enumCase(
Value,
"Proto", FormatStyle::LK_Proto);
440 IO.enumCase(
Value,
"TableGen", FormatStyle::LK_TableGen);
441 IO.enumCase(
Value,
"TextProto", FormatStyle::LK_TextProto);
442 IO.enumCase(
Value,
"CSharp", FormatStyle::LK_CSharp);
443 IO.enumCase(
Value,
"Json", FormatStyle::LK_Json);
444 IO.enumCase(
Value,
"Verilog", FormatStyle::LK_Verilog);
448template <>
struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
450 IO.enumCase(
Value,
"c++03", FormatStyle::LS_Cpp03);
451 IO.enumCase(
Value,
"C++03", FormatStyle::LS_Cpp03);
452 IO.enumCase(
Value,
"Cpp03", FormatStyle::LS_Cpp03);
454 IO.enumCase(
Value,
"c++11", FormatStyle::LS_Cpp11);
455 IO.enumCase(
Value,
"C++11", FormatStyle::LS_Cpp11);
457 IO.enumCase(
Value,
"c++14", FormatStyle::LS_Cpp14);
458 IO.enumCase(
Value,
"c++17", FormatStyle::LS_Cpp17);
459 IO.enumCase(
Value,
"c++20", FormatStyle::LS_Cpp20);
461 IO.enumCase(
Value,
"Latest", FormatStyle::LS_Latest);
462 IO.enumCase(
Value,
"Cpp11", FormatStyle::LS_Latest);
463 IO.enumCase(
Value,
"Auto", FormatStyle::LS_Auto);
468struct ScalarEnumerationTraits<FormatStyle::LambdaBodyIndentationKind> {
470 FormatStyle::LambdaBodyIndentationKind &
Value) {
471 IO.enumCase(
Value,
"Signature", FormatStyle::LBI_Signature);
472 IO.enumCase(
Value,
"OuterScope", FormatStyle::LBI_OuterScope);
476template <>
struct ScalarEnumerationTraits<FormatStyle::LineEndingStyle> {
478 IO.enumCase(
Value,
"LF", FormatStyle::LE_LF);
479 IO.enumCase(
Value,
"CRLF", FormatStyle::LE_CRLF);
480 IO.enumCase(
Value,
"DeriveLF", FormatStyle::LE_DeriveLF);
481 IO.enumCase(
Value,
"DeriveCRLF", FormatStyle::LE_DeriveCRLF);
486struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
488 FormatStyle::NamespaceIndentationKind &
Value) {
489 IO.enumCase(
Value,
"None", FormatStyle::NI_None);
490 IO.enumCase(
Value,
"Inner", FormatStyle::NI_Inner);
491 IO.enumCase(
Value,
"All", FormatStyle::NI_All);
496struct ScalarEnumerationTraits<FormatStyle::NumericLiteralComponentStyle> {
498 FormatStyle::NumericLiteralComponentStyle &
Value) {
499 IO.enumCase(
Value,
"Leave", FormatStyle::NLCS_Leave);
500 IO.enumCase(
Value,
"Upper", FormatStyle::NLCS_Upper);
501 IO.enumCase(
Value,
"Lower", FormatStyle::NLCS_Lower);
505template <>
struct MappingTraits<FormatStyle::NumericLiteralCaseStyle> {
506 static void mapping(IO &IO, FormatStyle::NumericLiteralCaseStyle &
Value) {
507 IO.mapOptional(
"ExponentLetter",
Value.ExponentLetter);
508 IO.mapOptional(
"HexDigit",
Value.HexDigit);
509 IO.mapOptional(
"Prefix",
Value.Prefix);
510 IO.mapOptional(
"Suffix",
Value.Suffix);
514template <>
struct ScalarEnumerationTraits<FormatStyle::OperandAlignmentStyle> {
516 IO.enumCase(
Value,
"DontAlign", FormatStyle::OAS_DontAlign);
517 IO.enumCase(
Value,
"Align", FormatStyle::OAS_Align);
518 IO.enumCase(
Value,
"AlignAfterOperator",
519 FormatStyle::OAS_AlignAfterOperator);
522 IO.enumCase(
Value,
"true", FormatStyle::OAS_Align);
523 IO.enumCase(
Value,
"false", FormatStyle::OAS_DontAlign);
528struct ScalarEnumerationTraits<FormatStyle::PackConstructorInitializersStyle> {
531 IO.enumCase(
Value,
"Never", FormatStyle::PCIS_Never);
532 IO.enumCase(
Value,
"BinPack", FormatStyle::PCIS_BinPack);
533 IO.enumCase(
Value,
"CurrentLine", FormatStyle::PCIS_CurrentLine);
534 IO.enumCase(
Value,
"NextLine", FormatStyle::PCIS_NextLine);
535 IO.enumCase(
Value,
"NextLineOnly", FormatStyle::PCIS_NextLineOnly);
539template <>
struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
541 IO.enumCase(
Value,
"Middle", FormatStyle::PAS_Middle);
542 IO.enumCase(
Value,
"Left", FormatStyle::PAS_Left);
543 IO.enumCase(
Value,
"Right", FormatStyle::PAS_Right);
546 IO.enumCase(
Value,
"true", FormatStyle::PAS_Left);
547 IO.enumCase(
Value,
"false", FormatStyle::PAS_Right);
552struct ScalarEnumerationTraits<FormatStyle::PPDirectiveIndentStyle> {
554 IO.enumCase(
Value,
"None", FormatStyle::PPDIS_None);
555 IO.enumCase(
Value,
"AfterHash", FormatStyle::PPDIS_AfterHash);
556 IO.enumCase(
Value,
"BeforeHash", FormatStyle::PPDIS_BeforeHash);
557 IO.enumCase(
Value,
"Leave", FormatStyle::PPDIS_Leave);
562struct ScalarEnumerationTraits<FormatStyle::QualifierAlignmentStyle> {
564 IO.enumCase(
Value,
"Leave", FormatStyle::QAS_Leave);
565 IO.enumCase(
Value,
"Left", FormatStyle::QAS_Left);
566 IO.enumCase(
Value,
"Right", FormatStyle::QAS_Right);
567 IO.enumCase(
Value,
"Custom", FormatStyle::QAS_Custom);
571template <>
struct MappingTraits<FormatStyle::RawStringFormat> {
572 static void mapping(IO &IO, FormatStyle::RawStringFormat &Format) {
573 IO.mapOptional(
"Language", Format.Language);
574 IO.mapOptional(
"Delimiters", Format.Delimiters);
575 IO.mapOptional(
"EnclosingFunctions", Format.EnclosingFunctions);
576 IO.mapOptional(
"CanonicalDelimiter", Format.CanonicalDelimiter);
577 IO.mapOptional(
"BasedOnStyle", Format.BasedOnStyle);
581template <>
struct ScalarEnumerationTraits<FormatStyle::ReflowCommentsStyle> {
583 IO.enumCase(
Value,
"Never", FormatStyle::RCS_Never);
584 IO.enumCase(
Value,
"IndentOnly", FormatStyle::RCS_IndentOnly);
585 IO.enumCase(
Value,
"Always", FormatStyle::RCS_Always);
587 IO.enumCase(
Value,
"false", FormatStyle::RCS_Never);
588 IO.enumCase(
Value,
"true", FormatStyle::RCS_Always);
593struct ScalarEnumerationTraits<FormatStyle::ReferenceAlignmentStyle> {
595 IO.enumCase(
Value,
"Pointer", FormatStyle::RAS_Pointer);
596 IO.enumCase(
Value,
"Middle", FormatStyle::RAS_Middle);
597 IO.enumCase(
Value,
"Left", FormatStyle::RAS_Left);
598 IO.enumCase(
Value,
"Right", FormatStyle::RAS_Right);
603struct ScalarEnumerationTraits<FormatStyle::RemoveParenthesesStyle> {
605 IO.enumCase(
Value,
"Leave", FormatStyle::RPS_Leave);
606 IO.enumCase(
Value,
"MultipleParentheses",
607 FormatStyle::RPS_MultipleParentheses);
608 IO.enumCase(
Value,
"ReturnStatement", FormatStyle::RPS_ReturnStatement);
613struct ScalarEnumerationTraits<FormatStyle::RequiresClausePositionStyle> {
615 FormatStyle::RequiresClausePositionStyle &
Value) {
616 IO.enumCase(
Value,
"OwnLine", FormatStyle::RCPS_OwnLine);
617 IO.enumCase(
Value,
"OwnLineWithBrace", FormatStyle::RCPS_OwnLineWithBrace);
618 IO.enumCase(
Value,
"WithPreceding", FormatStyle::RCPS_WithPreceding);
619 IO.enumCase(
Value,
"WithFollowing", FormatStyle::RCPS_WithFollowing);
620 IO.enumCase(
Value,
"SingleLine", FormatStyle::RCPS_SingleLine);
625struct ScalarEnumerationTraits<FormatStyle::RequiresExpressionIndentationKind> {
628 IO.enumCase(
Value,
"Keyword", FormatStyle::REI_Keyword);
629 IO.enumCase(
Value,
"OuterScope", FormatStyle::REI_OuterScope);
634struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
636 IO.enumCase(
Value,
"None", FormatStyle::RTBS_None);
637 IO.enumCase(
Value,
"Automatic", FormatStyle::RTBS_Automatic);
638 IO.enumCase(
Value,
"ExceptShortType", FormatStyle::RTBS_ExceptShortType);
639 IO.enumCase(
Value,
"All", FormatStyle::RTBS_All);
640 IO.enumCase(
Value,
"TopLevel", FormatStyle::RTBS_TopLevel);
641 IO.enumCase(
Value,
"TopLevelDefinitions",
642 FormatStyle::RTBS_TopLevelDefinitions);
643 IO.enumCase(
Value,
"AllDefinitions", FormatStyle::RTBS_AllDefinitions);
648struct ScalarEnumerationTraits<FormatStyle::SeparateDefinitionStyle> {
650 IO.enumCase(
Value,
"Leave", FormatStyle::SDS_Leave);
651 IO.enumCase(
Value,
"Always", FormatStyle::SDS_Always);
652 IO.enumCase(
Value,
"Never", FormatStyle::SDS_Never);
656template <>
struct ScalarEnumerationTraits<FormatStyle::ShortBlockStyle> {
658 IO.enumCase(
Value,
"Never", FormatStyle::SBS_Never);
659 IO.enumCase(
Value,
"false", FormatStyle::SBS_Never);
660 IO.enumCase(
Value,
"Always", FormatStyle::SBS_Always);
661 IO.enumCase(
Value,
"true", FormatStyle::SBS_Always);
662 IO.enumCase(
Value,
"Empty", FormatStyle::SBS_Empty);
666template <>
struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
668 IO.enumCase(
Value,
"None", FormatStyle::SFS_None);
669 IO.enumCase(
Value,
"false", FormatStyle::SFS_None);
670 IO.enumCase(
Value,
"All", FormatStyle::SFS_All);
671 IO.enumCase(
Value,
"true", FormatStyle::SFS_All);
672 IO.enumCase(
Value,
"Inline", FormatStyle::SFS_Inline);
673 IO.enumCase(
Value,
"InlineOnly", FormatStyle::SFS_InlineOnly);
674 IO.enumCase(
Value,
"Empty", FormatStyle::SFS_Empty);
678template <>
struct ScalarEnumerationTraits<FormatStyle::ShortIfStyle> {
680 IO.enumCase(
Value,
"Never", FormatStyle::SIS_Never);
681 IO.enumCase(
Value,
"WithoutElse", FormatStyle::SIS_WithoutElse);
682 IO.enumCase(
Value,
"OnlyFirstIf", FormatStyle::SIS_OnlyFirstIf);
683 IO.enumCase(
Value,
"AllIfsAndElse", FormatStyle::SIS_AllIfsAndElse);
686 IO.enumCase(
Value,
"Always", FormatStyle::SIS_OnlyFirstIf);
687 IO.enumCase(
Value,
"false", FormatStyle::SIS_Never);
688 IO.enumCase(
Value,
"true", FormatStyle::SIS_WithoutElse);
692template <>
struct ScalarEnumerationTraits<FormatStyle::ShortLambdaStyle> {
694 IO.enumCase(
Value,
"None", FormatStyle::SLS_None);
695 IO.enumCase(
Value,
"false", FormatStyle::SLS_None);
696 IO.enumCase(
Value,
"Empty", FormatStyle::SLS_Empty);
697 IO.enumCase(
Value,
"Inline", FormatStyle::SLS_Inline);
698 IO.enumCase(
Value,
"All", FormatStyle::SLS_All);
699 IO.enumCase(
Value,
"true", FormatStyle::SLS_All);
703template <>
struct MappingTraits<FormatStyle::SortIncludesOptions> {
705 IO.enumCase(
Value,
"Never", FormatStyle::SortIncludesOptions({}));
706 IO.enumCase(
Value,
"CaseInsensitive",
707 FormatStyle::SortIncludesOptions({
true,
710 IO.enumCase(
Value,
"CaseSensitive",
711 FormatStyle::SortIncludesOptions({
true,
716 IO.enumCase(
Value,
"false", FormatStyle::SortIncludesOptions({}));
717 IO.enumCase(
Value,
"true",
718 FormatStyle::SortIncludesOptions({
true,
724 IO.mapOptional(
"Enabled",
Value.Enabled);
725 IO.mapOptional(
"IgnoreCase",
Value.IgnoreCase);
726 IO.mapOptional(
"IgnoreExtension",
Value.IgnoreExtension);
731struct ScalarEnumerationTraits<FormatStyle::SortJavaStaticImportOptions> {
733 FormatStyle::SortJavaStaticImportOptions &
Value) {
734 IO.enumCase(
Value,
"Before", FormatStyle::SJSIO_Before);
735 IO.enumCase(
Value,
"After", FormatStyle::SJSIO_After);
740struct ScalarEnumerationTraits<FormatStyle::SortUsingDeclarationsOptions> {
742 FormatStyle::SortUsingDeclarationsOptions &
Value) {
743 IO.enumCase(
Value,
"Never", FormatStyle::SUD_Never);
744 IO.enumCase(
Value,
"Lexicographic", FormatStyle::SUD_Lexicographic);
745 IO.enumCase(
Value,
"LexicographicNumeric",
746 FormatStyle::SUD_LexicographicNumeric);
749 IO.enumCase(
Value,
"false", FormatStyle::SUD_Never);
750 IO.enumCase(
Value,
"true", FormatStyle::SUD_LexicographicNumeric);
755struct ScalarEnumerationTraits<FormatStyle::SpaceAroundPointerQualifiersStyle> {
758 IO.enumCase(
Value,
"Default", FormatStyle::SAPQ_Default);
759 IO.enumCase(
Value,
"Before", FormatStyle::SAPQ_Before);
760 IO.enumCase(
Value,
"After", FormatStyle::SAPQ_After);
761 IO.enumCase(
Value,
"Both", FormatStyle::SAPQ_Both);
765template <>
struct MappingTraits<FormatStyle::SpaceBeforeParensCustom> {
766 static void mapping(IO &IO, FormatStyle::SpaceBeforeParensCustom &Spacing) {
767 IO.mapOptional(
"AfterControlStatements", Spacing.AfterControlStatements);
768 IO.mapOptional(
"AfterForeachMacros", Spacing.AfterForeachMacros);
769 IO.mapOptional(
"AfterFunctionDefinitionName",
770 Spacing.AfterFunctionDefinitionName);
771 IO.mapOptional(
"AfterFunctionDeclarationName",
772 Spacing.AfterFunctionDeclarationName);
773 IO.mapOptional(
"AfterIfMacros", Spacing.AfterIfMacros);
774 IO.mapOptional(
"AfterNot", Spacing.AfterNot);
775 IO.mapOptional(
"AfterOverloadedOperator", Spacing.AfterOverloadedOperator);
776 IO.mapOptional(
"AfterPlacementOperator", Spacing.AfterPlacementOperator);
777 IO.mapOptional(
"AfterRequiresInClause", Spacing.AfterRequiresInClause);
778 IO.mapOptional(
"AfterRequiresInExpression",
779 Spacing.AfterRequiresInExpression);
780 IO.mapOptional(
"BeforeNonEmptyParentheses",
781 Spacing.BeforeNonEmptyParentheses);
786struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensStyle> {
788 IO.enumCase(
Value,
"Never", FormatStyle::SBPO_Never);
789 IO.enumCase(
Value,
"ControlStatements",
790 FormatStyle::SBPO_ControlStatements);
791 IO.enumCase(
Value,
"ControlStatementsExceptControlMacros",
792 FormatStyle::SBPO_ControlStatementsExceptControlMacros);
793 IO.enumCase(
Value,
"NonEmptyParentheses",
794 FormatStyle::SBPO_NonEmptyParentheses);
795 IO.enumCase(
Value,
"Always", FormatStyle::SBPO_Always);
796 IO.enumCase(
Value,
"Custom", FormatStyle::SBPO_Custom);
799 IO.enumCase(
Value,
"false", FormatStyle::SBPO_Never);
800 IO.enumCase(
Value,
"true", FormatStyle::SBPO_ControlStatements);
801 IO.enumCase(
Value,
"ControlStatementsExceptForEachMacros",
802 FormatStyle::SBPO_ControlStatementsExceptControlMacros);
807struct ScalarEnumerationTraits<FormatStyle::SpaceInEmptyBracesStyle> {
809 IO.enumCase(
Value,
"Always", FormatStyle::SIEB_Always);
810 IO.enumCase(
Value,
"Block", FormatStyle::SIEB_Block);
811 IO.enumCase(
Value,
"Never", FormatStyle::SIEB_Never);
815template <>
struct ScalarEnumerationTraits<FormatStyle::SpacesInAnglesStyle> {
817 IO.enumCase(
Value,
"Never", FormatStyle::SIAS_Never);
818 IO.enumCase(
Value,
"Always", FormatStyle::SIAS_Always);
819 IO.enumCase(
Value,
"Leave", FormatStyle::SIAS_Leave);
822 IO.enumCase(
Value,
"false", FormatStyle::SIAS_Never);
823 IO.enumCase(
Value,
"true", FormatStyle::SIAS_Always);
827template <>
struct MappingTraits<FormatStyle::SpacesInLineComment> {
828 static void mapping(IO &IO, FormatStyle::SpacesInLineComment &Space) {
830 int signedMaximum =
static_cast<int>(Space.Maximum);
831 IO.mapOptional(
"Minimum", Space.Minimum);
832 IO.mapOptional(
"Maximum", signedMaximum);
833 Space.Maximum =
static_cast<unsigned>(signedMaximum);
835 if (Space.Maximum < std::numeric_limits<unsigned>::max())
836 Space.Minimum = std::min(Space.Minimum, Space.Maximum);
840template <>
struct MappingTraits<FormatStyle::SpacesInParensCustom> {
841 static void mapping(IO &IO, FormatStyle::SpacesInParensCustom &Spaces) {
842 IO.mapOptional(
"ExceptDoubleParentheses", Spaces.ExceptDoubleParentheses);
843 IO.mapOptional(
"InCStyleCasts", Spaces.InCStyleCasts);
844 IO.mapOptional(
"InConditionalStatements", Spaces.InConditionalStatements);
845 IO.mapOptional(
"InEmptyParentheses", Spaces.InEmptyParentheses);
846 IO.mapOptional(
"Other", Spaces.Other);
850template <>
struct ScalarEnumerationTraits<FormatStyle::SpacesInParensStyle> {
852 IO.enumCase(
Value,
"Never", FormatStyle::SIPO_Never);
853 IO.enumCase(
Value,
"Custom", FormatStyle::SIPO_Custom);
857template <>
struct ScalarEnumerationTraits<FormatStyle::TrailingCommaStyle> {
859 IO.enumCase(
Value,
"None", FormatStyle::TCS_None);
860 IO.enumCase(
Value,
"Wrapped", FormatStyle::TCS_Wrapped);
865struct ScalarEnumerationTraits<FormatStyle::TrailingCommentsAlignmentKinds> {
867 FormatStyle::TrailingCommentsAlignmentKinds &
Value) {
868 IO.enumCase(
Value,
"Leave", FormatStyle::TCAS_Leave);
869 IO.enumCase(
Value,
"Always", FormatStyle::TCAS_Always);
870 IO.enumCase(
Value,
"Never", FormatStyle::TCAS_Never);
874template <>
struct MappingTraits<FormatStyle::TrailingCommentsAlignmentStyle> {
876 FormatStyle::TrailingCommentsAlignmentStyle &
Value) {
877 IO.enumCase(
Value,
"Leave",
878 FormatStyle::TrailingCommentsAlignmentStyle(
879 {FormatStyle::TCAS_Leave, 0}));
881 IO.enumCase(
Value,
"Always",
882 FormatStyle::TrailingCommentsAlignmentStyle(
883 {FormatStyle::TCAS_Always, 0}));
885 IO.enumCase(
Value,
"Never",
886 FormatStyle::TrailingCommentsAlignmentStyle(
887 {FormatStyle::TCAS_Never, 0}));
890 IO.enumCase(
Value,
"true",
891 FormatStyle::TrailingCommentsAlignmentStyle(
892 {FormatStyle::TCAS_Always, 0}));
893 IO.enumCase(
Value,
"false",
894 FormatStyle::TrailingCommentsAlignmentStyle(
895 {FormatStyle::TCAS_Never, 0}));
899 FormatStyle::TrailingCommentsAlignmentStyle &
Value) {
900 IO.mapOptional(
"Kind",
Value.Kind);
901 IO.mapOptional(
"OverEmptyLines",
Value.OverEmptyLines);
905template <>
struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
907 IO.enumCase(
Value,
"Never", FormatStyle::UT_Never);
908 IO.enumCase(
Value,
"false", FormatStyle::UT_Never);
909 IO.enumCase(
Value,
"Always", FormatStyle::UT_Always);
910 IO.enumCase(
Value,
"true", FormatStyle::UT_Always);
911 IO.enumCase(
Value,
"ForIndentation", FormatStyle::UT_ForIndentation);
912 IO.enumCase(
Value,
"ForContinuationAndIndentation",
913 FormatStyle::UT_ForContinuationAndIndentation);
914 IO.enumCase(
Value,
"AlignWithSpaces", FormatStyle::UT_AlignWithSpaces);
919struct ScalarEnumerationTraits<
920 FormatStyle::WrapNamespaceBodyWithEmptyLinesStyle> {
923 FormatStyle::WrapNamespaceBodyWithEmptyLinesStyle &
Value) {
924 IO.enumCase(
Value,
"Never", FormatStyle::WNBWELS_Never);
925 IO.enumCase(
Value,
"Always", FormatStyle::WNBWELS_Always);
926 IO.enumCase(
Value,
"Leave", FormatStyle::WNBWELS_Leave);
930template <>
struct MappingTraits<FormatStyle> {
931 static void mapping(IO &IO, FormatStyle &Style) {
933 IO.mapOptional(
"Language", Style.Language);
935 StringRef BasedOnStyle;
936 if (IO.outputting()) {
937 StringRef Styles[] = {
"LLVM",
"Google",
"Chromium",
"Mozilla",
938 "WebKit",
"GNU",
"Microsoft",
"clang-format"};
939 for (StringRef StyleName : Styles) {
940 FormatStyle PredefinedStyle;
942 Style == PredefinedStyle) {
943 BasedOnStyle = StyleName;
948 IO.mapOptional(
"BasedOnStyle", BasedOnStyle);
949 if (!BasedOnStyle.empty()) {
950 FormatStyle::LanguageKind OldLanguage = Style.Language;
951 FormatStyle::LanguageKind Language =
952 ((FormatStyle *)IO.getContext())->Language;
954 IO.setError(Twine(
"Unknown value for BasedOnStyle: ", BasedOnStyle));
957 Style.Language = OldLanguage;
972 const bool IsGoogleOrChromium = BasedOnStyle.equals_insensitive(
"google") ||
973 BasedOnStyle.equals_insensitive(
"chromium");
974 bool OnCurrentLine = IsGoogleOrChromium;
975 bool OnNextLine =
true;
977 bool BreakBeforeInheritanceComma =
false;
978 bool BreakConstructorInitializersBeforeComma =
false;
980 bool DeriveLineEnding =
true;
981 bool UseCRLF =
false;
983 bool SpaceInEmptyBlock =
false;
984 bool SpaceInEmptyParentheses =
false;
985 bool SpacesInConditionalStatement =
false;
986 bool SpacesInCStyleCastParentheses =
false;
987 bool SpacesInParentheses =
false;
989 if (IO.outputting()) {
990 IO.mapOptional(
"AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
994 if (IsGoogleOrChromium) {
995 FormatStyle::LanguageKind Language = Style.Language;
996 if (Language == FormatStyle::LK_None)
997 Language = ((FormatStyle *)IO.getContext())->Language;
998 if (Language == FormatStyle::LK_JavaScript)
1000 else if (Language == FormatStyle::LK_Java)
1002 }
else if (BasedOnStyle.equals_insensitive(
"webkit")) {
1005 IO.mapOptional(
"AlignAfterOpenBracket", LocalBAS);
1006 Style.BreakAfterOpenBracketBracedList =
false;
1007 Style.BreakAfterOpenBracketFunction =
false;
1008 Style.BreakAfterOpenBracketIf =
false;
1009 Style.BreakAfterOpenBracketLoop =
false;
1010 Style.BreakAfterOpenBracketSwitch =
false;
1011 Style.BreakBeforeCloseBracketBracedList =
false;
1012 Style.BreakBeforeCloseBracketFunction =
false;
1013 Style.BreakBeforeCloseBracketIf =
false;
1014 Style.BreakBeforeCloseBracketLoop =
false;
1015 Style.BreakBeforeCloseBracketSwitch =
false;
1019 Style.AlignAfterOpenBracket =
false;
1022 Style.BreakBeforeCloseBracketBracedList =
true;
1023 Style.BreakBeforeCloseBracketFunction =
true;
1024 Style.BreakBeforeCloseBracketIf =
true;
1027 Style.BreakAfterOpenBracketBracedList =
true;
1028 Style.BreakAfterOpenBracketFunction =
true;
1029 Style.BreakAfterOpenBracketIf =
true;
1032 Style.AlignAfterOpenBracket =
true;
1038 if (!IO.outputting()) {
1039 IO.mapOptional(
"AlignEscapedNewlinesLeft", Style.AlignEscapedNewlines);
1040 IO.mapOptional(
"AllowAllConstructorInitializersOnNextLine", OnNextLine);
1041 IO.mapOptional(
"AlwaysBreakAfterReturnType", Style.BreakAfterReturnType);
1042 IO.mapOptional(
"AlwaysBreakTemplateDeclarations",
1043 Style.BreakTemplateDeclarations);
1044 IO.mapOptional(
"BreakBeforeInheritanceComma",
1045 BreakBeforeInheritanceComma);
1046 IO.mapOptional(
"BreakConstructorInitializersBeforeComma",
1047 BreakConstructorInitializersBeforeComma);
1048 IO.mapOptional(
"ConstructorInitializerAllOnOneLineOrOnePerLine",
1050 IO.mapOptional(
"DeriveLineEnding", DeriveLineEnding);
1051 IO.mapOptional(
"DerivePointerBinding", Style.DerivePointerAlignment);
1052 IO.mapOptional(
"KeepEmptyLinesAtEOF", Style.KeepEmptyLines.AtEndOfFile);
1053 IO.mapOptional(
"KeepEmptyLinesAtTheStartOfBlocks",
1054 Style.KeepEmptyLines.AtStartOfBlock);
1055 IO.mapOptional(
"IndentFunctionDeclarationAfterType",
1056 Style.IndentWrappedFunctionNames);
1057 IO.mapOptional(
"IndentRequires", Style.IndentRequiresClause);
1058 IO.mapOptional(
"PointerBindsToType", Style.PointerAlignment);
1059 IO.mapOptional(
"SpaceAfterControlStatementKeyword",
1060 Style.SpaceBeforeParens);
1061 IO.mapOptional(
"SpaceInEmptyBlock", SpaceInEmptyBlock);
1062 IO.mapOptional(
"SpaceInEmptyParentheses", SpaceInEmptyParentheses);
1063 IO.mapOptional(
"SpacesInConditionalStatement",
1064 SpacesInConditionalStatement);
1065 IO.mapOptional(
"SpacesInCStyleCastParentheses",
1066 SpacesInCStyleCastParentheses);
1067 IO.mapOptional(
"SpacesInParentheses", SpacesInParentheses);
1068 IO.mapOptional(
"UseCRLF", UseCRLF);
1071 IO.mapOptional(
"AccessModifierOffset", Style.AccessModifierOffset);
1072 IO.mapOptional(
"AlignArrayOfStructures", Style.AlignArrayOfStructures);
1073 IO.mapOptional(
"AlignConsecutiveAssignments",
1074 Style.AlignConsecutiveAssignments);
1075 IO.mapOptional(
"AlignConsecutiveBitFields",
1076 Style.AlignConsecutiveBitFields);
1077 IO.mapOptional(
"AlignConsecutiveDeclarations",
1078 Style.AlignConsecutiveDeclarations);
1079 IO.mapOptional(
"AlignConsecutiveMacros", Style.AlignConsecutiveMacros);
1080 IO.mapOptional(
"AlignConsecutiveShortCaseStatements",
1081 Style.AlignConsecutiveShortCaseStatements);
1082 IO.mapOptional(
"AlignConsecutiveTableGenBreakingDAGArgColons",
1083 Style.AlignConsecutiveTableGenBreakingDAGArgColons);
1084 IO.mapOptional(
"AlignConsecutiveTableGenCondOperatorColons",
1085 Style.AlignConsecutiveTableGenCondOperatorColons);
1086 IO.mapOptional(
"AlignConsecutiveTableGenDefinitionColons",
1087 Style.AlignConsecutiveTableGenDefinitionColons);
1088 IO.mapOptional(
"AlignEscapedNewlines", Style.AlignEscapedNewlines);
1089 IO.mapOptional(
"AlignOperands", Style.AlignOperands);
1090 IO.mapOptional(
"AlignTrailingComments", Style.AlignTrailingComments);
1091 IO.mapOptional(
"AllowAllArgumentsOnNextLine",
1092 Style.AllowAllArgumentsOnNextLine);
1093 IO.mapOptional(
"AllowAllParametersOfDeclarationOnNextLine",
1094 Style.AllowAllParametersOfDeclarationOnNextLine);
1095 IO.mapOptional(
"AllowBreakBeforeNoexceptSpecifier",
1096 Style.AllowBreakBeforeNoexceptSpecifier);
1097 IO.mapOptional(
"AllowBreakBeforeQtProperty",
1098 Style.AllowBreakBeforeQtProperty);
1099 IO.mapOptional(
"AllowShortBlocksOnASingleLine",
1100 Style.AllowShortBlocksOnASingleLine);
1101 IO.mapOptional(
"AllowShortCaseExpressionOnASingleLine",
1102 Style.AllowShortCaseExpressionOnASingleLine);
1103 IO.mapOptional(
"AllowShortCaseLabelsOnASingleLine",
1104 Style.AllowShortCaseLabelsOnASingleLine);
1105 IO.mapOptional(
"AllowShortCompoundRequirementOnASingleLine",
1106 Style.AllowShortCompoundRequirementOnASingleLine);
1107 IO.mapOptional(
"AllowShortEnumsOnASingleLine",
1108 Style.AllowShortEnumsOnASingleLine);
1109 IO.mapOptional(
"AllowShortFunctionsOnASingleLine",
1110 Style.AllowShortFunctionsOnASingleLine);
1111 IO.mapOptional(
"AllowShortIfStatementsOnASingleLine",
1112 Style.AllowShortIfStatementsOnASingleLine);
1113 IO.mapOptional(
"AllowShortLambdasOnASingleLine",
1114 Style.AllowShortLambdasOnASingleLine);
1115 IO.mapOptional(
"AllowShortLoopsOnASingleLine",
1116 Style.AllowShortLoopsOnASingleLine);
1117 IO.mapOptional(
"AllowShortNamespacesOnASingleLine",
1118 Style.AllowShortNamespacesOnASingleLine);
1119 IO.mapOptional(
"AlwaysBreakAfterDefinitionReturnType",
1120 Style.AlwaysBreakAfterDefinitionReturnType);
1121 IO.mapOptional(
"AlwaysBreakBeforeMultilineStrings",
1122 Style.AlwaysBreakBeforeMultilineStrings);
1123 IO.mapOptional(
"AttributeMacros", Style.AttributeMacros);
1124 IO.mapOptional(
"BinPackArguments", Style.BinPackArguments);
1125 IO.mapOptional(
"BinPackLongBracedList", Style.BinPackLongBracedList);
1126 IO.mapOptional(
"BinPackParameters", Style.BinPackParameters);
1127 IO.mapOptional(
"BitFieldColonSpacing", Style.BitFieldColonSpacing);
1128 IO.mapOptional(
"BracedInitializerIndentWidth",
1129 Style.BracedInitializerIndentWidth);
1130 IO.mapOptional(
"BraceWrapping", Style.BraceWrapping);
1131 IO.mapOptional(
"BreakAdjacentStringLiterals",
1132 Style.BreakAdjacentStringLiterals);
1133 IO.mapOptional(
"BreakAfterAttributes", Style.BreakAfterAttributes);
1134 IO.mapOptional(
"BreakAfterJavaFieldAnnotations",
1135 Style.BreakAfterJavaFieldAnnotations);
1136 IO.mapOptional(
"BreakAfterOpenBracketBracedList",
1137 Style.BreakAfterOpenBracketBracedList);
1138 IO.mapOptional(
"BreakAfterOpenBracketFunction",
1139 Style.BreakAfterOpenBracketFunction);
1140 IO.mapOptional(
"BreakAfterOpenBracketIf", Style.BreakAfterOpenBracketIf);
1141 IO.mapOptional(
"BreakAfterOpenBracketLoop",
1142 Style.BreakAfterOpenBracketLoop);
1143 IO.mapOptional(
"BreakAfterOpenBracketSwitch",
1144 Style.BreakAfterOpenBracketSwitch);
1145 IO.mapOptional(
"BreakAfterReturnType", Style.BreakAfterReturnType);
1146 IO.mapOptional(
"BreakArrays", Style.BreakArrays);
1147 IO.mapOptional(
"BreakBeforeBinaryOperators",
1148 Style.BreakBeforeBinaryOperators);
1149 IO.mapOptional(
"BreakBeforeCloseBracketBracedList",
1150 Style.BreakBeforeCloseBracketBracedList);
1151 IO.mapOptional(
"BreakBeforeCloseBracketFunction",
1152 Style.BreakBeforeCloseBracketFunction);
1153 IO.mapOptional(
"BreakBeforeCloseBracketIf",
1154 Style.BreakBeforeCloseBracketIf);
1155 IO.mapOptional(
"BreakBeforeCloseBracketLoop",
1156 Style.BreakBeforeCloseBracketLoop);
1157 IO.mapOptional(
"BreakBeforeCloseBracketSwitch",
1158 Style.BreakBeforeCloseBracketSwitch);
1159 IO.mapOptional(
"BreakBeforeConceptDeclarations",
1160 Style.BreakBeforeConceptDeclarations);
1161 IO.mapOptional(
"BreakBeforeBraces", Style.BreakBeforeBraces);
1162 IO.mapOptional(
"BreakBeforeInlineASMColon",
1163 Style.BreakBeforeInlineASMColon);
1164 IO.mapOptional(
"BreakBeforeTemplateCloser",
1165 Style.BreakBeforeTemplateCloser);
1166 IO.mapOptional(
"BreakBeforeTernaryOperators",
1167 Style.BreakBeforeTernaryOperators);
1168 IO.mapOptional(
"BreakBinaryOperations", Style.BreakBinaryOperations);
1169 IO.mapOptional(
"BreakConstructorInitializers",
1170 Style.BreakConstructorInitializers);
1171 IO.mapOptional(
"BreakFunctionDefinitionParameters",
1172 Style.BreakFunctionDefinitionParameters);
1173 IO.mapOptional(
"BreakInheritanceList", Style.BreakInheritanceList);
1174 IO.mapOptional(
"BreakStringLiterals", Style.BreakStringLiterals);
1175 IO.mapOptional(
"BreakTemplateDeclarations",
1176 Style.BreakTemplateDeclarations);
1177 IO.mapOptional(
"ColumnLimit", Style.ColumnLimit);
1178 IO.mapOptional(
"CommentPragmas", Style.CommentPragmas);
1179 IO.mapOptional(
"CompactNamespaces", Style.CompactNamespaces);
1180 IO.mapOptional(
"ConstructorInitializerIndentWidth",
1181 Style.ConstructorInitializerIndentWidth);
1182 IO.mapOptional(
"ContinuationIndentWidth", Style.ContinuationIndentWidth);
1183 IO.mapOptional(
"Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
1184 IO.mapOptional(
"DerivePointerAlignment", Style.DerivePointerAlignment);
1185 IO.mapOptional(
"DisableFormat", Style.DisableFormat);
1186 IO.mapOptional(
"EmptyLineAfterAccessModifier",
1187 Style.EmptyLineAfterAccessModifier);
1188 IO.mapOptional(
"EmptyLineBeforeAccessModifier",
1189 Style.EmptyLineBeforeAccessModifier);
1190 IO.mapOptional(
"EnumTrailingComma", Style.EnumTrailingComma);
1191 IO.mapOptional(
"ExperimentalAutoDetectBinPacking",
1192 Style.ExperimentalAutoDetectBinPacking);
1193 IO.mapOptional(
"FixNamespaceComments", Style.FixNamespaceComments);
1194 IO.mapOptional(
"ForEachMacros", Style.ForEachMacros);
1195 IO.mapOptional(
"IfMacros", Style.IfMacros);
1196 IO.mapOptional(
"IncludeBlocks", Style.IncludeStyle.IncludeBlocks);
1197 IO.mapOptional(
"IncludeCategories", Style.IncludeStyle.IncludeCategories);
1198 IO.mapOptional(
"IncludeIsMainRegex", Style.IncludeStyle.IncludeIsMainRegex);
1199 IO.mapOptional(
"IncludeIsMainSourceRegex",
1200 Style.IncludeStyle.IncludeIsMainSourceRegex);
1201 IO.mapOptional(
"IndentAccessModifiers", Style.IndentAccessModifiers);
1202 IO.mapOptional(
"IndentCaseBlocks", Style.IndentCaseBlocks);
1203 IO.mapOptional(
"IndentCaseLabels", Style.IndentCaseLabels);
1204 IO.mapOptional(
"IndentExportBlock", Style.IndentExportBlock);
1205 IO.mapOptional(
"IndentExternBlock", Style.IndentExternBlock);
1206 IO.mapOptional(
"IndentGotoLabels", Style.IndentGotoLabels);
1207 IO.mapOptional(
"IndentPPDirectives", Style.IndentPPDirectives);
1208 IO.mapOptional(
"IndentRequiresClause", Style.IndentRequiresClause);
1209 IO.mapOptional(
"IndentWidth", Style.IndentWidth);
1210 IO.mapOptional(
"IndentWrappedFunctionNames",
1211 Style.IndentWrappedFunctionNames);
1212 IO.mapOptional(
"InsertBraces", Style.InsertBraces);
1213 IO.mapOptional(
"InsertNewlineAtEOF", Style.InsertNewlineAtEOF);
1214 IO.mapOptional(
"InsertTrailingCommas", Style.InsertTrailingCommas);
1215 IO.mapOptional(
"IntegerLiteralSeparator", Style.IntegerLiteralSeparator);
1216 IO.mapOptional(
"JavaImportGroups", Style.JavaImportGroups);
1217 IO.mapOptional(
"JavaScriptQuotes", Style.JavaScriptQuotes);
1218 IO.mapOptional(
"JavaScriptWrapImports", Style.JavaScriptWrapImports);
1219 IO.mapOptional(
"KeepEmptyLines", Style.KeepEmptyLines);
1220 IO.mapOptional(
"KeepFormFeed", Style.KeepFormFeed);
1221 IO.mapOptional(
"LambdaBodyIndentation", Style.LambdaBodyIndentation);
1222 IO.mapOptional(
"LineEnding", Style.LineEnding);
1223 IO.mapOptional(
"MacroBlockBegin", Style.MacroBlockBegin);
1224 IO.mapOptional(
"MacroBlockEnd", Style.MacroBlockEnd);
1225 IO.mapOptional(
"Macros", Style.Macros);
1226 IO.mapOptional(
"MacrosSkippedByRemoveParentheses",
1227 Style.MacrosSkippedByRemoveParentheses);
1228 IO.mapOptional(
"MainIncludeChar", Style.IncludeStyle.MainIncludeChar);
1229 IO.mapOptional(
"MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
1230 IO.mapOptional(
"NamespaceIndentation", Style.NamespaceIndentation);
1231 IO.mapOptional(
"NamespaceMacros", Style.NamespaceMacros);
1232 IO.mapOptional(
"NumericLiteralCase", Style.NumericLiteralCase);
1233 IO.mapOptional(
"ObjCBinPackProtocolList", Style.ObjCBinPackProtocolList);
1234 IO.mapOptional(
"ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
1235 IO.mapOptional(
"ObjCBreakBeforeNestedBlockParam",
1236 Style.ObjCBreakBeforeNestedBlockParam);
1237 IO.mapOptional(
"ObjCPropertyAttributeOrder",
1238 Style.ObjCPropertyAttributeOrder);
1239 IO.mapOptional(
"ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
1240 IO.mapOptional(
"ObjCSpaceBeforeProtocolList",
1241 Style.ObjCSpaceBeforeProtocolList);
1242 IO.mapOptional(
"OneLineFormatOffRegex", Style.OneLineFormatOffRegex);
1243 IO.mapOptional(
"PackConstructorInitializers",
1244 Style.PackConstructorInitializers);
1245 IO.mapOptional(
"PenaltyBreakAssignment", Style.PenaltyBreakAssignment);
1246 IO.mapOptional(
"PenaltyBreakBeforeFirstCallParameter",
1247 Style.PenaltyBreakBeforeFirstCallParameter);
1248 IO.mapOptional(
"PenaltyBreakBeforeMemberAccess",
1249 Style.PenaltyBreakBeforeMemberAccess);
1250 IO.mapOptional(
"PenaltyBreakComment", Style.PenaltyBreakComment);
1251 IO.mapOptional(
"PenaltyBreakFirstLessLess",
1252 Style.PenaltyBreakFirstLessLess);
1253 IO.mapOptional(
"PenaltyBreakOpenParenthesis",
1254 Style.PenaltyBreakOpenParenthesis);
1255 IO.mapOptional(
"PenaltyBreakScopeResolution",
1256 Style.PenaltyBreakScopeResolution);
1257 IO.mapOptional(
"PenaltyBreakString", Style.PenaltyBreakString);
1258 IO.mapOptional(
"PenaltyBreakTemplateDeclaration",
1259 Style.PenaltyBreakTemplateDeclaration);
1260 IO.mapOptional(
"PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
1261 IO.mapOptional(
"PenaltyIndentedWhitespace",
1262 Style.PenaltyIndentedWhitespace);
1263 IO.mapOptional(
"PenaltyReturnTypeOnItsOwnLine",
1264 Style.PenaltyReturnTypeOnItsOwnLine);
1265 IO.mapOptional(
"PointerAlignment", Style.PointerAlignment);
1266 IO.mapOptional(
"PPIndentWidth", Style.PPIndentWidth);
1267 IO.mapOptional(
"QualifierAlignment", Style.QualifierAlignment);
1269 if (Style.QualifierAlignment == FormatStyle::QAS_Right)
1270 Style.QualifierOrder = {
"type",
"const",
"volatile"};
1271 else if (Style.QualifierAlignment == FormatStyle::QAS_Left)
1272 Style.QualifierOrder = {
"const",
"volatile",
"type"};
1273 else if (Style.QualifierAlignment == FormatStyle::QAS_Custom)
1274 IO.mapOptional(
"QualifierOrder", Style.QualifierOrder);
1275 IO.mapOptional(
"RawStringFormats", Style.RawStringFormats);
1276 IO.mapOptional(
"ReferenceAlignment", Style.ReferenceAlignment);
1277 IO.mapOptional(
"ReflowComments", Style.ReflowComments);
1278 IO.mapOptional(
"RemoveBracesLLVM", Style.RemoveBracesLLVM);
1279 IO.mapOptional(
"RemoveEmptyLinesInUnwrappedLines",
1280 Style.RemoveEmptyLinesInUnwrappedLines);
1281 IO.mapOptional(
"RemoveParentheses", Style.RemoveParentheses);
1282 IO.mapOptional(
"RemoveSemicolon", Style.RemoveSemicolon);
1283 IO.mapOptional(
"RequiresClausePosition", Style.RequiresClausePosition);
1284 IO.mapOptional(
"RequiresExpressionIndentation",
1285 Style.RequiresExpressionIndentation);
1286 IO.mapOptional(
"SeparateDefinitionBlocks", Style.SeparateDefinitionBlocks);
1287 IO.mapOptional(
"ShortNamespaceLines", Style.ShortNamespaceLines);
1288 IO.mapOptional(
"SkipMacroDefinitionBody", Style.SkipMacroDefinitionBody);
1289 IO.mapOptional(
"SortIncludes", Style.SortIncludes);
1290 IO.mapOptional(
"SortJavaStaticImport", Style.SortJavaStaticImport);
1291 IO.mapOptional(
"SortUsingDeclarations", Style.SortUsingDeclarations);
1292 IO.mapOptional(
"SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
1293 IO.mapOptional(
"SpaceAfterLogicalNot", Style.SpaceAfterLogicalNot);
1294 IO.mapOptional(
"SpaceAfterOperatorKeyword",
1295 Style.SpaceAfterOperatorKeyword);
1296 IO.mapOptional(
"SpaceAfterTemplateKeyword",
1297 Style.SpaceAfterTemplateKeyword);
1298 IO.mapOptional(
"SpaceAroundPointerQualifiers",
1299 Style.SpaceAroundPointerQualifiers);
1300 IO.mapOptional(
"SpaceBeforeAssignmentOperators",
1301 Style.SpaceBeforeAssignmentOperators);
1302 IO.mapOptional(
"SpaceBeforeCaseColon", Style.SpaceBeforeCaseColon);
1303 IO.mapOptional(
"SpaceBeforeCpp11BracedList",
1304 Style.SpaceBeforeCpp11BracedList);
1305 IO.mapOptional(
"SpaceBeforeCtorInitializerColon",
1306 Style.SpaceBeforeCtorInitializerColon);
1307 IO.mapOptional(
"SpaceBeforeInheritanceColon",
1308 Style.SpaceBeforeInheritanceColon);
1309 IO.mapOptional(
"SpaceBeforeJsonColon", Style.SpaceBeforeJsonColon);
1310 IO.mapOptional(
"SpaceBeforeParens", Style.SpaceBeforeParens);
1311 IO.mapOptional(
"SpaceBeforeParensOptions", Style.SpaceBeforeParensOptions);
1312 IO.mapOptional(
"SpaceBeforeRangeBasedForLoopColon",
1313 Style.SpaceBeforeRangeBasedForLoopColon);
1314 IO.mapOptional(
"SpaceBeforeSquareBrackets",
1315 Style.SpaceBeforeSquareBrackets);
1316 IO.mapOptional(
"SpaceInEmptyBraces", Style.SpaceInEmptyBraces);
1317 IO.mapOptional(
"SpacesBeforeTrailingComments",
1318 Style.SpacesBeforeTrailingComments);
1319 IO.mapOptional(
"SpacesInAngles", Style.SpacesInAngles);
1320 IO.mapOptional(
"SpacesInContainerLiterals",
1321 Style.SpacesInContainerLiterals);
1322 IO.mapOptional(
"SpacesInLineCommentPrefix",
1323 Style.SpacesInLineCommentPrefix);
1324 IO.mapOptional(
"SpacesInParens", Style.SpacesInParens);
1325 IO.mapOptional(
"SpacesInParensOptions", Style.SpacesInParensOptions);
1326 IO.mapOptional(
"SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
1327 IO.mapOptional(
"Standard", Style.Standard);
1328 IO.mapOptional(
"StatementAttributeLikeMacros",
1329 Style.StatementAttributeLikeMacros);
1330 IO.mapOptional(
"StatementMacros", Style.StatementMacros);
1331 IO.mapOptional(
"TableGenBreakingDAGArgOperators",
1332 Style.TableGenBreakingDAGArgOperators);
1333 IO.mapOptional(
"TableGenBreakInsideDAGArg",
1334 Style.TableGenBreakInsideDAGArg);
1335 IO.mapOptional(
"TabWidth", Style.TabWidth);
1336 IO.mapOptional(
"TemplateNames", Style.TemplateNames);
1337 IO.mapOptional(
"TypeNames", Style.TypeNames);
1338 IO.mapOptional(
"TypenameMacros", Style.TypenameMacros);
1339 IO.mapOptional(
"UseTab", Style.UseTab);
1340 IO.mapOptional(
"VariableTemplates", Style.VariableTemplates);
1341 IO.mapOptional(
"VerilogBreakBetweenInstancePorts",
1342 Style.VerilogBreakBetweenInstancePorts);
1343 IO.mapOptional(
"WhitespaceSensitiveMacros",
1344 Style.WhitespaceSensitiveMacros);
1345 IO.mapOptional(
"WrapNamespaceBodyWithEmptyLines",
1346 Style.WrapNamespaceBodyWithEmptyLines);
1351 if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
1352 Style.BreakAfterReturnType == FormatStyle::RTBS_None) {
1353 if (Style.AlwaysBreakAfterDefinitionReturnType ==
1354 FormatStyle::DRTBS_All) {
1355 Style.BreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
1356 }
else if (Style.AlwaysBreakAfterDefinitionReturnType ==
1357 FormatStyle::DRTBS_TopLevel) {
1358 Style.BreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
1364 if (BreakBeforeInheritanceComma &&
1365 Style.BreakInheritanceList == FormatStyle::BILS_BeforeColon) {
1366 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
1372 if (BreakConstructorInitializersBeforeComma &&
1373 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon) {
1374 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
1377 if (!IsGoogleOrChromium) {
1378 if (Style.PackConstructorInitializers == FormatStyle::PCIS_BinPack &&
1380 Style.PackConstructorInitializers = OnNextLine
1381 ? FormatStyle::PCIS_NextLine
1382 : FormatStyle::PCIS_CurrentLine;
1384 }
else if (Style.PackConstructorInitializers ==
1385 FormatStyle::PCIS_NextLine) {
1387 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
1388 else if (!OnNextLine)
1389 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
1392 if (Style.LineEnding == FormatStyle::LE_DeriveLF) {
1393 if (!DeriveLineEnding)
1394 Style.LineEnding = UseCRLF ? FormatStyle::LE_CRLF : FormatStyle::LE_LF;
1396 Style.LineEnding = FormatStyle::LE_DeriveCRLF;
1401 if (SpaceInEmptyBlock &&
1402 Style.SpaceInEmptyBraces == FormatStyle::SIEB_Never) {
1403 Style.SpaceInEmptyBraces = FormatStyle::SIEB_Block;
1406 if (Style.SpacesInParens != FormatStyle::SIPO_Custom &&
1407 (SpacesInParentheses || SpaceInEmptyParentheses ||
1408 SpacesInConditionalStatement || SpacesInCStyleCastParentheses)) {
1409 if (SpacesInParentheses) {
1411 Style.SpacesInParensOptions.ExceptDoubleParentheses =
false;
1412 Style.SpacesInParensOptions.InConditionalStatements =
true;
1413 Style.SpacesInParensOptions.InCStyleCasts =
1414 SpacesInCStyleCastParentheses;
1415 Style.SpacesInParensOptions.InEmptyParentheses =
1416 SpaceInEmptyParentheses;
1417 Style.SpacesInParensOptions.Other =
true;
1419 Style.SpacesInParensOptions = {};
1420 Style.SpacesInParensOptions.InConditionalStatements =
1421 SpacesInConditionalStatement;
1422 Style.SpacesInParensOptions.InCStyleCasts =
1423 SpacesInCStyleCastParentheses;
1424 Style.SpacesInParensOptions.InEmptyParentheses =
1425 SpaceInEmptyParentheses;
1427 Style.SpacesInParens = FormatStyle::SIPO_Custom;
1437template <>
struct DocumentListTraits<
std::vector<FormatStyle>> {
1438 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
1441 static FormatStyle &
element(IO &IO, std::vector<FormatStyle> &Seq,
1443 if (Index >= Seq.size()) {
1444 assert(Index == Seq.size());
1445 FormatStyle Template;
1446 if (!Seq.empty() && Seq[0].Language == FormatStyle::LK_None) {
1449 Template = *((
const FormatStyle *)IO.getContext());
1450 Template.Language = FormatStyle::LK_None;
1452 Seq.resize(Index + 1, Template);
1472 return llvm::make_error<llvm::StringError>(Message,
1473 llvm::inconvertibleErrorCode());
1477 return "clang-format.parse_error";
1485 return "Invalid argument";
1487 return "Unsuitable";
1489 return "trailing comma insertion cannot be used with bin packing";
1491 return "Invalid qualifier specified in QualifierOrder";
1493 return "Duplicate qualifier specified in QualifierOrder";
1495 return "Missing type in QualifierOrder";
1497 return "Missing QualifierOrder";
1499 llvm_unreachable(
"unexpected parse error");
1503 if (Expanded.BreakBeforeBraces == FormatStyle::BS_Custom)
1505 Expanded.BraceWrapping = {
false,
1507 FormatStyle::BWACS_Never,
1523 switch (Expanded.BreakBeforeBraces) {
1524 case FormatStyle::BS_Linux:
1525 Expanded.BraceWrapping.AfterClass =
true;
1526 Expanded.BraceWrapping.AfterFunction =
true;
1527 Expanded.BraceWrapping.AfterNamespace =
true;
1529 case FormatStyle::BS_Mozilla:
1530 Expanded.BraceWrapping.AfterClass =
true;
1531 Expanded.BraceWrapping.AfterEnum =
true;
1532 Expanded.BraceWrapping.AfterFunction =
true;
1533 Expanded.BraceWrapping.AfterStruct =
true;
1534 Expanded.BraceWrapping.AfterUnion =
true;
1535 Expanded.BraceWrapping.AfterExternBlock =
true;
1536 Expanded.BraceWrapping.SplitEmptyFunction =
true;
1537 Expanded.BraceWrapping.SplitEmptyRecord =
false;
1539 case FormatStyle::BS_Stroustrup:
1540 Expanded.BraceWrapping.AfterFunction =
true;
1541 Expanded.BraceWrapping.BeforeCatch =
true;
1542 Expanded.BraceWrapping.BeforeElse =
true;
1544 case FormatStyle::BS_Allman:
1545 Expanded.BraceWrapping.AfterCaseLabel =
true;
1546 Expanded.BraceWrapping.AfterClass =
true;
1547 Expanded.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1548 Expanded.BraceWrapping.AfterEnum =
true;
1549 Expanded.BraceWrapping.AfterFunction =
true;
1550 Expanded.BraceWrapping.AfterNamespace =
true;
1551 Expanded.BraceWrapping.AfterObjCDeclaration =
true;
1552 Expanded.BraceWrapping.AfterStruct =
true;
1553 Expanded.BraceWrapping.AfterUnion =
true;
1554 Expanded.BraceWrapping.AfterExternBlock =
true;
1555 Expanded.BraceWrapping.BeforeCatch =
true;
1556 Expanded.BraceWrapping.BeforeElse =
true;
1557 Expanded.BraceWrapping.BeforeLambdaBody =
true;
1559 case FormatStyle::BS_Whitesmiths:
1560 Expanded.BraceWrapping.AfterCaseLabel =
true;
1561 Expanded.BraceWrapping.AfterClass =
true;
1562 Expanded.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1563 Expanded.BraceWrapping.AfterEnum =
true;
1564 Expanded.BraceWrapping.AfterFunction =
true;
1565 Expanded.BraceWrapping.AfterNamespace =
true;
1566 Expanded.BraceWrapping.AfterObjCDeclaration =
true;
1567 Expanded.BraceWrapping.AfterStruct =
true;
1568 Expanded.BraceWrapping.AfterExternBlock =
true;
1569 Expanded.BraceWrapping.BeforeCatch =
true;
1570 Expanded.BraceWrapping.BeforeElse =
true;
1571 Expanded.BraceWrapping.BeforeLambdaBody =
true;
1573 case FormatStyle::BS_GNU:
1574 Expanded.BraceWrapping = {
1577 FormatStyle::BWACS_Always,
1594 case FormatStyle::BS_WebKit:
1595 Expanded.BraceWrapping.AfterFunction =
true;
1603 if (Expanded.SpaceBeforeParens == FormatStyle::SBPO_Custom)
1606 Expanded.SpaceBeforeParensOptions = {};
1607 Expanded.SpaceBeforeParensOptions.AfterPlacementOperator =
true;
1609 switch (Expanded.SpaceBeforeParens) {
1610 case FormatStyle::SBPO_ControlStatements:
1611 Expanded.SpaceBeforeParensOptions.AfterControlStatements =
true;
1612 Expanded.SpaceBeforeParensOptions.AfterForeachMacros =
true;
1613 Expanded.SpaceBeforeParensOptions.AfterIfMacros =
true;
1615 case FormatStyle::SBPO_ControlStatementsExceptControlMacros:
1616 Expanded.SpaceBeforeParensOptions.AfterControlStatements =
true;
1618 case FormatStyle::SBPO_NonEmptyParentheses:
1619 Expanded.SpaceBeforeParensOptions.BeforeNonEmptyParentheses =
true;
1627 if (Expanded.SpacesInParens == FormatStyle::SIPO_Custom)
1629 assert(Expanded.SpacesInParens == FormatStyle::SIPO_Never);
1631 Expanded.SpacesInParensOptions = {};
1635 FormatStyle LLVMStyle;
1636 LLVMStyle.AccessModifierOffset = -2;
1637 LLVMStyle.AlignAfterOpenBracket =
true;
1638 LLVMStyle.AlignArrayOfStructures = FormatStyle::AIAS_None;
1639 LLVMStyle.AlignConsecutiveAssignments = {};
1640 LLVMStyle.AlignConsecutiveAssignments.PadOperators =
true;
1641 LLVMStyle.AlignConsecutiveBitFields = {};
1642 LLVMStyle.AlignConsecutiveDeclarations = {};
1643 LLVMStyle.AlignConsecutiveDeclarations.AlignFunctionDeclarations =
true;
1644 LLVMStyle.AlignConsecutiveMacros = {};
1645 LLVMStyle.AlignConsecutiveShortCaseStatements = {};
1646 LLVMStyle.AlignConsecutiveTableGenBreakingDAGArgColons = {};
1647 LLVMStyle.AlignConsecutiveTableGenCondOperatorColons = {};
1648 LLVMStyle.AlignConsecutiveTableGenDefinitionColons = {};
1649 LLVMStyle.AlignEscapedNewlines = FormatStyle::ENAS_Right;
1650 LLVMStyle.AlignOperands = FormatStyle::OAS_Align;
1651 LLVMStyle.AlignTrailingComments = {};
1652 LLVMStyle.AlignTrailingComments.Kind = FormatStyle::TCAS_Always;
1653 LLVMStyle.AlignTrailingComments.OverEmptyLines = 0;
1654 LLVMStyle.AllowAllArgumentsOnNextLine =
true;
1655 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine =
true;
1656 LLVMStyle.AllowBreakBeforeNoexceptSpecifier = FormatStyle::BBNSS_Never;
1657 LLVMStyle.AllowBreakBeforeQtProperty =
false;
1658 LLVMStyle.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
1659 LLVMStyle.AllowShortCaseExpressionOnASingleLine =
true;
1660 LLVMStyle.AllowShortCaseLabelsOnASingleLine =
false;
1661 LLVMStyle.AllowShortCompoundRequirementOnASingleLine =
true;
1662 LLVMStyle.AllowShortEnumsOnASingleLine =
true;
1663 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
1664 LLVMStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
1665 LLVMStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
1666 LLVMStyle.AllowShortLoopsOnASingleLine =
false;
1667 LLVMStyle.AllowShortNamespacesOnASingleLine =
false;
1668 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
1669 LLVMStyle.AlwaysBreakBeforeMultilineStrings =
false;
1670 LLVMStyle.AttributeMacros.push_back(
"__capability");
1671 LLVMStyle.BinPackArguments =
true;
1672 LLVMStyle.BinPackLongBracedList =
true;
1673 LLVMStyle.BinPackParameters = FormatStyle::BPPS_BinPack;
1674 LLVMStyle.BitFieldColonSpacing = FormatStyle::BFCS_Both;
1675 LLVMStyle.BracedInitializerIndentWidth = -1;
1676 LLVMStyle.BraceWrapping = {
false,
1678 FormatStyle::BWACS_Never,
1694 LLVMStyle.BreakAdjacentStringLiterals =
true;
1695 LLVMStyle.BreakAfterAttributes = FormatStyle::ABS_Leave;
1696 LLVMStyle.BreakAfterJavaFieldAnnotations =
false;
1697 LLVMStyle.BreakAfterOpenBracketBracedList =
false;
1698 LLVMStyle.BreakAfterOpenBracketFunction =
false;
1699 LLVMStyle.BreakAfterOpenBracketIf =
false;
1700 LLVMStyle.BreakAfterOpenBracketLoop =
false;
1701 LLVMStyle.BreakAfterOpenBracketSwitch =
false;
1702 LLVMStyle.BreakAfterReturnType = FormatStyle::RTBS_None;
1703 LLVMStyle.BreakArrays =
true;
1704 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
1705 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
1706 LLVMStyle.BreakBeforeCloseBracketBracedList =
false;
1707 LLVMStyle.BreakBeforeCloseBracketFunction =
false;
1708 LLVMStyle.BreakBeforeCloseBracketIf =
false;
1709 LLVMStyle.BreakBeforeCloseBracketLoop =
false;
1710 LLVMStyle.BreakBeforeCloseBracketSwitch =
false;
1711 LLVMStyle.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Always;
1712 LLVMStyle.BreakBeforeInlineASMColon = FormatStyle::BBIAS_OnlyMultiline;
1713 LLVMStyle.BreakBeforeTemplateCloser =
false;
1714 LLVMStyle.BreakBeforeTernaryOperators =
true;
1715 LLVMStyle.BreakBinaryOperations = FormatStyle::BBO_Never;
1716 LLVMStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
1717 LLVMStyle.BreakFunctionDefinitionParameters =
false;
1718 LLVMStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
1719 LLVMStyle.BreakStringLiterals =
true;
1720 LLVMStyle.BreakTemplateDeclarations = FormatStyle::BTDS_MultiLine;
1721 LLVMStyle.ColumnLimit = 80;
1722 LLVMStyle.CommentPragmas =
"^ IWYU pragma:";
1723 LLVMStyle.CompactNamespaces =
false;
1724 LLVMStyle.ConstructorInitializerIndentWidth = 4;
1725 LLVMStyle.ContinuationIndentWidth = 4;
1726 LLVMStyle.Cpp11BracedListStyle = FormatStyle::BLS_AlignFirstComment;
1727 LLVMStyle.DerivePointerAlignment =
false;
1728 LLVMStyle.DisableFormat =
false;
1729 LLVMStyle.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
1730 LLVMStyle.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
1731 LLVMStyle.EnumTrailingComma = FormatStyle::ETC_Leave;
1732 LLVMStyle.ExperimentalAutoDetectBinPacking =
false;
1733 LLVMStyle.FixNamespaceComments =
true;
1734 LLVMStyle.ForEachMacros.push_back(
"foreach");
1735 LLVMStyle.ForEachMacros.push_back(
"Q_FOREACH");
1736 LLVMStyle.ForEachMacros.push_back(
"BOOST_FOREACH");
1737 LLVMStyle.IfMacros.push_back(
"KJ_IF_MAYBE");
1739 LLVMStyle.IncludeStyle.IncludeCategories = {
1740 {
"^\"(llvm|llvm-c|clang|clang-c)/", 2, 0,
false},
1741 {
"^(<|\"(gtest|gmock|isl|json)/)", 3, 0,
false},
1742 {
".*", 1, 0,
false}};
1743 LLVMStyle.IncludeStyle.IncludeIsMainRegex =
"(Test)?$";
1744 LLVMStyle.IncludeStyle.MainIncludeChar = tooling::IncludeStyle::MICD_Quote;
1745 LLVMStyle.IndentAccessModifiers =
false;
1746 LLVMStyle.IndentCaseBlocks =
false;
1747 LLVMStyle.IndentCaseLabels =
false;
1748 LLVMStyle.IndentExportBlock =
true;
1749 LLVMStyle.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
1750 LLVMStyle.IndentGotoLabels =
true;
1751 LLVMStyle.IndentPPDirectives = FormatStyle::PPDIS_None;
1752 LLVMStyle.IndentRequiresClause =
true;
1753 LLVMStyle.IndentWidth = 2;
1754 LLVMStyle.IndentWrappedFunctionNames =
false;
1755 LLVMStyle.InheritsParentConfig =
false;
1756 LLVMStyle.InsertBraces =
false;
1757 LLVMStyle.InsertNewlineAtEOF =
false;
1758 LLVMStyle.InsertTrailingCommas = FormatStyle::TCS_None;
1759 LLVMStyle.IntegerLiteralSeparator = {
1763 LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
1764 LLVMStyle.JavaScriptWrapImports =
true;
1765 LLVMStyle.KeepEmptyLines = {
1770 LLVMStyle.KeepFormFeed =
false;
1771 LLVMStyle.LambdaBodyIndentation = FormatStyle::LBI_Signature;
1773 LLVMStyle.LineEnding = FormatStyle::LE_DeriveLF;
1774 LLVMStyle.MaxEmptyLinesToKeep = 1;
1775 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
1776 LLVMStyle.NumericLiteralCase = {FormatStyle::NLCS_Leave,
1777 FormatStyle::NLCS_Leave,
1778 FormatStyle::NLCS_Leave,
1779 FormatStyle::NLCS_Leave};
1780 LLVMStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Auto;
1781 LLVMStyle.ObjCBlockIndentWidth = 2;
1782 LLVMStyle.ObjCBreakBeforeNestedBlockParam =
true;
1783 LLVMStyle.ObjCSpaceAfterProperty =
false;
1784 LLVMStyle.ObjCSpaceBeforeProtocolList =
true;
1785 LLVMStyle.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
1786 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
1787 LLVMStyle.PPIndentWidth = -1;
1788 LLVMStyle.QualifierAlignment = FormatStyle::QAS_Leave;
1789 LLVMStyle.ReferenceAlignment = FormatStyle::RAS_Pointer;
1790 LLVMStyle.ReflowComments = FormatStyle::RCS_Always;
1791 LLVMStyle.RemoveBracesLLVM =
false;
1792 LLVMStyle.RemoveEmptyLinesInUnwrappedLines =
false;
1793 LLVMStyle.RemoveParentheses = FormatStyle::RPS_Leave;
1794 LLVMStyle.RemoveSemicolon =
false;
1795 LLVMStyle.RequiresClausePosition = FormatStyle::RCPS_OwnLine;
1796 LLVMStyle.RequiresExpressionIndentation = FormatStyle::REI_OuterScope;
1797 LLVMStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Leave;
1798 LLVMStyle.ShortNamespaceLines = 1;
1799 LLVMStyle.SkipMacroDefinitionBody =
false;
1800 LLVMStyle.SortIncludes = {
true,
false,
1802 LLVMStyle.SortJavaStaticImport = FormatStyle::SJSIO_Before;
1803 LLVMStyle.SortUsingDeclarations = FormatStyle::SUD_LexicographicNumeric;
1804 LLVMStyle.SpaceAfterCStyleCast =
false;
1805 LLVMStyle.SpaceAfterLogicalNot =
false;
1806 LLVMStyle.SpaceAfterOperatorKeyword =
false;
1807 LLVMStyle.SpaceAfterTemplateKeyword =
true;
1808 LLVMStyle.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
1809 LLVMStyle.SpaceBeforeAssignmentOperators =
true;
1810 LLVMStyle.SpaceBeforeCaseColon =
false;
1811 LLVMStyle.SpaceBeforeCpp11BracedList =
false;
1812 LLVMStyle.SpaceBeforeCtorInitializerColon =
true;
1813 LLVMStyle.SpaceBeforeInheritanceColon =
true;
1814 LLVMStyle.SpaceBeforeJsonColon =
false;
1815 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
1816 LLVMStyle.SpaceBeforeParensOptions = {};
1817 LLVMStyle.SpaceBeforeParensOptions.AfterControlStatements =
true;
1818 LLVMStyle.SpaceBeforeParensOptions.AfterForeachMacros =
true;
1819 LLVMStyle.SpaceBeforeParensOptions.AfterIfMacros =
true;
1820 LLVMStyle.SpaceBeforeRangeBasedForLoopColon =
true;
1821 LLVMStyle.SpaceBeforeSquareBrackets =
false;
1822 LLVMStyle.SpaceInEmptyBraces = FormatStyle::SIEB_Never;
1823 LLVMStyle.SpacesBeforeTrailingComments = 1;
1824 LLVMStyle.SpacesInAngles = FormatStyle::SIAS_Never;
1825 LLVMStyle.SpacesInContainerLiterals =
true;
1826 LLVMStyle.SpacesInLineCommentPrefix = {
1827 1, std::numeric_limits<unsigned>::max()};
1828 LLVMStyle.SpacesInParens = FormatStyle::SIPO_Never;
1829 LLVMStyle.SpacesInSquareBrackets =
false;
1830 LLVMStyle.Standard = FormatStyle::LS_Latest;
1831 LLVMStyle.StatementAttributeLikeMacros.push_back(
"Q_EMIT");
1832 LLVMStyle.StatementMacros.push_back(
"Q_UNUSED");
1833 LLVMStyle.StatementMacros.push_back(
"QT_REQUIRE_VERSION");
1834 LLVMStyle.TableGenBreakingDAGArgOperators = {};
1835 LLVMStyle.TableGenBreakInsideDAGArg = FormatStyle::DAS_DontBreak;
1836 LLVMStyle.TabWidth = 8;
1837 LLVMStyle.UseTab = FormatStyle::UT_Never;
1838 LLVMStyle.VerilogBreakBetweenInstancePorts =
true;
1839 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"BOOST_PP_STRINGIZE");
1840 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"CF_SWIFT_NAME");
1841 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"NS_SWIFT_NAME");
1842 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"PP_STRINGIZE");
1843 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"STRINGIZE");
1844 LLVMStyle.WrapNamespaceBodyWithEmptyLines = FormatStyle::WNBWELS_Leave;
1847 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
1848 LLVMStyle.PenaltyBreakBeforeMemberAccess = 150;
1849 LLVMStyle.PenaltyBreakComment = 300;
1850 LLVMStyle.PenaltyBreakFirstLessLess = 120;
1851 LLVMStyle.PenaltyBreakOpenParenthesis = 0;
1852 LLVMStyle.PenaltyBreakScopeResolution = 500;
1853 LLVMStyle.PenaltyBreakString = 1000;
1855 LLVMStyle.PenaltyExcessCharacter = 1'000'000;
1856 LLVMStyle.PenaltyIndentedWhitespace = 0;
1857 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
1861 case FormatStyle::LK_TableGen:
1862 LLVMStyle.SpacesInContainerLiterals =
false;
1864 case FormatStyle::LK_Json:
1865 LLVMStyle.ColumnLimit = 0;
1867 case FormatStyle::LK_Verilog:
1868 LLVMStyle.IndentCaseLabels =
true;
1869 LLVMStyle.SpacesInContainerLiterals =
false;
1879 if (
Language == FormatStyle::LK_TextProto) {
1881 GoogleStyle.Language = FormatStyle::LK_TextProto;
1888 GoogleStyle.AccessModifierOffset = -1;
1889 GoogleStyle.AlignEscapedNewlines = FormatStyle::ENAS_Left;
1890 GoogleStyle.AllowShortIfStatementsOnASingleLine =
1891 FormatStyle::SIS_WithoutElse;
1892 GoogleStyle.AllowShortLoopsOnASingleLine =
true;
1893 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
true;
1895 GoogleStyle.AttributeMacros.push_back(
"absl_nonnull");
1896 GoogleStyle.AttributeMacros.push_back(
"absl_nullable");
1897 GoogleStyle.AttributeMacros.push_back(
"absl_nullability_unknown");
1898 GoogleStyle.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
1900 GoogleStyle.IncludeStyle.IncludeCategories = {{
"^<ext/.*\\.h>", 2, 0,
false},
1901 {
"^<.*\\.h>", 1, 0,
false},
1902 {
"^<.*", 2, 0,
false},
1903 {
".*", 3, 0,
false}};
1904 GoogleStyle.IncludeStyle.IncludeIsMainRegex =
"([-_](test|unittest))?$";
1905 GoogleStyle.IndentCaseLabels =
true;
1906 GoogleStyle.KeepEmptyLines.AtStartOfBlock =
false;
1907 GoogleStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
1908 GoogleStyle.ObjCSpaceAfterProperty =
false;
1909 GoogleStyle.ObjCSpaceBeforeProtocolList =
true;
1910 GoogleStyle.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
1911 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
1912 GoogleStyle.RawStringFormats = {
1914 FormatStyle::LK_Cpp,
1931 FormatStyle::LK_TextProto,
1943 "PARSE_PARTIAL_TEXT_PROTO",
1947 "ParseTextProtoOrDie",
1949 "ParsePartialTestProto",
1956 GoogleStyle.SpacesBeforeTrailingComments = 2;
1957 GoogleStyle.Standard = FormatStyle::LS_Auto;
1959 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
1960 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
1962 if (
Language == FormatStyle::LK_Java) {
1963 GoogleStyle.AlignAfterOpenBracket =
false;
1964 GoogleStyle.AlignOperands = FormatStyle::OAS_DontAlign;
1965 GoogleStyle.AlignTrailingComments = {};
1966 GoogleStyle.AlignTrailingComments.Kind = FormatStyle::TCAS_Never;
1967 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
1968 GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
1969 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
1970 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
1971 GoogleStyle.ColumnLimit = 100;
1972 GoogleStyle.SpaceAfterCStyleCast =
true;
1973 GoogleStyle.SpacesBeforeTrailingComments = 1;
1974 }
else if (
Language == FormatStyle::LK_JavaScript) {
1975 GoogleStyle.BreakAfterOpenBracketBracedList =
true;
1976 GoogleStyle.BreakAfterOpenBracketFunction =
true;
1977 GoogleStyle.BreakAfterOpenBracketIf =
true;
1978 GoogleStyle.AlignOperands = FormatStyle::OAS_DontAlign;
1979 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
1981 GoogleStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
1982 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
1983 GoogleStyle.BreakBeforeTernaryOperators =
false;
1986 GoogleStyle.CommentPragmas =
"(taze:|^/[ \t]*<|tslint:|@see)";
1990 GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single;
1991 GoogleStyle.JavaScriptWrapImports =
false;
1992 GoogleStyle.MaxEmptyLinesToKeep = 3;
1993 GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
1994 GoogleStyle.SpacesInContainerLiterals =
false;
1995 }
else if (
Language == FormatStyle::LK_Proto) {
1996 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
1997 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
2003 GoogleStyle.BreakStringLiterals =
false;
2004 GoogleStyle.Cpp11BracedListStyle = FormatStyle::BLS_Block;
2005 GoogleStyle.SpacesInContainerLiterals =
false;
2006 }
else if (
Language == FormatStyle::LK_ObjC) {
2007 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
2008 GoogleStyle.ColumnLimit = 100;
2009 GoogleStyle.DerivePointerAlignment =
true;
2013 GoogleStyle.IncludeStyle.IncludeBlocks =
2015 }
else if (
Language == FormatStyle::LK_CSharp) {
2016 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
2017 GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
2018 GoogleStyle.BreakStringLiterals =
false;
2019 GoogleStyle.ColumnLimit = 100;
2020 GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
2046 ChromiumStyle.IncludeStyle.IncludeBlocks =
2049 if (
Language == FormatStyle::LK_Java) {
2050 ChromiumStyle.AllowShortIfStatementsOnASingleLine =
2051 FormatStyle::SIS_WithoutElse;
2052 ChromiumStyle.BreakAfterJavaFieldAnnotations =
true;
2053 ChromiumStyle.ContinuationIndentWidth = 8;
2054 ChromiumStyle.IndentWidth = 4;
2057 ChromiumStyle.JavaImportGroups = {
2064 "com.google.android.apps.chrome",
2069 }
else if (
Language == FormatStyle::LK_JavaScript) {
2070 ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
2071 ChromiumStyle.AllowShortLoopsOnASingleLine =
false;
2073 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine =
false;
2074 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
2075 ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
2076 ChromiumStyle.AllowShortLoopsOnASingleLine =
false;
2077 ChromiumStyle.BinPackParameters = FormatStyle::BPPS_OnePerLine;
2078 ChromiumStyle.DerivePointerAlignment =
false;
2079 if (
Language == FormatStyle::LK_ObjC)
2080 ChromiumStyle.ColumnLimit = 80;
2082 return ChromiumStyle;
2087 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine =
false;
2088 MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
2089 MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
2090 FormatStyle::DRTBS_TopLevel;
2091 MozillaStyle.BinPackArguments =
false;
2092 MozillaStyle.BinPackParameters = FormatStyle::BPPS_OnePerLine;
2093 MozillaStyle.BreakAfterReturnType = FormatStyle::RTBS_TopLevel;
2094 MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
2095 MozillaStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
2096 MozillaStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
2097 MozillaStyle.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
2098 MozillaStyle.ConstructorInitializerIndentWidth = 2;
2099 MozillaStyle.ContinuationIndentWidth = 2;
2100 MozillaStyle.Cpp11BracedListStyle = FormatStyle::BLS_Block;
2101 MozillaStyle.FixNamespaceComments =
false;
2102 MozillaStyle.IndentCaseLabels =
true;
2103 MozillaStyle.ObjCSpaceAfterProperty =
true;
2104 MozillaStyle.ObjCSpaceBeforeProtocolList =
false;
2105 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
2106 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
2107 MozillaStyle.SpaceAfterTemplateKeyword =
false;
2108 return MozillaStyle;
2113 Style.AccessModifierOffset = -4;
2114 Style.AlignAfterOpenBracket =
false;
2115 Style.AlignOperands = FormatStyle::OAS_DontAlign;
2116 Style.AlignTrailingComments = {};
2117 Style.AlignTrailingComments.Kind = FormatStyle::TCAS_Never;
2118 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
2119 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
2120 Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
2121 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
2122 Style.ColumnLimit = 0;
2123 Style.Cpp11BracedListStyle = FormatStyle::BLS_Block;
2124 Style.FixNamespaceComments =
false;
2125 Style.IndentWidth = 4;
2126 Style.NamespaceIndentation = FormatStyle::NI_Inner;
2127 Style.ObjCBlockIndentWidth = 4;
2128 Style.ObjCSpaceAfterProperty =
true;
2129 Style.PointerAlignment = FormatStyle::PAS_Left;
2130 Style.SpaceBeforeCpp11BracedList =
true;
2131 Style.SpaceInEmptyBraces = FormatStyle::SIEB_Always;
2137 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
2138 Style.BreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
2139 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
2140 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
2141 Style.BreakBeforeTernaryOperators =
true;
2142 Style.ColumnLimit = 79;
2143 Style.Cpp11BracedListStyle = FormatStyle::BLS_Block;
2144 Style.FixNamespaceComments =
false;
2145 Style.KeepFormFeed =
true;
2146 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
2152 Style.ColumnLimit = 120;
2154 Style.IndentWidth = 4;
2155 Style.UseTab = FormatStyle::UT_Never;
2156 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2157 Style.BraceWrapping.AfterClass =
true;
2158 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2159 Style.BraceWrapping.AfterEnum =
true;
2160 Style.BraceWrapping.AfterFunction =
true;
2161 Style.BraceWrapping.AfterNamespace =
true;
2162 Style.BraceWrapping.AfterObjCDeclaration =
true;
2163 Style.BraceWrapping.AfterStruct =
true;
2164 Style.BraceWrapping.AfterExternBlock =
true;
2165 Style.BraceWrapping.BeforeCatch =
true;
2166 Style.BraceWrapping.BeforeElse =
true;
2167 Style.BraceWrapping.BeforeWhile =
false;
2168 Style.PenaltyReturnTypeOnItsOwnLine = 1000;
2169 Style.AllowShortEnumsOnASingleLine =
false;
2170 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
2171 Style.AllowShortCaseLabelsOnASingleLine =
false;
2172 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
2173 Style.AllowShortLoopsOnASingleLine =
false;
2174 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
2175 Style.BreakAfterReturnType = FormatStyle::RTBS_None;
2181 Style.InsertBraces =
true;
2182 Style.InsertNewlineAtEOF =
true;
2183 Style.IntegerLiteralSeparator.Decimal = 3;
2184 Style.IntegerLiteralSeparator.DecimalMinDigits = 5;
2185 Style.LineEnding = FormatStyle::LE_LF;
2186 Style.RemoveBracesLLVM =
true;
2187 Style.RemoveEmptyLinesInUnwrappedLines =
true;
2188 Style.RemoveParentheses = FormatStyle::RPS_ReturnStatement;
2189 Style.RemoveSemicolon =
true;
2195 NoStyle.DisableFormat =
true;
2196 NoStyle.SortIncludes = {};
2197 NoStyle.SortUsingDeclarations = FormatStyle::SUD_Never;
2202 FormatStyle *Style) {
2203 if (Name.equals_insensitive(
"llvm"))
2205 else if (Name.equals_insensitive(
"chromium"))
2207 else if (Name.equals_insensitive(
"mozilla"))
2209 else if (Name.equals_insensitive(
"google"))
2211 else if (Name.equals_insensitive(
"webkit"))
2213 else if (Name.equals_insensitive(
"gnu"))
2215 else if (Name.equals_insensitive(
"microsoft"))
2217 else if (Name.equals_insensitive(
"clang-format"))
2219 else if (Name.equals_insensitive(
"none"))
2221 else if (Name.equals_insensitive(
"inheritparentconfig"))
2222 Style->InheritsParentConfig =
true;
2232 if (Style->QualifierOrder.empty())
2236 for (
const auto &Qualifier : Style->QualifierOrder) {
2237 if (Qualifier ==
"type")
2241 if (token == tok::identifier)
2246 std::set<std::string> UniqueQualifiers(Style->QualifierOrder.begin(),
2247 Style->QualifierOrder.end());
2248 if (Style->QualifierOrder.size() != UniqueQualifiers.size()) {
2249 LLVM_DEBUG(llvm::dbgs()
2250 <<
"Duplicate Qualifiers " << Style->QualifierOrder.size()
2251 <<
" vs " << UniqueQualifiers.size() <<
"\n");
2256 if (!llvm::is_contained(Style->QualifierOrder,
"type"))
2263 FormatStyle *Style,
bool AllowUnknownOptions,
2264 llvm::SourceMgr::DiagHandlerTy DiagHandler,
2265 void *DiagHandlerCtxt,
bool IsDotHFile) {
2267 FormatStyle::LanguageKind
Language = Style->Language;
2268 assert(
Language != FormatStyle::LK_None);
2269 if (Config.getBuffer().trim().empty())
2271 Style->StyleSet.Clear();
2272 std::vector<FormatStyle> Styles;
2273 llvm::yaml::Input Input(Config,
nullptr, DiagHandler,
2279 Input.setContext(Style);
2280 Input.setAllowUnknownKeys(AllowUnknownOptions);
2283 return Input.error();
2287 const auto StyleCount = Styles.size();
2290 for (
unsigned I = 1; I < StyleCount; ++I) {
2291 const auto Lang = Styles[I].Language;
2292 if (Lang == FormatStyle::LK_None)
2295 for (
unsigned J = 0; J < I; ++J) {
2297 LLVM_DEBUG(llvm::dbgs()
2298 <<
"Duplicate languages in the config file on positions "
2299 << J <<
" and " << I <<
'\n');
2305 int LanguagePos = -1;
2311 for (
unsigned I = 0; I < StyleCount; ++I) {
2312 const auto Lang = Styles[I].Language;
2317 if (Lang == FormatStyle::LK_Cpp)
2319 else if (Lang == FormatStyle::LK_C)
2326 if (LanguagePos < 0) {
2327 if (Styles[0].
Language == FormatStyle::LK_None)
2329 else if (IsDotHFile &&
Language == FormatStyle::LK_Cpp)
2331 else if (!IsDotHFile &&
Language == FormatStyle::LK_C)
2332 LanguagePos = CppPos;
2333 if (LanguagePos < 0)
2337 for (
const auto &S : llvm::reverse(llvm::drop_begin(Styles)))
2338 Style->StyleSet.Add(S);
2340 *Style = Styles[LanguagePos];
2342 if (LanguagePos == 0) {
2343 if (Style->Language == FormatStyle::LK_None)
2345 Style->StyleSet.Add(*Style);
2348 if (Style->InsertTrailingCommas != FormatStyle::TCS_None &&
2349 Style->BinPackArguments) {
2353 if (Style->QualifierAlignment != FormatStyle::QAS_Leave)
2360 llvm::raw_string_ostream Stream(
Text);
2361 llvm::yaml::Output Output(Stream);
2364 FormatStyle NonConstStyle = Style;
2368 Output << NonConstStyle;
2370 return Stream.str();
2373std::optional<FormatStyle>
2374FormatStyle::FormatStyleSet::Get(FormatStyle::LanguageKind
Language)
const {
2376 return std::nullopt;
2378 if (It == Styles->end())
2379 return std::nullopt;
2380 FormatStyle Style = It->second;
2381 Style.StyleSet = *
this;
2385void FormatStyle::FormatStyleSet::Add(FormatStyle Style) {
2386 assert(Style.Language !=
LK_None &&
2387 "Cannot add a style for LK_None to a StyleSet");
2389 !Style.StyleSet.Styles &&
2390 "Cannot add a style associated with an existing StyleSet to a StyleSet");
2392 Styles = std::make_shared<MapType>();
2393 (*Styles)[Style.Language] = std::move(Style);
2396void FormatStyle::FormatStyleSet::Clear() { Styles.reset(); }
2398std::optional<FormatStyle>
2399FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind
Language)
const {
2406 const SourceManager &SourceMgr, tooling::Replacements &
Result,
2407 StringRef
Text =
"") {
2408 const auto &
Tok = Token.Tok;
2409 SourceLocation Start;
2411 Start =
Tok.getLocation();
2414 Start = Token.WhitespaceRange.getBegin();
2417 cantFail(
Result.add(tooling::Replacement(SourceMgr, Range,
Text)));
2422 ParensRemover(
const Environment &Env,
const FormatStyle &Style)
2423 : TokenAnalyzer(Env, Style) {}
2425 std::pair<tooling::Replacements, unsigned>
2426 analyze(TokenAnnotator &Annotator,
2427 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2428 FormatTokenLexer &Tokens)
override {
2429 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2430 tooling::Replacements
Result;
2431 removeParens(AnnotatedLines,
Result);
2436 void removeParens(SmallVectorImpl<AnnotatedLine *> &Lines,
2437 tooling::Replacements &
Result) {
2438 const auto &SourceMgr = Env.getSourceManager();
2439 for (
auto *
Line : Lines) {
2440 if (!
Line->Children.empty())
2442 if (!
Line->Affected)
2444 for (
const auto *Token =
Line->First; Token && !Token->Finalized;
2445 Token = Token->Next) {
2446 if (Token->Optional && Token->isOneOf(tok::l_paren, tok::r_paren))
2455 BracesInserter(
const Environment &Env,
const FormatStyle &Style)
2456 : TokenAnalyzer(Env, Style) {}
2458 std::pair<tooling::Replacements, unsigned>
2459 analyze(TokenAnnotator &Annotator,
2460 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2461 FormatTokenLexer &Tokens)
override {
2462 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2463 tooling::Replacements
Result;
2464 insertBraces(AnnotatedLines,
Result);
2469 void insertBraces(SmallVectorImpl<AnnotatedLine *> &Lines,
2470 tooling::Replacements &
Result) {
2471 const auto &SourceMgr = Env.getSourceManager();
2472 int OpeningBraceSurplus = 0;
2473 for (AnnotatedLine *
Line : Lines) {
2474 if (!
Line->Children.empty())
2476 if (!
Line->Affected && OpeningBraceSurplus == 0)
2479 Token = Token->Next) {
2486 if (!
Line->Affected)
2488 Brace = Token->is(tok::comment) ?
"\n{" :
"{";
2489 ++OpeningBraceSurplus;
2491 if (OpeningBraceSurplus == 0)
2498 Token->BraceCount = 0;
2499 const auto Start = Token->Tok.getEndLoc();
2500 cantFail(
Result.add(tooling::Replacement(SourceMgr, Start, 0,
Brace)));
2503 assert(OpeningBraceSurplus == 0);
2509 BracesRemover(
const Environment &Env,
const FormatStyle &Style)
2510 : TokenAnalyzer(Env, Style) {}
2512 std::pair<tooling::Replacements, unsigned>
2513 analyze(TokenAnnotator &Annotator,
2514 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2515 FormatTokenLexer &Tokens)
override {
2516 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2517 tooling::Replacements
Result;
2518 removeBraces(AnnotatedLines,
Result);
2523 void removeBraces(SmallVectorImpl<AnnotatedLine *> &Lines,
2524 tooling::Replacements &
Result) {
2525 const auto &SourceMgr = Env.getSourceManager();
2526 const auto *End = Lines.end();
2527 for (
const auto *I = Lines.begin(); I != End; ++I) {
2528 const auto &
Line = *I;
2529 if (!
Line->Children.empty())
2531 if (!
Line->Affected)
2533 const auto *NextLine = I + 1 == End ?
nullptr : I[1];
2534 for (
const auto *Token =
Line->First; Token && !Token->Finalized;
2535 Token = Token->Next) {
2536 if (!Token->Optional || Token->isNoneOf(tok::l_brace, tok::r_brace))
2538 auto *
Next = Token->Next;
2539 assert(
Next || Token ==
Line->Last);
2540 if (!
Next && NextLine)
2541 Next = NextLine->First;
2550 SemiRemover(
const Environment &Env,
const FormatStyle &Style)
2551 : TokenAnalyzer(Env, Style) {}
2553 std::pair<tooling::Replacements, unsigned>
2554 analyze(TokenAnnotator &Annotator,
2555 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2556 FormatTokenLexer &Tokens)
override {
2557 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2558 tooling::Replacements
Result;
2559 removeSemi(Annotator, AnnotatedLines,
Result);
2564 void removeSemi(TokenAnnotator &Annotator,
2565 SmallVectorImpl<AnnotatedLine *> &Lines,
2566 tooling::Replacements &
Result) {
2568 const auto *Prev =
Tok.Previous;
2569 if (!Prev || Prev->isNot(tok::r_brace))
2571 const auto *LBrace = Prev->MatchingParen;
2572 return LBrace && LBrace->is(TT_FunctionLBrace);
2574 const auto &SourceMgr = Env.getSourceManager();
2575 const auto *End = Lines.end();
2576 for (
const auto *I = Lines.begin(); I != End; ++I) {
2577 const auto &
Line = *I;
2578 if (!
Line->Children.empty())
2579 removeSemi(Annotator,
Line->Children,
Result);
2580 if (!
Line->Affected)
2582 Annotator.calculateFormattingInformation(*
Line);
2583 const auto *NextLine = I + 1 == End ?
nullptr : I[1];
2584 for (
const auto *Token =
Line->First; Token && !Token->Finalized;
2585 Token = Token->Next) {
2586 if (Token->isNot(tok::semi) ||
2587 (!Token->Optional && !PrecededByFunctionRBrace(*Token))) {
2590 auto *
Next = Token->Next;
2591 assert(
Next || Token ==
Line->Last);
2592 if (!
Next && NextLine)
2593 Next = NextLine->First;
2602 EnumTrailingCommaEditor(
const Environment &Env,
const FormatStyle &Style)
2603 : TokenAnalyzer(Env, Style) {}
2605 std::pair<tooling::Replacements, unsigned>
2606 analyze(TokenAnnotator &Annotator,
2607 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2608 FormatTokenLexer &Tokens)
override {
2609 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2610 tooling::Replacements
Result;
2611 editEnumTrailingComma(AnnotatedLines,
Result);
2616 void editEnumTrailingComma(SmallVectorImpl<AnnotatedLine *> &Lines,
2617 tooling::Replacements &
Result) {
2618 bool InEnumBraces =
false;
2620 const auto &SourceMgr = Env.getSourceManager();
2621 for (
auto *
Line : Lines) {
2622 if (!
Line->Children.empty())
2623 editEnumTrailingComma(
Line->Children,
Result);
2624 for (
const auto *Token =
Line->First; Token && !Token->Finalized;
2625 Token = Token->Next) {
2626 if (Token->isNot(TT_EnumRBrace)) {
2627 if (Token->is(TT_EnumLBrace))
2628 InEnumBraces =
true;
2629 else if (InEnumBraces && Token->isNot(tok::comment))
2630 BeforeRBrace =
Line->Affected ? Token :
nullptr;
2633 InEnumBraces =
false;
2636 if (BeforeRBrace->is(tok::comma)) {
2637 if (Style.EnumTrailingComma == FormatStyle::ETC_Remove)
2639 }
else if (Style.EnumTrailingComma == FormatStyle::ETC_Insert) {
2640 cantFail(
Result.add(tooling::Replacement(
2641 SourceMgr, BeforeRBrace->Tok.getEndLoc(), 0,
",")));
2643 BeforeRBrace =
nullptr;
2651 JavaScriptRequoter(
const Environment &Env,
const FormatStyle &Style)
2652 : TokenAnalyzer(Env, Style) {}
2654 std::pair<tooling::Replacements, unsigned>
2655 analyze(TokenAnnotator &Annotator,
2656 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2657 FormatTokenLexer &Tokens)
override {
2658 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2659 tooling::Replacements
Result;
2660 requoteJSStringLiteral(AnnotatedLines,
Result);
2667 void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
2668 tooling::Replacements &
Result) {
2669 for (AnnotatedLine *
Line : Lines) {
2670 requoteJSStringLiteral(
Line->Children,
Result);
2671 if (!
Line->Affected)
2674 FormatTok = FormatTok->Next) {
2675 StringRef Input = FormatTok->TokenText;
2676 if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
2679 (Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
2680 !Input.starts_with(
"\"")) ||
2681 (Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
2682 !Input.starts_with(
"\'"))) {
2687 bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
2688 SourceLocation Start = FormatTok->Tok.getLocation();
2689 auto Replace = [&](SourceLocation Start,
unsigned Length,
2690 StringRef ReplacementText) {
2691 auto Err =
Result.add(tooling::Replacement(
2692 Env.getSourceManager(), Start, Length, ReplacementText));
2696 llvm::errs() <<
toString(std::move(Err)) <<
"\n";
2700 Replace(Start, 1, IsSingle ?
"'" :
"\"");
2701 Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
2702 IsSingle ?
"'" :
"\"");
2705 bool Escaped =
false;
2706 for (
size_t i = 1; i < Input.size() - 1; i++) {
2709 if (!Escaped && i + 1 < Input.size() &&
2710 ((IsSingle && Input[i + 1] ==
'"') ||
2711 (!IsSingle && Input[i + 1] ==
'\''))) {
2714 Replace(Start.getLocWithOffset(i), 1,
"");
2721 if (!Escaped && IsSingle == (Input[i] ==
'\'')) {
2723 Replace(Start.getLocWithOffset(i), 0,
"\\");
2739 Formatter(
const Environment &Env,
const FormatStyle &Style,
2740 FormattingAttemptStatus *Status)
2741 : TokenAnalyzer(Env, Style), Status(Status) {}
2743 std::pair<tooling::Replacements, unsigned>
2744 analyze(TokenAnnotator &Annotator,
2745 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2746 FormatTokenLexer &Tokens)
override {
2747 tooling::Replacements
Result;
2748 deriveLocalStyle(AnnotatedLines);
2749 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2750 for (AnnotatedLine *
Line : AnnotatedLines)
2751 Annotator.calculateFormattingInformation(*
Line);
2752 Annotator.setCommentLineLevels(AnnotatedLines);
2754 WhitespaceManager Whitespaces(
2755 Env.getSourceManager(), Style,
2756 Style.LineEnding > FormatStyle::LE_CRLF
2758 Env.getSourceManager().getBufferData(Env.getFileID()),
2759 Style.LineEnding == FormatStyle::LE_DeriveCRLF)
2760 : Style.LineEnding == FormatStyle::LE_CRLF);
2761 ContinuationIndenter Indenter(Style, Tokens.getKeywords(),
2762 Env.getSourceManager(), Whitespaces, Encoding,
2763 BinPackInconclusiveFunctions);
2765 UnwrappedLineFormatter(&Indenter, &Whitespaces, Style,
2766 Tokens.getKeywords(), Env.getSourceManager(),
2768 .format(AnnotatedLines,
false,
2771 Env.getFirstStartColumn(),
2772 Env.getNextStartColumn(),
2773 Env.getLastStartColumn());
2774 for (
const auto &R : Whitespaces.generateReplacements())
2776 return std::make_pair(
Result, 0);
2777 return std::make_pair(
Result, Penalty);
2782 hasCpp03IncompatibleFormat(
const SmallVectorImpl<AnnotatedLine *> &Lines) {
2783 for (
const AnnotatedLine *
Line : Lines) {
2784 if (hasCpp03IncompatibleFormat(
Line->Children))
2787 if (!
Tok->hasWhitespaceBefore()) {
2788 if (
Tok->is(tok::coloncolon) &&
Tok->Previous->is(TT_TemplateOpener))
2790 if (
Tok->is(TT_TemplateCloser) &&
2791 Tok->Previous->is(TT_TemplateCloser)) {
2800 int countVariableAlignments(
const SmallVectorImpl<AnnotatedLine *> &Lines) {
2801 int AlignmentDiff = 0;
2803 for (
const AnnotatedLine *
Line : Lines) {
2804 AlignmentDiff += countVariableAlignments(
Line->Children);
2807 if (
Tok->isNot(TT_PointerOrReference))
2810 const auto *Prev =
Tok->Previous;
2811 const bool PrecededByName = Prev && Prev->Tok.getIdentifierInfo();
2812 const bool SpaceBefore =
Tok->hasWhitespaceBefore();
2815 while (
Tok->Next &&
Tok->Next->is(TT_PointerOrReference))
2819 const bool FollowedByName =
Next &&
Next->Tok.getIdentifierInfo();
2820 const bool SpaceAfter =
Next &&
Next->hasWhitespaceBefore();
2822 if ((!PrecededByName && !FollowedByName) ||
2824 (PrecededByName && FollowedByName && SpaceBefore == SpaceAfter)) {
2828 if ((PrecededByName && SpaceBefore) ||
2829 (FollowedByName && !SpaceAfter)) {
2832 }
else if ((PrecededByName && !SpaceBefore) ||
2833 (FollowedByName && SpaceAfter)) {
2840 return AlignmentDiff;
2844 deriveLocalStyle(
const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
2845 bool HasBinPackedFunction =
false;
2846 bool HasOnePerLineFunction =
false;
2847 for (AnnotatedLine *
Line : AnnotatedLines) {
2848 if (!
Line->First->Next)
2853 HasBinPackedFunction =
true;
2855 HasOnePerLineFunction =
true;
2860 if (Style.DerivePointerAlignment) {
2861 const auto NetRightCount = countVariableAlignments(AnnotatedLines);
2862 if (NetRightCount > 0)
2863 Style.PointerAlignment = FormatStyle::PAS_Right;
2864 else if (NetRightCount < 0)
2865 Style.PointerAlignment = FormatStyle::PAS_Left;
2866 Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
2868 if (Style.Standard == FormatStyle::LS_Auto) {
2869 Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
2870 ? FormatStyle::LS_Latest
2871 : FormatStyle::LS_Cpp03;
2873 BinPackInconclusiveFunctions =
2874 HasBinPackedFunction || !HasOnePerLineFunction;
2877 bool BinPackInconclusiveFunctions;
2878 FormattingAttemptStatus *Status;
2894 TrailingCommaInserter(
const Environment &Env,
const FormatStyle &Style)
2895 : TokenAnalyzer(Env, Style) {}
2897 std::pair<tooling::Replacements, unsigned>
2898 analyze(TokenAnnotator &Annotator,
2899 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2900 FormatTokenLexer &Tokens)
override {
2901 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2902 tooling::Replacements
Result;
2903 insertTrailingCommas(AnnotatedLines,
Result);
2910 void insertTrailingCommas(SmallVectorImpl<AnnotatedLine *> &Lines,
2911 tooling::Replacements &
Result) {
2912 for (AnnotatedLine *
Line : Lines) {
2913 insertTrailingCommas(
Line->Children,
Result);
2914 if (!
Line->Affected)
2917 FormatTok = FormatTok->Next) {
2918 if (FormatTok->NewlinesBefore == 0)
2921 if (!Matching || !FormatTok->getPreviousNonComment())
2923 if (!(FormatTok->is(tok::r_square) &&
2924 Matching->is(TT_ArrayInitializerLSquare)) &&
2925 !(FormatTok->is(tok::r_brace) && Matching->is(TT_DictLiteral))) {
2928 FormatToken *Prev = FormatTok->getPreviousNonComment();
2929 if (Prev->is(tok::comma) || Prev->is(tok::semi))
2933 SourceLocation Start =
2934 Prev->Tok.getLocation().getLocWithOffset(Prev->TokenText.size());
2938 unsigned ColumnNumber =
2939 Env.getSourceManager().getSpellingColumnNumber(Start);
2940 if (ColumnNumber > Style.ColumnLimit)
2945 tooling::Replacement(Env.getSourceManager(), Start, 0,
",")));
2955 Cleaner(
const Environment &Env,
const FormatStyle &Style)
2956 : TokenAnalyzer(Env, Style),
2957 DeletedTokens(FormatTokenLess(Env.getSourceManager())) {}
2960 std::pair<tooling::Replacements, unsigned>
2961 analyze(TokenAnnotator &Annotator,
2962 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2963 FormatTokenLexer &Tokens)
override {
2971 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2973 checkEmptyNamespace(AnnotatedLines);
2975 for (
auto *
Line : AnnotatedLines)
2978 return {generateFixes(), 0};
2982 void cleanupLine(AnnotatedLine *
Line) {
2983 for (
auto *Child :
Line->Children)
2986 if (
Line->Affected) {
2987 cleanupRight(
Line->First, tok::comma, tok::comma);
2988 cleanupRight(
Line->First, TT_CtorInitializerColon, tok::comma);
2989 cleanupRight(
Line->First, tok::l_paren, tok::comma);
2990 cleanupLeft(
Line->First, tok::comma, tok::r_paren);
2991 cleanupLeft(
Line->First, TT_CtorInitializerComma, tok::l_brace);
2992 cleanupLeft(
Line->First, TT_CtorInitializerColon, tok::l_brace);
2993 cleanupLeft(
Line->First, TT_CtorInitializerColon, tok::equal);
2997 bool containsOnlyComments(
const AnnotatedLine &
Line) {
2999 if (
Tok->isNot(tok::comment))
3005 void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
3006 std::set<unsigned> DeletedLines;
3007 for (
unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
3008 auto &
Line = *AnnotatedLines[i];
3009 if (
Line.startsWithNamespace())
3010 checkEmptyNamespace(AnnotatedLines, i, i, DeletedLines);
3013 for (
auto Line : DeletedLines) {
3026 bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3027 unsigned CurrentLine,
unsigned &NewLine,
3028 std::set<unsigned> &DeletedLines) {
3029 unsigned InitLine = CurrentLine, End = AnnotatedLines.size();
3030 if (Style.BraceWrapping.AfterNamespace) {
3034 if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
3035 NewLine = CurrentLine;
3038 }
else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
3041 while (++CurrentLine < End) {
3042 if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
3045 if (AnnotatedLines[CurrentLine]->startsWithNamespace()) {
3046 if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine,
3050 CurrentLine = NewLine;
3054 if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
3059 NewLine = CurrentLine;
3063 NewLine = CurrentLine;
3064 if (CurrentLine >= End)
3069 AnnotatedLines[InitLine]->First->Tok.getLocation(),
3070 AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc()))) {
3074 for (
unsigned i = InitLine; i <= CurrentLine; ++i)
3075 DeletedLines.insert(i);
3084 template <
typename LeftKind,
typename RightKind>
3085 void cleanupPair(
FormatToken *Start, LeftKind LK, RightKind RK,
3088 for (
auto *Res =
Tok.Next; Res; Res = Res->Next) {
3089 if (Res->isNot(tok::comment) &&
3090 DeletedTokens.find(Res) == DeletedTokens.end()) {
3096 for (
auto *Left = Start;
Left;) {
3097 auto *
Right = NextNotDeleted(*Left);
3101 deleteToken(DeleteLeft ? Left : Right);
3113 template <
typename LeftKind,
typename RightKind>
3114 void cleanupLeft(
FormatToken *Start, LeftKind LK, RightKind RK) {
3115 cleanupPair(Start, LK, RK,
true);
3118 template <
typename LeftKind,
typename RightKind>
3119 void cleanupRight(
FormatToken *Start, LeftKind LK, RightKind RK) {
3120 cleanupPair(Start, LK, RK,
false);
3126 DeletedTokens.insert(
Tok);
3129 tooling::Replacements generateFixes() {
3130 tooling::Replacements Fixes;
3131 SmallVector<FormatToken *> Tokens;
3132 std::copy(DeletedTokens.begin(), DeletedTokens.end(),
3133 std::back_inserter(Tokens));
3139 while (Idx < Tokens.size()) {
3140 unsigned St = Idx, End = Idx;
3141 while ((End + 1) < Tokens.size() && Tokens[End]->Next == Tokens[End + 1])
3144 Tokens[End]->Tok.getEndLoc());
3146 Fixes.add(tooling::Replacement(Env.getSourceManager(), SR,
""));
3150 llvm::errs() <<
toString(std::move(Err)) <<
"\n";
3151 assert(
false &&
"Fixes must not conflict!");
3162 struct FormatTokenLess {
3163 FormatTokenLess(
const SourceManager &SM) : SM(SM) {}
3166 return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(),
3167 RHS->Tok.getLocation());
3169 const SourceManager &SM;
3173 std::set<FormatToken *, FormatTokenLess> DeletedTokens;
3178 ObjCHeaderStyleGuesser(
const Environment &Env,
const FormatStyle &Style)
3179 : TokenAnalyzer(Env, Style), IsObjC(
false) {}
3181 std::pair<tooling::Replacements, unsigned>
3182 analyze(TokenAnnotator &Annotator,
3183 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3184 FormatTokenLexer &Tokens)
override {
3185 assert(Style.Language == FormatStyle::LK_Cpp);
3186 IsObjC = guessIsObjC(Env.getSourceManager(), AnnotatedLines,
3187 Tokens.getKeywords());
3188 tooling::Replacements
Result;
3192 bool isObjC() {
return IsObjC; }
3196 guessIsObjC(
const SourceManager &SourceManager,
3197 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3198 const AdditionalKeywords &Keywords) {
3200 static constexpr llvm::StringLiteral FoundationIdentifiers[] = {
3215 "FOUNDATION_EXPORT",
3216 "FOUNDATION_EXTERN",
3217 "NSAffineTransform",
3219 "NSAttributedString",
3238 "NSInvocationOperation",
3242 "NSMutableAttributedString",
3243 "NSMutableCharacterSet",
3245 "NSMutableDictionary",
3246 "NSMutableIndexSet",
3247 "NSMutableOrderedSet",
3251 "NSNumberFormatter",
3255 "NSOperationQueuePriority",
3259 "NSQualityOfService",
3262 "NSRegularExpression",
3273 "NS_ASSUME_NONNULL_BEGIN",
3277 assert(llvm::is_sorted(FoundationIdentifiers));
3279 for (
auto *
Line : AnnotatedLines) {
3280 if (
Line->First && (
Line->First->TokenText.starts_with(
"#") ||
3281 Line->First->TokenText ==
"__pragma" ||
3282 Line->First->TokenText ==
"_Pragma")) {
3286 FormatTok = FormatTok->Next) {
3287 if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) &&
3288 (FormatTok->isNot(tok::objc_not_keyword) ||
3289 FormatTok->isOneOf(tok::numeric_constant, tok::l_square,
3291 (FormatTok->Tok.isAnyIdentifier() &&
3292 llvm::binary_search(FoundationIdentifiers,
3293 FormatTok->TokenText)) ||
3294 FormatTok->is(TT_ObjCStringLiteral) ||
3295 FormatTok->isOneOf(Keywords.kw_NS_CLOSED_ENUM, Keywords.kw_NS_ENUM,
3296 Keywords.kw_NS_ERROR_ENUM,
3297 Keywords.kw_NS_OPTIONS, TT_ObjCBlockLBrace,
3298 TT_ObjCBlockLParen, TT_ObjCDecl, TT_ObjCForIn,
3299 TT_ObjCMethodExpr, TT_ObjCMethodSpecifier,
3300 TT_ObjCProperty, TT_ObjCSelector)) {
3301 LLVM_DEBUG(llvm::dbgs()
3302 <<
"Detected ObjC at location "
3303 << FormatTok->Tok.getLocation().printToString(
3305 <<
" token: " << FormatTok->TokenText <<
" token type: "
3310 if (guessIsObjC(SourceManager,
Line->Children, Keywords))
3319struct IncludeDirective {
3327struct JavaImportDirective {
3328 StringRef Identifier;
3331 SmallVector<StringRef> AssociatedCommentLines;
3340 for (
const auto &Range : Ranges) {
3341 if (Range.getOffset() < End &&
3342 Range.getOffset() + Range.getLength() > Start) {
3357static std::pair<unsigned, unsigned>
3360 unsigned CursorIndex = std::numeric_limits<unsigned>::max();
3361 unsigned OffsetToEOL = 0;
3362 for (
int i = 0, e = Includes.size(); i != e; ++i) {
3363 unsigned Start = Includes[Indices[i]].Offset;
3364 unsigned End = Start + Includes[Indices[i]].Text.size();
3365 if (!(Cursor >= Start && Cursor < End))
3367 CursorIndex = Indices[i];
3368 OffsetToEOL = End - Cursor;
3371 while (--i >= 0 && Includes[CursorIndex].
Text == Includes[Indices[i]].
Text)
3375 return std::make_pair(CursorIndex, OffsetToEOL);
3380 std::string NewCode;
3381 size_t Pos = 0, LastPos = 0;
3384 Pos = Code.find(
"\r\n", LastPos);
3385 if (Pos == LastPos) {
3389 if (Pos == std::string::npos) {
3390 NewCode += Code.substr(LastPos);
3393 NewCode += Code.substr(LastPos, Pos - LastPos) +
"\n";
3395 }
while (Pos != std::string::npos);
3413 const unsigned IncludesBeginOffset = Includes.front().Offset;
3414 const unsigned IncludesEndOffset =
3415 Includes.back().Offset + Includes.back().Text.size();
3416 const unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset;
3417 if (!
affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset))
3420 llvm::to_vector<16>(llvm::seq<unsigned>(0, Includes.size()));
3422 if (Style.SortIncludes.Enabled) {
3423 stable_sort(Indices, [&](
unsigned LHSI,
unsigned RHSI) {
3425 if (Style.SortIncludes.IgnoreExtension) {
3426 LHSStem = Includes[LHSI].Filename;
3427 RHSStem = Includes[RHSI].Filename;
3428 llvm::sys::path::replace_extension(LHSStem,
"");
3429 llvm::sys::path::replace_extension(RHSStem,
"");
3431 std::string LHSStemLower, RHSStemLower;
3432 std::string LHSFilenameLower, RHSFilenameLower;
3433 if (Style.SortIncludes.IgnoreCase) {
3434 LHSStemLower = LHSStem.str().lower();
3435 RHSStemLower = RHSStem.str().lower();
3436 LHSFilenameLower = Includes[LHSI].Filename.lower();
3437 RHSFilenameLower = Includes[RHSI].Filename.lower();
3439 return std::tie(Includes[LHSI].Priority, LHSStemLower, LHSStem,
3440 LHSFilenameLower, Includes[LHSI].Filename) <
3441 std::tie(Includes[RHSI].Priority, RHSStemLower, RHSStem,
3442 RHSFilenameLower, Includes[RHSI].Filename);
3448 unsigned CursorIndex;
3450 unsigned CursorToEOLOffset;
3452 std::tie(CursorIndex, CursorToEOLOffset) =
3457 Indices.erase(llvm::unique(Indices,
3458 [&](
unsigned LHSI,
unsigned RHSI) {
3459 return Includes[LHSI].Text.trim() ==
3460 Includes[RHSI].Text.trim();
3464 int CurrentCategory = Includes.front().Category;
3472 if (Indices.size() == Includes.size() && is_sorted(Indices) &&
3477 const auto OldCursor = Cursor ? *Cursor : 0;
3479 for (
unsigned Index : Indices) {
3480 if (!result.empty()) {
3482 if (Style.IncludeStyle.IncludeBlocks ==
3484 CurrentCategory != Includes[Index].Category) {
3488 result += Includes[Index].Text;
3489 if (Cursor && CursorIndex == Index)
3490 *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
3491 CurrentCategory = Includes[Index].Category;
3494 if (Cursor && *Cursor >= IncludesEndOffset)
3495 *Cursor += result.size() - IncludesBlockSize;
3500 IncludesBeginOffset, IncludesBlockSize)))) {
3502 *Cursor = OldCursor;
3507 FileName, Includes.front().Offset, IncludesBlockSize, result));
3511 llvm::errs() <<
toString(std::move(Err)) <<
"\n";
3521 unsigned Prev = llvm::StringSwitch<size_t>(Code)
3522 .StartsWith(
"\xEF\xBB\xBF", 3)
3524 unsigned SearchFrom = 0;
3536 bool FirstIncludeBlock =
true;
3537 bool MainIncludeFound =
false;
3538 bool FormattingOff =
false;
3541 llvm::Regex RawStringRegex(
3542 "R\"([][A-Za-z0-9_{}#<>%:;.?*+/^&\\$|~!=,'-]*)\\(");
3544 std::string RawStringTermination =
")\"";
3546 for (
const auto Size = Code.size(); SearchFrom < Size;) {
3547 size_t Pos = SearchFrom;
3548 if (Code[SearchFrom] !=
'\n') {
3551 Pos = Code.find(
'\n', Pos);
3552 }
while (Pos != StringRef::npos && Code[Pos - 1] ==
'\\');
3556 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
3558 StringRef Trimmed =
Line.trim();
3563 if (RawStringRegex.match(Trimmed, &RawStringMatches)) {
3564 std::string CharSequence = RawStringMatches[1].str();
3565 RawStringTermination =
")" + CharSequence +
"\"";
3566 FormattingOff =
true;
3569 if (Trimmed.contains(RawStringTermination))
3570 FormattingOff =
false;
3572 bool IsBlockComment =
false;
3575 FormattingOff =
true;
3577 FormattingOff =
false;
3578 }
else if (Trimmed.starts_with(
"/*")) {
3579 IsBlockComment =
true;
3580 Pos = Code.find(
"*/", SearchFrom + 2);
3583 const bool EmptyLineSkipped =
3586 Style.IncludeStyle.IncludeBlocks ==
3589 bool MergeWithNextLine = Trimmed.ends_with(
"\\");
3590 if (!FormattingOff && !MergeWithNextLine) {
3591 if (!IsBlockComment &&
3593 StringRef IncludeName = Matches[2];
3594 if (Trimmed.contains(
"/*") && !Trimmed.contains(
"*/")) {
3599 Pos = Code.find(
"*/", SearchFrom);
3601 Prev, (Pos != StringRef::npos ? Pos + 2 : Code.size()) - Prev);
3605 !MainIncludeFound && FirstIncludeBlock);
3607 IncludeName, !MainIncludeFound && FirstIncludeBlock);
3609 MainIncludeFound =
true;
3610 IncludesInBlock.push_back(
3611 {IncludeName,
Line, Prev, Category, Priority});
3612 }
else if (!IncludesInBlock.empty() && !EmptyLineSkipped) {
3615 IncludesInBlock.clear();
3616 if (Trimmed.starts_with(
"#pragma hdrstop"))
3617 FirstIncludeBlock =
true;
3619 FirstIncludeBlock =
false;
3622 if (Pos == StringRef::npos || Pos + 1 == Code.size())
3625 if (!MergeWithNextLine)
3627 SearchFrom = Pos + 1;
3629 if (!IncludesInBlock.empty()) {
3640 StringRef ImportIdentifier) {
3641 unsigned LongestMatchIndex = std::numeric_limits<unsigned>::max();
3642 unsigned LongestMatchLength = 0;
3643 for (
unsigned I = 0; I < Style.JavaImportGroups.size(); I++) {
3644 const std::string &GroupPrefix = Style.JavaImportGroups[I];
3645 if (ImportIdentifier.starts_with(GroupPrefix) &&
3646 GroupPrefix.length() > LongestMatchLength) {
3647 LongestMatchIndex = I;
3648 LongestMatchLength = GroupPrefix.length();
3651 return LongestMatchIndex;
3663 unsigned ImportsBeginOffset = Imports.front().Offset;
3664 unsigned ImportsEndOffset =
3665 Imports.back().Offset + Imports.back().Text.size();
3666 unsigned ImportsBlockSize = ImportsEndOffset - ImportsBeginOffset;
3667 if (!
affectsRange(Ranges, ImportsBeginOffset, ImportsEndOffset))
3671 llvm::to_vector<16>(llvm::seq<unsigned>(0, Imports.size()));
3674 for (
const JavaImportDirective &Import : Imports)
3677 bool StaticImportAfterNormalImport =
3678 Style.SortJavaStaticImport == FormatStyle::SJSIO_After;
3679 sort(Indices, [&](
unsigned LHSI,
unsigned RHSI) {
3681 return std::make_tuple(!Imports[LHSI].IsStatic ^
3682 StaticImportAfterNormalImport,
3684 std::make_tuple(!Imports[RHSI].IsStatic ^
3685 StaticImportAfterNormalImport,
3690 Indices.erase(llvm::unique(Indices,
3691 [&](
unsigned LHSI,
unsigned RHSI) {
3692 return Imports[LHSI].Text == Imports[RHSI].Text;
3696 bool CurrentIsStatic = Imports[Indices.front()].IsStatic;
3700 for (
unsigned Index : Indices) {
3701 if (!result.empty()) {
3703 if (CurrentIsStatic != Imports[Index].IsStatic ||
3708 for (StringRef CommentLine : Imports[Index].AssociatedCommentLines) {
3709 result += CommentLine;
3712 result += Imports[Index].Text;
3713 CurrentIsStatic = Imports[Index].IsStatic;
3720 Imports.front().Offset, ImportsBlockSize)))) {
3725 ImportsBlockSize, result));
3729 llvm::errs() <<
toString(std::move(Err)) <<
"\n";
3736const char JavaImportRegexPattern[] =
3737 "^[\t ]*import[\t ]+(static[\t ]*)?([^\t ]*)[\t ]*;";
3746 unsigned SearchFrom = 0;
3747 llvm::Regex ImportRegex(JavaImportRegexPattern);
3752 bool FormattingOff =
false;
3755 auto Pos = Code.find(
'\n', SearchFrom);
3757 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
3759 StringRef Trimmed =
Line.trim();
3761 FormattingOff =
true;
3763 FormattingOff =
false;
3765 if (ImportRegex.match(
Line, &Matches)) {
3766 if (FormattingOff) {
3771 StringRef
Static = Matches[1];
3772 StringRef Identifier = Matches[2];
3773 bool IsStatic =
false;
3774 if (
Static.contains(
"static"))
3776 ImportsInBlock.push_back(
3777 {Identifier,
Line, Prev, AssociatedCommentLines, IsStatic});
3778 AssociatedCommentLines.clear();
3779 }
else if (!Trimmed.empty() && !ImportsInBlock.empty()) {
3781 AssociatedCommentLines.push_back(
Line);
3784 if (Pos == StringRef::npos || Pos + 1 == Code.size())
3786 SearchFrom = Pos + 1;
3788 if (!ImportsInBlock.empty())
3797 return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
3800bool isLikelyXml(StringRef Code) {
return Code.ltrim().starts_with(
"<"); }
3804 StringRef
FileName,
unsigned *Cursor) {
3806 if (!Style.SortIncludes.Enabled || Style.DisableFormat)
3810 if (Style.isJavaScript()) {
3822template <
typename T>
3826 const FormatStyle &Style) {
3827 if (Replaces.
empty())
3830 auto NewCode = applyAllReplacements(Code, Replaces);
3832 return NewCode.takeError();
3837 ProcessFunc(Style, *NewCode, ChangedRanges,
FileName);
3839 return Replaces.
merge(FormatReplaces);
3844 const FormatStyle &Style) {
3847 auto SortIncludes = [](
const FormatStyle &Style, StringRef Code,
3848 std::vector<tooling::Range> Ranges,
3852 auto SortedReplaces =
3854 if (!SortedReplaces)
3855 return SortedReplaces.takeError();
3859 auto Reformat = [](
const FormatStyle &Style, StringRef Code,
3860 std::vector<tooling::Range> Ranges,
3870 return Replace.
getOffset() == std::numeric_limits<unsigned>::max() &&
3876inline bool isHeaderDeletion(
const tooling::Replacement &Replace) {
3877 return Replace.getOffset() == std::numeric_limits<unsigned>::max() &&
3878 Replace.getLength() == 1;
3882tooling::Replacements
3883fixCppIncludeInsertions(StringRef Code,
const tooling::Replacements &Replaces,
3884 const FormatStyle &Style) {
3888 tooling::Replacements HeaderInsertions;
3889 std::set<StringRef> HeadersToDelete;
3890 tooling::Replacements
Result;
3891 for (
const auto &R : Replaces) {
3892 if (isHeaderInsertion(R)) {
3895 consumeError(HeaderInsertions.add(R));
3896 }
else if (isHeaderDeletion(R)) {
3897 HeadersToDelete.insert(R.getReplacementText());
3898 }
else if (R.getOffset() == std::numeric_limits<unsigned>::max()) {
3899 llvm::errs() <<
"Insertions other than header #include insertion are "
3901 << R.getReplacementText() <<
"\n";
3903 consumeError(
Result.add(R));
3906 if (HeaderInsertions.empty() && HeadersToDelete.empty())
3909 StringRef
FileName = Replaces.begin()->getFilePath();
3910 tooling::HeaderIncludes Includes(
FileName, Code, Style.IncludeStyle);
3912 for (
const auto &Header : HeadersToDelete) {
3913 tooling::Replacements Replaces =
3914 Includes.remove(Header.trim(
"\"<>"), Header.starts_with(
"<"));
3915 for (
const auto &R : Replaces) {
3916 auto Err =
Result.add(R);
3919 llvm::errs() <<
"Failed to add header deletion replacement for "
3920 << Header <<
": " <<
toString(std::move(Err)) <<
"\n";
3926 for (
const auto &R : HeaderInsertions) {
3927 auto IncludeDirective = R.getReplacementText();
3930 assert(Matched &&
"Header insertion replacement must have replacement text "
3933 auto IncludeName = Matches[2];
3935 Includes.insert(IncludeName.trim(
"\"<>"), IncludeName.starts_with(
"<"),
3938 auto Err =
Result.add(*Replace);
3940 consumeError(std::move(Err));
3941 unsigned NewOffset =
3942 Result.getShiftedCodePosition(Replace->getOffset());
3943 auto Shifted = tooling::Replacement(
FileName, NewOffset, 0,
3944 Replace->getReplacementText());
3956 const FormatStyle &Style) {
3959 auto Cleanup = [](
const FormatStyle &Style, StringRef Code,
3966 fixCppIncludeInsertions(Code, Replaces, Style);
3971std::pair<tooling::Replacements, unsigned>
3974 unsigned NextStartColumn,
unsigned LastStartColumn, StringRef
FileName,
3976 FormatStyle Expanded = Style;
3980 Expanded.InsertBraces =
false;
3981 Expanded.RemoveBracesLLVM =
false;
3982 Expanded.RemoveParentheses = FormatStyle::RPS_Leave;
3983 Expanded.RemoveSemicolon =
false;
3984 switch (Expanded.RequiresClausePosition) {
3985 case FormatStyle::RCPS_SingleLine:
3986 case FormatStyle::RCPS_WithPreceding:
3987 Expanded.IndentRequiresClause =
false;
3993 if (Expanded.DisableFormat)
3997 if (Expanded.isJavaScript() &&
isMpegTS(Code))
4001 if (Style.isJson()) {
4002 std::vector<tooling::Range> Ranges(1,
tooling::Range(0, Code.size()));
4004 NextStartColumn, LastStartColumn);
4009 Formatter(*Env, Style, Status).process().first;
4011 if (Code.starts_with(
"x = ")) {
4012 Replaces = Replaces.
merge(
4016 if (applyAllReplacements(Code, Replaces))
4017 return {Replaces, 0};
4022 NextStartColumn, LastStartColumn);
4040 if (Style.isCpp()) {
4041 if (Style.QualifierAlignment != FormatStyle::QAS_Leave)
4044 if (Style.RemoveParentheses != FormatStyle::RPS_Leave) {
4045 FormatStyle S = Expanded;
4046 S.RemoveParentheses = Style.RemoveParentheses;
4047 Passes.emplace_back([&, S = std::move(S)](
const Environment &Env) {
4048 return ParensRemover(Env, S).process(
true);
4052 if (Style.InsertBraces) {
4053 FormatStyle S = Expanded;
4054 S.InsertBraces =
true;
4055 Passes.emplace_back([&, S = std::move(S)](
const Environment &Env) {
4056 return BracesInserter(Env, S).process(
true);
4060 if (Style.RemoveBracesLLVM) {
4061 FormatStyle S = Expanded;
4062 S.RemoveBracesLLVM =
true;
4063 Passes.emplace_back([&, S = std::move(S)](
const Environment &Env) {
4064 return BracesRemover(Env, S).process(
true);
4068 if (Style.RemoveSemicolon) {
4069 FormatStyle S = Expanded;
4070 S.RemoveSemicolon =
true;
4071 Passes.emplace_back([&, S = std::move(S)](
const Environment &Env) {
4072 return SemiRemover(Env, S).process();
4076 if (Style.EnumTrailingComma != FormatStyle::ETC_Leave) {
4078 return EnumTrailingCommaEditor(Env, Expanded)
4083 if (Style.FixNamespaceComments) {
4089 if (Style.SortUsingDeclarations != FormatStyle::SUD_Never) {
4096 if (Style.SeparateDefinitionBlocks != FormatStyle::SDS_Leave) {
4102 if (Style.Language == FormatStyle::LK_ObjC &&
4103 !Style.ObjCPropertyAttributeOrder.empty()) {
4109 if (Style.isJavaScript() &&
4110 Style.JavaScriptQuotes != FormatStyle::JSQS_Leave) {
4112 return JavaScriptRequoter(Env, Expanded).process(
true);
4117 return Formatter(Env, Expanded, Status).process();
4120 if (Style.isJavaScript() &&
4121 Style.InsertTrailingCommas == FormatStyle::TCS_Wrapped) {
4123 return TrailingCommaInserter(Env, Expanded).process();
4127 std::optional<std::string> CurrentCode;
4129 unsigned Penalty = 0;
4130 for (
size_t I = 0, E = Passes.size(); I < E; ++I) {
4131 std::pair<tooling::Replacements, unsigned> PassFixes = Passes[I](*Env);
4132 auto NewCode = applyAllReplacements(
4133 CurrentCode ? StringRef(*CurrentCode) : Code, PassFixes.first);
4135 Fixes = Fixes.
merge(PassFixes.first);
4136 Penalty += PassFixes.second;
4138 CurrentCode = std::move(*NewCode);
4142 FirstStartColumn, NextStartColumn, LastStartColumn);
4149 if (Style.QualifierAlignment != FormatStyle::QAS_Leave) {
4155 StringRef OriginalCode = Code.substr(Fix.getOffset(), Fix.getLength());
4156 if (OriginalCode != Fix.getReplacementText()) {
4157 auto Err = NonNoOpFixes.
add(Fix);
4159 llvm::errs() <<
"Error adding replacements : "
4160 <<
toString(std::move(Err)) <<
"\n";
4164 Fixes = std::move(NonNoOpFixes);
4167 return {Fixes, Penalty};
4186 if (Style.Language != FormatStyle::LK_Cpp)
4191 return Cleaner(*Env, Style).process().first;
4196 StringRef
FileName,
bool *IncompleteFormat) {
4199 if (!Status.FormatComplete)
4200 *IncompleteFormat =
true;
4227 auto LexingStd = Style.Standard;
4228 if (LexingStd == FormatStyle::LS_Auto || LexingStd == FormatStyle::LS_Latest)
4229 LexingStd = FormatStyle::LS_Cpp20;
4231 const bool SinceCpp11 = LexingStd >= FormatStyle::LS_Cpp11;
4232 const bool SinceCpp20 = LexingStd >= FormatStyle::LS_Cpp20;
4234 switch (Style.Language) {
4235 case FormatStyle::LK_C:
4239 case FormatStyle::LK_Cpp:
4240 case FormatStyle::LK_ObjC:
4241 LangOpts.CXXOperatorNames = 1;
4242 LangOpts.CPlusPlus11 = SinceCpp11;
4243 LangOpts.CPlusPlus14 = LexingStd >= FormatStyle::LS_Cpp14;
4244 LangOpts.CPlusPlus17 = LexingStd >= FormatStyle::LS_Cpp17;
4245 LangOpts.CPlusPlus20 = SinceCpp20;
4248 LangOpts.CPlusPlus = 1;
4251 LangOpts.Char8 = SinceCpp20;
4255 LangOpts.Digraphs = SinceCpp11;
4257 LangOpts.LineComment = 1;
4260 LangOpts.MicrosoftExt = 1;
4261 LangOpts.DeclSpecKeyword = 1;
4268 "Set coding style. <string> can be:\n"
4269 "1. A preset: LLVM, GNU, Google, Chromium, Microsoft,\n"
4270 " Mozilla, WebKit.\n"
4271 "2. 'file' to load style configuration from a\n"
4272 " .clang-format file in one of the parent directories\n"
4273 " of the source file (for stdin, see --assume-filename).\n"
4274 " If no .clang-format file is found, falls back to\n"
4275 " --fallback-style.\n"
4276 " --style=file is the default.\n"
4277 "3. 'file:<format_file_path>' to explicitly specify\n"
4278 " the configuration file.\n"
4279 "4. \"{key: value, ...}\" to set specific parameters, e.g.:\n"
4280 " --style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
4284 return FormatStyle::LK_C;
4286 return FormatStyle::LK_Java;
4287 if (
FileName.ends_with_insensitive(
".js") ||
4288 FileName.ends_with_insensitive(
".mjs") ||
4289 FileName.ends_with_insensitive(
".cjs") ||
4290 FileName.ends_with_insensitive(
".ts")) {
4291 return FormatStyle::LK_JavaScript;
4294 return FormatStyle::LK_ObjC;
4295 if (
FileName.ends_with_insensitive(
".proto") ||
4296 FileName.ends_with_insensitive(
".protodevel")) {
4297 return FormatStyle::LK_Proto;
4302 if (
FileName.ends_with_insensitive(
".txtpb") ||
4303 FileName.ends_with_insensitive(
".textpb") ||
4304 FileName.ends_with_insensitive(
".pb.txt") ||
4305 FileName.ends_with_insensitive(
".textproto") ||
4306 FileName.ends_with_insensitive(
".asciipb")) {
4307 return FormatStyle::LK_TextProto;
4309 if (
FileName.ends_with_insensitive(
".td"))
4310 return FormatStyle::LK_TableGen;
4311 if (
FileName.ends_with_insensitive(
".cs"))
4312 return FormatStyle::LK_CSharp;
4313 if (
FileName.ends_with_insensitive(
".json") ||
4314 FileName.ends_with_insensitive(
".ipynb")) {
4315 return FormatStyle::LK_Json;
4317 if (
FileName.ends_with_insensitive(
".sv") ||
4318 FileName.ends_with_insensitive(
".svh") ||
4319 FileName.ends_with_insensitive(
".v") ||
4320 FileName.ends_with_insensitive(
".vh")) {
4321 return FormatStyle::LK_Verilog;
4323 return FormatStyle::LK_Cpp;
4331 LangOpts.CPlusPlus = 1;
4332 LangOpts.LineComment = 1;
4334 Lexer Lex(ID, SourceMgr.getBufferOrFake(ID), SourceMgr, LangOpts);
4338 auto Text = StringRef(SourceMgr.getCharacterData(
Tok.getLocation()),
4340 if (!
Text.consume_front(
"// clang-format Language:"))
4345 return FormatStyle::LK_C;
4347 return FormatStyle::LK_Cpp;
4349 return FormatStyle::LK_ObjC;
4352 return FormatStyle::LK_None;
4357 if (GuessedLanguage == FormatStyle::LK_Cpp) {
4358 auto Extension = llvm::sys::path::extension(
FileName);
4361 if (!Code.empty() && (Extension.empty() || Extension ==
".h")) {
4365 Language != FormatStyle::LK_None) {
4370 if (Guesser.isObjC())
4371 return FormatStyle::LK_ObjC;
4374 return GuessedLanguage;
4382llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
4384 FormatStyle *Style,
bool AllowUnknownOptions,
4385 llvm::SourceMgr::DiagHandlerTy DiagHandler,
4387 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Text =
4388 FS->getBufferForFile(ConfigFile.str());
4389 if (
auto EC =
Text.getError())
4392 DiagHandler,
nullptr,
4400 StringRef FallbackStyleName, StringRef Code,
4401 llvm::vfs::FileSystem *FS,
4402 bool AllowUnknownOptions,
4403 llvm::SourceMgr::DiagHandlerTy DiagHandler) {
4411 if (StyleName.starts_with(
"{")) {
4413 StringRef Source =
"<command-line>";
4414 if (std::error_code ec =
4416 AllowUnknownOptions, DiagHandler)) {
4420 if (!Style.InheritsParentConfig)
4423 ChildFormatTextToApply.emplace_back(
4424 llvm::MemoryBuffer::getMemBuffer(StyleName, Source,
false));
4428 FS = llvm::vfs::getRealFileSystem().get();
4431 const bool IsDotHFile =
FileName.ends_with(
".h");
4434 if (!Style.InheritsParentConfig &&
4435 StyleName.starts_with_insensitive(
"file:")) {
4436 auto ConfigFile = StyleName.substr(5);
4437 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Text =
4439 DiagHandler, IsDotHFile);
4440 if (
auto EC =
Text.getError()) {
4445 LLVM_DEBUG(llvm::dbgs()
4446 <<
"Using configuration file " << ConfigFile <<
"\n");
4448 if (!Style.InheritsParentConfig)
4454 ChildFormatTextToApply.emplace_back(std::move(*
Text));
4460 if (!Style.InheritsParentConfig && !StyleName.equals_insensitive(
"file")) {
4463 if (!Style.InheritsParentConfig)
4468 if (std::error_code EC = FS->makeAbsolute(Path))
4472 Style.InheritsParentConfig =
false;
4474 auto dropDiagnosticHandler = [](
const llvm::SMDiagnostic &,
void *) {};
4476 auto applyChildFormatTexts = [&](FormatStyle *Style) {
4477 for (
const auto &MemBuf : llvm::reverse(ChildFormatTextToApply)) {
4480 DiagHandler ? DiagHandler : dropDiagnosticHandler);
4483 static_cast<void>(EC);
4489 FilesToLookFor.push_back(
".clang-format");
4490 FilesToLookFor.push_back(
"_clang-format");
4493 for (StringRef Directory = Path; !Directory.empty();
4494 Directory = llvm::sys::path::parent_path(Directory)) {
4495 auto Status = FS->status(Directory);
4497 Status->getType() != llvm::sys::fs::file_type::directory_file) {
4501 for (
const auto &F : FilesToLookFor) {
4504 llvm::sys::path::append(ConfigFile, F);
4505 LLVM_DEBUG(llvm::dbgs() <<
"Trying " << ConfigFile <<
"...\n");
4507 Status = FS->status(ConfigFile);
4509 Status->getType() != llvm::sys::fs::file_type::regular_file) {
4513 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Text =
4515 DiagHandler, IsDotHFile);
4516 if (
auto EC =
Text.getError()) {
4521 if (!UnsuitableConfigFiles.empty())
4522 UnsuitableConfigFiles.append(
", ");
4523 UnsuitableConfigFiles.append(ConfigFile);
4527 LLVM_DEBUG(llvm::dbgs()
4528 <<
"Using configuration file " << ConfigFile <<
"\n");
4530 if (!Style.InheritsParentConfig) {
4531 if (!ChildFormatTextToApply.empty()) {
4532 LLVM_DEBUG(llvm::dbgs() <<
"Applying child configurations\n");
4533 applyChildFormatTexts(&Style);
4538 LLVM_DEBUG(llvm::dbgs() <<
"Inherits parent configuration\n");
4541 Style.InheritsParentConfig =
false;
4543 ChildFormatTextToApply.emplace_back(std::move(*
Text));
4553 if (!UnsuitableConfigFiles.empty()) {
4556 UnsuitableConfigFiles);
4559 if (!ChildFormatTextToApply.empty()) {
4560 LLVM_DEBUG(llvm::dbgs()
4561 <<
"Applying child configurations on fallback style\n");
4562 applyChildFormatTexts(&FallbackStyle);
4565 return FallbackStyle;
4569 if (Comment == (On ?
"/* clang-format on */" :
"/* clang-format off */"))
4572 static const char ClangFormatOn[] =
"// clang-format on";
4573 static const char ClangFormatOff[] =
"// clang-format off";
4574 const unsigned Size = (On ?
sizeof ClangFormatOn :
sizeof ClangFormatOff) - 1;
4576 return Comment.starts_with(On ? ClangFormatOn : ClangFormatOff) &&
4577 (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).
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.
const FunctionProtoType * T
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)