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