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