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(
"BinaryMinDigitsInsert",
Base.BinaryMinDigitsInsert);
409 IO.mapOptional(
"BinaryMaxDigitsRemove",
Base.BinaryMaxDigitsRemove);
410 IO.mapOptional(
"Decimal",
Base.Decimal);
411 IO.mapOptional(
"DecimalMinDigitsInsert",
Base.DecimalMinDigitsInsert);
412 IO.mapOptional(
"DecimalMaxDigitsRemove",
Base.DecimalMaxDigitsRemove);
413 IO.mapOptional(
"Hex",
Base.Hex);
414 IO.mapOptional(
"HexMinDigitsInsert",
Base.HexMinDigitsInsert);
415 IO.mapOptional(
"HexMaxDigitsRemove",
Base.HexMaxDigitsRemove);
418 IO.mapOptional(
"BinaryMinDigits",
Base.BinaryMinDigitsInsert);
419 IO.mapOptional(
"DecimalMinDigits",
Base.DecimalMinDigitsInsert);
420 IO.mapOptional(
"HexMinDigits",
Base.HexMinDigitsInsert);
424template <>
struct ScalarEnumerationTraits<FormatStyle::JavaScriptQuoteStyle> {
426 IO.enumCase(
Value,
"Leave", FormatStyle::JSQS_Leave);
427 IO.enumCase(
Value,
"Single", FormatStyle::JSQS_Single);
428 IO.enumCase(
Value,
"Double", FormatStyle::JSQS_Double);
432template <>
struct MappingTraits<FormatStyle::KeepEmptyLinesStyle> {
434 IO.mapOptional(
"AtEndOfFile",
Value.AtEndOfFile);
435 IO.mapOptional(
"AtStartOfBlock",
Value.AtStartOfBlock);
436 IO.mapOptional(
"AtStartOfFile",
Value.AtStartOfFile);
440template <>
struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
442 IO.enumCase(
Value,
"C", FormatStyle::LK_C);
443 IO.enumCase(
Value,
"Cpp", FormatStyle::LK_Cpp);
444 IO.enumCase(
Value,
"Java", FormatStyle::LK_Java);
445 IO.enumCase(
Value,
"JavaScript", FormatStyle::LK_JavaScript);
446 IO.enumCase(
Value,
"ObjC", FormatStyle::LK_ObjC);
447 IO.enumCase(
Value,
"Proto", FormatStyle::LK_Proto);
448 IO.enumCase(
Value,
"TableGen", FormatStyle::LK_TableGen);
449 IO.enumCase(
Value,
"TextProto", FormatStyle::LK_TextProto);
450 IO.enumCase(
Value,
"CSharp", FormatStyle::LK_CSharp);
451 IO.enumCase(
Value,
"Json", FormatStyle::LK_Json);
452 IO.enumCase(
Value,
"Verilog", FormatStyle::LK_Verilog);
456template <>
struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
458 IO.enumCase(
Value,
"c++03", FormatStyle::LS_Cpp03);
459 IO.enumCase(
Value,
"C++03", FormatStyle::LS_Cpp03);
460 IO.enumCase(
Value,
"Cpp03", FormatStyle::LS_Cpp03);
462 IO.enumCase(
Value,
"c++11", FormatStyle::LS_Cpp11);
463 IO.enumCase(
Value,
"C++11", FormatStyle::LS_Cpp11);
465 IO.enumCase(
Value,
"c++14", FormatStyle::LS_Cpp14);
466 IO.enumCase(
Value,
"c++17", FormatStyle::LS_Cpp17);
467 IO.enumCase(
Value,
"c++20", FormatStyle::LS_Cpp20);
469 IO.enumCase(
Value,
"Latest", FormatStyle::LS_Latest);
470 IO.enumCase(
Value,
"Cpp11", FormatStyle::LS_Latest);
471 IO.enumCase(
Value,
"Auto", FormatStyle::LS_Auto);
476struct ScalarEnumerationTraits<FormatStyle::LambdaBodyIndentationKind> {
478 FormatStyle::LambdaBodyIndentationKind &
Value) {
479 IO.enumCase(
Value,
"Signature", FormatStyle::LBI_Signature);
480 IO.enumCase(
Value,
"OuterScope", FormatStyle::LBI_OuterScope);
484template <>
struct ScalarEnumerationTraits<FormatStyle::LineEndingStyle> {
486 IO.enumCase(
Value,
"LF", FormatStyle::LE_LF);
487 IO.enumCase(
Value,
"CRLF", FormatStyle::LE_CRLF);
488 IO.enumCase(
Value,
"DeriveLF", FormatStyle::LE_DeriveLF);
489 IO.enumCase(
Value,
"DeriveCRLF", FormatStyle::LE_DeriveCRLF);
494struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
496 FormatStyle::NamespaceIndentationKind &
Value) {
497 IO.enumCase(
Value,
"None", FormatStyle::NI_None);
498 IO.enumCase(
Value,
"Inner", FormatStyle::NI_Inner);
499 IO.enumCase(
Value,
"All", FormatStyle::NI_All);
504struct ScalarEnumerationTraits<FormatStyle::NumericLiteralComponentStyle> {
506 FormatStyle::NumericLiteralComponentStyle &
Value) {
507 IO.enumCase(
Value,
"Leave", FormatStyle::NLCS_Leave);
508 IO.enumCase(
Value,
"Upper", FormatStyle::NLCS_Upper);
509 IO.enumCase(
Value,
"Lower", FormatStyle::NLCS_Lower);
513template <>
struct MappingTraits<FormatStyle::NumericLiteralCaseStyle> {
514 static void mapping(IO &IO, FormatStyle::NumericLiteralCaseStyle &
Value) {
515 IO.mapOptional(
"ExponentLetter",
Value.ExponentLetter);
516 IO.mapOptional(
"HexDigit",
Value.HexDigit);
517 IO.mapOptional(
"Prefix",
Value.Prefix);
518 IO.mapOptional(
"Suffix",
Value.Suffix);
522template <>
struct ScalarEnumerationTraits<FormatStyle::OperandAlignmentStyle> {
524 IO.enumCase(
Value,
"DontAlign", FormatStyle::OAS_DontAlign);
525 IO.enumCase(
Value,
"Align", FormatStyle::OAS_Align);
526 IO.enumCase(
Value,
"AlignAfterOperator",
527 FormatStyle::OAS_AlignAfterOperator);
530 IO.enumCase(
Value,
"true", FormatStyle::OAS_Align);
531 IO.enumCase(
Value,
"false", FormatStyle::OAS_DontAlign);
536struct ScalarEnumerationTraits<FormatStyle::PackConstructorInitializersStyle> {
539 IO.enumCase(
Value,
"Never", FormatStyle::PCIS_Never);
540 IO.enumCase(
Value,
"BinPack", FormatStyle::PCIS_BinPack);
541 IO.enumCase(
Value,
"CurrentLine", FormatStyle::PCIS_CurrentLine);
542 IO.enumCase(
Value,
"NextLine", FormatStyle::PCIS_NextLine);
543 IO.enumCase(
Value,
"NextLineOnly", FormatStyle::PCIS_NextLineOnly);
547template <>
struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
549 IO.enumCase(
Value,
"Middle", FormatStyle::PAS_Middle);
550 IO.enumCase(
Value,
"Left", FormatStyle::PAS_Left);
551 IO.enumCase(
Value,
"Right", FormatStyle::PAS_Right);
554 IO.enumCase(
Value,
"true", FormatStyle::PAS_Left);
555 IO.enumCase(
Value,
"false", FormatStyle::PAS_Right);
560struct ScalarEnumerationTraits<FormatStyle::PPDirectiveIndentStyle> {
562 IO.enumCase(
Value,
"None", FormatStyle::PPDIS_None);
563 IO.enumCase(
Value,
"AfterHash", FormatStyle::PPDIS_AfterHash);
564 IO.enumCase(
Value,
"BeforeHash", FormatStyle::PPDIS_BeforeHash);
565 IO.enumCase(
Value,
"Leave", FormatStyle::PPDIS_Leave);
570struct ScalarEnumerationTraits<FormatStyle::QualifierAlignmentStyle> {
572 IO.enumCase(
Value,
"Leave", FormatStyle::QAS_Leave);
573 IO.enumCase(
Value,
"Left", FormatStyle::QAS_Left);
574 IO.enumCase(
Value,
"Right", FormatStyle::QAS_Right);
575 IO.enumCase(
Value,
"Custom", FormatStyle::QAS_Custom);
579template <>
struct MappingTraits<FormatStyle::RawStringFormat> {
580 static void mapping(IO &IO, FormatStyle::RawStringFormat &Format) {
581 IO.mapOptional(
"Language", Format.Language);
582 IO.mapOptional(
"Delimiters", Format.Delimiters);
583 IO.mapOptional(
"EnclosingFunctions", Format.EnclosingFunctions);
584 IO.mapOptional(
"CanonicalDelimiter", Format.CanonicalDelimiter);
585 IO.mapOptional(
"BasedOnStyle", Format.BasedOnStyle);
589template <>
struct ScalarEnumerationTraits<FormatStyle::ReflowCommentsStyle> {
591 IO.enumCase(
Value,
"Never", FormatStyle::RCS_Never);
592 IO.enumCase(
Value,
"IndentOnly", FormatStyle::RCS_IndentOnly);
593 IO.enumCase(
Value,
"Always", FormatStyle::RCS_Always);
595 IO.enumCase(
Value,
"false", FormatStyle::RCS_Never);
596 IO.enumCase(
Value,
"true", FormatStyle::RCS_Always);
601struct ScalarEnumerationTraits<FormatStyle::ReferenceAlignmentStyle> {
603 IO.enumCase(
Value,
"Pointer", FormatStyle::RAS_Pointer);
604 IO.enumCase(
Value,
"Middle", FormatStyle::RAS_Middle);
605 IO.enumCase(
Value,
"Left", FormatStyle::RAS_Left);
606 IO.enumCase(
Value,
"Right", FormatStyle::RAS_Right);
611struct ScalarEnumerationTraits<FormatStyle::RemoveParenthesesStyle> {
613 IO.enumCase(
Value,
"Leave", FormatStyle::RPS_Leave);
614 IO.enumCase(
Value,
"MultipleParentheses",
615 FormatStyle::RPS_MultipleParentheses);
616 IO.enumCase(
Value,
"ReturnStatement", FormatStyle::RPS_ReturnStatement);
621struct ScalarEnumerationTraits<FormatStyle::RequiresClausePositionStyle> {
623 FormatStyle::RequiresClausePositionStyle &
Value) {
624 IO.enumCase(
Value,
"OwnLine", FormatStyle::RCPS_OwnLine);
625 IO.enumCase(
Value,
"OwnLineWithBrace", FormatStyle::RCPS_OwnLineWithBrace);
626 IO.enumCase(
Value,
"WithPreceding", FormatStyle::RCPS_WithPreceding);
627 IO.enumCase(
Value,
"WithFollowing", FormatStyle::RCPS_WithFollowing);
628 IO.enumCase(
Value,
"SingleLine", FormatStyle::RCPS_SingleLine);
633struct ScalarEnumerationTraits<FormatStyle::RequiresExpressionIndentationKind> {
636 IO.enumCase(
Value,
"Keyword", FormatStyle::REI_Keyword);
637 IO.enumCase(
Value,
"OuterScope", FormatStyle::REI_OuterScope);
642struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
644 IO.enumCase(
Value,
"None", FormatStyle::RTBS_None);
645 IO.enumCase(
Value,
"Automatic", FormatStyle::RTBS_Automatic);
646 IO.enumCase(
Value,
"ExceptShortType", FormatStyle::RTBS_ExceptShortType);
647 IO.enumCase(
Value,
"All", FormatStyle::RTBS_All);
648 IO.enumCase(
Value,
"TopLevel", FormatStyle::RTBS_TopLevel);
649 IO.enumCase(
Value,
"TopLevelDefinitions",
650 FormatStyle::RTBS_TopLevelDefinitions);
651 IO.enumCase(
Value,
"AllDefinitions", FormatStyle::RTBS_AllDefinitions);
656struct ScalarEnumerationTraits<FormatStyle::SeparateDefinitionStyle> {
658 IO.enumCase(
Value,
"Leave", FormatStyle::SDS_Leave);
659 IO.enumCase(
Value,
"Always", FormatStyle::SDS_Always);
660 IO.enumCase(
Value,
"Never", FormatStyle::SDS_Never);
664template <>
struct ScalarEnumerationTraits<FormatStyle::ShortBlockStyle> {
666 IO.enumCase(
Value,
"Never", FormatStyle::SBS_Never);
667 IO.enumCase(
Value,
"false", FormatStyle::SBS_Never);
668 IO.enumCase(
Value,
"Always", FormatStyle::SBS_Always);
669 IO.enumCase(
Value,
"true", FormatStyle::SBS_Always);
670 IO.enumCase(
Value,
"Empty", FormatStyle::SBS_Empty);
674template <>
struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
676 IO.enumCase(
Value,
"None", FormatStyle::SFS_None);
677 IO.enumCase(
Value,
"false", FormatStyle::SFS_None);
678 IO.enumCase(
Value,
"All", FormatStyle::SFS_All);
679 IO.enumCase(
Value,
"true", FormatStyle::SFS_All);
680 IO.enumCase(
Value,
"Inline", FormatStyle::SFS_Inline);
681 IO.enumCase(
Value,
"InlineOnly", FormatStyle::SFS_InlineOnly);
682 IO.enumCase(
Value,
"Empty", FormatStyle::SFS_Empty);
686template <>
struct ScalarEnumerationTraits<FormatStyle::ShortIfStyle> {
688 IO.enumCase(
Value,
"Never", FormatStyle::SIS_Never);
689 IO.enumCase(
Value,
"WithoutElse", FormatStyle::SIS_WithoutElse);
690 IO.enumCase(
Value,
"OnlyFirstIf", FormatStyle::SIS_OnlyFirstIf);
691 IO.enumCase(
Value,
"AllIfsAndElse", FormatStyle::SIS_AllIfsAndElse);
694 IO.enumCase(
Value,
"Always", FormatStyle::SIS_OnlyFirstIf);
695 IO.enumCase(
Value,
"false", FormatStyle::SIS_Never);
696 IO.enumCase(
Value,
"true", FormatStyle::SIS_WithoutElse);
700template <>
struct ScalarEnumerationTraits<FormatStyle::ShortLambdaStyle> {
702 IO.enumCase(
Value,
"None", FormatStyle::SLS_None);
703 IO.enumCase(
Value,
"false", FormatStyle::SLS_None);
704 IO.enumCase(
Value,
"Empty", FormatStyle::SLS_Empty);
705 IO.enumCase(
Value,
"Inline", FormatStyle::SLS_Inline);
706 IO.enumCase(
Value,
"All", FormatStyle::SLS_All);
707 IO.enumCase(
Value,
"true", FormatStyle::SLS_All);
711template <>
struct MappingTraits<FormatStyle::SortIncludesOptions> {
713 IO.enumCase(
Value,
"Never", FormatStyle::SortIncludesOptions({}));
714 IO.enumCase(
Value,
"CaseInsensitive",
715 FormatStyle::SortIncludesOptions({
true,
718 IO.enumCase(
Value,
"CaseSensitive",
719 FormatStyle::SortIncludesOptions({
true,
724 IO.enumCase(
Value,
"false", FormatStyle::SortIncludesOptions({}));
725 IO.enumCase(
Value,
"true",
726 FormatStyle::SortIncludesOptions({
true,
732 IO.mapOptional(
"Enabled",
Value.Enabled);
733 IO.mapOptional(
"IgnoreCase",
Value.IgnoreCase);
734 IO.mapOptional(
"IgnoreExtension",
Value.IgnoreExtension);
739struct ScalarEnumerationTraits<FormatStyle::SortJavaStaticImportOptions> {
741 FormatStyle::SortJavaStaticImportOptions &
Value) {
742 IO.enumCase(
Value,
"Before", FormatStyle::SJSIO_Before);
743 IO.enumCase(
Value,
"After", FormatStyle::SJSIO_After);
748struct ScalarEnumerationTraits<FormatStyle::SortUsingDeclarationsOptions> {
750 FormatStyle::SortUsingDeclarationsOptions &
Value) {
751 IO.enumCase(
Value,
"Never", FormatStyle::SUD_Never);
752 IO.enumCase(
Value,
"Lexicographic", FormatStyle::SUD_Lexicographic);
753 IO.enumCase(
Value,
"LexicographicNumeric",
754 FormatStyle::SUD_LexicographicNumeric);
757 IO.enumCase(
Value,
"false", FormatStyle::SUD_Never);
758 IO.enumCase(
Value,
"true", FormatStyle::SUD_LexicographicNumeric);
763struct ScalarEnumerationTraits<FormatStyle::SpaceAroundPointerQualifiersStyle> {
766 IO.enumCase(
Value,
"Default", FormatStyle::SAPQ_Default);
767 IO.enumCase(
Value,
"Before", FormatStyle::SAPQ_Before);
768 IO.enumCase(
Value,
"After", FormatStyle::SAPQ_After);
769 IO.enumCase(
Value,
"Both", FormatStyle::SAPQ_Both);
773template <>
struct MappingTraits<FormatStyle::SpaceBeforeParensCustom> {
774 static void mapping(IO &IO, FormatStyle::SpaceBeforeParensCustom &Spacing) {
775 IO.mapOptional(
"AfterControlStatements", Spacing.AfterControlStatements);
776 IO.mapOptional(
"AfterForeachMacros", Spacing.AfterForeachMacros);
777 IO.mapOptional(
"AfterFunctionDefinitionName",
778 Spacing.AfterFunctionDefinitionName);
779 IO.mapOptional(
"AfterFunctionDeclarationName",
780 Spacing.AfterFunctionDeclarationName);
781 IO.mapOptional(
"AfterIfMacros", Spacing.AfterIfMacros);
782 IO.mapOptional(
"AfterNot", Spacing.AfterNot);
783 IO.mapOptional(
"AfterOverloadedOperator", Spacing.AfterOverloadedOperator);
784 IO.mapOptional(
"AfterPlacementOperator", Spacing.AfterPlacementOperator);
785 IO.mapOptional(
"AfterRequiresInClause", Spacing.AfterRequiresInClause);
786 IO.mapOptional(
"AfterRequiresInExpression",
787 Spacing.AfterRequiresInExpression);
788 IO.mapOptional(
"BeforeNonEmptyParentheses",
789 Spacing.BeforeNonEmptyParentheses);
794struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensStyle> {
796 IO.enumCase(
Value,
"Never", FormatStyle::SBPO_Never);
797 IO.enumCase(
Value,
"ControlStatements",
798 FormatStyle::SBPO_ControlStatements);
799 IO.enumCase(
Value,
"ControlStatementsExceptControlMacros",
800 FormatStyle::SBPO_ControlStatementsExceptControlMacros);
801 IO.enumCase(
Value,
"NonEmptyParentheses",
802 FormatStyle::SBPO_NonEmptyParentheses);
803 IO.enumCase(
Value,
"Always", FormatStyle::SBPO_Always);
804 IO.enumCase(
Value,
"Custom", FormatStyle::SBPO_Custom);
807 IO.enumCase(
Value,
"false", FormatStyle::SBPO_Never);
808 IO.enumCase(
Value,
"true", FormatStyle::SBPO_ControlStatements);
809 IO.enumCase(
Value,
"ControlStatementsExceptForEachMacros",
810 FormatStyle::SBPO_ControlStatementsExceptControlMacros);
815struct ScalarEnumerationTraits<FormatStyle::SpaceInEmptyBracesStyle> {
817 IO.enumCase(
Value,
"Always", FormatStyle::SIEB_Always);
818 IO.enumCase(
Value,
"Block", FormatStyle::SIEB_Block);
819 IO.enumCase(
Value,
"Never", FormatStyle::SIEB_Never);
823template <>
struct ScalarEnumerationTraits<FormatStyle::SpacesInAnglesStyle> {
825 IO.enumCase(
Value,
"Never", FormatStyle::SIAS_Never);
826 IO.enumCase(
Value,
"Always", FormatStyle::SIAS_Always);
827 IO.enumCase(
Value,
"Leave", FormatStyle::SIAS_Leave);
830 IO.enumCase(
Value,
"false", FormatStyle::SIAS_Never);
831 IO.enumCase(
Value,
"true", FormatStyle::SIAS_Always);
835template <>
struct MappingTraits<FormatStyle::SpacesInLineComment> {
836 static void mapping(IO &IO, FormatStyle::SpacesInLineComment &Space) {
838 int signedMaximum =
static_cast<int>(Space.Maximum);
839 IO.mapOptional(
"Minimum", Space.Minimum);
840 IO.mapOptional(
"Maximum", signedMaximum);
841 Space.Maximum =
static_cast<unsigned>(signedMaximum);
843 if (Space.Maximum < std::numeric_limits<unsigned>::max())
844 Space.Minimum = std::min(Space.Minimum, Space.Maximum);
848template <>
struct MappingTraits<FormatStyle::SpacesInParensCustom> {
849 static void mapping(IO &IO, FormatStyle::SpacesInParensCustom &Spaces) {
850 IO.mapOptional(
"ExceptDoubleParentheses", Spaces.ExceptDoubleParentheses);
851 IO.mapOptional(
"InCStyleCasts", Spaces.InCStyleCasts);
852 IO.mapOptional(
"InConditionalStatements", Spaces.InConditionalStatements);
853 IO.mapOptional(
"InEmptyParentheses", Spaces.InEmptyParentheses);
854 IO.mapOptional(
"Other", Spaces.Other);
858template <>
struct ScalarEnumerationTraits<FormatStyle::SpacesInParensStyle> {
860 IO.enumCase(
Value,
"Never", FormatStyle::SIPO_Never);
861 IO.enumCase(
Value,
"Custom", FormatStyle::SIPO_Custom);
865template <>
struct ScalarEnumerationTraits<FormatStyle::TrailingCommaStyle> {
867 IO.enumCase(
Value,
"None", FormatStyle::TCS_None);
868 IO.enumCase(
Value,
"Wrapped", FormatStyle::TCS_Wrapped);
873struct ScalarEnumerationTraits<FormatStyle::TrailingCommentsAlignmentKinds> {
875 FormatStyle::TrailingCommentsAlignmentKinds &
Value) {
876 IO.enumCase(
Value,
"Leave", FormatStyle::TCAS_Leave);
877 IO.enumCase(
Value,
"Always", FormatStyle::TCAS_Always);
878 IO.enumCase(
Value,
"Never", FormatStyle::TCAS_Never);
882template <>
struct MappingTraits<FormatStyle::TrailingCommentsAlignmentStyle> {
884 FormatStyle::TrailingCommentsAlignmentStyle &
Value) {
885 IO.enumCase(
Value,
"Leave",
886 FormatStyle::TrailingCommentsAlignmentStyle(
887 {FormatStyle::TCAS_Leave, 0,
true}));
889 IO.enumCase(
Value,
"Always",
890 FormatStyle::TrailingCommentsAlignmentStyle(
891 {FormatStyle::TCAS_Always, 0,
true}));
893 IO.enumCase(
Value,
"Never",
894 FormatStyle::TrailingCommentsAlignmentStyle(
895 {FormatStyle::TCAS_Never, 0,
true}));
898 IO.enumCase(
Value,
"true",
899 FormatStyle::TrailingCommentsAlignmentStyle(
900 {FormatStyle::TCAS_Always, 0,
true}));
901 IO.enumCase(
Value,
"false",
902 FormatStyle::TrailingCommentsAlignmentStyle(
903 {FormatStyle::TCAS_Never, 0,
true}));
907 FormatStyle::TrailingCommentsAlignmentStyle &
Value) {
908 IO.mapOptional(
"AlignPPAndNotPP",
Value.AlignPPAndNotPP);
909 IO.mapOptional(
"Kind",
Value.Kind);
910 IO.mapOptional(
"OverEmptyLines",
Value.OverEmptyLines);
914template <>
struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
916 IO.enumCase(
Value,
"Never", FormatStyle::UT_Never);
917 IO.enumCase(
Value,
"false", FormatStyle::UT_Never);
918 IO.enumCase(
Value,
"Always", FormatStyle::UT_Always);
919 IO.enumCase(
Value,
"true", FormatStyle::UT_Always);
920 IO.enumCase(
Value,
"ForIndentation", FormatStyle::UT_ForIndentation);
921 IO.enumCase(
Value,
"ForContinuationAndIndentation",
922 FormatStyle::UT_ForContinuationAndIndentation);
923 IO.enumCase(
Value,
"AlignWithSpaces", FormatStyle::UT_AlignWithSpaces);
928struct ScalarEnumerationTraits<
929 FormatStyle::WrapNamespaceBodyWithEmptyLinesStyle> {
932 FormatStyle::WrapNamespaceBodyWithEmptyLinesStyle &
Value) {
933 IO.enumCase(
Value,
"Never", FormatStyle::WNBWELS_Never);
934 IO.enumCase(
Value,
"Always", FormatStyle::WNBWELS_Always);
935 IO.enumCase(
Value,
"Leave", FormatStyle::WNBWELS_Leave);
939template <>
struct MappingTraits<FormatStyle> {
940 static void mapping(IO &IO, FormatStyle &Style) {
942 IO.mapOptional(
"Language", Style.Language);
944 StringRef BasedOnStyle;
945 if (IO.outputting()) {
946 StringRef Styles[] = {
"LLVM",
"Google",
"Chromium",
"Mozilla",
947 "WebKit",
"GNU",
"Microsoft",
"clang-format"};
948 for (StringRef StyleName : Styles) {
949 FormatStyle PredefinedStyle;
951 Style == PredefinedStyle) {
952 BasedOnStyle = StyleName;
957 IO.mapOptional(
"BasedOnStyle", BasedOnStyle);
958 if (!BasedOnStyle.empty()) {
959 FormatStyle::LanguageKind OldLanguage = Style.Language;
960 FormatStyle::LanguageKind Language =
961 ((FormatStyle *)IO.getContext())->Language;
963 IO.setError(Twine(
"Unknown value for BasedOnStyle: ", BasedOnStyle));
966 Style.Language = OldLanguage;
981 const bool IsGoogleOrChromium = BasedOnStyle.equals_insensitive(
"google") ||
982 BasedOnStyle.equals_insensitive(
"chromium");
983 bool OnCurrentLine = IsGoogleOrChromium;
984 bool OnNextLine =
true;
986 bool BreakBeforeInheritanceComma =
false;
987 bool BreakConstructorInitializersBeforeComma =
false;
989 bool DeriveLineEnding =
true;
990 bool UseCRLF =
false;
992 bool SpaceInEmptyBlock =
false;
993 bool SpaceInEmptyParentheses =
false;
994 bool SpacesInConditionalStatement =
false;
995 bool SpacesInCStyleCastParentheses =
false;
996 bool SpacesInParentheses =
false;
998 if (IO.outputting()) {
999 IO.mapOptional(
"AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
1003 if (IsGoogleOrChromium) {
1004 FormatStyle::LanguageKind Language = Style.Language;
1005 if (Language == FormatStyle::LK_None)
1006 Language = ((FormatStyle *)IO.getContext())->Language;
1007 if (Language == FormatStyle::LK_JavaScript)
1009 else if (Language == FormatStyle::LK_Java)
1011 }
else if (BasedOnStyle.equals_insensitive(
"webkit")) {
1014 IO.mapOptional(
"AlignAfterOpenBracket", LocalBAS);
1015 Style.BreakAfterOpenBracketBracedList =
false;
1016 Style.BreakAfterOpenBracketFunction =
false;
1017 Style.BreakAfterOpenBracketIf =
false;
1018 Style.BreakAfterOpenBracketLoop =
false;
1019 Style.BreakAfterOpenBracketSwitch =
false;
1020 Style.BreakBeforeCloseBracketBracedList =
false;
1021 Style.BreakBeforeCloseBracketFunction =
false;
1022 Style.BreakBeforeCloseBracketIf =
false;
1023 Style.BreakBeforeCloseBracketLoop =
false;
1024 Style.BreakBeforeCloseBracketSwitch =
false;
1028 Style.AlignAfterOpenBracket =
false;
1031 Style.BreakBeforeCloseBracketBracedList =
true;
1032 Style.BreakBeforeCloseBracketFunction =
true;
1033 Style.BreakBeforeCloseBracketIf =
true;
1036 Style.BreakAfterOpenBracketBracedList =
true;
1037 Style.BreakAfterOpenBracketFunction =
true;
1038 Style.BreakAfterOpenBracketIf =
true;
1041 Style.AlignAfterOpenBracket =
true;
1047 if (!IO.outputting()) {
1048 IO.mapOptional(
"AlignEscapedNewlinesLeft", Style.AlignEscapedNewlines);
1049 IO.mapOptional(
"AllowAllConstructorInitializersOnNextLine", OnNextLine);
1050 IO.mapOptional(
"AlwaysBreakAfterReturnType", Style.BreakAfterReturnType);
1051 IO.mapOptional(
"AlwaysBreakTemplateDeclarations",
1052 Style.BreakTemplateDeclarations);
1053 IO.mapOptional(
"BreakBeforeInheritanceComma",
1054 BreakBeforeInheritanceComma);
1055 IO.mapOptional(
"BreakConstructorInitializersBeforeComma",
1056 BreakConstructorInitializersBeforeComma);
1057 IO.mapOptional(
"ConstructorInitializerAllOnOneLineOrOnePerLine",
1059 IO.mapOptional(
"DeriveLineEnding", DeriveLineEnding);
1060 IO.mapOptional(
"DerivePointerBinding", Style.DerivePointerAlignment);
1061 IO.mapOptional(
"KeepEmptyLinesAtEOF", Style.KeepEmptyLines.AtEndOfFile);
1062 IO.mapOptional(
"KeepEmptyLinesAtTheStartOfBlocks",
1063 Style.KeepEmptyLines.AtStartOfBlock);
1064 IO.mapOptional(
"IndentFunctionDeclarationAfterType",
1065 Style.IndentWrappedFunctionNames);
1066 IO.mapOptional(
"IndentRequires", Style.IndentRequiresClause);
1067 IO.mapOptional(
"PointerBindsToType", Style.PointerAlignment);
1068 IO.mapOptional(
"SpaceAfterControlStatementKeyword",
1069 Style.SpaceBeforeParens);
1070 IO.mapOptional(
"SpaceInEmptyBlock", SpaceInEmptyBlock);
1071 IO.mapOptional(
"SpaceInEmptyParentheses", SpaceInEmptyParentheses);
1072 IO.mapOptional(
"SpacesInConditionalStatement",
1073 SpacesInConditionalStatement);
1074 IO.mapOptional(
"SpacesInCStyleCastParentheses",
1075 SpacesInCStyleCastParentheses);
1076 IO.mapOptional(
"SpacesInParentheses", SpacesInParentheses);
1077 IO.mapOptional(
"UseCRLF", UseCRLF);
1080 IO.mapOptional(
"AccessModifierOffset", Style.AccessModifierOffset);
1081 IO.mapOptional(
"AlignArrayOfStructures", Style.AlignArrayOfStructures);
1082 IO.mapOptional(
"AlignConsecutiveAssignments",
1083 Style.AlignConsecutiveAssignments);
1084 IO.mapOptional(
"AlignConsecutiveBitFields",
1085 Style.AlignConsecutiveBitFields);
1086 IO.mapOptional(
"AlignConsecutiveDeclarations",
1087 Style.AlignConsecutiveDeclarations);
1088 IO.mapOptional(
"AlignConsecutiveMacros", Style.AlignConsecutiveMacros);
1089 IO.mapOptional(
"AlignConsecutiveShortCaseStatements",
1090 Style.AlignConsecutiveShortCaseStatements);
1091 IO.mapOptional(
"AlignConsecutiveTableGenBreakingDAGArgColons",
1092 Style.AlignConsecutiveTableGenBreakingDAGArgColons);
1093 IO.mapOptional(
"AlignConsecutiveTableGenCondOperatorColons",
1094 Style.AlignConsecutiveTableGenCondOperatorColons);
1095 IO.mapOptional(
"AlignConsecutiveTableGenDefinitionColons",
1096 Style.AlignConsecutiveTableGenDefinitionColons);
1097 IO.mapOptional(
"AlignEscapedNewlines", Style.AlignEscapedNewlines);
1098 IO.mapOptional(
"AlignOperands", Style.AlignOperands);
1099 IO.mapOptional(
"AlignTrailingComments", Style.AlignTrailingComments);
1100 IO.mapOptional(
"AllowAllArgumentsOnNextLine",
1101 Style.AllowAllArgumentsOnNextLine);
1102 IO.mapOptional(
"AllowAllParametersOfDeclarationOnNextLine",
1103 Style.AllowAllParametersOfDeclarationOnNextLine);
1104 IO.mapOptional(
"AllowBreakBeforeNoexceptSpecifier",
1105 Style.AllowBreakBeforeNoexceptSpecifier);
1106 IO.mapOptional(
"AllowBreakBeforeQtProperty",
1107 Style.AllowBreakBeforeQtProperty);
1108 IO.mapOptional(
"AllowShortBlocksOnASingleLine",
1109 Style.AllowShortBlocksOnASingleLine);
1110 IO.mapOptional(
"AllowShortCaseExpressionOnASingleLine",
1111 Style.AllowShortCaseExpressionOnASingleLine);
1112 IO.mapOptional(
"AllowShortCaseLabelsOnASingleLine",
1113 Style.AllowShortCaseLabelsOnASingleLine);
1114 IO.mapOptional(
"AllowShortCompoundRequirementOnASingleLine",
1115 Style.AllowShortCompoundRequirementOnASingleLine);
1116 IO.mapOptional(
"AllowShortEnumsOnASingleLine",
1117 Style.AllowShortEnumsOnASingleLine);
1118 IO.mapOptional(
"AllowShortFunctionsOnASingleLine",
1119 Style.AllowShortFunctionsOnASingleLine);
1120 IO.mapOptional(
"AllowShortIfStatementsOnASingleLine",
1121 Style.AllowShortIfStatementsOnASingleLine);
1122 IO.mapOptional(
"AllowShortLambdasOnASingleLine",
1123 Style.AllowShortLambdasOnASingleLine);
1124 IO.mapOptional(
"AllowShortLoopsOnASingleLine",
1125 Style.AllowShortLoopsOnASingleLine);
1126 IO.mapOptional(
"AllowShortNamespacesOnASingleLine",
1127 Style.AllowShortNamespacesOnASingleLine);
1128 IO.mapOptional(
"AlwaysBreakAfterDefinitionReturnType",
1129 Style.AlwaysBreakAfterDefinitionReturnType);
1130 IO.mapOptional(
"AlwaysBreakBeforeMultilineStrings",
1131 Style.AlwaysBreakBeforeMultilineStrings);
1132 IO.mapOptional(
"AttributeMacros", Style.AttributeMacros);
1133 IO.mapOptional(
"BinPackArguments", Style.BinPackArguments);
1134 IO.mapOptional(
"BinPackLongBracedList", Style.BinPackLongBracedList);
1135 IO.mapOptional(
"BinPackParameters", Style.BinPackParameters);
1136 IO.mapOptional(
"BitFieldColonSpacing", Style.BitFieldColonSpacing);
1137 IO.mapOptional(
"BracedInitializerIndentWidth",
1138 Style.BracedInitializerIndentWidth);
1139 IO.mapOptional(
"BraceWrapping", Style.BraceWrapping);
1140 IO.mapOptional(
"BreakAdjacentStringLiterals",
1141 Style.BreakAdjacentStringLiterals);
1142 IO.mapOptional(
"BreakAfterAttributes", Style.BreakAfterAttributes);
1143 IO.mapOptional(
"BreakAfterJavaFieldAnnotations",
1144 Style.BreakAfterJavaFieldAnnotations);
1145 IO.mapOptional(
"BreakAfterOpenBracketBracedList",
1146 Style.BreakAfterOpenBracketBracedList);
1147 IO.mapOptional(
"BreakAfterOpenBracketFunction",
1148 Style.BreakAfterOpenBracketFunction);
1149 IO.mapOptional(
"BreakAfterOpenBracketIf", Style.BreakAfterOpenBracketIf);
1150 IO.mapOptional(
"BreakAfterOpenBracketLoop",
1151 Style.BreakAfterOpenBracketLoop);
1152 IO.mapOptional(
"BreakAfterOpenBracketSwitch",
1153 Style.BreakAfterOpenBracketSwitch);
1154 IO.mapOptional(
"BreakAfterReturnType", Style.BreakAfterReturnType);
1155 IO.mapOptional(
"BreakArrays", Style.BreakArrays);
1156 IO.mapOptional(
"BreakBeforeBinaryOperators",
1157 Style.BreakBeforeBinaryOperators);
1158 IO.mapOptional(
"BreakBeforeCloseBracketBracedList",
1159 Style.BreakBeforeCloseBracketBracedList);
1160 IO.mapOptional(
"BreakBeforeCloseBracketFunction",
1161 Style.BreakBeforeCloseBracketFunction);
1162 IO.mapOptional(
"BreakBeforeCloseBracketIf",
1163 Style.BreakBeforeCloseBracketIf);
1164 IO.mapOptional(
"BreakBeforeCloseBracketLoop",
1165 Style.BreakBeforeCloseBracketLoop);
1166 IO.mapOptional(
"BreakBeforeCloseBracketSwitch",
1167 Style.BreakBeforeCloseBracketSwitch);
1168 IO.mapOptional(
"BreakBeforeConceptDeclarations",
1169 Style.BreakBeforeConceptDeclarations);
1170 IO.mapOptional(
"BreakBeforeBraces", Style.BreakBeforeBraces);
1171 IO.mapOptional(
"BreakBeforeInlineASMColon",
1172 Style.BreakBeforeInlineASMColon);
1173 IO.mapOptional(
"BreakBeforeTemplateCloser",
1174 Style.BreakBeforeTemplateCloser);
1175 IO.mapOptional(
"BreakBeforeTernaryOperators",
1176 Style.BreakBeforeTernaryOperators);
1177 IO.mapOptional(
"BreakBinaryOperations", Style.BreakBinaryOperations);
1178 IO.mapOptional(
"BreakConstructorInitializers",
1179 Style.BreakConstructorInitializers);
1180 IO.mapOptional(
"BreakFunctionDefinitionParameters",
1181 Style.BreakFunctionDefinitionParameters);
1182 IO.mapOptional(
"BreakInheritanceList", Style.BreakInheritanceList);
1183 IO.mapOptional(
"BreakStringLiterals", Style.BreakStringLiterals);
1184 IO.mapOptional(
"BreakTemplateDeclarations",
1185 Style.BreakTemplateDeclarations);
1186 IO.mapOptional(
"ColumnLimit", Style.ColumnLimit);
1187 IO.mapOptional(
"CommentPragmas", Style.CommentPragmas);
1188 IO.mapOptional(
"CompactNamespaces", Style.CompactNamespaces);
1189 IO.mapOptional(
"ConstructorInitializerIndentWidth",
1190 Style.ConstructorInitializerIndentWidth);
1191 IO.mapOptional(
"ContinuationIndentWidth", Style.ContinuationIndentWidth);
1192 IO.mapOptional(
"Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
1193 IO.mapOptional(
"DerivePointerAlignment", Style.DerivePointerAlignment);
1194 IO.mapOptional(
"DisableFormat", Style.DisableFormat);
1195 IO.mapOptional(
"EmptyLineAfterAccessModifier",
1196 Style.EmptyLineAfterAccessModifier);
1197 IO.mapOptional(
"EmptyLineBeforeAccessModifier",
1198 Style.EmptyLineBeforeAccessModifier);
1199 IO.mapOptional(
"EnumTrailingComma", Style.EnumTrailingComma);
1200 IO.mapOptional(
"ExperimentalAutoDetectBinPacking",
1201 Style.ExperimentalAutoDetectBinPacking);
1202 IO.mapOptional(
"FixNamespaceComments", Style.FixNamespaceComments);
1203 IO.mapOptional(
"ForEachMacros", Style.ForEachMacros);
1204 IO.mapOptional(
"IfMacros", Style.IfMacros);
1205 IO.mapOptional(
"IncludeBlocks", Style.IncludeStyle.IncludeBlocks);
1206 IO.mapOptional(
"IncludeCategories", Style.IncludeStyle.IncludeCategories);
1207 IO.mapOptional(
"IncludeIsMainRegex", Style.IncludeStyle.IncludeIsMainRegex);
1208 IO.mapOptional(
"IncludeIsMainSourceRegex",
1209 Style.IncludeStyle.IncludeIsMainSourceRegex);
1210 IO.mapOptional(
"IndentAccessModifiers", Style.IndentAccessModifiers);
1211 IO.mapOptional(
"IndentCaseBlocks", Style.IndentCaseBlocks);
1212 IO.mapOptional(
"IndentCaseLabels", Style.IndentCaseLabels);
1213 IO.mapOptional(
"IndentExportBlock", Style.IndentExportBlock);
1214 IO.mapOptional(
"IndentExternBlock", Style.IndentExternBlock);
1215 IO.mapOptional(
"IndentGotoLabels", Style.IndentGotoLabels);
1216 IO.mapOptional(
"IndentPPDirectives", Style.IndentPPDirectives);
1217 IO.mapOptional(
"IndentRequiresClause", Style.IndentRequiresClause);
1218 IO.mapOptional(
"IndentWidth", Style.IndentWidth);
1219 IO.mapOptional(
"IndentWrappedFunctionNames",
1220 Style.IndentWrappedFunctionNames);
1221 IO.mapOptional(
"InsertBraces", Style.InsertBraces);
1222 IO.mapOptional(
"InsertNewlineAtEOF", Style.InsertNewlineAtEOF);
1223 IO.mapOptional(
"InsertTrailingCommas", Style.InsertTrailingCommas);
1224 IO.mapOptional(
"IntegerLiteralSeparator", Style.IntegerLiteralSeparator);
1225 IO.mapOptional(
"JavaImportGroups", Style.JavaImportGroups);
1226 IO.mapOptional(
"JavaScriptQuotes", Style.JavaScriptQuotes);
1227 IO.mapOptional(
"JavaScriptWrapImports", Style.JavaScriptWrapImports);
1228 IO.mapOptional(
"KeepEmptyLines", Style.KeepEmptyLines);
1229 IO.mapOptional(
"KeepFormFeed", Style.KeepFormFeed);
1230 IO.mapOptional(
"LambdaBodyIndentation", Style.LambdaBodyIndentation);
1231 IO.mapOptional(
"LineEnding", Style.LineEnding);
1232 IO.mapOptional(
"MacroBlockBegin", Style.MacroBlockBegin);
1233 IO.mapOptional(
"MacroBlockEnd", Style.MacroBlockEnd);
1234 IO.mapOptional(
"Macros", Style.Macros);
1235 IO.mapOptional(
"MacrosSkippedByRemoveParentheses",
1236 Style.MacrosSkippedByRemoveParentheses);
1237 IO.mapOptional(
"MainIncludeChar", Style.IncludeStyle.MainIncludeChar);
1238 IO.mapOptional(
"MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
1239 IO.mapOptional(
"NamespaceIndentation", Style.NamespaceIndentation);
1240 IO.mapOptional(
"NamespaceMacros", Style.NamespaceMacros);
1241 IO.mapOptional(
"NumericLiteralCase", Style.NumericLiteralCase);
1242 IO.mapOptional(
"ObjCBinPackProtocolList", Style.ObjCBinPackProtocolList);
1243 IO.mapOptional(
"ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
1244 IO.mapOptional(
"ObjCBreakBeforeNestedBlockParam",
1245 Style.ObjCBreakBeforeNestedBlockParam);
1246 IO.mapOptional(
"ObjCPropertyAttributeOrder",
1247 Style.ObjCPropertyAttributeOrder);
1248 IO.mapOptional(
"ObjCSpaceAfterMethodDeclarationPrefix",
1249 Style.ObjCSpaceAfterMethodDeclarationPrefix);
1250 IO.mapOptional(
"ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
1251 IO.mapOptional(
"ObjCSpaceBeforeProtocolList",
1252 Style.ObjCSpaceBeforeProtocolList);
1253 IO.mapOptional(
"OneLineFormatOffRegex", Style.OneLineFormatOffRegex);
1254 IO.mapOptional(
"PackConstructorInitializers",
1255 Style.PackConstructorInitializers);
1256 IO.mapOptional(
"PenaltyBreakAssignment", Style.PenaltyBreakAssignment);
1257 IO.mapOptional(
"PenaltyBreakBeforeFirstCallParameter",
1258 Style.PenaltyBreakBeforeFirstCallParameter);
1259 IO.mapOptional(
"PenaltyBreakBeforeMemberAccess",
1260 Style.PenaltyBreakBeforeMemberAccess);
1261 IO.mapOptional(
"PenaltyBreakComment", Style.PenaltyBreakComment);
1262 IO.mapOptional(
"PenaltyBreakFirstLessLess",
1263 Style.PenaltyBreakFirstLessLess);
1264 IO.mapOptional(
"PenaltyBreakOpenParenthesis",
1265 Style.PenaltyBreakOpenParenthesis);
1266 IO.mapOptional(
"PenaltyBreakScopeResolution",
1267 Style.PenaltyBreakScopeResolution);
1268 IO.mapOptional(
"PenaltyBreakString", Style.PenaltyBreakString);
1269 IO.mapOptional(
"PenaltyBreakTemplateDeclaration",
1270 Style.PenaltyBreakTemplateDeclaration);
1271 IO.mapOptional(
"PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
1272 IO.mapOptional(
"PenaltyIndentedWhitespace",
1273 Style.PenaltyIndentedWhitespace);
1274 IO.mapOptional(
"PenaltyReturnTypeOnItsOwnLine",
1275 Style.PenaltyReturnTypeOnItsOwnLine);
1276 IO.mapOptional(
"PointerAlignment", Style.PointerAlignment);
1277 IO.mapOptional(
"PPIndentWidth", Style.PPIndentWidth);
1278 IO.mapOptional(
"QualifierAlignment", Style.QualifierAlignment);
1280 if (Style.QualifierAlignment == FormatStyle::QAS_Right)
1281 Style.QualifierOrder = {
"type",
"const",
"volatile"};
1282 else if (Style.QualifierAlignment == FormatStyle::QAS_Left)
1283 Style.QualifierOrder = {
"const",
"volatile",
"type"};
1284 else if (Style.QualifierAlignment == FormatStyle::QAS_Custom)
1285 IO.mapOptional(
"QualifierOrder", Style.QualifierOrder);
1286 IO.mapOptional(
"RawStringFormats", Style.RawStringFormats);
1287 IO.mapOptional(
"ReferenceAlignment", Style.ReferenceAlignment);
1288 IO.mapOptional(
"ReflowComments", Style.ReflowComments);
1289 IO.mapOptional(
"RemoveBracesLLVM", Style.RemoveBracesLLVM);
1290 IO.mapOptional(
"RemoveEmptyLinesInUnwrappedLines",
1291 Style.RemoveEmptyLinesInUnwrappedLines);
1292 IO.mapOptional(
"RemoveParentheses", Style.RemoveParentheses);
1293 IO.mapOptional(
"RemoveSemicolon", Style.RemoveSemicolon);
1294 IO.mapOptional(
"RequiresClausePosition", Style.RequiresClausePosition);
1295 IO.mapOptional(
"RequiresExpressionIndentation",
1296 Style.RequiresExpressionIndentation);
1297 IO.mapOptional(
"SeparateDefinitionBlocks", Style.SeparateDefinitionBlocks);
1298 IO.mapOptional(
"ShortNamespaceLines", Style.ShortNamespaceLines);
1299 IO.mapOptional(
"SkipMacroDefinitionBody", Style.SkipMacroDefinitionBody);
1300 IO.mapOptional(
"SortIncludes", Style.SortIncludes);
1301 IO.mapOptional(
"SortJavaStaticImport", Style.SortJavaStaticImport);
1302 IO.mapOptional(
"SortUsingDeclarations", Style.SortUsingDeclarations);
1303 IO.mapOptional(
"SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
1304 IO.mapOptional(
"SpaceAfterLogicalNot", Style.SpaceAfterLogicalNot);
1305 IO.mapOptional(
"SpaceAfterOperatorKeyword",
1306 Style.SpaceAfterOperatorKeyword);
1307 IO.mapOptional(
"SpaceAfterTemplateKeyword",
1308 Style.SpaceAfterTemplateKeyword);
1309 IO.mapOptional(
"SpaceAroundPointerQualifiers",
1310 Style.SpaceAroundPointerQualifiers);
1311 IO.mapOptional(
"SpaceBeforeAssignmentOperators",
1312 Style.SpaceBeforeAssignmentOperators);
1313 IO.mapOptional(
"SpaceBeforeCaseColon", Style.SpaceBeforeCaseColon);
1314 IO.mapOptional(
"SpaceBeforeCpp11BracedList",
1315 Style.SpaceBeforeCpp11BracedList);
1316 IO.mapOptional(
"SpaceBeforeCtorInitializerColon",
1317 Style.SpaceBeforeCtorInitializerColon);
1318 IO.mapOptional(
"SpaceBeforeInheritanceColon",
1319 Style.SpaceBeforeInheritanceColon);
1320 IO.mapOptional(
"SpaceBeforeJsonColon", Style.SpaceBeforeJsonColon);
1321 IO.mapOptional(
"SpaceBeforeParens", Style.SpaceBeforeParens);
1322 IO.mapOptional(
"SpaceBeforeParensOptions", Style.SpaceBeforeParensOptions);
1323 IO.mapOptional(
"SpaceBeforeRangeBasedForLoopColon",
1324 Style.SpaceBeforeRangeBasedForLoopColon);
1325 IO.mapOptional(
"SpaceBeforeSquareBrackets",
1326 Style.SpaceBeforeSquareBrackets);
1327 IO.mapOptional(
"SpaceInEmptyBraces", Style.SpaceInEmptyBraces);
1328 IO.mapOptional(
"SpacesBeforeTrailingComments",
1329 Style.SpacesBeforeTrailingComments);
1330 IO.mapOptional(
"SpacesInAngles", Style.SpacesInAngles);
1331 IO.mapOptional(
"SpacesInContainerLiterals",
1332 Style.SpacesInContainerLiterals);
1333 IO.mapOptional(
"SpacesInLineCommentPrefix",
1334 Style.SpacesInLineCommentPrefix);
1335 IO.mapOptional(
"SpacesInParens", Style.SpacesInParens);
1336 IO.mapOptional(
"SpacesInParensOptions", Style.SpacesInParensOptions);
1337 IO.mapOptional(
"SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
1338 IO.mapOptional(
"Standard", Style.Standard);
1339 IO.mapOptional(
"StatementAttributeLikeMacros",
1340 Style.StatementAttributeLikeMacros);
1341 IO.mapOptional(
"StatementMacros", Style.StatementMacros);
1342 IO.mapOptional(
"TableGenBreakingDAGArgOperators",
1343 Style.TableGenBreakingDAGArgOperators);
1344 IO.mapOptional(
"TableGenBreakInsideDAGArg",
1345 Style.TableGenBreakInsideDAGArg);
1346 IO.mapOptional(
"TabWidth", Style.TabWidth);
1347 IO.mapOptional(
"TemplateNames", Style.TemplateNames);
1348 IO.mapOptional(
"TypeNames", Style.TypeNames);
1349 IO.mapOptional(
"TypenameMacros", Style.TypenameMacros);
1350 IO.mapOptional(
"UseTab", Style.UseTab);
1351 IO.mapOptional(
"VariableTemplates", Style.VariableTemplates);
1352 IO.mapOptional(
"VerilogBreakBetweenInstancePorts",
1353 Style.VerilogBreakBetweenInstancePorts);
1354 IO.mapOptional(
"WhitespaceSensitiveMacros",
1355 Style.WhitespaceSensitiveMacros);
1356 IO.mapOptional(
"WrapNamespaceBodyWithEmptyLines",
1357 Style.WrapNamespaceBodyWithEmptyLines);
1362 if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
1363 Style.BreakAfterReturnType == FormatStyle::RTBS_None) {
1364 if (Style.AlwaysBreakAfterDefinitionReturnType ==
1365 FormatStyle::DRTBS_All) {
1366 Style.BreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
1367 }
else if (Style.AlwaysBreakAfterDefinitionReturnType ==
1368 FormatStyle::DRTBS_TopLevel) {
1369 Style.BreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
1375 if (BreakBeforeInheritanceComma &&
1376 Style.BreakInheritanceList == FormatStyle::BILS_BeforeColon) {
1377 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
1383 if (BreakConstructorInitializersBeforeComma &&
1384 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon) {
1385 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
1388 if (!IsGoogleOrChromium) {
1389 if (Style.PackConstructorInitializers == FormatStyle::PCIS_BinPack &&
1391 Style.PackConstructorInitializers = OnNextLine
1392 ? FormatStyle::PCIS_NextLine
1393 : FormatStyle::PCIS_CurrentLine;
1395 }
else if (Style.PackConstructorInitializers ==
1396 FormatStyle::PCIS_NextLine) {
1398 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
1399 else if (!OnNextLine)
1400 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
1403 if (Style.LineEnding == FormatStyle::LE_DeriveLF) {
1404 if (!DeriveLineEnding)
1405 Style.LineEnding = UseCRLF ? FormatStyle::LE_CRLF : FormatStyle::LE_LF;
1407 Style.LineEnding = FormatStyle::LE_DeriveCRLF;
1412 if (SpaceInEmptyBlock &&
1413 Style.SpaceInEmptyBraces == FormatStyle::SIEB_Never) {
1414 Style.SpaceInEmptyBraces = FormatStyle::SIEB_Block;
1417 if (Style.SpacesInParens != FormatStyle::SIPO_Custom &&
1418 (SpacesInParentheses || SpaceInEmptyParentheses ||
1419 SpacesInConditionalStatement || SpacesInCStyleCastParentheses)) {
1420 if (SpacesInParentheses) {
1422 Style.SpacesInParensOptions.ExceptDoubleParentheses =
false;
1423 Style.SpacesInParensOptions.InConditionalStatements =
true;
1424 Style.SpacesInParensOptions.InCStyleCasts =
1425 SpacesInCStyleCastParentheses;
1426 Style.SpacesInParensOptions.InEmptyParentheses =
1427 SpaceInEmptyParentheses;
1428 Style.SpacesInParensOptions.Other =
true;
1430 Style.SpacesInParensOptions = {};
1431 Style.SpacesInParensOptions.InConditionalStatements =
1432 SpacesInConditionalStatement;
1433 Style.SpacesInParensOptions.InCStyleCasts =
1434 SpacesInCStyleCastParentheses;
1435 Style.SpacesInParensOptions.InEmptyParentheses =
1436 SpaceInEmptyParentheses;
1438 Style.SpacesInParens = FormatStyle::SIPO_Custom;
1448template <>
struct DocumentListTraits<
std::vector<FormatStyle>> {
1449 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
1452 static FormatStyle &
element(IO &IO, std::vector<FormatStyle> &Seq,
1454 if (Index >= Seq.size()) {
1455 assert(Index == Seq.size());
1456 FormatStyle Template;
1457 if (!Seq.empty() && Seq[0].Language == FormatStyle::LK_None) {
1460 Template = *((
const FormatStyle *)IO.getContext());
1461 Template.Language = FormatStyle::LK_None;
1463 Seq.resize(Index + 1, Template);
1483 return llvm::make_error<llvm::StringError>(Message,
1484 llvm::inconvertibleErrorCode());
1488 return "clang-format.parse_error";
1496 return "Invalid argument";
1498 return "Unsuitable";
1500 return "trailing comma insertion cannot be used with bin packing";
1502 return "Invalid qualifier specified in QualifierOrder";
1504 return "Duplicate qualifier specified in QualifierOrder";
1506 return "Missing type in QualifierOrder";
1508 return "Missing QualifierOrder";
1510 llvm_unreachable(
"unexpected parse error");
1514 if (Expanded.BreakBeforeBraces == FormatStyle::BS_Custom)
1516 Expanded.BraceWrapping = {
false,
1518 FormatStyle::BWACS_Never,
1534 switch (Expanded.BreakBeforeBraces) {
1535 case FormatStyle::BS_Linux:
1536 Expanded.BraceWrapping.AfterClass =
true;
1537 Expanded.BraceWrapping.AfterFunction =
true;
1538 Expanded.BraceWrapping.AfterNamespace =
true;
1540 case FormatStyle::BS_Mozilla:
1541 Expanded.BraceWrapping.AfterClass =
true;
1542 Expanded.BraceWrapping.AfterEnum =
true;
1543 Expanded.BraceWrapping.AfterFunction =
true;
1544 Expanded.BraceWrapping.AfterStruct =
true;
1545 Expanded.BraceWrapping.AfterUnion =
true;
1546 Expanded.BraceWrapping.AfterExternBlock =
true;
1547 Expanded.BraceWrapping.SplitEmptyFunction =
true;
1548 Expanded.BraceWrapping.SplitEmptyRecord =
false;
1550 case FormatStyle::BS_Stroustrup:
1551 Expanded.BraceWrapping.AfterFunction =
true;
1552 Expanded.BraceWrapping.BeforeCatch =
true;
1553 Expanded.BraceWrapping.BeforeElse =
true;
1555 case FormatStyle::BS_Allman:
1556 Expanded.BraceWrapping.AfterCaseLabel =
true;
1557 Expanded.BraceWrapping.AfterClass =
true;
1558 Expanded.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1559 Expanded.BraceWrapping.AfterEnum =
true;
1560 Expanded.BraceWrapping.AfterFunction =
true;
1561 Expanded.BraceWrapping.AfterNamespace =
true;
1562 Expanded.BraceWrapping.AfterObjCDeclaration =
true;
1563 Expanded.BraceWrapping.AfterStruct =
true;
1564 Expanded.BraceWrapping.AfterUnion =
true;
1565 Expanded.BraceWrapping.AfterExternBlock =
true;
1566 Expanded.BraceWrapping.BeforeCatch =
true;
1567 Expanded.BraceWrapping.BeforeElse =
true;
1568 Expanded.BraceWrapping.BeforeLambdaBody =
true;
1570 case FormatStyle::BS_Whitesmiths:
1571 Expanded.BraceWrapping.AfterCaseLabel =
true;
1572 Expanded.BraceWrapping.AfterClass =
true;
1573 Expanded.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1574 Expanded.BraceWrapping.AfterEnum =
true;
1575 Expanded.BraceWrapping.AfterFunction =
true;
1576 Expanded.BraceWrapping.AfterNamespace =
true;
1577 Expanded.BraceWrapping.AfterObjCDeclaration =
true;
1578 Expanded.BraceWrapping.AfterStruct =
true;
1579 Expanded.BraceWrapping.AfterExternBlock =
true;
1580 Expanded.BraceWrapping.BeforeCatch =
true;
1581 Expanded.BraceWrapping.BeforeElse =
true;
1582 Expanded.BraceWrapping.BeforeLambdaBody =
true;
1584 case FormatStyle::BS_GNU:
1585 Expanded.BraceWrapping = {
1588 FormatStyle::BWACS_Always,
1605 case FormatStyle::BS_WebKit:
1606 Expanded.BraceWrapping.AfterFunction =
true;
1614 if (Expanded.SpaceBeforeParens == FormatStyle::SBPO_Custom)
1617 Expanded.SpaceBeforeParensOptions = {};
1618 Expanded.SpaceBeforeParensOptions.AfterPlacementOperator =
true;
1620 switch (Expanded.SpaceBeforeParens) {
1621 case FormatStyle::SBPO_ControlStatements:
1622 Expanded.SpaceBeforeParensOptions.AfterControlStatements =
true;
1623 Expanded.SpaceBeforeParensOptions.AfterForeachMacros =
true;
1624 Expanded.SpaceBeforeParensOptions.AfterIfMacros =
true;
1626 case FormatStyle::SBPO_ControlStatementsExceptControlMacros:
1627 Expanded.SpaceBeforeParensOptions.AfterControlStatements =
true;
1629 case FormatStyle::SBPO_NonEmptyParentheses:
1630 Expanded.SpaceBeforeParensOptions.BeforeNonEmptyParentheses =
true;
1638 if (Expanded.SpacesInParens == FormatStyle::SIPO_Custom)
1640 assert(Expanded.SpacesInParens == FormatStyle::SIPO_Never);
1642 Expanded.SpacesInParensOptions = {};
1646 FormatStyle LLVMStyle;
1647 LLVMStyle.AccessModifierOffset = -2;
1648 LLVMStyle.AlignAfterOpenBracket =
true;
1649 LLVMStyle.AlignArrayOfStructures = FormatStyle::AIAS_None;
1650 LLVMStyle.AlignConsecutiveAssignments = {};
1651 LLVMStyle.AlignConsecutiveAssignments.PadOperators =
true;
1652 LLVMStyle.AlignConsecutiveBitFields = {};
1653 LLVMStyle.AlignConsecutiveDeclarations = {};
1654 LLVMStyle.AlignConsecutiveDeclarations.AlignFunctionDeclarations =
true;
1655 LLVMStyle.AlignConsecutiveMacros = {};
1656 LLVMStyle.AlignConsecutiveShortCaseStatements = {};
1657 LLVMStyle.AlignConsecutiveTableGenBreakingDAGArgColons = {};
1658 LLVMStyle.AlignConsecutiveTableGenCondOperatorColons = {};
1659 LLVMStyle.AlignConsecutiveTableGenDefinitionColons = {};
1660 LLVMStyle.AlignEscapedNewlines = FormatStyle::ENAS_Right;
1661 LLVMStyle.AlignOperands = FormatStyle::OAS_Align;
1662 LLVMStyle.AlignTrailingComments = {};
1663 LLVMStyle.AlignTrailingComments.Kind = FormatStyle::TCAS_Always;
1664 LLVMStyle.AlignTrailingComments.OverEmptyLines = 0;
1665 LLVMStyle.AlignTrailingComments.AlignPPAndNotPP =
true;
1666 LLVMStyle.AllowAllArgumentsOnNextLine =
true;
1667 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine =
true;
1668 LLVMStyle.AllowBreakBeforeNoexceptSpecifier = FormatStyle::BBNSS_Never;
1669 LLVMStyle.AllowBreakBeforeQtProperty =
false;
1670 LLVMStyle.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
1671 LLVMStyle.AllowShortCaseExpressionOnASingleLine =
true;
1672 LLVMStyle.AllowShortCaseLabelsOnASingleLine =
false;
1673 LLVMStyle.AllowShortCompoundRequirementOnASingleLine =
true;
1674 LLVMStyle.AllowShortEnumsOnASingleLine =
true;
1675 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
1676 LLVMStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
1677 LLVMStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
1678 LLVMStyle.AllowShortLoopsOnASingleLine =
false;
1679 LLVMStyle.AllowShortNamespacesOnASingleLine =
false;
1680 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
1681 LLVMStyle.AlwaysBreakBeforeMultilineStrings =
false;
1682 LLVMStyle.AttributeMacros.push_back(
"__capability");
1683 LLVMStyle.BinPackArguments =
true;
1684 LLVMStyle.BinPackLongBracedList =
true;
1685 LLVMStyle.BinPackParameters = FormatStyle::BPPS_BinPack;
1686 LLVMStyle.BitFieldColonSpacing = FormatStyle::BFCS_Both;
1687 LLVMStyle.BracedInitializerIndentWidth = -1;
1688 LLVMStyle.BraceWrapping = {
false,
1690 FormatStyle::BWACS_Never,
1706 LLVMStyle.BreakAdjacentStringLiterals =
true;
1707 LLVMStyle.BreakAfterAttributes = FormatStyle::ABS_Leave;
1708 LLVMStyle.BreakAfterJavaFieldAnnotations =
false;
1709 LLVMStyle.BreakAfterOpenBracketBracedList =
false;
1710 LLVMStyle.BreakAfterOpenBracketFunction =
false;
1711 LLVMStyle.BreakAfterOpenBracketIf =
false;
1712 LLVMStyle.BreakAfterOpenBracketLoop =
false;
1713 LLVMStyle.BreakAfterOpenBracketSwitch =
false;
1714 LLVMStyle.BreakAfterReturnType = FormatStyle::RTBS_None;
1715 LLVMStyle.BreakArrays =
true;
1716 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
1717 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
1718 LLVMStyle.BreakBeforeCloseBracketBracedList =
false;
1719 LLVMStyle.BreakBeforeCloseBracketFunction =
false;
1720 LLVMStyle.BreakBeforeCloseBracketIf =
false;
1721 LLVMStyle.BreakBeforeCloseBracketLoop =
false;
1722 LLVMStyle.BreakBeforeCloseBracketSwitch =
false;
1723 LLVMStyle.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Always;
1724 LLVMStyle.BreakBeforeInlineASMColon = FormatStyle::BBIAS_OnlyMultiline;
1725 LLVMStyle.BreakBeforeTemplateCloser =
false;
1726 LLVMStyle.BreakBeforeTernaryOperators =
true;
1727 LLVMStyle.BreakBinaryOperations = FormatStyle::BBO_Never;
1728 LLVMStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
1729 LLVMStyle.BreakFunctionDefinitionParameters =
false;
1730 LLVMStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
1731 LLVMStyle.BreakStringLiterals =
true;
1732 LLVMStyle.BreakTemplateDeclarations = FormatStyle::BTDS_MultiLine;
1733 LLVMStyle.ColumnLimit = 80;
1734 LLVMStyle.CommentPragmas =
"^ IWYU pragma:";
1735 LLVMStyle.CompactNamespaces =
false;
1736 LLVMStyle.ConstructorInitializerIndentWidth = 4;
1737 LLVMStyle.ContinuationIndentWidth = 4;
1738 LLVMStyle.Cpp11BracedListStyle = FormatStyle::BLS_AlignFirstComment;
1739 LLVMStyle.DerivePointerAlignment =
false;
1740 LLVMStyle.DisableFormat =
false;
1741 LLVMStyle.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
1742 LLVMStyle.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
1743 LLVMStyle.EnumTrailingComma = FormatStyle::ETC_Leave;
1744 LLVMStyle.ExperimentalAutoDetectBinPacking =
false;
1745 LLVMStyle.FixNamespaceComments =
true;
1746 LLVMStyle.ForEachMacros.push_back(
"foreach");
1747 LLVMStyle.ForEachMacros.push_back(
"Q_FOREACH");
1748 LLVMStyle.ForEachMacros.push_back(
"BOOST_FOREACH");
1749 LLVMStyle.IfMacros.push_back(
"KJ_IF_MAYBE");
1751 LLVMStyle.IncludeStyle.IncludeCategories = {
1752 {
"^\"(llvm|llvm-c|clang|clang-c)/", 2, 0,
false},
1753 {
"^(<|\"(gtest|gmock|isl|json)/)", 3, 0,
false},
1754 {
".*", 1, 0,
false}};
1755 LLVMStyle.IncludeStyle.IncludeIsMainRegex =
"(Test)?$";
1756 LLVMStyle.IncludeStyle.MainIncludeChar = tooling::IncludeStyle::MICD_Quote;
1757 LLVMStyle.IndentAccessModifiers =
false;
1758 LLVMStyle.IndentCaseBlocks =
false;
1759 LLVMStyle.IndentCaseLabels =
false;
1760 LLVMStyle.IndentExportBlock =
true;
1761 LLVMStyle.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
1762 LLVMStyle.IndentGotoLabels =
true;
1763 LLVMStyle.IndentPPDirectives = FormatStyle::PPDIS_None;
1764 LLVMStyle.IndentRequiresClause =
true;
1765 LLVMStyle.IndentWidth = 2;
1766 LLVMStyle.IndentWrappedFunctionNames =
false;
1767 LLVMStyle.InheritsParentConfig =
false;
1768 LLVMStyle.InsertBraces =
false;
1769 LLVMStyle.InsertNewlineAtEOF =
false;
1770 LLVMStyle.InsertTrailingCommas = FormatStyle::TCS_None;
1771 LLVMStyle.IntegerLiteralSeparator = {};
1772 LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
1773 LLVMStyle.JavaScriptWrapImports =
true;
1774 LLVMStyle.KeepEmptyLines = {
1779 LLVMStyle.KeepFormFeed =
false;
1780 LLVMStyle.LambdaBodyIndentation = FormatStyle::LBI_Signature;
1782 LLVMStyle.LineEnding = FormatStyle::LE_DeriveLF;
1783 LLVMStyle.MaxEmptyLinesToKeep = 1;
1784 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
1785 LLVMStyle.NumericLiteralCase = {FormatStyle::NLCS_Leave,
1786 FormatStyle::NLCS_Leave,
1787 FormatStyle::NLCS_Leave,
1788 FormatStyle::NLCS_Leave};
1789 LLVMStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Auto;
1790 LLVMStyle.ObjCBlockIndentWidth = 2;
1791 LLVMStyle.ObjCBreakBeforeNestedBlockParam =
true;
1792 LLVMStyle.ObjCSpaceAfterMethodDeclarationPrefix =
true;
1793 LLVMStyle.ObjCSpaceAfterProperty =
false;
1794 LLVMStyle.ObjCSpaceBeforeProtocolList =
true;
1795 LLVMStyle.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
1796 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
1797 LLVMStyle.PPIndentWidth = -1;
1798 LLVMStyle.QualifierAlignment = FormatStyle::QAS_Leave;
1799 LLVMStyle.ReferenceAlignment = FormatStyle::RAS_Pointer;
1800 LLVMStyle.ReflowComments = FormatStyle::RCS_Always;
1801 LLVMStyle.RemoveBracesLLVM =
false;
1802 LLVMStyle.RemoveEmptyLinesInUnwrappedLines =
false;
1803 LLVMStyle.RemoveParentheses = FormatStyle::RPS_Leave;
1804 LLVMStyle.RemoveSemicolon =
false;
1805 LLVMStyle.RequiresClausePosition = FormatStyle::RCPS_OwnLine;
1806 LLVMStyle.RequiresExpressionIndentation = FormatStyle::REI_OuterScope;
1807 LLVMStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Leave;
1808 LLVMStyle.ShortNamespaceLines = 1;
1809 LLVMStyle.SkipMacroDefinitionBody =
false;
1810 LLVMStyle.SortIncludes = {
true,
false,
1812 LLVMStyle.SortJavaStaticImport = FormatStyle::SJSIO_Before;
1813 LLVMStyle.SortUsingDeclarations = FormatStyle::SUD_LexicographicNumeric;
1814 LLVMStyle.SpaceAfterCStyleCast =
false;
1815 LLVMStyle.SpaceAfterLogicalNot =
false;
1816 LLVMStyle.SpaceAfterOperatorKeyword =
false;
1817 LLVMStyle.SpaceAfterTemplateKeyword =
true;
1818 LLVMStyle.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
1819 LLVMStyle.SpaceBeforeAssignmentOperators =
true;
1820 LLVMStyle.SpaceBeforeCaseColon =
false;
1821 LLVMStyle.SpaceBeforeCpp11BracedList =
false;
1822 LLVMStyle.SpaceBeforeCtorInitializerColon =
true;
1823 LLVMStyle.SpaceBeforeInheritanceColon =
true;
1824 LLVMStyle.SpaceBeforeJsonColon =
false;
1825 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
1826 LLVMStyle.SpaceBeforeParensOptions = {};
1827 LLVMStyle.SpaceBeforeParensOptions.AfterControlStatements =
true;
1828 LLVMStyle.SpaceBeforeParensOptions.AfterForeachMacros =
true;
1829 LLVMStyle.SpaceBeforeParensOptions.AfterIfMacros =
true;
1830 LLVMStyle.SpaceBeforeRangeBasedForLoopColon =
true;
1831 LLVMStyle.SpaceBeforeSquareBrackets =
false;
1832 LLVMStyle.SpaceInEmptyBraces = FormatStyle::SIEB_Never;
1833 LLVMStyle.SpacesBeforeTrailingComments = 1;
1834 LLVMStyle.SpacesInAngles = FormatStyle::SIAS_Never;
1835 LLVMStyle.SpacesInContainerLiterals =
true;
1836 LLVMStyle.SpacesInLineCommentPrefix = {
1837 1, std::numeric_limits<unsigned>::max()};
1838 LLVMStyle.SpacesInParens = FormatStyle::SIPO_Never;
1839 LLVMStyle.SpacesInSquareBrackets =
false;
1840 LLVMStyle.Standard = FormatStyle::LS_Latest;
1841 LLVMStyle.StatementAttributeLikeMacros.push_back(
"Q_EMIT");
1842 LLVMStyle.StatementMacros.push_back(
"Q_UNUSED");
1843 LLVMStyle.StatementMacros.push_back(
"QT_REQUIRE_VERSION");
1844 LLVMStyle.TableGenBreakingDAGArgOperators = {};
1845 LLVMStyle.TableGenBreakInsideDAGArg = FormatStyle::DAS_DontBreak;
1846 LLVMStyle.TabWidth = 8;
1847 LLVMStyle.UseTab = FormatStyle::UT_Never;
1848 LLVMStyle.VerilogBreakBetweenInstancePorts =
true;
1849 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"BOOST_PP_STRINGIZE");
1850 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"CF_SWIFT_NAME");
1851 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"NS_SWIFT_NAME");
1852 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"PP_STRINGIZE");
1853 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"STRINGIZE");
1854 LLVMStyle.WrapNamespaceBodyWithEmptyLines = FormatStyle::WNBWELS_Leave;
1857 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
1858 LLVMStyle.PenaltyBreakBeforeMemberAccess = 150;
1859 LLVMStyle.PenaltyBreakComment = 300;
1860 LLVMStyle.PenaltyBreakFirstLessLess = 120;
1861 LLVMStyle.PenaltyBreakOpenParenthesis = 0;
1862 LLVMStyle.PenaltyBreakScopeResolution = 500;
1863 LLVMStyle.PenaltyBreakString = 1000;
1865 LLVMStyle.PenaltyExcessCharacter = 1'000'000;
1866 LLVMStyle.PenaltyIndentedWhitespace = 0;
1867 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
1871 case FormatStyle::LK_TableGen:
1872 LLVMStyle.SpacesInContainerLiterals =
false;
1874 case FormatStyle::LK_Json:
1875 LLVMStyle.ColumnLimit = 0;
1877 case FormatStyle::LK_Verilog:
1878 LLVMStyle.IndentCaseLabels =
true;
1879 LLVMStyle.SpacesInContainerLiterals =
false;
1889 if (
Language == FormatStyle::LK_TextProto) {
1891 GoogleStyle.Language = FormatStyle::LK_TextProto;
1898 GoogleStyle.AccessModifierOffset = -1;
1899 GoogleStyle.AlignEscapedNewlines = FormatStyle::ENAS_Left;
1900 GoogleStyle.AllowShortIfStatementsOnASingleLine =
1901 FormatStyle::SIS_WithoutElse;
1902 GoogleStyle.AllowShortLoopsOnASingleLine =
true;
1903 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
true;
1905 GoogleStyle.AttributeMacros.push_back(
"absl_nonnull");
1906 GoogleStyle.AttributeMacros.push_back(
"absl_nullable");
1907 GoogleStyle.AttributeMacros.push_back(
"absl_nullability_unknown");
1908 GoogleStyle.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
1910 GoogleStyle.IncludeStyle.IncludeCategories = {{
"^<ext/.*\\.h>", 2, 0,
false},
1911 {
"^<.*\\.h>", 1, 0,
false},
1912 {
"^<.*", 2, 0,
false},
1913 {
".*", 3, 0,
false}};
1914 GoogleStyle.IncludeStyle.IncludeIsMainRegex =
"([-_](test|unittest))?$";
1915 GoogleStyle.IndentCaseLabels =
true;
1916 GoogleStyle.KeepEmptyLines.AtStartOfBlock =
false;
1917 GoogleStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
1918 GoogleStyle.ObjCSpaceAfterProperty =
false;
1919 GoogleStyle.ObjCSpaceBeforeProtocolList =
true;
1920 GoogleStyle.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
1921 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
1922 GoogleStyle.RawStringFormats = {
1924 FormatStyle::LK_Cpp,
1941 FormatStyle::LK_TextProto,
1953 "PARSE_PARTIAL_TEXT_PROTO",
1957 "ParseTextProtoOrDie",
1959 "ParsePartialTestProto",
1966 GoogleStyle.SpacesBeforeTrailingComments = 2;
1967 GoogleStyle.Standard = FormatStyle::LS_Auto;
1969 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
1970 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
1972 if (
Language == FormatStyle::LK_Java) {
1973 GoogleStyle.AlignAfterOpenBracket =
false;
1974 GoogleStyle.AlignOperands = FormatStyle::OAS_DontAlign;
1975 GoogleStyle.AlignTrailingComments = {};
1976 GoogleStyle.AlignTrailingComments.Kind = FormatStyle::TCAS_Never;
1977 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
1978 GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
1979 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
1980 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
1981 GoogleStyle.ColumnLimit = 100;
1982 GoogleStyle.SpaceAfterCStyleCast =
true;
1983 GoogleStyle.SpacesBeforeTrailingComments = 1;
1984 }
else if (
Language == FormatStyle::LK_JavaScript) {
1985 GoogleStyle.BreakAfterOpenBracketBracedList =
true;
1986 GoogleStyle.BreakAfterOpenBracketFunction =
true;
1987 GoogleStyle.BreakAfterOpenBracketIf =
true;
1988 GoogleStyle.AlignOperands = FormatStyle::OAS_DontAlign;
1989 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
1991 GoogleStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
1992 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
1993 GoogleStyle.BreakBeforeTernaryOperators =
false;
1996 GoogleStyle.CommentPragmas =
"(taze:|^/[ \t]*<|tslint:|@see)";
2000 GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single;
2001 GoogleStyle.JavaScriptWrapImports =
false;
2002 GoogleStyle.MaxEmptyLinesToKeep = 3;
2003 GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
2004 GoogleStyle.SpacesInContainerLiterals =
false;
2005 }
else if (
Language == FormatStyle::LK_Proto) {
2006 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
2007 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
2013 GoogleStyle.BreakStringLiterals =
false;
2014 GoogleStyle.Cpp11BracedListStyle = FormatStyle::BLS_Block;
2015 GoogleStyle.SpacesInContainerLiterals =
false;
2016 }
else if (
Language == FormatStyle::LK_ObjC) {
2017 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
2018 GoogleStyle.ColumnLimit = 100;
2019 GoogleStyle.DerivePointerAlignment =
true;
2023 GoogleStyle.IncludeStyle.IncludeBlocks =
2025 }
else if (
Language == FormatStyle::LK_CSharp) {
2026 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
2027 GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
2028 GoogleStyle.BreakStringLiterals =
false;
2029 GoogleStyle.ColumnLimit = 100;
2030 GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
2056 ChromiumStyle.IncludeStyle.IncludeBlocks =
2059 if (
Language == FormatStyle::LK_Java) {
2060 ChromiumStyle.AllowShortIfStatementsOnASingleLine =
2061 FormatStyle::SIS_WithoutElse;
2062 ChromiumStyle.BreakAfterJavaFieldAnnotations =
true;
2063 ChromiumStyle.ContinuationIndentWidth = 8;
2064 ChromiumStyle.IndentWidth = 4;
2067 ChromiumStyle.JavaImportGroups = {
2074 "com.google.android.apps.chrome",
2079 }
else if (
Language == FormatStyle::LK_JavaScript) {
2080 ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
2081 ChromiumStyle.AllowShortLoopsOnASingleLine =
false;
2083 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine =
false;
2084 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
2085 ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
2086 ChromiumStyle.AllowShortLoopsOnASingleLine =
false;
2087 ChromiumStyle.BinPackParameters = FormatStyle::BPPS_OnePerLine;
2088 ChromiumStyle.DerivePointerAlignment =
false;
2089 if (
Language == FormatStyle::LK_ObjC)
2090 ChromiumStyle.ColumnLimit = 80;
2092 return ChromiumStyle;
2097 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine =
false;
2098 MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
2099 MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
2100 FormatStyle::DRTBS_TopLevel;
2101 MozillaStyle.BinPackArguments =
false;
2102 MozillaStyle.BinPackParameters = FormatStyle::BPPS_OnePerLine;
2103 MozillaStyle.BreakAfterReturnType = FormatStyle::RTBS_TopLevel;
2104 MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
2105 MozillaStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
2106 MozillaStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
2107 MozillaStyle.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
2108 MozillaStyle.ConstructorInitializerIndentWidth = 2;
2109 MozillaStyle.ContinuationIndentWidth = 2;
2110 MozillaStyle.Cpp11BracedListStyle = FormatStyle::BLS_Block;
2111 MozillaStyle.FixNamespaceComments =
false;
2112 MozillaStyle.IndentCaseLabels =
true;
2113 MozillaStyle.ObjCSpaceAfterProperty =
true;
2114 MozillaStyle.ObjCSpaceBeforeProtocolList =
false;
2115 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
2116 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
2117 MozillaStyle.SpaceAfterTemplateKeyword =
false;
2118 return MozillaStyle;
2123 Style.AccessModifierOffset = -4;
2124 Style.AlignAfterOpenBracket =
false;
2125 Style.AlignOperands = FormatStyle::OAS_DontAlign;
2126 Style.AlignTrailingComments = {};
2127 Style.AlignTrailingComments.Kind = FormatStyle::TCAS_Never;
2128 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
2129 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
2130 Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
2131 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
2132 Style.ColumnLimit = 0;
2133 Style.Cpp11BracedListStyle = FormatStyle::BLS_Block;
2134 Style.FixNamespaceComments =
false;
2135 Style.IndentWidth = 4;
2136 Style.NamespaceIndentation = FormatStyle::NI_Inner;
2137 Style.ObjCBlockIndentWidth = 4;
2138 Style.ObjCSpaceAfterProperty =
true;
2139 Style.PointerAlignment = FormatStyle::PAS_Left;
2140 Style.SpaceBeforeCpp11BracedList =
true;
2141 Style.SpaceInEmptyBraces = FormatStyle::SIEB_Always;
2147 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
2148 Style.BreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
2149 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
2150 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
2151 Style.BreakBeforeTernaryOperators =
true;
2152 Style.ColumnLimit = 79;
2153 Style.Cpp11BracedListStyle = FormatStyle::BLS_Block;
2154 Style.FixNamespaceComments =
false;
2155 Style.KeepFormFeed =
true;
2156 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
2162 Style.ColumnLimit = 120;
2164 Style.IndentWidth = 4;
2165 Style.UseTab = FormatStyle::UT_Never;
2166 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2167 Style.BraceWrapping.AfterClass =
true;
2168 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2169 Style.BraceWrapping.AfterEnum =
true;
2170 Style.BraceWrapping.AfterFunction =
true;
2171 Style.BraceWrapping.AfterNamespace =
true;
2172 Style.BraceWrapping.AfterObjCDeclaration =
true;
2173 Style.BraceWrapping.AfterStruct =
true;
2174 Style.BraceWrapping.AfterExternBlock =
true;
2175 Style.BraceWrapping.BeforeCatch =
true;
2176 Style.BraceWrapping.BeforeElse =
true;
2177 Style.BraceWrapping.BeforeWhile =
false;
2178 Style.PenaltyReturnTypeOnItsOwnLine = 1000;
2179 Style.AllowShortEnumsOnASingleLine =
false;
2180 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
2181 Style.AllowShortCaseLabelsOnASingleLine =
false;
2182 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
2183 Style.AllowShortLoopsOnASingleLine =
false;
2184 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
2185 Style.BreakAfterReturnType = FormatStyle::RTBS_None;
2191 Style.InsertBraces =
true;
2192 Style.InsertNewlineAtEOF =
true;
2193 Style.IntegerLiteralSeparator.Decimal = 3;
2194 Style.IntegerLiteralSeparator.DecimalMinDigitsInsert = 5;
2195 Style.LineEnding = FormatStyle::LE_LF;
2196 Style.RemoveBracesLLVM =
true;
2197 Style.RemoveEmptyLinesInUnwrappedLines =
true;
2198 Style.RemoveParentheses = FormatStyle::RPS_ReturnStatement;
2199 Style.RemoveSemicolon =
true;
2205 NoStyle.DisableFormat =
true;
2206 NoStyle.SortIncludes = {};
2207 NoStyle.SortUsingDeclarations = FormatStyle::SUD_Never;
2212 FormatStyle *Style) {
2213 if (Name.equals_insensitive(
"llvm"))
2215 else if (Name.equals_insensitive(
"chromium"))
2217 else if (Name.equals_insensitive(
"mozilla"))
2219 else if (Name.equals_insensitive(
"google"))
2221 else if (Name.equals_insensitive(
"webkit"))
2223 else if (Name.equals_insensitive(
"gnu"))
2225 else if (Name.equals_insensitive(
"microsoft"))
2227 else if (Name.equals_insensitive(
"clang-format"))
2229 else if (Name.equals_insensitive(
"none"))
2231 else if (Name.equals_insensitive(
"inheritparentconfig"))
2232 Style->InheritsParentConfig =
true;
2242 if (Style->QualifierOrder.empty())
2246 for (
const auto &Qualifier : Style->QualifierOrder) {
2247 if (Qualifier ==
"type")
2251 if (token == tok::identifier)
2256 std::set<std::string> UniqueQualifiers(Style->QualifierOrder.begin(),
2257 Style->QualifierOrder.end());
2258 if (Style->QualifierOrder.size() != UniqueQualifiers.size()) {
2259 LLVM_DEBUG(llvm::dbgs()
2260 <<
"Duplicate Qualifiers " << Style->QualifierOrder.size()
2261 <<
" vs " << UniqueQualifiers.size() <<
"\n");
2266 if (!llvm::is_contained(Style->QualifierOrder,
"type"))
2273 FormatStyle *Style,
bool AllowUnknownOptions,
2274 llvm::SourceMgr::DiagHandlerTy DiagHandler,
2275 void *DiagHandlerCtxt,
bool IsDotHFile) {
2277 FormatStyle::LanguageKind
Language = Style->Language;
2278 assert(
Language != FormatStyle::LK_None);
2279 if (Config.getBuffer().trim().empty())
2281 Style->StyleSet.Clear();
2282 std::vector<FormatStyle> Styles;
2283 llvm::yaml::Input Input(Config,
nullptr, DiagHandler,
2289 Input.setContext(Style);
2290 Input.setAllowUnknownKeys(AllowUnknownOptions);
2293 return Input.error();
2297 const auto StyleCount = Styles.size();
2300 for (
unsigned I = 1; I < StyleCount; ++I) {
2301 const auto Lang = Styles[I].Language;
2302 if (Lang == FormatStyle::LK_None)
2305 for (
unsigned J = 0; J < I; ++J) {
2307 LLVM_DEBUG(llvm::dbgs()
2308 <<
"Duplicate languages in the config file on positions "
2309 << J <<
" and " << I <<
'\n');
2315 int LanguagePos = -1;
2321 for (
unsigned I = 0; I < StyleCount; ++I) {
2322 const auto Lang = Styles[I].Language;
2327 if (Lang == FormatStyle::LK_Cpp)
2329 else if (Lang == FormatStyle::LK_C)
2336 if (LanguagePos < 0) {
2337 if (Styles[0].
Language == FormatStyle::LK_None)
2339 else if (IsDotHFile &&
Language == FormatStyle::LK_Cpp)
2341 else if (!IsDotHFile &&
Language == FormatStyle::LK_C)
2342 LanguagePos = CppPos;
2343 if (LanguagePos < 0)
2347 for (
const auto &S : llvm::reverse(llvm::drop_begin(Styles)))
2348 Style->StyleSet.Add(S);
2350 *Style = Styles[LanguagePos];
2352 if (LanguagePos == 0) {
2353 if (Style->Language == FormatStyle::LK_None)
2355 Style->StyleSet.Add(*Style);
2358 if (Style->InsertTrailingCommas != FormatStyle::TCS_None &&
2359 Style->BinPackArguments) {
2363 if (Style->QualifierAlignment != FormatStyle::QAS_Leave)
2370 llvm::raw_string_ostream Stream(
Text);
2371 llvm::yaml::Output Output(Stream);
2374 FormatStyle NonConstStyle = Style;
2378 Output << NonConstStyle;
2380 return Stream.str();
2383std::optional<FormatStyle>
2384FormatStyle::FormatStyleSet::Get(FormatStyle::LanguageKind
Language)
const {
2386 return std::nullopt;
2388 if (It == Styles->end())
2389 return std::nullopt;
2390 FormatStyle Style = It->second;
2391 Style.StyleSet = *
this;
2395void FormatStyle::FormatStyleSet::Add(FormatStyle Style) {
2396 assert(Style.Language !=
LK_None &&
2397 "Cannot add a style for LK_None to a StyleSet");
2399 !Style.StyleSet.Styles &&
2400 "Cannot add a style associated with an existing StyleSet to a StyleSet");
2402 Styles = std::make_shared<MapType>();
2403 (*Styles)[Style.Language] = std::move(Style);
2406void FormatStyle::FormatStyleSet::Clear() { Styles.reset(); }
2408std::optional<FormatStyle>
2409FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind
Language)
const {
2416 const SourceManager &SourceMgr, tooling::Replacements &
Result,
2417 StringRef
Text =
"") {
2418 const auto &
Tok = Token.Tok;
2419 SourceLocation Start;
2421 Start =
Tok.getLocation();
2424 Start = Token.WhitespaceRange.getBegin();
2427 cantFail(
Result.add(tooling::Replacement(SourceMgr, Range,
Text)));
2432 ParensRemover(
const Environment &Env,
const FormatStyle &Style)
2433 : TokenAnalyzer(Env, Style) {}
2435 std::pair<tooling::Replacements, unsigned>
2436 analyze(TokenAnnotator &Annotator,
2437 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2438 FormatTokenLexer &Tokens)
override {
2439 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2440 tooling::Replacements
Result;
2441 removeParens(AnnotatedLines,
Result);
2446 void removeParens(SmallVectorImpl<AnnotatedLine *> &Lines,
2447 tooling::Replacements &
Result) {
2448 const auto &SourceMgr = Env.getSourceManager();
2449 for (
auto *
Line : Lines) {
2450 if (!
Line->Children.empty())
2452 if (!
Line->Affected)
2454 for (
const auto *Token =
Line->First; Token && !Token->Finalized;
2455 Token = Token->Next) {
2456 if (Token->Optional && Token->isOneOf(tok::l_paren, tok::r_paren))
2465 BracesInserter(
const Environment &Env,
const FormatStyle &Style)
2466 : TokenAnalyzer(Env, Style) {}
2468 std::pair<tooling::Replacements, unsigned>
2469 analyze(TokenAnnotator &Annotator,
2470 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2471 FormatTokenLexer &Tokens)
override {
2472 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2473 tooling::Replacements
Result;
2474 insertBraces(AnnotatedLines,
Result);
2479 void insertBraces(SmallVectorImpl<AnnotatedLine *> &Lines,
2480 tooling::Replacements &
Result) {
2481 const auto &SourceMgr = Env.getSourceManager();
2482 int OpeningBraceSurplus = 0;
2483 for (AnnotatedLine *
Line : Lines) {
2484 if (!
Line->Children.empty())
2486 if (!
Line->Affected && OpeningBraceSurplus == 0)
2489 Token = Token->Next) {
2496 if (!
Line->Affected)
2498 Brace = Token->is(tok::comment) ?
"\n{" :
"{";
2499 ++OpeningBraceSurplus;
2501 if (OpeningBraceSurplus == 0)
2508 Token->BraceCount = 0;
2509 const auto Start = Token->Tok.getEndLoc();
2510 cantFail(
Result.add(tooling::Replacement(SourceMgr, Start, 0,
Brace)));
2513 assert(OpeningBraceSurplus == 0);
2519 BracesRemover(
const Environment &Env,
const FormatStyle &Style)
2520 : TokenAnalyzer(Env, Style) {}
2522 std::pair<tooling::Replacements, unsigned>
2523 analyze(TokenAnnotator &Annotator,
2524 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2525 FormatTokenLexer &Tokens)
override {
2526 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2527 tooling::Replacements
Result;
2528 removeBraces(AnnotatedLines,
Result);
2533 void removeBraces(SmallVectorImpl<AnnotatedLine *> &Lines,
2534 tooling::Replacements &
Result) {
2535 const auto &SourceMgr = Env.getSourceManager();
2536 const auto *End = Lines.end();
2537 for (
const auto *I = Lines.begin(); I != End; ++I) {
2538 const auto &
Line = *I;
2539 if (!
Line->Children.empty())
2541 if (!
Line->Affected)
2543 const auto *NextLine = I + 1 == End ?
nullptr : I[1];
2544 for (
const auto *Token =
Line->First; Token && !Token->Finalized;
2545 Token = Token->Next) {
2546 if (!Token->Optional || Token->isNoneOf(tok::l_brace, tok::r_brace))
2548 auto *
Next = Token->Next;
2549 assert(
Next || Token ==
Line->Last);
2550 if (!
Next && NextLine)
2551 Next = NextLine->First;
2560 SemiRemover(
const Environment &Env,
const FormatStyle &Style)
2561 : TokenAnalyzer(Env, Style) {}
2563 std::pair<tooling::Replacements, unsigned>
2564 analyze(TokenAnnotator &Annotator,
2565 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2566 FormatTokenLexer &Tokens)
override {
2567 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2568 tooling::Replacements
Result;
2569 removeSemi(Annotator, AnnotatedLines,
Result);
2574 void removeSemi(TokenAnnotator &Annotator,
2575 SmallVectorImpl<AnnotatedLine *> &Lines,
2576 tooling::Replacements &
Result) {
2578 const auto *Prev =
Tok.Previous;
2579 if (!Prev || Prev->isNot(tok::r_brace))
2581 const auto *LBrace = Prev->MatchingParen;
2582 return LBrace && LBrace->is(TT_FunctionLBrace);
2584 const auto &SourceMgr = Env.getSourceManager();
2585 const auto *End = Lines.end();
2586 for (
const auto *I = Lines.begin(); I != End; ++I) {
2587 const auto &
Line = *I;
2588 if (!
Line->Children.empty())
2589 removeSemi(Annotator,
Line->Children,
Result);
2590 if (!
Line->Affected)
2592 Annotator.calculateFormattingInformation(*
Line);
2593 const auto *NextLine = I + 1 == End ?
nullptr : I[1];
2594 for (
const auto *Token =
Line->First; Token && !Token->Finalized;
2595 Token = Token->Next) {
2596 if (Token->isNot(tok::semi) ||
2597 (!Token->Optional && !PrecededByFunctionRBrace(*Token))) {
2600 auto *
Next = Token->Next;
2601 assert(
Next || Token ==
Line->Last);
2602 if (!
Next && NextLine)
2603 Next = NextLine->First;
2612 EnumTrailingCommaEditor(
const Environment &Env,
const FormatStyle &Style)
2613 : TokenAnalyzer(Env, Style) {}
2615 std::pair<tooling::Replacements, unsigned>
2616 analyze(TokenAnnotator &Annotator,
2617 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2618 FormatTokenLexer &Tokens)
override {
2619 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2620 tooling::Replacements
Result;
2621 editEnumTrailingComma(AnnotatedLines,
Result);
2626 void editEnumTrailingComma(SmallVectorImpl<AnnotatedLine *> &Lines,
2627 tooling::Replacements &
Result) {
2628 bool InEnumBraces =
false;
2630 const auto &SourceMgr = Env.getSourceManager();
2631 for (
auto *
Line : Lines) {
2632 if (!
Line->Children.empty())
2633 editEnumTrailingComma(
Line->Children,
Result);
2634 for (
const auto *Token =
Line->First; Token && !Token->Finalized;
2635 Token = Token->Next) {
2636 if (Token->isNot(TT_EnumRBrace)) {
2637 if (Token->is(TT_EnumLBrace))
2638 InEnumBraces =
true;
2639 else if (InEnumBraces && Token->isNot(tok::comment))
2640 BeforeRBrace =
Line->Affected ? Token :
nullptr;
2643 InEnumBraces =
false;
2646 if (BeforeRBrace->is(tok::comma)) {
2647 if (Style.EnumTrailingComma == FormatStyle::ETC_Remove)
2649 }
else if (Style.EnumTrailingComma == FormatStyle::ETC_Insert) {
2650 cantFail(
Result.add(tooling::Replacement(
2651 SourceMgr, BeforeRBrace->Tok.getEndLoc(), 0,
",")));
2653 BeforeRBrace =
nullptr;
2661 JavaScriptRequoter(
const Environment &Env,
const FormatStyle &Style)
2662 : TokenAnalyzer(Env, Style) {}
2664 std::pair<tooling::Replacements, unsigned>
2665 analyze(TokenAnnotator &Annotator,
2666 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2667 FormatTokenLexer &Tokens)
override {
2668 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2669 tooling::Replacements
Result;
2670 requoteJSStringLiteral(AnnotatedLines,
Result);
2677 void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
2678 tooling::Replacements &
Result) {
2679 for (AnnotatedLine *
Line : Lines) {
2680 requoteJSStringLiteral(
Line->Children,
Result);
2681 if (!
Line->Affected)
2684 FormatTok = FormatTok->Next) {
2685 StringRef Input = FormatTok->TokenText;
2686 if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
2689 (Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
2690 !Input.starts_with(
"\"")) ||
2691 (Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
2692 !Input.starts_with(
"\'"))) {
2697 bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
2698 SourceLocation Start = FormatTok->Tok.getLocation();
2699 auto Replace = [&](SourceLocation Start,
unsigned Length,
2700 StringRef ReplacementText) {
2701 auto Err =
Result.add(tooling::Replacement(
2702 Env.getSourceManager(), Start, Length, ReplacementText));
2706 llvm::errs() <<
toString(std::move(Err)) <<
"\n";
2710 Replace(Start, 1, IsSingle ?
"'" :
"\"");
2711 Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
2712 IsSingle ?
"'" :
"\"");
2715 bool Escaped =
false;
2716 for (
size_t i = 1; i < Input.size() - 1; i++) {
2719 if (!Escaped && i + 1 < Input.size() &&
2720 ((IsSingle && Input[i + 1] ==
'"') ||
2721 (!IsSingle && Input[i + 1] ==
'\''))) {
2724 Replace(Start.getLocWithOffset(i), 1,
"");
2731 if (!Escaped && IsSingle == (Input[i] ==
'\'')) {
2733 Replace(Start.getLocWithOffset(i), 0,
"\\");
2749 Formatter(
const Environment &Env,
const FormatStyle &Style,
2750 FormattingAttemptStatus *Status)
2751 : TokenAnalyzer(Env, Style), Status(Status) {}
2753 std::pair<tooling::Replacements, unsigned>
2754 analyze(TokenAnnotator &Annotator,
2755 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2756 FormatTokenLexer &Tokens)
override {
2757 tooling::Replacements
Result;
2758 deriveLocalStyle(AnnotatedLines);
2759 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2760 for (AnnotatedLine *
Line : AnnotatedLines)
2761 Annotator.calculateFormattingInformation(*
Line);
2762 Annotator.setCommentLineLevels(AnnotatedLines);
2764 WhitespaceManager Whitespaces(
2765 Env.getSourceManager(), Style,
2766 Style.LineEnding > FormatStyle::LE_CRLF
2768 Env.getSourceManager().getBufferData(Env.getFileID()),
2769 Style.LineEnding == FormatStyle::LE_DeriveCRLF)
2770 : Style.LineEnding == FormatStyle::LE_CRLF);
2771 ContinuationIndenter Indenter(Style, Tokens.getKeywords(),
2772 Env.getSourceManager(), Whitespaces, Encoding,
2773 BinPackInconclusiveFunctions);
2775 UnwrappedLineFormatter(&Indenter, &Whitespaces, Style,
2776 Tokens.getKeywords(), Env.getSourceManager(),
2778 .format(AnnotatedLines,
false,
2781 Env.getFirstStartColumn(),
2782 Env.getNextStartColumn(),
2783 Env.getLastStartColumn());
2784 for (
const auto &R : Whitespaces.generateReplacements())
2786 return std::make_pair(
Result, 0);
2787 return std::make_pair(
Result, Penalty);
2792 hasCpp03IncompatibleFormat(
const SmallVectorImpl<AnnotatedLine *> &Lines) {
2793 for (
const AnnotatedLine *
Line : Lines) {
2794 if (hasCpp03IncompatibleFormat(
Line->Children))
2797 if (!
Tok->hasWhitespaceBefore()) {
2798 if (
Tok->is(tok::coloncolon) &&
Tok->Previous->is(TT_TemplateOpener))
2800 if (
Tok->is(TT_TemplateCloser) &&
2801 Tok->Previous->is(TT_TemplateCloser)) {
2810 int countVariableAlignments(
const SmallVectorImpl<AnnotatedLine *> &Lines) {
2811 int AlignmentDiff = 0;
2813 for (
const AnnotatedLine *
Line : Lines) {
2814 AlignmentDiff += countVariableAlignments(
Line->Children);
2817 if (
Tok->isNot(TT_PointerOrReference))
2820 const auto *Prev =
Tok->Previous;
2821 const bool PrecededByName = Prev && Prev->Tok.getIdentifierInfo();
2822 const bool SpaceBefore =
Tok->hasWhitespaceBefore();
2825 while (
Tok->Next &&
Tok->Next->is(TT_PointerOrReference))
2829 const bool FollowedByName =
Next &&
Next->Tok.getIdentifierInfo();
2830 const bool SpaceAfter =
Next &&
Next->hasWhitespaceBefore();
2832 if ((!PrecededByName && !FollowedByName) ||
2834 (PrecededByName && FollowedByName && SpaceBefore == SpaceAfter)) {
2838 if ((PrecededByName && SpaceBefore) ||
2839 (FollowedByName && !SpaceAfter)) {
2842 }
else if ((PrecededByName && !SpaceBefore) ||
2843 (FollowedByName && SpaceAfter)) {
2850 return AlignmentDiff;
2854 deriveLocalStyle(
const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
2855 bool HasBinPackedFunction =
false;
2856 bool HasOnePerLineFunction =
false;
2857 for (AnnotatedLine *
Line : AnnotatedLines) {
2858 if (!
Line->First->Next)
2863 HasBinPackedFunction =
true;
2865 HasOnePerLineFunction =
true;
2870 if (Style.DerivePointerAlignment) {
2871 const auto NetRightCount = countVariableAlignments(AnnotatedLines);
2872 if (NetRightCount > 0)
2873 Style.PointerAlignment = FormatStyle::PAS_Right;
2874 else if (NetRightCount < 0)
2875 Style.PointerAlignment = FormatStyle::PAS_Left;
2876 Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
2878 if (Style.Standard == FormatStyle::LS_Auto) {
2879 Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
2880 ? FormatStyle::LS_Latest
2881 : FormatStyle::LS_Cpp03;
2883 BinPackInconclusiveFunctions =
2884 HasBinPackedFunction || !HasOnePerLineFunction;
2887 bool BinPackInconclusiveFunctions;
2888 FormattingAttemptStatus *Status;
2904 TrailingCommaInserter(
const Environment &Env,
const FormatStyle &Style)
2905 : TokenAnalyzer(Env, Style) {}
2907 std::pair<tooling::Replacements, unsigned>
2908 analyze(TokenAnnotator &Annotator,
2909 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2910 FormatTokenLexer &Tokens)
override {
2911 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2912 tooling::Replacements
Result;
2913 insertTrailingCommas(AnnotatedLines,
Result);
2920 void insertTrailingCommas(SmallVectorImpl<AnnotatedLine *> &Lines,
2921 tooling::Replacements &
Result) {
2922 for (AnnotatedLine *
Line : Lines) {
2923 insertTrailingCommas(
Line->Children,
Result);
2924 if (!
Line->Affected)
2927 FormatTok = FormatTok->Next) {
2928 if (FormatTok->NewlinesBefore == 0)
2931 if (!Matching || !FormatTok->getPreviousNonComment())
2933 if (!(FormatTok->is(tok::r_square) &&
2934 Matching->is(TT_ArrayInitializerLSquare)) &&
2935 !(FormatTok->is(tok::r_brace) && Matching->is(TT_DictLiteral))) {
2938 FormatToken *Prev = FormatTok->getPreviousNonComment();
2939 if (Prev->is(tok::comma) || Prev->is(tok::semi))
2943 SourceLocation Start =
2944 Prev->Tok.getLocation().getLocWithOffset(Prev->TokenText.size());
2948 unsigned ColumnNumber =
2949 Env.getSourceManager().getSpellingColumnNumber(Start);
2950 if (ColumnNumber > Style.ColumnLimit)
2955 tooling::Replacement(Env.getSourceManager(), Start, 0,
",")));
2965 Cleaner(
const Environment &Env,
const FormatStyle &Style)
2966 : TokenAnalyzer(Env, Style),
2967 DeletedTokens(FormatTokenLess(Env.getSourceManager())) {}
2970 std::pair<tooling::Replacements, unsigned>
2971 analyze(TokenAnnotator &Annotator,
2972 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2973 FormatTokenLexer &Tokens)
override {
2981 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2983 checkEmptyNamespace(AnnotatedLines);
2985 for (
auto *
Line : AnnotatedLines)
2988 return {generateFixes(), 0};
2992 void cleanupLine(AnnotatedLine *
Line) {
2993 for (
auto *Child :
Line->Children)
2996 if (
Line->Affected) {
2997 cleanupRight(
Line->First, tok::comma, tok::comma);
2998 cleanupRight(
Line->First, TT_CtorInitializerColon, tok::comma);
2999 cleanupRight(
Line->First, tok::l_paren, tok::comma);
3000 cleanupLeft(
Line->First, tok::comma, tok::r_paren);
3001 cleanupLeft(
Line->First, TT_CtorInitializerComma, tok::l_brace);
3002 cleanupLeft(
Line->First, TT_CtorInitializerColon, tok::l_brace);
3003 cleanupLeft(
Line->First, TT_CtorInitializerColon, tok::equal);
3007 bool containsOnlyComments(
const AnnotatedLine &
Line) {
3009 if (
Tok->isNot(tok::comment))
3015 void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
3016 std::set<unsigned> DeletedLines;
3017 for (
unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
3018 auto &
Line = *AnnotatedLines[i];
3019 if (
Line.startsWithNamespace())
3020 checkEmptyNamespace(AnnotatedLines, i, i, DeletedLines);
3023 for (
auto Line : DeletedLines) {
3036 bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3037 unsigned CurrentLine,
unsigned &NewLine,
3038 std::set<unsigned> &DeletedLines) {
3039 unsigned InitLine = CurrentLine, End = AnnotatedLines.size();
3040 if (Style.BraceWrapping.AfterNamespace) {
3044 if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
3045 NewLine = CurrentLine;
3048 }
else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
3051 while (++CurrentLine < End) {
3052 if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
3055 if (AnnotatedLines[CurrentLine]->startsWithNamespace()) {
3056 if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine,
3060 CurrentLine = NewLine;
3064 if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
3069 NewLine = CurrentLine;
3073 NewLine = CurrentLine;
3074 if (CurrentLine >= End)
3079 AnnotatedLines[InitLine]->First->Tok.getLocation(),
3080 AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc()))) {
3084 for (
unsigned i = InitLine; i <= CurrentLine; ++i)
3085 DeletedLines.insert(i);
3094 template <
typename LeftKind,
typename RightKind>
3095 void cleanupPair(
FormatToken *Start, LeftKind LK, RightKind RK,
3098 for (
auto *Res =
Tok.Next; Res; Res = Res->Next) {
3099 if (Res->isNot(tok::comment) &&
3100 DeletedTokens.find(Res) == DeletedTokens.end()) {
3106 for (
auto *Left = Start;
Left;) {
3107 auto *
Right = NextNotDeleted(*Left);
3111 deleteToken(DeleteLeft ? Left : Right);
3123 template <
typename LeftKind,
typename RightKind>
3124 void cleanupLeft(
FormatToken *Start, LeftKind LK, RightKind RK) {
3125 cleanupPair(Start, LK, RK,
true);
3128 template <
typename LeftKind,
typename RightKind>
3129 void cleanupRight(
FormatToken *Start, LeftKind LK, RightKind RK) {
3130 cleanupPair(Start, LK, RK,
false);
3136 DeletedTokens.insert(
Tok);
3139 tooling::Replacements generateFixes() {
3140 tooling::Replacements Fixes;
3141 SmallVector<FormatToken *> Tokens;
3142 std::copy(DeletedTokens.begin(), DeletedTokens.end(),
3143 std::back_inserter(Tokens));
3149 while (Idx < Tokens.size()) {
3150 unsigned St = Idx, End = Idx;
3151 while ((End + 1) < Tokens.size() && Tokens[End]->Next == Tokens[End + 1])
3154 Tokens[End]->Tok.getEndLoc());
3156 Fixes.add(tooling::Replacement(Env.getSourceManager(), SR,
""));
3160 llvm::errs() <<
toString(std::move(Err)) <<
"\n";
3161 assert(
false &&
"Fixes must not conflict!");
3172 struct FormatTokenLess {
3173 FormatTokenLess(
const SourceManager &SM) : SM(SM) {}
3176 return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(),
3177 RHS->Tok.getLocation());
3179 const SourceManager &SM;
3183 std::set<FormatToken *, FormatTokenLess> DeletedTokens;
3188 ObjCHeaderStyleGuesser(
const Environment &Env,
const FormatStyle &Style)
3189 : TokenAnalyzer(Env, Style), IsObjC(
false) {}
3191 std::pair<tooling::Replacements, unsigned>
3192 analyze(TokenAnnotator &Annotator,
3193 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3194 FormatTokenLexer &Tokens)
override {
3195 assert(Style.Language == FormatStyle::LK_Cpp);
3196 IsObjC = guessIsObjC(Env.getSourceManager(), AnnotatedLines,
3197 Tokens.getKeywords());
3198 tooling::Replacements
Result;
3202 bool isObjC() {
return IsObjC; }
3206 guessIsObjC(
const SourceManager &SourceManager,
3207 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3208 const AdditionalKeywords &Keywords) {
3210 static constexpr llvm::StringLiteral FoundationIdentifiers[] = {
3225 "FOUNDATION_EXPORT",
3226 "FOUNDATION_EXTERN",
3227 "NSAffineTransform",
3229 "NSAttributedString",
3248 "NSInvocationOperation",
3252 "NSMutableAttributedString",
3253 "NSMutableCharacterSet",
3255 "NSMutableDictionary",
3256 "NSMutableIndexSet",
3257 "NSMutableOrderedSet",
3261 "NSNumberFormatter",
3265 "NSOperationQueuePriority",
3269 "NSQualityOfService",
3272 "NSRegularExpression",
3283 "NS_ASSUME_NONNULL_BEGIN",
3287 assert(llvm::is_sorted(FoundationIdentifiers));
3289 for (
auto *
Line : AnnotatedLines) {
3290 if (
Line->First && (
Line->First->TokenText.starts_with(
"#") ||
3291 Line->First->TokenText ==
"__pragma" ||
3292 Line->First->TokenText ==
"_Pragma")) {
3296 FormatTok = FormatTok->Next) {
3297 if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) &&
3298 (FormatTok->isNot(tok::objc_not_keyword) ||
3299 FormatTok->isOneOf(tok::numeric_constant, tok::l_square,
3301 (FormatTok->Tok.isAnyIdentifier() &&
3302 llvm::binary_search(FoundationIdentifiers,
3303 FormatTok->TokenText)) ||
3304 FormatTok->is(TT_ObjCStringLiteral) ||
3305 FormatTok->isOneOf(Keywords.kw_NS_CLOSED_ENUM, Keywords.kw_NS_ENUM,
3306 Keywords.kw_NS_ERROR_ENUM,
3307 Keywords.kw_NS_OPTIONS, TT_ObjCBlockLBrace,
3308 TT_ObjCBlockLParen, TT_ObjCDecl, TT_ObjCForIn,
3309 TT_ObjCMethodExpr, TT_ObjCMethodSpecifier,
3310 TT_ObjCProperty, TT_ObjCSelector)) {
3311 LLVM_DEBUG(llvm::dbgs()
3312 <<
"Detected ObjC at location "
3313 << FormatTok->Tok.getLocation().printToString(
3315 <<
" token: " << FormatTok->TokenText <<
" token type: "
3320 if (guessIsObjC(SourceManager,
Line->Children, Keywords))
3329struct IncludeDirective {
3337struct JavaImportDirective {
3338 StringRef Identifier;
3341 SmallVector<StringRef> AssociatedCommentLines;
3350 for (
const auto &Range : Ranges) {
3351 if (Range.getOffset() < End &&
3352 Range.getOffset() + Range.getLength() > Start) {
3367static std::pair<unsigned, unsigned>
3370 unsigned CursorIndex = std::numeric_limits<unsigned>::max();
3371 unsigned OffsetToEOL = 0;
3372 for (
int i = 0, e = Includes.size(); i != e; ++i) {
3373 unsigned Start = Includes[Indices[i]].Offset;
3374 unsigned End = Start + Includes[Indices[i]].Text.size();
3375 if (!(Cursor >= Start && Cursor < End))
3377 CursorIndex = Indices[i];
3378 OffsetToEOL = End - Cursor;
3381 while (--i >= 0 && Includes[CursorIndex].
Text == Includes[Indices[i]].
Text)
3385 return std::make_pair(CursorIndex, OffsetToEOL);
3390 std::string NewCode;
3391 size_t Pos = 0, LastPos = 0;
3394 Pos = Code.find(
"\r\n", LastPos);
3395 if (Pos == LastPos) {
3399 if (Pos == std::string::npos) {
3400 NewCode += Code.substr(LastPos);
3403 NewCode += Code.substr(LastPos, Pos - LastPos) +
"\n";
3405 }
while (Pos != std::string::npos);
3423 const unsigned IncludesBeginOffset = Includes.front().Offset;
3424 const unsigned IncludesEndOffset =
3425 Includes.back().Offset + Includes.back().Text.size();
3426 const unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset;
3427 if (!
affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset))
3430 llvm::to_vector<16>(llvm::seq<unsigned>(0, Includes.size()));
3432 if (Style.SortIncludes.Enabled) {
3433 stable_sort(Indices, [&](
unsigned LHSI,
unsigned RHSI) {
3435 if (Style.SortIncludes.IgnoreExtension) {
3436 LHSStem = Includes[LHSI].Filename;
3437 RHSStem = Includes[RHSI].Filename;
3438 llvm::sys::path::replace_extension(LHSStem,
"");
3439 llvm::sys::path::replace_extension(RHSStem,
"");
3441 std::string LHSStemLower, RHSStemLower;
3442 std::string LHSFilenameLower, RHSFilenameLower;
3443 if (Style.SortIncludes.IgnoreCase) {
3444 LHSStemLower = LHSStem.str().lower();
3445 RHSStemLower = RHSStem.str().lower();
3446 LHSFilenameLower = Includes[LHSI].Filename.lower();
3447 RHSFilenameLower = Includes[RHSI].Filename.lower();
3449 return std::tie(Includes[LHSI].Priority, LHSStemLower, LHSStem,
3450 LHSFilenameLower, Includes[LHSI].Filename) <
3451 std::tie(Includes[RHSI].Priority, RHSStemLower, RHSStem,
3452 RHSFilenameLower, Includes[RHSI].Filename);
3458 unsigned CursorIndex;
3460 unsigned CursorToEOLOffset;
3462 std::tie(CursorIndex, CursorToEOLOffset) =
3467 Indices.erase(llvm::unique(Indices,
3468 [&](
unsigned LHSI,
unsigned RHSI) {
3469 return Includes[LHSI].Text.trim() ==
3470 Includes[RHSI].Text.trim();
3474 int CurrentCategory = Includes.front().Category;
3482 if (Indices.size() == Includes.size() && is_sorted(Indices) &&
3487 const auto OldCursor = Cursor ? *Cursor : 0;
3489 for (
unsigned Index : Indices) {
3490 if (!result.empty()) {
3492 if (Style.IncludeStyle.IncludeBlocks ==
3494 CurrentCategory != Includes[Index].Category) {
3498 result += Includes[Index].Text;
3499 if (Cursor && CursorIndex == Index)
3500 *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
3501 CurrentCategory = Includes[Index].Category;
3504 if (Cursor && *Cursor >= IncludesEndOffset)
3505 *Cursor += result.size() - IncludesBlockSize;
3510 IncludesBeginOffset, IncludesBlockSize)))) {
3512 *Cursor = OldCursor;
3517 FileName, Includes.front().Offset, IncludesBlockSize, result));
3521 llvm::errs() <<
toString(std::move(Err)) <<
"\n";
3531 unsigned Prev = llvm::StringSwitch<size_t>(Code)
3532 .StartsWith(
"\xEF\xBB\xBF", 3)
3534 unsigned SearchFrom = 0;
3546 bool FirstIncludeBlock =
true;
3547 bool MainIncludeFound =
false;
3548 bool FormattingOff =
false;
3551 llvm::Regex RawStringRegex(
3552 "R\"([][A-Za-z0-9_{}#<>%:;.?*+/^&\\$|~!=,'-]*)\\(");
3554 std::string RawStringTermination =
")\"";
3556 for (
const auto Size = Code.size(); SearchFrom < Size;) {
3557 size_t Pos = SearchFrom;
3558 if (Code[SearchFrom] !=
'\n') {
3561 Pos = Code.find(
'\n', Pos);
3562 }
while (Pos != StringRef::npos && Code[Pos - 1] ==
'\\');
3566 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
3568 StringRef Trimmed =
Line.trim();
3573 if (RawStringRegex.match(Trimmed, &RawStringMatches)) {
3574 std::string CharSequence = RawStringMatches[1].str();
3575 RawStringTermination =
")" + CharSequence +
"\"";
3576 FormattingOff =
true;
3579 if (Trimmed.contains(RawStringTermination))
3580 FormattingOff =
false;
3582 bool IsBlockComment =
false;
3585 FormattingOff =
true;
3587 FormattingOff =
false;
3588 }
else if (Trimmed.starts_with(
"/*")) {
3589 IsBlockComment =
true;
3590 Pos = Code.find(
"*/", SearchFrom + 2);
3593 const bool EmptyLineSkipped =
3596 Style.IncludeStyle.IncludeBlocks ==
3599 bool MergeWithNextLine = Trimmed.ends_with(
"\\");
3600 if (!FormattingOff && !MergeWithNextLine) {
3601 if (!IsBlockComment &&
3603 StringRef IncludeName = Matches[2];
3604 if (Trimmed.contains(
"/*") && !Trimmed.contains(
"*/")) {
3609 Pos = Code.find(
"*/", SearchFrom);
3611 Prev, (Pos != StringRef::npos ? Pos + 2 : Code.size()) - Prev);
3615 !MainIncludeFound && FirstIncludeBlock);
3617 IncludeName, !MainIncludeFound && FirstIncludeBlock);
3619 MainIncludeFound =
true;
3620 IncludesInBlock.push_back(
3621 {IncludeName,
Line, Prev, Category, Priority});
3622 }
else if (!IncludesInBlock.empty() && !EmptyLineSkipped) {
3625 IncludesInBlock.clear();
3626 if (Trimmed.starts_with(
"#pragma hdrstop"))
3627 FirstIncludeBlock =
true;
3629 FirstIncludeBlock =
false;
3632 if (Pos == StringRef::npos || Pos + 1 == Code.size())
3635 if (!MergeWithNextLine)
3637 SearchFrom = Pos + 1;
3639 if (!IncludesInBlock.empty()) {
3650 StringRef ImportIdentifier) {
3651 unsigned LongestMatchIndex = std::numeric_limits<unsigned>::max();
3652 unsigned LongestMatchLength = 0;
3653 for (
unsigned I = 0; I < Style.JavaImportGroups.size(); I++) {
3654 const std::string &GroupPrefix = Style.JavaImportGroups[I];
3655 if (ImportIdentifier.starts_with(GroupPrefix) &&
3656 GroupPrefix.length() > LongestMatchLength) {
3657 LongestMatchIndex = I;
3658 LongestMatchLength = GroupPrefix.length();
3661 return LongestMatchIndex;
3673 unsigned ImportsBeginOffset = Imports.front().Offset;
3674 unsigned ImportsEndOffset =
3675 Imports.back().Offset + Imports.back().Text.size();
3676 unsigned ImportsBlockSize = ImportsEndOffset - ImportsBeginOffset;
3677 if (!
affectsRange(Ranges, ImportsBeginOffset, ImportsEndOffset))
3681 llvm::to_vector<16>(llvm::seq<unsigned>(0, Imports.size()));
3684 for (
const JavaImportDirective &Import : Imports)
3687 bool StaticImportAfterNormalImport =
3688 Style.SortJavaStaticImport == FormatStyle::SJSIO_After;
3689 sort(Indices, [&](
unsigned LHSI,
unsigned RHSI) {
3691 return std::make_tuple(!Imports[LHSI].IsStatic ^
3692 StaticImportAfterNormalImport,
3694 std::make_tuple(!Imports[RHSI].IsStatic ^
3695 StaticImportAfterNormalImport,
3700 Indices.erase(llvm::unique(Indices,
3701 [&](
unsigned LHSI,
unsigned RHSI) {
3702 return Imports[LHSI].Text == Imports[RHSI].Text;
3706 bool CurrentIsStatic = Imports[Indices.front()].IsStatic;
3710 for (
unsigned Index : Indices) {
3711 if (!result.empty()) {
3713 if (CurrentIsStatic != Imports[Index].IsStatic ||
3718 for (StringRef CommentLine : Imports[Index].AssociatedCommentLines) {
3719 result += CommentLine;
3722 result += Imports[Index].Text;
3723 CurrentIsStatic = Imports[Index].IsStatic;
3730 Imports.front().Offset, ImportsBlockSize)))) {
3735 ImportsBlockSize, result));
3739 llvm::errs() <<
toString(std::move(Err)) <<
"\n";
3746const char JavaImportRegexPattern[] =
3747 "^[\t ]*import[\t ]+(static[\t ]*)?([^\t ]*)[\t ]*;";
3756 unsigned SearchFrom = 0;
3757 llvm::Regex ImportRegex(JavaImportRegexPattern);
3762 bool FormattingOff =
false;
3765 auto Pos = Code.find(
'\n', SearchFrom);
3767 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
3769 StringRef Trimmed =
Line.trim();
3771 FormattingOff =
true;
3773 FormattingOff =
false;
3775 if (ImportRegex.match(
Line, &Matches)) {
3776 if (FormattingOff) {
3781 StringRef
Static = Matches[1];
3782 StringRef Identifier = Matches[2];
3783 bool IsStatic =
false;
3784 if (
Static.contains(
"static"))
3786 ImportsInBlock.push_back(
3787 {Identifier,
Line, Prev, AssociatedCommentLines, IsStatic});
3788 AssociatedCommentLines.clear();
3789 }
else if (!Trimmed.empty() && !ImportsInBlock.empty()) {
3791 AssociatedCommentLines.push_back(
Line);
3794 if (Pos == StringRef::npos || Pos + 1 == Code.size())
3796 SearchFrom = Pos + 1;
3798 if (!ImportsInBlock.empty())
3807 return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
3810bool isLikelyXml(StringRef Code) {
return Code.ltrim().starts_with(
"<"); }
3814 StringRef
FileName,
unsigned *Cursor) {
3816 if (!Style.SortIncludes.Enabled || Style.DisableFormat)
3820 if (Style.isJavaScript()) {
3832template <
typename T>
3836 const FormatStyle &Style) {
3837 if (Replaces.
empty())
3840 auto NewCode = applyAllReplacements(Code, Replaces);
3842 return NewCode.takeError();
3847 ProcessFunc(Style, *NewCode, ChangedRanges,
FileName);
3849 return Replaces.
merge(FormatReplaces);
3854 const FormatStyle &Style) {
3857 auto SortIncludes = [](
const FormatStyle &Style, StringRef Code,
3858 std::vector<tooling::Range> Ranges,
3862 auto SortedReplaces =
3864 if (!SortedReplaces)
3865 return SortedReplaces.takeError();
3869 auto Reformat = [](
const FormatStyle &Style, StringRef Code,
3870 std::vector<tooling::Range> Ranges,
3880 return Replace.
getOffset() == std::numeric_limits<unsigned>::max() &&
3886inline bool isHeaderDeletion(
const tooling::Replacement &Replace) {
3887 return Replace.getOffset() == std::numeric_limits<unsigned>::max() &&
3888 Replace.getLength() == 1;
3892tooling::Replacements
3893fixCppIncludeInsertions(StringRef Code,
const tooling::Replacements &Replaces,
3894 const FormatStyle &Style) {
3898 tooling::Replacements HeaderInsertions;
3899 std::set<StringRef> HeadersToDelete;
3900 tooling::Replacements
Result;
3901 for (
const auto &R : Replaces) {
3902 if (isHeaderInsertion(R)) {
3905 consumeError(HeaderInsertions.add(R));
3906 }
else if (isHeaderDeletion(R)) {
3907 HeadersToDelete.insert(R.getReplacementText());
3908 }
else if (R.getOffset() == std::numeric_limits<unsigned>::max()) {
3909 llvm::errs() <<
"Insertions other than header #include insertion are "
3911 << R.getReplacementText() <<
"\n";
3913 consumeError(
Result.add(R));
3916 if (HeaderInsertions.empty() && HeadersToDelete.empty())
3919 StringRef
FileName = Replaces.begin()->getFilePath();
3920 tooling::HeaderIncludes Includes(
FileName, Code, Style.IncludeStyle);
3922 for (
const auto &Header : HeadersToDelete) {
3923 tooling::Replacements Replaces =
3924 Includes.remove(Header.trim(
"\"<>"), Header.starts_with(
"<"));
3925 for (
const auto &R : Replaces) {
3926 auto Err =
Result.add(R);
3929 llvm::errs() <<
"Failed to add header deletion replacement for "
3930 << Header <<
": " <<
toString(std::move(Err)) <<
"\n";
3936 for (
const auto &R : HeaderInsertions) {
3937 auto IncludeDirective = R.getReplacementText();
3940 assert(Matched &&
"Header insertion replacement must have replacement text "
3943 auto IncludeName = Matches[2];
3945 Includes.insert(IncludeName.trim(
"\"<>"), IncludeName.starts_with(
"<"),
3948 auto Err =
Result.add(*Replace);
3950 consumeError(std::move(Err));
3951 unsigned NewOffset =
3952 Result.getShiftedCodePosition(Replace->getOffset());
3953 auto Shifted = tooling::Replacement(
FileName, NewOffset, 0,
3954 Replace->getReplacementText());
3966 const FormatStyle &Style) {
3969 auto Cleanup = [](
const FormatStyle &Style, StringRef Code,
3976 fixCppIncludeInsertions(Code, Replaces, Style);
3981std::pair<tooling::Replacements, unsigned>
3984 unsigned NextStartColumn,
unsigned LastStartColumn, StringRef
FileName,
3986 FormatStyle Expanded = Style;
3990 Expanded.InsertBraces =
false;
3991 Expanded.RemoveBracesLLVM =
false;
3992 Expanded.RemoveParentheses = FormatStyle::RPS_Leave;
3993 Expanded.RemoveSemicolon =
false;
3994 switch (Expanded.RequiresClausePosition) {
3995 case FormatStyle::RCPS_SingleLine:
3996 case FormatStyle::RCPS_WithPreceding:
3997 Expanded.IndentRequiresClause =
false;
4003 if (Expanded.DisableFormat)
4007 if (Expanded.isJavaScript() &&
isMpegTS(Code))
4011 if (Style.isJson()) {
4012 std::vector<tooling::Range> Ranges(1,
tooling::Range(0, Code.size()));
4014 NextStartColumn, LastStartColumn);
4019 Formatter(*Env, Style, Status).process().first;
4021 if (Code.starts_with(
"x = ")) {
4022 Replaces = Replaces.
merge(
4026 if (applyAllReplacements(Code, Replaces))
4027 return {Replaces, 0};
4032 NextStartColumn, LastStartColumn);
4050 if (Style.isCpp()) {
4051 if (Style.QualifierAlignment != FormatStyle::QAS_Leave)
4054 if (Style.RemoveParentheses != FormatStyle::RPS_Leave) {
4055 FormatStyle S = Expanded;
4056 S.RemoveParentheses = Style.RemoveParentheses;
4057 Passes.emplace_back([&, S = std::move(S)](
const Environment &Env) {
4058 return ParensRemover(Env, S).process(
true);
4062 if (Style.InsertBraces) {
4063 FormatStyle S = Expanded;
4064 S.InsertBraces =
true;
4065 Passes.emplace_back([&, S = std::move(S)](
const Environment &Env) {
4066 return BracesInserter(Env, S).process(
true);
4070 if (Style.RemoveBracesLLVM) {
4071 FormatStyle S = Expanded;
4072 S.RemoveBracesLLVM =
true;
4073 Passes.emplace_back([&, S = std::move(S)](
const Environment &Env) {
4074 return BracesRemover(Env, S).process(
true);
4078 if (Style.RemoveSemicolon) {
4079 FormatStyle S = Expanded;
4080 S.RemoveSemicolon =
true;
4081 Passes.emplace_back([&, S = std::move(S)](
const Environment &Env) {
4082 return SemiRemover(Env, S).process();
4086 if (Style.EnumTrailingComma != FormatStyle::ETC_Leave) {
4088 return EnumTrailingCommaEditor(Env, Expanded)
4093 if (Style.FixNamespaceComments) {
4099 if (Style.SortUsingDeclarations != FormatStyle::SUD_Never) {
4106 if (Style.SeparateDefinitionBlocks != FormatStyle::SDS_Leave) {
4112 if (Style.Language == FormatStyle::LK_ObjC &&
4113 !Style.ObjCPropertyAttributeOrder.empty()) {
4119 if (Style.isJavaScript() &&
4120 Style.JavaScriptQuotes != FormatStyle::JSQS_Leave) {
4122 return JavaScriptRequoter(Env, Expanded).process(
true);
4127 return Formatter(Env, Expanded, Status).process();
4130 if (Style.isJavaScript() &&
4131 Style.InsertTrailingCommas == FormatStyle::TCS_Wrapped) {
4133 return TrailingCommaInserter(Env, Expanded).process();
4137 std::optional<std::string> CurrentCode;
4139 unsigned Penalty = 0;
4140 for (
size_t I = 0, E = Passes.size(); I < E; ++I) {
4141 std::pair<tooling::Replacements, unsigned> PassFixes = Passes[I](*Env);
4142 auto NewCode = applyAllReplacements(
4143 CurrentCode ? StringRef(*CurrentCode) : Code, PassFixes.first);
4145 Fixes = Fixes.
merge(PassFixes.first);
4146 Penalty += PassFixes.second;
4148 CurrentCode = std::move(*NewCode);
4152 FirstStartColumn, NextStartColumn, LastStartColumn);
4159 if (Style.QualifierAlignment != FormatStyle::QAS_Leave) {
4165 StringRef OriginalCode = Code.substr(Fix.getOffset(), Fix.getLength());
4166 if (OriginalCode != Fix.getReplacementText()) {
4167 auto Err = NonNoOpFixes.
add(Fix);
4169 llvm::errs() <<
"Error adding replacements : "
4170 <<
toString(std::move(Err)) <<
"\n";
4174 Fixes = std::move(NonNoOpFixes);
4177 return {Fixes, Penalty};
4196 if (Style.Language != FormatStyle::LK_Cpp)
4201 return Cleaner(*Env, Style).process().first;
4206 StringRef
FileName,
bool *IncompleteFormat) {
4209 if (!Status.FormatComplete)
4210 *IncompleteFormat =
true;
4237 auto LexingStd = Style.Standard;
4238 if (LexingStd == FormatStyle::LS_Auto || LexingStd == FormatStyle::LS_Latest)
4239 LexingStd = FormatStyle::LS_Cpp20;
4241 const bool SinceCpp11 = LexingStd >= FormatStyle::LS_Cpp11;
4242 const bool SinceCpp20 = LexingStd >= FormatStyle::LS_Cpp20;
4244 switch (Style.Language) {
4245 case FormatStyle::LK_C:
4249 case FormatStyle::LK_Cpp:
4250 case FormatStyle::LK_ObjC:
4251 LangOpts.CXXOperatorNames = 1;
4252 LangOpts.CPlusPlus11 = SinceCpp11;
4253 LangOpts.CPlusPlus14 = LexingStd >= FormatStyle::LS_Cpp14;
4254 LangOpts.CPlusPlus17 = LexingStd >= FormatStyle::LS_Cpp17;
4255 LangOpts.CPlusPlus20 = SinceCpp20;
4258 LangOpts.CPlusPlus = 1;
4261 LangOpts.Char8 = SinceCpp20;
4265 LangOpts.Digraphs = SinceCpp11;
4267 LangOpts.LineComment = 1;
4270 LangOpts.MicrosoftExt = 1;
4271 LangOpts.DeclSpecKeyword = 1;
4278 "Set coding style. <string> can be:\n"
4279 "1. A preset: LLVM, GNU, Google, Chromium, Microsoft,\n"
4280 " Mozilla, WebKit.\n"
4281 "2. 'file' to load style configuration from a\n"
4282 " .clang-format file in one of the parent directories\n"
4283 " of the source file (for stdin, see --assume-filename).\n"
4284 " If no .clang-format file is found, falls back to\n"
4285 " --fallback-style.\n"
4286 " --style=file is the default.\n"
4287 "3. 'file:<format_file_path>' to explicitly specify\n"
4288 " the configuration file.\n"
4289 "4. \"{key: value, ...}\" to set specific parameters, e.g.:\n"
4290 " --style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
4294 return FormatStyle::LK_C;
4296 return FormatStyle::LK_Java;
4297 if (
FileName.ends_with_insensitive(
".js") ||
4298 FileName.ends_with_insensitive(
".mjs") ||
4299 FileName.ends_with_insensitive(
".cjs") ||
4300 FileName.ends_with_insensitive(
".ts")) {
4301 return FormatStyle::LK_JavaScript;
4304 return FormatStyle::LK_ObjC;
4305 if (
FileName.ends_with_insensitive(
".proto") ||
4306 FileName.ends_with_insensitive(
".protodevel")) {
4307 return FormatStyle::LK_Proto;
4312 if (
FileName.ends_with_insensitive(
".txtpb") ||
4313 FileName.ends_with_insensitive(
".textpb") ||
4314 FileName.ends_with_insensitive(
".pb.txt") ||
4315 FileName.ends_with_insensitive(
".textproto") ||
4316 FileName.ends_with_insensitive(
".asciipb")) {
4317 return FormatStyle::LK_TextProto;
4319 if (
FileName.ends_with_insensitive(
".td"))
4320 return FormatStyle::LK_TableGen;
4321 if (
FileName.ends_with_insensitive(
".cs"))
4322 return FormatStyle::LK_CSharp;
4323 if (
FileName.ends_with_insensitive(
".json") ||
4324 FileName.ends_with_insensitive(
".ipynb")) {
4325 return FormatStyle::LK_Json;
4327 if (
FileName.ends_with_insensitive(
".sv") ||
4328 FileName.ends_with_insensitive(
".svh") ||
4329 FileName.ends_with_insensitive(
".v") ||
4330 FileName.ends_with_insensitive(
".vh")) {
4331 return FormatStyle::LK_Verilog;
4333 return FormatStyle::LK_Cpp;
4341 LangOpts.CPlusPlus = 1;
4342 LangOpts.LineComment = 1;
4344 Lexer Lex(ID, SourceMgr.getBufferOrFake(ID), SourceMgr, LangOpts);
4348 auto Text = StringRef(SourceMgr.getCharacterData(
Tok.getLocation()),
4350 if (!
Text.consume_front(
"// clang-format Language:"))
4355 return FormatStyle::LK_C;
4357 return FormatStyle::LK_Cpp;
4359 return FormatStyle::LK_ObjC;
4362 return FormatStyle::LK_None;
4367 if (GuessedLanguage == FormatStyle::LK_Cpp) {
4368 auto Extension = llvm::sys::path::extension(
FileName);
4371 if (!Code.empty() && (Extension.empty() || Extension ==
".h")) {
4375 Language != FormatStyle::LK_None) {
4380 if (Guesser.isObjC())
4381 return FormatStyle::LK_ObjC;
4384 return GuessedLanguage;
4392llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
4394 FormatStyle *Style,
bool AllowUnknownOptions,
4395 llvm::SourceMgr::DiagHandlerTy DiagHandler,
4397 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Text =
4398 FS->getBufferForFile(ConfigFile.str());
4399 if (
auto EC =
Text.getError())
4402 DiagHandler,
nullptr,
4410 StringRef FallbackStyleName, StringRef Code,
4411 llvm::vfs::FileSystem *FS,
4412 bool AllowUnknownOptions,
4413 llvm::SourceMgr::DiagHandlerTy DiagHandler) {
4421 if (StyleName.starts_with(
"{")) {
4423 StringRef Source =
"<command-line>";
4424 if (std::error_code ec =
4426 AllowUnknownOptions, DiagHandler)) {
4430 if (!Style.InheritsParentConfig)
4433 ChildFormatTextToApply.emplace_back(
4434 llvm::MemoryBuffer::getMemBuffer(StyleName, Source,
false));
4438 FS = llvm::vfs::getRealFileSystem().get();
4441 const bool IsDotHFile =
FileName.ends_with(
".h");
4444 if (!Style.InheritsParentConfig &&
4445 StyleName.starts_with_insensitive(
"file:")) {
4446 auto ConfigFile = StyleName.substr(5);
4447 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Text =
4449 DiagHandler, IsDotHFile);
4450 if (
auto EC =
Text.getError()) {
4455 LLVM_DEBUG(llvm::dbgs()
4456 <<
"Using configuration file " << ConfigFile <<
"\n");
4458 if (!Style.InheritsParentConfig)
4464 ChildFormatTextToApply.emplace_back(std::move(*
Text));
4470 if (!Style.InheritsParentConfig && !StyleName.equals_insensitive(
"file")) {
4473 if (!Style.InheritsParentConfig)
4478 if (std::error_code EC = FS->makeAbsolute(Path))
4482 Style.InheritsParentConfig =
false;
4484 auto dropDiagnosticHandler = [](
const llvm::SMDiagnostic &,
void *) {};
4486 auto applyChildFormatTexts = [&](FormatStyle *Style) {
4487 for (
const auto &MemBuf : llvm::reverse(ChildFormatTextToApply)) {
4490 DiagHandler ? DiagHandler : dropDiagnosticHandler);
4493 static_cast<void>(EC);
4499 FilesToLookFor.push_back(
".clang-format");
4500 FilesToLookFor.push_back(
"_clang-format");
4503 for (StringRef Directory = Path; !Directory.empty();
4504 Directory = llvm::sys::path::parent_path(Directory)) {
4505 auto Status = FS->status(Directory);
4507 Status->getType() != llvm::sys::fs::file_type::directory_file) {
4511 for (
const auto &F : FilesToLookFor) {
4514 llvm::sys::path::append(ConfigFile, F);
4515 LLVM_DEBUG(llvm::dbgs() <<
"Trying " << ConfigFile <<
"...\n");
4517 Status = FS->status(ConfigFile);
4519 Status->getType() != llvm::sys::fs::file_type::regular_file) {
4523 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Text =
4525 DiagHandler, IsDotHFile);
4526 if (
auto EC =
Text.getError()) {
4531 if (!UnsuitableConfigFiles.empty())
4532 UnsuitableConfigFiles.append(
", ");
4533 UnsuitableConfigFiles.append(ConfigFile);
4537 LLVM_DEBUG(llvm::dbgs()
4538 <<
"Using configuration file " << ConfigFile <<
"\n");
4540 if (!Style.InheritsParentConfig) {
4541 if (!ChildFormatTextToApply.empty()) {
4542 LLVM_DEBUG(llvm::dbgs() <<
"Applying child configurations\n");
4543 applyChildFormatTexts(&Style);
4548 LLVM_DEBUG(llvm::dbgs() <<
"Inherits parent configuration\n");
4551 Style.InheritsParentConfig =
false;
4553 ChildFormatTextToApply.emplace_back(std::move(*
Text));
4563 if (!UnsuitableConfigFiles.empty()) {
4566 UnsuitableConfigFiles);
4569 if (!ChildFormatTextToApply.empty()) {
4570 LLVM_DEBUG(llvm::dbgs()
4571 <<
"Applying child configurations on fallback style\n");
4572 applyChildFormatTexts(&FallbackStyle);
4575 return FallbackStyle;
4579 if (Comment == (On ?
"/* clang-format on */" :
"/* clang-format off */"))
4582 static const char ClangFormatOn[] =
"// clang-format on";
4583 static const char ClangFormatOff[] =
"// clang-format off";
4584 const unsigned Size = (On ?
sizeof ClangFormatOn :
sizeof ClangFormatOff) - 1;
4586 return Comment.starts_with(On ? ClangFormatOn : ClangFormatOff) &&
4587 (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)