clang 24.0.0git
Format.cpp
Go to the documentation of this file.
1//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file implements functions declared in Format.h. This will be
11/// split into separate files as we go.
12///
13//===----------------------------------------------------------------------===//
14
15#include "clang/Format/Format.h"
26#include "llvm/ADT/Sequence.h"
27#include "llvm/ADT/StringSet.h"
28#include "llvm/Support/FileSystem.h"
29#include "llvm/Support/VirtualFileSystem.h"
30#include <functional>
31#include <limits>
32
33#define DEBUG_TYPE "format-formatter"
34
36
37LLVM_YAML_IS_SEQUENCE_VECTOR(FormatStyle::RawStringFormat)
38LLVM_YAML_IS_SEQUENCE_VECTOR(FormatStyle::BinaryOperationBreakRule)
39LLVM_YAML_IS_SEQUENCE_VECTOR(clang::tok::TokenKind)
40
48
49namespace llvm {
50namespace yaml {
51template <>
52struct ScalarEnumerationTraits<FormatStyle::BreakBeforeNoexceptSpecifierStyle> {
53 static void
55 IO.enumCase(Value, "Never", FormatStyle::BBNSS_Never);
56 IO.enumCase(Value, "OnlyWithParen", FormatStyle::BBNSS_OnlyWithParen);
57 IO.enumCase(Value, "Always", FormatStyle::BBNSS_Always);
58 }
59};
60
61template <> struct MappingTraits<FormatStyle::AlignConsecutiveStyle> {
63 IO.enumCase(Value, "None", FormatStyle::AlignConsecutiveStyle{});
64 IO.enumCase(Value, "Consecutive",
66 {/*Enabled=*/true, /*AcrossEmptyLines=*/false,
67 /*AcrossComments=*/false, /*AlignCompound=*/false,
68 /*AlignFunctionDeclarations=*/true,
69 /*AlignFunctionPointers=*/false,
70 /*EnumAssignments=*/true, /*PadOperators=*/true}));
71 IO.enumCase(Value, "AcrossEmptyLines",
73 {/*Enabled=*/true, /*AcrossEmptyLines=*/true,
74 /*AcrossComments=*/false, /*AlignCompound=*/false,
75 /*AlignFunctionDeclarations=*/true,
76 /*AlignFunctionPointers=*/false,
77 /*EnumAssignments=*/true, /*PadOperators=*/true}));
78 IO.enumCase(Value, "AcrossComments",
80 {/*Enabled=*/true, /*AcrossEmptyLines=*/false,
81 /*AcrossComments=*/true, /*AlignCompound=*/false,
82 /*AlignFunctionDeclarations=*/true,
83 /*AlignFunctionPointers=*/false,
84 /*EnumAssignments=*/true, /*PadOperators=*/true}));
85 IO.enumCase(Value, "AcrossEmptyLinesAndComments",
87 {/*Enabled=*/true, /*AcrossEmptyLines=*/true,
88 /*AcrossComments=*/true, /*AlignCompound=*/false,
89 /*AlignFunctionDeclarations=*/true,
90 /*AlignFunctionPointers=*/false,
91 /*EnumAssignments=*/true, /*PadOperators=*/true}));
92
93 // For backward compatibility.
94 IO.enumCase(Value, "true",
96 {/*Enabled=*/true, /*AcrossEmptyLines=*/false,
97 /*AcrossComments=*/false, /*AlignCompound=*/false,
98 /*AlignFunctionDeclarations=*/true,
99 /*AlignFunctionPointers=*/false,
100 /*EnumAssignments=*/true, /*PadOperators=*/true}));
101 IO.enumCase(Value, "false", FormatStyle::AlignConsecutiveStyle{});
102 }
103
105 IO.mapOptional("Enabled", Value.Enabled);
106 IO.mapOptional("AcrossEmptyLines", Value.AcrossEmptyLines);
107 IO.mapOptional("AcrossComments", Value.AcrossComments);
108 IO.mapOptional("AlignCompound", Value.AlignCompound);
109 IO.mapOptional("AlignFunctionDeclarations",
110 Value.AlignFunctionDeclarations);
111 IO.mapOptional("AlignFunctionPointers", Value.AlignFunctionPointers);
112 IO.mapOptional("EnumAssignments", Value.EnumAssignments);
113 IO.mapOptional("PadOperators", Value.PadOperators);
114 }
115};
116
117template <>
118struct MappingTraits<FormatStyle::ShortCaseStatementsAlignmentStyle> {
119 static void mapping(IO &IO,
121 IO.mapOptional("Enabled", Value.Enabled);
122 IO.mapOptional("AcrossEmptyLines", Value.AcrossEmptyLines);
123 IO.mapOptional("AcrossComments", Value.AcrossComments);
124 IO.mapOptional("AlignCaseArrows", Value.AlignCaseArrows);
125 IO.mapOptional("AlignCaseColons", Value.AlignCaseColons);
126 }
127};
128
129template <>
130struct ScalarEnumerationTraits<FormatStyle::AttributeBreakingStyle> {
132 IO.enumCase(Value, "Always", FormatStyle::ABS_Always);
133 IO.enumCase(Value, "Leave", FormatStyle::ABS_Leave);
134 IO.enumCase(Value, "LeaveAll", FormatStyle::ABS_LeaveAll);
135 IO.enumCase(Value, "Never", FormatStyle::ABS_Never);
136 }
137};
138
139template <>
140struct ScalarEnumerationTraits<FormatStyle::ArrayInitializerAlignmentStyle> {
141 static void enumeration(IO &IO,
143 IO.enumCase(Value, "None", FormatStyle::AIAS_None);
144 IO.enumCase(Value, "Left", FormatStyle::AIAS_Left);
145 IO.enumCase(Value, "Right", FormatStyle::AIAS_Right);
146 }
147};
148
149template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
151 IO.enumCase(Value, "All", FormatStyle::BOS_All);
152 IO.enumCase(Value, "true", FormatStyle::BOS_All);
153 IO.enumCase(Value, "None", FormatStyle::BOS_None);
154 IO.enumCase(Value, "false", FormatStyle::BOS_None);
155 IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
156 }
157};
158
159template <> struct ScalarEnumerationTraits<FormatStyle::BinPackArgumentsStyle> {
161 IO.enumCase(Value, "BinPack", FormatStyle::BPAS_BinPack);
162 IO.enumCase(Value, "OnePerLine", FormatStyle::BPAS_OnePerLine);
163 IO.enumCase(Value, "UseBreakAfter", FormatStyle::BPAS_UseBreakAfter);
164
165 // For backward compatibility.
166 IO.enumCase(Value, "true", FormatStyle::BPAS_BinPack);
167 IO.enumCase(Value, "false", FormatStyle::BPAS_OnePerLine);
168 }
169};
170
171template <>
172struct ScalarEnumerationTraits<FormatStyle::BinPackParametersStyle> {
174 IO.enumCase(Value, "BinPack", FormatStyle::BPPS_BinPack);
175 IO.enumCase(Value, "OnePerLine", FormatStyle::BPPS_OnePerLine);
176 IO.enumCase(Value, "AlwaysOnePerLine", FormatStyle::BPPS_AlwaysOnePerLine);
177 IO.enumCase(Value, "UseBreakAfter", FormatStyle::BPPS_UseBreakAfter);
178
179 // For backward compatibility.
180 IO.enumCase(Value, "true", FormatStyle::BPPS_BinPack);
181 IO.enumCase(Value, "false", FormatStyle::BPPS_OnePerLine);
182 }
183};
184
185template <> struct ScalarEnumerationTraits<FormatStyle::BinPackStyle> {
187 IO.enumCase(Value, "Auto", FormatStyle::BPS_Auto);
188 IO.enumCase(Value, "Always", FormatStyle::BPS_Always);
189 IO.enumCase(Value, "Never", FormatStyle::BPS_Never);
190 }
191};
192
193template <>
194struct ScalarEnumerationTraits<FormatStyle::BitFieldColonSpacingStyle> {
195 static void enumeration(IO &IO,
197 IO.enumCase(Value, "Both", FormatStyle::BFCS_Both);
198 IO.enumCase(Value, "None", FormatStyle::BFCS_None);
199 IO.enumCase(Value, "Before", FormatStyle::BFCS_Before);
200 IO.enumCase(Value, "After", FormatStyle::BFCS_After);
201 }
202};
203
204template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
206 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
207 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
208 IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
209 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
210 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
211 IO.enumCase(Value, "Whitesmiths", FormatStyle::BS_Whitesmiths);
212 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
213 IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
214 IO.enumCase(Value, "Custom", FormatStyle::BS_Custom);
215 }
216};
217
218template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
219 static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
220 IO.mapOptional("AfterCaseLabel", Wrapping.AfterCaseLabel);
221 IO.mapOptional("AfterClass", Wrapping.AfterClass);
222 IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
223 IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
224 IO.mapOptional("AfterExportBlock", Wrapping.AfterExportBlock);
225 IO.mapOptional("AfterExternBlock", Wrapping.AfterExternBlock);
226 IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
227 IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
228 IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
229 IO.mapOptional("AfterRequiresExpression", Wrapping.AfterRequiresExpression);
230 IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
231 IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
232 IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
233 IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
234 IO.mapOptional("BeforeLambdaBody", Wrapping.BeforeLambdaBody);
235 IO.mapOptional("BeforeWhile", Wrapping.BeforeWhile);
236 IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
237 IO.mapOptional("SplitEmptyFunction", Wrapping.SplitEmptyFunction);
238 IO.mapOptional("SplitEmptyRecord", Wrapping.SplitEmptyRecord);
239 IO.mapOptional("SplitEmptyNamespace", Wrapping.SplitEmptyNamespace);
240 }
241};
242
243template <> struct ScalarEnumerationTraits<BracketAlignmentStyle> {
245 IO.enumCase(Value, "Align", BAS_Align);
246 IO.enumCase(Value, "DontAlign", BAS_DontAlign);
247
248 // For backward compatibility.
249 IO.enumCase(Value, "true", BAS_Align);
250 IO.enumCase(Value, "false", BAS_DontAlign);
251 IO.enumCase(Value, "AlwaysBreak", BAS_AlwaysBreak);
252 IO.enumCase(Value, "BlockIndent", BAS_BlockIndent);
253 }
254};
255
256template <>
257struct ScalarEnumerationTraits<
258 FormatStyle::BraceWrappingAfterControlStatementStyle> {
259 static void
262 IO.enumCase(Value, "Never", FormatStyle::BWACS_Never);
263 IO.enumCase(Value, "MultiLine", FormatStyle::BWACS_MultiLine);
264 IO.enumCase(Value, "Always", FormatStyle::BWACS_Always);
265
266 // For backward compatibility.
267 IO.enumCase(Value, "false", FormatStyle::BWACS_Never);
268 IO.enumCase(Value, "true", FormatStyle::BWACS_Always);
269 }
270};
271
272template <>
273struct ScalarEnumerationTraits<
274 FormatStyle::BreakBeforeConceptDeclarationsStyle> {
275 static void
277 IO.enumCase(Value, "Never", FormatStyle::BBCDS_Never);
278 IO.enumCase(Value, "Allowed", FormatStyle::BBCDS_Allowed);
279 IO.enumCase(Value, "Always", FormatStyle::BBCDS_Always);
280
281 // For backward compatibility.
282 IO.enumCase(Value, "true", FormatStyle::BBCDS_Always);
283 IO.enumCase(Value, "false", FormatStyle::BBCDS_Allowed);
284 }
285};
286
287template <>
288struct ScalarEnumerationTraits<FormatStyle::BreakBeforeInlineASMColonStyle> {
289 static void enumeration(IO &IO,
291 IO.enumCase(Value, "Never", FormatStyle::BBIAS_Never);
292 IO.enumCase(Value, "OnlyMultiline", FormatStyle::BBIAS_OnlyMultiline);
293 IO.enumCase(Value, "Always", FormatStyle::BBIAS_Always);
294 }
295};
296
297template <>
298struct ScalarEnumerationTraits<FormatStyle::BreakBinaryOperationsStyle> {
299 static void enumeration(IO &IO,
301 IO.enumCase(Value, "Never", FormatStyle::BBO_Never);
302 IO.enumCase(Value, "OnePerLine", FormatStyle::BBO_OnePerLine);
303 IO.enumCase(Value, "RespectPrecedence", FormatStyle::BBO_RespectPrecedence);
304 }
305};
306
307template <> struct ScalarTraits<clang::tok::TokenKind> {
308 static void output(const clang::tok::TokenKind &Value, void *,
309 llvm::raw_ostream &Out) {
310 if (const char *Spelling = clang::tok::getPunctuatorSpelling(Value))
311 Out << Spelling;
312 else
314 }
315
316 static StringRef input(StringRef Scalar, void *,
318 // Map operator spelling strings to tok::TokenKind.
319#define PUNCTUATOR(Name, Spelling) \
320 if (Scalar == Spelling) { \
321 Value = clang::tok::Name; \
322 return {}; \
323 }
324#include "clang/Basic/TokenKinds.def"
325 return "unknown operator";
326 }
327
328 static QuotingType mustQuote(StringRef) { return QuotingType::None; }
329};
330
331template <> struct MappingTraits<FormatStyle::BinaryOperationBreakRule> {
333 IO.mapOptional("Operators", Value.Operators);
334 // Default to OnePerLine since a per-operator rule with Never is a no-op.
335 if (!IO.outputting())
337 IO.mapOptional("Style", Value.Style);
338 IO.mapOptional("MinChainLength", Value.MinChainLength);
339 }
340};
341
342template <> struct MappingTraits<FormatStyle::BreakBinaryOperationsOptions> {
343 static void enumInput(IO &IO,
345 IO.enumCase(Value, "Never",
348 IO.enumCase(Value, "OnePerLine",
351 IO.enumCase(Value, "RespectPrecedence",
354 }
355
356 static void mapping(IO &IO,
358 IO.mapOptional("Default", Value.Default);
359 IO.mapOptional("PerOperator", Value.PerOperator);
360 }
361};
362
363template <>
364struct ScalarEnumerationTraits<FormatStyle::BreakConstructorInitializersStyle> {
365 static void
367 IO.enumCase(Value, "BeforeColon", FormatStyle::BCIS_BeforeColon);
368 IO.enumCase(Value, "BeforeComma", FormatStyle::BCIS_BeforeComma);
369 IO.enumCase(Value, "AfterColon", FormatStyle::BCIS_AfterColon);
370 IO.enumCase(Value, "AfterComma", FormatStyle::BCIS_AfterComma);
371 }
372};
373
374template <>
375struct ScalarEnumerationTraits<FormatStyle::BreakInheritanceListStyle> {
376 static void enumeration(IO &IO,
378 IO.enumCase(Value, "BeforeColon", FormatStyle::BILS_BeforeColon);
379 IO.enumCase(Value, "BeforeComma", FormatStyle::BILS_BeforeComma);
380 IO.enumCase(Value, "AfterColon", FormatStyle::BILS_AfterColon);
381 IO.enumCase(Value, "AfterComma", FormatStyle::BILS_AfterComma);
382 }
383};
384
385template <>
386struct ScalarEnumerationTraits<FormatStyle::BreakTemplateDeclarationsStyle> {
387 static void enumeration(IO &IO,
389 IO.enumCase(Value, "Leave", FormatStyle::BTDS_Leave);
390 IO.enumCase(Value, "No", FormatStyle::BTDS_No);
391 IO.enumCase(Value, "MultiLine", FormatStyle::BTDS_MultiLine);
392 IO.enumCase(Value, "Yes", FormatStyle::BTDS_Yes);
393
394 // For backward compatibility.
395 IO.enumCase(Value, "false", FormatStyle::BTDS_MultiLine);
396 IO.enumCase(Value, "true", FormatStyle::BTDS_Yes);
397 }
398};
399
400template <> struct ScalarEnumerationTraits<FormatStyle::BracedListStyle> {
402 IO.enumCase(Value, "Block", FormatStyle::BLS_Block);
403 IO.enumCase(Value, "FunctionCall", FormatStyle::BLS_FunctionCall);
404 IO.enumCase(Value, "AlignFirstComment", FormatStyle::BLS_AlignFirstComment);
405
406 // For backward compatibility.
407 IO.enumCase(Value, "false", FormatStyle::BLS_Block);
408 IO.enumCase(Value, "true", FormatStyle::BLS_AlignFirstComment);
409 }
410};
411
412template <> struct ScalarEnumerationTraits<FormatStyle::DAGArgStyle> {
414 IO.enumCase(Value, "DontBreak", FormatStyle::DAS_DontBreak);
415 IO.enumCase(Value, "BreakElements", FormatStyle::DAS_BreakElements);
416 IO.enumCase(Value, "BreakAll", FormatStyle::DAS_BreakAll);
417 }
418};
419
420template <>
421struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
422 static void
424 IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
425 IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
426 IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
427
428 // For backward compatibility.
429 IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
430 IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
431 }
432};
433
434template <>
435struct ScalarEnumerationTraits<FormatStyle::EscapedNewlineAlignmentStyle> {
436 static void enumeration(IO &IO,
438 IO.enumCase(Value, "DontAlign", FormatStyle::ENAS_DontAlign);
439 IO.enumCase(Value, "Left", FormatStyle::ENAS_Left);
440 IO.enumCase(Value, "LeftWithLastLine", FormatStyle::ENAS_LeftWithLastLine);
441 IO.enumCase(Value, "Right", FormatStyle::ENAS_Right);
442
443 // For backward compatibility.
444 IO.enumCase(Value, "true", FormatStyle::ENAS_Left);
445 IO.enumCase(Value, "false", FormatStyle::ENAS_Right);
446 }
447};
448
449template <>
450struct ScalarEnumerationTraits<FormatStyle::EmptyLineAfterAccessModifierStyle> {
451 static void
453 IO.enumCase(Value, "Never", FormatStyle::ELAAMS_Never);
454 IO.enumCase(Value, "Leave", FormatStyle::ELAAMS_Leave);
455 IO.enumCase(Value, "Always", FormatStyle::ELAAMS_Always);
456 }
457};
458
459template <>
460struct ScalarEnumerationTraits<
461 FormatStyle::EmptyLineBeforeAccessModifierStyle> {
462 static void
464 IO.enumCase(Value, "Never", FormatStyle::ELBAMS_Never);
465 IO.enumCase(Value, "Leave", FormatStyle::ELBAMS_Leave);
466 IO.enumCase(Value, "LogicalBlock", FormatStyle::ELBAMS_LogicalBlock);
467 IO.enumCase(Value, "Always", FormatStyle::ELBAMS_Always);
468 }
469};
470
471template <>
472struct ScalarEnumerationTraits<FormatStyle::EnumTrailingCommaStyle> {
474 IO.enumCase(Value, "Leave", FormatStyle::ETC_Leave);
475 IO.enumCase(Value, "Insert", FormatStyle::ETC_Insert);
476 IO.enumCase(Value, "Remove", FormatStyle::ETC_Remove);
477 }
478};
479
480template <>
481struct ScalarEnumerationTraits<FormatStyle::IndentAccessModifierStyle> {
482 static void enumeration(IO &IO,
484 IO.enumCase(Value, "Never", FormatStyle::IAMS_Never);
485 IO.enumCase(Value, "Always", FormatStyle::IAMS_Always);
486 IO.enumCase(Value, "AfterFirstAccessModifier",
488
489 // For backward compatibility.
490 IO.enumCase(Value, "false", FormatStyle::IAMS_Never);
491 IO.enumCase(Value, "true", FormatStyle::IAMS_Always);
492 }
493};
494
495template <>
496struct ScalarEnumerationTraits<FormatStyle::IndentExternBlockStyle> {
498 IO.enumCase(Value, "AfterExternBlock", FormatStyle::IEBS_AfterExternBlock);
499 IO.enumCase(Value, "Indent", FormatStyle::IEBS_Indent);
500 IO.enumCase(Value, "NoIndent", FormatStyle::IEBS_NoIndent);
501 IO.enumCase(Value, "true", FormatStyle::IEBS_Indent);
502 IO.enumCase(Value, "false", FormatStyle::IEBS_NoIndent);
503 }
504};
505
506template <> struct MappingTraits<FormatStyle::IntegerLiteralSeparatorStyle> {
508 IO.mapOptional("Binary", Base.Binary);
509 IO.mapOptional("BinaryMinDigitsInsert", Base.BinaryMinDigitsInsert);
510 IO.mapOptional("BinaryMaxDigitsRemove", Base.BinaryMaxDigitsRemove);
511 IO.mapOptional("Decimal", Base.Decimal);
512 IO.mapOptional("DecimalMinDigitsInsert", Base.DecimalMinDigitsInsert);
513 IO.mapOptional("DecimalMaxDigitsRemove", Base.DecimalMaxDigitsRemove);
514 IO.mapOptional("Hex", Base.Hex);
515 IO.mapOptional("HexMinDigitsInsert", Base.HexMinDigitsInsert);
516 IO.mapOptional("HexMaxDigitsRemove", Base.HexMaxDigitsRemove);
517
518 // For backward compatibility.
519 IO.mapOptional("BinaryMinDigits", Base.BinaryMinDigitsInsert);
520 IO.mapOptional("DecimalMinDigits", Base.DecimalMinDigitsInsert);
521 IO.mapOptional("HexMinDigits", Base.HexMinDigitsInsert);
522 }
523};
524
525template <> struct ScalarEnumerationTraits<FormatStyle::JavaScriptQuoteStyle> {
527 IO.enumCase(Value, "Leave", FormatStyle::JSQS_Leave);
528 IO.enumCase(Value, "Single", FormatStyle::JSQS_Single);
529 IO.enumCase(Value, "Double", FormatStyle::JSQS_Double);
530 }
531};
532
533template <> struct MappingTraits<FormatStyle::KeepEmptyLinesStyle> {
535 IO.mapOptional("AtEndOfBlock", Value.AtEndOfBlock);
536 IO.mapOptional("AtEndOfFile", Value.AtEndOfFile);
537 IO.mapOptional("AtStartOfBlock", Value.AtStartOfBlock);
538 IO.mapOptional("AtStartOfFile", Value.AtStartOfFile);
539 }
540};
541
542template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
544 IO.enumCase(Value, "C", FormatStyle::LK_C);
545 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
546 IO.enumCase(Value, "Java", FormatStyle::LK_Java);
547 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
548 IO.enumCase(Value, "ObjC", FormatStyle::LK_ObjC);
549 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
550 IO.enumCase(Value, "TableGen", FormatStyle::LK_TableGen);
551 IO.enumCase(Value, "TextProto", FormatStyle::LK_TextProto);
552 IO.enumCase(Value, "CSharp", FormatStyle::LK_CSharp);
553 IO.enumCase(Value, "Json", FormatStyle::LK_Json);
554 IO.enumCase(Value, "Verilog", FormatStyle::LK_Verilog);
555 }
556};
557
558template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
560 IO.enumCase(Value, "c++03", FormatStyle::LS_Cpp03);
561 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03); // Legacy alias
562 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03); // Legacy alias
563
564 IO.enumCase(Value, "c++11", FormatStyle::LS_Cpp11);
565 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11); // Legacy alias
566
567 IO.enumCase(Value, "c++14", FormatStyle::LS_Cpp14);
568 IO.enumCase(Value, "c++17", FormatStyle::LS_Cpp17);
569 IO.enumCase(Value, "c++20", FormatStyle::LS_Cpp20);
570 IO.enumCase(Value, "c++23", FormatStyle::LS_Cpp23);
571 IO.enumCase(Value, "c++26", FormatStyle::LS_Cpp26);
572
573 IO.enumCase(Value, "Latest", FormatStyle::LS_Latest);
574 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Latest); // Legacy alias
575 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
576 }
577};
578
579template <>
580struct ScalarEnumerationTraits<FormatStyle::LambdaBodyIndentationKind> {
581 static void enumeration(IO &IO,
583 IO.enumCase(Value, "Signature", FormatStyle::LBI_Signature);
584 IO.enumCase(Value, "OuterScope", FormatStyle::LBI_OuterScope);
585 }
586};
587
588template <> struct ScalarEnumerationTraits<FormatStyle::LineEndingStyle> {
590 IO.enumCase(Value, "LF", FormatStyle::LE_LF);
591 IO.enumCase(Value, "CRLF", FormatStyle::LE_CRLF);
592 IO.enumCase(Value, "DeriveLF", FormatStyle::LE_DeriveLF);
593 IO.enumCase(Value, "DeriveCRLF", FormatStyle::LE_DeriveCRLF);
594 }
595};
596
597template <>
598struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
599 static void enumeration(IO &IO,
601 IO.enumCase(Value, "None", FormatStyle::NI_None);
602 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
603 IO.enumCase(Value, "All", FormatStyle::NI_All);
604 }
605};
606
607template <>
608struct ScalarEnumerationTraits<FormatStyle::NumericLiteralComponentStyle> {
609 static void enumeration(IO &IO,
611 IO.enumCase(Value, "Leave", FormatStyle::NLCS_Leave);
612 IO.enumCase(Value, "Upper", FormatStyle::NLCS_Upper);
613 IO.enumCase(Value, "Lower", FormatStyle::NLCS_Lower);
614 }
615};
616
617template <> struct MappingTraits<FormatStyle::NumericLiteralCaseStyle> {
619 IO.mapOptional("ExponentLetter", Value.ExponentLetter);
620 IO.mapOptional("HexDigit", Value.HexDigit);
621 IO.mapOptional("Prefix", Value.Prefix);
622 IO.mapOptional("Suffix", Value.Suffix);
623 }
624};
625
626template <> struct ScalarEnumerationTraits<FormatStyle::OperandAlignmentStyle> {
628 IO.enumCase(Value, "DontAlign", FormatStyle::OAS_DontAlign);
629 IO.enumCase(Value, "Align", FormatStyle::OAS_Align);
630 IO.enumCase(Value, "AlignAfterOperator",
632
633 // For backward compatibility.
634 IO.enumCase(Value, "true", FormatStyle::OAS_Align);
635 IO.enumCase(Value, "false", FormatStyle::OAS_DontAlign);
636 }
637};
638
639template <> struct MappingTraits<FormatStyle::PackParametersStyle> {
641 IO.mapOptional("BinPack", Value.BinPack);
642 IO.mapOptional("BreakAfter", Value.BreakAfter);
643 }
644};
645
646template <>
647struct ScalarEnumerationTraits<FormatStyle::PackConstructorInitializersStyle> {
648 static void
650 IO.enumCase(Value, "Never", FormatStyle::PCIS_Never);
651 IO.enumCase(Value, "BinPack", FormatStyle::PCIS_BinPack);
652 IO.enumCase(Value, "CurrentLine", FormatStyle::PCIS_CurrentLine);
653 IO.enumCase(Value, "NextLine", FormatStyle::PCIS_NextLine);
654 IO.enumCase(Value, "NextLineOnly", FormatStyle::PCIS_NextLineOnly);
655 }
656};
657
658template <> struct MappingTraits<FormatStyle::PackArgumentsStyle> {
660 IO.mapOptional("BinPack", Value.BinPack);
661 IO.mapOptional("BreakAfter", Value.BreakAfter);
662 }
663};
664
665template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
667 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
668 IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
669 IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
670
671 // For backward compatibility.
672 IO.enumCase(Value, "true", FormatStyle::PAS_Left);
673 IO.enumCase(Value, "false", FormatStyle::PAS_Right);
674 }
675};
676
677template <>
678struct ScalarEnumerationTraits<FormatStyle::PPDirectiveIndentStyle> {
680 IO.enumCase(Value, "None", FormatStyle::PPDIS_None);
681 IO.enumCase(Value, "AfterHash", FormatStyle::PPDIS_AfterHash);
682 IO.enumCase(Value, "BeforeHash", FormatStyle::PPDIS_BeforeHash);
683 IO.enumCase(Value, "Leave", FormatStyle::PPDIS_Leave);
684 }
685};
686
687template <>
688struct ScalarEnumerationTraits<FormatStyle::QualifierAlignmentStyle> {
690 IO.enumCase(Value, "Leave", FormatStyle::QAS_Leave);
691 IO.enumCase(Value, "Left", FormatStyle::QAS_Left);
692 IO.enumCase(Value, "Right", FormatStyle::QAS_Right);
693 IO.enumCase(Value, "Custom", FormatStyle::QAS_Custom);
694 }
695};
696
697template <> struct MappingTraits<FormatStyle::RawStringFormat> {
698 static void mapping(IO &IO, FormatStyle::RawStringFormat &Format) {
699 IO.mapOptional("Language", Format.Language);
700 IO.mapOptional("Delimiters", Format.Delimiters);
701 IO.mapOptional("EnclosingFunctions", Format.EnclosingFunctions);
702 IO.mapOptional("CanonicalDelimiter", Format.CanonicalDelimiter);
703 IO.mapOptional("BasedOnStyle", Format.BasedOnStyle);
704 }
705};
706
707template <> struct ScalarEnumerationTraits<FormatStyle::ReflowCommentsStyle> {
709 IO.enumCase(Value, "Never", FormatStyle::RCS_Never);
710 IO.enumCase(Value, "IndentOnly", FormatStyle::RCS_IndentOnly);
711 IO.enumCase(Value, "Always", FormatStyle::RCS_Always);
712 // For backward compatibility:
713 IO.enumCase(Value, "false", FormatStyle::RCS_Never);
714 IO.enumCase(Value, "true", FormatStyle::RCS_Always);
715 }
716};
717
718template <>
719struct ScalarEnumerationTraits<FormatStyle::ReferenceAlignmentStyle> {
721 IO.enumCase(Value, "Pointer", FormatStyle::RAS_Pointer);
722 IO.enumCase(Value, "Middle", FormatStyle::RAS_Middle);
723 IO.enumCase(Value, "Left", FormatStyle::RAS_Left);
724 IO.enumCase(Value, "Right", FormatStyle::RAS_Right);
725 }
726};
727
728template <>
729struct ScalarEnumerationTraits<FormatStyle::RemoveParenthesesStyle> {
731 IO.enumCase(Value, "Leave", FormatStyle::RPS_Leave);
732 IO.enumCase(Value, "MultipleParentheses",
734 IO.enumCase(Value, "ReturnStatement", FormatStyle::RPS_ReturnStatement);
735 }
736};
737
738template <>
739struct ScalarEnumerationTraits<FormatStyle::RequiresClausePositionStyle> {
740 static void enumeration(IO &IO,
742 IO.enumCase(Value, "OwnLine", FormatStyle::RCPS_OwnLine);
743 IO.enumCase(Value, "OwnLineWithBrace", FormatStyle::RCPS_OwnLineWithBrace);
744 IO.enumCase(Value, "WithPreceding", FormatStyle::RCPS_WithPreceding);
745 IO.enumCase(Value, "WithFollowing", FormatStyle::RCPS_WithFollowing);
746 IO.enumCase(Value, "SingleLine", FormatStyle::RCPS_SingleLine);
747 }
748};
749
750template <>
751struct ScalarEnumerationTraits<FormatStyle::RequiresExpressionIndentationKind> {
752 static void
754 IO.enumCase(Value, "Keyword", FormatStyle::REI_Keyword);
755 IO.enumCase(Value, "OuterScope", FormatStyle::REI_OuterScope);
756 }
757};
758
759template <>
760struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
762 IO.enumCase(Value, "None", FormatStyle::RTBS_None);
763 IO.enumCase(Value, "Automatic", FormatStyle::RTBS_Automatic);
764 IO.enumCase(Value, "ExceptShortType", FormatStyle::RTBS_ExceptShortType);
765 IO.enumCase(Value, "All", FormatStyle::RTBS_All);
766 IO.enumCase(Value, "TopLevel", FormatStyle::RTBS_TopLevel);
767 IO.enumCase(Value, "TopLevelDefinitions",
769 IO.enumCase(Value, "AllDefinitions", FormatStyle::RTBS_AllDefinitions);
770 }
771};
772
773template <>
774struct ScalarEnumerationTraits<FormatStyle::BreakBeforeReturnTypeStyle> {
775 static void enumeration(IO &IO,
777 IO.enumCase(Value, "None", FormatStyle::BBRTS_None);
778 IO.enumCase(Value, "All", FormatStyle::BBRTS_All);
779 IO.enumCase(Value, "TopLevel", FormatStyle::BBRTS_TopLevel);
780 IO.enumCase(Value, "AllDefinitions", FormatStyle::BBRTS_AllDefinitions);
781 IO.enumCase(Value, "TopLevelDefinitions",
783 }
784};
785
786template <>
787struct ScalarEnumerationTraits<FormatStyle::SeparateDefinitionStyle> {
789 IO.enumCase(Value, "Leave", FormatStyle::SDS_Leave);
790 IO.enumCase(Value, "Always", FormatStyle::SDS_Always);
791 IO.enumCase(Value, "Never", FormatStyle::SDS_Never);
792 }
793};
794
795template <> struct ScalarEnumerationTraits<FormatStyle::ShortBlockStyle> {
797 IO.enumCase(Value, "Never", FormatStyle::SBS_Never);
798 IO.enumCase(Value, "false", FormatStyle::SBS_Never);
799 IO.enumCase(Value, "Always", FormatStyle::SBS_Always);
800 IO.enumCase(Value, "true", FormatStyle::SBS_Always);
801 IO.enumCase(Value, "Empty", FormatStyle::SBS_Empty);
802 }
803};
804
805template <> struct MappingTraits<FormatStyle::ShortFunctionStyle> {
807 IO.enumCase(Value, "None", FormatStyle::ShortFunctionStyle());
808 IO.enumCase(Value, "Empty",
810 IO.enumCase(Value, "Inline",
812 IO.enumCase(Value, "InlineOnly",
814 IO.enumCase(Value, "All", FormatStyle::ShortFunctionStyle::setAll());
815
816 // For backward compatibility.
817 IO.enumCase(Value, "true", FormatStyle::ShortFunctionStyle::setAll());
818 IO.enumCase(Value, "false", FormatStyle::ShortFunctionStyle());
819 }
820
822 IO.mapOptional("Empty", Value.Empty);
823 IO.mapOptional("Inline", Value.Inline);
824 IO.mapOptional("Other", Value.Other);
825 }
826};
827
828template <> struct ScalarEnumerationTraits<FormatStyle::ShortIfStyle> {
830 IO.enumCase(Value, "Never", FormatStyle::SIS_Never);
831 IO.enumCase(Value, "WithoutElse", FormatStyle::SIS_WithoutElse);
832 IO.enumCase(Value, "OnlyFirstIf", FormatStyle::SIS_OnlyFirstIf);
833 IO.enumCase(Value, "AllIfsAndElse", FormatStyle::SIS_AllIfsAndElse);
834
835 // For backward compatibility.
836 IO.enumCase(Value, "Always", FormatStyle::SIS_OnlyFirstIf);
837 IO.enumCase(Value, "false", FormatStyle::SIS_Never);
838 IO.enumCase(Value, "true", FormatStyle::SIS_WithoutElse);
839 }
840};
841
842template <> struct ScalarEnumerationTraits<FormatStyle::ShortLambdaStyle> {
844 IO.enumCase(Value, "None", FormatStyle::SLS_None);
845 IO.enumCase(Value, "false", FormatStyle::SLS_None);
846 IO.enumCase(Value, "Empty", FormatStyle::SLS_Empty);
847 IO.enumCase(Value, "Inline", FormatStyle::SLS_Inline);
848 IO.enumCase(Value, "All", FormatStyle::SLS_All);
849 IO.enumCase(Value, "true", FormatStyle::SLS_All);
850 }
851};
852
853template <> struct ScalarEnumerationTraits<FormatStyle::ShortRecordStyle> {
855 IO.enumCase(Value, "Never", FormatStyle::SRS_Never);
856 IO.enumCase(Value, "EmptyAndAttached", FormatStyle::SRS_EmptyAndAttached);
857 IO.enumCase(Value, "Empty", FormatStyle::SRS_Empty);
858 IO.enumCase(Value, "Always", FormatStyle::SRS_Always);
859 }
860};
861
862template <> struct MappingTraits<FormatStyle::SortIncludesOptions> {
864 IO.enumCase(Value, "Never", FormatStyle::SortIncludesOptions{});
865 IO.enumCase(Value, "CaseInsensitive",
866 FormatStyle::SortIncludesOptions{/*Enabled=*/true,
867 /*IgnoreCase=*/true,
868 /*IgnoreExtension=*/false,
869 /*Natural=*/false,
870 /*FilesBeforeFolders=*/false});
871 IO.enumCase(Value, "CaseSensitive",
872 FormatStyle::SortIncludesOptions{/*Enabled=*/true,
873 /*IgnoreCase=*/false,
874 /*IgnoreExtension=*/false,
875 /*Natural=*/false,
876 /*FilesBeforeFolders=*/false});
877 IO.enumCase(Value, "Natural",
878 FormatStyle::SortIncludesOptions{/*Enabled=*/true,
879 /*IgnoreCase=*/false,
880 /*IgnoreExtension=*/false,
881 /*Natural=*/true,
882 /*FilesBeforeFolders=*/false});
883
884 // For backward compatibility.
885 IO.enumCase(Value, "false", FormatStyle::SortIncludesOptions{});
886 IO.enumCase(Value, "true",
887 FormatStyle::SortIncludesOptions{/*Enabled=*/true,
888 /*IgnoreCase=*/false,
889 /*IgnoreExtension=*/false,
890 /*Natural=*/false,
891 /*FilesBeforeFolders=*/false});
892 }
894 IO.mapOptional("Enabled", Value.Enabled);
895 IO.mapOptional("IgnoreCase", Value.IgnoreCase);
896 IO.mapOptional("IgnoreExtension", Value.IgnoreExtension);
897 IO.mapOptional("Natural", Value.Natural);
898 IO.mapOptional("FilesBeforeFolders", Value.FilesBeforeFolders);
899 }
900};
901
902template <>
903struct ScalarEnumerationTraits<FormatStyle::SortJavaStaticImportOptions> {
904 static void enumeration(IO &IO,
906 IO.enumCase(Value, "Before", FormatStyle::SJSIO_Before);
907 IO.enumCase(Value, "After", FormatStyle::SJSIO_After);
908 }
909};
910
911template <>
912struct ScalarEnumerationTraits<FormatStyle::SortUsingDeclarationsOptions> {
913 static void enumeration(IO &IO,
915 IO.enumCase(Value, "Never", FormatStyle::SUD_Never);
916 IO.enumCase(Value, "Lexicographic", FormatStyle::SUD_Lexicographic);
917 IO.enumCase(Value, "LexicographicNumeric",
919
920 // For backward compatibility.
921 IO.enumCase(Value, "false", FormatStyle::SUD_Never);
922 IO.enumCase(Value, "true", FormatStyle::SUD_LexicographicNumeric);
923 }
924};
925
926template <>
927struct ScalarEnumerationTraits<FormatStyle::SpaceAroundPointerQualifiersStyle> {
928 static void
930 IO.enumCase(Value, "Default", FormatStyle::SAPQ_Default);
931 IO.enumCase(Value, "Before", FormatStyle::SAPQ_Before);
932 IO.enumCase(Value, "After", FormatStyle::SAPQ_After);
933 IO.enumCase(Value, "Both", FormatStyle::SAPQ_Both);
934 }
935};
936
937template <> struct MappingTraits<FormatStyle::SpaceBeforeParensCustom> {
938 static void mapping(IO &IO, FormatStyle::SpaceBeforeParensCustom &Spacing) {
939 IO.mapOptional("AfterControlStatements", Spacing.AfterControlStatements);
940 IO.mapOptional("AfterForeachMacros", Spacing.AfterForeachMacros);
941 IO.mapOptional("AfterFunctionDefinitionName",
943 IO.mapOptional("AfterFunctionDeclarationName",
945 IO.mapOptional("AfterIfMacros", Spacing.AfterIfMacros);
946 IO.mapOptional("AfterNot", Spacing.AfterNot);
947 IO.mapOptional("AfterOverloadedOperator", Spacing.AfterOverloadedOperator);
948 IO.mapOptional("AfterPlacementOperator", Spacing.AfterPlacementOperator);
949 IO.mapOptional("AfterRequiresInClause", Spacing.AfterRequiresInClause);
950 IO.mapOptional("AfterRequiresInExpression",
952 IO.mapOptional("BeforeNonEmptyParentheses",
954 }
955};
956
957template <>
958struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensStyle> {
960 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
961 IO.enumCase(Value, "ControlStatements",
963 IO.enumCase(Value, "ControlStatementsExceptControlMacros",
965 IO.enumCase(Value, "NonEmptyParentheses",
967 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
968 IO.enumCase(Value, "Custom", FormatStyle::SBPO_Custom);
969
970 // For backward compatibility.
971 IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
972 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
973 IO.enumCase(Value, "ControlStatementsExceptForEachMacros",
975 }
976};
977
978template <>
979struct ScalarEnumerationTraits<FormatStyle::SpaceInEmptyBracesStyle> {
981 IO.enumCase(Value, "Always", FormatStyle::SIEB_Always);
982 IO.enumCase(Value, "Block", FormatStyle::SIEB_Block);
983 IO.enumCase(Value, "Never", FormatStyle::SIEB_Never);
984 }
985};
986
987template <> struct ScalarEnumerationTraits<FormatStyle::SpacesInAnglesStyle> {
989 IO.enumCase(Value, "Never", FormatStyle::SIAS_Never);
990 IO.enumCase(Value, "Always", FormatStyle::SIAS_Always);
991 IO.enumCase(Value, "Leave", FormatStyle::SIAS_Leave);
992
993 // For backward compatibility.
994 IO.enumCase(Value, "false", FormatStyle::SIAS_Never);
995 IO.enumCase(Value, "true", FormatStyle::SIAS_Always);
996 }
997};
998
999template <>
1000struct ScalarEnumerationTraits<FormatStyle::SpacesInBlockCommentsStyle> {
1001 static void enumeration(IO &IO,
1003 IO.enumCase(Value, "Never", FormatStyle::SIBCS_Never);
1004 IO.enumCase(Value, "Always", FormatStyle::SIBCS_Always);
1005 IO.enumCase(Value, "Leave", FormatStyle::SIBCS_Leave);
1006 }
1007};
1008
1009template <> struct MappingTraits<FormatStyle::SpacesInLineComment> {
1010 static void mapping(IO &IO, FormatStyle::SpacesInLineComment &Space) {
1011 // Transform the maximum to signed, to parse "-1" correctly
1012 int signedMaximum = static_cast<int>(Space.Maximum);
1013 IO.mapOptional("Minimum", Space.Minimum);
1014 IO.mapOptional("Maximum", signedMaximum);
1015 Space.Maximum = static_cast<unsigned>(signedMaximum);
1016
1017 if (Space.Maximum < std::numeric_limits<unsigned>::max())
1018 Space.Minimum = std::min(Space.Minimum, Space.Maximum);
1019 }
1020};
1021
1022template <> struct MappingTraits<FormatStyle::SpacesInParensCustom> {
1023 static void mapping(IO &IO, FormatStyle::SpacesInParensCustom &Spaces) {
1024 IO.mapOptional("ExceptDoubleParentheses", Spaces.ExceptDoubleParentheses);
1025 IO.mapOptional("InCStyleCasts", Spaces.InCStyleCasts);
1026 IO.mapOptional("InConditionalStatements", Spaces.InConditionalStatements);
1027 IO.mapOptional("InEmptyParentheses", Spaces.InEmptyParentheses);
1028 IO.mapOptional("Other", Spaces.Other);
1029 }
1030};
1031
1032template <> struct ScalarEnumerationTraits<FormatStyle::SpacesInParensStyle> {
1034 IO.enumCase(Value, "Never", FormatStyle::SIPO_Never);
1035 IO.enumCase(Value, "Custom", FormatStyle::SIPO_Custom);
1036 }
1037};
1038
1039template <> struct ScalarEnumerationTraits<FormatStyle::TrailingCommaStyle> {
1041 IO.enumCase(Value, "None", FormatStyle::TCS_None);
1042 IO.enumCase(Value, "Wrapped", FormatStyle::TCS_Wrapped);
1043 }
1044};
1045
1046template <>
1047struct ScalarEnumerationTraits<FormatStyle::TrailingCommentsAlignmentKinds> {
1048 static void enumeration(IO &IO,
1050 IO.enumCase(Value, "Leave", FormatStyle::TCAS_Leave);
1051 IO.enumCase(Value, "Always", FormatStyle::TCAS_Always);
1052 IO.enumCase(Value, "Never", FormatStyle::TCAS_Never);
1053 }
1054};
1055
1056template <> struct MappingTraits<FormatStyle::TrailingCommentsAlignmentStyle> {
1057 static void enumInput(IO &IO,
1059 IO.enumCase(Value, "Leave",
1061 {FormatStyle::TCAS_Leave, 0, true}));
1062
1063 IO.enumCase(Value, "Always",
1065 {FormatStyle::TCAS_Always, 0, true}));
1066
1067 IO.enumCase(Value, "Never",
1069 {FormatStyle::TCAS_Never, 0, true}));
1070
1071 // For backwards compatibility
1072 IO.enumCase(Value, "true",
1074 {FormatStyle::TCAS_Always, 0, true}));
1075 IO.enumCase(Value, "false",
1077 {FormatStyle::TCAS_Never, 0, true}));
1078 }
1079
1080 static void mapping(IO &IO,
1082 IO.mapOptional("AlignPPAndNotPP", Value.AlignPPAndNotPP);
1083 IO.mapOptional("Kind", Value.Kind);
1084 IO.mapOptional("OverEmptyLines", Value.OverEmptyLines);
1085 }
1086};
1087
1088template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
1090 IO.enumCase(Value, "Never", FormatStyle::UT_Never);
1091 IO.enumCase(Value, "false", FormatStyle::UT_Never);
1092 IO.enumCase(Value, "Always", FormatStyle::UT_Always);
1093 IO.enumCase(Value, "true", FormatStyle::UT_Always);
1094 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
1095 IO.enumCase(Value, "ForContinuationAndIndentation",
1097 IO.enumCase(Value, "AlignWithSpaces", FormatStyle::UT_AlignWithSpaces);
1098 }
1099};
1100
1101template <>
1102struct ScalarEnumerationTraits<
1103 FormatStyle::WrapNamespaceBodyWithEmptyLinesStyle> {
1104 static void
1107 IO.enumCase(Value, "Never", FormatStyle::WNBWELS_Never);
1108 IO.enumCase(Value, "Always", FormatStyle::WNBWELS_Always);
1109 IO.enumCase(Value, "Leave", FormatStyle::WNBWELS_Leave);
1110 }
1111};
1112
1113template <> struct MappingTraits<FormatStyle> {
1114 static void mapping(IO &IO, FormatStyle &Style) {
1115 // When reading, read the language first, we need it for getPredefinedStyle.
1116 IO.mapOptional("Language", Style.Language);
1117
1118 StringRef BasedOnStyle;
1119 if (IO.outputting()) {
1120 StringRef Styles[] = {"LLVM", "Google", "Chromium", "Mozilla",
1121 "WebKit", "GNU", "Microsoft", "clang-format"};
1122 for (StringRef StyleName : Styles) {
1123 FormatStyle PredefinedStyle;
1124 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
1125 Style == PredefinedStyle) {
1126 BasedOnStyle = StyleName;
1127 break;
1128 }
1129 }
1130 } else {
1131 IO.mapOptional("BasedOnStyle", BasedOnStyle);
1132 if (!BasedOnStyle.empty()) {
1133 FormatStyle::LanguageKind OldLanguage = Style.Language;
1134 FormatStyle::LanguageKind Language =
1135 ((FormatStyle *)IO.getContext())->Language;
1136 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
1137 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
1138 return;
1139 }
1140 Style.Language = OldLanguage;
1141 }
1142 }
1143
1144 // Initialize some variables used in the parsing. The using logic is at the
1145 // end.
1146
1147 // For backward compatibility:
1148 // The default value of ConstructorInitializerAllOnOneLineOrOnePerLine was
1149 // false unless BasedOnStyle was Google or Chromium whereas that of
1150 // AllowAllConstructorInitializersOnNextLine was always true, so the
1151 // equivalent default value of PackConstructorInitializers is PCIS_NextLine
1152 // for Google/Chromium or PCIS_BinPack otherwise. If the deprecated options
1153 // had a non-default value while PackConstructorInitializers has a default
1154 // value, set the latter to an equivalent non-default value if needed.
1155 const bool IsGoogleOrChromium = BasedOnStyle.equals_insensitive("google") ||
1156 BasedOnStyle.equals_insensitive("chromium");
1157 bool OnCurrentLine = IsGoogleOrChromium;
1158 bool OnNextLine = true;
1159
1160 bool BreakBeforeInheritanceComma = false;
1161 bool BreakConstructorInitializersBeforeComma = false;
1162
1163 bool DeriveLineEnding = true;
1164 bool UseCRLF = false;
1165
1166 bool SpaceInEmptyBlock = false;
1167 bool SpaceInEmptyParentheses = false;
1168 bool SpacesInConditionalStatement = false;
1169 bool SpacesInCStyleCastParentheses = false;
1170 bool SpacesInParentheses = false;
1171
1172 if (IO.outputting()) {
1173 IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
1174 } else {
1175 // For backward compatibility.
1177 if (IsGoogleOrChromium) {
1178 FormatStyle::LanguageKind Language = Style.Language;
1179 if (Language == FormatStyle::LK_None)
1180 Language = ((FormatStyle *)IO.getContext())->Language;
1181 if (Language == FormatStyle::LK_JavaScript)
1182 LocalBAS = BAS_AlwaysBreak;
1183 else if (Language == FormatStyle::LK_Java)
1184 LocalBAS = BAS_DontAlign;
1185 } else if (BasedOnStyle.equals_insensitive("webkit")) {
1186 LocalBAS = BAS_DontAlign;
1187 }
1188 IO.mapOptional("AlignAfterOpenBracket", LocalBAS);
1189
1190 switch (LocalBAS) {
1191 case BAS_DontAlign:
1192 Style.AlignAfterOpenBracket = false;
1193 Style.BreakAfterOpenBracketBracedList = false;
1194 Style.BreakAfterOpenBracketFunction = false;
1195 Style.BreakAfterOpenBracketIf = false;
1196 Style.BreakAfterOpenBracketLoop = false;
1197 Style.BreakAfterOpenBracketSwitch = false;
1198 Style.BreakBeforeCloseBracketBracedList = false;
1199 Style.BreakBeforeCloseBracketFunction = false;
1200 Style.BreakBeforeCloseBracketIf = false;
1201 Style.BreakBeforeCloseBracketLoop = false;
1202 Style.BreakBeforeCloseBracketSwitch = false;
1203 break;
1204 case BAS_BlockIndent:
1205 Style.AlignAfterOpenBracket = true;
1206 Style.BreakAfterOpenBracketBracedList = true;
1207 Style.BreakAfterOpenBracketFunction = true;
1208 Style.BreakAfterOpenBracketIf = true;
1209 Style.BreakAfterOpenBracketLoop = false;
1210 Style.BreakAfterOpenBracketSwitch = false;
1211 Style.BreakBeforeCloseBracketBracedList = true;
1212 Style.BreakBeforeCloseBracketFunction = true;
1213 Style.BreakBeforeCloseBracketIf = true;
1214 Style.BreakBeforeCloseBracketLoop = false;
1215 Style.BreakBeforeCloseBracketSwitch = false;
1216 break;
1217 case BAS_AlwaysBreak:
1218 Style.AlignAfterOpenBracket = true;
1219 Style.BreakAfterOpenBracketBracedList = true;
1220 Style.BreakAfterOpenBracketFunction = true;
1221 Style.BreakAfterOpenBracketIf = true;
1222 Style.BreakAfterOpenBracketLoop = false;
1223 Style.BreakAfterOpenBracketSwitch = false;
1224 Style.BreakBeforeCloseBracketBracedList = false;
1225 Style.BreakBeforeCloseBracketFunction = false;
1226 Style.BreakBeforeCloseBracketIf = false;
1227 Style.BreakBeforeCloseBracketLoop = false;
1228 Style.BreakBeforeCloseBracketSwitch = false;
1229 break;
1230 case BAS_Align:
1231 Style.AlignAfterOpenBracket = true;
1232 Style.BreakAfterOpenBracketBracedList = false;
1233 Style.BreakAfterOpenBracketFunction = false;
1234 Style.BreakAfterOpenBracketIf = false;
1235 Style.BreakAfterOpenBracketLoop = false;
1236 Style.BreakAfterOpenBracketSwitch = false;
1237 Style.BreakBeforeCloseBracketBracedList = false;
1238 Style.BreakBeforeCloseBracketFunction = false;
1239 Style.BreakBeforeCloseBracketIf = false;
1240 Style.BreakBeforeCloseBracketLoop = false;
1241 Style.BreakBeforeCloseBracketSwitch = false;
1242 break;
1243 case BAS_Ignore:
1244 break;
1245 }
1246 }
1247
1248 // For backward compatibility.
1249 if (!IO.outputting()) {
1250 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlines);
1251 IO.mapOptional("AllowAllConstructorInitializersOnNextLine", OnNextLine);
1252 IO.mapOptional("AlwaysBreakAfterReturnType", Style.BreakAfterReturnType);
1253 IO.mapOptional("AlwaysBreakTemplateDeclarations",
1254 Style.BreakTemplateDeclarations);
1255 IO.mapOptional("BinPackArguments", Style.PackArguments.BinPack);
1256 IO.mapOptional("BinPackParameters", Style.PackParameters.BinPack);
1257 IO.mapOptional("BreakBeforeInheritanceComma",
1258 BreakBeforeInheritanceComma);
1259 IO.mapOptional("BreakConstructorInitializersBeforeComma",
1260 BreakConstructorInitializersBeforeComma);
1261 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
1262 OnCurrentLine);
1263 IO.mapOptional("DeriveLineEnding", DeriveLineEnding);
1264 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
1265 IO.mapOptional("KeepEmptyLinesAtEOF", Style.KeepEmptyLines.AtEndOfFile);
1266 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
1267 Style.KeepEmptyLines.AtStartOfBlock);
1268 IO.mapOptional("IndentFunctionDeclarationAfterType",
1269 Style.IndentWrappedFunctionNames);
1270 IO.mapOptional("IndentRequires", Style.IndentRequiresClause);
1271 IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
1272 IO.mapOptional("SpaceAfterControlStatementKeyword",
1273 Style.SpaceBeforeParens);
1274 IO.mapOptional("SpaceInEmptyBlock", SpaceInEmptyBlock);
1275 IO.mapOptional("SpaceInEmptyParentheses", SpaceInEmptyParentheses);
1276 IO.mapOptional("SpacesInConditionalStatement",
1277 SpacesInConditionalStatement);
1278 IO.mapOptional("SpacesInCStyleCastParentheses",
1279 SpacesInCStyleCastParentheses);
1280 IO.mapOptional("SpacesInParentheses", SpacesInParentheses);
1281 IO.mapOptional("UseCRLF", UseCRLF);
1282 }
1283
1284 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
1285 IO.mapOptional("AlignArrayOfStructures", Style.AlignArrayOfStructures);
1286 IO.mapOptional("AlignConsecutiveAssignments",
1287 Style.AlignConsecutiveAssignments);
1288 IO.mapOptional("AlignConsecutiveBitFields",
1289 Style.AlignConsecutiveBitFields);
1290 IO.mapOptional("AlignConsecutiveDeclarations",
1291 Style.AlignConsecutiveDeclarations);
1292 IO.mapOptional("AlignConsecutiveMacros", Style.AlignConsecutiveMacros);
1293 IO.mapOptional("AlignConsecutiveShortCaseStatements",
1294 Style.AlignConsecutiveShortCaseStatements);
1295 IO.mapOptional("AlignConsecutiveTableGenBreakingDAGArgColons",
1296 Style.AlignConsecutiveTableGenBreakingDAGArgColons);
1297 IO.mapOptional("AlignConsecutiveTableGenCondOperatorColons",
1298 Style.AlignConsecutiveTableGenCondOperatorColons);
1299 IO.mapOptional("AlignConsecutiveTableGenDefinitionColons",
1300 Style.AlignConsecutiveTableGenDefinitionColons);
1301 IO.mapOptional("AlignEscapedNewlines", Style.AlignEscapedNewlines);
1302 IO.mapOptional("AlignOperands", Style.AlignOperands);
1303 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
1304 IO.mapOptional("AllowAllArgumentsOnNextLine",
1305 Style.AllowAllArgumentsOnNextLine);
1306 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
1307 Style.AllowAllParametersOfDeclarationOnNextLine);
1308 IO.mapOptional("AllowBreakBeforeNoexceptSpecifier",
1309 Style.AllowBreakBeforeNoexceptSpecifier);
1310 IO.mapOptional("AllowBreakBeforeQtProperty",
1311 Style.AllowBreakBeforeQtProperty);
1312 IO.mapOptional("AllowShortBlocksOnASingleLine",
1313 Style.AllowShortBlocksOnASingleLine);
1314 IO.mapOptional("AllowShortCaseExpressionOnASingleLine",
1315 Style.AllowShortCaseExpressionOnASingleLine);
1316 IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
1317 Style.AllowShortCaseLabelsOnASingleLine);
1318 IO.mapOptional("AllowShortCompoundRequirementOnASingleLine",
1319 Style.AllowShortCompoundRequirementOnASingleLine);
1320 IO.mapOptional("AllowShortEnumsOnASingleLine",
1321 Style.AllowShortEnumsOnASingleLine);
1322 IO.mapOptional("AllowShortFunctionsOnASingleLine",
1323 Style.AllowShortFunctionsOnASingleLine);
1324 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
1325 Style.AllowShortIfStatementsOnASingleLine);
1326 IO.mapOptional("AllowShortLambdasOnASingleLine",
1327 Style.AllowShortLambdasOnASingleLine);
1328 IO.mapOptional("AllowShortLoopsOnASingleLine",
1329 Style.AllowShortLoopsOnASingleLine);
1330 IO.mapOptional("AllowShortNamespacesOnASingleLine",
1331 Style.AllowShortNamespacesOnASingleLine);
1332 IO.mapOptional("AllowShortRecordOnASingleLine",
1333 Style.AllowShortRecordOnASingleLine);
1334 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
1335 Style.AlwaysBreakAfterDefinitionReturnType);
1336 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
1337 Style.AlwaysBreakBeforeMultilineStrings);
1338 IO.mapOptional("AttributeMacros", Style.AttributeMacros);
1339 IO.mapOptional("BinPackLongBracedList", Style.BinPackLongBracedList);
1340 IO.mapOptional("BitFieldColonSpacing", Style.BitFieldColonSpacing);
1341 IO.mapOptional("BracedInitializerIndentWidth",
1342 Style.BracedInitializerIndentWidth);
1343 IO.mapOptional("BraceWrapping", Style.BraceWrapping);
1344 IO.mapOptional("BreakAdjacentStringLiterals",
1345 Style.BreakAdjacentStringLiterals);
1346 IO.mapOptional("BreakAfterAttributes", Style.BreakAfterAttributes);
1347 IO.mapOptional("BreakAfterJavaFieldAnnotations",
1348 Style.BreakAfterJavaFieldAnnotations);
1349 IO.mapOptional("BreakAfterOpenBracketBracedList",
1350 Style.BreakAfterOpenBracketBracedList);
1351 IO.mapOptional("BreakAfterOpenBracketFunction",
1352 Style.BreakAfterOpenBracketFunction);
1353 IO.mapOptional("BreakAfterOpenBracketIf", Style.BreakAfterOpenBracketIf);
1354 IO.mapOptional("BreakAfterOpenBracketLoop",
1355 Style.BreakAfterOpenBracketLoop);
1356 IO.mapOptional("BreakAfterOpenBracketSwitch",
1357 Style.BreakAfterOpenBracketSwitch);
1358 IO.mapOptional("BreakAfterReturnType", Style.BreakAfterReturnType);
1359 IO.mapOptional("BreakArrays", Style.BreakArrays);
1360 IO.mapOptional("BreakBeforeBinaryOperators",
1361 Style.BreakBeforeBinaryOperators);
1362 IO.mapOptional("BreakBeforeCloseBracketBracedList",
1363 Style.BreakBeforeCloseBracketBracedList);
1364 IO.mapOptional("BreakBeforeCloseBracketFunction",
1365 Style.BreakBeforeCloseBracketFunction);
1366 IO.mapOptional("BreakBeforeCloseBracketIf",
1367 Style.BreakBeforeCloseBracketIf);
1368 IO.mapOptional("BreakBeforeCloseBracketLoop",
1369 Style.BreakBeforeCloseBracketLoop);
1370 IO.mapOptional("BreakBeforeCloseBracketSwitch",
1371 Style.BreakBeforeCloseBracketSwitch);
1372 IO.mapOptional("BreakBeforeConceptDeclarations",
1373 Style.BreakBeforeConceptDeclarations);
1374 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
1375 IO.mapOptional("BreakBeforeInlineASMColon",
1376 Style.BreakBeforeInlineASMColon);
1377 IO.mapOptional("BreakBeforeReturnType", Style.BreakBeforeReturnType);
1378 IO.mapOptional("BreakBeforeTemplateCloser",
1379 Style.BreakBeforeTemplateCloser);
1380 IO.mapOptional("BreakBeforeTernaryOperators",
1381 Style.BreakBeforeTernaryOperators);
1382 IO.mapOptional("BreakBinaryOperations", Style.BreakBinaryOperations);
1383 IO.mapOptional("BreakConstructorInitializers",
1384 Style.BreakConstructorInitializers);
1385 IO.mapOptional("BreakFunctionDeclarationParameters",
1386 Style.BreakFunctionDeclarationParameters);
1387 IO.mapOptional("BreakFunctionDefinitionParameters",
1388 Style.BreakFunctionDefinitionParameters);
1389 IO.mapOptional("BreakInheritanceList", Style.BreakInheritanceList);
1390 IO.mapOptional("BreakStringLiterals", Style.BreakStringLiterals);
1391 IO.mapOptional("BreakTemplateDeclarations",
1392 Style.BreakTemplateDeclarations);
1393 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
1394 IO.mapOptional("CommentPragmas", Style.CommentPragmas);
1395 IO.mapOptional("CompactCaseLabels", Style.CompactCaseLabels);
1396 IO.mapOptional("CompactNamespaces", Style.CompactNamespaces);
1397 IO.mapOptional("ConstructorInitializerIndentWidth",
1398 Style.ConstructorInitializerIndentWidth);
1399 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
1400 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
1401 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
1402 IO.mapOptional("DisableFormat", Style.DisableFormat);
1403 IO.mapOptional("EmptyLineAfterAccessModifier",
1404 Style.EmptyLineAfterAccessModifier);
1405 IO.mapOptional("EmptyLineBeforeAccessModifier",
1406 Style.EmptyLineBeforeAccessModifier);
1407 IO.mapOptional("EnumTrailingComma", Style.EnumTrailingComma);
1408 IO.mapOptional("ExperimentalAutoDetectBinPacking",
1409 Style.ExperimentalAutoDetectBinPacking);
1410 IO.mapOptional("FixNamespaceComments", Style.FixNamespaceComments);
1411 IO.mapOptional("ForEachMacros", Style.ForEachMacros);
1412 IO.mapOptional("IfMacros", Style.IfMacros);
1413 IO.mapOptional("IncludeBlocks", Style.IncludeStyle.IncludeBlocks);
1414 IO.mapOptional("IncludeCategories", Style.IncludeStyle.IncludeCategories);
1415 IO.mapOptional("IncludeIsMainRegex", Style.IncludeStyle.IncludeIsMainRegex);
1416 IO.mapOptional("IncludeIsMainSourceRegex",
1417 Style.IncludeStyle.IncludeIsMainSourceRegex);
1418 IO.mapOptional("IndentAccessModifiers", Style.IndentAccessModifiers);
1419 IO.mapOptional("IndentCaseBlocks", Style.IndentCaseBlocks);
1420 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
1421 IO.mapOptional("IndentExportBlock", Style.IndentExportBlock);
1422 IO.mapOptional("IndentExternBlock", Style.IndentExternBlock);
1423 IO.mapOptional("IndentGotoLabels", Style.IndentGotoLabels);
1424 IO.mapOptional("IndentPPDirectives", Style.IndentPPDirectives);
1425 IO.mapOptional("IndentRequiresClause", Style.IndentRequiresClause);
1426 IO.mapOptional("IndentWidth", Style.IndentWidth);
1427 IO.mapOptional("IndentWrappedFunctionNames",
1428 Style.IndentWrappedFunctionNames);
1429 IO.mapOptional("InsertBraces", Style.InsertBraces);
1430 IO.mapOptional("InsertNewlineAtEOF", Style.InsertNewlineAtEOF);
1431 IO.mapOptional("InsertTrailingCommas", Style.InsertTrailingCommas);
1432 IO.mapOptional("IntegerLiteralSeparator", Style.IntegerLiteralSeparator);
1433 IO.mapOptional("JavaImportGroups", Style.JavaImportGroups);
1434 IO.mapOptional("JavaScriptQuotes", Style.JavaScriptQuotes);
1435 IO.mapOptional("JavaScriptWrapImports", Style.JavaScriptWrapImports);
1436 IO.mapOptional("KeepEmptyLines", Style.KeepEmptyLines);
1437 IO.mapOptional("KeepFormFeed", Style.KeepFormFeed);
1438 IO.mapOptional("LambdaBodyIndentation", Style.LambdaBodyIndentation);
1439 IO.mapOptional("LineEnding", Style.LineEnding);
1440 IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
1441 IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
1442 IO.mapOptional("Macros", Style.Macros);
1443 IO.mapOptional("MacrosSkippedByRemoveParentheses",
1444 Style.MacrosSkippedByRemoveParentheses);
1445 IO.mapOptional("MainIncludeChar", Style.IncludeStyle.MainIncludeChar);
1446 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
1447 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
1448 IO.mapOptional("NamespaceMacros", Style.NamespaceMacros);
1449 IO.mapOptional("NumericLiteralCase", Style.NumericLiteralCase);
1450 IO.mapOptional("ObjCBinPackProtocolList", Style.ObjCBinPackProtocolList);
1451 IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
1452 IO.mapOptional("ObjCBreakBeforeNestedBlockParam",
1453 Style.ObjCBreakBeforeNestedBlockParam);
1454 IO.mapOptional("ObjCPropertyAttributeOrder",
1455 Style.ObjCPropertyAttributeOrder);
1456 IO.mapOptional("ObjCSpaceAfterMethodDeclarationPrefix",
1457 Style.ObjCSpaceAfterMethodDeclarationPrefix);
1458 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
1459 IO.mapOptional("ObjCSpaceBeforeProtocolList",
1460 Style.ObjCSpaceBeforeProtocolList);
1461 IO.mapOptional("OneLineFormatOffRegex", Style.OneLineFormatOffRegex);
1462 IO.mapOptional("PackArguments", Style.PackArguments);
1463 IO.mapOptional("PackConstructorInitializers",
1464 Style.PackConstructorInitializers);
1465 IO.mapOptional("PackParameters", Style.PackParameters);
1466 IO.mapOptional("PenaltyBreakAssignment", Style.PenaltyBreakAssignment);
1467 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
1468 Style.PenaltyBreakBeforeFirstCallParameter);
1469 IO.mapOptional("PenaltyBreakBeforeMemberAccess",
1470 Style.PenaltyBreakBeforeMemberAccess);
1471 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
1472 IO.mapOptional("PenaltyBreakFirstLessLess",
1473 Style.PenaltyBreakFirstLessLess);
1474 IO.mapOptional("PenaltyBreakOpenParenthesis",
1475 Style.PenaltyBreakOpenParenthesis);
1476 IO.mapOptional("PenaltyBreakScopeResolution",
1477 Style.PenaltyBreakScopeResolution);
1478 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
1479 IO.mapOptional("PenaltyBreakTemplateDeclaration",
1480 Style.PenaltyBreakTemplateDeclaration);
1481 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
1482 IO.mapOptional("PenaltyIndentedWhitespace",
1483 Style.PenaltyIndentedWhitespace);
1484 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
1485 Style.PenaltyReturnTypeOnItsOwnLine);
1486 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
1487 IO.mapOptional("PPIndentWidth", Style.PPIndentWidth);
1488 IO.mapOptional("QualifierAlignment", Style.QualifierAlignment);
1489 // Default Order for Left/Right based Qualifier alignment.
1490 if (Style.QualifierAlignment == FormatStyle::QAS_Right)
1491 Style.QualifierOrder = {"type", "const", "volatile"};
1492 else if (Style.QualifierAlignment == FormatStyle::QAS_Left)
1493 Style.QualifierOrder = {"const", "volatile", "type"};
1494 else if (Style.QualifierAlignment == FormatStyle::QAS_Custom)
1495 IO.mapOptional("QualifierOrder", Style.QualifierOrder);
1496 IO.mapOptional("RawStringFormats", Style.RawStringFormats);
1497 IO.mapOptional("ReferenceAlignment", Style.ReferenceAlignment);
1498 IO.mapOptional("ReflowComments", Style.ReflowComments);
1499 IO.mapOptional("RemoveBracesLLVM", Style.RemoveBracesLLVM);
1500 IO.mapOptional("RemoveEmptyLinesInUnwrappedLines",
1501 Style.RemoveEmptyLinesInUnwrappedLines);
1502 IO.mapOptional("RemoveParentheses", Style.RemoveParentheses);
1503 IO.mapOptional("RemoveSemicolon", Style.RemoveSemicolon);
1504 IO.mapOptional("RequiresClausePosition", Style.RequiresClausePosition);
1505 IO.mapOptional("RequiresExpressionIndentation",
1506 Style.RequiresExpressionIndentation);
1507 IO.mapOptional("SeparateDefinitionBlocks", Style.SeparateDefinitionBlocks);
1508 IO.mapOptional("ShortNamespaceLines", Style.ShortNamespaceLines);
1509 IO.mapOptional("SkipMacroDefinitionBody", Style.SkipMacroDefinitionBody);
1510 IO.mapOptional("SortIncludes", Style.SortIncludes);
1511 IO.mapOptional("SortJavaStaticImport", Style.SortJavaStaticImport);
1512 IO.mapOptional("SortUsingDeclarations", Style.SortUsingDeclarations);
1513 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
1514 IO.mapOptional("SpaceAfterLogicalNot", Style.SpaceAfterLogicalNot);
1515 IO.mapOptional("SpaceAfterOperatorKeyword",
1516 Style.SpaceAfterOperatorKeyword);
1517 IO.mapOptional("SpaceAfterTemplateKeyword",
1518 Style.SpaceAfterTemplateKeyword);
1519 IO.mapOptional("SpaceAroundPointerQualifiers",
1520 Style.SpaceAroundPointerQualifiers);
1521 IO.mapOptional("SpaceBeforeAssignmentOperators",
1522 Style.SpaceBeforeAssignmentOperators);
1523 IO.mapOptional("SpaceBeforeCaseColon", Style.SpaceBeforeCaseColon);
1524 IO.mapOptional("SpaceBeforeCpp11BracedList",
1525 Style.SpaceBeforeCpp11BracedList);
1526 IO.mapOptional("SpaceBeforeCtorInitializerColon",
1527 Style.SpaceBeforeCtorInitializerColon);
1528 IO.mapOptional("SpaceBeforeEnumUnderlyingTypeColon",
1529 Style.SpaceBeforeEnumUnderlyingTypeColon);
1530 IO.mapOptional("SpaceBeforeInheritanceColon",
1531 Style.SpaceBeforeInheritanceColon);
1532 IO.mapOptional("SpaceBeforeJsonColon", Style.SpaceBeforeJsonColon);
1533 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
1534 IO.mapOptional("SpaceBeforeParensOptions", Style.SpaceBeforeParensOptions);
1535 IO.mapOptional("SpaceBeforeRangeBasedForLoopColon",
1536 Style.SpaceBeforeRangeBasedForLoopColon);
1537 IO.mapOptional("SpaceBeforeSquareBrackets",
1538 Style.SpaceBeforeSquareBrackets);
1539 IO.mapOptional("SpaceInEmptyBraces", Style.SpaceInEmptyBraces);
1540 IO.mapOptional("SpacesBeforeTrailingComments",
1541 Style.SpacesBeforeTrailingComments);
1542 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
1543 IO.mapOptional("SpacesInBlockComments", Style.SpacesInBlockComments);
1544 IO.mapOptional("SpacesInContainerLiterals",
1545 Style.SpacesInContainerLiterals);
1546 IO.mapOptional("SpacesInLineCommentPrefix",
1547 Style.SpacesInLineCommentPrefix);
1548 IO.mapOptional("SpacesInParens", Style.SpacesInParens);
1549 IO.mapOptional("SpacesInParensOptions", Style.SpacesInParensOptions);
1550 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
1551 IO.mapOptional("Standard", Style.Standard);
1552 IO.mapOptional("StatementAttributeLikeMacros",
1553 Style.StatementAttributeLikeMacros);
1554 IO.mapOptional("StatementMacros", Style.StatementMacros);
1555 IO.mapOptional("TableGenBreakingDAGArgOperators",
1556 Style.TableGenBreakingDAGArgOperators);
1557 IO.mapOptional("TableGenBreakInsideDAGArg",
1558 Style.TableGenBreakInsideDAGArg);
1559 IO.mapOptional("TabWidth", Style.TabWidth);
1560 IO.mapOptional("TemplateNames", Style.TemplateNames);
1561 IO.mapOptional("TypeNames", Style.TypeNames);
1562 IO.mapOptional("TypenameMacros", Style.TypenameMacros);
1563 IO.mapOptional("UseTab", Style.UseTab);
1564 IO.mapOptional("VariableTemplates", Style.VariableTemplates);
1565 IO.mapOptional("VerilogBreakBetweenInstancePorts",
1566 Style.VerilogBreakBetweenInstancePorts);
1567 IO.mapOptional("WhitespaceSensitiveMacros",
1568 Style.WhitespaceSensitiveMacros);
1569 IO.mapOptional("WrapNamespaceBodyWithEmptyLines",
1570 Style.WrapNamespaceBodyWithEmptyLines);
1571
1572 // If AlwaysBreakAfterDefinitionReturnType was specified but
1573 // BreakAfterReturnType was not, initialize the latter from the former for
1574 // backwards compatibility.
1575 if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
1576 Style.BreakAfterReturnType == FormatStyle::RTBS_None) {
1577 if (Style.AlwaysBreakAfterDefinitionReturnType ==
1579 Style.BreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
1580 } else if (Style.AlwaysBreakAfterDefinitionReturnType ==
1582 Style.BreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
1583 }
1584 }
1585
1586 // If BreakBeforeInheritanceComma was specified but BreakInheritance was
1587 // not, initialize the latter from the former for backwards compatibility.
1588 if (BreakBeforeInheritanceComma &&
1589 Style.BreakInheritanceList == FormatStyle::BILS_BeforeColon) {
1590 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
1591 }
1592
1593 // If BreakConstructorInitializersBeforeComma was specified but
1594 // BreakConstructorInitializers was not, initialize the latter from the
1595 // former for backwards compatibility.
1596 if (BreakConstructorInitializersBeforeComma &&
1597 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon) {
1598 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
1599 }
1600
1601 if (!IsGoogleOrChromium) {
1602 if (Style.PackConstructorInitializers == FormatStyle::PCIS_BinPack &&
1603 OnCurrentLine) {
1604 Style.PackConstructorInitializers = OnNextLine
1607 }
1608 } else if (Style.PackConstructorInitializers ==
1610 if (!OnCurrentLine)
1611 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
1612 else if (!OnNextLine)
1613 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
1614 }
1615
1616 if (Style.LineEnding == FormatStyle::LE_DeriveLF) {
1617 if (!DeriveLineEnding)
1618 Style.LineEnding = UseCRLF ? FormatStyle::LE_CRLF : FormatStyle::LE_LF;
1619 else if (UseCRLF)
1620 Style.LineEnding = FormatStyle::LE_DeriveCRLF;
1621 }
1622
1623 // If SpaceInEmptyBlock was specified but SpaceInEmptyBraces was not,
1624 // initialize the latter from the former for backward compatibility.
1625 if (SpaceInEmptyBlock &&
1626 Style.SpaceInEmptyBraces == FormatStyle::SIEB_Never) {
1627 Style.SpaceInEmptyBraces = FormatStyle::SIEB_Block;
1628 }
1629
1630 if (Style.SpacesInParens != FormatStyle::SIPO_Custom &&
1631 (SpacesInParentheses || SpaceInEmptyParentheses ||
1632 SpacesInConditionalStatement || SpacesInCStyleCastParentheses)) {
1633 if (SpacesInParentheses) {
1634 // For backward compatibility.
1635 Style.SpacesInParensOptions.ExceptDoubleParentheses = false;
1636 Style.SpacesInParensOptions.InConditionalStatements = true;
1637 Style.SpacesInParensOptions.InCStyleCasts =
1638 SpacesInCStyleCastParentheses;
1639 Style.SpacesInParensOptions.InEmptyParentheses =
1640 SpaceInEmptyParentheses;
1641 Style.SpacesInParensOptions.Other = true;
1642 } else {
1643 Style.SpacesInParensOptions = {};
1644 Style.SpacesInParensOptions.InConditionalStatements =
1645 SpacesInConditionalStatement;
1646 Style.SpacesInParensOptions.InCStyleCasts =
1647 SpacesInCStyleCastParentheses;
1648 Style.SpacesInParensOptions.InEmptyParentheses =
1649 SpaceInEmptyParentheses;
1650 }
1651 Style.SpacesInParens = FormatStyle::SIPO_Custom;
1652 }
1653 }
1654};
1655
1656// Allows to read vector<FormatStyle> while keeping default values.
1657// IO.getContext() should contain a pointer to the FormatStyle structure, that
1658// will be used to get default values for missing keys.
1659// If the first element has no Language specified, it will be treated as the
1660// default one for the following elements.
1661template <> struct DocumentListTraits<std::vector<FormatStyle>> {
1662 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
1663 return Seq.size();
1664 }
1665 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
1666 size_t Index) {
1667 if (Index >= Seq.size()) {
1668 assert(Index == Seq.size());
1669 FormatStyle Template;
1670 if (!Seq.empty() && Seq[0].Language == FormatStyle::LK_None) {
1671 Template = Seq[0];
1672 } else {
1673 Template = *((const FormatStyle *)IO.getContext());
1674 Template.Language = FormatStyle::LK_None;
1675 }
1676 Seq.resize(Index + 1, Template);
1677 }
1678 return Seq[Index];
1679 }
1680};
1681
1682template <> struct ScalarEnumerationTraits<FormatStyle::IndentGotoLabelStyle> {
1684 IO.enumCase(Value, "NoIndent", FormatStyle::IGLS_NoIndent);
1685 IO.enumCase(Value, "OuterIndent", FormatStyle::IGLS_OuterIndent);
1686 IO.enumCase(Value, "InnerIndent", FormatStyle::IGLS_InnerIndent);
1687 IO.enumCase(Value, "HalfIndent", FormatStyle::IGLS_HalfIndent);
1688
1689 // For backward compatibility.
1690 IO.enumCase(Value, "false", FormatStyle::IGLS_NoIndent);
1691 IO.enumCase(Value, "true", FormatStyle::IGLS_OuterIndent);
1692 }
1693};
1694
1695} // namespace yaml
1696} // namespace llvm
1697
1698namespace clang {
1699namespace format {
1700
1701const std::error_category &getParseCategory() {
1702 static const ParseErrorCategory C{};
1703 return C;
1704}
1705std::error_code make_error_code(ParseError e) {
1706 return std::error_code(static_cast<int>(e), getParseCategory());
1707}
1708
1709inline llvm::Error make_string_error(const Twine &Message) {
1710 return llvm::make_error<llvm::StringError>(Message,
1711 llvm::inconvertibleErrorCode());
1712}
1713
1714const char *ParseErrorCategory::name() const noexcept {
1715 return "clang-format.parse_error";
1716}
1717
1718std::string ParseErrorCategory::message(int EV) const {
1719 switch (static_cast<ParseError>(EV)) {
1721 return "Success";
1722 case ParseError::Error:
1723 return "Invalid argument";
1725 return "Unsuitable";
1727 return "trailing comma insertion cannot be used with bin packing";
1729 return "Invalid qualifier specified in QualifierOrder";
1731 return "Duplicate qualifier specified in QualifierOrder";
1733 return "Missing type in QualifierOrder";
1735 return "Missing QualifierOrder";
1736 }
1737 llvm_unreachable("unexpected parse error");
1738}
1739
1742 return;
1743 Expanded.BraceWrapping = {/*AfterCaseLabel=*/false,
1744 /*AfterClass=*/false,
1745 /*AfterControlStatement=*/FormatStyle::BWACS_Never,
1746 /*AfterEnum=*/false,
1747 /*AfterFunction=*/false,
1748 /*AfterNamespace=*/false,
1749 /*AfterObjCDeclaration=*/false,
1750 /*AfterRequiresExpression=*/false,
1751 /*AfterStruct=*/false,
1752 /*AfterUnion=*/false,
1753 /*AfterExportBlock=*/false,
1754 /*AfterExternBlock=*/false,
1755 /*BeforeCatch=*/false,
1756 /*BeforeElse=*/false,
1757 /*BeforeLambdaBody=*/false,
1758 /*BeforeWhile=*/false,
1759 /*IndentBraces=*/false,
1760 /*SplitEmptyFunction=*/true,
1761 /*SplitEmptyRecord=*/true,
1762 /*SplitEmptyNamespace=*/true};
1763 switch (Expanded.BreakBeforeBraces) {
1765 Expanded.BraceWrapping.AfterClass = true;
1766 Expanded.BraceWrapping.AfterFunction = true;
1767 Expanded.BraceWrapping.AfterNamespace = true;
1768 break;
1770 Expanded.BraceWrapping.AfterClass = true;
1771 Expanded.BraceWrapping.AfterEnum = true;
1772 Expanded.BraceWrapping.AfterFunction = true;
1773 Expanded.BraceWrapping.AfterStruct = true;
1774 Expanded.BraceWrapping.AfterUnion = true;
1775 Expanded.BraceWrapping.AfterExportBlock = true;
1776 Expanded.BraceWrapping.AfterExternBlock = true;
1777 Expanded.BraceWrapping.SplitEmptyFunction = true;
1778 Expanded.BraceWrapping.SplitEmptyRecord = false;
1779 break;
1781 Expanded.BraceWrapping.AfterFunction = true;
1782 Expanded.BraceWrapping.BeforeCatch = true;
1783 Expanded.BraceWrapping.BeforeElse = true;
1784 break;
1786 Expanded.BraceWrapping.AfterCaseLabel = true;
1787 Expanded.BraceWrapping.AfterClass = true;
1789 Expanded.BraceWrapping.AfterEnum = true;
1790 Expanded.BraceWrapping.AfterFunction = true;
1791 Expanded.BraceWrapping.AfterNamespace = true;
1792 Expanded.BraceWrapping.AfterObjCDeclaration = true;
1793 Expanded.BraceWrapping.AfterRequiresExpression = true;
1794 Expanded.BraceWrapping.AfterStruct = true;
1795 Expanded.BraceWrapping.AfterUnion = true;
1796 Expanded.BraceWrapping.AfterExportBlock = true;
1797 Expanded.BraceWrapping.AfterExternBlock = true;
1798 Expanded.BraceWrapping.BeforeCatch = true;
1799 Expanded.BraceWrapping.BeforeElse = true;
1800 Expanded.BraceWrapping.BeforeLambdaBody = true;
1801 break;
1803 Expanded.BraceWrapping.AfterCaseLabel = true;
1804 Expanded.BraceWrapping.AfterClass = true;
1806 Expanded.BraceWrapping.AfterEnum = true;
1807 Expanded.BraceWrapping.AfterFunction = true;
1808 Expanded.BraceWrapping.AfterNamespace = true;
1809 Expanded.BraceWrapping.AfterObjCDeclaration = true;
1810 Expanded.BraceWrapping.AfterRequiresExpression = true;
1811 Expanded.BraceWrapping.AfterStruct = true;
1812 Expanded.BraceWrapping.AfterExternBlock = true;
1813 Expanded.BraceWrapping.BeforeCatch = true;
1814 Expanded.BraceWrapping.BeforeElse = true;
1815 Expanded.BraceWrapping.BeforeLambdaBody = true;
1816 break;
1818 Expanded.BraceWrapping = {
1819 /*AfterCaseLabel=*/true,
1820 /*AfterClass=*/true,
1821 /*AfterControlStatement=*/FormatStyle::BWACS_Always,
1822 /*AfterEnum=*/true,
1823 /*AfterFunction=*/true,
1824 /*AfterNamespace=*/true,
1825 /*AfterObjCDeclaration=*/true,
1826 /*AfterRequiresExpression=*/true,
1827 /*AfterStruct=*/true,
1828 /*AfterUnion=*/true,
1829 /*AfterExportBlock=*/true,
1830 /*AfterExternBlock=*/true,
1831 /*BeforeCatch=*/true,
1832 /*BeforeElse=*/true,
1833 /*BeforeLambdaBody=*/true,
1834 /*BeforeWhile=*/true,
1835 /*IndentBraces=*/true,
1836 /*SplitEmptyFunction=*/true,
1837 /*SplitEmptyRecord=*/true,
1838 /*SplitEmptyNamespace=*/true};
1839 break;
1841 Expanded.BraceWrapping.AfterFunction = true;
1842 break;
1843 default:
1844 break;
1845 }
1846}
1847
1850 return;
1851 // Reset all flags
1852 Expanded.SpaceBeforeParensOptions = {};
1854
1855 switch (Expanded.SpaceBeforeParens) {
1860 break;
1863 break;
1866 break;
1867 default:
1868 break;
1869 }
1870}
1871
1874 return;
1875 assert(Expanded.SpacesInParens == FormatStyle::SIPO_Never);
1876 // Reset all flags
1877 Expanded.SpacesInParensOptions = {};
1878}
1879
1881 FormatStyle LLVMStyle;
1882 LLVMStyle.AccessModifierOffset = -2;
1883 LLVMStyle.AlignAfterOpenBracket = true;
1885 LLVMStyle.AlignConsecutiveAssignments = {};
1887 LLVMStyle.AlignConsecutiveBitFields = {};
1888 LLVMStyle.AlignConsecutiveDeclarations = {};
1890 LLVMStyle.AlignConsecutiveMacros = {};
1897 LLVMStyle.AlignTrailingComments = {};
1900 LLVMStyle.AlignTrailingComments.AlignPPAndNotPP = true;
1901 LLVMStyle.AllowAllArgumentsOnNextLine = true;
1904 LLVMStyle.AllowBreakBeforeQtProperty = false;
1907 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
1909 LLVMStyle.AllowShortEnumsOnASingleLine = true;
1914 LLVMStyle.AllowShortLoopsOnASingleLine = false;
1915 LLVMStyle.AllowShortNamespacesOnASingleLine = false;
1918 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
1919 LLVMStyle.AttributeMacros.push_back("__capability");
1920 LLVMStyle.BinPackLongBracedList = true;
1922 LLVMStyle.BracedInitializerIndentWidth = -1;
1923 LLVMStyle.BraceWrapping = {/*AfterCaseLabel=*/false,
1924 /*AfterClass=*/false,
1925 /*AfterControlStatement=*/FormatStyle::BWACS_Never,
1926 /*AfterEnum=*/false,
1927 /*AfterFunction=*/false,
1928 /*AfterNamespace=*/false,
1929 /*AfterObjCDeclaration=*/false,
1930 /*AfterRequiresExpression=*/false,
1931 /*AfterStruct=*/false,
1932 /*AfterUnion=*/false,
1933 /*AfterExportBlock=*/false,
1934 /*AfterExternBlock=*/false,
1935 /*BeforeCatch=*/false,
1936 /*BeforeElse=*/false,
1937 /*BeforeLambdaBody=*/false,
1938 /*BeforeWhile=*/false,
1939 /*IndentBraces=*/false,
1940 /*SplitEmptyFunction=*/true,
1941 /*SplitEmptyRecord=*/true,
1942 /*SplitEmptyNamespace=*/true};
1943 LLVMStyle.BreakAdjacentStringLiterals = true;
1945 LLVMStyle.BreakAfterJavaFieldAnnotations = false;
1946 LLVMStyle.BreakAfterOpenBracketBracedList = false;
1947 LLVMStyle.BreakAfterOpenBracketFunction = false;
1948 LLVMStyle.BreakAfterOpenBracketIf = false;
1949 LLVMStyle.BreakAfterOpenBracketLoop = false;
1950 LLVMStyle.BreakAfterOpenBracketSwitch = false;
1952 LLVMStyle.BreakArrays = true;
1955 LLVMStyle.BreakBeforeCloseBracketBracedList = false;
1956 LLVMStyle.BreakBeforeCloseBracketFunction = false;
1957 LLVMStyle.BreakBeforeCloseBracketIf = false;
1958 LLVMStyle.BreakBeforeCloseBracketLoop = false;
1959 LLVMStyle.BreakBeforeCloseBracketSwitch = false;
1963 LLVMStyle.BreakBeforeTemplateCloser = false;
1964 LLVMStyle.BreakBeforeTernaryOperators = true;
1967 LLVMStyle.BreakFunctionDeclarationParameters = false;
1968 LLVMStyle.BreakFunctionDefinitionParameters = false;
1970 LLVMStyle.BreakStringLiterals = true;
1972 LLVMStyle.ColumnLimit = 80;
1973 LLVMStyle.CommentPragmas = "^ IWYU pragma:";
1974 LLVMStyle.CompactCaseLabels = false;
1975 LLVMStyle.CompactNamespaces = false;
1977 LLVMStyle.ContinuationIndentWidth = 4;
1979 LLVMStyle.DerivePointerAlignment = false;
1980 LLVMStyle.DisableFormat = false;
1984 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
1985 LLVMStyle.FixNamespaceComments = true;
1986 LLVMStyle.ForEachMacros.push_back("foreach");
1987 LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
1988 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
1989 LLVMStyle.IfMacros.push_back("KJ_IF_MAYBE");
1991 LLVMStyle.IncludeStyle.IncludeCategories = {
1992 {"^\"(llvm|llvm-c|clang|clang-c)/", 2, 0, false},
1993 {"^(<|\"(gtest|gmock|isl|json)/)", 3, 0, false},
1994 {".*", 1, 0, false}};
1995 LLVMStyle.IncludeStyle.IncludeIsMainRegex = "(Test)?$";
1998 LLVMStyle.IndentCaseBlocks = false;
1999 LLVMStyle.IndentCaseLabels = false;
2000 LLVMStyle.IndentExportBlock = true;
2004 LLVMStyle.IndentRequiresClause = true;
2005 LLVMStyle.IndentWidth = 2;
2006 LLVMStyle.IndentWrappedFunctionNames = false;
2007 LLVMStyle.InsertBraces = false;
2008 LLVMStyle.InsertNewlineAtEOF = false;
2010 LLVMStyle.IntegerLiteralSeparator = {};
2012 LLVMStyle.JavaScriptWrapImports = true;
2013 LLVMStyle.KeepEmptyLines = {
2014 /*AtEndOfBlock=*/false,
2015 /*AtEndOfFile=*/false,
2016 /*AtStartOfBlock=*/true,
2017 /*AtStartOfFile=*/true,
2018 };
2019 LLVMStyle.KeepFormFeed = false;
2021 LLVMStyle.Language = Language;
2023 LLVMStyle.MaxEmptyLinesToKeep = 1;
2025 LLVMStyle.NumericLiteralCase = {/*ExponentLetter=*/FormatStyle::NLCS_Leave,
2026 /*HexDigit=*/FormatStyle::NLCS_Leave,
2027 /*Prefix=*/FormatStyle::NLCS_Leave,
2028 /*Suffix=*/FormatStyle::NLCS_Leave};
2030 LLVMStyle.ObjCBlockIndentWidth = 2;
2031 LLVMStyle.ObjCBreakBeforeNestedBlockParam = true;
2033 LLVMStyle.ObjCSpaceAfterProperty = false;
2034 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
2035 LLVMStyle.PackArguments = {/*BinPack=*/FormatStyle::BPAS_BinPack,
2036 /*BreakAfter=*/0};
2038 LLVMStyle.PackParameters = {/*BinPack=*/FormatStyle::BPPS_BinPack,
2039 /*BreakAfter=*/0};
2041 LLVMStyle.PPIndentWidth = -1;
2045 LLVMStyle.RemoveBracesLLVM = false;
2046 LLVMStyle.RemoveEmptyLinesInUnwrappedLines = false;
2048 LLVMStyle.RemoveSemicolon = false;
2052 LLVMStyle.ShortNamespaceLines = 1;
2053 LLVMStyle.SkipMacroDefinitionBody = false;
2054 LLVMStyle.SortIncludes = {/*Enabled=*/true, /*IgnoreCase=*/false,
2055 /*IgnoreExtension=*/false, /*Natural=*/false,
2056 /*FilesBeforeFolders=*/false};
2059 LLVMStyle.SpaceAfterCStyleCast = false;
2060 LLVMStyle.SpaceAfterLogicalNot = false;
2061 LLVMStyle.SpaceAfterOperatorKeyword = false;
2062 LLVMStyle.SpaceAfterTemplateKeyword = true;
2064 LLVMStyle.SpaceBeforeAssignmentOperators = true;
2065 LLVMStyle.SpaceBeforeCaseColon = false;
2066 LLVMStyle.SpaceBeforeCpp11BracedList = false;
2067 LLVMStyle.SpaceBeforeCtorInitializerColon = true;
2068 LLVMStyle.SpaceBeforeEnumUnderlyingTypeColon = true;
2069 LLVMStyle.SpaceBeforeInheritanceColon = true;
2070 LLVMStyle.SpaceBeforeJsonColon = false;
2072 LLVMStyle.SpaceBeforeParensOptions = {};
2075 LLVMStyle.SpaceBeforeParensOptions.AfterIfMacros = true;
2076 LLVMStyle.SpaceBeforeRangeBasedForLoopColon = true;
2077 LLVMStyle.SpaceBeforeSquareBrackets = false;
2079 LLVMStyle.SpacesBeforeTrailingComments = 1;
2081 LLVMStyle.SpacesInBlockComments = FormatStyle::SIBCS_Leave;
2082 LLVMStyle.SpacesInContainerLiterals = true;
2083 LLVMStyle.SpacesInLineCommentPrefix = {
2084 /*Minimum=*/1, /*Maximum=*/std::numeric_limits<unsigned>::max()};
2086 LLVMStyle.SpacesInSquareBrackets = false;
2087 LLVMStyle.Standard = FormatStyle::LS_Latest;
2088 LLVMStyle.StatementAttributeLikeMacros.push_back("Q_EMIT");
2089 LLVMStyle.StatementMacros.push_back("Q_UNUSED");
2090 LLVMStyle.StatementMacros.push_back("QT_REQUIRE_VERSION");
2091 LLVMStyle.TableGenBreakingDAGArgOperators = {};
2093 LLVMStyle.TabWidth = 8;
2094 LLVMStyle.UseTab = FormatStyle::UT_Never;
2095 LLVMStyle.VerilogBreakBetweenInstancePorts = true;
2096 LLVMStyle.WhitespaceSensitiveMacros.push_back("BOOST_PP_STRINGIZE");
2097 LLVMStyle.WhitespaceSensitiveMacros.push_back("CF_SWIFT_NAME");
2098 LLVMStyle.WhitespaceSensitiveMacros.push_back("NS_SWIFT_NAME");
2099 LLVMStyle.WhitespaceSensitiveMacros.push_back("PP_STRINGIZE");
2100 LLVMStyle.WhitespaceSensitiveMacros.push_back("STRINGIZE");
2102
2105 LLVMStyle.PenaltyBreakBeforeMemberAccess = 150;
2106 LLVMStyle.PenaltyBreakComment = 300;
2107 LLVMStyle.PenaltyBreakFirstLessLess = 120;
2108 LLVMStyle.PenaltyBreakOpenParenthesis = 0;
2109 LLVMStyle.PenaltyBreakScopeResolution = 500;
2110 LLVMStyle.PenaltyBreakString = 1000;
2112 LLVMStyle.PenaltyExcessCharacter = 1'000'000;
2113 LLVMStyle.PenaltyIndentedWhitespace = 0;
2114 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
2115
2116 // Defaults that differ when not C++.
2117 switch (Language) {
2119 LLVMStyle.SpacesInContainerLiterals = false;
2120 break;
2122 LLVMStyle.ColumnLimit = 0;
2123 break;
2125 LLVMStyle.IndentCaseLabels = true;
2126 LLVMStyle.SpacesInContainerLiterals = false;
2127 break;
2128 default:
2129 break;
2130 }
2131
2132 return LLVMStyle;
2133}
2134
2138 GoogleStyle.Language = FormatStyle::LK_TextProto;
2139
2140 return GoogleStyle;
2141 }
2142
2143 FormatStyle GoogleStyle = getLLVMStyle(Language);
2144
2145 GoogleStyle.AccessModifierOffset = -1;
2149 GoogleStyle.AllowShortLoopsOnASingleLine = true;
2150 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
2151 // Abseil aliases to clang's `_Nonnull`, `_Nullable` and `_Null_unspecified`.
2152 GoogleStyle.AttributeMacros.push_back("absl_nonnull");
2153 GoogleStyle.AttributeMacros.push_back("absl_nullable");
2154 GoogleStyle.AttributeMacros.push_back("absl_nullability_unknown");
2157 GoogleStyle.IncludeStyle.IncludeCategories = {{"^<ext/.*\\.h>", 2, 0, false},
2158 {"^<.*\\.h>", 1, 0, false},
2159 {"^<.*", 2, 0, false},
2160 {".*", 3, 0, false}};
2161 GoogleStyle.IncludeStyle.IncludeIsMainRegex = "([-_](test|unittest))?$";
2162 GoogleStyle.IndentCaseLabels = true;
2163 GoogleStyle.KeepEmptyLines.AtStartOfBlock = false;
2165 GoogleStyle.ObjCSpaceAfterProperty = false;
2166 GoogleStyle.ObjCSpaceBeforeProtocolList = true;
2169 GoogleStyle.RawStringFormats = {
2170 {
2172 /*Delimiters=*/
2173 {
2174 "cc",
2175 "CC",
2176 "cpp",
2177 "Cpp",
2178 "CPP",
2179 "c++",
2180 "C++",
2181 },
2182 /*EnclosingFunctionNames=*/
2183 {},
2184 /*CanonicalDelimiter=*/"",
2185 /*BasedOnStyle=*/"google",
2186 },
2187 {
2189 /*Delimiters=*/
2190 {
2191 "pb",
2192 "PB",
2193 "proto",
2194 "PROTO",
2195 },
2196 /*EnclosingFunctionNames=*/
2197 {
2198 "EqualsProto",
2199 "EquivToProto",
2200 "PARSE_PARTIAL_TEXT_PROTO",
2201 "PARSE_TEST_PROTO",
2202 "PARSE_TEXT_PROTO",
2203 "ParseTextOrDie",
2204 "ParseTextProtoOrDie",
2205 "ParseTestProto",
2206 "ParsePartialTestProto",
2207 },
2208 /*CanonicalDelimiter=*/"pb",
2209 /*BasedOnStyle=*/"google",
2210 },
2211 };
2212
2213 GoogleStyle.SpacesBeforeTrailingComments = 2;
2214 GoogleStyle.Standard = FormatStyle::LS_Auto;
2215
2217 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
2218
2220 GoogleStyle.AlignAfterOpenBracket = false;
2222 GoogleStyle.AlignTrailingComments = {};
2227 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
2229 GoogleStyle.ColumnLimit = 100;
2230 GoogleStyle.SpaceAfterCStyleCast = true;
2231 GoogleStyle.SpacesBeforeTrailingComments = 1;
2232 } else if (Language == FormatStyle::LK_JavaScript) {
2233 GoogleStyle.BreakAfterOpenBracketBracedList = true;
2234 GoogleStyle.BreakAfterOpenBracketFunction = true;
2235 GoogleStyle.BreakAfterOpenBracketIf = true;
2239 // TODO: still under discussion whether to switch to SLS_All.
2241 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
2242 GoogleStyle.BreakBeforeTernaryOperators = false;
2243 // taze:, triple slash directives (`/// <...`), tslint:, and @see, which is
2244 // commonly followed by overlong URLs.
2245 GoogleStyle.CommentPragmas = "(taze:|^/[ \t]*<|tslint:|@see)";
2246 // TODO: enable once decided, in particular re disabling bin packing.
2247 // https://google.github.io/styleguide/jsguide.html#features-arrays-trailing-comma
2248 // GoogleStyle.InsertTrailingCommas = FormatStyle::TCS_Wrapped;
2250 GoogleStyle.JavaScriptWrapImports = false;
2251 GoogleStyle.MaxEmptyLinesToKeep = 3;
2253 GoogleStyle.SpacesInContainerLiterals = false;
2254 } else if (Language == FormatStyle::LK_Proto) {
2257 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
2258 // This affects protocol buffer options specifications and text protos.
2259 // Text protos are currently mostly formatted inside C++ raw string literals
2260 // and often the current breaking behavior of string literals is not
2261 // beneficial there. Investigate turning this on once proper string reflow
2262 // has been implemented.
2263 GoogleStyle.BreakStringLiterals = false;
2265 GoogleStyle.SpacesInContainerLiterals = false;
2266 } else if (Language == FormatStyle::LK_ObjC) {
2267 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
2268 GoogleStyle.ColumnLimit = 100;
2269 GoogleStyle.DerivePointerAlignment = true;
2270 // "Regroup" doesn't work well for ObjC yet (main header heuristic,
2271 // relationship between ObjC standard library headers and other heades,
2272 // #imports, etc.)
2273 GoogleStyle.IncludeStyle.IncludeBlocks =
2275 } else if (Language == FormatStyle::LK_CSharp) {
2279 GoogleStyle.BreakStringLiterals = false;
2280 GoogleStyle.ColumnLimit = 100;
2282 }
2283
2284 return GoogleStyle;
2285}
2286
2288 FormatStyle ChromiumStyle = getGoogleStyle(Language);
2289
2290 // Disable include reordering across blocks in Chromium code.
2291 // - clang-format tries to detect that foo.h is the "main" header for
2292 // foo.cc and foo_unittest.cc via IncludeIsMainRegex. However, Chromium
2293 // uses many other suffices (_win.cc, _mac.mm, _posix.cc, _browsertest.cc,
2294 // _private.cc, _impl.cc etc) in different permutations
2295 // (_win_browsertest.cc) so disable this until IncludeIsMainRegex has a
2296 // better default for Chromium code.
2297 // - The default for .cc and .mm files is different (r357695) for Google style
2298 // for the same reason. The plan is to unify this again once the main
2299 // header detection works for Google's ObjC code, but this hasn't happened
2300 // yet. Since Chromium has some ObjC code, switching Chromium is blocked
2301 // on that.
2302 // - Finally, "If include reordering is harmful, put things in different
2303 // blocks to prevent it" has been a recommendation for a long time that
2304 // people are used to. We'll need a dev education push to change this to
2305 // "If include reordering is harmful, put things in a different block and
2306 // _prepend that with a comment_ to prevent it" before changing behavior.
2307 ChromiumStyle.IncludeStyle.IncludeBlocks =
2309
2313 ChromiumStyle.BreakAfterJavaFieldAnnotations = true;
2314 ChromiumStyle.ContinuationIndentWidth = 8;
2315 ChromiumStyle.IndentWidth = 4;
2316 // See styleguide for import groups:
2317 // https://chromium.googlesource.com/chromium/src/+/refs/heads/main/styleguide/java/java.md#Import-Order
2318 ChromiumStyle.JavaImportGroups = {
2319 "android",
2320 "androidx",
2321 "com",
2322 "dalvik",
2323 "junit",
2324 "org",
2325 "com.google.android.apps.chrome",
2326 "org.chromium",
2327 "java",
2328 "javax",
2329 };
2330 } else if (Language == FormatStyle::LK_JavaScript) {
2332 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
2333 } else {
2334 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
2335 ChromiumStyle.AllowShortFunctionsOnASingleLine =
2338 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
2340 ChromiumStyle.DerivePointerAlignment = false;
2342 ChromiumStyle.ColumnLimit = 80;
2343 }
2344 return ChromiumStyle;
2345}
2346
2348 FormatStyle MozillaStyle = getLLVMStyle();
2349 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
2361 MozillaStyle.ConstructorInitializerIndentWidth = 2;
2362 MozillaStyle.ContinuationIndentWidth = 2;
2364 MozillaStyle.FixNamespaceComments = false;
2365 MozillaStyle.IndentCaseLabels = true;
2366 MozillaStyle.ObjCSpaceAfterProperty = true;
2367 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
2368 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
2370 MozillaStyle.SpaceAfterTemplateKeyword = false;
2371 return MozillaStyle;
2372}
2373
2375 FormatStyle Style = getLLVMStyle();
2376 Style.AccessModifierOffset = -4;
2377 Style.AlignAfterOpenBracket = false;
2378 Style.AlignOperands = FormatStyle::OAS_DontAlign;
2379 Style.AlignTrailingComments = {};
2380 Style.AlignTrailingComments.Kind = FormatStyle::TCAS_Never;
2381 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
2382 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
2383 Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
2384 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
2385 Style.ColumnLimit = 0;
2386 Style.Cpp11BracedListStyle = FormatStyle::BLS_Block;
2387 Style.FixNamespaceComments = false;
2388 Style.IndentWidth = 4;
2389 Style.NamespaceIndentation = FormatStyle::NI_Inner;
2390 Style.ObjCBlockIndentWidth = 4;
2391 Style.ObjCSpaceAfterProperty = true;
2392 Style.PointerAlignment = FormatStyle::PAS_Left;
2393 Style.SpaceBeforeCpp11BracedList = true;
2394 Style.SpaceInEmptyBraces = FormatStyle::SIEB_Always;
2395 return Style;
2396}
2397
2399 FormatStyle Style = getLLVMStyle();
2400 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
2401 Style.BreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
2402 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
2403 Style.BreakBeforeBraces = FormatStyle::BS_GNU;
2404 Style.BreakBeforeTernaryOperators = true;
2405 Style.ColumnLimit = 79;
2406 Style.Cpp11BracedListStyle = FormatStyle::BLS_Block;
2407 Style.FixNamespaceComments = false;
2408 Style.KeepFormFeed = true;
2409 Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
2410 return Style;
2411}
2412
2415 Style.ColumnLimit = 120;
2416 Style.TabWidth = 4;
2417 Style.IndentWidth = 4;
2418 Style.UseTab = FormatStyle::UT_Never;
2419 Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2420 Style.BraceWrapping.AfterClass = true;
2421 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2422 Style.BraceWrapping.AfterEnum = true;
2423 Style.BraceWrapping.AfterFunction = true;
2424 Style.BraceWrapping.AfterNamespace = true;
2425 Style.BraceWrapping.AfterObjCDeclaration = true;
2426 Style.BraceWrapping.AfterStruct = true;
2427 Style.BraceWrapping.AfterExternBlock = true;
2428 Style.BraceWrapping.BeforeCatch = true;
2429 Style.BraceWrapping.BeforeElse = true;
2430 Style.BraceWrapping.BeforeWhile = false;
2431 Style.PenaltyReturnTypeOnItsOwnLine = 1000;
2432 Style.AllowShortEnumsOnASingleLine = false;
2433 Style.AllowShortFunctionsOnASingleLine = FormatStyle::ShortFunctionStyle();
2434 Style.AllowShortCaseLabelsOnASingleLine = false;
2435 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
2436 Style.AllowShortLoopsOnASingleLine = false;
2437 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
2438 Style.BreakAfterReturnType = FormatStyle::RTBS_None;
2439 return Style;
2440}
2441
2443 FormatStyle Style = getLLVMStyle();
2444 Style.InsertBraces = true;
2445 Style.InsertNewlineAtEOF = true;
2446 Style.IntegerLiteralSeparator.Decimal = 3;
2447 Style.IntegerLiteralSeparator.DecimalMinDigitsInsert = 5;
2448 Style.LineEnding = FormatStyle::LE_LF;
2449 Style.RemoveBracesLLVM = true;
2450 Style.RemoveEmptyLinesInUnwrappedLines = true;
2451 Style.RemoveParentheses = FormatStyle::RPS_ReturnStatement;
2452 Style.RemoveSemicolon = true;
2453 return Style;
2454}
2455
2457 FormatStyle NoStyle = getLLVMStyle();
2458 NoStyle.DisableFormat = true;
2459 NoStyle.SortIncludes = {};
2461 return NoStyle;
2462}
2463
2465 FormatStyle *Style) {
2466 constexpr StringRef Prefix("inheritparentconfig=");
2467
2468 if (Name.equals_insensitive("llvm"))
2469 *Style = getLLVMStyle(Language);
2470 else if (Name.equals_insensitive("chromium"))
2471 *Style = getChromiumStyle(Language);
2472 else if (Name.equals_insensitive("mozilla"))
2473 *Style = getMozillaStyle();
2474 else if (Name.equals_insensitive("google"))
2475 *Style = getGoogleStyle(Language);
2476 else if (Name.equals_insensitive("webkit"))
2477 *Style = getWebKitStyle();
2478 else if (Name.equals_insensitive("gnu"))
2479 *Style = getGNUStyle();
2480 else if (Name.equals_insensitive("microsoft"))
2481 *Style = getMicrosoftStyle(Language);
2482 else if (Name.equals_insensitive("clang-format"))
2483 *Style = getClangFormatStyle();
2484 else if (Name.equals_insensitive("none"))
2485 *Style = getNoStyle();
2486 else if (Name.equals_insensitive(Prefix.drop_back()))
2487 Style->InheritConfig = "..";
2488 else if (Name.size() > Prefix.size() && Name.starts_with_insensitive(Prefix))
2489 Style->InheritConfig = Name.substr(Prefix.size());
2490 else
2491 return false;
2492
2493 Style->Language = Language;
2494 return true;
2495}
2496
2498 // If its empty then it means don't do anything.
2499 if (Style->QualifierOrder.empty())
2501
2502 // Ensure the list contains only currently valid qualifiers.
2503 for (const auto &Qualifier : Style->QualifierOrder) {
2504 if (Qualifier == "type")
2505 continue;
2506 auto token =
2508 if (token == tok::identifier)
2510 }
2511
2512 // Ensure the list is unique (no duplicates).
2513 std::set<std::string> UniqueQualifiers(Style->QualifierOrder.begin(),
2514 Style->QualifierOrder.end());
2515 if (Style->QualifierOrder.size() != UniqueQualifiers.size()) {
2516 LLVM_DEBUG(llvm::dbgs()
2517 << "Duplicate Qualifiers " << Style->QualifierOrder.size()
2518 << " vs " << UniqueQualifiers.size() << "\n");
2520 }
2521
2522 // Ensure the list has 'type' in it.
2523 if (!llvm::is_contained(Style->QualifierOrder, "type"))
2525
2526 return ParseError::Success;
2527}
2528
2529std::error_code parseConfiguration(llvm::MemoryBufferRef Config,
2530 FormatStyle *Style, bool AllowUnknownOptions,
2531 llvm::SourceMgr::DiagHandlerTy DiagHandler,
2532 void *DiagHandlerCtxt, bool IsDotHFile) {
2533 assert(Style);
2534 FormatStyle::LanguageKind Language = Style->Language;
2535 assert(Language != FormatStyle::LK_None);
2536 if (Config.getBuffer().trim().empty())
2538 Style->StyleSet.Clear();
2539 std::vector<FormatStyle> Styles;
2540 llvm::yaml::Input Input(Config, /*Ctxt=*/nullptr, DiagHandler,
2541 DiagHandlerCtxt);
2542 // DocumentListTraits<vector<FormatStyle>> uses the context to get default
2543 // values for the fields, keys for which are missing from the configuration.
2544 // Mapping also uses the context to get the language to find the correct
2545 // base style.
2546 Input.setContext(Style);
2547 Input.setAllowUnknownKeys(AllowUnknownOptions);
2548 Input >> Styles;
2549 if (Input.error())
2550 return Input.error();
2551 if (Styles.empty())
2553
2554 const auto StyleCount = Styles.size();
2555
2556 // Start from the second style as (only) the first one may be the default.
2557 for (unsigned I = 1; I < StyleCount; ++I) {
2558 const auto Lang = Styles[I].Language;
2559 if (Lang == FormatStyle::LK_None)
2561 // Ensure that each language is configured at most once.
2562 for (unsigned J = 0; J < I; ++J) {
2563 if (Lang == Styles[J].Language) {
2564 LLVM_DEBUG(llvm::dbgs()
2565 << "Duplicate languages in the config file on positions "
2566 << J << " and " << I << '\n');
2568 }
2569 }
2570 }
2571
2572 int LanguagePos = -1; // Position of the style for Language.
2573 int CppPos = -1; // Position of the style for C++.
2574 int CPos = -1; // Position of the style for C.
2575
2576 // Search Styles for Language and store the positions of C++ and C styles in
2577 // case Language is not found.
2578 for (unsigned I = 0; I < StyleCount; ++I) {
2579 const auto Lang = Styles[I].Language;
2580 if (Lang == Language) {
2581 LanguagePos = I;
2582 break;
2583 }
2584 if (Lang == FormatStyle::LK_Cpp)
2585 CppPos = I;
2586 else if (Lang == FormatStyle::LK_C)
2587 CPos = I;
2588 }
2589
2590 // If Language is not found, use the default style if there is one. Otherwise,
2591 // use the C style for C++ .h files and for backward compatibility, the C++
2592 // style for .c files.
2593 if (LanguagePos < 0) {
2594 if (Styles[0].Language == FormatStyle::LK_None) // Default style.
2595 LanguagePos = 0;
2596 else if (IsDotHFile && Language == FormatStyle::LK_Cpp)
2597 LanguagePos = CPos;
2598 else if (!IsDotHFile && Language == FormatStyle::LK_C)
2599 LanguagePos = CppPos;
2600 if (LanguagePos < 0)
2602 }
2603
2604 for (const auto &S : llvm::reverse(llvm::drop_begin(Styles)))
2605 Style->StyleSet.Add(S);
2606
2607 *Style = Styles[LanguagePos];
2608
2609 if (LanguagePos == 0) {
2610 if (Style->Language == FormatStyle::LK_None) // Default style.
2611 Style->Language = Language;
2612 Style->StyleSet.Add(*Style);
2613 }
2614
2615 if (Style->InsertTrailingCommas != FormatStyle::TCS_None &&
2616 (Style->PackArguments.BinPack == FormatStyle::BPAS_BinPack ||
2617 Style->PackArguments.BinPack == FormatStyle::BPAS_UseBreakAfter)) {
2618 // See comment on FormatStyle::TSC_Wrapped.
2620 }
2621 if (Style->QualifierAlignment != FormatStyle::QAS_Leave)
2624}
2625
2626std::string configurationAsText(const FormatStyle &Style) {
2627 std::string Text;
2628 llvm::raw_string_ostream Stream(Text);
2629 llvm::yaml::Output Output(Stream);
2630 // We use the same mapping method for input and output, so we need a non-const
2631 // reference here.
2632 FormatStyle NonConstStyle = Style;
2633 expandPresetsBraceWrapping(NonConstStyle);
2634 expandPresetsSpaceBeforeParens(NonConstStyle);
2635 expandPresetsSpacesInParens(NonConstStyle);
2636 Output << NonConstStyle;
2637
2638 return Stream.str();
2639}
2640
2641std::optional<FormatStyle>
2643 if (!Styles)
2644 return std::nullopt;
2645 auto It = Styles->find(Language);
2646 if (It == Styles->end())
2647 return std::nullopt;
2648 FormatStyle Style = It->second;
2649 Style.StyleSet = *this;
2650 return Style;
2651}
2652
2654 assert(Style.Language != LK_None &&
2655 "Cannot add a style for LK_None to a StyleSet");
2656 assert(
2657 !Style.StyleSet.Styles &&
2658 "Cannot add a style associated with an existing StyleSet to a StyleSet");
2659 if (!Styles)
2660 Styles = std::make_shared<MapType>();
2661 (*Styles)[Style.Language] = std::move(Style);
2662}
2663
2664void FormatStyle::FormatStyleSet::Clear() { Styles.reset(); }
2665
2666std::optional<FormatStyle>
2670
2671namespace {
2672
2674 const SourceManager &SourceMgr, tooling::Replacements &Result,
2675 StringRef Text = "") {
2676 const auto &Tok = Token.Tok;
2677 SourceLocation Start;
2678 if (Next && Next->NewlinesBefore == 0 && Next->isNot(tok::eof)) {
2679 Start = Tok.getLocation();
2680 Next->WhitespaceRange = Token.WhitespaceRange;
2681 } else {
2682 Start = Token.WhitespaceRange.getBegin();
2683 }
2684 const auto &Range = CharSourceRange::getCharRange(Start, Tok.getEndLoc());
2685 cantFail(Result.add(tooling::Replacement(SourceMgr, Range, Text)));
2686}
2687
2688class ParensRemover : public TokenAnalyzer {
2689public:
2690 ParensRemover(const Environment &Env, const FormatStyle &Style)
2691 : TokenAnalyzer(Env, Style) {}
2692
2693 std::pair<tooling::Replacements, unsigned>
2694 analyze(TokenAnnotator &Annotator,
2695 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2696 FormatTokenLexer &Tokens) override {
2697 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2698 tooling::Replacements Result;
2699 removeParens(AnnotatedLines, Result);
2700 return {Result, 0};
2701 }
2702
2703private:
2704 void removeParens(SmallVectorImpl<AnnotatedLine *> &Lines,
2705 tooling::Replacements &Result) {
2706 const auto &SourceMgr = Env.getSourceManager();
2707 for (auto *Line : Lines) {
2708 if (!Line->Children.empty())
2709 removeParens(Line->Children, Result);
2710 if (!Line->Affected)
2711 continue;
2712 for (const auto *Token = Line->First; Token && !Token->Finalized;
2713 Token = Token->Next) {
2714 if (Token->Optional && Token->isOneOf(tok::l_paren, tok::r_paren))
2715 replaceToken(*Token, Token->Next, SourceMgr, Result, " ");
2716 }
2717 }
2718 }
2719};
2720
2721class BracesInserter : public TokenAnalyzer {
2722public:
2723 BracesInserter(const Environment &Env, const FormatStyle &Style)
2724 : TokenAnalyzer(Env, Style) {}
2725
2726 std::pair<tooling::Replacements, unsigned>
2727 analyze(TokenAnnotator &Annotator,
2728 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2729 FormatTokenLexer &Tokens) override {
2730 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2731 tooling::Replacements Result;
2732 insertBraces(AnnotatedLines, Result);
2733 return {Result, 0};
2734 }
2735
2736private:
2737 void insertBraces(SmallVectorImpl<AnnotatedLine *> &Lines,
2738 tooling::Replacements &Result) {
2739 const auto &SourceMgr = Env.getSourceManager();
2740 int OpeningBraceSurplus = 0;
2741 for (AnnotatedLine *Line : Lines) {
2742 if (!Line->Children.empty())
2743 insertBraces(Line->Children, Result);
2744 if (!Line->Affected && OpeningBraceSurplus == 0)
2745 continue;
2746 for (FormatToken *Token = Line->First; Token && !Token->Finalized;
2747 Token = Token->Next) {
2748 int BraceCount = Token->BraceCount;
2749 if (BraceCount == 0)
2750 continue;
2751 std::string Brace;
2752 if (BraceCount < 0) {
2753 assert(BraceCount == -1);
2754 // Keep the marker so that the parser doesn't mark the token again in
2755 // a later run.
2756 if (Token->LBraceInserted)
2757 continue;
2758 if (!Line->Affected)
2759 break;
2760 Brace = Token->is(tok::comment) ? "\n{" : "{";
2761 ++OpeningBraceSurplus;
2762 Token->LBraceInserted = true;
2763 } else {
2764 if (OpeningBraceSurplus == 0)
2765 break;
2766 if (OpeningBraceSurplus < BraceCount)
2767 BraceCount = OpeningBraceSurplus;
2768 Brace = '\n' + std::string(BraceCount, '}');
2769 OpeningBraceSurplus -= BraceCount;
2770 Token->BraceCount = 0;
2771 }
2772 const auto Start = Token->Tok.getEndLoc();
2773 cantFail(Result.add(tooling::Replacement(SourceMgr, Start, 0, Brace)));
2774 }
2775 }
2776 assert(OpeningBraceSurplus == 0);
2777 }
2778};
2779
2780class BracesRemover : public TokenAnalyzer {
2781public:
2782 BracesRemover(const Environment &Env, const FormatStyle &Style)
2783 : TokenAnalyzer(Env, Style) {}
2784
2785 std::pair<tooling::Replacements, unsigned>
2786 analyze(TokenAnnotator &Annotator,
2787 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2788 FormatTokenLexer &Tokens) override {
2789 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2790 tooling::Replacements Result;
2791 removeBraces(AnnotatedLines, Result);
2792 return {Result, 0};
2793 }
2794
2795private:
2796 void removeBraces(SmallVectorImpl<AnnotatedLine *> &Lines,
2797 tooling::Replacements &Result) {
2798 const auto &SourceMgr = Env.getSourceManager();
2799 const auto *End = Lines.end();
2800 for (const auto *I = Lines.begin(); I != End; ++I) {
2801 const auto &Line = *I;
2802 if (!Line->Children.empty())
2803 removeBraces(Line->Children, Result);
2804 if (!Line->Affected)
2805 continue;
2806 const auto *NextLine = I + 1 == End ? nullptr : I[1];
2807 for (const auto *Token = Line->First; Token && !Token->Finalized;
2808 Token = Token->Next) {
2809 if (!Token->Optional || Token->isNoneOf(tok::l_brace, tok::r_brace))
2810 continue;
2811 auto *Next = Token->Next;
2812 assert(Next || Token == Line->Last);
2813 if (!Next && NextLine)
2814 Next = NextLine->First;
2815 replaceToken(*Token, Next, SourceMgr, Result);
2816 }
2817 }
2818 }
2819};
2820
2821class SemiRemover : public TokenAnalyzer {
2822public:
2823 SemiRemover(const Environment &Env, const FormatStyle &Style)
2824 : TokenAnalyzer(Env, Style) {}
2825
2826 std::pair<tooling::Replacements, unsigned>
2827 analyze(TokenAnnotator &Annotator,
2828 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2829 FormatTokenLexer &Tokens) override {
2830 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2831 tooling::Replacements Result;
2832 removeSemi(Annotator, AnnotatedLines, Result);
2833 return {Result, 0};
2834 }
2835
2836private:
2837 void removeSemi(TokenAnnotator &Annotator,
2838 SmallVectorImpl<AnnotatedLine *> &Lines,
2839 tooling::Replacements &Result) {
2840 auto PrecededByFunctionRBrace = [](const FormatToken &Tok) {
2841 const auto *Prev = Tok.Previous;
2842 if (!Prev || Prev->isNot(tok::r_brace))
2843 return false;
2844 const auto *LBrace = Prev->MatchingParen;
2845 return LBrace && LBrace->is(TT_FunctionLBrace);
2846 };
2847 const auto &SourceMgr = Env.getSourceManager();
2848 const auto *End = Lines.end();
2849 for (const auto *I = Lines.begin(); I != End; ++I) {
2850 const auto &Line = *I;
2851 if (!Line->Children.empty())
2852 removeSemi(Annotator, Line->Children, Result);
2853 if (!Line->Affected)
2854 continue;
2855 Annotator.calculateFormattingInformation(*Line);
2856 const auto *NextLine = I + 1 == End ? nullptr : I[1];
2857 for (const auto *Token = Line->First; Token && !Token->Finalized;
2858 Token = Token->Next) {
2859 if (Token->isNot(tok::semi) ||
2860 (!Token->Optional && !PrecededByFunctionRBrace(*Token))) {
2861 continue;
2862 }
2863 auto *Next = Token->Next;
2864 assert(Next || Token == Line->Last);
2865 if (!Next && NextLine)
2866 Next = NextLine->First;
2867 replaceToken(*Token, Next, SourceMgr, Result);
2868 }
2869 }
2870 }
2871};
2872
2873class EnumTrailingCommaEditor : public TokenAnalyzer {
2874public:
2875 EnumTrailingCommaEditor(const Environment &Env, const FormatStyle &Style)
2876 : TokenAnalyzer(Env, Style) {}
2877
2878 std::pair<tooling::Replacements, unsigned>
2879 analyze(TokenAnnotator &Annotator,
2880 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2881 FormatTokenLexer &Tokens) override {
2882 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2883 tooling::Replacements Result;
2884 editEnumTrailingComma(AnnotatedLines, Result);
2885 return {Result, 0};
2886 }
2887
2888private:
2889 void editEnumTrailingComma(SmallVectorImpl<AnnotatedLine *> &Lines,
2890 tooling::Replacements &Result) {
2891 bool InEnumBraces = false;
2892 FormatToken *BeforeRBrace = nullptr;
2893 const auto &SourceMgr = Env.getSourceManager();
2894 for (auto *Line : Lines) {
2895 if (!Line->Children.empty())
2896 editEnumTrailingComma(Line->Children, Result);
2897 for (auto *Token = Line->First; Token && !Token->Finalized;
2898 Token = Token->Next) {
2899 if (Token->isNot(TT_EnumRBrace)) {
2900 if (Token->is(TT_EnumLBrace))
2901 InEnumBraces = true;
2902 else if (InEnumBraces && Token->isNot(tok::comment))
2903 BeforeRBrace = Line->Affected ? Token : nullptr;
2904 continue;
2905 }
2906 InEnumBraces = false;
2907 if (!BeforeRBrace || BeforeRBrace->HasEnumTrailingCommaHandled) {
2908 // Empty braces, or Line not affected, or already handled.
2909 continue;
2910 }
2911 if (BeforeRBrace->is(tok::comma)) {
2912 if (Style.EnumTrailingComma == FormatStyle::ETC_Remove)
2913 replaceToken(*BeforeRBrace, BeforeRBrace->Next, SourceMgr, Result);
2914 } else if (Style.EnumTrailingComma == FormatStyle::ETC_Insert &&
2915 BeforeRBrace->isNot(TT_TrailingCommaVaOptRParen)) {
2916 cantFail(Result.add(tooling::Replacement(
2917 SourceMgr, BeforeRBrace->Tok.getEndLoc(), 0, ",")));
2918 }
2919 BeforeRBrace->HasEnumTrailingCommaHandled = true;
2920 BeforeRBrace = nullptr;
2921 }
2922 }
2923 }
2924};
2925
2926class JavaScriptRequoter : public TokenAnalyzer {
2927public:
2928 JavaScriptRequoter(const Environment &Env, const FormatStyle &Style)
2929 : TokenAnalyzer(Env, Style) {}
2930
2931 std::pair<tooling::Replacements, unsigned>
2932 analyze(TokenAnnotator &Annotator,
2933 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
2934 FormatTokenLexer &Tokens) override {
2935 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
2936 tooling::Replacements Result;
2937 requoteJSStringLiteral(AnnotatedLines, Result);
2938 return {Result, 0};
2939 }
2940
2941private:
2942 // Replaces double/single-quoted string literal as appropriate, re-escaping
2943 // the contents in the process.
2944 void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
2945 tooling::Replacements &Result) {
2946 for (AnnotatedLine *Line : Lines) {
2947 requoteJSStringLiteral(Line->Children, Result);
2948 if (!Line->Affected)
2949 continue;
2950 for (FormatToken *FormatTok = Line->First; FormatTok;
2951 FormatTok = FormatTok->Next) {
2952 StringRef Input = FormatTok->TokenText;
2953 if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
2954 // NB: testing for not starting with a double quote to avoid
2955 // breaking `template strings`.
2956 (Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
2957 !Input.starts_with("\"")) ||
2958 (Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
2959 !Input.starts_with("\'"))) {
2960 continue;
2961 }
2962
2963 // Change start and end quote.
2964 bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
2965 SourceLocation Start = FormatTok->Tok.getLocation();
2966 auto Replace = [&](SourceLocation Start, unsigned Length,
2967 StringRef ReplacementText) {
2968 auto Err = Result.add(tooling::Replacement(
2969 Env.getSourceManager(), Start, Length, ReplacementText));
2970 // FIXME: handle error. For now, print error message and skip the
2971 // replacement for release version.
2972 if (Err) {
2973 llvm::errs() << toString(std::move(Err)) << "\n";
2974 assert(false);
2975 }
2976 };
2977 Replace(Start, 1, IsSingle ? "'" : "\"");
2978 Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
2979 IsSingle ? "'" : "\"");
2980
2981 // Escape internal quotes.
2982 bool Escaped = false;
2983 for (size_t i = 1; i < Input.size() - 1; i++) {
2984 switch (Input[i]) {
2985 case '\\':
2986 if (!Escaped && i + 1 < Input.size() &&
2987 ((IsSingle && Input[i + 1] == '"') ||
2988 (!IsSingle && Input[i + 1] == '\''))) {
2989 // Remove this \, it's escaping a " or ' that no longer needs
2990 // escaping
2991 Replace(Start.getLocWithOffset(i), 1, "");
2992 continue;
2993 }
2994 Escaped = !Escaped;
2995 break;
2996 case '\"':
2997 case '\'':
2998 if (!Escaped && IsSingle == (Input[i] == '\'')) {
2999 // Escape the quote.
3000 Replace(Start.getLocWithOffset(i), 0, "\\");
3001 }
3002 Escaped = false;
3003 break;
3004 default:
3005 Escaped = false;
3006 break;
3007 }
3008 }
3009 }
3010 }
3011 }
3012};
3013
3014class Formatter : public TokenAnalyzer {
3015public:
3016 Formatter(const Environment &Env, const FormatStyle &Style,
3017 FormattingAttemptStatus *Status)
3018 : TokenAnalyzer(Env, Style), Status(Status) {}
3019
3020 std::pair<tooling::Replacements, unsigned>
3021 analyze(TokenAnnotator &Annotator,
3022 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3023 FormatTokenLexer &Tokens) override {
3024 tooling::Replacements Result;
3025 deriveLocalStyle(AnnotatedLines);
3026 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
3027 for (AnnotatedLine *Line : AnnotatedLines)
3028 Annotator.calculateFormattingInformation(*Line);
3029 Annotator.setCommentLineLevels(AnnotatedLines);
3030
3031 WhitespaceManager Whitespaces(
3032 Env.getSourceManager(), Style,
3033 Style.LineEnding > FormatStyle::LE_CRLF
3034 ? WhitespaceManager::inputUsesCRLF(
3035 Env.getSourceManager().getBufferData(Env.getFileID()),
3036 Style.LineEnding == FormatStyle::LE_DeriveCRLF)
3037 : Style.LineEnding == FormatStyle::LE_CRLF);
3038 ContinuationIndenter Indenter(Style, Tokens.getKeywords(),
3039 Env.getSourceManager(), Whitespaces, Encoding,
3040 BinPackInconclusiveFunctions);
3041 uint64_t Penalty =
3042 UnwrappedLineFormatter(&Indenter, &Whitespaces, Style,
3043 Tokens.getKeywords(), Env.getSourceManager(),
3044 Status)
3045 .format(AnnotatedLines, /*DryRun=*/false,
3046 /*AdditionalIndent=*/0,
3047 /*FixBadIndentation=*/false,
3048 /*FirstStartColumn=*/Env.getFirstStartColumn(),
3049 /*NextStartColumn=*/Env.getNextStartColumn(),
3050 /*LastStartColumn=*/Env.getLastStartColumn());
3051 for (const auto &R : Whitespaces.generateReplacements())
3052 if (Result.add(R))
3053 return std::make_pair(Result, 0);
3054 return std::make_pair(
3055 Result, static_cast<unsigned>(std::min<uint64_t>(Penalty, UINT_MAX)));
3056 }
3057
3058private:
3059 bool
3060 hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
3061 for (const AnnotatedLine *Line : Lines) {
3062 if (hasCpp03IncompatibleFormat(Line->Children))
3063 return true;
3064 for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
3065 if (!Tok->hasWhitespaceBefore()) {
3066 if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
3067 return true;
3068 if (Tok->is(TT_TemplateCloser) &&
3069 Tok->Previous->is(TT_TemplateCloser)) {
3070 return true;
3071 }
3072 }
3073 }
3074 }
3075 return false;
3076 }
3077
3078 int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
3079 int AlignmentDiff = 0;
3080
3081 for (const AnnotatedLine *Line : Lines) {
3082 AlignmentDiff += countVariableAlignments(Line->Children);
3083
3084 for (const auto *Tok = Line->getFirstNonComment(); Tok; Tok = Tok->Next) {
3085 if (Tok->isNot(TT_PointerOrReference))
3086 continue;
3087
3088 const auto *Prev = Tok->Previous;
3089 const bool PrecededByName = Prev && Prev->Tok.getIdentifierInfo();
3090 const bool SpaceBefore = Tok->hasWhitespaceBefore();
3091
3092 // e.g. `int **`, `int*&`, etc.
3093 while (Tok->Next && Tok->Next->is(TT_PointerOrReference))
3094 Tok = Tok->Next;
3095
3096 const auto *Next = Tok->Next;
3097 const bool FollowedByName = Next && Next->Tok.getIdentifierInfo();
3098 const bool SpaceAfter = Next && Next->hasWhitespaceBefore();
3099
3100 if ((!PrecededByName && !FollowedByName) ||
3101 // e.g. `int * i` or `int*i`
3102 (PrecededByName && FollowedByName && SpaceBefore == SpaceAfter)) {
3103 continue;
3104 }
3105
3106 if ((PrecededByName && SpaceBefore) ||
3107 (FollowedByName && !SpaceAfter)) {
3108 // Right alignment.
3109 ++AlignmentDiff;
3110 } else if ((PrecededByName && !SpaceBefore) ||
3111 (FollowedByName && SpaceAfter)) {
3112 // Left alignment.
3113 --AlignmentDiff;
3114 }
3115 }
3116 }
3117
3118 return AlignmentDiff;
3119 }
3120
3121 void
3122 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
3123 bool HasBinPackedFunction = false;
3124 bool HasOnePerLineFunction = false;
3125 for (AnnotatedLine *Line : AnnotatedLines) {
3126 if (!Line->First->Next)
3127 continue;
3128 FormatToken *Tok = Line->First->Next;
3129 while (Tok->Next) {
3130 if (Tok->is(PPK_BinPacked))
3131 HasBinPackedFunction = true;
3132 if (Tok->is(PPK_OnePerLine))
3133 HasOnePerLineFunction = true;
3134
3135 Tok = Tok->Next;
3136 }
3137 }
3138 if (Style.DerivePointerAlignment) {
3139 const auto NetRightCount = countVariableAlignments(AnnotatedLines);
3140 if (NetRightCount > 0)
3141 Style.PointerAlignment = FormatStyle::PAS_Right;
3142 else if (NetRightCount < 0)
3143 Style.PointerAlignment = FormatStyle::PAS_Left;
3144 Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
3145 }
3146 if (Style.Standard == FormatStyle::LS_Auto) {
3147 Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
3150 }
3151 BinPackInconclusiveFunctions =
3152 HasBinPackedFunction || !HasOnePerLineFunction;
3153 }
3154
3155 bool BinPackInconclusiveFunctions;
3156 FormattingAttemptStatus *Status;
3157};
3158
3159/// TrailingCommaInserter inserts trailing commas into container literals.
3160/// E.g.:
3161/// const x = [
3162/// 1,
3163/// ];
3164/// TrailingCommaInserter runs after formatting. To avoid causing a required
3165/// reformatting (and thus reflow), it never inserts a comma that'd exceed the
3166/// ColumnLimit.
3167///
3168/// Because trailing commas disable binpacking of arrays, TrailingCommaInserter
3169/// is conceptually incompatible with bin packing.
3170class TrailingCommaInserter : public TokenAnalyzer {
3171public:
3172 TrailingCommaInserter(const Environment &Env, const FormatStyle &Style)
3173 : TokenAnalyzer(Env, Style) {}
3174
3175 std::pair<tooling::Replacements, unsigned>
3176 analyze(TokenAnnotator &Annotator,
3177 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3178 FormatTokenLexer &Tokens) override {
3179 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
3180 tooling::Replacements Result;
3181 insertTrailingCommas(AnnotatedLines, Result);
3182 return {Result, 0};
3183 }
3184
3185private:
3186 /// Inserts trailing commas in [] and {} initializers if they wrap over
3187 /// multiple lines.
3188 void insertTrailingCommas(SmallVectorImpl<AnnotatedLine *> &Lines,
3189 tooling::Replacements &Result) {
3190 for (AnnotatedLine *Line : Lines) {
3191 insertTrailingCommas(Line->Children, Result);
3192 if (!Line->Affected)
3193 continue;
3194 for (FormatToken *FormatTok = Line->First; FormatTok;
3195 FormatTok = FormatTok->Next) {
3196 if (FormatTok->NewlinesBefore == 0)
3197 continue;
3198 FormatToken *Matching = FormatTok->MatchingParen;
3199 if (!Matching || !FormatTok->getPreviousNonComment())
3200 continue;
3201 if (!(FormatTok->is(tok::r_square) &&
3202 Matching->is(TT_ArrayInitializerLSquare)) &&
3203 !(FormatTok->is(tok::r_brace) && Matching->is(TT_DictLiteral))) {
3204 continue;
3205 }
3206 FormatToken *Prev = FormatTok->getPreviousNonComment();
3207 if (Prev->is(tok::comma) || Prev->is(tok::semi))
3208 continue;
3209 // getEndLoc is not reliably set during re-lexing, use text length
3210 // instead.
3211 SourceLocation Start =
3212 Prev->Tok.getLocation().getLocWithOffset(Prev->TokenText.size());
3213 // If inserting a comma would push the code over the column limit, skip
3214 // this location - it'd introduce an unstable formatting due to the
3215 // required reflow.
3216 unsigned ColumnNumber =
3217 Env.getSourceManager().getSpellingColumnNumber(Start);
3218 if (ColumnNumber > Style.ColumnLimit)
3219 continue;
3220 // Comma insertions cannot conflict with each other, and this pass has a
3221 // clean set of Replacements, so the operation below cannot fail.
3222 cantFail(Result.add(
3223 tooling::Replacement(Env.getSourceManager(), Start, 0, ",")));
3224 }
3225 }
3226 }
3227};
3228
3229// This class clean up the erroneous/redundant code around the given ranges in
3230// file.
3231class Cleaner : public TokenAnalyzer {
3232public:
3233 Cleaner(const Environment &Env, const FormatStyle &Style)
3234 : TokenAnalyzer(Env, Style),
3235 DeletedTokens(FormatTokenLess(Env.getSourceManager())) {}
3236
3237 // FIXME: eliminate unused parameters.
3238 std::pair<tooling::Replacements, unsigned>
3239 analyze(TokenAnnotator &Annotator,
3240 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3241 FormatTokenLexer &Tokens) override {
3242 // FIXME: in the current implementation the granularity of affected range
3243 // is an annotated line. However, this is not sufficient. Furthermore,
3244 // redundant code introduced by replacements does not necessarily
3245 // intercept with ranges of replacements that result in the redundancy.
3246 // To determine if some redundant code is actually introduced by
3247 // replacements(e.g. deletions), we need to come up with a more
3248 // sophisticated way of computing affected ranges.
3249 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
3250
3251 checkEmptyNamespace(AnnotatedLines);
3252
3253 for (auto *Line : AnnotatedLines)
3254 cleanupLine(Line);
3255
3256 return {generateFixes(), 0};
3257 }
3258
3259private:
3260 void cleanupLine(AnnotatedLine *Line) {
3261 for (auto *Child : Line->Children)
3262 cleanupLine(Child);
3263
3264 if (Line->Affected) {
3265 cleanupRight(Line->First, tok::comma, tok::comma);
3266 cleanupRight(Line->First, TT_CtorInitializerColon, tok::comma);
3267 cleanupRight(Line->First, tok::l_paren, tok::comma);
3268 cleanupLeft(Line->First, tok::comma, tok::r_paren);
3269 cleanupLeft(Line->First, TT_CtorInitializerComma, tok::l_brace);
3270 cleanupLeft(Line->First, TT_CtorInitializerColon, tok::l_brace);
3271 cleanupLeft(Line->First, TT_CtorInitializerColon, tok::equal);
3272 }
3273 }
3274
3275 bool containsOnlyComments(const AnnotatedLine &Line) {
3276 for (FormatToken *Tok = Line.First; Tok; Tok = Tok->Next)
3277 if (Tok->isNot(tok::comment))
3278 return false;
3279 return true;
3280 }
3281
3282 // Iterate through all lines and remove any empty (nested) namespaces.
3283 void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
3284 std::set<unsigned> DeletedLines;
3285 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
3286 auto &Line = *AnnotatedLines[i];
3287 if (Line.startsWithNamespace())
3288 checkEmptyNamespace(AnnotatedLines, i, i, DeletedLines);
3289 }
3290
3291 for (auto Line : DeletedLines) {
3292 FormatToken *Tok = AnnotatedLines[Line]->First;
3293 while (Tok) {
3294 deleteToken(Tok);
3295 Tok = Tok->Next;
3296 }
3297 }
3298 }
3299
3300 // The function checks if the namespace, which starts from \p CurrentLine, and
3301 // its nested namespaces are empty and delete them if they are empty. It also
3302 // sets \p NewLine to the last line checked.
3303 // Returns true if the current namespace is empty.
3304 bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3305 unsigned CurrentLine, unsigned &NewLine,
3306 std::set<unsigned> &DeletedLines) {
3307 unsigned InitLine = CurrentLine, End = AnnotatedLines.size();
3308 if (Style.BraceWrapping.AfterNamespace) {
3309 // If the left brace is in a new line, we should consume it first so that
3310 // it does not make the namespace non-empty.
3311 // FIXME: error handling if there is no left brace.
3312 if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
3313 NewLine = CurrentLine;
3314 return false;
3315 }
3316 } else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
3317 return false;
3318 }
3319 while (++CurrentLine < End) {
3320 if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
3321 break;
3322
3323 if (AnnotatedLines[CurrentLine]->startsWithNamespace()) {
3324 if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine,
3325 DeletedLines)) {
3326 return false;
3327 }
3328 CurrentLine = NewLine;
3329 continue;
3330 }
3331
3332 if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
3333 continue;
3334
3335 // If there is anything other than comments or nested namespaces in the
3336 // current namespace, the namespace cannot be empty.
3337 NewLine = CurrentLine;
3338 return false;
3339 }
3340
3341 NewLine = CurrentLine;
3342 if (CurrentLine >= End)
3343 return false;
3344
3345 // Check if the empty namespace is actually affected by changed ranges.
3346 if (!AffectedRangeMgr.affectsCharSourceRange(CharSourceRange::getCharRange(
3347 AnnotatedLines[InitLine]->First->Tok.getLocation(),
3348 AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc()))) {
3349 return false;
3350 }
3351
3352 for (unsigned i = InitLine; i <= CurrentLine; ++i)
3353 DeletedLines.insert(i);
3354
3355 return true;
3356 }
3357
3358 // Checks pairs {start, start->next},..., {end->previous, end} and deletes one
3359 // of the token in the pair if the left token has \p LK token kind and the
3360 // right token has \p RK token kind. If \p DeleteLeft is true, the left token
3361 // is deleted on match; otherwise, the right token is deleted.
3362 template <typename LeftKind, typename RightKind>
3363 void cleanupPair(FormatToken *Start, LeftKind LK, RightKind RK,
3364 bool DeleteLeft) {
3365 auto NextNotDeleted = [this](const FormatToken &Tok) -> FormatToken * {
3366 for (auto *Res = Tok.Next; Res; Res = Res->Next) {
3367 if (Res->isNot(tok::comment) &&
3368 DeletedTokens.find(Res) == DeletedTokens.end()) {
3369 return Res;
3370 }
3371 }
3372 return nullptr;
3373 };
3374 for (auto *Left = Start; Left;) {
3375 auto *Right = NextNotDeleted(*Left);
3376 if (!Right)
3377 break;
3378 if (Left->is(LK) && Right->is(RK)) {
3379 deleteToken(DeleteLeft ? Left : Right);
3380 for (auto *Tok = Left->Next; Tok && Tok != Right; Tok = Tok->Next)
3381 deleteToken(Tok);
3382 // If the right token is deleted, we should keep the left token
3383 // unchanged and pair it with the new right token.
3384 if (!DeleteLeft)
3385 continue;
3386 }
3387 Left = Right;
3388 }
3389 }
3390
3391 template <typename LeftKind, typename RightKind>
3392 void cleanupLeft(FormatToken *Start, LeftKind LK, RightKind RK) {
3393 cleanupPair(Start, LK, RK, /*DeleteLeft=*/true);
3394 }
3395
3396 template <typename LeftKind, typename RightKind>
3397 void cleanupRight(FormatToken *Start, LeftKind LK, RightKind RK) {
3398 cleanupPair(Start, LK, RK, /*DeleteLeft=*/false);
3399 }
3400
3401 // Delete the given token.
3402 inline void deleteToken(FormatToken *Tok) {
3403 if (Tok)
3404 DeletedTokens.insert(Tok);
3405 }
3406
3407 tooling::Replacements generateFixes() {
3408 tooling::Replacements Fixes;
3409 SmallVector<FormatToken *> Tokens;
3410 std::copy(DeletedTokens.begin(), DeletedTokens.end(),
3411 std::back_inserter(Tokens));
3412
3413 // Merge multiple continuous token deletions into one big deletion so that
3414 // the number of replacements can be reduced. This makes computing affected
3415 // ranges more efficient when we run reformat on the changed code.
3416 unsigned Idx = 0;
3417 while (Idx < Tokens.size()) {
3418 unsigned St = Idx, End = Idx;
3419 while ((End + 1) < Tokens.size() && Tokens[End]->Next == Tokens[End + 1])
3420 ++End;
3421 auto SR = CharSourceRange::getCharRange(Tokens[St]->Tok.getLocation(),
3422 Tokens[End]->Tok.getEndLoc());
3423 auto Err =
3424 Fixes.add(tooling::Replacement(Env.getSourceManager(), SR, ""));
3425 // FIXME: better error handling. for now just print error message and skip
3426 // for the release version.
3427 if (Err) {
3428 llvm::errs() << toString(std::move(Err)) << "\n";
3429 assert(false && "Fixes must not conflict!");
3430 }
3431 Idx = End + 1;
3432 }
3433
3434 return Fixes;
3435 }
3436
3437 // Class for less-than inequality comparason for the set `RedundantTokens`.
3438 // We store tokens in the order they appear in the translation unit so that
3439 // we do not need to sort them in `generateFixes()`.
3440 struct FormatTokenLess {
3441 FormatTokenLess(const SourceManager &SM) : SM(SM) {}
3442
3443 bool operator()(const FormatToken *LHS, const FormatToken *RHS) const {
3444 return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(),
3445 RHS->Tok.getLocation());
3446 }
3447 const SourceManager &SM;
3448 };
3449
3450 // Tokens to be deleted.
3451 std::set<FormatToken *, FormatTokenLess> DeletedTokens;
3452};
3453
3454class ObjCHeaderStyleGuesser : public TokenAnalyzer {
3455public:
3456 ObjCHeaderStyleGuesser(const Environment &Env, const FormatStyle &Style)
3457 : TokenAnalyzer(Env, Style), IsObjC(false) {}
3458
3459 std::pair<tooling::Replacements, unsigned>
3460 analyze(TokenAnnotator &Annotator,
3461 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3462 FormatTokenLexer &Tokens) override {
3463 assert(Style.Language == FormatStyle::LK_Cpp);
3464 IsObjC = guessIsObjC(Env.getSourceManager(), AnnotatedLines,
3465 Tokens.getKeywords());
3466 tooling::Replacements Result;
3467 return {Result, 0};
3468 }
3469
3470 bool isObjC() { return IsObjC; }
3471
3472private:
3473 static bool
3474 guessIsObjC(const SourceManager &SourceManager,
3475 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
3476 const AdditionalKeywords &Keywords) {
3477 // Keep this array sorted, since we are binary searching over it.
3478 static constexpr llvm::StringLiteral FoundationIdentifiers[] = {
3479 "CGFloat",
3480 "CGPoint",
3481 "CGPointMake",
3482 "CGPointZero",
3483 "CGRect",
3484 "CGRectEdge",
3485 "CGRectInfinite",
3486 "CGRectMake",
3487 "CGRectNull",
3488 "CGRectZero",
3489 "CGSize",
3490 "CGSizeMake",
3491 "CGVector",
3492 "CGVectorMake",
3493 "FOUNDATION_EXPORT", // This is an alias for FOUNDATION_EXTERN.
3494 "FOUNDATION_EXTERN",
3495 "NSAffineTransform",
3496 "NSArray",
3497 "NSAttributedString",
3498 "NSBlockOperation",
3499 "NSBundle",
3500 "NSCache",
3501 "NSCalendar",
3502 "NSCharacterSet",
3503 "NSCountedSet",
3504 "NSData",
3505 "NSDataDetector",
3506 "NSDecimal",
3507 "NSDecimalNumber",
3508 "NSDictionary",
3509 "NSEdgeInsets",
3510 "NSError",
3511 "NSErrorDomain",
3512 "NSHashTable",
3513 "NSIndexPath",
3514 "NSIndexSet",
3515 "NSInteger",
3516 "NSInvocationOperation",
3517 "NSLocale",
3518 "NSMapTable",
3519 "NSMutableArray",
3520 "NSMutableAttributedString",
3521 "NSMutableCharacterSet",
3522 "NSMutableData",
3523 "NSMutableDictionary",
3524 "NSMutableIndexSet",
3525 "NSMutableOrderedSet",
3526 "NSMutableSet",
3527 "NSMutableString",
3528 "NSNumber",
3529 "NSNumberFormatter",
3530 "NSObject",
3531 "NSOperation",
3532 "NSOperationQueue",
3533 "NSOperationQueuePriority",
3534 "NSOrderedSet",
3535 "NSPoint",
3536 "NSPointerArray",
3537 "NSQualityOfService",
3538 "NSRange",
3539 "NSRect",
3540 "NSRegularExpression",
3541 "NSSet",
3542 "NSSize",
3543 "NSString",
3544 "NSTimeZone",
3545 "NSUInteger",
3546 "NSURL",
3547 "NSURLComponents",
3548 "NSURLQueryItem",
3549 "NSUUID",
3550 "NSValue",
3551 "NS_ASSUME_NONNULL_BEGIN",
3552 "UIImage",
3553 "UIView",
3554 };
3555 assert(llvm::is_sorted(FoundationIdentifiers));
3556
3557 for (auto *Line : AnnotatedLines) {
3558 if (Line->First && (Line->First->TokenText.starts_with("#") ||
3559 Line->First->TokenText == "__pragma" ||
3560 Line->First->TokenText == "_Pragma")) {
3561 continue;
3562 }
3563 for (const FormatToken *FormatTok = Line->First; FormatTok;
3564 FormatTok = FormatTok->Next) {
3565 if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) &&
3566 (FormatTok->isNot(tok::objc_not_keyword) ||
3567 FormatTok->isOneOf(tok::numeric_constant, tok::l_square,
3568 tok::l_brace))) ||
3569 (FormatTok->Tok.isAnyIdentifier() &&
3570 llvm::binary_search(FoundationIdentifiers,
3571 FormatTok->TokenText)) ||
3572 FormatTok->is(TT_ObjCStringLiteral) ||
3573 FormatTok->isOneOf(Keywords.kw_NS_CLOSED_ENUM, Keywords.kw_NS_ENUM,
3574 Keywords.kw_NS_ERROR_ENUM,
3575 Keywords.kw_NS_OPTIONS, TT_ObjCBlockLBrace,
3576 TT_ObjCBlockLParen, TT_ObjCDecl, TT_ObjCForIn,
3577 TT_ObjCMethodExpr, TT_ObjCMethodSpecifier,
3578 TT_ObjCProperty, TT_ObjCSelector)) {
3579 LLVM_DEBUG(llvm::dbgs()
3580 << "Detected ObjC at location "
3581 << FormatTok->Tok.getLocation().printToString(
3582 SourceManager)
3583 << " token: " << FormatTok->TokenText << " token type: "
3584 << getTokenTypeName(FormatTok->getType()) << "\n");
3585 return true;
3586 }
3587 }
3588 if (guessIsObjC(SourceManager, Line->Children, Keywords))
3589 return true;
3590 }
3591 return false;
3592 }
3593
3594 bool IsObjC;
3595};
3596
3597struct IncludeDirective {
3598 StringRef Filename;
3599 StringRef Text;
3600 unsigned Offset;
3601 int Category;
3602 int Priority;
3603};
3604
3605struct JavaImportDirective {
3606 StringRef Identifier;
3607 StringRef Text;
3608 unsigned Offset;
3609 SmallVector<StringRef> AssociatedCommentLines;
3610 bool IsStatic;
3611};
3612
3613} // end anonymous namespace
3614
3615// Determines whether 'Ranges' intersects with ('Start', 'End').
3616static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
3617 unsigned End) {
3618 for (const auto &Range : Ranges) {
3619 if (Range.getOffset() < End &&
3620 Range.getOffset() + Range.getLength() > Start) {
3621 return true;
3622 }
3623 }
3624 return false;
3625}
3626
3627// Returns a pair (Index, OffsetToEOL) describing the position of the cursor
3628// before sorting/deduplicating. Index is the index of the include under the
3629// cursor in the original set of includes. If this include has duplicates, it is
3630// the index of the first of the duplicates as the others are going to be
3631// removed. OffsetToEOL describes the cursor's position relative to the end of
3632// its current line.
3633// If `Cursor` is not on any #include, `Index` will be
3634// std::numeric_limits<unsigned>::max().
3635static std::pair<unsigned, unsigned>
3637 const ArrayRef<unsigned> &Indices, unsigned Cursor) {
3638 unsigned CursorIndex = std::numeric_limits<unsigned>::max();
3639 unsigned OffsetToEOL = 0;
3640 for (int i = 0, e = Includes.size(); i != e; ++i) {
3641 unsigned Start = Includes[Indices[i]].Offset;
3642 unsigned End = Start + Includes[Indices[i]].Text.size();
3643 if (!(Cursor >= Start && Cursor < End))
3644 continue;
3645 CursorIndex = Indices[i];
3646 OffsetToEOL = End - Cursor;
3647 // Put the cursor on the only remaining #include among the duplicate
3648 // #includes.
3649 while (--i >= 0 && Includes[CursorIndex].Text == Includes[Indices[i]].Text)
3650 CursorIndex = i;
3651 break;
3652 }
3653 return std::make_pair(CursorIndex, OffsetToEOL);
3654}
3655
3656// Replace all "\r\n" with "\n".
3657std::string replaceCRLF(const std::string &Code) {
3658 std::string NewCode;
3659 size_t Pos = 0, LastPos = 0;
3660
3661 do {
3662 Pos = Code.find("\r\n", LastPos);
3663 if (Pos == LastPos) {
3664 ++LastPos;
3665 continue;
3666 }
3667 if (Pos == std::string::npos) {
3668 NewCode += Code.substr(LastPos);
3669 break;
3670 }
3671 NewCode += Code.substr(LastPos, Pos - LastPos) + "\n";
3672 LastPos = Pos + 2;
3673 } while (Pos != std::string::npos);
3674
3675 return NewCode;
3676}
3677
3678// Sorts and deduplicate a block of includes given by 'Includes' alphabetically
3679// adding the necessary replacement to 'Replaces'. 'Includes' must be in strict
3680// source order.
3681// #include directives with the same text will be deduplicated, and only the
3682// first #include in the duplicate #includes remains. If the `Cursor` is
3683// provided and put on a deleted #include, it will be moved to the remaining
3684// #include in the duplicate #includes.
3685static void sortCppIncludes(const FormatStyle &Style,
3686 const ArrayRef<IncludeDirective> &Includes,
3687 ArrayRef<tooling::Range> Ranges, StringRef FileName,
3688 StringRef Code, tooling::Replacements &Replaces,
3689 unsigned *Cursor) {
3690 tooling::IncludeCategoryManager Categories(Style.IncludeStyle, FileName);
3691 const unsigned IncludesBeginOffset = Includes.front().Offset;
3692 const unsigned IncludesEndOffset =
3693 Includes.back().Offset + Includes.back().Text.size();
3694 const unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset;
3695 if (!affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset))
3696 return;
3698 llvm::to_vector<16>(llvm::seq<unsigned>(0, Includes.size()));
3699
3700 if (Style.SortIncludes.Enabled) {
3701 stable_sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
3702 if (Includes[LHSI].Priority != Includes[RHSI].Priority)
3703 return Includes[LHSI].Priority < Includes[RHSI].Priority;
3704
3705 auto LHSStem = Includes[LHSI].Filename;
3706 auto RHSStem = Includes[RHSI].Filename;
3707
3708 SmallString<128> LHSStemStorage, RHSStemStorage;
3709 if (Style.SortIncludes.IgnoreExtension) {
3710 LHSStemStorage = Includes[LHSI].Filename;
3711 RHSStemStorage = Includes[RHSI].Filename;
3712 llvm::sys::path::replace_extension(LHSStemStorage, "");
3713 llvm::sys::path::replace_extension(RHSStemStorage, "");
3714 LHSStem = LHSStemStorage;
3715 RHSStem = RHSStemStorage;
3716 }
3717
3718 std::string LHSStemLower, RHSStemLower;
3719 std::string LHSFilenameLower, RHSFilenameLower;
3720 if (Style.SortIncludes.IgnoreCase) {
3721 LHSStemLower = LHSStem.lower();
3722 RHSStemLower = RHSStem.lower();
3723 LHSFilenameLower = Includes[LHSI].Filename.lower();
3724 RHSFilenameLower = Includes[RHSI].Filename.lower();
3725 }
3726
3727 const auto Compare = Style.SortIncludes.Natural
3728 ? &StringRef::compare_numeric
3729 : &StringRef::compare;
3730
3731 while (Style.SortIncludes.FilesBeforeFolders) {
3732 auto [LHead, LTail] = LHSStem.split('/');
3733 auto [RHead, RTail] = RHSStem.split('/');
3734
3735 bool LIsFile = LTail.empty();
3736 bool RIsFile = RTail.empty();
3737
3738 // A file at this level sorts before a subdirectory at this level.
3739 if (LIsFile != RIsFile)
3740 return LIsFile;
3741
3742 // Both are leaf filenames — they are equal at this level, so we
3743 // can break out of the loop and compare the full filenames later.
3744 if (LIsFile)
3745 break;
3746
3747 // Both are directory components at this level — compare them.
3748 if (Style.SortIncludes.IgnoreCase) {
3749 int Cmp = std::invoke(Compare, StringRef(LHead.lower()),
3750 StringRef(RHead.lower()));
3751 if (Cmp != 0)
3752 return Cmp < 0;
3753 }
3754 if (int Cmp = std::invoke(Compare, LHead, RHead); Cmp != 0)
3755 return Cmp < 0;
3756
3757 // Directory components are equal; descend into the next level.
3758 LHSStem = LTail;
3759 RHSStem = RTail;
3760 }
3761
3762 if (Style.SortIncludes.IgnoreCase) {
3763 int Cmp = std::invoke(Compare, StringRef(LHSStemLower), RHSStemLower);
3764 if (Cmp != 0)
3765 return Cmp < 0;
3766 }
3767
3768 if (int Cmp = std::invoke(Compare, LHSStem, RHSStem); Cmp != 0)
3769 return Cmp < 0;
3770
3771 if (Style.SortIncludes.IgnoreCase) {
3772 int Cmp =
3773 std::invoke(Compare, StringRef(LHSFilenameLower), RHSFilenameLower);
3774 if (Cmp != 0)
3775 return Cmp < 0;
3776 }
3777 return std::invoke(Compare, Includes[LHSI].Filename,
3778 Includes[RHSI].Filename) < 0;
3779 });
3780 }
3781
3782 // The index of the include on which the cursor will be put after
3783 // sorting/deduplicating.
3784 unsigned CursorIndex;
3785 // The offset from cursor to the end of line.
3786 unsigned CursorToEOLOffset;
3787 if (Cursor) {
3788 std::tie(CursorIndex, CursorToEOLOffset) =
3789 FindCursorIndex(Includes, Indices, *Cursor);
3790 }
3791
3792 // Deduplicate #includes.
3793 Indices.erase(llvm::unique(Indices,
3794 [&](unsigned LHSI, unsigned RHSI) {
3795 return Includes[LHSI].Text.trim() ==
3796 Includes[RHSI].Text.trim();
3797 }),
3798 Indices.end());
3799
3800 int CurrentCategory = Includes.front().Category;
3801 const auto TopLevelDirectory = [](StringRef Filename) {
3802 Filename = Filename.drop_front(); // Strip leading '"' or '<'.
3803 const size_t SlashPos = Filename.find('/');
3804 return SlashPos == StringRef::npos ? StringRef()
3805 : Filename.take_front(SlashPos);
3806 };
3807 StringRef CurrentDirectory = TopLevelDirectory(Includes.front().Filename);
3808 const auto DirectoryChanged = [&](StringRef Filename) {
3809 const StringRef Directory = TopLevelDirectory(Filename);
3810 return Style.SortIncludes.IgnoreCase
3811 ? !CurrentDirectory.equals_insensitive(Directory)
3812 : CurrentDirectory != Directory;
3813 };
3814
3815 // If the #includes are out of order, we generate a single replacement fixing
3816 // the entire block. Otherwise, no replacement is generated.
3817 // In case Style.IncldueStyle.IncludeBlocks != IBS_Preserve, this check is not
3818 // enough as additional newlines might be added or removed across #include
3819 // blocks. This we handle below by generating the updated #include blocks and
3820 // comparing it to the original.
3821 if (Indices.size() == Includes.size() && is_sorted(Indices) &&
3822 Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Preserve) {
3823 return;
3824 }
3825
3826 const auto OldCursor = Cursor ? *Cursor : 0;
3827 std::string result;
3828 for (unsigned Index : Indices) {
3829 if (!result.empty()) {
3830 result += "\n";
3831 if (Style.IncludeStyle.IncludeBlocks ==
3833 CurrentCategory != Includes[Index].Category) {
3834 result += "\n";
3835 } else if (Style.IncludeStyle.IncludeBlocks ==
3837 (CurrentCategory != Includes[Index].Category ||
3838 DirectoryChanged(Includes[Index].Filename))) {
3839 result += "\n";
3840 }
3841 }
3842 result += Includes[Index].Text;
3843 if (Cursor && CursorIndex == Index)
3844 *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
3845 CurrentCategory = Includes[Index].Category;
3846 CurrentDirectory = TopLevelDirectory(Includes[Index].Filename);
3847 }
3848
3849 if (Cursor && *Cursor >= IncludesEndOffset)
3850 *Cursor += result.size() - IncludesBlockSize;
3851
3852 // If the #includes are out of order, we generate a single replacement fixing
3853 // the entire range of blocks. Otherwise, no replacement is generated.
3854 if (replaceCRLF(result) == replaceCRLF(std::string(Code.substr(
3855 IncludesBeginOffset, IncludesBlockSize)))) {
3856 if (Cursor)
3857 *Cursor = OldCursor;
3858 return;
3859 }
3860
3861 auto Err = Replaces.add(tooling::Replacement(
3862 FileName, Includes.front().Offset, IncludesBlockSize, result));
3863 // FIXME: better error handling. For now, just skip the replacement for the
3864 // release version.
3865 if (Err) {
3866 llvm::errs() << toString(std::move(Err)) << "\n";
3867 assert(false);
3868 }
3869}
3870
3873 StringRef FileName,
3874 tooling::Replacements &Replaces,
3875 unsigned *Cursor) {
3876 unsigned Prev = llvm::StringSwitch<size_t>(Code)
3877 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
3878 .Default(0);
3879 unsigned SearchFrom = 0;
3881 SmallVector<IncludeDirective, 16> IncludesInBlock;
3882
3883 // In compiled files, consider the first #include to be the main #include of
3884 // the file if it is not a system #include. This ensures that the header
3885 // doesn't have hidden dependencies
3886 // (http://llvm.org/docs/CodingStandards.html#include-style).
3887 //
3888 // FIXME: Do some validation, e.g. edit distance of the base name, to fix
3889 // cases where the first #include is unlikely to be the main header.
3890 tooling::IncludeCategoryManager Categories(Style.IncludeStyle, FileName);
3891 bool FirstIncludeBlock = true;
3892 bool MainIncludeFound = false;
3893 bool FormattingOff = false;
3894
3895 // '[' must be the first and '-' the last character inside [...].
3896 llvm::Regex RawStringRegex(
3897 "R\"([][A-Za-z0-9_{}#<>%:;.?*+/^&\\$|~!=,'-]*)\\(");
3898 SmallVector<StringRef, 2> RawStringMatches;
3899 std::string RawStringTermination = ")\"";
3900
3901 for (const auto Size = Code.size(); SearchFrom < Size;) {
3902 size_t Pos = SearchFrom;
3903 if (Code[SearchFrom] != '\n') {
3904 do { // Search for the first newline while skipping line splices.
3905 ++Pos;
3906 Pos = Code.find('\n', Pos);
3907 } while (Pos != StringRef::npos && Code[Pos - 1] == '\\');
3908 }
3909
3910 StringRef Line =
3911 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
3912
3913 StringRef Trimmed = Line.trim();
3914
3915 // #includes inside raw string literals need to be ignored.
3916 // or we will sort the contents of the string.
3917 // Skip past until we think we are at the rawstring literal close.
3918 if (RawStringRegex.match(Trimmed, &RawStringMatches)) {
3919 std::string CharSequence = RawStringMatches[1].str();
3920 RawStringTermination = ")" + CharSequence + "\"";
3921 FormattingOff = true;
3922 }
3923
3924 if (Trimmed.contains(RawStringTermination))
3925 FormattingOff = false;
3926
3927 bool IsBlockComment = false;
3928
3929 if (isClangFormatOff(Trimmed)) {
3930 FormattingOff = true;
3931 } else if (isClangFormatOn(Trimmed)) {
3932 FormattingOff = false;
3933 } else if (Trimmed.starts_with("/*")) {
3934 IsBlockComment = true;
3935 Pos = Code.find("*/", SearchFrom + 2);
3936 }
3937
3938 const bool EmptyLineSkipped =
3939 Trimmed.empty() &&
3940 (Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Merge ||
3941 Style.IncludeStyle.IncludeBlocks ==
3943 Style.IncludeStyle.IncludeBlocks ==
3945
3946 bool MergeWithNextLine = Trimmed.ends_with("\\");
3947 if (!FormattingOff && !MergeWithNextLine) {
3948 if (!IsBlockComment &&
3949 tooling::HeaderIncludes::IncludeRegex.match(Trimmed, &Matches)) {
3950 StringRef IncludeName = Matches[2];
3951 if (Trimmed.contains("/*") && !Trimmed.contains("*/")) {
3952 // #include with a start of a block comment, but without the end.
3953 // Need to keep all the lines until the end of the comment together.
3954 // FIXME: This is somehow simplified check that probably does not work
3955 // correctly if there are multiple comments on a line.
3956 Pos = Code.find("*/", SearchFrom);
3957 Line = Code.substr(
3958 Prev, (Pos != StringRef::npos ? Pos + 2 : Code.size()) - Prev);
3959 }
3960 int Category = Categories.getIncludePriority(
3961 IncludeName,
3962 /*CheckMainHeader=*/!MainIncludeFound && FirstIncludeBlock);
3963 int Priority = Categories.getSortIncludePriority(
3964 IncludeName, !MainIncludeFound && FirstIncludeBlock);
3965 if (Category == 0)
3966 MainIncludeFound = true;
3967 IncludesInBlock.push_back(
3968 {IncludeName, Line, Prev, Category, Priority});
3969 } else if (!IncludesInBlock.empty() && !EmptyLineSkipped) {
3970 sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Code,
3971 Replaces, Cursor);
3972 IncludesInBlock.clear();
3973 if (Trimmed.starts_with("#pragma hdrstop")) // Precompiled headers.
3974 FirstIncludeBlock = true;
3975 else
3976 FirstIncludeBlock = false;
3977 }
3978 }
3979 if (Pos == StringRef::npos || Pos + 1 == Code.size())
3980 break;
3981
3982 if (!MergeWithNextLine)
3983 Prev = Pos + 1;
3984 SearchFrom = Pos + 1;
3985 }
3986 if (!IncludesInBlock.empty()) {
3987 sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Code, Replaces,
3988 Cursor);
3989 }
3990 return Replaces;
3991}
3992
3993// Returns group number to use as a first order sort on imports. Gives
3994// std::numeric_limits<unsigned>::max() if the import does not match any given
3995// groups.
3996static unsigned findJavaImportGroup(const FormatStyle &Style,
3997 StringRef ImportIdentifier) {
3998 unsigned LongestMatchIndex = std::numeric_limits<unsigned>::max();
3999 unsigned LongestMatchLength = 0;
4000 for (unsigned I = 0; I < Style.JavaImportGroups.size(); I++) {
4001 const std::string &GroupPrefix = Style.JavaImportGroups[I];
4002 if (ImportIdentifier.starts_with(GroupPrefix) &&
4003 GroupPrefix.length() > LongestMatchLength) {
4004 LongestMatchIndex = I;
4005 LongestMatchLength = GroupPrefix.length();
4006 }
4007 }
4008 return LongestMatchIndex;
4009}
4010
4011// Sorts and deduplicates a block of includes given by 'Imports' based on
4012// JavaImportGroups, then adding the necessary replacement to 'Replaces'.
4013// Import declarations with the same text will be deduplicated. Between each
4014// import group, a newline is inserted, and within each import group, a
4015// lexicographic sort based on ASCII value is performed.
4016static void sortJavaImports(const FormatStyle &Style,
4017 const ArrayRef<JavaImportDirective> &Imports,
4018 ArrayRef<tooling::Range> Ranges, StringRef FileName,
4019 StringRef Code, tooling::Replacements &Replaces) {
4020 unsigned ImportsBeginOffset = Imports.front().Offset;
4021 unsigned ImportsEndOffset =
4022 Imports.back().Offset + Imports.back().Text.size();
4023 unsigned ImportsBlockSize = ImportsEndOffset - ImportsBeginOffset;
4024 if (!affectsRange(Ranges, ImportsBeginOffset, ImportsEndOffset))
4025 return;
4026
4028 llvm::to_vector<16>(llvm::seq<unsigned>(0, Imports.size()));
4030 JavaImportGroups.reserve(Imports.size());
4031 for (const JavaImportDirective &Import : Imports)
4032 JavaImportGroups.push_back(findJavaImportGroup(Style, Import.Identifier));
4033
4034 bool StaticImportAfterNormalImport =
4035 Style.SortJavaStaticImport == FormatStyle::SJSIO_After;
4036 sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
4037 // Negating IsStatic to push static imports above non-static imports.
4038 return std::make_tuple(!Imports[LHSI].IsStatic ^
4039 StaticImportAfterNormalImport,
4040 JavaImportGroups[LHSI], Imports[LHSI].Identifier) <
4041 std::make_tuple(!Imports[RHSI].IsStatic ^
4042 StaticImportAfterNormalImport,
4043 JavaImportGroups[RHSI], Imports[RHSI].Identifier);
4044 });
4045
4046 // Deduplicate imports.
4047 Indices.erase(llvm::unique(Indices,
4048 [&](unsigned LHSI, unsigned RHSI) {
4049 return Imports[LHSI].Text == Imports[RHSI].Text;
4050 }),
4051 Indices.end());
4052
4053 bool CurrentIsStatic = Imports[Indices.front()].IsStatic;
4054 unsigned CurrentImportGroup = JavaImportGroups[Indices.front()];
4055
4056 std::string result;
4057 for (unsigned Index : Indices) {
4058 if (!result.empty()) {
4059 result += "\n";
4060 if (CurrentIsStatic != Imports[Index].IsStatic ||
4061 CurrentImportGroup != JavaImportGroups[Index]) {
4062 result += "\n";
4063 }
4064 }
4065 for (StringRef CommentLine : Imports[Index].AssociatedCommentLines) {
4066 result += CommentLine;
4067 result += "\n";
4068 }
4069 result += Imports[Index].Text;
4070 CurrentIsStatic = Imports[Index].IsStatic;
4071 CurrentImportGroup = JavaImportGroups[Index];
4072 }
4073
4074 // If the imports are out of order, we generate a single replacement fixing
4075 // the entire block. Otherwise, no replacement is generated.
4076 if (replaceCRLF(result) == replaceCRLF(std::string(Code.substr(
4077 Imports.front().Offset, ImportsBlockSize)))) {
4078 return;
4079 }
4080
4081 auto Err = Replaces.add(tooling::Replacement(FileName, Imports.front().Offset,
4082 ImportsBlockSize, result));
4083 // FIXME: better error handling. For now, just skip the replacement for the
4084 // release version.
4085 if (Err) {
4086 llvm::errs() << toString(std::move(Err)) << "\n";
4087 assert(false);
4088 }
4089}
4090
4091namespace {
4092
4093constexpr StringRef
4094 JavaImportRegexPattern("^import[\t ]+(static[\t ]*)?([^\t ]*)[\t ]*;");
4095
4096constexpr StringRef JavaPackageRegexPattern("^package[\t ]");
4097
4098} // anonymous namespace
4099
4102 StringRef FileName,
4103 tooling::Replacements &Replaces) {
4104 unsigned Prev = 0;
4105 bool HasImport = false;
4106 llvm::Regex ImportRegex(JavaImportRegexPattern);
4107 llvm::Regex PackageRegex(JavaPackageRegexPattern);
4110 SmallVector<StringRef> AssociatedCommentLines;
4111
4112 for (bool FormattingOff = false;;) {
4113 auto Pos = Code.find('\n', Prev);
4114 auto GetLine = [&] {
4115 return Code.substr(Prev,
4116 (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
4117 };
4118 StringRef Line = GetLine();
4119
4120 StringRef Trimmed = Line.trim();
4121 if (Trimmed.empty() || PackageRegex.match(Trimmed)) {
4122 // Skip empty line and package statement.
4123 } else if (isClangFormatOff(Trimmed)) {
4124 FormattingOff = true;
4125 } else if (isClangFormatOn(Trimmed)) {
4126 FormattingOff = false;
4127 } else if (Trimmed.starts_with("//")) {
4128 // Associating comments within the imports with the nearest import below.
4129 if (HasImport)
4130 AssociatedCommentLines.push_back(Line);
4131 } else if (Trimmed.starts_with("/*")) {
4132 Pos = Code.find("*/", Pos + 2);
4133 if (Pos != StringRef::npos)
4134 Pos = Code.find('\n', Pos + 2);
4135 if (HasImport) {
4136 // Extend `Line` for a multiline comment to include all lines the
4137 // comment spans.
4138 Line = GetLine();
4139 AssociatedCommentLines.push_back(Line);
4140 }
4141 } else if (ImportRegex.match(Trimmed, &Matches)) {
4142 if (FormattingOff) {
4143 // If at least one import line has formatting turned off, turn off
4144 // formatting entirely.
4145 return Replaces;
4146 }
4147 StringRef Static = Matches[1];
4148 StringRef Identifier = Matches[2];
4149 bool IsStatic = false;
4150 if (Static.contains("static"))
4151 IsStatic = true;
4152 ImportsInBlock.push_back(
4153 {Identifier, Line, Prev, AssociatedCommentLines, IsStatic});
4154 HasImport = true;
4155 AssociatedCommentLines.clear();
4156 } else {
4157 // `Trimmed` is neither empty, nor a comment or a package/import
4158 // statement.
4159 break;
4160 }
4161 if (Pos == StringRef::npos || Pos + 1 == Code.size())
4162 break;
4163 Prev = Pos + 1;
4164 }
4165 if (HasImport)
4166 sortJavaImports(Style, ImportsInBlock, Ranges, FileName, Code, Replaces);
4167 return Replaces;
4168}
4169
4170bool isMpegTS(StringRef Code) {
4171 // MPEG transport streams use the ".ts" file extension. clang-format should
4172 // not attempt to format those. MPEG TS' frame format starts with 0x47 every
4173 // 189 bytes - detect that and return.
4174 return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
4175}
4176
4177bool isLikelyXml(StringRef Code) { return Code.ltrim().starts_with("<"); }
4178
4181 StringRef FileName, unsigned *Cursor) {
4182 tooling::Replacements Replaces;
4183 if (!Style.SortIncludes.Enabled || Style.DisableFormat)
4184 return Replaces;
4185 if (isLikelyXml(Code))
4186 return Replaces;
4187 if (Style.isJavaScript()) {
4188 if (isMpegTS(Code))
4189 return Replaces;
4190 return sortJavaScriptImports(Style, Code, Ranges, FileName);
4191 }
4192 if (Style.isJava())
4193 return sortJavaImports(Style, Code, Ranges, FileName, Replaces);
4194 if (Style.isCpp())
4195 sortCppIncludes(Style, Code, Ranges, FileName, Replaces, Cursor);
4196 return Replaces;
4197}
4198
4199template <typename T>
4201processReplacements(T ProcessFunc, StringRef Code,
4202 const tooling::Replacements &Replaces,
4203 const FormatStyle &Style) {
4204 if (Replaces.empty())
4205 return tooling::Replacements();
4206
4207 auto NewCode = applyAllReplacements(Code, Replaces);
4208 if (!NewCode)
4209 return NewCode.takeError();
4210 std::vector<tooling::Range> ChangedRanges = Replaces.getAffectedRanges();
4211 StringRef FileName = Replaces.begin()->getFilePath();
4212
4213 tooling::Replacements FormatReplaces =
4214 ProcessFunc(Style, *NewCode, ChangedRanges, FileName);
4215
4216 return Replaces.merge(FormatReplaces);
4217}
4218
4220formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
4221 const FormatStyle &Style) {
4222 // We need to use lambda function here since there are two versions of
4223 // `sortIncludes`.
4224 auto SortIncludes = [](const FormatStyle &Style, StringRef Code,
4225 std::vector<tooling::Range> Ranges,
4226 StringRef FileName) -> tooling::Replacements {
4227 return sortIncludes(Style, Code, Ranges, FileName);
4228 };
4229 auto SortedReplaces =
4230 processReplacements(SortIncludes, Code, Replaces, Style);
4231 if (!SortedReplaces)
4232 return SortedReplaces.takeError();
4233
4234 // We need to use lambda function here since there are two versions of
4235 // `reformat`.
4236 auto Reformat = [](const FormatStyle &Style, StringRef Code,
4237 std::vector<tooling::Range> Ranges,
4238 StringRef FileName) -> tooling::Replacements {
4239 return reformat(Style, Code, Ranges, FileName);
4240 };
4241 return processReplacements(Reformat, Code, *SortedReplaces, Style);
4242}
4243
4244namespace {
4245
4246inline bool isHeaderInsertion(const tooling::Replacement &Replace) {
4247 return Replace.getOffset() == std::numeric_limits<unsigned>::max() &&
4248 Replace.getLength() == 0 &&
4250 Replace.getReplacementText());
4251}
4252
4253inline bool isHeaderDeletion(const tooling::Replacement &Replace) {
4254 return Replace.getOffset() == std::numeric_limits<unsigned>::max() &&
4255 Replace.getLength() == 1;
4256}
4257
4258// FIXME: insert empty lines between newly created blocks.
4259tooling::Replacements
4260fixCppIncludeInsertions(StringRef Code, const tooling::Replacements &Replaces,
4261 const FormatStyle &Style) {
4262 if (!Style.isCpp())
4263 return Replaces;
4264
4265 tooling::Replacements HeaderInsertions;
4266 std::set<StringRef> HeadersToDelete;
4267 tooling::Replacements Result;
4268 for (const auto &R : Replaces) {
4269 if (isHeaderInsertion(R)) {
4270 // Replacements from \p Replaces must be conflict-free already, so we can
4271 // simply consume the error.
4272 consumeError(HeaderInsertions.add(R));
4273 } else if (isHeaderDeletion(R)) {
4274 HeadersToDelete.insert(R.getReplacementText());
4275 } else if (R.getOffset() == std::numeric_limits<unsigned>::max()) {
4276 llvm::errs() << "Insertions other than header #include insertion are "
4277 "not supported! "
4278 << R.getReplacementText() << "\n";
4279 } else {
4280 consumeError(Result.add(R));
4281 }
4282 }
4283 if (HeaderInsertions.empty() && HeadersToDelete.empty())
4284 return Replaces;
4285
4286 StringRef FileName = Replaces.begin()->getFilePath();
4287 tooling::HeaderIncludes Includes(FileName, Code, Style.IncludeStyle);
4288
4289 for (const auto &Header : HeadersToDelete) {
4290 tooling::Replacements Replaces =
4291 Includes.remove(Header.trim("\"<>"), Header.starts_with("<"));
4292 for (const auto &R : Replaces) {
4293 auto Err = Result.add(R);
4294 if (Err) {
4295 // Ignore the deletion on conflict.
4296 llvm::errs() << "Failed to add header deletion replacement for "
4297 << Header << ": " << toString(std::move(Err)) << "\n";
4298 }
4299 }
4300 }
4301
4302 SmallVector<StringRef, 4> Matches;
4303 SmallVector<tooling::HeaderIncludes::HeaderToInsert, 4> HeadersToInsert;
4304 for (const auto &R : HeaderInsertions) {
4305 auto IncludeDirective = R.getReplacementText();
4306 bool Matched =
4307 tooling::HeaderIncludes::IncludeRegex.match(IncludeDirective, &Matches);
4308 assert(Matched && "Header insertion replacement must have replacement text "
4309 "'#include ...'");
4310 (void)Matched;
4311 auto IncludeName = Matches[2];
4312 HeadersToInsert.emplace_back(IncludeName,
4314 }
4315 for (const auto &Replace : Includes.insert(HeadersToInsert)) {
4316 auto Err = Result.add(Replace);
4317 if (Err) {
4318 consumeError(std::move(Err));
4319 unsigned NewOffset = Result.getShiftedCodePosition(Replace.getOffset());
4320 auto Shifted = tooling::Replacement(FileName, NewOffset, 0,
4321 Replace.getReplacementText());
4322 Result = Result.merge(tooling::Replacements(Shifted));
4323 }
4324 }
4325 return Result;
4326}
4327
4328} // anonymous namespace
4329
4330Expected<tooling::Replacements>
4331cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
4332 const FormatStyle &Style) {
4333 // We need to use lambda function here since there are two versions of
4334 // `cleanup`.
4335 auto Cleanup = [](const FormatStyle &Style, StringRef Code,
4337 StringRef FileName) -> tooling::Replacements {
4338 return cleanup(Style, Code, Ranges, FileName);
4339 };
4340 // Make header insertion replacements insert new headers into correct blocks.
4341 tooling::Replacements NewReplaces =
4342 fixCppIncludeInsertions(Code, Replaces, Style);
4343 return cantFail(processReplacements(Cleanup, Code, NewReplaces, Style));
4344}
4345
4346namespace internal {
4347std::pair<tooling::Replacements, unsigned>
4348reformat(const FormatStyle &Style, StringRef Code,
4349 ArrayRef<tooling::Range> Ranges, unsigned FirstStartColumn,
4350 unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName,
4351 FormattingAttemptStatus *Status) {
4352 FormatStyle Expanded = Style;
4356
4357 // These are handled by separate passes.
4358 Expanded.InsertBraces = false;
4359 Expanded.RemoveBracesLLVM = false;
4361 Expanded.RemoveSemicolon = false;
4362
4363 // Make some sanity adjustments.
4364 switch (Expanded.RequiresClausePosition) {
4367 Expanded.IndentRequiresClause = false;
4368 break;
4369 default:
4370 break;
4371 }
4372 if (Expanded.BraceWrapping.AfterEnum)
4373 Expanded.AllowShortEnumsOnASingleLine = false;
4374
4375 if (Expanded.DisableFormat)
4376 return {tooling::Replacements(), 0};
4377 if (isLikelyXml(Code))
4378 return {tooling::Replacements(), 0};
4379 if (Expanded.isJavaScript() && isMpegTS(Code))
4380 return {tooling::Replacements(), 0};
4381
4382 // JSON only needs the formatting passing.
4383 if (Style.isJson()) {
4384 std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
4385 auto Env = Environment::make(Code, FileName, Ranges, FirstStartColumn,
4386 NextStartColumn, LastStartColumn);
4387 if (!Env)
4388 return {};
4389 // Perform the actual formatting pass.
4390 tooling::Replacements Replaces =
4391 Formatter(*Env, Style, Status).process().first;
4392 // add a replacement to remove the "x = " from the result.
4393 if (Code.starts_with("x = ")) {
4394 Replaces = Replaces.merge(
4396 }
4397 // apply the reformatting changes and the removal of "x = ".
4398 if (applyAllReplacements(Code, Replaces))
4399 return {Replaces, 0};
4400 return {tooling::Replacements(), 0};
4401 }
4402
4403 auto Env = Environment::make(Code, FileName, Ranges, FirstStartColumn,
4404 NextStartColumn, LastStartColumn);
4405 if (!Env)
4406 return {};
4407
4409 const Environment &)>
4411
4413
4414 Passes.emplace_back([&](const Environment &Env) {
4415 return IntegerLiteralSeparatorFixer().process(Env, Expanded);
4416 });
4417
4418 Passes.emplace_back([&](const Environment &Env) {
4419 return NumericLiteralCaseFixer().process(Env, Expanded);
4420 });
4421
4422 if (Style.isCpp()) {
4423 if (Style.QualifierAlignment != FormatStyle::QAS_Leave)
4424 addQualifierAlignmentFixerPasses(Expanded, Passes);
4425
4426 if (Style.RemoveParentheses != FormatStyle::RPS_Leave) {
4427 FormatStyle S = Expanded;
4428 S.RemoveParentheses = Style.RemoveParentheses;
4429 Passes.emplace_back([&, S = std::move(S)](const Environment &Env) {
4430 return ParensRemover(Env, S).process(/*SkipAnnotation=*/true);
4431 });
4432 }
4433
4434 if (Style.InsertBraces) {
4435 FormatStyle S = Expanded;
4436 S.InsertBraces = true;
4437 Passes.emplace_back([&, S = std::move(S)](const Environment &Env) {
4438 return BracesInserter(Env, S).process(/*SkipAnnotation=*/true);
4439 });
4440 }
4441
4442 if (Style.RemoveBracesLLVM) {
4443 FormatStyle S = Expanded;
4444 S.RemoveBracesLLVM = true;
4445 Passes.emplace_back([&, S = std::move(S)](const Environment &Env) {
4446 return BracesRemover(Env, S).process(/*SkipAnnotation=*/true);
4447 });
4448 }
4449
4450 if (Style.RemoveSemicolon) {
4451 FormatStyle S = Expanded;
4452 S.RemoveSemicolon = true;
4453 Passes.emplace_back([&, S = std::move(S)](const Environment &Env) {
4454 return SemiRemover(Env, S).process();
4455 });
4456 }
4457
4458 if (Style.EnumTrailingComma != FormatStyle::ETC_Leave) {
4459 Passes.emplace_back([&](const Environment &Env) {
4460 return EnumTrailingCommaEditor(Env, Expanded)
4461 .process(/*SkipAnnotation=*/true);
4462 });
4463 }
4464
4465 if (Style.FixNamespaceComments) {
4466 Passes.emplace_back([&](const Environment &Env) {
4467 return NamespaceEndCommentsFixer(Env, Expanded).process();
4468 });
4469 }
4470
4471 if (Style.SortUsingDeclarations != FormatStyle::SUD_Never) {
4472 Passes.emplace_back([&](const Environment &Env) {
4473 return UsingDeclarationsSorter(Env, Expanded).process();
4474 });
4475 }
4476 }
4477
4478 if (Style.Language == FormatStyle::LK_ObjC &&
4479 !Style.ObjCPropertyAttributeOrder.empty()) {
4480 Passes.emplace_back([&](const Environment &Env) {
4481 return ObjCPropertyAttributeOrderFixer(Env, Expanded).process();
4482 });
4483 }
4484
4485 if (Style.isJavaScript() &&
4486 Style.JavaScriptQuotes != FormatStyle::JSQS_Leave) {
4487 Passes.emplace_back([&](const Environment &Env) {
4488 return JavaScriptRequoter(Env, Expanded).process(/*SkipAnnotation=*/true);
4489 });
4490 }
4491
4492 Passes.emplace_back([&](const Environment &Env) {
4493 return Formatter(Env, Expanded, Status).process();
4494 });
4495
4496 if (Style.SeparateDefinitionBlocks != FormatStyle::SDS_Leave) {
4497 Passes.emplace_back([&](const Environment &Env) {
4498 return DefinitionBlockSeparator(Env, Expanded).process();
4499 });
4500 }
4501
4502 if (Style.isJavaScript() &&
4503 Style.InsertTrailingCommas == FormatStyle::TCS_Wrapped) {
4504 Passes.emplace_back([&](const Environment &Env) {
4505 return TrailingCommaInserter(Env, Expanded).process();
4506 });
4507 }
4508
4509 std::optional<std::string> CurrentCode;
4511 unsigned Penalty = 0;
4512 for (size_t I = 0, E = Passes.size(); I < E; ++I) {
4513 std::pair<tooling::Replacements, unsigned> PassFixes = Passes[I](*Env);
4514 auto NewCode = applyAllReplacements(
4515 CurrentCode ? StringRef(*CurrentCode) : Code, PassFixes.first);
4516 if (NewCode) {
4517 Fixes = Fixes.merge(PassFixes.first);
4518 Penalty += PassFixes.second;
4519 if (I + 1 < E) {
4520 CurrentCode = std::move(*NewCode);
4521 Env = Environment::make(
4522 *CurrentCode, FileName,
4524 FirstStartColumn, NextStartColumn, LastStartColumn);
4525 if (!Env)
4526 return {};
4527 }
4528 }
4529 }
4530
4531 if (Style.QualifierAlignment != FormatStyle::QAS_Leave) {
4532 // Don't make replacements that replace nothing. QualifierAlignment can
4533 // produce them if one of its early passes changes e.g. `const volatile` to
4534 // `volatile const` and then a later pass changes it back again.
4535 tooling::Replacements NonNoOpFixes;
4536 for (const tooling::Replacement &Fix : Fixes) {
4537 StringRef OriginalCode = Code.substr(Fix.getOffset(), Fix.getLength());
4538 if (OriginalCode != Fix.getReplacementText()) {
4539 auto Err = NonNoOpFixes.add(Fix);
4540 if (Err) {
4541 llvm::errs() << "Error adding replacements : "
4542 << toString(std::move(Err)) << "\n";
4543 }
4544 }
4545 }
4546 Fixes = std::move(NonNoOpFixes);
4547 }
4548
4549 return {Fixes, Penalty};
4550}
4551} // namespace internal
4552
4553tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
4555 StringRef FileName,
4556 FormattingAttemptStatus *Status) {
4557 return internal::reformat(Style, Code, Ranges,
4558 /*FirstStartColumn=*/0,
4559 /*NextStartColumn=*/0,
4560 /*LastStartColumn=*/0, FileName, Status)
4561 .first;
4562}
4563
4564tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
4566 StringRef FileName) {
4567 // cleanups only apply to C++ (they mostly concern ctor commas etc.)
4568 if (Style.Language != FormatStyle::LK_Cpp)
4569 return tooling::Replacements();
4570 auto Env = Environment::make(Code, FileName, Ranges);
4571 if (!Env)
4572 return {};
4573 return Cleaner(*Env, Style).process().first;
4574}
4575
4576tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
4578 StringRef FileName, bool *IncompleteFormat) {
4580 auto Result = reformat(Style, Code, Ranges, FileName, &Status);
4581 if (!Status.FormatComplete)
4582 *IncompleteFormat = true;
4583 return Result;
4584}
4585
4587 StringRef Code,
4589 StringRef FileName) {
4590 auto Env = Environment::make(Code, FileName, Ranges);
4591 if (!Env)
4592 return {};
4593 return NamespaceEndCommentsFixer(*Env, Style).process().first;
4594}
4595
4597 StringRef Code,
4599 StringRef FileName) {
4600 auto Env = Environment::make(Code, FileName, Ranges);
4601 if (!Env)
4602 return {};
4603 return UsingDeclarationsSorter(*Env, Style).process().first;
4604}
4605
4607 LangOptions LangOpts;
4608
4609 auto LexingStd = Style.Standard;
4610 if (LexingStd == FormatStyle::LS_Auto || LexingStd == FormatStyle::LS_Latest)
4611 LexingStd = FormatStyle::LS_Cpp20;
4612
4613 const bool SinceCpp11 = LexingStd >= FormatStyle::LS_Cpp11;
4614 const bool SinceCpp20 = LexingStd >= FormatStyle::LS_Cpp20;
4615
4616 switch (Style.Language) {
4617 case FormatStyle::LK_C:
4618 LangOpts.C11 = 1;
4619 LangOpts.C23 = 1;
4620 break;
4623 LangOpts.CXXOperatorNames = 1;
4624 LangOpts.CPlusPlus11 = SinceCpp11;
4625 LangOpts.CPlusPlus14 = LexingStd >= FormatStyle::LS_Cpp14;
4626 LangOpts.CPlusPlus17 = LexingStd >= FormatStyle::LS_Cpp17;
4627 LangOpts.CPlusPlus20 = SinceCpp20;
4628 LangOpts.CPlusPlus23 = LexingStd >= FormatStyle::LS_Cpp23;
4629 LangOpts.CPlusPlus26 = LexingStd >= FormatStyle::LS_Cpp26;
4630 [[fallthrough]];
4631 default:
4632 LangOpts.CPlusPlus = 1;
4633 }
4634
4635 LangOpts.Char8 = SinceCpp20;
4636 LangOpts.AllowLiteralDigitSeparator = LangOpts.CPlusPlus14 || LangOpts.C23;
4637 // Turning on digraphs in standards before C++0x is error-prone, because e.g.
4638 // the sequence "<::" will be unconditionally treated as "[:".
4639 // Cf. Lexer::LexTokenInternal.
4640 LangOpts.Digraphs = SinceCpp11;
4641
4642 LangOpts.LineComment = 1;
4643 LangOpts.Bool = 1;
4644 LangOpts.ObjC = 1;
4645 LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
4646 LangOpts.DeclSpecKeyword = 1; // To get __declspec.
4647 LangOpts.C99 = 1; // To get kw_restrict for non-underscore-prefixed restrict.
4648
4649 return LangOpts;
4650}
4651
4653 "Set coding style. <string> can be:\n"
4654 "1. A preset: LLVM, GNU, Google, Chromium, Microsoft,\n"
4655 " Mozilla, WebKit.\n"
4656 "2. 'file' to load style configuration from a\n"
4657 " .clang-format file in one of the parent directories\n"
4658 " of the source file (for stdin, see --assume-filename).\n"
4659 " If no .clang-format file is found, falls back to\n"
4660 " --fallback-style.\n"
4661 " --style=file is the default.\n"
4662 "3. 'file:<format_file_path>' to explicitly specify\n"
4663 " the configuration file.\n"
4664 "4. \"{key: value, ...}\" to set specific parameters, e.g.:\n"
4665 " --style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
4666
4668 static constexpr std::array<llvm::StringLiteral, 2> TemplateSuffixes{
4669 ".in",
4670 ".template",
4671 };
4672 for (auto Suffix : TemplateSuffixes)
4673 if (FileName.consume_back(Suffix))
4674 break;
4675
4676 if (FileName.ends_with(".c"))
4677 return FormatStyle::LK_C;
4678 if (FileName.ends_with(".java"))
4679 return FormatStyle::LK_Java;
4680 if (FileName.ends_with_insensitive(".js") ||
4681 FileName.ends_with_insensitive(".mjs") ||
4682 FileName.ends_with_insensitive(".cjs") ||
4683 FileName.ends_with_insensitive(".ts") ||
4684 FileName.ends_with_insensitive(".mts") ||
4685 FileName.ends_with_insensitive(".cts")) {
4686 return FormatStyle::LK_JavaScript; // (module) JavaScript or TypeScript.
4687 }
4688 if (FileName.ends_with(".m") || FileName.ends_with(".mm"))
4689 return FormatStyle::LK_ObjC;
4690 if (FileName.ends_with_insensitive(".proto") ||
4691 FileName.ends_with_insensitive(".protodevel")) {
4692 return FormatStyle::LK_Proto;
4693 }
4694 // txtpb is the canonical extension, and textproto is the legacy canonical
4695 // extension
4696 // https://protobuf.dev/reference/protobuf/textformat-spec/#text-format-files
4697 if (FileName.ends_with_insensitive(".txtpb") ||
4698 FileName.ends_with_insensitive(".textpb") ||
4699 FileName.ends_with_insensitive(".pb.txt") ||
4700 FileName.ends_with_insensitive(".textproto") ||
4701 FileName.ends_with_insensitive(".asciipb")) {
4703 }
4704 if (FileName.ends_with_insensitive(".td"))
4706 if (FileName.ends_with_insensitive(".cs"))
4708 if (FileName.ends_with_insensitive(".json") ||
4709 FileName.ends_with_insensitive(".ipynb")) {
4710 return FormatStyle::LK_Json;
4711 }
4712 if (FileName.ends_with_insensitive(".sv") ||
4713 FileName.ends_with_insensitive(".svh") ||
4714 FileName.ends_with_insensitive(".v") ||
4715 FileName.ends_with_insensitive(".vh")) {
4717 }
4718 return FormatStyle::LK_Cpp;
4719}
4720
4722 const auto ID = Env.getFileID();
4723 const auto &SourceMgr = Env.getSourceManager();
4724
4725 LangOptions LangOpts;
4726 LangOpts.CPlusPlus = 1;
4727 LangOpts.LineComment = 1;
4728
4729 Lexer Lex(ID, SourceMgr.getBufferOrFake(ID), SourceMgr, LangOpts);
4730 Lex.SetCommentRetentionState(true);
4731
4732 for (Token Tok; !Lex.LexFromRawLexer(Tok) && Tok.is(tok::comment);) {
4733 auto Text = StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
4734 Tok.getLength());
4735 if (!Text.consume_front("// clang-format Language:"))
4736 continue;
4737
4738 Text = Text.trim();
4739 if (Text == "C")
4740 return FormatStyle::LK_C;
4741 if (Text == "Cpp")
4742 return FormatStyle::LK_Cpp;
4743 if (Text == "ObjC")
4744 return FormatStyle::LK_ObjC;
4745 }
4746
4747 return FormatStyle::LK_None;
4748}
4749
4751 const auto GuessedLanguage = getLanguageByFileName(FileName);
4752 if (GuessedLanguage == FormatStyle::LK_Cpp) {
4753 auto Extension = llvm::sys::path::extension(FileName);
4754 // If there's no file extension (or it's .h), we need to check the contents
4755 // of the code to see if it contains Objective-C.
4756 if (!Code.empty() && (Extension.empty() || Extension == ".h")) {
4757 auto NonEmptyFileName = FileName.empty() ? "guess.h" : FileName;
4758 Environment Env(Code, NonEmptyFileName, /*Ranges=*/{});
4759 if (const auto Language = getLanguageByComment(Env);
4761 return Language;
4762 }
4763 ObjCHeaderStyleGuesser Guesser(Env, getLLVMStyle());
4764 Guesser.process();
4765 if (Guesser.isObjC())
4766 return FormatStyle::LK_ObjC;
4767 }
4768 }
4769 return GuessedLanguage;
4770}
4771
4772// Update StyleOptionHelpDescription above when changing this.
4773const char *DefaultFormatStyle = "file";
4774
4775const char *DefaultFallbackStyle = "LLVM";
4776
4777llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
4778loadAndParseConfigFile(StringRef ConfigFile, llvm::vfs::FileSystem *FS,
4779 FormatStyle *Style, bool AllowUnknownOptions,
4780 llvm::SourceMgr::DiagHandlerTy DiagHandler,
4781 bool IsDotHFile) {
4782 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
4783 FS->getBufferForFile(ConfigFile);
4784 if (auto EC = Text.getError())
4785 return EC;
4786 if (auto EC = parseConfiguration(*Text.get(), Style, AllowUnknownOptions,
4787 DiagHandler, /*DiagHandlerCtx=*/nullptr,
4788 IsDotHFile)) {
4789 return EC;
4790 }
4791 return Text;
4792}
4793
4794Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
4795 StringRef FallbackStyleName, StringRef Code,
4796 llvm::vfs::FileSystem *FS,
4797 bool AllowUnknownOptions,
4798 llvm::SourceMgr::DiagHandlerTy DiagHandler) {
4800 FormatStyle FallbackStyle = getNoStyle();
4801 if (!getPredefinedStyle(FallbackStyleName, Style.Language, &FallbackStyle))
4802 return make_string_error("Invalid fallback style: " + FallbackStyleName);
4803
4804 SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 1> ChildFormatTextToApply;
4805
4806 if (StyleName.starts_with("{")) {
4807 // Parse YAML/JSON style from the command line.
4808 StringRef Source = "<command-line>";
4809 if (std::error_code ec =
4810 parseConfiguration(llvm::MemoryBufferRef(StyleName, Source), &Style,
4811 AllowUnknownOptions, DiagHandler)) {
4812 return make_string_error("Error parsing -style: " + ec.message());
4813 }
4814
4815 if (Style.InheritConfig.empty())
4816 return Style;
4817
4818 ChildFormatTextToApply.emplace_back(
4819 llvm::MemoryBuffer::getMemBuffer(StyleName, Source, false));
4820 }
4821
4822 if (!FS)
4823 FS = llvm::vfs::getRealFileSystem().get();
4824 assert(FS);
4825
4826 const bool IsDotHFile = FileName.ends_with(".h");
4827
4828 // User provided clang-format file using -style=file:path/to/format/file.
4829 if (Style.InheritConfig.empty() &&
4830 StyleName.starts_with_insensitive("file:")) {
4831 auto ConfigFile = StyleName.substr(5);
4832 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
4833 loadAndParseConfigFile(ConfigFile, FS, &Style, AllowUnknownOptions,
4834 DiagHandler, IsDotHFile);
4835 if (auto EC = Text.getError()) {
4836 return make_string_error("Error reading " + ConfigFile + ": " +
4837 EC.message());
4838 }
4839
4840 LLVM_DEBUG(llvm::dbgs()
4841 << "Using configuration file " << ConfigFile << "\n");
4842
4843 if (Style.InheritConfig.empty())
4844 return Style;
4845
4846 // Search for parent configs starting from the parent directory of
4847 // ConfigFile.
4848 FileName = ConfigFile;
4849 ChildFormatTextToApply.emplace_back(std::move(*Text));
4850 }
4851
4852 // If the style inherits the parent configuration it is a command line
4853 // configuration, which wants to inherit, so we have to skip the check of the
4854 // StyleName.
4855 if (Style.InheritConfig.empty() && !StyleName.equals_insensitive("file")) {
4856 if (!getPredefinedStyle(StyleName, Style.Language, &Style))
4857 return make_string_error("Invalid value for -style");
4858 if (Style.InheritConfig.empty())
4859 return Style;
4860 }
4861
4862 using namespace llvm::sys::path;
4863 using String = SmallString<128>;
4864
4865 String Path(FileName);
4866 if (std::error_code EC = FS->makeAbsolute(Path))
4867 return make_string_error(EC.message());
4868
4869 auto Normalize = [](String &Path) {
4870 Path = convert_to_slash(Path);
4871 remove_dots(Path, /*remove_dot_dot=*/true, Style::posix);
4872 };
4873
4874 Normalize(Path);
4875
4876 // Reset possible inheritance
4877 Style.InheritConfig.clear();
4878
4879 auto dropDiagnosticHandler = [](const llvm::SMDiagnostic &, void *) {};
4880
4881 auto applyChildFormatTexts = [&](FormatStyle *Style) {
4882 for (const auto &MemBuf : llvm::reverse(ChildFormatTextToApply)) {
4883 auto EC =
4884 parseConfiguration(*MemBuf, Style, AllowUnknownOptions,
4885 DiagHandler ? DiagHandler : dropDiagnosticHandler);
4886 // It was already correctly parsed.
4887 assert(!EC);
4888 static_cast<void>(EC);
4889 }
4890 };
4891
4892 // Look for .clang-format/_clang-format file in the file's parent directories.
4893 SmallVector<std::string, 2> FilesToLookFor;
4894 FilesToLookFor.push_back(".clang-format");
4895 FilesToLookFor.push_back("_clang-format");
4896
4897 llvm::StringSet<> Directories; // Inherited directories.
4898 bool Redirected = false;
4899 String Dir, UnsuitableConfigFiles;
4900 for (StringRef Directory = Path; !Directory.empty();
4901 Directory = Redirected ? Dir.str() : parent_path(Directory)) {
4902 auto Status = FS->status(Directory);
4903 if (!Status ||
4904 Status->getType() != llvm::sys::fs::file_type::directory_file) {
4905 if (!Redirected)
4906 continue;
4907 return make_string_error("Failed to inherit configuration directory " +
4908 Directory);
4909 }
4910
4911 for (const auto &F : FilesToLookFor) {
4912 String ConfigFile(Directory);
4913
4914 append(ConfigFile, F);
4915 LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
4916
4917 Status = FS->status(ConfigFile);
4918 if (!Status ||
4919 Status->getType() != llvm::sys::fs::file_type::regular_file) {
4920 continue;
4921 }
4922
4923 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
4924 loadAndParseConfigFile(ConfigFile, FS, &Style, AllowUnknownOptions,
4925 DiagHandler, IsDotHFile);
4926 if (auto EC = Text.getError()) {
4927 if (EC != ParseError::Unsuitable) {
4928 return make_string_error("Error reading " + ConfigFile + ": " +
4929 EC.message());
4930 }
4931 if (!UnsuitableConfigFiles.empty())
4932 UnsuitableConfigFiles.append(", ");
4933 UnsuitableConfigFiles.append(ConfigFile);
4934 continue;
4935 }
4936
4937 LLVM_DEBUG(llvm::dbgs()
4938 << "Using configuration file " << ConfigFile << "\n");
4939
4940 if (Style.InheritConfig.empty()) {
4941 if (!ChildFormatTextToApply.empty()) {
4942 LLVM_DEBUG(llvm::dbgs() << "Applying child configurations\n");
4943 applyChildFormatTexts(&Style);
4944 }
4945 return Style;
4946 }
4947
4948 if (!Directories.insert(Directory).second) {
4949 return make_string_error(
4950 "Loop detected when inheriting configuration file in " + Directory);
4951 }
4952
4953 LLVM_DEBUG(llvm::dbgs() << "Inherits parent configuration\n");
4954
4955 if (Style.InheritConfig == "..") {
4956 Redirected = false;
4957 } else {
4958 Redirected = true;
4959 String ExpandedDir;
4960 llvm::sys::fs::expand_tilde(Style.InheritConfig, ExpandedDir);
4961 Normalize(ExpandedDir);
4962 if (is_absolute(ExpandedDir, Style::posix)) {
4963 Dir = ExpandedDir;
4964 } else {
4965 Dir = Directory.str();
4966 append(Dir, Style::posix, ExpandedDir);
4967 }
4968 }
4969
4970 // Reset inheritance of style
4971 Style.InheritConfig.clear();
4972
4973 ChildFormatTextToApply.emplace_back(std::move(*Text));
4974
4975 // Breaking out of the inner loop, since we don't want to parse
4976 // .clang-format AND _clang-format, if both exist. Then we continue the
4977 // outer loop (parent directories) in search for the parent
4978 // configuration.
4979 break;
4980 }
4981 }
4982
4983 if (!UnsuitableConfigFiles.empty()) {
4984 return make_string_error("Configuration file(s) do(es) not support " +
4985 getLanguageName(Style.Language) + ": " +
4986 UnsuitableConfigFiles);
4987 }
4988
4989 if (!ChildFormatTextToApply.empty()) {
4990 LLVM_DEBUG(llvm::dbgs()
4991 << "Applying child configurations on fallback style\n");
4992 applyChildFormatTexts(&FallbackStyle);
4993 }
4994
4995 return FallbackStyle;
4996}
4997
4998static bool isClangFormatOnOff(StringRef Comment, bool On) {
4999 if (Comment == (On ? "/* clang-format on */" : "/* clang-format off */"))
5000 return true;
5001
5002 static const char ClangFormatOn[] = "// clang-format on";
5003 static const char ClangFormatOff[] = "// clang-format off";
5004 const unsigned Size = (On ? sizeof ClangFormatOn : sizeof ClangFormatOff) - 1;
5005
5006 return Comment.starts_with(On ? ClangFormatOn : ClangFormatOff) &&
5007 (Comment.size() == Size || Comment[Size] == ':');
5008}
5009
5010bool isClangFormatOn(StringRef Comment) {
5011 return isClangFormatOnOff(Comment, /*On=*/true);
5012}
5013
5014bool isClangFormatOff(StringRef Comment) {
5015 return isClangFormatOnOff(Comment, /*On=*/false);
5016}
5017
5018} // namespace format
5019} // namespace clang
This file declares DefinitionBlockSeparator, a TokenAnalyzer that inserts or removes empty lines sepa...
int8_t BraceCount
Number of optional braces to be inserted after this token: -1: a single left brace 0: no braces >0: n...
FormatToken()
Token Tok
The Token.
FormatToken * Next
The next token in the unwrapped line.
BracketAlignmentStyle
Definition Format.cpp:41
@ BAS_DontAlign
Definition Format.cpp:43
@ BAS_Ignore
Definition Format.cpp:46
@ BAS_BlockIndent
Definition Format.cpp:45
@ BAS_Align
Definition Format.cpp:42
@ BAS_AlwaysBreak
Definition Format.cpp:44
Various functions to configurably format source code.
This file declares IntegerLiteralSeparatorFixer that fixes C++ integer literal separators.
Result
Implement __builtin_bit_cast and related operations.
This file declares NamespaceEndCommentsFixer, a TokenAnalyzer that fixes namespace end comments.
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.
Implements a combinatorial exploration of all the different linebreaks unwrapped lines can be formatt...
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.
Definition Lexer.h:79
bool LexFromRawLexer(Token &Result)
LexFromRawLexer - Lex a token from a designated raw lexer (one with no associated preprocessor object...
Definition Lexer.h:236
void SetCommentRetentionState(bool Mode)
SetCommentRetentionMode - Change the comment retention mode of the lexer to the specified mode.
Definition Lexer.h:269
Encodes a location in the source.
This class handles loading and caching of source files into memory.
Token - This structure provides full information about a lexed token.
Definition Token.h:36
SourceLocation getEndLoc() const
Definition Token.h:169
SourceManager & getSourceManager() const
static std::unique_ptr< Environment > make(StringRef Code, StringRef FileName, ArrayRef< tooling::Range > Ranges, unsigned FirstStartColumn=0, unsigned NextStartColumn=0, unsigned LastStartColumn=0)
std::pair< tooling::Replacements, unsigned > process(const Environment &Env, const FormatStyle &Style)
static tok::TokenKind getTokenFromQualifier(const std::string &Qualifier)
std::pair< tooling::Replacements, unsigned > process(const Environment &Env, const FormatStyle &Style)
const char * name() const noexcept override
Definition Format.cpp:1714
std::string message(int EV) const override
Definition Format.cpp:1718
std::pair< tooling::Replacements, unsigned > process(bool SkipAnnotation=false)
static const llvm::Regex IncludeRegex
This class manages priorities of C++ include categories and calculates priorities for headers.
int getIncludePriority(StringRef IncludeName, bool CheckMainHeader) const
Returns the priority of the category which IncludeName belongs to.
int getSortIncludePriority(StringRef IncludeName, bool CheckMainHeader) const
A source range independent of the SourceManager.
Definition Replacement.h:44
A text replacement.
Definition Replacement.h:83
unsigned getLength() const
StringRef getReplacementText() const
unsigned getOffset() const
Maintains a set of replacements that are conflict-free.
std::vector< Range > getAffectedRanges() const
const_iterator begin() const
llvm::Error add(const Replacement &R)
Adds a new replacement R to the current set of replacements.
Replacements merge(const Replacements &Replaces) const
Merges Replaces into the current replacements.
#define UINT_MAX
Definition limits.h:64
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).
Definition Types.cpp:240
std::pair< tooling::Replacements, unsigned > reformat(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, unsigned FirstStartColumn, unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName, FormattingAttemptStatus *Status)
Reformats the given Ranges in the code fragment Code.
Definition Format.cpp:4348
const char * StyleOptionHelpDescription
Description to be used for help text for a llvm::cl option for specifying format style.
Definition Format.cpp:4652
void addQualifierAlignmentFixerPasses(const FormatStyle &Style, SmallVectorImpl< AnalyzerPass > &Passes)
static void expandPresetsSpaceBeforeParens(FormatStyle &Expanded)
Definition Format.cpp:1848
const char * DefaultFallbackStyle
The suggested predefined style to use as the fallback style in getStyle.
Definition Format.cpp:4775
static bool affectsRange(ArrayRef< tooling::Range > Ranges, unsigned Start, unsigned End)
Definition Format.cpp:3616
const char * getTokenTypeName(TokenType Type)
Determines the name of a token type.
FormatStyle getWebKitStyle()
Returns a format style complying with Webkit's style guide: http://www.webkit.org/coding/coding-style...
Definition Format.cpp:2374
bool isLikelyXml(StringRef Code)
Definition Format.cpp:4177
static unsigned findJavaImportGroup(const FormatStyle &Style, StringRef ImportIdentifier)
Definition Format.cpp:3996
std::string replaceCRLF(const std::string &Code)
Definition Format.cpp:3657
std::error_code make_error_code(ParseError e)
Definition Format.cpp:1705
FormatStyle getClangFormatStyle()
Definition Format.cpp:2442
std::function< std::pair< tooling::Replacements, unsigned >(const Environment &)> AnalyzerPass
FormatStyle getLLVMStyle(FormatStyle::LanguageKind Language=FormatStyle::LK_Cpp)
Returns a format style complying with the LLVM coding standards: http://llvm.org/docs/CodingStandards...
Definition Format.cpp:1880
static void replaceToken(const SourceManager &SourceMgr, tooling::Replacements &Fixes, const CharSourceRange &Range, std::string NewText)
FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language)
Returns a format style complying with one of Google's style guides: http://google-styleguide....
Definition Format.cpp:2135
std::string configurationAsText(const FormatStyle &Style)
Gets configuration in a YAML string.
Definition Format.cpp:2626
FormatStyle getMicrosoftStyle(FormatStyle::LanguageKind Language)
Returns a format style complying with Microsoft style guide: https://docs.microsoft....
Definition Format.cpp:2413
std::error_code parseConfiguration(llvm::MemoryBufferRef Config, FormatStyle *Style, bool AllowUnknownOptions=false, llvm::SourceMgr::DiagHandlerTy DiagHandler=nullptr, void *DiagHandlerCtx=nullptr, bool IsDotHFile=false)
Parse configuration from YAML-formatted text.
Definition Format.cpp:2529
const std::error_category & getParseCategory()
Definition Format.cpp:1701
tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Fix namespace end comments in the given Ranges in Code.
Definition Format.cpp:4586
FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code)
Definition Format.cpp:4750
Expected< FormatStyle > getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyle, StringRef Code="", llvm::vfs::FileSystem *FS=nullptr, bool AllowUnknownOptions=false, llvm::SourceMgr::DiagHandlerTy DiagHandler=nullptr)
Construct a FormatStyle based on StyleName.
Definition Format.cpp:4794
bool isMpegTS(StringRef Code)
Definition Format.cpp:4170
static std::pair< unsigned, unsigned > FindCursorIndex(const ArrayRef< IncludeDirective > &Includes, const ArrayRef< unsigned > &Indices, unsigned Cursor)
Definition Format.cpp:3636
const char * DefaultFormatStyle
The suggested format style to use by default.
Definition Format.cpp:4773
static FormatStyle::LanguageKind getLanguageByComment(const Environment &Env)
Definition Format.cpp:4721
FormatStyle getGNUStyle()
Returns a format style complying with GNU Coding Standards: http://www.gnu.org/prep/standards/standar...
Definition Format.cpp:2398
bool isClangFormatOff(StringRef Comment)
Definition Format.cpp:5014
LangOptions getFormattingLangOpts(const FormatStyle &Style=getLLVMStyle())
Returns the LangOpts that the formatter expects you to set.
Definition Format.cpp:4606
static bool isClangFormatOnOff(StringRef Comment, bool On)
Definition Format.cpp:4998
static FormatStyle::LanguageKind getLanguageByFileName(StringRef &FileName)
Definition Format.cpp:4667
tooling::Replacements sortJavaScriptImports(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName)
static void sortJavaImports(const FormatStyle &Style, const ArrayRef< JavaImportDirective > &Imports, ArrayRef< tooling::Range > Ranges, StringRef FileName, StringRef Code, tooling::Replacements &Replaces)
Definition Format.cpp:4016
FormatStyle getMozillaStyle()
Returns a format style complying with Mozilla's style guide: https://firefox-source-docs....
Definition Format.cpp:2347
bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language, FormatStyle *Style)
Gets a predefined style for the specified language by name.
Definition Format.cpp:2464
Expected< tooling::Replacements > cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces, const FormatStyle &Style)
Returns the replacements corresponding to applying Replaces and cleaning up the code after that on su...
Definition Format.cpp:4331
static void expandPresetsBraceWrapping(FormatStyle &Expanded)
Definition Format.cpp:1740
static void sortCppIncludes(const FormatStyle &Style, const ArrayRef< IncludeDirective > &Includes, ArrayRef< tooling::Range > Ranges, StringRef FileName, StringRef Code, tooling::Replacements &Replaces, unsigned *Cursor)
Definition Format.cpp:3685
tooling::Replacements reformat(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>", FormattingAttemptStatus *Status=nullptr)
Reformats the given Ranges in Code.
Definition Format.cpp:4553
bool isClangFormatOn(StringRef Comment)
Definition Format.cpp:5010
tooling::Replacements sortUsingDeclarations(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Sort consecutive using declarations in the given Ranges in Code.
Definition Format.cpp:4596
llvm::Error make_string_error(const Twine &Message)
Definition Format.cpp:1709
ParseError validateQualifierOrder(FormatStyle *Style)
Definition Format.cpp:2497
FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language)
Returns a format style complying with Chromium's style guide: http://www.chromium....
Definition Format.cpp:2287
static void expandPresetsSpacesInParens(FormatStyle &Expanded)
Definition Format.cpp:1872
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
Definition Format.cpp:4564
Expected< tooling::Replacements > formatReplacements(StringRef Code, const tooling::Replacements &Replaces, const FormatStyle &Style)
Returns the replacements corresponding to applying and formatting Replaces on success; otheriwse,...
Definition Format.cpp:4220
FormatStyle getNoStyle()
Returns style indicating formatting should be not applied at all.
Definition Format.cpp:2456
tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName, unsigned *Cursor=nullptr)
Returns the replacements necessary to sort all #include blocks that are affected by Ranges.
Definition Format.cpp:4179
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > loadAndParseConfigFile(StringRef ConfigFile, llvm::vfs::FileSystem *FS, FormatStyle *Style, bool AllowUnknownOptions, llvm::SourceMgr::DiagHandlerTy DiagHandler, bool IsDotHFile)
Definition Format.cpp:4778
static Expected< tooling::Replacements > processReplacements(T ProcessFunc, StringRef Code, const tooling::Replacements &Replaces, const FormatStyle &Style)
Definition Format.cpp:4201
StringRef getLanguageName(FormatStyle::LanguageKind Language)
Definition Format.h:6666
const char * getTokenName(TokenKind Kind) LLVM_READNONE
Determines the name of a token as used within the front end.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:33
const char * getPunctuatorSpelling(TokenKind Kind) LLVM_READNONE
Determines the spelling of simple punctuation tokens like '!
std::vector< Range > calculateRangesAfterReplacements(const Replacements &Replaces, const std::vector< Range > &Ranges)
Calculates the new ranges after Replaces are applied.
Top level wrappers for InstallAPI frontend operations.
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.
Definition TypeBase.h:906
const FunctionProtoType * T
@ On
Always emit colors regardless of the output stream.
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
int const char * function
Definition c++config.h:31
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
int32_t uint32_t uint32_t __builtin_riscv_mhracc_i32 __builtin_riscv_mhraccu_u32 __builtin_riscv_mhraccsu_i32 __builtin_riscv_mhacc_h1_i32 __builtin_riscv_mhaccsu_h1_i32 __builtin_riscv_mulqr_i32 __builtin_riscv_mqrwacc_i64 int8_t
#define false
Definition stdbool.h:26
A rule that specifies how to break a specific set of binary operators.
Definition Format.h:2585
Precise control over the wrapping of braces.
Definition Format.h:1425
bool SplitEmptyRecord
If false, empty record (e.g.
Definition Format.h:1660
bool AfterClass
Wrap class definitions.
Definition Format.h:1451
bool AfterCaseLabel
Wrap case labels.
Definition Format.h:1441
bool AfterStruct
Wrap struct definitions.
Definition Format.h:1534
bool AfterRequiresExpression
Wrap requires expression body.
Definition Format.h:1520
bool BeforeLambdaBody
Wrap lambda block.
Definition Format.h:1618
bool AfterUnion
Wrap union definitions.
Definition Format.h:1548
bool AfterExportBlock
Wrap export blocks.
Definition Format.h:1557
bool AfterEnum
Wrap enum definitions.
Definition Format.h:1466
bool IndentBraces
Indent the wrapped braces themselves.
Definition Format.h:1634
bool AfterObjCDeclaration
Wrap ObjC definitions (interfaces, implementations...).
Definition Format.h:1504
bool BeforeElse
Wrap before else.
Definition Format.h:1601
bool AfterNamespace
Wrap namespace definitions.
Definition Format.h:1498
bool BeforeWhile
Wrap before while.
Definition Format.h:1632
bool SplitEmptyNamespace
If false, empty namespace body can be put on a single line.
Definition Format.h:1672
BraceWrappingAfterControlStatementStyle AfterControlStatement
Wrap control statements (if/for/while/switch/..).
Definition Format.h:1454
bool AfterFunction
Wrap function definitions.
Definition Format.h:1482
bool BeforeCatch
Wrap before catch.
Definition Format.h:1587
bool SplitEmptyFunction
If false, empty function body can be put on a single line.
Definition Format.h:1648
bool AfterExternBlock
Wrap extern blocks.
Definition Format.h:1571
Options for BreakBinaryOperations.
Definition Format.h:2619
Separator format of integer literals of different bases.
Definition Format.h:3589
Options regarding which empty lines are kept.
Definition Format.h:3784
Separate control for each numeric literal component.
Definition Format.h:4102
Options related to packing arguments of function calls.
Definition Format.h:4309
Options related to packing parameters of function declarations and definitions.
Definition Format.h:4443
See documentation of RawStringFormats.
Definition Format.h:4656
Different styles for merging short functions containing at most one statement.
Definition Format.h:893
static ShortFunctionStyle setAll()
Definition Format.h:943
static ShortFunctionStyle setEmptyOnly()
Definition Format.h:934
static ShortFunctionStyle setInlineOnly()
Definition Format.h:940
static ShortFunctionStyle setEmptyAndInline()
Definition Format.h:937
Includes sorting options.
Definition Format.h:5123
Precise control over the spacing before parentheses.
Definition Format.h:5462
bool AfterControlStatements
If true, put space between control statement keywords (for/if/while...) and opening parentheses.
Definition Format.h:5469
bool AfterOverloadedOperator
If true, put a space between operator overloading and opening parentheses.
Definition Format.h:5512
bool AfterRequiresInExpression
If true, put space between requires keyword in a requires expression and opening parentheses.
Definition Format.h:5539
bool AfterFunctionDeclarationName
If true, put a space between function declaration name and opening parentheses.
Definition Format.h:5483
bool AfterRequiresInClause
If true, put space between requires keyword in a requires clause and opening parentheses,...
Definition Format.h:5529
bool AfterForeachMacros
If true, put space between foreach macros and opening parentheses.
Definition Format.h:5476
bool AfterNot
If true, put a space between alternative operator not and the opening parenthesis.
Definition Format.h:5504
bool AfterFunctionDefinitionName
If true, put a space between function definition name and opening parentheses.
Definition Format.h:5490
bool BeforeNonEmptyParentheses
If true, put a space before opening parentheses only if the parentheses are not empty.
Definition Format.h:5547
bool AfterIfMacros
If true, put space between if macros and opening parentheses.
Definition Format.h:5497
bool AfterPlacementOperator
If true, put a space between operator new/delete and opening parenthesis.
Definition Format.h:5520
If true, spaces may be inserted into C style casts.
Definition Format.h:5745
unsigned Maximum
The maximum number of spaces at the start of the comment.
Definition Format.h:5749
unsigned Minimum
The minimum number of spaces at the start of the comment.
Definition Format.h:5747
Precise control over the spacing in parentheses.
Definition Format.h:5824
bool ExceptDoubleParentheses
Override any of the following options to prevent addition of space when both opening and closing pare...
Definition Format.h:5835
bool Other
Put a space in parentheses not covered by preceding options.
Definition Format.h:5867
bool InEmptyParentheses
Insert a space in empty parentheses, i.e.
Definition Format.h:5861
bool InCStyleCasts
Put a space in C style casts.
Definition Format.h:5850
bool InConditionalStatements
Put a space in parentheses only inside conditional statements (for/if/while/switch....
Definition Format.h:5843
UseTabStyle
This option is deprecated.
Definition Format.h:6084
@ UT_AlignWithSpaces
Use tabs for line continuation and indentation, and spaces for alignment.
Definition Format.h:6094
@ UT_ForContinuationAndIndentation
Fill all leading whitespace with tabs, and use spaces for alignment that appears within a line (e....
Definition Format.h:6091
@ UT_ForIndentation
Use tabs only for indentation.
Definition Format.h:6088
@ UT_Always
Use tabs whenever we need to fill whitespace that spans at least from one tab stop to the next one.
Definition Format.h:6097
@ UT_Never
Never use tab.
Definition Format.h:6086
LanguageKind
Supported languages.
Definition Format.h:3874
@ LK_C
Should be used for C.
Definition Format.h:3878
@ LK_CSharp
Should be used for C#.
Definition Format.h:3882
@ LK_None
Do not use.
Definition Format.h:3876
@ LK_Java
Should be used for Java.
Definition Format.h:3884
@ LK_Cpp
Should be used for C++.
Definition Format.h:3880
@ LK_JavaScript
Should be used for JavaScript.
Definition Format.h:3886
@ LK_ObjC
Should be used for Objective-C, Objective-C++.
Definition Format.h:3890
@ LK_Verilog
Should be used for Verilog and SystemVerilog.
Definition Format.h:3901
@ LK_TableGen
Should be used for TableGen code.
Definition Format.h:3894
@ LK_Proto
Should be used for Protocol Buffers
Definition Format.h:3892
@ LK_Json
Should be used for JSON.
Definition Format.h:3888
@ LK_TextProto
Should be used for Protocol Buffer messages in text format.
Definition Format.h:3897
ShortLambdaStyle
Different styles for merging short lambdas containing at most one statement.
Definition Format.h:1026
@ SLS_All
Merge all lambdas fitting on a single line.
Definition Format.h:1050
@ SLS_Inline
Merge lambda into a single line if the lambda is argument of a function.
Definition Format.h:1044
@ SLS_None
Never merge lambdas into a single line.
Definition Format.h:1028
@ SLS_Empty
Only merge empty lambdas.
Definition Format.h:1036
SeparateDefinitionStyle
The style if definition blocks should be separated.
Definition Format.h:5039
@ SDS_Never
Remove any empty line between definition blocks.
Definition Format.h:5045
@ SDS_Always
Insert an empty line between definition blocks.
Definition Format.h:5043
@ SDS_Leave
Leave definition blocks as they are.
Definition Format.h:5041
SortJavaStaticImportOptions
Position for Java Static imports.
Definition Format.h:5194
@ SJSIO_Before
Static imports are placed before non-static imports.
Definition Format.h:5201
@ SJSIO_After
Static imports are placed after non-static imports.
Definition Format.h:5208
EnumTrailingCommaStyle
Styles for enum trailing commas.
Definition Format.h:3095
@ ETC_Remove
Remove trailing commas.
Definition Format.h:3113
@ ETC_Insert
Insert trailing commas.
Definition Format.h:3107
@ ETC_Leave
Don't insert or remove trailing commas.
Definition Format.h:3101
TrailingCommaStyle
The style of inserting trailing commas into container literals.
Definition Format.h:3530
@ TCS_Wrapped
Insert trailing commas in container literals that were wrapped over multiple lines.
Definition Format.h:3538
@ TCS_None
Do not insert trailing commas.
Definition Format.h:3532
BinPackParametersStyle
Different ways to try to fit all parameters on a line.
Definition Format.h:4412
@ BPPS_OnePerLine
Put all parameters on the current line if they fit.
Definition Format.h:4428
@ BPPS_UseBreakAfter
Use the BreakAfter option to handle parameter packing instead.
Definition Format.h:4438
@ BPPS_BinPack
Bin-pack parameters.
Definition Format.h:4418
@ BPPS_AlwaysOnePerLine
Always put each parameter on its own line.
Definition Format.h:4435
BinPackStyle
The style of wrapping parameters on the same line (bin-packed) or on one line each.
Definition Format.h:1881
@ BPS_Never
Never bin-pack parameters.
Definition Format.h:1887
@ BPS_Auto
Automatically determine parameter bin-packing behavior.
Definition Format.h:1883
@ BPS_Always
Always bin-pack parameters.
Definition Format.h:1885
ReflowCommentsStyle
Types of comment reflow style.
Definition Format.h:4742
@ RCS_IndentOnly
Only apply indentation rules, moving comments left or right, without changing formatting inside the c...
Definition Format.h:4759
@ RCS_Never
Leave comments untouched.
Definition Format.h:4750
@ RCS_Always
Apply indentation rules and reflow long comments into new lines, trying to obey the ColumnLimit.
Definition Format.h:4770
EmptyLineBeforeAccessModifierStyle
Different styles for empty line before access modifiers.
Definition Format.h:3032
@ ELBAMS_LogicalBlock
Add empty line only when access modifier starts a new logical block.
Definition Format.h:3067
@ ELBAMS_Never
Remove all empty lines before access modifiers.
Definition Format.h:3047
@ ELBAMS_Always
Always add empty line before access modifiers unless access modifier is at the start of struct or cla...
Definition Format.h:3087
@ ELBAMS_Leave
Keep existing empty lines before access modifiers.
Definition Format.h:3049
BreakConstructorInitializersStyle
Different ways to break initializers.
Definition Format.h:2663
@ BCIS_AfterColon
Break constructor initializers after the colon and commas.
Definition Format.h:2685
@ BCIS_AfterComma
Break constructor initializers only after the commas.
Definition Format.h:2691
@ BCIS_BeforeColon
Break constructor initializers before the colon and after the commas.
Definition Format.h:2670
@ BCIS_BeforeComma
Break constructor initializers before the colon and commas, and align the commas with the colon.
Definition Format.h:2678
IndentExternBlockStyle
Indents extern blocks.
Definition Format.h:3298
@ IEBS_AfterExternBlock
Backwards compatible with AfterExternBlock's indenting.
Definition Format.h:3316
@ IEBS_Indent
Indents extern blocks.
Definition Format.h:3330
@ IEBS_NoIndent
Does not indent extern blocks.
Definition Format.h:3323
BinaryOperatorStyle
The style of breaking before or after binary operators.
Definition Format.h:1891
@ BOS_All
Break before operators.
Definition Format.h:1927
@ BOS_None
Break after operators.
Definition Format.h:1903
@ BOS_NonAssignment
Break before operators that aren't assignments.
Definition Format.h:1915
LineEndingStyle
Line ending style.
Definition Format.h:3925
@ LE_DeriveLF
Use \n unless the input has more lines ending in \r\n.
Definition Format.h:3931
@ LE_CRLF
Use \r\n.
Definition Format.h:3929
@ LE_DeriveCRLF
Use \r\n unless the input has more lines ending in \n.
Definition Format.h:3933
@ LE_LF
Use \n.
Definition Format.h:3927
TrailingCommentsAlignmentKinds
Enums for AlignTrailingComments.
Definition Format.h:552
@ TCAS_Never
Don't align trailing comments but other formatter applies.
Definition Format.h:579
@ TCAS_Leave
Leave trailing comments as they are.
Definition Format.h:561
@ TCAS_Always
Align trailing comments.
Definition Format.h:570
NumericLiteralComponentStyle
Control over each component in a numeric literal.
Definition Format.h:4081
@ NLCS_Lower
Format this component with lowercase characters.
Definition Format.h:4087
@ NLCS_Leave
Leave this component of the literal as is.
Definition Format.h:4083
@ NLCS_Upper
Format this component with uppercase characters.
Definition Format.h:4085
SpacesInParensStyle
Different ways to put a space before opening and closing parentheses.
Definition Format.h:5787
@ SIPO_Custom
Configure each individual space in parentheses in SpacesInParensOptions.
Definition Format.h:5799
@ SIPO_Never
Never put a space in parentheses.
Definition Format.h:5796
ShortRecordStyle
Different styles for merging short records (class,struct, and union).
Definition Format.h:1069
@ SRS_EmptyAndAttached
Only merge empty records if the opening brace was not wrapped, i.e.
Definition Format.h:1074
@ SRS_Empty
Only merge empty records.
Definition Format.h:1083
@ SRS_Always
Merge all records that fit on a single line.
Definition Format.h:1089
@ SRS_Never
Never merge records into a single line.
Definition Format.h:1071
BreakBeforeInlineASMColonStyle
Different ways to break ASM parameters.
Definition Format.h:2457
@ BBIAS_Always
Always break before inline ASM colon.
Definition Format.h:2478
@ BBIAS_OnlyMultiline
Break before inline ASM colon if the line length is longer than column limit.
Definition Format.h:2471
@ BBIAS_Never
No break before inline ASM colon.
Definition Format.h:2462
PPDirectiveIndentStyle
Options for indenting preprocessor directives.
Definition Format.h:3396
@ PPDIS_Leave
Leaves indentation of directives as-is.
Definition Format.h:3435
@ PPDIS_BeforeHash
Indents directives before the hash.
Definition Format.h:3423
@ PPDIS_None
Does not indent any directives.
Definition Format.h:3405
@ PPDIS_AfterHash
Indents directives after the hash.
Definition Format.h:3414
LambdaBodyIndentationKind
Indentation logic for lambda bodies.
Definition Format.h:3836
@ LBI_OuterScope
For statements within block scope, align lambda body relative to the indentation level of the outer s...
Definition Format.h:3858
@ LBI_Signature
Align lambda body relative to the lambda signature.
Definition Format.h:3844
ShortBlockStyle
Different styles for merging short blocks containing at most one statement.
Definition Format.h:737
@ SBS_Always
Always merge short blocks into a single line.
Definition Format.h:760
@ SBS_Empty
Only merge empty blocks.
Definition Format.h:754
@ SBS_Never
Never merge blocks into a single line.
Definition Format.h:746
ShortIfStyle
Different styles for handling short if statements.
Definition Format.h:954
@ SIS_WithoutElse
Put short ifs on the same line only if there is no else statement.
Definition Format.h:987
@ SIS_Never
Never put short ifs on the same line.
Definition Format.h:971
@ SIS_OnlyFirstIf
Put short ifs, but not else ifs nor else statements, on the same line.
Definition Format.h:1003
@ SIS_AllIfsAndElse
Always put short ifs, else ifs and else statements on the same line.
Definition Format.h:1017
BreakTemplateDeclarationsStyle
Different ways to break after the template declaration.
Definition Format.h:1229
@ BTDS_No
Do not force break before declaration.
Definition Format.h:1249
@ BTDS_MultiLine
Force break after template declaration only when the following declaration spans multiple lines.
Definition Format.h:1260
@ BTDS_Yes
Always break after template declaration.
Definition Format.h:1271
@ BTDS_Leave
Do not change the line breaking before the declaration.
Definition Format.h:1239
SpaceBeforeParensStyle
Different ways to put a space before opening parentheses.
Definition Format.h:5394
@ SBPO_Never
This is deprecated and replaced by Custom below, with all SpaceBeforeParensOptions but AfterPlacement...
Definition Format.h:5398
@ SBPO_Custom
Configure each individual space before parentheses in SpaceBeforeParensOptions.
Definition Format.h:5447
@ SBPO_NonEmptyParentheses
Put a space before opening parentheses only if the parentheses are not empty.
Definition Format.h:5432
@ SBPO_ControlStatementsExceptControlMacros
Same as SBPO_ControlStatements except this option doesn't apply to ForEach and If macros.
Definition Format.h:5421
@ SBPO_ControlStatements
Put a space before opening parentheses only after control statement keywords (for/if/while....
Definition Format.h:5408
@ SBPO_Always
Always put a space before opening parentheses, except when it's prohibited by the syntax rules (in fu...
Definition Format.h:5444
PackConstructorInitializersStyle
Different ways to try to fit all constructor initializers on a line.
Definition Format.h:4350
@ PCIS_NextLineOnly
Put all constructor initializers on the next line if they fit.
Definition Format.h:4404
@ PCIS_Never
Always put each constructor initializer on its own line.
Definition Format.h:4357
@ PCIS_CurrentLine
Put all constructor initializers on the current line if they fit.
Definition Format.h:4375
@ PCIS_BinPack
Bin-pack constructor initializers.
Definition Format.h:4364
@ PCIS_NextLine
Same as PCIS_CurrentLine except that if all constructor initializers do not fit on the current line,...
Definition Format.h:4389
BreakBeforeReturnTypeStyle
Different ways to break before the function return type.
Definition Format.h:2486
@ BBRTS_None
Do not force a break before the return type.
Definition Format.h:2488
@ BBRTS_TopLevelDefinitions
Break before the return type of top-level definitions only.
Definition Format.h:2500
@ BBRTS_TopLevel
Break before the return type of top-level functions only.
Definition Format.h:2496
@ BBRTS_All
Always break before the return type.
Definition Format.h:2494
@ BBRTS_AllDefinitions
Break before the return type of function definitions only.
Definition Format.h:2498
BreakInheritanceListStyle
Different ways to break inheritance list.
Definition Format.h:2798
@ BILS_AfterColon
Break inheritance list after the colon and commas.
Definition Format.h:2823
@ BILS_AfterComma
Break inheritance list only after the commas.
Definition Format.h:2830
@ BILS_BeforeColon
Break inheritance list before the colon and after the commas.
Definition Format.h:2806
@ BILS_BeforeComma
Break inheritance list before the colon and commas, and align the commas with the colon.
Definition Format.h:2815
SpacesInBlockCommentsStyle
Styles for controlling spacing after /* and before `.
Definition Format.h:5698
@ SIBCS_Always
Add spaces after /* and before `.
Definition Format.h:5708
@ SIBCS_Leave
Leave existing spaces unchanged.
Definition Format.h:5710
@ SIBCS_Never
Remove spaces after /* and before `.
Definition Format.h:5703
DAGArgStyle
Different ways to control the format inside TableGen DAGArg.
Definition Format.h:6012
@ DAS_BreakElements
Break inside DAGArg after each list element but for the last.
Definition Format.h:6024
@ DAS_DontBreak
Never break inside DAGArg.
Definition Format.h:6017
@ DAS_BreakAll
Break inside DAGArg after the operator and the all elements.
Definition Format.h:6032
BreakBeforeNoexceptSpecifierStyle
Different ways to break before a noexcept specifier.
Definition Format.h:689
@ BBNSS_Never
No line break allowed.
Definition Format.h:699
@ BBNSS_Always
Line breaks are allowed.
Definition Format.h:722
@ BBNSS_OnlyWithParen
For a simple noexcept there is no line break allowed, but when we have a condition it is.
Definition Format.h:710
RequiresClausePositionStyle
The possible positions for the requires clause.
Definition Format.h:4911
@ RCPS_OwnLineWithBrace
As with OwnLine, except, unless otherwise prohibited, place a following open brace (of a function def...
Definition Format.h:4950
@ RCPS_OwnLine
Always put the requires clause on its own line (possibly followed by a semicolon).
Definition Format.h:4932
@ RCPS_WithPreceding
Try to put the clause together with the preceding part of a declaration.
Definition Format.h:4967
@ RCPS_SingleLine
Try to put everything in the same line if possible.
Definition Format.h:5005
@ RCPS_WithFollowing
Try to put the requires clause together with the class or function declaration.
Definition Format.h:4981
LanguageStandard
Supported language standards for parsing and formatting C++ constructs.
Definition Format.h:5927
@ LS_Cpp17
Parse and format as C++17.
Definition Format.h:5936
@ LS_Cpp26
Parse and format as C++26.
Definition Format.h:5942
@ LS_Cpp23
Parse and format as C++23.
Definition Format.h:5940
@ LS_Latest
Parse and format using the latest supported language version.
Definition Format.h:5945
@ LS_Cpp11
Parse and format as C++11.
Definition Format.h:5932
@ LS_Auto
Automatic detection based on the input.
Definition Format.h:5947
@ LS_Cpp03
Parse and format as C++03.
Definition Format.h:5930
@ LS_Cpp14
Parse and format as C++14.
Definition Format.h:5934
@ LS_Cpp20
Parse and format as C++20.
Definition Format.h:5938
BraceWrappingAfterControlStatementStyle
Different ways to wrap braces after control statements.
Definition Format.h:1385
@ BWACS_Always
Always wrap braces after a control statement.
Definition Format.h:1415
@ BWACS_Never
Never wrap braces after a control statement.
Definition Format.h:1394
@ BWACS_MultiLine
Only wrap braces after a multi-line control statement.
Definition Format.h:1405
JavaScriptQuoteStyle
Quotation styles for JavaScript strings.
Definition Format.h:3730
@ JSQS_Double
Always use double quotes.
Definition Format.h:3748
@ JSQS_Single
Always use single quotes.
Definition Format.h:3742
@ JSQS_Leave
Leave string quotes as they are.
Definition Format.h:3736
IndentAccessModifierStyle
Modes for indenting access modifiers and record members.
Definition Format.h:3200
@ IAMS_Never
Use AccessModifierOffset for access modifiers and indent members one level below the record.
Definition Format.h:3211
@ IAMS_AfterFirstAccessModifier
In C, C++, and Objective-C, indent members one level until the first explicit access modifier,...
Definition Format.h:3235
@ IAMS_Always
Give access modifiers their own indentation level and indent all members two levels below the record.
Definition Format.h:3223
WrapNamespaceBodyWithEmptyLinesStyle
Different styles for wrapping namespace body with empty lines.
Definition Format.h:6145
@ WNBWELS_Always
Always have at least one empty line at the beginning and the end of namespace body except that the nu...
Definition Format.h:6167
@ WNBWELS_Leave
Keep existing newlines at the beginning and the end of namespace body.
Definition Format.h:6170
@ WNBWELS_Never
Remove all empty lines at the beginning and the end of namespace body.
Definition Format.h:6154
BraceBreakingStyle
Different ways to attach braces to their surrounding context.
Definition Format.h:1935
@ BS_Mozilla
Like Attach, but break before braces on enum, function, and record definitions.
Definition Format.h:2080
@ BS_Whitesmiths
Like Allman but always indent braces and line up code with braces.
Definition Format.h:2250
@ BS_Allman
Always break before braces.
Definition Format.h:2190
@ BS_Stroustrup
Like Attach, but break before function definitions, catch, and else.
Definition Format.h:2130
@ BS_Linux
Like Attach, but break before braces on function, namespace and class definitions.
Definition Format.h:2030
@ BS_WebKit
Like Attach, but break before functions.
Definition Format.h:2360
@ BS_Custom
Configure each individual brace in BraceWrapping.
Definition Format.h:2362
@ BS_GNU
Always break before braces and add an extra level of indentation to braces of control statements,...
Definition Format.h:2313
@ BS_Attach
Always attach braces to surrounding context.
Definition Format.h:1980
AttributeBreakingStyle
Different ways to break after the last attribute of a group before a declaration or control statement...
Definition Format.h:1705
@ ABS_Leave
Leave the line breaking after the last attribute of the group as is.
Definition Format.h:1759
@ ABS_Never
Never break after the last attribute of the group.
Definition Format.h:1795
@ ABS_Always
Always break after the last attribute of the group.
Definition Format.h:1734
@ ABS_LeaveAll
Same as Leave except that it applies to all attributes of the group.
Definition Format.h:1773
BitFieldColonSpacingStyle
This option is deprecated.
Definition Format.h:1323
@ BFCS_Both
Add one space on each side of the :
Definition Format.h:1328
@ BFCS_Before
Add space before the : only.
Definition Format.h:1339
@ BFCS_None
Add no space around the : (except when needed for AlignConsecutiveBitFields).
Definition Format.h:1334
@ BFCS_After
Add space after the : only (space may be added before if needed for AlignConsecutiveBitFields).
Definition Format.h:1345
RequiresExpressionIndentationKind
Indentation logic for requires expression bodies.
Definition Format.h:5013
@ REI_Keyword
Align requires expression body relative to the requires keyword.
Definition Format.h:5031
@ REI_OuterScope
Align requires expression body relative to the indentation level of the outer scope the requires expr...
Definition Format.h:5023
BreakBeforeConceptDeclarationsStyle
Different ways to break before concept declarations.
Definition Format.h:2433
@ BBCDS_Allowed
Breaking between template declaration and concept is allowed.
Definition Format.h:2442
@ BBCDS_Never
Keep the template declaration line together with concept.
Definition Format.h:2438
@ BBCDS_Always
Always break before concept, putting it in the line after the template declaration.
Definition Format.h:2449
BracedListStyle
Different ways to handle braced lists.
Definition Format.h:2902
@ BLS_AlignFirstComment
Same as FunctionCall, except for the handling of a comment at the begin, it then aligns everything fo...
Definition Format.h:2956
@ BLS_FunctionCall
Best suited for C++11 braced lists.
Definition Format.h:2938
@ BLS_Block
Best suited for pre C++11 braced lists.
Definition Format.h:2918
SpaceAroundPointerQualifiersStyle
Different ways to put a space before opening parentheses.
Definition Format.h:5294
@ SAPQ_After
Ensure that there is a space after pointer qualifiers.
Definition Format.h:5313
@ SAPQ_Default
Don't ensure spaces around pointer qualifiers and use PointerAlignment instead.
Definition Format.h:5301
@ SAPQ_Both
Ensure that there is a space both before and after pointer qualifiers.
Definition Format.h:5319
@ SAPQ_Before
Ensure that there is a space before pointer qualifiers.
Definition Format.h:5307
EmptyLineAfterAccessModifierStyle
Different styles for empty line after access modifiers.
Definition Format.h:2983
@ ELAAMS_Always
Always add empty line after access modifiers if there are none.
Definition Format.h:3022
@ ELAAMS_Never
Remove all empty lines after access modifiers.
Definition Format.h:2998
@ ELAAMS_Leave
Keep existing empty lines after access modifiers.
Definition Format.h:3001
DefinitionReturnTypeBreakingStyle
Different ways to break after the function definition return type.
Definition Format.h:1099
@ DRTBS_All
Always break after the return type.
Definition Format.h:1104
@ DRTBS_TopLevel
Always break after the return types of top-level functions.
Definition Format.h:1106
@ DRTBS_None
Break after return type automatically.
Definition Format.h:1102
ArrayInitializerAlignmentStyle
Different style for aligning array initializers.
Definition Format.h:85
@ AIAS_Left
Align array column and left justify the columns e.g.:
Definition Format.h:95
@ AIAS_Right
Align array column and right justify the columns e.g.:
Definition Format.h:105
@ AIAS_None
Don't align array initializer columns.
Definition Format.h:107
BreakBinaryOperationsStyle
Different ways to break binary operations.
Definition Format.h:2553
@ BBO_OnePerLine
Binary operations will either be all on the same line, or each operation will have one line each.
Definition Format.h:2570
@ BBO_Never
Don't break binary operations.
Definition Format.h:2559
@ BBO_RespectPrecedence
Binary operations of a particular precedence that exceed the column limit will have one line each.
Definition Format.h:2580
EscapedNewlineAlignmentStyle
Different styles for aligning escaped newlines.
Definition Format.h:472
@ ENAS_DontAlign
Don't align escaped newlines.
Definition Format.h:480
@ ENAS_Left
Align escaped newlines as far left as possible.
Definition Format.h:488
@ ENAS_Right
Align escaped newlines in the right-most column.
Definition Format.h:505
@ ENAS_LeftWithLastLine
Align escaped newlines as far left as possible, using the last line of the preprocessor directive as ...
Definition Format.h:497
SpacesInAnglesStyle
Styles for adding spacing after < and before > in template argument lists.
Definition Format.h:5675
@ SIAS_Never
Remove spaces after < and before >.
Definition Format.h:5681
@ SIAS_Always
Add spaces after < and before >.
Definition Format.h:5687
@ SIAS_Leave
Keep a single space after < and before > if any spaces were present.
Definition Format.h:5690
BinPackArgumentsStyle
Different ways to try to fit all arguments on a line.
Definition Format.h:4284
@ BPAS_OnePerLine
Put all arguments on the current line if they fit.
Definition Format.h:4302
@ BPAS_BinPack
Bin-pack arguments.
Definition Format.h:4292
@ BPAS_UseBreakAfter
Use the BreakAfter option to handle argument packing instead.
Definition Format.h:4305
SortUsingDeclarationsOptions
Using declaration sorting options.
Definition Format.h:5218
@ SUD_LexicographicNumeric
Using declarations are sorted in the order defined as follows: Split the strings by :: and discard an...
Definition Format.h:5254
@ SUD_Lexicographic
Using declarations are sorted in the order defined as follows: Split the strings by :: and discard an...
Definition Format.h:5239
@ SUD_Never
Using declarations are never sorted.
Definition Format.h:5227
SpaceInEmptyBracesStyle
This option is deprecated.
Definition Format.h:5612
@ SIEB_Always
Always insert a space in empty braces.
Definition Format.h:5620
@ SIEB_Block
Only insert a space in empty blocks.
Definition Format.h:5628
@ SIEB_Never
Never insert a space in empty braces.
Definition Format.h:5636
RemoveParenthesesStyle
Types of redundant parentheses to remove.
Definition Format.h:4856
@ RPS_Leave
Do not remove parentheses.
Definition Format.h:4863
@ RPS_ReturnStatement
Also remove parentheses enclosing the expression in a return/co_return statement.
Definition Format.h:4878
@ RPS_MultipleParentheses
Replace multiple parentheses with single parentheses.
Definition Format.h:4870
PointerAlignmentStyle
The &, && and * alignment style.
Definition Format.h:4532
@ PAS_Left
Align pointer to the left.
Definition Format.h:4537
@ PAS_Middle
Align pointer in the middle.
Definition Format.h:4547
@ PAS_Right
Align pointer to the right.
Definition Format.h:4542
NamespaceIndentationKind
Different ways to indent namespace contents.
Definition Format.h:4030
@ NI_None
Don't indent in namespaces.
Definition Format.h:4040
@ NI_All
Indent in all namespaces.
Definition Format.h:4060
@ NI_Inner
Indent only in inner namespaces (nested in other namespaces).
Definition Format.h:4050
ReturnTypeBreakingStyle
Different ways to break after the function definition or declaration return type.
Definition Format.h:1111
@ RTBS_TopLevelDefinitions
Always break after the return type of top-level definitions.
Definition Format.h:1200
@ RTBS_ExceptShortType
Same as Automatic above, except that there is no break after short return types.
Definition Format.h:1136
@ RTBS_All
Always break after the return type.
Definition Format.h:1154
@ RTBS_TopLevel
Always break after the return types of top-level functions.
Definition Format.h:1169
@ RTBS_None
This is deprecated. See Automatic below.
Definition Format.h:1113
@ RTBS_Automatic
Break after return type based on PenaltyReturnTypeOnItsOwnLine.
Definition Format.h:1124
@ RTBS_AllDefinitions
Always break after the return type of function definitions.
Definition Format.h:1186
ReferenceAlignmentStyle
The & and && alignment style.
Definition Format.h:4716
@ RAS_Right
Align reference to the right.
Definition Format.h:4728
@ RAS_Left
Align reference to the left.
Definition Format.h:4723
@ RAS_Pointer
Align reference like PointerAlignment.
Definition Format.h:4718
@ RAS_Middle
Align reference in the middle.
Definition Format.h:4733
IndentGotoLabelStyle
Options for indenting goto labels.
Definition Format.h:3338
@ IGLS_InnerIndent
Indent goto labels to the surrounding statements (current indenting level).
Definition Format.h:3375
@ IGLS_OuterIndent
Indent goto labels to the enclosing block (previous indenting level).
Definition Format.h:3362
@ IGLS_HalfIndent
Indent goto labels to half the indentation of the surrounding code.
Definition Format.h:3388
@ IGLS_NoIndent
Do not indent goto labels.
Definition Format.h:3350
QualifierAlignmentStyle
Different specifiers and qualifiers alignment styles.
Definition Format.h:4570
@ QAS_Right
Change specifiers/qualifiers to be right-aligned.
Definition Format.h:4589
@ QAS_Custom
Change specifiers/qualifiers to be aligned based on QualifierOrder.
Definition Format.h:4601
@ QAS_Left
Change specifiers/qualifiers to be left-aligned.
Definition Format.h:4583
@ QAS_Leave
Don't change specifiers/qualifiers to either Left or Right alignment (default).
Definition Format.h:4577
OperandAlignmentStyle
Different styles for aligning operands.
Definition Format.h:513
@ OAS_Align
Horizontally align operands of binary and ternary expressions.
Definition Format.h:533
@ OAS_AlignAfterOperator
Horizontally align operands of binary and ternary expressions.
Definition Format.h:543
@ OAS_DontAlign
Do not align operands of binary and ternary expressions.
Definition Format.h:517
bool PadOperators
Only for AlignConsecutiveAssignments.
Definition Format.h:257
bool AlignFunctionDeclarations
Only for AlignConsecutiveDeclarations.
Definition Format.h:217
bool SplitEmptyRecord
If false, empty record (e.g.
Definition Format.h:1660
bool AfterClass
Wrap class definitions.
Definition Format.h:1451
bool AfterStruct
Wrap struct definitions.
Definition Format.h:1534
bool AfterRequiresExpression
Wrap requires expression body.
Definition Format.h:1520
bool AfterUnion
Wrap union definitions.
Definition Format.h:1548
bool AfterEnum
Wrap enum definitions.
Definition Format.h:1466
bool AfterObjCDeclaration
Wrap ObjC definitions (interfaces, implementations...).
Definition Format.h:1504
bool AfterNamespace
Wrap namespace definitions.
Definition Format.h:1498
BraceWrappingAfterControlStatementStyle AfterControlStatement
Wrap control statements (if/for/while/switch/..).
Definition Format.h:1454
bool AfterFunction
Wrap function definitions.
Definition Format.h:1482
bool SplitEmptyFunction
If false, empty function body can be put on a single line.
Definition Format.h:1648
std::optional< FormatStyle > Get(LanguageKind Language) const
Definition Format.cpp:2642
bool AtStartOfBlock
Keep empty lines at start of a block.
Definition Format.h:3804
BinPackArgumentsStyle BinPack
The bin pack arguments style to use.
Definition Format.h:4313
BinPackParametersStyle BinPack
The bin pack parameters style to use.
Definition Format.h:4447
Different styles for merging short functions containing at most one statement.
Definition Format.h:893
static ShortFunctionStyle setAll()
Definition Format.h:943
static ShortFunctionStyle setEmptyOnly()
Definition Format.h:934
static ShortFunctionStyle setEmptyAndInline()
Definition Format.h:937
bool AfterControlStatements
If true, put space between control statement keywords (for/if/while...) and opening parentheses.
Definition Format.h:5469
bool AfterForeachMacros
If true, put space between foreach macros and opening parentheses.
Definition Format.h:5476
bool BeforeNonEmptyParentheses
If true, put a space before opening parentheses only if the parentheses are not empty.
Definition Format.h:5547
bool AfterIfMacros
If true, put space between if macros and opening parentheses.
Definition Format.h:5497
bool AfterPlacementOperator
If true, put a space between operator new/delete and opening parenthesis.
Definition Format.h:5520
TrailingCommentsAlignmentKinds Kind
Specifies the way to align trailing comments.
Definition Format.h:585
unsigned OverEmptyLines
How many empty lines to apply alignment.
Definition Format.h:608
bool AlignPPAndNotPP
If comments following preprocessor directive should be aligned with comments that don't.
Definition Format.h:617
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition Format.h:51
@ UT_Never
Never use tab.
Definition Format.h:6086
bool SpaceBeforeInheritanceColon
If false, spaces will be removed before inheritance colon.
Definition Format.h:5380
unsigned ContinuationIndentWidth
Indent width for line continuations.
Definition Format.h:2899
bool AlwaysBreakBeforeMultilineStrings
This option is renamed to BreakAfterReturnType.
Definition Format.h:1226
LanguageStandard Standard
Parse and format C++ constructs compatible with this standard.
Definition Format.h:5956
bool BreakAdjacentStringLiterals
Break between adjacent string literals.
Definition Format.h:1701
ReturnTypeBreakingStyle BreakAfterReturnType
The function declaration return type breaking style to use.
Definition Format.h:1858
LanguageKind
Supported languages.
Definition Format.h:3874
@ LK_C
Should be used for C.
Definition Format.h:3878
@ LK_CSharp
Should be used for C#.
Definition Format.h:3882
@ LK_Java
Should be used for Java.
Definition Format.h:3884
@ LK_Cpp
Should be used for C++.
Definition Format.h:3880
@ LK_JavaScript
Should be used for JavaScript.
Definition Format.h:3886
@ LK_ObjC
Should be used for Objective-C, Objective-C++.
Definition Format.h:3890
@ LK_Verilog
Should be used for Verilog and SystemVerilog.
Definition Format.h:3901
@ LK_TableGen
Should be used for TableGen code.
Definition Format.h:3894
@ LK_Proto
Should be used for Protocol Buffers
Definition Format.h:3892
@ LK_Json
Should be used for JSON.
Definition Format.h:3888
@ LK_TextProto
Should be used for Protocol Buffer messages in text format.
Definition Format.h:3897
SortIncludesOptions SortIncludes
Controls if and how clang-format will sort #includes.
Definition Format.h:5191
BreakInheritanceListStyle BreakInheritanceList
The inheritance list style to use.
Definition Format.h:2835
bool BreakAfterOpenBracketIf
Force break after the left parenthesis of an if control statement when the expression exceeds the col...
Definition Format.h:1834
unsigned IndentWidth
The number of columns to use for indentation.
Definition Format.h:3477
std::vector< std::string > AttributeMacros
This option is renamed to BreakTemplateDeclarations.
Definition Format.h:1296
@ SLS_All
Merge all lambdas fitting on a single line.
Definition Format.h:1050
@ SLS_Empty
Only merge empty lambdas.
Definition Format.h:1036
@ SDS_Leave
Leave definition blocks as they are.
Definition Format.h:5041
bool IndentRequiresClause
Indent the requires clause in a template.
Definition Format.h:3463
SpacesInAnglesStyle SpacesInAngles
The SpacesInAnglesStyle to use for template argument lists.
Definition Format.h:5694
bool KeepFormFeed
This option is deprecated.
Definition Format.h:3833
bool IndentCaseLabels
Indent case labels one level from the switch statement.
Definition Format.h:3282
std::vector< RawStringFormat > RawStringFormats
Defines hints for detecting supported languages code blocks in raw strings.
Definition Format.h:4713
@ SJSIO_Before
Static imports are placed before non-static imports.
Definition Format.h:5201
@ SJSIO_After
Static imports are placed after non-static imports.
Definition Format.h:5208
PPDirectiveIndentStyle IndentPPDirectives
The preprocessor directive indenting style to use.
Definition Format.h:3440
bool RemoveSemicolon
Remove semicolons after the closing braces of functions and constructors/destructors.
Definition Format.h:4907
@ ETC_Leave
Don't insert or remove trailing commas.
Definition Format.h:3101
bool SpaceBeforeJsonColon
If true, a space will be added before a JSON colon.
Definition Format.h:5391
@ TCS_Wrapped
Insert trailing commas in container literals that were wrapped over multiple lines.
Definition Format.h:3538
@ TCS_None
Do not insert trailing commas.
Definition Format.h:3532
unsigned PenaltyBreakBeforeFirstCallParameter
The penalty for breaking a function call after call(.
Definition Format.h:4488
bool SpaceBeforeCtorInitializerColon
If false, spaces will be removed before constructor initializer colon.
Definition Format.h:5364
@ BPPS_OnePerLine
Put all parameters on the current line if they fit.
Definition Format.h:4428
@ BPPS_BinPack
Bin-pack parameters.
Definition Format.h:4418
BinaryOperatorStyle BreakBeforeBinaryOperators
The way to wrap binary operators.
Definition Format.h:1932
bool IndentExportBlock
If true, clang-format will indent the body of an export { ... } block.
Definition Format.h:3295
@ BPS_Never
Never bin-pack parameters.
Definition Format.h:1887
@ BPS_Auto
Automatically determine parameter bin-packing behavior.
Definition Format.h:1883
BitFieldColonSpacingStyle BitFieldColonSpacing
The BitFieldColonSpacingStyle to use for bitfields.
Definition Format.h:1349
@ RCS_Always
Apply indentation rules and reflow long comments into new lines, trying to obey the ColumnLimit.
Definition Format.h:4770
@ ELBAMS_LogicalBlock
Add empty line only when access modifier starts a new logical block.
Definition Format.h:3067
unsigned SpacesBeforeTrailingComments
If true, spaces may be inserted into ().
Definition Format.h:5671
@ BCIS_BeforeColon
Break constructor initializers before the colon and after the commas.
Definition Format.h:2670
@ BCIS_BeforeComma
Break constructor initializers before the colon and commas, and align the commas with the colon.
Definition Format.h:2678
@ IEBS_AfterExternBlock
Backwards compatible with AfterExternBlock's indenting.
Definition Format.h:3316
bool IndentCaseBlocks
Indent case label blocks one level from the case label.
Definition Format.h:3263
bool InsertBraces
Insert braces after control statements (if, else, for, do, and while) in C++ unless the control state...
Definition Format.h:3523
BreakBeforeConceptDeclarationsStyle BreakBeforeConceptDeclarations
The concept declaration style to use.
Definition Format.h:2454
BreakTemplateDeclarationsStyle BreakTemplateDeclarations
The template declaration breaking style to use.
Definition Format.h:2839
bool DerivePointerAlignment
This option is deprecated.
Definition Format.h:2974
@ BOS_All
Break before operators.
Definition Format.h:1927
@ BOS_None
Break after operators.
Definition Format.h:1903
@ BOS_NonAssignment
Break before operators that aren't assignments.
Definition Format.h:1915
@ LE_DeriveLF
Use \n unless the input has more lines ending in \r\n.
Definition Format.h:3931
bool SpacesInSquareBrackets
If true, spaces will be inserted after [ and before ].
Definition Format.h:5917
bool IndentWrappedFunctionNames
Indent if a function definition or declaration is wrapped after the type.
Definition Format.h:3491
AlignConsecutiveStyle AlignConsecutiveTableGenBreakingDAGArgColons
Style of aligning consecutive TableGen DAGArg operator colons.
Definition Format.h:449
WrapNamespaceBodyWithEmptyLinesStyle WrapNamespaceBodyWithEmptyLines
Wrap namespace body with empty lines.
Definition Format.h:6175
bool FixNamespaceComments
If true, clang-format adds missing namespace end comments for namespaces and fixes invalid existing o...
Definition Format.h:3156
bool ObjCSpaceBeforeProtocolList
Add a space in front of an Objective-C protocol list, i.e.
Definition Format.h:4256
@ TCAS_Never
Don't align trailing comments but other formatter applies.
Definition Format.h:579
@ TCAS_Always
Align trailing comments.
Definition Format.h:570
RemoveParenthesesStyle RemoveParentheses
Remove redundant parentheses.
Definition Format.h:4889
LanguageKind Language
The language that this format style targets.
Definition Format.h:3922
@ NLCS_Leave
Leave this component of the literal as is.
Definition Format.h:4083
bool BreakBeforeCloseBracketFunction
Force break before the right parenthesis of a function (declaration, definition, call) when the param...
Definition Format.h:2391
@ SIPO_Custom
Configure each individual space in parentheses in SpacesInParensOptions.
Definition Format.h:5799
@ SIPO_Never
Never put a space in parentheses.
Definition Format.h:5796
@ SRS_EmptyAndAttached
Only merge empty records if the opening brace was not wrapped, i.e.
Definition Format.h:1074
bool RemoveBracesLLVM
Remove optional braces of control statements (if, else, for, and while) in C++ according to the LLVM ...
Definition Format.h:4830
@ BBIAS_OnlyMultiline
Break before inline ASM colon if the line length is longer than column limit.
Definition Format.h:2471
bool VerilogBreakBetweenInstancePorts
For Verilog, put each port on its own line in module instantiations.
Definition Format.h:6125
unsigned TabWidth
The number of columns used for tab stops.
Definition Format.h:6041
BreakBeforeReturnTypeStyle BreakBeforeReturnType
The function declaration/definition return type breaking style to use.
Definition Format.h:2508
@ PPDIS_None
Does not indent any directives.
Definition Format.h:3405
@ LBI_Signature
Align lambda body relative to the lambda signature.
Definition Format.h:3844
std::vector< std::string > JavaImportGroups
A vector of prefixes ordered by the desired groups for Java imports.
Definition Format.h:3726
bool AllowShortCaseLabelsOnASingleLine
If true, short case labels will be contracted to a single line.
Definition Format.h:793
unsigned PenaltyBreakFirstLessLess
The penalty for breaking before the first <<.
Definition Format.h:4500
std::vector< std::string > StatementAttributeLikeMacros
Macros which are ignored in front of a statement, as if they were an attribute.
Definition Format.h:5973
unsigned ObjCBlockIndentWidth
The number of characters to use for indentation of ObjC blocks.
Definition Format.h:4189
bool AllowShortLoopsOnASingleLine
If true, while (true) continue; can be put on a single line.
Definition Format.h:1061
int AccessModifierOffset
The extra indent or outdent of access modifiers, e.g.
Definition Format.h:59
bool AllowShortEnumsOnASingleLine
Allow short enums on a single line.
Definition Format.h:826
@ SBS_Empty
Only merge empty blocks.
Definition Format.h:754
@ SBS_Never
Never merge blocks into a single line.
Definition Format.h:746
std::optional< FormatStyle > GetLanguageStyle(LanguageKind Language) const
Definition Format.cpp:2667
std::vector< std::string > IfMacros
A vector of macros that should be interpreted as conditionals instead of as function calls.
Definition Format.h:3197
bool SpaceBeforeEnumUnderlyingTypeColon
If false, spaces will be removed before enum underlying type colon.
Definition Format.h:5372
NamespaceIndentationKind NamespaceIndentation
The indentation used for namespaces.
Definition Format.h:4065
bool BreakArrays
If true, clang-format will always break after a Json array [ otherwise it will scan until the closing...
Definition Format.h:1877
bool BreakAfterJavaFieldAnnotations
Break after each annotation on a field in Java files.
Definition Format.h:2734
@ SIS_WithoutElse
Put short ifs on the same line only if there is no else statement.
Definition Format.h:987
@ SIS_Never
Never put short ifs on the same line.
Definition Format.h:971
bool AllowBreakBeforeQtProperty
Allow breaking before Q_Property keywords READ, WRITE, etc.
Definition Format.h:733
bool BreakBeforeCloseBracketBracedList
Force break before the right bracket of a braced initializer list (when Cpp11BracedListStyle is true)...
Definition Format.h:2380
bool ExperimentalAutoDetectBinPacking
If true, clang-format detects whether function calls and definitions are formatted with one parameter...
Definition Format.h:3140
bool ObjCBreakBeforeNestedBlockParam
Break parameters list into lines when there is nested block parameters in a function call.
Definition Format.h:4213
bool BreakFunctionDeclarationParameters
If true, clang-format will always break before function declaration parameters.
Definition Format.h:2710
OperandAlignmentStyle AlignOperands
If true, horizontally align operands of binary and ternary expressions.
Definition Format.h:549
unsigned PenaltyBreakOpenParenthesis
The penalty for breaking after (.
Definition Format.h:4504
bool BreakAfterOpenBracketLoop
Force break after the left parenthesis of a loop control statement when the expression exceeds the co...
Definition Format.h:1844
friend std::error_code parseConfiguration(llvm::MemoryBufferRef Config, FormatStyle *Style, bool AllowUnknownOptions, llvm::SourceMgr::DiagHandlerTy DiagHandler, void *DiagHandlerCtxt, bool IsDotHFile)
Parse configuration from YAML-formatted text.
Definition Format.cpp:2529
unsigned PenaltyBreakBeforeMemberAccess
The penalty for breaking before a member access operator (.
Definition Format.h:4492
@ BTDS_MultiLine
Force break after template declaration only when the following declaration spans multiple lines.
Definition Format.h:1260
@ BTDS_Yes
Always break after template declaration.
Definition Format.h:1271
bool AllowShortCompoundRequirementOnASingleLine
Allow short compound requirement on a single line.
Definition Format.h:812
SpacesInParensStyle SpacesInParens
If true, spaces will be inserted after ( and before ).
Definition Format.h:5813
SpacesInParensCustom SpacesInParensOptions
Control of individual spaces in parentheses.
Definition Format.h:5906
std::vector< std::string > ForEachMacros
A vector of macros that should be interpreted as foreach loops instead of as function calls.
Definition Format.h:3174
ReferenceAlignmentStyle ReferenceAlignment
Reference alignment style (overrides PointerAlignment for references).
Definition Format.h:4738
bool CompactCaseLabels
Keep the break keyword and the following case label on the same line.
Definition Format.h:2854
AlignConsecutiveStyle AlignConsecutiveTableGenDefinitionColons
Style of aligning consecutive TableGen definition colons.
Definition Format.h:469
TrailingCommaStyle InsertTrailingCommas
If set to TCS_Wrapped will insert trailing commas in container literals (arrays and objects) that wra...
Definition Format.h:3557
unsigned PenaltyBreakTemplateDeclaration
The penalty for breaking after template declaration.
Definition Format.h:4516
SpaceBeforeParensCustom SpaceBeforeParensOptions
Control of individual space before parentheses.
Definition Format.h:5586
BreakConstructorInitializersStyle BreakConstructorInitializers
The break constructor initializers style to use.
Definition Format.h:2696
bool RemoveEmptyLinesInUnwrappedLines
Remove empty lines within unwrapped lines.
Definition Format.h:4853
bool BreakStringLiterals
Allow breaking string literals when formatting.
Definition Format.h:2777
bool SpaceAfterLogicalNot
If true, a space is inserted after the logical not operator (!).
Definition Format.h:5275
@ SBPO_Custom
Configure each individual space before parentheses in SpaceBeforeParensOptions.
Definition Format.h:5447
@ SBPO_NonEmptyParentheses
Put a space before opening parentheses only if the parentheses are not empty.
Definition Format.h:5432
@ SBPO_ControlStatementsExceptControlMacros
Same as SBPO_ControlStatements except this option doesn't apply to ForEach and If macros.
Definition Format.h:5421
@ SBPO_ControlStatements
Put a space before opening parentheses only after control statement keywords (for/if/while....
Definition Format.h:5408
@ SBPO_Always
Always put a space before opening parentheses, except when it's prohibited by the syntax rules (in fu...
Definition Format.h:5444
@ PCIS_BinPack
Bin-pack constructor initializers.
Definition Format.h:4364
@ PCIS_NextLine
Same as PCIS_CurrentLine except that if all constructor initializers do not fit on the current line,...
Definition Format.h:4389
bool ObjCSpaceAfterProperty
Add a space after @property in Objective-C, i.e.
Definition Format.h:4251
@ BBRTS_None
Do not force a break before the return type.
Definition Format.h:2488
bool BreakAfterOpenBracketSwitch
Force break after the left parenthesis of a switch control statement when the expression exceeds the ...
Definition Format.h:1854
BraceBreakingStyle BreakBeforeBraces
The brace breaking style to use.
Definition Format.h:2367
@ BILS_BeforeColon
Break inheritance list before the colon and after the commas.
Definition Format.h:2806
@ BILS_BeforeComma
Break inheritance list before the colon and commas, and align the commas with the colon.
Definition Format.h:2815
@ SIBCS_Leave
Leave existing spaces unchanged.
Definition Format.h:5710
unsigned PenaltyExcessCharacter
The penalty for each character outside of the column limit.
Definition Format.h:4520
std::vector< std::string > WhitespaceSensitiveMacros
A vector of macros which are whitespace-sensitive and should not be touched.
Definition Format.h:6142
bool AlignAfterOpenBracket
If true, horizontally aligns arguments after an open bracket.
Definition Format.h:82
@ DAS_DontBreak
Never break inside DAGArg.
Definition Format.h:6017
unsigned ConstructorInitializerIndentWidth
This option is deprecated.
Definition Format.h:2888
@ BBNSS_Never
No line break allowed.
Definition Format.h:699
bool CompactNamespaces
If true, consecutive namespace declarations will be on the same line.
Definition Format.h:2878
@ RCPS_OwnLine
Always put the requires clause on its own line (possibly followed by a semicolon).
Definition Format.h:4932
@ RCPS_WithPreceding
Try to put the clause together with the preceding part of a declaration.
Definition Format.h:4967
@ RCPS_SingleLine
Try to put everything in the same line if possible.
Definition Format.h:5005
bool BreakBeforeCloseBracketSwitch
Force break before the right parenthesis of a switch control statement when the expression exceeds th...
Definition Format.h:2430
@ LS_Cpp17
Parse and format as C++17.
Definition Format.h:5936
@ LS_Cpp26
Parse and format as C++26.
Definition Format.h:5942
@ LS_Cpp23
Parse and format as C++23.
Definition Format.h:5940
@ LS_Latest
Parse and format using the latest supported language version.
Definition Format.h:5945
@ LS_Cpp11
Parse and format as C++11.
Definition Format.h:5932
@ LS_Auto
Automatic detection based on the input.
Definition Format.h:5947
@ LS_Cpp14
Parse and format as C++14.
Definition Format.h:5934
@ LS_Cpp20
Parse and format as C++20.
Definition Format.h:5938
@ BWACS_Always
Always wrap braces after a control statement.
Definition Format.h:1415
@ BWACS_Never
Never wrap braces after a control statement.
Definition Format.h:1394
RequiresClausePositionStyle RequiresClausePosition
The position of the requires clause.
Definition Format.h:5010
@ JSQS_Single
Always use single quotes.
Definition Format.h:3742
@ JSQS_Leave
Leave string quotes as they are.
Definition Format.h:3736
bool SpaceAfterCStyleCast
If true, a space is inserted after C style casts.
Definition Format.h:5267
AlignConsecutiveStyle AlignConsecutiveBitFields
Style of aligning consecutive bit fields.
Definition Format.h:293
int PPIndentWidth
The number of columns to use for indentation of preprocessor statements.
Definition Format.h:4567
AlignConsecutiveStyle AlignConsecutiveDeclarations
Style of aligning consecutive declarations.
Definition Format.h:305
IntegerLiteralSeparatorStyle IntegerLiteralSeparator
Format integer literal separators (‘’ for C/C++ and _` for C#, Java, and JavaScript).
Definition Format.h:3692
SpaceAroundPointerQualifiersStyle SpaceAroundPointerQualifiers
Defines in which cases to put a space before or after pointer qualifiers.
Definition Format.h:5324
@ IAMS_Never
Use AccessModifierOffset for access modifiers and indent members one level below the record.
Definition Format.h:3211
DefinitionReturnTypeBreakingStyle AlwaysBreakAfterDefinitionReturnType
The function definition return type breaking style to use.
Definition Format.h:1206
ShortRecordStyle AllowShortRecordOnASingleLine
Dependent on the value, struct bar { int i; }; can be put on a single line.
Definition Format.h:1095
bool SpaceBeforeAssignmentOperators
If false, spaces will be removed before assignment operators.
Definition Format.h:5333
BreakBeforeInlineASMColonStyle BreakBeforeInlineASMColon
The inline ASM colon style to use.
Definition Format.h:2483
@ WNBWELS_Leave
Keep existing newlines at the beginning and the end of namespace body.
Definition Format.h:6170
SpaceInEmptyBracesStyle SpaceInEmptyBraces
Specifies when to insert a space in empty braces.
Definition Format.h:5645
@ BS_Mozilla
Like Attach, but break before braces on enum, function, and record definitions.
Definition Format.h:2080
@ BS_Whitesmiths
Like Allman but always indent braces and line up code with braces.
Definition Format.h:2250
@ BS_Allman
Always break before braces.
Definition Format.h:2190
@ BS_Stroustrup
Like Attach, but break before function definitions, catch, and else.
Definition Format.h:2130
@ BS_Linux
Like Attach, but break before braces on function, namespace and class definitions.
Definition Format.h:2030
@ BS_WebKit
Like Attach, but break before functions.
Definition Format.h:2360
@ BS_Custom
Configure each individual brace in BraceWrapping.
Definition Format.h:2362
@ BS_GNU
Always break before braces and add an extra level of indentation to braces of control statements,...
Definition Format.h:2313
@ BS_Attach
Always attach braces to surrounding context.
Definition Format.h:1980
bool ObjCSpaceAfterMethodDeclarationPrefix
Add or remove a space between the '-'/'+' and the return type in Objective-C method declarations.
Definition Format.h:4246
@ ABS_Leave
Leave the line breaking after the last attribute of the group as is.
Definition Format.h:1759
bool BreakBeforeCloseBracketLoop
Force break before the right parenthesis of a loop control statement when the expression exceeds the ...
Definition Format.h:2417
ShortLambdaStyle AllowShortLambdasOnASingleLine
Dependent on the value, auto lambda []() { return 0; } can be put on a single line.
Definition Format.h:1056
bool BinPackLongBracedList
This option is deprecated.
Definition Format.h:1316
unsigned PenaltyBreakScopeResolution
The penalty for breaking after ::.
Definition Format.h:4508
unsigned PenaltyReturnTypeOnItsOwnLine
Penalty for putting the return type of a function onto its own line.
Definition Format.h:4529
@ BFCS_Both
Add one space on each side of the :
Definition Format.h:1328
PointerAlignmentStyle PointerAlignment
Pointer and reference alignment style.
Definition Format.h:4552
bool BreakBeforeTemplateCloser
If true, break before a template closing bracket (>) when there is a line break after the matching op...
Definition Format.h:2535
int BracedInitializerIndentWidth
The number of columns to use to indent the contents of braced init lists.
Definition Format.h:1382
PackParametersStyle PackParameters
Options related to packing parameters of function declarations and definitions.
Definition Format.h:4480
bool BreakFunctionDefinitionParameters
If true, clang-format will always break before function definition parameters.
Definition Format.h:2724
@ REI_OuterScope
Align requires expression body relative to the indentation level of the outer scope the requires expr...
Definition Format.h:5023
PackConstructorInitializersStyle PackConstructorInitializers
The pack constructor initializers style to use.
Definition Format.h:4409
@ BBCDS_Always
Always break before concept, putting it in the line after the template declaration.
Definition Format.h:2449
ReflowCommentsStyle ReflowComments
Comment reformatting style.
Definition Format.h:4776
KeepEmptyLinesStyle KeepEmptyLines
Which empty lines are kept.
Definition Format.h:3816
bool AllowAllParametersOfDeclarationOnNextLine
This option is deprecated.
Definition Format.h:686
AlignConsecutiveStyle AlignConsecutiveTableGenCondOperatorColons
Style of aligning consecutive TableGen cond operator colons.
Definition Format.h:459
@ BLS_AlignFirstComment
Same as FunctionCall, except for the handling of a comment at the begin, it then aligns everything fo...
Definition Format.h:2956
@ BLS_Block
Best suited for pre C++11 braced lists.
Definition Format.h:2918
bool AllowShortCaseExpressionOnASingleLine
Whether to merge a short switch labeled rule into a single line.
Definition Format.h:779
bool BreakBeforeCloseBracketIf
Force break before the right parenthesis of an if control statement when the expression exceeds the c...
Definition Format.h:2404
unsigned MaxEmptyLinesToKeep
The maximum number of consecutive empty lines to keep.
Definition Format.h:4027
bool SpaceBeforeSquareBrackets
If true, spaces will be before [.
Definition Format.h:5596
BinPackStyle ObjCBinPackProtocolList
Controls bin-packing Objective-C protocol conformance list items into as few lines as possible when t...
Definition Format.h:4178
PackArgumentsStyle PackArguments
Options related to packing arguments of function calls.
Definition Format.h:4347
ShortCaseStatementsAlignmentStyle AlignConsecutiveShortCaseStatements
Style of aligning consecutive short case labels.
Definition Format.h:434
EscapedNewlineAlignmentStyle AlignEscapedNewlines
Options for aligning backslashes in escaped newlines.
Definition Format.h:510
SpacesInLineComment SpacesInLineCommentPrefix
How many spaces are allowed at the start of a line comment.
Definition Format.h:5784
std::string CommentPragmas
A regular expression that describes comments with special meaning, which should not be split into lin...
Definition Format.h:2795
bool isJavaScript() const
Definition Format.h:3909
DAGArgStyle TableGenBreakInsideDAGArg
The styles of the line break inside the DAGArg in TableGen.
Definition Format.h:6037
JavaScriptQuoteStyle JavaScriptQuotes
The JavaScriptQuoteStyle to use for JavaScript strings.
Definition Format.h:3753
bool SpacesInContainerLiterals
If true, spaces will be inserted around if/for/switch/while conditions.
Definition Format.h:5736
SortJavaStaticImportOptions SortJavaStaticImport
When sorting Java imports, by default static imports are placed before non-static imports.
Definition Format.h:5215
BreakBinaryOperationsOptions BreakBinaryOperations
The break binary operations style to use.
Definition Format.h:2660
@ SAPQ_Default
Don't ensure spaces around pointer qualifiers and use PointerAlignment instead.
Definition Format.h:5301
bool SpaceBeforeRangeBasedForLoopColon
If false, spaces will be removed before range-based for loop colon.
Definition Format.h:5605
bool DisableFormat
Disables formatting completely.
Definition Format.h:2978
@ ELAAMS_Never
Remove all empty lines after access modifiers.
Definition Format.h:2998
@ DRTBS_All
Always break after the return type.
Definition Format.h:1104
@ DRTBS_TopLevel
Always break after the return types of top-level functions.
Definition Format.h:1106
@ DRTBS_None
Break after return type automatically.
Definition Format.h:1102
bool AllowShortNamespacesOnASingleLine
If true, namespace a { class b; } can be put on a single line.
Definition Format.h:1065
AttributeBreakingStyle BreakAfterAttributes
Break after a group of C++11 attributes before variable or function (including constructor/destructor...
Definition Format.h:1803
TrailingCommentsAlignmentStyle AlignTrailingComments
Control of trailing comments.
Definition Format.h:646
@ AIAS_None
Don't align array initializer columns.
Definition Format.h:107
LambdaBodyIndentationKind LambdaBodyIndentation
The indentation style of lambda bodies.
Definition Format.h:3867
QualifierAlignmentStyle QualifierAlignment
Different ways to arrange specifiers and qualifiers (e.g.
Definition Format.h:4613
@ BBO_Never
Don't break binary operations.
Definition Format.h:2559
BraceWrappingFlags BraceWrapping
Control of individual brace wrapping cases.
Definition Format.h:1688
@ ENAS_Left
Align escaped newlines as far left as possible.
Definition Format.h:488
@ ENAS_Right
Align escaped newlines in the right-most column.
Definition Format.h:505
AlignConsecutiveStyle AlignConsecutiveMacros
Style of aligning consecutive macro definitions.
Definition Format.h:318
IndentAccessModifierStyle IndentAccessModifiers
Specify how access modifiers and record members are indented.
Definition Format.h:3240
std::vector< std::string > StatementMacros
A vector of macros that should be interpreted as complete statements.
Definition Format.h:5983
@ SIAS_Never
Remove spaces after < and before >.
Definition Format.h:5681
@ BPAS_OnePerLine
Put all arguments on the current line if they fit.
Definition Format.h:4302
@ BPAS_BinPack
Bin-pack arguments.
Definition Format.h:4292
@ BPAS_UseBreakAfter
Use the BreakAfter option to handle argument packing instead.
Definition Format.h:4305
@ SUD_LexicographicNumeric
Using declarations are sorted in the order defined as follows: Split the strings by :: and discard an...
Definition Format.h:5254
@ SUD_Never
Using declarations are never sorted.
Definition Format.h:5227
AlignConsecutiveStyle AlignConsecutiveAssignments
Style of aligning consecutive assignments.
Definition Format.h:281
@ SIEB_Always
Always insert a space in empty braces.
Definition Format.h:5620
@ SIEB_Never
Never insert a space in empty braces.
Definition Format.h:5636
ShortIfStyle AllowShortIfStatementsOnASingleLine
Dependent on the value, if (a) return; can be put on a single line.
Definition Format.h:1022
@ RPS_Leave
Do not remove parentheses.
Definition Format.h:4863
@ RPS_ReturnStatement
Also remove parentheses enclosing the expression in a return/co_return statement.
Definition Format.h:4878
std::vector< std::string > TableGenBreakingDAGArgOperators
Works only when TableGenBreakInsideDAGArg is not DontBreak.
Definition Format.h:6009
EmptyLineBeforeAccessModifierStyle EmptyLineBeforeAccessModifier
Defines in which cases to put empty line before access modifiers.
Definition Format.h:3092
EnumTrailingCommaStyle EnumTrailingComma
Insert a comma (if missing) or remove the comma at the end of an enum enumerator list.
Definition Format.h:3125
bool SpaceBeforeCaseColon
If false, spaces will be removed before case colon.
Definition Format.h:5343
BreakBeforeNoexceptSpecifierStyle AllowBreakBeforeNoexceptSpecifier
Controls if there could be a line break before a noexcept specifier.
Definition Format.h:727
bool JavaScriptWrapImports
Whether to wrap JavaScript import/export statements.
Definition Format.h:3769
bool BreakAfterOpenBracketFunction
Force break after the left parenthesis of a function (declaration, definition, call) when the paramet...
Definition Format.h:1824
bool SkipMacroDefinitionBody
Do not format macro definition body.
Definition Format.h:5120
unsigned PenaltyBreakAssignment
The penalty for breaking around an assignment operator.
Definition Format.h:4484
@ PAS_Left
Align pointer to the left.
Definition Format.h:4537
@ PAS_Right
Align pointer to the right.
Definition Format.h:4542
unsigned PenaltyBreakString
The penalty for each line break introduced inside a string literal.
Definition Format.h:4512
RequiresExpressionIndentationKind RequiresExpressionIndentation
The indentation used for requires expression bodies.
Definition Format.h:5036
IndentGotoLabelStyle IndentGotoLabels
The goto label indenting style to use.
Definition Format.h:3393
bool SpaceAfterTemplateKeyword
If true, a space will be inserted after the template keyword.
Definition Format.h:5291
unsigned PenaltyIndentedWhitespace
Penalty for each character of whitespace indentation (counted relative to leading non-whitespace colu...
Definition Format.h:4525
ArrayInitializerAlignmentStyle AlignArrayOfStructures
If not None, when using initialization for an array of structs aligns the fields into columns.
Definition Format.h:118
@ NI_None
Don't indent in namespaces.
Definition Format.h:4040
@ NI_All
Indent in all namespaces.
Definition Format.h:4060
@ NI_Inner
Indent only in inner namespaces (nested in other namespaces).
Definition Format.h:4050
ShortBlockStyle AllowShortBlocksOnASingleLine
Dependent on the value, while (true) { continue; } can be put on a single line.
Definition Format.h:766
ShortFunctionStyle AllowShortFunctionsOnASingleLine
Dependent on the value, int f() { return 0; } can be put on a single line.
Definition Format.h:951
bool AllowAllArgumentsOnNextLine
If a function call or braced initializer list doesn't fit on a line, allow putting all arguments onto...
Definition Format.h:663
unsigned PenaltyBreakComment
The penalty for each line break introduced inside a comment.
Definition Format.h:4496
bool SpaceAfterOperatorKeyword
If true, a space will be inserted after the operator keyword.
Definition Format.h:5283
@ RTBS_TopLevel
Always break after the return types of top-level functions.
Definition Format.h:1169
@ RTBS_None
This is deprecated. See Automatic below.
Definition Format.h:1113
@ RTBS_AllDefinitions
Always break after the return type of function definitions.
Definition Format.h:1186
@ RAS_Pointer
Align reference like PointerAlignment.
Definition Format.h:4718
EmptyLineAfterAccessModifierStyle EmptyLineAfterAccessModifier
Defines when to put an empty line after access modifiers.
Definition Format.h:3029
@ IGLS_OuterIndent
Indent goto labels to the enclosing block (previous indenting level).
Definition Format.h:3362
bool InsertNewlineAtEOF
Insert a newline at end of file if missing.
Definition Format.h:3527
SpaceBeforeParensStyle SpaceBeforeParens
Defines in which cases to put a space before opening parentheses.
Definition Format.h:5452
bool SpaceBeforeCpp11BracedList
If true, a space will be inserted before a C++11 braced list used to initialize an object (after the ...
Definition Format.h:5355
NumericLiteralCaseStyle NumericLiteralCase
Capitalization style for numeric literals.
Definition Format.h:4145
UseTabStyle UseTab
The way to use tab characters in the resulting file.
Definition Format.h:6102
@ QAS_Leave
Don't change specifiers/qualifiers to either Left or Right alignment (default).
Definition Format.h:4577
@ OAS_Align
Horizontally align operands of binary and ternary expressions.
Definition Format.h:533
@ OAS_DontAlign
Do not align operands of binary and ternary expressions.
Definition Format.h:517
LineEndingStyle LineEnding
Line ending style (\n or \r\n) to use.
Definition Format.h:3938
bool BreakAfterOpenBracketBracedList
Force break after the left bracket of a braced initializer list (when Cpp11BracedListStyle is true) w...
Definition Format.h:1814
bool BreakBeforeTernaryOperators
If true, ternary operators will be placed after line breaks.
Definition Format.h:2550
BracedListStyle Cpp11BracedListStyle
The style to handle braced lists.
Definition Format.h:2961
unsigned ShortNamespaceLines
The maximal number of unwrapped lines that a short namespace spans.
Definition Format.h:5116
SortUsingDeclarationsOptions SortUsingDeclarations
Controls if and how clang-format will sort using declarations.
Definition Format.h:5259
IndentExternBlockStyle IndentExternBlock
IndentExternBlockStyle is the type of indenting of extern blocks.
Definition Format.h:3335
SeparateDefinitionStyle SeparateDefinitionBlocks
Specifies the use of empty lines to separate definition blocks, including classes,...
Definition Format.h:5094
tooling::IncludeStyle IncludeStyle
Definition Format.h:3176
unsigned ColumnLimit
The column limit.
Definition Format.h:2785
A wrapper around a Token storing information about the whitespace characters preceding it.
bool Optional
Is optional and can be removed.
bool isNot(T Kind) const
unsigned Finalized
If true, this token has been fully formatted (indented and potentially re-formatted inside),...
bool isNoneOf(Ts... Ks) const
FormatToken * Next
The next token in the unwrapped line.
bool LBraceInserted
Whether a left brace was already inserted after this token when an earlier run was analyzed.
bool is(tok::TokenKind Kind) const
bool isOneOf(A K1, B K2) const
int8_t BraceCount
Number of optional braces to be inserted after this token: -1: a single left brace 0: no braces >0: n...
Represents the status of a formatting attempt.
Definition Format.h:6547
MainIncludeCharDiscriminator MainIncludeChar
When guessing whether a include is the "main" include, only the include directives that use the speci...
@ IBS_Preserve
Sort each #include block separately.
@ IBS_RegroupByDirectory
Merge multiple #include blocks together and sort as one.
@ IBS_Regroup
Merge multiple #include blocks together and sort as one.
@ IBS_Merge
Merge multiple #include blocks together and sort as one.
std::string IncludeIsMainRegex
Specify a regular expression of suffixes that are allowed in the file-to-main-include mapping.
@ MICD_Quote
Main include uses quotes: #include "foo.hpp" (the default).
IncludeBlocksStyle IncludeBlocks
Dependent on the value, multiple #include blocks can be sorted as one and divided based on category.
std::vector< IncludeCategory > IncludeCategories
Regular expressions denoting the different #include categories used for ordering #includes.
static FormatStyle & element(IO &IO, std::vector< FormatStyle > &Seq, size_t Index)
Definition Format.cpp:1665
static size_t size(IO &IO, std::vector< FormatStyle > &Seq)
Definition Format.cpp:1662
static void mapping(IO &IO, FormatStyle &Style)
Definition Format.cpp:1114
static void enumInput(IO &IO, FormatStyle::AlignConsecutiveStyle &Value)
Definition Format.cpp:62
static void mapping(IO &IO, FormatStyle::AlignConsecutiveStyle &Value)
Definition Format.cpp:104
static void mapping(IO &IO, FormatStyle::BinaryOperationBreakRule &Value)
Definition Format.cpp:332
static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping)
Definition Format.cpp:219
static void mapping(IO &IO, FormatStyle::BreakBinaryOperationsOptions &Value)
Definition Format.cpp:356
static void enumInput(IO &IO, FormatStyle::BreakBinaryOperationsOptions &Value)
Definition Format.cpp:343
static void mapping(IO &IO, FormatStyle::IntegerLiteralSeparatorStyle &Base)
Definition Format.cpp:507
static void mapping(IO &IO, FormatStyle::KeepEmptyLinesStyle &Value)
Definition Format.cpp:534
static void mapping(IO &IO, FormatStyle::NumericLiteralCaseStyle &Value)
Definition Format.cpp:618
static void mapping(IO &IO, FormatStyle::PackArgumentsStyle &Value)
Definition Format.cpp:659
static void mapping(IO &IO, FormatStyle::PackParametersStyle &Value)
Definition Format.cpp:640
static void mapping(IO &IO, FormatStyle::RawStringFormat &Format)
Definition Format.cpp:698
static void mapping(IO &IO, FormatStyle::ShortCaseStatementsAlignmentStyle &Value)
Definition Format.cpp:119
static void mapping(IO &IO, FormatStyle::ShortFunctionStyle &Value)
Definition Format.cpp:821
static void enumInput(IO &IO, FormatStyle::ShortFunctionStyle &Value)
Definition Format.cpp:806
static void mapping(IO &IO, FormatStyle::SortIncludesOptions &Value)
Definition Format.cpp:893
static void enumInput(IO &IO, FormatStyle::SortIncludesOptions &Value)
Definition Format.cpp:863
static void mapping(IO &IO, FormatStyle::SpaceBeforeParensCustom &Spacing)
Definition Format.cpp:938
static void mapping(IO &IO, FormatStyle::SpacesInLineComment &Space)
Definition Format.cpp:1010
static void mapping(IO &IO, FormatStyle::SpacesInParensCustom &Spaces)
Definition Format.cpp:1023
static void mapping(IO &IO, FormatStyle::TrailingCommentsAlignmentStyle &Value)
Definition Format.cpp:1080
static void enumInput(IO &IO, FormatStyle::TrailingCommentsAlignmentStyle &Value)
Definition Format.cpp:1057
static void enumeration(IO &IO, BracketAlignmentStyle &Value)
Definition Format.cpp:244
static void enumeration(IO &IO, FormatStyle::ArrayInitializerAlignmentStyle &Value)
Definition Format.cpp:141
static void enumeration(IO &IO, FormatStyle::AttributeBreakingStyle &Value)
Definition Format.cpp:131
static void enumeration(IO &IO, FormatStyle::BinPackArgumentsStyle &Value)
Definition Format.cpp:160
static void enumeration(IO &IO, FormatStyle::BinPackParametersStyle &Value)
Definition Format.cpp:173
static void enumeration(IO &IO, FormatStyle::BinPackStyle &Value)
Definition Format.cpp:186
static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value)
Definition Format.cpp:150
static void enumeration(IO &IO, FormatStyle::BitFieldColonSpacingStyle &Value)
Definition Format.cpp:195
static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value)
Definition Format.cpp:205
static void enumeration(IO &IO, FormatStyle::BraceWrappingAfterControlStatementStyle &Value)
Definition Format.cpp:260
static void enumeration(IO &IO, FormatStyle::BracedListStyle &Value)
Definition Format.cpp:401
static void enumeration(IO &IO, FormatStyle::BreakBeforeConceptDeclarationsStyle &Value)
Definition Format.cpp:276
static void enumeration(IO &IO, FormatStyle::BreakBeforeInlineASMColonStyle &Value)
Definition Format.cpp:289
static void enumeration(IO &IO, FormatStyle::BreakBeforeNoexceptSpecifierStyle &Value)
Definition Format.cpp:54
static void enumeration(IO &IO, FormatStyle::BreakBeforeReturnTypeStyle &Value)
Definition Format.cpp:775
static void enumeration(IO &IO, FormatStyle::BreakBinaryOperationsStyle &Value)
Definition Format.cpp:299
static void enumeration(IO &IO, FormatStyle::BreakConstructorInitializersStyle &Value)
Definition Format.cpp:366
static void enumeration(IO &IO, FormatStyle::BreakInheritanceListStyle &Value)
Definition Format.cpp:376
static void enumeration(IO &IO, FormatStyle::BreakTemplateDeclarationsStyle &Value)
Definition Format.cpp:387
static void enumeration(IO &IO, FormatStyle::DAGArgStyle &Value)
Definition Format.cpp:413
static void enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value)
Definition Format.cpp:423
static void enumeration(IO &IO, FormatStyle::EmptyLineAfterAccessModifierStyle &Value)
Definition Format.cpp:452
static void enumeration(IO &IO, FormatStyle::EmptyLineBeforeAccessModifierStyle &Value)
Definition Format.cpp:463
static void enumeration(IO &IO, FormatStyle::EnumTrailingCommaStyle &Value)
Definition Format.cpp:473
static void enumeration(IO &IO, FormatStyle::EscapedNewlineAlignmentStyle &Value)
Definition Format.cpp:436
static void enumeration(IO &IO, FormatStyle::IndentAccessModifierStyle &Value)
Definition Format.cpp:482
static void enumeration(IO &IO, FormatStyle::IndentExternBlockStyle &Value)
Definition Format.cpp:497
static void enumeration(IO &IO, FormatStyle::IndentGotoLabelStyle &Value)
Definition Format.cpp:1683
static void enumeration(IO &IO, FormatStyle::JavaScriptQuoteStyle &Value)
Definition Format.cpp:526
static void enumeration(IO &IO, FormatStyle::LambdaBodyIndentationKind &Value)
Definition Format.cpp:581
static void enumeration(IO &IO, FormatStyle::LanguageKind &Value)
Definition Format.cpp:543
static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value)
Definition Format.cpp:559
static void enumeration(IO &IO, FormatStyle::LineEndingStyle &Value)
Definition Format.cpp:589
static void enumeration(IO &IO, FormatStyle::NamespaceIndentationKind &Value)
Definition Format.cpp:599
static void enumeration(IO &IO, FormatStyle::NumericLiteralComponentStyle &Value)
Definition Format.cpp:609
static void enumeration(IO &IO, FormatStyle::OperandAlignmentStyle &Value)
Definition Format.cpp:627
static void enumeration(IO &IO, FormatStyle::PPDirectiveIndentStyle &Value)
Definition Format.cpp:679
static void enumeration(IO &IO, FormatStyle::PackConstructorInitializersStyle &Value)
Definition Format.cpp:649
static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value)
Definition Format.cpp:666
static void enumeration(IO &IO, FormatStyle::QualifierAlignmentStyle &Value)
Definition Format.cpp:689
static void enumeration(IO &IO, FormatStyle::ReferenceAlignmentStyle &Value)
Definition Format.cpp:720
static void enumeration(IO &IO, FormatStyle::ReflowCommentsStyle &Value)
Definition Format.cpp:708
static void enumeration(IO &IO, FormatStyle::RemoveParenthesesStyle &Value)
Definition Format.cpp:730
static void enumeration(IO &IO, FormatStyle::RequiresClausePositionStyle &Value)
Definition Format.cpp:740
static void enumeration(IO &IO, FormatStyle::RequiresExpressionIndentationKind &Value)
Definition Format.cpp:753
static void enumeration(IO &IO, FormatStyle::ReturnTypeBreakingStyle &Value)
Definition Format.cpp:761
static void enumeration(IO &IO, FormatStyle::SeparateDefinitionStyle &Value)
Definition Format.cpp:788
static void enumeration(IO &IO, FormatStyle::ShortBlockStyle &Value)
Definition Format.cpp:796
static void enumeration(IO &IO, FormatStyle::ShortIfStyle &Value)
Definition Format.cpp:829
static void enumeration(IO &IO, FormatStyle::ShortLambdaStyle &Value)
Definition Format.cpp:843
static void enumeration(IO &IO, FormatStyle::ShortRecordStyle &Value)
Definition Format.cpp:854
static void enumeration(IO &IO, FormatStyle::SortJavaStaticImportOptions &Value)
Definition Format.cpp:904
static void enumeration(IO &IO, FormatStyle::SortUsingDeclarationsOptions &Value)
Definition Format.cpp:913
static void enumeration(IO &IO, FormatStyle::SpaceAroundPointerQualifiersStyle &Value)
Definition Format.cpp:929
static void enumeration(IO &IO, FormatStyle::SpaceBeforeParensStyle &Value)
Definition Format.cpp:959
static void enumeration(IO &IO, FormatStyle::SpaceInEmptyBracesStyle &Value)
Definition Format.cpp:980
static void enumeration(IO &IO, FormatStyle::SpacesInAnglesStyle &Value)
Definition Format.cpp:988
static void enumeration(IO &IO, FormatStyle::SpacesInBlockCommentsStyle &Value)
Definition Format.cpp:1001
static void enumeration(IO &IO, FormatStyle::SpacesInParensStyle &Value)
Definition Format.cpp:1033
static void enumeration(IO &IO, FormatStyle::TrailingCommaStyle &Value)
Definition Format.cpp:1040
static void enumeration(IO &IO, FormatStyle::TrailingCommentsAlignmentKinds &Value)
Definition Format.cpp:1048
static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value)
Definition Format.cpp:1089
static void enumeration(IO &IO, FormatStyle::WrapNamespaceBodyWithEmptyLinesStyle &Value)
Definition Format.cpp:1105
static StringRef input(StringRef Scalar, void *, clang::tok::TokenKind &Value)
Definition Format.cpp:316
static QuotingType mustQuote(StringRef)
Definition Format.cpp:328
static void output(const clang::tok::TokenKind &Value, void *, llvm::raw_ostream &Out)
Definition Format.cpp:308