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