33 #include "llvm/ADT/STLExtras.h" 34 #include "llvm/ADT/StringRef.h" 35 #include "llvm/Support/Allocator.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/Path.h" 38 #include "llvm/Support/Regex.h" 39 #include "llvm/Support/VirtualFileSystem.h" 40 #include "llvm/Support/YAMLTraits.h" 45 #include <unordered_map> 47 #define DEBUG_TYPE "format-formatter" 51 LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::RawStringFormat)
55 template <>
struct ScalarEnumerationTraits<
FormatStyle::LanguageKind> {
57 IO.enumCase(Value,
"Cpp", FormatStyle::LK_Cpp);
58 IO.enumCase(Value,
"Java", FormatStyle::LK_Java);
59 IO.enumCase(Value,
"JavaScript", FormatStyle::LK_JavaScript);
60 IO.enumCase(Value,
"ObjC", FormatStyle::LK_ObjC);
61 IO.enumCase(Value,
"Proto", FormatStyle::LK_Proto);
62 IO.enumCase(Value,
"TableGen", FormatStyle::LK_TableGen);
63 IO.enumCase(Value,
"TextProto", FormatStyle::LK_TextProto);
64 IO.enumCase(Value,
"CSharp", FormatStyle::LK_CSharp);
68 template <>
struct ScalarEnumerationTraits<
FormatStyle::LanguageStandard> {
70 IO.enumCase(Value,
"c++03", FormatStyle::LS_Cpp03);
71 IO.enumCase(Value,
"C++03", FormatStyle::LS_Cpp03);
72 IO.enumCase(Value,
"Cpp03", FormatStyle::LS_Cpp03);
74 IO.enumCase(Value,
"c++11", FormatStyle::LS_Cpp11);
75 IO.enumCase(Value,
"C++11", FormatStyle::LS_Cpp11);
77 IO.enumCase(Value,
"c++14", FormatStyle::LS_Cpp14);
78 IO.enumCase(Value,
"c++17", FormatStyle::LS_Cpp17);
79 IO.enumCase(Value,
"c++20", FormatStyle::LS_Cpp20);
81 IO.enumCase(Value,
"Latest", FormatStyle::LS_Latest);
82 IO.enumCase(Value,
"Cpp11", FormatStyle::LS_Latest);
83 IO.enumCase(Value,
"Auto", FormatStyle::LS_Auto);
87 template <>
struct ScalarEnumerationTraits<
FormatStyle::UseTabStyle> {
89 IO.enumCase(Value,
"Never", FormatStyle::UT_Never);
90 IO.enumCase(Value,
"false", FormatStyle::UT_Never);
91 IO.enumCase(Value,
"Always", FormatStyle::UT_Always);
92 IO.enumCase(Value,
"true", FormatStyle::UT_Always);
93 IO.enumCase(Value,
"ForIndentation", FormatStyle::UT_ForIndentation);
94 IO.enumCase(Value,
"ForContinuationAndIndentation",
95 FormatStyle::UT_ForContinuationAndIndentation);
99 template <>
struct ScalarEnumerationTraits<
FormatStyle::JavaScriptQuoteStyle> {
101 IO.enumCase(Value,
"Leave", FormatStyle::JSQS_Leave);
102 IO.enumCase(Value,
"Single", FormatStyle::JSQS_Single);
103 IO.enumCase(Value,
"Double", FormatStyle::JSQS_Double);
107 template <>
struct ScalarEnumerationTraits<
FormatStyle::ShortBlockStyle> {
109 IO.enumCase(Value,
"Never", FormatStyle::SBS_Never);
110 IO.enumCase(Value,
"false", FormatStyle::SBS_Never);
111 IO.enumCase(Value,
"Always", FormatStyle::SBS_Always);
112 IO.enumCase(Value,
"true", FormatStyle::SBS_Always);
113 IO.enumCase(Value,
"Empty", FormatStyle::SBS_Empty);
117 template <>
struct ScalarEnumerationTraits<
FormatStyle::ShortFunctionStyle> {
119 IO.enumCase(Value,
"None", FormatStyle::SFS_None);
120 IO.enumCase(Value,
"false", FormatStyle::SFS_None);
121 IO.enumCase(Value,
"All", FormatStyle::SFS_All);
122 IO.enumCase(Value,
"true", FormatStyle::SFS_All);
123 IO.enumCase(Value,
"Inline", FormatStyle::SFS_Inline);
124 IO.enumCase(Value,
"InlineOnly", FormatStyle::SFS_InlineOnly);
125 IO.enumCase(Value,
"Empty", FormatStyle::SFS_Empty);
129 template <>
struct ScalarEnumerationTraits<
FormatStyle::ShortIfStyle> {
131 IO.enumCase(Value,
"Never", FormatStyle::SIS_Never);
132 IO.enumCase(Value,
"Always", FormatStyle::SIS_Always);
133 IO.enumCase(Value,
"WithoutElse", FormatStyle::SIS_WithoutElse);
136 IO.enumCase(Value,
"false", FormatStyle::SIS_Never);
137 IO.enumCase(Value,
"true", FormatStyle::SIS_WithoutElse);
141 template <>
struct ScalarEnumerationTraits<
FormatStyle::ShortLambdaStyle> {
143 IO.enumCase(Value,
"None", FormatStyle::SLS_None);
144 IO.enumCase(Value,
"false", FormatStyle::SLS_None);
145 IO.enumCase(Value,
"Empty", FormatStyle::SLS_Empty);
146 IO.enumCase(Value,
"Inline", FormatStyle::SLS_Inline);
147 IO.enumCase(Value,
"All", FormatStyle::SLS_All);
148 IO.enumCase(Value,
"true", FormatStyle::SLS_All);
152 template <>
struct ScalarEnumerationTraits<
FormatStyle::BinPackStyle> {
154 IO.enumCase(Value,
"Auto", FormatStyle::BPS_Auto);
155 IO.enumCase(Value,
"Always", FormatStyle::BPS_Always);
156 IO.enumCase(Value,
"Never", FormatStyle::BPS_Never);
160 template <>
struct ScalarEnumerationTraits<
FormatStyle::BinaryOperatorStyle> {
162 IO.enumCase(Value,
"All", FormatStyle::BOS_All);
163 IO.enumCase(Value,
"true", FormatStyle::BOS_All);
164 IO.enumCase(Value,
"None", FormatStyle::BOS_None);
165 IO.enumCase(Value,
"false", FormatStyle::BOS_None);
166 IO.enumCase(Value,
"NonAssignment", FormatStyle::BOS_NonAssignment);
170 template <>
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);
185 struct ScalarEnumerationTraits<
186 FormatStyle::BraceWrappingAfterControlStatementStyle> {
189 FormatStyle::BraceWrappingAfterControlStatementStyle &
Value) {
190 IO.enumCase(Value,
"false", FormatStyle::BWACS_Never);
191 IO.enumCase(Value,
"true", FormatStyle::BWACS_Always);
192 IO.enumCase(Value,
"Never", FormatStyle::BWACS_Never);
193 IO.enumCase(Value,
"MultiLine", FormatStyle::BWACS_MultiLine);
194 IO.enumCase(Value,
"Always", FormatStyle::BWACS_Always);
199 struct ScalarEnumerationTraits<
FormatStyle::BreakConstructorInitializersStyle> {
202 IO.enumCase(Value,
"BeforeColon", FormatStyle::BCIS_BeforeColon);
203 IO.enumCase(Value,
"BeforeComma", FormatStyle::BCIS_BeforeComma);
204 IO.enumCase(Value,
"AfterColon", FormatStyle::BCIS_AfterColon);
209 struct ScalarEnumerationTraits<
FormatStyle::BreakInheritanceListStyle> {
211 FormatStyle::BreakInheritanceListStyle &
Value) {
212 IO.enumCase(Value,
"BeforeColon", FormatStyle::BILS_BeforeColon);
213 IO.enumCase(Value,
"BeforeComma", FormatStyle::BILS_BeforeComma);
214 IO.enumCase(Value,
"AfterColon", FormatStyle::BILS_AfterColon);
219 struct ScalarEnumerationTraits<
FormatStyle::PPDirectiveIndentStyle> {
221 IO.enumCase(Value,
"None", FormatStyle::PPDIS_None);
222 IO.enumCase(Value,
"AfterHash", FormatStyle::PPDIS_AfterHash);
223 IO.enumCase(Value,
"BeforeHash", FormatStyle::PPDIS_BeforeHash);
228 struct ScalarEnumerationTraits<
FormatStyle::ReturnTypeBreakingStyle> {
230 IO.enumCase(Value,
"None", FormatStyle::RTBS_None);
231 IO.enumCase(Value,
"All", FormatStyle::RTBS_All);
232 IO.enumCase(Value,
"TopLevel", FormatStyle::RTBS_TopLevel);
233 IO.enumCase(Value,
"TopLevelDefinitions",
234 FormatStyle::RTBS_TopLevelDefinitions);
235 IO.enumCase(Value,
"AllDefinitions", FormatStyle::RTBS_AllDefinitions);
240 struct ScalarEnumerationTraits<
FormatStyle::BreakTemplateDeclarationsStyle> {
242 FormatStyle::BreakTemplateDeclarationsStyle &
Value) {
243 IO.enumCase(Value,
"No", FormatStyle::BTDS_No);
244 IO.enumCase(Value,
"MultiLine", FormatStyle::BTDS_MultiLine);
245 IO.enumCase(Value,
"Yes", FormatStyle::BTDS_Yes);
248 IO.enumCase(Value,
"false", FormatStyle::BTDS_MultiLine);
249 IO.enumCase(Value,
"true", FormatStyle::BTDS_Yes);
254 struct ScalarEnumerationTraits<
FormatStyle::DefinitionReturnTypeBreakingStyle> {
257 IO.enumCase(Value,
"None", FormatStyle::DRTBS_None);
258 IO.enumCase(Value,
"All", FormatStyle::DRTBS_All);
259 IO.enumCase(Value,
"TopLevel", FormatStyle::DRTBS_TopLevel);
262 IO.enumCase(Value,
"false", FormatStyle::DRTBS_None);
263 IO.enumCase(Value,
"true", FormatStyle::DRTBS_All);
268 struct ScalarEnumerationTraits<
FormatStyle::NamespaceIndentationKind> {
270 FormatStyle::NamespaceIndentationKind &
Value) {
271 IO.enumCase(Value,
"None", FormatStyle::NI_None);
272 IO.enumCase(Value,
"Inner", FormatStyle::NI_Inner);
273 IO.enumCase(Value,
"All", FormatStyle::NI_All);
277 template <>
struct ScalarEnumerationTraits<
FormatStyle::BracketAlignmentStyle> {
279 IO.enumCase(Value,
"Align", FormatStyle::BAS_Align);
280 IO.enumCase(Value,
"DontAlign", FormatStyle::BAS_DontAlign);
281 IO.enumCase(Value,
"AlwaysBreak", FormatStyle::BAS_AlwaysBreak);
284 IO.enumCase(Value,
"true", FormatStyle::BAS_Align);
285 IO.enumCase(Value,
"false", FormatStyle::BAS_DontAlign);
290 struct ScalarEnumerationTraits<
FormatStyle::EscapedNewlineAlignmentStyle> {
292 FormatStyle::EscapedNewlineAlignmentStyle &
Value) {
293 IO.enumCase(Value,
"DontAlign", FormatStyle::ENAS_DontAlign);
294 IO.enumCase(Value,
"Left", FormatStyle::ENAS_Left);
295 IO.enumCase(Value,
"Right", FormatStyle::ENAS_Right);
298 IO.enumCase(Value,
"true", FormatStyle::ENAS_Left);
299 IO.enumCase(Value,
"false", FormatStyle::ENAS_Right);
303 template <>
struct ScalarEnumerationTraits<
FormatStyle::PointerAlignmentStyle> {
305 IO.enumCase(Value,
"Middle", FormatStyle::PAS_Middle);
306 IO.enumCase(Value,
"Left", FormatStyle::PAS_Left);
307 IO.enumCase(Value,
"Right", FormatStyle::PAS_Right);
310 IO.enumCase(Value,
"true", FormatStyle::PAS_Left);
311 IO.enumCase(Value,
"false", FormatStyle::PAS_Right);
316 struct ScalarEnumerationTraits<
FormatStyle::SpaceBeforeParensOptions> {
318 FormatStyle::SpaceBeforeParensOptions &
Value) {
319 IO.enumCase(Value,
"Never", FormatStyle::SBPO_Never);
320 IO.enumCase(Value,
"ControlStatements",
321 FormatStyle::SBPO_ControlStatements);
322 IO.enumCase(Value,
"NonEmptyParentheses",
323 FormatStyle::SBPO_NonEmptyParentheses);
324 IO.enumCase(Value,
"Always", FormatStyle::SBPO_Always);
327 IO.enumCase(Value,
"false", FormatStyle::SBPO_Never);
328 IO.enumCase(Value,
"true", FormatStyle::SBPO_ControlStatements);
335 IO.mapOptional(
"Language", Style.Language);
337 if (IO.outputting()) {
338 StringRef StylesArray[] = {
"LLVM",
"Google",
"Chromium",
"Mozilla",
339 "WebKit",
"GNU",
"Microsoft"};
341 for (
size_t i = 0, e = Styles.size(); i < e; ++i) {
342 StringRef StyleName(Styles[i]);
345 Style == PredefinedStyle) {
346 IO.mapOptional(
"# BasedOnStyle", StyleName);
351 StringRef BasedOnStyle;
352 IO.mapOptional(
"BasedOnStyle", BasedOnStyle);
353 if (!BasedOnStyle.empty()) {
354 FormatStyle::LanguageKind OldLanguage = Style.Language;
355 FormatStyle::LanguageKind
Language =
358 IO.setError(Twine(
"Unknown value for BasedOnStyle: ", BasedOnStyle));
361 Style.Language = OldLanguage;
366 if (!IO.outputting()) {
368 IO.mapOptional(
"DerivePointerBinding", Style.DerivePointerAlignment);
369 IO.mapOptional(
"IndentFunctionDeclarationAfterType",
370 Style.IndentWrappedFunctionNames);
371 IO.mapOptional(
"PointerBindsToType", Style.PointerAlignment);
372 IO.mapOptional(
"SpaceAfterControlStatementKeyword",
373 Style.SpaceBeforeParens);
379 IO.mapOptional(
"AlignConsecutiveAssignments",
381 IO.mapOptional(
"AlignConsecutiveDeclarations",
386 IO.mapOptional(
"AllowAllArgumentsOnNextLine",
388 IO.mapOptional(
"AllowAllConstructorInitializersOnNextLine",
389 Style.AllowAllConstructorInitializersOnNextLine);
390 IO.mapOptional(
"AllowAllParametersOfDeclarationOnNextLine",
391 Style.AllowAllParametersOfDeclarationOnNextLine);
392 IO.mapOptional(
"AllowShortBlocksOnASingleLine",
393 Style.AllowShortBlocksOnASingleLine);
394 IO.mapOptional(
"AllowShortCaseLabelsOnASingleLine",
395 Style.AllowShortCaseLabelsOnASingleLine);
396 IO.mapOptional(
"AllowShortFunctionsOnASingleLine",
397 Style.AllowShortFunctionsOnASingleLine);
398 IO.mapOptional(
"AllowShortLambdasOnASingleLine",
399 Style.AllowShortLambdasOnASingleLine);
400 IO.mapOptional(
"AllowShortIfStatementsOnASingleLine",
401 Style.AllowShortIfStatementsOnASingleLine);
402 IO.mapOptional(
"AllowShortLoopsOnASingleLine",
403 Style.AllowShortLoopsOnASingleLine);
404 IO.mapOptional(
"AlwaysBreakAfterDefinitionReturnType",
405 Style.AlwaysBreakAfterDefinitionReturnType);
406 IO.mapOptional(
"AlwaysBreakAfterReturnType",
407 Style.AlwaysBreakAfterReturnType);
412 if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
413 Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None) {
414 if (Style.AlwaysBreakAfterDefinitionReturnType == FormatStyle::DRTBS_All)
415 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
416 else if (Style.AlwaysBreakAfterDefinitionReturnType ==
417 FormatStyle::DRTBS_TopLevel)
418 Style.AlwaysBreakAfterReturnType =
419 FormatStyle::RTBS_TopLevelDefinitions;
422 IO.mapOptional(
"AlwaysBreakBeforeMultilineStrings",
423 Style.AlwaysBreakBeforeMultilineStrings);
424 IO.mapOptional(
"AlwaysBreakTemplateDeclarations",
425 Style.AlwaysBreakTemplateDeclarations);
426 IO.mapOptional(
"BinPackArguments", Style.BinPackArguments);
427 IO.mapOptional(
"BinPackParameters", Style.BinPackParameters);
428 IO.mapOptional(
"BraceWrapping", Style.BraceWrapping);
429 IO.mapOptional(
"BreakBeforeBinaryOperators",
430 Style.BreakBeforeBinaryOperators);
431 IO.mapOptional(
"BreakBeforeBraces", Style.BreakBeforeBraces);
433 bool BreakBeforeInheritanceComma =
false;
434 IO.mapOptional(
"BreakBeforeInheritanceComma", BreakBeforeInheritanceComma);
435 IO.mapOptional(
"BreakInheritanceList", Style.BreakInheritanceList);
439 if (BreakBeforeInheritanceComma &&
440 Style.BreakInheritanceList == FormatStyle::BILS_BeforeColon)
441 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
443 IO.mapOptional(
"BreakBeforeTernaryOperators",
444 Style.BreakBeforeTernaryOperators);
446 bool BreakConstructorInitializersBeforeComma =
false;
447 IO.mapOptional(
"BreakConstructorInitializersBeforeComma",
448 BreakConstructorInitializersBeforeComma);
449 IO.mapOptional(
"BreakConstructorInitializers",
450 Style.BreakConstructorInitializers);
454 if (BreakConstructorInitializersBeforeComma &&
455 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon)
456 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
458 IO.mapOptional(
"BreakAfterJavaFieldAnnotations",
459 Style.BreakAfterJavaFieldAnnotations);
460 IO.mapOptional(
"BreakStringLiterals", Style.BreakStringLiterals);
461 IO.mapOptional(
"ColumnLimit", Style.ColumnLimit);
462 IO.mapOptional(
"CommentPragmas", Style.CommentPragmas);
463 IO.mapOptional(
"CompactNamespaces", Style.CompactNamespaces);
464 IO.mapOptional(
"ConstructorInitializerAllOnOneLineOrOnePerLine",
465 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
466 IO.mapOptional(
"ConstructorInitializerIndentWidth",
467 Style.ConstructorInitializerIndentWidth);
468 IO.mapOptional(
"ContinuationIndentWidth", Style.ContinuationIndentWidth);
469 IO.mapOptional(
"Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
470 IO.mapOptional(
"DeriveLineEnding", Style.DeriveLineEnding);
471 IO.mapOptional(
"DerivePointerAlignment", Style.DerivePointerAlignment);
472 IO.mapOptional(
"DisableFormat", Style.DisableFormat);
473 IO.mapOptional(
"ExperimentalAutoDetectBinPacking",
474 Style.ExperimentalAutoDetectBinPacking);
475 IO.mapOptional(
"FixNamespaceComments", Style.FixNamespaceComments);
476 IO.mapOptional(
"ForEachMacros", Style.ForEachMacros);
477 IO.mapOptional(
"IncludeBlocks", Style.IncludeStyle.IncludeBlocks);
478 IO.mapOptional(
"IncludeCategories", Style.IncludeStyle.IncludeCategories);
479 IO.mapOptional(
"IncludeIsMainRegex", Style.IncludeStyle.IncludeIsMainRegex);
480 IO.mapOptional(
"IncludeIsMainSourceRegex",
481 Style.IncludeStyle.IncludeIsMainSourceRegex);
482 IO.mapOptional(
"IndentCaseLabels", Style.IndentCaseLabels);
483 IO.mapOptional(
"IndentGotoLabels", Style.IndentGotoLabels);
484 IO.mapOptional(
"IndentPPDirectives", Style.IndentPPDirectives);
485 IO.mapOptional(
"IndentWidth", Style.IndentWidth);
486 IO.mapOptional(
"IndentWrappedFunctionNames",
487 Style.IndentWrappedFunctionNames);
488 IO.mapOptional(
"JavaImportGroups", Style.JavaImportGroups);
489 IO.mapOptional(
"JavaScriptQuotes", Style.JavaScriptQuotes);
490 IO.mapOptional(
"JavaScriptWrapImports", Style.JavaScriptWrapImports);
491 IO.mapOptional(
"KeepEmptyLinesAtTheStartOfBlocks",
492 Style.KeepEmptyLinesAtTheStartOfBlocks);
493 IO.mapOptional(
"MacroBlockBegin", Style.MacroBlockBegin);
494 IO.mapOptional(
"MacroBlockEnd", Style.MacroBlockEnd);
495 IO.mapOptional(
"MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
496 IO.mapOptional(
"NamespaceIndentation", Style.NamespaceIndentation);
497 IO.mapOptional(
"NamespaceMacros", Style.NamespaceMacros);
498 IO.mapOptional(
"ObjCBinPackProtocolList", Style.ObjCBinPackProtocolList);
499 IO.mapOptional(
"ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
500 IO.mapOptional(
"ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
501 IO.mapOptional(
"ObjCSpaceBeforeProtocolList",
502 Style.ObjCSpaceBeforeProtocolList);
503 IO.mapOptional(
"PenaltyBreakAssignment", Style.PenaltyBreakAssignment);
504 IO.mapOptional(
"PenaltyBreakBeforeFirstCallParameter",
505 Style.PenaltyBreakBeforeFirstCallParameter);
506 IO.mapOptional(
"PenaltyBreakComment", Style.PenaltyBreakComment);
507 IO.mapOptional(
"PenaltyBreakFirstLessLess",
508 Style.PenaltyBreakFirstLessLess);
509 IO.mapOptional(
"PenaltyBreakString", Style.PenaltyBreakString);
510 IO.mapOptional(
"PenaltyBreakTemplateDeclaration",
511 Style.PenaltyBreakTemplateDeclaration);
512 IO.mapOptional(
"PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
513 IO.mapOptional(
"PenaltyReturnTypeOnItsOwnLine",
514 Style.PenaltyReturnTypeOnItsOwnLine);
515 IO.mapOptional(
"PointerAlignment", Style.PointerAlignment);
516 IO.mapOptional(
"RawStringFormats", Style.RawStringFormats);
517 IO.mapOptional(
"ReflowComments", Style.ReflowComments);
518 IO.mapOptional(
"SortIncludes", Style.SortIncludes);
519 IO.mapOptional(
"SortUsingDeclarations", Style.SortUsingDeclarations);
520 IO.mapOptional(
"SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
521 IO.mapOptional(
"SpaceAfterLogicalNot", Style.SpaceAfterLogicalNot);
522 IO.mapOptional(
"SpaceAfterTemplateKeyword",
523 Style.SpaceAfterTemplateKeyword);
524 IO.mapOptional(
"SpaceBeforeAssignmentOperators",
525 Style.SpaceBeforeAssignmentOperators);
526 IO.mapOptional(
"SpaceBeforeCpp11BracedList",
527 Style.SpaceBeforeCpp11BracedList);
528 IO.mapOptional(
"SpaceBeforeCtorInitializerColon",
529 Style.SpaceBeforeCtorInitializerColon);
530 IO.mapOptional(
"SpaceBeforeInheritanceColon",
531 Style.SpaceBeforeInheritanceColon);
532 IO.mapOptional(
"SpaceBeforeParens", Style.SpaceBeforeParens);
533 IO.mapOptional(
"SpaceBeforeRangeBasedForLoopColon",
534 Style.SpaceBeforeRangeBasedForLoopColon);
535 IO.mapOptional(
"SpaceInEmptyBlock", Style.SpaceInEmptyBlock);
536 IO.mapOptional(
"SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
537 IO.mapOptional(
"SpacesBeforeTrailingComments",
538 Style.SpacesBeforeTrailingComments);
539 IO.mapOptional(
"SpacesInAngles", Style.SpacesInAngles);
540 IO.mapOptional(
"SpacesInConditionalStatement",
541 Style.SpacesInConditionalStatement);
542 IO.mapOptional(
"SpacesInContainerLiterals",
543 Style.SpacesInContainerLiterals);
544 IO.mapOptional(
"SpacesInCStyleCastParentheses",
545 Style.SpacesInCStyleCastParentheses);
546 IO.mapOptional(
"SpacesInParentheses", Style.SpacesInParentheses);
547 IO.mapOptional(
"SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
548 IO.mapOptional(
"SpaceBeforeSquareBrackets",
549 Style.SpaceBeforeSquareBrackets);
550 IO.mapOptional(
"Standard", Style.Standard);
551 IO.mapOptional(
"StatementMacros", Style.StatementMacros);
552 IO.mapOptional(
"TabWidth", Style.TabWidth);
553 IO.mapOptional(
"TypenameMacros", Style.TypenameMacros);
554 IO.mapOptional(
"UseCRLF", Style.UseCRLF);
555 IO.mapOptional(
"UseTab", Style.UseTab);
559 template <>
struct MappingTraits<
FormatStyle::BraceWrappingFlags> {
560 static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
561 IO.mapOptional(
"AfterCaseLabel", Wrapping.AfterCaseLabel);
562 IO.mapOptional(
"AfterClass", Wrapping.AfterClass);
563 IO.mapOptional(
"AfterControlStatement", Wrapping.AfterControlStatement);
564 IO.mapOptional(
"AfterEnum", Wrapping.AfterEnum);
565 IO.mapOptional(
"AfterFunction", Wrapping.AfterFunction);
566 IO.mapOptional(
"AfterNamespace", Wrapping.AfterNamespace);
567 IO.mapOptional(
"AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
568 IO.mapOptional(
"AfterStruct", Wrapping.AfterStruct);
569 IO.mapOptional(
"AfterUnion", Wrapping.AfterUnion);
570 IO.mapOptional(
"AfterExternBlock", Wrapping.AfterExternBlock);
571 IO.mapOptional(
"BeforeCatch", Wrapping.BeforeCatch);
572 IO.mapOptional(
"BeforeElse", Wrapping.BeforeElse);
573 IO.mapOptional(
"IndentBraces", Wrapping.IndentBraces);
574 IO.mapOptional(
"SplitEmptyFunction", Wrapping.SplitEmptyFunction);
575 IO.mapOptional(
"SplitEmptyRecord", Wrapping.SplitEmptyRecord);
576 IO.mapOptional(
"SplitEmptyNamespace", Wrapping.SplitEmptyNamespace);
581 static void mapping(IO &IO, FormatStyle::RawStringFormat &Format) {
582 IO.mapOptional(
"Language", Format.Language);
583 IO.mapOptional(
"Delimiters", Format.Delimiters);
584 IO.mapOptional(
"EnclosingFunctions", Format.EnclosingFunctions);
585 IO.mapOptional(
"CanonicalDelimiter", Format.CanonicalDelimiter);
586 IO.mapOptional(
"BasedOnStyle", Format.BasedOnStyle);
595 template <>
struct DocumentListTraits<
std::vector<FormatStyle>> {
596 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
601 if (Index >= Seq.size()) {
602 assert(Index == Seq.size());
604 if (!Seq.empty() && Seq[0].Language == FormatStyle::LK_None) {
607 Template = *((
const FormatStyle *)IO.getContext());
608 Template.Language = FormatStyle::LK_None;
610 Seq.resize(Index + 1, Template);
630 return llvm::make_error<llvm::StringError>(Message,
631 llvm::inconvertibleErrorCode());
635 return "clang-format.parse_error";
638 std::string ParseErrorCategory::message(
int EV)
const {
639 switch (static_cast<ParseError>(EV)) {
640 case ParseError::Success:
643 return "Invalid argument";
644 case ParseError::Unsuitable:
647 llvm_unreachable(
"unexpected parse error");
651 if (Style.BreakBeforeBraces == FormatStyle::BS_Custom)
654 Expanded.BraceWrapping = {
false,
false, FormatStyle::BWACS_Never,
660 switch (Style.BreakBeforeBraces) {
661 case FormatStyle::BS_Linux:
662 Expanded.BraceWrapping.AfterClass =
true;
663 Expanded.BraceWrapping.AfterFunction =
true;
664 Expanded.BraceWrapping.AfterNamespace =
true;
666 case FormatStyle::BS_Mozilla:
667 Expanded.BraceWrapping.AfterClass =
true;
668 Expanded.BraceWrapping.AfterEnum =
true;
669 Expanded.BraceWrapping.AfterFunction =
true;
670 Expanded.BraceWrapping.AfterStruct =
true;
671 Expanded.BraceWrapping.AfterUnion =
true;
672 Expanded.BraceWrapping.AfterExternBlock =
true;
673 Expanded.BraceWrapping.SplitEmptyFunction =
true;
674 Expanded.BraceWrapping.SplitEmptyRecord =
false;
676 case FormatStyle::BS_Stroustrup:
677 Expanded.BraceWrapping.AfterFunction =
true;
678 Expanded.BraceWrapping.BeforeCatch =
true;
679 Expanded.BraceWrapping.BeforeElse =
true;
681 case FormatStyle::BS_Allman:
682 Expanded.BraceWrapping.AfterCaseLabel =
true;
683 Expanded.BraceWrapping.AfterClass =
true;
684 Expanded.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
685 Expanded.BraceWrapping.AfterEnum =
true;
686 Expanded.BraceWrapping.AfterFunction =
true;
687 Expanded.BraceWrapping.AfterNamespace =
true;
688 Expanded.BraceWrapping.AfterObjCDeclaration =
true;
689 Expanded.BraceWrapping.AfterStruct =
true;
690 Expanded.BraceWrapping.AfterUnion =
true;
691 Expanded.BraceWrapping.AfterExternBlock =
true;
692 Expanded.BraceWrapping.BeforeCatch =
true;
693 Expanded.BraceWrapping.BeforeElse =
true;
695 case FormatStyle::BS_Whitesmiths:
696 Expanded.BraceWrapping.AfterCaseLabel =
true;
697 Expanded.BraceWrapping.AfterClass =
true;
698 Expanded.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
699 Expanded.BraceWrapping.AfterEnum =
true;
700 Expanded.BraceWrapping.AfterFunction =
true;
701 Expanded.BraceWrapping.AfterNamespace =
true;
702 Expanded.BraceWrapping.AfterObjCDeclaration =
true;
703 Expanded.BraceWrapping.AfterStruct =
true;
704 Expanded.BraceWrapping.AfterExternBlock =
true;
705 Expanded.BraceWrapping.BeforeCatch =
true;
706 Expanded.BraceWrapping.BeforeElse =
true;
708 case FormatStyle::BS_GNU:
709 Expanded.BraceWrapping = {
true,
true, FormatStyle::BWACS_Always,
716 case FormatStyle::BS_WebKit:
717 Expanded.BraceWrapping.AfterFunction =
true;
737 LLVMStyle.AllowAllConstructorInitializersOnNextLine =
true;
738 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine =
true;
739 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
740 LLVMStyle.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
741 LLVMStyle.AllowShortCaseLabelsOnASingleLine =
false;
742 LLVMStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
743 LLVMStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
744 LLVMStyle.AllowShortLoopsOnASingleLine =
false;
745 LLVMStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
746 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
747 LLVMStyle.AlwaysBreakBeforeMultilineStrings =
false;
748 LLVMStyle.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_MultiLine;
749 LLVMStyle.BinPackArguments =
true;
750 LLVMStyle.BinPackParameters =
true;
751 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
752 LLVMStyle.BreakBeforeTernaryOperators =
true;
753 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
754 LLVMStyle.BraceWrapping = {
false,
false, FormatStyle::BWACS_Never,
760 LLVMStyle.BreakAfterJavaFieldAnnotations =
false;
761 LLVMStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
762 LLVMStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
763 LLVMStyle.BreakStringLiterals =
true;
764 LLVMStyle.ColumnLimit = 80;
765 LLVMStyle.CommentPragmas =
"^ IWYU pragma:";
766 LLVMStyle.CompactNamespaces =
false;
767 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine =
false;
768 LLVMStyle.ConstructorInitializerIndentWidth = 4;
769 LLVMStyle.ContinuationIndentWidth = 4;
770 LLVMStyle.Cpp11BracedListStyle =
true;
771 LLVMStyle.DeriveLineEnding =
true;
772 LLVMStyle.DerivePointerAlignment =
false;
773 LLVMStyle.ExperimentalAutoDetectBinPacking =
false;
774 LLVMStyle.FixNamespaceComments =
true;
775 LLVMStyle.ForEachMacros.push_back(
"foreach");
776 LLVMStyle.ForEachMacros.push_back(
"Q_FOREACH");
777 LLVMStyle.ForEachMacros.push_back(
"BOOST_FOREACH");
778 LLVMStyle.IncludeStyle.IncludeCategories = {
779 {
"^\"(llvm|llvm-c|clang|clang-c)/", 2, 0},
780 {
"^(<|\"(gtest|gmock|isl|json)/)", 3, 0},
782 LLVMStyle.IncludeStyle.IncludeIsMainRegex =
"(Test)?$";
783 LLVMStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Preserve;
784 LLVMStyle.IndentCaseLabels =
false;
785 LLVMStyle.IndentGotoLabels =
true;
786 LLVMStyle.IndentPPDirectives = FormatStyle::PPDIS_None;
787 LLVMStyle.IndentWrappedFunctionNames =
false;
788 LLVMStyle.IndentWidth = 2;
789 LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
790 LLVMStyle.JavaScriptWrapImports =
true;
791 LLVMStyle.TabWidth = 8;
792 LLVMStyle.MaxEmptyLinesToKeep = 1;
793 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks =
true;
794 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
795 LLVMStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Auto;
796 LLVMStyle.ObjCBlockIndentWidth = 2;
797 LLVMStyle.ObjCSpaceAfterProperty =
false;
798 LLVMStyle.ObjCSpaceBeforeProtocolList =
true;
799 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
800 LLVMStyle.SpacesBeforeTrailingComments = 1;
801 LLVMStyle.Standard = FormatStyle::LS_Latest;
802 LLVMStyle.UseCRLF =
false;
803 LLVMStyle.UseTab = FormatStyle::UT_Never;
804 LLVMStyle.ReflowComments =
true;
805 LLVMStyle.SpacesInParentheses =
false;
806 LLVMStyle.SpacesInSquareBrackets =
false;
807 LLVMStyle.SpaceInEmptyBlock =
false;
808 LLVMStyle.SpaceInEmptyParentheses =
false;
809 LLVMStyle.SpacesInContainerLiterals =
true;
810 LLVMStyle.SpacesInCStyleCastParentheses =
false;
811 LLVMStyle.SpaceAfterCStyleCast =
false;
812 LLVMStyle.SpaceAfterLogicalNot =
false;
813 LLVMStyle.SpaceAfterTemplateKeyword =
true;
814 LLVMStyle.SpaceBeforeCtorInitializerColon =
true;
815 LLVMStyle.SpaceBeforeInheritanceColon =
true;
816 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
817 LLVMStyle.SpaceBeforeRangeBasedForLoopColon =
true;
818 LLVMStyle.SpaceBeforeAssignmentOperators =
true;
819 LLVMStyle.SpaceBeforeCpp11BracedList =
false;
820 LLVMStyle.SpaceBeforeSquareBrackets =
false;
821 LLVMStyle.SpacesInAngles =
false;
822 LLVMStyle.SpacesInConditionalStatement =
false;
825 LLVMStyle.PenaltyBreakComment = 300;
826 LLVMStyle.PenaltyBreakFirstLessLess = 120;
827 LLVMStyle.PenaltyBreakString = 1000;
828 LLVMStyle.PenaltyExcessCharacter = 1000000;
829 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
830 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
833 LLVMStyle.DisableFormat =
false;
834 LLVMStyle.SortIncludes =
true;
835 LLVMStyle.SortUsingDeclarations =
true;
836 LLVMStyle.StatementMacros.push_back(
"Q_UNUSED");
837 LLVMStyle.StatementMacros.push_back(
"QT_REQUIRE_VERSION");
840 if (Language == FormatStyle::LK_TableGen) {
841 LLVMStyle.SpacesInContainerLiterals =
false;
848 if (Language == FormatStyle::LK_TextProto) {
850 GoogleStyle.Language = FormatStyle::LK_TextProto;
859 GoogleStyle.AllowShortIfStatementsOnASingleLine =
860 FormatStyle::SIS_WithoutElse;
861 GoogleStyle.AllowShortLoopsOnASingleLine =
true;
862 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
true;
863 GoogleStyle.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
864 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine =
true;
865 GoogleStyle.DerivePointerAlignment =
true;
866 GoogleStyle.IncludeStyle.IncludeCategories = {{
"^<ext/.*\\.h>", 2, 0},
870 GoogleStyle.IncludeStyle.IncludeIsMainRegex =
"([-_](test|unittest))?$";
871 GoogleStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Regroup;
872 GoogleStyle.IndentCaseLabels =
true;
873 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks =
false;
874 GoogleStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
875 GoogleStyle.ObjCSpaceAfterProperty =
false;
876 GoogleStyle.ObjCSpaceBeforeProtocolList =
true;
877 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
878 GoogleStyle.RawStringFormats = {
897 FormatStyle::LK_TextProto,
909 "PARSE_PARTIAL_TEXT_PROTO",
913 "ParseTextProtoOrDie",
919 GoogleStyle.SpacesBeforeTrailingComments = 2;
920 GoogleStyle.Standard = FormatStyle::LS_Auto;
922 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
923 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
925 if (Language == FormatStyle::LK_Java) {
929 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
930 GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
931 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
932 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
933 GoogleStyle.ColumnLimit = 100;
934 GoogleStyle.SpaceAfterCStyleCast =
true;
935 GoogleStyle.SpacesBeforeTrailingComments = 1;
936 }
else if (Language == FormatStyle::LK_JavaScript) {
939 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
940 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
941 GoogleStyle.BreakBeforeTernaryOperators =
false;
944 GoogleStyle.CommentPragmas =
"(taze:|^/[ \t]*<|@see)";
945 GoogleStyle.MaxEmptyLinesToKeep = 3;
946 GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
947 GoogleStyle.SpacesInContainerLiterals =
false;
948 GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single;
949 GoogleStyle.JavaScriptWrapImports =
false;
950 }
else if (Language == FormatStyle::LK_Proto) {
951 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
952 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
953 GoogleStyle.SpacesInContainerLiterals =
false;
954 GoogleStyle.Cpp11BracedListStyle =
false;
960 GoogleStyle.BreakStringLiterals =
false;
961 }
else if (Language == FormatStyle::LK_ObjC) {
962 GoogleStyle.AlwaysBreakBeforeMultilineStrings =
false;
963 GoogleStyle.ColumnLimit = 100;
967 GoogleStyle.IncludeStyle.IncludeBlocks =
968 tooling::IncludeStyle::IBS_Preserve;
994 ChromiumStyle.IncludeStyle.IncludeBlocks =
995 tooling::IncludeStyle::IBS_Preserve;
997 if (Language == FormatStyle::LK_Java) {
998 ChromiumStyle.AllowShortIfStatementsOnASingleLine =
999 FormatStyle::SIS_WithoutElse;
1000 ChromiumStyle.BreakAfterJavaFieldAnnotations =
true;
1001 ChromiumStyle.ContinuationIndentWidth = 8;
1002 ChromiumStyle.IndentWidth = 4;
1005 ChromiumStyle.JavaImportGroups = {
1012 "com.google.android.apps.chrome",
1017 ChromiumStyle.SortIncludes =
true;
1018 }
else if (Language == FormatStyle::LK_JavaScript) {
1019 ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
1020 ChromiumStyle.AllowShortLoopsOnASingleLine =
false;
1022 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine =
false;
1023 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
1024 ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
1025 ChromiumStyle.AllowShortLoopsOnASingleLine =
false;
1026 ChromiumStyle.BinPackParameters =
false;
1027 ChromiumStyle.DerivePointerAlignment =
false;
1028 if (Language == FormatStyle::LK_ObjC)
1029 ChromiumStyle.ColumnLimit = 80;
1031 return ChromiumStyle;
1036 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine =
false;
1037 MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
1038 MozillaStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
1039 MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
1040 FormatStyle::DRTBS_TopLevel;
1041 MozillaStyle.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
1042 MozillaStyle.BinPackParameters =
false;
1043 MozillaStyle.BinPackArguments =
false;
1044 MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
1045 MozillaStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
1046 MozillaStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
1047 MozillaStyle.ConstructorInitializerIndentWidth = 2;
1048 MozillaStyle.ContinuationIndentWidth = 2;
1049 MozillaStyle.Cpp11BracedListStyle =
false;
1050 MozillaStyle.FixNamespaceComments =
false;
1051 MozillaStyle.IndentCaseLabels =
true;
1052 MozillaStyle.ObjCSpaceAfterProperty =
true;
1053 MozillaStyle.ObjCSpaceBeforeProtocolList =
false;
1054 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
1055 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
1056 MozillaStyle.SpaceAfterTemplateKeyword =
false;
1057 return MozillaStyle;
1066 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
1067 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
1068 Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
1069 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
1070 Style.Cpp11BracedListStyle =
false;
1071 Style.ColumnLimit = 0;
1072 Style.FixNamespaceComments =
false;
1073 Style.IndentWidth = 4;
1074 Style.NamespaceIndentation = FormatStyle::NI_Inner;
1075 Style.ObjCBlockIndentWidth = 4;
1076 Style.ObjCSpaceAfterProperty =
true;
1077 Style.PointerAlignment = FormatStyle::PAS_Left;
1078 Style.SpaceBeforeCpp11BracedList =
true;
1079 Style.SpaceInEmptyBlock =
true;
1085 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
1086 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
1087 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
1088 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
1089 Style.BreakBeforeTernaryOperators =
true;
1090 Style.Cpp11BracedListStyle =
false;
1091 Style.ColumnLimit = 79;
1092 Style.FixNamespaceComments =
false;
1093 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
1094 Style.Standard = FormatStyle::LS_Cpp03;
1100 Style.ColumnLimit = 120;
1102 Style.IndentWidth = 4;
1103 Style.UseTab = FormatStyle::UT_Never;
1104 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
1105 Style.BraceWrapping.AfterClass =
true;
1106 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1107 Style.BraceWrapping.AfterEnum =
true;
1108 Style.BraceWrapping.AfterFunction =
true;
1109 Style.BraceWrapping.AfterNamespace =
true;
1110 Style.BraceWrapping.AfterObjCDeclaration =
true;
1111 Style.BraceWrapping.AfterStruct =
true;
1112 Style.BraceWrapping.AfterExternBlock =
true;
1113 Style.BraceWrapping.BeforeCatch =
true;
1114 Style.BraceWrapping.BeforeElse =
true;
1115 Style.PenaltyReturnTypeOnItsOwnLine = 1000;
1116 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
1117 Style.AllowShortCaseLabelsOnASingleLine =
false;
1118 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
1119 Style.AllowShortLoopsOnASingleLine =
false;
1120 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
1121 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
1127 NoStyle.DisableFormat =
true;
1128 NoStyle.SortIncludes =
false;
1129 NoStyle.SortUsingDeclarations =
false;
1135 if (Name.equals_lower(
"llvm")) {
1137 }
else if (Name.equals_lower(
"chromium")) {
1139 }
else if (Name.equals_lower(
"mozilla")) {
1141 }
else if (Name.equals_lower(
"google")) {
1143 }
else if (Name.equals_lower(
"webkit")) {
1145 }
else if (Name.equals_lower(
"gnu")) {
1147 }
else if (Name.equals_lower(
"microsoft")) {
1149 }
else if (Name.equals_lower(
"none")) {
1161 FormatStyle::LanguageKind
Language = Style->Language;
1162 assert(Language != FormatStyle::LK_None);
1163 if (Text.trim().empty())
1165 Style->StyleSet.Clear();
1166 std::vector<FormatStyle> Styles;
1167 llvm::yaml::Input Input(Text);
1172 Input.setContext(Style);
1175 return Input.error();
1177 for (
unsigned i = 0; i < Styles.size(); ++i) {
1179 if (Styles[i].Language == FormatStyle::LK_None && i != 0)
1182 for (
unsigned j = 0; j < i; ++j) {
1183 if (Styles[i].Language == Styles[j].Language) {
1184 LLVM_DEBUG(llvm::dbgs()
1185 <<
"Duplicate languages in the config file on positions " 1186 << j <<
" and " << i <<
"\n");
1194 FormatStyle::FormatStyleSet StyleSet;
1195 bool LanguageFound =
false;
1196 for (
int i = Styles.size() - 1; i >= 0; --i) {
1197 if (Styles[i].Language != FormatStyle::LK_None)
1198 StyleSet.Add(Styles[i]);
1199 if (Styles[i].Language == Language)
1200 LanguageFound =
true;
1202 if (!LanguageFound) {
1203 if (Styles.empty() || Styles[0].Language != FormatStyle::LK_None)
1207 StyleSet.Add(std::move(DefaultStyle));
1209 *Style = *StyleSet.Get(Language);
1215 llvm::raw_string_ostream Stream(Text);
1216 llvm::yaml::Output Output(Stream);
1220 Output << NonConstStyle;
1221 return Stream.str();
1225 FormatStyle::FormatStyleSet::Get(FormatStyle::LanguageKind
Language)
const {
1228 auto It = Styles->find(Language);
1229 if (It == Styles->end())
1232 Style.StyleSet = *
this;
1237 assert(Style.Language != LK_None &&
1238 "Cannot add a style for LK_None to a StyleSet");
1240 !Style.StyleSet.Styles &&
1241 "Cannot add a style associated with an existing StyleSet to a StyleSet");
1243 Styles = std::make_shared<MapType>();
1244 (*Styles)[Style.Language] = std::move(Style);
1247 void FormatStyle::FormatStyleSet::Clear() { Styles.reset(); }
1250 FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind Language)
const {
1251 return StyleSet.Get(Language);
1261 std::pair<tooling::Replacements, unsigned>
1265 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
1267 requoteJSStringLiteral(AnnotatedLines, Result);
1277 requoteJSStringLiteral(
Line->Children, Result);
1278 if (!
Line->Affected)
1281 FormatTok = FormatTok->Next) {
1282 StringRef Input = FormatTok->TokenText;
1283 if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
1286 (Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
1287 !Input.startswith(
"\"")) ||
1288 (Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
1289 !Input.startswith(
"\'")))
1293 bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
1296 StringRef ReplacementText) {
1306 Replace(Start, 1, IsSingle ?
"'" :
"\"");
1307 Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
1308 IsSingle ?
"'" :
"\"");
1311 bool Escaped =
false;
1312 for (
size_t i = 1; i < Input.size() - 1; i++) {
1315 if (!Escaped && i + 1 < Input.size() &&
1316 ((IsSingle && Input[i + 1] ==
'"') ||
1317 (!IsSingle && Input[i + 1] ==
'\''))) {
1327 if (!Escaped && IsSingle == (Input[i] ==
'\'')) {
1349 std::pair<tooling::Replacements, unsigned>
1354 deriveLocalStyle(AnnotatedLines);
1355 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
1356 for (
unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1363 Style.DeriveLineEnding
1370 BinPackInconclusiveFunctions);
1375 .format(AnnotatedLines,
false,
1381 for (
const auto &R : Whitespaces.generateReplacements())
1383 return std::make_pair(Result, 0);
1384 return std::make_pair(Result, Penalty);
1388 static bool inputUsesCRLF(StringRef
Text,
bool DefaultToCRLF) {
1389 size_t LF = Text.count(
'\n');
1390 size_t CR = Text.count(
'\r') * 2;
1391 return LF == CR ? DefaultToCRLF : CR > LF;
1397 if (hasCpp03IncompatibleFormat(
Line->Children))
1403 if (
Tok->
is(TT_TemplateCloser) &&
1413 int AlignmentDiff = 0;
1415 AlignmentDiff += countVariableAlignments(
Line->Children);
1417 if (!
Tok->
is(TT_PointerOrReference))
1423 if (SpaceBefore && !SpaceAfter)
1425 if (!SpaceBefore && SpaceAfter)
1429 return AlignmentDiff;
1434 bool HasBinPackedFunction =
false;
1435 bool HasOnePerLineFunction =
false;
1436 for (
unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1437 if (!AnnotatedLines[i]->
First->Next)
1442 HasBinPackedFunction =
true;
1444 HasOnePerLineFunction =
true;
1449 if (Style.DerivePointerAlignment)
1450 Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
1451 ? FormatStyle::PAS_Left
1452 : FormatStyle::PAS_Right;
1453 if (Style.Standard == FormatStyle::LS_Auto)
1454 Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
1455 ? FormatStyle::LS_Latest
1456 : FormatStyle::LS_Cpp03;
1457 BinPackInconclusiveFunctions =
1458 HasBinPackedFunction || !HasOnePerLineFunction;
1461 bool BinPackInconclusiveFunctions;
1474 std::pair<tooling::Replacements, unsigned>
1485 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
1487 checkEmptyNamespace(AnnotatedLines);
1489 for (
auto *
Line : AnnotatedLines)
1492 return {generateFixes(), 0};
1497 for (
auto *Child : Line->
Children) {
1502 cleanupRight(Line->
First, tok::comma, tok::comma);
1503 cleanupRight(Line->
First, TT_CtorInitializerColon, tok::comma);
1504 cleanupRight(Line->
First, tok::l_paren, tok::comma);
1505 cleanupLeft(Line->
First, tok::comma, tok::r_paren);
1506 cleanupLeft(Line->
First, TT_CtorInitializerComma, tok::l_brace);
1507 cleanupLeft(Line->
First, TT_CtorInitializerColon, tok::l_brace);
1508 cleanupLeft(Line->
First, TT_CtorInitializerColon, tok::equal);
1522 std::set<unsigned> DeletedLines;
1523 for (
unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1524 auto &Line = *AnnotatedLines[i];
1526 checkEmptyNamespace(AnnotatedLines, i, i, DeletedLines);
1530 for (
auto Line : DeletedLines) {
1544 unsigned CurrentLine,
unsigned &
NewLine,
1545 std::set<unsigned> &DeletedLines) {
1546 unsigned InitLine = CurrentLine,
End = AnnotatedLines.size();
1547 if (Style.BraceWrapping.AfterNamespace) {
1551 if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
1552 NewLine = CurrentLine;
1555 }
else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
1558 while (++CurrentLine < End) {
1559 if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
1562 if (AnnotatedLines[CurrentLine]->startsWithNamespace()) {
1563 if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine,
1570 if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
1575 NewLine = CurrentLine;
1579 NewLine = CurrentLine;
1580 if (CurrentLine >= End)
1584 if (!AffectedRangeMgr.affectsCharSourceRange(CharSourceRange::getCharRange(
1585 AnnotatedLines[InitLine]->First->Tok.getLocation(),
1586 AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc())))
1589 for (
unsigned i = InitLine; i <= CurrentLine; ++i) {
1590 DeletedLines.insert(i);
1600 template <
typename LeftKind,
typename RightKind>
1601 void cleanupPair(
FormatToken *Start, LeftKind LK, RightKind RK,
1605 if (!Res->is(tok::comment) &&
1606 DeletedTokens.find(Res) == DeletedTokens.end())
1610 for (
auto *Left = Start; Left;) {
1611 auto *Right = NextNotDeleted(*Left);
1614 if (Left->is(LK) && Right->is(RK)) {
1615 deleteToken(DeleteLeft ? Left : Right);
1627 template <
typename LeftKind,
typename RightKind>
1628 void cleanupLeft(
FormatToken *Start, LeftKind LK, RightKind RK) {
1629 cleanupPair(Start, LK, RK,
true);
1632 template <
typename LeftKind,
typename RightKind>
1633 void cleanupRight(
FormatToken *Start, LeftKind LK, RightKind RK) {
1634 cleanupPair(Start, LK, RK,
false);
1640 DeletedTokens.insert(Tok);
1645 std::vector<FormatToken *> Tokens;
1646 std::copy(DeletedTokens.begin(), DeletedTokens.end(),
1647 std::back_inserter(Tokens));
1653 while (Idx < Tokens.size()) {
1654 unsigned St = Idx,
End = Idx;
1655 while ((End + 1) < Tokens.size() &&
1656 Tokens[
End]->Next == Tokens[End + 1]) {
1659 auto SR = CharSourceRange::getCharRange(Tokens[St]->Tok.getLocation(),
1667 assert(
false &&
"Fixes must not conflict!");
1678 struct FormatTokenLess {
1689 std::set<FormatToken *, FormatTokenLess> DeletedTokens;
1692 class ObjCHeaderStyleGuesser :
public TokenAnalyzer {
1694 ObjCHeaderStyleGuesser(
const Environment &Env,
const FormatStyle &Style)
1695 : TokenAnalyzer(Env, Style), IsObjC(
false) {}
1697 std::pair<tooling::Replacements, unsigned>
1698 analyze(TokenAnnotator &Annotator,
1699 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1700 FormatTokenLexer &Tokens)
override {
1701 assert(Style.Language == FormatStyle::LK_Cpp);
1702 IsObjC = guessIsObjC(Env.getSourceManager(), AnnotatedLines,
1703 Tokens.getKeywords());
1704 tooling::Replacements Result;
1708 bool isObjC() {
return IsObjC; }
1712 guessIsObjC(
const SourceManager &SourceManager,
1713 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1714 const AdditionalKeywords &Keywords) {
1716 static constexpr llvm::StringLiteral FoundationIdentifiers[] = {
1731 "NSAffineTransform",
1733 "NSAttributedString",
1750 "NSInvocationOperation",
1754 "NSMutableAttributedString",
1755 "NSMutableCharacterSet",
1757 "NSMutableDictionary",
1758 "NSMutableIndexSet",
1759 "NSMutableOrderedSet",
1763 "NSNumberFormatter",
1767 "NSOperationQueuePriority",
1771 "NSQualityOfService",
1774 "NSRegularExpression",
1789 for (
auto Line : AnnotatedLines) {
1790 for (
const FormatToken *FormatTok =
Line->First; FormatTok;
1791 FormatTok = FormatTok->Next) {
1792 if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) &&
1793 (FormatTok->Tok.getObjCKeywordID() != tok::objc_not_keyword ||
1794 FormatTok->isOneOf(tok::numeric_constant, tok::l_square,
1796 (FormatTok->Tok.isAnyIdentifier() &&
1797 std::binary_search(std::begin(FoundationIdentifiers),
1798 std::end(FoundationIdentifiers),
1799 FormatTok->TokenText)) ||
1800 FormatTok->is(TT_ObjCStringLiteral) ||
1801 FormatTok->isOneOf(Keywords.kw_NS_CLOSED_ENUM, Keywords.kw_NS_ENUM,
1802 Keywords.kw_NS_OPTIONS, TT_ObjCBlockLBrace,
1803 TT_ObjCBlockLParen, TT_ObjCDecl, TT_ObjCForIn,
1804 TT_ObjCMethodExpr, TT_ObjCMethodSpecifier,
1806 LLVM_DEBUG(llvm::dbgs()
1807 <<
"Detected ObjC at location " 1808 << FormatTok->Tok.getLocation().printToString(
1810 <<
" token: " << FormatTok->TokenText <<
" token type: " 1814 if (guessIsObjC(SourceManager,
Line->Children, Keywords))
1824 struct IncludeDirective {
1832 struct JavaImportDirective {
1845 for (
auto Range : Ranges) {
1846 if (Range.getOffset() < End &&
1847 Range.getOffset() + Range.getLength() > Start)
1860 static std::pair<unsigned, unsigned>
1864 unsigned OffsetToEOL = 0;
1865 for (
int i = 0, e = Includes.size(); i != e; ++i) {
1866 unsigned Start = Includes[Indices[i]].Offset;
1867 unsigned End = Start + Includes[Indices[i]].Text.size();
1868 if (!(Cursor >= Start && Cursor < End))
1870 CursorIndex = Indices[i];
1871 OffsetToEOL = End -
Cursor;
1874 while (--i >= 0 && Includes[CursorIndex].
Text == Includes[Indices[i]].
Text)
1878 return std::make_pair(CursorIndex, OffsetToEOL);
1883 std::string NewCode;
1884 size_t Pos = 0, LastPos = 0;
1887 Pos = Code.find(
"\r\n", LastPos);
1888 if (Pos == LastPos) {
1892 if (Pos == std::string::npos) {
1893 NewCode += Code.substr(LastPos);
1896 NewCode += Code.substr(LastPos, Pos - LastPos) +
"\n";
1898 }
while (Pos != std::string::npos);
1916 unsigned IncludesBeginOffset = Includes.front().Offset;
1917 unsigned IncludesEndOffset =
1918 Includes.back().Offset + Includes.back().Text.size();
1919 unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset;
1920 if (!
affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset))
1923 for (
unsigned i = 0, e = Includes.size(); i != e; ++i) {
1924 Indices.push_back(i);
1926 llvm::stable_sort(Indices, [&](
unsigned LHSI,
unsigned RHSI) {
1928 std::tie(Includes[RHSI].Priority, Includes[RHSI].Filename);
1932 unsigned CursorIndex;
1934 unsigned CursorToEOLOffset;
1936 std::tie(CursorIndex, CursorToEOLOffset) =
1940 Indices.erase(std::unique(Indices.begin(), Indices.end(),
1941 [&](
unsigned LHSI,
unsigned RHSI) {
1942 return Includes[LHSI].Text == Includes[RHSI].Text;
1946 int CurrentCategory = Includes.front().Category;
1954 if (Indices.size() == Includes.size() &&
1955 std::is_sorted(Indices.begin(), Indices.end()) &&
1956 Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Preserve)
1960 for (
unsigned Index : Indices) {
1961 if (!result.empty()) {
1963 if (Style.IncludeStyle.IncludeBlocks ==
1964 tooling::IncludeStyle::IBS_Regroup &&
1965 CurrentCategory != Includes[Index].Category)
1968 result += Includes[Index].Text;
1969 if (Cursor && CursorIndex == Index)
1970 *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
1971 CurrentCategory = Includes[Index].Category;
1977 replaceCRLF(Code.substr(IncludesBeginOffset, IncludesBlockSize)))
1981 FileName, Includes.front().Offset, IncludesBlockSize, result));
1992 const char CppIncludeRegexPattern[] =
1993 R
"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))"; 2003 unsigned SearchFrom = 0;
2004 llvm::Regex IncludeRegex(CppIncludeRegexPattern);
2016 bool FirstIncludeBlock =
true;
2017 bool MainIncludeFound =
false;
2018 bool FormattingOff =
false;
2021 auto Pos = Code.find(
'\n', SearchFrom);
2023 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
2025 StringRef Trimmed = Line.trim();
2026 if (Trimmed ==
"// clang-format off" || Trimmed ==
"/* clang-format off */")
2027 FormattingOff =
true;
2028 else if (Trimmed ==
"// clang-format on" ||
2029 Trimmed ==
"/* clang-format on */")
2030 FormattingOff =
false;
2032 const bool EmptyLineSkipped =
2034 (Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Merge ||
2035 Style.IncludeStyle.IncludeBlocks ==
2036 tooling::IncludeStyle::IBS_Regroup);
2038 if (!FormattingOff && !Line.endswith(
"\\")) {
2039 if (IncludeRegex.match(Line, &Matches)) {
2040 StringRef IncludeName = Matches[2];
2043 !MainIncludeFound && FirstIncludeBlock);
2045 IncludeName, !MainIncludeFound && FirstIncludeBlock);
2047 MainIncludeFound =
true;
2048 IncludesInBlock.push_back(
2050 }
else if (!IncludesInBlock.empty() && !EmptyLineSkipped) {
2053 IncludesInBlock.clear();
2054 FirstIncludeBlock =
false;
2058 if (Pos == StringRef::npos || Pos + 1 == Code.size())
2060 SearchFrom = Pos + 1;
2062 if (!IncludesInBlock.empty()) {
2063 sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Code, Replaces,
2072 StringRef ImportIdentifier) {
2073 unsigned LongestMatchIndex =
UINT_MAX;
2074 unsigned LongestMatchLength = 0;
2075 for (
unsigned I = 0; I < Style.JavaImportGroups.size(); I++) {
2076 std::string GroupPrefix = Style.JavaImportGroups[I];
2077 if (ImportIdentifier.startswith(GroupPrefix) &&
2078 GroupPrefix.length() > LongestMatchLength) {
2079 LongestMatchIndex = I;
2080 LongestMatchLength = GroupPrefix.length();
2083 return LongestMatchIndex;
2095 unsigned ImportsBeginOffset = Imports.front().Offset;
2096 unsigned ImportsEndOffset =
2097 Imports.back().Offset + Imports.back().Text.size();
2098 unsigned ImportsBlockSize = ImportsEndOffset - ImportsBeginOffset;
2099 if (!
affectsRange(Ranges, ImportsBeginOffset, ImportsEndOffset))
2103 for (
unsigned i = 0, e = Imports.size(); i != e; ++i) {
2104 Indices.push_back(i);
2105 JavaImportGroups.push_back(
2108 llvm::sort(Indices, [&](
unsigned LHSI,
unsigned RHSI) {
2110 return std::make_tuple(!Imports[LHSI].
IsStatic, JavaImportGroups[LHSI],
2112 std::make_tuple(!Imports[RHSI].IsStatic, JavaImportGroups[RHSI],
2113 Imports[RHSI].Identifier);
2117 Indices.erase(std::unique(Indices.begin(), Indices.end(),
2118 [&](
unsigned LHSI,
unsigned RHSI) {
2119 return Imports[LHSI].Text == Imports[RHSI].Text;
2123 bool CurrentIsStatic = Imports[Indices.front()].IsStatic;
2124 unsigned CurrentImportGroup = JavaImportGroups[Indices.front()];
2127 for (
unsigned Index : Indices) {
2128 if (!result.empty()) {
2130 if (CurrentIsStatic != Imports[Index].
IsStatic ||
2131 CurrentImportGroup != JavaImportGroups[Index])
2135 result += CommentLine;
2138 result += Imports[Index].Text;
2139 CurrentIsStatic = Imports[Index].IsStatic;
2140 CurrentImportGroup = JavaImportGroups[Index];
2146 replaceCRLF(Code.substr(Imports.front().Offset, ImportsBlockSize)))
2150 ImportsBlockSize, result));
2161 const char JavaImportRegexPattern[] =
2162 "^[\t ]*import[\t ]+(static[\t ]*)?([^\t ]*)[\t ]*;";
2171 unsigned SearchFrom = 0;
2172 llvm::Regex ImportRegex(JavaImportRegexPattern);
2177 bool FormattingOff =
false;
2180 auto Pos = Code.find(
'\n', SearchFrom);
2182 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
2184 StringRef Trimmed = Line.trim();
2185 if (Trimmed ==
"// clang-format off")
2186 FormattingOff =
true;
2187 else if (Trimmed ==
"// clang-format on")
2188 FormattingOff =
false;
2190 if (ImportRegex.match(Line, &Matches)) {
2191 if (FormattingOff) {
2196 StringRef Static = Matches[1];
2199 if (Static.contains(
"static")) {
2202 ImportsInBlock.push_back(
2204 AssociatedCommentLines.clear();
2205 }
else if (Trimmed.size() > 0 && !ImportsInBlock.empty()) {
2207 AssociatedCommentLines.push_back(Line);
2210 if (Pos == StringRef::npos || Pos + 1 == Code.size())
2212 SearchFrom = Pos + 1;
2214 if (!ImportsInBlock.empty())
2215 sortJavaImports(Style, ImportsInBlock, Ranges, FileName, Code, Replaces);
2223 return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
2226 bool isLikelyXml(StringRef Code) {
return Code.ltrim().startswith(
"<"); }
2230 StringRef FileName,
unsigned *
Cursor) {
2232 if (!Style.SortIncludes)
2236 if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
2239 if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript)
2241 if (Style.Language == FormatStyle::LanguageKind::LK_Java)
2247 template <
typename T>
2252 if (Replaces.
empty())
2257 return NewCode.takeError();
2259 StringRef FileName = Replaces.
begin()->getFilePath();
2262 ProcessFunc(Style, *NewCode, ChangedRanges, FileName);
2264 return Replaces.
merge(FormatReplaces);
2273 std::vector<tooling::Range> Ranges,
2277 auto SortedReplaces =
2279 if (!SortedReplaces)
2280 return SortedReplaces.takeError();
2285 std::vector<tooling::Range> Ranges,
2287 return reformat(Style, Code, Ranges, FileName);
2296 llvm::Regex(CppIncludeRegexPattern)
2312 std::set<llvm::StringRef> HeadersToDelete;
2314 for (
const auto &R : Replaces) {
2315 if (isHeaderInsertion(R)) {
2318 llvm::consumeError(HeaderInsertions.
add(R));
2319 }
else if (isHeaderDeletion(R)) {
2320 HeadersToDelete.insert(R.getReplacementText());
2321 }
else if (R.getOffset() ==
UINT_MAX) {
2322 llvm::errs() <<
"Insertions other than header #include insertion are " 2324 << R.getReplacementText() <<
"\n";
2326 llvm::consumeError(Result.
add(R));
2329 if (HeaderInsertions.
empty() && HeadersToDelete.empty())
2332 StringRef FileName = Replaces.begin()->getFilePath();
2335 for (
const auto &Header : HeadersToDelete) {
2337 Includes.
remove(Header.trim(
"\"<>"), Header.startswith(
"<"));
2338 for (
const auto &R : Replaces) {
2339 auto Err = Result.
add(R);
2342 llvm::errs() <<
"Failed to add header deletion replacement for " 2349 llvm::Regex IncludeRegex = llvm::Regex(CppIncludeRegexPattern);
2351 for (
const auto &R : HeaderInsertions) {
2352 auto IncludeDirective = R.getReplacementText();
2353 bool Matched = IncludeRegex.match(IncludeDirective, &Matches);
2354 assert(Matched &&
"Header insertion replacement must have replacement text " 2357 auto IncludeName = Matches[2];
2359 Includes.
insert(IncludeName.trim(
"\"<>"), IncludeName.startswith(
"<"));
2361 auto Err = Result.
add(*Replace);
2363 llvm::consumeError(std::move(Err));
2364 unsigned NewOffset =
2383 std::vector<tooling::Range> Ranges,
2385 return cleanup(Style, Code, Ranges, FileName);
2389 fixCppIncludeInsertions(Code, Replaces, Style);
2393 namespace internal {
2394 std::pair<tooling::Replacements, unsigned>
2397 unsigned NextStartColumn,
unsigned LastStartColumn, StringRef FileName,
2400 if (Expanded.DisableFormat)
2404 if (Expanded.Language == FormatStyle::LK_JavaScript &&
isMpegTS(Code))
2407 typedef std::function<std::pair<tooling::Replacements, unsigned>(
2412 if (Style.Language == FormatStyle::LK_Cpp) {
2413 if (Style.FixNamespaceComments)
2418 if (Style.SortUsingDeclarations)
2424 if (Style.Language == FormatStyle::LK_JavaScript &&
2425 Style.JavaScriptQuotes != FormatStyle::JSQS_Leave)
2427 return JavaScriptRequoter(Env, Expanded).process();
2431 return Formatter(Env, Expanded, Status).process();
2435 std::make_unique<Environment>(Code, FileName, Ranges, FirstStartColumn,
2436 NextStartColumn, LastStartColumn);
2439 unsigned Penalty = 0;
2440 for (
size_t I = 0, E = Passes.size(); I < E; ++I) {
2441 std::pair<tooling::Replacements, unsigned> PassFixes = Passes[I](*Env);
2443 CurrentCode ? StringRef(*CurrentCode) : Code, PassFixes.first);
2445 Fixes = Fixes.
merge(PassFixes.first);
2446 Penalty += PassFixes.second;
2448 CurrentCode = std::move(*NewCode);
2449 Env = std::make_unique<Environment>(
2450 *CurrentCode, FileName,
2452 FirstStartColumn, NextStartColumn, LastStartColumn);
2457 return {Fixes, Penalty};
2468 0, FileName, Status)
2474 StringRef FileName) {
2476 if (Style.Language != FormatStyle::LK_Cpp)
2478 return Cleaner(
Environment(Code, FileName, Ranges), Style).process().first;
2483 StringRef FileName,
bool *IncompleteFormat) {
2485 auto Result =
reformat(Style, Code, Ranges, FileName, &Status);
2487 *IncompleteFormat =
true;
2494 StringRef FileName) {
2503 StringRef FileName) {
2512 FormatStyle::LanguageStandard LexingStd = Style.Standard;
2513 if (LexingStd == FormatStyle::LS_Auto)
2514 LexingStd = FormatStyle::LS_Latest;
2515 if (LexingStd == FormatStyle::LS_Latest)
2516 LexingStd = FormatStyle::LS_Cpp20;
2517 LangOpts.CPlusPlus = 1;
2518 LangOpts.CPlusPlus11 = LexingStd >= FormatStyle::LS_Cpp11;
2519 LangOpts.CPlusPlus14 = LexingStd >= FormatStyle::LS_Cpp14;
2520 LangOpts.CPlusPlus17 = LexingStd >= FormatStyle::LS_Cpp17;
2521 LangOpts.CPlusPlus2a = LexingStd >= FormatStyle::LS_Cpp20;
2523 LangOpts.LineComment = 1;
2524 bool AlternativeOperators = Style.isCpp();
2525 LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
2528 LangOpts.MicrosoftExt = 1;
2529 LangOpts.DeclSpecKeyword = 1;
2534 "Coding style, currently supports:\n" 2535 " LLVM, Google, Chromium, Mozilla, WebKit.\n" 2536 "Use -style=file to load style configuration from\n" 2537 ".clang-format file located in one of the parent\n" 2538 "directories of the source file (or current\n" 2539 "directory for stdin).\n" 2540 "Use -style=\"{key: value, ...}\" to set specific\n" 2541 "parameters, e.g.:\n" 2542 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
2545 if (FileName.endswith(
".java"))
2546 return FormatStyle::LK_Java;
2547 if (FileName.endswith_lower(
".js") || FileName.endswith_lower(
".mjs") ||
2548 FileName.endswith_lower(
".ts"))
2549 return FormatStyle::LK_JavaScript;
2550 if (FileName.endswith(
".m") || FileName.endswith(
".mm"))
2551 return FormatStyle::LK_ObjC;
2552 if (FileName.endswith_lower(
".proto") ||
2553 FileName.endswith_lower(
".protodevel"))
2554 return FormatStyle::LK_Proto;
2555 if (FileName.endswith_lower(
".textpb") ||
2556 FileName.endswith_lower(
".pb.txt") ||
2557 FileName.endswith_lower(
".textproto") ||
2558 FileName.endswith_lower(
".asciipb"))
2559 return FormatStyle::LK_TextProto;
2560 if (FileName.endswith_lower(
".td"))
2561 return FormatStyle::LK_TableGen;
2562 if (FileName.endswith_lower(
".cs"))
2563 return FormatStyle::LK_CSharp;
2564 return FormatStyle::LK_Cpp;
2569 if (GuessedLanguage == FormatStyle::LK_Cpp) {
2570 auto Extension = llvm::sys::path::extension(FileName);
2573 if (Extension.empty() || Extension ==
".h") {
2574 auto NonEmptyFileName = FileName.empty() ?
"guess.h" : FileName;
2578 if (Guesser.isObjC())
2579 return FormatStyle::LK_ObjC;
2582 return GuessedLanguage;
2590 StringRef FallbackStyleName,
2592 llvm::vfs::FileSystem *FS) {
2594 FS = llvm::vfs::getRealFileSystem().get();
2602 if (StyleName.startswith(
"{")) {
2609 if (!StyleName.equals_lower(
"file")) {
2618 if (std::error_code EC = FS->makeAbsolute(Path))
2622 FilesToLookFor.push_back(
".clang-format");
2623 FilesToLookFor.push_back(
"_clang-format");
2625 for (StringRef Directory = Path; !Directory.empty();
2626 Directory = llvm::sys::path::parent_path(Directory)) {
2628 auto Status = FS->status(Directory);
2630 Status->getType() != llvm::sys::fs::file_type::directory_file) {
2634 for (
const auto &F : FilesToLookFor) {
2637 llvm::sys::path::append(ConfigFile, F);
2638 LLVM_DEBUG(llvm::dbgs() <<
"Trying " << ConfigFile <<
"...\n");
2640 Status = FS->status(ConfigFile.str());
2643 (Status->getType() == llvm::sys::fs::file_type::regular_file)) {
2644 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Text =
2645 FS->getBufferForFile(ConfigFile.str());
2646 if (std::error_code EC = Text.getError())
2648 if (std::error_code ec =
2650 if (ec == ParseError::Unsuitable) {
2651 if (!UnsuitableConfigFiles.empty())
2652 UnsuitableConfigFiles.append(
", ");
2653 UnsuitableConfigFiles.append(ConfigFile);
2659 LLVM_DEBUG(llvm::dbgs()
2660 <<
"Using configuration file " << ConfigFile <<
"\n");
2665 if (!UnsuitableConfigFiles.empty())
2668 UnsuitableConfigFiles);
2669 return FallbackStyle;
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
Specialize PointerLikeTypeTraits to allow LazyGenerationalUpdatePtr to be placed into a PointerUnion...
Defines the SourceManager interface.
AffectedRangeManager class manages affected ranges in the code.
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
StringRef getBufferData(FileID FID, bool *Invalid=nullptr) const
Return a StringRef to the source buffer data for the specified FileID.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file implements a token annotator, i.e.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Defines the Diagnostic-related interfaces.
Language
The language for the input, used to select and validate the language standard and possible actions...
WhitespaceManager class manages whitespace around tokens and their replacements.
const AnnotatedLine * Line
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
SourceLocation getEnd() const
Encodes a location in the source.
This file contains the declaration of the UnwrappedLineParser, which turns a stream of tokens into Un...
Dataflow Directional Tag Classes.
This file implements a sorter for JavaScript ES6 imports.
This file declares an abstract TokenAnalyzer, and associated helper classes.
bool Add(InterpState &S, CodePtr OpPC)
This file implements an indenter that manages the indentation of continuations.
This file declares UsingDeclarationsSorter, a TokenAnalyzer that sorts consecutive using declarations...
SourceLocation getBegin() const
This class handles loading and caching of source files into memory.
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
SourceLocation getEndLoc() const