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 "AffectedRangeManager.h"
17 #include "ContinuationIndenter.h"
18 #include "FormatInternal.h"
19 #include "FormatTokenLexer.h"
20 #include "NamespaceEndCommentsFixer.h"
21 #include "SortJavaScriptImports.h"
22 #include "TokenAnalyzer.h"
23 #include "TokenAnnotator.h"
24 #include "UnwrappedLineFormatter.h"
25 #include "UnwrappedLineParser.h"
26 #include "UsingDeclarationsSorter.h"
27 #include "WhitespaceManager.h"
28 #include "clang/Basic/Diagnostic.h"
29 #include "clang/Basic/DiagnosticOptions.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Lex/Lexer.h"
32 #include "clang/Tooling/Inclusions/HeaderIncludes.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/StringRef.h"
35 #include "llvm/Support/Allocator.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/Regex.h"
39 #include "llvm/Support/VirtualFileSystem.h"
40 #include "llvm/Support/YAMLTraits.h"
41 #include <algorithm>
42 #include <memory>
43 #include <mutex>
44 #include <string>
45 #include <unordered_map>
46 
47 #define DEBUG_TYPE "format-formatter"
48 
49 using clang::format::FormatStyle;
50 
51 LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::RawStringFormat)
52 
53 namespace llvm {
54 namespace yaml {
55 template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
56   static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
57     IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
58     IO.enumCase(Value, "Java", FormatStyle::LK_Java);
59     IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
60     IO.enumCase(Value, "ObjC", FormatStyle::LK_ObjC);
61     IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
62     IO.enumCase(Value, "TableGen", FormatStyle::LK_TableGen);
63     IO.enumCase(Value, "TextProto", FormatStyle::LK_TextProto);
64   }
65 };
66 
67 template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
68   static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
69     IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
70     IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
71     IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
72     IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
73     IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
74   }
75 };
76 
77 template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
78   static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
79     IO.enumCase(Value, "Never", FormatStyle::UT_Never);
80     IO.enumCase(Value, "false", FormatStyle::UT_Never);
81     IO.enumCase(Value, "Always", FormatStyle::UT_Always);
82     IO.enumCase(Value, "true", FormatStyle::UT_Always);
83     IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
84     IO.enumCase(Value, "ForContinuationAndIndentation",
85                 FormatStyle::UT_ForContinuationAndIndentation);
86   }
87 };
88 
89 template <> struct ScalarEnumerationTraits<FormatStyle::JavaScriptQuoteStyle> {
90   static void enumeration(IO &IO, FormatStyle::JavaScriptQuoteStyle &Value) {
91     IO.enumCase(Value, "Leave", FormatStyle::JSQS_Leave);
92     IO.enumCase(Value, "Single", FormatStyle::JSQS_Single);
93     IO.enumCase(Value, "Double", FormatStyle::JSQS_Double);
94   }
95 };
96 
97 template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
98   static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
99     IO.enumCase(Value, "None", FormatStyle::SFS_None);
100     IO.enumCase(Value, "false", FormatStyle::SFS_None);
101     IO.enumCase(Value, "All", FormatStyle::SFS_All);
102     IO.enumCase(Value, "true", FormatStyle::SFS_All);
103     IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
104     IO.enumCase(Value, "InlineOnly", FormatStyle::SFS_InlineOnly);
105     IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
106   }
107 };
108 
109 template <> struct ScalarEnumerationTraits<FormatStyle::BinPackStyle> {
110   static void enumeration(IO &IO, FormatStyle::BinPackStyle &Value) {
111     IO.enumCase(Value, "Auto", FormatStyle::BPS_Auto);
112     IO.enumCase(Value, "Always", FormatStyle::BPS_Always);
113     IO.enumCase(Value, "Never", FormatStyle::BPS_Never);
114   }
115 };
116 
117 template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
118   static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
119     IO.enumCase(Value, "All", FormatStyle::BOS_All);
120     IO.enumCase(Value, "true", FormatStyle::BOS_All);
121     IO.enumCase(Value, "None", FormatStyle::BOS_None);
122     IO.enumCase(Value, "false", FormatStyle::BOS_None);
123     IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
124   }
125 };
126 
127 template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
128   static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
129     IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
130     IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
131     IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
132     IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
133     IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
134     IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
135     IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
136     IO.enumCase(Value, "Custom", FormatStyle::BS_Custom);
137   }
138 };
139 
140 template <>
141 struct ScalarEnumerationTraits<FormatStyle::BreakConstructorInitializersStyle> {
142   static void
143   enumeration(IO &IO, FormatStyle::BreakConstructorInitializersStyle &Value) {
144     IO.enumCase(Value, "BeforeColon", FormatStyle::BCIS_BeforeColon);
145     IO.enumCase(Value, "BeforeComma", FormatStyle::BCIS_BeforeComma);
146     IO.enumCase(Value, "AfterColon", FormatStyle::BCIS_AfterColon);
147   }
148 };
149 
150 template <>
151 struct ScalarEnumerationTraits<FormatStyle::BreakInheritanceListStyle> {
152   static void
153   enumeration(IO &IO, FormatStyle::BreakInheritanceListStyle &Value) {
154     IO.enumCase(Value, "BeforeColon", FormatStyle::BILS_BeforeColon);
155     IO.enumCase(Value, "BeforeComma", FormatStyle::BILS_BeforeComma);
156     IO.enumCase(Value, "AfterColon", FormatStyle::BILS_AfterColon);
157   }
158 };
159 
160 template <>
161 struct ScalarEnumerationTraits<FormatStyle::PPDirectiveIndentStyle> {
162   static void enumeration(IO &IO, FormatStyle::PPDirectiveIndentStyle &Value) {
163     IO.enumCase(Value, "None", FormatStyle::PPDIS_None);
164     IO.enumCase(Value, "AfterHash", FormatStyle::PPDIS_AfterHash);
165   }
166 };
167 
168 template <>
169 struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
170   static void enumeration(IO &IO, FormatStyle::ReturnTypeBreakingStyle &Value) {
171     IO.enumCase(Value, "None", FormatStyle::RTBS_None);
172     IO.enumCase(Value, "All", FormatStyle::RTBS_All);
173     IO.enumCase(Value, "TopLevel", FormatStyle::RTBS_TopLevel);
174     IO.enumCase(Value, "TopLevelDefinitions",
175                 FormatStyle::RTBS_TopLevelDefinitions);
176     IO.enumCase(Value, "AllDefinitions", FormatStyle::RTBS_AllDefinitions);
177   }
178 };
179 
180 template <>
181 struct ScalarEnumerationTraits<FormatStyle::BreakTemplateDeclarationsStyle> {
182   static void enumeration(IO &IO, FormatStyle::BreakTemplateDeclarationsStyle &Value) {
183     IO.enumCase(Value, "No", FormatStyle::BTDS_No);
184     IO.enumCase(Value, "MultiLine", FormatStyle::BTDS_MultiLine);
185     IO.enumCase(Value, "Yes", FormatStyle::BTDS_Yes);
186 
187     // For backward compatibility.
188     IO.enumCase(Value, "false", FormatStyle::BTDS_MultiLine);
189     IO.enumCase(Value, "true", FormatStyle::BTDS_Yes);
190   }
191 };
192 
193 template <>
194 struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
195   static void
196   enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) {
197     IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
198     IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
199     IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
200 
201     // For backward compatibility.
202     IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
203     IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
204   }
205 };
206 
207 template <>
208 struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
209   static void enumeration(IO &IO,
210                           FormatStyle::NamespaceIndentationKind &Value) {
211     IO.enumCase(Value, "None", FormatStyle::NI_None);
212     IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
213     IO.enumCase(Value, "All", FormatStyle::NI_All);
214   }
215 };
216 
217 template <> struct ScalarEnumerationTraits<FormatStyle::BracketAlignmentStyle> {
218   static void enumeration(IO &IO, FormatStyle::BracketAlignmentStyle &Value) {
219     IO.enumCase(Value, "Align", FormatStyle::BAS_Align);
220     IO.enumCase(Value, "DontAlign", FormatStyle::BAS_DontAlign);
221     IO.enumCase(Value, "AlwaysBreak", FormatStyle::BAS_AlwaysBreak);
222 
223     // For backward compatibility.
224     IO.enumCase(Value, "true", FormatStyle::BAS_Align);
225     IO.enumCase(Value, "false", FormatStyle::BAS_DontAlign);
226   }
227 };
228 
229 template <>
230 struct ScalarEnumerationTraits<FormatStyle::EscapedNewlineAlignmentStyle> {
231   static void enumeration(IO &IO,
232                           FormatStyle::EscapedNewlineAlignmentStyle &Value) {
233     IO.enumCase(Value, "DontAlign", FormatStyle::ENAS_DontAlign);
234     IO.enumCase(Value, "Left", FormatStyle::ENAS_Left);
235     IO.enumCase(Value, "Right", FormatStyle::ENAS_Right);
236 
237     // For backward compatibility.
238     IO.enumCase(Value, "true", FormatStyle::ENAS_Left);
239     IO.enumCase(Value, "false", FormatStyle::ENAS_Right);
240   }
241 };
242 
243 template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
244   static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
245     IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
246     IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
247     IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
248 
249     // For backward compatibility.
250     IO.enumCase(Value, "true", FormatStyle::PAS_Left);
251     IO.enumCase(Value, "false", FormatStyle::PAS_Right);
252   }
253 };
254 
255 template <>
256 struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
257   static void enumeration(IO &IO,
258                           FormatStyle::SpaceBeforeParensOptions &Value) {
259     IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
260     IO.enumCase(Value, "ControlStatements",
261                 FormatStyle::SBPO_ControlStatements);
262     IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
263 
264     // For backward compatibility.
265     IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
266     IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
267   }
268 };
269 
270 template <> struct MappingTraits<FormatStyle> {
271   static void mapping(IO &IO, FormatStyle &Style) {
272     // When reading, read the language first, we need it for getPredefinedStyle.
273     IO.mapOptional("Language", Style.Language);
274 
275     if (IO.outputting()) {
276       StringRef StylesArray[] = {"LLVM",    "Google", "Chromium",
277                                  "Mozilla", "WebKit", "GNU"};
278       ArrayRef<StringRef> Styles(StylesArray);
279       for (size_t i = 0, e = Styles.size(); i < e; ++i) {
280         StringRef StyleName(Styles[i]);
281         FormatStyle PredefinedStyle;
282         if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
283             Style == PredefinedStyle) {
284           IO.mapOptional("# BasedOnStyle", StyleName);
285           break;
286         }
287       }
288     } else {
289       StringRef BasedOnStyle;
290       IO.mapOptional("BasedOnStyle", BasedOnStyle);
291       if (!BasedOnStyle.empty()) {
292         FormatStyle::LanguageKind OldLanguage = Style.Language;
293         FormatStyle::LanguageKind Language =
294             ((FormatStyle *)IO.getContext())->Language;
295         if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
296           IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
297           return;
298         }
299         Style.Language = OldLanguage;
300       }
301     }
302 
303     // For backward compatibility.
304     if (!IO.outputting()) {
305       IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlines);
306       IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
307       IO.mapOptional("IndentFunctionDeclarationAfterType",
308                      Style.IndentWrappedFunctionNames);
309       IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
310       IO.mapOptional("SpaceAfterControlStatementKeyword",
311                      Style.SpaceBeforeParens);
312     }
313 
314     IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
315     IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
316     IO.mapOptional("AlignConsecutiveAssignments",
317                    Style.AlignConsecutiveAssignments);
318     IO.mapOptional("AlignConsecutiveDeclarations",
319                    Style.AlignConsecutiveDeclarations);
320     IO.mapOptional("AlignEscapedNewlines", Style.AlignEscapedNewlines);
321     IO.mapOptional("AlignOperands", Style.AlignOperands);
322     IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
323     IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
324                    Style.AllowAllParametersOfDeclarationOnNextLine);
325     IO.mapOptional("AllowShortBlocksOnASingleLine",
326                    Style.AllowShortBlocksOnASingleLine);
327     IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
328                    Style.AllowShortCaseLabelsOnASingleLine);
329     IO.mapOptional("AllowShortFunctionsOnASingleLine",
330                    Style.AllowShortFunctionsOnASingleLine);
331     IO.mapOptional("AllowShortIfStatementsOnASingleLine",
332                    Style.AllowShortIfStatementsOnASingleLine);
333     IO.mapOptional("AllowShortLoopsOnASingleLine",
334                    Style.AllowShortLoopsOnASingleLine);
335     IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
336                    Style.AlwaysBreakAfterDefinitionReturnType);
337     IO.mapOptional("AlwaysBreakAfterReturnType",
338                    Style.AlwaysBreakAfterReturnType);
339     // If AlwaysBreakAfterDefinitionReturnType was specified but
340     // AlwaysBreakAfterReturnType was not, initialize the latter from the
341     // former for backwards compatibility.
342     if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
343         Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None) {
344       if (Style.AlwaysBreakAfterDefinitionReturnType == FormatStyle::DRTBS_All)
345         Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
346       else if (Style.AlwaysBreakAfterDefinitionReturnType ==
347                FormatStyle::DRTBS_TopLevel)
348         Style.AlwaysBreakAfterReturnType =
349             FormatStyle::RTBS_TopLevelDefinitions;
350     }
351 
352     IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
353                    Style.AlwaysBreakBeforeMultilineStrings);
354     IO.mapOptional("AlwaysBreakTemplateDeclarations",
355                    Style.AlwaysBreakTemplateDeclarations);
356     IO.mapOptional("BinPackArguments", Style.BinPackArguments);
357     IO.mapOptional("BinPackParameters", Style.BinPackParameters);
358     IO.mapOptional("BraceWrapping", Style.BraceWrapping);
359     IO.mapOptional("BreakBeforeBinaryOperators",
360                    Style.BreakBeforeBinaryOperators);
361     IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
362 
363     bool BreakBeforeInheritanceComma = false;
364     IO.mapOptional("BreakBeforeInheritanceComma",
365                    BreakBeforeInheritanceComma);
366     IO.mapOptional("BreakInheritanceList",
367                    Style.BreakInheritanceList);
368     // If BreakBeforeInheritanceComma was specified but
369     // BreakInheritance was not, initialize the latter from the
370     // former for backwards compatibility.
371     if (BreakBeforeInheritanceComma &&
372         Style.BreakInheritanceList == FormatStyle::BILS_BeforeColon)
373       Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
374 
375     IO.mapOptional("BreakBeforeTernaryOperators",
376                    Style.BreakBeforeTernaryOperators);
377 
378     bool BreakConstructorInitializersBeforeComma = false;
379     IO.mapOptional("BreakConstructorInitializersBeforeComma",
380                    BreakConstructorInitializersBeforeComma);
381     IO.mapOptional("BreakConstructorInitializers",
382                    Style.BreakConstructorInitializers);
383     // If BreakConstructorInitializersBeforeComma was specified but
384     // BreakConstructorInitializers was not, initialize the latter from the
385     // former for backwards compatibility.
386     if (BreakConstructorInitializersBeforeComma &&
387         Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon)
388       Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
389 
390     IO.mapOptional("BreakAfterJavaFieldAnnotations",
391                    Style.BreakAfterJavaFieldAnnotations);
392     IO.mapOptional("BreakStringLiterals", Style.BreakStringLiterals);
393     IO.mapOptional("ColumnLimit", Style.ColumnLimit);
394     IO.mapOptional("CommentPragmas", Style.CommentPragmas);
395     IO.mapOptional("CompactNamespaces", Style.CompactNamespaces);
396     IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
397                    Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
398     IO.mapOptional("ConstructorInitializerIndentWidth",
399                    Style.ConstructorInitializerIndentWidth);
400     IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
401     IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
402     IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
403     IO.mapOptional("DisableFormat", Style.DisableFormat);
404     IO.mapOptional("ExperimentalAutoDetectBinPacking",
405                    Style.ExperimentalAutoDetectBinPacking);
406     IO.mapOptional("FixNamespaceComments", Style.FixNamespaceComments);
407     IO.mapOptional("ForEachMacros", Style.ForEachMacros);
408     IO.mapOptional("IncludeBlocks", Style.IncludeStyle.IncludeBlocks);
409     IO.mapOptional("IncludeCategories", Style.IncludeStyle.IncludeCategories);
410     IO.mapOptional("IncludeIsMainRegex", Style.IncludeStyle.IncludeIsMainRegex);
411     IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
412     IO.mapOptional("IndentPPDirectives", Style.IndentPPDirectives);
413     IO.mapOptional("IndentWidth", Style.IndentWidth);
414     IO.mapOptional("IndentWrappedFunctionNames",
415                    Style.IndentWrappedFunctionNames);
416     IO.mapOptional("JavaImportGroups", Style.JavaImportGroups);
417     IO.mapOptional("JavaScriptQuotes", Style.JavaScriptQuotes);
418     IO.mapOptional("JavaScriptWrapImports", Style.JavaScriptWrapImports);
419     IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
420                    Style.KeepEmptyLinesAtTheStartOfBlocks);
421     IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
422     IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
423     IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
424     IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
425     IO.mapOptional("ObjCBinPackProtocolList", Style.ObjCBinPackProtocolList);
426     IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
427     IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
428     IO.mapOptional("ObjCSpaceBeforeProtocolList",
429                    Style.ObjCSpaceBeforeProtocolList);
430     IO.mapOptional("PenaltyBreakAssignment", Style.PenaltyBreakAssignment);
431     IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
432                    Style.PenaltyBreakBeforeFirstCallParameter);
433     IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
434     IO.mapOptional("PenaltyBreakFirstLessLess",
435                    Style.PenaltyBreakFirstLessLess);
436     IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
437     IO.mapOptional("PenaltyBreakTemplateDeclaration",
438                    Style.PenaltyBreakTemplateDeclaration);
439     IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
440     IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
441                    Style.PenaltyReturnTypeOnItsOwnLine);
442     IO.mapOptional("PointerAlignment", Style.PointerAlignment);
443     IO.mapOptional("RawStringFormats", Style.RawStringFormats);
444     IO.mapOptional("ReflowComments", Style.ReflowComments);
445     IO.mapOptional("SortIncludes", Style.SortIncludes);
446     IO.mapOptional("SortUsingDeclarations", Style.SortUsingDeclarations);
447     IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
448     IO.mapOptional("SpaceAfterTemplateKeyword",
449                    Style.SpaceAfterTemplateKeyword);
450     IO.mapOptional("SpaceBeforeAssignmentOperators",
451                    Style.SpaceBeforeAssignmentOperators);
452     IO.mapOptional("SpaceBeforeCpp11BracedList",
453                    Style.SpaceBeforeCpp11BracedList);
454     IO.mapOptional("SpaceBeforeCtorInitializerColon",
455                    Style.SpaceBeforeCtorInitializerColon);
456     IO.mapOptional("SpaceBeforeInheritanceColon",
457                    Style.SpaceBeforeInheritanceColon);
458     IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
459     IO.mapOptional("SpaceBeforeRangeBasedForLoopColon",
460                    Style.SpaceBeforeRangeBasedForLoopColon);
461     IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
462     IO.mapOptional("SpacesBeforeTrailingComments",
463                    Style.SpacesBeforeTrailingComments);
464     IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
465     IO.mapOptional("SpacesInContainerLiterals",
466                    Style.SpacesInContainerLiterals);
467     IO.mapOptional("SpacesInCStyleCastParentheses",
468                    Style.SpacesInCStyleCastParentheses);
469     IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
470     IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
471     IO.mapOptional("Standard", Style.Standard);
472     IO.mapOptional("StatementMacros", Style.StatementMacros);
473     IO.mapOptional("TabWidth", Style.TabWidth);
474     IO.mapOptional("UseTab", Style.UseTab);
475   }
476 };
477 
478 template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
479   static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
480     IO.mapOptional("AfterClass", Wrapping.AfterClass);
481     IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
482     IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
483     IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
484     IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
485     IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
486     IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
487     IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
488     IO.mapOptional("AfterExternBlock", Wrapping.AfterExternBlock);
489     IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
490     IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
491     IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
492     IO.mapOptional("SplitEmptyFunction", Wrapping.SplitEmptyFunction);
493     IO.mapOptional("SplitEmptyRecord", Wrapping.SplitEmptyRecord);
494     IO.mapOptional("SplitEmptyNamespace", Wrapping.SplitEmptyNamespace);
495   }
496 };
497 
498 template <> struct MappingTraits<FormatStyle::RawStringFormat> {
499   static void mapping(IO &IO, FormatStyle::RawStringFormat &Format) {
500     IO.mapOptional("Language", Format.Language);
501     IO.mapOptional("Delimiters", Format.Delimiters);
502     IO.mapOptional("EnclosingFunctions", Format.EnclosingFunctions);
503     IO.mapOptional("CanonicalDelimiter", Format.CanonicalDelimiter);
504     IO.mapOptional("BasedOnStyle", Format.BasedOnStyle);
505   }
506 };
507 
508 // Allows to read vector<FormatStyle> while keeping default values.
509 // IO.getContext() should contain a pointer to the FormatStyle structure, that
510 // will be used to get default values for missing keys.
511 // If the first element has no Language specified, it will be treated as the
512 // default one for the following elements.
513 template <> struct DocumentListTraits<std::vector<FormatStyle>> {
514   static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
515     return Seq.size();
516   }
517   static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
518                               size_t Index) {
519     if (Index >= Seq.size()) {
520       assert(Index == Seq.size());
521       FormatStyle Template;
522       if (!Seq.empty() && Seq[0].Language == FormatStyle::LK_None) {
523         Template = Seq[0];
524       } else {
525         Template = *((const FormatStyle *)IO.getContext());
526         Template.Language = FormatStyle::LK_None;
527       }
528       Seq.resize(Index + 1, Template);
529     }
530     return Seq[Index];
531   }
532 };
533 } // namespace yaml
534 } // namespace llvm
535 
536 namespace clang {
537 namespace format {
538 
539 const std::error_category &getParseCategory() {
540   static const ParseErrorCategory C{};
541   return C;
542 }
543 std::error_code make_error_code(ParseError e) {
544   return std::error_code(static_cast<int>(e), getParseCategory());
545 }
546 
547 inline llvm::Error make_string_error(const llvm::Twine &Message) {
548   return llvm::make_error<llvm::StringError>(Message,
549                                              llvm::inconvertibleErrorCode());
550 }
551 
552 const char *ParseErrorCategory::name() const noexcept {
553   return "clang-format.parse_error";
554 }
555 
556 std::string ParseErrorCategory::message(int EV) const {
557   switch (static_cast<ParseError>(EV)) {
558   case ParseError::Success:
559     return "Success";
560   case ParseError::Error:
561     return "Invalid argument";
562   case ParseError::Unsuitable:
563     return "Unsuitable";
564   }
565   llvm_unreachable("unexpected parse error");
566 }
567 
568 static FormatStyle expandPresets(const FormatStyle &Style) {
569   if (Style.BreakBeforeBraces == FormatStyle::BS_Custom)
570     return Style;
571   FormatStyle Expanded = Style;
572   Expanded.BraceWrapping = {false, false, false, false, false,
573                             false, false, false, false, false,
574                             false, false, true,  true,  true};
575   switch (Style.BreakBeforeBraces) {
576   case FormatStyle::BS_Linux:
577     Expanded.BraceWrapping.AfterClass = true;
578     Expanded.BraceWrapping.AfterFunction = true;
579     Expanded.BraceWrapping.AfterNamespace = true;
580     break;
581   case FormatStyle::BS_Mozilla:
582     Expanded.BraceWrapping.AfterClass = true;
583     Expanded.BraceWrapping.AfterEnum = true;
584     Expanded.BraceWrapping.AfterFunction = true;
585     Expanded.BraceWrapping.AfterStruct = true;
586     Expanded.BraceWrapping.AfterUnion = true;
587     Expanded.BraceWrapping.AfterExternBlock = true;
588     Expanded.BraceWrapping.SplitEmptyFunction = true;
589     Expanded.BraceWrapping.SplitEmptyRecord = false;
590     break;
591   case FormatStyle::BS_Stroustrup:
592     Expanded.BraceWrapping.AfterFunction = true;
593     Expanded.BraceWrapping.BeforeCatch = true;
594     Expanded.BraceWrapping.BeforeElse = true;
595     break;
596   case FormatStyle::BS_Allman:
597     Expanded.BraceWrapping.AfterClass = true;
598     Expanded.BraceWrapping.AfterControlStatement = true;
599     Expanded.BraceWrapping.AfterEnum = true;
600     Expanded.BraceWrapping.AfterFunction = true;
601     Expanded.BraceWrapping.AfterNamespace = true;
602     Expanded.BraceWrapping.AfterObjCDeclaration = true;
603     Expanded.BraceWrapping.AfterStruct = true;
604     Expanded.BraceWrapping.AfterExternBlock = true;
605     Expanded.BraceWrapping.BeforeCatch = true;
606     Expanded.BraceWrapping.BeforeElse = true;
607     break;
608   case FormatStyle::BS_GNU:
609     Expanded.BraceWrapping = {true, true, true, true, true, true, true, true,
610                               true, true, true, true, true, true, true};
611     break;
612   case FormatStyle::BS_WebKit:
613     Expanded.BraceWrapping.AfterFunction = true;
614     break;
615   default:
616     break;
617   }
618   return Expanded;
619 }
620 
621 FormatStyle getLLVMStyle(FormatStyle::LanguageKind Language) {
622   FormatStyle LLVMStyle;
623   LLVMStyle.Language = Language;
624   LLVMStyle.AccessModifierOffset = -2;
625   LLVMStyle.AlignEscapedNewlines = FormatStyle::ENAS_Right;
626   LLVMStyle.AlignAfterOpenBracket = FormatStyle::BAS_Align;
627   LLVMStyle.AlignOperands = true;
628   LLVMStyle.AlignTrailingComments = true;
629   LLVMStyle.AlignConsecutiveAssignments = false;
630   LLVMStyle.AlignConsecutiveDeclarations = false;
631   LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
632   LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
633   LLVMStyle.AllowShortBlocksOnASingleLine = false;
634   LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
635   LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
636   LLVMStyle.AllowShortLoopsOnASingleLine = false;
637   LLVMStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
638   LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
639   LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
640   LLVMStyle.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_MultiLine;
641   LLVMStyle.BinPackArguments = true;
642   LLVMStyle.BinPackParameters = true;
643   LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
644   LLVMStyle.BreakBeforeTernaryOperators = true;
645   LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
646   LLVMStyle.BraceWrapping = {false, false, false, false, false,
647                              false, false, false, false, false,
648                              false, false, true,  true,  true};
649   LLVMStyle.BreakAfterJavaFieldAnnotations = false;
650   LLVMStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
651   LLVMStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
652   LLVMStyle.BreakStringLiterals = true;
653   LLVMStyle.ColumnLimit = 80;
654   LLVMStyle.CommentPragmas = "^ IWYU pragma:";
655   LLVMStyle.CompactNamespaces = false;
656   LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
657   LLVMStyle.ConstructorInitializerIndentWidth = 4;
658   LLVMStyle.ContinuationIndentWidth = 4;
659   LLVMStyle.Cpp11BracedListStyle = true;
660   LLVMStyle.DerivePointerAlignment = false;
661   LLVMStyle.ExperimentalAutoDetectBinPacking = false;
662   LLVMStyle.FixNamespaceComments = true;
663   LLVMStyle.ForEachMacros.push_back("foreach");
664   LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
665   LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
666   LLVMStyle.IncludeStyle.IncludeCategories = {
667       {"^\"(llvm|llvm-c|clang|clang-c)/", 2},
668       {"^(<|\"(gtest|gmock|isl|json)/)", 3},
669       {".*", 1}};
670   LLVMStyle.IncludeStyle.IncludeIsMainRegex = "(Test)?$";
671   LLVMStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Preserve;
672   LLVMStyle.IndentCaseLabels = false;
673   LLVMStyle.IndentPPDirectives = FormatStyle::PPDIS_None;
674   LLVMStyle.IndentWrappedFunctionNames = false;
675   LLVMStyle.IndentWidth = 2;
676   LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
677   LLVMStyle.JavaScriptWrapImports = true;
678   LLVMStyle.TabWidth = 8;
679   LLVMStyle.MaxEmptyLinesToKeep = 1;
680   LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
681   LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
682   LLVMStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Auto;
683   LLVMStyle.ObjCBlockIndentWidth = 2;
684   LLVMStyle.ObjCSpaceAfterProperty = false;
685   LLVMStyle.ObjCSpaceBeforeProtocolList = true;
686   LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
687   LLVMStyle.SpacesBeforeTrailingComments = 1;
688   LLVMStyle.Standard = FormatStyle::LS_Cpp11;
689   LLVMStyle.UseTab = FormatStyle::UT_Never;
690   LLVMStyle.ReflowComments = true;
691   LLVMStyle.SpacesInParentheses = false;
692   LLVMStyle.SpacesInSquareBrackets = false;
693   LLVMStyle.SpaceInEmptyParentheses = false;
694   LLVMStyle.SpacesInContainerLiterals = true;
695   LLVMStyle.SpacesInCStyleCastParentheses = false;
696   LLVMStyle.SpaceAfterCStyleCast = false;
697   LLVMStyle.SpaceAfterTemplateKeyword = true;
698   LLVMStyle.SpaceBeforeCtorInitializerColon = true;
699   LLVMStyle.SpaceBeforeInheritanceColon = true;
700   LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
701   LLVMStyle.SpaceBeforeRangeBasedForLoopColon = true;
702   LLVMStyle.SpaceBeforeAssignmentOperators = true;
703   LLVMStyle.SpaceBeforeCpp11BracedList = false;
704   LLVMStyle.SpacesInAngles = false;
705 
706   LLVMStyle.PenaltyBreakAssignment = prec::Assignment;
707   LLVMStyle.PenaltyBreakComment = 300;
708   LLVMStyle.PenaltyBreakFirstLessLess = 120;
709   LLVMStyle.PenaltyBreakString = 1000;
710   LLVMStyle.PenaltyExcessCharacter = 1000000;
711   LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
712   LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
713   LLVMStyle.PenaltyBreakTemplateDeclaration = prec::Relational;
714 
715   LLVMStyle.DisableFormat = false;
716   LLVMStyle.SortIncludes = true;
717   LLVMStyle.SortUsingDeclarations = true;
718   LLVMStyle.StatementMacros.push_back("Q_UNUSED");
719   LLVMStyle.StatementMacros.push_back("QT_REQUIRE_VERSION");
720 
721   // Defaults that differ when not C++.
722   if (Language == FormatStyle::LK_TableGen) {
723     LLVMStyle.SpacesInContainerLiterals = false;
724   }
725 
726   return LLVMStyle;
727 }
728 
729 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
730   if (Language == FormatStyle::LK_TextProto) {
731     FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_Proto);
732     GoogleStyle.Language = FormatStyle::LK_TextProto;
733 
734     return GoogleStyle;
735   }
736 
737   FormatStyle GoogleStyle = getLLVMStyle(Language);
738 
739   GoogleStyle.AccessModifierOffset = -1;
740   GoogleStyle.AlignEscapedNewlines = FormatStyle::ENAS_Left;
741   GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
742   GoogleStyle.AllowShortLoopsOnASingleLine = true;
743   GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
744   GoogleStyle.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
745   GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
746   GoogleStyle.DerivePointerAlignment = true;
747   GoogleStyle.IncludeStyle.IncludeCategories = {
748       {"^<ext/.*\\.h>", 2}, {"^<.*\\.h>", 1}, {"^<.*", 2}, {".*", 3}};
749   GoogleStyle.IncludeStyle.IncludeIsMainRegex = "([-_](test|unittest))?$";
750   GoogleStyle.IndentCaseLabels = true;
751   GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
752   GoogleStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
753   GoogleStyle.ObjCSpaceAfterProperty = false;
754   GoogleStyle.ObjCSpaceBeforeProtocolList = true;
755   GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
756   GoogleStyle.RawStringFormats = {
757       {
758           FormatStyle::LK_Cpp,
759           /*Delimiters=*/
760           {
761               "cc",
762               "CC",
763               "cpp",
764               "Cpp",
765               "CPP",
766               "c++",
767               "C++",
768           },
769           /*EnclosingFunctionNames=*/
770           {},
771           /*CanonicalDelimiter=*/"",
772           /*BasedOnStyle=*/"google",
773       },
774       {
775           FormatStyle::LK_TextProto,
776           /*Delimiters=*/
777           {
778               "pb",
779               "PB",
780               "proto",
781               "PROTO",
782           },
783           /*EnclosingFunctionNames=*/
784           {
785               "EqualsProto",
786               "EquivToProto",
787               "PARSE_PARTIAL_TEXT_PROTO",
788               "PARSE_TEST_PROTO",
789               "PARSE_TEXT_PROTO",
790               "ParseTextOrDie",
791               "ParseTextProtoOrDie",
792           },
793           /*CanonicalDelimiter=*/"",
794           /*BasedOnStyle=*/"google",
795       },
796   };
797   GoogleStyle.SpacesBeforeTrailingComments = 2;
798   GoogleStyle.Standard = FormatStyle::LS_Auto;
799 
800   GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
801   GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
802 
803   if (Language == FormatStyle::LK_Java) {
804     GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
805     GoogleStyle.AlignOperands = false;
806     GoogleStyle.AlignTrailingComments = false;
807     GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
808     GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
809     GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
810     GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
811     GoogleStyle.ColumnLimit = 100;
812     GoogleStyle.SpaceAfterCStyleCast = true;
813     GoogleStyle.SpacesBeforeTrailingComments = 1;
814   } else if (Language == FormatStyle::LK_JavaScript) {
815     GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
816     GoogleStyle.AlignOperands = false;
817     GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
818     GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
819     GoogleStyle.BreakBeforeTernaryOperators = false;
820     // taze:, triple slash directives (`/// <...`), @see, which is commonly
821     // followed by overlong URLs.
822     GoogleStyle.CommentPragmas = "(taze:|^/[ \t]*<|@see)";
823     GoogleStyle.MaxEmptyLinesToKeep = 3;
824     GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
825     GoogleStyle.SpacesInContainerLiterals = false;
826     GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single;
827     GoogleStyle.JavaScriptWrapImports = false;
828   } else if (Language == FormatStyle::LK_Proto) {
829     GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
830     GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
831     GoogleStyle.SpacesInContainerLiterals = false;
832     GoogleStyle.Cpp11BracedListStyle = false;
833     // This affects protocol buffer options specifications and text protos.
834     // Text protos are currently mostly formatted inside C++ raw string literals
835     // and often the current breaking behavior of string literals is not
836     // beneficial there. Investigate turning this on once proper string reflow
837     // has been implemented.
838     GoogleStyle.BreakStringLiterals = false;
839   } else if (Language == FormatStyle::LK_ObjC) {
840     GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
841     GoogleStyle.ColumnLimit = 100;
842   }
843 
844   return GoogleStyle;
845 }
846 
847 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
848   FormatStyle ChromiumStyle = getGoogleStyle(Language);
849   if (Language == FormatStyle::LK_Java) {
850     ChromiumStyle.AllowShortIfStatementsOnASingleLine = true;
851     ChromiumStyle.BreakAfterJavaFieldAnnotations = true;
852     ChromiumStyle.ContinuationIndentWidth = 8;
853     ChromiumStyle.IndentWidth = 4;
854     // See styleguide for import groups:
855     // https://chromium.googlesource.com/chromium/src/+/master/styleguide/java/java.md#Import-Order
856     ChromiumStyle.JavaImportGroups = {
857         "android",
858         "com",
859         "dalvik",
860         "junit",
861         "org",
862         "com.google.android.apps.chrome",
863         "org.chromium",
864         "java",
865         "javax",
866     };
867     ChromiumStyle.SortIncludes = true;
868   } else if (Language == FormatStyle::LK_JavaScript) {
869     ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
870     ChromiumStyle.AllowShortLoopsOnASingleLine = false;
871   } else {
872     ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
873     ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
874     ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
875     ChromiumStyle.AllowShortLoopsOnASingleLine = false;
876     ChromiumStyle.BinPackParameters = false;
877     ChromiumStyle.DerivePointerAlignment = false;
878     if (Language == FormatStyle::LK_ObjC)
879       ChromiumStyle.ColumnLimit = 80;
880   }
881   return ChromiumStyle;
882 }
883 
884 FormatStyle getMozillaStyle() {
885   FormatStyle MozillaStyle = getLLVMStyle();
886   MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
887   MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
888   MozillaStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
889   MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
890       FormatStyle::DRTBS_TopLevel;
891   MozillaStyle.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
892   MozillaStyle.BinPackParameters = false;
893   MozillaStyle.BinPackArguments = false;
894   MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
895   MozillaStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
896   MozillaStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
897   MozillaStyle.ConstructorInitializerIndentWidth = 2;
898   MozillaStyle.ContinuationIndentWidth = 2;
899   MozillaStyle.Cpp11BracedListStyle = false;
900   MozillaStyle.FixNamespaceComments = false;
901   MozillaStyle.IndentCaseLabels = true;
902   MozillaStyle.ObjCSpaceAfterProperty = true;
903   MozillaStyle.ObjCSpaceBeforeProtocolList = false;
904   MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
905   MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
906   MozillaStyle.SpaceAfterTemplateKeyword = false;
907   return MozillaStyle;
908 }
909 
910 FormatStyle getWebKitStyle() {
911   FormatStyle Style = getLLVMStyle();
912   Style.AccessModifierOffset = -4;
913   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
914   Style.AlignOperands = false;
915   Style.AlignTrailingComments = false;
916   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
917   Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
918   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
919   Style.Cpp11BracedListStyle = false;
920   Style.ColumnLimit = 0;
921   Style.FixNamespaceComments = false;
922   Style.IndentWidth = 4;
923   Style.NamespaceIndentation = FormatStyle::NI_Inner;
924   Style.ObjCBlockIndentWidth = 4;
925   Style.ObjCSpaceAfterProperty = true;
926   Style.PointerAlignment = FormatStyle::PAS_Left;
927   Style.SpaceBeforeCpp11BracedList = true;
928   return Style;
929 }
930 
931 FormatStyle getGNUStyle() {
932   FormatStyle Style = getLLVMStyle();
933   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
934   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
935   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
936   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
937   Style.BreakBeforeTernaryOperators = true;
938   Style.Cpp11BracedListStyle = false;
939   Style.ColumnLimit = 79;
940   Style.FixNamespaceComments = false;
941   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
942   Style.Standard = FormatStyle::LS_Cpp03;
943   return Style;
944 }
945 
946 FormatStyle getNoStyle() {
947   FormatStyle NoStyle = getLLVMStyle();
948   NoStyle.DisableFormat = true;
949   NoStyle.SortIncludes = false;
950   NoStyle.SortUsingDeclarations = false;
951   return NoStyle;
952 }
953 
954 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
955                         FormatStyle *Style) {
956   if (Name.equals_lower("llvm")) {
957     *Style = getLLVMStyle();
958   } else if (Name.equals_lower("chromium")) {
959     *Style = getChromiumStyle(Language);
960   } else if (Name.equals_lower("mozilla")) {
961     *Style = getMozillaStyle();
962   } else if (Name.equals_lower("google")) {
963     *Style = getGoogleStyle(Language);
964   } else if (Name.equals_lower("webkit")) {
965     *Style = getWebKitStyle();
966   } else if (Name.equals_lower("gnu")) {
967     *Style = getGNUStyle();
968   } else if (Name.equals_lower("none")) {
969     *Style = getNoStyle();
970   } else {
971     return false;
972   }
973 
974   Style->Language = Language;
975   return true;
976 }
977 
978 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
979   assert(Style);
980   FormatStyle::LanguageKind Language = Style->Language;
981   assert(Language != FormatStyle::LK_None);
982   if (Text.trim().empty())
983     return make_error_code(ParseError::Error);
984   Style->StyleSet.Clear();
985   std::vector<FormatStyle> Styles;
986   llvm::yaml::Input Input(Text);
987   // DocumentListTraits<vector<FormatStyle>> uses the context to get default
988   // values for the fields, keys for which are missing from the configuration.
989   // Mapping also uses the context to get the language to find the correct
990   // base style.
991   Input.setContext(Style);
992   Input >> Styles;
993   if (Input.error())
994     return Input.error();
995 
996   for (unsigned i = 0; i < Styles.size(); ++i) {
997     // Ensures that only the first configuration can skip the Language option.
998     if (Styles[i].Language == FormatStyle::LK_None && i != 0)
999       return make_error_code(ParseError::Error);
1000     // Ensure that each language is configured at most once.
1001     for (unsigned j = 0; j < i; ++j) {
1002       if (Styles[i].Language == Styles[j].Language) {
1003         LLVM_DEBUG(llvm::dbgs()
1004                    << "Duplicate languages in the config file on positions "
1005                    << j << " and " << i << "\n");
1006         return make_error_code(ParseError::Error);
1007       }
1008     }
1009   }
1010   // Look for a suitable configuration starting from the end, so we can
1011   // find the configuration for the specific language first, and the default
1012   // configuration (which can only be at slot 0) after it.
1013   FormatStyle::FormatStyleSet StyleSet;
1014   bool LanguageFound = false;
1015   for (int i = Styles.size() - 1; i >= 0; --i) {
1016     if (Styles[i].Language != FormatStyle::LK_None)
1017       StyleSet.Add(Styles[i]);
1018     if (Styles[i].Language == Language)
1019       LanguageFound = true;
1020   }
1021   if (!LanguageFound) {
1022     if (Styles.empty() || Styles[0].Language != FormatStyle::LK_None)
1023       return make_error_code(ParseError::Unsuitable);
1024     FormatStyle DefaultStyle = Styles[0];
1025     DefaultStyle.Language = Language;
1026     StyleSet.Add(std::move(DefaultStyle));
1027   }
1028   *Style = *StyleSet.Get(Language);
1029   return make_error_code(ParseError::Success);
1030 }
1031 
1032 std::string configurationAsText(const FormatStyle &Style) {
1033   std::string Text;
1034   llvm::raw_string_ostream Stream(Text);
1035   llvm::yaml::Output Output(Stream);
1036   // We use the same mapping method for input and output, so we need a non-const
1037   // reference here.
1038   FormatStyle NonConstStyle = expandPresets(Style);
1039   Output << NonConstStyle;
1040   return Stream.str();
1041 }
1042 
1043 llvm::Optional<FormatStyle>
1044 FormatStyle::FormatStyleSet::Get(FormatStyle::LanguageKind Language) const {
1045   if (!Styles)
1046     return None;
1047   auto It = Styles->find(Language);
1048   if (It == Styles->end())
1049     return None;
1050   FormatStyle Style = It->second;
1051   Style.StyleSet = *this;
1052   return Style;
1053 }
1054 
1055 void FormatStyle::FormatStyleSet::Add(FormatStyle Style) {
1056   assert(Style.Language != LK_None &&
1057          "Cannot add a style for LK_None to a StyleSet");
1058   assert(
1059       !Style.StyleSet.Styles &&
1060       "Cannot add a style associated with an existing StyleSet to a StyleSet");
1061   if (!Styles)
1062     Styles = std::make_shared<MapType>();
1063   (*Styles)[Style.Language] = std::move(Style);
1064 }
1065 
1066 void FormatStyle::FormatStyleSet::Clear() {
1067   Styles.reset();
1068 }
1069 
1070 llvm::Optional<FormatStyle>
1071 FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind Language) const {
1072   return StyleSet.Get(Language);
1073 }
1074 
1075 namespace {
1076 
1077 class JavaScriptRequoter : public TokenAnalyzer {
1078 public:
1079   JavaScriptRequoter(const Environment &Env, const FormatStyle &Style)
1080       : TokenAnalyzer(Env, Style) {}
1081 
1082   std::pair<tooling::Replacements, unsigned>
1083   analyze(TokenAnnotator &Annotator,
1084           SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1085           FormatTokenLexer &Tokens) override {
1086     AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
1087     tooling::Replacements Result;
1088     requoteJSStringLiteral(AnnotatedLines, Result);
1089     return {Result, 0};
1090   }
1091 
1092 private:
1093   // Replaces double/single-quoted string literal as appropriate, re-escaping
1094   // the contents in the process.
1095   void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
1096                               tooling::Replacements &Result) {
1097     for (AnnotatedLine *Line : Lines) {
1098       requoteJSStringLiteral(Line->Children, Result);
1099       if (!Line->Affected)
1100         continue;
1101       for (FormatToken *FormatTok = Line->First; FormatTok;
1102            FormatTok = FormatTok->Next) {
1103         StringRef Input = FormatTok->TokenText;
1104         if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
1105             // NB: testing for not starting with a double quote to avoid
1106             // breaking `template strings`.
1107             (Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
1108              !Input.startswith("\"")) ||
1109             (Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
1110              !Input.startswith("\'")))
1111           continue;
1112 
1113         // Change start and end quote.
1114         bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
1115         SourceLocation Start = FormatTok->Tok.getLocation();
1116         auto Replace = [&](SourceLocation Start, unsigned Length,
1117                            StringRef ReplacementText) {
1118           auto Err = Result.add(tooling::Replacement(
1119               Env.getSourceManager(), Start, Length, ReplacementText));
1120           // FIXME: handle error. For now, print error message and skip the
1121           // replacement for release version.
1122           if (Err) {
1123             llvm::errs() << llvm::toString(std::move(Err)) << "\n";
1124             assert(false);
1125           }
1126         };
1127         Replace(Start, 1, IsSingle ? "'" : "\"");
1128         Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
1129                 IsSingle ? "'" : "\"");
1130 
1131         // Escape internal quotes.
1132         bool Escaped = false;
1133         for (size_t i = 1; i < Input.size() - 1; i++) {
1134           switch (Input[i]) {
1135           case '\\':
1136             if (!Escaped && i + 1 < Input.size() &&
1137                 ((IsSingle && Input[i + 1] == '"') ||
1138                  (!IsSingle && Input[i + 1] == '\''))) {
1139               // Remove this \, it's escaping a " or ' that no longer needs
1140               // escaping
1141               Replace(Start.getLocWithOffset(i), 1, "");
1142               continue;
1143             }
1144             Escaped = !Escaped;
1145             break;
1146           case '\"':
1147           case '\'':
1148             if (!Escaped && IsSingle == (Input[i] == '\'')) {
1149               // Escape the quote.
1150               Replace(Start.getLocWithOffset(i), 0, "\\");
1151             }
1152             Escaped = false;
1153             break;
1154           default:
1155             Escaped = false;
1156             break;
1157           }
1158         }
1159       }
1160     }
1161   }
1162 };
1163 
1164 class Formatter : public TokenAnalyzer {
1165 public:
1166   Formatter(const Environment &Env, const FormatStyle &Style,
1167             FormattingAttemptStatus *Status)
1168       : TokenAnalyzer(Env, Style), Status(Status) {}
1169 
1170   std::pair<tooling::Replacements, unsigned>
1171   analyze(TokenAnnotator &Annotator,
1172           SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1173           FormatTokenLexer &Tokens) override {
1174     tooling::Replacements Result;
1175     deriveLocalStyle(AnnotatedLines);
1176     AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
1177     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1178       Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
1179     }
1180     Annotator.setCommentLineLevels(AnnotatedLines);
1181 
1182     WhitespaceManager Whitespaces(
1183         Env.getSourceManager(), Style,
1184         inputUsesCRLF(Env.getSourceManager().getBufferData(Env.getFileID())));
1185     ContinuationIndenter Indenter(Style, Tokens.getKeywords(),
1186                                   Env.getSourceManager(), Whitespaces, Encoding,
1187                                   BinPackInconclusiveFunctions);
1188     unsigned Penalty =
1189         UnwrappedLineFormatter(&Indenter, &Whitespaces, Style,
1190                                Tokens.getKeywords(), Env.getSourceManager(),
1191                                Status)
1192             .format(AnnotatedLines, /*DryRun=*/false,
1193                     /*AdditionalIndent=*/0,
1194                     /*FixBadIndentation=*/false,
1195                     /*FirstStartColumn=*/Env.getFirstStartColumn(),
1196                     /*NextStartColumn=*/Env.getNextStartColumn(),
1197                     /*LastStartColumn=*/Env.getLastStartColumn());
1198     for (const auto &R : Whitespaces.generateReplacements())
1199       if (Result.add(R))
1200         return std::make_pair(Result, 0);
1201     return std::make_pair(Result, Penalty);
1202   }
1203 
1204 private:
1205   static bool inputUsesCRLF(StringRef Text) {
1206     return Text.count('\r') * 2 > Text.count('\n');
1207   }
1208 
1209   bool
1210   hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1211     for (const AnnotatedLine *Line : Lines) {
1212       if (hasCpp03IncompatibleFormat(Line->Children))
1213         return true;
1214       for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
1215         if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1216           if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
1217             return true;
1218           if (Tok->is(TT_TemplateCloser) &&
1219               Tok->Previous->is(TT_TemplateCloser))
1220             return true;
1221         }
1222       }
1223     }
1224     return false;
1225   }
1226 
1227   int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1228     int AlignmentDiff = 0;
1229     for (const AnnotatedLine *Line : Lines) {
1230       AlignmentDiff += countVariableAlignments(Line->Children);
1231       for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
1232         if (!Tok->is(TT_PointerOrReference))
1233           continue;
1234         bool SpaceBefore =
1235             Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1236         bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() !=
1237                           Tok->Next->WhitespaceRange.getEnd();
1238         if (SpaceBefore && !SpaceAfter)
1239           ++AlignmentDiff;
1240         if (!SpaceBefore && SpaceAfter)
1241           --AlignmentDiff;
1242       }
1243     }
1244     return AlignmentDiff;
1245   }
1246 
1247   void
1248   deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
1249     bool HasBinPackedFunction = false;
1250     bool HasOnePerLineFunction = false;
1251     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1252       if (!AnnotatedLines[i]->First->Next)
1253         continue;
1254       FormatToken *Tok = AnnotatedLines[i]->First->Next;
1255       while (Tok->Next) {
1256         if (Tok->PackingKind == PPK_BinPacked)
1257           HasBinPackedFunction = true;
1258         if (Tok->PackingKind == PPK_OnePerLine)
1259           HasOnePerLineFunction = true;
1260 
1261         Tok = Tok->Next;
1262       }
1263     }
1264     if (Style.DerivePointerAlignment)
1265       Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
1266                                    ? FormatStyle::PAS_Left
1267                                    : FormatStyle::PAS_Right;
1268     if (Style.Standard == FormatStyle::LS_Auto)
1269       Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
1270                            ? FormatStyle::LS_Cpp11
1271                            : FormatStyle::LS_Cpp03;
1272     BinPackInconclusiveFunctions =
1273         HasBinPackedFunction || !HasOnePerLineFunction;
1274   }
1275 
1276   bool BinPackInconclusiveFunctions;
1277   FormattingAttemptStatus *Status;
1278 };
1279 
1280 // This class clean up the erroneous/redundant code around the given ranges in
1281 // file.
1282 class Cleaner : public TokenAnalyzer {
1283 public:
1284   Cleaner(const Environment &Env, const FormatStyle &Style)
1285       : TokenAnalyzer(Env, Style),
1286         DeletedTokens(FormatTokenLess(Env.getSourceManager())) {}
1287 
1288   // FIXME: eliminate unused parameters.
1289   std::pair<tooling::Replacements, unsigned>
1290   analyze(TokenAnnotator &Annotator,
1291           SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1292           FormatTokenLexer &Tokens) override {
1293     // FIXME: in the current implementation the granularity of affected range
1294     // is an annotated line. However, this is not sufficient. Furthermore,
1295     // redundant code introduced by replacements does not necessarily
1296     // intercept with ranges of replacements that result in the redundancy.
1297     // To determine if some redundant code is actually introduced by
1298     // replacements(e.g. deletions), we need to come up with a more
1299     // sophisticated way of computing affected ranges.
1300     AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
1301 
1302     checkEmptyNamespace(AnnotatedLines);
1303 
1304     for (auto &Line : AnnotatedLines) {
1305       if (Line->Affected) {
1306         cleanupRight(Line->First, tok::comma, tok::comma);
1307         cleanupRight(Line->First, TT_CtorInitializerColon, tok::comma);
1308         cleanupRight(Line->First, tok::l_paren, tok::comma);
1309         cleanupLeft(Line->First, tok::comma, tok::r_paren);
1310         cleanupLeft(Line->First, TT_CtorInitializerComma, tok::l_brace);
1311         cleanupLeft(Line->First, TT_CtorInitializerColon, tok::l_brace);
1312         cleanupLeft(Line->First, TT_CtorInitializerColon, tok::equal);
1313       }
1314     }
1315 
1316     return {generateFixes(), 0};
1317   }
1318 
1319 private:
1320   bool containsOnlyComments(const AnnotatedLine &Line) {
1321     for (FormatToken *Tok = Line.First; Tok != nullptr; Tok = Tok->Next) {
1322       if (Tok->isNot(tok::comment))
1323         return false;
1324     }
1325     return true;
1326   }
1327 
1328   // Iterate through all lines and remove any empty (nested) namespaces.
1329   void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
1330     std::set<unsigned> DeletedLines;
1331     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1332       auto &Line = *AnnotatedLines[i];
1333       if (Line.startsWithNamespace()) {
1334         checkEmptyNamespace(AnnotatedLines, i, i, DeletedLines);
1335       }
1336     }
1337 
1338     for (auto Line : DeletedLines) {
1339       FormatToken *Tok = AnnotatedLines[Line]->First;
1340       while (Tok) {
1341         deleteToken(Tok);
1342         Tok = Tok->Next;
1343       }
1344     }
1345   }
1346 
1347   // The function checks if the namespace, which starts from \p CurrentLine, and
1348   // its nested namespaces are empty and delete them if they are empty. It also
1349   // sets \p NewLine to the last line checked.
1350   // Returns true if the current namespace is empty.
1351   bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1352                            unsigned CurrentLine, unsigned &NewLine,
1353                            std::set<unsigned> &DeletedLines) {
1354     unsigned InitLine = CurrentLine, End = AnnotatedLines.size();
1355     if (Style.BraceWrapping.AfterNamespace) {
1356       // If the left brace is in a new line, we should consume it first so that
1357       // it does not make the namespace non-empty.
1358       // FIXME: error handling if there is no left brace.
1359       if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
1360         NewLine = CurrentLine;
1361         return false;
1362       }
1363     } else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
1364       return false;
1365     }
1366     while (++CurrentLine < End) {
1367       if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
1368         break;
1369 
1370       if (AnnotatedLines[CurrentLine]->startsWithNamespace()) {
1371         if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine,
1372                                  DeletedLines))
1373           return false;
1374         CurrentLine = NewLine;
1375         continue;
1376       }
1377 
1378       if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
1379         continue;
1380 
1381       // If there is anything other than comments or nested namespaces in the
1382       // current namespace, the namespace cannot be empty.
1383       NewLine = CurrentLine;
1384       return false;
1385     }
1386 
1387     NewLine = CurrentLine;
1388     if (CurrentLine >= End)
1389       return false;
1390 
1391     // Check if the empty namespace is actually affected by changed ranges.
1392     if (!AffectedRangeMgr.affectsCharSourceRange(CharSourceRange::getCharRange(
1393             AnnotatedLines[InitLine]->First->Tok.getLocation(),
1394             AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc())))
1395       return false;
1396 
1397     for (unsigned i = InitLine; i <= CurrentLine; ++i) {
1398       DeletedLines.insert(i);
1399     }
1400 
1401     return true;
1402   }
1403 
1404   // Checks pairs {start, start->next},..., {end->previous, end} and deletes one
1405   // of the token in the pair if the left token has \p LK token kind and the
1406   // right token has \p RK token kind. If \p DeleteLeft is true, the left token
1407   // is deleted on match; otherwise, the right token is deleted.
1408   template <typename LeftKind, typename RightKind>
1409   void cleanupPair(FormatToken *Start, LeftKind LK, RightKind RK,
1410                    bool DeleteLeft) {
1411     auto NextNotDeleted = [this](const FormatToken &Tok) -> FormatToken * {
1412       for (auto *Res = Tok.Next; Res; Res = Res->Next)
1413         if (!Res->is(tok::comment) &&
1414             DeletedTokens.find(Res) == DeletedTokens.end())
1415           return Res;
1416       return nullptr;
1417     };
1418     for (auto *Left = Start; Left;) {
1419       auto *Right = NextNotDeleted(*Left);
1420       if (!Right)
1421         break;
1422       if (Left->is(LK) && Right->is(RK)) {
1423         deleteToken(DeleteLeft ? Left : Right);
1424         for (auto *Tok = Left->Next; Tok && Tok != Right; Tok = Tok->Next)
1425           deleteToken(Tok);
1426         // If the right token is deleted, we should keep the left token
1427         // unchanged and pair it with the new right token.
1428         if (!DeleteLeft)
1429           continue;
1430       }
1431       Left = Right;
1432     }
1433   }
1434 
1435   template <typename LeftKind, typename RightKind>
1436   void cleanupLeft(FormatToken *Start, LeftKind LK, RightKind RK) {
1437     cleanupPair(Start, LK, RK, /*DeleteLeft=*/true);
1438   }
1439 
1440   template <typename LeftKind, typename RightKind>
1441   void cleanupRight(FormatToken *Start, LeftKind LK, RightKind RK) {
1442     cleanupPair(Start, LK, RK, /*DeleteLeft=*/false);
1443   }
1444 
1445   // Delete the given token.
1446   inline void deleteToken(FormatToken *Tok) {
1447     if (Tok)
1448       DeletedTokens.insert(Tok);
1449   }
1450 
1451   tooling::Replacements generateFixes() {
1452     tooling::Replacements Fixes;
1453     std::vector<FormatToken *> Tokens;
1454     std::copy(DeletedTokens.begin(), DeletedTokens.end(),
1455               std::back_inserter(Tokens));
1456 
1457     // Merge multiple continuous token deletions into one big deletion so that
1458     // the number of replacements can be reduced. This makes computing affected
1459     // ranges more efficient when we run reformat on the changed code.
1460     unsigned Idx = 0;
1461     while (Idx < Tokens.size()) {
1462       unsigned St = Idx, End = Idx;
1463       while ((End + 1) < Tokens.size() &&
1464              Tokens[End]->Next == Tokens[End + 1]) {
1465         End++;
1466       }
1467       auto SR = CharSourceRange::getCharRange(Tokens[St]->Tok.getLocation(),
1468                                               Tokens[End]->Tok.getEndLoc());
1469       auto Err =
1470           Fixes.add(tooling::Replacement(Env.getSourceManager(), SR, ""));
1471       // FIXME: better error handling. for now just print error message and skip
1472       // for the release version.
1473       if (Err) {
1474         llvm::errs() << llvm::toString(std::move(Err)) << "\n";
1475         assert(false && "Fixes must not conflict!");
1476       }
1477       Idx = End + 1;
1478     }
1479 
1480     return Fixes;
1481   }
1482 
1483   // Class for less-than inequality comparason for the set `RedundantTokens`.
1484   // We store tokens in the order they appear in the translation unit so that
1485   // we do not need to sort them in `generateFixes()`.
1486   struct FormatTokenLess {
1487     FormatTokenLess(const SourceManager &SM) : SM(SM) {}
1488 
1489     bool operator()(const FormatToken *LHS, const FormatToken *RHS) const {
1490       return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(),
1491                                           RHS->Tok.getLocation());
1492     }
1493     const SourceManager &SM;
1494   };
1495 
1496   // Tokens to be deleted.
1497   std::set<FormatToken *, FormatTokenLess> DeletedTokens;
1498 };
1499 
1500 class ObjCHeaderStyleGuesser : public TokenAnalyzer {
1501 public:
1502   ObjCHeaderStyleGuesser(const Environment &Env, const FormatStyle &Style)
1503       : TokenAnalyzer(Env, Style), IsObjC(false) {}
1504 
1505   std::pair<tooling::Replacements, unsigned>
1506   analyze(TokenAnnotator &Annotator,
1507           SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1508           FormatTokenLexer &Tokens) override {
1509     assert(Style.Language == FormatStyle::LK_Cpp);
1510     IsObjC = guessIsObjC(Env.getSourceManager(), AnnotatedLines,
1511                          Tokens.getKeywords());
1512     tooling::Replacements Result;
1513     return {Result, 0};
1514   }
1515 
1516   bool isObjC() { return IsObjC; }
1517 
1518 private:
1519   static bool
1520   guessIsObjC(const SourceManager &SourceManager,
1521               const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1522               const AdditionalKeywords &Keywords) {
1523     // Keep this array sorted, since we are binary searching over it.
1524     static constexpr llvm::StringLiteral FoundationIdentifiers[] = {
1525         "CGFloat",
1526         "CGPoint",
1527         "CGPointMake",
1528         "CGPointZero",
1529         "CGRect",
1530         "CGRectEdge",
1531         "CGRectInfinite",
1532         "CGRectMake",
1533         "CGRectNull",
1534         "CGRectZero",
1535         "CGSize",
1536         "CGSizeMake",
1537         "CGVector",
1538         "CGVectorMake",
1539         "NSAffineTransform",
1540         "NSArray",
1541         "NSAttributedString",
1542         "NSBlockOperation",
1543         "NSBundle",
1544         "NSCache",
1545         "NSCalendar",
1546         "NSCharacterSet",
1547         "NSCountedSet",
1548         "NSData",
1549         "NSDataDetector",
1550         "NSDecimal",
1551         "NSDecimalNumber",
1552         "NSDictionary",
1553         "NSEdgeInsets",
1554         "NSHashTable",
1555         "NSIndexPath",
1556         "NSIndexSet",
1557         "NSInteger",
1558         "NSInvocationOperation",
1559         "NSLocale",
1560         "NSMapTable",
1561         "NSMutableArray",
1562         "NSMutableAttributedString",
1563         "NSMutableCharacterSet",
1564         "NSMutableData",
1565         "NSMutableDictionary",
1566         "NSMutableIndexSet",
1567         "NSMutableOrderedSet",
1568         "NSMutableSet",
1569         "NSMutableString",
1570         "NSNumber",
1571         "NSNumberFormatter",
1572         "NSObject",
1573         "NSOperation",
1574         "NSOperationQueue",
1575         "NSOperationQueuePriority",
1576         "NSOrderedSet",
1577         "NSPoint",
1578         "NSPointerArray",
1579         "NSQualityOfService",
1580         "NSRange",
1581         "NSRect",
1582         "NSRegularExpression",
1583         "NSSet",
1584         "NSSize",
1585         "NSString",
1586         "NSTimeZone",
1587         "NSUInteger",
1588         "NSURL",
1589         "NSURLComponents",
1590         "NSURLQueryItem",
1591         "NSUUID",
1592         "NSValue",
1593         "UIImage",
1594         "UIView",
1595     };
1596 
1597     for (auto Line : AnnotatedLines) {
1598       for (const FormatToken *FormatTok = Line->First; FormatTok;
1599            FormatTok = FormatTok->Next) {
1600         if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) &&
1601              (FormatTok->Tok.getObjCKeywordID() != tok::objc_not_keyword ||
1602               FormatTok->isOneOf(tok::numeric_constant, tok::l_square,
1603                                  tok::l_brace))) ||
1604             (FormatTok->Tok.isAnyIdentifier() &&
1605              std::binary_search(std::begin(FoundationIdentifiers),
1606                                 std::end(FoundationIdentifiers),
1607                                 FormatTok->TokenText)) ||
1608             FormatTok->is(TT_ObjCStringLiteral) ||
1609             FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1610                                TT_ObjCBlockLBrace, TT_ObjCBlockLParen,
1611                                TT_ObjCDecl, TT_ObjCForIn, TT_ObjCMethodExpr,
1612                                TT_ObjCMethodSpecifier, TT_ObjCProperty)) {
1613           LLVM_DEBUG(llvm::dbgs()
1614                      << "Detected ObjC at location "
1615                      << FormatTok->Tok.getLocation().printToString(
1616                             SourceManager)
1617                      << " token: " << FormatTok->TokenText << " token type: "
1618                      << getTokenTypeName(FormatTok->Type) << "\n");
1619           return true;
1620         }
1621         if (guessIsObjC(SourceManager, Line->Children, Keywords))
1622           return true;
1623       }
1624     }
1625     return false;
1626   }
1627 
1628   bool IsObjC;
1629 };
1630 
1631 struct IncludeDirective {
1632   StringRef Filename;
1633   StringRef Text;
1634   unsigned Offset;
1635   int Category;
1636 };
1637 
1638 struct JavaImportDirective {
1639   StringRef Identifier;
1640   StringRef Text;
1641   unsigned Offset;
1642   std::vector<StringRef> AssociatedCommentLines;
1643   bool IsStatic;
1644 };
1645 
1646 } // end anonymous namespace
1647 
1648 // Determines whether 'Ranges' intersects with ('Start', 'End').
1649 static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
1650                          unsigned End) {
1651   for (auto Range : Ranges) {
1652     if (Range.getOffset() < End &&
1653         Range.getOffset() + Range.getLength() > Start)
1654       return true;
1655   }
1656   return false;
1657 }
1658 
1659 // Returns a pair (Index, OffsetToEOL) describing the position of the cursor
1660 // before sorting/deduplicating. Index is the index of the include under the
1661 // cursor in the original set of includes. If this include has duplicates, it is
1662 // the index of the first of the duplicates as the others are going to be
1663 // removed. OffsetToEOL describes the cursor's position relative to the end of
1664 // its current line.
1665 // If `Cursor` is not on any #include, `Index` will be UINT_MAX.
1666 static std::pair<unsigned, unsigned>
1667 FindCursorIndex(const SmallVectorImpl<IncludeDirective> &Includes,
1668                 const SmallVectorImpl<unsigned> &Indices, unsigned Cursor) {
1669   unsigned CursorIndex = UINT_MAX;
1670   unsigned OffsetToEOL = 0;
1671   for (int i = 0, e = Includes.size(); i != e; ++i) {
1672     unsigned Start = Includes[Indices[i]].Offset;
1673     unsigned End = Start + Includes[Indices[i]].Text.size();
1674     if (!(Cursor >= Start && Cursor < End))
1675       continue;
1676     CursorIndex = Indices[i];
1677     OffsetToEOL = End - Cursor;
1678     // Put the cursor on the only remaining #include among the duplicate
1679     // #includes.
1680     while (--i >= 0 && Includes[CursorIndex].Text == Includes[Indices[i]].Text)
1681       CursorIndex = i;
1682     break;
1683   }
1684   return std::make_pair(CursorIndex, OffsetToEOL);
1685 }
1686 
1687 // Sorts and deduplicate a block of includes given by 'Includes' alphabetically
1688 // adding the necessary replacement to 'Replaces'. 'Includes' must be in strict
1689 // source order.
1690 // #include directives with the same text will be deduplicated, and only the
1691 // first #include in the duplicate #includes remains. If the `Cursor` is
1692 // provided and put on a deleted #include, it will be moved to the remaining
1693 // #include in the duplicate #includes.
1694 static void sortCppIncludes(const FormatStyle &Style,
1695                             const SmallVectorImpl<IncludeDirective> &Includes,
1696                             ArrayRef<tooling::Range> Ranges, StringRef FileName,
1697                             tooling::Replacements &Replaces, unsigned *Cursor) {
1698   unsigned IncludesBeginOffset = Includes.front().Offset;
1699   unsigned IncludesEndOffset =
1700       Includes.back().Offset + Includes.back().Text.size();
1701   unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset;
1702   if (!affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset))
1703     return;
1704   SmallVector<unsigned, 16> Indices;
1705   for (unsigned i = 0, e = Includes.size(); i != e; ++i)
1706     Indices.push_back(i);
1707   std::stable_sort(
1708       Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) {
1709         return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) <
1710                std::tie(Includes[RHSI].Category, Includes[RHSI].Filename);
1711       });
1712   // The index of the include on which the cursor will be put after
1713   // sorting/deduplicating.
1714   unsigned CursorIndex;
1715   // The offset from cursor to the end of line.
1716   unsigned CursorToEOLOffset;
1717   if (Cursor)
1718     std::tie(CursorIndex, CursorToEOLOffset) =
1719         FindCursorIndex(Includes, Indices, *Cursor);
1720 
1721   // Deduplicate #includes.
1722   Indices.erase(std::unique(Indices.begin(), Indices.end(),
1723                             [&](unsigned LHSI, unsigned RHSI) {
1724                               return Includes[LHSI].Text == Includes[RHSI].Text;
1725                             }),
1726                 Indices.end());
1727 
1728   int CurrentCategory = Includes.front().Category;
1729 
1730   // If the #includes are out of order, we generate a single replacement fixing
1731   // the entire block. Otherwise, no replacement is generated.
1732   if (Indices.size() == Includes.size() &&
1733       std::is_sorted(Indices.begin(), Indices.end()) &&
1734       Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Preserve)
1735     return;
1736 
1737   std::string result;
1738   for (unsigned Index : Indices) {
1739     if (!result.empty()) {
1740       result += "\n";
1741       if (Style.IncludeStyle.IncludeBlocks ==
1742               tooling::IncludeStyle::IBS_Regroup &&
1743           CurrentCategory != Includes[Index].Category)
1744         result += "\n";
1745     }
1746     result += Includes[Index].Text;
1747     if (Cursor && CursorIndex == Index)
1748       *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
1749     CurrentCategory = Includes[Index].Category;
1750   }
1751 
1752   auto Err = Replaces.add(tooling::Replacement(
1753       FileName, Includes.front().Offset, IncludesBlockSize, result));
1754   // FIXME: better error handling. For now, just skip the replacement for the
1755   // release version.
1756   if (Err) {
1757     llvm::errs() << llvm::toString(std::move(Err)) << "\n";
1758     assert(false);
1759   }
1760 }
1761 
1762 namespace {
1763 
1764 const char CppIncludeRegexPattern[] =
1765     R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))";
1766 
1767 } // anonymous namespace
1768 
1769 tooling::Replacements sortCppIncludes(const FormatStyle &Style, StringRef Code,
1770                                       ArrayRef<tooling::Range> Ranges,
1771                                       StringRef FileName,
1772                                       tooling::Replacements &Replaces,
1773                                       unsigned *Cursor) {
1774   unsigned Prev = 0;
1775   unsigned SearchFrom = 0;
1776   llvm::Regex IncludeRegex(CppIncludeRegexPattern);
1777   SmallVector<StringRef, 4> Matches;
1778   SmallVector<IncludeDirective, 16> IncludesInBlock;
1779 
1780   // In compiled files, consider the first #include to be the main #include of
1781   // the file if it is not a system #include. This ensures that the header
1782   // doesn't have hidden dependencies
1783   // (http://llvm.org/docs/CodingStandards.html#include-style).
1784   //
1785   // FIXME: Do some sanity checking, e.g. edit distance of the base name, to fix
1786   // cases where the first #include is unlikely to be the main header.
1787   tooling::IncludeCategoryManager Categories(Style.IncludeStyle, FileName);
1788   bool FirstIncludeBlock = true;
1789   bool MainIncludeFound = false;
1790   bool FormattingOff = false;
1791 
1792   for (;;) {
1793     auto Pos = Code.find('\n', SearchFrom);
1794     StringRef Line =
1795         Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
1796 
1797     StringRef Trimmed = Line.trim();
1798     if (Trimmed == "// clang-format off")
1799       FormattingOff = true;
1800     else if (Trimmed == "// clang-format on")
1801       FormattingOff = false;
1802 
1803     const bool EmptyLineSkipped =
1804         Trimmed.empty() &&
1805         (Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Merge ||
1806          Style.IncludeStyle.IncludeBlocks ==
1807              tooling::IncludeStyle::IBS_Regroup);
1808 
1809     if (!FormattingOff && !Line.endswith("\\")) {
1810       if (IncludeRegex.match(Line, &Matches)) {
1811         StringRef IncludeName = Matches[2];
1812         int Category = Categories.getIncludePriority(
1813             IncludeName,
1814             /*CheckMainHeader=*/!MainIncludeFound && FirstIncludeBlock);
1815         if (Category == 0)
1816           MainIncludeFound = true;
1817         IncludesInBlock.push_back({IncludeName, Line, Prev, Category});
1818       } else if (!IncludesInBlock.empty() && !EmptyLineSkipped) {
1819         sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces,
1820                         Cursor);
1821         IncludesInBlock.clear();
1822         FirstIncludeBlock = false;
1823       }
1824       Prev = Pos + 1;
1825     }
1826     if (Pos == StringRef::npos || Pos + 1 == Code.size())
1827       break;
1828     SearchFrom = Pos + 1;
1829   }
1830   if (!IncludesInBlock.empty())
1831     sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces, Cursor);
1832   return Replaces;
1833 }
1834 
1835 // Returns group number to use as a first order sort on imports. Gives UINT_MAX
1836 // if the import does not match any given groups.
1837 static unsigned findJavaImportGroup(const FormatStyle &Style,
1838                                     StringRef ImportIdentifier) {
1839   unsigned LongestMatchIndex = UINT_MAX;
1840   unsigned LongestMatchLength = 0;
1841   for (unsigned I = 0; I < Style.JavaImportGroups.size(); I++) {
1842     std::string GroupPrefix = Style.JavaImportGroups[I];
1843     if (ImportIdentifier.startswith(GroupPrefix) &&
1844         GroupPrefix.length() > LongestMatchLength) {
1845       LongestMatchIndex = I;
1846       LongestMatchLength = GroupPrefix.length();
1847     }
1848   }
1849   return LongestMatchIndex;
1850 }
1851 
1852 // Sorts and deduplicates a block of includes given by 'Imports' based on
1853 // JavaImportGroups, then adding the necessary replacement to 'Replaces'.
1854 // Import declarations with the same text will be deduplicated. Between each
1855 // import group, a newline is inserted, and within each import group, a
1856 // lexicographic sort based on ASCII value is performed.
1857 static void sortJavaImports(const FormatStyle &Style,
1858                             const SmallVectorImpl<JavaImportDirective> &Imports,
1859                             ArrayRef<tooling::Range> Ranges, StringRef FileName,
1860                             StringRef Code,
1861                             tooling::Replacements &Replaces) {
1862   unsigned ImportsBeginOffset = Imports.front().Offset;
1863   unsigned ImportsEndOffset =
1864       Imports.back().Offset + Imports.back().Text.size();
1865   unsigned ImportsBlockSize = ImportsEndOffset - ImportsBeginOffset;
1866   if (!affectsRange(Ranges, ImportsBeginOffset, ImportsEndOffset))
1867     return;
1868   SmallVector<unsigned, 16> Indices;
1869   SmallVector<unsigned, 16> JavaImportGroups;
1870   for (unsigned i = 0, e = Imports.size(); i != e; ++i) {
1871     Indices.push_back(i);
1872     JavaImportGroups.push_back(
1873         findJavaImportGroup(Style, Imports[i].Identifier));
1874   }
1875   llvm::sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
1876     // Negating IsStatic to push static imports above non-static imports.
1877     return std::make_tuple(!Imports[LHSI].IsStatic, JavaImportGroups[LHSI],
1878                            Imports[LHSI].Identifier) <
1879            std::make_tuple(!Imports[RHSI].IsStatic, JavaImportGroups[RHSI],
1880                            Imports[RHSI].Identifier);
1881   });
1882 
1883   // Deduplicate imports.
1884   Indices.erase(std::unique(Indices.begin(), Indices.end(),
1885                             [&](unsigned LHSI, unsigned RHSI) {
1886                               return Imports[LHSI].Text == Imports[RHSI].Text;
1887                             }),
1888                 Indices.end());
1889 
1890   bool CurrentIsStatic = Imports[Indices.front()].IsStatic;
1891   unsigned CurrentImportGroup = JavaImportGroups[Indices.front()];
1892 
1893   std::string result;
1894   for (unsigned Index : Indices) {
1895     if (!result.empty()) {
1896       result += "\n";
1897       if (CurrentIsStatic != Imports[Index].IsStatic ||
1898           CurrentImportGroup != JavaImportGroups[Index])
1899         result += "\n";
1900     }
1901     for (StringRef CommentLine : Imports[Index].AssociatedCommentLines) {
1902       result += CommentLine;
1903       result += "\n";
1904     }
1905     result += Imports[Index].Text;
1906     CurrentIsStatic = Imports[Index].IsStatic;
1907     CurrentImportGroup = JavaImportGroups[Index];
1908   }
1909 
1910   // If the imports are out of order, we generate a single replacement fixing
1911   // the entire block. Otherwise, no replacement is generated.
1912   if (result == Code.substr(Imports.front().Offset, ImportsBlockSize))
1913     return;
1914 
1915   auto Err = Replaces.add(tooling::Replacement(FileName, Imports.front().Offset,
1916                                                ImportsBlockSize, result));
1917   // FIXME: better error handling. For now, just skip the replacement for the
1918   // release version.
1919   if (Err) {
1920     llvm::errs() << llvm::toString(std::move(Err)) << "\n";
1921     assert(false);
1922   }
1923 }
1924 
1925 namespace {
1926 
1927 const char JavaImportRegexPattern[] =
1928     "^[\t ]*import[\t ]*(static[\t ]*)?([^\t ]*)[\t ]*;";
1929 
1930 } // anonymous namespace
1931 
1932 tooling::Replacements sortJavaImports(const FormatStyle &Style, StringRef Code,
1933                                       ArrayRef<tooling::Range> Ranges,
1934                                       StringRef FileName,
1935                                       tooling::Replacements &Replaces) {
1936   unsigned Prev = 0;
1937   unsigned SearchFrom = 0;
1938   llvm::Regex ImportRegex(JavaImportRegexPattern);
1939   SmallVector<StringRef, 4> Matches;
1940   SmallVector<JavaImportDirective, 16> ImportsInBlock;
1941   std::vector<StringRef> AssociatedCommentLines;
1942 
1943   bool FormattingOff = false;
1944 
1945   for (;;) {
1946     auto Pos = Code.find('\n', SearchFrom);
1947     StringRef Line =
1948         Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
1949 
1950     StringRef Trimmed = Line.trim();
1951     if (Trimmed == "// clang-format off")
1952       FormattingOff = true;
1953     else if (Trimmed == "// clang-format on")
1954       FormattingOff = false;
1955 
1956     if (ImportRegex.match(Line, &Matches)) {
1957       if (FormattingOff) {
1958         // If at least one import line has formatting turned off, turn off
1959         // formatting entirely.
1960         return Replaces;
1961       }
1962       StringRef Static = Matches[1];
1963       StringRef Identifier = Matches[2];
1964       bool IsStatic = false;
1965       if (Static.contains("static")) {
1966         IsStatic = true;
1967       }
1968       ImportsInBlock.push_back({Identifier, Line, Prev, AssociatedCommentLines, IsStatic});
1969       AssociatedCommentLines.clear();
1970     } else if (Trimmed.size() > 0 && !ImportsInBlock.empty()) {
1971       // Associating comments within the imports with the nearest import below
1972       AssociatedCommentLines.push_back(Line);
1973     }
1974     Prev = Pos + 1;
1975     if (Pos == StringRef::npos || Pos + 1 == Code.size())
1976       break;
1977     SearchFrom = Pos + 1;
1978   }
1979   if (!ImportsInBlock.empty())
1980     sortJavaImports(Style, ImportsInBlock, Ranges, FileName, Code, Replaces);
1981   return Replaces;
1982 }
1983 
1984 bool isMpegTS(StringRef Code) {
1985   // MPEG transport streams use the ".ts" file extension. clang-format should
1986   // not attempt to format those. MPEG TS' frame format starts with 0x47 every
1987   // 189 bytes - detect that and return.
1988   return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
1989 }
1990 
1991 bool isLikelyXml(StringRef Code) { return Code.ltrim().startswith("<"); }
1992 
1993 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
1994                                    ArrayRef<tooling::Range> Ranges,
1995                                    StringRef FileName, unsigned *Cursor) {
1996   tooling::Replacements Replaces;
1997   if (!Style.SortIncludes)
1998     return Replaces;
1999   if (isLikelyXml(Code))
2000     return Replaces;
2001   if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
2002       isMpegTS(Code))
2003     return Replaces;
2004   if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript)
2005     return sortJavaScriptImports(Style, Code, Ranges, FileName);
2006   if (Style.Language == FormatStyle::LanguageKind::LK_Java)
2007     return sortJavaImports(Style, Code, Ranges, FileName, Replaces);
2008   sortCppIncludes(Style, Code, Ranges, FileName, Replaces, Cursor);
2009   return Replaces;
2010 }
2011 
2012 template <typename T>
2013 static llvm::Expected<tooling::Replacements>
2014 processReplacements(T ProcessFunc, StringRef Code,
2015                     const tooling::Replacements &Replaces,
2016                     const FormatStyle &Style) {
2017   if (Replaces.empty())
2018     return tooling::Replacements();
2019 
2020   auto NewCode = applyAllReplacements(Code, Replaces);
2021   if (!NewCode)
2022     return NewCode.takeError();
2023   std::vector<tooling::Range> ChangedRanges = Replaces.getAffectedRanges();
2024   StringRef FileName = Replaces.begin()->getFilePath();
2025 
2026   tooling::Replacements FormatReplaces =
2027       ProcessFunc(Style, *NewCode, ChangedRanges, FileName);
2028 
2029   return Replaces.merge(FormatReplaces);
2030 }
2031 
2032 llvm::Expected<tooling::Replacements>
2033 formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
2034                    const FormatStyle &Style) {
2035   // We need to use lambda function here since there are two versions of
2036   // `sortIncludes`.
2037   auto SortIncludes = [](const FormatStyle &Style, StringRef Code,
2038                          std::vector<tooling::Range> Ranges,
2039                          StringRef FileName) -> tooling::Replacements {
2040     return sortIncludes(Style, Code, Ranges, FileName);
2041   };
2042   auto SortedReplaces =
2043       processReplacements(SortIncludes, Code, Replaces, Style);
2044   if (!SortedReplaces)
2045     return SortedReplaces.takeError();
2046 
2047   // We need to use lambda function here since there are two versions of
2048   // `reformat`.
2049   auto Reformat = [](const FormatStyle &Style, StringRef Code,
2050                      std::vector<tooling::Range> Ranges,
2051                      StringRef FileName) -> tooling::Replacements {
2052     return reformat(Style, Code, Ranges, FileName);
2053   };
2054   return processReplacements(Reformat, Code, *SortedReplaces, Style);
2055 }
2056 
2057 namespace {
2058 
2059 inline bool isHeaderInsertion(const tooling::Replacement &Replace) {
2060   return Replace.getOffset() == UINT_MAX && Replace.getLength() == 0 &&
2061          llvm::Regex(CppIncludeRegexPattern)
2062              .match(Replace.getReplacementText());
2063 }
2064 
2065 inline bool isHeaderDeletion(const tooling::Replacement &Replace) {
2066   return Replace.getOffset() == UINT_MAX && Replace.getLength() == 1;
2067 }
2068 
2069 // FIXME: insert empty lines between newly created blocks.
2070 tooling::Replacements
2071 fixCppIncludeInsertions(StringRef Code, const tooling::Replacements &Replaces,
2072                         const FormatStyle &Style) {
2073   if (!Style.isCpp())
2074     return Replaces;
2075 
2076   tooling::Replacements HeaderInsertions;
2077   std::set<llvm::StringRef> HeadersToDelete;
2078   tooling::Replacements Result;
2079   for (const auto &R : Replaces) {
2080     if (isHeaderInsertion(R)) {
2081       // Replacements from \p Replaces must be conflict-free already, so we can
2082       // simply consume the error.
2083       llvm::consumeError(HeaderInsertions.add(R));
2084     } else if (isHeaderDeletion(R)) {
2085       HeadersToDelete.insert(R.getReplacementText());
2086     } else if (R.getOffset() == UINT_MAX) {
2087       llvm::errs() << "Insertions other than header #include insertion are "
2088                       "not supported! "
2089                    << R.getReplacementText() << "\n";
2090     } else {
2091       llvm::consumeError(Result.add(R));
2092     }
2093   }
2094   if (HeaderInsertions.empty() && HeadersToDelete.empty())
2095     return Replaces;
2096 
2097 
2098   StringRef FileName = Replaces.begin()->getFilePath();
2099   tooling::HeaderIncludes Includes(FileName, Code, Style.IncludeStyle);
2100 
2101   for (const auto &Header : HeadersToDelete) {
2102     tooling::Replacements Replaces =
2103         Includes.remove(Header.trim("\"<>"), Header.startswith("<"));
2104     for (const auto &R : Replaces) {
2105       auto Err = Result.add(R);
2106       if (Err) {
2107         // Ignore the deletion on conflict.
2108         llvm::errs() << "Failed to add header deletion replacement for "
2109                      << Header << ": " << llvm::toString(std::move(Err))
2110                      << "\n";
2111       }
2112     }
2113   }
2114 
2115   llvm::Regex IncludeRegex = llvm::Regex(CppIncludeRegexPattern);
2116   llvm::SmallVector<StringRef, 4> Matches;
2117   for (const auto &R : HeaderInsertions) {
2118     auto IncludeDirective = R.getReplacementText();
2119     bool Matched = IncludeRegex.match(IncludeDirective, &Matches);
2120     assert(Matched && "Header insertion replacement must have replacement text "
2121                       "'#include ...'");
2122     (void)Matched;
2123     auto IncludeName = Matches[2];
2124     auto Replace =
2125         Includes.insert(IncludeName.trim("\"<>"), IncludeName.startswith("<"));
2126     if (Replace) {
2127       auto Err = Result.add(*Replace);
2128       if (Err) {
2129         llvm::consumeError(std::move(Err));
2130         unsigned NewOffset = Result.getShiftedCodePosition(Replace->getOffset());
2131         auto Shifted = tooling::Replacement(FileName, NewOffset, 0,
2132                                             Replace->getReplacementText());
2133         Result = Result.merge(tooling::Replacements(Shifted));
2134       }
2135     }
2136   }
2137   return Result;
2138 }
2139 
2140 } // anonymous namespace
2141 
2142 llvm::Expected<tooling::Replacements>
2143 cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
2144                           const FormatStyle &Style) {
2145   // We need to use lambda function here since there are two versions of
2146   // `cleanup`.
2147   auto Cleanup = [](const FormatStyle &Style, StringRef Code,
2148                     std::vector<tooling::Range> Ranges,
2149                     StringRef FileName) -> tooling::Replacements {
2150     return cleanup(Style, Code, Ranges, FileName);
2151   };
2152   // Make header insertion replacements insert new headers into correct blocks.
2153   tooling::Replacements NewReplaces =
2154       fixCppIncludeInsertions(Code, Replaces, Style);
2155   return processReplacements(Cleanup, Code, NewReplaces, Style);
2156 }
2157 
2158 namespace internal {
2159 std::pair<tooling::Replacements, unsigned>
2160 reformat(const FormatStyle &Style, StringRef Code,
2161          ArrayRef<tooling::Range> Ranges, unsigned FirstStartColumn,
2162          unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName,
2163          FormattingAttemptStatus *Status) {
2164   FormatStyle Expanded = expandPresets(Style);
2165   if (Expanded.DisableFormat)
2166     return {tooling::Replacements(), 0};
2167   if (isLikelyXml(Code))
2168     return {tooling::Replacements(), 0};
2169   if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code))
2170     return {tooling::Replacements(), 0};
2171 
2172   typedef std::function<std::pair<tooling::Replacements, unsigned>(
2173       const Environment &)>
2174       AnalyzerPass;
2175   SmallVector<AnalyzerPass, 4> Passes;
2176 
2177   if (Style.Language == FormatStyle::LK_Cpp) {
2178     if (Style.FixNamespaceComments)
2179       Passes.emplace_back([&](const Environment &Env) {
2180         return NamespaceEndCommentsFixer(Env, Expanded).process();
2181       });
2182 
2183     if (Style.SortUsingDeclarations)
2184       Passes.emplace_back([&](const Environment &Env) {
2185         return UsingDeclarationsSorter(Env, Expanded).process();
2186       });
2187   }
2188 
2189   if (Style.Language == FormatStyle::LK_JavaScript &&
2190       Style.JavaScriptQuotes != FormatStyle::JSQS_Leave)
2191     Passes.emplace_back([&](const Environment &Env) {
2192       return JavaScriptRequoter(Env, Expanded).process();
2193     });
2194 
2195   Passes.emplace_back([&](const Environment &Env) {
2196     return Formatter(Env, Expanded, Status).process();
2197   });
2198 
2199   auto Env =
2200       llvm::make_unique<Environment>(Code, FileName, Ranges, FirstStartColumn,
2201                                      NextStartColumn, LastStartColumn);
2202   llvm::Optional<std::string> CurrentCode = None;
2203   tooling::Replacements Fixes;
2204   unsigned Penalty = 0;
2205   for (size_t I = 0, E = Passes.size(); I < E; ++I) {
2206     std::pair<tooling::Replacements, unsigned> PassFixes = Passes[I](*Env);
2207     auto NewCode = applyAllReplacements(
2208         CurrentCode ? StringRef(*CurrentCode) : Code, PassFixes.first);
2209     if (NewCode) {
2210       Fixes = Fixes.merge(PassFixes.first);
2211       Penalty += PassFixes.second;
2212       if (I + 1 < E) {
2213         CurrentCode = std::move(*NewCode);
2214         Env = llvm::make_unique<Environment>(
2215             *CurrentCode, FileName,
2216             tooling::calculateRangesAfterReplacements(Fixes, Ranges),
2217             FirstStartColumn, NextStartColumn, LastStartColumn);
2218       }
2219     }
2220   }
2221 
2222   return {Fixes, Penalty};
2223 }
2224 } // namespace internal
2225 
2226 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
2227                                ArrayRef<tooling::Range> Ranges,
2228                                StringRef FileName,
2229                                FormattingAttemptStatus *Status) {
2230   return internal::reformat(Style, Code, Ranges,
2231                             /*FirstStartColumn=*/0,
2232                             /*NextStartColumn=*/0,
2233                             /*LastStartColumn=*/0, FileName, Status)
2234       .first;
2235 }
2236 
2237 tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
2238                               ArrayRef<tooling::Range> Ranges,
2239                               StringRef FileName) {
2240   // cleanups only apply to C++ (they mostly concern ctor commas etc.)
2241   if (Style.Language != FormatStyle::LK_Cpp)
2242     return tooling::Replacements();
2243   return Cleaner(Environment(Code, FileName, Ranges), Style).process().first;
2244 }
2245 
2246 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
2247                                ArrayRef<tooling::Range> Ranges,
2248                                StringRef FileName, bool *IncompleteFormat) {
2249   FormattingAttemptStatus Status;
2250   auto Result = reformat(Style, Code, Ranges, FileName, &Status);
2251   if (!Status.FormatComplete)
2252     *IncompleteFormat = true;
2253   return Result;
2254 }
2255 
2256 tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
2257                                               StringRef Code,
2258                                               ArrayRef<tooling::Range> Ranges,
2259                                               StringRef FileName) {
2260   return NamespaceEndCommentsFixer(Environment(Code, FileName, Ranges), Style)
2261       .process()
2262       .first;
2263 }
2264 
2265 tooling::Replacements sortUsingDeclarations(const FormatStyle &Style,
2266                                             StringRef Code,
2267                                             ArrayRef<tooling::Range> Ranges,
2268                                             StringRef FileName) {
2269   return UsingDeclarationsSorter(Environment(Code, FileName, Ranges), Style)
2270       .process()
2271       .first;
2272 }
2273 
2274 LangOptions getFormattingLangOpts(const FormatStyle &Style) {
2275   LangOptions LangOpts;
2276   LangOpts.CPlusPlus = 1;
2277   LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2278   LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2279   LangOpts.CPlusPlus17 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2280   LangOpts.CPlusPlus2a = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2281   LangOpts.LineComment = 1;
2282   bool AlternativeOperators = Style.isCpp();
2283   LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
2284   LangOpts.Bool = 1;
2285   LangOpts.ObjC = 1;
2286   LangOpts.MicrosoftExt = 1;    // To get kw___try, kw___finally.
2287   LangOpts.DeclSpecKeyword = 1; // To get __declspec.
2288   return LangOpts;
2289 }
2290 
2291 const char *StyleOptionHelpDescription =
2292     "Coding style, currently supports:\n"
2293     "  LLVM, Google, Chromium, Mozilla, WebKit.\n"
2294     "Use -style=file to load style configuration from\n"
2295     ".clang-format file located in one of the parent\n"
2296     "directories of the source file (or current\n"
2297     "directory for stdin).\n"
2298     "Use -style=\"{key: value, ...}\" to set specific\n"
2299     "parameters, e.g.:\n"
2300     "  -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
2301 
2302 static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
2303   if (FileName.endswith(".java"))
2304     return FormatStyle::LK_Java;
2305   if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts"))
2306     return FormatStyle::LK_JavaScript; // JavaScript or TypeScript.
2307   if (FileName.endswith(".m") || FileName.endswith(".mm"))
2308     return FormatStyle::LK_ObjC;
2309   if (FileName.endswith_lower(".proto") ||
2310       FileName.endswith_lower(".protodevel"))
2311     return FormatStyle::LK_Proto;
2312   if (FileName.endswith_lower(".textpb") ||
2313       FileName.endswith_lower(".pb.txt") ||
2314       FileName.endswith_lower(".textproto") ||
2315       FileName.endswith_lower(".asciipb"))
2316     return FormatStyle::LK_TextProto;
2317   if (FileName.endswith_lower(".td"))
2318     return FormatStyle::LK_TableGen;
2319   return FormatStyle::LK_Cpp;
2320 }
2321 
2322 FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code) {
2323   const auto GuessedLanguage = getLanguageByFileName(FileName);
2324   if (GuessedLanguage == FormatStyle::LK_Cpp) {
2325     auto Extension = llvm::sys::path::extension(FileName);
2326     // If there's no file extension (or it's .h), we need to check the contents
2327     // of the code to see if it contains Objective-C.
2328     if (Extension.empty() || Extension == ".h") {
2329       auto NonEmptyFileName = FileName.empty() ? "guess.h" : FileName;
2330       Environment Env(Code, NonEmptyFileName, /*Ranges=*/{});
2331       ObjCHeaderStyleGuesser Guesser(Env, getLLVMStyle());
2332       Guesser.process();
2333       if (Guesser.isObjC())
2334         return FormatStyle::LK_ObjC;
2335     }
2336   }
2337   return GuessedLanguage;
2338 }
2339 
2340 const char *DefaultFormatStyle = "file";
2341 
2342 const char *DefaultFallbackStyle = "LLVM";
2343 
2344 llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
2345                                      StringRef FallbackStyleName,
2346                                      StringRef Code,
2347                                      llvm::vfs::FileSystem *FS) {
2348   if (!FS) {
2349     FS = llvm::vfs::getRealFileSystem().get();
2350   }
2351   FormatStyle Style = getLLVMStyle(guessLanguage(FileName, Code));
2352 
2353   FormatStyle FallbackStyle = getNoStyle();
2354   if (!getPredefinedStyle(FallbackStyleName, Style.Language, &FallbackStyle))
2355     return make_string_error("Invalid fallback style \"" + FallbackStyleName);
2356 
2357   if (StyleName.startswith("{")) {
2358     // Parse YAML/JSON style from the command line.
2359     if (std::error_code ec = parseConfiguration(StyleName, &Style))
2360       return make_string_error("Error parsing -style: " + ec.message());
2361     return Style;
2362   }
2363 
2364   if (!StyleName.equals_lower("file")) {
2365     if (!getPredefinedStyle(StyleName, Style.Language, &Style))
2366       return make_string_error("Invalid value for -style");
2367     return Style;
2368   }
2369 
2370   // Look for .clang-format/_clang-format file in the file's parent directories.
2371   SmallString<128> UnsuitableConfigFiles;
2372   SmallString<128> Path(FileName);
2373   if (std::error_code EC = FS->makeAbsolute(Path))
2374     return make_string_error(EC.message());
2375 
2376   for (StringRef Directory = Path; !Directory.empty();
2377        Directory = llvm::sys::path::parent_path(Directory)) {
2378 
2379     auto Status = FS->status(Directory);
2380     if (!Status ||
2381         Status->getType() != llvm::sys::fs::file_type::directory_file) {
2382       continue;
2383     }
2384 
2385     SmallString<128> ConfigFile(Directory);
2386 
2387     llvm::sys::path::append(ConfigFile, ".clang-format");
2388     LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2389 
2390     Status = FS->status(ConfigFile.str());
2391     bool FoundConfigFile =
2392         Status && (Status->getType() == llvm::sys::fs::file_type::regular_file);
2393     if (!FoundConfigFile) {
2394       // Try _clang-format too, since dotfiles are not commonly used on Windows.
2395       ConfigFile = Directory;
2396       llvm::sys::path::append(ConfigFile, "_clang-format");
2397       LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2398       Status = FS->status(ConfigFile.str());
2399       FoundConfigFile = Status && (Status->getType() ==
2400                                    llvm::sys::fs::file_type::regular_file);
2401     }
2402 
2403     if (FoundConfigFile) {
2404       llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
2405           FS->getBufferForFile(ConfigFile.str());
2406       if (std::error_code EC = Text.getError())
2407         return make_string_error(EC.message());
2408       if (std::error_code ec =
2409               parseConfiguration(Text.get()->getBuffer(), &Style)) {
2410         if (ec == ParseError::Unsuitable) {
2411           if (!UnsuitableConfigFiles.empty())
2412             UnsuitableConfigFiles.append(", ");
2413           UnsuitableConfigFiles.append(ConfigFile);
2414           continue;
2415         }
2416         return make_string_error("Error reading " + ConfigFile + ": " +
2417                                  ec.message());
2418       }
2419       LLVM_DEBUG(llvm::dbgs()
2420                  << "Using configuration file " << ConfigFile << "\n");
2421       return Style;
2422     }
2423   }
2424   if (!UnsuitableConfigFiles.empty())
2425     return make_string_error("Configuration file(s) do(es) not support " +
2426                              getLanguageName(Style.Language) + ": " +
2427                              UnsuitableConfigFiles);
2428   return FallbackStyle;
2429 }
2430 
2431 } // namespace format
2432 } // namespace clang
2433