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,
true}));
881 IO.enumCase(
Value,
"Always",
882 FormatStyle::TrailingCommentsAlignmentStyle(
883 {FormatStyle::TCAS_Always, 0,
true}));
885 IO.enumCase(
Value,
"Never",
886 FormatStyle::TrailingCommentsAlignmentStyle(
887 {FormatStyle::TCAS_Never, 0,
true}));
890 IO.enumCase(
Value,
"true",
891 FormatStyle::TrailingCommentsAlignmentStyle(
892 {FormatStyle::TCAS_Always, 0,
true}));
893 IO.enumCase(
Value,
"false",
894 FormatStyle::TrailingCommentsAlignmentStyle(
895 {FormatStyle::TCAS_Never, 0,
true}));
899 FormatStyle::TrailingCommentsAlignmentStyle &
Value) {
900 IO.mapOptional(
"AlignPPAndNotPP",
Value.AlignPPAndNotPP);
901 IO.mapOptional(
"Kind",
Value.Kind);
902 IO.mapOptional(
"OverEmptyLines",
Value.OverEmptyLines);
906template <>
struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
908 IO.enumCase(
Value,
"Never", FormatStyle::UT_Never);
909 IO.enumCase(
Value,
"false", FormatStyle::UT_Never);
910 IO.enumCase(
Value,
"Always", FormatStyle::UT_Always);
911 IO.enumCase(
Value,
"true", FormatStyle::UT_Always);
912 IO.enumCase(
Value,
"ForIndentation", FormatStyle::UT_ForIndentation);
913 IO.enumCase(
Value,
"ForContinuationAndIndentation",
914 FormatStyle::UT_ForContinuationAndIndentation);
915 IO.enumCase(
Value,
"AlignWithSpaces", FormatStyle::UT_AlignWithSpaces);
920struct ScalarEnumerationTraits<
921 FormatStyle::WrapNamespaceBodyWithEmptyLinesStyle> {
924 FormatStyle::WrapNamespaceBodyWithEmptyLinesStyle &
Value) {
925 IO.enumCase(
Value,
"Never", FormatStyle::WNBWELS_Never);
926 IO.enumCase(
Value,
"Always", FormatStyle::WNBWELS_Always);
927 IO.enumCase(
Value,
"Leave", FormatStyle::WNBWELS_Leave);
931template <>
struct MappingTraits<FormatStyle> {
932 static void mapping(IO &IO, FormatStyle &Style) {
934 IO.mapOptional(
"Language", Style.Language);
936 StringRef BasedOnStyle;
937 if (IO.outputting()) {
938 StringRef Styles[] = {
"LLVM",
"Google",
"Chromium",
"Mozilla",
939 "WebKit",
"GNU",
"Microsoft",
"clang-format"};
940 for (StringRef StyleName : Styles) {
941 FormatStyle PredefinedStyle;
943 Style == PredefinedStyle) {
944 BasedOnStyle = StyleName;
949 IO.mapOptional(
"BasedOnStyle", BasedOnStyle);
950 if (!BasedOnStyle.empty()) {
951 FormatStyle::LanguageKind OldLanguage = Style.Language;
952 FormatStyle::LanguageKind Language =
953 ((FormatStyle *)IO.getContext())->Language;
955 IO.setError(Twine(
"Unknown value for BasedOnStyle: ", BasedOnStyle));
958 Style.Language = OldLanguage;
973 const bool IsGoogleOrChromium = BasedOnStyle.equals_insensitive(
"google") ||
974 BasedOnStyle.equals_insensitive(
"chromium");
975 bool OnCurrentLine = IsGoogleOrChromium;
976 bool OnNextLine =
true;
978 bool BreakBeforeInheritanceComma =
false;
979 bool BreakConstructorInitializersBeforeComma =
false;
981 bool DeriveLineEnding =
true;
982 bool UseCRLF =
false;
984 bool SpaceInEmptyBlock =
false;
985 bool SpaceInEmptyParentheses =
false;
986 bool SpacesInConditionalStatement =
false;
987 bool SpacesInCStyleCastParentheses =
false;
988 bool SpacesInParentheses =
false;
990 if (IO.outputting()) {
991 IO.mapOptional(
"AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
995 if (IsGoogleOrChromium) {
996 FormatStyle::LanguageKind Language = Style.Language;
997 if (Language == FormatStyle::LK_None)
998 Language = ((FormatStyle *)IO.getContext())->Language;
999 if (Language == FormatStyle::LK_JavaScript)
1001 else if (Language == FormatStyle::LK_Java)
1003 }
else if (BasedOnStyle.equals_insensitive(
"webkit")) {
1006 IO.mapOptional(
"AlignAfterOpenBracket", LocalBAS);
1007 Style.BreakAfterOpenBracketBracedList =
false;
1008 Style.BreakAfterOpenBracketFunction =
false;
1009 Style.BreakAfterOpenBracketIf =
false;
1010 Style.BreakAfterOpenBracketLoop =
false;
1011 Style.BreakAfterOpenBracketSwitch =
false;
1012 Style.BreakBeforeCloseBracketBracedList =
false;
1013 Style.BreakBeforeCloseBracketFunction =
false;
1014 Style.BreakBeforeCloseBracketIf =
false;
1015 Style.BreakBeforeCloseBracketLoop =
false;
1016 Style.BreakBeforeCloseBracketSwitch =
false;
1020 Style.AlignAfterOpenBracket =
false;
1023 Style.BreakBeforeCloseBracketBracedList =
true;
1024 Style.BreakBeforeCloseBracketFunction =
true;
1025 Style.BreakBeforeCloseBracketIf =
true;
1028 Style.BreakAfterOpenBracketBracedList =
true;
1029 Style.BreakAfterOpenBracketFunction =
true;
1030 Style.BreakAfterOpenBracketIf =
true;
1033 Style.AlignAfterOpenBracket =
true;
1039 if (!IO.outputting()) {
1040 IO.mapOptional(
"AlignEscapedNewlinesLeft", Style.AlignEscapedNewlines);
1041 IO.mapOptional(
"AllowAllConstructorInitializersOnNextLine", OnNextLine);
1042 IO.mapOptional(
"AlwaysBreakAfterReturnType", Style.BreakAfterReturnType);
1043 IO.mapOptional(
"AlwaysBreakTemplateDeclarations",
1044 Style.BreakTemplateDeclarations);
1045 IO.mapOptional(
"BreakBeforeInheritanceComma",
1046 BreakBeforeInheritanceComma);
1047 IO.mapOptional(
"BreakConstructorInitializersBeforeComma",
1048 BreakConstructorInitializersBeforeComma);
1049 IO.mapOptional(
"ConstructorInitializerAllOnOneLineOrOnePerLine",
1051 IO.mapOptional(
"DeriveLineEnding", DeriveLineEnding);
1052 IO.mapOptional(
"DerivePointerBinding", Style.DerivePointerAlignment);
1053 IO.mapOptional(
"KeepEmptyLinesAtEOF", Style.KeepEmptyLines.AtEndOfFile);
1054 IO.mapOptional(
"KeepEmptyLinesAtTheStartOfBlocks",
1055 Style.KeepEmptyLines.AtStartOfBlock);
1056 IO.mapOptional(
"IndentFunctionDeclarationAfterType",
1057 Style.IndentWrappedFunctionNames);
1058 IO.mapOptional(
"IndentRequires", Style.IndentRequiresClause);
1059 IO.mapOptional(
"PointerBindsToType", Style.PointerAlignment);
1060 IO.mapOptional(
"SpaceAfterControlStatementKeyword",
1061 Style.SpaceBeforeParens);
1062 IO.mapOptional(
"SpaceInEmptyBlock", SpaceInEmptyBlock);
1063 IO.mapOptional(
"SpaceInEmptyParentheses", SpaceInEmptyParentheses);
1064 IO.mapOptional(
"SpacesInConditionalStatement",
1065 SpacesInConditionalStatement);
1066 IO.mapOptional(
"SpacesInCStyleCastParentheses",
1067 SpacesInCStyleCastParentheses);
1068 IO.mapOptional(
"SpacesInParentheses", SpacesInParentheses);
1069 IO.mapOptional(
"UseCRLF", UseCRLF);
1072 IO.mapOptional(
"AccessModifierOffset", Style.AccessModifierOffset);
1073 IO.mapOptional(
"AlignArrayOfStructures", Style.AlignArrayOfStructures);
1074 IO.mapOptional(
"AlignConsecutiveAssignments",
1075 Style.AlignConsecutiveAssignments);
1076 IO.mapOptional(
"AlignConsecutiveBitFields",
1077 Style.AlignConsecutiveBitFields);
1078 IO.mapOptional(
"AlignConsecutiveDeclarations",
1079 Style.AlignConsecutiveDeclarations);
1080 IO.mapOptional(
"AlignConsecutiveMacros", Style.AlignConsecutiveMacros);
1081 IO.mapOptional(
"AlignConsecutiveShortCaseStatements",
1082 Style.AlignConsecutiveShortCaseStatements);
1083 IO.mapOptional(
"AlignConsecutiveTableGenBreakingDAGArgColons",
1084 Style.AlignConsecutiveTableGenBreakingDAGArgColons);
1085 IO.mapOptional(
"AlignConsecutiveTableGenCondOperatorColons",
1086 Style.AlignConsecutiveTableGenCondOperatorColons);
1087 IO.mapOptional(
"AlignConsecutiveTableGenDefinitionColons",
1088 Style.AlignConsecutiveTableGenDefinitionColons);
1089 IO.mapOptional(
"AlignEscapedNewlines", Style.AlignEscapedNewlines);
1090 IO.mapOptional(
"AlignOperands", Style.AlignOperands);
1091 IO.mapOptional(
"AlignTrailingComments", Style.AlignTrailingComments);
1092 IO.mapOptional(
"AllowAllArgumentsOnNextLine",
1093 Style.AllowAllArgumentsOnNextLine);
1094 IO.mapOptional(
"AllowAllParametersOfDeclarationOnNextLine",
1095 Style.AllowAllParametersOfDeclarationOnNextLine);
1096 IO.mapOptional(
"AllowBreakBeforeNoexceptSpecifier",
1097 Style.AllowBreakBeforeNoexceptSpecifier);
1098 IO.mapOptional(
"AllowBreakBeforeQtProperty",
1099 Style.AllowBreakBeforeQtProperty);
1100 IO.mapOptional(
"AllowShortBlocksOnASingleLine",
1101 Style.AllowShortBlocksOnASingleLine);
1102 IO.mapOptional(
"AllowShortCaseExpressionOnASingleLine",
1103 Style.AllowShortCaseExpressionOnASingleLine);
1104 IO.mapOptional(
"AllowShortCaseLabelsOnASingleLine",
1105 Style.AllowShortCaseLabelsOnASingleLine);
1106 IO.mapOptional(
"AllowShortCompoundRequirementOnASingleLine",
1107 Style.AllowShortCompoundRequirementOnASingleLine);
1108 IO.mapOptional(
"AllowShortEnumsOnASingleLine",
1109 Style.AllowShortEnumsOnASingleLine);
1110 IO.mapOptional(
"AllowShortFunctionsOnASingleLine",
1111 Style.AllowShortFunctionsOnASingleLine);
1112 IO.mapOptional(
"AllowShortIfStatementsOnASingleLine",
1113 Style.AllowShortIfStatementsOnASingleLine);
1114 IO.mapOptional(
"AllowShortLambdasOnASingleLine",
1115 Style.AllowShortLambdasOnASingleLine);
1116 IO.mapOptional(
"AllowShortLoopsOnASingleLine",
1117 Style.AllowShortLoopsOnASingleLine);
1118 IO.mapOptional(
"AllowShortNamespacesOnASingleLine",
1119 Style.AllowShortNamespacesOnASingleLine);
1120 IO.mapOptional(
"AlwaysBreakAfterDefinitionReturnType",
1121 Style.AlwaysBreakAfterDefinitionReturnType);
1122 IO.mapOptional(
"AlwaysBreakBeforeMultilineStrings",
1123 Style.AlwaysBreakBeforeMultilineStrings);
1124 IO.mapOptional(
"AttributeMacros", Style.AttributeMacros);
1125 IO.mapOptional(
"BinPackArguments", Style.BinPackArguments);
1126 IO.mapOptional(
"BinPackLongBracedList", Style.BinPackLongBracedList);
1127 IO.mapOptional(
"BinPackParameters", Style.BinPackParameters);
1128 IO.mapOptional(
"BitFieldColonSpacing", Style.BitFieldColonSpacing);
1129 IO.mapOptional(
"BracedInitializerIndentWidth",
1130 Style.BracedInitializerIndentWidth);
1131 IO.mapOptional(
"BraceWrapping", Style.BraceWrapping);
1132 IO.mapOptional(
"BreakAdjacentStringLiterals",
1133 Style.BreakAdjacentStringLiterals);
1134 IO.mapOptional(
"BreakAfterAttributes", Style.BreakAfterAttributes);
1135 IO.mapOptional(
"BreakAfterJavaFieldAnnotations",
1136 Style.BreakAfterJavaFieldAnnotations);
1137 IO.mapOptional(
"BreakAfterOpenBracketBracedList",
1138 Style.BreakAfterOpenBracketBracedList);
1139 IO.mapOptional(
"BreakAfterOpenBracketFunction",
1140 Style.BreakAfterOpenBracketFunction);
1141 IO.mapOptional(
"BreakAfterOpenBracketIf", Style.BreakAfterOpenBracketIf);
1142 IO.mapOptional(
"BreakAfterOpenBracketLoop",
1143 Style.BreakAfterOpenBracketLoop);
1144 IO.mapOptional(
"BreakAfterOpenBracketSwitch",
1145 Style.BreakAfterOpenBracketSwitch);
1146 IO.mapOptional(
"BreakAfterReturnType", Style.BreakAfterReturnType);
1147 IO.mapOptional(
"BreakArrays", Style.BreakArrays);
1148 IO.mapOptional(
"BreakBeforeBinaryOperators",
1149 Style.BreakBeforeBinaryOperators);
1150 IO.mapOptional(
"BreakBeforeCloseBracketBracedList",
1151 Style.BreakBeforeCloseBracketBracedList);
1152 IO.mapOptional(
"BreakBeforeCloseBracketFunction",
1153 Style.BreakBeforeCloseBracketFunction);
1154 IO.mapOptional(
"BreakBeforeCloseBracketIf",
1155 Style.BreakBeforeCloseBracketIf);
1156 IO.mapOptional(
"BreakBeforeCloseBracketLoop",
1157 Style.BreakBeforeCloseBracketLoop);
1158 IO.mapOptional(
"BreakBeforeCloseBracketSwitch",
1159 Style.BreakBeforeCloseBracketSwitch);
1160 IO.mapOptional(
"BreakBeforeConceptDeclarations",
1161 Style.BreakBeforeConceptDeclarations);
1162 IO.mapOptional(
"BreakBeforeBraces", Style.BreakBeforeBraces);
1163 IO.mapOptional(
"BreakBeforeInlineASMColon",
1164 Style.BreakBeforeInlineASMColon);
1165 IO.mapOptional(
"BreakBeforeTemplateCloser",
1166 Style.BreakBeforeTemplateCloser);
1167 IO.mapOptional(
"BreakBeforeTernaryOperators",
1168 Style.BreakBeforeTernaryOperators);
1169 IO.mapOptional(
"BreakBinaryOperations", Style.BreakBinaryOperations);
1170 IO.mapOptional(
"BreakConstructorInitializers",
1171 Style.BreakConstructorInitializers);
1172 IO.mapOptional(
"BreakFunctionDefinitionParameters",
1173 Style.BreakFunctionDefinitionParameters);
1174 IO.mapOptional(
"BreakInheritanceList", Style.BreakInheritanceList);
1175 IO.mapOptional(
"BreakStringLiterals", Style.BreakStringLiterals);
1176 IO.mapOptional(
"BreakTemplateDeclarations",
1177 Style.BreakTemplateDeclarations);
1178 IO.mapOptional(
"ColumnLimit", Style.ColumnLimit);
1179 IO.mapOptional(
"CommentPragmas", Style.CommentPragmas);
1180 IO.mapOptional(
"CompactNamespaces", Style.CompactNamespaces);
1181 IO.mapOptional(
"ConstructorInitializerIndentWidth",
1182 Style.ConstructorInitializerIndentWidth);
1183 IO.mapOptional(
"ContinuationIndentWidth", Style.ContinuationIndentWidth);
1184 IO.mapOptional(
"Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
1185 IO.mapOptional(
"DerivePointerAlignment", Style.DerivePointerAlignment);
1186 IO.mapOptional(
"DisableFormat", Style.DisableFormat);
1187 IO.mapOptional(
"EmptyLineAfterAccessModifier",
1188 Style.EmptyLineAfterAccessModifier);
1189 IO.mapOptional(
"EmptyLineBeforeAccessModifier",
1190 Style.EmptyLineBeforeAccessModifier);
1191 IO.mapOptional(
"EnumTrailingComma", Style.EnumTrailingComma);
1192 IO.mapOptional(
"ExperimentalAutoDetectBinPacking",
1193 Style.ExperimentalAutoDetectBinPacking);
1194 IO.mapOptional(
"FixNamespaceComments", Style.FixNamespaceComments);
1195 IO.mapOptional(
"ForEachMacros", Style.ForEachMacros);
1196 IO.mapOptional(
"IfMacros", Style.IfMacros);
1197 IO.mapOptional(
"IncludeBlocks", Style.IncludeStyle.IncludeBlocks);
1198 IO.mapOptional(
"IncludeCategories", Style.IncludeStyle.IncludeCategories);
1199 IO.mapOptional(
"IncludeIsMainRegex", Style.IncludeStyle.IncludeIsMainRegex);
1200 IO.mapOptional(
"IncludeIsMainSourceRegex",
1201 Style.IncludeStyle.IncludeIsMainSourceRegex);
1202 IO.mapOptional(
"IndentAccessModifiers", Style.IndentAccessModifiers);
1203 IO.mapOptional(
"IndentCaseBlocks", Style.IndentCaseBlocks);
1204 IO.mapOptional(
"IndentCaseLabels", Style.IndentCaseLabels);
1205 IO.mapOptional(
"IndentExportBlock", Style.IndentExportBlock);
1206 IO.mapOptional(
"IndentExternBlock", Style.IndentExternBlock);
1207 IO.mapOptional(
"IndentGotoLabels", Style.IndentGotoLabels);
1208 IO.mapOptional(
"IndentPPDirectives", Style.IndentPPDirectives);
1209 IO.mapOptional(
"IndentRequiresClause", Style.IndentRequiresClause);
1210 IO.mapOptional(
"IndentWidth", Style.IndentWidth);
1211 IO.mapOptional(
"IndentWrappedFunctionNames",
1212 Style.IndentWrappedFunctionNames);
1213 IO.mapOptional(
"InsertBraces", Style.InsertBraces);
1214 IO.mapOptional(
"InsertNewlineAtEOF", Style.InsertNewlineAtEOF);
1215 IO.mapOptional(
"InsertTrailingCommas", Style.InsertTrailingCommas);
1216 IO.mapOptional(
"IntegerLiteralSeparator", Style.IntegerLiteralSeparator);
1217 IO.mapOptional(
"JavaImportGroups", Style.JavaImportGroups);
1218 IO.mapOptional(
"JavaScriptQuotes", Style.JavaScriptQuotes);
1219 IO.mapOptional(
"JavaScriptWrapImports", Style.JavaScriptWrapImports);
1220 IO.mapOptional(
"KeepEmptyLines", Style.KeepEmptyLines);
1221 IO.mapOptional(
"KeepFormFeed", Style.KeepFormFeed);
1222 IO.mapOptional(
"LambdaBodyIndentation", Style.LambdaBodyIndentation);
1223 IO.mapOptional(
"LineEnding", Style.LineEnding);
1224 IO.mapOptional(
"MacroBlockBegin", Style.MacroBlockBegin);
1225 IO.mapOptional(
"MacroBlockEnd", Style.MacroBlockEnd);
1226 IO.mapOptional(
"Macros", Style.Macros);
1227 IO.mapOptional(
"MacrosSkippedByRemoveParentheses",
1228 Style.MacrosSkippedByRemoveParentheses);
1229 IO.mapOptional(
"MainIncludeChar", Style.IncludeStyle.MainIncludeChar);
1230 IO.mapOptional(
"MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
1231 IO.mapOptional(
"NamespaceIndentation", Style.NamespaceIndentation);
1232 IO.mapOptional(
"NamespaceMacros", Style.NamespaceMacros);
1233 IO.mapOptional(
"NumericLiteralCase", Style.NumericLiteralCase);
1234 IO.mapOptional(
"ObjCBinPackProtocolList", Style.ObjCBinPackProtocolList);
1235 IO.mapOptional(
"ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
1236 IO.mapOptional(
"ObjCBreakBeforeNestedBlockParam",
1237 Style.ObjCBreakBeforeNestedBlockParam);
1238 IO.mapOptional(
"ObjCPropertyAttributeOrder",
1239 Style.ObjCPropertyAttributeOrder);
1240 IO.mapOptional(
"ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
1241 IO.mapOptional(
"ObjCSpaceBeforeProtocolList",
1242 Style.ObjCSpaceBeforeProtocolList);
1243 IO.mapOptional(
"OneLineFormatOffRegex", Style.OneLineFormatOffRegex);
1244 IO.mapOptional(
"PackConstructorInitializers",
1245 Style.PackConstructorInitializers);
1246 IO.mapOptional(
"PenaltyBreakAssignment", Style.PenaltyBreakAssignment);
1247 IO.mapOptional(
"PenaltyBreakBeforeFirstCallParameter",
1248 Style.PenaltyBreakBeforeFirstCallParameter);
1249 IO.mapOptional(
"PenaltyBreakBeforeMemberAccess",
1250 Style.PenaltyBreakBeforeMemberAccess);
1251 IO.mapOptional(
"PenaltyBreakComment", Style.PenaltyBreakComment);
1252 IO.mapOptional(
"PenaltyBreakFirstLessLess",
1253 Style.PenaltyBreakFirstLessLess);
1254 IO.mapOptional(
"PenaltyBreakOpenParenthesis",
1255 Style.PenaltyBreakOpenParenthesis);
1256 IO.mapOptional(
"PenaltyBreakScopeResolution",
1257 Style.PenaltyBreakScopeResolution);
1258 IO.mapOptional(
"PenaltyBreakString", Style.PenaltyBreakString);
1259 IO.mapOptional(
"PenaltyBreakTemplateDeclaration",
1260 Style.PenaltyBreakTemplateDeclaration);
1261 IO.mapOptional(
"PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
1262 IO.mapOptional(
"PenaltyIndentedWhitespace",
1263 Style.PenaltyIndentedWhitespace);
1264 IO.mapOptional(
"PenaltyReturnTypeOnItsOwnLine",
1265 Style.PenaltyReturnTypeOnItsOwnLine);
1266 IO.mapOptional(
"PointerAlignment", Style.PointerAlignment);
1267 IO.mapOptional(
"PPIndentWidth", Style.PPIndentWidth);
1268 IO.mapOptional(
"QualifierAlignment", Style.QualifierAlignment);
1270 if (Style.QualifierAlignment == FormatStyle::QAS_Right)
1271 Style.QualifierOrder = {
"type",
"const",
"volatile"};
1272 else if (Style.QualifierAlignment == FormatStyle::QAS_Left)
1273 Style.QualifierOrder = {
"const",
"volatile",
"type"};
1274 else if (Style.QualifierAlignment == FormatStyle::QAS_Custom)
1275 IO.mapOptional(
"QualifierOrder", Style.QualifierOrder);
1276 IO.mapOptional(
"RawStringFormats", Style.RawStringFormats);
1277 IO.mapOptional(
"ReferenceAlignment", Style.ReferenceAlignment);
1278 IO.mapOptional(
"ReflowComments", Style.ReflowComments);
1279 IO.mapOptional(
"RemoveBracesLLVM", Style.RemoveBracesLLVM);
1280 IO.mapOptional(
"RemoveEmptyLinesInUnwrappedLines",
1281 Style.RemoveEmptyLinesInUnwrappedLines);
1282 IO.mapOptional(
"RemoveParentheses", Style.RemoveParentheses);
1283 IO.mapOptional(
"RemoveSemicolon", Style.RemoveSemicolon);
1284 IO.mapOptional(
"RequiresClausePosition", Style.RequiresClausePosition);
1285 IO.mapOptional(
"RequiresExpressionIndentation",
1286 Style.RequiresExpressionIndentation);
1287 IO.mapOptional(
"SeparateDefinitionBlocks", Style.SeparateDefinitionBlocks);
1288 IO.mapOptional(
"ShortNamespaceLines", Style.ShortNamespaceLines);
1289 IO.mapOptional(
"SkipMacroDefinitionBody", Style.SkipMacroDefinitionBody);
1290 IO.mapOptional(
"SortIncludes", Style.SortIncludes);
1291 IO.mapOptional(
"SortJavaStaticImport", Style.SortJavaStaticImport);
1292 IO.mapOptional(
"SortUsingDeclarations", Style.SortUsingDeclarations);
1293 IO.mapOptional(
"SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
1294 IO.mapOptional(
"SpaceAfterLogicalNot", Style.SpaceAfterLogicalNot);
1295 IO.mapOptional(
"SpaceAfterOperatorKeyword",
1296 Style.SpaceAfterOperatorKeyword);
1297 IO.mapOptional(
"SpaceAfterTemplateKeyword",
1298 Style.SpaceAfterTemplateKeyword);
1299 IO.mapOptional(
"SpaceAroundPointerQualifiers",
1300 Style.SpaceAroundPointerQualifiers);
1301 IO.mapOptional(
"SpaceBeforeAssignmentOperators",
1302 Style.SpaceBeforeAssignmentOperators);
1303 IO.mapOptional(
"SpaceBeforeCaseColon", Style.SpaceBeforeCaseColon);
1304 IO.mapOptional(
"SpaceBeforeCpp11BracedList",
1305 Style.SpaceBeforeCpp11BracedList);
1306 IO.mapOptional(
"SpaceBeforeCtorInitializerColon",
1307 Style.SpaceBeforeCtorInitializerColon);
1308 IO.mapOptional(
"SpaceBeforeInheritanceColon",
1309 Style.SpaceBeforeInheritanceColon);
1310 IO.mapOptional(
"SpaceBeforeJsonColon", Style.SpaceBeforeJsonColon);
1311 IO.mapOptional(
"SpaceBeforeParens", Style.SpaceBeforeParens);
1312 IO.mapOptional(
"SpaceBeforeParensOptions", Style.SpaceBeforeParensOptions);
1313 IO.mapOptional(
"SpaceBeforeRangeBasedForLoopColon",
1314 Style.SpaceBeforeRangeBasedForLoopColon);
1315 IO.mapOptional(
"SpaceBeforeSquareBrackets",
1316 Style.SpaceBeforeSquareBrackets);
1317 IO.mapOptional(
"SpaceInEmptyBraces", Style.SpaceInEmptyBraces);
1318 IO.mapOptional(
"SpacesBeforeTrailingComments",
1319 Style.SpacesBeforeTrailingComments);
1320 IO.mapOptional(
"SpacesInAngles", Style.SpacesInAngles);
1321 IO.mapOptional(
"SpacesInContainerLiterals",
1322 Style.SpacesInContainerLiterals);
1323 IO.mapOptional(
"SpacesInLineCommentPrefix",
1324 Style.SpacesInLineCommentPrefix);
1325 IO.mapOptional(
"SpacesInParens", Style.SpacesInParens);
1326 IO.mapOptional(
"SpacesInParensOptions", Style.SpacesInParensOptions);
1327 IO.mapOptional(
"SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
1328 IO.mapOptional(
"Standard", Style.Standard);
1329 IO.mapOptional(
"StatementAttributeLikeMacros",
1330 Style.StatementAttributeLikeMacros);
1331 IO.mapOptional(
"StatementMacros", Style.StatementMacros);
1332 IO.mapOptional(
"TableGenBreakingDAGArgOperators",
1333 Style.TableGenBreakingDAGArgOperators);
1334 IO.mapOptional(
"TableGenBreakInsideDAGArg",
1335 Style.TableGenBreakInsideDAGArg);
1336 IO.mapOptional(
"TabWidth", Style.TabWidth);
1337 IO.mapOptional(
"TemplateNames", Style.TemplateNames);
1338 IO.mapOptional(
"TypeNames", Style.TypeNames);
1339 IO.mapOptional(
"TypenameMacros", Style.TypenameMacros);
1340 IO.mapOptional(
"UseTab", Style.UseTab);
1341 IO.mapOptional(
"VariableTemplates", Style.VariableTemplates);
1342 IO.mapOptional(
"VerilogBreakBetweenInstancePorts",
1343 Style.VerilogBreakBetweenInstancePorts);
1344 IO.mapOptional(
"WhitespaceSensitiveMacros",
1345 Style.WhitespaceSensitiveMacros);
1346 IO.mapOptional(
"WrapNamespaceBodyWithEmptyLines",
1347 Style.WrapNamespaceBodyWithEmptyLines);
1352 if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
1353 Style.BreakAfterReturnType == FormatStyle::RTBS_None) {
1354 if (Style.AlwaysBreakAfterDefinitionReturnType ==
1355 FormatStyle::DRTBS_All) {
1356 Style.BreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
1357 }
else if (Style.AlwaysBreakAfterDefinitionReturnType ==
1358 FormatStyle::DRTBS_TopLevel) {
1359 Style.BreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
1365 if (BreakBeforeInheritanceComma &&
1366 Style.BreakInheritanceList == FormatStyle::BILS_BeforeColon) {
1367 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
1373 if (BreakConstructorInitializersBeforeComma &&
1374 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon) {
1375 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
1378 if (!IsGoogleOrChromium) {
1379 if (Style.PackConstructorInitializers == FormatStyle::PCIS_BinPack &&
1381 Style.PackConstructorInitializers = OnNextLine
1382 ? FormatStyle::PCIS_NextLine
1383 : FormatStyle::PCIS_CurrentLine;
1385 }
else if (Style.PackConstructorInitializers ==
1386 FormatStyle::PCIS_NextLine) {
1388 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
1389 else if (!OnNextLine)
1390 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
1393 if (Style.LineEnding == FormatStyle::LE_DeriveLF) {
1394 if (!DeriveLineEnding)
1395 Style.LineEnding = UseCRLF ? FormatStyle::LE_CRLF : FormatStyle::LE_LF;
1397 Style.LineEnding = FormatStyle::LE_DeriveCRLF;
1402 if (SpaceInEmptyBlock &&
1403 Style.SpaceInEmptyBraces == FormatStyle::SIEB_Never) {
1404 Style.SpaceInEmptyBraces = FormatStyle::SIEB_Block;
1407 if (Style.SpacesInParens != FormatStyle::SIPO_Custom &&
1408 (SpacesInParentheses || SpaceInEmptyParentheses ||
1409 SpacesInConditionalStatement || SpacesInCStyleCastParentheses)) {
1410 if (SpacesInParentheses) {
1412 Style.SpacesInParensOptions.ExceptDoubleParentheses =
false;
1413 Style.SpacesInParensOptions.InConditionalStatements =
true;
1414 Style.SpacesInParensOptions.InCStyleCasts =
1415 SpacesInCStyleCastParentheses;
1416 Style.SpacesInParensOptions.InEmptyParentheses =
1417 SpaceInEmptyParentheses;
1418 Style.SpacesInParensOptions.Other =
true;
1420 Style.SpacesInParensOptions = {};
1421 Style.SpacesInParensOptions.InConditionalStatements =
1422 SpacesInConditionalStatement;
1423 Style.SpacesInParensOptions.InCStyleCasts =
1424 SpacesInCStyleCastParentheses;
1425 Style.SpacesInParensOptions.InEmptyParentheses =
1426 SpaceInEmptyParentheses;
1428 Style.SpacesInParens = FormatStyle::SIPO_Custom;
1438template <>
struct DocumentListTraits<
std::vector<FormatStyle>> {
1439 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
1442 static FormatStyle &
element(IO &IO, std::vector<FormatStyle> &Seq,
1444 if (Index >= Seq.size()) {
1445 assert(Index == Seq.size());
1446 FormatStyle Template;
1447 if (!Seq.empty() && Seq[0].Language == FormatStyle::LK_None) {
1450 Template = *((
const FormatStyle *)IO.getContext());
1451 Template.Language = FormatStyle::LK_None;
1453 Seq.resize(Index + 1, Template);
1473 return llvm::make_error<llvm::StringError>(Message,
1474 llvm::inconvertibleErrorCode());
1478 return "clang-format.parse_error";
1486 return "Invalid argument";
1488 return "Unsuitable";
1490 return "trailing comma insertion cannot be used with bin packing";
1492 return "Invalid qualifier specified in QualifierOrder";
1494 return "Duplicate qualifier specified in QualifierOrder";
1496 return "Missing type in QualifierOrder";
1498 return "Missing QualifierOrder";
1500 llvm_unreachable(
"unexpected parse error");
1504 if (Expanded.BreakBeforeBraces == FormatStyle::BS_Custom)
1506 Expanded.BraceWrapping = {
false,
1508 FormatStyle::BWACS_Never,
1524 switch (Expanded.BreakBeforeBraces) {
1525 case FormatStyle::BS_Linux:
1526 Expanded.BraceWrapping.AfterClass =
true;
1527 Expanded.BraceWrapping.AfterFunction =
true;
1528 Expanded.BraceWrapping.AfterNamespace =
true;
1530 case FormatStyle::BS_Mozilla:
1531 Expanded.BraceWrapping.AfterClass =
true;
1532 Expanded.BraceWrapping.AfterEnum =
true;
1533 Expanded.BraceWrapping.AfterFunction =
true;
1534 Expanded.BraceWrapping.AfterStruct =
true;
1535 Expanded.BraceWrapping.AfterUnion =
true;
1536 Expanded.BraceWrapping.AfterExternBlock =
true;
1537 Expanded.BraceWrapping.SplitEmptyFunction =
true;
1538 Expanded.BraceWrapping.SplitEmptyRecord =
false;
1540 case FormatStyle::BS_Stroustrup:
1541 Expanded.BraceWrapping.AfterFunction =
true;
1542 Expanded.BraceWrapping.BeforeCatch =
true;
1543 Expanded.BraceWrapping.BeforeElse =
true;
1545 case FormatStyle::BS_Allman:
1546 Expanded.BraceWrapping.AfterCaseLabel =
true;
1547 Expanded.BraceWrapping.AfterClass =
true;
1548 Expanded.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1549 Expanded.BraceWrapping.AfterEnum =
true;
1550 Expanded.BraceWrapping.AfterFunction =
true;
1551 Expanded.BraceWrapping.AfterNamespace =
true;
1552 Expanded.BraceWrapping.AfterObjCDeclaration =
true;
1553 Expanded.BraceWrapping.AfterStruct =
true;
1554 Expanded.BraceWrapping.AfterUnion =
true;
1555 Expanded.BraceWrapping.AfterExternBlock =
true;
1556 Expanded.BraceWrapping.BeforeCatch =
true;
1557 Expanded.BraceWrapping.BeforeElse =
true;
1558 Expanded.BraceWrapping.BeforeLambdaBody =
true;
1560 case FormatStyle::BS_Whitesmiths:
1561 Expanded.BraceWrapping.AfterCaseLabel =
true;
1562 Expanded.BraceWrapping.AfterClass =
true;
1563 Expanded.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1564 Expanded.BraceWrapping.AfterEnum =
true;
1565 Expanded.BraceWrapping.AfterFunction =
true;
1566 Expanded.BraceWrapping.AfterNamespace =
true;
1567 Expanded.BraceWrapping.AfterObjCDeclaration =
true;
1568 Expanded.BraceWrapping.AfterStruct =
true;
1569 Expanded.BraceWrapping.AfterExternBlock =
true;
1570 Expanded.BraceWrapping.BeforeCatch =
true;
1571 Expanded.BraceWrapping.BeforeElse =
true;
1572 Expanded.BraceWrapping.BeforeLambdaBody =
true;
1574 case FormatStyle::BS_GNU:
1575 Expanded.BraceWrapping = {
1578 FormatStyle::BWACS_Always,
1595 case FormatStyle::BS_WebKit:
1596 Expanded.BraceWrapping.AfterFunction =
true;
1604 if (Expanded.SpaceBeforeParens == FormatStyle::SBPO_Custom)
1607 Expanded.SpaceBeforeParensOptions = {};
1608 Expanded.SpaceBeforeParensOptions.AfterPlacementOperator =
true;
1610 switch (Expanded.SpaceBeforeParens) {
1611 case FormatStyle::SBPO_ControlStatements:
1612 Expanded.SpaceBeforeParensOptions.AfterControlStatements =
true;
1613 Expanded.SpaceBeforeParensOptions.AfterForeachMacros =
true;
1614 Expanded.SpaceBeforeParensOptions.AfterIfMacros =
true;
1616 case FormatStyle::SBPO_ControlStatementsExceptControlMacros:
1617 Expanded.SpaceBeforeParensOptions.AfterControlStatements =
true;
1619 case FormatStyle::SBPO_NonEmptyParentheses:
1620 Expanded.SpaceBeforeParensOptions.BeforeNonEmptyParentheses =
true;
1628 if (Expanded.SpacesInParens == FormatStyle::SIPO_Custom)
1630 assert(Expanded.SpacesInParens == FormatStyle::SIPO_Never);
1632 Expanded.SpacesInParensOptions = {};
1636 FormatStyle LLVMStyle;
1637 LLVMStyle.AccessModifierOffset = -2;
1638 LLVMStyle.AlignAfterOpenBracket =
true;
1639 LLVMStyle.AlignArrayOfStructures = FormatStyle::AIAS_None;
1640 LLVMStyle.AlignConsecutiveAssignments = {};
1641 LLVMStyle.AlignConsecutiveAssignments.PadOperators =
true;
1642 LLVMStyle.AlignConsecutiveBitFields = {};
1643 LLVMStyle.AlignConsecutiveDeclarations = {};
1644 LLVMStyle.AlignConsecutiveDeclarations.AlignFunctionDeclarations =
true;
1645 LLVMStyle.AlignConsecutiveMacros = {};
1646 LLVMStyle.AlignConsecutiveShortCaseStatements = {};
1647 LLVMStyle.AlignConsecutiveTableGenBreakingDAGArgColons = {};
1648 LLVMStyle.AlignConsecutiveTableGenCondOperatorColons = {};
1649 LLVMStyle.AlignConsecutiveTableGenDefinitionColons = {};
1650 LLVMStyle.AlignEscapedNewlines = FormatStyle::ENAS_Right;
1651 LLVMStyle.AlignOperands = FormatStyle::OAS_Align;
1652 LLVMStyle.AlignTrailingComments = {};
1653 LLVMStyle.AlignTrailingComments.Kind = FormatStyle::TCAS_Always;
1654 LLVMStyle.AlignTrailingComments.OverEmptyLines = 0;
1655 LLVMStyle.AlignTrailingComments.AlignPPAndNotPP =
true;
1656 LLVMStyle.AllowAllArgumentsOnNextLine =
true;
1657 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine =
true;
1658 LLVMStyle.AllowBreakBeforeNoexceptSpecifier = FormatStyle::BBNSS_Never;
1659 LLVMStyle.AllowBreakBeforeQtProperty =
false;
1660 LLVMStyle.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
1661 LLVMStyle.AllowShortCaseExpressionOnASingleLine =
true;
1662 LLVMStyle.AllowShortCaseLabelsOnASingleLine =
false;
1663 LLVMStyle.AllowShortCompoundRequirementOnASingleLine =
true;
1664 LLVMStyle.AllowShortEnumsOnASingleLine =
true;
1665 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
1666 LLVMStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
1667 LLVMStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
1668 LLVMStyle.AllowShortLoopsOnASingleLine =
false;
1669 LLVMStyle.AllowShortNamespacesOnASingleLine =
false;
1670 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
1671 LLVMStyle.AlwaysBreakBeforeMultilineStrings =
false;
1672 LLVMStyle.AttributeMacros.push_back(
"__capability");
1673 LLVMStyle.BinPackArguments =
true;
1674 LLVMStyle.BinPackLongBracedList =
true;
1675 LLVMStyle.BinPackParameters = FormatStyle::BPPS_BinPack;
1676 LLVMStyle.BitFieldColonSpacing = FormatStyle::BFCS_Both;
1677 LLVMStyle.BracedInitializerIndentWidth = -1;
1678 LLVMStyle.BraceWrapping = {
false,
1680 FormatStyle::BWACS_Never,
1696 LLVMStyle.BreakAdjacentStringLiterals =
true;
1697 LLVMStyle.BreakAfterAttributes = FormatStyle::ABS_Leave;
1698 LLVMStyle.BreakAfterJavaFieldAnnotations =
false;
1699 LLVMStyle.BreakAfterOpenBracketBracedList =
false;
1700 LLVMStyle.BreakAfterOpenBracketFunction =
false;
1701 LLVMStyle.BreakAfterOpenBracketIf =
false;
1702 LLVMStyle.BreakAfterOpenBracketLoop =
false;
1703 LLVMStyle.BreakAfterOpenBracketSwitch =
false;
1704 LLVMStyle.BreakAfterReturnType = FormatStyle::RTBS_None;
1705 LLVMStyle.BreakArrays =
true;
1706 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
1707 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
1708 LLVMStyle.BreakBeforeCloseBracketBracedList =
false;
1709 LLVMStyle.BreakBeforeCloseBracketFunction =
false;
1710 LLVMStyle.BreakBeforeCloseBracketIf =
false;
1711 LLVMStyle.BreakBeforeCloseBracketLoop =
false;
1712 LLVMStyle.BreakBeforeCloseBracketSwitch =
false;
1713 LLVMStyle.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Always;
1714 LLVMStyle.BreakBeforeInlineASMColon = FormatStyle::BBIAS_OnlyMultiline;
1715 LLVMStyle.BreakBeforeTemplateCloser =
false;
1716 LLVMStyle.BreakBeforeTernaryOperators =
true;
1717 LLVMStyle.BreakBinaryOperations = FormatStyle::BBO_Never;
1718 LLVMStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
1719 LLVMStyle.BreakFunctionDefinitionParameters =
false;
1720 LLVMStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
1721 LLVMStyle.BreakStringLiterals =
true;
1722 LLVMStyle.BreakTemplateDeclarations = FormatStyle::BTDS_MultiLine;
1723 LLVMStyle.ColumnLimit = 80;
1724 LLVMStyle.CommentPragmas =
"^ IWYU pragma:";
1725 LLVMStyle.CompactNamespaces =
false;
1726 LLVMStyle.ConstructorInitializerIndentWidth = 4;
1727 LLVMStyle.ContinuationIndentWidth = 4;
1728 LLVMStyle.Cpp11BracedListStyle = FormatStyle::BLS_AlignFirstComment;
1729 LLVMStyle.DerivePointerAlignment =
false;
1730 LLVMStyle.DisableFormat =
false;
1731 LLVMStyle.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
1732 LLVMStyle.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
1733 LLVMStyle.EnumTrailingComma = FormatStyle::ETC_Leave;
1734 LLVMStyle.ExperimentalAutoDetectBinPacking =
false;
1735 LLVMStyle.FixNamespaceComments =
true;
1736 LLVMStyle.ForEachMacros.push_back(
"foreach");
1737 LLVMStyle.ForEachMacros.push_back(
"Q_FOREACH");
1738 LLVMStyle.ForEachMacros.push_back(
"BOOST_FOREACH");
1739 LLVMStyle.IfMacros.push_back(
"KJ_IF_MAYBE");
1741 LLVMStyle.IncludeStyle.IncludeCategories = {
1742 {
"^\"(llvm|llvm-c|clang|clang-c)/", 2, 0,
false},
1743 {
"^(<|\"(gtest|gmock|isl|json)/)", 3, 0,
false},
1744 {
".*", 1, 0,
false}};
1745 LLVMStyle.IncludeStyle.IncludeIsMainRegex =
"(Test)?$";
1746 LLVMStyle.IncludeStyle.MainIncludeChar = tooling::IncludeStyle::MICD_Quote;
1747 LLVMStyle.IndentAccessModifiers =
false;
1748 LLVMStyle.IndentCaseBlocks =
false;
1749 LLVMStyle.IndentCaseLabels =
false;
1750 LLVMStyle.IndentExportBlock =
true;
1751 LLVMStyle.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
1752 LLVMStyle.IndentGotoLabels =
true;
1753 LLVMStyle.IndentPPDirectives = FormatStyle::PPDIS_None;
1754 LLVMStyle.IndentRequiresClause =
true;
1755 LLVMStyle.IndentWidth = 2;
1756 LLVMStyle.IndentWrappedFunctionNames =
false;
1757 LLVMStyle.InheritsParentConfig =
false;
1758 LLVMStyle.InsertBraces =
false;
1759 LLVMStyle.InsertNewlineAtEOF =
false;
1760 LLVMStyle.InsertTrailingCommas = FormatStyle::TCS_None;
1761 LLVMStyle.IntegerLiteralSeparator = {
1765 LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
1766 LLVMStyle.JavaScriptWrapImports =
true;
1767 LLVMStyle.KeepEmptyLines = {
1772 LLVMStyle.KeepFormFeed =
false;
1773 LLVMStyle.LambdaBodyIndentation = FormatStyle::LBI_Signature;
1775 LLVMStyle.LineEnding = FormatStyle::LE_DeriveLF;
1776 LLVMStyle.MaxEmptyLinesToKeep = 1;
1777 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
1778 LLVMStyle.NumericLiteralCase = {FormatStyle::NLCS_Leave,
1779 FormatStyle::NLCS_Leave,
1780 FormatStyle::NLCS_Leave,
1781 FormatStyle::NLCS_Leave};
1782 LLVMStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Auto;
1783 LLVMStyle.ObjCBlockIndentWidth = 2;
1784 LLVMStyle.ObjCBreakBeforeNestedBlockParam =
true;
1785 LLVMStyle.ObjCSpaceAfterProperty =
false;
1786 LLVMStyle.ObjCSpaceBeforeProtocolList =
true;
1787 LLVMStyle.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
1788 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
1789 LLVMStyle.PPIndentWidth = -1;
1790 LLVMStyle.QualifierAlignment = FormatStyle::QAS_Leave;
1791 LLVMStyle.ReferenceAlignment = FormatStyle::RAS_Pointer;
1792 LLVMStyle.ReflowComments = FormatStyle::RCS_Always;
1793 LLVMStyle.RemoveBracesLLVM =
false;
1794 LLVMStyle.RemoveEmptyLinesInUnwrappedLines =
false;
1795 LLVMStyle.RemoveParentheses = FormatStyle::RPS_Leave;
1796 LLVMStyle.RemoveSemicolon =
false;
1797 LLVMStyle.RequiresClausePosition = FormatStyle::RCPS_OwnLine;
1798 LLVMStyle.RequiresExpressionIndentation = FormatStyle::REI_OuterScope;
1799 LLVMStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Leave;
1800 LLVMStyle.ShortNamespaceLines = 1;
1801 LLVMStyle.SkipMacroDefinitionBody =
false;
1802 LLVMStyle.SortIncludes = {
true,
false,
1804 LLVMStyle.SortJavaStaticImport = FormatStyle::SJSIO_Before;
1805 LLVMStyle.SortUsingDeclarations = FormatStyle::SUD_LexicographicNumeric;
1806 LLVMStyle.SpaceAfterCStyleCast =
false;
1807 LLVMStyle.SpaceAfterLogicalNot =
false;
1808 LLVMStyle.SpaceAfterOperatorKeyword =
false;
1809 LLVMStyle.SpaceAfterTemplateKeyword =
true;
1810 LLVMStyle.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
1811 LLVMStyle.SpaceBeforeAssignmentOperators =
true;
1812 LLVMStyle.SpaceBeforeCaseColon =
false;
1813 LLVMStyle.SpaceBeforeCpp11BracedList =
false;
1814 LLVMStyle.SpaceBeforeCtorInitializerColon =
true;
1815 LLVMStyle.SpaceBeforeInheritanceColon =
true;
1816 LLVMStyle.SpaceBeforeJsonColon =
false;
1817 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
1818 LLVMStyle.SpaceBeforeParensOptions = {};
1819 LLVMStyle.SpaceBeforeParensOptions.AfterControlStatements =
true;
1820 LLVMStyle.SpaceBeforeParensOptions.AfterForeachMacros =
true;
1821 LLVMStyle.SpaceBeforeParensOptions.AfterIfMacros =
true;
1822 LLVMStyle.SpaceBeforeRangeBasedForLoopColon =
true;
1823 LLVMStyle.SpaceBeforeSquareBrackets =
false;
1824 LLVMStyle.SpaceInEmptyBraces = FormatStyle::SIEB_Never;
1825 LLVMStyle.SpacesBeforeTrailingComments = 1;
1826 LLVMStyle.SpacesInAngles = FormatStyle::SIAS_Never;
1827 LLVMStyle.SpacesInContainerLiterals =
true;
1828 LLVMStyle.SpacesInLineCommentPrefix = {
1829 1, std::numeric_limits<unsigned>::max()};
1830 LLVMStyle.SpacesInParens = FormatStyle::SIPO_Never;
1831 LLVMStyle.SpacesInSquareBrackets =
false;
1832 LLVMStyle.Standard = FormatStyle::LS_Latest;
1833 LLVMStyle.StatementAttributeLikeMacros.push_back(
"Q_EMIT");
1834 LLVMStyle.StatementMacros.push_back(
"Q_UNUSED");
1835 LLVMStyle.StatementMacros.push_back(
"QT_REQUIRE_VERSION");
1836 LLVMStyle.TableGenBreakingDAGArgOperators = {};
1837 LLVMStyle.TableGenBreakInsideDAGArg = FormatStyle::DAS_DontBreak;
1838 LLVMStyle.TabWidth = 8;
1839 LLVMStyle.UseTab = FormatStyle::UT_Never;
1840 LLVMStyle.VerilogBreakBetweenInstancePorts =
true;
1841 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"BOOST_PP_STRINGIZE");
1842 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"CF_SWIFT_NAME");
1843 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"NS_SWIFT_NAME");
1844 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"PP_STRINGIZE");
1845 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"STRINGIZE");
1846 LLVMStyle.WrapNamespaceBodyWithEmptyLines = FormatStyle::WNBWELS_Leave;
1849 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
1850 LLVMStyle.PenaltyBreakBeforeMemberAccess = 150;
1851 LLVMStyle.PenaltyBreakComment = 300;
1852 LLVMStyle.PenaltyBreakFirstLessLess = 120;
1853 LLVMStyle.PenaltyBreakOpenParenthesis = 0;
1854 LLVMStyle.PenaltyBreakScopeResolution = 500;
1855 LLVMStyle.PenaltyBreakString = 1000;
1857 LLVMStyle.PenaltyExcessCharacter = 1'000'000;
1858 LLVMStyle.PenaltyIndentedWhitespace = 0;
1859 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
1863 case FormatStyle::LK_TableGen:
1864 LLVMStyle.SpacesInContainerLiterals =
false;
1866 case FormatStyle::LK_Json:
1867 LLVMStyle.ColumnLimit = 0;
1869 case FormatStyle::LK_Verilog:
1870 LLVMStyle.IndentCaseLabels =
true;
1871 LLVMStyle.SpacesInContainerLiterals =
false;
1881 if (
Language == FormatStyle::LK_TextProto) {
1883 GoogleStyle.Language = FormatStyle::LK_TextProto;
1890 GoogleStyle.AccessModifierOffset = -1;
1891 GoogleStyle.AlignEscapedNewlines = FormatStyle::ENAS_Left;
1892 GoogleStyle.AllowShortIfStatementsOnASingleLine =
1893 FormatStyle::SIS_WithoutElse;
1894 GoogleStyle.AllowShortLoopsOnASingleLine =
true;
1895 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
true;
1897 GoogleStyle.AttributeMacros.push_back(
"absl_nonnull");
1898 GoogleStyle.AttributeMacros.push_back(
"absl_nullable");
1899 GoogleStyle.AttributeMacros.push_back(
"absl_nullability_unknown");
1900 GoogleStyle.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
1902 GoogleStyle.IncludeStyle.IncludeCategories = {{
"^<ext/.*\\.h>", 2, 0,
false},
1903 {
"^<.*\\.h>", 1, 0,
false},
1904 {
"^<.*", 2, 0,
false},
1905 {
".*", 3, 0,
false}};
1906 GoogleStyle.IncludeStyle.IncludeIsMainRegex =
"([-_](test|unittest))?$";
1907 GoogleStyle.IndentCaseLabels =
true;
1908 GoogleStyle.KeepEmptyLines.AtStartOfBlock =
false;
1909 GoogleStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
1910 GoogleStyle.ObjCSpaceAfterProperty =
false;
1911 GoogleStyle.ObjCSpaceBeforeProtocolList =
true;
1912 GoogleStyle.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
1913 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
1914 GoogleStyle.RawStringFormats = {
1916 FormatStyle::LK_Cpp,
1933 FormatStyle::LK_TextProto,
1945 "PARSE_PARTIAL_TEXT_PROTO",
1949 "ParseTextProtoOrDie",
1951 "ParsePartialTestProto",
1958 GoogleStyle.SpacesBeforeTrailingComments = 2;
1959 GoogleStyle.Standard = FormatStyle::LS_Auto;
1961 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
1962 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
1964 if (
Language == FormatStyle::LK_Java) {
1965 GoogleStyle.AlignAfterOpenBracket =
false;
1966 GoogleStyle.AlignOperands = FormatStyle::OAS_DontAlign;
1967 GoogleStyle.AlignTrailingComments = {};
1968 GoogleStyle.AlignTrailingComments.Kind = FormatStyle::TCAS_Never;
1969 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
1970 GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
1971 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
1972 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
1973 GoogleStyle.ColumnLimit = 100;
1974 GoogleStyle.SpaceAfterCStyleCast =
true;
1975 GoogleStyle.SpacesBeforeTrailingComments = 1;
1976 }
else if (
Language == FormatStyle::LK_JavaScript) {
1977 GoogleStyle.BreakAfterOpenBracketBracedList =
true;
1978 GoogleStyle.BreakAfterOpenBracketFunction =
true;
1979 GoogleStyle.BreakAfterOpenBracketIf =
true;
1980 GoogleStyle.AlignOperands = FormatStyle::OAS_DontAlign;
1981 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
1983 GoogleStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
1984 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
1985 GoogleStyle.BreakBeforeTernaryOperators =
false;
1988 GoogleStyle.CommentPragmas =
"(taze:|^/[ \t]*<|tslint:|@see)";
1992 GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single;
1993 GoogleStyle.JavaScriptWrapImports =
false;
1994 GoogleStyle.MaxEmptyLinesToKeep = 3;
1995 GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
1996 GoogleStyle.SpacesInContainerLiterals =
false;
1997 }
else if (
Language == FormatStyle::LK_Proto) {
1998 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
1999 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
2005 GoogleStyle.BreakStringLiterals =
false;
2006 GoogleStyle.Cpp11BracedListStyle = FormatStyle::BLS_Block;
2007 GoogleStyle.SpacesInContainerLiterals =
false;
2008 }
else if (
Language == FormatStyle::LK_ObjC) {
2009 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
2010 GoogleStyle.ColumnLimit = 100;
2011 GoogleStyle.DerivePointerAlignment =
true;
2015 GoogleStyle.IncludeStyle.IncludeBlocks =
2017 }
else if (
Language == FormatStyle::LK_CSharp) {
2018 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
2019 GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
2020 GoogleStyle.BreakStringLiterals =
false;
2021 GoogleStyle.ColumnLimit = 100;
2022 GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
2048 ChromiumStyle.IncludeStyle.IncludeBlocks =
2051 if (
Language == FormatStyle::LK_Java) {
2052 ChromiumStyle.AllowShortIfStatementsOnASingleLine =
2053 FormatStyle::SIS_WithoutElse;
2054 ChromiumStyle.BreakAfterJavaFieldAnnotations =
true;
2055 ChromiumStyle.ContinuationIndentWidth = 8;
2056 ChromiumStyle.IndentWidth = 4;
2059 ChromiumStyle.JavaImportGroups = {
2066 "com.google.android.apps.chrome",
2071 }
else if (
Language == FormatStyle::LK_JavaScript) {
2072 ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
2073 ChromiumStyle.AllowShortLoopsOnASingleLine =
false;
2075 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine =
false;
2076 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
2077 ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
2078 ChromiumStyle.AllowShortLoopsOnASingleLine =
false;
2079 ChromiumStyle.BinPackParameters = FormatStyle::BPPS_OnePerLine;
2080 ChromiumStyle.DerivePointerAlignment =
false;
2081 if (
Language == FormatStyle::LK_ObjC)
2082 ChromiumStyle.ColumnLimit = 80;
2084 return ChromiumStyle;
2089 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine =
false;
2090 MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
2091 MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
2092 FormatStyle::DRTBS_TopLevel;
2093 MozillaStyle.BinPackArguments =
false;
2094 MozillaStyle.BinPackParameters = FormatStyle::BPPS_OnePerLine;
2095 MozillaStyle.BreakAfterReturnType = FormatStyle::RTBS_TopLevel;
2096 MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
2097 MozillaStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
2098 MozillaStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
2099 MozillaStyle.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
2100 MozillaStyle.ConstructorInitializerIndentWidth = 2;
2101 MozillaStyle.ContinuationIndentWidth = 2;
2102 MozillaStyle.Cpp11BracedListStyle = FormatStyle::BLS_Block;
2103 MozillaStyle.FixNamespaceComments =
false;
2104 MozillaStyle.IndentCaseLabels =
true;
2105 MozillaStyle.ObjCSpaceAfterProperty =
true;
2106 MozillaStyle.ObjCSpaceBeforeProtocolList =
false;
2107 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
2108 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
2109 MozillaStyle.SpaceAfterTemplateKeyword =
false;
2110 return MozillaStyle;
2115 Style.AccessModifierOffset = -4;
2116 Style.AlignAfterOpenBracket =
false;
2117 Style.AlignOperands = FormatStyle::OAS_DontAlign;
2118 Style.AlignTrailingComments = {};
2119 Style.AlignTrailingComments.Kind = FormatStyle::TCAS_Never;
2120 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
2121 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
2122 Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
2123 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
2124 Style.ColumnLimit = 0;
2125 Style.Cpp11BracedListStyle = FormatStyle::BLS_Block;
2126 Style.FixNamespaceComments =
false;
2127 Style.IndentWidth = 4;
2128 Style.NamespaceIndentation = FormatStyle::NI_Inner;
2129 Style.ObjCBlockIndentWidth = 4;
2130 Style.ObjCSpaceAfterProperty =
true;
2131 Style.PointerAlignment = FormatStyle::PAS_Left;
2132 Style.SpaceBeforeCpp11BracedList =
true;
2133 Style.SpaceInEmptyBraces = FormatStyle::SIEB_Always;
2139 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
2140 Style.BreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
2141 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
2142 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
2143 Style.BreakBeforeTernaryOperators =
true;
2144 Style.ColumnLimit = 79;
2145 Style.Cpp11BracedListStyle = FormatStyle::BLS_Block;
2146 Style.FixNamespaceComments =
false;
2147 Style.KeepFormFeed =
true;
2148 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
2154 Style.ColumnLimit = 120;
2156 Style.IndentWidth = 4;
2157 Style.UseTab = FormatStyle::UT_Never;
2158 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2159 Style.BraceWrapping.AfterClass =
true;
2160 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2161 Style.BraceWrapping.AfterEnum =
true;
2162 Style.BraceWrapping.AfterFunction =
true;
2163 Style.BraceWrapping.AfterNamespace =
true;
2164 Style.BraceWrapping.AfterObjCDeclaration =
true;
2165 Style.BraceWrapping.AfterStruct =
true;
2166 Style.BraceWrapping.AfterExternBlock =
true;
2167 Style.BraceWrapping.BeforeCatch =
true;
2168 Style.BraceWrapping.BeforeElse =
true;
2169 Style.BraceWrapping.BeforeWhile =
false;
2170 Style.PenaltyReturnTypeOnItsOwnLine = 1000;
2171 Style.AllowShortEnumsOnASingleLine =
false;
2172 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
2173 Style.AllowShortCaseLabelsOnASingleLine =
false;
2174 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
2175 Style.AllowShortLoopsOnASingleLine =
false;
2176 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
2177 Style.BreakAfterReturnType = FormatStyle::RTBS_None;
2183 Style.InsertBraces =
true;
2184 Style.InsertNewlineAtEOF =
true;
2185 Style.IntegerLiteralSeparator.Decimal = 3;
2186 Style.IntegerLiteralSeparator.DecimalMinDigits = 5;
2187 Style.LineEnding = FormatStyle::LE_LF;
2188 Style.RemoveBracesLLVM =
true;
2189 Style.RemoveEmptyLinesInUnwrappedLines =
true;
2190 Style.RemoveParentheses = FormatStyle::RPS_ReturnStatement;
2191 Style.RemoveSemicolon =
true;
2197 NoStyle.DisableFormat =
true;
2198 NoStyle.SortIncludes = {};
2199 NoStyle.SortUsingDeclarations = FormatStyle::SUD_Never;
2204 FormatStyle *Style) {
2205 if (Name.equals_insensitive(
"llvm"))
2207 else if (Name.equals_insensitive(
"chromium"))
2209 else if (Name.equals_insensitive(
"mozilla"))
2211 else if (Name.equals_insensitive(
"google"))
2213 else if (Name.equals_insensitive(
"webkit"))
2215 else if (Name.equals_insensitive(
"gnu"))
2217 else if (Name.equals_insensitive(
"microsoft"))
2219 else if (Name.equals_insensitive(
"clang-format"))
2221 else if (Name.equals_insensitive(
"none"))
2223 else if (Name.equals_insensitive(
"inheritparentconfig"))
2224 Style->InheritsParentConfig =
true;
2234 if (Style->QualifierOrder.empty())
2238 for (
const auto &Qualifier : Style->QualifierOrder) {
2239 if (Qualifier ==
"type")
2243 if (token == tok::identifier)
2248 std::set<std::string> UniqueQualifiers(Style->QualifierOrder.begin(),
2249 Style->QualifierOrder.end());
2250 if (Style->QualifierOrder.size() != UniqueQualifiers.size()) {
2251 LLVM_DEBUG(llvm::dbgs()
2252 <<
"Duplicate Qualifiers " << Style->QualifierOrder.size()
2253 <<
" vs " << UniqueQualifiers.size() <<
"\n");
2258 if (!llvm::is_contained(Style->QualifierOrder,
"type"))
2265 FormatStyle *Style,
bool AllowUnknownOptions,
2266 llvm::SourceMgr::DiagHandlerTy DiagHandler,
2267 void *DiagHandlerCtxt,
bool IsDotHFile) {
2269 FormatStyle::LanguageKind
Language = Style->Language;
2270 assert(
Language != FormatStyle::LK_None);
2271 if (Config.getBuffer().trim().empty())
2273 Style->StyleSet.Clear();
2274 std::vector<FormatStyle> Styles;
2275 llvm::yaml::Input Input(Config,
nullptr, DiagHandler,
2281 Input.setContext(Style);
2282 Input.setAllowUnknownKeys(AllowUnknownOptions);
2285 return Input.error();
2289 const auto StyleCount = Styles.size();
2292 for (
unsigned I = 1; I < StyleCount; ++I) {
2293 const auto Lang = Styles[I].Language;
2294 if (Lang == FormatStyle::LK_None)
2297 for (
unsigned J = 0; J < I; ++J) {
2299 LLVM_DEBUG(llvm::dbgs()
2300 <<
"Duplicate languages in the config file on positions "
2301 << J <<
" and " << I <<
'\n');
2307 int LanguagePos = -1;
2313 for (
unsigned I = 0; I < StyleCount; ++I) {
2314 const auto Lang = Styles[I].Language;
2319 if (Lang == FormatStyle::LK_Cpp)
2321 else if (Lang == FormatStyle::LK_C)
2328 if (LanguagePos < 0) {
2329 if (Styles[0].
Language == FormatStyle::LK_None)
2331 else if (IsDotHFile &&
Language == FormatStyle::LK_Cpp)
2333 else if (!IsDotHFile &&
Language == FormatStyle::LK_C)
2334 LanguagePos = CppPos;
2335 if (LanguagePos < 0)
2339 for (
const auto &S : llvm::reverse(llvm::drop_begin(Styles)))
2340 Style->StyleSet.Add(S);
2342 *Style = Styles[LanguagePos];
2344 if (LanguagePos == 0) {
2345 if (Style->Language == FormatStyle::LK_None)
2347 Style->StyleSet.Add(*Style);
2350 if (Style->InsertTrailingCommas != FormatStyle::TCS_None &&
2351 Style->BinPackArguments) {
2355 if (Style->QualifierAlignment != FormatStyle::QAS_Leave)
2362 llvm::raw_string_ostream Stream(
Text);
2363 llvm::yaml::Output Output(Stream);
2366 FormatStyle NonConstStyle = Style;
2370 Output << NonConstStyle;
2372 return Stream.str();
2375std::optional<FormatStyle>
2376FormatStyle::FormatStyleSet::Get(FormatStyle::LanguageKind
Language)
const {
2378 return std::nullopt;
2380 if (It == Styles->end())
2381 return std::nullopt;
2382 FormatStyle Style = It->second;
2383 Style.StyleSet = *
this;
2387void FormatStyle::FormatStyleSet::Add(FormatStyle Style) {
2388 assert(Style.Language !=
LK_None &&
2389 "Cannot add a style for LK_None to a StyleSet");
2391 !Style.StyleSet.Styles &&
2392 "Cannot add a style associated with an existing StyleSet to a StyleSet");
2394 Styles = std::make_shared<MapType>();
2395 (*Styles)[Style.Language] = std::move(Style);
2398void FormatStyle::FormatStyleSet::Clear() { Styles.reset(); }
2400std::optional<FormatStyle>
2401FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind
Language)
const {
2408 const SourceManager &SourceMgr, tooling::Replacements &
Result,
2409 StringRef
Text =
"") {
2410 const auto &
Tok = Token.Tok;
2411 SourceLocation Start;
2413 Start =
Tok.getLocation();
2416 Start = Token.WhitespaceRange.getBegin();
2419 cantFail(
Result.add(tooling::Replacement(SourceMgr, Range,
Text)));
2424 ParensRemover(
const Environment &Env,
const FormatStyle &Style)
2425 : TokenAnalyzer(Env, Style) {}
2427 std::pair<tooling::Replacements, unsigned>
2428 analyze(TokenAnnotator &Annotator,
2429 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2430 FormatTokenLexer &Tokens)
override {
2431 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2432 tooling::Replacements
Result;
2433 removeParens(AnnotatedLines,
Result);
2438 void removeParens(SmallVectorImpl<AnnotatedLine *> &Lines,
2439 tooling::Replacements &
Result) {
2440 const auto &SourceMgr = Env.getSourceManager();
2441 for (
auto *
Line : Lines) {
2442 if (!
Line->Children.empty())
2444 if (!
Line->Affected)
2446 for (
const auto *Token =
Line->First; Token && !Token->Finalized;
2447 Token = Token->Next) {
2448 if (Token->Optional && Token->isOneOf(tok::l_paren, tok::r_paren))
2457 BracesInserter(
const Environment &Env,
const FormatStyle &Style)
2458 : TokenAnalyzer(Env, Style) {}
2460 std::pair<tooling::Replacements, unsigned>
2461 analyze(TokenAnnotator &Annotator,
2462 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2463 FormatTokenLexer &Tokens)
override {
2464 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2465 tooling::Replacements
Result;
2466 insertBraces(AnnotatedLines,
Result);
2471 void insertBraces(SmallVectorImpl<AnnotatedLine *> &Lines,
2472 tooling::Replacements &
Result) {
2473 const auto &SourceMgr = Env.getSourceManager();
2474 int OpeningBraceSurplus = 0;
2475 for (AnnotatedLine *
Line : Lines) {
2476 if (!
Line->Children.empty())
2478 if (!
Line->Affected && OpeningBraceSurplus == 0)
2481 Token = Token->Next) {
2488 if (!
Line->Affected)
2490 Brace = Token->is(tok::comment) ?
"\n{" :
"{";
2491 ++OpeningBraceSurplus;
2493 if (OpeningBraceSurplus == 0)
2500 Token->BraceCount = 0;
2501 const auto Start = Token->Tok.getEndLoc();
2502 cantFail(
Result.add(tooling::Replacement(SourceMgr, Start, 0,
Brace)));
2505 assert(OpeningBraceSurplus == 0);
2511 BracesRemover(
const Environment &Env,
const FormatStyle &Style)
2512 : TokenAnalyzer(Env, Style) {}
2514 std::pair<tooling::Replacements, unsigned>
2515 analyze(TokenAnnotator &Annotator,
2516 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2517 FormatTokenLexer &Tokens)
override {
2518 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2519 tooling::Replacements
Result;
2520 removeBraces(AnnotatedLines,
Result);
2525 void removeBraces(SmallVectorImpl<AnnotatedLine *> &Lines,
2526 tooling::Replacements &
Result) {
2527 const auto &SourceMgr = Env.getSourceManager();
2528 const auto *End = Lines.end();
2529 for (
const auto *I = Lines.begin(); I != End; ++I) {
2530 const auto &
Line = *I;
2531 if (!
Line->Children.empty())
2533 if (!
Line->Affected)
2535 const auto *NextLine = I + 1 == End ?
nullptr : I[1];
2536 for (
const auto *Token =
Line->First; Token && !Token->Finalized;
2537 Token = Token->Next) {
2538 if (!Token->Optional || Token->isNoneOf(tok::l_brace, tok::r_brace))
2540 auto *
Next = Token->Next;
2541 assert(
Next || Token ==
Line->Last);
2542 if (!
Next && NextLine)
2543 Next = NextLine->First;
2552 SemiRemover(
const Environment &Env,
const FormatStyle &Style)
2553 : TokenAnalyzer(Env, Style) {}
2555 std::pair<tooling::Replacements, unsigned>
2556 analyze(TokenAnnotator &Annotator,
2557 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2558 FormatTokenLexer &Tokens)
override {
2559 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2560 tooling::Replacements
Result;
2561 removeSemi(Annotator, AnnotatedLines,
Result);
2566 void removeSemi(TokenAnnotator &Annotator,
2567 SmallVectorImpl<AnnotatedLine *> &Lines,
2568 tooling::Replacements &
Result) {
2570 const auto *Prev =
Tok.Previous;
2571 if (!Prev || Prev->isNot(tok::r_brace))
2573 const auto *LBrace = Prev->MatchingParen;
2574 return LBrace && LBrace->is(TT_FunctionLBrace);
2576 const auto &SourceMgr = Env.getSourceManager();
2577 const auto *End = Lines.end();
2578 for (
const auto *I = Lines.begin(); I != End; ++I) {
2579 const auto &
Line = *I;
2580 if (!
Line->Children.empty())
2581 removeSemi(Annotator,
Line->Children,
Result);
2582 if (!
Line->Affected)
2584 Annotator.calculateFormattingInformation(*
Line);
2585 const auto *NextLine = I + 1 == End ?
nullptr : I[1];
2586 for (
const auto *Token =
Line->First; Token && !Token->Finalized;
2587 Token = Token->Next) {
2588 if (Token->isNot(tok::semi) ||
2589 (!Token->Optional && !PrecededByFunctionRBrace(*Token))) {
2592 auto *
Next = Token->Next;
2593 assert(
Next || Token ==
Line->Last);
2594 if (!
Next && NextLine)
2595 Next = NextLine->First;
2604 EnumTrailingCommaEditor(
const Environment &Env,
const FormatStyle &Style)
2605 : TokenAnalyzer(Env, Style) {}
2607 std::pair<tooling::Replacements, unsigned>
2608 analyze(TokenAnnotator &Annotator,
2609 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2610 FormatTokenLexer &Tokens)
override {
2611 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2612 tooling::Replacements
Result;
2613 editEnumTrailingComma(AnnotatedLines,
Result);
2618 void editEnumTrailingComma(SmallVectorImpl<AnnotatedLine *> &Lines,
2619 tooling::Replacements &
Result) {
2620 bool InEnumBraces =
false;
2622 const auto &SourceMgr = Env.getSourceManager();
2623 for (
auto *
Line : Lines) {
2624 if (!
Line->Children.empty())
2625 editEnumTrailingComma(
Line->Children,
Result);
2626 for (
const auto *Token =
Line->First; Token && !Token->Finalized;
2627 Token = Token->Next) {
2628 if (Token->isNot(TT_EnumRBrace)) {
2629 if (Token->is(TT_EnumLBrace))
2630 InEnumBraces =
true;
2631 else if (InEnumBraces && Token->isNot(tok::comment))
2632 BeforeRBrace =
Line->Affected ? Token :
nullptr;
2635 InEnumBraces =
false;
2638 if (BeforeRBrace->is(tok::comma)) {
2639 if (Style.EnumTrailingComma == FormatStyle::ETC_Remove)
2641 }
else if (Style.EnumTrailingComma == FormatStyle::ETC_Insert) {
2642 cantFail(
Result.add(tooling::Replacement(
2643 SourceMgr, BeforeRBrace->Tok.getEndLoc(), 0,
",")));
2645 BeforeRBrace =
nullptr;
2653 JavaScriptRequoter(
const Environment &Env,
const FormatStyle &Style)
2654 : TokenAnalyzer(Env, Style) {}
2656 std::pair<tooling::Replacements, unsigned>
2657 analyze(TokenAnnotator &Annotator,
2658 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2659 FormatTokenLexer &Tokens)
override {
2660 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2661 tooling::Replacements
Result;
2662 requoteJSStringLiteral(AnnotatedLines,
Result);
2669 void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
2670 tooling::Replacements &
Result) {
2671 for (AnnotatedLine *
Line : Lines) {
2672 requoteJSStringLiteral(
Line->Children,
Result);
2673 if (!
Line->Affected)
2676 FormatTok = FormatTok->Next) {
2677 StringRef Input = FormatTok->TokenText;
2678 if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
2681 (Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
2682 !Input.starts_with(
"\"")) ||
2683 (Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
2684 !Input.starts_with(
"\'"))) {
2689 bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
2690 SourceLocation Start = FormatTok->Tok.getLocation();
2691 auto Replace = [&](SourceLocation Start,
unsigned Length,
2692 StringRef ReplacementText) {
2693 auto Err =
Result.add(tooling::Replacement(
2694 Env.getSourceManager(), Start, Length, ReplacementText));
2698 llvm::errs() <<
toString(std::move(Err)) <<
"\n";
2702 Replace(Start, 1, IsSingle ?
"'" :
"\"");
2703 Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
2704 IsSingle ?
"'" :
"\"");
2707 bool Escaped =
false;
2708 for (
size_t i = 1; i < Input.size() - 1; i++) {
2711 if (!Escaped && i + 1 < Input.size() &&
2712 ((IsSingle && Input[i + 1] ==
'"') ||
2713 (!IsSingle && Input[i + 1] ==
'\''))) {
2716 Replace(Start.getLocWithOffset(i), 1,
"");
2723 if (!Escaped && IsSingle == (Input[i] ==
'\'')) {
2725 Replace(Start.getLocWithOffset(i), 0,
"\\");
2741 Formatter(
const Environment &Env,
const FormatStyle &Style,
2742 FormattingAttemptStatus *Status)
2743 : TokenAnalyzer(Env, Style), Status(Status) {}
2745 std::pair<tooling::Replacements, unsigned>
2746 analyze(TokenAnnotator &Annotator,
2747 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2748 FormatTokenLexer &Tokens)
override {
2749 tooling::Replacements
Result;
2750 deriveLocalStyle(AnnotatedLines);
2751 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2752 for (AnnotatedLine *
Line : AnnotatedLines)
2753 Annotator.calculateFormattingInformation(*
Line);
2754 Annotator.setCommentLineLevels(AnnotatedLines);
2756 WhitespaceManager Whitespaces(
2757 Env.getSourceManager(), Style,
2758 Style.LineEnding > FormatStyle::LE_CRLF
2760 Env.getSourceManager().getBufferData(Env.getFileID()),
2761 Style.LineEnding == FormatStyle::LE_DeriveCRLF)
2762 : Style.LineEnding == FormatStyle::LE_CRLF);
2763 ContinuationIndenter Indenter(Style, Tokens.getKeywords(),
2764 Env.getSourceManager(), Whitespaces, Encoding,
2765 BinPackInconclusiveFunctions);
2767 UnwrappedLineFormatter(&Indenter, &Whitespaces, Style,
2768 Tokens.getKeywords(), Env.getSourceManager(),
2770 .format(AnnotatedLines,
false,
2773 Env.getFirstStartColumn(),
2774 Env.getNextStartColumn(),
2775 Env.getLastStartColumn());
2776 for (
const auto &R : Whitespaces.generateReplacements())
2778 return std::make_pair(
Result, 0);
2779 return std::make_pair(
Result, Penalty);
2784 hasCpp03IncompatibleFormat(
const SmallVectorImpl<AnnotatedLine *> &Lines) {
2785 for (
const AnnotatedLine *
Line : Lines) {
2786 if (hasCpp03IncompatibleFormat(
Line->Children))
2789 if (!
Tok->hasWhitespaceBefore()) {
2790 if (
Tok->is(tok::coloncolon) &&
Tok->Previous->is(TT_TemplateOpener))
2792 if (
Tok->is(TT_TemplateCloser) &&
2793 Tok->Previous->is(TT_TemplateCloser)) {
2802 int countVariableAlignments(
const SmallVectorImpl<AnnotatedLine *> &Lines) {
2803 int AlignmentDiff = 0;
2805 for (
const AnnotatedLine *
Line : Lines) {
2806 AlignmentDiff += countVariableAlignments(
Line->Children);
2809 if (
Tok->isNot(TT_PointerOrReference))
2812 const auto *Prev =
Tok->Previous;
2813 const bool PrecededByName = Prev && Prev->Tok.getIdentifierInfo();
2814 const bool SpaceBefore =
Tok->hasWhitespaceBefore();
2817 while (
Tok->Next &&
Tok->Next->is(TT_PointerOrReference))
2821 const bool FollowedByName =
Next &&
Next->Tok.getIdentifierInfo();
2822 const bool SpaceAfter =
Next &&
Next->hasWhitespaceBefore();
2824 if ((!PrecededByName && !FollowedByName) ||
2826 (PrecededByName && FollowedByName && SpaceBefore == SpaceAfter)) {
2830 if ((PrecededByName && SpaceBefore) ||
2831 (FollowedByName && !SpaceAfter)) {
2834 }
else if ((PrecededByName && !SpaceBefore) ||
2835 (FollowedByName && SpaceAfter)) {
2842 return AlignmentDiff;
2846 deriveLocalStyle(
const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
2847 bool HasBinPackedFunction =
false;
2848 bool HasOnePerLineFunction =
false;
2849 for (AnnotatedLine *
Line : AnnotatedLines) {
2850 if (!
Line->First->Next)
2855 HasBinPackedFunction =
true;
2857 HasOnePerLineFunction =
true;
2862 if (Style.DerivePointerAlignment) {
2863 const auto NetRightCount = countVariableAlignments(AnnotatedLines);
2864 if (NetRightCount > 0)
2865 Style.PointerAlignment = FormatStyle::PAS_Right;
2866 else if (NetRightCount < 0)
2867 Style.PointerAlignment = FormatStyle::PAS_Left;
2868 Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
2870 if (Style.Standard == FormatStyle::LS_Auto) {
2871 Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
2872 ? FormatStyle::LS_Latest
2873 : FormatStyle::LS_Cpp03;
2875 BinPackInconclusiveFunctions =
2876 HasBinPackedFunction || !HasOnePerLineFunction;
2879 bool BinPackInconclusiveFunctions;
2880 FormattingAttemptStatus *Status;
2896 TrailingCommaInserter(
const Environment &Env,
const FormatStyle &Style)
2897 : TokenAnalyzer(Env, Style) {}
2899 std::pair<tooling::Replacements, unsigned>
2900 analyze(TokenAnnotator &Annotator,
2901 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2902 FormatTokenLexer &Tokens)
override {
2903 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2904 tooling::Replacements
Result;
2905 insertTrailingCommas(AnnotatedLines,
Result);
2912 void insertTrailingCommas(SmallVectorImpl<AnnotatedLine *> &Lines,
2913 tooling::Replacements &
Result) {
2914 for (AnnotatedLine *
Line : Lines) {
2915 insertTrailingCommas(
Line->Children,
Result);
2916 if (!
Line->Affected)
2919 FormatTok = FormatTok->Next) {
2920 if (FormatTok->NewlinesBefore == 0)
2923 if (!Matching || !FormatTok->getPreviousNonComment())
2925 if (!(FormatTok->is(tok::r_square) &&
2926 Matching->is(TT_ArrayInitializerLSquare)) &&
2927 !(FormatTok->is(tok::r_brace) && Matching->is(TT_DictLiteral))) {
2930 FormatToken *Prev = FormatTok->getPreviousNonComment();
2931 if (Prev->is(tok::comma) || Prev->is(tok::semi))
2935 SourceLocation Start =
2936 Prev->Tok.getLocation().getLocWithOffset(Prev->TokenText.size());
2940 unsigned ColumnNumber =
2941 Env.getSourceManager().getSpellingColumnNumber(Start);
2942 if (ColumnNumber > Style.ColumnLimit)
2947 tooling::Replacement(Env.getSourceManager(), Start, 0,
",")));
2957 Cleaner(
const Environment &Env,
const FormatStyle &Style)
2958 : TokenAnalyzer(Env, Style),
2959 DeletedTokens(FormatTokenLess(Env.getSourceManager())) {}
2962 std::pair<tooling::Replacements, unsigned>
2963 analyze(TokenAnnotator &Annotator,
2964 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2965 FormatTokenLexer &Tokens)
override {
2973 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2975 checkEmptyNamespace(AnnotatedLines);
2977 for (
auto *
Line : AnnotatedLines)
2980 return {generateFixes(), 0};
2984 void cleanupLine(AnnotatedLine *
Line) {
2985 for (
auto *Child :
Line->Children)
2988 if (
Line->Affected) {
2989 cleanupRight(
Line->First, tok::comma, tok::comma);
2990 cleanupRight(
Line->First, TT_CtorInitializerColon, tok::comma);
2991 cleanupRight(
Line->First, tok::l_paren, tok::comma);
2992 cleanupLeft(
Line->First, tok::comma, tok::r_paren);
2993 cleanupLeft(
Line->First, TT_CtorInitializerComma, tok::l_brace);
2994 cleanupLeft(
Line->First, TT_CtorInitializerColon, tok::l_brace);
2995 cleanupLeft(
Line->First, TT_CtorInitializerColon, tok::equal);
2999 bool containsOnlyComments(
const AnnotatedLine &
Line) {
3001 if (
Tok->isNot(tok::comment))
3007 void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
3008 std::set<unsigned> DeletedLines;
3009 for (
unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
3010 auto &
Line = *AnnotatedLines[i];
3011 if (
Line.startsWithNamespace())
3012 checkEmptyNamespace(AnnotatedLines, i, i, DeletedLines);
3015 for (
auto Line : DeletedLines) {
3028 bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3029 unsigned CurrentLine,
unsigned &NewLine,
3030 std::set<unsigned> &DeletedLines) {
3031 unsigned InitLine = CurrentLine, End = AnnotatedLines.size();
3032 if (Style.BraceWrapping.AfterNamespace) {
3036 if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
3037 NewLine = CurrentLine;
3040 }
else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
3043 while (++CurrentLine < End) {
3044 if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
3047 if (AnnotatedLines[CurrentLine]->startsWithNamespace()) {
3048 if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine,
3052 CurrentLine = NewLine;
3056 if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
3061 NewLine = CurrentLine;
3065 NewLine = CurrentLine;
3066 if (CurrentLine >= End)
3071 AnnotatedLines[InitLine]->First->Tok.getLocation(),
3072 AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc()))) {
3076 for (
unsigned i = InitLine; i <= CurrentLine; ++i)
3077 DeletedLines.insert(i);
3086 template <
typename LeftKind,
typename RightKind>
3087 void cleanupPair(
FormatToken *Start, LeftKind LK, RightKind RK,
3090 for (
auto *Res =
Tok.Next; Res; Res = Res->Next) {
3091 if (Res->isNot(tok::comment) &&
3092 DeletedTokens.find(Res) == DeletedTokens.end()) {
3098 for (
auto *Left = Start;
Left;) {
3099 auto *
Right = NextNotDeleted(*Left);
3103 deleteToken(DeleteLeft ? Left : Right);
3115 template <
typename LeftKind,
typename RightKind>
3116 void cleanupLeft(
FormatToken *Start, LeftKind LK, RightKind RK) {
3117 cleanupPair(Start, LK, RK,
true);
3120 template <
typename LeftKind,
typename RightKind>
3121 void cleanupRight(
FormatToken *Start, LeftKind LK, RightKind RK) {
3122 cleanupPair(Start, LK, RK,
false);
3128 DeletedTokens.insert(
Tok);
3131 tooling::Replacements generateFixes() {
3132 tooling::Replacements Fixes;
3133 SmallVector<FormatToken *> Tokens;
3134 std::copy(DeletedTokens.begin(), DeletedTokens.end(),
3135 std::back_inserter(Tokens));
3141 while (Idx < Tokens.size()) {
3142 unsigned St = Idx, End = Idx;
3143 while ((End + 1) < Tokens.size() && Tokens[End]->Next == Tokens[End + 1])
3146 Tokens[End]->Tok.getEndLoc());
3148 Fixes.add(tooling::Replacement(Env.getSourceManager(), SR,
""));
3152 llvm::errs() <<
toString(std::move(Err)) <<
"\n";
3153 assert(
false &&
"Fixes must not conflict!");
3164 struct FormatTokenLess {
3165 FormatTokenLess(
const SourceManager &SM) : SM(SM) {}
3168 return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(),
3169 RHS->Tok.getLocation());
3171 const SourceManager &SM;
3175 std::set<FormatToken *, FormatTokenLess> DeletedTokens;
3180 ObjCHeaderStyleGuesser(
const Environment &Env,
const FormatStyle &Style)
3181 : TokenAnalyzer(Env, Style), IsObjC(
false) {}
3183 std::pair<tooling::Replacements, unsigned>
3184 analyze(TokenAnnotator &Annotator,
3185 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3186 FormatTokenLexer &Tokens)
override {
3187 assert(Style.Language == FormatStyle::LK_Cpp);
3188 IsObjC = guessIsObjC(Env.getSourceManager(), AnnotatedLines,
3189 Tokens.getKeywords());
3190 tooling::Replacements
Result;
3194 bool isObjC() {
return IsObjC; }
3198 guessIsObjC(
const SourceManager &SourceManager,
3199 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3200 const AdditionalKeywords &Keywords) {
3202 static constexpr llvm::StringLiteral FoundationIdentifiers[] = {
3217 "FOUNDATION_EXPORT",
3218 "FOUNDATION_EXTERN",
3219 "NSAffineTransform",
3221 "NSAttributedString",
3240 "NSInvocationOperation",
3244 "NSMutableAttributedString",
3245 "NSMutableCharacterSet",
3247 "NSMutableDictionary",
3248 "NSMutableIndexSet",
3249 "NSMutableOrderedSet",
3253 "NSNumberFormatter",
3257 "NSOperationQueuePriority",
3261 "NSQualityOfService",
3264 "NSRegularExpression",
3275 "NS_ASSUME_NONNULL_BEGIN",
3279 assert(llvm::is_sorted(FoundationIdentifiers));
3281 for (
auto *
Line : AnnotatedLines) {
3282 if (
Line->First && (
Line->First->TokenText.starts_with(
"#") ||
3283 Line->First->TokenText ==
"__pragma" ||
3284 Line->First->TokenText ==
"_Pragma")) {
3288 FormatTok = FormatTok->Next) {
3289 if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) &&
3290 (FormatTok->isNot(tok::objc_not_keyword) ||
3291 FormatTok->isOneOf(tok::numeric_constant, tok::l_square,
3293 (FormatTok->Tok.isAnyIdentifier() &&
3294 llvm::binary_search(FoundationIdentifiers,
3295 FormatTok->TokenText)) ||
3296 FormatTok->is(TT_ObjCStringLiteral) ||
3297 FormatTok->isOneOf(Keywords.kw_NS_CLOSED_ENUM, Keywords.kw_NS_ENUM,
3298 Keywords.kw_NS_ERROR_ENUM,
3299 Keywords.kw_NS_OPTIONS, TT_ObjCBlockLBrace,
3300 TT_ObjCBlockLParen, TT_ObjCDecl, TT_ObjCForIn,
3301 TT_ObjCMethodExpr, TT_ObjCMethodSpecifier,
3302 TT_ObjCProperty, TT_ObjCSelector)) {
3303 LLVM_DEBUG(llvm::dbgs()
3304 <<
"Detected ObjC at location "
3305 << FormatTok->Tok.getLocation().printToString(
3307 <<
" token: " << FormatTok->TokenText <<
" token type: "
3312 if (guessIsObjC(SourceManager,
Line->Children, Keywords))
3321struct IncludeDirective {
3329struct JavaImportDirective {
3330 StringRef Identifier;
3333 SmallVector<StringRef> AssociatedCommentLines;
3342 for (
const auto &Range : Ranges) {
3343 if (Range.getOffset() < End &&
3344 Range.getOffset() + Range.getLength() > Start) {
3359static std::pair<unsigned, unsigned>
3362 unsigned CursorIndex = std::numeric_limits<unsigned>::max();
3363 unsigned OffsetToEOL = 0;
3364 for (
int i = 0, e = Includes.size(); i != e; ++i) {
3365 unsigned Start = Includes[Indices[i]].Offset;
3366 unsigned End = Start + Includes[Indices[i]].Text.size();
3367 if (!(Cursor >= Start && Cursor < End))
3369 CursorIndex = Indices[i];
3370 OffsetToEOL = End - Cursor;
3373 while (--i >= 0 && Includes[CursorIndex].
Text == Includes[Indices[i]].
Text)
3377 return std::make_pair(CursorIndex, OffsetToEOL);
3382 std::string NewCode;
3383 size_t Pos = 0, LastPos = 0;
3386 Pos = Code.find(
"\r\n", LastPos);
3387 if (Pos == LastPos) {
3391 if (Pos == std::string::npos) {
3392 NewCode += Code.substr(LastPos);
3395 NewCode += Code.substr(LastPos, Pos - LastPos) +
"\n";
3397 }
while (Pos != std::string::npos);
3415 const unsigned IncludesBeginOffset = Includes.front().Offset;
3416 const unsigned IncludesEndOffset =
3417 Includes.back().Offset + Includes.back().Text.size();
3418 const unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset;
3419 if (!
affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset))
3422 llvm::to_vector<16>(llvm::seq<unsigned>(0, Includes.size()));
3424 if (Style.SortIncludes.Enabled) {
3425 stable_sort(Indices, [&](
unsigned LHSI,
unsigned RHSI) {
3427 if (Style.SortIncludes.IgnoreExtension) {
3428 LHSStem = Includes[LHSI].Filename;
3429 RHSStem = Includes[RHSI].Filename;
3430 llvm::sys::path::replace_extension(LHSStem,
"");
3431 llvm::sys::path::replace_extension(RHSStem,
"");
3433 std::string LHSStemLower, RHSStemLower;
3434 std::string LHSFilenameLower, RHSFilenameLower;
3435 if (Style.SortIncludes.IgnoreCase) {
3436 LHSStemLower = LHSStem.str().lower();
3437 RHSStemLower = RHSStem.str().lower();
3438 LHSFilenameLower = Includes[LHSI].Filename.lower();
3439 RHSFilenameLower = Includes[RHSI].Filename.lower();
3441 return std::tie(Includes[LHSI].Priority, LHSStemLower, LHSStem,
3442 LHSFilenameLower, Includes[LHSI].Filename) <
3443 std::tie(Includes[RHSI].Priority, RHSStemLower, RHSStem,
3444 RHSFilenameLower, Includes[RHSI].Filename);
3450 unsigned CursorIndex;
3452 unsigned CursorToEOLOffset;
3454 std::tie(CursorIndex, CursorToEOLOffset) =
3459 Indices.erase(llvm::unique(Indices,
3460 [&](
unsigned LHSI,
unsigned RHSI) {
3461 return Includes[LHSI].Text.trim() ==
3462 Includes[RHSI].Text.trim();
3466 int CurrentCategory = Includes.front().Category;
3474 if (Indices.size() == Includes.size() && is_sorted(Indices) &&
3479 const auto OldCursor = Cursor ? *Cursor : 0;
3481 for (
unsigned Index : Indices) {
3482 if (!result.empty()) {
3484 if (Style.IncludeStyle.IncludeBlocks ==
3486 CurrentCategory != Includes[Index].Category) {
3490 result += Includes[Index].Text;
3491 if (Cursor && CursorIndex == Index)
3492 *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
3493 CurrentCategory = Includes[Index].Category;
3496 if (Cursor && *Cursor >= IncludesEndOffset)
3497 *Cursor += result.size() - IncludesBlockSize;
3502 IncludesBeginOffset, IncludesBlockSize)))) {
3504 *Cursor = OldCursor;
3509 FileName, Includes.front().Offset, IncludesBlockSize, result));
3513 llvm::errs() <<
toString(std::move(Err)) <<
"\n";
3523 unsigned Prev = llvm::StringSwitch<size_t>(Code)
3524 .StartsWith(
"\xEF\xBB\xBF", 3)
3526 unsigned SearchFrom = 0;
3538 bool FirstIncludeBlock =
true;
3539 bool MainIncludeFound =
false;
3540 bool FormattingOff =
false;
3543 llvm::Regex RawStringRegex(
3544 "R\"([][A-Za-z0-9_{}#<>%:;.?*+/^&\\$|~!=,'-]*)\\(");
3546 std::string RawStringTermination =
")\"";
3548 for (
const auto Size = Code.size(); SearchFrom < Size;) {
3549 size_t Pos = SearchFrom;
3550 if (Code[SearchFrom] !=
'\n') {
3553 Pos = Code.find(
'\n', Pos);
3554 }
while (Pos != StringRef::npos && Code[Pos - 1] ==
'\\');
3558 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
3560 StringRef Trimmed =
Line.trim();
3565 if (RawStringRegex.match(Trimmed, &RawStringMatches)) {
3566 std::string CharSequence = RawStringMatches[1].str();
3567 RawStringTermination =
")" + CharSequence +
"\"";
3568 FormattingOff =
true;
3571 if (Trimmed.contains(RawStringTermination))
3572 FormattingOff =
false;
3574 bool IsBlockComment =
false;
3577 FormattingOff =
true;
3579 FormattingOff =
false;
3580 }
else if (Trimmed.starts_with(
"/*")) {
3581 IsBlockComment =
true;
3582 Pos = Code.find(
"*/", SearchFrom + 2);
3585 const bool EmptyLineSkipped =
3588 Style.IncludeStyle.IncludeBlocks ==
3591 bool MergeWithNextLine = Trimmed.ends_with(
"\\");
3592 if (!FormattingOff && !MergeWithNextLine) {
3593 if (!IsBlockComment &&
3595 StringRef IncludeName = Matches[2];
3596 if (Trimmed.contains(
"/*") && !Trimmed.contains(
"*/")) {
3601 Pos = Code.find(
"*/", SearchFrom);
3603 Prev, (Pos != StringRef::npos ? Pos + 2 : Code.size()) - Prev);
3607 !MainIncludeFound && FirstIncludeBlock);
3609 IncludeName, !MainIncludeFound && FirstIncludeBlock);
3611 MainIncludeFound =
true;
3612 IncludesInBlock.push_back(
3613 {IncludeName,
Line, Prev, Category, Priority});
3614 }
else if (!IncludesInBlock.empty() && !EmptyLineSkipped) {
3617 IncludesInBlock.clear();
3618 if (Trimmed.starts_with(
"#pragma hdrstop"))
3619 FirstIncludeBlock =
true;
3621 FirstIncludeBlock =
false;
3624 if (Pos == StringRef::npos || Pos + 1 == Code.size())
3627 if (!MergeWithNextLine)
3629 SearchFrom = Pos + 1;
3631 if (!IncludesInBlock.empty()) {
3642 StringRef ImportIdentifier) {
3643 unsigned LongestMatchIndex = std::numeric_limits<unsigned>::max();
3644 unsigned LongestMatchLength = 0;
3645 for (
unsigned I = 0; I < Style.JavaImportGroups.size(); I++) {
3646 const std::string &GroupPrefix = Style.JavaImportGroups[I];
3647 if (ImportIdentifier.starts_with(GroupPrefix) &&
3648 GroupPrefix.length() > LongestMatchLength) {
3649 LongestMatchIndex = I;
3650 LongestMatchLength = GroupPrefix.length();
3653 return LongestMatchIndex;
3665 unsigned ImportsBeginOffset = Imports.front().Offset;
3666 unsigned ImportsEndOffset =
3667 Imports.back().Offset + Imports.back().Text.size();
3668 unsigned ImportsBlockSize = ImportsEndOffset - ImportsBeginOffset;
3669 if (!
affectsRange(Ranges, ImportsBeginOffset, ImportsEndOffset))
3673 llvm::to_vector<16>(llvm::seq<unsigned>(0, Imports.size()));
3676 for (
const JavaImportDirective &Import : Imports)
3679 bool StaticImportAfterNormalImport =
3680 Style.SortJavaStaticImport == FormatStyle::SJSIO_After;
3681 sort(Indices, [&](
unsigned LHSI,
unsigned RHSI) {
3683 return std::make_tuple(!Imports[LHSI].IsStatic ^
3684 StaticImportAfterNormalImport,
3686 std::make_tuple(!Imports[RHSI].IsStatic ^
3687 StaticImportAfterNormalImport,
3692 Indices.erase(llvm::unique(Indices,
3693 [&](
unsigned LHSI,
unsigned RHSI) {
3694 return Imports[LHSI].Text == Imports[RHSI].Text;
3698 bool CurrentIsStatic = Imports[Indices.front()].IsStatic;
3702 for (
unsigned Index : Indices) {
3703 if (!result.empty()) {
3705 if (CurrentIsStatic != Imports[Index].IsStatic ||
3710 for (StringRef CommentLine : Imports[Index].AssociatedCommentLines) {
3711 result += CommentLine;
3714 result += Imports[Index].Text;
3715 CurrentIsStatic = Imports[Index].IsStatic;
3722 Imports.front().Offset, ImportsBlockSize)))) {
3727 ImportsBlockSize, result));
3731 llvm::errs() <<
toString(std::move(Err)) <<
"\n";
3738const char JavaImportRegexPattern[] =
3739 "^[\t ]*import[\t ]+(static[\t ]*)?([^\t ]*)[\t ]*;";
3748 unsigned SearchFrom = 0;
3749 llvm::Regex ImportRegex(JavaImportRegexPattern);
3754 bool FormattingOff =
false;
3757 auto Pos = Code.find(
'\n', SearchFrom);
3759 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
3761 StringRef Trimmed =
Line.trim();
3763 FormattingOff =
true;
3765 FormattingOff =
false;
3767 if (ImportRegex.match(
Line, &Matches)) {
3768 if (FormattingOff) {
3773 StringRef
Static = Matches[1];
3774 StringRef Identifier = Matches[2];
3775 bool IsStatic =
false;
3776 if (
Static.contains(
"static"))
3778 ImportsInBlock.push_back(
3779 {Identifier,
Line, Prev, AssociatedCommentLines, IsStatic});
3780 AssociatedCommentLines.clear();
3781 }
else if (!Trimmed.empty() && !ImportsInBlock.empty()) {
3783 AssociatedCommentLines.push_back(
Line);
3786 if (Pos == StringRef::npos || Pos + 1 == Code.size())
3788 SearchFrom = Pos + 1;
3790 if (!ImportsInBlock.empty())
3799 return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
3802bool isLikelyXml(StringRef Code) {
return Code.ltrim().starts_with(
"<"); }
3806 StringRef
FileName,
unsigned *Cursor) {
3808 if (!Style.SortIncludes.Enabled || Style.DisableFormat)
3812 if (Style.isJavaScript()) {
3824template <
typename T>
3828 const FormatStyle &Style) {
3829 if (Replaces.
empty())
3832 auto NewCode = applyAllReplacements(Code, Replaces);
3834 return NewCode.takeError();
3839 ProcessFunc(Style, *NewCode, ChangedRanges,
FileName);
3841 return Replaces.
merge(FormatReplaces);
3846 const FormatStyle &Style) {
3849 auto SortIncludes = [](
const FormatStyle &Style, StringRef Code,
3850 std::vector<tooling::Range> Ranges,
3854 auto SortedReplaces =
3856 if (!SortedReplaces)
3857 return SortedReplaces.takeError();
3861 auto Reformat = [](
const FormatStyle &Style, StringRef Code,
3862 std::vector<tooling::Range> Ranges,
3872 return Replace.
getOffset() == std::numeric_limits<unsigned>::max() &&
3878inline bool isHeaderDeletion(
const tooling::Replacement &Replace) {
3879 return Replace.getOffset() == std::numeric_limits<unsigned>::max() &&
3880 Replace.getLength() == 1;
3884tooling::Replacements
3885fixCppIncludeInsertions(StringRef Code,
const tooling::Replacements &Replaces,
3886 const FormatStyle &Style) {
3890 tooling::Replacements HeaderInsertions;
3891 std::set<StringRef> HeadersToDelete;
3892 tooling::Replacements
Result;
3893 for (
const auto &R : Replaces) {
3894 if (isHeaderInsertion(R)) {
3897 consumeError(HeaderInsertions.add(R));
3898 }
else if (isHeaderDeletion(R)) {
3899 HeadersToDelete.insert(R.getReplacementText());
3900 }
else if (R.getOffset() == std::numeric_limits<unsigned>::max()) {
3901 llvm::errs() <<
"Insertions other than header #include insertion are "
3903 << R.getReplacementText() <<
"\n";
3905 consumeError(
Result.add(R));
3908 if (HeaderInsertions.empty() && HeadersToDelete.empty())
3911 StringRef
FileName = Replaces.begin()->getFilePath();
3912 tooling::HeaderIncludes Includes(
FileName, Code, Style.IncludeStyle);
3914 for (
const auto &Header : HeadersToDelete) {
3915 tooling::Replacements Replaces =
3916 Includes.remove(Header.trim(
"\"<>"), Header.starts_with(
"<"));
3917 for (
const auto &R : Replaces) {
3918 auto Err =
Result.add(R);
3921 llvm::errs() <<
"Failed to add header deletion replacement for "
3922 << Header <<
": " <<
toString(std::move(Err)) <<
"\n";
3928 for (
const auto &R : HeaderInsertions) {
3929 auto IncludeDirective = R.getReplacementText();
3932 assert(Matched &&
"Header insertion replacement must have replacement text "
3935 auto IncludeName = Matches[2];
3937 Includes.insert(IncludeName.trim(
"\"<>"), IncludeName.starts_with(
"<"),
3940 auto Err =
Result.add(*Replace);
3942 consumeError(std::move(Err));
3943 unsigned NewOffset =
3944 Result.getShiftedCodePosition(Replace->getOffset());
3945 auto Shifted = tooling::Replacement(
FileName, NewOffset, 0,
3946 Replace->getReplacementText());
3958 const FormatStyle &Style) {
3961 auto Cleanup = [](
const FormatStyle &Style, StringRef Code,
3968 fixCppIncludeInsertions(Code, Replaces, Style);
3973std::pair<tooling::Replacements, unsigned>
3976 unsigned NextStartColumn,
unsigned LastStartColumn, StringRef
FileName,
3978 FormatStyle Expanded = Style;
3982 Expanded.InsertBraces =
false;
3983 Expanded.RemoveBracesLLVM =
false;
3984 Expanded.RemoveParentheses = FormatStyle::RPS_Leave;
3985 Expanded.RemoveSemicolon =
false;
3986 switch (Expanded.RequiresClausePosition) {
3987 case FormatStyle::RCPS_SingleLine:
3988 case FormatStyle::RCPS_WithPreceding:
3989 Expanded.IndentRequiresClause =
false;
3995 if (Expanded.DisableFormat)
3999 if (Expanded.isJavaScript() &&
isMpegTS(Code))
4003 if (Style.isJson()) {
4004 std::vector<tooling::Range> Ranges(1,
tooling::Range(0, Code.size()));
4006 NextStartColumn, LastStartColumn);
4011 Formatter(*Env, Style, Status).process().first;
4013 if (Code.starts_with(
"x = ")) {
4014 Replaces = Replaces.
merge(
4018 if (applyAllReplacements(Code, Replaces))
4019 return {Replaces, 0};
4024 NextStartColumn, LastStartColumn);
4042 if (Style.isCpp()) {
4043 if (Style.QualifierAlignment != FormatStyle::QAS_Leave)
4046 if (Style.RemoveParentheses != FormatStyle::RPS_Leave) {
4047 FormatStyle S = Expanded;
4048 S.RemoveParentheses = Style.RemoveParentheses;
4049 Passes.emplace_back([&, S = std::move(S)](
const Environment &Env) {
4050 return ParensRemover(Env, S).process(
true);
4054 if (Style.InsertBraces) {
4055 FormatStyle S = Expanded;
4056 S.InsertBraces =
true;
4057 Passes.emplace_back([&, S = std::move(S)](
const Environment &Env) {
4058 return BracesInserter(Env, S).process(
true);
4062 if (Style.RemoveBracesLLVM) {
4063 FormatStyle S = Expanded;
4064 S.RemoveBracesLLVM =
true;
4065 Passes.emplace_back([&, S = std::move(S)](
const Environment &Env) {
4066 return BracesRemover(Env, S).process(
true);
4070 if (Style.RemoveSemicolon) {
4071 FormatStyle S = Expanded;
4072 S.RemoveSemicolon =
true;
4073 Passes.emplace_back([&, S = std::move(S)](
const Environment &Env) {
4074 return SemiRemover(Env, S).process();
4078 if (Style.EnumTrailingComma != FormatStyle::ETC_Leave) {
4080 return EnumTrailingCommaEditor(Env, Expanded)
4085 if (Style.FixNamespaceComments) {
4091 if (Style.SortUsingDeclarations != FormatStyle::SUD_Never) {
4098 if (Style.SeparateDefinitionBlocks != FormatStyle::SDS_Leave) {
4104 if (Style.Language == FormatStyle::LK_ObjC &&
4105 !Style.ObjCPropertyAttributeOrder.empty()) {
4111 if (Style.isJavaScript() &&
4112 Style.JavaScriptQuotes != FormatStyle::JSQS_Leave) {
4114 return JavaScriptRequoter(Env, Expanded).process(
true);
4119 return Formatter(Env, Expanded, Status).process();
4122 if (Style.isJavaScript() &&
4123 Style.InsertTrailingCommas == FormatStyle::TCS_Wrapped) {
4125 return TrailingCommaInserter(Env, Expanded).process();
4129 std::optional<std::string> CurrentCode;
4131 unsigned Penalty = 0;
4132 for (
size_t I = 0, E = Passes.size(); I < E; ++I) {
4133 std::pair<tooling::Replacements, unsigned> PassFixes = Passes[I](*Env);
4134 auto NewCode = applyAllReplacements(
4135 CurrentCode ? StringRef(*CurrentCode) : Code, PassFixes.first);
4137 Fixes = Fixes.
merge(PassFixes.first);
4138 Penalty += PassFixes.second;
4140 CurrentCode = std::move(*NewCode);
4144 FirstStartColumn, NextStartColumn, LastStartColumn);
4151 if (Style.QualifierAlignment != FormatStyle::QAS_Leave) {
4157 StringRef OriginalCode = Code.substr(Fix.getOffset(), Fix.getLength());
4158 if (OriginalCode != Fix.getReplacementText()) {
4159 auto Err = NonNoOpFixes.
add(Fix);
4161 llvm::errs() <<
"Error adding replacements : "
4162 <<
toString(std::move(Err)) <<
"\n";
4166 Fixes = std::move(NonNoOpFixes);
4169 return {Fixes, Penalty};
4188 if (Style.Language != FormatStyle::LK_Cpp)
4193 return Cleaner(*Env, Style).process().first;
4198 StringRef
FileName,
bool *IncompleteFormat) {
4201 if (!Status.FormatComplete)
4202 *IncompleteFormat =
true;
4229 auto LexingStd = Style.Standard;
4230 if (LexingStd == FormatStyle::LS_Auto || LexingStd == FormatStyle::LS_Latest)
4231 LexingStd = FormatStyle::LS_Cpp20;
4233 const bool SinceCpp11 = LexingStd >= FormatStyle::LS_Cpp11;
4234 const bool SinceCpp20 = LexingStd >= FormatStyle::LS_Cpp20;
4236 switch (Style.Language) {
4237 case FormatStyle::LK_C:
4241 case FormatStyle::LK_Cpp:
4242 case FormatStyle::LK_ObjC:
4243 LangOpts.CXXOperatorNames = 1;
4244 LangOpts.CPlusPlus11 = SinceCpp11;
4245 LangOpts.CPlusPlus14 = LexingStd >= FormatStyle::LS_Cpp14;
4246 LangOpts.CPlusPlus17 = LexingStd >= FormatStyle::LS_Cpp17;
4247 LangOpts.CPlusPlus20 = SinceCpp20;
4250 LangOpts.CPlusPlus = 1;
4253 LangOpts.Char8 = SinceCpp20;
4257 LangOpts.Digraphs = SinceCpp11;
4259 LangOpts.LineComment = 1;
4262 LangOpts.MicrosoftExt = 1;
4263 LangOpts.DeclSpecKeyword = 1;
4270 "Set coding style. <string> can be:\n"
4271 "1. A preset: LLVM, GNU, Google, Chromium, Microsoft,\n"
4272 " Mozilla, WebKit.\n"
4273 "2. 'file' to load style configuration from a\n"
4274 " .clang-format file in one of the parent directories\n"
4275 " of the source file (for stdin, see --assume-filename).\n"
4276 " If no .clang-format file is found, falls back to\n"
4277 " --fallback-style.\n"
4278 " --style=file is the default.\n"
4279 "3. 'file:<format_file_path>' to explicitly specify\n"
4280 " the configuration file.\n"
4281 "4. \"{key: value, ...}\" to set specific parameters, e.g.:\n"
4282 " --style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
4286 return FormatStyle::LK_C;
4288 return FormatStyle::LK_Java;
4289 if (
FileName.ends_with_insensitive(
".js") ||
4290 FileName.ends_with_insensitive(
".mjs") ||
4291 FileName.ends_with_insensitive(
".cjs") ||
4292 FileName.ends_with_insensitive(
".ts")) {
4293 return FormatStyle::LK_JavaScript;
4296 return FormatStyle::LK_ObjC;
4297 if (
FileName.ends_with_insensitive(
".proto") ||
4298 FileName.ends_with_insensitive(
".protodevel")) {
4299 return FormatStyle::LK_Proto;
4304 if (
FileName.ends_with_insensitive(
".txtpb") ||
4305 FileName.ends_with_insensitive(
".textpb") ||
4306 FileName.ends_with_insensitive(
".pb.txt") ||
4307 FileName.ends_with_insensitive(
".textproto") ||
4308 FileName.ends_with_insensitive(
".asciipb")) {
4309 return FormatStyle::LK_TextProto;
4311 if (
FileName.ends_with_insensitive(
".td"))
4312 return FormatStyle::LK_TableGen;
4313 if (
FileName.ends_with_insensitive(
".cs"))
4314 return FormatStyle::LK_CSharp;
4315 if (
FileName.ends_with_insensitive(
".json") ||
4316 FileName.ends_with_insensitive(
".ipynb")) {
4317 return FormatStyle::LK_Json;
4319 if (
FileName.ends_with_insensitive(
".sv") ||
4320 FileName.ends_with_insensitive(
".svh") ||
4321 FileName.ends_with_insensitive(
".v") ||
4322 FileName.ends_with_insensitive(
".vh")) {
4323 return FormatStyle::LK_Verilog;
4325 return FormatStyle::LK_Cpp;
4333 LangOpts.CPlusPlus = 1;
4334 LangOpts.LineComment = 1;
4336 Lexer Lex(ID, SourceMgr.getBufferOrFake(ID), SourceMgr, LangOpts);
4340 auto Text = StringRef(SourceMgr.getCharacterData(
Tok.getLocation()),
4342 if (!
Text.consume_front(
"// clang-format Language:"))
4347 return FormatStyle::LK_C;
4349 return FormatStyle::LK_Cpp;
4351 return FormatStyle::LK_ObjC;
4354 return FormatStyle::LK_None;
4359 if (GuessedLanguage == FormatStyle::LK_Cpp) {
4360 auto Extension = llvm::sys::path::extension(
FileName);
4363 if (!Code.empty() && (Extension.empty() || Extension ==
".h")) {
4367 Language != FormatStyle::LK_None) {
4372 if (Guesser.isObjC())
4373 return FormatStyle::LK_ObjC;
4376 return GuessedLanguage;
4384llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
4386 FormatStyle *Style,
bool AllowUnknownOptions,
4387 llvm::SourceMgr::DiagHandlerTy DiagHandler,
4389 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Text =
4390 FS->getBufferForFile(ConfigFile.str());
4391 if (
auto EC =
Text.getError())
4394 DiagHandler,
nullptr,
4402 StringRef FallbackStyleName, StringRef Code,
4403 llvm::vfs::FileSystem *FS,
4404 bool AllowUnknownOptions,
4405 llvm::SourceMgr::DiagHandlerTy DiagHandler) {
4413 if (StyleName.starts_with(
"{")) {
4415 StringRef Source =
"<command-line>";
4416 if (std::error_code ec =
4418 AllowUnknownOptions, DiagHandler)) {
4422 if (!Style.InheritsParentConfig)
4425 ChildFormatTextToApply.emplace_back(
4426 llvm::MemoryBuffer::getMemBuffer(StyleName, Source,
false));
4430 FS = llvm::vfs::getRealFileSystem().get();
4433 const bool IsDotHFile =
FileName.ends_with(
".h");
4436 if (!Style.InheritsParentConfig &&
4437 StyleName.starts_with_insensitive(
"file:")) {
4438 auto ConfigFile = StyleName.substr(5);
4439 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Text =
4441 DiagHandler, IsDotHFile);
4442 if (
auto EC =
Text.getError()) {
4447 LLVM_DEBUG(llvm::dbgs()
4448 <<
"Using configuration file " << ConfigFile <<
"\n");
4450 if (!Style.InheritsParentConfig)
4456 ChildFormatTextToApply.emplace_back(std::move(*
Text));
4462 if (!Style.InheritsParentConfig && !StyleName.equals_insensitive(
"file")) {
4465 if (!Style.InheritsParentConfig)
4470 if (std::error_code EC = FS->makeAbsolute(Path))
4474 Style.InheritsParentConfig =
false;
4476 auto dropDiagnosticHandler = [](
const llvm::SMDiagnostic &,
void *) {};
4478 auto applyChildFormatTexts = [&](FormatStyle *Style) {
4479 for (
const auto &MemBuf : llvm::reverse(ChildFormatTextToApply)) {
4482 DiagHandler ? DiagHandler : dropDiagnosticHandler);
4485 static_cast<void>(EC);
4491 FilesToLookFor.push_back(
".clang-format");
4492 FilesToLookFor.push_back(
"_clang-format");
4495 for (StringRef Directory = Path; !Directory.empty();
4496 Directory = llvm::sys::path::parent_path(Directory)) {
4497 auto Status = FS->status(Directory);
4499 Status->getType() != llvm::sys::fs::file_type::directory_file) {
4503 for (
const auto &F : FilesToLookFor) {
4506 llvm::sys::path::append(ConfigFile, F);
4507 LLVM_DEBUG(llvm::dbgs() <<
"Trying " << ConfigFile <<
"...\n");
4509 Status = FS->status(ConfigFile);
4511 Status->getType() != llvm::sys::fs::file_type::regular_file) {
4515 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Text =
4517 DiagHandler, IsDotHFile);
4518 if (
auto EC =
Text.getError()) {
4523 if (!UnsuitableConfigFiles.empty())
4524 UnsuitableConfigFiles.append(
", ");
4525 UnsuitableConfigFiles.append(ConfigFile);
4529 LLVM_DEBUG(llvm::dbgs()
4530 <<
"Using configuration file " << ConfigFile <<
"\n");
4532 if (!Style.InheritsParentConfig) {
4533 if (!ChildFormatTextToApply.empty()) {
4534 LLVM_DEBUG(llvm::dbgs() <<
"Applying child configurations\n");
4535 applyChildFormatTexts(&Style);
4540 LLVM_DEBUG(llvm::dbgs() <<
"Inherits parent configuration\n");
4543 Style.InheritsParentConfig =
false;
4545 ChildFormatTextToApply.emplace_back(std::move(*
Text));
4555 if (!UnsuitableConfigFiles.empty()) {
4558 UnsuitableConfigFiles);
4561 if (!ChildFormatTextToApply.empty()) {
4562 LLVM_DEBUG(llvm::dbgs()
4563 <<
"Applying child configurations on fallback style\n");
4564 applyChildFormatTexts(&FallbackStyle);
4567 return FallbackStyle;
4571 if (Comment == (On ?
"/* clang-format on */" :
"/* clang-format off */"))
4574 static const char ClangFormatOn[] =
"// clang-format on";
4575 static const char ClangFormatOff[] =
"// clang-format off";
4576 const unsigned Size = (On ?
sizeof ClangFormatOn :
sizeof ClangFormatOff) - 1;
4578 return Comment.starts_with(On ? ClangFormatOn : ClangFormatOff) &&
4579 (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)