26#include "llvm/ADT/Sequence.h"
29#define DEBUG_TYPE "format-formatter"
31using clang::format::FormatStyle;
33LLVM_YAML_IS_SEQUENCE_VECTOR(FormatStyle::RawStringFormat)
38struct ScalarEnumerationTraits<FormatStyle::BreakBeforeNoexceptSpecifierStyle> {
41 IO.enumCase(
Value,
"Never", FormatStyle::BBNSS_Never);
42 IO.enumCase(
Value,
"OnlyWithParen", FormatStyle::BBNSS_OnlyWithParen);
43 IO.enumCase(
Value,
"Always", FormatStyle::BBNSS_Always);
47template <>
struct MappingTraits<FormatStyle::AlignConsecutiveStyle> {
49 IO.enumCase(
Value,
"None", FormatStyle::AlignConsecutiveStyle({}));
50 IO.enumCase(
Value,
"Consecutive",
51 FormatStyle::AlignConsecutiveStyle(
56 IO.enumCase(
Value,
"AcrossEmptyLines",
57 FormatStyle::AlignConsecutiveStyle(
62 IO.enumCase(
Value,
"AcrossComments",
63 FormatStyle::AlignConsecutiveStyle(
68 IO.enumCase(
Value,
"AcrossEmptyLinesAndComments",
69 FormatStyle::AlignConsecutiveStyle(
76 IO.enumCase(
Value,
"true",
77 FormatStyle::AlignConsecutiveStyle(
82 IO.enumCase(
Value,
"false", FormatStyle::AlignConsecutiveStyle({}));
85 static void mapping(IO &IO, FormatStyle::AlignConsecutiveStyle &
Value) {
86 IO.mapOptional(
"Enabled",
Value.Enabled);
87 IO.mapOptional(
"AcrossEmptyLines",
Value.AcrossEmptyLines);
88 IO.mapOptional(
"AcrossComments",
Value.AcrossComments);
89 IO.mapOptional(
"AlignCompound",
Value.AlignCompound);
90 IO.mapOptional(
"AlignFunctionDeclarations",
91 Value.AlignFunctionDeclarations);
92 IO.mapOptional(
"AlignFunctionPointers",
Value.AlignFunctionPointers);
93 IO.mapOptional(
"PadOperators",
Value.PadOperators);
98struct MappingTraits<FormatStyle::ShortCaseStatementsAlignmentStyle> {
100 FormatStyle::ShortCaseStatementsAlignmentStyle &
Value) {
101 IO.mapOptional(
"Enabled",
Value.Enabled);
102 IO.mapOptional(
"AcrossEmptyLines",
Value.AcrossEmptyLines);
103 IO.mapOptional(
"AcrossComments",
Value.AcrossComments);
104 IO.mapOptional(
"AlignCaseArrows",
Value.AlignCaseArrows);
105 IO.mapOptional(
"AlignCaseColons",
Value.AlignCaseColons);
110struct ScalarEnumerationTraits<FormatStyle::AttributeBreakingStyle> {
112 IO.enumCase(
Value,
"Always", FormatStyle::ABS_Always);
113 IO.enumCase(
Value,
"Leave", FormatStyle::ABS_Leave);
114 IO.enumCase(
Value,
"Never", FormatStyle::ABS_Never);
119struct ScalarEnumerationTraits<FormatStyle::ArrayInitializerAlignmentStyle> {
121 FormatStyle::ArrayInitializerAlignmentStyle &
Value) {
122 IO.enumCase(
Value,
"None", FormatStyle::AIAS_None);
123 IO.enumCase(
Value,
"Left", FormatStyle::AIAS_Left);
124 IO.enumCase(
Value,
"Right", FormatStyle::AIAS_Right);
128template <>
struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
130 IO.enumCase(
Value,
"All", FormatStyle::BOS_All);
131 IO.enumCase(
Value,
"true", FormatStyle::BOS_All);
132 IO.enumCase(
Value,
"None", FormatStyle::BOS_None);
133 IO.enumCase(
Value,
"false", FormatStyle::BOS_None);
134 IO.enumCase(
Value,
"NonAssignment", FormatStyle::BOS_NonAssignment);
139struct ScalarEnumerationTraits<FormatStyle::BinPackParametersStyle> {
141 IO.enumCase(
Value,
"BinPack", FormatStyle::BPPS_BinPack);
142 IO.enumCase(
Value,
"OnePerLine", FormatStyle::BPPS_OnePerLine);
143 IO.enumCase(
Value,
"AlwaysOnePerLine", FormatStyle::BPPS_AlwaysOnePerLine);
146 IO.enumCase(
Value,
"true", FormatStyle::BPPS_BinPack);
147 IO.enumCase(
Value,
"false", FormatStyle::BPPS_OnePerLine);
151template <>
struct ScalarEnumerationTraits<FormatStyle::BinPackStyle> {
153 IO.enumCase(
Value,
"Auto", FormatStyle::BPS_Auto);
154 IO.enumCase(
Value,
"Always", FormatStyle::BPS_Always);
155 IO.enumCase(
Value,
"Never", FormatStyle::BPS_Never);
160struct ScalarEnumerationTraits<FormatStyle::BitFieldColonSpacingStyle> {
162 FormatStyle::BitFieldColonSpacingStyle &
Value) {
163 IO.enumCase(
Value,
"Both", FormatStyle::BFCS_Both);
164 IO.enumCase(
Value,
"None", FormatStyle::BFCS_None);
165 IO.enumCase(
Value,
"Before", FormatStyle::BFCS_Before);
166 IO.enumCase(
Value,
"After", FormatStyle::BFCS_After);
170template <>
struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
172 IO.enumCase(
Value,
"Attach", FormatStyle::BS_Attach);
173 IO.enumCase(
Value,
"Linux", FormatStyle::BS_Linux);
174 IO.enumCase(
Value,
"Mozilla", FormatStyle::BS_Mozilla);
175 IO.enumCase(
Value,
"Stroustrup", FormatStyle::BS_Stroustrup);
176 IO.enumCase(
Value,
"Allman", FormatStyle::BS_Allman);
177 IO.enumCase(
Value,
"Whitesmiths", FormatStyle::BS_Whitesmiths);
178 IO.enumCase(
Value,
"GNU", FormatStyle::BS_GNU);
179 IO.enumCase(
Value,
"WebKit", FormatStyle::BS_WebKit);
180 IO.enumCase(
Value,
"Custom", FormatStyle::BS_Custom);
184template <>
struct MappingTraits<FormatStyle::BraceWrappingFlags> {
185 static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
186 IO.mapOptional(
"AfterCaseLabel", Wrapping.AfterCaseLabel);
187 IO.mapOptional(
"AfterClass", Wrapping.AfterClass);
188 IO.mapOptional(
"AfterControlStatement", Wrapping.AfterControlStatement);
189 IO.mapOptional(
"AfterEnum", Wrapping.AfterEnum);
190 IO.mapOptional(
"AfterExternBlock", Wrapping.AfterExternBlock);
191 IO.mapOptional(
"AfterFunction", Wrapping.AfterFunction);
192 IO.mapOptional(
"AfterNamespace", Wrapping.AfterNamespace);
193 IO.mapOptional(
"AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
194 IO.mapOptional(
"AfterStruct", Wrapping.AfterStruct);
195 IO.mapOptional(
"AfterUnion", Wrapping.AfterUnion);
196 IO.mapOptional(
"BeforeCatch", Wrapping.BeforeCatch);
197 IO.mapOptional(
"BeforeElse", Wrapping.BeforeElse);
198 IO.mapOptional(
"BeforeLambdaBody", Wrapping.BeforeLambdaBody);
199 IO.mapOptional(
"BeforeWhile", Wrapping.BeforeWhile);
200 IO.mapOptional(
"IndentBraces", Wrapping.IndentBraces);
201 IO.mapOptional(
"SplitEmptyFunction", Wrapping.SplitEmptyFunction);
202 IO.mapOptional(
"SplitEmptyRecord", Wrapping.SplitEmptyRecord);
203 IO.mapOptional(
"SplitEmptyNamespace", Wrapping.SplitEmptyNamespace);
207template <>
struct ScalarEnumerationTraits<FormatStyle::BracketAlignmentStyle> {
209 IO.enumCase(
Value,
"Align", FormatStyle::BAS_Align);
210 IO.enumCase(
Value,
"DontAlign", FormatStyle::BAS_DontAlign);
211 IO.enumCase(
Value,
"AlwaysBreak", FormatStyle::BAS_AlwaysBreak);
212 IO.enumCase(
Value,
"BlockIndent", FormatStyle::BAS_BlockIndent);
215 IO.enumCase(
Value,
"true", FormatStyle::BAS_Align);
216 IO.enumCase(
Value,
"false", FormatStyle::BAS_DontAlign);
221struct ScalarEnumerationTraits<
222 FormatStyle::BraceWrappingAfterControlStatementStyle> {
225 FormatStyle::BraceWrappingAfterControlStatementStyle &
Value) {
226 IO.enumCase(
Value,
"Never", FormatStyle::BWACS_Never);
227 IO.enumCase(
Value,
"MultiLine", FormatStyle::BWACS_MultiLine);
228 IO.enumCase(
Value,
"Always", FormatStyle::BWACS_Always);
231 IO.enumCase(
Value,
"false", FormatStyle::BWACS_Never);
232 IO.enumCase(
Value,
"true", FormatStyle::BWACS_Always);
237struct ScalarEnumerationTraits<
238 FormatStyle::BreakBeforeConceptDeclarationsStyle> {
241 IO.enumCase(
Value,
"Never", FormatStyle::BBCDS_Never);
242 IO.enumCase(
Value,
"Allowed", FormatStyle::BBCDS_Allowed);
243 IO.enumCase(
Value,
"Always", FormatStyle::BBCDS_Always);
246 IO.enumCase(
Value,
"true", FormatStyle::BBCDS_Always);
247 IO.enumCase(
Value,
"false", FormatStyle::BBCDS_Allowed);
252struct ScalarEnumerationTraits<FormatStyle::BreakBeforeInlineASMColonStyle> {
254 FormatStyle::BreakBeforeInlineASMColonStyle &
Value) {
255 IO.enumCase(
Value,
"Never", FormatStyle::BBIAS_Never);
256 IO.enumCase(
Value,
"OnlyMultiline", FormatStyle::BBIAS_OnlyMultiline);
257 IO.enumCase(
Value,
"Always", FormatStyle::BBIAS_Always);
262struct ScalarEnumerationTraits<FormatStyle::BreakBinaryOperationsStyle> {
264 FormatStyle::BreakBinaryOperationsStyle &
Value) {
265 IO.enumCase(
Value,
"Never", FormatStyle::BBO_Never);
266 IO.enumCase(
Value,
"OnePerLine", FormatStyle::BBO_OnePerLine);
267 IO.enumCase(
Value,
"RespectPrecedence", FormatStyle::BBO_RespectPrecedence);
272struct ScalarEnumerationTraits<FormatStyle::BreakConstructorInitializersStyle> {
275 IO.enumCase(
Value,
"BeforeColon", FormatStyle::BCIS_BeforeColon);
276 IO.enumCase(
Value,
"BeforeComma", FormatStyle::BCIS_BeforeComma);
277 IO.enumCase(
Value,
"AfterColon", FormatStyle::BCIS_AfterColon);
282struct ScalarEnumerationTraits<FormatStyle::BreakInheritanceListStyle> {
284 FormatStyle::BreakInheritanceListStyle &
Value) {
285 IO.enumCase(
Value,
"BeforeColon", FormatStyle::BILS_BeforeColon);
286 IO.enumCase(
Value,
"BeforeComma", FormatStyle::BILS_BeforeComma);
287 IO.enumCase(
Value,
"AfterColon", FormatStyle::BILS_AfterColon);
288 IO.enumCase(
Value,
"AfterComma", FormatStyle::BILS_AfterComma);
293struct ScalarEnumerationTraits<FormatStyle::BreakTemplateDeclarationsStyle> {
295 FormatStyle::BreakTemplateDeclarationsStyle &
Value) {
296 IO.enumCase(
Value,
"Leave", FormatStyle::BTDS_Leave);
297 IO.enumCase(
Value,
"No", FormatStyle::BTDS_No);
298 IO.enumCase(
Value,
"MultiLine", FormatStyle::BTDS_MultiLine);
299 IO.enumCase(
Value,
"Yes", FormatStyle::BTDS_Yes);
302 IO.enumCase(
Value,
"false", FormatStyle::BTDS_MultiLine);
303 IO.enumCase(
Value,
"true", FormatStyle::BTDS_Yes);
307template <>
struct ScalarEnumerationTraits<FormatStyle::DAGArgStyle> {
309 IO.enumCase(
Value,
"DontBreak", FormatStyle::DAS_DontBreak);
310 IO.enumCase(
Value,
"BreakElements", FormatStyle::DAS_BreakElements);
311 IO.enumCase(
Value,
"BreakAll", FormatStyle::DAS_BreakAll);
316struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
319 IO.enumCase(
Value,
"None", FormatStyle::DRTBS_None);
320 IO.enumCase(
Value,
"All", FormatStyle::DRTBS_All);
321 IO.enumCase(
Value,
"TopLevel", FormatStyle::DRTBS_TopLevel);
324 IO.enumCase(
Value,
"false", FormatStyle::DRTBS_None);
325 IO.enumCase(
Value,
"true", FormatStyle::DRTBS_All);
330struct ScalarEnumerationTraits<FormatStyle::EscapedNewlineAlignmentStyle> {
332 FormatStyle::EscapedNewlineAlignmentStyle &
Value) {
333 IO.enumCase(
Value,
"DontAlign", FormatStyle::ENAS_DontAlign);
334 IO.enumCase(
Value,
"Left", FormatStyle::ENAS_Left);
335 IO.enumCase(
Value,
"LeftWithLastLine", FormatStyle::ENAS_LeftWithLastLine);
336 IO.enumCase(
Value,
"Right", FormatStyle::ENAS_Right);
339 IO.enumCase(
Value,
"true", FormatStyle::ENAS_Left);
340 IO.enumCase(
Value,
"false", FormatStyle::ENAS_Right);
345struct ScalarEnumerationTraits<FormatStyle::EmptyLineAfterAccessModifierStyle> {
348 IO.enumCase(
Value,
"Never", FormatStyle::ELAAMS_Never);
349 IO.enumCase(
Value,
"Leave", FormatStyle::ELAAMS_Leave);
350 IO.enumCase(
Value,
"Always", FormatStyle::ELAAMS_Always);
355struct ScalarEnumerationTraits<
356 FormatStyle::EmptyLineBeforeAccessModifierStyle> {
359 IO.enumCase(
Value,
"Never", FormatStyle::ELBAMS_Never);
360 IO.enumCase(
Value,
"Leave", FormatStyle::ELBAMS_Leave);
361 IO.enumCase(
Value,
"LogicalBlock", FormatStyle::ELBAMS_LogicalBlock);
362 IO.enumCase(
Value,
"Always", FormatStyle::ELBAMS_Always);
367struct ScalarEnumerationTraits<FormatStyle::EnumTrailingCommaStyle> {
369 IO.enumCase(
Value,
"Leave", FormatStyle::ETC_Leave);
370 IO.enumCase(
Value,
"Insert", FormatStyle::ETC_Insert);
371 IO.enumCase(
Value,
"Remove", FormatStyle::ETC_Remove);
376struct ScalarEnumerationTraits<FormatStyle::IndentExternBlockStyle> {
378 IO.enumCase(
Value,
"AfterExternBlock", FormatStyle::IEBS_AfterExternBlock);
379 IO.enumCase(
Value,
"Indent", FormatStyle::IEBS_Indent);
380 IO.enumCase(
Value,
"NoIndent", FormatStyle::IEBS_NoIndent);
381 IO.enumCase(
Value,
"true", FormatStyle::IEBS_Indent);
382 IO.enumCase(
Value,
"false", FormatStyle::IEBS_NoIndent);
386template <>
struct MappingTraits<FormatStyle::IntegerLiteralSeparatorStyle> {
387 static void mapping(IO &IO, FormatStyle::IntegerLiteralSeparatorStyle &
Base) {
388 IO.mapOptional(
"Binary",
Base.Binary);
389 IO.mapOptional(
"BinaryMinDigits",
Base.BinaryMinDigits);
390 IO.mapOptional(
"Decimal",
Base.Decimal);
391 IO.mapOptional(
"DecimalMinDigits",
Base.DecimalMinDigits);
392 IO.mapOptional(
"Hex",
Base.Hex);
393 IO.mapOptional(
"HexMinDigits",
Base.HexMinDigits);
397template <>
struct ScalarEnumerationTraits<FormatStyle::JavaScriptQuoteStyle> {
399 IO.enumCase(
Value,
"Leave", FormatStyle::JSQS_Leave);
400 IO.enumCase(
Value,
"Single", FormatStyle::JSQS_Single);
401 IO.enumCase(
Value,
"Double", FormatStyle::JSQS_Double);
405template <>
struct MappingTraits<FormatStyle::KeepEmptyLinesStyle> {
407 IO.mapOptional(
"AtEndOfFile",
Value.AtEndOfFile);
408 IO.mapOptional(
"AtStartOfBlock",
Value.AtStartOfBlock);
409 IO.mapOptional(
"AtStartOfFile",
Value.AtStartOfFile);
413template <>
struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
415 IO.enumCase(
Value,
"C", FormatStyle::LK_C);
416 IO.enumCase(
Value,
"Cpp", FormatStyle::LK_Cpp);
417 IO.enumCase(
Value,
"Java", FormatStyle::LK_Java);
418 IO.enumCase(
Value,
"JavaScript", FormatStyle::LK_JavaScript);
419 IO.enumCase(
Value,
"ObjC", FormatStyle::LK_ObjC);
420 IO.enumCase(
Value,
"Proto", FormatStyle::LK_Proto);
421 IO.enumCase(
Value,
"TableGen", FormatStyle::LK_TableGen);
422 IO.enumCase(
Value,
"TextProto", FormatStyle::LK_TextProto);
423 IO.enumCase(
Value,
"CSharp", FormatStyle::LK_CSharp);
424 IO.enumCase(
Value,
"Json", FormatStyle::LK_Json);
425 IO.enumCase(
Value,
"Verilog", FormatStyle::LK_Verilog);
429template <>
struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
431 IO.enumCase(
Value,
"c++03", FormatStyle::LS_Cpp03);
432 IO.enumCase(
Value,
"C++03", FormatStyle::LS_Cpp03);
433 IO.enumCase(
Value,
"Cpp03", FormatStyle::LS_Cpp03);
435 IO.enumCase(
Value,
"c++11", FormatStyle::LS_Cpp11);
436 IO.enumCase(
Value,
"C++11", FormatStyle::LS_Cpp11);
438 IO.enumCase(
Value,
"c++14", FormatStyle::LS_Cpp14);
439 IO.enumCase(
Value,
"c++17", FormatStyle::LS_Cpp17);
440 IO.enumCase(
Value,
"c++20", FormatStyle::LS_Cpp20);
442 IO.enumCase(
Value,
"Latest", FormatStyle::LS_Latest);
443 IO.enumCase(
Value,
"Cpp11", FormatStyle::LS_Latest);
444 IO.enumCase(
Value,
"Auto", FormatStyle::LS_Auto);
449struct ScalarEnumerationTraits<FormatStyle::LambdaBodyIndentationKind> {
451 FormatStyle::LambdaBodyIndentationKind &
Value) {
452 IO.enumCase(
Value,
"Signature", FormatStyle::LBI_Signature);
453 IO.enumCase(
Value,
"OuterScope", FormatStyle::LBI_OuterScope);
457template <>
struct ScalarEnumerationTraits<FormatStyle::LineEndingStyle> {
459 IO.enumCase(
Value,
"LF", FormatStyle::LE_LF);
460 IO.enumCase(
Value,
"CRLF", FormatStyle::LE_CRLF);
461 IO.enumCase(
Value,
"DeriveLF", FormatStyle::LE_DeriveLF);
462 IO.enumCase(
Value,
"DeriveCRLF", FormatStyle::LE_DeriveCRLF);
467struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
469 FormatStyle::NamespaceIndentationKind &
Value) {
470 IO.enumCase(
Value,
"None", FormatStyle::NI_None);
471 IO.enumCase(
Value,
"Inner", FormatStyle::NI_Inner);
472 IO.enumCase(
Value,
"All", FormatStyle::NI_All);
477struct ScalarEnumerationTraits<FormatStyle::NumericLiteralComponentStyle> {
479 FormatStyle::NumericLiteralComponentStyle &
Value) {
480 IO.enumCase(
Value,
"Leave", FormatStyle::NLCS_Leave);
481 IO.enumCase(
Value,
"Upper", FormatStyle::NLCS_Upper);
482 IO.enumCase(
Value,
"Lower", FormatStyle::NLCS_Lower);
486template <>
struct MappingTraits<FormatStyle::NumericLiteralCaseStyle> {
487 static void mapping(IO &IO, FormatStyle::NumericLiteralCaseStyle &
Value) {
488 IO.mapOptional(
"ExponentLetter",
Value.ExponentLetter);
489 IO.mapOptional(
"HexDigit",
Value.HexDigit);
490 IO.mapOptional(
"Prefix",
Value.Prefix);
491 IO.mapOptional(
"Suffix",
Value.Suffix);
495template <>
struct ScalarEnumerationTraits<FormatStyle::OperandAlignmentStyle> {
497 IO.enumCase(
Value,
"DontAlign", FormatStyle::OAS_DontAlign);
498 IO.enumCase(
Value,
"Align", FormatStyle::OAS_Align);
499 IO.enumCase(
Value,
"AlignAfterOperator",
500 FormatStyle::OAS_AlignAfterOperator);
503 IO.enumCase(
Value,
"true", FormatStyle::OAS_Align);
504 IO.enumCase(
Value,
"false", FormatStyle::OAS_DontAlign);
509struct ScalarEnumerationTraits<FormatStyle::PackConstructorInitializersStyle> {
512 IO.enumCase(
Value,
"Never", FormatStyle::PCIS_Never);
513 IO.enumCase(
Value,
"BinPack", FormatStyle::PCIS_BinPack);
514 IO.enumCase(
Value,
"CurrentLine", FormatStyle::PCIS_CurrentLine);
515 IO.enumCase(
Value,
"NextLine", FormatStyle::PCIS_NextLine);
516 IO.enumCase(
Value,
"NextLineOnly", FormatStyle::PCIS_NextLineOnly);
520template <>
struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
522 IO.enumCase(
Value,
"Middle", FormatStyle::PAS_Middle);
523 IO.enumCase(
Value,
"Left", FormatStyle::PAS_Left);
524 IO.enumCase(
Value,
"Right", FormatStyle::PAS_Right);
527 IO.enumCase(
Value,
"true", FormatStyle::PAS_Left);
528 IO.enumCase(
Value,
"false", FormatStyle::PAS_Right);
533struct ScalarEnumerationTraits<FormatStyle::PPDirectiveIndentStyle> {
535 IO.enumCase(
Value,
"None", FormatStyle::PPDIS_None);
536 IO.enumCase(
Value,
"AfterHash", FormatStyle::PPDIS_AfterHash);
537 IO.enumCase(
Value,
"BeforeHash", FormatStyle::PPDIS_BeforeHash);
542struct ScalarEnumerationTraits<FormatStyle::QualifierAlignmentStyle> {
544 IO.enumCase(
Value,
"Leave", FormatStyle::QAS_Leave);
545 IO.enumCase(
Value,
"Left", FormatStyle::QAS_Left);
546 IO.enumCase(
Value,
"Right", FormatStyle::QAS_Right);
547 IO.enumCase(
Value,
"Custom", FormatStyle::QAS_Custom);
551template <>
struct MappingTraits<FormatStyle::RawStringFormat> {
552 static void mapping(IO &IO, FormatStyle::RawStringFormat &Format) {
553 IO.mapOptional(
"Language", Format.Language);
554 IO.mapOptional(
"Delimiters", Format.Delimiters);
555 IO.mapOptional(
"EnclosingFunctions", Format.EnclosingFunctions);
556 IO.mapOptional(
"CanonicalDelimiter", Format.CanonicalDelimiter);
557 IO.mapOptional(
"BasedOnStyle", Format.BasedOnStyle);
561template <>
struct ScalarEnumerationTraits<FormatStyle::ReflowCommentsStyle> {
563 IO.enumCase(
Value,
"Never", FormatStyle::RCS_Never);
564 IO.enumCase(
Value,
"IndentOnly", FormatStyle::RCS_IndentOnly);
565 IO.enumCase(
Value,
"Always", FormatStyle::RCS_Always);
567 IO.enumCase(
Value,
"false", FormatStyle::RCS_Never);
568 IO.enumCase(
Value,
"true", FormatStyle::RCS_Always);
573struct ScalarEnumerationTraits<FormatStyle::ReferenceAlignmentStyle> {
575 IO.enumCase(
Value,
"Pointer", FormatStyle::RAS_Pointer);
576 IO.enumCase(
Value,
"Middle", FormatStyle::RAS_Middle);
577 IO.enumCase(
Value,
"Left", FormatStyle::RAS_Left);
578 IO.enumCase(
Value,
"Right", FormatStyle::RAS_Right);
583struct ScalarEnumerationTraits<FormatStyle::RemoveParenthesesStyle> {
585 IO.enumCase(
Value,
"Leave", FormatStyle::RPS_Leave);
586 IO.enumCase(
Value,
"MultipleParentheses",
587 FormatStyle::RPS_MultipleParentheses);
588 IO.enumCase(
Value,
"ReturnStatement", FormatStyle::RPS_ReturnStatement);
593struct ScalarEnumerationTraits<FormatStyle::RequiresClausePositionStyle> {
595 FormatStyle::RequiresClausePositionStyle &
Value) {
596 IO.enumCase(
Value,
"OwnLine", FormatStyle::RCPS_OwnLine);
597 IO.enumCase(
Value,
"OwnLineWithBrace", FormatStyle::RCPS_OwnLineWithBrace);
598 IO.enumCase(
Value,
"WithPreceding", FormatStyle::RCPS_WithPreceding);
599 IO.enumCase(
Value,
"WithFollowing", FormatStyle::RCPS_WithFollowing);
600 IO.enumCase(
Value,
"SingleLine", FormatStyle::RCPS_SingleLine);
605struct ScalarEnumerationTraits<FormatStyle::RequiresExpressionIndentationKind> {
608 IO.enumCase(
Value,
"Keyword", FormatStyle::REI_Keyword);
609 IO.enumCase(
Value,
"OuterScope", FormatStyle::REI_OuterScope);
614struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
616 IO.enumCase(
Value,
"None", FormatStyle::RTBS_None);
617 IO.enumCase(
Value,
"Automatic", FormatStyle::RTBS_Automatic);
618 IO.enumCase(
Value,
"ExceptShortType", FormatStyle::RTBS_ExceptShortType);
619 IO.enumCase(
Value,
"All", FormatStyle::RTBS_All);
620 IO.enumCase(
Value,
"TopLevel", FormatStyle::RTBS_TopLevel);
621 IO.enumCase(
Value,
"TopLevelDefinitions",
622 FormatStyle::RTBS_TopLevelDefinitions);
623 IO.enumCase(
Value,
"AllDefinitions", FormatStyle::RTBS_AllDefinitions);
628struct ScalarEnumerationTraits<FormatStyle::SeparateDefinitionStyle> {
630 IO.enumCase(
Value,
"Leave", FormatStyle::SDS_Leave);
631 IO.enumCase(
Value,
"Always", FormatStyle::SDS_Always);
632 IO.enumCase(
Value,
"Never", FormatStyle::SDS_Never);
636template <>
struct ScalarEnumerationTraits<FormatStyle::ShortBlockStyle> {
638 IO.enumCase(
Value,
"Never", FormatStyle::SBS_Never);
639 IO.enumCase(
Value,
"false", FormatStyle::SBS_Never);
640 IO.enumCase(
Value,
"Always", FormatStyle::SBS_Always);
641 IO.enumCase(
Value,
"true", FormatStyle::SBS_Always);
642 IO.enumCase(
Value,
"Empty", FormatStyle::SBS_Empty);
646template <>
struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
648 IO.enumCase(
Value,
"None", FormatStyle::SFS_None);
649 IO.enumCase(
Value,
"false", FormatStyle::SFS_None);
650 IO.enumCase(
Value,
"All", FormatStyle::SFS_All);
651 IO.enumCase(
Value,
"true", FormatStyle::SFS_All);
652 IO.enumCase(
Value,
"Inline", FormatStyle::SFS_Inline);
653 IO.enumCase(
Value,
"InlineOnly", FormatStyle::SFS_InlineOnly);
654 IO.enumCase(
Value,
"Empty", FormatStyle::SFS_Empty);
658template <>
struct ScalarEnumerationTraits<FormatStyle::ShortIfStyle> {
660 IO.enumCase(
Value,
"Never", FormatStyle::SIS_Never);
661 IO.enumCase(
Value,
"WithoutElse", FormatStyle::SIS_WithoutElse);
662 IO.enumCase(
Value,
"OnlyFirstIf", FormatStyle::SIS_OnlyFirstIf);
663 IO.enumCase(
Value,
"AllIfsAndElse", FormatStyle::SIS_AllIfsAndElse);
666 IO.enumCase(
Value,
"Always", FormatStyle::SIS_OnlyFirstIf);
667 IO.enumCase(
Value,
"false", FormatStyle::SIS_Never);
668 IO.enumCase(
Value,
"true", FormatStyle::SIS_WithoutElse);
672template <>
struct ScalarEnumerationTraits<FormatStyle::ShortLambdaStyle> {
674 IO.enumCase(
Value,
"None", FormatStyle::SLS_None);
675 IO.enumCase(
Value,
"false", FormatStyle::SLS_None);
676 IO.enumCase(
Value,
"Empty", FormatStyle::SLS_Empty);
677 IO.enumCase(
Value,
"Inline", FormatStyle::SLS_Inline);
678 IO.enumCase(
Value,
"All", FormatStyle::SLS_All);
679 IO.enumCase(
Value,
"true", FormatStyle::SLS_All);
683template <>
struct MappingTraits<FormatStyle::SortIncludesOptions> {
685 IO.enumCase(
Value,
"Never", FormatStyle::SortIncludesOptions({}));
686 IO.enumCase(
Value,
"CaseInsensitive",
687 FormatStyle::SortIncludesOptions({
true,
690 IO.enumCase(
Value,
"CaseSensitive",
691 FormatStyle::SortIncludesOptions({
true,
696 IO.enumCase(
Value,
"false", FormatStyle::SortIncludesOptions({}));
697 IO.enumCase(
Value,
"true",
698 FormatStyle::SortIncludesOptions({
true,
704 IO.mapOptional(
"Enabled",
Value.Enabled);
705 IO.mapOptional(
"IgnoreCase",
Value.IgnoreCase);
706 IO.mapOptional(
"IgnoreExtension",
Value.IgnoreExtension);
711struct ScalarEnumerationTraits<FormatStyle::SortJavaStaticImportOptions> {
713 FormatStyle::SortJavaStaticImportOptions &
Value) {
714 IO.enumCase(
Value,
"Before", FormatStyle::SJSIO_Before);
715 IO.enumCase(
Value,
"After", FormatStyle::SJSIO_After);
720struct ScalarEnumerationTraits<FormatStyle::SortUsingDeclarationsOptions> {
722 FormatStyle::SortUsingDeclarationsOptions &
Value) {
723 IO.enumCase(
Value,
"Never", FormatStyle::SUD_Never);
724 IO.enumCase(
Value,
"Lexicographic", FormatStyle::SUD_Lexicographic);
725 IO.enumCase(
Value,
"LexicographicNumeric",
726 FormatStyle::SUD_LexicographicNumeric);
729 IO.enumCase(
Value,
"false", FormatStyle::SUD_Never);
730 IO.enumCase(
Value,
"true", FormatStyle::SUD_LexicographicNumeric);
735struct ScalarEnumerationTraits<FormatStyle::SpaceAroundPointerQualifiersStyle> {
738 IO.enumCase(
Value,
"Default", FormatStyle::SAPQ_Default);
739 IO.enumCase(
Value,
"Before", FormatStyle::SAPQ_Before);
740 IO.enumCase(
Value,
"After", FormatStyle::SAPQ_After);
741 IO.enumCase(
Value,
"Both", FormatStyle::SAPQ_Both);
745template <>
struct MappingTraits<FormatStyle::SpaceBeforeParensCustom> {
746 static void mapping(IO &IO, FormatStyle::SpaceBeforeParensCustom &Spacing) {
747 IO.mapOptional(
"AfterControlStatements", Spacing.AfterControlStatements);
748 IO.mapOptional(
"AfterForeachMacros", Spacing.AfterForeachMacros);
749 IO.mapOptional(
"AfterFunctionDefinitionName",
750 Spacing.AfterFunctionDefinitionName);
751 IO.mapOptional(
"AfterFunctionDeclarationName",
752 Spacing.AfterFunctionDeclarationName);
753 IO.mapOptional(
"AfterIfMacros", Spacing.AfterIfMacros);
754 IO.mapOptional(
"AfterNot", Spacing.AfterNot);
755 IO.mapOptional(
"AfterOverloadedOperator", Spacing.AfterOverloadedOperator);
756 IO.mapOptional(
"AfterPlacementOperator", Spacing.AfterPlacementOperator);
757 IO.mapOptional(
"AfterRequiresInClause", Spacing.AfterRequiresInClause);
758 IO.mapOptional(
"AfterRequiresInExpression",
759 Spacing.AfterRequiresInExpression);
760 IO.mapOptional(
"BeforeNonEmptyParentheses",
761 Spacing.BeforeNonEmptyParentheses);
766struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensStyle> {
768 IO.enumCase(
Value,
"Never", FormatStyle::SBPO_Never);
769 IO.enumCase(
Value,
"ControlStatements",
770 FormatStyle::SBPO_ControlStatements);
771 IO.enumCase(
Value,
"ControlStatementsExceptControlMacros",
772 FormatStyle::SBPO_ControlStatementsExceptControlMacros);
773 IO.enumCase(
Value,
"NonEmptyParentheses",
774 FormatStyle::SBPO_NonEmptyParentheses);
775 IO.enumCase(
Value,
"Always", FormatStyle::SBPO_Always);
776 IO.enumCase(
Value,
"Custom", FormatStyle::SBPO_Custom);
779 IO.enumCase(
Value,
"false", FormatStyle::SBPO_Never);
780 IO.enumCase(
Value,
"true", FormatStyle::SBPO_ControlStatements);
781 IO.enumCase(
Value,
"ControlStatementsExceptForEachMacros",
782 FormatStyle::SBPO_ControlStatementsExceptControlMacros);
787struct ScalarEnumerationTraits<FormatStyle::SpaceInEmptyBracesStyle> {
789 IO.enumCase(
Value,
"Always", FormatStyle::SIEB_Always);
790 IO.enumCase(
Value,
"Block", FormatStyle::SIEB_Block);
791 IO.enumCase(
Value,
"Never", FormatStyle::SIEB_Never);
795template <>
struct ScalarEnumerationTraits<FormatStyle::SpacesInAnglesStyle> {
797 IO.enumCase(
Value,
"Never", FormatStyle::SIAS_Never);
798 IO.enumCase(
Value,
"Always", FormatStyle::SIAS_Always);
799 IO.enumCase(
Value,
"Leave", FormatStyle::SIAS_Leave);
802 IO.enumCase(
Value,
"false", FormatStyle::SIAS_Never);
803 IO.enumCase(
Value,
"true", FormatStyle::SIAS_Always);
807template <>
struct MappingTraits<FormatStyle::SpacesInLineComment> {
808 static void mapping(IO &IO, FormatStyle::SpacesInLineComment &Space) {
810 int signedMaximum =
static_cast<int>(Space.Maximum);
811 IO.mapOptional(
"Minimum", Space.Minimum);
812 IO.mapOptional(
"Maximum", signedMaximum);
813 Space.Maximum =
static_cast<unsigned>(signedMaximum);
815 if (Space.Maximum < std::numeric_limits<unsigned>::max())
816 Space.Minimum = std::min(Space.Minimum, Space.Maximum);
820template <>
struct MappingTraits<FormatStyle::SpacesInParensCustom> {
821 static void mapping(IO &IO, FormatStyle::SpacesInParensCustom &Spaces) {
822 IO.mapOptional(
"ExceptDoubleParentheses", Spaces.ExceptDoubleParentheses);
823 IO.mapOptional(
"InCStyleCasts", Spaces.InCStyleCasts);
824 IO.mapOptional(
"InConditionalStatements", Spaces.InConditionalStatements);
825 IO.mapOptional(
"InEmptyParentheses", Spaces.InEmptyParentheses);
826 IO.mapOptional(
"Other", Spaces.Other);
830template <>
struct ScalarEnumerationTraits<FormatStyle::SpacesInParensStyle> {
832 IO.enumCase(
Value,
"Never", FormatStyle::SIPO_Never);
833 IO.enumCase(
Value,
"Custom", FormatStyle::SIPO_Custom);
837template <>
struct ScalarEnumerationTraits<FormatStyle::TrailingCommaStyle> {
839 IO.enumCase(
Value,
"None", FormatStyle::TCS_None);
840 IO.enumCase(
Value,
"Wrapped", FormatStyle::TCS_Wrapped);
845struct ScalarEnumerationTraits<FormatStyle::TrailingCommentsAlignmentKinds> {
847 FormatStyle::TrailingCommentsAlignmentKinds &
Value) {
848 IO.enumCase(
Value,
"Leave", FormatStyle::TCAS_Leave);
849 IO.enumCase(
Value,
"Always", FormatStyle::TCAS_Always);
850 IO.enumCase(
Value,
"Never", FormatStyle::TCAS_Never);
854template <>
struct MappingTraits<FormatStyle::TrailingCommentsAlignmentStyle> {
856 FormatStyle::TrailingCommentsAlignmentStyle &
Value) {
857 IO.enumCase(
Value,
"Leave",
858 FormatStyle::TrailingCommentsAlignmentStyle(
859 {FormatStyle::TCAS_Leave, 0}));
861 IO.enumCase(
Value,
"Always",
862 FormatStyle::TrailingCommentsAlignmentStyle(
863 {FormatStyle::TCAS_Always, 0}));
865 IO.enumCase(
Value,
"Never",
866 FormatStyle::TrailingCommentsAlignmentStyle(
867 {FormatStyle::TCAS_Never, 0}));
870 IO.enumCase(
Value,
"true",
871 FormatStyle::TrailingCommentsAlignmentStyle(
872 {FormatStyle::TCAS_Always, 0}));
873 IO.enumCase(
Value,
"false",
874 FormatStyle::TrailingCommentsAlignmentStyle(
875 {FormatStyle::TCAS_Never, 0}));
879 FormatStyle::TrailingCommentsAlignmentStyle &
Value) {
880 IO.mapOptional(
"Kind",
Value.Kind);
881 IO.mapOptional(
"OverEmptyLines",
Value.OverEmptyLines);
885template <>
struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
887 IO.enumCase(
Value,
"Never", FormatStyle::UT_Never);
888 IO.enumCase(
Value,
"false", FormatStyle::UT_Never);
889 IO.enumCase(
Value,
"Always", FormatStyle::UT_Always);
890 IO.enumCase(
Value,
"true", FormatStyle::UT_Always);
891 IO.enumCase(
Value,
"ForIndentation", FormatStyle::UT_ForIndentation);
892 IO.enumCase(
Value,
"ForContinuationAndIndentation",
893 FormatStyle::UT_ForContinuationAndIndentation);
894 IO.enumCase(
Value,
"AlignWithSpaces", FormatStyle::UT_AlignWithSpaces);
899struct ScalarEnumerationTraits<
900 FormatStyle::WrapNamespaceBodyWithEmptyLinesStyle> {
903 FormatStyle::WrapNamespaceBodyWithEmptyLinesStyle &
Value) {
904 IO.enumCase(
Value,
"Never", FormatStyle::WNBWELS_Never);
905 IO.enumCase(
Value,
"Always", FormatStyle::WNBWELS_Always);
906 IO.enumCase(
Value,
"Leave", FormatStyle::WNBWELS_Leave);
910template <>
struct MappingTraits<FormatStyle> {
911 static void mapping(IO &IO, FormatStyle &Style) {
913 IO.mapOptional(
"Language", Style.Language);
915 StringRef BasedOnStyle;
916 if (IO.outputting()) {
917 StringRef Styles[] = {
"LLVM",
"Google",
"Chromium",
"Mozilla",
918 "WebKit",
"GNU",
"Microsoft",
"clang-format"};
919 for (StringRef StyleName : Styles) {
920 FormatStyle PredefinedStyle;
922 Style == PredefinedStyle) {
923 BasedOnStyle = StyleName;
928 IO.mapOptional(
"BasedOnStyle", BasedOnStyle);
929 if (!BasedOnStyle.empty()) {
930 FormatStyle::LanguageKind OldLanguage = Style.Language;
931 FormatStyle::LanguageKind Language =
932 ((FormatStyle *)IO.getContext())->Language;
934 IO.setError(Twine(
"Unknown value for BasedOnStyle: ", BasedOnStyle));
937 Style.Language = OldLanguage;
952 const bool IsGoogleOrChromium = BasedOnStyle.equals_insensitive(
"google") ||
953 BasedOnStyle.equals_insensitive(
"chromium");
954 bool OnCurrentLine = IsGoogleOrChromium;
955 bool OnNextLine =
true;
957 bool BreakBeforeInheritanceComma =
false;
958 bool BreakConstructorInitializersBeforeComma =
false;
960 bool DeriveLineEnding =
true;
961 bool UseCRLF =
false;
963 bool SpaceInEmptyBlock =
false;
964 bool SpaceInEmptyParentheses =
false;
965 bool SpacesInConditionalStatement =
false;
966 bool SpacesInCStyleCastParentheses =
false;
967 bool SpacesInParentheses =
false;
970 if (!IO.outputting()) {
971 IO.mapOptional(
"AlignEscapedNewlinesLeft", Style.AlignEscapedNewlines);
972 IO.mapOptional(
"AllowAllConstructorInitializersOnNextLine", OnNextLine);
973 IO.mapOptional(
"AlwaysBreakAfterReturnType", Style.BreakAfterReturnType);
974 IO.mapOptional(
"AlwaysBreakTemplateDeclarations",
975 Style.BreakTemplateDeclarations);
976 IO.mapOptional(
"BreakBeforeInheritanceComma",
977 BreakBeforeInheritanceComma);
978 IO.mapOptional(
"BreakConstructorInitializersBeforeComma",
979 BreakConstructorInitializersBeforeComma);
980 IO.mapOptional(
"ConstructorInitializerAllOnOneLineOrOnePerLine",
982 IO.mapOptional(
"DeriveLineEnding", DeriveLineEnding);
983 IO.mapOptional(
"DerivePointerBinding", Style.DerivePointerAlignment);
984 IO.mapOptional(
"KeepEmptyLinesAtEOF", Style.KeepEmptyLines.AtEndOfFile);
985 IO.mapOptional(
"KeepEmptyLinesAtTheStartOfBlocks",
986 Style.KeepEmptyLines.AtStartOfBlock);
987 IO.mapOptional(
"IndentFunctionDeclarationAfterType",
988 Style.IndentWrappedFunctionNames);
989 IO.mapOptional(
"IndentRequires", Style.IndentRequiresClause);
990 IO.mapOptional(
"PointerBindsToType", Style.PointerAlignment);
991 IO.mapOptional(
"SpaceAfterControlStatementKeyword",
992 Style.SpaceBeforeParens);
993 IO.mapOptional(
"SpaceInEmptyBlock", SpaceInEmptyBlock);
994 IO.mapOptional(
"SpaceInEmptyParentheses", SpaceInEmptyParentheses);
995 IO.mapOptional(
"SpacesInConditionalStatement",
996 SpacesInConditionalStatement);
997 IO.mapOptional(
"SpacesInCStyleCastParentheses",
998 SpacesInCStyleCastParentheses);
999 IO.mapOptional(
"SpacesInParentheses", SpacesInParentheses);
1000 IO.mapOptional(
"UseCRLF", UseCRLF);
1003 IO.mapOptional(
"AccessModifierOffset", Style.AccessModifierOffset);
1004 IO.mapOptional(
"AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
1005 IO.mapOptional(
"AlignArrayOfStructures", Style.AlignArrayOfStructures);
1006 IO.mapOptional(
"AlignConsecutiveAssignments",
1007 Style.AlignConsecutiveAssignments);
1008 IO.mapOptional(
"AlignConsecutiveBitFields",
1009 Style.AlignConsecutiveBitFields);
1010 IO.mapOptional(
"AlignConsecutiveDeclarations",
1011 Style.AlignConsecutiveDeclarations);
1012 IO.mapOptional(
"AlignConsecutiveMacros", Style.AlignConsecutiveMacros);
1013 IO.mapOptional(
"AlignConsecutiveShortCaseStatements",
1014 Style.AlignConsecutiveShortCaseStatements);
1015 IO.mapOptional(
"AlignConsecutiveTableGenBreakingDAGArgColons",
1016 Style.AlignConsecutiveTableGenBreakingDAGArgColons);
1017 IO.mapOptional(
"AlignConsecutiveTableGenCondOperatorColons",
1018 Style.AlignConsecutiveTableGenCondOperatorColons);
1019 IO.mapOptional(
"AlignConsecutiveTableGenDefinitionColons",
1020 Style.AlignConsecutiveTableGenDefinitionColons);
1021 IO.mapOptional(
"AlignEscapedNewlines", Style.AlignEscapedNewlines);
1022 IO.mapOptional(
"AlignOperands", Style.AlignOperands);
1023 IO.mapOptional(
"AlignTrailingComments", Style.AlignTrailingComments);
1024 IO.mapOptional(
"AllowAllArgumentsOnNextLine",
1025 Style.AllowAllArgumentsOnNextLine);
1026 IO.mapOptional(
"AllowAllParametersOfDeclarationOnNextLine",
1027 Style.AllowAllParametersOfDeclarationOnNextLine);
1028 IO.mapOptional(
"AllowBreakBeforeNoexceptSpecifier",
1029 Style.AllowBreakBeforeNoexceptSpecifier);
1030 IO.mapOptional(
"AllowShortBlocksOnASingleLine",
1031 Style.AllowShortBlocksOnASingleLine);
1032 IO.mapOptional(
"AllowShortCaseExpressionOnASingleLine",
1033 Style.AllowShortCaseExpressionOnASingleLine);
1034 IO.mapOptional(
"AllowShortCaseLabelsOnASingleLine",
1035 Style.AllowShortCaseLabelsOnASingleLine);
1036 IO.mapOptional(
"AllowShortCompoundRequirementOnASingleLine",
1037 Style.AllowShortCompoundRequirementOnASingleLine);
1038 IO.mapOptional(
"AllowShortEnumsOnASingleLine",
1039 Style.AllowShortEnumsOnASingleLine);
1040 IO.mapOptional(
"AllowShortFunctionsOnASingleLine",
1041 Style.AllowShortFunctionsOnASingleLine);
1042 IO.mapOptional(
"AllowShortIfStatementsOnASingleLine",
1043 Style.AllowShortIfStatementsOnASingleLine);
1044 IO.mapOptional(
"AllowShortLambdasOnASingleLine",
1045 Style.AllowShortLambdasOnASingleLine);
1046 IO.mapOptional(
"AllowShortLoopsOnASingleLine",
1047 Style.AllowShortLoopsOnASingleLine);
1048 IO.mapOptional(
"AllowShortNamespacesOnASingleLine",
1049 Style.AllowShortNamespacesOnASingleLine);
1050 IO.mapOptional(
"AlwaysBreakAfterDefinitionReturnType",
1051 Style.AlwaysBreakAfterDefinitionReturnType);
1052 IO.mapOptional(
"AlwaysBreakBeforeMultilineStrings",
1053 Style.AlwaysBreakBeforeMultilineStrings);
1054 IO.mapOptional(
"AttributeMacros", Style.AttributeMacros);
1055 IO.mapOptional(
"BinPackArguments", Style.BinPackArguments);
1056 IO.mapOptional(
"BinPackLongBracedList", Style.BinPackLongBracedList);
1057 IO.mapOptional(
"BinPackParameters", Style.BinPackParameters);
1058 IO.mapOptional(
"BitFieldColonSpacing", Style.BitFieldColonSpacing);
1059 IO.mapOptional(
"BracedInitializerIndentWidth",
1060 Style.BracedInitializerIndentWidth);
1061 IO.mapOptional(
"BraceWrapping", Style.BraceWrapping);
1062 IO.mapOptional(
"BreakAdjacentStringLiterals",
1063 Style.BreakAdjacentStringLiterals);
1064 IO.mapOptional(
"BreakAfterAttributes", Style.BreakAfterAttributes);
1065 IO.mapOptional(
"BreakAfterJavaFieldAnnotations",
1066 Style.BreakAfterJavaFieldAnnotations);
1067 IO.mapOptional(
"BreakAfterReturnType", Style.BreakAfterReturnType);
1068 IO.mapOptional(
"BreakArrays", Style.BreakArrays);
1069 IO.mapOptional(
"BreakBeforeBinaryOperators",
1070 Style.BreakBeforeBinaryOperators);
1071 IO.mapOptional(
"BreakBeforeConceptDeclarations",
1072 Style.BreakBeforeConceptDeclarations);
1073 IO.mapOptional(
"BreakBeforeBraces", Style.BreakBeforeBraces);
1074 IO.mapOptional(
"BreakBeforeInlineASMColon",
1075 Style.BreakBeforeInlineASMColon);
1076 IO.mapOptional(
"BreakBeforeTemplateCloser",
1077 Style.BreakBeforeTemplateCloser);
1078 IO.mapOptional(
"BreakBeforeTernaryOperators",
1079 Style.BreakBeforeTernaryOperators);
1080 IO.mapOptional(
"BreakBinaryOperations", Style.BreakBinaryOperations);
1081 IO.mapOptional(
"BreakConstructorInitializers",
1082 Style.BreakConstructorInitializers);
1083 IO.mapOptional(
"BreakFunctionDefinitionParameters",
1084 Style.BreakFunctionDefinitionParameters);
1085 IO.mapOptional(
"BreakInheritanceList", Style.BreakInheritanceList);
1086 IO.mapOptional(
"BreakStringLiterals", Style.BreakStringLiterals);
1087 IO.mapOptional(
"BreakTemplateDeclarations",
1088 Style.BreakTemplateDeclarations);
1089 IO.mapOptional(
"ColumnLimit", Style.ColumnLimit);
1090 IO.mapOptional(
"CommentPragmas", Style.CommentPragmas);
1091 IO.mapOptional(
"CompactNamespaces", Style.CompactNamespaces);
1092 IO.mapOptional(
"ConstructorInitializerIndentWidth",
1093 Style.ConstructorInitializerIndentWidth);
1094 IO.mapOptional(
"ContinuationIndentWidth", Style.ContinuationIndentWidth);
1095 IO.mapOptional(
"Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
1096 IO.mapOptional(
"DerivePointerAlignment", Style.DerivePointerAlignment);
1097 IO.mapOptional(
"DisableFormat", Style.DisableFormat);
1098 IO.mapOptional(
"EmptyLineAfterAccessModifier",
1099 Style.EmptyLineAfterAccessModifier);
1100 IO.mapOptional(
"EmptyLineBeforeAccessModifier",
1101 Style.EmptyLineBeforeAccessModifier);
1102 IO.mapOptional(
"EnumTrailingComma", Style.EnumTrailingComma);
1103 IO.mapOptional(
"ExperimentalAutoDetectBinPacking",
1104 Style.ExperimentalAutoDetectBinPacking);
1105 IO.mapOptional(
"FixNamespaceComments", Style.FixNamespaceComments);
1106 IO.mapOptional(
"ForEachMacros", Style.ForEachMacros);
1107 IO.mapOptional(
"IfMacros", Style.IfMacros);
1108 IO.mapOptional(
"IncludeBlocks", Style.IncludeStyle.IncludeBlocks);
1109 IO.mapOptional(
"IncludeCategories", Style.IncludeStyle.IncludeCategories);
1110 IO.mapOptional(
"IncludeIsMainRegex", Style.IncludeStyle.IncludeIsMainRegex);
1111 IO.mapOptional(
"IncludeIsMainSourceRegex",
1112 Style.IncludeStyle.IncludeIsMainSourceRegex);
1113 IO.mapOptional(
"IndentAccessModifiers", Style.IndentAccessModifiers);
1114 IO.mapOptional(
"IndentCaseBlocks", Style.IndentCaseBlocks);
1115 IO.mapOptional(
"IndentCaseLabels", Style.IndentCaseLabels);
1116 IO.mapOptional(
"IndentExportBlock", Style.IndentExportBlock);
1117 IO.mapOptional(
"IndentExternBlock", Style.IndentExternBlock);
1118 IO.mapOptional(
"IndentGotoLabels", Style.IndentGotoLabels);
1119 IO.mapOptional(
"IndentPPDirectives", Style.IndentPPDirectives);
1120 IO.mapOptional(
"IndentRequiresClause", Style.IndentRequiresClause);
1121 IO.mapOptional(
"IndentWidth", Style.IndentWidth);
1122 IO.mapOptional(
"IndentWrappedFunctionNames",
1123 Style.IndentWrappedFunctionNames);
1124 IO.mapOptional(
"InsertBraces", Style.InsertBraces);
1125 IO.mapOptional(
"InsertNewlineAtEOF", Style.InsertNewlineAtEOF);
1126 IO.mapOptional(
"InsertTrailingCommas", Style.InsertTrailingCommas);
1127 IO.mapOptional(
"IntegerLiteralSeparator", Style.IntegerLiteralSeparator);
1128 IO.mapOptional(
"JavaImportGroups", Style.JavaImportGroups);
1129 IO.mapOptional(
"JavaScriptQuotes", Style.JavaScriptQuotes);
1130 IO.mapOptional(
"JavaScriptWrapImports", Style.JavaScriptWrapImports);
1131 IO.mapOptional(
"KeepEmptyLines", Style.KeepEmptyLines);
1132 IO.mapOptional(
"KeepFormFeed", Style.KeepFormFeed);
1133 IO.mapOptional(
"LambdaBodyIndentation", Style.LambdaBodyIndentation);
1134 IO.mapOptional(
"LineEnding", Style.LineEnding);
1135 IO.mapOptional(
"MacroBlockBegin", Style.MacroBlockBegin);
1136 IO.mapOptional(
"MacroBlockEnd", Style.MacroBlockEnd);
1137 IO.mapOptional(
"Macros", Style.Macros);
1138 IO.mapOptional(
"MacrosSkippedByRemoveParentheses",
1139 Style.MacrosSkippedByRemoveParentheses);
1140 IO.mapOptional(
"MainIncludeChar", Style.IncludeStyle.MainIncludeChar);
1141 IO.mapOptional(
"MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
1142 IO.mapOptional(
"NamespaceIndentation", Style.NamespaceIndentation);
1143 IO.mapOptional(
"NamespaceMacros", Style.NamespaceMacros);
1144 IO.mapOptional(
"NumericLiteralCase", Style.NumericLiteralCase);
1145 IO.mapOptional(
"ObjCBinPackProtocolList", Style.ObjCBinPackProtocolList);
1146 IO.mapOptional(
"ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
1147 IO.mapOptional(
"ObjCBreakBeforeNestedBlockParam",
1148 Style.ObjCBreakBeforeNestedBlockParam);
1149 IO.mapOptional(
"ObjCPropertyAttributeOrder",
1150 Style.ObjCPropertyAttributeOrder);
1151 IO.mapOptional(
"ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
1152 IO.mapOptional(
"ObjCSpaceBeforeProtocolList",
1153 Style.ObjCSpaceBeforeProtocolList);
1154 IO.mapOptional(
"OneLineFormatOffRegex", Style.OneLineFormatOffRegex);
1155 IO.mapOptional(
"PackConstructorInitializers",
1156 Style.PackConstructorInitializers);
1157 IO.mapOptional(
"PenaltyBreakAssignment", Style.PenaltyBreakAssignment);
1158 IO.mapOptional(
"PenaltyBreakBeforeFirstCallParameter",
1159 Style.PenaltyBreakBeforeFirstCallParameter);
1160 IO.mapOptional(
"PenaltyBreakBeforeMemberAccess",
1161 Style.PenaltyBreakBeforeMemberAccess);
1162 IO.mapOptional(
"PenaltyBreakComment", Style.PenaltyBreakComment);
1163 IO.mapOptional(
"PenaltyBreakFirstLessLess",
1164 Style.PenaltyBreakFirstLessLess);
1165 IO.mapOptional(
"PenaltyBreakOpenParenthesis",
1166 Style.PenaltyBreakOpenParenthesis);
1167 IO.mapOptional(
"PenaltyBreakScopeResolution",
1168 Style.PenaltyBreakScopeResolution);
1169 IO.mapOptional(
"PenaltyBreakString", Style.PenaltyBreakString);
1170 IO.mapOptional(
"PenaltyBreakTemplateDeclaration",
1171 Style.PenaltyBreakTemplateDeclaration);
1172 IO.mapOptional(
"PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
1173 IO.mapOptional(
"PenaltyIndentedWhitespace",
1174 Style.PenaltyIndentedWhitespace);
1175 IO.mapOptional(
"PenaltyReturnTypeOnItsOwnLine",
1176 Style.PenaltyReturnTypeOnItsOwnLine);
1177 IO.mapOptional(
"PointerAlignment", Style.PointerAlignment);
1178 IO.mapOptional(
"PPIndentWidth", Style.PPIndentWidth);
1179 IO.mapOptional(
"QualifierAlignment", Style.QualifierAlignment);
1181 if (Style.QualifierAlignment == FormatStyle::QAS_Right)
1182 Style.QualifierOrder = {
"type",
"const",
"volatile"};
1183 else if (Style.QualifierAlignment == FormatStyle::QAS_Left)
1184 Style.QualifierOrder = {
"const",
"volatile",
"type"};
1185 else if (Style.QualifierAlignment == FormatStyle::QAS_Custom)
1186 IO.mapOptional(
"QualifierOrder", Style.QualifierOrder);
1187 IO.mapOptional(
"RawStringFormats", Style.RawStringFormats);
1188 IO.mapOptional(
"ReferenceAlignment", Style.ReferenceAlignment);
1189 IO.mapOptional(
"ReflowComments", Style.ReflowComments);
1190 IO.mapOptional(
"RemoveBracesLLVM", Style.RemoveBracesLLVM);
1191 IO.mapOptional(
"RemoveEmptyLinesInUnwrappedLines",
1192 Style.RemoveEmptyLinesInUnwrappedLines);
1193 IO.mapOptional(
"RemoveParentheses", Style.RemoveParentheses);
1194 IO.mapOptional(
"RemoveSemicolon", Style.RemoveSemicolon);
1195 IO.mapOptional(
"RequiresClausePosition", Style.RequiresClausePosition);
1196 IO.mapOptional(
"RequiresExpressionIndentation",
1197 Style.RequiresExpressionIndentation);
1198 IO.mapOptional(
"SeparateDefinitionBlocks", Style.SeparateDefinitionBlocks);
1199 IO.mapOptional(
"ShortNamespaceLines", Style.ShortNamespaceLines);
1200 IO.mapOptional(
"SkipMacroDefinitionBody", Style.SkipMacroDefinitionBody);
1201 IO.mapOptional(
"SortIncludes", Style.SortIncludes);
1202 IO.mapOptional(
"SortJavaStaticImport", Style.SortJavaStaticImport);
1203 IO.mapOptional(
"SortUsingDeclarations", Style.SortUsingDeclarations);
1204 IO.mapOptional(
"SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
1205 IO.mapOptional(
"SpaceAfterLogicalNot", Style.SpaceAfterLogicalNot);
1206 IO.mapOptional(
"SpaceAfterOperatorKeyword",
1207 Style.SpaceAfterOperatorKeyword);
1208 IO.mapOptional(
"SpaceAfterTemplateKeyword",
1209 Style.SpaceAfterTemplateKeyword);
1210 IO.mapOptional(
"SpaceAroundPointerQualifiers",
1211 Style.SpaceAroundPointerQualifiers);
1212 IO.mapOptional(
"SpaceBeforeAssignmentOperators",
1213 Style.SpaceBeforeAssignmentOperators);
1214 IO.mapOptional(
"SpaceBeforeCaseColon", Style.SpaceBeforeCaseColon);
1215 IO.mapOptional(
"SpaceBeforeCpp11BracedList",
1216 Style.SpaceBeforeCpp11BracedList);
1217 IO.mapOptional(
"SpaceBeforeCtorInitializerColon",
1218 Style.SpaceBeforeCtorInitializerColon);
1219 IO.mapOptional(
"SpaceBeforeInheritanceColon",
1220 Style.SpaceBeforeInheritanceColon);
1221 IO.mapOptional(
"SpaceBeforeJsonColon", Style.SpaceBeforeJsonColon);
1222 IO.mapOptional(
"SpaceBeforeParens", Style.SpaceBeforeParens);
1223 IO.mapOptional(
"SpaceBeforeParensOptions", Style.SpaceBeforeParensOptions);
1224 IO.mapOptional(
"SpaceBeforeRangeBasedForLoopColon",
1225 Style.SpaceBeforeRangeBasedForLoopColon);
1226 IO.mapOptional(
"SpaceBeforeSquareBrackets",
1227 Style.SpaceBeforeSquareBrackets);
1228 IO.mapOptional(
"SpaceInEmptyBraces", Style.SpaceInEmptyBraces);
1229 IO.mapOptional(
"SpacesBeforeTrailingComments",
1230 Style.SpacesBeforeTrailingComments);
1231 IO.mapOptional(
"SpacesInAngles", Style.SpacesInAngles);
1232 IO.mapOptional(
"SpacesInContainerLiterals",
1233 Style.SpacesInContainerLiterals);
1234 IO.mapOptional(
"SpacesInLineCommentPrefix",
1235 Style.SpacesInLineCommentPrefix);
1236 IO.mapOptional(
"SpacesInParens", Style.SpacesInParens);
1237 IO.mapOptional(
"SpacesInParensOptions", Style.SpacesInParensOptions);
1238 IO.mapOptional(
"SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
1239 IO.mapOptional(
"Standard", Style.Standard);
1240 IO.mapOptional(
"StatementAttributeLikeMacros",
1241 Style.StatementAttributeLikeMacros);
1242 IO.mapOptional(
"StatementMacros", Style.StatementMacros);
1243 IO.mapOptional(
"TableGenBreakingDAGArgOperators",
1244 Style.TableGenBreakingDAGArgOperators);
1245 IO.mapOptional(
"TableGenBreakInsideDAGArg",
1246 Style.TableGenBreakInsideDAGArg);
1247 IO.mapOptional(
"TabWidth", Style.TabWidth);
1248 IO.mapOptional(
"TemplateNames", Style.TemplateNames);
1249 IO.mapOptional(
"TypeNames", Style.TypeNames);
1250 IO.mapOptional(
"TypenameMacros", Style.TypenameMacros);
1251 IO.mapOptional(
"UseTab", Style.UseTab);
1252 IO.mapOptional(
"VariableTemplates", Style.VariableTemplates);
1253 IO.mapOptional(
"VerilogBreakBetweenInstancePorts",
1254 Style.VerilogBreakBetweenInstancePorts);
1255 IO.mapOptional(
"WhitespaceSensitiveMacros",
1256 Style.WhitespaceSensitiveMacros);
1257 IO.mapOptional(
"WrapNamespaceBodyWithEmptyLines",
1258 Style.WrapNamespaceBodyWithEmptyLines);
1263 if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
1264 Style.BreakAfterReturnType == FormatStyle::RTBS_None) {
1265 if (Style.AlwaysBreakAfterDefinitionReturnType ==
1266 FormatStyle::DRTBS_All) {
1267 Style.BreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
1268 }
else if (Style.AlwaysBreakAfterDefinitionReturnType ==
1269 FormatStyle::DRTBS_TopLevel) {
1270 Style.BreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
1276 if (BreakBeforeInheritanceComma &&
1277 Style.BreakInheritanceList == FormatStyle::BILS_BeforeColon) {
1278 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
1284 if (BreakConstructorInitializersBeforeComma &&
1285 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon) {
1286 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
1289 if (!IsGoogleOrChromium) {
1290 if (Style.PackConstructorInitializers == FormatStyle::PCIS_BinPack &&
1292 Style.PackConstructorInitializers = OnNextLine
1293 ? FormatStyle::PCIS_NextLine
1294 : FormatStyle::PCIS_CurrentLine;
1296 }
else if (Style.PackConstructorInitializers ==
1297 FormatStyle::PCIS_NextLine) {
1299 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
1300 else if (!OnNextLine)
1301 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
1304 if (Style.LineEnding == FormatStyle::LE_DeriveLF) {
1305 if (!DeriveLineEnding)
1306 Style.LineEnding = UseCRLF ? FormatStyle::LE_CRLF : FormatStyle::LE_LF;
1308 Style.LineEnding = FormatStyle::LE_DeriveCRLF;
1313 if (SpaceInEmptyBlock &&
1314 Style.SpaceInEmptyBraces == FormatStyle::SIEB_Never) {
1315 Style.SpaceInEmptyBraces = FormatStyle::SIEB_Block;
1318 if (Style.SpacesInParens != FormatStyle::SIPO_Custom &&
1319 (SpacesInParentheses || SpaceInEmptyParentheses ||
1320 SpacesInConditionalStatement || SpacesInCStyleCastParentheses)) {
1321 if (SpacesInParentheses) {
1323 Style.SpacesInParensOptions.ExceptDoubleParentheses =
false;
1324 Style.SpacesInParensOptions.InConditionalStatements =
true;
1325 Style.SpacesInParensOptions.InCStyleCasts =
1326 SpacesInCStyleCastParentheses;
1327 Style.SpacesInParensOptions.InEmptyParentheses =
1328 SpaceInEmptyParentheses;
1329 Style.SpacesInParensOptions.Other =
true;
1331 Style.SpacesInParensOptions = {};
1332 Style.SpacesInParensOptions.InConditionalStatements =
1333 SpacesInConditionalStatement;
1334 Style.SpacesInParensOptions.InCStyleCasts =
1335 SpacesInCStyleCastParentheses;
1336 Style.SpacesInParensOptions.InEmptyParentheses =
1337 SpaceInEmptyParentheses;
1339 Style.SpacesInParens = FormatStyle::SIPO_Custom;
1349template <>
struct DocumentListTraits<
std::vector<FormatStyle>> {
1350 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
1353 static FormatStyle &
element(IO &IO, std::vector<FormatStyle> &Seq,
1355 if (Index >= Seq.size()) {
1356 assert(Index == Seq.size());
1357 FormatStyle Template;
1358 if (!Seq.empty() && Seq[0].Language == FormatStyle::LK_None) {
1361 Template = *((
const FormatStyle *)IO.getContext());
1362 Template.Language = FormatStyle::LK_None;
1364 Seq.resize(Index + 1, Template);
1384 return llvm::make_error<llvm::StringError>(Message,
1385 llvm::inconvertibleErrorCode());
1389 return "clang-format.parse_error";
1397 return "Invalid argument";
1399 return "Unsuitable";
1401 return "trailing comma insertion cannot be used with bin packing";
1403 return "Invalid qualifier specified in QualifierOrder";
1405 return "Duplicate qualifier specified in QualifierOrder";
1407 return "Missing type in QualifierOrder";
1409 return "Missing QualifierOrder";
1411 llvm_unreachable(
"unexpected parse error");
1415 if (Expanded.BreakBeforeBraces == FormatStyle::BS_Custom)
1417 Expanded.BraceWrapping = {
false,
1419 FormatStyle::BWACS_Never,
1435 switch (Expanded.BreakBeforeBraces) {
1436 case FormatStyle::BS_Linux:
1437 Expanded.BraceWrapping.AfterClass =
true;
1438 Expanded.BraceWrapping.AfterFunction =
true;
1439 Expanded.BraceWrapping.AfterNamespace =
true;
1441 case FormatStyle::BS_Mozilla:
1442 Expanded.BraceWrapping.AfterClass =
true;
1443 Expanded.BraceWrapping.AfterEnum =
true;
1444 Expanded.BraceWrapping.AfterFunction =
true;
1445 Expanded.BraceWrapping.AfterStruct =
true;
1446 Expanded.BraceWrapping.AfterUnion =
true;
1447 Expanded.BraceWrapping.AfterExternBlock =
true;
1448 Expanded.BraceWrapping.SplitEmptyFunction =
true;
1449 Expanded.BraceWrapping.SplitEmptyRecord =
false;
1451 case FormatStyle::BS_Stroustrup:
1452 Expanded.BraceWrapping.AfterFunction =
true;
1453 Expanded.BraceWrapping.BeforeCatch =
true;
1454 Expanded.BraceWrapping.BeforeElse =
true;
1456 case FormatStyle::BS_Allman:
1457 Expanded.BraceWrapping.AfterCaseLabel =
true;
1458 Expanded.BraceWrapping.AfterClass =
true;
1459 Expanded.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1460 Expanded.BraceWrapping.AfterEnum =
true;
1461 Expanded.BraceWrapping.AfterFunction =
true;
1462 Expanded.BraceWrapping.AfterNamespace =
true;
1463 Expanded.BraceWrapping.AfterObjCDeclaration =
true;
1464 Expanded.BraceWrapping.AfterStruct =
true;
1465 Expanded.BraceWrapping.AfterUnion =
true;
1466 Expanded.BraceWrapping.AfterExternBlock =
true;
1467 Expanded.BraceWrapping.BeforeCatch =
true;
1468 Expanded.BraceWrapping.BeforeElse =
true;
1469 Expanded.BraceWrapping.BeforeLambdaBody =
true;
1471 case FormatStyle::BS_Whitesmiths:
1472 Expanded.BraceWrapping.AfterCaseLabel =
true;
1473 Expanded.BraceWrapping.AfterClass =
true;
1474 Expanded.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1475 Expanded.BraceWrapping.AfterEnum =
true;
1476 Expanded.BraceWrapping.AfterFunction =
true;
1477 Expanded.BraceWrapping.AfterNamespace =
true;
1478 Expanded.BraceWrapping.AfterObjCDeclaration =
true;
1479 Expanded.BraceWrapping.AfterStruct =
true;
1480 Expanded.BraceWrapping.AfterExternBlock =
true;
1481 Expanded.BraceWrapping.BeforeCatch =
true;
1482 Expanded.BraceWrapping.BeforeElse =
true;
1483 Expanded.BraceWrapping.BeforeLambdaBody =
true;
1485 case FormatStyle::BS_GNU:
1486 Expanded.BraceWrapping = {
1489 FormatStyle::BWACS_Always,
1506 case FormatStyle::BS_WebKit:
1507 Expanded.BraceWrapping.AfterFunction =
true;
1515 if (Expanded.SpaceBeforeParens == FormatStyle::SBPO_Custom)
1518 Expanded.SpaceBeforeParensOptions = {};
1519 Expanded.SpaceBeforeParensOptions.AfterPlacementOperator =
true;
1521 switch (Expanded.SpaceBeforeParens) {
1522 case FormatStyle::SBPO_ControlStatements:
1523 Expanded.SpaceBeforeParensOptions.AfterControlStatements =
true;
1524 Expanded.SpaceBeforeParensOptions.AfterForeachMacros =
true;
1525 Expanded.SpaceBeforeParensOptions.AfterIfMacros =
true;
1527 case FormatStyle::SBPO_ControlStatementsExceptControlMacros:
1528 Expanded.SpaceBeforeParensOptions.AfterControlStatements =
true;
1530 case FormatStyle::SBPO_NonEmptyParentheses:
1531 Expanded.SpaceBeforeParensOptions.BeforeNonEmptyParentheses =
true;
1539 if (Expanded.SpacesInParens == FormatStyle::SIPO_Custom)
1541 assert(Expanded.SpacesInParens == FormatStyle::SIPO_Never);
1543 Expanded.SpacesInParensOptions = {};
1547 FormatStyle LLVMStyle;
1548 LLVMStyle.AccessModifierOffset = -2;
1549 LLVMStyle.AlignAfterOpenBracket = FormatStyle::BAS_Align;
1550 LLVMStyle.AlignArrayOfStructures = FormatStyle::AIAS_None;
1551 LLVMStyle.AlignConsecutiveAssignments = {};
1552 LLVMStyle.AlignConsecutiveAssignments.PadOperators =
true;
1553 LLVMStyle.AlignConsecutiveBitFields = {};
1554 LLVMStyle.AlignConsecutiveDeclarations = {};
1555 LLVMStyle.AlignConsecutiveDeclarations.AlignFunctionDeclarations =
true;
1556 LLVMStyle.AlignConsecutiveMacros = {};
1557 LLVMStyle.AlignConsecutiveShortCaseStatements = {};
1558 LLVMStyle.AlignConsecutiveTableGenBreakingDAGArgColons = {};
1559 LLVMStyle.AlignConsecutiveTableGenCondOperatorColons = {};
1560 LLVMStyle.AlignConsecutiveTableGenDefinitionColons = {};
1561 LLVMStyle.AlignEscapedNewlines = FormatStyle::ENAS_Right;
1562 LLVMStyle.AlignOperands = FormatStyle::OAS_Align;
1563 LLVMStyle.AlignTrailingComments = {};
1564 LLVMStyle.AlignTrailingComments.Kind = FormatStyle::TCAS_Always;
1565 LLVMStyle.AlignTrailingComments.OverEmptyLines = 0;
1566 LLVMStyle.AllowAllArgumentsOnNextLine =
true;
1567 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine =
true;
1568 LLVMStyle.AllowBreakBeforeNoexceptSpecifier = FormatStyle::BBNSS_Never;
1569 LLVMStyle.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
1570 LLVMStyle.AllowShortCaseExpressionOnASingleLine =
true;
1571 LLVMStyle.AllowShortCaseLabelsOnASingleLine =
false;
1572 LLVMStyle.AllowShortCompoundRequirementOnASingleLine =
true;
1573 LLVMStyle.AllowShortEnumsOnASingleLine =
true;
1574 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
1575 LLVMStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
1576 LLVMStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
1577 LLVMStyle.AllowShortLoopsOnASingleLine =
false;
1578 LLVMStyle.AllowShortNamespacesOnASingleLine =
false;
1579 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
1580 LLVMStyle.AlwaysBreakBeforeMultilineStrings =
false;
1581 LLVMStyle.AttributeMacros.push_back(
"__capability");
1582 LLVMStyle.BinPackArguments =
true;
1583 LLVMStyle.BinPackLongBracedList =
true;
1584 LLVMStyle.BinPackParameters = FormatStyle::BPPS_BinPack;
1585 LLVMStyle.BitFieldColonSpacing = FormatStyle::BFCS_Both;
1586 LLVMStyle.BracedInitializerIndentWidth = -1;
1587 LLVMStyle.BraceWrapping = {
false,
1589 FormatStyle::BWACS_Never,
1605 LLVMStyle.BreakAdjacentStringLiterals =
true;
1606 LLVMStyle.BreakAfterAttributes = FormatStyle::ABS_Leave;
1607 LLVMStyle.BreakAfterJavaFieldAnnotations =
false;
1608 LLVMStyle.BreakAfterReturnType = FormatStyle::RTBS_None;
1609 LLVMStyle.BreakArrays =
true;
1610 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
1611 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
1612 LLVMStyle.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Always;
1613 LLVMStyle.BreakBeforeInlineASMColon = FormatStyle::BBIAS_OnlyMultiline;
1614 LLVMStyle.BreakBeforeTemplateCloser =
false;
1615 LLVMStyle.BreakBeforeTernaryOperators =
true;
1616 LLVMStyle.BreakBinaryOperations = FormatStyle::BBO_Never;
1617 LLVMStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
1618 LLVMStyle.BreakFunctionDefinitionParameters =
false;
1619 LLVMStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
1620 LLVMStyle.BreakStringLiterals =
true;
1621 LLVMStyle.BreakTemplateDeclarations = FormatStyle::BTDS_MultiLine;
1622 LLVMStyle.ColumnLimit = 80;
1623 LLVMStyle.CommentPragmas =
"^ IWYU pragma:";
1624 LLVMStyle.CompactNamespaces =
false;
1625 LLVMStyle.ConstructorInitializerIndentWidth = 4;
1626 LLVMStyle.ContinuationIndentWidth = 4;
1627 LLVMStyle.Cpp11BracedListStyle =
true;
1628 LLVMStyle.DerivePointerAlignment =
false;
1629 LLVMStyle.DisableFormat =
false;
1630 LLVMStyle.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
1631 LLVMStyle.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
1632 LLVMStyle.EnumTrailingComma = FormatStyle::ETC_Leave;
1633 LLVMStyle.ExperimentalAutoDetectBinPacking =
false;
1634 LLVMStyle.FixNamespaceComments =
true;
1635 LLVMStyle.ForEachMacros.push_back(
"foreach");
1636 LLVMStyle.ForEachMacros.push_back(
"Q_FOREACH");
1637 LLVMStyle.ForEachMacros.push_back(
"BOOST_FOREACH");
1638 LLVMStyle.IfMacros.push_back(
"KJ_IF_MAYBE");
1640 LLVMStyle.IncludeStyle.IncludeCategories = {
1641 {
"^\"(llvm|llvm-c|clang|clang-c)/", 2, 0,
false},
1642 {
"^(<|\"(gtest|gmock|isl|json)/)", 3, 0,
false},
1643 {
".*", 1, 0,
false}};
1644 LLVMStyle.IncludeStyle.IncludeIsMainRegex =
"(Test)?$";
1645 LLVMStyle.IncludeStyle.MainIncludeChar = tooling::IncludeStyle::MICD_Quote;
1646 LLVMStyle.IndentAccessModifiers =
false;
1647 LLVMStyle.IndentCaseBlocks =
false;
1648 LLVMStyle.IndentCaseLabels =
false;
1649 LLVMStyle.IndentExportBlock =
true;
1650 LLVMStyle.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
1651 LLVMStyle.IndentGotoLabels =
true;
1652 LLVMStyle.IndentPPDirectives = FormatStyle::PPDIS_None;
1653 LLVMStyle.IndentRequiresClause =
true;
1654 LLVMStyle.IndentWidth = 2;
1655 LLVMStyle.IndentWrappedFunctionNames =
false;
1656 LLVMStyle.InheritsParentConfig =
false;
1657 LLVMStyle.InsertBraces =
false;
1658 LLVMStyle.InsertNewlineAtEOF =
false;
1659 LLVMStyle.InsertTrailingCommas = FormatStyle::TCS_None;
1660 LLVMStyle.IntegerLiteralSeparator = {
1664 LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
1665 LLVMStyle.JavaScriptWrapImports =
true;
1666 LLVMStyle.KeepEmptyLines = {
1671 LLVMStyle.KeepFormFeed =
false;
1672 LLVMStyle.LambdaBodyIndentation = FormatStyle::LBI_Signature;
1674 LLVMStyle.LineEnding = FormatStyle::LE_DeriveLF;
1675 LLVMStyle.MaxEmptyLinesToKeep = 1;
1676 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
1677 LLVMStyle.NumericLiteralCase = {FormatStyle::NLCS_Leave,
1678 FormatStyle::NLCS_Leave,
1679 FormatStyle::NLCS_Leave,
1680 FormatStyle::NLCS_Leave};
1681 LLVMStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Auto;
1682 LLVMStyle.ObjCBlockIndentWidth = 2;
1683 LLVMStyle.ObjCBreakBeforeNestedBlockParam =
true;
1684 LLVMStyle.ObjCSpaceAfterProperty =
false;
1685 LLVMStyle.ObjCSpaceBeforeProtocolList =
true;
1686 LLVMStyle.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
1687 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
1688 LLVMStyle.PPIndentWidth = -1;
1689 LLVMStyle.QualifierAlignment = FormatStyle::QAS_Leave;
1690 LLVMStyle.ReferenceAlignment = FormatStyle::RAS_Pointer;
1691 LLVMStyle.ReflowComments = FormatStyle::RCS_Always;
1692 LLVMStyle.RemoveBracesLLVM =
false;
1693 LLVMStyle.RemoveEmptyLinesInUnwrappedLines =
false;
1694 LLVMStyle.RemoveParentheses = FormatStyle::RPS_Leave;
1695 LLVMStyle.RemoveSemicolon =
false;
1696 LLVMStyle.RequiresClausePosition = FormatStyle::RCPS_OwnLine;
1697 LLVMStyle.RequiresExpressionIndentation = FormatStyle::REI_OuterScope;
1698 LLVMStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Leave;
1699 LLVMStyle.ShortNamespaceLines = 1;
1700 LLVMStyle.SkipMacroDefinitionBody =
false;
1701 LLVMStyle.SortIncludes = {
true,
false,
1703 LLVMStyle.SortJavaStaticImport = FormatStyle::SJSIO_Before;
1704 LLVMStyle.SortUsingDeclarations = FormatStyle::SUD_LexicographicNumeric;
1705 LLVMStyle.SpaceAfterCStyleCast =
false;
1706 LLVMStyle.SpaceAfterLogicalNot =
false;
1707 LLVMStyle.SpaceAfterOperatorKeyword =
false;
1708 LLVMStyle.SpaceAfterTemplateKeyword =
true;
1709 LLVMStyle.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
1710 LLVMStyle.SpaceBeforeAssignmentOperators =
true;
1711 LLVMStyle.SpaceBeforeCaseColon =
false;
1712 LLVMStyle.SpaceBeforeCpp11BracedList =
false;
1713 LLVMStyle.SpaceBeforeCtorInitializerColon =
true;
1714 LLVMStyle.SpaceBeforeInheritanceColon =
true;
1715 LLVMStyle.SpaceBeforeJsonColon =
false;
1716 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
1717 LLVMStyle.SpaceBeforeParensOptions = {};
1718 LLVMStyle.SpaceBeforeParensOptions.AfterControlStatements =
true;
1719 LLVMStyle.SpaceBeforeParensOptions.AfterForeachMacros =
true;
1720 LLVMStyle.SpaceBeforeParensOptions.AfterIfMacros =
true;
1721 LLVMStyle.SpaceBeforeRangeBasedForLoopColon =
true;
1722 LLVMStyle.SpaceBeforeSquareBrackets =
false;
1723 LLVMStyle.SpaceInEmptyBraces = FormatStyle::SIEB_Never;
1724 LLVMStyle.SpacesBeforeTrailingComments = 1;
1725 LLVMStyle.SpacesInAngles = FormatStyle::SIAS_Never;
1726 LLVMStyle.SpacesInContainerLiterals =
true;
1727 LLVMStyle.SpacesInLineCommentPrefix = {
1728 1, std::numeric_limits<unsigned>::max()};
1729 LLVMStyle.SpacesInParens = FormatStyle::SIPO_Never;
1730 LLVMStyle.SpacesInSquareBrackets =
false;
1731 LLVMStyle.Standard = FormatStyle::LS_Latest;
1732 LLVMStyle.StatementAttributeLikeMacros.push_back(
"Q_EMIT");
1733 LLVMStyle.StatementMacros.push_back(
"Q_UNUSED");
1734 LLVMStyle.StatementMacros.push_back(
"QT_REQUIRE_VERSION");
1735 LLVMStyle.TableGenBreakingDAGArgOperators = {};
1736 LLVMStyle.TableGenBreakInsideDAGArg = FormatStyle::DAS_DontBreak;
1737 LLVMStyle.TabWidth = 8;
1738 LLVMStyle.UseTab = FormatStyle::UT_Never;
1739 LLVMStyle.VerilogBreakBetweenInstancePorts =
true;
1740 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"BOOST_PP_STRINGIZE");
1741 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"CF_SWIFT_NAME");
1742 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"NS_SWIFT_NAME");
1743 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"PP_STRINGIZE");
1744 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"STRINGIZE");
1745 LLVMStyle.WrapNamespaceBodyWithEmptyLines = FormatStyle::WNBWELS_Leave;
1748 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
1749 LLVMStyle.PenaltyBreakBeforeMemberAccess = 150;
1750 LLVMStyle.PenaltyBreakComment = 300;
1751 LLVMStyle.PenaltyBreakFirstLessLess = 120;
1752 LLVMStyle.PenaltyBreakOpenParenthesis = 0;
1753 LLVMStyle.PenaltyBreakScopeResolution = 500;
1754 LLVMStyle.PenaltyBreakString = 1000;
1756 LLVMStyle.PenaltyExcessCharacter = 1'000'000;
1757 LLVMStyle.PenaltyIndentedWhitespace = 0;
1758 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
1762 case FormatStyle::LK_TableGen:
1763 LLVMStyle.SpacesInContainerLiterals =
false;
1765 case FormatStyle::LK_Json:
1766 LLVMStyle.ColumnLimit = 0;
1768 case FormatStyle::LK_Verilog:
1769 LLVMStyle.IndentCaseLabels =
true;
1770 LLVMStyle.SpacesInContainerLiterals =
false;
1780 if (
Language == FormatStyle::LK_TextProto) {
1782 GoogleStyle.Language = FormatStyle::LK_TextProto;
1789 GoogleStyle.AccessModifierOffset = -1;
1790 GoogleStyle.AlignEscapedNewlines = FormatStyle::ENAS_Left;
1791 GoogleStyle.AllowShortIfStatementsOnASingleLine =
1792 FormatStyle::SIS_WithoutElse;
1793 GoogleStyle.AllowShortLoopsOnASingleLine =
true;
1794 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
true;
1796 GoogleStyle.AttributeMacros.push_back(
"absl_nonnull");
1797 GoogleStyle.AttributeMacros.push_back(
"absl_nullable");
1798 GoogleStyle.AttributeMacros.push_back(
"absl_nullability_unknown");
1799 GoogleStyle.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
1801 GoogleStyle.IncludeStyle.IncludeCategories = {{
"^<ext/.*\\.h>", 2, 0,
false},
1802 {
"^<.*\\.h>", 1, 0,
false},
1803 {
"^<.*", 2, 0,
false},
1804 {
".*", 3, 0,
false}};
1805 GoogleStyle.IncludeStyle.IncludeIsMainRegex =
"([-_](test|unittest))?$";
1806 GoogleStyle.IndentCaseLabels =
true;
1807 GoogleStyle.KeepEmptyLines.AtStartOfBlock =
false;
1808 GoogleStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
1809 GoogleStyle.ObjCSpaceAfterProperty =
false;
1810 GoogleStyle.ObjCSpaceBeforeProtocolList =
true;
1811 GoogleStyle.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
1812 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
1813 GoogleStyle.RawStringFormats = {
1815 FormatStyle::LK_Cpp,
1832 FormatStyle::LK_TextProto,
1844 "PARSE_PARTIAL_TEXT_PROTO",
1848 "ParseTextProtoOrDie",
1850 "ParsePartialTestProto",
1857 GoogleStyle.SpacesBeforeTrailingComments = 2;
1858 GoogleStyle.Standard = FormatStyle::LS_Auto;
1860 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
1861 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
1863 if (
Language == FormatStyle::LK_Java) {
1864 GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
1865 GoogleStyle.AlignOperands = FormatStyle::OAS_DontAlign;
1866 GoogleStyle.AlignTrailingComments = {};
1867 GoogleStyle.AlignTrailingComments.Kind = FormatStyle::TCAS_Never;
1868 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
1869 GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
1870 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
1871 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
1872 GoogleStyle.ColumnLimit = 100;
1873 GoogleStyle.SpaceAfterCStyleCast =
true;
1874 GoogleStyle.SpacesBeforeTrailingComments = 1;
1875 }
else if (
Language == FormatStyle::LK_JavaScript) {
1876 GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
1877 GoogleStyle.AlignOperands = FormatStyle::OAS_DontAlign;
1878 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
1880 GoogleStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
1881 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
1882 GoogleStyle.BreakBeforeTernaryOperators =
false;
1885 GoogleStyle.CommentPragmas =
"(taze:|^/[ \t]*<|tslint:|@see)";
1889 GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single;
1890 GoogleStyle.JavaScriptWrapImports =
false;
1891 GoogleStyle.MaxEmptyLinesToKeep = 3;
1892 GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
1893 GoogleStyle.SpacesInContainerLiterals =
false;
1894 }
else if (
Language == FormatStyle::LK_Proto) {
1895 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
1896 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
1902 GoogleStyle.BreakStringLiterals =
false;
1903 GoogleStyle.Cpp11BracedListStyle =
false;
1904 GoogleStyle.SpacesInContainerLiterals =
false;
1905 }
else if (
Language == FormatStyle::LK_ObjC) {
1906 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
1907 GoogleStyle.ColumnLimit = 100;
1908 GoogleStyle.DerivePointerAlignment =
true;
1912 GoogleStyle.IncludeStyle.IncludeBlocks =
1914 }
else if (
Language == FormatStyle::LK_CSharp) {
1915 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
1916 GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
1917 GoogleStyle.BreakStringLiterals =
false;
1918 GoogleStyle.ColumnLimit = 100;
1919 GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
1945 ChromiumStyle.IncludeStyle.IncludeBlocks =
1948 if (
Language == FormatStyle::LK_Java) {
1949 ChromiumStyle.AllowShortIfStatementsOnASingleLine =
1950 FormatStyle::SIS_WithoutElse;
1951 ChromiumStyle.BreakAfterJavaFieldAnnotations =
true;
1952 ChromiumStyle.ContinuationIndentWidth = 8;
1953 ChromiumStyle.IndentWidth = 4;
1956 ChromiumStyle.JavaImportGroups = {
1963 "com.google.android.apps.chrome",
1968 }
else if (
Language == FormatStyle::LK_JavaScript) {
1969 ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
1970 ChromiumStyle.AllowShortLoopsOnASingleLine =
false;
1972 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine =
false;
1973 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
1974 ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
1975 ChromiumStyle.AllowShortLoopsOnASingleLine =
false;
1976 ChromiumStyle.BinPackParameters = FormatStyle::BPPS_OnePerLine;
1977 ChromiumStyle.DerivePointerAlignment =
false;
1978 if (
Language == FormatStyle::LK_ObjC)
1979 ChromiumStyle.ColumnLimit = 80;
1981 return ChromiumStyle;
1986 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine =
false;
1987 MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
1988 MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
1989 FormatStyle::DRTBS_TopLevel;
1990 MozillaStyle.BinPackArguments =
false;
1991 MozillaStyle.BinPackParameters = FormatStyle::BPPS_OnePerLine;
1992 MozillaStyle.BreakAfterReturnType = FormatStyle::RTBS_TopLevel;
1993 MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
1994 MozillaStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
1995 MozillaStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
1996 MozillaStyle.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
1997 MozillaStyle.ConstructorInitializerIndentWidth = 2;
1998 MozillaStyle.ContinuationIndentWidth = 2;
1999 MozillaStyle.Cpp11BracedListStyle =
false;
2000 MozillaStyle.FixNamespaceComments =
false;
2001 MozillaStyle.IndentCaseLabels =
true;
2002 MozillaStyle.ObjCSpaceAfterProperty =
true;
2003 MozillaStyle.ObjCSpaceBeforeProtocolList =
false;
2004 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
2005 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
2006 MozillaStyle.SpaceAfterTemplateKeyword =
false;
2007 return MozillaStyle;
2012 Style.AccessModifierOffset = -4;
2013 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
2014 Style.AlignOperands = FormatStyle::OAS_DontAlign;
2015 Style.AlignTrailingComments = {};
2016 Style.AlignTrailingComments.Kind = FormatStyle::TCAS_Never;
2017 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
2018 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
2019 Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
2020 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
2021 Style.ColumnLimit = 0;
2022 Style.Cpp11BracedListStyle =
false;
2023 Style.FixNamespaceComments =
false;
2024 Style.IndentWidth = 4;
2025 Style.NamespaceIndentation = FormatStyle::NI_Inner;
2026 Style.ObjCBlockIndentWidth = 4;
2027 Style.ObjCSpaceAfterProperty =
true;
2028 Style.PointerAlignment = FormatStyle::PAS_Left;
2029 Style.SpaceBeforeCpp11BracedList =
true;
2030 Style.SpaceInEmptyBraces = FormatStyle::SIEB_Always;
2036 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
2037 Style.BreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
2038 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
2039 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
2040 Style.BreakBeforeTernaryOperators =
true;
2041 Style.ColumnLimit = 79;
2042 Style.Cpp11BracedListStyle =
false;
2043 Style.FixNamespaceComments =
false;
2044 Style.KeepFormFeed =
true;
2045 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
2051 Style.ColumnLimit = 120;
2053 Style.IndentWidth = 4;
2054 Style.UseTab = FormatStyle::UT_Never;
2055 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2056 Style.BraceWrapping.AfterClass =
true;
2057 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2058 Style.BraceWrapping.AfterEnum =
true;
2059 Style.BraceWrapping.AfterFunction =
true;
2060 Style.BraceWrapping.AfterNamespace =
true;
2061 Style.BraceWrapping.AfterObjCDeclaration =
true;
2062 Style.BraceWrapping.AfterStruct =
true;
2063 Style.BraceWrapping.AfterExternBlock =
true;
2064 Style.BraceWrapping.BeforeCatch =
true;
2065 Style.BraceWrapping.BeforeElse =
true;
2066 Style.BraceWrapping.BeforeWhile =
false;
2067 Style.PenaltyReturnTypeOnItsOwnLine = 1000;
2068 Style.AllowShortEnumsOnASingleLine =
false;
2069 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
2070 Style.AllowShortCaseLabelsOnASingleLine =
false;
2071 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
2072 Style.AllowShortLoopsOnASingleLine =
false;
2073 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
2074 Style.BreakAfterReturnType = FormatStyle::RTBS_None;
2080 Style.InsertBraces =
true;
2081 Style.InsertNewlineAtEOF =
true;
2082 Style.IntegerLiteralSeparator.Decimal = 3;
2083 Style.IntegerLiteralSeparator.DecimalMinDigits = 5;
2084 Style.LineEnding = FormatStyle::LE_LF;
2085 Style.RemoveBracesLLVM =
true;
2086 Style.RemoveEmptyLinesInUnwrappedLines =
true;
2087 Style.RemoveParentheses = FormatStyle::RPS_ReturnStatement;
2088 Style.RemoveSemicolon =
true;
2094 NoStyle.DisableFormat =
true;
2095 NoStyle.SortIncludes = {};
2096 NoStyle.SortUsingDeclarations = FormatStyle::SUD_Never;
2101 FormatStyle *Style) {
2102 if (Name.equals_insensitive(
"llvm"))
2104 else if (Name.equals_insensitive(
"chromium"))
2106 else if (Name.equals_insensitive(
"mozilla"))
2108 else if (Name.equals_insensitive(
"google"))
2110 else if (Name.equals_insensitive(
"webkit"))
2112 else if (Name.equals_insensitive(
"gnu"))
2114 else if (Name.equals_insensitive(
"microsoft"))
2116 else if (Name.equals_insensitive(
"clang-format"))
2118 else if (Name.equals_insensitive(
"none"))
2120 else if (Name.equals_insensitive(
"inheritparentconfig"))
2121 Style->InheritsParentConfig =
true;
2131 if (Style->QualifierOrder.empty())
2135 for (
const auto &Qualifier : Style->QualifierOrder) {
2136 if (Qualifier ==
"type")
2140 if (token == tok::identifier)
2145 std::set<std::string> UniqueQualifiers(Style->QualifierOrder.begin(),
2146 Style->QualifierOrder.end());
2147 if (Style->QualifierOrder.size() != UniqueQualifiers.size()) {
2148 LLVM_DEBUG(llvm::dbgs()
2149 <<
"Duplicate Qualifiers " << Style->QualifierOrder.size()
2150 <<
" vs " << UniqueQualifiers.size() <<
"\n");
2155 if (!llvm::is_contained(Style->QualifierOrder,
"type"))
2162 FormatStyle *Style,
bool AllowUnknownOptions,
2163 llvm::SourceMgr::DiagHandlerTy DiagHandler,
2164 void *DiagHandlerCtxt,
bool IsDotHFile) {
2166 FormatStyle::LanguageKind
Language = Style->Language;
2167 assert(
Language != FormatStyle::LK_None);
2168 if (Config.getBuffer().trim().empty())
2170 Style->StyleSet.Clear();
2171 std::vector<FormatStyle> Styles;
2172 llvm::yaml::Input Input(Config,
nullptr, DiagHandler,
2178 Input.setContext(Style);
2179 Input.setAllowUnknownKeys(AllowUnknownOptions);
2182 return Input.error();
2184 for (
unsigned i = 0; i < Styles.size(); ++i) {
2186 if (Styles[i].
Language == FormatStyle::LK_None && i != 0)
2189 for (
unsigned j = 0; j < i; ++j) {
2191 LLVM_DEBUG(llvm::dbgs()
2192 <<
"Duplicate languages in the config file on positions "
2193 << j <<
" and " << i <<
"\n");
2201 FormatStyle::FormatStyleSet StyleSet;
2202 bool LanguageFound =
false;
2203 for (
const FormatStyle &Style : llvm::reverse(Styles)) {
2204 const auto Lang = Style.Language;
2205 if (Lang != FormatStyle::LK_None)
2206 StyleSet.Add(Style);
2209 (Lang == FormatStyle::LK_Cpp &&
Language == FormatStyle::LK_C)) {
2210 LanguageFound =
true;
2211 }
else if (IsDotHFile &&
Language == FormatStyle::LK_Cpp &&
2212 (Lang == FormatStyle::LK_C || Lang == FormatStyle::LK_ObjC)) {
2214 LanguageFound =
true;
2217 if (!LanguageFound) {
2218 if (Styles.empty() || Styles[0].Language != FormatStyle::LK_None)
2220 FormatStyle DefaultStyle = Styles[0];
2222 StyleSet.Add(std::move(DefaultStyle));
2225 if (Style->InsertTrailingCommas != FormatStyle::TCS_None &&
2226 Style->BinPackArguments) {
2230 if (Style->QualifierAlignment != FormatStyle::QAS_Leave)
2237 llvm::raw_string_ostream Stream(
Text);
2238 llvm::yaml::Output Output(Stream);
2241 FormatStyle NonConstStyle = Style;
2245 Output << NonConstStyle;
2247 return Stream.str();
2250std::optional<FormatStyle>
2251FormatStyle::FormatStyleSet::Get(FormatStyle::LanguageKind
Language)
const {
2253 return std::nullopt;
2255 if (It == Styles->end()) {
2257 return std::nullopt;
2259 It = Styles->find(FormatStyle::LK_Cpp);
2260 if (It == Styles->end())
2261 return std::nullopt;
2263 FormatStyle Style = It->second;
2264 Style.StyleSet = *
this;
2268void FormatStyle::FormatStyleSet::Add(FormatStyle Style) {
2269 assert(Style.Language !=
LK_None &&
2270 "Cannot add a style for LK_None to a StyleSet");
2272 !Style.StyleSet.Styles &&
2273 "Cannot add a style associated with an existing StyleSet to a StyleSet");
2275 Styles = std::make_shared<MapType>();
2276 (*Styles)[Style.Language] = std::move(Style);
2279void FormatStyle::FormatStyleSet::Clear() { Styles.reset(); }
2281std::optional<FormatStyle>
2282FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind
Language)
const {
2289 const SourceManager &SourceMgr, tooling::Replacements &
Result,
2290 StringRef
Text =
"") {
2291 const auto &
Tok = Token.Tok;
2292 SourceLocation Start;
2294 Start =
Tok.getLocation();
2297 Start = Token.WhitespaceRange.getBegin();
2300 cantFail(
Result.add(tooling::Replacement(SourceMgr, Range,
Text)));
2305 ParensRemover(
const Environment &Env,
const FormatStyle &Style)
2306 : TokenAnalyzer(Env, Style) {}
2308 std::pair<tooling::Replacements, unsigned>
2309 analyze(TokenAnnotator &Annotator,
2310 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2311 FormatTokenLexer &Tokens)
override {
2312 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2313 tooling::Replacements
Result;
2314 removeParens(AnnotatedLines,
Result);
2319 void removeParens(SmallVectorImpl<AnnotatedLine *> &Lines,
2320 tooling::Replacements &
Result) {
2321 const auto &SourceMgr = Env.getSourceManager();
2322 for (
auto *
Line : Lines) {
2323 if (!
Line->Children.empty())
2325 if (!
Line->Affected)
2327 for (
const auto *Token =
Line->First; Token && !Token->Finalized;
2328 Token = Token->Next) {
2329 if (Token->Optional && Token->isOneOf(tok::l_paren, tok::r_paren))
2338 BracesInserter(
const Environment &Env,
const FormatStyle &Style)
2339 : TokenAnalyzer(Env, Style) {}
2341 std::pair<tooling::Replacements, unsigned>
2342 analyze(TokenAnnotator &Annotator,
2343 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2344 FormatTokenLexer &Tokens)
override {
2345 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2346 tooling::Replacements
Result;
2347 insertBraces(AnnotatedLines,
Result);
2352 void insertBraces(SmallVectorImpl<AnnotatedLine *> &Lines,
2353 tooling::Replacements &
Result) {
2354 const auto &SourceMgr = Env.getSourceManager();
2355 int OpeningBraceSurplus = 0;
2356 for (AnnotatedLine *
Line : Lines) {
2357 if (!
Line->Children.empty())
2359 if (!
Line->Affected && OpeningBraceSurplus == 0)
2362 Token = Token->Next) {
2369 if (!
Line->Affected)
2371 Brace = Token->is(tok::comment) ?
"\n{" :
"{";
2372 ++OpeningBraceSurplus;
2374 if (OpeningBraceSurplus == 0)
2381 Token->BraceCount = 0;
2382 const auto Start = Token->Tok.getEndLoc();
2383 cantFail(
Result.add(tooling::Replacement(SourceMgr, Start, 0,
Brace)));
2386 assert(OpeningBraceSurplus == 0);
2392 BracesRemover(
const Environment &Env,
const FormatStyle &Style)
2393 : TokenAnalyzer(Env, Style) {}
2395 std::pair<tooling::Replacements, unsigned>
2396 analyze(TokenAnnotator &Annotator,
2397 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2398 FormatTokenLexer &Tokens)
override {
2399 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2400 tooling::Replacements
Result;
2401 removeBraces(AnnotatedLines,
Result);
2406 void removeBraces(SmallVectorImpl<AnnotatedLine *> &Lines,
2407 tooling::Replacements &
Result) {
2408 const auto &SourceMgr = Env.getSourceManager();
2409 const auto *End = Lines.end();
2410 for (
const auto *I = Lines.begin(); I != End; ++I) {
2411 const auto &
Line = *I;
2412 if (!
Line->Children.empty())
2414 if (!
Line->Affected)
2416 const auto *NextLine = I + 1 == End ?
nullptr : I[1];
2417 for (
const auto *Token =
Line->First; Token && !Token->Finalized;
2418 Token = Token->Next) {
2419 if (!Token->Optional || !Token->isOneOf(tok::l_brace, tok::r_brace))
2421 auto *
Next = Token->Next;
2422 assert(
Next || Token ==
Line->Last);
2423 if (!
Next && NextLine)
2424 Next = NextLine->First;
2433 SemiRemover(
const Environment &Env,
const FormatStyle &Style)
2434 : TokenAnalyzer(Env, Style) {}
2436 std::pair<tooling::Replacements, unsigned>
2437 analyze(TokenAnnotator &Annotator,
2438 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2439 FormatTokenLexer &Tokens)
override {
2440 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2441 tooling::Replacements
Result;
2442 removeSemi(Annotator, AnnotatedLines,
Result);
2447 void removeSemi(TokenAnnotator &Annotator,
2448 SmallVectorImpl<AnnotatedLine *> &Lines,
2449 tooling::Replacements &
Result) {
2451 const auto *Prev =
Tok.Previous;
2452 if (!Prev || Prev->isNot(tok::r_brace))
2454 const auto *LBrace = Prev->MatchingParen;
2455 return LBrace && LBrace->is(TT_FunctionLBrace);
2457 const auto &SourceMgr = Env.getSourceManager();
2458 const auto *End = Lines.end();
2459 for (
const auto *I = Lines.begin(); I != End; ++I) {
2460 const auto &
Line = *I;
2461 if (!
Line->Children.empty())
2462 removeSemi(Annotator,
Line->Children,
Result);
2463 if (!
Line->Affected)
2465 Annotator.calculateFormattingInformation(*
Line);
2466 const auto *NextLine = I + 1 == End ?
nullptr : I[1];
2467 for (
const auto *Token =
Line->First; Token && !Token->Finalized;
2468 Token = Token->Next) {
2469 if (Token->isNot(tok::semi) ||
2470 (!Token->Optional && !PrecededByFunctionRBrace(*Token))) {
2473 auto *
Next = Token->Next;
2474 assert(
Next || Token ==
Line->Last);
2475 if (!
Next && NextLine)
2476 Next = NextLine->First;
2485 EnumTrailingCommaEditor(
const Environment &Env,
const FormatStyle &Style)
2486 : TokenAnalyzer(Env, Style) {}
2488 std::pair<tooling::Replacements, unsigned>
2489 analyze(TokenAnnotator &Annotator,
2490 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2491 FormatTokenLexer &Tokens)
override {
2492 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2493 tooling::Replacements
Result;
2494 editEnumTrailingComma(AnnotatedLines,
Result);
2499 void editEnumTrailingComma(SmallVectorImpl<AnnotatedLine *> &Lines,
2500 tooling::Replacements &
Result) {
2501 bool InEnumBraces =
false;
2503 const auto &SourceMgr = Env.getSourceManager();
2504 for (
auto *
Line : Lines) {
2505 if (!
Line->Children.empty())
2506 editEnumTrailingComma(
Line->Children,
Result);
2507 for (
const auto *Token =
Line->First; Token && !Token->Finalized;
2508 Token = Token->Next) {
2509 if (Token->isNot(TT_EnumRBrace)) {
2510 if (Token->is(TT_EnumLBrace))
2511 InEnumBraces =
true;
2512 else if (InEnumBraces && Token->isNot(tok::comment))
2513 BeforeRBrace =
Line->Affected ? Token :
nullptr;
2516 InEnumBraces =
false;
2519 if (BeforeRBrace->is(tok::comma)) {
2520 if (Style.EnumTrailingComma == FormatStyle::ETC_Remove)
2522 }
else if (Style.EnumTrailingComma == FormatStyle::ETC_Insert) {
2523 cantFail(
Result.add(tooling::Replacement(
2524 SourceMgr, BeforeRBrace->Tok.getEndLoc(), 0,
",")));
2526 BeforeRBrace =
nullptr;
2534 JavaScriptRequoter(
const Environment &Env,
const FormatStyle &Style)
2535 : TokenAnalyzer(Env, Style) {}
2537 std::pair<tooling::Replacements, unsigned>
2538 analyze(TokenAnnotator &Annotator,
2539 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2540 FormatTokenLexer &Tokens)
override {
2541 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2542 tooling::Replacements
Result;
2543 requoteJSStringLiteral(AnnotatedLines,
Result);
2550 void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
2551 tooling::Replacements &
Result) {
2552 for (AnnotatedLine *
Line : Lines) {
2553 requoteJSStringLiteral(
Line->Children,
Result);
2554 if (!
Line->Affected)
2557 FormatTok = FormatTok->Next) {
2558 StringRef Input = FormatTok->TokenText;
2559 if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
2562 (Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
2563 !Input.starts_with(
"\"")) ||
2564 (Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
2565 !Input.starts_with(
"\'"))) {
2570 bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
2571 SourceLocation Start = FormatTok->Tok.getLocation();
2572 auto Replace = [&](SourceLocation Start,
unsigned Length,
2573 StringRef ReplacementText) {
2574 auto Err =
Result.add(tooling::Replacement(
2575 Env.getSourceManager(), Start, Length, ReplacementText));
2579 llvm::errs() <<
toString(std::move(Err)) <<
"\n";
2583 Replace(Start, 1, IsSingle ?
"'" :
"\"");
2584 Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
2585 IsSingle ?
"'" :
"\"");
2588 bool Escaped =
false;
2589 for (
size_t i = 1; i < Input.size() - 1; i++) {
2592 if (!Escaped && i + 1 < Input.size() &&
2593 ((IsSingle && Input[i + 1] ==
'"') ||
2594 (!IsSingle && Input[i + 1] ==
'\''))) {
2597 Replace(Start.getLocWithOffset(i), 1,
"");
2604 if (!Escaped && IsSingle == (Input[i] ==
'\'')) {
2606 Replace(Start.getLocWithOffset(i), 0,
"\\");
2622 Formatter(
const Environment &Env,
const FormatStyle &Style,
2623 FormattingAttemptStatus *Status)
2624 : TokenAnalyzer(Env, Style), Status(Status) {}
2626 std::pair<tooling::Replacements, unsigned>
2627 analyze(TokenAnnotator &Annotator,
2628 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2629 FormatTokenLexer &Tokens)
override {
2630 tooling::Replacements
Result;
2631 deriveLocalStyle(AnnotatedLines);
2632 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2633 for (AnnotatedLine *
Line : AnnotatedLines)
2634 Annotator.calculateFormattingInformation(*
Line);
2635 Annotator.setCommentLineLevels(AnnotatedLines);
2637 WhitespaceManager Whitespaces(
2638 Env.getSourceManager(), Style,
2639 Style.LineEnding > FormatStyle::LE_CRLF
2641 Env.getSourceManager().getBufferData(Env.getFileID()),
2642 Style.LineEnding == FormatStyle::LE_DeriveCRLF)
2643 : Style.LineEnding == FormatStyle::LE_CRLF);
2644 ContinuationIndenter Indenter(Style, Tokens.getKeywords(),
2645 Env.getSourceManager(), Whitespaces, Encoding,
2646 BinPackInconclusiveFunctions);
2648 UnwrappedLineFormatter(&Indenter, &Whitespaces, Style,
2649 Tokens.getKeywords(), Env.getSourceManager(),
2651 .format(AnnotatedLines,
false,
2654 Env.getFirstStartColumn(),
2655 Env.getNextStartColumn(),
2656 Env.getLastStartColumn());
2657 for (
const auto &R : Whitespaces.generateReplacements())
2659 return std::make_pair(
Result, 0);
2660 return std::make_pair(
Result, Penalty);
2665 hasCpp03IncompatibleFormat(
const SmallVectorImpl<AnnotatedLine *> &Lines) {
2666 for (
const AnnotatedLine *
Line : Lines) {
2667 if (hasCpp03IncompatibleFormat(
Line->Children))
2670 if (!
Tok->hasWhitespaceBefore()) {
2671 if (
Tok->is(tok::coloncolon) &&
Tok->Previous->is(TT_TemplateOpener))
2673 if (
Tok->is(TT_TemplateCloser) &&
2674 Tok->Previous->is(TT_TemplateCloser)) {
2683 int countVariableAlignments(
const SmallVectorImpl<AnnotatedLine *> &Lines) {
2684 int AlignmentDiff = 0;
2686 for (
const AnnotatedLine *
Line : Lines) {
2687 AlignmentDiff += countVariableAlignments(
Line->Children);
2690 if (
Tok->isNot(TT_PointerOrReference))
2693 const auto *Prev =
Tok->Previous;
2694 const bool PrecededByName = Prev && Prev->Tok.getIdentifierInfo();
2695 const bool SpaceBefore =
Tok->hasWhitespaceBefore();
2698 while (
Tok->Next &&
Tok->Next->is(TT_PointerOrReference))
2702 const bool FollowedByName =
Next &&
Next->Tok.getIdentifierInfo();
2703 const bool SpaceAfter =
Next &&
Next->hasWhitespaceBefore();
2705 if ((!PrecededByName && !FollowedByName) ||
2707 (PrecededByName && FollowedByName && SpaceBefore == SpaceAfter)) {
2711 if ((PrecededByName && SpaceBefore) ||
2712 (FollowedByName && !SpaceAfter)) {
2715 }
else if ((PrecededByName && !SpaceBefore) ||
2716 (FollowedByName && SpaceAfter)) {
2723 return AlignmentDiff;
2727 deriveLocalStyle(
const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
2728 bool HasBinPackedFunction =
false;
2729 bool HasOnePerLineFunction =
false;
2730 for (AnnotatedLine *
Line : AnnotatedLines) {
2731 if (!
Line->First->Next)
2736 HasBinPackedFunction =
true;
2738 HasOnePerLineFunction =
true;
2743 if (Style.DerivePointerAlignment) {
2744 const auto NetRightCount = countVariableAlignments(AnnotatedLines);
2745 if (NetRightCount > 0)
2746 Style.PointerAlignment = FormatStyle::PAS_Right;
2747 else if (NetRightCount < 0)
2748 Style.PointerAlignment = FormatStyle::PAS_Left;
2749 Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
2751 if (Style.Standard == FormatStyle::LS_Auto) {
2752 Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
2753 ? FormatStyle::LS_Latest
2754 : FormatStyle::LS_Cpp03;
2756 BinPackInconclusiveFunctions =
2757 HasBinPackedFunction || !HasOnePerLineFunction;
2760 bool BinPackInconclusiveFunctions;
2761 FormattingAttemptStatus *Status;
2777 TrailingCommaInserter(
const Environment &Env,
const FormatStyle &Style)
2778 : TokenAnalyzer(Env, Style) {}
2780 std::pair<tooling::Replacements, unsigned>
2781 analyze(TokenAnnotator &Annotator,
2782 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2783 FormatTokenLexer &Tokens)
override {
2784 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2785 tooling::Replacements
Result;
2786 insertTrailingCommas(AnnotatedLines,
Result);
2793 void insertTrailingCommas(SmallVectorImpl<AnnotatedLine *> &Lines,
2794 tooling::Replacements &
Result) {
2795 for (AnnotatedLine *
Line : Lines) {
2796 insertTrailingCommas(
Line->Children,
Result);
2797 if (!
Line->Affected)
2800 FormatTok = FormatTok->Next) {
2801 if (FormatTok->NewlinesBefore == 0)
2804 if (!Matching || !FormatTok->getPreviousNonComment())
2806 if (!(FormatTok->is(tok::r_square) &&
2807 Matching->is(TT_ArrayInitializerLSquare)) &&
2808 !(FormatTok->is(tok::r_brace) && Matching->is(TT_DictLiteral))) {
2811 FormatToken *Prev = FormatTok->getPreviousNonComment();
2812 if (Prev->is(tok::comma) || Prev->is(tok::semi))
2816 SourceLocation Start =
2817 Prev->Tok.getLocation().getLocWithOffset(Prev->TokenText.size());
2821 unsigned ColumnNumber =
2822 Env.getSourceManager().getSpellingColumnNumber(Start);
2823 if (ColumnNumber > Style.ColumnLimit)
2828 tooling::Replacement(Env.getSourceManager(), Start, 0,
",")));
2838 Cleaner(
const Environment &Env,
const FormatStyle &Style)
2839 : TokenAnalyzer(Env, Style),
2840 DeletedTokens(FormatTokenLess(Env.getSourceManager())) {}
2843 std::pair<tooling::Replacements, unsigned>
2844 analyze(TokenAnnotator &Annotator,
2845 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2846 FormatTokenLexer &Tokens)
override {
2854 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2856 checkEmptyNamespace(AnnotatedLines);
2858 for (
auto *
Line : AnnotatedLines)
2861 return {generateFixes(), 0};
2865 void cleanupLine(AnnotatedLine *
Line) {
2866 for (
auto *Child :
Line->Children)
2869 if (
Line->Affected) {
2870 cleanupRight(
Line->First, tok::comma, tok::comma);
2871 cleanupRight(
Line->First, TT_CtorInitializerColon, tok::comma);
2872 cleanupRight(
Line->First, tok::l_paren, tok::comma);
2873 cleanupLeft(
Line->First, tok::comma, tok::r_paren);
2874 cleanupLeft(
Line->First, TT_CtorInitializerComma, tok::l_brace);
2875 cleanupLeft(
Line->First, TT_CtorInitializerColon, tok::l_brace);
2876 cleanupLeft(
Line->First, TT_CtorInitializerColon, tok::equal);
2880 bool containsOnlyComments(
const AnnotatedLine &
Line) {
2882 if (
Tok->isNot(tok::comment))
2888 void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
2889 std::set<unsigned> DeletedLines;
2890 for (
unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
2891 auto &
Line = *AnnotatedLines[i];
2892 if (
Line.startsWithNamespace())
2893 checkEmptyNamespace(AnnotatedLines, i, i, DeletedLines);
2896 for (
auto Line : DeletedLines) {
2909 bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2910 unsigned CurrentLine,
unsigned &NewLine,
2911 std::set<unsigned> &DeletedLines) {
2912 unsigned InitLine = CurrentLine, End = AnnotatedLines.size();
2913 if (Style.BraceWrapping.AfterNamespace) {
2917 if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
2918 NewLine = CurrentLine;
2921 }
else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
2924 while (++CurrentLine < End) {
2925 if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
2928 if (AnnotatedLines[CurrentLine]->startsWithNamespace()) {
2929 if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine,
2933 CurrentLine = NewLine;
2937 if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
2942 NewLine = CurrentLine;
2946 NewLine = CurrentLine;
2947 if (CurrentLine >= End)
2952 AnnotatedLines[InitLine]->First->Tok.getLocation(),
2953 AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc()))) {
2957 for (
unsigned i = InitLine; i <= CurrentLine; ++i)
2958 DeletedLines.insert(i);
2967 template <
typename LeftKind,
typename RightKind>
2968 void cleanupPair(
FormatToken *Start, LeftKind LK, RightKind RK,
2971 for (
auto *Res =
Tok.Next; Res; Res = Res->Next) {
2972 if (Res->isNot(tok::comment) &&
2973 DeletedTokens.find(Res) == DeletedTokens.end()) {
2979 for (
auto *Left = Start;
Left;) {
2980 auto *
Right = NextNotDeleted(*Left);
2984 deleteToken(DeleteLeft ? Left : Right);
2996 template <
typename LeftKind,
typename RightKind>
2997 void cleanupLeft(
FormatToken *Start, LeftKind LK, RightKind RK) {
2998 cleanupPair(Start, LK, RK,
true);
3001 template <
typename LeftKind,
typename RightKind>
3002 void cleanupRight(
FormatToken *Start, LeftKind LK, RightKind RK) {
3003 cleanupPair(Start, LK, RK,
false);
3009 DeletedTokens.insert(
Tok);
3012 tooling::Replacements generateFixes() {
3013 tooling::Replacements Fixes;
3014 SmallVector<FormatToken *> Tokens;
3015 std::copy(DeletedTokens.begin(), DeletedTokens.end(),
3016 std::back_inserter(Tokens));
3022 while (Idx < Tokens.size()) {
3023 unsigned St = Idx, End = Idx;
3024 while ((End + 1) < Tokens.size() && Tokens[End]->Next == Tokens[End + 1])
3027 Tokens[End]->Tok.getEndLoc());
3029 Fixes.add(tooling::Replacement(Env.getSourceManager(), SR,
""));
3033 llvm::errs() <<
toString(std::move(Err)) <<
"\n";
3034 assert(
false &&
"Fixes must not conflict!");
3045 struct FormatTokenLess {
3046 FormatTokenLess(
const SourceManager &SM) : SM(SM) {}
3049 return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(),
3050 RHS->Tok.getLocation());
3052 const SourceManager &SM;
3056 std::set<FormatToken *, FormatTokenLess> DeletedTokens;
3061 ObjCHeaderStyleGuesser(
const Environment &Env,
const FormatStyle &Style)
3062 : TokenAnalyzer(Env, Style), IsObjC(
false) {}
3064 std::pair<tooling::Replacements, unsigned>
3065 analyze(TokenAnnotator &Annotator,
3066 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3067 FormatTokenLexer &Tokens)
override {
3068 assert(Style.Language == FormatStyle::LK_Cpp);
3069 IsObjC = guessIsObjC(Env.getSourceManager(), AnnotatedLines,
3070 Tokens.getKeywords());
3071 tooling::Replacements
Result;
3075 bool isObjC() {
return IsObjC; }
3079 guessIsObjC(
const SourceManager &SourceManager,
3080 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3081 const AdditionalKeywords &Keywords) {
3083 static constexpr llvm::StringLiteral FoundationIdentifiers[] = {
3098 "FOUNDATION_EXPORT",
3099 "FOUNDATION_EXTERN",
3100 "NSAffineTransform",
3102 "NSAttributedString",
3121 "NSInvocationOperation",
3125 "NSMutableAttributedString",
3126 "NSMutableCharacterSet",
3128 "NSMutableDictionary",
3129 "NSMutableIndexSet",
3130 "NSMutableOrderedSet",
3134 "NSNumberFormatter",
3138 "NSOperationQueuePriority",
3142 "NSQualityOfService",
3145 "NSRegularExpression",
3156 "NS_ASSUME_NONNULL_BEGIN",
3161 for (
auto *
Line : AnnotatedLines) {
3162 if (
Line->First && (
Line->First->TokenText.starts_with(
"#") ||
3163 Line->First->TokenText ==
"__pragma" ||
3164 Line->First->TokenText ==
"_Pragma")) {
3168 FormatTok = FormatTok->Next) {
3169 if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) &&
3170 (FormatTok->isNot(tok::objc_not_keyword) ||
3171 FormatTok->isOneOf(tok::numeric_constant, tok::l_square,
3173 (FormatTok->Tok.isAnyIdentifier() &&
3174 llvm::binary_search(FoundationIdentifiers,
3175 FormatTok->TokenText)) ||
3176 FormatTok->is(TT_ObjCStringLiteral) ||
3177 FormatTok->isOneOf(Keywords.kw_NS_CLOSED_ENUM, Keywords.kw_NS_ENUM,
3178 Keywords.kw_NS_ERROR_ENUM,
3179 Keywords.kw_NS_OPTIONS, TT_ObjCBlockLBrace,
3180 TT_ObjCBlockLParen, TT_ObjCDecl, TT_ObjCForIn,
3181 TT_ObjCMethodExpr, TT_ObjCMethodSpecifier,
3183 LLVM_DEBUG(llvm::dbgs()
3184 <<
"Detected ObjC at location "
3185 << FormatTok->Tok.getLocation().printToString(
3187 <<
" token: " << FormatTok->TokenText <<
" token type: "
3192 if (guessIsObjC(SourceManager,
Line->Children, Keywords))
3201struct IncludeDirective {
3209struct JavaImportDirective {
3210 StringRef Identifier;
3213 SmallVector<StringRef> AssociatedCommentLines;
3222 for (
const auto &Range : Ranges) {
3223 if (Range.getOffset() < End &&
3224 Range.getOffset() + Range.getLength() > Start) {
3239static std::pair<unsigned, unsigned>
3242 unsigned CursorIndex = std::numeric_limits<unsigned>::max();
3243 unsigned OffsetToEOL = 0;
3244 for (
int i = 0, e = Includes.size(); i != e; ++i) {
3245 unsigned Start = Includes[Indices[i]].Offset;
3246 unsigned End = Start + Includes[Indices[i]].Text.size();
3247 if (!(Cursor >= Start && Cursor < End))
3249 CursorIndex = Indices[i];
3250 OffsetToEOL = End - Cursor;
3253 while (--i >= 0 && Includes[CursorIndex].
Text == Includes[Indices[i]].
Text)
3257 return std::make_pair(CursorIndex, OffsetToEOL);
3262 std::string NewCode;
3263 size_t Pos = 0, LastPos = 0;
3266 Pos = Code.find(
"\r\n", LastPos);
3267 if (Pos == LastPos) {
3271 if (Pos == std::string::npos) {
3272 NewCode += Code.substr(LastPos);
3275 NewCode += Code.substr(LastPos, Pos - LastPos) +
"\n";
3277 }
while (Pos != std::string::npos);
3295 const unsigned IncludesBeginOffset = Includes.front().Offset;
3296 const unsigned IncludesEndOffset =
3297 Includes.back().Offset + Includes.back().Text.size();
3298 const unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset;
3299 if (!
affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset))
3302 llvm::to_vector<16>(llvm::seq<unsigned>(0, Includes.size()));
3304 if (Style.SortIncludes.Enabled) {
3305 stable_sort(Indices, [&](
unsigned LHSI,
unsigned RHSI) {
3307 if (Style.SortIncludes.IgnoreExtension) {
3308 LHSStem = Includes[LHSI].Filename;
3309 RHSStem = Includes[RHSI].Filename;
3310 llvm::sys::path::replace_extension(LHSStem,
"");
3311 llvm::sys::path::replace_extension(RHSStem,
"");
3313 std::string LHSStemLower, RHSStemLower;
3314 std::string LHSFilenameLower, RHSFilenameLower;
3315 if (Style.SortIncludes.IgnoreCase) {
3316 LHSStemLower = LHSStem.str().lower();
3317 RHSStemLower = RHSStem.str().lower();
3318 LHSFilenameLower = Includes[LHSI].Filename.lower();
3319 RHSFilenameLower = Includes[RHSI].Filename.lower();
3321 return std::tie(Includes[LHSI].Priority, LHSStemLower, LHSStem,
3322 LHSFilenameLower, Includes[LHSI].Filename) <
3323 std::tie(Includes[RHSI].Priority, RHSStemLower, RHSStem,
3324 RHSFilenameLower, Includes[RHSI].Filename);
3330 unsigned CursorIndex;
3332 unsigned CursorToEOLOffset;
3334 std::tie(CursorIndex, CursorToEOLOffset) =
3339 Indices.erase(llvm::unique(Indices,
3340 [&](
unsigned LHSI,
unsigned RHSI) {
3341 return Includes[LHSI].Text.trim() ==
3342 Includes[RHSI].Text.trim();
3346 int CurrentCategory = Includes.front().Category;
3354 if (Indices.size() == Includes.size() && is_sorted(Indices) &&
3359 const auto OldCursor = Cursor ? *Cursor : 0;
3361 for (
unsigned Index : Indices) {
3362 if (!result.empty()) {
3364 if (Style.IncludeStyle.IncludeBlocks ==
3366 CurrentCategory != Includes[Index].Category) {
3370 result += Includes[Index].Text;
3371 if (Cursor && CursorIndex == Index)
3372 *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
3373 CurrentCategory = Includes[Index].Category;
3376 if (Cursor && *Cursor >= IncludesEndOffset)
3377 *Cursor += result.size() - IncludesBlockSize;
3382 IncludesBeginOffset, IncludesBlockSize)))) {
3384 *Cursor = OldCursor;
3389 FileName, Includes.front().Offset, IncludesBlockSize, result));
3393 llvm::errs() <<
toString(std::move(Err)) <<
"\n";
3403 unsigned Prev = llvm::StringSwitch<size_t>(Code)
3404 .StartsWith(
"\xEF\xBB\xBF", 3)
3406 unsigned SearchFrom = 0;
3418 bool FirstIncludeBlock =
true;
3419 bool MainIncludeFound =
false;
3420 bool FormattingOff =
false;
3423 llvm::Regex RawStringRegex(
3424 "R\"([][A-Za-z0-9_{}#<>%:;.?*+/^&\\$|~!=,'-]*)\\(");
3426 std::string RawStringTermination =
")\"";
3428 for (
const auto Size = Code.size(); SearchFrom < Size;) {
3429 size_t Pos = SearchFrom;
3430 if (Code[SearchFrom] !=
'\n') {
3433 Pos = Code.find(
'\n', Pos);
3434 }
while (Pos != StringRef::npos && Code[Pos - 1] ==
'\\');
3438 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
3440 StringRef Trimmed =
Line.trim();
3445 if (RawStringRegex.match(Trimmed, &RawStringMatches)) {
3446 std::string CharSequence = RawStringMatches[1].str();
3447 RawStringTermination =
")" + CharSequence +
"\"";
3448 FormattingOff =
true;
3451 if (Trimmed.contains(RawStringTermination))
3452 FormattingOff =
false;
3454 bool IsBlockComment =
false;
3457 FormattingOff =
true;
3459 FormattingOff =
false;
3460 }
else if (Trimmed.starts_with(
"/*")) {
3461 IsBlockComment =
true;
3462 Pos = Code.find(
"*/", SearchFrom + 2);
3465 const bool EmptyLineSkipped =
3468 Style.IncludeStyle.IncludeBlocks ==
3471 bool MergeWithNextLine = Trimmed.ends_with(
"\\");
3472 if (!FormattingOff && !MergeWithNextLine) {
3473 if (!IsBlockComment &&
3475 StringRef IncludeName = Matches[2];
3476 if (Trimmed.contains(
"/*") && !Trimmed.contains(
"*/")) {
3481 Pos = Code.find(
"*/", SearchFrom);
3483 Prev, (Pos != StringRef::npos ? Pos + 2 : Code.size()) - Prev);
3487 !MainIncludeFound && FirstIncludeBlock);
3489 IncludeName, !MainIncludeFound && FirstIncludeBlock);
3491 MainIncludeFound =
true;
3492 IncludesInBlock.push_back(
3493 {IncludeName,
Line, Prev, Category, Priority});
3494 }
else if (!IncludesInBlock.empty() && !EmptyLineSkipped) {
3497 IncludesInBlock.clear();
3498 if (Trimmed.starts_with(
"#pragma hdrstop"))
3499 FirstIncludeBlock =
true;
3501 FirstIncludeBlock =
false;
3504 if (Pos == StringRef::npos || Pos + 1 == Code.size())
3507 if (!MergeWithNextLine)
3509 SearchFrom = Pos + 1;
3511 if (!IncludesInBlock.empty()) {
3522 StringRef ImportIdentifier) {
3523 unsigned LongestMatchIndex = std::numeric_limits<unsigned>::max();
3524 unsigned LongestMatchLength = 0;
3525 for (
unsigned I = 0; I < Style.JavaImportGroups.size(); I++) {
3526 const std::string &GroupPrefix = Style.JavaImportGroups[I];
3527 if (ImportIdentifier.starts_with(GroupPrefix) &&
3528 GroupPrefix.length() > LongestMatchLength) {
3529 LongestMatchIndex = I;
3530 LongestMatchLength = GroupPrefix.length();
3533 return LongestMatchIndex;
3545 unsigned ImportsBeginOffset = Imports.front().Offset;
3546 unsigned ImportsEndOffset =
3547 Imports.back().Offset + Imports.back().Text.size();
3548 unsigned ImportsBlockSize = ImportsEndOffset - ImportsBeginOffset;
3549 if (!
affectsRange(Ranges, ImportsBeginOffset, ImportsEndOffset))
3553 llvm::to_vector<16>(llvm::seq<unsigned>(0, Imports.size()));
3556 for (
const JavaImportDirective &Import : Imports)
3559 bool StaticImportAfterNormalImport =
3560 Style.SortJavaStaticImport == FormatStyle::SJSIO_After;
3561 sort(Indices, [&](
unsigned LHSI,
unsigned RHSI) {
3563 return std::make_tuple(!Imports[LHSI].IsStatic ^
3564 StaticImportAfterNormalImport,
3566 std::make_tuple(!Imports[RHSI].IsStatic ^
3567 StaticImportAfterNormalImport,
3572 Indices.erase(llvm::unique(Indices,
3573 [&](
unsigned LHSI,
unsigned RHSI) {
3574 return Imports[LHSI].Text == Imports[RHSI].Text;
3578 bool CurrentIsStatic = Imports[Indices.front()].IsStatic;
3582 for (
unsigned Index : Indices) {
3583 if (!result.empty()) {
3585 if (CurrentIsStatic != Imports[Index].IsStatic ||
3590 for (StringRef CommentLine : Imports[Index].AssociatedCommentLines) {
3591 result += CommentLine;
3594 result += Imports[Index].Text;
3595 CurrentIsStatic = Imports[Index].IsStatic;
3602 Imports.front().Offset, ImportsBlockSize)))) {
3607 ImportsBlockSize, result));
3611 llvm::errs() <<
toString(std::move(Err)) <<
"\n";
3618const char JavaImportRegexPattern[] =
3619 "^[\t ]*import[\t ]+(static[\t ]*)?([^\t ]*)[\t ]*;";
3628 unsigned SearchFrom = 0;
3629 llvm::Regex ImportRegex(JavaImportRegexPattern);
3634 bool FormattingOff =
false;
3637 auto Pos = Code.find(
'\n', SearchFrom);
3639 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
3641 StringRef Trimmed =
Line.trim();
3643 FormattingOff =
true;
3645 FormattingOff =
false;
3647 if (ImportRegex.match(
Line, &Matches)) {
3648 if (FormattingOff) {
3653 StringRef
Static = Matches[1];
3654 StringRef Identifier = Matches[2];
3655 bool IsStatic =
false;
3656 if (
Static.contains(
"static"))
3658 ImportsInBlock.push_back(
3659 {Identifier,
Line, Prev, AssociatedCommentLines, IsStatic});
3660 AssociatedCommentLines.clear();
3661 }
else if (!Trimmed.empty() && !ImportsInBlock.empty()) {
3663 AssociatedCommentLines.push_back(
Line);
3666 if (Pos == StringRef::npos || Pos + 1 == Code.size())
3668 SearchFrom = Pos + 1;
3670 if (!ImportsInBlock.empty())
3679 return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
3682bool isLikelyXml(StringRef Code) {
return Code.ltrim().starts_with(
"<"); }
3686 StringRef
FileName,
unsigned *Cursor) {
3688 if (!Style.SortIncludes.Enabled || Style.DisableFormat)
3692 if (Style.isJavaScript()) {
3704template <
typename T>
3708 const FormatStyle &Style) {
3709 if (Replaces.
empty())
3712 auto NewCode = applyAllReplacements(Code, Replaces);
3714 return NewCode.takeError();
3719 ProcessFunc(Style, *NewCode, ChangedRanges,
FileName);
3721 return Replaces.
merge(FormatReplaces);
3726 const FormatStyle &Style) {
3729 auto SortIncludes = [](
const FormatStyle &Style, StringRef Code,
3730 std::vector<tooling::Range> Ranges,
3734 auto SortedReplaces =
3736 if (!SortedReplaces)
3737 return SortedReplaces.takeError();
3741 auto Reformat = [](
const FormatStyle &Style, StringRef Code,
3742 std::vector<tooling::Range> Ranges,
3752 return Replace.
getOffset() == std::numeric_limits<unsigned>::max() &&
3758inline bool isHeaderDeletion(
const tooling::Replacement &Replace) {
3759 return Replace.getOffset() == std::numeric_limits<unsigned>::max() &&
3760 Replace.getLength() == 1;
3764tooling::Replacements
3765fixCppIncludeInsertions(StringRef Code,
const tooling::Replacements &Replaces,
3766 const FormatStyle &Style) {
3770 tooling::Replacements HeaderInsertions;
3771 std::set<StringRef> HeadersToDelete;
3772 tooling::Replacements
Result;
3773 for (
const auto &R : Replaces) {
3774 if (isHeaderInsertion(R)) {
3777 consumeError(HeaderInsertions.add(R));
3778 }
else if (isHeaderDeletion(R)) {
3779 HeadersToDelete.insert(R.getReplacementText());
3780 }
else if (R.getOffset() == std::numeric_limits<unsigned>::max()) {
3781 llvm::errs() <<
"Insertions other than header #include insertion are "
3783 << R.getReplacementText() <<
"\n";
3785 consumeError(
Result.add(R));
3788 if (HeaderInsertions.empty() && HeadersToDelete.empty())
3791 StringRef
FileName = Replaces.begin()->getFilePath();
3792 tooling::HeaderIncludes Includes(
FileName, Code, Style.IncludeStyle);
3794 for (
const auto &Header : HeadersToDelete) {
3795 tooling::Replacements Replaces =
3796 Includes.remove(Header.trim(
"\"<>"), Header.starts_with(
"<"));
3797 for (
const auto &R : Replaces) {
3798 auto Err =
Result.add(R);
3801 llvm::errs() <<
"Failed to add header deletion replacement for "
3802 << Header <<
": " <<
toString(std::move(Err)) <<
"\n";
3808 for (
const auto &R : HeaderInsertions) {
3809 auto IncludeDirective = R.getReplacementText();
3812 assert(Matched &&
"Header insertion replacement must have replacement text "
3815 auto IncludeName = Matches[2];
3817 Includes.insert(IncludeName.trim(
"\"<>"), IncludeName.starts_with(
"<"),
3820 auto Err =
Result.add(*Replace);
3822 consumeError(std::move(Err));
3823 unsigned NewOffset =
3824 Result.getShiftedCodePosition(Replace->getOffset());
3825 auto Shifted = tooling::Replacement(
FileName, NewOffset, 0,
3826 Replace->getReplacementText());
3838 const FormatStyle &Style) {
3841 auto Cleanup = [](
const FormatStyle &Style, StringRef Code,
3848 fixCppIncludeInsertions(Code, Replaces, Style);
3853std::pair<tooling::Replacements, unsigned>
3856 unsigned NextStartColumn,
unsigned LastStartColumn, StringRef
FileName,
3858 FormatStyle Expanded = Style;
3862 Expanded.InsertBraces =
false;
3863 Expanded.RemoveBracesLLVM =
false;
3864 Expanded.RemoveParentheses = FormatStyle::RPS_Leave;
3865 Expanded.RemoveSemicolon =
false;
3866 switch (Expanded.RequiresClausePosition) {
3867 case FormatStyle::RCPS_SingleLine:
3868 case FormatStyle::RCPS_WithPreceding:
3869 Expanded.IndentRequiresClause =
false;
3875 if (Expanded.DisableFormat)
3879 if (Expanded.isJavaScript() &&
isMpegTS(Code))
3883 if (Style.isJson()) {
3884 std::vector<tooling::Range> Ranges(1,
tooling::Range(0, Code.size()));
3886 NextStartColumn, LastStartColumn);
3891 Formatter(*Env, Style, Status).process().first;
3893 if (Code.starts_with(
"x = ")) {
3894 Replaces = Replaces.
merge(
3898 if (applyAllReplacements(Code, Replaces))
3899 return {Replaces, 0};
3904 NextStartColumn, LastStartColumn);
3922 if (Style.isCpp()) {
3923 if (Style.QualifierAlignment != FormatStyle::QAS_Leave)
3926 if (Style.RemoveParentheses != FormatStyle::RPS_Leave) {
3927 FormatStyle S = Expanded;
3928 S.RemoveParentheses = Style.RemoveParentheses;
3929 Passes.emplace_back([&, S = std::move(S)](
const Environment &Env) {
3930 return ParensRemover(Env, S).process(
true);
3934 if (Style.InsertBraces) {
3935 FormatStyle S = Expanded;
3936 S.InsertBraces =
true;
3937 Passes.emplace_back([&, S = std::move(S)](
const Environment &Env) {
3938 return BracesInserter(Env, S).process(
true);
3942 if (Style.RemoveBracesLLVM) {
3943 FormatStyle S = Expanded;
3944 S.RemoveBracesLLVM =
true;
3945 Passes.emplace_back([&, S = std::move(S)](
const Environment &Env) {
3946 return BracesRemover(Env, S).process(
true);
3950 if (Style.RemoveSemicolon) {
3951 FormatStyle S = Expanded;
3952 S.RemoveSemicolon =
true;
3953 Passes.emplace_back([&, S = std::move(S)](
const Environment &Env) {
3954 return SemiRemover(Env, S).process();
3958 if (Style.EnumTrailingComma != FormatStyle::ETC_Leave) {
3960 return EnumTrailingCommaEditor(Env, Expanded)
3965 if (Style.FixNamespaceComments) {
3971 if (Style.SortUsingDeclarations != FormatStyle::SUD_Never) {
3978 if (Style.SeparateDefinitionBlocks != FormatStyle::SDS_Leave) {
3984 if (Style.Language == FormatStyle::LK_ObjC &&
3985 !Style.ObjCPropertyAttributeOrder.empty()) {
3991 if (Style.isJavaScript() &&
3992 Style.JavaScriptQuotes != FormatStyle::JSQS_Leave) {
3994 return JavaScriptRequoter(Env, Expanded).process(
true);
3999 return Formatter(Env, Expanded, Status).process();
4002 if (Style.isJavaScript() &&
4003 Style.InsertTrailingCommas == FormatStyle::TCS_Wrapped) {
4005 return TrailingCommaInserter(Env, Expanded).process();
4009 std::optional<std::string> CurrentCode;
4011 unsigned Penalty = 0;
4012 for (
size_t I = 0, E = Passes.size(); I < E; ++I) {
4013 std::pair<tooling::Replacements, unsigned> PassFixes = Passes[I](*Env);
4014 auto NewCode = applyAllReplacements(
4015 CurrentCode ? StringRef(*CurrentCode) : Code, PassFixes.first);
4017 Fixes = Fixes.
merge(PassFixes.first);
4018 Penalty += PassFixes.second;
4020 CurrentCode = std::move(*NewCode);
4024 FirstStartColumn, NextStartColumn, LastStartColumn);
4031 if (Style.QualifierAlignment != FormatStyle::QAS_Leave) {
4037 StringRef OriginalCode = Code.substr(Fix.getOffset(), Fix.getLength());
4038 if (OriginalCode != Fix.getReplacementText()) {
4039 auto Err = NonNoOpFixes.
add(Fix);
4041 llvm::errs() <<
"Error adding replacements : "
4042 <<
toString(std::move(Err)) <<
"\n";
4046 Fixes = std::move(NonNoOpFixes);
4049 return {Fixes, Penalty};
4068 if (Style.Language != FormatStyle::LK_Cpp)
4073 return Cleaner(*Env, Style).process().first;
4078 StringRef
FileName,
bool *IncompleteFormat) {
4081 if (!Status.FormatComplete)
4082 *IncompleteFormat =
true;
4109 auto LexingStd = Style.Standard;
4110 if (LexingStd == FormatStyle::LS_Auto || LexingStd == FormatStyle::LS_Latest)
4111 LexingStd = FormatStyle::LS_Cpp20;
4113 const bool SinceCpp11 = LexingStd >= FormatStyle::LS_Cpp11;
4114 const bool SinceCpp20 = LexingStd >= FormatStyle::LS_Cpp20;
4116 switch (Style.Language) {
4117 case FormatStyle::LK_C:
4120 case FormatStyle::LK_Cpp:
4121 case FormatStyle::LK_ObjC:
4122 LangOpts.CXXOperatorNames = 1;
4123 LangOpts.CPlusPlus11 = SinceCpp11;
4124 LangOpts.CPlusPlus14 = LexingStd >= FormatStyle::LS_Cpp14;
4125 LangOpts.CPlusPlus17 = LexingStd >= FormatStyle::LS_Cpp17;
4126 LangOpts.CPlusPlus20 = SinceCpp20;
4129 LangOpts.CPlusPlus = 1;
4132 LangOpts.Char8 = SinceCpp20;
4136 LangOpts.Digraphs = SinceCpp11;
4138 LangOpts.LineComment = 1;
4141 LangOpts.MicrosoftExt = 1;
4142 LangOpts.DeclSpecKeyword = 1;
4149 "Set coding style. <string> can be:\n"
4150 "1. A preset: LLVM, GNU, Google, Chromium, Microsoft,\n"
4151 " Mozilla, WebKit.\n"
4152 "2. 'file' to load style configuration from a\n"
4153 " .clang-format file in one of the parent directories\n"
4154 " of the source file (for stdin, see --assume-filename).\n"
4155 " If no .clang-format file is found, falls back to\n"
4156 " --fallback-style.\n"
4157 " --style=file is the default.\n"
4158 "3. 'file:<format_file_path>' to explicitly specify\n"
4159 " the configuration file.\n"
4160 "4. \"{key: value, ...}\" to set specific parameters, e.g.:\n"
4161 " --style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
4165 return FormatStyle::LK_C;
4167 return FormatStyle::LK_Java;
4168 if (
FileName.ends_with_insensitive(
".js") ||
4169 FileName.ends_with_insensitive(
".mjs") ||
4170 FileName.ends_with_insensitive(
".cjs") ||
4171 FileName.ends_with_insensitive(
".ts")) {
4172 return FormatStyle::LK_JavaScript;
4175 return FormatStyle::LK_ObjC;
4176 if (
FileName.ends_with_insensitive(
".proto") ||
4177 FileName.ends_with_insensitive(
".protodevel")) {
4178 return FormatStyle::LK_Proto;
4183 if (
FileName.ends_with_insensitive(
".txtpb") ||
4184 FileName.ends_with_insensitive(
".textpb") ||
4185 FileName.ends_with_insensitive(
".pb.txt") ||
4186 FileName.ends_with_insensitive(
".textproto") ||
4187 FileName.ends_with_insensitive(
".asciipb")) {
4188 return FormatStyle::LK_TextProto;
4190 if (
FileName.ends_with_insensitive(
".td"))
4191 return FormatStyle::LK_TableGen;
4192 if (
FileName.ends_with_insensitive(
".cs"))
4193 return FormatStyle::LK_CSharp;
4194 if (
FileName.ends_with_insensitive(
".json") ||
4195 FileName.ends_with_insensitive(
".ipynb")) {
4196 return FormatStyle::LK_Json;
4198 if (
FileName.ends_with_insensitive(
".sv") ||
4199 FileName.ends_with_insensitive(
".svh") ||
4200 FileName.ends_with_insensitive(
".v") ||
4201 FileName.ends_with_insensitive(
".vh")) {
4202 return FormatStyle::LK_Verilog;
4204 return FormatStyle::LK_Cpp;
4212 LangOpts.CPlusPlus = 1;
4213 LangOpts.LineComment = 1;
4215 Lexer Lex(ID, SourceMgr.getBufferOrFake(ID), SourceMgr, LangOpts);
4219 auto Text = StringRef(SourceMgr.getCharacterData(
Tok.getLocation()),
4221 if (!
Text.consume_front(
"// clang-format Language:"))
4226 return FormatStyle::LK_C;
4228 return FormatStyle::LK_Cpp;
4230 return FormatStyle::LK_ObjC;
4233 return FormatStyle::LK_None;
4238 if (GuessedLanguage == FormatStyle::LK_Cpp) {
4239 auto Extension = llvm::sys::path::extension(
FileName);
4242 if (!Code.empty() && (Extension.empty() || Extension ==
".h")) {
4246 Language != FormatStyle::LK_None) {
4251 if (Guesser.isObjC())
4252 return FormatStyle::LK_ObjC;
4255 return GuessedLanguage;
4263llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
4265 FormatStyle *Style,
bool AllowUnknownOptions,
4266 llvm::SourceMgr::DiagHandlerTy DiagHandler,
4268 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Text =
4269 FS->getBufferForFile(ConfigFile.str());
4270 if (
auto EC =
Text.getError())
4273 DiagHandler,
nullptr,
4281 StringRef FallbackStyleName, StringRef Code,
4282 llvm::vfs::FileSystem *FS,
4283 bool AllowUnknownOptions,
4284 llvm::SourceMgr::DiagHandlerTy DiagHandler) {
4292 if (StyleName.starts_with(
"{")) {
4294 StringRef Source =
"<command-line>";
4295 if (std::error_code ec =
4297 AllowUnknownOptions, DiagHandler)) {
4301 if (!Style.InheritsParentConfig)
4304 ChildFormatTextToApply.emplace_back(
4305 llvm::MemoryBuffer::getMemBuffer(StyleName, Source,
false));
4309 FS = llvm::vfs::getRealFileSystem().get();
4312 const bool IsDotHFile =
FileName.ends_with(
".h");
4315 if (!Style.InheritsParentConfig &&
4316 StyleName.starts_with_insensitive(
"file:")) {
4317 auto ConfigFile = StyleName.substr(5);
4318 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Text =
4320 DiagHandler, IsDotHFile);
4321 if (
auto EC =
Text.getError()) {
4326 LLVM_DEBUG(llvm::dbgs()
4327 <<
"Using configuration file " << ConfigFile <<
"\n");
4329 if (!Style.InheritsParentConfig)
4335 ChildFormatTextToApply.emplace_back(std::move(*
Text));
4341 if (!Style.InheritsParentConfig && !StyleName.equals_insensitive(
"file")) {
4344 if (!Style.InheritsParentConfig)
4349 if (std::error_code EC = FS->makeAbsolute(Path))
4353 Style.InheritsParentConfig =
false;
4355 auto dropDiagnosticHandler = [](
const llvm::SMDiagnostic &,
void *) {};
4357 auto applyChildFormatTexts = [&](FormatStyle *Style) {
4358 for (
const auto &MemBuf : llvm::reverse(ChildFormatTextToApply)) {
4361 DiagHandler ? DiagHandler : dropDiagnosticHandler);
4364 static_cast<void>(EC);
4370 FilesToLookFor.push_back(
".clang-format");
4371 FilesToLookFor.push_back(
"_clang-format");
4374 for (StringRef Directory = Path; !Directory.empty();
4375 Directory = llvm::sys::path::parent_path(Directory)) {
4376 auto Status = FS->status(Directory);
4378 Status->getType() != llvm::sys::fs::file_type::directory_file) {
4382 for (
const auto &F : FilesToLookFor) {
4385 llvm::sys::path::append(ConfigFile, F);
4386 LLVM_DEBUG(llvm::dbgs() <<
"Trying " << ConfigFile <<
"...\n");
4388 Status = FS->status(ConfigFile);
4390 Status->getType() != llvm::sys::fs::file_type::regular_file) {
4394 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Text =
4396 DiagHandler, IsDotHFile);
4397 if (
auto EC =
Text.getError()) {
4402 if (!UnsuitableConfigFiles.empty())
4403 UnsuitableConfigFiles.append(
", ");
4404 UnsuitableConfigFiles.append(ConfigFile);
4408 LLVM_DEBUG(llvm::dbgs()
4409 <<
"Using configuration file " << ConfigFile <<
"\n");
4411 if (!Style.InheritsParentConfig) {
4412 if (!ChildFormatTextToApply.empty()) {
4413 LLVM_DEBUG(llvm::dbgs() <<
"Applying child configurations\n");
4414 applyChildFormatTexts(&Style);
4419 LLVM_DEBUG(llvm::dbgs() <<
"Inherits parent configuration\n");
4422 Style.InheritsParentConfig =
false;
4424 ChildFormatTextToApply.emplace_back(std::move(*
Text));
4434 if (!UnsuitableConfigFiles.empty()) {
4437 UnsuitableConfigFiles);
4440 if (!ChildFormatTextToApply.empty()) {
4441 LLVM_DEBUG(llvm::dbgs()
4442 <<
"Applying child configurations on fallback style\n");
4443 applyChildFormatTexts(&FallbackStyle);
4446 return FallbackStyle;
4450 if (Comment == (On ?
"/* clang-format on */" :
"/* clang-format off */"))
4453 static const char ClangFormatOn[] =
"// clang-format on";
4454 static const char ClangFormatOff[] =
"// clang-format off";
4455 const unsigned Size = (On ?
sizeof ClangFormatOn :
sizeof ClangFormatOff) - 1;
4457 return Comment.starts_with(On ? ClangFormatOn : ClangFormatOff) &&
4458 (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, FormatStyle::IndentExternBlockStyle &Value)
static void enumeration(IO &IO, FormatStyle::LambdaBodyIndentationKind &Value)
static void enumeration(IO &IO, FormatStyle::WrapNamespaceBodyWithEmptyLinesStyle &Value)