1 //===--- Format.cpp - Format C++ code -------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief This file implements functions declared in Format.h. This will be
12 /// split into separate files as we go.
13 ///
14 //===----------------------------------------------------------------------===//
15 
16 #include "clang/Format/Format.h"
17 #include "ContinuationIndenter.h"
18 #include "TokenAnnotator.h"
19 #include "UnwrappedLineFormatter.h"
20 #include "UnwrappedLineParser.h"
21 #include "WhitespaceManager.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Lex/Lexer.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/Support/Allocator.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/Regex.h"
31 #include "llvm/Support/YAMLTraits.h"
32 #include <queue>
33 #include <string>
34 
35 #define DEBUG_TYPE "format-formatter"
36 
37 using clang::format::FormatStyle;
38 
39 LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
40 LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::IncludeCategory)
41 
42 namespace llvm {
43 namespace yaml {
44 template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
45   static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
46     IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
47     IO.enumCase(Value, "Java", FormatStyle::LK_Java);
48     IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
49     IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
50     IO.enumCase(Value, "TableGen", FormatStyle::LK_TableGen);
51   }
52 };
53 
54 template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
55   static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
56     IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
57     IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
58     IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
59     IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
60     IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
61   }
62 };
63 
64 template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
65   static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
66     IO.enumCase(Value, "Never", FormatStyle::UT_Never);
67     IO.enumCase(Value, "false", FormatStyle::UT_Never);
68     IO.enumCase(Value, "Always", FormatStyle::UT_Always);
69     IO.enumCase(Value, "true", FormatStyle::UT_Always);
70     IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
71   }
72 };
73 
74 template <> struct ScalarEnumerationTraits<FormatStyle::JavaScriptQuoteStyle> {
75   static void enumeration(IO &IO, FormatStyle::JavaScriptQuoteStyle &Value) {
76     IO.enumCase(Value, "Leave", FormatStyle::JSQS_Leave);
77     IO.enumCase(Value, "Single", FormatStyle::JSQS_Single);
78     IO.enumCase(Value, "Double", FormatStyle::JSQS_Double);
79   }
80 };
81 
82 template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
83   static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
84     IO.enumCase(Value, "None", FormatStyle::SFS_None);
85     IO.enumCase(Value, "false", FormatStyle::SFS_None);
86     IO.enumCase(Value, "All", FormatStyle::SFS_All);
87     IO.enumCase(Value, "true", FormatStyle::SFS_All);
88     IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
89     IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
90   }
91 };
92 
93 template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
94   static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
95     IO.enumCase(Value, "All", FormatStyle::BOS_All);
96     IO.enumCase(Value, "true", FormatStyle::BOS_All);
97     IO.enumCase(Value, "None", FormatStyle::BOS_None);
98     IO.enumCase(Value, "false", FormatStyle::BOS_None);
99     IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
100   }
101 };
102 
103 template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
104   static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
105     IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
106     IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
107     IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
108     IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
109     IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
110     IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
111     IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
112     IO.enumCase(Value, "Custom", FormatStyle::BS_Custom);
113   }
114 };
115 
116 template <>
117 struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
118   static void enumeration(IO &IO, FormatStyle::ReturnTypeBreakingStyle &Value) {
119     IO.enumCase(Value, "None", FormatStyle::RTBS_None);
120     IO.enumCase(Value, "All", FormatStyle::RTBS_All);
121     IO.enumCase(Value, "TopLevel", FormatStyle::RTBS_TopLevel);
122     IO.enumCase(Value, "TopLevelDefinitions",
123                 FormatStyle::RTBS_TopLevelDefinitions);
124     IO.enumCase(Value, "AllDefinitions", FormatStyle::RTBS_AllDefinitions);
125   }
126 };
127 
128 template <>
129 struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
130   static void
131   enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) {
132     IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
133     IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
134     IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
135 
136     // For backward compatibility.
137     IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
138     IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
139   }
140 };
141 
142 template <>
143 struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
144   static void enumeration(IO &IO,
145                           FormatStyle::NamespaceIndentationKind &Value) {
146     IO.enumCase(Value, "None", FormatStyle::NI_None);
147     IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
148     IO.enumCase(Value, "All", FormatStyle::NI_All);
149   }
150 };
151 
152 template <> struct ScalarEnumerationTraits<FormatStyle::BracketAlignmentStyle> {
153   static void enumeration(IO &IO, FormatStyle::BracketAlignmentStyle &Value) {
154     IO.enumCase(Value, "Align", FormatStyle::BAS_Align);
155     IO.enumCase(Value, "DontAlign", FormatStyle::BAS_DontAlign);
156     IO.enumCase(Value, "AlwaysBreak", FormatStyle::BAS_AlwaysBreak);
157 
158     // For backward compatibility.
159     IO.enumCase(Value, "true", FormatStyle::BAS_Align);
160     IO.enumCase(Value, "false", FormatStyle::BAS_DontAlign);
161   }
162 };
163 
164 template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
165   static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
166     IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
167     IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
168     IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
169 
170     // For backward compatibility.
171     IO.enumCase(Value, "true", FormatStyle::PAS_Left);
172     IO.enumCase(Value, "false", FormatStyle::PAS_Right);
173   }
174 };
175 
176 template <>
177 struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
178   static void enumeration(IO &IO,
179                           FormatStyle::SpaceBeforeParensOptions &Value) {
180     IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
181     IO.enumCase(Value, "ControlStatements",
182                 FormatStyle::SBPO_ControlStatements);
183     IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
184 
185     // For backward compatibility.
186     IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
187     IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
188   }
189 };
190 
191 template <> struct MappingTraits<FormatStyle> {
192   static void mapping(IO &IO, FormatStyle &Style) {
193     // When reading, read the language first, we need it for getPredefinedStyle.
194     IO.mapOptional("Language", Style.Language);
195 
196     if (IO.outputting()) {
197       StringRef StylesArray[] = {"LLVM",    "Google", "Chromium",
198                                  "Mozilla", "WebKit", "GNU"};
199       ArrayRef<StringRef> Styles(StylesArray);
200       for (size_t i = 0, e = Styles.size(); i < e; ++i) {
201         StringRef StyleName(Styles[i]);
202         FormatStyle PredefinedStyle;
203         if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
204             Style == PredefinedStyle) {
205           IO.mapOptional("# BasedOnStyle", StyleName);
206           break;
207         }
208       }
209     } else {
210       StringRef BasedOnStyle;
211       IO.mapOptional("BasedOnStyle", BasedOnStyle);
212       if (!BasedOnStyle.empty()) {
213         FormatStyle::LanguageKind OldLanguage = Style.Language;
214         FormatStyle::LanguageKind Language =
215             ((FormatStyle *)IO.getContext())->Language;
216         if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
217           IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
218           return;
219         }
220         Style.Language = OldLanguage;
221       }
222     }
223 
224     // For backward compatibility.
225     if (!IO.outputting()) {
226       IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
227       IO.mapOptional("IndentFunctionDeclarationAfterType",
228                      Style.IndentWrappedFunctionNames);
229       IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
230       IO.mapOptional("SpaceAfterControlStatementKeyword",
231                      Style.SpaceBeforeParens);
232     }
233 
234     IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
235     IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
236     IO.mapOptional("AlignConsecutiveAssignments",
237                    Style.AlignConsecutiveAssignments);
238     IO.mapOptional("AlignConsecutiveDeclarations",
239                    Style.AlignConsecutiveDeclarations);
240     IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
241     IO.mapOptional("AlignOperands", Style.AlignOperands);
242     IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
243     IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
244                    Style.AllowAllParametersOfDeclarationOnNextLine);
245     IO.mapOptional("AllowShortBlocksOnASingleLine",
246                    Style.AllowShortBlocksOnASingleLine);
247     IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
248                    Style.AllowShortCaseLabelsOnASingleLine);
249     IO.mapOptional("AllowShortFunctionsOnASingleLine",
250                    Style.AllowShortFunctionsOnASingleLine);
251     IO.mapOptional("AllowShortIfStatementsOnASingleLine",
252                    Style.AllowShortIfStatementsOnASingleLine);
253     IO.mapOptional("AllowShortLoopsOnASingleLine",
254                    Style.AllowShortLoopsOnASingleLine);
255     IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
256                    Style.AlwaysBreakAfterDefinitionReturnType);
257     IO.mapOptional("AlwaysBreakAfterReturnType",
258                    Style.AlwaysBreakAfterReturnType);
259     // If AlwaysBreakAfterDefinitionReturnType was specified but
260     // AlwaysBreakAfterReturnType was not, initialize the latter from the
261     // former for backwards compatibility.
262     if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
263         Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None) {
264       if (Style.AlwaysBreakAfterDefinitionReturnType == FormatStyle::DRTBS_All)
265         Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
266       else if (Style.AlwaysBreakAfterDefinitionReturnType ==
267                FormatStyle::DRTBS_TopLevel)
268         Style.AlwaysBreakAfterReturnType =
269             FormatStyle::RTBS_TopLevelDefinitions;
270     }
271 
272     IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
273                    Style.AlwaysBreakBeforeMultilineStrings);
274     IO.mapOptional("AlwaysBreakTemplateDeclarations",
275                    Style.AlwaysBreakTemplateDeclarations);
276     IO.mapOptional("BinPackArguments", Style.BinPackArguments);
277     IO.mapOptional("BinPackParameters", Style.BinPackParameters);
278     IO.mapOptional("BraceWrapping", Style.BraceWrapping);
279     IO.mapOptional("BreakBeforeBinaryOperators",
280                    Style.BreakBeforeBinaryOperators);
281     IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
282     IO.mapOptional("BreakBeforeTernaryOperators",
283                    Style.BreakBeforeTernaryOperators);
284     IO.mapOptional("BreakConstructorInitializersBeforeComma",
285                    Style.BreakConstructorInitializersBeforeComma);
286     IO.mapOptional("BreakAfterJavaFieldAnnotations",
287                    Style.BreakAfterJavaFieldAnnotations);
288     IO.mapOptional("BreakStringLiterals", Style.BreakStringLiterals);
289     IO.mapOptional("ColumnLimit", Style.ColumnLimit);
290     IO.mapOptional("CommentPragmas", Style.CommentPragmas);
291     IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
292                    Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
293     IO.mapOptional("ConstructorInitializerIndentWidth",
294                    Style.ConstructorInitializerIndentWidth);
295     IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
296     IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
297     IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
298     IO.mapOptional("DisableFormat", Style.DisableFormat);
299     IO.mapOptional("ExperimentalAutoDetectBinPacking",
300                    Style.ExperimentalAutoDetectBinPacking);
301     IO.mapOptional("ForEachMacros", Style.ForEachMacros);
302     IO.mapOptional("IncludeCategories", Style.IncludeCategories);
303     IO.mapOptional("IncludeIsMainRegex", Style.IncludeIsMainRegex);
304     IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
305     IO.mapOptional("IndentWidth", Style.IndentWidth);
306     IO.mapOptional("IndentWrappedFunctionNames",
307                    Style.IndentWrappedFunctionNames);
308     IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
309                    Style.KeepEmptyLinesAtTheStartOfBlocks);
310     IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
311     IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
312     IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
313     IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
314     IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
315     IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
316     IO.mapOptional("ObjCSpaceBeforeProtocolList",
317                    Style.ObjCSpaceBeforeProtocolList);
318     IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
319                    Style.PenaltyBreakBeforeFirstCallParameter);
320     IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
321     IO.mapOptional("PenaltyBreakFirstLessLess",
322                    Style.PenaltyBreakFirstLessLess);
323     IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
324     IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
325     IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
326                    Style.PenaltyReturnTypeOnItsOwnLine);
327     IO.mapOptional("PointerAlignment", Style.PointerAlignment);
328     IO.mapOptional("ReflowComments", Style.ReflowComments);
329     IO.mapOptional("SortIncludes", Style.SortIncludes);
330     IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
331     IO.mapOptional("SpaceBeforeAssignmentOperators",
332                    Style.SpaceBeforeAssignmentOperators);
333     IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
334     IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
335     IO.mapOptional("SpacesBeforeTrailingComments",
336                    Style.SpacesBeforeTrailingComments);
337     IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
338     IO.mapOptional("SpacesInContainerLiterals",
339                    Style.SpacesInContainerLiterals);
340     IO.mapOptional("SpacesInCStyleCastParentheses",
341                    Style.SpacesInCStyleCastParentheses);
342     IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
343     IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
344     IO.mapOptional("Standard", Style.Standard);
345     IO.mapOptional("TabWidth", Style.TabWidth);
346     IO.mapOptional("UseTab", Style.UseTab);
347     IO.mapOptional("JavaScriptQuotes", Style.JavaScriptQuotes);
348   }
349 };
350 
351 template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
352   static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
353     IO.mapOptional("AfterClass", Wrapping.AfterClass);
354     IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
355     IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
356     IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
357     IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
358     IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
359     IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
360     IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
361     IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
362     IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
363     IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
364   }
365 };
366 
367 template <> struct MappingTraits<FormatStyle::IncludeCategory> {
368   static void mapping(IO &IO, FormatStyle::IncludeCategory &Category) {
369     IO.mapOptional("Regex", Category.Regex);
370     IO.mapOptional("Priority", Category.Priority);
371   }
372 };
373 
374 // Allows to read vector<FormatStyle> while keeping default values.
375 // IO.getContext() should contain a pointer to the FormatStyle structure, that
376 // will be used to get default values for missing keys.
377 // If the first element has no Language specified, it will be treated as the
378 // default one for the following elements.
379 template <> struct DocumentListTraits<std::vector<FormatStyle>> {
380   static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
381     return Seq.size();
382   }
383   static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
384                               size_t Index) {
385     if (Index >= Seq.size()) {
386       assert(Index == Seq.size());
387       FormatStyle Template;
388       if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
389         Template = Seq[0];
390       } else {
391         Template = *((const FormatStyle *)IO.getContext());
392         Template.Language = FormatStyle::LK_None;
393       }
394       Seq.resize(Index + 1, Template);
395     }
396     return Seq[Index];
397   }
398 };
399 } // namespace yaml
400 } // namespace llvm
401 
402 namespace clang {
403 namespace format {
404 
405 const std::error_category &getParseCategory() {
406   static ParseErrorCategory C;
407   return C;
408 }
409 std::error_code make_error_code(ParseError e) {
410   return std::error_code(static_cast<int>(e), getParseCategory());
411 }
412 
413 const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
414   return "clang-format.parse_error";
415 }
416 
417 std::string ParseErrorCategory::message(int EV) const {
418   switch (static_cast<ParseError>(EV)) {
419   case ParseError::Success:
420     return "Success";
421   case ParseError::Error:
422     return "Invalid argument";
423   case ParseError::Unsuitable:
424     return "Unsuitable";
425   }
426   llvm_unreachable("unexpected parse error");
427 }
428 
429 static FormatStyle expandPresets(const FormatStyle &Style) {
430   if (Style.BreakBeforeBraces == FormatStyle::BS_Custom)
431     return Style;
432   FormatStyle Expanded = Style;
433   Expanded.BraceWrapping = {false, false, false, false, false, false,
434                             false, false, false, false, false};
435   switch (Style.BreakBeforeBraces) {
436   case FormatStyle::BS_Linux:
437     Expanded.BraceWrapping.AfterClass = true;
438     Expanded.BraceWrapping.AfterFunction = true;
439     Expanded.BraceWrapping.AfterNamespace = true;
440     break;
441   case FormatStyle::BS_Mozilla:
442     Expanded.BraceWrapping.AfterClass = true;
443     Expanded.BraceWrapping.AfterEnum = true;
444     Expanded.BraceWrapping.AfterFunction = true;
445     Expanded.BraceWrapping.AfterStruct = true;
446     Expanded.BraceWrapping.AfterUnion = true;
447     break;
448   case FormatStyle::BS_Stroustrup:
449     Expanded.BraceWrapping.AfterFunction = true;
450     Expanded.BraceWrapping.BeforeCatch = true;
451     Expanded.BraceWrapping.BeforeElse = true;
452     break;
453   case FormatStyle::BS_Allman:
454     Expanded.BraceWrapping.AfterClass = true;
455     Expanded.BraceWrapping.AfterControlStatement = true;
456     Expanded.BraceWrapping.AfterEnum = true;
457     Expanded.BraceWrapping.AfterFunction = true;
458     Expanded.BraceWrapping.AfterNamespace = true;
459     Expanded.BraceWrapping.AfterObjCDeclaration = true;
460     Expanded.BraceWrapping.AfterStruct = true;
461     Expanded.BraceWrapping.BeforeCatch = true;
462     Expanded.BraceWrapping.BeforeElse = true;
463     break;
464   case FormatStyle::BS_GNU:
465     Expanded.BraceWrapping = {true, true, true, true, true, true,
466                               true, true, true, true, true};
467     break;
468   case FormatStyle::BS_WebKit:
469     Expanded.BraceWrapping.AfterFunction = true;
470     break;
471   default:
472     break;
473   }
474   return Expanded;
475 }
476 
477 FormatStyle getLLVMStyle() {
478   FormatStyle LLVMStyle;
479   LLVMStyle.Language = FormatStyle::LK_Cpp;
480   LLVMStyle.AccessModifierOffset = -2;
481   LLVMStyle.AlignEscapedNewlinesLeft = false;
482   LLVMStyle.AlignAfterOpenBracket = FormatStyle::BAS_Align;
483   LLVMStyle.AlignOperands = true;
484   LLVMStyle.AlignTrailingComments = true;
485   LLVMStyle.AlignConsecutiveAssignments = false;
486   LLVMStyle.AlignConsecutiveDeclarations = false;
487   LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
488   LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
489   LLVMStyle.AllowShortBlocksOnASingleLine = false;
490   LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
491   LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
492   LLVMStyle.AllowShortLoopsOnASingleLine = false;
493   LLVMStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
494   LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
495   LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
496   LLVMStyle.AlwaysBreakTemplateDeclarations = false;
497   LLVMStyle.BinPackParameters = true;
498   LLVMStyle.BinPackArguments = true;
499   LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
500   LLVMStyle.BreakBeforeTernaryOperators = true;
501   LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
502   LLVMStyle.BraceWrapping = {false, false, false, false, false, false,
503                              false, false, false, false, false};
504   LLVMStyle.BreakAfterJavaFieldAnnotations = false;
505   LLVMStyle.BreakConstructorInitializersBeforeComma = false;
506   LLVMStyle.BreakStringLiterals = true;
507   LLVMStyle.ColumnLimit = 80;
508   LLVMStyle.CommentPragmas = "^ IWYU pragma:";
509   LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
510   LLVMStyle.ConstructorInitializerIndentWidth = 4;
511   LLVMStyle.ContinuationIndentWidth = 4;
512   LLVMStyle.Cpp11BracedListStyle = true;
513   LLVMStyle.DerivePointerAlignment = false;
514   LLVMStyle.ExperimentalAutoDetectBinPacking = false;
515   LLVMStyle.ForEachMacros.push_back("foreach");
516   LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
517   LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
518   LLVMStyle.IncludeCategories = {{"^\"(llvm|llvm-c|clang|clang-c)/", 2},
519                                  {"^(<|\"(gtest|isl|json)/)", 3},
520                                  {".*", 1}};
521   LLVMStyle.IncludeIsMainRegex = "$";
522   LLVMStyle.IndentCaseLabels = false;
523   LLVMStyle.IndentWrappedFunctionNames = false;
524   LLVMStyle.IndentWidth = 2;
525   LLVMStyle.TabWidth = 8;
526   LLVMStyle.MaxEmptyLinesToKeep = 1;
527   LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
528   LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
529   LLVMStyle.ObjCBlockIndentWidth = 2;
530   LLVMStyle.ObjCSpaceAfterProperty = false;
531   LLVMStyle.ObjCSpaceBeforeProtocolList = true;
532   LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
533   LLVMStyle.SpacesBeforeTrailingComments = 1;
534   LLVMStyle.Standard = FormatStyle::LS_Cpp11;
535   LLVMStyle.UseTab = FormatStyle::UT_Never;
536   LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
537   LLVMStyle.ReflowComments = true;
538   LLVMStyle.SpacesInParentheses = false;
539   LLVMStyle.SpacesInSquareBrackets = false;
540   LLVMStyle.SpaceInEmptyParentheses = false;
541   LLVMStyle.SpacesInContainerLiterals = true;
542   LLVMStyle.SpacesInCStyleCastParentheses = false;
543   LLVMStyle.SpaceAfterCStyleCast = false;
544   LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
545   LLVMStyle.SpaceBeforeAssignmentOperators = true;
546   LLVMStyle.SpacesInAngles = false;
547 
548   LLVMStyle.PenaltyBreakComment = 300;
549   LLVMStyle.PenaltyBreakFirstLessLess = 120;
550   LLVMStyle.PenaltyBreakString = 1000;
551   LLVMStyle.PenaltyExcessCharacter = 1000000;
552   LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
553   LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
554 
555   LLVMStyle.DisableFormat = false;
556   LLVMStyle.SortIncludes = true;
557 
558   return LLVMStyle;
559 }
560 
561 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
562   FormatStyle GoogleStyle = getLLVMStyle();
563   GoogleStyle.Language = Language;
564 
565   GoogleStyle.AccessModifierOffset = -1;
566   GoogleStyle.AlignEscapedNewlinesLeft = true;
567   GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
568   GoogleStyle.AllowShortLoopsOnASingleLine = true;
569   GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
570   GoogleStyle.AlwaysBreakTemplateDeclarations = true;
571   GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
572   GoogleStyle.DerivePointerAlignment = true;
573   GoogleStyle.IncludeCategories = {{"^<.*\\.h>", 1}, {"^<.*", 2}, {".*", 3}};
574   GoogleStyle.IncludeIsMainRegex = "([-_](test|unittest))?$";
575   GoogleStyle.IndentCaseLabels = true;
576   GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
577   GoogleStyle.ObjCSpaceAfterProperty = false;
578   GoogleStyle.ObjCSpaceBeforeProtocolList = false;
579   GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
580   GoogleStyle.SpacesBeforeTrailingComments = 2;
581   GoogleStyle.Standard = FormatStyle::LS_Auto;
582 
583   GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
584   GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
585 
586   if (Language == FormatStyle::LK_Java) {
587     GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
588     GoogleStyle.AlignOperands = false;
589     GoogleStyle.AlignTrailingComments = false;
590     GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
591     GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
592     GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
593     GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
594     GoogleStyle.ColumnLimit = 100;
595     GoogleStyle.SpaceAfterCStyleCast = true;
596     GoogleStyle.SpacesBeforeTrailingComments = 1;
597   } else if (Language == FormatStyle::LK_JavaScript) {
598     GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
599     GoogleStyle.AlignOperands = false;
600     GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
601     GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
602     GoogleStyle.BreakBeforeTernaryOperators = false;
603     GoogleStyle.CommentPragmas = "@(export|return|see|visibility) ";
604     GoogleStyle.MaxEmptyLinesToKeep = 3;
605     GoogleStyle.SpacesInContainerLiterals = false;
606     GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single;
607   } else if (Language == FormatStyle::LK_Proto) {
608     GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
609     GoogleStyle.SpacesInContainerLiterals = false;
610   }
611 
612   return GoogleStyle;
613 }
614 
615 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
616   FormatStyle ChromiumStyle = getGoogleStyle(Language);
617   if (Language == FormatStyle::LK_Java) {
618     ChromiumStyle.AllowShortIfStatementsOnASingleLine = true;
619     ChromiumStyle.BreakAfterJavaFieldAnnotations = true;
620     ChromiumStyle.ContinuationIndentWidth = 8;
621     ChromiumStyle.IndentWidth = 4;
622   } else {
623     ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
624     ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
625     ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
626     ChromiumStyle.AllowShortLoopsOnASingleLine = false;
627     ChromiumStyle.BinPackParameters = false;
628     ChromiumStyle.DerivePointerAlignment = false;
629   }
630   ChromiumStyle.SortIncludes = false;
631   return ChromiumStyle;
632 }
633 
634 FormatStyle getMozillaStyle() {
635   FormatStyle MozillaStyle = getLLVMStyle();
636   MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
637   MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
638   MozillaStyle.AlwaysBreakAfterReturnType =
639       FormatStyle::RTBS_TopLevelDefinitions;
640   MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
641       FormatStyle::DRTBS_TopLevel;
642   MozillaStyle.AlwaysBreakTemplateDeclarations = true;
643   MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
644   MozillaStyle.BreakConstructorInitializersBeforeComma = true;
645   MozillaStyle.ConstructorInitializerIndentWidth = 2;
646   MozillaStyle.ContinuationIndentWidth = 2;
647   MozillaStyle.Cpp11BracedListStyle = false;
648   MozillaStyle.IndentCaseLabels = true;
649   MozillaStyle.ObjCSpaceAfterProperty = true;
650   MozillaStyle.ObjCSpaceBeforeProtocolList = false;
651   MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
652   MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
653   return MozillaStyle;
654 }
655 
656 FormatStyle getWebKitStyle() {
657   FormatStyle Style = getLLVMStyle();
658   Style.AccessModifierOffset = -4;
659   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
660   Style.AlignOperands = false;
661   Style.AlignTrailingComments = false;
662   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
663   Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
664   Style.BreakConstructorInitializersBeforeComma = true;
665   Style.Cpp11BracedListStyle = false;
666   Style.ColumnLimit = 0;
667   Style.IndentWidth = 4;
668   Style.NamespaceIndentation = FormatStyle::NI_Inner;
669   Style.ObjCBlockIndentWidth = 4;
670   Style.ObjCSpaceAfterProperty = true;
671   Style.PointerAlignment = FormatStyle::PAS_Left;
672   Style.Standard = FormatStyle::LS_Cpp03;
673   return Style;
674 }
675 
676 FormatStyle getGNUStyle() {
677   FormatStyle Style = getLLVMStyle();
678   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
679   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
680   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
681   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
682   Style.BreakBeforeTernaryOperators = true;
683   Style.Cpp11BracedListStyle = false;
684   Style.ColumnLimit = 79;
685   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
686   Style.Standard = FormatStyle::LS_Cpp03;
687   return Style;
688 }
689 
690 FormatStyle getNoStyle() {
691   FormatStyle NoStyle = getLLVMStyle();
692   NoStyle.DisableFormat = true;
693   NoStyle.SortIncludes = false;
694   return NoStyle;
695 }
696 
697 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
698                         FormatStyle *Style) {
699   if (Name.equals_lower("llvm")) {
700     *Style = getLLVMStyle();
701   } else if (Name.equals_lower("chromium")) {
702     *Style = getChromiumStyle(Language);
703   } else if (Name.equals_lower("mozilla")) {
704     *Style = getMozillaStyle();
705   } else if (Name.equals_lower("google")) {
706     *Style = getGoogleStyle(Language);
707   } else if (Name.equals_lower("webkit")) {
708     *Style = getWebKitStyle();
709   } else if (Name.equals_lower("gnu")) {
710     *Style = getGNUStyle();
711   } else if (Name.equals_lower("none")) {
712     *Style = getNoStyle();
713   } else {
714     return false;
715   }
716 
717   Style->Language = Language;
718   return true;
719 }
720 
721 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
722   assert(Style);
723   FormatStyle::LanguageKind Language = Style->Language;
724   assert(Language != FormatStyle::LK_None);
725   if (Text.trim().empty())
726     return make_error_code(ParseError::Error);
727 
728   std::vector<FormatStyle> Styles;
729   llvm::yaml::Input Input(Text);
730   // DocumentListTraits<vector<FormatStyle>> uses the context to get default
731   // values for the fields, keys for which are missing from the configuration.
732   // Mapping also uses the context to get the language to find the correct
733   // base style.
734   Input.setContext(Style);
735   Input >> Styles;
736   if (Input.error())
737     return Input.error();
738 
739   for (unsigned i = 0; i < Styles.size(); ++i) {
740     // Ensures that only the first configuration can skip the Language option.
741     if (Styles[i].Language == FormatStyle::LK_None && i != 0)
742       return make_error_code(ParseError::Error);
743     // Ensure that each language is configured at most once.
744     for (unsigned j = 0; j < i; ++j) {
745       if (Styles[i].Language == Styles[j].Language) {
746         DEBUG(llvm::dbgs()
747               << "Duplicate languages in the config file on positions " << j
748               << " and " << i << "\n");
749         return make_error_code(ParseError::Error);
750       }
751     }
752   }
753   // Look for a suitable configuration starting from the end, so we can
754   // find the configuration for the specific language first, and the default
755   // configuration (which can only be at slot 0) after it.
756   for (int i = Styles.size() - 1; i >= 0; --i) {
757     if (Styles[i].Language == Language ||
758         Styles[i].Language == FormatStyle::LK_None) {
759       *Style = Styles[i];
760       Style->Language = Language;
761       return make_error_code(ParseError::Success);
762     }
763   }
764   return make_error_code(ParseError::Unsuitable);
765 }
766 
767 std::string configurationAsText(const FormatStyle &Style) {
768   std::string Text;
769   llvm::raw_string_ostream Stream(Text);
770   llvm::yaml::Output Output(Stream);
771   // We use the same mapping method for input and output, so we need a non-const
772   // reference here.
773   FormatStyle NonConstStyle = expandPresets(Style);
774   Output << NonConstStyle;
775   return Stream.str();
776 }
777 
778 namespace {
779 
780 class FormatTokenLexer {
781 public:
782   FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
783                    encoding::Encoding Encoding)
784       : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
785         LessStashed(false), Column(0), TrailingWhitespace(0),
786         SourceMgr(SourceMgr), ID(ID), Style(Style),
787         IdentTable(getFormattingLangOpts(Style)), Keywords(IdentTable),
788         Encoding(Encoding), FirstInLineIndex(0), FormattingDisabled(false),
789         MacroBlockBeginRegex(Style.MacroBlockBegin),
790         MacroBlockEndRegex(Style.MacroBlockEnd) {
791     Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
792                         getFormattingLangOpts(Style)));
793     Lex->SetKeepWhitespaceMode(true);
794 
795     for (const std::string &ForEachMacro : Style.ForEachMacros)
796       ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
797     std::sort(ForEachMacros.begin(), ForEachMacros.end());
798   }
799 
800   ArrayRef<FormatToken *> lex() {
801     assert(Tokens.empty());
802     assert(FirstInLineIndex == 0);
803     do {
804       Tokens.push_back(getNextToken());
805       if (Style.Language == FormatStyle::LK_JavaScript)
806         tryParseJSRegexLiteral();
807       tryMergePreviousTokens();
808       if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
809         FirstInLineIndex = Tokens.size() - 1;
810     } while (Tokens.back()->Tok.isNot(tok::eof));
811     return Tokens;
812   }
813 
814   const AdditionalKeywords &getKeywords() { return Keywords; }
815 
816 private:
817   void tryMergePreviousTokens() {
818     if (tryMerge_TMacro())
819       return;
820     if (tryMergeConflictMarkers())
821       return;
822     if (tryMergeLessLess())
823       return;
824 
825     if (Style.Language == FormatStyle::LK_JavaScript) {
826       if (tryMergeTemplateString())
827         return;
828 
829       static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
830       static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
831                                                      tok::equal};
832       static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
833                                                     tok::greaterequal};
834       static const tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater};
835       // FIXME: Investigate what token type gives the correct operator priority.
836       if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
837         return;
838       if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
839         return;
840       if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
841         return;
842       if (tryMergeTokens(JSRightArrow, TT_JsFatArrow))
843         return;
844     }
845   }
846 
847   bool tryMergeLessLess() {
848     // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
849     if (Tokens.size() < 3)
850       return false;
851 
852     bool FourthTokenIsLess = false;
853     if (Tokens.size() > 3)
854       FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less);
855 
856     auto First = Tokens.end() - 3;
857     if (First[2]->is(tok::less) || First[1]->isNot(tok::less) ||
858         First[0]->isNot(tok::less) || FourthTokenIsLess)
859       return false;
860 
861     // Only merge if there currently is no whitespace between the two "<".
862     if (First[1]->WhitespaceRange.getBegin() !=
863         First[1]->WhitespaceRange.getEnd())
864       return false;
865 
866     First[0]->Tok.setKind(tok::lessless);
867     First[0]->TokenText = "<<";
868     First[0]->ColumnWidth += 1;
869     Tokens.erase(Tokens.end() - 2);
870     return true;
871   }
872 
873   bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds, TokenType NewType) {
874     if (Tokens.size() < Kinds.size())
875       return false;
876 
877     SmallVectorImpl<FormatToken *>::const_iterator First =
878         Tokens.end() - Kinds.size();
879     if (!First[0]->is(Kinds[0]))
880       return false;
881     unsigned AddLength = 0;
882     for (unsigned i = 1; i < Kinds.size(); ++i) {
883       if (!First[i]->is(Kinds[i]) ||
884           First[i]->WhitespaceRange.getBegin() !=
885               First[i]->WhitespaceRange.getEnd())
886         return false;
887       AddLength += First[i]->TokenText.size();
888     }
889     Tokens.resize(Tokens.size() - Kinds.size() + 1);
890     First[0]->TokenText = StringRef(First[0]->TokenText.data(),
891                                     First[0]->TokenText.size() + AddLength);
892     First[0]->ColumnWidth += AddLength;
893     First[0]->Type = NewType;
894     return true;
895   }
896 
897   // Returns \c true if \p Tok can only be followed by an operand in JavaScript.
898   bool precedesOperand(FormatToken *Tok) {
899     // NB: This is not entirely correct, as an r_paren can introduce an operand
900     // location in e.g. `if (foo) /bar/.exec(...);`. That is a rare enough
901     // corner case to not matter in practice, though.
902     return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace,
903                         tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
904                         tok::colon, tok::question, tok::tilde) ||
905            Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
906                         tok::kw_else, tok::kw_new, tok::kw_delete, tok::kw_void,
907                         tok::kw_typeof, Keywords.kw_instanceof,
908                         Keywords.kw_in) ||
909            Tok->isBinaryOperator();
910   }
911 
912   bool canPrecedeRegexLiteral(FormatToken *Prev) {
913     if (!Prev)
914       return true;
915 
916     // Regex literals can only follow after prefix unary operators, not after
917     // postfix unary operators. If the '++' is followed by a non-operand
918     // introducing token, the slash here is the operand and not the start of a
919     // regex.
920     if (Prev->isOneOf(tok::plusplus, tok::minusminus))
921       return (Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]));
922 
923     // The previous token must introduce an operand location where regex
924     // literals can occur.
925     if (!precedesOperand(Prev))
926       return false;
927 
928     return true;
929   }
930 
931   // Tries to parse a JavaScript Regex literal starting at the current token,
932   // if that begins with a slash and is in a location where JavaScript allows
933   // regex literals. Changes the current token to a regex literal and updates
934   // its text if successful.
935   void tryParseJSRegexLiteral() {
936     FormatToken *RegexToken = Tokens.back();
937     if (!RegexToken->isOneOf(tok::slash, tok::slashequal))
938       return;
939 
940     FormatToken *Prev = nullptr;
941     for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
942       // NB: Because previous pointers are not initialized yet, this cannot use
943       // Token.getPreviousNonComment.
944       if ((*I)->isNot(tok::comment)) {
945         Prev = *I;
946         break;
947       }
948     }
949 
950     if (!canPrecedeRegexLiteral(Prev))
951       return;
952 
953     // 'Manually' lex ahead in the current file buffer.
954     const char *Offset = Lex->getBufferLocation();
955     const char *RegexBegin = Offset - RegexToken->TokenText.size();
956     StringRef Buffer = Lex->getBuffer();
957     bool InCharacterClass = false;
958     bool HaveClosingSlash = false;
959     for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) {
960       // Regular expressions are terminated with a '/', which can only be
961       // escaped using '\' or a character class between '[' and ']'.
962       // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5.
963       switch (*Offset) {
964       case '\\':
965         // Skip the escaped character.
966         ++Offset;
967         break;
968       case '[':
969         InCharacterClass = true;
970         break;
971       case ']':
972         InCharacterClass = false;
973         break;
974       case '/':
975         if (!InCharacterClass)
976           HaveClosingSlash = true;
977         break;
978       }
979     }
980 
981     RegexToken->Type = TT_RegexLiteral;
982     // Treat regex literals like other string_literals.
983     RegexToken->Tok.setKind(tok::string_literal);
984     RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin);
985     RegexToken->ColumnWidth = RegexToken->TokenText.size();
986 
987     resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
988   }
989 
990   bool tryMergeTemplateString() {
991     if (Tokens.size() < 2)
992       return false;
993 
994     FormatToken *EndBacktick = Tokens.back();
995     // Backticks get lexed as tok::unknown tokens. If a template string contains
996     // a comment start, it gets lexed as a tok::comment, or tok::unknown if
997     // unterminated.
998     if (!EndBacktick->isOneOf(tok::comment, tok::string_literal,
999                               tok::char_constant, tok::unknown))
1000       return false;
1001     size_t CommentBacktickPos = EndBacktick->TokenText.find('`');
1002     // Unknown token that's not actually a backtick, or a comment that doesn't
1003     // contain a backtick.
1004     if (CommentBacktickPos == StringRef::npos)
1005       return false;
1006 
1007     unsigned TokenCount = 0;
1008     bool IsMultiline = false;
1009     unsigned EndColumnInFirstLine =
1010         EndBacktick->OriginalColumn + EndBacktick->ColumnWidth;
1011     for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; I++) {
1012       ++TokenCount;
1013       if (I[0]->IsMultiline)
1014         IsMultiline = true;
1015 
1016       // If there was a preceding template string, this must be the start of a
1017       // template string, not the end.
1018       if (I[0]->is(TT_TemplateString))
1019         return false;
1020 
1021       if (I[0]->isNot(tok::unknown) || I[0]->TokenText != "`") {
1022         // Keep track of the rhs offset of the last token to wrap across lines -
1023         // its the rhs offset of the first line of the template string, used to
1024         // determine its width.
1025         if (I[0]->IsMultiline)
1026           EndColumnInFirstLine = I[0]->OriginalColumn + I[0]->ColumnWidth;
1027         // If the token has newlines, the token before it (if it exists) is the
1028         // rhs end of the previous line.
1029         if (I[0]->NewlinesBefore > 0 && (I + 1 != E)) {
1030           EndColumnInFirstLine = I[1]->OriginalColumn + I[1]->ColumnWidth;
1031           IsMultiline = true;
1032         }
1033         continue;
1034       }
1035 
1036       Tokens.resize(Tokens.size() - TokenCount);
1037       Tokens.back()->Type = TT_TemplateString;
1038       const char *EndOffset =
1039           EndBacktick->TokenText.data() + 1 + CommentBacktickPos;
1040       if (CommentBacktickPos != 0) {
1041         // If the backtick was not the first character (e.g. in a comment),
1042         // re-lex after the backtick position.
1043         SourceLocation Loc = EndBacktick->Tok.getLocation();
1044         resetLexer(SourceMgr.getFileOffset(Loc) + CommentBacktickPos + 1);
1045       }
1046       Tokens.back()->TokenText =
1047           StringRef(Tokens.back()->TokenText.data(),
1048                     EndOffset - Tokens.back()->TokenText.data());
1049 
1050       unsigned EndOriginalColumn = EndBacktick->OriginalColumn;
1051       if (EndOriginalColumn == 0) {
1052         SourceLocation Loc = EndBacktick->Tok.getLocation();
1053         EndOriginalColumn = SourceMgr.getSpellingColumnNumber(Loc);
1054       }
1055       // If the ` is further down within the token (e.g. in a comment).
1056       EndOriginalColumn += CommentBacktickPos;
1057 
1058       if (IsMultiline) {
1059         // ColumnWidth is from backtick to last token in line.
1060         // LastLineColumnWidth is 0 to backtick.
1061         // x = `some content
1062         //     until here`;
1063         Tokens.back()->ColumnWidth =
1064             EndColumnInFirstLine - Tokens.back()->OriginalColumn;
1065         // +1 for the ` itself.
1066         Tokens.back()->LastLineColumnWidth = EndOriginalColumn + 1;
1067         Tokens.back()->IsMultiline = true;
1068       } else {
1069         // Token simply spans from start to end, +1 for the ` itself.
1070         Tokens.back()->ColumnWidth =
1071             EndOriginalColumn - Tokens.back()->OriginalColumn + 1;
1072       }
1073       return true;
1074     }
1075     return false;
1076   }
1077 
1078   bool tryMerge_TMacro() {
1079     if (Tokens.size() < 4)
1080       return false;
1081     FormatToken *Last = Tokens.back();
1082     if (!Last->is(tok::r_paren))
1083       return false;
1084 
1085     FormatToken *String = Tokens[Tokens.size() - 2];
1086     if (!String->is(tok::string_literal) || String->IsMultiline)
1087       return false;
1088 
1089     if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
1090       return false;
1091 
1092     FormatToken *Macro = Tokens[Tokens.size() - 4];
1093     if (Macro->TokenText != "_T")
1094       return false;
1095 
1096     const char *Start = Macro->TokenText.data();
1097     const char *End = Last->TokenText.data() + Last->TokenText.size();
1098     String->TokenText = StringRef(Start, End - Start);
1099     String->IsFirst = Macro->IsFirst;
1100     String->LastNewlineOffset = Macro->LastNewlineOffset;
1101     String->WhitespaceRange = Macro->WhitespaceRange;
1102     String->OriginalColumn = Macro->OriginalColumn;
1103     String->ColumnWidth = encoding::columnWidthWithTabs(
1104         String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1105     String->NewlinesBefore = Macro->NewlinesBefore;
1106     String->HasUnescapedNewline = Macro->HasUnescapedNewline;
1107 
1108     Tokens.pop_back();
1109     Tokens.pop_back();
1110     Tokens.pop_back();
1111     Tokens.back() = String;
1112     return true;
1113   }
1114 
1115   bool tryMergeConflictMarkers() {
1116     if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1117       return false;
1118 
1119     // Conflict lines look like:
1120     // <marker> <text from the vcs>
1121     // For example:
1122     // >>>>>>> /file/in/file/system at revision 1234
1123     //
1124     // We merge all tokens in a line that starts with a conflict marker
1125     // into a single token with a special token type that the unwrapped line
1126     // parser will use to correctly rebuild the underlying code.
1127 
1128     FileID ID;
1129     // Get the position of the first token in the line.
1130     unsigned FirstInLineOffset;
1131     std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1132         Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1133     StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
1134     // Calculate the offset of the start of the current line.
1135     auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1136     if (LineOffset == StringRef::npos) {
1137       LineOffset = 0;
1138     } else {
1139       ++LineOffset;
1140     }
1141 
1142     auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1143     StringRef LineStart;
1144     if (FirstSpace == StringRef::npos) {
1145       LineStart = Buffer.substr(LineOffset);
1146     } else {
1147       LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1148     }
1149 
1150     TokenType Type = TT_Unknown;
1151     if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1152       Type = TT_ConflictStart;
1153     } else if (LineStart == "|||||||" || LineStart == "=======" ||
1154                LineStart == "====") {
1155       Type = TT_ConflictAlternative;
1156     } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1157       Type = TT_ConflictEnd;
1158     }
1159 
1160     if (Type != TT_Unknown) {
1161       FormatToken *Next = Tokens.back();
1162 
1163       Tokens.resize(FirstInLineIndex + 1);
1164       // We do not need to build a complete token here, as we will skip it
1165       // during parsing anyway (as we must not touch whitespace around conflict
1166       // markers).
1167       Tokens.back()->Type = Type;
1168       Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1169 
1170       Tokens.push_back(Next);
1171       return true;
1172     }
1173 
1174     return false;
1175   }
1176 
1177   FormatToken *getStashedToken() {
1178     // Create a synthesized second '>' or '<' token.
1179     Token Tok = FormatTok->Tok;
1180     StringRef TokenText = FormatTok->TokenText;
1181 
1182     unsigned OriginalColumn = FormatTok->OriginalColumn;
1183     FormatTok = new (Allocator.Allocate()) FormatToken;
1184     FormatTok->Tok = Tok;
1185     SourceLocation TokLocation =
1186         FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
1187     FormatTok->Tok.setLocation(TokLocation);
1188     FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
1189     FormatTok->TokenText = TokenText;
1190     FormatTok->ColumnWidth = 1;
1191     FormatTok->OriginalColumn = OriginalColumn + 1;
1192 
1193     return FormatTok;
1194   }
1195 
1196   FormatToken *getNextToken() {
1197     if (GreaterStashed) {
1198       GreaterStashed = false;
1199       return getStashedToken();
1200     }
1201     if (LessStashed) {
1202       LessStashed = false;
1203       return getStashedToken();
1204     }
1205 
1206     FormatTok = new (Allocator.Allocate()) FormatToken;
1207     readRawToken(*FormatTok);
1208     SourceLocation WhitespaceStart =
1209         FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
1210     FormatTok->IsFirst = IsFirstToken;
1211     IsFirstToken = false;
1212 
1213     // Consume and record whitespace until we find a significant token.
1214     unsigned WhitespaceLength = TrailingWhitespace;
1215     while (FormatTok->Tok.is(tok::unknown)) {
1216       StringRef Text = FormatTok->TokenText;
1217       auto EscapesNewline = [&](int pos) {
1218         // A '\r' here is just part of '\r\n'. Skip it.
1219         if (pos >= 0 && Text[pos] == '\r')
1220           --pos;
1221         // See whether there is an odd number of '\' before this.
1222         unsigned count = 0;
1223         for (; pos >= 0; --pos, ++count)
1224           if (Text[pos] != '\\')
1225             break;
1226         return count & 1;
1227       };
1228       // FIXME: This miscounts tok:unknown tokens that are not just
1229       // whitespace, e.g. a '`' character.
1230       for (int i = 0, e = Text.size(); i != e; ++i) {
1231         switch (Text[i]) {
1232         case '\n':
1233           ++FormatTok->NewlinesBefore;
1234           FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1);
1235           FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1236           Column = 0;
1237           break;
1238         case '\r':
1239           FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1240           Column = 0;
1241           break;
1242         case '\f':
1243         case '\v':
1244           Column = 0;
1245           break;
1246         case ' ':
1247           ++Column;
1248           break;
1249         case '\t':
1250           Column += Style.TabWidth - Column % Style.TabWidth;
1251           break;
1252         case '\\':
1253           if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n'))
1254             FormatTok->Type = TT_ImplicitStringLiteral;
1255           break;
1256         default:
1257           FormatTok->Type = TT_ImplicitStringLiteral;
1258           break;
1259         }
1260         if (FormatTok->Type == TT_ImplicitStringLiteral)
1261           break;
1262       }
1263 
1264       if (FormatTok->is(TT_ImplicitStringLiteral))
1265         break;
1266       WhitespaceLength += FormatTok->Tok.getLength();
1267 
1268       readRawToken(*FormatTok);
1269     }
1270 
1271     // In case the token starts with escaped newlines, we want to
1272     // take them into account as whitespace - this pattern is quite frequent
1273     // in macro definitions.
1274     // FIXME: Add a more explicit test.
1275     while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1276            FormatTok->TokenText[1] == '\n') {
1277       ++FormatTok->NewlinesBefore;
1278       WhitespaceLength += 2;
1279       FormatTok->LastNewlineOffset = 2;
1280       Column = 0;
1281       FormatTok->TokenText = FormatTok->TokenText.substr(2);
1282     }
1283 
1284     FormatTok->WhitespaceRange = SourceRange(
1285         WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1286 
1287     FormatTok->OriginalColumn = Column;
1288 
1289     TrailingWhitespace = 0;
1290     if (FormatTok->Tok.is(tok::comment)) {
1291       // FIXME: Add the trimmed whitespace to Column.
1292       StringRef UntrimmedText = FormatTok->TokenText;
1293       FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
1294       TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
1295     } else if (FormatTok->Tok.is(tok::raw_identifier)) {
1296       IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
1297       FormatTok->Tok.setIdentifierInfo(&Info);
1298       FormatTok->Tok.setKind(Info.getTokenID());
1299       if (Style.Language == FormatStyle::LK_Java &&
1300           FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete,
1301                              tok::kw_operator)) {
1302         FormatTok->Tok.setKind(tok::identifier);
1303         FormatTok->Tok.setIdentifierInfo(nullptr);
1304       } else if (Style.Language == FormatStyle::LK_JavaScript &&
1305                  FormatTok->isOneOf(tok::kw_struct, tok::kw_union,
1306                                     tok::kw_operator)) {
1307         FormatTok->Tok.setKind(tok::identifier);
1308         FormatTok->Tok.setIdentifierInfo(nullptr);
1309       }
1310     } else if (FormatTok->Tok.is(tok::greatergreater)) {
1311       FormatTok->Tok.setKind(tok::greater);
1312       FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1313       GreaterStashed = true;
1314     } else if (FormatTok->Tok.is(tok::lessless)) {
1315       FormatTok->Tok.setKind(tok::less);
1316       FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1317       LessStashed = true;
1318     }
1319 
1320     // Now FormatTok is the next non-whitespace token.
1321 
1322     StringRef Text = FormatTok->TokenText;
1323     size_t FirstNewlinePos = Text.find('\n');
1324     if (FirstNewlinePos == StringRef::npos) {
1325       // FIXME: ColumnWidth actually depends on the start column, we need to
1326       // take this into account when the token is moved.
1327       FormatTok->ColumnWidth =
1328           encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1329       Column += FormatTok->ColumnWidth;
1330     } else {
1331       FormatTok->IsMultiline = true;
1332       // FIXME: ColumnWidth actually depends on the start column, we need to
1333       // take this into account when the token is moved.
1334       FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1335           Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1336 
1337       // The last line of the token always starts in column 0.
1338       // Thus, the length can be precomputed even in the presence of tabs.
1339       FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1340           Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
1341           Encoding);
1342       Column = FormatTok->LastLineColumnWidth;
1343     }
1344 
1345     if (Style.Language == FormatStyle::LK_Cpp) {
1346       if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
1347             Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
1348                 tok::pp_define) &&
1349           std::find(ForEachMacros.begin(), ForEachMacros.end(),
1350                     FormatTok->Tok.getIdentifierInfo()) != ForEachMacros.end()) {
1351         FormatTok->Type = TT_ForEachMacro;
1352       } else if (FormatTok->is(tok::identifier)) {
1353         if (MacroBlockBeginRegex.match(Text)) {
1354           FormatTok->Type = TT_MacroBlockBegin;
1355         } else if (MacroBlockEndRegex.match(Text)) {
1356           FormatTok->Type = TT_MacroBlockEnd;
1357         }
1358       }
1359     }
1360 
1361     return FormatTok;
1362   }
1363 
1364   FormatToken *FormatTok;
1365   bool IsFirstToken;
1366   bool GreaterStashed, LessStashed;
1367   unsigned Column;
1368   unsigned TrailingWhitespace;
1369   std::unique_ptr<Lexer> Lex;
1370   SourceManager &SourceMgr;
1371   FileID ID;
1372   FormatStyle &Style;
1373   IdentifierTable IdentTable;
1374   AdditionalKeywords Keywords;
1375   encoding::Encoding Encoding;
1376   llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1377   // Index (in 'Tokens') of the last token that starts a new line.
1378   unsigned FirstInLineIndex;
1379   SmallVector<FormatToken *, 16> Tokens;
1380   SmallVector<IdentifierInfo *, 8> ForEachMacros;
1381 
1382   bool FormattingDisabled;
1383 
1384   llvm::Regex MacroBlockBeginRegex;
1385   llvm::Regex MacroBlockEndRegex;
1386 
1387   void readRawToken(FormatToken &Tok) {
1388     Lex->LexFromRawLexer(Tok.Tok);
1389     Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1390                               Tok.Tok.getLength());
1391     // For formatting, treat unterminated string literals like normal string
1392     // literals.
1393     if (Tok.is(tok::unknown)) {
1394       if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1395         Tok.Tok.setKind(tok::string_literal);
1396         Tok.IsUnterminatedLiteral = true;
1397       } else if (Style.Language == FormatStyle::LK_JavaScript &&
1398                  Tok.TokenText == "''") {
1399         Tok.Tok.setKind(tok::string_literal);
1400       }
1401     }
1402 
1403     if (Style.Language == FormatStyle::LK_JavaScript &&
1404         Tok.is(tok::char_constant)) {
1405       Tok.Tok.setKind(tok::string_literal);
1406     }
1407 
1408     if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1409                                  Tok.TokenText == "/* clang-format on */")) {
1410       FormattingDisabled = false;
1411     }
1412 
1413     Tok.Finalized = FormattingDisabled;
1414 
1415     if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1416                                  Tok.TokenText == "/* clang-format off */")) {
1417       FormattingDisabled = true;
1418     }
1419   }
1420 
1421   void resetLexer(unsigned Offset) {
1422     StringRef Buffer = SourceMgr.getBufferData(ID);
1423     Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1424                         getFormattingLangOpts(Style), Buffer.begin(),
1425                         Buffer.begin() + Offset, Buffer.end()));
1426     Lex->SetKeepWhitespaceMode(true);
1427     TrailingWhitespace = 0;
1428   }
1429 };
1430 
1431 static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1432   switch (Language) {
1433   case FormatStyle::LK_Cpp:
1434     return "C++";
1435   case FormatStyle::LK_Java:
1436     return "Java";
1437   case FormatStyle::LK_JavaScript:
1438     return "JavaScript";
1439   case FormatStyle::LK_Proto:
1440     return "Proto";
1441   default:
1442     return "Unknown";
1443   }
1444 }
1445 
1446 class Formatter : public UnwrappedLineConsumer {
1447 public:
1448   Formatter(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID,
1449             ArrayRef<CharSourceRange> Ranges)
1450       : Style(Style), ID(ID), SourceMgr(SourceMgr),
1451         Whitespaces(SourceMgr, Style,
1452                     inputUsesCRLF(SourceMgr.getBufferData(ID))),
1453         Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
1454         Encoding(encoding::detectEncoding(SourceMgr.getBufferData(ID))) {
1455     DEBUG(llvm::dbgs() << "File encoding: "
1456                        << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1457                                                                : "unknown")
1458                        << "\n");
1459     DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
1460                        << "\n");
1461   }
1462 
1463   tooling::Replacements format(bool *IncompleteFormat) {
1464     tooling::Replacements Result;
1465     FormatTokenLexer Tokens(SourceMgr, ID, Style, Encoding);
1466 
1467     UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
1468                                *this);
1469     Parser.parse();
1470     assert(UnwrappedLines.rbegin()->empty());
1471     for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
1472          ++Run) {
1473       DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
1474       SmallVector<AnnotatedLine *, 16> AnnotatedLines;
1475       for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
1476         AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
1477       }
1478       tooling::Replacements RunResult =
1479           format(AnnotatedLines, Tokens, Result, IncompleteFormat);
1480       DEBUG({
1481         llvm::dbgs() << "Replacements for run " << Run << ":\n";
1482         for (tooling::Replacements::iterator I = RunResult.begin(),
1483                                              E = RunResult.end();
1484              I != E; ++I) {
1485           llvm::dbgs() << I->toString() << "\n";
1486         }
1487       });
1488       for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1489         delete AnnotatedLines[i];
1490       }
1491       Result.insert(RunResult.begin(), RunResult.end());
1492       Whitespaces.reset();
1493     }
1494     return Result;
1495   }
1496 
1497   tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
1498                                FormatTokenLexer &Tokens,
1499                                tooling::Replacements &Result,
1500                                bool *IncompleteFormat) {
1501     TokenAnnotator Annotator(Style, Tokens.getKeywords());
1502     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1503       Annotator.annotate(*AnnotatedLines[i]);
1504     }
1505     deriveLocalStyle(AnnotatedLines);
1506     computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
1507     if (Style.Language == FormatStyle::LK_JavaScript &&
1508         Style.JavaScriptQuotes != FormatStyle::JSQS_Leave)
1509       requoteJSStringLiteral(AnnotatedLines, Result);
1510 
1511     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1512       Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
1513     }
1514 
1515     Annotator.setCommentLineLevels(AnnotatedLines);
1516     ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
1517                                   Whitespaces, Encoding,
1518                                   BinPackInconclusiveFunctions);
1519     UnwrappedLineFormatter(&Indenter, &Whitespaces, Style, Tokens.getKeywords(),
1520                            IncompleteFormat)
1521         .format(AnnotatedLines);
1522     return Whitespaces.generateReplacements();
1523   }
1524 
1525 private:
1526   // Determines which lines are affected by the SourceRanges given as input.
1527   // Returns \c true if at least one line between I and E or one of their
1528   // children is affected.
1529   bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
1530                             SmallVectorImpl<AnnotatedLine *>::iterator E) {
1531     bool SomeLineAffected = false;
1532     const AnnotatedLine *PreviousLine = nullptr;
1533     while (I != E) {
1534       AnnotatedLine *Line = *I;
1535       Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
1536 
1537       // If a line is part of a preprocessor directive, it needs to be formatted
1538       // if any token within the directive is affected.
1539       if (Line->InPPDirective) {
1540         FormatToken *Last = Line->Last;
1541         SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
1542         while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
1543           Last = (*PPEnd)->Last;
1544           ++PPEnd;
1545         }
1546 
1547         if (affectsTokenRange(*Line->First, *Last,
1548                               /*IncludeLeadingNewlines=*/false)) {
1549           SomeLineAffected = true;
1550           markAllAsAffected(I, PPEnd);
1551         }
1552         I = PPEnd;
1553         continue;
1554       }
1555 
1556       if (nonPPLineAffected(Line, PreviousLine))
1557         SomeLineAffected = true;
1558 
1559       PreviousLine = Line;
1560       ++I;
1561     }
1562     return SomeLineAffected;
1563   }
1564 
1565   // If the last token is a double/single-quoted string literal, generates a
1566   // replacement with a single/double quoted string literal, re-escaping the
1567   // contents in the process.
1568   void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
1569                                  tooling::Replacements &Result) {
1570     for (AnnotatedLine *Line : Lines) {
1571       requoteJSStringLiteral(Line->Children, Result);
1572       if (!Line->Affected)
1573         continue;
1574       for (FormatToken *FormatTok = Line->First; FormatTok;
1575            FormatTok = FormatTok->Next) {
1576         StringRef Input = FormatTok->TokenText;
1577         if (!FormatTok->isStringLiteral() ||
1578             // NB: testing for not starting with a double quote to avoid
1579             // breaking
1580             // `template strings`.
1581             (Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
1582              !Input.startswith("\"")) ||
1583             (Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
1584              !Input.startswith("\'")))
1585           continue;
1586 
1587         // Change start and end quote.
1588         bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
1589         SourceLocation Start = FormatTok->Tok.getLocation();
1590         auto Replace = [&](SourceLocation Start, unsigned Length,
1591                            StringRef ReplacementText) {
1592           Result.insert(
1593               tooling::Replacement(SourceMgr, Start, Length, ReplacementText));
1594         };
1595         Replace(Start, 1, IsSingle ? "'" : "\"");
1596         Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
1597                 IsSingle ? "'" : "\"");
1598 
1599         // Escape internal quotes.
1600         size_t ColumnWidth = FormatTok->TokenText.size();
1601         bool Escaped = false;
1602         for (size_t i = 1; i < Input.size() - 1; i++) {
1603           switch (Input[i]) {
1604             case '\\':
1605               if (!Escaped && i + 1 < Input.size() &&
1606                   ((IsSingle && Input[i + 1] == '"') ||
1607                    (!IsSingle && Input[i + 1] == '\''))) {
1608                 // Remove this \, it's escaping a " or ' that no longer needs
1609                 // escaping
1610                 ColumnWidth--;
1611                 Replace(Start.getLocWithOffset(i), 1, "");
1612                 continue;
1613               }
1614               Escaped = !Escaped;
1615               break;
1616             case '\"':
1617             case '\'':
1618               if (!Escaped && IsSingle == (Input[i] == '\'')) {
1619                 // Escape the quote.
1620                 Replace(Start.getLocWithOffset(i), 0, "\\");
1621                 ColumnWidth++;
1622               }
1623               Escaped = false;
1624               break;
1625             default:
1626               Escaped = false;
1627               break;
1628           }
1629         }
1630 
1631         // For formatting, count the number of non-escaped single quotes in them
1632         // and adjust ColumnWidth to take the added escapes into account.
1633         // FIXME(martinprobst): this might conflict with code breaking a long string
1634         // literal (which clang-format doesn't do, yet). For that to work, this code
1635         // would have to modify TokenText directly.
1636         FormatTok->ColumnWidth = ColumnWidth;
1637       }
1638     }
1639   }
1640 
1641 
1642   // Determines whether 'Line' is affected by the SourceRanges given as input.
1643   // Returns \c true if line or one if its children is affected.
1644   bool nonPPLineAffected(AnnotatedLine *Line,
1645                          const AnnotatedLine *PreviousLine) {
1646     bool SomeLineAffected = false;
1647     Line->ChildrenAffected =
1648         computeAffectedLines(Line->Children.begin(), Line->Children.end());
1649     if (Line->ChildrenAffected)
1650       SomeLineAffected = true;
1651 
1652     // Stores whether one of the line's tokens is directly affected.
1653     bool SomeTokenAffected = false;
1654     // Stores whether we need to look at the leading newlines of the next token
1655     // in order to determine whether it was affected.
1656     bool IncludeLeadingNewlines = false;
1657 
1658     // Stores whether the first child line of any of this line's tokens is
1659     // affected.
1660     bool SomeFirstChildAffected = false;
1661 
1662     for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
1663       // Determine whether 'Tok' was affected.
1664       if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
1665         SomeTokenAffected = true;
1666 
1667       // Determine whether the first child of 'Tok' was affected.
1668       if (!Tok->Children.empty() && Tok->Children.front()->Affected)
1669         SomeFirstChildAffected = true;
1670 
1671       IncludeLeadingNewlines = Tok->Children.empty();
1672     }
1673 
1674     // Was this line moved, i.e. has it previously been on the same line as an
1675     // affected line?
1676     bool LineMoved = PreviousLine && PreviousLine->Affected &&
1677                      Line->First->NewlinesBefore == 0;
1678 
1679     bool IsContinuedComment =
1680         Line->First->is(tok::comment) && Line->First->Next == nullptr &&
1681         Line->First->NewlinesBefore < 2 && PreviousLine &&
1682         PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
1683 
1684     if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
1685         IsContinuedComment) {
1686       Line->Affected = true;
1687       SomeLineAffected = true;
1688     }
1689     return SomeLineAffected;
1690   }
1691 
1692   // Marks all lines between I and E as well as all their children as affected.
1693   void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
1694                          SmallVectorImpl<AnnotatedLine *>::iterator E) {
1695     while (I != E) {
1696       (*I)->Affected = true;
1697       markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
1698       ++I;
1699     }
1700   }
1701 
1702   // Returns true if the range from 'First' to 'Last' intersects with one of the
1703   // input ranges.
1704   bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
1705                          bool IncludeLeadingNewlines) {
1706     SourceLocation Start = First.WhitespaceRange.getBegin();
1707     if (!IncludeLeadingNewlines)
1708       Start = Start.getLocWithOffset(First.LastNewlineOffset);
1709     SourceLocation End = Last.getStartOfNonWhitespace();
1710     End = End.getLocWithOffset(Last.TokenText.size());
1711     CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
1712     return affectsCharSourceRange(Range);
1713   }
1714 
1715   // Returns true if one of the input ranges intersect the leading empty lines
1716   // before 'Tok'.
1717   bool affectsLeadingEmptyLines(const FormatToken &Tok) {
1718     CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
1719         Tok.WhitespaceRange.getBegin(),
1720         Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
1721     return affectsCharSourceRange(EmptyLineRange);
1722   }
1723 
1724   // Returns true if 'Range' intersects with one of the input ranges.
1725   bool affectsCharSourceRange(const CharSourceRange &Range) {
1726     for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
1727                                                           E = Ranges.end();
1728          I != E; ++I) {
1729       if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
1730           !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
1731         return true;
1732     }
1733     return false;
1734   }
1735 
1736   static bool inputUsesCRLF(StringRef Text) {
1737     return Text.count('\r') * 2 > Text.count('\n');
1738   }
1739 
1740   bool
1741   hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1742     for (const AnnotatedLine* Line : Lines) {
1743       if (hasCpp03IncompatibleFormat(Line->Children))
1744         return true;
1745       for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
1746         if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
1747           if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
1748             return true;
1749           if (Tok->is(TT_TemplateCloser) &&
1750               Tok->Previous->is(TT_TemplateCloser))
1751             return true;
1752         }
1753       }
1754     }
1755     return false;
1756   }
1757 
1758   int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
1759     int AlignmentDiff = 0;
1760     for (const AnnotatedLine* Line : Lines) {
1761       AlignmentDiff += countVariableAlignments(Line->Children);
1762       for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
1763         if (!Tok->is(TT_PointerOrReference))
1764           continue;
1765         bool SpaceBefore =
1766             Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1767         bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() !=
1768                           Tok->Next->WhitespaceRange.getEnd();
1769         if (SpaceBefore && !SpaceAfter)
1770           ++AlignmentDiff;
1771         if (!SpaceBefore && SpaceAfter)
1772           --AlignmentDiff;
1773       }
1774     }
1775     return AlignmentDiff;
1776   }
1777 
1778   void
1779   deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
1780     bool HasBinPackedFunction = false;
1781     bool HasOnePerLineFunction = false;
1782     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1783       if (!AnnotatedLines[i]->First->Next)
1784         continue;
1785       FormatToken *Tok = AnnotatedLines[i]->First->Next;
1786       while (Tok->Next) {
1787         if (Tok->PackingKind == PPK_BinPacked)
1788           HasBinPackedFunction = true;
1789         if (Tok->PackingKind == PPK_OnePerLine)
1790           HasOnePerLineFunction = true;
1791 
1792         Tok = Tok->Next;
1793       }
1794     }
1795     if (Style.DerivePointerAlignment)
1796       Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
1797                                    ? FormatStyle::PAS_Left
1798                                    : FormatStyle::PAS_Right;
1799     if (Style.Standard == FormatStyle::LS_Auto)
1800       Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
1801                            ? FormatStyle::LS_Cpp11
1802                            : FormatStyle::LS_Cpp03;
1803     BinPackInconclusiveFunctions =
1804         HasBinPackedFunction || !HasOnePerLineFunction;
1805   }
1806 
1807   void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
1808     assert(!UnwrappedLines.empty());
1809     UnwrappedLines.back().push_back(TheLine);
1810   }
1811 
1812   void finishRun() override {
1813     UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
1814   }
1815 
1816   FormatStyle Style;
1817   FileID ID;
1818   SourceManager &SourceMgr;
1819   WhitespaceManager Whitespaces;
1820   SmallVector<CharSourceRange, 8> Ranges;
1821   SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
1822 
1823   encoding::Encoding Encoding;
1824   bool BinPackInconclusiveFunctions;
1825 };
1826 
1827 struct IncludeDirective {
1828   StringRef Filename;
1829   StringRef Text;
1830   unsigned Offset;
1831   int Category;
1832 };
1833 
1834 } // end anonymous namespace
1835 
1836 // Determines whether 'Ranges' intersects with ('Start', 'End').
1837 static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
1838                          unsigned End) {
1839   for (auto Range : Ranges) {
1840     if (Range.getOffset() < End &&
1841         Range.getOffset() + Range.getLength() > Start)
1842       return true;
1843   }
1844   return false;
1845 }
1846 
1847 // Sorts a block of includes given by 'Includes' alphabetically adding the
1848 // necessary replacement to 'Replaces'. 'Includes' must be in strict source
1849 // order.
1850 static void sortIncludes(const FormatStyle &Style,
1851                          const SmallVectorImpl<IncludeDirective> &Includes,
1852                          ArrayRef<tooling::Range> Ranges, StringRef FileName,
1853                          tooling::Replacements &Replaces, unsigned *Cursor) {
1854   if (!affectsRange(Ranges, Includes.front().Offset,
1855                     Includes.back().Offset + Includes.back().Text.size()))
1856     return;
1857   SmallVector<unsigned, 16> Indices;
1858   for (unsigned i = 0, e = Includes.size(); i != e; ++i)
1859     Indices.push_back(i);
1860   std::stable_sort(
1861       Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) {
1862         return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) <
1863                std::tie(Includes[RHSI].Category, Includes[RHSI].Filename);
1864       });
1865 
1866   // If the #includes are out of order, we generate a single replacement fixing
1867   // the entire block. Otherwise, no replacement is generated.
1868   bool OutOfOrder = false;
1869   for (unsigned i = 1, e = Indices.size(); i != e; ++i) {
1870     if (Indices[i] != i) {
1871       OutOfOrder = true;
1872       break;
1873     }
1874   }
1875   if (!OutOfOrder)
1876     return;
1877 
1878   std::string result;
1879   bool CursorMoved = false;
1880   for (unsigned Index : Indices) {
1881     if (!result.empty())
1882       result += "\n";
1883     result += Includes[Index].Text;
1884 
1885     if (Cursor && !CursorMoved) {
1886       unsigned Start = Includes[Index].Offset;
1887       unsigned End = Start + Includes[Index].Text.size();
1888       if (*Cursor >= Start && *Cursor < End) {
1889         *Cursor = Includes.front().Offset + result.size() + *Cursor - End;
1890         CursorMoved = true;
1891       }
1892     }
1893   }
1894 
1895   // Sorting #includes shouldn't change their total number of characters.
1896   // This would otherwise mess up 'Ranges'.
1897   assert(result.size() ==
1898          Includes.back().Offset + Includes.back().Text.size() -
1899              Includes.front().Offset);
1900 
1901   Replaces.insert(tooling::Replacement(FileName, Includes.front().Offset,
1902                                        result.size(), result));
1903 }
1904 
1905 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
1906                                    ArrayRef<tooling::Range> Ranges,
1907                                    StringRef FileName, unsigned *Cursor) {
1908   tooling::Replacements Replaces;
1909   if (!Style.SortIncludes)
1910     return Replaces;
1911 
1912   unsigned Prev = 0;
1913   unsigned SearchFrom = 0;
1914   llvm::Regex IncludeRegex(
1915       R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))");
1916   SmallVector<StringRef, 4> Matches;
1917   SmallVector<IncludeDirective, 16> IncludesInBlock;
1918 
1919   // In compiled files, consider the first #include to be the main #include of
1920   // the file if it is not a system #include. This ensures that the header
1921   // doesn't have hidden dependencies
1922   // (http://llvm.org/docs/CodingStandards.html#include-style).
1923   //
1924   // FIXME: Do some sanity checking, e.g. edit distance of the base name, to fix
1925   // cases where the first #include is unlikely to be the main header.
1926   bool IsSource = FileName.endswith(".c") || FileName.endswith(".cc") ||
1927                   FileName.endswith(".cpp") || FileName.endswith(".c++") ||
1928                   FileName.endswith(".cxx") || FileName.endswith(".m") ||
1929                   FileName.endswith(".mm");
1930   StringRef FileStem = llvm::sys::path::stem(FileName);
1931   bool FirstIncludeBlock = true;
1932   bool MainIncludeFound = false;
1933 
1934   // Create pre-compiled regular expressions for the #include categories.
1935   SmallVector<llvm::Regex, 4> CategoryRegexs;
1936   for (const auto &Category : Style.IncludeCategories)
1937     CategoryRegexs.emplace_back(Category.Regex);
1938 
1939   bool FormattingOff = false;
1940 
1941   for (;;) {
1942     auto Pos = Code.find('\n', SearchFrom);
1943     StringRef Line =
1944         Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
1945 
1946     StringRef Trimmed = Line.trim();
1947     if (Trimmed == "// clang-format off")
1948       FormattingOff = true;
1949     else if (Trimmed == "// clang-format on")
1950       FormattingOff = false;
1951 
1952     if (!FormattingOff && !Line.endswith("\\")) {
1953       if (IncludeRegex.match(Line, &Matches)) {
1954         StringRef IncludeName = Matches[2];
1955         int Category = INT_MAX;
1956         for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i) {
1957           if (CategoryRegexs[i].match(IncludeName)) {
1958             Category = Style.IncludeCategories[i].Priority;
1959             break;
1960           }
1961         }
1962         if (IsSource && !MainIncludeFound && Category > 0 &&
1963             FirstIncludeBlock && IncludeName.startswith("\"")) {
1964           StringRef HeaderStem =
1965               llvm::sys::path::stem(IncludeName.drop_front(1).drop_back(1));
1966           if (FileStem.startswith(HeaderStem)) {
1967             llvm::Regex MainIncludeRegex(
1968                 (HeaderStem + Style.IncludeIsMainRegex).str());
1969             if (MainIncludeRegex.match(FileStem)) {
1970               Category = 0;
1971               MainIncludeFound = true;
1972             }
1973           }
1974         }
1975         IncludesInBlock.push_back({IncludeName, Line, Prev, Category});
1976       } else if (!IncludesInBlock.empty()) {
1977         sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces,
1978                      Cursor);
1979         IncludesInBlock.clear();
1980         FirstIncludeBlock = false;
1981       }
1982       Prev = Pos + 1;
1983     }
1984     if (Pos == StringRef::npos || Pos + 1 == Code.size())
1985       break;
1986     SearchFrom = Pos + 1;
1987   }
1988   if (!IncludesInBlock.empty())
1989     sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces, Cursor);
1990   return Replaces;
1991 }
1992 
1993 tooling::Replacements formatReplacements(StringRef Code,
1994                                          const tooling::Replacements &Replaces,
1995                                          const FormatStyle &Style) {
1996   if (Replaces.empty())
1997     return tooling::Replacements();
1998 
1999   std::string NewCode = applyAllReplacements(Code, Replaces);
2000   std::vector<tooling::Range> ChangedRanges =
2001       tooling::calculateChangedRanges(Replaces);
2002   StringRef FileName = Replaces.begin()->getFilePath();
2003   tooling::Replacements FormatReplaces =
2004       reformat(Style, NewCode, ChangedRanges, FileName);
2005 
2006   tooling::Replacements MergedReplacements =
2007       mergeReplacements(Replaces, FormatReplaces);
2008 
2009   return MergedReplacements;
2010 }
2011 
2012 tooling::Replacements reformat(const FormatStyle &Style,
2013                                SourceManager &SourceMgr, FileID ID,
2014                                ArrayRef<CharSourceRange> Ranges,
2015                                bool *IncompleteFormat) {
2016   FormatStyle Expanded = expandPresets(Style);
2017   if (Expanded.DisableFormat)
2018     return tooling::Replacements();
2019   Formatter formatter(Expanded, SourceMgr, ID, Ranges);
2020   return formatter.format(IncompleteFormat);
2021 }
2022 
2023 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
2024                                ArrayRef<tooling::Range> Ranges,
2025                                StringRef FileName, bool *IncompleteFormat) {
2026   if (Style.DisableFormat)
2027     return tooling::Replacements();
2028 
2029   IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
2030       new vfs::InMemoryFileSystem);
2031   FileManager Files(FileSystemOptions(), InMemoryFileSystem);
2032   DiagnosticsEngine Diagnostics(
2033       IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2034       new DiagnosticOptions);
2035   SourceManager SourceMgr(Diagnostics, Files);
2036   InMemoryFileSystem->addFile(
2037       FileName, 0, llvm::MemoryBuffer::getMemBuffer(
2038                        Code, FileName, /*RequiresNullTerminator=*/false));
2039   FileID ID = SourceMgr.createFileID(Files.getFile(FileName), SourceLocation(),
2040                                      clang::SrcMgr::C_User);
2041   SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
2042   std::vector<CharSourceRange> CharRanges;
2043   for (const tooling::Range &Range : Ranges) {
2044     SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
2045     SourceLocation End = Start.getLocWithOffset(Range.getLength());
2046     CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
2047   }
2048   return reformat(Style, SourceMgr, ID, CharRanges, IncompleteFormat);
2049 }
2050 
2051 LangOptions getFormattingLangOpts(const FormatStyle &Style) {
2052   LangOptions LangOpts;
2053   LangOpts.CPlusPlus = 1;
2054   LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2055   LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
2056   LangOpts.LineComment = 1;
2057   bool AlternativeOperators = Style.Language == FormatStyle::LK_Cpp;
2058   LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
2059   LangOpts.Bool = 1;
2060   LangOpts.ObjC1 = 1;
2061   LangOpts.ObjC2 = 1;
2062   LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
2063   LangOpts.DeclSpecKeyword = 1; // To get __declspec.
2064   return LangOpts;
2065 }
2066 
2067 const char *StyleOptionHelpDescription =
2068     "Coding style, currently supports:\n"
2069     "  LLVM, Google, Chromium, Mozilla, WebKit.\n"
2070     "Use -style=file to load style configuration from\n"
2071     ".clang-format file located in one of the parent\n"
2072     "directories of the source file (or current\n"
2073     "directory for stdin).\n"
2074     "Use -style=\"{key: value, ...}\" to set specific\n"
2075     "parameters, e.g.:\n"
2076     "  -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
2077 
2078 static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
2079   if (FileName.endswith(".java"))
2080     return FormatStyle::LK_Java;
2081   if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts"))
2082     return FormatStyle::LK_JavaScript; // JavaScript or TypeScript.
2083   if (FileName.endswith_lower(".proto") ||
2084       FileName.endswith_lower(".protodevel"))
2085     return FormatStyle::LK_Proto;
2086   if (FileName.endswith_lower(".td"))
2087     return FormatStyle::LK_TableGen;
2088   return FormatStyle::LK_Cpp;
2089 }
2090 
2091 FormatStyle getStyle(StringRef StyleName, StringRef FileName,
2092                      StringRef FallbackStyle, vfs::FileSystem *FS) {
2093   if (!FS) {
2094     FS = vfs::getRealFileSystem().get();
2095   }
2096   FormatStyle Style = getLLVMStyle();
2097   Style.Language = getLanguageByFileName(FileName);
2098   if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
2099     llvm::errs() << "Invalid fallback style \"" << FallbackStyle
2100                  << "\" using LLVM style\n";
2101     return Style;
2102   }
2103 
2104   if (StyleName.startswith("{")) {
2105     // Parse YAML/JSON style from the command line.
2106     if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
2107       llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
2108                    << FallbackStyle << " style\n";
2109     }
2110     return Style;
2111   }
2112 
2113   if (!StyleName.equals_lower("file")) {
2114     if (!getPredefinedStyle(StyleName, Style.Language, &Style))
2115       llvm::errs() << "Invalid value for -style, using " << FallbackStyle
2116                    << " style\n";
2117     return Style;
2118   }
2119 
2120   // Look for .clang-format/_clang-format file in the file's parent directories.
2121   SmallString<128> UnsuitableConfigFiles;
2122   SmallString<128> Path(FileName);
2123   llvm::sys::fs::make_absolute(Path);
2124   for (StringRef Directory = Path; !Directory.empty();
2125        Directory = llvm::sys::path::parent_path(Directory)) {
2126 
2127     auto Status = FS->status(Directory);
2128     if (!Status ||
2129         Status->getType() != llvm::sys::fs::file_type::directory_file) {
2130       continue;
2131     }
2132 
2133     SmallString<128> ConfigFile(Directory);
2134 
2135     llvm::sys::path::append(ConfigFile, ".clang-format");
2136     DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2137 
2138     Status = FS->status(ConfigFile.str());
2139     bool IsFile =
2140         Status && (Status->getType() == llvm::sys::fs::file_type::regular_file);
2141     if (!IsFile) {
2142       // Try _clang-format too, since dotfiles are not commonly used on Windows.
2143       ConfigFile = Directory;
2144       llvm::sys::path::append(ConfigFile, "_clang-format");
2145       DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
2146       Status = FS->status(ConfigFile.str());
2147       IsFile = Status &&
2148                (Status->getType() == llvm::sys::fs::file_type::regular_file);
2149     }
2150 
2151     if (IsFile) {
2152       llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
2153           FS->getBufferForFile(ConfigFile.str());
2154       if (std::error_code EC = Text.getError()) {
2155         llvm::errs() << EC.message() << "\n";
2156         break;
2157       }
2158       if (std::error_code ec =
2159               parseConfiguration(Text.get()->getBuffer(), &Style)) {
2160         if (ec == ParseError::Unsuitable) {
2161           if (!UnsuitableConfigFiles.empty())
2162             UnsuitableConfigFiles.append(", ");
2163           UnsuitableConfigFiles.append(ConfigFile);
2164           continue;
2165         }
2166         llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
2167                      << "\n";
2168         break;
2169       }
2170       DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
2171       return Style;
2172     }
2173   }
2174   if (!UnsuitableConfigFiles.empty()) {
2175     llvm::errs() << "Configuration file(s) do(es) not support "
2176                  << getLanguageName(Style.Language) << ": "
2177                  << UnsuitableConfigFiles << "\n";
2178   }
2179   return Style;
2180 }
2181 
2182 } // namespace format
2183 } // namespace clang
2184