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