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