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::BracedListStyle> {
309 IO.enumCase(
Value,
"Block", FormatStyle::BLS_Block);
310 IO.enumCase(
Value,
"FunctionCall", FormatStyle::BLS_FunctionCall);
311 IO.enumCase(
Value,
"AlignFirstComment", FormatStyle::BLS_AlignFirstComment);
314 IO.enumCase(
Value,
"false", FormatStyle::BLS_Block);
315 IO.enumCase(
Value,
"true", FormatStyle::BLS_AlignFirstComment);
319template <>
struct ScalarEnumerationTraits<FormatStyle::DAGArgStyle> {
321 IO.enumCase(
Value,
"DontBreak", FormatStyle::DAS_DontBreak);
322 IO.enumCase(
Value,
"BreakElements", FormatStyle::DAS_BreakElements);
323 IO.enumCase(
Value,
"BreakAll", FormatStyle::DAS_BreakAll);
328struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
331 IO.enumCase(
Value,
"None", FormatStyle::DRTBS_None);
332 IO.enumCase(
Value,
"All", FormatStyle::DRTBS_All);
333 IO.enumCase(
Value,
"TopLevel", FormatStyle::DRTBS_TopLevel);
336 IO.enumCase(
Value,
"false", FormatStyle::DRTBS_None);
337 IO.enumCase(
Value,
"true", FormatStyle::DRTBS_All);
342struct ScalarEnumerationTraits<FormatStyle::EscapedNewlineAlignmentStyle> {
344 FormatStyle::EscapedNewlineAlignmentStyle &
Value) {
345 IO.enumCase(
Value,
"DontAlign", FormatStyle::ENAS_DontAlign);
346 IO.enumCase(
Value,
"Left", FormatStyle::ENAS_Left);
347 IO.enumCase(
Value,
"LeftWithLastLine", FormatStyle::ENAS_LeftWithLastLine);
348 IO.enumCase(
Value,
"Right", FormatStyle::ENAS_Right);
351 IO.enumCase(
Value,
"true", FormatStyle::ENAS_Left);
352 IO.enumCase(
Value,
"false", FormatStyle::ENAS_Right);
357struct ScalarEnumerationTraits<FormatStyle::EmptyLineAfterAccessModifierStyle> {
360 IO.enumCase(
Value,
"Never", FormatStyle::ELAAMS_Never);
361 IO.enumCase(
Value,
"Leave", FormatStyle::ELAAMS_Leave);
362 IO.enumCase(
Value,
"Always", FormatStyle::ELAAMS_Always);
367struct ScalarEnumerationTraits<
368 FormatStyle::EmptyLineBeforeAccessModifierStyle> {
371 IO.enumCase(
Value,
"Never", FormatStyle::ELBAMS_Never);
372 IO.enumCase(
Value,
"Leave", FormatStyle::ELBAMS_Leave);
373 IO.enumCase(
Value,
"LogicalBlock", FormatStyle::ELBAMS_LogicalBlock);
374 IO.enumCase(
Value,
"Always", FormatStyle::ELBAMS_Always);
379struct ScalarEnumerationTraits<FormatStyle::EnumTrailingCommaStyle> {
381 IO.enumCase(
Value,
"Leave", FormatStyle::ETC_Leave);
382 IO.enumCase(
Value,
"Insert", FormatStyle::ETC_Insert);
383 IO.enumCase(
Value,
"Remove", FormatStyle::ETC_Remove);
388struct ScalarEnumerationTraits<FormatStyle::IndentExternBlockStyle> {
390 IO.enumCase(
Value,
"AfterExternBlock", FormatStyle::IEBS_AfterExternBlock);
391 IO.enumCase(
Value,
"Indent", FormatStyle::IEBS_Indent);
392 IO.enumCase(
Value,
"NoIndent", FormatStyle::IEBS_NoIndent);
393 IO.enumCase(
Value,
"true", FormatStyle::IEBS_Indent);
394 IO.enumCase(
Value,
"false", FormatStyle::IEBS_NoIndent);
398template <>
struct MappingTraits<FormatStyle::IntegerLiteralSeparatorStyle> {
399 static void mapping(IO &IO, FormatStyle::IntegerLiteralSeparatorStyle &
Base) {
400 IO.mapOptional(
"Binary",
Base.Binary);
401 IO.mapOptional(
"BinaryMinDigits",
Base.BinaryMinDigits);
402 IO.mapOptional(
"Decimal",
Base.Decimal);
403 IO.mapOptional(
"DecimalMinDigits",
Base.DecimalMinDigits);
404 IO.mapOptional(
"Hex",
Base.Hex);
405 IO.mapOptional(
"HexMinDigits",
Base.HexMinDigits);
409template <>
struct ScalarEnumerationTraits<FormatStyle::JavaScriptQuoteStyle> {
411 IO.enumCase(
Value,
"Leave", FormatStyle::JSQS_Leave);
412 IO.enumCase(
Value,
"Single", FormatStyle::JSQS_Single);
413 IO.enumCase(
Value,
"Double", FormatStyle::JSQS_Double);
417template <>
struct MappingTraits<FormatStyle::KeepEmptyLinesStyle> {
419 IO.mapOptional(
"AtEndOfFile",
Value.AtEndOfFile);
420 IO.mapOptional(
"AtStartOfBlock",
Value.AtStartOfBlock);
421 IO.mapOptional(
"AtStartOfFile",
Value.AtStartOfFile);
425template <>
struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
427 IO.enumCase(
Value,
"C", FormatStyle::LK_C);
428 IO.enumCase(
Value,
"Cpp", FormatStyle::LK_Cpp);
429 IO.enumCase(
Value,
"Java", FormatStyle::LK_Java);
430 IO.enumCase(
Value,
"JavaScript", FormatStyle::LK_JavaScript);
431 IO.enumCase(
Value,
"ObjC", FormatStyle::LK_ObjC);
432 IO.enumCase(
Value,
"Proto", FormatStyle::LK_Proto);
433 IO.enumCase(
Value,
"TableGen", FormatStyle::LK_TableGen);
434 IO.enumCase(
Value,
"TextProto", FormatStyle::LK_TextProto);
435 IO.enumCase(
Value,
"CSharp", FormatStyle::LK_CSharp);
436 IO.enumCase(
Value,
"Json", FormatStyle::LK_Json);
437 IO.enumCase(
Value,
"Verilog", FormatStyle::LK_Verilog);
441template <>
struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
443 IO.enumCase(
Value,
"c++03", FormatStyle::LS_Cpp03);
444 IO.enumCase(
Value,
"C++03", FormatStyle::LS_Cpp03);
445 IO.enumCase(
Value,
"Cpp03", FormatStyle::LS_Cpp03);
447 IO.enumCase(
Value,
"c++11", FormatStyle::LS_Cpp11);
448 IO.enumCase(
Value,
"C++11", FormatStyle::LS_Cpp11);
450 IO.enumCase(
Value,
"c++14", FormatStyle::LS_Cpp14);
451 IO.enumCase(
Value,
"c++17", FormatStyle::LS_Cpp17);
452 IO.enumCase(
Value,
"c++20", FormatStyle::LS_Cpp20);
454 IO.enumCase(
Value,
"Latest", FormatStyle::LS_Latest);
455 IO.enumCase(
Value,
"Cpp11", FormatStyle::LS_Latest);
456 IO.enumCase(
Value,
"Auto", FormatStyle::LS_Auto);
461struct ScalarEnumerationTraits<FormatStyle::LambdaBodyIndentationKind> {
463 FormatStyle::LambdaBodyIndentationKind &
Value) {
464 IO.enumCase(
Value,
"Signature", FormatStyle::LBI_Signature);
465 IO.enumCase(
Value,
"OuterScope", FormatStyle::LBI_OuterScope);
469template <>
struct ScalarEnumerationTraits<FormatStyle::LineEndingStyle> {
471 IO.enumCase(
Value,
"LF", FormatStyle::LE_LF);
472 IO.enumCase(
Value,
"CRLF", FormatStyle::LE_CRLF);
473 IO.enumCase(
Value,
"DeriveLF", FormatStyle::LE_DeriveLF);
474 IO.enumCase(
Value,
"DeriveCRLF", FormatStyle::LE_DeriveCRLF);
479struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
481 FormatStyle::NamespaceIndentationKind &
Value) {
482 IO.enumCase(
Value,
"None", FormatStyle::NI_None);
483 IO.enumCase(
Value,
"Inner", FormatStyle::NI_Inner);
484 IO.enumCase(
Value,
"All", FormatStyle::NI_All);
489struct ScalarEnumerationTraits<FormatStyle::NumericLiteralComponentStyle> {
491 FormatStyle::NumericLiteralComponentStyle &
Value) {
492 IO.enumCase(
Value,
"Leave", FormatStyle::NLCS_Leave);
493 IO.enumCase(
Value,
"Upper", FormatStyle::NLCS_Upper);
494 IO.enumCase(
Value,
"Lower", FormatStyle::NLCS_Lower);
498template <>
struct MappingTraits<FormatStyle::NumericLiteralCaseStyle> {
499 static void mapping(IO &IO, FormatStyle::NumericLiteralCaseStyle &
Value) {
500 IO.mapOptional(
"ExponentLetter",
Value.ExponentLetter);
501 IO.mapOptional(
"HexDigit",
Value.HexDigit);
502 IO.mapOptional(
"Prefix",
Value.Prefix);
503 IO.mapOptional(
"Suffix",
Value.Suffix);
507template <>
struct ScalarEnumerationTraits<FormatStyle::OperandAlignmentStyle> {
509 IO.enumCase(
Value,
"DontAlign", FormatStyle::OAS_DontAlign);
510 IO.enumCase(
Value,
"Align", FormatStyle::OAS_Align);
511 IO.enumCase(
Value,
"AlignAfterOperator",
512 FormatStyle::OAS_AlignAfterOperator);
515 IO.enumCase(
Value,
"true", FormatStyle::OAS_Align);
516 IO.enumCase(
Value,
"false", FormatStyle::OAS_DontAlign);
521struct ScalarEnumerationTraits<FormatStyle::PackConstructorInitializersStyle> {
524 IO.enumCase(
Value,
"Never", FormatStyle::PCIS_Never);
525 IO.enumCase(
Value,
"BinPack", FormatStyle::PCIS_BinPack);
526 IO.enumCase(
Value,
"CurrentLine", FormatStyle::PCIS_CurrentLine);
527 IO.enumCase(
Value,
"NextLine", FormatStyle::PCIS_NextLine);
528 IO.enumCase(
Value,
"NextLineOnly", FormatStyle::PCIS_NextLineOnly);
532template <>
struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
534 IO.enumCase(
Value,
"Middle", FormatStyle::PAS_Middle);
535 IO.enumCase(
Value,
"Left", FormatStyle::PAS_Left);
536 IO.enumCase(
Value,
"Right", FormatStyle::PAS_Right);
539 IO.enumCase(
Value,
"true", FormatStyle::PAS_Left);
540 IO.enumCase(
Value,
"false", FormatStyle::PAS_Right);
545struct ScalarEnumerationTraits<FormatStyle::PPDirectiveIndentStyle> {
547 IO.enumCase(
Value,
"None", FormatStyle::PPDIS_None);
548 IO.enumCase(
Value,
"AfterHash", FormatStyle::PPDIS_AfterHash);
549 IO.enumCase(
Value,
"BeforeHash", FormatStyle::PPDIS_BeforeHash);
550 IO.enumCase(
Value,
"Leave", FormatStyle::PPDIS_Leave);
555struct ScalarEnumerationTraits<FormatStyle::QualifierAlignmentStyle> {
557 IO.enumCase(
Value,
"Leave", FormatStyle::QAS_Leave);
558 IO.enumCase(
Value,
"Left", FormatStyle::QAS_Left);
559 IO.enumCase(
Value,
"Right", FormatStyle::QAS_Right);
560 IO.enumCase(
Value,
"Custom", FormatStyle::QAS_Custom);
564template <>
struct MappingTraits<FormatStyle::RawStringFormat> {
565 static void mapping(IO &IO, FormatStyle::RawStringFormat &Format) {
566 IO.mapOptional(
"Language", Format.Language);
567 IO.mapOptional(
"Delimiters", Format.Delimiters);
568 IO.mapOptional(
"EnclosingFunctions", Format.EnclosingFunctions);
569 IO.mapOptional(
"CanonicalDelimiter", Format.CanonicalDelimiter);
570 IO.mapOptional(
"BasedOnStyle", Format.BasedOnStyle);
574template <>
struct ScalarEnumerationTraits<FormatStyle::ReflowCommentsStyle> {
576 IO.enumCase(
Value,
"Never", FormatStyle::RCS_Never);
577 IO.enumCase(
Value,
"IndentOnly", FormatStyle::RCS_IndentOnly);
578 IO.enumCase(
Value,
"Always", FormatStyle::RCS_Always);
580 IO.enumCase(
Value,
"false", FormatStyle::RCS_Never);
581 IO.enumCase(
Value,
"true", FormatStyle::RCS_Always);
586struct ScalarEnumerationTraits<FormatStyle::ReferenceAlignmentStyle> {
588 IO.enumCase(
Value,
"Pointer", FormatStyle::RAS_Pointer);
589 IO.enumCase(
Value,
"Middle", FormatStyle::RAS_Middle);
590 IO.enumCase(
Value,
"Left", FormatStyle::RAS_Left);
591 IO.enumCase(
Value,
"Right", FormatStyle::RAS_Right);
596struct ScalarEnumerationTraits<FormatStyle::RemoveParenthesesStyle> {
598 IO.enumCase(
Value,
"Leave", FormatStyle::RPS_Leave);
599 IO.enumCase(
Value,
"MultipleParentheses",
600 FormatStyle::RPS_MultipleParentheses);
601 IO.enumCase(
Value,
"ReturnStatement", FormatStyle::RPS_ReturnStatement);
606struct ScalarEnumerationTraits<FormatStyle::RequiresClausePositionStyle> {
608 FormatStyle::RequiresClausePositionStyle &
Value) {
609 IO.enumCase(
Value,
"OwnLine", FormatStyle::RCPS_OwnLine);
610 IO.enumCase(
Value,
"OwnLineWithBrace", FormatStyle::RCPS_OwnLineWithBrace);
611 IO.enumCase(
Value,
"WithPreceding", FormatStyle::RCPS_WithPreceding);
612 IO.enumCase(
Value,
"WithFollowing", FormatStyle::RCPS_WithFollowing);
613 IO.enumCase(
Value,
"SingleLine", FormatStyle::RCPS_SingleLine);
618struct ScalarEnumerationTraits<FormatStyle::RequiresExpressionIndentationKind> {
621 IO.enumCase(
Value,
"Keyword", FormatStyle::REI_Keyword);
622 IO.enumCase(
Value,
"OuterScope", FormatStyle::REI_OuterScope);
627struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
629 IO.enumCase(
Value,
"None", FormatStyle::RTBS_None);
630 IO.enumCase(
Value,
"Automatic", FormatStyle::RTBS_Automatic);
631 IO.enumCase(
Value,
"ExceptShortType", FormatStyle::RTBS_ExceptShortType);
632 IO.enumCase(
Value,
"All", FormatStyle::RTBS_All);
633 IO.enumCase(
Value,
"TopLevel", FormatStyle::RTBS_TopLevel);
634 IO.enumCase(
Value,
"TopLevelDefinitions",
635 FormatStyle::RTBS_TopLevelDefinitions);
636 IO.enumCase(
Value,
"AllDefinitions", FormatStyle::RTBS_AllDefinitions);
641struct ScalarEnumerationTraits<FormatStyle::SeparateDefinitionStyle> {
643 IO.enumCase(
Value,
"Leave", FormatStyle::SDS_Leave);
644 IO.enumCase(
Value,
"Always", FormatStyle::SDS_Always);
645 IO.enumCase(
Value,
"Never", FormatStyle::SDS_Never);
649template <>
struct ScalarEnumerationTraits<FormatStyle::ShortBlockStyle> {
651 IO.enumCase(
Value,
"Never", FormatStyle::SBS_Never);
652 IO.enumCase(
Value,
"false", FormatStyle::SBS_Never);
653 IO.enumCase(
Value,
"Always", FormatStyle::SBS_Always);
654 IO.enumCase(
Value,
"true", FormatStyle::SBS_Always);
655 IO.enumCase(
Value,
"Empty", FormatStyle::SBS_Empty);
659template <>
struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
661 IO.enumCase(
Value,
"None", FormatStyle::SFS_None);
662 IO.enumCase(
Value,
"false", FormatStyle::SFS_None);
663 IO.enumCase(
Value,
"All", FormatStyle::SFS_All);
664 IO.enumCase(
Value,
"true", FormatStyle::SFS_All);
665 IO.enumCase(
Value,
"Inline", FormatStyle::SFS_Inline);
666 IO.enumCase(
Value,
"InlineOnly", FormatStyle::SFS_InlineOnly);
667 IO.enumCase(
Value,
"Empty", FormatStyle::SFS_Empty);
671template <>
struct ScalarEnumerationTraits<FormatStyle::ShortIfStyle> {
673 IO.enumCase(
Value,
"Never", FormatStyle::SIS_Never);
674 IO.enumCase(
Value,
"WithoutElse", FormatStyle::SIS_WithoutElse);
675 IO.enumCase(
Value,
"OnlyFirstIf", FormatStyle::SIS_OnlyFirstIf);
676 IO.enumCase(
Value,
"AllIfsAndElse", FormatStyle::SIS_AllIfsAndElse);
679 IO.enumCase(
Value,
"Always", FormatStyle::SIS_OnlyFirstIf);
680 IO.enumCase(
Value,
"false", FormatStyle::SIS_Never);
681 IO.enumCase(
Value,
"true", FormatStyle::SIS_WithoutElse);
685template <>
struct ScalarEnumerationTraits<FormatStyle::ShortLambdaStyle> {
687 IO.enumCase(
Value,
"None", FormatStyle::SLS_None);
688 IO.enumCase(
Value,
"false", FormatStyle::SLS_None);
689 IO.enumCase(
Value,
"Empty", FormatStyle::SLS_Empty);
690 IO.enumCase(
Value,
"Inline", FormatStyle::SLS_Inline);
691 IO.enumCase(
Value,
"All", FormatStyle::SLS_All);
692 IO.enumCase(
Value,
"true", FormatStyle::SLS_All);
696template <>
struct MappingTraits<FormatStyle::SortIncludesOptions> {
698 IO.enumCase(
Value,
"Never", FormatStyle::SortIncludesOptions({}));
699 IO.enumCase(
Value,
"CaseInsensitive",
700 FormatStyle::SortIncludesOptions({
true,
703 IO.enumCase(
Value,
"CaseSensitive",
704 FormatStyle::SortIncludesOptions({
true,
709 IO.enumCase(
Value,
"false", FormatStyle::SortIncludesOptions({}));
710 IO.enumCase(
Value,
"true",
711 FormatStyle::SortIncludesOptions({
true,
717 IO.mapOptional(
"Enabled",
Value.Enabled);
718 IO.mapOptional(
"IgnoreCase",
Value.IgnoreCase);
719 IO.mapOptional(
"IgnoreExtension",
Value.IgnoreExtension);
724struct ScalarEnumerationTraits<FormatStyle::SortJavaStaticImportOptions> {
726 FormatStyle::SortJavaStaticImportOptions &
Value) {
727 IO.enumCase(
Value,
"Before", FormatStyle::SJSIO_Before);
728 IO.enumCase(
Value,
"After", FormatStyle::SJSIO_After);
733struct ScalarEnumerationTraits<FormatStyle::SortUsingDeclarationsOptions> {
735 FormatStyle::SortUsingDeclarationsOptions &
Value) {
736 IO.enumCase(
Value,
"Never", FormatStyle::SUD_Never);
737 IO.enumCase(
Value,
"Lexicographic", FormatStyle::SUD_Lexicographic);
738 IO.enumCase(
Value,
"LexicographicNumeric",
739 FormatStyle::SUD_LexicographicNumeric);
742 IO.enumCase(
Value,
"false", FormatStyle::SUD_Never);
743 IO.enumCase(
Value,
"true", FormatStyle::SUD_LexicographicNumeric);
748struct ScalarEnumerationTraits<FormatStyle::SpaceAroundPointerQualifiersStyle> {
751 IO.enumCase(
Value,
"Default", FormatStyle::SAPQ_Default);
752 IO.enumCase(
Value,
"Before", FormatStyle::SAPQ_Before);
753 IO.enumCase(
Value,
"After", FormatStyle::SAPQ_After);
754 IO.enumCase(
Value,
"Both", FormatStyle::SAPQ_Both);
758template <>
struct MappingTraits<FormatStyle::SpaceBeforeParensCustom> {
759 static void mapping(IO &IO, FormatStyle::SpaceBeforeParensCustom &Spacing) {
760 IO.mapOptional(
"AfterControlStatements", Spacing.AfterControlStatements);
761 IO.mapOptional(
"AfterForeachMacros", Spacing.AfterForeachMacros);
762 IO.mapOptional(
"AfterFunctionDefinitionName",
763 Spacing.AfterFunctionDefinitionName);
764 IO.mapOptional(
"AfterFunctionDeclarationName",
765 Spacing.AfterFunctionDeclarationName);
766 IO.mapOptional(
"AfterIfMacros", Spacing.AfterIfMacros);
767 IO.mapOptional(
"AfterNot", Spacing.AfterNot);
768 IO.mapOptional(
"AfterOverloadedOperator", Spacing.AfterOverloadedOperator);
769 IO.mapOptional(
"AfterPlacementOperator", Spacing.AfterPlacementOperator);
770 IO.mapOptional(
"AfterRequiresInClause", Spacing.AfterRequiresInClause);
771 IO.mapOptional(
"AfterRequiresInExpression",
772 Spacing.AfterRequiresInExpression);
773 IO.mapOptional(
"BeforeNonEmptyParentheses",
774 Spacing.BeforeNonEmptyParentheses);
779struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensStyle> {
781 IO.enumCase(
Value,
"Never", FormatStyle::SBPO_Never);
782 IO.enumCase(
Value,
"ControlStatements",
783 FormatStyle::SBPO_ControlStatements);
784 IO.enumCase(
Value,
"ControlStatementsExceptControlMacros",
785 FormatStyle::SBPO_ControlStatementsExceptControlMacros);
786 IO.enumCase(
Value,
"NonEmptyParentheses",
787 FormatStyle::SBPO_NonEmptyParentheses);
788 IO.enumCase(
Value,
"Always", FormatStyle::SBPO_Always);
789 IO.enumCase(
Value,
"Custom", FormatStyle::SBPO_Custom);
792 IO.enumCase(
Value,
"false", FormatStyle::SBPO_Never);
793 IO.enumCase(
Value,
"true", FormatStyle::SBPO_ControlStatements);
794 IO.enumCase(
Value,
"ControlStatementsExceptForEachMacros",
795 FormatStyle::SBPO_ControlStatementsExceptControlMacros);
800struct ScalarEnumerationTraits<FormatStyle::SpaceInEmptyBracesStyle> {
802 IO.enumCase(
Value,
"Always", FormatStyle::SIEB_Always);
803 IO.enumCase(
Value,
"Block", FormatStyle::SIEB_Block);
804 IO.enumCase(
Value,
"Never", FormatStyle::SIEB_Never);
808template <>
struct ScalarEnumerationTraits<FormatStyle::SpacesInAnglesStyle> {
810 IO.enumCase(
Value,
"Never", FormatStyle::SIAS_Never);
811 IO.enumCase(
Value,
"Always", FormatStyle::SIAS_Always);
812 IO.enumCase(
Value,
"Leave", FormatStyle::SIAS_Leave);
815 IO.enumCase(
Value,
"false", FormatStyle::SIAS_Never);
816 IO.enumCase(
Value,
"true", FormatStyle::SIAS_Always);
820template <>
struct MappingTraits<FormatStyle::SpacesInLineComment> {
821 static void mapping(IO &IO, FormatStyle::SpacesInLineComment &Space) {
823 int signedMaximum =
static_cast<int>(Space.Maximum);
824 IO.mapOptional(
"Minimum", Space.Minimum);
825 IO.mapOptional(
"Maximum", signedMaximum);
826 Space.Maximum =
static_cast<unsigned>(signedMaximum);
828 if (Space.Maximum < std::numeric_limits<unsigned>::max())
829 Space.Minimum = std::min(Space.Minimum, Space.Maximum);
833template <>
struct MappingTraits<FormatStyle::SpacesInParensCustom> {
834 static void mapping(IO &IO, FormatStyle::SpacesInParensCustom &Spaces) {
835 IO.mapOptional(
"ExceptDoubleParentheses", Spaces.ExceptDoubleParentheses);
836 IO.mapOptional(
"InCStyleCasts", Spaces.InCStyleCasts);
837 IO.mapOptional(
"InConditionalStatements", Spaces.InConditionalStatements);
838 IO.mapOptional(
"InEmptyParentheses", Spaces.InEmptyParentheses);
839 IO.mapOptional(
"Other", Spaces.Other);
843template <>
struct ScalarEnumerationTraits<FormatStyle::SpacesInParensStyle> {
845 IO.enumCase(
Value,
"Never", FormatStyle::SIPO_Never);
846 IO.enumCase(
Value,
"Custom", FormatStyle::SIPO_Custom);
850template <>
struct ScalarEnumerationTraits<FormatStyle::TrailingCommaStyle> {
852 IO.enumCase(
Value,
"None", FormatStyle::TCS_None);
853 IO.enumCase(
Value,
"Wrapped", FormatStyle::TCS_Wrapped);
858struct ScalarEnumerationTraits<FormatStyle::TrailingCommentsAlignmentKinds> {
860 FormatStyle::TrailingCommentsAlignmentKinds &
Value) {
861 IO.enumCase(
Value,
"Leave", FormatStyle::TCAS_Leave);
862 IO.enumCase(
Value,
"Always", FormatStyle::TCAS_Always);
863 IO.enumCase(
Value,
"Never", FormatStyle::TCAS_Never);
867template <>
struct MappingTraits<FormatStyle::TrailingCommentsAlignmentStyle> {
869 FormatStyle::TrailingCommentsAlignmentStyle &
Value) {
870 IO.enumCase(
Value,
"Leave",
871 FormatStyle::TrailingCommentsAlignmentStyle(
872 {FormatStyle::TCAS_Leave, 0}));
874 IO.enumCase(
Value,
"Always",
875 FormatStyle::TrailingCommentsAlignmentStyle(
876 {FormatStyle::TCAS_Always, 0}));
878 IO.enumCase(
Value,
"Never",
879 FormatStyle::TrailingCommentsAlignmentStyle(
880 {FormatStyle::TCAS_Never, 0}));
883 IO.enumCase(
Value,
"true",
884 FormatStyle::TrailingCommentsAlignmentStyle(
885 {FormatStyle::TCAS_Always, 0}));
886 IO.enumCase(
Value,
"false",
887 FormatStyle::TrailingCommentsAlignmentStyle(
888 {FormatStyle::TCAS_Never, 0}));
892 FormatStyle::TrailingCommentsAlignmentStyle &
Value) {
893 IO.mapOptional(
"Kind",
Value.Kind);
894 IO.mapOptional(
"OverEmptyLines",
Value.OverEmptyLines);
898template <>
struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
900 IO.enumCase(
Value,
"Never", FormatStyle::UT_Never);
901 IO.enumCase(
Value,
"false", FormatStyle::UT_Never);
902 IO.enumCase(
Value,
"Always", FormatStyle::UT_Always);
903 IO.enumCase(
Value,
"true", FormatStyle::UT_Always);
904 IO.enumCase(
Value,
"ForIndentation", FormatStyle::UT_ForIndentation);
905 IO.enumCase(
Value,
"ForContinuationAndIndentation",
906 FormatStyle::UT_ForContinuationAndIndentation);
907 IO.enumCase(
Value,
"AlignWithSpaces", FormatStyle::UT_AlignWithSpaces);
912struct ScalarEnumerationTraits<
913 FormatStyle::WrapNamespaceBodyWithEmptyLinesStyle> {
916 FormatStyle::WrapNamespaceBodyWithEmptyLinesStyle &
Value) {
917 IO.enumCase(
Value,
"Never", FormatStyle::WNBWELS_Never);
918 IO.enumCase(
Value,
"Always", FormatStyle::WNBWELS_Always);
919 IO.enumCase(
Value,
"Leave", FormatStyle::WNBWELS_Leave);
923template <>
struct MappingTraits<FormatStyle> {
924 static void mapping(IO &IO, FormatStyle &Style) {
926 IO.mapOptional(
"Language", Style.Language);
928 StringRef BasedOnStyle;
929 if (IO.outputting()) {
930 StringRef Styles[] = {
"LLVM",
"Google",
"Chromium",
"Mozilla",
931 "WebKit",
"GNU",
"Microsoft",
"clang-format"};
932 for (StringRef StyleName : Styles) {
933 FormatStyle PredefinedStyle;
935 Style == PredefinedStyle) {
936 BasedOnStyle = StyleName;
941 IO.mapOptional(
"BasedOnStyle", BasedOnStyle);
942 if (!BasedOnStyle.empty()) {
943 FormatStyle::LanguageKind OldLanguage = Style.Language;
944 FormatStyle::LanguageKind Language =
945 ((FormatStyle *)IO.getContext())->Language;
947 IO.setError(Twine(
"Unknown value for BasedOnStyle: ", BasedOnStyle));
950 Style.Language = OldLanguage;
965 const bool IsGoogleOrChromium = BasedOnStyle.equals_insensitive(
"google") ||
966 BasedOnStyle.equals_insensitive(
"chromium");
967 bool OnCurrentLine = IsGoogleOrChromium;
968 bool OnNextLine =
true;
970 bool BreakBeforeInheritanceComma =
false;
971 bool BreakConstructorInitializersBeforeComma =
false;
973 bool DeriveLineEnding =
true;
974 bool UseCRLF =
false;
976 bool SpaceInEmptyBlock =
false;
977 bool SpaceInEmptyParentheses =
false;
978 bool SpacesInConditionalStatement =
false;
979 bool SpacesInCStyleCastParentheses =
false;
980 bool SpacesInParentheses =
false;
983 if (!IO.outputting()) {
984 IO.mapOptional(
"AlignEscapedNewlinesLeft", Style.AlignEscapedNewlines);
985 IO.mapOptional(
"AllowAllConstructorInitializersOnNextLine", OnNextLine);
986 IO.mapOptional(
"AlwaysBreakAfterReturnType", Style.BreakAfterReturnType);
987 IO.mapOptional(
"AlwaysBreakTemplateDeclarations",
988 Style.BreakTemplateDeclarations);
989 IO.mapOptional(
"BreakBeforeInheritanceComma",
990 BreakBeforeInheritanceComma);
991 IO.mapOptional(
"BreakConstructorInitializersBeforeComma",
992 BreakConstructorInitializersBeforeComma);
993 IO.mapOptional(
"ConstructorInitializerAllOnOneLineOrOnePerLine",
995 IO.mapOptional(
"DeriveLineEnding", DeriveLineEnding);
996 IO.mapOptional(
"DerivePointerBinding", Style.DerivePointerAlignment);
997 IO.mapOptional(
"KeepEmptyLinesAtEOF", Style.KeepEmptyLines.AtEndOfFile);
998 IO.mapOptional(
"KeepEmptyLinesAtTheStartOfBlocks",
999 Style.KeepEmptyLines.AtStartOfBlock);
1000 IO.mapOptional(
"IndentFunctionDeclarationAfterType",
1001 Style.IndentWrappedFunctionNames);
1002 IO.mapOptional(
"IndentRequires", Style.IndentRequiresClause);
1003 IO.mapOptional(
"PointerBindsToType", Style.PointerAlignment);
1004 IO.mapOptional(
"SpaceAfterControlStatementKeyword",
1005 Style.SpaceBeforeParens);
1006 IO.mapOptional(
"SpaceInEmptyBlock", SpaceInEmptyBlock);
1007 IO.mapOptional(
"SpaceInEmptyParentheses", SpaceInEmptyParentheses);
1008 IO.mapOptional(
"SpacesInConditionalStatement",
1009 SpacesInConditionalStatement);
1010 IO.mapOptional(
"SpacesInCStyleCastParentheses",
1011 SpacesInCStyleCastParentheses);
1012 IO.mapOptional(
"SpacesInParentheses", SpacesInParentheses);
1013 IO.mapOptional(
"UseCRLF", UseCRLF);
1016 IO.mapOptional(
"AccessModifierOffset", Style.AccessModifierOffset);
1017 IO.mapOptional(
"AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
1018 IO.mapOptional(
"AlignArrayOfStructures", Style.AlignArrayOfStructures);
1019 IO.mapOptional(
"AlignConsecutiveAssignments",
1020 Style.AlignConsecutiveAssignments);
1021 IO.mapOptional(
"AlignConsecutiveBitFields",
1022 Style.AlignConsecutiveBitFields);
1023 IO.mapOptional(
"AlignConsecutiveDeclarations",
1024 Style.AlignConsecutiveDeclarations);
1025 IO.mapOptional(
"AlignConsecutiveMacros", Style.AlignConsecutiveMacros);
1026 IO.mapOptional(
"AlignConsecutiveShortCaseStatements",
1027 Style.AlignConsecutiveShortCaseStatements);
1028 IO.mapOptional(
"AlignConsecutiveTableGenBreakingDAGArgColons",
1029 Style.AlignConsecutiveTableGenBreakingDAGArgColons);
1030 IO.mapOptional(
"AlignConsecutiveTableGenCondOperatorColons",
1031 Style.AlignConsecutiveTableGenCondOperatorColons);
1032 IO.mapOptional(
"AlignConsecutiveTableGenDefinitionColons",
1033 Style.AlignConsecutiveTableGenDefinitionColons);
1034 IO.mapOptional(
"AlignEscapedNewlines", Style.AlignEscapedNewlines);
1035 IO.mapOptional(
"AlignOperands", Style.AlignOperands);
1036 IO.mapOptional(
"AlignTrailingComments", Style.AlignTrailingComments);
1037 IO.mapOptional(
"AllowAllArgumentsOnNextLine",
1038 Style.AllowAllArgumentsOnNextLine);
1039 IO.mapOptional(
"AllowAllParametersOfDeclarationOnNextLine",
1040 Style.AllowAllParametersOfDeclarationOnNextLine);
1041 IO.mapOptional(
"AllowBreakBeforeNoexceptSpecifier",
1042 Style.AllowBreakBeforeNoexceptSpecifier);
1043 IO.mapOptional(
"AllowBreakBeforeQtProperty",
1044 Style.AllowBreakBeforeQtProperty);
1045 IO.mapOptional(
"AllowShortBlocksOnASingleLine",
1046 Style.AllowShortBlocksOnASingleLine);
1047 IO.mapOptional(
"AllowShortCaseExpressionOnASingleLine",
1048 Style.AllowShortCaseExpressionOnASingleLine);
1049 IO.mapOptional(
"AllowShortCaseLabelsOnASingleLine",
1050 Style.AllowShortCaseLabelsOnASingleLine);
1051 IO.mapOptional(
"AllowShortCompoundRequirementOnASingleLine",
1052 Style.AllowShortCompoundRequirementOnASingleLine);
1053 IO.mapOptional(
"AllowShortEnumsOnASingleLine",
1054 Style.AllowShortEnumsOnASingleLine);
1055 IO.mapOptional(
"AllowShortFunctionsOnASingleLine",
1056 Style.AllowShortFunctionsOnASingleLine);
1057 IO.mapOptional(
"AllowShortIfStatementsOnASingleLine",
1058 Style.AllowShortIfStatementsOnASingleLine);
1059 IO.mapOptional(
"AllowShortLambdasOnASingleLine",
1060 Style.AllowShortLambdasOnASingleLine);
1061 IO.mapOptional(
"AllowShortLoopsOnASingleLine",
1062 Style.AllowShortLoopsOnASingleLine);
1063 IO.mapOptional(
"AllowShortNamespacesOnASingleLine",
1064 Style.AllowShortNamespacesOnASingleLine);
1065 IO.mapOptional(
"AlwaysBreakAfterDefinitionReturnType",
1066 Style.AlwaysBreakAfterDefinitionReturnType);
1067 IO.mapOptional(
"AlwaysBreakBeforeMultilineStrings",
1068 Style.AlwaysBreakBeforeMultilineStrings);
1069 IO.mapOptional(
"AttributeMacros", Style.AttributeMacros);
1070 IO.mapOptional(
"BinPackArguments", Style.BinPackArguments);
1071 IO.mapOptional(
"BinPackLongBracedList", Style.BinPackLongBracedList);
1072 IO.mapOptional(
"BinPackParameters", Style.BinPackParameters);
1073 IO.mapOptional(
"BitFieldColonSpacing", Style.BitFieldColonSpacing);
1074 IO.mapOptional(
"BracedInitializerIndentWidth",
1075 Style.BracedInitializerIndentWidth);
1076 IO.mapOptional(
"BraceWrapping", Style.BraceWrapping);
1077 IO.mapOptional(
"BreakAdjacentStringLiterals",
1078 Style.BreakAdjacentStringLiterals);
1079 IO.mapOptional(
"BreakAfterAttributes", Style.BreakAfterAttributes);
1080 IO.mapOptional(
"BreakAfterJavaFieldAnnotations",
1081 Style.BreakAfterJavaFieldAnnotations);
1082 IO.mapOptional(
"BreakAfterReturnType", Style.BreakAfterReturnType);
1083 IO.mapOptional(
"BreakArrays", Style.BreakArrays);
1084 IO.mapOptional(
"BreakBeforeBinaryOperators",
1085 Style.BreakBeforeBinaryOperators);
1086 IO.mapOptional(
"BreakBeforeConceptDeclarations",
1087 Style.BreakBeforeConceptDeclarations);
1088 IO.mapOptional(
"BreakBeforeBraces", Style.BreakBeforeBraces);
1089 IO.mapOptional(
"BreakBeforeInlineASMColon",
1090 Style.BreakBeforeInlineASMColon);
1091 IO.mapOptional(
"BreakBeforeTemplateCloser",
1092 Style.BreakBeforeTemplateCloser);
1093 IO.mapOptional(
"BreakBeforeTernaryOperators",
1094 Style.BreakBeforeTernaryOperators);
1095 IO.mapOptional(
"BreakBinaryOperations", Style.BreakBinaryOperations);
1096 IO.mapOptional(
"BreakConstructorInitializers",
1097 Style.BreakConstructorInitializers);
1098 IO.mapOptional(
"BreakFunctionDefinitionParameters",
1099 Style.BreakFunctionDefinitionParameters);
1100 IO.mapOptional(
"BreakInheritanceList", Style.BreakInheritanceList);
1101 IO.mapOptional(
"BreakStringLiterals", Style.BreakStringLiterals);
1102 IO.mapOptional(
"BreakTemplateDeclarations",
1103 Style.BreakTemplateDeclarations);
1104 IO.mapOptional(
"ColumnLimit", Style.ColumnLimit);
1105 IO.mapOptional(
"CommentPragmas", Style.CommentPragmas);
1106 IO.mapOptional(
"CompactNamespaces", Style.CompactNamespaces);
1107 IO.mapOptional(
"ConstructorInitializerIndentWidth",
1108 Style.ConstructorInitializerIndentWidth);
1109 IO.mapOptional(
"ContinuationIndentWidth", Style.ContinuationIndentWidth);
1110 IO.mapOptional(
"Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
1111 IO.mapOptional(
"DerivePointerAlignment", Style.DerivePointerAlignment);
1112 IO.mapOptional(
"DisableFormat", Style.DisableFormat);
1113 IO.mapOptional(
"EmptyLineAfterAccessModifier",
1114 Style.EmptyLineAfterAccessModifier);
1115 IO.mapOptional(
"EmptyLineBeforeAccessModifier",
1116 Style.EmptyLineBeforeAccessModifier);
1117 IO.mapOptional(
"EnumTrailingComma", Style.EnumTrailingComma);
1118 IO.mapOptional(
"ExperimentalAutoDetectBinPacking",
1119 Style.ExperimentalAutoDetectBinPacking);
1120 IO.mapOptional(
"FixNamespaceComments", Style.FixNamespaceComments);
1121 IO.mapOptional(
"ForEachMacros", Style.ForEachMacros);
1122 IO.mapOptional(
"IfMacros", Style.IfMacros);
1123 IO.mapOptional(
"IncludeBlocks", Style.IncludeStyle.IncludeBlocks);
1124 IO.mapOptional(
"IncludeCategories", Style.IncludeStyle.IncludeCategories);
1125 IO.mapOptional(
"IncludeIsMainRegex", Style.IncludeStyle.IncludeIsMainRegex);
1126 IO.mapOptional(
"IncludeIsMainSourceRegex",
1127 Style.IncludeStyle.IncludeIsMainSourceRegex);
1128 IO.mapOptional(
"IndentAccessModifiers", Style.IndentAccessModifiers);
1129 IO.mapOptional(
"IndentCaseBlocks", Style.IndentCaseBlocks);
1130 IO.mapOptional(
"IndentCaseLabels", Style.IndentCaseLabels);
1131 IO.mapOptional(
"IndentExportBlock", Style.IndentExportBlock);
1132 IO.mapOptional(
"IndentExternBlock", Style.IndentExternBlock);
1133 IO.mapOptional(
"IndentGotoLabels", Style.IndentGotoLabels);
1134 IO.mapOptional(
"IndentPPDirectives", Style.IndentPPDirectives);
1135 IO.mapOptional(
"IndentRequiresClause", Style.IndentRequiresClause);
1136 IO.mapOptional(
"IndentWidth", Style.IndentWidth);
1137 IO.mapOptional(
"IndentWrappedFunctionNames",
1138 Style.IndentWrappedFunctionNames);
1139 IO.mapOptional(
"InsertBraces", Style.InsertBraces);
1140 IO.mapOptional(
"InsertNewlineAtEOF", Style.InsertNewlineAtEOF);
1141 IO.mapOptional(
"InsertTrailingCommas", Style.InsertTrailingCommas);
1142 IO.mapOptional(
"IntegerLiteralSeparator", Style.IntegerLiteralSeparator);
1143 IO.mapOptional(
"JavaImportGroups", Style.JavaImportGroups);
1144 IO.mapOptional(
"JavaScriptQuotes", Style.JavaScriptQuotes);
1145 IO.mapOptional(
"JavaScriptWrapImports", Style.JavaScriptWrapImports);
1146 IO.mapOptional(
"KeepEmptyLines", Style.KeepEmptyLines);
1147 IO.mapOptional(
"KeepFormFeed", Style.KeepFormFeed);
1148 IO.mapOptional(
"LambdaBodyIndentation", Style.LambdaBodyIndentation);
1149 IO.mapOptional(
"LineEnding", Style.LineEnding);
1150 IO.mapOptional(
"MacroBlockBegin", Style.MacroBlockBegin);
1151 IO.mapOptional(
"MacroBlockEnd", Style.MacroBlockEnd);
1152 IO.mapOptional(
"Macros", Style.Macros);
1153 IO.mapOptional(
"MacrosSkippedByRemoveParentheses",
1154 Style.MacrosSkippedByRemoveParentheses);
1155 IO.mapOptional(
"MainIncludeChar", Style.IncludeStyle.MainIncludeChar);
1156 IO.mapOptional(
"MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
1157 IO.mapOptional(
"NamespaceIndentation", Style.NamespaceIndentation);
1158 IO.mapOptional(
"NamespaceMacros", Style.NamespaceMacros);
1159 IO.mapOptional(
"NumericLiteralCase", Style.NumericLiteralCase);
1160 IO.mapOptional(
"ObjCBinPackProtocolList", Style.ObjCBinPackProtocolList);
1161 IO.mapOptional(
"ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
1162 IO.mapOptional(
"ObjCBreakBeforeNestedBlockParam",
1163 Style.ObjCBreakBeforeNestedBlockParam);
1164 IO.mapOptional(
"ObjCPropertyAttributeOrder",
1165 Style.ObjCPropertyAttributeOrder);
1166 IO.mapOptional(
"ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
1167 IO.mapOptional(
"ObjCSpaceBeforeProtocolList",
1168 Style.ObjCSpaceBeforeProtocolList);
1169 IO.mapOptional(
"OneLineFormatOffRegex", Style.OneLineFormatOffRegex);
1170 IO.mapOptional(
"PackConstructorInitializers",
1171 Style.PackConstructorInitializers);
1172 IO.mapOptional(
"PenaltyBreakAssignment", Style.PenaltyBreakAssignment);
1173 IO.mapOptional(
"PenaltyBreakBeforeFirstCallParameter",
1174 Style.PenaltyBreakBeforeFirstCallParameter);
1175 IO.mapOptional(
"PenaltyBreakBeforeMemberAccess",
1176 Style.PenaltyBreakBeforeMemberAccess);
1177 IO.mapOptional(
"PenaltyBreakComment", Style.PenaltyBreakComment);
1178 IO.mapOptional(
"PenaltyBreakFirstLessLess",
1179 Style.PenaltyBreakFirstLessLess);
1180 IO.mapOptional(
"PenaltyBreakOpenParenthesis",
1181 Style.PenaltyBreakOpenParenthesis);
1182 IO.mapOptional(
"PenaltyBreakScopeResolution",
1183 Style.PenaltyBreakScopeResolution);
1184 IO.mapOptional(
"PenaltyBreakString", Style.PenaltyBreakString);
1185 IO.mapOptional(
"PenaltyBreakTemplateDeclaration",
1186 Style.PenaltyBreakTemplateDeclaration);
1187 IO.mapOptional(
"PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
1188 IO.mapOptional(
"PenaltyIndentedWhitespace",
1189 Style.PenaltyIndentedWhitespace);
1190 IO.mapOptional(
"PenaltyReturnTypeOnItsOwnLine",
1191 Style.PenaltyReturnTypeOnItsOwnLine);
1192 IO.mapOptional(
"PointerAlignment", Style.PointerAlignment);
1193 IO.mapOptional(
"PPIndentWidth", Style.PPIndentWidth);
1194 IO.mapOptional(
"QualifierAlignment", Style.QualifierAlignment);
1196 if (Style.QualifierAlignment == FormatStyle::QAS_Right)
1197 Style.QualifierOrder = {
"type",
"const",
"volatile"};
1198 else if (Style.QualifierAlignment == FormatStyle::QAS_Left)
1199 Style.QualifierOrder = {
"const",
"volatile",
"type"};
1200 else if (Style.QualifierAlignment == FormatStyle::QAS_Custom)
1201 IO.mapOptional(
"QualifierOrder", Style.QualifierOrder);
1202 IO.mapOptional(
"RawStringFormats", Style.RawStringFormats);
1203 IO.mapOptional(
"ReferenceAlignment", Style.ReferenceAlignment);
1204 IO.mapOptional(
"ReflowComments", Style.ReflowComments);
1205 IO.mapOptional(
"RemoveBracesLLVM", Style.RemoveBracesLLVM);
1206 IO.mapOptional(
"RemoveEmptyLinesInUnwrappedLines",
1207 Style.RemoveEmptyLinesInUnwrappedLines);
1208 IO.mapOptional(
"RemoveParentheses", Style.RemoveParentheses);
1209 IO.mapOptional(
"RemoveSemicolon", Style.RemoveSemicolon);
1210 IO.mapOptional(
"RequiresClausePosition", Style.RequiresClausePosition);
1211 IO.mapOptional(
"RequiresExpressionIndentation",
1212 Style.RequiresExpressionIndentation);
1213 IO.mapOptional(
"SeparateDefinitionBlocks", Style.SeparateDefinitionBlocks);
1214 IO.mapOptional(
"ShortNamespaceLines", Style.ShortNamespaceLines);
1215 IO.mapOptional(
"SkipMacroDefinitionBody", Style.SkipMacroDefinitionBody);
1216 IO.mapOptional(
"SortIncludes", Style.SortIncludes);
1217 IO.mapOptional(
"SortJavaStaticImport", Style.SortJavaStaticImport);
1218 IO.mapOptional(
"SortUsingDeclarations", Style.SortUsingDeclarations);
1219 IO.mapOptional(
"SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
1220 IO.mapOptional(
"SpaceAfterLogicalNot", Style.SpaceAfterLogicalNot);
1221 IO.mapOptional(
"SpaceAfterOperatorKeyword",
1222 Style.SpaceAfterOperatorKeyword);
1223 IO.mapOptional(
"SpaceAfterTemplateKeyword",
1224 Style.SpaceAfterTemplateKeyword);
1225 IO.mapOptional(
"SpaceAroundPointerQualifiers",
1226 Style.SpaceAroundPointerQualifiers);
1227 IO.mapOptional(
"SpaceBeforeAssignmentOperators",
1228 Style.SpaceBeforeAssignmentOperators);
1229 IO.mapOptional(
"SpaceBeforeCaseColon", Style.SpaceBeforeCaseColon);
1230 IO.mapOptional(
"SpaceBeforeCpp11BracedList",
1231 Style.SpaceBeforeCpp11BracedList);
1232 IO.mapOptional(
"SpaceBeforeCtorInitializerColon",
1233 Style.SpaceBeforeCtorInitializerColon);
1234 IO.mapOptional(
"SpaceBeforeInheritanceColon",
1235 Style.SpaceBeforeInheritanceColon);
1236 IO.mapOptional(
"SpaceBeforeJsonColon", Style.SpaceBeforeJsonColon);
1237 IO.mapOptional(
"SpaceBeforeParens", Style.SpaceBeforeParens);
1238 IO.mapOptional(
"SpaceBeforeParensOptions", Style.SpaceBeforeParensOptions);
1239 IO.mapOptional(
"SpaceBeforeRangeBasedForLoopColon",
1240 Style.SpaceBeforeRangeBasedForLoopColon);
1241 IO.mapOptional(
"SpaceBeforeSquareBrackets",
1242 Style.SpaceBeforeSquareBrackets);
1243 IO.mapOptional(
"SpaceInEmptyBraces", Style.SpaceInEmptyBraces);
1244 IO.mapOptional(
"SpacesBeforeTrailingComments",
1245 Style.SpacesBeforeTrailingComments);
1246 IO.mapOptional(
"SpacesInAngles", Style.SpacesInAngles);
1247 IO.mapOptional(
"SpacesInContainerLiterals",
1248 Style.SpacesInContainerLiterals);
1249 IO.mapOptional(
"SpacesInLineCommentPrefix",
1250 Style.SpacesInLineCommentPrefix);
1251 IO.mapOptional(
"SpacesInParens", Style.SpacesInParens);
1252 IO.mapOptional(
"SpacesInParensOptions", Style.SpacesInParensOptions);
1253 IO.mapOptional(
"SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
1254 IO.mapOptional(
"Standard", Style.Standard);
1255 IO.mapOptional(
"StatementAttributeLikeMacros",
1256 Style.StatementAttributeLikeMacros);
1257 IO.mapOptional(
"StatementMacros", Style.StatementMacros);
1258 IO.mapOptional(
"TableGenBreakingDAGArgOperators",
1259 Style.TableGenBreakingDAGArgOperators);
1260 IO.mapOptional(
"TableGenBreakInsideDAGArg",
1261 Style.TableGenBreakInsideDAGArg);
1262 IO.mapOptional(
"TabWidth", Style.TabWidth);
1263 IO.mapOptional(
"TemplateNames", Style.TemplateNames);
1264 IO.mapOptional(
"TypeNames", Style.TypeNames);
1265 IO.mapOptional(
"TypenameMacros", Style.TypenameMacros);
1266 IO.mapOptional(
"UseTab", Style.UseTab);
1267 IO.mapOptional(
"VariableTemplates", Style.VariableTemplates);
1268 IO.mapOptional(
"VerilogBreakBetweenInstancePorts",
1269 Style.VerilogBreakBetweenInstancePorts);
1270 IO.mapOptional(
"WhitespaceSensitiveMacros",
1271 Style.WhitespaceSensitiveMacros);
1272 IO.mapOptional(
"WrapNamespaceBodyWithEmptyLines",
1273 Style.WrapNamespaceBodyWithEmptyLines);
1278 if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
1279 Style.BreakAfterReturnType == FormatStyle::RTBS_None) {
1280 if (Style.AlwaysBreakAfterDefinitionReturnType ==
1281 FormatStyle::DRTBS_All) {
1282 Style.BreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
1283 }
else if (Style.AlwaysBreakAfterDefinitionReturnType ==
1284 FormatStyle::DRTBS_TopLevel) {
1285 Style.BreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
1291 if (BreakBeforeInheritanceComma &&
1292 Style.BreakInheritanceList == FormatStyle::BILS_BeforeColon) {
1293 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
1299 if (BreakConstructorInitializersBeforeComma &&
1300 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon) {
1301 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
1304 if (!IsGoogleOrChromium) {
1305 if (Style.PackConstructorInitializers == FormatStyle::PCIS_BinPack &&
1307 Style.PackConstructorInitializers = OnNextLine
1308 ? FormatStyle::PCIS_NextLine
1309 : FormatStyle::PCIS_CurrentLine;
1311 }
else if (Style.PackConstructorInitializers ==
1312 FormatStyle::PCIS_NextLine) {
1314 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
1315 else if (!OnNextLine)
1316 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
1319 if (Style.LineEnding == FormatStyle::LE_DeriveLF) {
1320 if (!DeriveLineEnding)
1321 Style.LineEnding = UseCRLF ? FormatStyle::LE_CRLF : FormatStyle::LE_LF;
1323 Style.LineEnding = FormatStyle::LE_DeriveCRLF;
1328 if (SpaceInEmptyBlock &&
1329 Style.SpaceInEmptyBraces == FormatStyle::SIEB_Never) {
1330 Style.SpaceInEmptyBraces = FormatStyle::SIEB_Block;
1333 if (Style.SpacesInParens != FormatStyle::SIPO_Custom &&
1334 (SpacesInParentheses || SpaceInEmptyParentheses ||
1335 SpacesInConditionalStatement || SpacesInCStyleCastParentheses)) {
1336 if (SpacesInParentheses) {
1338 Style.SpacesInParensOptions.ExceptDoubleParentheses =
false;
1339 Style.SpacesInParensOptions.InConditionalStatements =
true;
1340 Style.SpacesInParensOptions.InCStyleCasts =
1341 SpacesInCStyleCastParentheses;
1342 Style.SpacesInParensOptions.InEmptyParentheses =
1343 SpaceInEmptyParentheses;
1344 Style.SpacesInParensOptions.Other =
true;
1346 Style.SpacesInParensOptions = {};
1347 Style.SpacesInParensOptions.InConditionalStatements =
1348 SpacesInConditionalStatement;
1349 Style.SpacesInParensOptions.InCStyleCasts =
1350 SpacesInCStyleCastParentheses;
1351 Style.SpacesInParensOptions.InEmptyParentheses =
1352 SpaceInEmptyParentheses;
1354 Style.SpacesInParens = FormatStyle::SIPO_Custom;
1364template <>
struct DocumentListTraits<
std::vector<FormatStyle>> {
1365 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
1368 static FormatStyle &
element(IO &IO, std::vector<FormatStyle> &Seq,
1370 if (Index >= Seq.size()) {
1371 assert(Index == Seq.size());
1372 FormatStyle Template;
1373 if (!Seq.empty() && Seq[0].Language == FormatStyle::LK_None) {
1376 Template = *((
const FormatStyle *)IO.getContext());
1377 Template.Language = FormatStyle::LK_None;
1379 Seq.resize(Index + 1, Template);
1399 return llvm::make_error<llvm::StringError>(Message,
1400 llvm::inconvertibleErrorCode());
1404 return "clang-format.parse_error";
1412 return "Invalid argument";
1414 return "Unsuitable";
1416 return "trailing comma insertion cannot be used with bin packing";
1418 return "Invalid qualifier specified in QualifierOrder";
1420 return "Duplicate qualifier specified in QualifierOrder";
1422 return "Missing type in QualifierOrder";
1424 return "Missing QualifierOrder";
1426 llvm_unreachable(
"unexpected parse error");
1430 if (Expanded.BreakBeforeBraces == FormatStyle::BS_Custom)
1432 Expanded.BraceWrapping = {
false,
1434 FormatStyle::BWACS_Never,
1450 switch (Expanded.BreakBeforeBraces) {
1451 case FormatStyle::BS_Linux:
1452 Expanded.BraceWrapping.AfterClass =
true;
1453 Expanded.BraceWrapping.AfterFunction =
true;
1454 Expanded.BraceWrapping.AfterNamespace =
true;
1456 case FormatStyle::BS_Mozilla:
1457 Expanded.BraceWrapping.AfterClass =
true;
1458 Expanded.BraceWrapping.AfterEnum =
true;
1459 Expanded.BraceWrapping.AfterFunction =
true;
1460 Expanded.BraceWrapping.AfterStruct =
true;
1461 Expanded.BraceWrapping.AfterUnion =
true;
1462 Expanded.BraceWrapping.AfterExternBlock =
true;
1463 Expanded.BraceWrapping.SplitEmptyFunction =
true;
1464 Expanded.BraceWrapping.SplitEmptyRecord =
false;
1466 case FormatStyle::BS_Stroustrup:
1467 Expanded.BraceWrapping.AfterFunction =
true;
1468 Expanded.BraceWrapping.BeforeCatch =
true;
1469 Expanded.BraceWrapping.BeforeElse =
true;
1471 case FormatStyle::BS_Allman:
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.AfterUnion =
true;
1481 Expanded.BraceWrapping.AfterExternBlock =
true;
1482 Expanded.BraceWrapping.BeforeCatch =
true;
1483 Expanded.BraceWrapping.BeforeElse =
true;
1484 Expanded.BraceWrapping.BeforeLambdaBody =
true;
1486 case FormatStyle::BS_Whitesmiths:
1487 Expanded.BraceWrapping.AfterCaseLabel =
true;
1488 Expanded.BraceWrapping.AfterClass =
true;
1489 Expanded.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1490 Expanded.BraceWrapping.AfterEnum =
true;
1491 Expanded.BraceWrapping.AfterFunction =
true;
1492 Expanded.BraceWrapping.AfterNamespace =
true;
1493 Expanded.BraceWrapping.AfterObjCDeclaration =
true;
1494 Expanded.BraceWrapping.AfterStruct =
true;
1495 Expanded.BraceWrapping.AfterExternBlock =
true;
1496 Expanded.BraceWrapping.BeforeCatch =
true;
1497 Expanded.BraceWrapping.BeforeElse =
true;
1498 Expanded.BraceWrapping.BeforeLambdaBody =
true;
1500 case FormatStyle::BS_GNU:
1501 Expanded.BraceWrapping = {
1504 FormatStyle::BWACS_Always,
1521 case FormatStyle::BS_WebKit:
1522 Expanded.BraceWrapping.AfterFunction =
true;
1530 if (Expanded.SpaceBeforeParens == FormatStyle::SBPO_Custom)
1533 Expanded.SpaceBeforeParensOptions = {};
1534 Expanded.SpaceBeforeParensOptions.AfterPlacementOperator =
true;
1536 switch (Expanded.SpaceBeforeParens) {
1537 case FormatStyle::SBPO_ControlStatements:
1538 Expanded.SpaceBeforeParensOptions.AfterControlStatements =
true;
1539 Expanded.SpaceBeforeParensOptions.AfterForeachMacros =
true;
1540 Expanded.SpaceBeforeParensOptions.AfterIfMacros =
true;
1542 case FormatStyle::SBPO_ControlStatementsExceptControlMacros:
1543 Expanded.SpaceBeforeParensOptions.AfterControlStatements =
true;
1545 case FormatStyle::SBPO_NonEmptyParentheses:
1546 Expanded.SpaceBeforeParensOptions.BeforeNonEmptyParentheses =
true;
1554 if (Expanded.SpacesInParens == FormatStyle::SIPO_Custom)
1556 assert(Expanded.SpacesInParens == FormatStyle::SIPO_Never);
1558 Expanded.SpacesInParensOptions = {};
1562 FormatStyle LLVMStyle;
1563 LLVMStyle.AccessModifierOffset = -2;
1564 LLVMStyle.AlignAfterOpenBracket = FormatStyle::BAS_Align;
1565 LLVMStyle.AlignArrayOfStructures = FormatStyle::AIAS_None;
1566 LLVMStyle.AlignConsecutiveAssignments = {};
1567 LLVMStyle.AlignConsecutiveAssignments.PadOperators =
true;
1568 LLVMStyle.AlignConsecutiveBitFields = {};
1569 LLVMStyle.AlignConsecutiveDeclarations = {};
1570 LLVMStyle.AlignConsecutiveDeclarations.AlignFunctionDeclarations =
true;
1571 LLVMStyle.AlignConsecutiveMacros = {};
1572 LLVMStyle.AlignConsecutiveShortCaseStatements = {};
1573 LLVMStyle.AlignConsecutiveTableGenBreakingDAGArgColons = {};
1574 LLVMStyle.AlignConsecutiveTableGenCondOperatorColons = {};
1575 LLVMStyle.AlignConsecutiveTableGenDefinitionColons = {};
1576 LLVMStyle.AlignEscapedNewlines = FormatStyle::ENAS_Right;
1577 LLVMStyle.AlignOperands = FormatStyle::OAS_Align;
1578 LLVMStyle.AlignTrailingComments = {};
1579 LLVMStyle.AlignTrailingComments.Kind = FormatStyle::TCAS_Always;
1580 LLVMStyle.AlignTrailingComments.OverEmptyLines = 0;
1581 LLVMStyle.AllowAllArgumentsOnNextLine =
true;
1582 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine =
true;
1583 LLVMStyle.AllowBreakBeforeNoexceptSpecifier = FormatStyle::BBNSS_Never;
1584 LLVMStyle.AllowBreakBeforeQtProperty =
false;
1585 LLVMStyle.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
1586 LLVMStyle.AllowShortCaseExpressionOnASingleLine =
true;
1587 LLVMStyle.AllowShortCaseLabelsOnASingleLine =
false;
1588 LLVMStyle.AllowShortCompoundRequirementOnASingleLine =
true;
1589 LLVMStyle.AllowShortEnumsOnASingleLine =
true;
1590 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
1591 LLVMStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
1592 LLVMStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
1593 LLVMStyle.AllowShortLoopsOnASingleLine =
false;
1594 LLVMStyle.AllowShortNamespacesOnASingleLine =
false;
1595 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
1596 LLVMStyle.AlwaysBreakBeforeMultilineStrings =
false;
1597 LLVMStyle.AttributeMacros.push_back(
"__capability");
1598 LLVMStyle.BinPackArguments =
true;
1599 LLVMStyle.BinPackLongBracedList =
true;
1600 LLVMStyle.BinPackParameters = FormatStyle::BPPS_BinPack;
1601 LLVMStyle.BitFieldColonSpacing = FormatStyle::BFCS_Both;
1602 LLVMStyle.BracedInitializerIndentWidth = -1;
1603 LLVMStyle.BraceWrapping = {
false,
1605 FormatStyle::BWACS_Never,
1621 LLVMStyle.BreakAdjacentStringLiterals =
true;
1622 LLVMStyle.BreakAfterAttributes = FormatStyle::ABS_Leave;
1623 LLVMStyle.BreakAfterJavaFieldAnnotations =
false;
1624 LLVMStyle.BreakAfterReturnType = FormatStyle::RTBS_None;
1625 LLVMStyle.BreakArrays =
true;
1626 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
1627 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
1628 LLVMStyle.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Always;
1629 LLVMStyle.BreakBeforeInlineASMColon = FormatStyle::BBIAS_OnlyMultiline;
1630 LLVMStyle.BreakBeforeTemplateCloser =
false;
1631 LLVMStyle.BreakBeforeTernaryOperators =
true;
1632 LLVMStyle.BreakBinaryOperations = FormatStyle::BBO_Never;
1633 LLVMStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
1634 LLVMStyle.BreakFunctionDefinitionParameters =
false;
1635 LLVMStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
1636 LLVMStyle.BreakStringLiterals =
true;
1637 LLVMStyle.BreakTemplateDeclarations = FormatStyle::BTDS_MultiLine;
1638 LLVMStyle.ColumnLimit = 80;
1639 LLVMStyle.CommentPragmas =
"^ IWYU pragma:";
1640 LLVMStyle.CompactNamespaces =
false;
1641 LLVMStyle.ConstructorInitializerIndentWidth = 4;
1642 LLVMStyle.ContinuationIndentWidth = 4;
1643 LLVMStyle.Cpp11BracedListStyle = FormatStyle::BLS_AlignFirstComment;
1644 LLVMStyle.DerivePointerAlignment =
false;
1645 LLVMStyle.DisableFormat =
false;
1646 LLVMStyle.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
1647 LLVMStyle.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
1648 LLVMStyle.EnumTrailingComma = FormatStyle::ETC_Leave;
1649 LLVMStyle.ExperimentalAutoDetectBinPacking =
false;
1650 LLVMStyle.FixNamespaceComments =
true;
1651 LLVMStyle.ForEachMacros.push_back(
"foreach");
1652 LLVMStyle.ForEachMacros.push_back(
"Q_FOREACH");
1653 LLVMStyle.ForEachMacros.push_back(
"BOOST_FOREACH");
1654 LLVMStyle.IfMacros.push_back(
"KJ_IF_MAYBE");
1656 LLVMStyle.IncludeStyle.IncludeCategories = {
1657 {
"^\"(llvm|llvm-c|clang|clang-c)/", 2, 0,
false},
1658 {
"^(<|\"(gtest|gmock|isl|json)/)", 3, 0,
false},
1659 {
".*", 1, 0,
false}};
1660 LLVMStyle.IncludeStyle.IncludeIsMainRegex =
"(Test)?$";
1661 LLVMStyle.IncludeStyle.MainIncludeChar = tooling::IncludeStyle::MICD_Quote;
1662 LLVMStyle.IndentAccessModifiers =
false;
1663 LLVMStyle.IndentCaseBlocks =
false;
1664 LLVMStyle.IndentCaseLabels =
false;
1665 LLVMStyle.IndentExportBlock =
true;
1666 LLVMStyle.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
1667 LLVMStyle.IndentGotoLabels =
true;
1668 LLVMStyle.IndentPPDirectives = FormatStyle::PPDIS_None;
1669 LLVMStyle.IndentRequiresClause =
true;
1670 LLVMStyle.IndentWidth = 2;
1671 LLVMStyle.IndentWrappedFunctionNames =
false;
1672 LLVMStyle.InheritsParentConfig =
false;
1673 LLVMStyle.InsertBraces =
false;
1674 LLVMStyle.InsertNewlineAtEOF =
false;
1675 LLVMStyle.InsertTrailingCommas = FormatStyle::TCS_None;
1676 LLVMStyle.IntegerLiteralSeparator = {
1680 LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
1681 LLVMStyle.JavaScriptWrapImports =
true;
1682 LLVMStyle.KeepEmptyLines = {
1687 LLVMStyle.KeepFormFeed =
false;
1688 LLVMStyle.LambdaBodyIndentation = FormatStyle::LBI_Signature;
1690 LLVMStyle.LineEnding = FormatStyle::LE_DeriveLF;
1691 LLVMStyle.MaxEmptyLinesToKeep = 1;
1692 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
1693 LLVMStyle.NumericLiteralCase = {FormatStyle::NLCS_Leave,
1694 FormatStyle::NLCS_Leave,
1695 FormatStyle::NLCS_Leave,
1696 FormatStyle::NLCS_Leave};
1697 LLVMStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Auto;
1698 LLVMStyle.ObjCBlockIndentWidth = 2;
1699 LLVMStyle.ObjCBreakBeforeNestedBlockParam =
true;
1700 LLVMStyle.ObjCSpaceAfterProperty =
false;
1701 LLVMStyle.ObjCSpaceBeforeProtocolList =
true;
1702 LLVMStyle.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
1703 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
1704 LLVMStyle.PPIndentWidth = -1;
1705 LLVMStyle.QualifierAlignment = FormatStyle::QAS_Leave;
1706 LLVMStyle.ReferenceAlignment = FormatStyle::RAS_Pointer;
1707 LLVMStyle.ReflowComments = FormatStyle::RCS_Always;
1708 LLVMStyle.RemoveBracesLLVM =
false;
1709 LLVMStyle.RemoveEmptyLinesInUnwrappedLines =
false;
1710 LLVMStyle.RemoveParentheses = FormatStyle::RPS_Leave;
1711 LLVMStyle.RemoveSemicolon =
false;
1712 LLVMStyle.RequiresClausePosition = FormatStyle::RCPS_OwnLine;
1713 LLVMStyle.RequiresExpressionIndentation = FormatStyle::REI_OuterScope;
1714 LLVMStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Leave;
1715 LLVMStyle.ShortNamespaceLines = 1;
1716 LLVMStyle.SkipMacroDefinitionBody =
false;
1717 LLVMStyle.SortIncludes = {
true,
false,
1719 LLVMStyle.SortJavaStaticImport = FormatStyle::SJSIO_Before;
1720 LLVMStyle.SortUsingDeclarations = FormatStyle::SUD_LexicographicNumeric;
1721 LLVMStyle.SpaceAfterCStyleCast =
false;
1722 LLVMStyle.SpaceAfterLogicalNot =
false;
1723 LLVMStyle.SpaceAfterOperatorKeyword =
false;
1724 LLVMStyle.SpaceAfterTemplateKeyword =
true;
1725 LLVMStyle.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
1726 LLVMStyle.SpaceBeforeAssignmentOperators =
true;
1727 LLVMStyle.SpaceBeforeCaseColon =
false;
1728 LLVMStyle.SpaceBeforeCpp11BracedList =
false;
1729 LLVMStyle.SpaceBeforeCtorInitializerColon =
true;
1730 LLVMStyle.SpaceBeforeInheritanceColon =
true;
1731 LLVMStyle.SpaceBeforeJsonColon =
false;
1732 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
1733 LLVMStyle.SpaceBeforeParensOptions = {};
1734 LLVMStyle.SpaceBeforeParensOptions.AfterControlStatements =
true;
1735 LLVMStyle.SpaceBeforeParensOptions.AfterForeachMacros =
true;
1736 LLVMStyle.SpaceBeforeParensOptions.AfterIfMacros =
true;
1737 LLVMStyle.SpaceBeforeRangeBasedForLoopColon =
true;
1738 LLVMStyle.SpaceBeforeSquareBrackets =
false;
1739 LLVMStyle.SpaceInEmptyBraces = FormatStyle::SIEB_Never;
1740 LLVMStyle.SpacesBeforeTrailingComments = 1;
1741 LLVMStyle.SpacesInAngles = FormatStyle::SIAS_Never;
1742 LLVMStyle.SpacesInContainerLiterals =
true;
1743 LLVMStyle.SpacesInLineCommentPrefix = {
1744 1, std::numeric_limits<unsigned>::max()};
1745 LLVMStyle.SpacesInParens = FormatStyle::SIPO_Never;
1746 LLVMStyle.SpacesInSquareBrackets =
false;
1747 LLVMStyle.Standard = FormatStyle::LS_Latest;
1748 LLVMStyle.StatementAttributeLikeMacros.push_back(
"Q_EMIT");
1749 LLVMStyle.StatementMacros.push_back(
"Q_UNUSED");
1750 LLVMStyle.StatementMacros.push_back(
"QT_REQUIRE_VERSION");
1751 LLVMStyle.TableGenBreakingDAGArgOperators = {};
1752 LLVMStyle.TableGenBreakInsideDAGArg = FormatStyle::DAS_DontBreak;
1753 LLVMStyle.TabWidth = 8;
1754 LLVMStyle.UseTab = FormatStyle::UT_Never;
1755 LLVMStyle.VerilogBreakBetweenInstancePorts =
true;
1756 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"BOOST_PP_STRINGIZE");
1757 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"CF_SWIFT_NAME");
1758 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"NS_SWIFT_NAME");
1759 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"PP_STRINGIZE");
1760 LLVMStyle.WhitespaceSensitiveMacros.push_back(
"STRINGIZE");
1761 LLVMStyle.WrapNamespaceBodyWithEmptyLines = FormatStyle::WNBWELS_Leave;
1764 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
1765 LLVMStyle.PenaltyBreakBeforeMemberAccess = 150;
1766 LLVMStyle.PenaltyBreakComment = 300;
1767 LLVMStyle.PenaltyBreakFirstLessLess = 120;
1768 LLVMStyle.PenaltyBreakOpenParenthesis = 0;
1769 LLVMStyle.PenaltyBreakScopeResolution = 500;
1770 LLVMStyle.PenaltyBreakString = 1000;
1772 LLVMStyle.PenaltyExcessCharacter = 1'000'000;
1773 LLVMStyle.PenaltyIndentedWhitespace = 0;
1774 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
1778 case FormatStyle::LK_TableGen:
1779 LLVMStyle.SpacesInContainerLiterals =
false;
1781 case FormatStyle::LK_Json:
1782 LLVMStyle.ColumnLimit = 0;
1784 case FormatStyle::LK_Verilog:
1785 LLVMStyle.IndentCaseLabels =
true;
1786 LLVMStyle.SpacesInContainerLiterals =
false;
1796 if (
Language == FormatStyle::LK_TextProto) {
1798 GoogleStyle.Language = FormatStyle::LK_TextProto;
1805 GoogleStyle.AccessModifierOffset = -1;
1806 GoogleStyle.AlignEscapedNewlines = FormatStyle::ENAS_Left;
1807 GoogleStyle.AllowShortIfStatementsOnASingleLine =
1808 FormatStyle::SIS_WithoutElse;
1809 GoogleStyle.AllowShortLoopsOnASingleLine =
true;
1810 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
true;
1812 GoogleStyle.AttributeMacros.push_back(
"absl_nonnull");
1813 GoogleStyle.AttributeMacros.push_back(
"absl_nullable");
1814 GoogleStyle.AttributeMacros.push_back(
"absl_nullability_unknown");
1815 GoogleStyle.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
1817 GoogleStyle.IncludeStyle.IncludeCategories = {{
"^<ext/.*\\.h>", 2, 0,
false},
1818 {
"^<.*\\.h>", 1, 0,
false},
1819 {
"^<.*", 2, 0,
false},
1820 {
".*", 3, 0,
false}};
1821 GoogleStyle.IncludeStyle.IncludeIsMainRegex =
"([-_](test|unittest))?$";
1822 GoogleStyle.IndentCaseLabels =
true;
1823 GoogleStyle.KeepEmptyLines.AtStartOfBlock =
false;
1824 GoogleStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
1825 GoogleStyle.ObjCSpaceAfterProperty =
false;
1826 GoogleStyle.ObjCSpaceBeforeProtocolList =
true;
1827 GoogleStyle.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
1828 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
1829 GoogleStyle.RawStringFormats = {
1831 FormatStyle::LK_Cpp,
1848 FormatStyle::LK_TextProto,
1860 "PARSE_PARTIAL_TEXT_PROTO",
1864 "ParseTextProtoOrDie",
1866 "ParsePartialTestProto",
1873 GoogleStyle.SpacesBeforeTrailingComments = 2;
1874 GoogleStyle.Standard = FormatStyle::LS_Auto;
1876 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
1877 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
1879 if (
Language == FormatStyle::LK_Java) {
1880 GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
1881 GoogleStyle.AlignOperands = FormatStyle::OAS_DontAlign;
1882 GoogleStyle.AlignTrailingComments = {};
1883 GoogleStyle.AlignTrailingComments.Kind = FormatStyle::TCAS_Never;
1884 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
1885 GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
1886 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
1887 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
1888 GoogleStyle.ColumnLimit = 100;
1889 GoogleStyle.SpaceAfterCStyleCast =
true;
1890 GoogleStyle.SpacesBeforeTrailingComments = 1;
1891 }
else if (
Language == FormatStyle::LK_JavaScript) {
1892 GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
1893 GoogleStyle.AlignOperands = FormatStyle::OAS_DontAlign;
1894 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
1896 GoogleStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
1897 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
1898 GoogleStyle.BreakBeforeTernaryOperators =
false;
1901 GoogleStyle.CommentPragmas =
"(taze:|^/[ \t]*<|tslint:|@see)";
1905 GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single;
1906 GoogleStyle.JavaScriptWrapImports =
false;
1907 GoogleStyle.MaxEmptyLinesToKeep = 3;
1908 GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
1909 GoogleStyle.SpacesInContainerLiterals =
false;
1910 }
else if (
Language == FormatStyle::LK_Proto) {
1911 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
1912 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
1918 GoogleStyle.BreakStringLiterals =
false;
1919 GoogleStyle.Cpp11BracedListStyle = FormatStyle::BLS_Block;
1920 GoogleStyle.SpacesInContainerLiterals =
false;
1921 }
else if (
Language == FormatStyle::LK_ObjC) {
1922 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
1923 GoogleStyle.ColumnLimit = 100;
1924 GoogleStyle.DerivePointerAlignment =
true;
1928 GoogleStyle.IncludeStyle.IncludeBlocks =
1930 }
else if (
Language == FormatStyle::LK_CSharp) {
1931 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
1932 GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
1933 GoogleStyle.BreakStringLiterals =
false;
1934 GoogleStyle.ColumnLimit = 100;
1935 GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
1961 ChromiumStyle.IncludeStyle.IncludeBlocks =
1964 if (
Language == FormatStyle::LK_Java) {
1965 ChromiumStyle.AllowShortIfStatementsOnASingleLine =
1966 FormatStyle::SIS_WithoutElse;
1967 ChromiumStyle.BreakAfterJavaFieldAnnotations =
true;
1968 ChromiumStyle.ContinuationIndentWidth = 8;
1969 ChromiumStyle.IndentWidth = 4;
1972 ChromiumStyle.JavaImportGroups = {
1979 "com.google.android.apps.chrome",
1984 }
else if (
Language == FormatStyle::LK_JavaScript) {
1985 ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
1986 ChromiumStyle.AllowShortLoopsOnASingleLine =
false;
1988 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine =
false;
1989 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
1990 ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
1991 ChromiumStyle.AllowShortLoopsOnASingleLine =
false;
1992 ChromiumStyle.BinPackParameters = FormatStyle::BPPS_OnePerLine;
1993 ChromiumStyle.DerivePointerAlignment =
false;
1994 if (
Language == FormatStyle::LK_ObjC)
1995 ChromiumStyle.ColumnLimit = 80;
1997 return ChromiumStyle;
2002 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine =
false;
2003 MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
2004 MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
2005 FormatStyle::DRTBS_TopLevel;
2006 MozillaStyle.BinPackArguments =
false;
2007 MozillaStyle.BinPackParameters = FormatStyle::BPPS_OnePerLine;
2008 MozillaStyle.BreakAfterReturnType = FormatStyle::RTBS_TopLevel;
2009 MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
2010 MozillaStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
2011 MozillaStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
2012 MozillaStyle.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
2013 MozillaStyle.ConstructorInitializerIndentWidth = 2;
2014 MozillaStyle.ContinuationIndentWidth = 2;
2015 MozillaStyle.Cpp11BracedListStyle = FormatStyle::BLS_Block;
2016 MozillaStyle.FixNamespaceComments =
false;
2017 MozillaStyle.IndentCaseLabels =
true;
2018 MozillaStyle.ObjCSpaceAfterProperty =
true;
2019 MozillaStyle.ObjCSpaceBeforeProtocolList =
false;
2020 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
2021 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
2022 MozillaStyle.SpaceAfterTemplateKeyword =
false;
2023 return MozillaStyle;
2028 Style.AccessModifierOffset = -4;
2029 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
2030 Style.AlignOperands = FormatStyle::OAS_DontAlign;
2031 Style.AlignTrailingComments = {};
2032 Style.AlignTrailingComments.Kind = FormatStyle::TCAS_Never;
2033 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
2034 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
2035 Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
2036 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
2037 Style.ColumnLimit = 0;
2038 Style.Cpp11BracedListStyle = FormatStyle::BLS_Block;
2039 Style.FixNamespaceComments =
false;
2040 Style.IndentWidth = 4;
2041 Style.NamespaceIndentation = FormatStyle::NI_Inner;
2042 Style.ObjCBlockIndentWidth = 4;
2043 Style.ObjCSpaceAfterProperty =
true;
2044 Style.PointerAlignment = FormatStyle::PAS_Left;
2045 Style.SpaceBeforeCpp11BracedList =
true;
2046 Style.SpaceInEmptyBraces = FormatStyle::SIEB_Always;
2052 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
2053 Style.BreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
2054 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
2055 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
2056 Style.BreakBeforeTernaryOperators =
true;
2057 Style.ColumnLimit = 79;
2058 Style.Cpp11BracedListStyle = FormatStyle::BLS_Block;
2059 Style.FixNamespaceComments =
false;
2060 Style.KeepFormFeed =
true;
2061 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
2067 Style.ColumnLimit = 120;
2069 Style.IndentWidth = 4;
2070 Style.UseTab = FormatStyle::UT_Never;
2071 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2072 Style.BraceWrapping.AfterClass =
true;
2073 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2074 Style.BraceWrapping.AfterEnum =
true;
2075 Style.BraceWrapping.AfterFunction =
true;
2076 Style.BraceWrapping.AfterNamespace =
true;
2077 Style.BraceWrapping.AfterObjCDeclaration =
true;
2078 Style.BraceWrapping.AfterStruct =
true;
2079 Style.BraceWrapping.AfterExternBlock =
true;
2080 Style.BraceWrapping.BeforeCatch =
true;
2081 Style.BraceWrapping.BeforeElse =
true;
2082 Style.BraceWrapping.BeforeWhile =
false;
2083 Style.PenaltyReturnTypeOnItsOwnLine = 1000;
2084 Style.AllowShortEnumsOnASingleLine =
false;
2085 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
2086 Style.AllowShortCaseLabelsOnASingleLine =
false;
2087 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
2088 Style.AllowShortLoopsOnASingleLine =
false;
2089 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
2090 Style.BreakAfterReturnType = FormatStyle::RTBS_None;
2096 Style.InsertBraces =
true;
2097 Style.InsertNewlineAtEOF =
true;
2098 Style.IntegerLiteralSeparator.Decimal = 3;
2099 Style.IntegerLiteralSeparator.DecimalMinDigits = 5;
2100 Style.LineEnding = FormatStyle::LE_LF;
2101 Style.RemoveBracesLLVM =
true;
2102 Style.RemoveEmptyLinesInUnwrappedLines =
true;
2103 Style.RemoveParentheses = FormatStyle::RPS_ReturnStatement;
2104 Style.RemoveSemicolon =
true;
2110 NoStyle.DisableFormat =
true;
2111 NoStyle.SortIncludes = {};
2112 NoStyle.SortUsingDeclarations = FormatStyle::SUD_Never;
2117 FormatStyle *Style) {
2118 if (Name.equals_insensitive(
"llvm"))
2120 else if (Name.equals_insensitive(
"chromium"))
2122 else if (Name.equals_insensitive(
"mozilla"))
2124 else if (Name.equals_insensitive(
"google"))
2126 else if (Name.equals_insensitive(
"webkit"))
2128 else if (Name.equals_insensitive(
"gnu"))
2130 else if (Name.equals_insensitive(
"microsoft"))
2132 else if (Name.equals_insensitive(
"clang-format"))
2134 else if (Name.equals_insensitive(
"none"))
2136 else if (Name.equals_insensitive(
"inheritparentconfig"))
2137 Style->InheritsParentConfig =
true;
2147 if (Style->QualifierOrder.empty())
2151 for (
const auto &Qualifier : Style->QualifierOrder) {
2152 if (Qualifier ==
"type")
2156 if (token == tok::identifier)
2161 std::set<std::string> UniqueQualifiers(Style->QualifierOrder.begin(),
2162 Style->QualifierOrder.end());
2163 if (Style->QualifierOrder.size() != UniqueQualifiers.size()) {
2164 LLVM_DEBUG(llvm::dbgs()
2165 <<
"Duplicate Qualifiers " << Style->QualifierOrder.size()
2166 <<
" vs " << UniqueQualifiers.size() <<
"\n");
2171 if (!llvm::is_contained(Style->QualifierOrder,
"type"))
2178 FormatStyle *Style,
bool AllowUnknownOptions,
2179 llvm::SourceMgr::DiagHandlerTy DiagHandler,
2180 void *DiagHandlerCtxt,
bool IsDotHFile) {
2182 FormatStyle::LanguageKind
Language = Style->Language;
2183 assert(
Language != FormatStyle::LK_None);
2184 if (Config.getBuffer().trim().empty())
2186 Style->StyleSet.Clear();
2187 std::vector<FormatStyle> Styles;
2188 llvm::yaml::Input Input(Config,
nullptr, DiagHandler,
2194 Input.setContext(Style);
2195 Input.setAllowUnknownKeys(AllowUnknownOptions);
2198 return Input.error();
2202 const auto StyleCount = Styles.size();
2205 for (
unsigned I = 1; I < StyleCount; ++I) {
2206 const auto Lang = Styles[I].Language;
2207 if (Lang == FormatStyle::LK_None)
2210 for (
unsigned J = 0; J < I; ++J) {
2212 LLVM_DEBUG(llvm::dbgs()
2213 <<
"Duplicate languages in the config file on positions "
2214 << J <<
" and " << I <<
'\n');
2220 int LanguagePos = -1;
2226 for (
unsigned I = 0; I < StyleCount; ++I) {
2227 const auto Lang = Styles[I].Language;
2232 if (Lang == FormatStyle::LK_Cpp)
2234 else if (Lang == FormatStyle::LK_C)
2241 if (LanguagePos < 0) {
2242 if (Styles[0].
Language == FormatStyle::LK_None)
2244 else if (IsDotHFile &&
Language == FormatStyle::LK_Cpp)
2246 else if (!IsDotHFile &&
Language == FormatStyle::LK_C)
2247 LanguagePos = CppPos;
2248 if (LanguagePos < 0)
2252 for (
const auto &S : llvm::reverse(llvm::drop_begin(Styles)))
2253 Style->StyleSet.Add(S);
2255 *Style = Styles[LanguagePos];
2257 if (LanguagePos == 0) {
2258 if (Style->Language == FormatStyle::LK_None)
2260 Style->StyleSet.Add(*Style);
2263 if (Style->InsertTrailingCommas != FormatStyle::TCS_None &&
2264 Style->BinPackArguments) {
2268 if (Style->QualifierAlignment != FormatStyle::QAS_Leave)
2275 llvm::raw_string_ostream Stream(
Text);
2276 llvm::yaml::Output Output(Stream);
2279 FormatStyle NonConstStyle = Style;
2283 Output << NonConstStyle;
2285 return Stream.str();
2288std::optional<FormatStyle>
2289FormatStyle::FormatStyleSet::Get(FormatStyle::LanguageKind
Language)
const {
2291 return std::nullopt;
2293 if (It == Styles->end())
2294 return std::nullopt;
2295 FormatStyle Style = It->second;
2296 Style.StyleSet = *
this;
2300void FormatStyle::FormatStyleSet::Add(FormatStyle Style) {
2301 assert(Style.Language !=
LK_None &&
2302 "Cannot add a style for LK_None to a StyleSet");
2304 !Style.StyleSet.Styles &&
2305 "Cannot add a style associated with an existing StyleSet to a StyleSet");
2307 Styles = std::make_shared<MapType>();
2308 (*Styles)[Style.Language] = std::move(Style);
2311void FormatStyle::FormatStyleSet::Clear() { Styles.reset(); }
2313std::optional<FormatStyle>
2314FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind
Language)
const {
2321 const SourceManager &SourceMgr, tooling::Replacements &
Result,
2322 StringRef
Text =
"") {
2323 const auto &
Tok = Token.Tok;
2324 SourceLocation Start;
2326 Start =
Tok.getLocation();
2329 Start = Token.WhitespaceRange.getBegin();
2332 cantFail(
Result.add(tooling::Replacement(SourceMgr, Range,
Text)));
2337 ParensRemover(
const Environment &Env,
const FormatStyle &Style)
2338 : TokenAnalyzer(Env, Style) {}
2340 std::pair<tooling::Replacements, unsigned>
2341 analyze(TokenAnnotator &Annotator,
2342 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2343 FormatTokenLexer &Tokens)
override {
2344 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2345 tooling::Replacements
Result;
2346 removeParens(AnnotatedLines,
Result);
2351 void removeParens(SmallVectorImpl<AnnotatedLine *> &Lines,
2352 tooling::Replacements &
Result) {
2353 const auto &SourceMgr = Env.getSourceManager();
2354 for (
auto *
Line : Lines) {
2355 if (!
Line->Children.empty())
2357 if (!
Line->Affected)
2359 for (
const auto *Token =
Line->First; Token && !Token->Finalized;
2360 Token = Token->Next) {
2361 if (Token->Optional && Token->isOneOf(tok::l_paren, tok::r_paren))
2370 BracesInserter(
const Environment &Env,
const FormatStyle &Style)
2371 : TokenAnalyzer(Env, Style) {}
2373 std::pair<tooling::Replacements, unsigned>
2374 analyze(TokenAnnotator &Annotator,
2375 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2376 FormatTokenLexer &Tokens)
override {
2377 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2378 tooling::Replacements
Result;
2379 insertBraces(AnnotatedLines,
Result);
2384 void insertBraces(SmallVectorImpl<AnnotatedLine *> &Lines,
2385 tooling::Replacements &
Result) {
2386 const auto &SourceMgr = Env.getSourceManager();
2387 int OpeningBraceSurplus = 0;
2388 for (AnnotatedLine *
Line : Lines) {
2389 if (!
Line->Children.empty())
2391 if (!
Line->Affected && OpeningBraceSurplus == 0)
2394 Token = Token->Next) {
2401 if (!
Line->Affected)
2403 Brace = Token->is(tok::comment) ?
"\n{" :
"{";
2404 ++OpeningBraceSurplus;
2406 if (OpeningBraceSurplus == 0)
2413 Token->BraceCount = 0;
2414 const auto Start = Token->Tok.getEndLoc();
2415 cantFail(
Result.add(tooling::Replacement(SourceMgr, Start, 0,
Brace)));
2418 assert(OpeningBraceSurplus == 0);
2424 BracesRemover(
const Environment &Env,
const FormatStyle &Style)
2425 : TokenAnalyzer(Env, Style) {}
2427 std::pair<tooling::Replacements, unsigned>
2428 analyze(TokenAnnotator &Annotator,
2429 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2430 FormatTokenLexer &Tokens)
override {
2431 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2432 tooling::Replacements
Result;
2433 removeBraces(AnnotatedLines,
Result);
2438 void removeBraces(SmallVectorImpl<AnnotatedLine *> &Lines,
2439 tooling::Replacements &
Result) {
2440 const auto &SourceMgr = Env.getSourceManager();
2441 const auto *End = Lines.end();
2442 for (
const auto *I = Lines.begin(); I != End; ++I) {
2443 const auto &
Line = *I;
2444 if (!
Line->Children.empty())
2446 if (!
Line->Affected)
2448 const auto *NextLine = I + 1 == End ?
nullptr : I[1];
2449 for (
const auto *Token =
Line->First; Token && !Token->Finalized;
2450 Token = Token->Next) {
2451 if (!Token->Optional || Token->isNoneOf(tok::l_brace, tok::r_brace))
2453 auto *
Next = Token->Next;
2454 assert(
Next || Token ==
Line->Last);
2455 if (!
Next && NextLine)
2456 Next = NextLine->First;
2465 SemiRemover(
const Environment &Env,
const FormatStyle &Style)
2466 : TokenAnalyzer(Env, Style) {}
2468 std::pair<tooling::Replacements, unsigned>
2469 analyze(TokenAnnotator &Annotator,
2470 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2471 FormatTokenLexer &Tokens)
override {
2472 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2473 tooling::Replacements
Result;
2474 removeSemi(Annotator, AnnotatedLines,
Result);
2479 void removeSemi(TokenAnnotator &Annotator,
2480 SmallVectorImpl<AnnotatedLine *> &Lines,
2481 tooling::Replacements &
Result) {
2483 const auto *Prev =
Tok.Previous;
2484 if (!Prev || Prev->isNot(tok::r_brace))
2486 const auto *LBrace = Prev->MatchingParen;
2487 return LBrace && LBrace->is(TT_FunctionLBrace);
2489 const auto &SourceMgr = Env.getSourceManager();
2490 const auto *End = Lines.end();
2491 for (
const auto *I = Lines.begin(); I != End; ++I) {
2492 const auto &
Line = *I;
2493 if (!
Line->Children.empty())
2494 removeSemi(Annotator,
Line->Children,
Result);
2495 if (!
Line->Affected)
2497 Annotator.calculateFormattingInformation(*
Line);
2498 const auto *NextLine = I + 1 == End ?
nullptr : I[1];
2499 for (
const auto *Token =
Line->First; Token && !Token->Finalized;
2500 Token = Token->Next) {
2501 if (Token->isNot(tok::semi) ||
2502 (!Token->Optional && !PrecededByFunctionRBrace(*Token))) {
2505 auto *
Next = Token->Next;
2506 assert(
Next || Token ==
Line->Last);
2507 if (!
Next && NextLine)
2508 Next = NextLine->First;
2517 EnumTrailingCommaEditor(
const Environment &Env,
const FormatStyle &Style)
2518 : TokenAnalyzer(Env, Style) {}
2520 std::pair<tooling::Replacements, unsigned>
2521 analyze(TokenAnnotator &Annotator,
2522 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2523 FormatTokenLexer &Tokens)
override {
2524 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2525 tooling::Replacements
Result;
2526 editEnumTrailingComma(AnnotatedLines,
Result);
2531 void editEnumTrailingComma(SmallVectorImpl<AnnotatedLine *> &Lines,
2532 tooling::Replacements &
Result) {
2533 bool InEnumBraces =
false;
2535 const auto &SourceMgr = Env.getSourceManager();
2536 for (
auto *
Line : Lines) {
2537 if (!
Line->Children.empty())
2538 editEnumTrailingComma(
Line->Children,
Result);
2539 for (
const auto *Token =
Line->First; Token && !Token->Finalized;
2540 Token = Token->Next) {
2541 if (Token->isNot(TT_EnumRBrace)) {
2542 if (Token->is(TT_EnumLBrace))
2543 InEnumBraces =
true;
2544 else if (InEnumBraces && Token->isNot(tok::comment))
2545 BeforeRBrace =
Line->Affected ? Token :
nullptr;
2548 InEnumBraces =
false;
2551 if (BeforeRBrace->is(tok::comma)) {
2552 if (Style.EnumTrailingComma == FormatStyle::ETC_Remove)
2554 }
else if (Style.EnumTrailingComma == FormatStyle::ETC_Insert) {
2555 cantFail(
Result.add(tooling::Replacement(
2556 SourceMgr, BeforeRBrace->Tok.getEndLoc(), 0,
",")));
2558 BeforeRBrace =
nullptr;
2566 JavaScriptRequoter(
const Environment &Env,
const FormatStyle &Style)
2567 : TokenAnalyzer(Env, Style) {}
2569 std::pair<tooling::Replacements, unsigned>
2570 analyze(TokenAnnotator &Annotator,
2571 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2572 FormatTokenLexer &Tokens)
override {
2573 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2574 tooling::Replacements
Result;
2575 requoteJSStringLiteral(AnnotatedLines,
Result);
2582 void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
2583 tooling::Replacements &
Result) {
2584 for (AnnotatedLine *
Line : Lines) {
2585 requoteJSStringLiteral(
Line->Children,
Result);
2586 if (!
Line->Affected)
2589 FormatTok = FormatTok->Next) {
2590 StringRef Input = FormatTok->TokenText;
2591 if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
2594 (Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
2595 !Input.starts_with(
"\"")) ||
2596 (Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
2597 !Input.starts_with(
"\'"))) {
2602 bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
2603 SourceLocation Start = FormatTok->Tok.getLocation();
2604 auto Replace = [&](SourceLocation Start,
unsigned Length,
2605 StringRef ReplacementText) {
2606 auto Err =
Result.add(tooling::Replacement(
2607 Env.getSourceManager(), Start, Length, ReplacementText));
2611 llvm::errs() <<
toString(std::move(Err)) <<
"\n";
2615 Replace(Start, 1, IsSingle ?
"'" :
"\"");
2616 Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
2617 IsSingle ?
"'" :
"\"");
2620 bool Escaped =
false;
2621 for (
size_t i = 1; i < Input.size() - 1; i++) {
2624 if (!Escaped && i + 1 < Input.size() &&
2625 ((IsSingle && Input[i + 1] ==
'"') ||
2626 (!IsSingle && Input[i + 1] ==
'\''))) {
2629 Replace(Start.getLocWithOffset(i), 1,
"");
2636 if (!Escaped && IsSingle == (Input[i] ==
'\'')) {
2638 Replace(Start.getLocWithOffset(i), 0,
"\\");
2654 Formatter(
const Environment &Env,
const FormatStyle &Style,
2655 FormattingAttemptStatus *Status)
2656 : TokenAnalyzer(Env, Style), Status(Status) {}
2658 std::pair<tooling::Replacements, unsigned>
2659 analyze(TokenAnnotator &Annotator,
2660 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2661 FormatTokenLexer &Tokens)
override {
2662 tooling::Replacements
Result;
2663 deriveLocalStyle(AnnotatedLines);
2664 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2665 for (AnnotatedLine *
Line : AnnotatedLines)
2666 Annotator.calculateFormattingInformation(*
Line);
2667 Annotator.setCommentLineLevels(AnnotatedLines);
2669 WhitespaceManager Whitespaces(
2670 Env.getSourceManager(), Style,
2671 Style.LineEnding > FormatStyle::LE_CRLF
2673 Env.getSourceManager().getBufferData(Env.getFileID()),
2674 Style.LineEnding == FormatStyle::LE_DeriveCRLF)
2675 : Style.LineEnding == FormatStyle::LE_CRLF);
2676 ContinuationIndenter Indenter(Style, Tokens.getKeywords(),
2677 Env.getSourceManager(), Whitespaces, Encoding,
2678 BinPackInconclusiveFunctions);
2680 UnwrappedLineFormatter(&Indenter, &Whitespaces, Style,
2681 Tokens.getKeywords(), Env.getSourceManager(),
2683 .format(AnnotatedLines,
false,
2686 Env.getFirstStartColumn(),
2687 Env.getNextStartColumn(),
2688 Env.getLastStartColumn());
2689 for (
const auto &R : Whitespaces.generateReplacements())
2691 return std::make_pair(
Result, 0);
2692 return std::make_pair(
Result, Penalty);
2697 hasCpp03IncompatibleFormat(
const SmallVectorImpl<AnnotatedLine *> &Lines) {
2698 for (
const AnnotatedLine *
Line : Lines) {
2699 if (hasCpp03IncompatibleFormat(
Line->Children))
2702 if (!
Tok->hasWhitespaceBefore()) {
2703 if (
Tok->is(tok::coloncolon) &&
Tok->Previous->is(TT_TemplateOpener))
2705 if (
Tok->is(TT_TemplateCloser) &&
2706 Tok->Previous->is(TT_TemplateCloser)) {
2715 int countVariableAlignments(
const SmallVectorImpl<AnnotatedLine *> &Lines) {
2716 int AlignmentDiff = 0;
2718 for (
const AnnotatedLine *
Line : Lines) {
2719 AlignmentDiff += countVariableAlignments(
Line->Children);
2722 if (
Tok->isNot(TT_PointerOrReference))
2725 const auto *Prev =
Tok->Previous;
2726 const bool PrecededByName = Prev && Prev->Tok.getIdentifierInfo();
2727 const bool SpaceBefore =
Tok->hasWhitespaceBefore();
2730 while (
Tok->Next &&
Tok->Next->is(TT_PointerOrReference))
2734 const bool FollowedByName =
Next &&
Next->Tok.getIdentifierInfo();
2735 const bool SpaceAfter =
Next &&
Next->hasWhitespaceBefore();
2737 if ((!PrecededByName && !FollowedByName) ||
2739 (PrecededByName && FollowedByName && SpaceBefore == SpaceAfter)) {
2743 if ((PrecededByName && SpaceBefore) ||
2744 (FollowedByName && !SpaceAfter)) {
2747 }
else if ((PrecededByName && !SpaceBefore) ||
2748 (FollowedByName && SpaceAfter)) {
2755 return AlignmentDiff;
2759 deriveLocalStyle(
const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
2760 bool HasBinPackedFunction =
false;
2761 bool HasOnePerLineFunction =
false;
2762 for (AnnotatedLine *
Line : AnnotatedLines) {
2763 if (!
Line->First->Next)
2768 HasBinPackedFunction =
true;
2770 HasOnePerLineFunction =
true;
2775 if (Style.DerivePointerAlignment) {
2776 const auto NetRightCount = countVariableAlignments(AnnotatedLines);
2777 if (NetRightCount > 0)
2778 Style.PointerAlignment = FormatStyle::PAS_Right;
2779 else if (NetRightCount < 0)
2780 Style.PointerAlignment = FormatStyle::PAS_Left;
2781 Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
2783 if (Style.Standard == FormatStyle::LS_Auto) {
2784 Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
2785 ? FormatStyle::LS_Latest
2786 : FormatStyle::LS_Cpp03;
2788 BinPackInconclusiveFunctions =
2789 HasBinPackedFunction || !HasOnePerLineFunction;
2792 bool BinPackInconclusiveFunctions;
2793 FormattingAttemptStatus *Status;
2809 TrailingCommaInserter(
const Environment &Env,
const FormatStyle &Style)
2810 : TokenAnalyzer(Env, Style) {}
2812 std::pair<tooling::Replacements, unsigned>
2813 analyze(TokenAnnotator &Annotator,
2814 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2815 FormatTokenLexer &Tokens)
override {
2816 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2817 tooling::Replacements
Result;
2818 insertTrailingCommas(AnnotatedLines,
Result);
2825 void insertTrailingCommas(SmallVectorImpl<AnnotatedLine *> &Lines,
2826 tooling::Replacements &
Result) {
2827 for (AnnotatedLine *
Line : Lines) {
2828 insertTrailingCommas(
Line->Children,
Result);
2829 if (!
Line->Affected)
2832 FormatTok = FormatTok->Next) {
2833 if (FormatTok->NewlinesBefore == 0)
2836 if (!Matching || !FormatTok->getPreviousNonComment())
2838 if (!(FormatTok->is(tok::r_square) &&
2839 Matching->is(TT_ArrayInitializerLSquare)) &&
2840 !(FormatTok->is(tok::r_brace) && Matching->is(TT_DictLiteral))) {
2843 FormatToken *Prev = FormatTok->getPreviousNonComment();
2844 if (Prev->is(tok::comma) || Prev->is(tok::semi))
2848 SourceLocation Start =
2849 Prev->Tok.getLocation().getLocWithOffset(Prev->TokenText.size());
2853 unsigned ColumnNumber =
2854 Env.getSourceManager().getSpellingColumnNumber(Start);
2855 if (ColumnNumber > Style.ColumnLimit)
2860 tooling::Replacement(Env.getSourceManager(), Start, 0,
",")));
2870 Cleaner(
const Environment &Env,
const FormatStyle &Style)
2871 : TokenAnalyzer(Env, Style),
2872 DeletedTokens(FormatTokenLess(Env.getSourceManager())) {}
2875 std::pair<tooling::Replacements, unsigned>
2876 analyze(TokenAnnotator &Annotator,
2877 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2878 FormatTokenLexer &Tokens)
override {
2886 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2888 checkEmptyNamespace(AnnotatedLines);
2890 for (
auto *
Line : AnnotatedLines)
2893 return {generateFixes(), 0};
2897 void cleanupLine(AnnotatedLine *
Line) {
2898 for (
auto *Child :
Line->Children)
2901 if (
Line->Affected) {
2902 cleanupRight(
Line->First, tok::comma, tok::comma);
2903 cleanupRight(
Line->First, TT_CtorInitializerColon, tok::comma);
2904 cleanupRight(
Line->First, tok::l_paren, tok::comma);
2905 cleanupLeft(
Line->First, tok::comma, tok::r_paren);
2906 cleanupLeft(
Line->First, TT_CtorInitializerComma, tok::l_brace);
2907 cleanupLeft(
Line->First, TT_CtorInitializerColon, tok::l_brace);
2908 cleanupLeft(
Line->First, TT_CtorInitializerColon, tok::equal);
2912 bool containsOnlyComments(
const AnnotatedLine &
Line) {
2914 if (
Tok->isNot(tok::comment))
2920 void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
2921 std::set<unsigned> DeletedLines;
2922 for (
unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
2923 auto &
Line = *AnnotatedLines[i];
2924 if (
Line.startsWithNamespace())
2925 checkEmptyNamespace(AnnotatedLines, i, i, DeletedLines);
2928 for (
auto Line : DeletedLines) {
2941 bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2942 unsigned CurrentLine,
unsigned &NewLine,
2943 std::set<unsigned> &DeletedLines) {
2944 unsigned InitLine = CurrentLine, End = AnnotatedLines.size();
2945 if (Style.BraceWrapping.AfterNamespace) {
2949 if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
2950 NewLine = CurrentLine;
2953 }
else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
2956 while (++CurrentLine < End) {
2957 if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
2960 if (AnnotatedLines[CurrentLine]->startsWithNamespace()) {
2961 if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine,
2965 CurrentLine = NewLine;
2969 if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
2974 NewLine = CurrentLine;
2978 NewLine = CurrentLine;
2979 if (CurrentLine >= End)
2984 AnnotatedLines[InitLine]->First->Tok.getLocation(),
2985 AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc()))) {
2989 for (
unsigned i = InitLine; i <= CurrentLine; ++i)
2990 DeletedLines.insert(i);
2999 template <
typename LeftKind,
typename RightKind>
3000 void cleanupPair(
FormatToken *Start, LeftKind LK, RightKind RK,
3003 for (
auto *Res =
Tok.Next; Res; Res = Res->Next) {
3004 if (Res->isNot(tok::comment) &&
3005 DeletedTokens.find(Res) == DeletedTokens.end()) {
3011 for (
auto *Left = Start;
Left;) {
3012 auto *
Right = NextNotDeleted(*Left);
3016 deleteToken(DeleteLeft ? Left : Right);
3028 template <
typename LeftKind,
typename RightKind>
3029 void cleanupLeft(
FormatToken *Start, LeftKind LK, RightKind RK) {
3030 cleanupPair(Start, LK, RK,
true);
3033 template <
typename LeftKind,
typename RightKind>
3034 void cleanupRight(
FormatToken *Start, LeftKind LK, RightKind RK) {
3035 cleanupPair(Start, LK, RK,
false);
3041 DeletedTokens.insert(
Tok);
3044 tooling::Replacements generateFixes() {
3045 tooling::Replacements Fixes;
3046 SmallVector<FormatToken *> Tokens;
3047 std::copy(DeletedTokens.begin(), DeletedTokens.end(),
3048 std::back_inserter(Tokens));
3054 while (Idx < Tokens.size()) {
3055 unsigned St = Idx, End = Idx;
3056 while ((End + 1) < Tokens.size() && Tokens[End]->Next == Tokens[End + 1])
3059 Tokens[End]->Tok.getEndLoc());
3061 Fixes.add(tooling::Replacement(Env.getSourceManager(), SR,
""));
3065 llvm::errs() <<
toString(std::move(Err)) <<
"\n";
3066 assert(
false &&
"Fixes must not conflict!");
3077 struct FormatTokenLess {
3078 FormatTokenLess(
const SourceManager &SM) : SM(SM) {}
3081 return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(),
3082 RHS->Tok.getLocation());
3084 const SourceManager &SM;
3088 std::set<FormatToken *, FormatTokenLess> DeletedTokens;
3093 ObjCHeaderStyleGuesser(
const Environment &Env,
const FormatStyle &Style)
3094 : TokenAnalyzer(Env, Style), IsObjC(
false) {}
3096 std::pair<tooling::Replacements, unsigned>
3097 analyze(TokenAnnotator &Annotator,
3098 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3099 FormatTokenLexer &Tokens)
override {
3100 assert(Style.Language == FormatStyle::LK_Cpp);
3101 IsObjC = guessIsObjC(Env.getSourceManager(), AnnotatedLines,
3102 Tokens.getKeywords());
3103 tooling::Replacements
Result;
3107 bool isObjC() {
return IsObjC; }
3111 guessIsObjC(
const SourceManager &SourceManager,
3112 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3113 const AdditionalKeywords &Keywords) {
3115 static constexpr llvm::StringLiteral FoundationIdentifiers[] = {
3130 "FOUNDATION_EXPORT",
3131 "FOUNDATION_EXTERN",
3132 "NSAffineTransform",
3134 "NSAttributedString",
3153 "NSInvocationOperation",
3157 "NSMutableAttributedString",
3158 "NSMutableCharacterSet",
3160 "NSMutableDictionary",
3161 "NSMutableIndexSet",
3162 "NSMutableOrderedSet",
3166 "NSNumberFormatter",
3170 "NSOperationQueuePriority",
3174 "NSQualityOfService",
3177 "NSRegularExpression",
3188 "NS_ASSUME_NONNULL_BEGIN",
3192 assert(llvm::is_sorted(FoundationIdentifiers));
3194 for (
auto *
Line : AnnotatedLines) {
3195 if (
Line->First && (
Line->First->TokenText.starts_with(
"#") ||
3196 Line->First->TokenText ==
"__pragma" ||
3197 Line->First->TokenText ==
"_Pragma")) {
3201 FormatTok = FormatTok->Next) {
3202 if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) &&
3203 (FormatTok->isNot(tok::objc_not_keyword) ||
3204 FormatTok->isOneOf(tok::numeric_constant, tok::l_square,
3206 (FormatTok->Tok.isAnyIdentifier() &&
3207 llvm::binary_search(FoundationIdentifiers,
3208 FormatTok->TokenText)) ||
3209 FormatTok->is(TT_ObjCStringLiteral) ||
3210 FormatTok->isOneOf(Keywords.kw_NS_CLOSED_ENUM, Keywords.kw_NS_ENUM,
3211 Keywords.kw_NS_ERROR_ENUM,
3212 Keywords.kw_NS_OPTIONS, TT_ObjCBlockLBrace,
3213 TT_ObjCBlockLParen, TT_ObjCDecl, TT_ObjCForIn,
3214 TT_ObjCMethodExpr, TT_ObjCMethodSpecifier,
3215 TT_ObjCProperty, TT_ObjCSelector)) {
3216 LLVM_DEBUG(llvm::dbgs()
3217 <<
"Detected ObjC at location "
3218 << FormatTok->Tok.getLocation().printToString(
3220 <<
" token: " << FormatTok->TokenText <<
" token type: "
3225 if (guessIsObjC(SourceManager,
Line->Children, Keywords))
3234struct IncludeDirective {
3242struct JavaImportDirective {
3243 StringRef Identifier;
3246 SmallVector<StringRef> AssociatedCommentLines;
3255 for (
const auto &Range : Ranges) {
3256 if (Range.getOffset() < End &&
3257 Range.getOffset() + Range.getLength() > Start) {
3272static std::pair<unsigned, unsigned>
3275 unsigned CursorIndex = std::numeric_limits<unsigned>::max();
3276 unsigned OffsetToEOL = 0;
3277 for (
int i = 0, e = Includes.size(); i != e; ++i) {
3278 unsigned Start = Includes[Indices[i]].Offset;
3279 unsigned End = Start + Includes[Indices[i]].Text.size();
3280 if (!(Cursor >= Start && Cursor < End))
3282 CursorIndex = Indices[i];
3283 OffsetToEOL = End - Cursor;
3286 while (--i >= 0 && Includes[CursorIndex].
Text == Includes[Indices[i]].
Text)
3290 return std::make_pair(CursorIndex, OffsetToEOL);
3295 std::string NewCode;
3296 size_t Pos = 0, LastPos = 0;
3299 Pos = Code.find(
"\r\n", LastPos);
3300 if (Pos == LastPos) {
3304 if (Pos == std::string::npos) {
3305 NewCode += Code.substr(LastPos);
3308 NewCode += Code.substr(LastPos, Pos - LastPos) +
"\n";
3310 }
while (Pos != std::string::npos);
3328 const unsigned IncludesBeginOffset = Includes.front().Offset;
3329 const unsigned IncludesEndOffset =
3330 Includes.back().Offset + Includes.back().Text.size();
3331 const unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset;
3332 if (!
affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset))
3335 llvm::to_vector<16>(llvm::seq<unsigned>(0, Includes.size()));
3337 if (Style.SortIncludes.Enabled) {
3338 stable_sort(Indices, [&](
unsigned LHSI,
unsigned RHSI) {
3340 if (Style.SortIncludes.IgnoreExtension) {
3341 LHSStem = Includes[LHSI].Filename;
3342 RHSStem = Includes[RHSI].Filename;
3343 llvm::sys::path::replace_extension(LHSStem,
"");
3344 llvm::sys::path::replace_extension(RHSStem,
"");
3346 std::string LHSStemLower, RHSStemLower;
3347 std::string LHSFilenameLower, RHSFilenameLower;
3348 if (Style.SortIncludes.IgnoreCase) {
3349 LHSStemLower = LHSStem.str().lower();
3350 RHSStemLower = RHSStem.str().lower();
3351 LHSFilenameLower = Includes[LHSI].Filename.lower();
3352 RHSFilenameLower = Includes[RHSI].Filename.lower();
3354 return std::tie(Includes[LHSI].Priority, LHSStemLower, LHSStem,
3355 LHSFilenameLower, Includes[LHSI].Filename) <
3356 std::tie(Includes[RHSI].Priority, RHSStemLower, RHSStem,
3357 RHSFilenameLower, Includes[RHSI].Filename);
3363 unsigned CursorIndex;
3365 unsigned CursorToEOLOffset;
3367 std::tie(CursorIndex, CursorToEOLOffset) =
3372 Indices.erase(llvm::unique(Indices,
3373 [&](
unsigned LHSI,
unsigned RHSI) {
3374 return Includes[LHSI].Text.trim() ==
3375 Includes[RHSI].Text.trim();
3379 int CurrentCategory = Includes.front().Category;
3387 if (Indices.size() == Includes.size() && is_sorted(Indices) &&
3392 const auto OldCursor = Cursor ? *Cursor : 0;
3394 for (
unsigned Index : Indices) {
3395 if (!result.empty()) {
3397 if (Style.IncludeStyle.IncludeBlocks ==
3399 CurrentCategory != Includes[Index].Category) {
3403 result += Includes[Index].Text;
3404 if (Cursor && CursorIndex == Index)
3405 *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
3406 CurrentCategory = Includes[Index].Category;
3409 if (Cursor && *Cursor >= IncludesEndOffset)
3410 *Cursor += result.size() - IncludesBlockSize;
3415 IncludesBeginOffset, IncludesBlockSize)))) {
3417 *Cursor = OldCursor;
3422 FileName, Includes.front().Offset, IncludesBlockSize, result));
3426 llvm::errs() <<
toString(std::move(Err)) <<
"\n";
3436 unsigned Prev = llvm::StringSwitch<size_t>(Code)
3437 .StartsWith(
"\xEF\xBB\xBF", 3)
3439 unsigned SearchFrom = 0;
3451 bool FirstIncludeBlock =
true;
3452 bool MainIncludeFound =
false;
3453 bool FormattingOff =
false;
3456 llvm::Regex RawStringRegex(
3457 "R\"([][A-Za-z0-9_{}#<>%:;.?*+/^&\\$|~!=,'-]*)\\(");
3459 std::string RawStringTermination =
")\"";
3461 for (
const auto Size = Code.size(); SearchFrom < Size;) {
3462 size_t Pos = SearchFrom;
3463 if (Code[SearchFrom] !=
'\n') {
3466 Pos = Code.find(
'\n', Pos);
3467 }
while (Pos != StringRef::npos && Code[Pos - 1] ==
'\\');
3471 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
3473 StringRef Trimmed =
Line.trim();
3478 if (RawStringRegex.match(Trimmed, &RawStringMatches)) {
3479 std::string CharSequence = RawStringMatches[1].str();
3480 RawStringTermination =
")" + CharSequence +
"\"";
3481 FormattingOff =
true;
3484 if (Trimmed.contains(RawStringTermination))
3485 FormattingOff =
false;
3487 bool IsBlockComment =
false;
3490 FormattingOff =
true;
3492 FormattingOff =
false;
3493 }
else if (Trimmed.starts_with(
"/*")) {
3494 IsBlockComment =
true;
3495 Pos = Code.find(
"*/", SearchFrom + 2);
3498 const bool EmptyLineSkipped =
3501 Style.IncludeStyle.IncludeBlocks ==
3504 bool MergeWithNextLine = Trimmed.ends_with(
"\\");
3505 if (!FormattingOff && !MergeWithNextLine) {
3506 if (!IsBlockComment &&
3508 StringRef IncludeName = Matches[2];
3509 if (Trimmed.contains(
"/*") && !Trimmed.contains(
"*/")) {
3514 Pos = Code.find(
"*/", SearchFrom);
3516 Prev, (Pos != StringRef::npos ? Pos + 2 : Code.size()) - Prev);
3520 !MainIncludeFound && FirstIncludeBlock);
3522 IncludeName, !MainIncludeFound && FirstIncludeBlock);
3524 MainIncludeFound =
true;
3525 IncludesInBlock.push_back(
3526 {IncludeName,
Line, Prev, Category, Priority});
3527 }
else if (!IncludesInBlock.empty() && !EmptyLineSkipped) {
3530 IncludesInBlock.clear();
3531 if (Trimmed.starts_with(
"#pragma hdrstop"))
3532 FirstIncludeBlock =
true;
3534 FirstIncludeBlock =
false;
3537 if (Pos == StringRef::npos || Pos + 1 == Code.size())
3540 if (!MergeWithNextLine)
3542 SearchFrom = Pos + 1;
3544 if (!IncludesInBlock.empty()) {
3555 StringRef ImportIdentifier) {
3556 unsigned LongestMatchIndex = std::numeric_limits<unsigned>::max();
3557 unsigned LongestMatchLength = 0;
3558 for (
unsigned I = 0; I < Style.JavaImportGroups.size(); I++) {
3559 const std::string &GroupPrefix = Style.JavaImportGroups[I];
3560 if (ImportIdentifier.starts_with(GroupPrefix) &&
3561 GroupPrefix.length() > LongestMatchLength) {
3562 LongestMatchIndex = I;
3563 LongestMatchLength = GroupPrefix.length();
3566 return LongestMatchIndex;
3578 unsigned ImportsBeginOffset = Imports.front().Offset;
3579 unsigned ImportsEndOffset =
3580 Imports.back().Offset + Imports.back().Text.size();
3581 unsigned ImportsBlockSize = ImportsEndOffset - ImportsBeginOffset;
3582 if (!
affectsRange(Ranges, ImportsBeginOffset, ImportsEndOffset))
3586 llvm::to_vector<16>(llvm::seq<unsigned>(0, Imports.size()));
3589 for (
const JavaImportDirective &Import : Imports)
3592 bool StaticImportAfterNormalImport =
3593 Style.SortJavaStaticImport == FormatStyle::SJSIO_After;
3594 sort(Indices, [&](
unsigned LHSI,
unsigned RHSI) {
3596 return std::make_tuple(!Imports[LHSI].IsStatic ^
3597 StaticImportAfterNormalImport,
3599 std::make_tuple(!Imports[RHSI].IsStatic ^
3600 StaticImportAfterNormalImport,
3605 Indices.erase(llvm::unique(Indices,
3606 [&](
unsigned LHSI,
unsigned RHSI) {
3607 return Imports[LHSI].Text == Imports[RHSI].Text;
3611 bool CurrentIsStatic = Imports[Indices.front()].IsStatic;
3615 for (
unsigned Index : Indices) {
3616 if (!result.empty()) {
3618 if (CurrentIsStatic != Imports[Index].IsStatic ||
3623 for (StringRef CommentLine : Imports[Index].AssociatedCommentLines) {
3624 result += CommentLine;
3627 result += Imports[Index].Text;
3628 CurrentIsStatic = Imports[Index].IsStatic;
3635 Imports.front().Offset, ImportsBlockSize)))) {
3640 ImportsBlockSize, result));
3644 llvm::errs() <<
toString(std::move(Err)) <<
"\n";
3651const char JavaImportRegexPattern[] =
3652 "^[\t ]*import[\t ]+(static[\t ]*)?([^\t ]*)[\t ]*;";
3661 unsigned SearchFrom = 0;
3662 llvm::Regex ImportRegex(JavaImportRegexPattern);
3667 bool FormattingOff =
false;
3670 auto Pos = Code.find(
'\n', SearchFrom);
3672 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
3674 StringRef Trimmed =
Line.trim();
3676 FormattingOff =
true;
3678 FormattingOff =
false;
3680 if (ImportRegex.match(
Line, &Matches)) {
3681 if (FormattingOff) {
3686 StringRef
Static = Matches[1];
3687 StringRef Identifier = Matches[2];
3688 bool IsStatic =
false;
3689 if (
Static.contains(
"static"))
3691 ImportsInBlock.push_back(
3692 {Identifier,
Line, Prev, AssociatedCommentLines, IsStatic});
3693 AssociatedCommentLines.clear();
3694 }
else if (!Trimmed.empty() && !ImportsInBlock.empty()) {
3696 AssociatedCommentLines.push_back(
Line);
3699 if (Pos == StringRef::npos || Pos + 1 == Code.size())
3701 SearchFrom = Pos + 1;
3703 if (!ImportsInBlock.empty())
3712 return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
3715bool isLikelyXml(StringRef Code) {
return Code.ltrim().starts_with(
"<"); }
3719 StringRef
FileName,
unsigned *Cursor) {
3721 if (!Style.SortIncludes.Enabled || Style.DisableFormat)
3725 if (Style.isJavaScript()) {
3737template <
typename T>
3741 const FormatStyle &Style) {
3742 if (Replaces.
empty())
3745 auto NewCode = applyAllReplacements(Code, Replaces);
3747 return NewCode.takeError();
3752 ProcessFunc(Style, *NewCode, ChangedRanges,
FileName);
3754 return Replaces.
merge(FormatReplaces);
3759 const FormatStyle &Style) {
3762 auto SortIncludes = [](
const FormatStyle &Style, StringRef Code,
3763 std::vector<tooling::Range> Ranges,
3767 auto SortedReplaces =
3769 if (!SortedReplaces)
3770 return SortedReplaces.takeError();
3774 auto Reformat = [](
const FormatStyle &Style, StringRef Code,
3775 std::vector<tooling::Range> Ranges,
3785 return Replace.
getOffset() == std::numeric_limits<unsigned>::max() &&
3791inline bool isHeaderDeletion(
const tooling::Replacement &Replace) {
3792 return Replace.getOffset() == std::numeric_limits<unsigned>::max() &&
3793 Replace.getLength() == 1;
3797tooling::Replacements
3798fixCppIncludeInsertions(StringRef Code,
const tooling::Replacements &Replaces,
3799 const FormatStyle &Style) {
3803 tooling::Replacements HeaderInsertions;
3804 std::set<StringRef> HeadersToDelete;
3805 tooling::Replacements
Result;
3806 for (
const auto &R : Replaces) {
3807 if (isHeaderInsertion(R)) {
3810 consumeError(HeaderInsertions.add(R));
3811 }
else if (isHeaderDeletion(R)) {
3812 HeadersToDelete.insert(R.getReplacementText());
3813 }
else if (R.getOffset() == std::numeric_limits<unsigned>::max()) {
3814 llvm::errs() <<
"Insertions other than header #include insertion are "
3816 << R.getReplacementText() <<
"\n";
3818 consumeError(
Result.add(R));
3821 if (HeaderInsertions.empty() && HeadersToDelete.empty())
3824 StringRef
FileName = Replaces.begin()->getFilePath();
3825 tooling::HeaderIncludes Includes(
FileName, Code, Style.IncludeStyle);
3827 for (
const auto &Header : HeadersToDelete) {
3828 tooling::Replacements Replaces =
3829 Includes.remove(Header.trim(
"\"<>"), Header.starts_with(
"<"));
3830 for (
const auto &R : Replaces) {
3831 auto Err =
Result.add(R);
3834 llvm::errs() <<
"Failed to add header deletion replacement for "
3835 << Header <<
": " <<
toString(std::move(Err)) <<
"\n";
3841 for (
const auto &R : HeaderInsertions) {
3842 auto IncludeDirective = R.getReplacementText();
3845 assert(Matched &&
"Header insertion replacement must have replacement text "
3848 auto IncludeName = Matches[2];
3850 Includes.insert(IncludeName.trim(
"\"<>"), IncludeName.starts_with(
"<"),
3853 auto Err =
Result.add(*Replace);
3855 consumeError(std::move(Err));
3856 unsigned NewOffset =
3857 Result.getShiftedCodePosition(Replace->getOffset());
3858 auto Shifted = tooling::Replacement(
FileName, NewOffset, 0,
3859 Replace->getReplacementText());
3871 const FormatStyle &Style) {
3874 auto Cleanup = [](
const FormatStyle &Style, StringRef Code,
3881 fixCppIncludeInsertions(Code, Replaces, Style);
3886std::pair<tooling::Replacements, unsigned>
3889 unsigned NextStartColumn,
unsigned LastStartColumn, StringRef
FileName,
3891 FormatStyle Expanded = Style;
3895 Expanded.InsertBraces =
false;
3896 Expanded.RemoveBracesLLVM =
false;
3897 Expanded.RemoveParentheses = FormatStyle::RPS_Leave;
3898 Expanded.RemoveSemicolon =
false;
3899 switch (Expanded.RequiresClausePosition) {
3900 case FormatStyle::RCPS_SingleLine:
3901 case FormatStyle::RCPS_WithPreceding:
3902 Expanded.IndentRequiresClause =
false;
3908 if (Expanded.DisableFormat)
3912 if (Expanded.isJavaScript() &&
isMpegTS(Code))
3916 if (Style.isJson()) {
3917 std::vector<tooling::Range> Ranges(1,
tooling::Range(0, Code.size()));
3919 NextStartColumn, LastStartColumn);
3924 Formatter(*Env, Style, Status).process().first;
3926 if (Code.starts_with(
"x = ")) {
3927 Replaces = Replaces.
merge(
3931 if (applyAllReplacements(Code, Replaces))
3932 return {Replaces, 0};
3937 NextStartColumn, LastStartColumn);
3955 if (Style.isCpp()) {
3956 if (Style.QualifierAlignment != FormatStyle::QAS_Leave)
3959 if (Style.RemoveParentheses != FormatStyle::RPS_Leave) {
3960 FormatStyle S = Expanded;
3961 S.RemoveParentheses = Style.RemoveParentheses;
3962 Passes.emplace_back([&, S = std::move(S)](
const Environment &Env) {
3963 return ParensRemover(Env, S).process(
true);
3967 if (Style.InsertBraces) {
3968 FormatStyle S = Expanded;
3969 S.InsertBraces =
true;
3970 Passes.emplace_back([&, S = std::move(S)](
const Environment &Env) {
3971 return BracesInserter(Env, S).process(
true);
3975 if (Style.RemoveBracesLLVM) {
3976 FormatStyle S = Expanded;
3977 S.RemoveBracesLLVM =
true;
3978 Passes.emplace_back([&, S = std::move(S)](
const Environment &Env) {
3979 return BracesRemover(Env, S).process(
true);
3983 if (Style.RemoveSemicolon) {
3984 FormatStyle S = Expanded;
3985 S.RemoveSemicolon =
true;
3986 Passes.emplace_back([&, S = std::move(S)](
const Environment &Env) {
3987 return SemiRemover(Env, S).process();
3991 if (Style.EnumTrailingComma != FormatStyle::ETC_Leave) {
3993 return EnumTrailingCommaEditor(Env, Expanded)
3998 if (Style.FixNamespaceComments) {
4004 if (Style.SortUsingDeclarations != FormatStyle::SUD_Never) {
4011 if (Style.SeparateDefinitionBlocks != FormatStyle::SDS_Leave) {
4017 if (Style.Language == FormatStyle::LK_ObjC &&
4018 !Style.ObjCPropertyAttributeOrder.empty()) {
4024 if (Style.isJavaScript() &&
4025 Style.JavaScriptQuotes != FormatStyle::JSQS_Leave) {
4027 return JavaScriptRequoter(Env, Expanded).process(
true);
4032 return Formatter(Env, Expanded, Status).process();
4035 if (Style.isJavaScript() &&
4036 Style.InsertTrailingCommas == FormatStyle::TCS_Wrapped) {
4038 return TrailingCommaInserter(Env, Expanded).process();
4042 std::optional<std::string> CurrentCode;
4044 unsigned Penalty = 0;
4045 for (
size_t I = 0, E = Passes.size(); I < E; ++I) {
4046 std::pair<tooling::Replacements, unsigned> PassFixes = Passes[I](*Env);
4047 auto NewCode = applyAllReplacements(
4048 CurrentCode ? StringRef(*CurrentCode) : Code, PassFixes.first);
4050 Fixes = Fixes.
merge(PassFixes.first);
4051 Penalty += PassFixes.second;
4053 CurrentCode = std::move(*NewCode);
4057 FirstStartColumn, NextStartColumn, LastStartColumn);
4064 if (Style.QualifierAlignment != FormatStyle::QAS_Leave) {
4070 StringRef OriginalCode = Code.substr(Fix.getOffset(), Fix.getLength());
4071 if (OriginalCode != Fix.getReplacementText()) {
4072 auto Err = NonNoOpFixes.
add(Fix);
4074 llvm::errs() <<
"Error adding replacements : "
4075 <<
toString(std::move(Err)) <<
"\n";
4079 Fixes = std::move(NonNoOpFixes);
4082 return {Fixes, Penalty};
4101 if (Style.Language != FormatStyle::LK_Cpp)
4106 return Cleaner(*Env, Style).process().first;
4111 StringRef
FileName,
bool *IncompleteFormat) {
4114 if (!Status.FormatComplete)
4115 *IncompleteFormat =
true;
4142 auto LexingStd = Style.Standard;
4143 if (LexingStd == FormatStyle::LS_Auto || LexingStd == FormatStyle::LS_Latest)
4144 LexingStd = FormatStyle::LS_Cpp20;
4146 const bool SinceCpp11 = LexingStd >= FormatStyle::LS_Cpp11;
4147 const bool SinceCpp20 = LexingStd >= FormatStyle::LS_Cpp20;
4149 switch (Style.Language) {
4150 case FormatStyle::LK_C:
4154 case FormatStyle::LK_Cpp:
4155 case FormatStyle::LK_ObjC:
4156 LangOpts.CXXOperatorNames = 1;
4157 LangOpts.CPlusPlus11 = SinceCpp11;
4158 LangOpts.CPlusPlus14 = LexingStd >= FormatStyle::LS_Cpp14;
4159 LangOpts.CPlusPlus17 = LexingStd >= FormatStyle::LS_Cpp17;
4160 LangOpts.CPlusPlus20 = SinceCpp20;
4163 LangOpts.CPlusPlus = 1;
4166 LangOpts.Char8 = SinceCpp20;
4170 LangOpts.Digraphs = SinceCpp11;
4172 LangOpts.LineComment = 1;
4175 LangOpts.MicrosoftExt = 1;
4176 LangOpts.DeclSpecKeyword = 1;
4183 "Set coding style. <string> can be:\n"
4184 "1. A preset: LLVM, GNU, Google, Chromium, Microsoft,\n"
4185 " Mozilla, WebKit.\n"
4186 "2. 'file' to load style configuration from a\n"
4187 " .clang-format file in one of the parent directories\n"
4188 " of the source file (for stdin, see --assume-filename).\n"
4189 " If no .clang-format file is found, falls back to\n"
4190 " --fallback-style.\n"
4191 " --style=file is the default.\n"
4192 "3. 'file:<format_file_path>' to explicitly specify\n"
4193 " the configuration file.\n"
4194 "4. \"{key: value, ...}\" to set specific parameters, e.g.:\n"
4195 " --style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
4199 return FormatStyle::LK_C;
4201 return FormatStyle::LK_Java;
4202 if (
FileName.ends_with_insensitive(
".js") ||
4203 FileName.ends_with_insensitive(
".mjs") ||
4204 FileName.ends_with_insensitive(
".cjs") ||
4205 FileName.ends_with_insensitive(
".ts")) {
4206 return FormatStyle::LK_JavaScript;
4209 return FormatStyle::LK_ObjC;
4210 if (
FileName.ends_with_insensitive(
".proto") ||
4211 FileName.ends_with_insensitive(
".protodevel")) {
4212 return FormatStyle::LK_Proto;
4217 if (
FileName.ends_with_insensitive(
".txtpb") ||
4218 FileName.ends_with_insensitive(
".textpb") ||
4219 FileName.ends_with_insensitive(
".pb.txt") ||
4220 FileName.ends_with_insensitive(
".textproto") ||
4221 FileName.ends_with_insensitive(
".asciipb")) {
4222 return FormatStyle::LK_TextProto;
4224 if (
FileName.ends_with_insensitive(
".td"))
4225 return FormatStyle::LK_TableGen;
4226 if (
FileName.ends_with_insensitive(
".cs"))
4227 return FormatStyle::LK_CSharp;
4228 if (
FileName.ends_with_insensitive(
".json") ||
4229 FileName.ends_with_insensitive(
".ipynb")) {
4230 return FormatStyle::LK_Json;
4232 if (
FileName.ends_with_insensitive(
".sv") ||
4233 FileName.ends_with_insensitive(
".svh") ||
4234 FileName.ends_with_insensitive(
".v") ||
4235 FileName.ends_with_insensitive(
".vh")) {
4236 return FormatStyle::LK_Verilog;
4238 return FormatStyle::LK_Cpp;
4246 LangOpts.CPlusPlus = 1;
4247 LangOpts.LineComment = 1;
4249 Lexer Lex(ID, SourceMgr.getBufferOrFake(ID), SourceMgr, LangOpts);
4253 auto Text = StringRef(SourceMgr.getCharacterData(
Tok.getLocation()),
4255 if (!
Text.consume_front(
"// clang-format Language:"))
4260 return FormatStyle::LK_C;
4262 return FormatStyle::LK_Cpp;
4264 return FormatStyle::LK_ObjC;
4267 return FormatStyle::LK_None;
4272 if (GuessedLanguage == FormatStyle::LK_Cpp) {
4273 auto Extension = llvm::sys::path::extension(
FileName);
4276 if (!Code.empty() && (Extension.empty() || Extension ==
".h")) {
4280 Language != FormatStyle::LK_None) {
4285 if (Guesser.isObjC())
4286 return FormatStyle::LK_ObjC;
4289 return GuessedLanguage;
4297llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
4299 FormatStyle *Style,
bool AllowUnknownOptions,
4300 llvm::SourceMgr::DiagHandlerTy DiagHandler,
4302 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Text =
4303 FS->getBufferForFile(ConfigFile.str());
4304 if (
auto EC =
Text.getError())
4307 DiagHandler,
nullptr,
4315 StringRef FallbackStyleName, StringRef Code,
4316 llvm::vfs::FileSystem *FS,
4317 bool AllowUnknownOptions,
4318 llvm::SourceMgr::DiagHandlerTy DiagHandler) {
4326 if (StyleName.starts_with(
"{")) {
4328 StringRef Source =
"<command-line>";
4329 if (std::error_code ec =
4331 AllowUnknownOptions, DiagHandler)) {
4335 if (!Style.InheritsParentConfig)
4338 ChildFormatTextToApply.emplace_back(
4339 llvm::MemoryBuffer::getMemBuffer(StyleName, Source,
false));
4343 FS = llvm::vfs::getRealFileSystem().get();
4346 const bool IsDotHFile =
FileName.ends_with(
".h");
4349 if (!Style.InheritsParentConfig &&
4350 StyleName.starts_with_insensitive(
"file:")) {
4351 auto ConfigFile = StyleName.substr(5);
4352 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Text =
4354 DiagHandler, IsDotHFile);
4355 if (
auto EC =
Text.getError()) {
4360 LLVM_DEBUG(llvm::dbgs()
4361 <<
"Using configuration file " << ConfigFile <<
"\n");
4363 if (!Style.InheritsParentConfig)
4369 ChildFormatTextToApply.emplace_back(std::move(*
Text));
4375 if (!Style.InheritsParentConfig && !StyleName.equals_insensitive(
"file")) {
4378 if (!Style.InheritsParentConfig)
4383 if (std::error_code EC = FS->makeAbsolute(Path))
4387 Style.InheritsParentConfig =
false;
4389 auto dropDiagnosticHandler = [](
const llvm::SMDiagnostic &,
void *) {};
4391 auto applyChildFormatTexts = [&](FormatStyle *Style) {
4392 for (
const auto &MemBuf : llvm::reverse(ChildFormatTextToApply)) {
4395 DiagHandler ? DiagHandler : dropDiagnosticHandler);
4398 static_cast<void>(EC);
4404 FilesToLookFor.push_back(
".clang-format");
4405 FilesToLookFor.push_back(
"_clang-format");
4408 for (StringRef Directory = Path; !Directory.empty();
4409 Directory = llvm::sys::path::parent_path(Directory)) {
4410 auto Status = FS->status(Directory);
4412 Status->getType() != llvm::sys::fs::file_type::directory_file) {
4416 for (
const auto &F : FilesToLookFor) {
4419 llvm::sys::path::append(ConfigFile, F);
4420 LLVM_DEBUG(llvm::dbgs() <<
"Trying " << ConfigFile <<
"...\n");
4422 Status = FS->status(ConfigFile);
4424 Status->getType() != llvm::sys::fs::file_type::regular_file) {
4428 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Text =
4430 DiagHandler, IsDotHFile);
4431 if (
auto EC =
Text.getError()) {
4436 if (!UnsuitableConfigFiles.empty())
4437 UnsuitableConfigFiles.append(
", ");
4438 UnsuitableConfigFiles.append(ConfigFile);
4442 LLVM_DEBUG(llvm::dbgs()
4443 <<
"Using configuration file " << ConfigFile <<
"\n");
4445 if (!Style.InheritsParentConfig) {
4446 if (!ChildFormatTextToApply.empty()) {
4447 LLVM_DEBUG(llvm::dbgs() <<
"Applying child configurations\n");
4448 applyChildFormatTexts(&Style);
4453 LLVM_DEBUG(llvm::dbgs() <<
"Inherits parent configuration\n");
4456 Style.InheritsParentConfig =
false;
4458 ChildFormatTextToApply.emplace_back(std::move(*
Text));
4468 if (!UnsuitableConfigFiles.empty()) {
4471 UnsuitableConfigFiles);
4474 if (!ChildFormatTextToApply.empty()) {
4475 LLVM_DEBUG(llvm::dbgs()
4476 <<
"Applying child configurations on fallback style\n");
4477 applyChildFormatTexts(&FallbackStyle);
4480 return FallbackStyle;
4484 if (Comment == (On ?
"/* clang-format on */" :
"/* clang-format off */"))
4487 static const char ClangFormatOn[] =
"// clang-format on";
4488 static const char ClangFormatOff[] =
"// clang-format off";
4489 const unsigned Size = (On ?
sizeof ClangFormatOn :
sizeof ClangFormatOff) - 1;
4491 return Comment.starts_with(On ? ClangFormatOn : ClangFormatOff) &&
4492 (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)